mirror of
https://github.com/supabase/supabase.git
synced 2026-12-03 23:18:57 +00:00
## 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>
169 lines
4.7 KiB
TypeScript
169 lines
4.7 KiB
TypeScript
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
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 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)
|
|
}
|
|
|
|
/**
|
|
* Collect URL search params into a record. A key that appears more than once maps to an array of
|
|
* its values, so zod string schemas reject repeated params.
|
|
*/
|
|
export function getSearchParamsRecord(searchParams: URLSearchParams) {
|
|
const record: Record<string, string | string[]> = {}
|
|
for (const key of new Set(searchParams.keys())) {
|
|
const values = searchParams.getAll(key)
|
|
record[key] = values.length === 1 ? values[0] : values
|
|
}
|
|
return record
|
|
}
|
|
|
|
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()
|
|
}
|
|
}
|