Commit Graph
8 Commits
Author SHA1 Message Date
Alaister YoungandAlaister Young 0252fd8cad [FE-5114] (part 7) – refactor(studio): remove Next API adapter (#54034)
## Problem

With all Studio API routes migrated to native TanStack Start handlers
(or removed when unused) in parts 1–6, the Next Pages Router API adapter
and legacy `NextApiRequest`/`NextApiResponse` wrappers are no longer
used. Part 7 of 7 for
[FE-5114](https://linear.app/supabase/issue/FE-5114/rewrite-api-routes-as-native-tanstack-start-handlers-and-remove-the)
tears them down.

## Solution

**Removed:**

- `compat/next/api.ts` and `compat/next/api.test.ts` (`toWebHandler`)
- Legacy `apiWrapper`, `apiAuthenticate`, and `fetchUserClaims`
(`NextApiRequest`/`NextApiResponse`) functions and their legacy tests in
`lib/api/apiWrapper.ts`, `lib/api/apiAuthenticate.ts`,
`lib/api/apiWrappers.test.ts`, and `lib/api/apiAuthenticate.test.ts`
- The now-unused `fromNodeHeaders` helper (and its `node:http` import)
and its tests in `lib/api/apiHelpers.ts` / `lib/api/apiHelpers.test.ts`

**Changed:**

- Updated comment in `lib/server/configcat.ts` from `apiAuthenticate` to
`authenticateRequest`

## Review instructions

1. Confirm `git grep -E
"NextApiRequest|NextApiResponse|compat/next/api|toWebHandler|fromNodeHeaders|from
'next'" apps/studio/` returns no matches.
2. Run `pnpm --filter studio run typecheck`, `pnpm knip --workspace
apps/studio`, and `pnpm --filter studio exec vitest run lib/api/
tests/routes/api/ scripts/__tests__/server-source-maps.test.ts`.

## Checklist

- [x] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [ ] If I wrote a new docs topic or edited an existing topic, I used
the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs
[style
guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide)

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-12-01 23:01:47 +08:00
Alaister YoungandAlaister Young 37414c5a61 [FE-5114] (part 5) – refactor(studio): migrate platform project routes (#54032)
## Problem

Studio's `routes/api/platform/projects/**` routes still run legacy Next
Pages Router handlers through `compat/next/api.ts`, and
`projects/$ref/config/index.ts` and `projects/$ref/billing/addons.ts`
are unused in self-hosted mode. Part 5 of 7 for
[FE-5114](https://linear.app/supabase/issue/FE-5114/rewrite-api-routes-as-native-tanstack-start-handlers-and-remove-the)
migrates the 19 active project routes to native TanStack Start handlers
and removes the 2 unused routes.

## Solution

**Changed:**

- Migrated 19 project routes — analytics (`endpoints/$name`,
`log-drains`, `log-drains/$uuid`), API proxies (`api/graphql`,
`api/rest`), content snippets & folders (`content/**`), and
config/settings/databases/lints/keys/monitoring routes — to
`createApiHandlers`
- Preserved FE-5124 fixes on `log-drains/$uuid` (empty-body `204` on
`DELETE`, `try`/`catch` + `!response.ok` → `500`); its `Allow: GET, PUT,
DELETE` and the previously stale `Allow` on `log-drains` (`GET, POST`)
now come from `createApiHandlers`
- Forwarded upstream error status and JSON body (falling back to `500` /
`{ error: { message } }`) in `api/graphql` and `api/rest`
- Parsed the JSON body once in `content/index.ts` `PUT` so the `not
found` create fallback does not attempt to re-read the request stream
- `content/index.ts` and `content/folders/index.ts` read query params
through `getSearchParamsRecord`, so repeated `ids` (and repeated GET
params on `content/index`) return `400` as they did with Next's query
parsing
- `run-lints` forwards headers via
`constructHeaders(Object.fromEntries(request.headers))`

**Added:**

- `getSearchParamsRecord` in `lib/api/apiHelpers.ts`: collects URL
search params into a record, mapping repeated keys to arrays so zod
string schemas reject them
- `folderQueryParamsSchema` and `listFolderContents(request, folderId?)`
in `lib/api/snippets.utils.ts`, shared by `content/folders/index` and
`content/folders/$id`
- `getLogflareConfig()` in `lib/api/self-hosted/logflare.ts`: reads the
Logflare env vars at call time (same `500` naming the missing vars) and
builds the request URLs and headers for `analytics/log-drains` and
`analytics/log-drains/$uuid`
- Unit tests for `getSearchParamsRecord`, `analytics/endpoints/$name`,
`analytics/log-drains/$uuid`, `content/index`, `content/folders`, and
`api/rest` (`HEAD` and upstream error forwarding)

**Removed:**

- Removed 2 unused routes
(`routes/api/platform/projects/$ref/config/index.ts` and
`routes/api/platform/projects/$ref/billing/addons.ts`) and regenerated
`routeTree.gen.ts`

**Behavior changes vs master:**

- `analytics/endpoints/$name` GET strips `name` and `ref` from the
forwarded query (parity with master, where they arrived as route params
in `req.query`)
- `content/folders` and `content/folders/$id` GET validate query params
and return `400` for invalid or repeated values
- `api/graphql` and `api/rest` forward upstream non-OK status codes and
error bodies instead of always returning `500`
- Unused `projects/$ref/config/index` and `projects/$ref/billing/addons`
routes have been removed

## Review instructions

1. Run `pnpm --filter studio exec vitest run lib/api/apiHelpers.test.ts
tests/routes/api/platform/projects/`.
2. On self-hosted Studio, create/update/delete a log drain,
create/save/delete a SQL snippet and folder, and verify REST/GraphQL API
docs load.

## Checklist

- [x] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [ ] If I wrote a new docs topic or edited an existing topic, I used
the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs
[style
guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide)

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-12-01 22:38:58 +08:00
Alaister YoungandAlaister Young b6c391a058 [FE-5114] (part 1) – refactor(studio): add native API helpers & routes (#54028)
## Problem

Studio's `routes/api/**` server routes still run legacy Next Pages
Router handlers through the `toWebHandler` shim in `compat/next/api.ts`.
Part 1 of 7 for
[FE-5114](https://linear.app/supabase/issue/FE-5114/rewrite-api-routes-as-native-tanstack-start-handlers-and-remove-the)
adds native TanStack Start (`Request` → `Response`) helpers and migrates
the top-level utility routes so we can remove the adapter at the end of
the stack.

## Solution

**Added:**

- `createApiHandlers` in `lib/api/apiWrapper.ts`: wraps native TanStack
Start route handlers with optional platform JWT auth, JSON `400` (`{
error: { message: 'Invalid JSON' } }`) on `InvalidJsonError`, Sentry
capture + generic `500` on unexpected throws, and an `ANY` handler that
returns `405` with an `Allow` header derived from the registered
methods. Exports `ApiHandler` / `ApiHandlerContext` (`params` is
`Record<string, string>`)
- `authenticateRequest` in `lib/api/apiAuthenticate.ts` (Web `Request`
counterpart of `apiAuthenticate`, same error messages)
- `InvalidJsonError` and `parseJsonBody` in `lib/api/apiHelpers.ts`
- `callRoute(route, request, params)` test helper in
`tests/lib/server-route.ts`
- Unit tests for `createApiHandlers` (exercising real
`authenticateRequest` through MSW in
`lib/api/createApiHandlers.test.ts`), `authenticateRequest`,
`parseJsonBody`, `/api/generate-attachment-url`, and
`/api/integrations/stripe-sync`

**Changed:**

- Updated `getRouteHandler` in `tests/lib/server-route.ts` to mirror
TanStack Start's `HEAD` → `GET` → `ANY` dispatch order
- Migrated 11 top-level API routes (`check-cname`,
`cli-release-version`, `content/graphql`, `edge-functions/test`,
`enabled-features-overrides`, `generate-attachment-url`,
`get-deployment-commit`, `get-ip-address`, `get-s3-keys`,
`get-utc-time`, `integrations/stripe-sync`) to native handlers
- Added `withAuth: true` to `check-cname`, `content/graphql`, and
`integrations/stripe-sync`, and updated `check-cname-mutation.ts` and
`data/graphql/execute.ts` to attach `constructHeaders()`
- Reused `withAuth` `claims` in `generate-attachment-url` to avoid a
duplicate GoTrue lookup in platform mode
- Converted `tests/routes/api/get-deployment-commit.test.ts` to
`callRoute`

**Removed:**

- Removed 2 unused routes (`routes/api/connect/index.ts` and
`routes/api/parse-query.ts`), dropped `/parse-query` from
`lib/hosted-api-allowlist.ts`, removed Nitro's `traceDeps:
['libpg-query*']` in `vite.config.ts` (no server runtime route imports
`libpg-query` anymore), and regenerated `routeTree.gen.ts`

**Behavior changes vs master:**

- Methods a route doesn't register now get a JSON `405` with an `Allow`
header (previously they fell through to the SSR app). `HEAD` requests
that TanStack Start dispatches to a `GET` handler also get `405`,
matching master's method switches
- `InvalidJsonError` returns JSON `{ error: { message: 'Invalid JSON' }
}` (`400`) instead of plain text
- `check-cname`, `content/graphql`, and `integrations/stripe-sync` now
verify the platform JWT via `withAuth: true`
- Unexpected throws return a generic `500` with `{ error: { message:
'Internal Server Error' } }`
- Unused `/api/connect` and `/api/parse-query` routes have been removed

## Review instructions

1. Run `pnpm --filter studio exec vitest run
lib/api/apiAuthenticate.test.ts lib/api/apiHelpers.test.ts
lib/api/apiWrappers.test.ts lib/api/createApiHandlers.test.ts
tests/routes/api/ scripts/__tests__/server-source-maps.test.ts`.
2. Smoke-test `/api/get-deployment-commit`, `/api/check-cname`,
`/api/content/graphql`, `/api/generate-attachment-url`, and
`/api/edge-functions/test` in Studio and confirm unsupported HTTP
methods return `405` with an `Allow` header.

## Checklist

- [x] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [ ] If I wrote a new docs topic or edited an existing topic, I used
the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs
[style
guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide)

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-12-01 20:53:57 +08:00
Alaister YoungandAlaister Young 5e7e9d2cf5 fix(studio): parse stripe sync bearer token without backtracking regex (#53254)
`getBearerToken` in the Stripe Sync API handler parsed the
`Authorization` header with `/^Bearer\s+(.+)$/i`. Both `\s+` and `(.+)`
can match whitespace, so a header made of `Bearer` and a long run of
whitespace backtracks in quadratic time (CodeQL `js/polynomial-redos`).
The token is now parsed with `slice`, a case-insensitive scheme check
and `trim`.

**Changed:**
- `apps/studio/lib/api/apiHelpers.ts` – new shared
`getBearerToken(authorization)` that parses in linear time. It returns
`null` for a missing, array-valued, non-Bearer or empty/whitespace-only
header. Previously a whitespace-only token returned `''` instead of
`null`, which still got a 401.
- `apps/studio/pages/api/integrations/stripe-sync.ts` – drops the local
regex helper and uses the shared one.
`apps/studio/routes/api/integrations/stripe-sync.ts` re-exports this
handler on `master`, so both routes get the fix.

**Added:**
- `apps/studio/lib/api/apiHelpers.test.ts` – `getBearerToken` cases: a
valid token, lowercase `bearer`, extra whitespace,
missing/array/wrong-scheme/empty headers, and a 100k-whitespace header
that has to return in under 100 ms (the old regex takes about 4 s).

No other API handlers in `apps/studio` or `packages/` use this regex.
The remaining `Authorization` parsing in `lib/api/apiAuthenticate.ts`
and `lib/gotrue.ts` uses `replace(/bearer /i, '')`, which runs in linear
time.

## To test
- [ ] On a project, install the Stripe Sync integration from Studio
(Integrations → Stripe Sync). Installation starts and finishes.
- [ ] Uninstall it again. Uninstallation starts and finishes.
- [ ] `curl -i -X POST <studio-url>/api/integrations/stripe-sync -H
'Authorization: Basic abc' -H 'Content-Type: application/json' -d '{}'`
returns 401. Do the same with `Authorization: Bearer` followed only by
spaces, and with no `Authorization` header: both return 401.

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-11-11 15:38:13 +09:00
Charis 205cbe7d26 chore(studio}: enforce import order, remove bare import specifiers (#44585) 2026-04-07 20:34:10 -04:00
Joshen LimandAlaister Young 91209faab1 Remove unused old env var (#41178)
* Remove unused old env var

* Update apps/studio/lib/api/apiHelpers.ts

Co-authored-by: Alaister Young <alaister@users.noreply.github.com>

* Fix

* Add comment

---------

Co-authored-by: Alaister Young <alaister@users.noreply.github.com>
2025-12-09 13:22:10 +08:00
Greg Richardson 9820707d71 feat: local mcp server (#38797)
* feat: local mcp server

* feat(local-mcp): implement migrations

* fix: remove unsupported mcp args

* feat(local-mcp): tests

* fix(local-mcp): packages to adhere to minimumReleaseAge

* fix(mcp): import path for createSupabaseApiPlatform

* fix(local-mcp): move tests out of pages/api dir

* refactor: self-hosted execute sql logic

* fix: deps
2025-09-23 12:00:08 -06:00
Jordi EnricandJoshen Lim 6e91494b16 Add coveralls integration (#35424)
* update gh action, update vitest config

* debug

* debug cov

* idk try something different

* test2

* test3

* add base path

* rm debug

* add apiAuthenticate tests

* supabaseClient tests

* apiWrappers tests

* add apiHelpers tests

* add configcat tests

* add formatSql tests

* add github tests

* add cloudprovider utils tests

* add helpers tests

* fix typeerr

* add missing readonly err

* fix typeerrrs

* fix type errors in apiWrapper tests

* fix apiHelpers test

* add packages/ui tests

* add coveralls flags

* try coveralls parallel config

* fix coveralls parallel config

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
2025-05-08 12:23:37 +02:00