> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ancha.io/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> These docs describe the Ancha CLI, npm package @ancha-labs/cli, and the hosted workspace at app.ancha.io. Coding agents should start at https://docs.ancha.io/coding-agents. Run the CLI as `ancha` after `npm install -g @ancha-labs/cli`, or as `npx -y @ancha-labs/cli` without installing. Pass --json for machine-readable output, or set ANCHA_JSON=1. Every command ends with a `next:` line naming the next command. Exit codes: 0 pass, 1 a check failed or a comparison regressed, 2 usage, config or authentication error, 3 infrastructure error, 4 unimplemented endpoint with --strict.

# Connect your app to the Supabase mock

> Run an app's own Supabase code against a world: Postgres built from its migrations with row-level security, Auth with emailed codes and links, and Storage with signed URLs.

A world's Supabase project is a Postgres database built from the app's own `supabase/migrations` and `supabase/seed.sql`. The Data API, Auth and Storage answer the official `@supabase/supabase-js` client, and the app's row-level security policies decide every request.

The [Supabase mock page](https://ancha.io/tools/supabase) has a scene and checks you can copy.

Select this tool with `twins: [supabase]` in a scene or `--tools supabase` when creating a world. Inspect its API coverage and connection code:

```bash theme={null}
ancha twins coverage supabase
ancha connect supabase --lang ts
```

## Connect

| Variable | Value |
| - | - |
| `SUPABASE_URL` | Project URL. The client adds `/rest/v1`, `/auth/v1` and `/storage/v1`. Also `NEXT_PUBLIC_SUPABASE_URL`, `VITE_SUPABASE_URL` and `EXPO_PUBLIC_SUPABASE_URL`. |
| `SUPABASE_ANON_KEY` | Fake anon key, a JWT with role `anon`. Also `NEXT_PUBLIC_SUPABASE_ANON_KEY`, `VITE_SUPABASE_ANON_KEY` and `EXPO_PUBLIC_SUPABASE_ANON_KEY`. |
| `SUPABASE_PUBLISHABLE_KEY` | `sb_publishable_` key with the anon role. Also `NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY` and `VITE_SUPABASE_PUBLISHABLE_KEY`. |
| `SUPABASE_SERVICE_ROLE_KEY` | Fake service role key. Requests with it bypass row-level security, as on Supabase. |
| `SUPABASE_SECRET_KEY` | `sb_secret_` key with the service role. |
| `SUPABASE_JWT_SECRET` | The project's JWT secret. Access tokens are HS256 JWTs signed with it. |
| `SUPABASE_PROJECT_REF` | Project ref. Also `VITE_SUPABASE_PROJECT_ID`. |

```js Node theme={null}
import { createClient } from '@supabase/supabase-js';
const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_ANON_KEY);
const { data, error } = await supabase.from('invoices').select('id, number, amount_cents');
```

A server route acts as the signed-in person by passing their access token:

```js Node theme={null}
const db = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_ANON_KEY, {
  global: { headers: { Authorization: `Bearer ${accessToken}` } },
});
```

## The database

Ancha builds each world's database the way `supabase db reset` does: the files in `supabase/migrations` in file-name order, then `supabase/seed.sql`, then the scene's `seed.supabase`. When the scene gives `migrations` or `seed_sql` inline, those are used instead of the project's files. A migration that fails stops the run and names its file and line.

The project starts with the `auth`, `storage` and `extensions` schemas, the roles `anon`, `authenticated` and `service_role`, and `uuid-ossp` and `pgcrypto` in `extensions`. Migrations can also create `citext` and `pg_trgm`. Triggers on `auth.users`, such as one that creates a profile row for each new person, run on sign-up and for every seeded user.

Every Data API and Storage request runs in Postgres as the caller's role, with the JWT claims that `auth.uid()`, `auth.role()` and `auth.jwt()` read. The app's policies decide what each person sees and changes. `now()`, token lifetimes, code expiry and signed URL expiry follow the world's clock.

```yaml theme={null}
seed:
  supabase:
    users:
      - { email: alice.romero@kilnstreet.example, password: kiln-street-owner-1, user_metadata: { full_name: Alice Romero } }
      - { email: bea.okafor@kilnstreet.example, user_metadata: { full_name: Bea Okafor } }
    sql:
      - |
        insert into public.memberships (user_id, tenant_id, role)
          select id, 'studio-a', 'owner' from auth.users where email = 'alice.romero@kilnstreet.example';
    buckets:
      - { id: invoices, file_size_limit: 5242880, allowed_mime_types: [application/pdf] }
    objects:
      - { bucket: invoices, path: studio-a/INV-0999.pdf, base64: "<base64 of the file>", content_type: application/pdf, owner: alice.romero@kilnstreet.example }
```

Seeded users are created the way sign-up creates them: a row in `auth.users` and an email identity. `confirmed` defaults to `true`; `created` and `last_sign_in` are offsets from the scene's start, such as `-900h`. `sql` runs as the database owner after the users exist. A file's bucket can come from `buckets` or from one of the app's migrations.

## Sign people in

Auth answers `supabase.auth` and `supabase.auth.admin`: sign-up, password sign-in, email codes and magic links, PKCE, refresh token rotation, sign-out, password recovery, email change and the admin API. Sign-up asks the person to confirm their email by default. Codes, links, confirmations and invitations arrive in the world's inbox; read them with `ancha world inbox`.

| `seed.supabase.auth` | Default | Effect |
| - | - | - |
| `email_otp` | `code` | What `signInWithOtp` sends: a 6-digit `code` or a magic `link`. |
| `confirm_email` | `true` | New sign-ups confirm their email before they can sign in. |
| `access_token_ttl` | `1h` | Lifetime of access tokens. |
| `otp_ttl` | `1h` | Lifetime of codes and links. |
| `email_rate_limit` | `30` | Auth emails per hour before `over_email_send_rate_limit`. |
| `site_url` | `http://localhost:3000` | Where email links redirect by default. |
| `redirect_urls` | `[]` | Other allowed redirect URLs, with `*` and `**` wildcards. |

A scene calls the app as a person with `as` on an app call:

```yaml theme={null}
world_rules:
  app_calls:
    - at: 2s
      method: POST
      path: /api/invoices
      as: { supabase: alice.romero@kilnstreet.example }
      body: { tenant: studio-a, number: INV-1001, amount_cents: 120000 }
```

The world signs the person in and sends the call with their access token in `Authorization`. From a harness, `ancha world act supabase.sign_in --env <id> --args '{"email":"alice.romero@kilnstreet.example"}'` returns an `access_token`, a `refresh_token` and the `authorization` header value.

## Storage

Buckets keep their `public` flag, `file_size_limit` and `allowed_mime_types`. Uploads, downloads, lists, moves, copies and removals run as the caller against the policies on `storage.objects`; a file's `owner` is the uploader's user id. Public buckets serve files at `/object/public/...` without a key. Signed download and upload URLs are JWTs signed with the project secret and expire on the world's clock.

## Endpoints

### Data API

| Method | Path | Notes |
| - | - | - |
| `GET`, `HEAD` | `/rest/v1/{table}` | `select` with aliases, casts, JSON paths and embedded resources over foreign keys (`!inner`, hints); filters with `and`, `or` and `not`; `order`, `limit`, `offset`, `Range`; `Prefer: count=exact`. |
| `POST` | `/rest/v1/{table}` | Insert, bulk insert, `columns`, upsert with `on_conflict` and `Prefer: resolution`. |
| `PATCH`, `DELETE` | `/rest/v1/{table}` | Filters are required, as on Supabase. |
| `PUT` | `/rest/v1/{table}` | Upsert one row by its primary key. |
| `POST`, `GET`, `HEAD` | `/rest/v1/rpc/{function}` | Named arguments; scalar, set and table results. |
| `GET` | `/rest/v1/` | OpenAPI description of the tables the caller can read. |

`Accept: application/vnd.pgrst.object+json` (`.single()`) and `text/csv` (`.csv()`) are answered as PostgREST answers them, and errors carry PostgREST's `code`, `details`, `hint` and `message`.

### Auth

| Method | Path | Notes |
| - | - | - |
| `POST` | `/auth/v1/signup` | |
| `POST` | `/auth/v1/token` | `grant_type`: `password`, `refresh_token` or `pkce`. |
| `POST` | `/auth/v1/otp` | Email code or magic link. |
| `POST`, `GET` | `/auth/v1/verify` | Codes, and the links in emails. |
| `GET`, `PUT` | `/auth/v1/user` | |
| `POST` | `/auth/v1/logout` | `scope`: `global`, `local` or `others`. |
| `POST` | `/auth/v1/recover`, `/auth/v1/resend` | |
| `GET` | `/auth/v1/settings`, `/auth/v1/.well-known/jwks.json` | |
| `GET`, `POST` | `/auth/v1/admin/users` | `page` and `per_page`. |
| `GET`, `PUT`, `DELETE` | `/auth/v1/admin/users/{id}` | |
| `POST` | `/auth/v1/admin/generate_link`, `/auth/v1/invite` | |

### Storage

| Method | Path | Notes |
| - | - | - |
| `GET`, `POST` | `/storage/v1/bucket` | |
| `GET`, `PUT`, `DELETE` | `/storage/v1/bucket/{id}` | A bucket is deleted only when it is empty. |
| `POST` | `/storage/v1/bucket/{id}/empty` | |
| `POST`, `PUT` | `/storage/v1/object/{bucket}/{path}` | Upload or replace; raw bytes or multipart; `x-upsert`. |
| `GET` | `/storage/v1/object/{bucket}/{path}`, `/object/authenticated/{bucket}/{path}` | Download as the caller. |
| `GET` | `/storage/v1/object/public/{bucket}/{path}` | Public buckets. |
| `GET`, `HEAD` | `/storage/v1/object/info/{bucket}/{path}` | |
| `POST` | `/storage/v1/object/list/{bucket}` | `prefix`, `search`, `limit`, `offset`, `sortBy`. |
| `POST` | `/storage/v1/object/move`, `/storage/v1/object/copy` | |
| `DELETE` | `/storage/v1/object/{bucket}` | Removes a list of paths. |
| `POST`, `GET` | `/storage/v1/object/sign/{bucket}/{path}` | Create a signed URL; download with its `token`. |
| `POST` | `/storage/v1/object/sign/{bucket}` | Signed URLs for several paths. |
| `POST`, `PUT` | `/storage/v1/object/upload/sign/{bucket}/{path}` | Create a signed upload URL; upload with its `token`. |

## Starter data

Inspect the starter records and the fields you can use in a scene:

```bash theme={null}
ancha sandbox configuration --tools supabase --json
ancha twins seed supabase
```

The first command prints the starter dataset. The second lists accepted seed fields and the built-in check examples. A scene uses the data you put in its `seed` field, and the tables come from the app's migrations.

The `supabase-starter` dataset is a client portal for an accounting firm, Brightwell CPA: Maria Okafor on the firm's staff, Tom Reyes and Jen Park at Harborview Dental, and Sam Adeyemi at Northgate Bakery, whose email is not confirmed. The private `documents` bucket holds Harborview Dental's Q3 payroll CSV and its engagement letter; the public `avatars` bucket takes PNG and JPEG images. A `document_requests` table asks Tom for the Q4 payroll file. Row-level security shows each person their own requests, and Storage policies let Tom and Jen read and upload files in the `harborview-dental/` folder.

## Checks

State checks read the database and the stored files at the end of a run, as the database owner, so policies hide nothing. In `where`, `{ user: <email> }` stands for that person's user id:

```yaml theme={null}
checks:
  - id: alice_saved_the_invoice
    state: { supabase.rows: { table: invoices, where: { number: INV-1001, status: complete, uploaded_by: { user: alice.romero@kilnstreet.example } }, count: 1 } }
  - id: the_pdf_is_the_one_she_uploaded
    state: { supabase.objects: { bucket: invoices, path: studio-a/INV-1001.pdf, size: 624, owner: alice.romero@kilnstreet.example } }
  - id: bea_signed_in
    state: { supabase.users: { email: bea.okafor@kilnstreet.example, signed_in: true } }
```

`supabase.rows` takes `count`, `count_gte` or `count_lte`; `supabase.objects` takes a `path` or a `prefix`, with `count`, `size`, `sha256` and `owner`; `supabase.users` takes `exists`, `confirmed` and `signed_in`. `inbox.messages` counts the codes and links a person received.

The `supabase.sql` action runs SQL as the database owner during a run, for example an administrator changing someone's role. `world_rules.call_faults` fails Supabase calls with a 5xx error or a 429, such as `match: "POST /storage/v1/object/{bucket}/{path*}"` for uploads.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.