mirror of
https://github.com/supabase/supabase.git
synced 2026-12-05 07:59:03 +00:00
## Problem Studio's `routes/api/platform/pg-meta/**` and `routes/api/v1/**` routes still run legacy Next Pages Router handlers through `compat/next/api.ts`, and 10 legacy `pg-meta` GET proxy routes are no longer called anywhere in the repo. Part 3 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 9 active routes to native TanStack Start handlers and deletes the 10 unused proxy routes. ## Solution **Changed:** - Migrated `platform/pg-meta/$ref/query/index.ts` and all 8 `v1` routes (`api-keys`, `api-keys/$id`, `config/auth/signing-keys/{index,legacy}`, `database/migrations`, `functions/{index,$slug/index}`, `types/typescript`) to `createApiHandlers`; `query` and `database/migrations` share `pgMetaErrorResponse` - Enabled `{ withAuth: true }` on `api-keys`, `api-keys/$id`, and `config/auth/signing-keys/{index,legacy}` for consistency with the other `v1` routes - Updated `api-keys` route tests to use `callRoute` **Added:** - `pgMetaErrorResponse(error)` in `lib/api/self-hosted/pg-meta.ts` (keeps a `PgMetaDatabaseError`'s status and `{ message, formattedError }` payload expected by `data/error-classification.ts`, otherwise `500`) - Unit test for `pg-meta/$ref/query` (`tests/routes/api/platform/pg-meta/$ref/query/index.test.ts`) **Removed:** - Removed all 10 unused `pg-meta` GET proxy routes (`column-privileges`, `extensions`, `foreign-tables`, `materialized-views`, `policies`, `publications`, `tables`, `triggers`, `types`, `views`), removed their `FETCH_TYPE_BYPASS_EXCEPTIONS` entries from `eslint.config.cjs`, and regenerated `routeTree.gen.ts` - Removed `getPgMetaRedirectUrl` (`lib/api/apiHelpers.ts`) and `parseRevealQuery` (`lib/api/self-hosted/api-keys.ts`) **Behavior changes vs master:** - Routes forward only `cookie` and `x-connection-encrypted` to pg-meta via `constructHeaders(Object.fromEntries(request.headers))`, matching what master's adapter forwarded - `database/migrations` GET now forwards headers to `listMigrationVersions` (master passed them as the wrong argument) - `v1/projects/$ref/api-keys*` and `config/auth/signing-keys*` now pass `{ withAuth: true }` (no-op in self-hosted mode; consistent with the other `v1` routes) - The 10 unused `pg-meta` GET proxy routes have been removed (`pg-meta/$ref/query` and `v1/projects/$ref/types/typescript` remain) ## Review instructions 1. Run `pnpm --filter studio exec vitest run tests/routes/api/v1/ tests/routes/api/platform/pg-meta/`. 2. On self-hosted Studio, load tables/views/policies/extensions, run a query in the SQL Editor, check API keys, and generate TypeScript types. ## 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>
172 lines
4.7 KiB
TypeScript
172 lines
4.7 KiB
TypeScript
import type { IncomingHttpHeaders } from 'node:http'
|
|
import { snakeCase } from 'lodash'
|
|
import z from 'zod'
|
|
|
|
import { IS_PLATFORM } from '@/lib/constants'
|
|
|
|
/**
|
|
* Construct headers for api request.
|
|
* For platform, it will include apiKey into the provided headers.
|
|
*
|
|
* To prevent relay frontend request headers like useragent, referrer... into the middleware requests.
|
|
* We will only keep the header keys that are in this list: Accept, Authorization, Content-Type, x-connection-encrypted
|
|
*/
|
|
export function constructHeaders(headers: { [prop: string]: any }) {
|
|
if (headers) {
|
|
const cleansedHeaders = {
|
|
Accept: headers.Accept,
|
|
Authorization: headers.Authorization,
|
|
cookie: headers.cookie,
|
|
'Content-Type': headers['Content-Type'],
|
|
'x-connection-encrypted': headers['x-connection-encrypted'],
|
|
} as any
|
|
// clean up key with underfined value
|
|
Object.keys(cleansedHeaders).forEach((key) =>
|
|
cleansedHeaders[key] === undefined ? delete cleansedHeaders[key] : {}
|
|
)
|
|
return {
|
|
...cleansedHeaders,
|
|
// [Joshen] JFYI both Alaister and I checked on this and realised this might not be used actually
|
|
// Could be safe to remove but leaving it here for now
|
|
...(!IS_PLATFORM && { apiKey: `${process.env.SUPABASE_SERVICE_KEY}` }),
|
|
}
|
|
} else {
|
|
return {
|
|
'Content-Type': 'application/json',
|
|
Accept: 'application/json',
|
|
}
|
|
}
|
|
}
|
|
|
|
// Typically for HTTP payloads
|
|
// @ts-ignore
|
|
export const toSnakeCase = (object) => {
|
|
const snakeCaseObject = {}
|
|
const snakeCaseArray = []
|
|
|
|
if (!object) return null
|
|
|
|
if (Array.isArray(object)) {
|
|
for (const item of object) {
|
|
if (typeof item === 'object') {
|
|
snakeCaseArray.push(toSnakeCase(item))
|
|
} else {
|
|
snakeCaseArray.push(item)
|
|
}
|
|
}
|
|
return snakeCaseArray
|
|
} else if (typeof object === 'object') {
|
|
for (const key of Object.keys(object)) {
|
|
if (typeof object[key] === 'object') {
|
|
// @ts-ignore
|
|
snakeCaseObject[snakeCase(key)] = toSnakeCase(object[key])
|
|
} else {
|
|
// @ts-ignore
|
|
snakeCaseObject[snakeCase(key)] = object[key]
|
|
}
|
|
}
|
|
return snakeCaseObject
|
|
} else {
|
|
return object
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Converts Node.js `IncomingHttpHeaders` to Fetch API `Headers`.
|
|
*/
|
|
export function fromNodeHeaders(nodeHeaders: IncomingHttpHeaders): Headers {
|
|
const headers = new Headers()
|
|
for (const [key, value] of Object.entries(nodeHeaders)) {
|
|
if (Array.isArray(value)) {
|
|
value.forEach((v) => headers.append(key, v))
|
|
} else if (value !== undefined) {
|
|
headers.append(key, value)
|
|
}
|
|
}
|
|
return headers
|
|
}
|
|
|
|
/**
|
|
* Zod transformer to parse boolean values from strings.
|
|
*
|
|
* Use when accepting a boolean value in a query parameter.
|
|
*/
|
|
export function zBooleanString(errorMsg?: string) {
|
|
return z.string().transform((value, ctx) => {
|
|
if (value === 'true') {
|
|
return true
|
|
}
|
|
|
|
if (value === 'false') {
|
|
return false
|
|
}
|
|
|
|
ctx.addIssue({
|
|
code: z.ZodIssueCode.custom,
|
|
message: errorMsg || 'must be a boolean string',
|
|
})
|
|
return z.NEVER
|
|
})
|
|
}
|
|
|
|
/**
|
|
* Transform a comma-separated string into an array of strings.
|
|
*
|
|
* Use when accepting a list of values in a query parameter.
|
|
*/
|
|
export function commaSeparatedStringIntoArray(value: string): string[] {
|
|
return value
|
|
.split(',')
|
|
.map((v) => v.trim())
|
|
.filter(Boolean)
|
|
}
|
|
|
|
const BEARER_SCHEME = 'bearer'
|
|
|
|
/**
|
|
* Extract the token from a `Bearer <token>` Authorization header (scheme is case-insensitive).
|
|
*
|
|
* Returns `null` for a missing, array-valued, non-Bearer or empty header. Parsed without a regex
|
|
* over the token so untrusted input can't trigger backtracking.
|
|
*/
|
|
export function getBearerToken(authorization: string | string[] | undefined | null) {
|
|
if (typeof authorization !== 'string') return null
|
|
|
|
const scheme = authorization.slice(0, BEARER_SCHEME.length)
|
|
const rest = authorization.slice(BEARER_SCHEME.length)
|
|
if (scheme.toLowerCase() !== BEARER_SCHEME || !/^\s/.test(rest)) return null
|
|
|
|
return rest.trim() || null
|
|
}
|
|
|
|
export class InternalServerError extends Error {
|
|
constructor(
|
|
message: string,
|
|
public details?: Record<string, unknown>
|
|
) {
|
|
super(message)
|
|
this.name = 'InternalServerError'
|
|
}
|
|
}
|
|
|
|
export class InvalidJsonError extends Error {
|
|
constructor(message = 'Invalid JSON') {
|
|
super(message)
|
|
this.name = 'InvalidJsonError'
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Parse a JSON request body. Empty bodies resolve to `{}` (matching prior API behavior);
|
|
* malformed JSON throws `InvalidJsonError` so route wrappers can return a 400 response.
|
|
*/
|
|
export async function parseJsonBody<T = unknown>(request: Request): Promise<T> {
|
|
const text = await request.text()
|
|
if (!text) return {} as T
|
|
try {
|
|
return JSON.parse(text) as T
|
|
} catch {
|
|
throw new InvalidJsonError()
|
|
}
|
|
}
|