---
name: login-required-check
description: Checks whether people who are not logged in can see or change things in a web app that they should not, and whether ordinary users can get into admin-only parts. Use when the user asks if strangers or logged-out visitors can see their data, whether their pages are protected, whether their login actually protects anything, whether their admin page is locked, or wants an access check before launch. Looks at both the pages and the server side (API routes, Supabase Edge Functions) and catches the common mistake of hiding a button or page while the request behind it is left open. Explains each problem in plain language with code to paste.
allowed-tools: Read Grep Glob
license: MIT
---

# Login-required check

Find the parts of the app that show or change private data for people who are not signed in, and the admin-only parts that any signed-in user can reach. Report them in plain language. Change nothing.

## Rules

- **Read only.** Use Read, Grep and Glob. Do not edit or create files and do not run commands. Give each fix as a prompt the user can paste into their AI builder (Lovable, Bolt, Replit and similar) and as code they can paste; do not apply it.
- You are reading the code, not the live app. What is deployed may differ from these files. Say this under "Not checked" every time.
- Write for someone who is not an engineer. Say "anyone on the internet" and "any signed-in user". If you use a technical word (Edge Function, route, service role key), explain it once in a few words.
- Do not guess. If you could not tell whether something is protected, say what you could not tell and why, under "Check this is intended" or "Not checked". Never call the app "safe" or "secure"; say what you checked and what you found.

## Background you need

**The page is not the lock.** Everything in the browser code can be skipped. A visitor can copy the site's public key from the page and call any Edge Function or API route directly, without ever opening the page that normally calls it. So:

- Hiding a button (`{isAdmin && <button>}`), redirecting away from a page, or greying out a link changes what is drawn. It stops nobody from sending the request behind it.
- The real lock is the server code that answers the request. A page guard is still worth having (it stops strangers seeing the screen and is often where people notice a hole), but a page guard with an open server function behind it is a problem.

**What counts as a real sign-in check in the browser:** a guard component, layout or hook that asks Supabase (or the app's auth provider) for the current session, such as `supabase.auth.getSession()`, `getUser()`, `onAuthStateChange`, or a `useAuth`/`useSession` hook built on them, and redirects when there is none. Clerk's `<SignedIn>`/`<RedirectToSignIn>`, Auth0's `withAuthenticationRequired` and NextAuth's `useSession({ required: true })` also count.

**What does not count:** a flag the browser keeps for itself. `localStorage.getItem("isLoggedIn")`, `sessionStorage`, a cookie set by the browser code, a value in the URL, a hard-coded password in browser code, or an environment variable. Anyone can set these in their browser's developer tools in a few seconds.

**What counts as a real sign-in check on the server:** the function reads the `Authorization` header, asks Supabase who it belongs to (`supabase.auth.getUser(token)`, `supabase.auth.getClaims(token)`, or a client created with that header followed by `getUser()`), and stops with an error when there is no user. Follow helper functions (for example a `requireUser` in `_shared/`) to see what they do.

**Supabase details that matter:**

- The **service role key** (`SUPABASE_SERVICE_ROLE_KEY`, `sb_secret_…`) skips every database rule. A function that uses it must check the caller itself. If it does not, whoever can call the function gets whatever the function returns.
- A function that uses the **anon or publishable key with the caller's `Authorization` header** acts as that caller, so the database's own rules (row-level security) still apply. Whether those rules are right is a separate check (see "Not checked").
- **`verify_jwt`** in `supabase/config.toml` (on unless set to `false`) makes Supabase reject calls without a valid token. The app's public anon key is a valid token, so `verify_jwt` on its own does **not** mean "signed in". With `verify_jwt = false`, anyone on the internet can call the function with no key at all.
- **Signed in is not the same as admin.** Anyone can create an account. An admin check must look up the role on the server: a `role` column read on the server, a table of admins, or `app_metadata`. A role taken from the request body, a header, the URL, or `user_metadata` does not count, because the user can set all of those themselves (`supabase.auth.updateUser({ data: { role: "admin" } })` writes `user_metadata`).

**Meant to be open:** the home page, pricing, login, sign-up, password reset, legal pages, blog or docs; functions that return only public catalogue data (product names, prices, descriptions); and webhooks. A webhook is called by another service (Stripe, Paddle, Resend), not by a person, so it cannot have a signed-in user. Its lock is a signature check (`stripe.webhooks.constructEvent` or `constructEventAsync`, a verified HMAC, or a shared secret compared on the server). A webhook that checks its signature is fine. One that does not is a problem.

## Step 1: Map the app

1. **Pages.** Find the router. React Router: Grep for `<Route`, `createBrowserRouter`, `path:` in `src/`. Next.js: list `app/**/page.*` and `pages/**/*`, and read `middleware.*`. TanStack Router, Remix or SvelteKit: their route folders. Note every page (route), the component it shows, and every wrapper around it. A layout route whose `element` is a guard with `<Outlet />` protects every route nested inside it.
2. **Guards.** Read every guard component, layout and middleware you found. Decide for each: real sign-in check, real admin check, sign-in only, or a fake check (Background).
3. **Server code.** Glob `supabase/functions/*/index.ts` (and `.js`), `supabase/functions/_shared/**`, `supabase/config.toml`, `api/**`, `server/**`, `functions/**`, `netlify/functions/**`, `app/**/route.*`, `pages/api/**`, and files starting with `"use server"`. Read each one in full, including the helpers it imports.

## Step 2: Check each page

For each page, Read the component file in full (not just Grep it) and note what it shows and every request it sends: `supabase.functions.invoke("<name>")`, `fetch("/api/…")`, `supabase.from("<table>")`, server actions. A direct table read with `supabase.from(...)` is a request: never describe a page that makes one as sending no requests or showing no data. Keep a list of every page that reads a table directly and the tables it reads; Step 5 and "Not checked" need it.

- A page that shows a person's own or private data (dashboard, account, billing, messages, invoices, anything with "my" or "your" in it) and has **no guard, or a fake guard**, is a problem.
- An admin page (`/admin`, "all users", moderation, reports, settings for the whole app) wrapped only in a sign-in check is a problem, unless every server function it uses checks the admin role. Then it is a lower-priority note under "Check this is intended".
- Public pages (Background) are not problems.

## Step 3: Check each server function

For each Edge Function or API route, answer:

1. Who can call it? (`verify_jwt` setting; any extra secret check.)
2. Does it find out who the caller is, and stop when there is no user?
3. Which key does it use: service role (skips the rules) or the caller's own token?
4. What does it return or change? Is that limited to the caller's own rows (`.eq("user_id", user.id)` or similar, or rules that apply because it acts as the caller)?
5. If it does something only admins should do (lists every user, deletes or edits other people's things, changes roles, refunds), does it check the admin role on the server?

Report as a problem:

- **No sign-in check** on a function that returns or changes private data. Who can get in: anyone on the internet.
- **Checks who the caller is but returns everyone's rows** (service role key, no filter to the caller). Who can get in: any signed-in user.
- **Admin action with only a sign-in check**, or a role taken from somewhere the user controls. Who can get in: any signed-in user.
- **A webhook with no signature check.** Who can get in: anyone on the internet.

## Step 4: Join the buttons to the doors

Grep the browser code for things shown only to some people: `isAdmin`, `role ===`, `role !==`, `profile?.role`, `user?.role`, `canEdit`, `canDelete`, `hidden`, `disabled={!`. For each one that wraps a button, link or form, find the request it sends and the server function that answers it. If that function does not itself check the same thing, report it as a **hidden button, open door** problem: name both the file with the button and the function, and say plainly that hiding the button stopped nobody.

Do the same for whole admin pages: find every function the page calls.

## Step 5: Decide what to report

Report each fault once. If the same hole shows up in two places (a hidden button and the open function behind it, or an admin page and its admin function that both check sign-in only), give it **one** entry, name both files, and put the server fix first.

Merge only in those two cases. Every other fault gets its own numbered entry, even when two faults touch the same page: a page with no guard and an open function that page calls are two entries, and two pages with missing or fake guards are two entries.

Do **not** report:

- Public pages and public catalogue functions (put catalogue functions under "Check this is intended" so the user can confirm nothing private is in them).
- Pages behind a real guard, and functions that check the user and limit what they return to that user.
- Webhooks that check their signature.
- Browser-only admin checks (`RequireAdmin`, hidden buttons) when every server function behind them checks the role. Mention them under "Looks right".
- Data the browser reads straight from the database with `supabase.from(...)`. Whether that is protected depends on the database rules, which this check does not read. Mention it under "Not checked", naming the tables.
- Code-quality issues that do not let anyone see or change something they should not.
- Risks that depend on something you cannot see in these files: database rules, dashboard settings, or whether a user can edit their own role in a table. Put them under "Not checked". Every numbered problem must be a fault you can point to in the code you read.

## Output

Reply with this and nothing before it.

````
Login-required check: <N> problem(s) found in <P> page(s) and <F> server function(s) reviewed

## Problems

1. <what is open, in one plain sentence>
   Where: `<file>:<line>` (and `<second file>:<line>` if the fault spans two)
   Who can get in: <Anyone on the internet | Any signed-in user>
   What this means: <what that person can see or do, in plain words>
   Paste this to your builder: "<one plain-language instruction describing the same fix as the code below>"
   Fix:
   ```ts
   <code to paste, with the file it goes in>
   ```

## Check this is intended

- <page or function>: <what is open and to whom> (`<file>:<line>`)

## Looks right

- <page or function>: <one line on why>

## Not checked

- The live app. This check read the code only.
````

- Settle the headline last: decide the full list of numbered Problems entries first, including any merges, then count them and write the headline. `<N>` is the number of numbered entries under Problems, exactly. Count the entries, not the faults: if one entry covers two places, it counts once.
- Then write exactly those entries, no more and no fewer. Never add an entry that is not a problem, never take an entry back, and never correct the headline inside the reply. If the count would be wrong, fix it before you write the reply.
- `<P>` is every page route you reviewed and `<F>` every server function (each Edge Function folder with an entry file, not `_shared`, plus each API route), including the ones with nothing wrong.
- Order problems by damage: anyone on the internet can change or delete, then anyone on the internet can see private data, then any signed-in user can reach admin data or actions, then pages that are open but whose data is protected elsewhere.
- Write fixes that are complete and fit the project's own code: reuse its guard component, its Supabase client and its CORS headers if it has them. For an Edge Function, show the check at the top of the handler:

  ```ts
  const token = (req.headers.get("Authorization") ?? "").replace("Bearer ", "");
  const { data: { user }, error } = await supabase.auth.getUser(token);
  if (error || !user) {
    return new Response(JSON.stringify({ error: "Not signed in" }), {
      status: 401,
      headers: { ...corsHeaders, "Content-Type": "application/json" },
    });
  }
  ```

  then limit the query to the caller (`.eq("user_id", user.id)`) or, for admin actions, look up the role on the server and return 403 when it is not admin. For a page, wrap the route in the project's working guard; if it has none, give a small guard that uses `supabase.auth.getSession()` and `onAuthStateChange`. For a fake guard, replace it with the real one and remove the flag it relied on.
- Every problem gets a **"Paste this to your builder:"** line, before the code. Most readers change their app by prompting an AI builder, not by editing files. Write it as one or two plain sentences in quotes that:
  - describe the same fix as the code, step by step if the code does more than one thing (for example "check the caller is signed in, then return only their own invoices");
  - name the file, page or Edge Function to change, so the builder changes the right place;
  - ask only for checks to be added or a fake check to be replaced with the real one. Never ask the builder to turn off, remove, bypass or loosen a check, a guard or a database rule, and never ask it to delete data.
  If one entry covers two places (a page and its server function), the prompt covers both, server first.
- When a page fix adds an admin guard in the browser, say in one line that it only tidies the screen and the server check is the lock.
- If there are no problems, write `Login-required check: 0 problems found in <P> page(s) and <F> server function(s) reviewed`, write "None." under Problems, and keep the other sections. Do not invent a problem.

## Not checked

Always list, adjusted to what you found:

- **The live app.** Deployed functions, settings changed in the Supabase dashboard (including `verify_jwt`) and environment variables can differ from these files.
- **Database rules (row-level security).** Pages that read tables directly with `supabase.from(...)`, and functions that act as the caller, rely on these rules. List every page that reads a table directly, with each table it reads, and every table a function reads as the caller. Leave none out. The Supabase RLS review skill checks them. If the admin role lives in a table, say that a user must not be able to change their own role there.
- **File storage** (Supabase Storage buckets and their policies), if the app uses it.
- **Whether a signed-in user can reach another user's record by changing an id** in functions that take an id from the request, beyond what the code above shows.
- **Sign-in itself**: password reset, email confirmation, magic links, social login settings, rate limits on sign-in.
- Anything outside this project: other services, scheduled jobs, or functions that exist only in the dashboard.

<!--
MIT License

Copyright (c) 2026 PT Maverick Rintis Karya

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-->
