mirror of
https://github.com/supabase/supabase.git
synced 2026-12-05 07:59:03 +00:00
## 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>
132 lines
4.1 KiB
TypeScript
132 lines
4.1 KiB
TypeScript
import * as Sentry from '@sentry/react'
|
|
import type { JwtPayload } from '@supabase/supabase-js'
|
|
import type { NextApiRequest, NextApiResponse } from 'next'
|
|
|
|
import { IS_PLATFORM } from '../constants'
|
|
import { apiAuthenticate, authenticateRequest } from './apiAuthenticate'
|
|
import { InvalidJsonError } from './apiHelpers'
|
|
import { isStudioError } from '@/lib/errors/studio-errors'
|
|
import type { ResponseFailure } from '@/types'
|
|
|
|
type ApiMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS'
|
|
|
|
export interface ApiHandlerContext {
|
|
request: Request
|
|
params: Record<string, string>
|
|
claims?: JwtPayload
|
|
}
|
|
|
|
export type ApiHandler = (ctx: ApiHandlerContext) => Response | Promise<Response>
|
|
|
|
type ServerRouteHandler = (ctx: {
|
|
request: Request
|
|
params?: Record<string, string>
|
|
}) => Promise<Response>
|
|
|
|
export function isResponseOk<T>(response: T | ResponseFailure | undefined): response is T {
|
|
if (response === undefined || response === null) {
|
|
return false
|
|
}
|
|
|
|
if (isStudioError(response)) {
|
|
return false
|
|
}
|
|
|
|
if (typeof response === 'object' && 'error' in response && Boolean(response.error)) {
|
|
return false
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
/**
|
|
* Wrap native TanStack Start API route handlers with optional platform JWT authentication,
|
|
* malformed-JSON 400 handling, Sentry error reporting, and 405 Method Not Allowed (with an
|
|
* `Allow` header derived from the registered methods) for any other method, via `ANY` and
|
|
* for a HEAD request dispatched to a GET-only handler.
|
|
*/
|
|
export function createApiHandlers<M extends ApiMethod>(
|
|
handlers: Record<M, ApiHandler>,
|
|
options?: { withAuth?: boolean }
|
|
): Record<M | 'ANY', ServerRouteHandler> {
|
|
const allowedMethods = Object.keys(handlers) as M[]
|
|
const wrapped = {} as Record<M | 'ANY', ServerRouteHandler>
|
|
|
|
const methodNotAllowed = (request: Request) =>
|
|
Response.json(
|
|
{ data: null, error: { message: `Method ${request.method} Not Allowed` } },
|
|
{ status: 405, headers: { Allow: allowedMethods.join(', ') } }
|
|
)
|
|
|
|
for (const method of allowedMethods) {
|
|
const handler = handlers[method]
|
|
wrapped[method] = async ({ request, params = {} }) => {
|
|
// TanStack Start dispatches HEAD to GET when no HEAD handler is registered.
|
|
if (request.method !== method) return methodNotAllowed(request)
|
|
|
|
try {
|
|
let claims: JwtPayload | undefined
|
|
|
|
if (IS_PLATFORM && options?.withAuth) {
|
|
const authResult = await authenticateRequest(request)
|
|
if (!isResponseOk(authResult)) {
|
|
return Response.json(
|
|
{ error: { message: `Unauthorized: ${authResult.error.message}` } },
|
|
{ status: 401 }
|
|
)
|
|
}
|
|
claims = authResult
|
|
}
|
|
|
|
return await handler({ request, params, claims })
|
|
} catch (error) {
|
|
if (error instanceof InvalidJsonError) {
|
|
return Response.json({ error: { message: 'Invalid JSON' } }, { status: 400 })
|
|
}
|
|
Sentry.captureException(error)
|
|
return Response.json({ error: { message: 'Internal Server Error' } }, { status: 500 })
|
|
}
|
|
}
|
|
}
|
|
|
|
wrapped.ANY = async ({ request }) => methodNotAllowed(request)
|
|
|
|
return wrapped
|
|
}
|
|
|
|
// Purpose of this apiWrapper is to function like a global catchall for ANY errors
|
|
// It's a safety net as the API service should never drop, nor fail
|
|
|
|
export async function apiWrapper(
|
|
req: NextApiRequest,
|
|
res: NextApiResponse,
|
|
handler: (
|
|
req: NextApiRequest,
|
|
res: NextApiResponse,
|
|
claims?: JwtPayload
|
|
) => Promise<NextApiResponse | Response | void>,
|
|
options?: { withAuth: boolean }
|
|
): Promise<NextApiResponse | Response | void> {
|
|
try {
|
|
const { withAuth } = options || {}
|
|
let claims: JwtPayload | undefined
|
|
|
|
if (IS_PLATFORM && withAuth) {
|
|
const response = await apiAuthenticate(req, res)
|
|
if (!isResponseOk(response)) {
|
|
return res.status(401).json({
|
|
error: {
|
|
message: `Unauthorized: ${response.error.message}`,
|
|
},
|
|
})
|
|
}
|
|
claims = response
|
|
}
|
|
|
|
return await handler(req, res, claims)
|
|
} catch (error) {
|
|
Sentry.captureException(error)
|
|
return res.status(500).json({ error })
|
|
}
|
|
}
|