mirror of
https://github.com/supabase/supabase.git
synced 2026-12-03 23:18:57 +00:00
docs/tutorial-template
664
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
923bbc16fd |
feat(studio): sample perf-relevant routes at a higher Sentry trace rate (#54205)
## Problem Studio traces run at a flat `tracesSampleRate` of 0.02. That's too few samples to trust per-surface perf numbers for the dashboard performance work, and raising the global rate would increase Sentry quota use everywhere. Part of [FE-3828](https://linear.app/supabase/issue/FE-3828/raise-sentry-sample-rate-for-perf-work-stand-up-a-studio-owned-perf). ## Solution Replace the flat rate with a `tracesSampler` (`lib/sentry-traces-sampler.ts`): - Project home, editor, SQL, auth and database routes are sampled at 0.2 (10x). - Everything else stays at 0.02. - Both rates are named constants. - The route pattern matches the TanStack route ID (`/project/$ref/editor`) and the resolved path, with or without the `/dashboard` base path. A pageload's transaction name is the raw path when it is sampled. - A sampling decision made upstream (for example a propagated `sentry-trace` header) is honored on navigations. - **Each pageload starts a new trace.** Studio serves one prerendered `_shell.html` to every visitor, and it carries `sentry-trace` and `baggage` meta tags frozen at build time. The pageload span continues the trace from them, so every full load shared one trace ID and one frozen `sample_rand`. A build whose frozen value was above the route rate could never sample a pageload, whatever the sampler returned. `initSentryTanStackClient` now removes those two tags before `Sentry.init`, so each pageload gets its own trace and is sampled at the route rate. This is temporary while the baseline is collected. To revert, delete `sentry-traces-sampler.ts` and restore `tracesSampleRate: 0.02` in `buildSentryClientOptions`. To only dial the boost down, lower `PERF_ROUTE_TRACES_SAMPLE_RATE`. The steps are also in a comment at the top of the sampler file. The server-side rate is unchanged. Not in this PR: the Sentry Performance view (initial load, per-surface navigation, request timings), which is built in the Sentry UI and tracked on the ticket. ## Review instructions 1. Read `apps/studio/lib/sentry-traces-sampler.ts` and check the route list, rates and pageload handling. 2. Run `pnpm --filter studio exec vitest run lib/sentry-traces-sampler.test.ts lib/sentry-client-options.test.ts sentry.tanstack.test.ts`. 3. On a preview, check in the Sentry transaction envelopes that a navigation to the editor, SQL, auth or database routes records `sample_rate` 0.2, and storage records 0.02. Do a full page load of the project home or table editor and confirm pageload transactions are now recorded for it, with a different trace ID per load. |
||
|
|
7e56800992 |
fix(assistant): update support assistant messaging for clarity and consistency (#54112)
## Problem The AI Assistant follow-up on support requests (behind the `supportAssistantFollowUp` flag) told users with service restrictions to ask Support for an exception. In almost every restriction ticket we reviewed during the production test, the Assistant suggested this, and Support then declined. ## Solution Rather than a rule for each ticket type, this adds one general rule to the server-side support-mode context and removes the "a human will reply" framing. `escalate_to_human` is unchanged, so users who ask for a person can still be escalated. ## Review instructions Read the diff to `assistant-context.ts` and `SupportAssistant.utils.ts`, and check that the rule is general and doesn't name a particular ticket type. ## Checklist Check all before review: - [x] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [x] 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) |
||
|
|
0c97b9789b |
[FE-3107] chore(studio): remove remaining Next.js references (#54426)
Removes the remaining Next.js dependencies, compatibility shims, test
mocks, ESLint/TypeScript presets, and webpack/Next workarounds from
Studio following the TanStack Start migration.
Addresses FE-3107.
**Removed:**
- `next` and `next-router-mock` from `apps/studio/package.json` (and
updated `pnpm-lock.yaml`)
- Orphaned `apps/studio/compat/next/script.tsx` shim, `script.test.tsx`,
`compat/**` knip entry, and `nextCompat()` / `ssr.noExternal` `/^next/`
plumbing from `apps/studio/vite.config.ts`
- `apps/studio/tests/lib/route-mock.ts` and all `next-router-mock`
setup/imports across `tests/vitestSetup.ts`,
`tests/lib/custom-render.tsx`, and 12 test files
- `apps/studio/tests/pages/` directory (moved the 3 remaining tests to
`components/interfaces/Organization/Organization.utils.test.ts` and
`apps/studio/tests/routes/`)
- Unused `'use client'` directives across 23 Studio files
- Next.js/webpack workarounds: `graphiqlViteWorkers()` in
`vite.config.ts`, webpack `import.meta.glob` `try/catch` fallback in
`ConnectStepsSection.tsx`, shell `NODE_ENV=test` override in
`vite.config.ts` / root `package.json` / `studio-e2e-test.yml`, Next
`getPathMatch` and `_next` passthrough in `redirects.shared.*`,
`window.next?.router` check in `monaco-graphiql-coexistence.spec.ts`,
and unused `ANALYZE` env var in `apps/studio/turbo.jsonc`
- Next-only Sentry/chunk-load filters (`NEXT_NOT_FOUND`,
`NEXT_REDIRECT`, Next `/org/[slug]/` regex, `/app:\/\//`, dead
`includeThirdPartyErrorFilter` plumbing, webpack chunk error regex) and
stale Next/Pages Router comments, docs, and `#__next` CSS selector
**Changed:**
- `apps/studio/eslint.config.cjs`: switched from
`eslint-config-supabase/next` to the new `eslint-config-supabase/react`
preset (dropping `@next/next/no-img-element: off`, keeping `.next` /
`next-env.d.ts` ignored for local checkouts with stale pre-migration
build artifacts)
- `apps/studio/tsconfig.json`: extends `tsconfig/base.json` directly
instead of `tsconfig/nextjs.json` (identical resolved compiler options)
- `apps/studio/.github/eslint-rule-baselines.json`: pruned 33 stale
`pages/...` and `types/next.ts` entries without changing any rule
thresholds
- `apps/studio/tests/lib/custom-render.tsx`: backed
`TestFrameworkProvider` with TanStack Router instead of
`next-router-mock`
-
`apps/studio/components/interfaces/Integrations/GraphQL/GraphiQLTab.tsx`:
imports `graphiql/setup-workers/vite` directly
- `apps/studio/styles/globals.css`: replaced `@source
'../pages/**/*.{js,ts,jsx,tsx}'` with `@source
'../routes/**/*.{js,ts,jsx,tsx}'`
- `apps/studio/turbo.jsonc`: declared `"NEXT_PUBLIC_*"` in
`tasks.build.env` now that Turborepo infers `nitro` instead of `nextjs`
-
`apps/studio/components/interfaces/Organization/Organization.utils.ts`:
narrowed `buildOrgUrl`'s `slug` parameter to `string[] | undefined`
**Added:**
- `packages/eslint-config-supabase/shared.js` and
`packages/eslint-config-supabase/react.js` (plus `presets.test.ts`),
decoupling non-Next React apps from `eslint-config-next` with verified
zero non-`@next/*` rule drift while keeping
`eslint-config-supabase/next` unchanged for the Next.js apps
## To test
- Run `pnpm --filter eslint-config-supabase run test` and confirm preset
parity tests pass
- Run `pnpm --filter studio run lint`, `pnpm --filter studio run
lint:ratchet`, `pnpm --filter studio run typecheck`, `pnpm knip
--workspace apps/studio`, and `pnpm --filter studio run test`
- Run `pnpm --filter studio run build` and verify the production build,
prerendered routes, chunk-cycle check, and GraphiQL web workers succeed
- Smoke-test Studio locally (`pnpm dev:studio`): verify GraphiQL loads
cleanly, ConnectSheet framework steps render, and Tailwind styles on
route pages are intact
---------
Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
|
||
|
|
07101b6894 |
[FE-3200] chore(studio): lift bundler workarounds and stabilize hooks (#54121)
Cleans up obsolete Rolldown/Vite bundler workarounds from the TanStack Start migration and fixes unstable router selectors and inline default array props that could cause unnecessary re-renders or render loops. Addresses [FE-3200](https://linear.app/supabase/issue/FE-3200/lift-bundler-workarounds-and-fix-latent-issues-next-was-masking). **Removed:** - Emptied `KNOWN_CHUNK_CYCLES` in `apps/studio/vite.config.ts` while keeping the `assertNoChunkCycles` build guard enabled - Removed obsolete `manualChunks` workarounds (`class-variance-authority`, `ui-field`, `ui-drawer`, `ui-form`, `ui-sidebar`, `ui-slider`, `ui-avatar`), keeping the React and `lucide-react` vendor chunks so React stays a single leaf chunk and Lucide does not fan out into per-icon modulepreload requests - Removed the obsolete `sharedDefines` (`global: 'globalThis'`) substitution from `apps/studio/vite.config.ts` **Changed:** - `StudioLink` (`StudioFrameworkProvider.tsx`): split `useRouterState` into primitive `currentPathname` and `currentSearch` selectors instead of returning a fresh object on every router state tick - `useNuqsTanStackRouterAdapter` (`nuqs-tanstack-adapter.tsx`): select a serialized query string key from `useLocation` so `useQueryState` consumers do not re-render when unwatched search params change - `FilterPopover`: replaced inline `[]` defaults for `options` and `activeOptions` with shared `EMPTY_ARR` (`@/lib/void`), and guarded `setSelectedOptions` with an element-wise equality check when closed - `InputWithSuggestions`: replaced inline `[]` default for `suggestions` with shared `EMPTY_ARR` (`@/lib/void`) so `useEffect` does not loop when `suggestions` is omitted at runtime **Added:** - Regression tests covering router selector stability and default-prop render loops in `StudioFrameworkProvider.test.tsx`, `nuqs-tanstack-adapter.test.tsx`, `FilterPopover.test.tsx`, and `InputWithSuggestions.test.tsx` ## To test - Run `pnpm --filter studio run build` and verify the build passes with `KNOWN_CHUNK_CYCLES` empty and `assertNoChunkCycles` enabled - Run the new/updated unit tests in `apps/studio` (`StudioFrameworkProvider.test.tsx`, `nuqs-tanstack-adapter.test.tsx`, `FilterPopover.test.tsx`, `InputWithSuggestions.test.tsx`) - Smoke-test Studio navigation, URL search-param filters (`nuqs`), Table Editor column suggestions, `FilterPopover` interactions, and `/auth/hooks` (confirming no `global` ReferenceError) --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
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> |
||
|
|
ccd691423b |
[FE-5114] (part 6) – refactor(studio): migrate platform storage routes (#54033)
## Problem Studio's `routes/api/platform/storage/**` routes still run legacy Next Pages Router handlers through `compat/next/api.ts`, and `buckets/$id/objects/download.ts` has no remaining callers. Part 6 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 14 active storage routes to native TanStack Start handlers and removes the unused download route. ## Solution **Changed:** - Migrated 14 `buckets/**` and `vector-buckets/**` routes to `createApiHandlers` and `parseJsonBody` - Replaced the `parseAsInt`/`parseAsString`/`parseAsStringEnum` helpers in `buckets/index.ts` with a zod query schema that drops invalid values, keeping the conditional spreads so unset keys aren't sent to storage-js - Forwarded upstream `StorageError` status codes across all storage and vector-bucket routes via `storageErrorResponse` / `getStorageErrorStatus` (falling back to the route's default 400/500 when no valid HTTP status is present) - Guarded missing/invalid `SUPABASE_PUBLIC_URL` with a `500` error response in `objects/public-url`, `objects/sign`, and `objects/sign-multi` - Typed the `vector-buckets/$id/indexes` POST body from storage-js's `createIndex` options - Corrected stale `Allow` headers on `vector-buckets/$id` (`GET, DELETE`) and `vector-buckets/$id/indexes/$indexName` (`DELETE`) via `createApiHandlers` **Added:** - `lib/api/self-hosted/storage.ts` with `getStorageErrorStatus`, `storageErrorResponse`, `getStoragePublicOrigin`, `missingStoragePublicUrlResponse`, and `remapStoragePublicUrl` - Unit tests for `buckets/index` query parsing, `buckets/$id/objects/sign-multi` (`SUPABASE_PUBLIC_URL` guard, origin remapping, and upstream error status), and `vector-buckets` POST (exercising the real storage client through MSW) **Removed:** - Removed unused `routes/api/platform/storage/$ref/buckets/$id/objects/download.ts` and regenerated `routeTree.gen.ts` **Behavior changes vs master:** - `buckets` GET drops malformed `limit`/`offset`/sort values instead of `parseInt`-truncating them (e.g. `offset=1.5` is ignored rather than sent as `1`) - `vector-buckets` POST validates the body with zod and returns `400` when `bucketName` is missing or not a string - Storage routes forward the upstream HTTP status code from `StorageApiError` instead of hardcoding `400`/`500` - `objects/public-url`, `objects/sign`, and `objects/sign-multi` return a `500` JSON error when `SUPABASE_PUBLIC_URL` is unset or invalid instead of throwing an uncaught `TypeError` - Unused `buckets/$id/objects/download` route has been removed ## Review instructions 1. Run `pnpm --filter studio exec vitest run tests/routes/api/platform/storage/`. 2. On self-hosted Studio, create/list/empty/delete a storage bucket, upload/download/move/sign/delete an object, and check vector bucket operations. ## 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> |
||
|
|
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> |
||
|
|
975689dcfc |
feat(studio): send pageview and global crash metrics on staging and preview (#54331)
## Problem We need simple counts of every pageview and every global crash for SLO monitoring. These counts need to go to observability ingest, not to Sentry, etc., so they can be part of our Grafana dashboards pipeline. ## Solution - `usePageviewMetric` sends one `pageview` event on first load (hydration) and on every client-side navigation that changes the pathname. Changes to only the query string or hash do not count. - A `global_crash` event is sent once when the global crash screen is shown. That covers both the root `ErrorBoundary` and the root route `errorComponent`. Chunk-load errors that are recovered by an automatic reload are not counted, which matches what is reported to Sentry. - Both are gated by a new `IS_STAGING_OR_PREVIEW` constant. It is false on production, local development, self-hosted and Nimbus. - The request is a fire-and-forget `fetch` with `keepalive: true` and `credentials: 'omit'`. It uses a `text/plain` body, so there is no CORS preflight. Errors are swallowed. - The endpoint origin is added to `connect-src` for all platform environments, because production will need it later. No other CSP directive changes. ## Review instructions 1. Open the Studio preview deployment for this PR with the network panel open. 2. Load any page. See one `POST /api/metrics` request that returns 204. 3. Navigate to another page. See one more request. 4. Change only a query parameter (for example a table filter). See no new request. ## Checklist Check all before review: - [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) |
||
|
|
be32a941cd |
[FE-5114] (part 4) – refactor(studio): migrate platform auth and misc routes (#54031)
## Problem Studio's `routes/api/platform/auth/**` and platform misc/stub routes still run legacy Next Pages Router handlers through `compat/next/api.ts`, and 4 legacy database/props routes have no callers left. Part 4 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 16 active routes to native TanStack Start handlers and removes the 4 unused ones. ## Solution **Changed:** - Migrated `platform/auth/$ref/{invite,magiclink,otp,recover}` to one-line `createAuthSenderHandlers` routes, and `users/index`, `users/$id/index`, and `users/$id/factors` to `createApiHandlers`, preserving the FE-5124 fixes (`Promise.all` MFA factor deletion, `code ?? 500` on auth senders, `Allow: PATCH, DELETE` on `users/$id`, now derived by `createApiHandlers`) - Migrated 9 platform misc/stub routes (`deployment-mode`, `integrations/{$slug,github/*}`, `organizations/{index,$slug/billing/subscription}`, `profile/index`, and `telemetry/event`) - Moved the `FETCH_TYPE_BYPASS_EXCEPTIONS` entries for the four sender routes in `eslint.config.cjs` to `lib/api/self-hosted/auth-senders.ts` **Added:** - `createAuthSenderHandlers(endpoint, field)` in `lib/api/self-hosted/auth-senders.ts`: shared POST handler for the self-hosted GoTrue `invite`, `magiclink`, `otp`, and `recover` endpoints (forwards only `email` or `phone`, uses `constructHeaders` with the service role key, and passes upstream errors through with `code ?? 500`) - Regression tests for `auth/$ref/users/$id/factors`, `auth/$ref/users/$id`, and all four auth sender routes **Removed:** - Removed 4 unused routes (`platform/database/$ref/pooling`, `platform/props/org/$slug`, `platform/props/project/$ref/index`, and `platform/props/project/$ref/api`) and regenerated `routeTree.gen.ts` ## Review instructions 1. Run `pnpm --filter studio exec vitest run tests/routes/api/platform/auth/`. 2. On self-hosted Studio, invite/ban/delete a user, remove MFA factors for a user, and confirm `GET /api/platform/auth/default/users/<id>` returns `405` with `Allow: PATCH, DELETE`. ## 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> |
||
|
|
20a5212c42 |
[FE-5114] (part 3) – refactor(studio): migrate pg-meta and v1 routes (#54030)
## 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> |
||
|
|
c5fca0a0d7 |
[FE-5114] (part 2) – refactor(studio): migrate AI API routes (#54029)
## Problem Studio's AI API routes under `routes/api/ai/**` still run legacy Next Pages Router handlers through `compat/next/api.ts`. Part 2 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 active AI routes to native TanStack Start (`Request` → `Response`) handlers and drops 3 unused AI endpoints. ## Solution **Changed:** - Migrated 8 active AI routes (`ai/code/complete`, `ai/feedback/{classify,rate}`, and `ai/sql/{check-api-key,cron-v2,filter-v1,generate-v4,title-v2}`) to `createApiHandlers` and `parseJsonBody` - Replaced Node `pipeUIMessageStreamToResponse` in `ai/sql/generate-v4.ts` with native `createUIMessageStreamResponse`, preserving the `x-braintrust-span-id` header - Replaced `req.on`/`res.on` in `ai/sql/generate-v4.ts` with `AbortSignal.any([request.signal, done.signal])` and a `TransformStream` whose `flush`/`cancel` tear down the MCP connection opened in `getTools` on stream completion, cancellation, or setup error - Removed the custom malformed-JSON handling in `ai/code/complete.ts` in favor of the wrapper's `400` - Updated `lib/api/generate-v4.test.ts` to assert against the real native SSE `Response` stream instead of mocking `pipeUIMessageStreamToResponse`, with a shared `mockOpenStream()` helper, a stream-cancellation abort test, and a Braintrust tracing test asserting `x-braintrust-span-id` matches the exported root span - Updated `lib/ai/README.md` to drop references to removed endpoints **Removed:** - Removed 3 unused AI routes (`routes/api/ai/onboarding/design.ts`, `routes/api/ai/sql/parse-client-code.ts`, and `routes/api/ai/sql/policy.ts`), dropped them from `lib/hosted-api-allowlist.ts`, and regenerated `routeTree.gen.ts` - Removed the now-unused `withoutApprovalTools` helper from `lib/ai/tool-filter.ts` and its test from `lib/ai/tool-filter.test.ts` **Behavior changes vs master:** - `ai/code/complete` returns the wrapper's `400` JSON `{ error: { message: 'Invalid JSON' } }` for malformed bodies - Unused `ai/onboarding/design`, `ai/sql/parse-client-code`, and `ai/sql/policy` endpoints have been removed ## Review instructions 1. Run `pnpm --filter studio exec vitest run lib/api/generate-v4.test.ts lib/api/rate.test.ts lib/ai/tool-filter.test.ts`. 2. Send a prompt in the AI Assistant panel, verify streaming output, and cancel mid-stream. 3. Trigger SQL title, cron, and filter generation as well as AI code completion. ## 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> |
||
|
|
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> |
||
|
|
e395e057cf |
[FE-5108] (part 6) chore(studio): remove next/link shim and Vite alias (#54309)
Part 6 (final) of a 6-PR stack migrating all `next/link` imports in `apps/studio` onto TanStack Router's `Link` (or plain `<a>` for known external URLs) and removing `compat/next/link.tsx`. | Part | PR | Scope | | --- | --- | --- | | 1 | #54304 | `data/prefetchers/PrefetchableLink.tsx` and `components/ui/**` | | 2 | #54305 | `components/layouts/**` and top-level shell components | | 3 | #54306 | Database, TableGridEditor, Storage, SQLEditor, BranchManagement, Branching, Functions, Realtime | | 4 | #54307 | Integrations, Settings, Observability, LogDrains, Issues, Linter, Reports, QueryPerformance, QuerySources, ConfigDrift, DiskManagement, Compute | | 5 | #54308 | Remaining `components/interfaces/**` (Org, Billing, Auth, Support, Home, SignIn, ConnectSheet, etc.) | | **6** | **#54309 ← this PR** | **Remove `compat/next/link.tsx` shim, Vite alias, and update basePath tests/docs** | Now that no files in `apps/studio` import `next/link`, deletes `compat/next/link.tsx` and removes its Vite alias so any future `next/link` import fails the build. **Removed:** - `apps/studio/compat/next/link.tsx` - `'next/link'` entry from `nextShims` in `apps/studio/vite.config.ts` **Changed:** - Moved `apps/studio/compat/next/link-basepath-navigation.test.tsx` to `apps/studio/lib/navigation-basepath.test.tsx` to keep basePath navigation coverage for `DynamicLink` and `navigateToUrl` - Updated `nextCompat()` error text in `apps/studio/vite.config.ts` and routing docs in `apps/studio/AGENTS.md` to reflect that only `next/script` remains shimmed - Cleaned up stale `next/link` / `Link shim` comments in `apps/studio/lib/internal-url.ts`, `apps/studio/lib/router-url-shape.test.tsx`, and `knip.jsonc` Addresses [FE-5108](https://linear.app/supabase/issue/FE-5108/replace-the-nextlink-shim-with-tanstack-link) ## To test - [ ] Confirm `git grep -E 'next/link|compat/next/link' apps/studio knip.jsonc` returns zero matches - [ ] Confirm Studio typecheck, ESLint ratchet, Knip, production Vite build, and Vitest suite pass - [ ] Spot-check `apps/studio/lib/navigation-basepath.test.tsx` and `apps/studio/lib/router-url-shape.test.tsx` Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
477e2c136f |
[FE-5109] (part 6) chore(studio): remove next/router shims, aliases, and test mocks (#54058)
Part 6 (final) of a 6-PR stack migrating all `next/router` and `next/compat/router` imports in `apps/studio` onto TanStack Router hooks and removing the router shims. | Part | PR | Scope | | --- | --- | --- | | 1 | #54053 | Core navigation helpers, `hooks/**`, `lib/**`, `data/prefetchers/**` | | 2 | #54054 | `components/ui/**` | | 3 | #54055 | `components/layouts/**` and `state/tabs.tsx` | | 4 | #54056 | Database, Branching, Compute, Edge Functions, Explorer, SQL Editor, Storage, Table Editor | | 5 | #54057 | Remaining `components/interfaces/**` and `QueryInsightsTable` router events | | **6** | **#54058 ← this PR** | **Remove `next/router` & `next/compat/router` shims, `_router-events.ts`, Vite aliases, and test mocks** | Now that no files in `apps/studio` (or `packages/**`) import `next/router` or `next/compat/router`, deletes the router shims, `_router-events.ts`, their Vite aliases, and the obsolete router test mocks. `RouteValidationWrapper` is intentionally left for FE-3107. **Removed:** - `apps/studio/compat/next/router.ts`, `apps/studio/compat/next/compat/router.ts`, and `apps/studio/compat/next/_router-events.ts` - `'next/router'` and `'next/compat/router'` entries from `nextShims` in `apps/studio/vite.config.ts` - Global `vi.mock('next/router', ...)` and `vi.mock('next/compat/router', ...)` in `apps/studio/tests/vitestSetup.ts`, `mockNextRouter` in `apps/studio/tests/lib/route-aware-hooks.ts`, and the unused `vi.mock('next/router')` in `tests/features/logs/LogTable.test.tsx` - Obsolete shim tests and test helpers: `compat/next/router.test.ts`, `compat/next/router-navigation.test.tsx`, `tests/config/router.tsx`, and `tests/config/router.test.tsx` **Changed:** - Simplified `createNavigationHandler` in `apps/studio/lib/navigation.ts` (and `navigation.test.ts`) to accept TanStack's `UseNavigateResult<string>` only, dropping the `NextRouter` union branch - Updated `compat/next/link-basepath-navigation.test.tsx` (renamed from `router-basepath-navigation.test.tsx`), `lib/router-url-shape.test.tsx`, and `tests/lib/route-render.test.tsx` to exercise TanStack Router hooks directly instead of the removed router shim - Cleaned up stale `next/router` comments in `compat/next/link.tsx`, `lib/internal-url.ts`, `router.tsx`, and `tests/lib/route-mock.ts` **Simplified:** - Removed `routerMock` setup from about 19 tests that no longer read it. `next-router-mock` stays for now, because the test `FrameworkProvider` still feeds `useParams` from it. - `AGENTS.md` and the `vite.config.ts` error text now say only `next/link` and `next/script` are shimmed - Renamed `compat/next/router-basepath-navigation.test.tsx` to `link-basepath-navigation.test.tsx`, and removed stale router-shim references from comments Addresses [FE-5109](https://linear.app/supabase/issue/FE-5109/replace-the-nextrouter-shims-with-tanstack-router-hooks) ## To test - [ ] Confirm `git grep -E "next/(compat/)?router|_router-events" apps/studio` returns no code or config imports (only the prose guideline in `apps/studio/AGENTS.md`) - [ ] Confirm `pnpm --filter studio run typecheck`, `pnpm --filter studio run lint`, `pnpm --filter studio run build`, Knip, and the full Studio Vitest suite pass - [ ] Spot-check basePath navigation (`next/link` + `navigateToUrl`) and multi-line query param URLs in Studio --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
57d40e4705 |
[FE-5109] (part 3) refactor(studio): migrate layout components off next/router (#54055)
Part 3 of a 6-PR stack migrating all `next/router` and `next/compat/router` imports in `apps/studio` onto TanStack Router hooks and removing the router shims. | Part | PR | Scope | | --- | --- | --- | | 1 | #54053 | Core navigation helpers, `hooks/**`, `lib/**`, `data/prefetchers/**` | | 2 | #54054 | `components/ui/**` | | **3** | **#54055 ← this PR** | **`components/layouts/**` and `state/tabs.tsx`** | | 4 | #54056 | Database, Branching, Compute, Edge Functions, Explorer, SQL Editor, Storage, Table Editor | | 5 | #54057 | Remaining `components/interfaces/**` and `QueryInsightsTable` router events | | 6 | #54058 | Remove `next/router` & `next/compat/router` shims, `_router-events.ts`, Vite aliases, and test mocks | Migrates all `apps/studio/components/layouts/**` files and the studio tab router integration off `next/router`. **Added:** - `useTabRouter()` in `apps/studio/state/tabs.tsx` so tab state actions navigate via TanStack's `useNavigate` + `navigateToUrl` instead of taking a `NextRouter` instance **Changed:** - Replaced `useRouter` across all layout directories (`AccountLayout`, `AdvisorsLayout`, `AppLayout`, `AuthLayout`, `BranchLayout`, `ComputeLayout`, `DatabaseLayout`, `DefaultLayout`, `EdgeFunctionsLayout`, `ExplorerLayout`, `LogsLayout`, `Navigation/*`, `ObservabilityLayout`, `OrganizationLayout`, `ProjectLayout`, `ProjectNeedsSecuring`, `ProjectSettingsLayout`, `RealtimeLayout`, `SQLEditorLayout`, `SignInLayout`, and `Tabs`) with TanStack Router hooks (`useNavigate`, `useLocation`, `useRoutePattern`) and `useParams` from `common` - Updated `ProjectDropdown.utils.ts` and `ProjectDropdown.test.ts` to work with TanStack `$param` route templates - Updated layout component tests (`AccountLayout.selfhosted.test.tsx`, `AdvisorsNavigationShortcuts.test.tsx`, `BranchLink.test.tsx`, `ExplorerLayout.test.tsx`, `ExplorerNavChats.test.tsx`, `ObservabilityMenu.utils.test.tsx`, `MobileIssuesNavigation.platform.test.tsx`, `ProjectLayout/index.test.tsx`, `ProjectNeedsSecuring.test.tsx`, `ProjectDropdown.test.tsx`) **Simplified:** - `OrganizationLayout` and `SettingsLayout` match against `useRoutePattern()` instead of the real pathname. An org slug ending in a settings segment (e.g. `acmeapps`) no longer gets the settings title. - `ProjectSettings.Commands` opens the Connect sheet through nuqs, the same way `Connect.Commands` does - `OrgMenuContent`, `OrganizationSettingsMenu` and `useTabRouter` read `orgSlug`/`schema` from `useParams` instead of casting `location.search` - Removed the dead `getPathnameWithoutQuery` helpers and their tests - `usePreservedQueryParams` builds its string in the `useLocation` selector (no `useMemo`), and `UnhealthyState` only navigates when `ref` is set - Moved `MobileIssuesNavigation.platform.test.tsx` onto a TanStack test router. It now covers the active-route logic again. - Tests use the shared `createTestRouter` and `customRender` router Addresses [FE-5109](https://linear.app/supabase/issue/FE-5109/replace-the-nextrouter-shims-with-tanstack-router-hooks) ## To test - [ ] Switching projects, organizations, and branches from the top header dropdowns preserves the current sub-route where supported - [ ] Opening, switching, and closing Table Editor / SQL Editor tabs updates the URL and active tab cleanly - [ ] Active sidebar item highlighting works across Database, Auth, Edge Functions, Observability, Logs, Realtime, Explorer, and Project Settings layouts - [ ] Mobile navigation menu and floating toolbar sheets open and navigate properly --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
c2edb29076 |
fix(studio): explain Supavisor session pool limits DEBUG-43 (#53930)
## Problem When Supavisor rejects a session because its connection pool is full, Studio shows the error without explaining how to recover. ## Fix Show a troubleshooting step for the session-mode limit that explains how pool size limits concurrent clients and links to the configuration guide. ## Screenshot The Table Editor’s troubleshooting step, rendered locally with a sample session-pool error. <img width="660" alt="Expanded Supavisor session pool limit guidance in the Table Editor" src="https://github.com/user-attachments/assets/6072eec4-e243-4d53-a40f-30fb14d21d05" /> ## How to test - Display a classified MaxClientsInSessionMode error in Studio and expand its troubleshooting step. The link should open the pool size section of the database connection management guide. - Display a generic transaction-mode connection limit error. It should keep its usual fallback. - The pattern, classification and ErrorMatcher suites exercise these paths (144 tests passed locally). Fixes [DEBUG-43](https://linear.app/supabase/issue/DEBUG-43). |
||
|
|
90a0bcdcfe |
feat(studio): bump @supabase/mcp-server-supabase to 0.20.0 and pass schemas to type generation (#54139)
## Problem Self-hosted Studio still uses `@supabase/mcp-server-supabase` 0.17.0, two releases behind even before [0.20.0](https://github.com/supabase/mcp/releases/tag/mcp-server-supabase-v0.20.0). ## Solution Bump `^0.17.0` to `^0.20.0` in `apps/studio/package.json` and update the lockfile, which takes `@supabase/mcp-utils` from 0.10.0 to 0.11.1. The platform interface only gained optional arguments, so the bump itself compiles without changes. - The debugging group gains `get_issues`, which covers security and performance checks on self-hosted. It reports the health check as unavailable because self-hosted has no health advisors. - `generate_typescript_types` now accepts an optional `schemas` parameter. Without this fix, self-hosted would silently ignore it and could return types for different schemas than the caller requested. `lib/api/self-hosted/mcp.ts` now passes `schemas` to `generateTypescriptTypes` in `lib/api/self-hosted/generate-types.ts`, which sends it to pg-meta as `included_schemas`. When the caller omits `schemas`, self-hosted still uses the schemas PostgREST exposes. Tests in `generate-types.test.ts` and `mcp.test.ts` cover both cases. The MCP Apps support from 0.18.0 and 0.19.0 stays off because Studio doesn’t opt in. ## Review instructions 1. Confirm CI passes. 2. With self-hosted Studio running, connect an MCP client to `/api/mcp` and confirm `tools/list` includes `get_issues`. 3. Call `generate_typescript_types` with `schemas: ["auth"]` (or another schema PostgREST doesn’t expose) and confirm it returns types only for the requested schema. Closes [AI-1582](https://linear.app/supabase/issue/AI-1582) |
||
|
|
23424bec35 | fix(studio): use Databow for Warehouse connections (#54147) | ||
|
|
d98f706b7c |
[FE-5109] (part 1) refactor(studio): migrate core hooks, lib, and prefetchers off next/router (#54053)
Part 1 of a 6-PR stack migrating all `next/router` and `next/compat/router` imports in `apps/studio` onto TanStack Router hooks and removing the router shims. | Part | PR | Scope | | --- | --- | --- | | **1** | **#54053 ← this PR** | **Core navigation helpers, `hooks/**`, `lib/**`, `data/prefetchers/**`** | | 2 | #54054 | `components/ui/**` | | 3 | #54055 | `components/layouts/**` and `state/tabs.tsx` | | 4 | #54056 | Database, Branching, Compute, Edge Functions, Explorer, SQL Editor, Storage, Table Editor | | 5 | #54057 | Remaining `components/interfaces/**` and `QueryInsightsTable` router events | | 6 | #54058 | Remove `next/router` & `next/compat/router` shims, `_router-events.ts`, Vite aliases, and test mocks | Introduces the shared TanStack navigation helpers needed across the stack and migrates `hooks/**`, `lib/**`, and `data/prefetchers/**` off `next/router`. **Added:** - `navigateToUrl` in `apps/studio/lib/navigation.ts` (plus unit tests in `lib/navigation.test.ts`): shared helper for navigating to internal string URLs via TanStack's `useNavigate` (splitting pathname, search params, and hash via `splitInternalUrl`, and handling external/protocol-relative URLs) - `useRoutePattern` in `apps/studio/hooks/misc/useRoutePattern.ts` (plus `useRoutePattern.test.tsx`): returns the active matched TanStack route template (e.g. `/project/$ref/editor/$id`) as the replacement for Next's `router.pathname` **Changed:** - Migrated `hooks/misc/*` (`useHydratedQuery`, `useStudioCommandMenuTelemetry`, `useTableEditorFiltersSort`, `withAuth`) and `hooks/use-check-latest-deploy.tsx` to TanStack's `useLocation`, `useNavigate`, `useRoutePattern`, and `useParams` from `common` - Migrated `lib/profile.tsx` and `lib/telemetry/track.ts` off `next/router` - Migrated `data/prefetchers/project.$ref.tsx`, `project.$ref.editor.tsx`, and `project.$ref.editor.$id.tsx` to `useRouter().preloadRoute` - Wrapped `ReactQueryTestConfig` in `apps/studio/tests/helpers.tsx` with `RouterContextProvider` and updated hook/navigation tests (`useTableEditorFiltersSort*.test.*`, `useFilterLifeCycle.navigation.test.tsx`, `useTableFilter.navigation.test.tsx`, `useInboundBranding.test.ts`, `state/tabs.test.ts`) **Simplified:** - `navigateToUrl` passes `replace` straight through and documents that `url` must be an app-relative path or an external URL. `StudioFrameworkProvider`'s `push` now reuses it. - `useRoutePattern` reads matches and location in a single `useRouterState` subscription - `useTrack` and `useStudioCommandMenuTelemetry` take the pathname from `useFramework()`, the same source as pageviews, so custom events and pageviews always send the same pattern (e.g. `/project/[ref]/sql/[id]`). New tests pin the strings sent, and `toRoutePattern` now has its own unit tests. - Removed `useCurrentPath` (a one-line wrapper with one consumer): `OrganizationSettingsLayout` calls `useLocation` directly - Dropped the no-op `.catch(() => {})` on `preloadRoute` in the prefetchers (`preloadRoute` never rejects) - `useTableEditorFiltersSort` builds the next search with a spread instead of a delete loop - Added `createTestRouter()` to `tests/lib/custom-render.tsx`, and `customRender`/`customRenderHook` now return the `router`. The rest of the stack uses these instead of hand-copied `createRouter` setups. Addresses [FE-5109](https://linear.app/supabase/issue/FE-5109/replace-the-nextrouter-shims-with-tanstack-router-hooks) ## To test - [ ] Auth redirect flow (`withAuth`) still preserves `returnTo` query parameters when redirecting unauthenticated users to `/sign-in` - [ ] Table Editor sort and filter URL sync (`useTableEditorFiltersSort`) persists and clears `?sort=` / `?filter=` across table switches - [ ] Hovering project and table editor links still triggers route/data prefetching without console errors - [ ] Page view and command menu telemetry still records route patterns and paths accurately --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
d336555617 |
fix(telemetry): redact url params and page titles (#54044)
The frontend apps send the current URL and page title with every analytics event. The redaction added in #53500 and extended in #53955 only covers the `keywords` and `schema` params, so Table Editor filters, search text, invite tokens, OAuth codes and the auth redirect hash still go out in URL properties, and Studio's title carries the table, project and org names. **Changed:** - **Query values are redacted by default**: every `name=value` in a URL property now goes out as `name=redacted`, unless the name is one that attribution reads downstream (`utm_*`, the click ids the first-referrer cookie already collects, `dub_id`, `campaign_id`, `cid`, `promo_code`). Param names and the `?` stay, so reports that match on a param being present keep working. Fixed-vocabulary params such as `tab` are not on the list: nothing reads them today, and several of those names carry customer data on other pages. - **A change to a redacted value no longer sends a pageview**: picking a new filter value on the same page used to send a pageview, which would now be identical to the previous one. The dedupe check compares the redacted URL, so it is skipped. This lowers Studio pageview counts: on current traffic, at most about 9% of dashboard pageviews repeat the previous path with a query string. - **Events from both transports are covered, and the hash is dropped**: `identify` and `group` let the SDK stamp its own `$current_url` with the hash, and `$set_once` pinned that on the person. `before_send` now strips it, and the SDK no longer captures hashes itself. Custom events skip `before_send`, so the same redaction also runs on their `pathname` field, where www was appending the raw query string. The SDK's copy of a search-engine referrer's query (`ph_keyword`) is dropped too. - **Studio sends a route-level title**: `Tables | Database | Supabase` in place of `users | Tables | Database | <project> | <org> | Supabase`. The tab title users see is unchanged, and so are titles in the other apps, which are public content. - **Dead clicks, heatmaps and web vitals are pinned off**: each one puts page text or the page URL in a nested payload the redaction does not walk, and each can be switched on from project settings without a deploy. All three are off today. **Note:** One path is only partly covered. Feature-flag requests carry the first URL and referrer the SDK stored for the browser, and they never pass through `before_send`. The hash is now gone from them; query values in that first URL (for example an invite link opened in a fresh browser) still go out on those requests. ## To test Signed in on the Studio preview, with analytics consent accepted. Check events in the staging analytics project, filtered to the preview host. Tested on the PR preview: - [x] Open the Table Editor, add a filter with the value `leaktest@example.com` and a sort, type `leaktest` in the Tables search and in a logs search, then click through a few pages. Expect no event containing `leaktest`, and `filter=redacted`, `sort=redacted`, `search=redacted` and `s=redacted` in `$current_url`. Observed: zero events from the preview host contained `leaktest`; custom events, `$pageview`, `$pageleave` and `$set` all carried the `=redacted` forms. The filter and sort were applied by loading the Table Editor URL with them, which is how the app restores them - [x] Same session: expect `page_title` and `title` on every event to hold only page names (for example `Tables | Database | Supabase`), with no project, org or table name. Observed: `Table Editor | Supabase`, `Tables | Database | Supabase`, `Postgres Logs | Logs | Supabase`, `Team | Supabase` and similar; no event carried the project, org or table name. `explorer_*` events keep their existing fixed title `Explorer` - [x] Load `/dashboard/project/<ref>?token=leaktest1&projectName=leaktest2#access_token=leaktest3`, then open `/join?token=leaktest4&slug=x`. Expect zero events containing `leaktest`, including `$set`, `$identify` and `$groupidentify`. Observed: zero, with `token=redacted&projectName=redacted` and no hash on any stored URL. `$set` and `$groupidentify` fired and were clean; no `$identify` fired in this session (the user was already identified), so that event was not observed - [x] Load any page with `?utm_source=readable5` appended. Expect `utm_source=readable5` readable in `$current_url`. Observed on Database > Tables with `?utm_source=readable5&gclid=readable6&tab=readable7`: both attribution params readable, `tab=redacted`. The Table Editor route rewrites its own query string and drops unknown params before any event fires, so use another page - [x] Open a table in the Table Editor. Expect the browser tab title to still lead with the table name and include the project and org names. Observed: `<table> | Table Editor | <project> | <org> | Supabase` - [x] On the Table Editor with a filter applied, change the filter value twice, then add a sort. Expect no new `$pageview` for the two value changes and one for the added sort (a new param name). Observed, all through the UI with no reload: adding the filter sent one pageview, the two value changes sent none, adding the sort sent one, and a sidebar navigation sent one; the staging analytics project shows the same four pageviews ## Linear - fixes GROWTH-1572 |
||
|
|
953e508a3e |
[FE-5110] refactor(studio): replace next/navigation with TanStack (#54041)
Moves the remaining `next/navigation` imports in Studio onto TanStack
Router hooks (and `useParams` from `common`), finishes migrating the
remaining `next/link` and `next/router` usages in the touched
components, and removes the `compat/next/navigation.ts` shim and its
Vite alias. Shared packages (`packages/**`) no longer import
`next/navigation`, so the alias can be dropped now.
**Removed:**
- `apps/studio/compat/next/navigation.ts` and the `'next/navigation'`
entry in `apps/studio/vite.config.ts`
- Global `next/navigation` mock in `apps/studio/tests/vitestSetup.ts`
and the obsolete `apps/studio/tests/lib/route-mock.test.tsx`
**Changed:**
- Replaced `usePathname` (12 files) and `useSearchParams` (3 files) with
`useLocation({ select })` from `@tanstack/react-router`
- Replaced `useRouter` in Storage bucket tables, SQL Editor commands,
and `SignInMfaForm` with `useNavigate` from `@tanstack/react-router`,
and updated `createNavigationHandler` in `lib/navigation.ts` to accept
either `NextRouter` or TanStack's `useNavigate`
- Replaced remaining `next/link` imports in touched components
(`SignInMfaForm`, `Restriction`, `DownloadLogsButton`,
`DownloadResultsButton`, `AuthEmailsLayout`, `AuthProvidersLayout`,
`JWTKeysLayout`, `StorageBucketsLayout`) with TanStack Router's `Link`
- Replaced `useParams` in `CreatePublishableAPIKeyDialog` with
`useParams` from `common` (matching `CreateSecretAPIKeyDialog`)
- Wrapped `CustomWrapper` (`tests/lib/custom-render.tsx`) in a default
TanStack `RouterContextProvider` (with optional `router` / `initialUrl`
overrides) and updated affected component tests to drop their
`next/navigation` mocks
Addresses
[FE-5110](https://linear.app/supabase/issue/FE-5110/replace-the-nextnavigation-shim-with-tanstack-router-hooks)
## To test
1. Check active tab highlighting and navigation across Auth Emails, Auth
Providers, JWT Keys, Storage Buckets, and Editor layouts
2. Verify clicking, Cmd/Ctrl-clicking, middle-clicking, and pressing
Enter on Storage bucket rows (Files, Analytics, Vector) navigates as
before
3. Run "Query a table..." and open SQL snippets from the Command Menu
and confirm `/project/$ref/sql/$id` opens with multi-line SQL preserved
in `?content=`
4. In the MFA sign-in flow, verify the recovery code link and
`forgot-password` completion preserve query params (`returnTo`,
`context=forgot-password`), and Cancel signs out and replaces history
with `/sign-in`
5. Confirm Table Editor sort/filter URL sync persists filters per table
without leaking across table switches
---------
Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
|
||
|
|
01d4d4d430 |
[FE-5113] refactor(studio): replace next/dynamic shim with React.lazy (#54022)
## Problem
Now that Studio runs on TanStack Start, `apps/studio` still routes 13
`next/dynamic` imports through a local compatibility shim
(`apps/studio/compat/next/dynamic.tsx` aliased in
`apps/studio/vite.config.ts`). Keeping the shim adds unnecessary
indirection during the Next.js teardown (FE-5113).
## Solution
Replaces every `next/dynamic` import in `apps/studio` with `React.lazy`
+ `Suspense` (or static imports where already inside a lazy chunk), then
deletes `compat/next/dynamic.tsx` and its Vite alias.
None of the previously `ssr: false` call sites need `ClientOnly`: Studio
runs TanStack Start with `spa: { enabled: true }` and only prerenders
the signed-out auth routes (`/sign-in`, `/sign-up`, `/sign-in-sso`,
`/forgot-password`), `__root.tsx` gates `<Outlet />` behind
`canRenderPage`, and `StudioCommandMenu` is already gated by
`useCommandMenuInitiated()` (which starts `false` per render).
**Removed:**
- `apps/studio/compat/next/dynamic.tsx` and the `'next/dynamic'` entry
in `nextShims` in `apps/studio/vite.config.ts`
**Changed:**
- Migrated all `next/dynamic` call sites to `React.lazy` + `Suspense`:
- `StudioCommandMenu`, `ContextSearchResults`,
`Marketplace/OverviewTab`, `QueryDetail` (`SqlMonacoBlock`),
`SQLEditorEditorPanel` (`MonacoEditor`, `DiffEditor`),
`SupportAssistantSuccessCard`, `LayoutSidebarProvider`,
`MessageMarkdown` (`Streamdown`), and
`SupportAssistantSuccessCardContent` (`Streamdown`)
- `ConnectStepsSection`: hoisted the lazy component cache out of
`useMemo` to module scope (also clears its
`react/no-unstable-nested-components` warning)
- `Integrations.constants.tsx` and `useAvailableIntegrations.tsx`:
hoisted all lazy integration tab/page definitions (including
`GraphiQLTab`) to module scope so `navigate()` returns stable component
references, added `Suspense` boundaries with `<Loading />` at both
render points (`MarketplaceDetail` and the integration child route), and
keyed integration tab/creation sheet instances (`integration.id` in
`MarketplaceDetail` and `wrapperMeta.name` in `WrappersTab`) so state
cannot leak when switching between wrappers or OAuth integrations;
preserves `umdAmdShortCircuit`, `ssrStubGraphiql`, and
`graphiqlViteWorkers` in `vite.config.ts`
- Replaced `dynamic()` calls for `AiIconAnimation`, `Badge`, and 4
`icons` in `CreateCommands.tsx` with static imports (already inside the
lazy `CommandMenu` chunk)
- Removed the stale `next/dynamic` mention from the
`lib/chunk-load-error.ts` doc comment (`React.lazy` chunk failures
continue bubbling to the root `ErrorBoundary` reload handler)
**Added:**
- Reference-stability tests for `INTEGRATIONS.navigate` in
`Integrations.constants.test.ts` (running in Vitest's Node environment)
## Review instructions
1. Open the SQL Editor and Query Performance query detail panel, and
confirm the Monaco editor and diff view load cleanly.
2. Open the GraphQL integration's GraphiQL tab, and confirm the loading
skeleton displays while the chunk loads and GraphiQL mounts with working
autocomplete/workers.
3. Open a Wrapper integration's Wrappers tab, open the create sheet,
then navigate via history to a different wrapper's create sheet and
confirm the form resets to the new wrapper's defaults.
4. Open the Command Menu (`Cmd+K`), navigate to context search (for
example, Search Database Tables) and Create commands, and confirm icons,
badges, and search results load without flicker.
5. Open the Connect sheet and switch between frameworks/steps,
confirming step content loads with the skeleton fallback.
6. Toggle sidebars (AI Assistant, Inline SQL Editor, Advisor, Help) and
verify markdown streaming in AI Assistant.
7. Confirm CI passes `pnpm --filter studio run build` (including
prerendering and chunk-cycle checks), typecheck, lint ratchet, and
Studio tests.
---------
Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
|
||
|
|
6a305cd311 |
docs(skills): treat user-defined names as sensitive in telemetry-standards (#53963)
## Problem The `telemetry-standards` skill only says not to track PII. It doesn't cover other identifiers from a user's project, such as schema or table names. Those are customer data and outside our privacy policy, but nothing told contributors or reviewers to avoid them. The skill also pointed at existing `schema_name` and `table_name` properties as conventions to match, which invites copying them. This came up in #53955, where schema names were masked because they weren't needed. ## Solution Updates `.agents/skills/telemetry-standards/SKILL.md`: - New Privacy section requiring that schema, table, column, function, bucket, policy, project and branch names be masked or omitted, along with other user-defined names, SQL and free text, and extra IDs. It notes that `useTrack` already attaches the project ref and org slug. - Recommends counts, enums, booleans or action categories instead of raw names, and typing new properties as string-literal unions rather than plain `string`. - Short masked vs unmasked example. - Reviewers now flag this as a required change (new rule 6), and the verification checklist has matching items. - The Property Standards note now says to match casing only and not copy existing `schema_name` or `table_name` properties. - The event definition template uses a literal union instead of `string`, so it no longer contradicts the rule. ## How to verify Read the diff of `.agents/skills/telemetry-standards/SKILL.md`. Each identifier listed in FE-5207 appears in the Privacy section and in review rule 6. No code changes. Fixes FE-5207 --------- Co-authored-by: Pamela Chia <pamelachiamayyee@gmail.com> |
||
|
|
d6e4089b1a |
feat(common): add FrameworkProvider and remove next imports (#53905)
Introduces a lightweight `FrameworkProvider` React context in `packages/common` (`Link`, `Image`, `pathname`, `asPath`, `isReady`, `params`, `push`), wires it up in the consuming apps, and removes the `next` dependency from `packages/common`. **Added:** - `FrameworkProvider`, `useFramework`, `FrameworkLink`, and `FrameworkImage` in `packages/common/framework.tsx`, with plain HTML defaults (`DefaultFrameworkLink` / `DefaultFrameworkImage`). `useFramework().push` always exists and falls back to `window.location.assign` - App-level framework providers wiring `next/link`, `next/image`, and router state in `www` (App + Pages routers), `docs`, `design-system`, `learn`, and `ui-library`, and native TanStack Router bindings in `studio` (`StudioFrameworkProvider`) - `StudioFrameworkProvider` reuses the common defaults (its image only applies the basePath) and reports `isReady` once the first route load commits, so the first page view carries the final route after any redirect - Unit tests for `StudioFrameworkProvider` (`useParams`, `FrameworkLink`, `FrameworkImage`, query/hash-only navigation, `isReady`) and for `PageTelemetry` route-change sends and the `TelemetryTagManager` consent gate **Changed:** - `common/hooks/useParams.ts`: read params from `useFramework()` instead of `next/compat/router` - `common/telemetry.tsx`: replace `next/script` in `TelemetryTagManager` with `useEffect` script injection, and read route state from `useFramework()` in `PageTelemetry` - `common/MetaFavicons/app-router.ts`: drop type-only `Metadata` import from `next` - Moved `MetaFaviconsPagesRouter` to `apps/www/components/MetaFaviconsPagesRouter.tsx` (its sole consumer) - Studio: `toRoutePattern` and `applyBasePath` now live once in `lib/internal-url.ts`, shared by the provider and the `compat/next` shims - `PageTelemetry` throws outside production when no `FrameworkProvider` is mounted, since it would otherwise send only the landing pageview. `useFramework()` itself still falls back to the defaults - `ui-library`: renamed its code-sample framework context to `FrameworkPreferenceProvider` / `useFrameworkPreference` so `FrameworkProvider` only means the `common` one **Removed:** - `learn`'s unused copy of that context (`useCourse` had no callers) - `next` from `packages/common/package.json` peerDependencies App Router adapters set `asPath` to the pathname only, same as the `usePathname`-based telemetry on master (reading search params at the root would opt static pages out of static rendering). ## To test - Run `packages/common` tests and typecheck, and `apps/studio` `StudioFrameworkProvider` / `route-render` / `telemetry` tests - Navigate between routes in Studio, Docs, and WWW and confirm page telemetry fires once per navigation (and does not duplicate on hash-only changes) - Load Studio at `/` (which redirects) and confirm the first page event has the final route - Verify URL params (`useParams`) continue resolving route and search params in Studio --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
06fc7c4f4e |
fix(studio): clear telemetry cookies on sign-out (#53915)
Studio's sign-out never called the API to clear the HttpOnly telemetry cookies (`user_id`, `organization_slug`, `project_ref`). Events sent from the sign-in page after a sign-out were still recorded under the user who had just signed out, and the next user on that browser inherited the previous user's org and project cookies. I call the existing `resetServerTelemetryCookies` helper (already used when consent is withdrawn) from `useSignOut`, right after the auth sign-out, and only when a session existed. A stored session whose refresh fails during sign-out counts as existing. **Note:** `withAuth` also calls `useSignOut` when a visitor with no session opens a protected page. I skip the reset there because the endpoint also clears the anonymous id and session id cookies, and a visitor who has not signed in yet needs them until sign-in links them to the account. When the reset does run, I make sign-out wait for it (capped at 1 second by the helper) so the sign-in page cannot send an event with the old cookies first. ## To test Tested on the PR preview: - [x] Sign in, open the network tab, then click "Sign out" in the avatar menu: expect one `POST /platform/telemetry/reset` with a 2xx response. Observed: one reset request (201), sent right after the auth `logout` request (204). - [x] While signed out, open a protected page such as `/dashboard/organizations`: expect a redirect to sign-in and no `POST /platform/telemetry/reset`. Observed: redirect to `/dashboard/sign-in?returnTo=%2Forganizations`, no reset request. The preview is cross-site to the staging API, so the browser never stores these `SameSite=Lax` cookies there and the cookie-clearing effect cannot be observed on it. I'll check that on the staging dashboard after merge. ## Linear - fixes GROWTH-1556 |
||
|
|
fcbdda8107 |
chore: migrate formatter from Prettier to oxfmt (#53835)
Migrate code formatting across the monorepo from Prettier to `oxfmt`
(`0.79.0`, pinned) for much faster formatting checks locally and in CI
while keeping code churn minimal (78 files total, 0.7% of the repo).
Studio's `@ianvs/prettier-plugin-sort-imports` ordering
(`<BUILTIN_MODULES>`, `<THIRD_PARTY_MODULES>`, blank line, then `@/` and
relative imports) is preserved via `oxfmt`'s native `sortImports`
override for `apps/studio/**/*.{js,jsx,ts,tsx}`.
### Performance (before vs after, uncached)
| Benchmark | Prettier (`3.8.x`) | oxfmt (`0.79.0`) | Speedup |
| --- | ---: | ---: | ---: |
| CI formatting step (`blacksmith-4vcpu-ubuntu-2404`, full repo) | `73s`
| **`7s`** | **~10×** |
| Local `apps/studio` JS/TS (`5,157` files) | `17.74s` | **`0.36s`** |
**~49×** |
| Local full monorepo (`11,131` files) | — | **`2.39s`** | — |
**Added:**
- `.oxfmtrc.jsonc` at repo root with Prettier-matching options,
`sortPackageJson: false`, the Studio `sortImports` override, and ignore
patterns migrated from `.prettierignore`
- `oxfmt` (`0.79.0` exact pin) in `pnpm-workspace.yaml` catalog and
workspace `devDependencies` / `dependencies`
- Shared `.agents/scripts/format_and_lint.sh` hook script and
`.agents/hooks.json` (used by both Claude Code and Antigravity)
**Changed:**
- Replaced `test:prettier` with `format:check` and switched `format` in
root `package.json` to `oxfmt`
- Updated `packages/api-types` (`codegen`,
`verify-production-types.mjs`), `apps/design-system` (`build:registry`),
`apps/docs` (`CodeSample.ts`, `generate-sitemap.ts`, `next.config.mjs`,
`spec/Makefile`), `apps/www` (`generate-sitemap.mjs`), and
`packages/build-icons` (`generateIconFiles.mjs`) from Prettier to
`oxfmt`
- Updated `.github/workflows/prettier.yml` (keeping the `format` job ID
intact), `.github/workflows/autofix_linters.yml`,
`.claude/settings.json`, `AGENTS.md`, `CONTRIBUTING.md`, and
`.github/copilot-instructions.md`
- Applied one-time `oxfmt` formatting pass in a separate commit (78
files: 30 `i18n/README.*.md` trailing spaces, 19 Studio files, 17 other
TS/TSX/generated types, 8 MD/MDX, 3 `package.json`, 2 example CSS files)
**Removed:**
- `prettier`, `@ianvs/prettier-plugin-sort-imports`, and
`prettier-plugin-sql-cst` from `devDependencies` (note: `.sql` files
were not part of the CI formatting glob; `eslint-config-prettier` is
kept for ESLint)
- `prettier.config.mjs`, `.prettierignore`, and
`.claude/scripts/format_and_lint.sh`
## To test
- Run `pnpm run format:check` and confirm it passes cleanly across all
matched files
- Run `pnpm --filter api-types test`, `pnpm --filter docs exec vitest
run features/directives/CodeSample.test.ts`, and `pnpm --filter www exec
vitest run generate-sitemap.test.ts`
- Edit an `apps/studio` file with out-of-order imports and run `pnpm run
format` to confirm builtin/third-party vs `@/`/relative grouping matches
prior behavior
- Check that the `Check Code Formatting` CI workflow passes on this PR
---------
Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
|
||
|
|
fb3ed7ee3c |
fix(studio): treat WebKit's CORS-denied module load as a chunk-load error (#53532)
## Problem When a lazily loaded module chunk fails an access-control check in Safari/WebKit (including every iOS browser) — for example, when a corporate proxy, VPN, or captive portal redirects a chunk request cross-origin, or a cross-origin response lacks CORS headers — WebKit's `ScriptModuleLoader` does not throw `"Importing a module script failed."` Instead it rejects the dynamic `import()` with `TypeError: Cross-origin script load denied by Cross-Origin Resource Sharing policy.` and caches the failed module fetch in the document's module map. `isChunkLoadError` in `apps/studio/lib/chunk-load-error.ts` did not recognize this message. The global error boundary and router error component therefore skipped the guarded auto-reload, showed the error page immediately, and reported the error without the `chunkLoadError` tag. ## Solution Add WebKit's access-control module load error message to `CHUNK_LOAD_ERROR_PATTERNS`. Because WebKit only emits this message from `ScriptModuleLoader` (never for `fetch()` or XHR) and Studio only uses dynamic `import()` for internal chunks, it gets the same handling as other chunk-load failures: - one guarded page reload under the existing time window and per-tab cap - if the error recurs inside the window, it falls through to the error UI and is reported with the `chunkLoadError` tag Unit tests cover the new message and verify that a generic CORS-denied `fetch` error is still not treated as a chunk-load error. ## Review instructions This change has no UI. Check it with: 1. `pnpm --filter studio exec vitest run lib/chunk-load-error.test.ts components/ui/ErrorBoundary/useChunkLoadReload.test.tsx` (50 passed). 2. `pnpm --filter studio exec tsc --noEmit` and ESLint on the changed files. ## 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) [FE-4940](https://linear.app/supabase/issue/FE-4940/typeerror-cross-origin-script-load-denied-by-cross-origin-resource) --------- Co-authored-by: supabase-vercel-tedd[bot] <336548405+supabase-vercel-tedd[bot]@users.noreply.github.com> Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
8f73c10ce1 |
feat(studio): sample browser-translation DOM errors in Sentry (#53600)
## Problem Browser translation (e.g. Chrome Translate) and some extensions rewrite DOM text nodes, which makes React throw `insertBefore` / `removeChild` errors. We drop all of these via `ignoreErrors`, so we have no signal on how often they still happen after the dynamic-text ESLint rule (#52949). Linear: [FE-5008](https://linear.app/supabase/issue/FE-5008/sample-sentry-events-for-browser-translation-crashes-instead-of), from the investigation in [FE-5013](https://linear.app/supabase/issue/FE-5013/investigate-how-we-currently-hide-browser-translation-insertremove). ## Solution Stop ignoring these errors in Studio and send a 5% sample, tagged so they are easy to find in Sentry. - Move the insert/remove node messages from `BROWSER_NOISE_IGNORE_ERRORS` into a new `BROWSER_TRANSLATION_DOM_ERRORS` list in `packages/common/sentry.ts`. `docs` and `www` add it to `ignoreErrors`, so their behavior is unchanged. - In Studio's `beforeSend`, tag matching events with `browser_translation`, `page_translated` and `sample_rate`. The existing `shouldDropForSampleRate` applies the rate. - `page_translated` is best effort: it checks for the `translated-ltr` / `translated-rtl` class on `<html>` and Google Translate `<font>` wrappers. Firefox and Edge are less reliable, so `false` is not proof. - `filterSentryEvent` skips its 1% non-crash sampling for tagged events. Without this the rates would multiply and 5% would really be 0.05%. - The generic `parentNode` / `removeChild` null reads stay ignored. They have many unrelated causes, so tagging them as translation would mislead. Not in this PR: - The `text content does not match` and hydration ignores. They are related symptoms and should be a follow-up. - The user-facing fallback in `InsertBeforeRemoveChildErrorHandler`. ## Review instructions 1. Check that `docs` and `www` still ignore the five DOM messages, via `BROWSER_TRANSLATION_DOM_ERRORS` in their `instrumentation-client.ts`. 2. Run `pnpm exec vitest run lib/sentry-client-options.test.ts` from `apps/studio`, and `pnpm exec vitest run sentry.test.ts` from `packages/common`. 3. After merge, filter Sentry for `browser_translation:true` on the production Studio project and compare `page_translated` true against false. ## Before merging Sentry also has server-side inbound filters on the production Studio project. Someone with project access should confirm the `error-message` filter doesn't match these messages. If it does, the sampled events will be dropped on arrival. ## 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 (not applicable) |
||
|
|
0c95428678 |
fix(studio): strip auth error and method params when building sign-in redirects (#53598)
## Context Bit of an odd bug that I happened to come across which I can't remember how to reproduce from scratch but its a valid issue. If i try to log in on the sign-in route with `method` and `error_description` query params in the URL, the `error_description` param gets carried forward to the next page, which if my account has MFA, it'll then bounce back to `/sign-in` `/sign-in?error_description=Unable+to+exchange+external+code%3A+53f8&method=github` Am opting to strip transient params when building the sign-in redirects ## To test - [ ] Ensure that you've got an account with MFA - [ ] Try logging in via this URL `/sign-in?error_description=Unable+to+exchange+external+code%3A+53f8&method=github` - [ ] You should be able to land on the sign-in-mfa page with no issue + no error toasts |
||
|
|
f0986f5f24 |
fix(studio): treat 401 API errors as a user fault for Sentry routing (#53411)
## Problem
A 401 from the platform API means the browser sent no valid session
token: the user signed out, or the session expired. Studio then
redirects to sign-in. `classifyResponseError` turns any 4xx into
`UnclassifiedApiError` with `fault: 'studio'`, so every query that fails
while the session is gone goes to Sentry at the Studio-owned sample
rate. The first query to fail is often the read-replicas query. Sentry
fills with errors that Studio can't fix.
## Solution
- `UnclassifiedApiError` now derives its fault from the status: a 401 is
`user`, and every other 4xx stays `studio`.
- `ERROR_ROUTING.UnclassifiedApiError` gets a `user` entry at
`SAMPLE_USER_FAULT`. 401s still send a small trickle to catch
misclassification, and 403/404/429 keep `SAMPLE_OWNED`.
- Because the fault is `user`, `AlertError` shows the user-fault
presentation for a 401 ("try again / refresh"), with no contact-support
prompt.
- Tests: `handleError.test.ts` expects `user` for a 401, and
`error-routing.test.ts` covers the 401 and 403 routing.
## Review instructions
This change has no new UI. To check it:
1. In `apps/studio`, run `vitest run lib/errors data/handleError.test.ts
data/error-classification.test.ts data/fetchers-errors.test.ts
data/query-client-reporting.test.ts components/ui`. All tests pass.
2. In `apps/studio`, run `eslint` on the changed files. It reports
nothing.
3. `tsc --noEmit` in `apps/studio` reports one error, in
`packages/ui-patterns/src/McpUrlBuilder/components/InstructionBlocks.tsx`.
The same error appears without this change: it comes from running `tsc`
without `next typegen` first.
[FE-5086](https://linear.app/supabase/issue/FE-5086/unclassifiedapierror-no-access-token-provided)
Co-authored-by: supabase-vercel-tedd[bot] <336548405+supabase-vercel-tedd[bot]@users.noreply.github.com>
|
||
|
|
5d69a2d4ee |
Show OAuth provider connect in sign in methods (#53576)
## Context Opt to show "Connect" providers CTA in Sign-in Methods by default to allow users to link more identities to their account This way if I did unlink my GH identity, i can link to another one as well <img width="745" height="393" alt="image" src="https://github.com/user-attachments/assets/58f1b973-c175-4da5-931f-43735f493998" /> |
||
|
|
b23e9e8d94 |
fix(consent): clear tracking state and reload when consent is withdrawn (#53294)
## Problem Opting out from the Privacy Settings modal (www, docs, kb) clears no cookies, and GTM keeps running. The banner's Opt out misses `_ga_<id>`, `_dcid`, and PostHog. ## Solution - `revokeTrackingConsent()` runs from `denyAll`, and from `updateServices` unless every service is accepted. It clears `_ga`, `_ga_*`, `_gcl_*`, `FP*`, `_dcid`, `session_id`, `ph_*_posthog`, PostHog's localStorage, stale consent copies. - PostHog resets and opts out, with persistence off. The opt-out survives sign-out. A saved accept opts back in. - Every opt-out calls `POST /platform/telemetry/reset` (keepalive, errors ignored) to clear the API's HttpOnly `session_id`, `anonymous_id`, and `user_id`. Studio's own call is removed. - To stop GTM, a saved opt-out reloads the page if tracking was on, waiting at most 1s for the reset. ## Review instructions 1. `cd packages/common && npx vitest run consent-state.test.ts posthog-client.test.ts` 2. On prod: accept, open Privacy Settings, turn Marketing off, Confirm. The page reloads with cookies gone and no `collect` request. Tested: `common` (237 pass), `AnalyticsSettings` tests, CI unit tests and typecheck. No browser test (previews lack Usercentrics). ## 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 |
||
|
|
e20bf8829c |
chore(studio,docs,www) - update [YOUR-PASSWORD] to be [YOUR-DATABASE-PASSWORD] for semantics + subsequent search terms (#53531)
## Problem Flavor of #41370 , but we can see that at least some traffic for this search query is searching using phrases like `supabase password reset` and `supabase password` and then accidentally find themselves on the `/docs/guides/auth/passwords` page. You can see this through user flow mappings in PostHog + also in search query traffic in Google Search Console. <img width="1261" height="669" alt="image" src="https://github.com/user-attachments/assets/70af109c-dbc8-42c2-887a-63133f3f82d5" /> <img width="1128" height="669" alt="image" src="https://github.com/user-attachments/assets/52358d87-55a8-4491-ad26-a0d390ebe55b" /> ## Solution Renames the placeholder across docs / studio / www to `[YOUR-DATABASE-PASSWORD]` and adds an admonition to the current `/docs/guides/auth/passwords` to direct folks to the correct place. Might also be a UX fix in the dash.... but poking into it feel like we already have a lot of affordances there already (`Reset database password` button on the direct connection panel + quick search action for `Reset database password`). ## Preview links ### Studio `https://studio-staging-obj7agk56-supabase.vercel.app/dashboard/project/$PROJECT?showConnect=true&connectTab=direct` <img width="1128" height="801" alt="image" src="https://github.com/user-attachments/assets/420c8582-97bd-45ff-914e-ea9bb25aed91" /> ### Docs https://docs-git-kody-devrel-866-database-password-placeholder-supabase.vercel.app/docs/guides/auth/passwords <img width="838" height="463" alt="image" src="https://github.com/user-attachments/assets/c4bb0242-6ff7-4de7-90c7-386818649209" /> --------- Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com> |
||
|
|
bbb0af65cb |
[FE-3106] (part 14) – refactor(studio): drop the dual-runtime shims and aliases (#53223)
Drops the remaining Next-era shims and aliases that only existed for the dual runtime (FE-3106). Part 14 of the stack. **Depends on:** #53222 **Changed:** - ~45 files – import Sentry from `@sentry/react` directly instead of the aliased `@sentry/nextjs` - `hooks/ui/usePreventNavigationOnUnsavedChanges.ts` – is now the TanStack `useBlocker` implementation (previously swapped in by a Vite alias) - `components/interfaces/App/RouteValidationWrapper.tsx` – `next/router` → `useNavigate` + the leaf route's `fullPath` (`/project/$ref/sql/$id`) for the exempt-route and last-visited checks - `hooks/misc/withAuth.tsx` – no `getLayout` forwarding - `TemplateEditor.test.tsx` – renders inside a router for the unsaved-changes blocker **Removed:** - `compat/sentry-nextjs.ts` and its Vite alias, the `usePreventNavigationOnUnsavedChanges` alias and Next hook, `types/next.ts` (`NextPageWithLayout`), the `@sentry/nextjs` dependency The `compat/next/*` shims for `link`, `router`, `head`, `image`, `navigation`, `dynamic` and `script` stay: about 300 components outside `routes/**` still import them. Addresses [FE-3106](https://linear.app/supabase/issue/FE-3106/move-page-bodies-into-route-files-and-delete-pages). ## To test - Trigger an error (e.g. a failing query) – it reaches Sentry as before - Edit an email template or edge function and navigate away – the unsaved-changes prompt appears - Open an org you don't belong to – toast and redirect home; open a SQL snippet, leave and come back – last snippet is restored --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
cf223ae74a |
[FE-3106] (part 13) – chore(studio): remove next entry files and config (#53222)
Removes the Next-only entry files and config now that every page lives in `routes/**` (FE-3106). `routes/__root.tsx` already mirrors `pages/_app.tsx` (dayjs plugins, providers, telemetry, error boundary, favicons). Part 13 of the stack. **Depends on:** #53221 **Changed:** - `components/interfaces/App/{NotFoundPage,ServerErrorPage}.tsx` – the 404/500 pages, rendered by `__root.tsx`, now with native `Link`/`useNavigate` and `<img>` - `routes/api/{status-page,scoped-access-token-permissions}.ts` – App Router handlers from `app/api/**` moved in (`NextResponse.json` → `Response.json`); `buildAPIPermissionScopeMap` moves to `lib/api/` - `package.json`, `tsconfig.json` – no `next typegen` step or `.next/types` include - `packages/ui-patterns/.../InstructionBlocks.tsx` – asset map typed `StaticImageData | string`: under Vite a png import is a URL string, which Next's global image types used to hide - `vite.config.ts`, `knip.jsonc`, `turbo.jsonc` and comments across studio – Next build references removed **Removed:** - `pages/{_app,_document,404,500}.tsx`, `pages/_error.jsx`, `pages/README.md`, `app/**`, `next.config.ts`, `proxy.ts`, `instrumentation{,-client}.ts`, `sentry.{server,edge}.config.ts`, `fonts/index.ts` (next/font), `BootTimeoutFallback`, `postcss.config.cjs`, the `next/server` shim - `@next/bundle-analyzer`, `raw-loader`, `postcss`, `@tailwindcss/postcss` dev dependencies Addresses [FE-3106](https://linear.app/supabase/issue/FE-3106/move-page-bodies-into-route-files-and-delete-pages). ## To test - Open an unknown URL – the 404 page renders with working "Head back" - `/api/status-page` and `/api/scoped-access-token-permissions` on platform – same JSON and `Cache-Control` - Fonts (Inter, Manrope, Source Code Pro) still load --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
04a7b1ac64 | fix(studio): reject cross-origin writes on self-hosted (#53452) | ||
|
|
ddabeac30c |
feat(studio): enable EU Assistant tracing (#53332)
Enables Braintrust tracing and feedback for Assistant chats on EU-region projects. This was the final holdout that makes it so that tracing is applied consistently across all projects. Adds `projectRegion` metadata to root traces so the project’s region is recorded with each chat (consistent with the existing [isHighComplianceProject metadata](https://github.com/supabase/supabase/blob/917dcb388939b8c54ea13c1e31b3c7285fb2ca65/apps/studio/lib/ai/generate-assistant-response.ts#L188)). Verified in staging with a [successful Assistant trace recording `projectRegion: eu-central-1`](https://www.braintrust.dev/app/supabase.io/p/Assistant/logs?r=1b4a05d7a6c1414e62f532094aa39dc1&sid=4fdc76b08a4c5a43). <img width="2656" height="1560" alt="CleanShot 2026-11-12 at 1 12 30 PM@2x" src="https://github.com/user-attachments/assets/4e81033a-c754-46db-845d-586d1d71e035" /> Closes AI-1197 |
||
|
|
c8748c7c26 |
chore: pin Node.js to v24 across the repository (#53287)
## Problem `engines.node` used open-ended ranges (`>=22.23.4` at the root, `>=22.12.0` in `apps/kb`). Vercel resolves an open-ended range to the newest Node.js major, so it overrides the project's configured version and warns that future majors will be picked automatically. The other apps declared no engine at all, and `.nvmrc` (used by local dev and CI) still pointed at Node 22. ## Solution Pin Node.js 24 everywhere the repo declares a Node version: - `.nvmrc`: `22.23.4` -> `24.22.3` (latest v24 LTS). CI workflows read `node-version-file: .nvmrc`, so they follow. - Root `package.json` and `apps/kb/package.json`: `engines.node` -> `24.x`. - Every other app (`design-system`, `docs`, `learn`, `lite-studio`, `studio`, `ui-library`, `www`): add `engines.node: "24.x"`. Vercel reads the Node.js version from `engines.node` in the project's `package.json`; `vercel.json` has no setting for it, so this is how each Vercel project gets an explicit version. - `.agents/skills/test-the-docs/sandbox/Dockerfile`: `node:22-bookworm-slim` -> `node:24-bookworm-slim`. - `AGENTS.md`: update the stated Node requirement. Notes: - `engineStrict: true` is set in `pnpm-workspace.yaml`, so `pnpm install` now requires Node 24 locally. - `.github/workflows/self-host-tests-smoke.yml` hardcodes `node-version: '22'` and is not changed here. - No builds or tests were run for this change. Checked that all changed `package.json` files parse and that Prettier passes on the changed files. ## Review instructions 1. Open the Vercel build logs for this PR's deployments (studio, docs, www, kb, and so on). 2. Confirm each build uses Node.js 24.x. 3. Confirm the logs no longer show the warning that the `engines` field overrides the project's Node.js version, or the warning about automatic upgrades to new major versions. 4. Confirm CI jobs that use `.nvmrc` set up Node 24.22.3. ## 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) [FE-5004](https://linear.app/supabase/issue/FE-5004/bump-the-nodejs-version-across-the-repository) --------- Co-authored-by: supabase-vercel-tedd[bot] <336548405+supabase-vercel-tedd[bot]@users.noreply.github.com> Co-authored-by: Ivan Vasilov <vasilov.ivan@gmail.com> |
||
|
|
b046f12571 |
chore(api-types): update generated API types from production (#53364)
Regenerates the API types with `pnpm api:codegen:prod` and fixes the
Studio type errors the new types caused.
## Changes from the API
- **Branch merge now requires production write permission.** `POST
/v1/branches/{branch_id_or_ref}/merge` changed from accepting either
`branching_development_write` or `branching_production_write` to
requiring `branching_production_write`. Studio's FGA refinement for
merge no longer matched and failed typecheck.
- Removed the merge entry from `lib/fga-refinements.ts`.
- `merge.tsx` checks merge permission with `useGrant` instead of
`useBranchGrant`.
- `BranchMergeGrant` uses `GrantFor` instead of `GrantForVariants`.
- Removed merge from the "requires a variant" test in
`guarded-fetch.test.ts`.
- Users with only development branching permissions can no longer merge
in Studio. This matches what the API now enforces.
- **Replication pipelines have a required `cluster_id`.** Added it to
the pipeline fixtures in six test files.
- **`MemberWithFreeProjectLimit` has a required
`free_plan_organizations`.** Added it to the mock in
`tests/pages/new/[slug].test.tsx`. No app code reads it yet.
## Testing
- `pnpm typecheck` passes.
- Vitest passes for the affected Studio tests.
|
||
|
|
ed6d1b4c63 |
feat(studio): show error details in AlertError and attribute user faults in SQL errors (#53242)
## Problem `AlertError` gives users and support no way to correlate a failure with Sentry or platform logs. It also treats every failure the same: a bad table editor filter or an offline browser gets "try refreshing, contact support". On the reporting side, SQL errors were attributed by who wrote the whole statement. That made errors in the user's part of mixed SQL Studio's fault: policy expressions, function bodies, cron schedules, table editor filters and row edits. Marking them as user SQL instead would drop them from Sentry entirely. Part of FE-4772. ## Solution **`AlertError`** - Platform and Studio faults show the request ID, the Sentry event ID (labeled "before sampling", since the event may be sampled out) and a "Copy details" button. - The copied text never includes `formattedError`, metadata, the cause or SQL. - SQL errors copy the SQLSTATE, position and query name instead of the message. - User faults (`isUserError`) show their message with "Please try again. If the issue persists, try refreshing your browser." There is no support link, no IDs and no copy button. - Offline shows only "You may be temporarily offline. Check your internet connection and try again." - Defaults come from `getErrorPresentation`, and props the caller passes still win. The table editor passes a filter-specific description when filters are set. **SQL error classification** - `executeSql` takes an optional `isUserFaultSqlState` predicate for Studio SQL. When it matches, the error is a `StudioSqlError` with reason `user_input` and fault `user`, and is still redacted to SQLSTATE plus query name. - `isUserFaultForValues` (classes 22, 23 and P0, plus 42501 and 57014) is for typed values: table editor filters and row edits, cron name and schedule. - `isUserFaultForSql` (any SQLSTATE except server classes 08, 53, 57 other than 57014, 58 and XX) is for embedded user SQL: policies, functions, the custom access token hook. - `isUserFaultForStatsStatement` is for `pg_stat_statements` text (Query Insights `EXPLAIN`, index advisor). It treats 42P02 (`$1` placeholders) as Studio's fault. - `UserSqlError` is now only SQL the user wrote in full, and it is still never sent. - The policy, function and cron mutation hooks no longer take `sqlOrigin`. **Routing and types** - `ERROR_ROUTING` is one table keyed by tag, then by fault. Its type requires exactly the faults each class can produce. - User faults get `SAMPLE_USER_FAULT` (default 0.01, set with `NEXT_PUBLIC_SENTRY_SAMPLE_RATE_USER_FAULT`) to catch misclassification. - The error class decides privacy (`isNeverReportedError`), separately from the rate. - Sentry events get a `reason` tag. - Each class declares its `reasons`, so a mistyped reason fails typecheck. ## Review instructions 1. Open the table editor, add a filter with a wrong-typed value (text on an integer column). The alert shows the Postgres error, the filter hint, and no support link, IDs or copy button. 2. Make a query fail with a platform error (e.g. block a `/platform/` request in DevTools). The alert shows the request ID, the event ID and "Copy details". Paste the copied text and check it has no SQL or `formattedError`. 3. Go offline in DevTools and trigger a query. Only the offline message shows. 4. Create a policy with an invalid `USING` expression. The toast shows the Postgres error. In Sentry it is a `StudioSqlError` with reason `user_input`, sampled at the user-fault rate. 5. Review `lib/errors/error-routing.ts` and `data/error-classification.ts` for the routing table and the SQLSTATE predicates. |
||
|
|
0e29dfda1b |
fix(studio): return no edge functions when the self-hosted functions folder is missing (#53229)
## Problem In self-hosted and local Studio, `FileSystemFunctionsArtifactStore` reads the folder set by `EDGE_FUNCTIONS_MANAGEMENT_FOLDER` with `readdir`. When that folder does not exist yet (for example, a fresh project before any function is created), `readdir` throws `ENOENT`, the `/api/v1/projects/[ref]/functions` route returns a 500, and the Edge Functions page shows "Failed to retrieve edge functions" instead of its empty state. ## Solution - Add a private `readFunctionsFolder()` helper that returns an empty list when the folder is missing (`ENOENT`) and rethrows every other error. - `getFunctions()` now returns `[]` and `getFunctionBySlug()` returns `undefined` for a missing folder. - Add `fileSystemStore.test.ts`, which uses real temp folders to cover the missing folder, a non-ENOENT error (path is a file), and the normal listing (skips `main` and folders without an `index` entrypoint). No change to the hosted platform path. ## Review instructions This only affects self-hosted Studio, so the Vercel preview cannot show it. Check it with: 1. `cd apps/studio && pnpm exec vitest run lib/api/self-hosted/functions/`: all tests pass. 2. Optional, locally: run self-hosted Studio with `EDGE_FUNCTIONS_MANAGEMENT_FOLDER` pointing to a folder that does not exist, open Edge Functions, and see the empty state instead of a 500. Checks run: the Vitest command above, `pnpm turbo run typecheck --filter='...[origin/master]'`, ESLint and Prettier on the changed files. ## 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) [FE-4923](https://linear.app/supabase/issue/FE-4923/fix-studio-edge-functions-500-error-when-local-functions-folder-does) --------- Co-authored-by: supabase-vercel-tedd[bot] <336548405+supabase-vercel-tedd[bot]@users.noreply.github.com> Co-authored-by: Ali Waseem <waseema393@gmail.com> |
||
|
|
afe5b4ed58 |
fix(studio): remove Braintrust tool output masking workaround (#53244)
Removes the temporary `TODO:` tool output masking introduced in https://github.com/supabase/supabase/pull/52106 now that [Braintrust 3.40.0](https://github.com/braintrustdata/braintrust-sdk-javascript/releases/tag/braintrust%403.40.0) logs `toModelOutput` in tool spans and parent span results. SQL error redaction remains in place. Verified locally at the `schema` opt-in level by running the Assistant against a development project. The Braintrust traces for [SQL rows](https://www.braintrust.dev/app/supabase.io/p/Dev%20(mattrossman%2FAssistant)/logs?r=2bca625a69c40d34ee41289acc073ea5&sid=a6304c155ecf7eed), [SQL error](https://www.braintrust.dev/app/supabase.io/p/Dev%20(mattrossman%2FAssistant)/logs?r=b6f0581cbd273c7cd1d70bb6713877d8&sid=43fbbf283faa0da9), and [notebook results](https://www.braintrust.dev/app/supabase.io/p/Dev%20(mattrossman%2FAssistant)/logs?r=05409f3af4e66131efa768a03bb8a67f&sid=321520afdd3fa7af) omit the sample rows and errors shown in Studio. | Studio | Braintrust | | --- | --- | | <a href="https://github.com/user-attachments/assets/dbf43dda-c78e-4782-acf7-951d8920a283"><img src="https://github.com/user-attachments/assets/dbf43dda-c78e-4782-acf7-951d8920a283" width="350" alt="Notebook results at limited sharing"></a> | <a href="https://github.com/user-attachments/assets/4ff513ae-c76c-47ad-ba1f-0dbc8bcfeee7"><img src="https://github.com/user-attachments/assets/4ff513ae-c76c-47ad-ba1f-0dbc8bcfeee7" width="350" alt="Braintrust notebook output with redacted results"></a> | Closes AI-1374 |
||
|
|
1854331fb6 |
[FE-3106] (part 2) – refactor(studio): move api handlers into route files (#53202)
Moves every `pages/api/**` handler into its TanStack server route under `routes/api/**` and deletes `pages/api/**`, part of the final pass of the TanStack Start migration (FE-3106). Handlers move verbatim and still run through `toWebHandler`, so auth (`apiWrapper`), response shapes and headers are unchanged. Part 2 of the stack. **Depends on:** #53199 **Changed:** - `routes/api/**` – each route now holds its handler (formerly the `pages/api` default export) as a local `nextHandler`/named function. Next-only `config`/`maxDuration` exports are dropped: `vite.config.ts` already sets the function `maxDuration`, and `toWebHandler` parses bodies itself - `routes/api/ai/docs.ts` – Web-native handler inlined, `NextRequest` → `Request` - `lib/api/apiHelpers.ts` – `getPgMetaRedirectUrl` moved here from the old `tables` handler, which the other pg-meta routes imported it from - `eslint.config.cjs`, `.github/CODEOWNERS` – `pages/api` paths → `routes/api` - `tests/routes/api/**`, `lib/api/{generate-v4,rate}.test.ts`, `scripts/__tests__/server-source-maps.test.ts` – call the route's registered handler with a Web `Request` (`tests/lib/server-route.ts`); the MCP query-validation cases now run against the native route **Removed:** - `pages/api/**` (102 files), including the Next twins of the already-native `routes/api/mcp/index.ts` and `functions/$slug/body.ts` - unused `ProjectSettings` types and the `node-mocks-http` dev dependency Parity: every route registers the same methods its handler serves. The exceptions are `check-cname`, `get-ip-address`, `get-utc-time`, `get-s3-keys`, `get-deployment-commit`, `cli-release-version` and `connect`: in Next they answered any method, and their routes register `GET` only, as before this PR. Addresses [FE-3106](https://linear.app/supabase/issue/FE-3106/move-page-bodies-into-route-files-and-delete-pages). ## To test - Load the table editor, SQL editor and Auth users on a self-hosted build – `/api/platform/**` and `/api/v1/**` respond as before - Use the Assistant and the docs search – `/api/ai/**` streams as before - `GET /api/get-deployment-commit` – same JSON and `Cache-Control` Ran typecheck, ESLint, lint ratchet, knip, Prettier, the TanStack build and the full Studio vitest suite: all pass except `lib/server/configcat.test.ts`, which also fails on `master` in an environment with ConfigCat env vars set. Self-hosted E2E is CI-only. --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
31711c0762 |
fix(studio): validate edge function test proxy target url (#53256)
The edge function test proxy (`pages/api/edge-functions/test.ts`, also
served by `routes/api/edge-functions/test.ts`) fetched the URL from the
request body after checking it only with the regexes in
`isValidEdgeFunctionURL`, and on self-hosted any
`http(s)://<host>/functions/vN/...` URL passed. It now fetches only a
URL rebuilt from parts it has validated.
**Changed:**
- `apps/studio/lib/api/edgeFunctions.ts` – replaced
`isValidEdgeFunctionURL` with `getEdgeFunctionTestUrl`, which parses the
URL, rejects non-http(s) schemes and credentials, requires a
`/functions/vN/` path, checks the host (platform:
`<ref>.supabase.co|red` over https; the Nimbus apex domain when
`NIMBUS_PROD_PROJECTS_URL` is set; self-hosted: the `SUPABASE_URL` or
`SUPABASE_PUBLIC_URL` host) and returns the fetch target rebuilt from
the validated origin, path and query. Self-hosted requests always go to
the `SUPABASE_URL` origin, replacing the old `SUPABASE_PUBLIC_URL`
string rewrite.
- `apps/studio/pages/api/edge-functions/test.ts` – fetches the URL
returned by `getEdgeFunctionTestUrl` and returns 400 when there is none.
`redirect: 'manual'` is unchanged.
**Added:**
- `apps/studio/lib/api/edgeFunctions.test.ts` – allowed platform,
`.red`, Nimbus and self-hosted URLs, and rejected cases: other hosts,
lookalike hosts, userinfo, ports, non-http schemes, paths outside
`/functions/vN/`.
- `apps/studio/tests/pages/api/edge-functions/test.test.ts` – handler
rejects userinfo and non-functions paths, and on self-hosted calls the
public URL through `SUPABASE_URL` and rejects other hosts.
## To test
- [ ] On platform (including staging `.red`), open an edge function,
click **Test**, and send a request with a query parameter: the response
shows as before.
- [ ] On self-hosted (`docker compose`), do the same from the edge
function tester: the response shows as before.
- [ ] `POST /api/edge-functions/test` with `{ "url":
"https://example.com/functions/v1/hello", "method": "GET" }`: the
response is 400 with "Provided URL is not a valid Supabase edge function
URL".
---------
Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
|
||
|
|
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>
|
||
|
|
395a54f2b7 |
feat(studio): gate jwt signing keys, legacy api keys, and third-party auth on grants (#53241)
Resolves [FE-4732](https://linear.app/supabase/issue/FE-4732/grants-rollout-jwt-signing-keys-legacy-api-keys-and-third-party-auth). ## Changes Gates the JWT signing keys, legacy API keys, and third-party auth endpoints on grants instead of `unguarded.migrating`, and replaces their V2 permission guards with `useGrant`: - **Data layer (11 sites):** `data/jwt-signing-keys/*`, `data/api-keys/legacy-api-keys-status-query`, `data/api-keys/legacy-api-key-toggle-mutation`, and `data/third-party-auth/*`. Queries become grant-gated query option factories; mutations take the grant in their variables. - **Consumers:** the JWT settings page, the JWT signing keys table and its dialogs, `jwt-settings`, `ToggleLegacyApiKeys`, `Project/APIKeys`, and the third-party auth page, form, and create dialogs. Each consumer renders denied and error states. - **JWT signing keys table:** - It's gated only on the signing keys reads (`GET signing-keys` and `GET signing-keys/legacy`, both `auth_signing_keys_read`). - The legacy API keys status is only used by the revoke dialogs. If it can't be read, revoking the legacy JWT secret fails closed: the user sees the "disable legacy API keys first" warning, with copy explaining why, instead of the confirm modal. - **Legacy JWT secret query:** a 404 (secret not imported as a signing key yet) resolves to `null` and shows the "Migrate JWT secret" panel. Other errors now render an error instead of being treated as "not migrated". - **Write actions:** - `getWriteGrantTooltip` moves from `APIKeys.utils` to `lib/grants` and takes a resource noun. Disabled write actions use it to explain why they're disabled. - New `getWriteGrantToastMessage`: handlers that run without a grant now show a toast instead of silently doing nothing. This includes the API keys handlers from #52966. ## Permission changes - **Legacy API keys toggle and status** (`GET`/`PUT /v1/projects/{ref}/api-keys/legacy`): the guard moves from `auth_signing_keys_read`/`_write` to the endpoint annotation, `api_gateway_keys_read`/`_write`. The annotation was confirmed against the backend controller (FE-4728). As a result, the JWT signing keys table's legacy revoke check now depends on `api_gateway_keys_read`. - **API keys last-used analytics** (`/platform/projects/{ref}/analytics/endpoints/api_keys.last_used.otel`): this endpoint uses legacy permissions (`analytics:Read` on `logflare`), not FGA. Its check moves from the V2 `auth_signing_keys_read` check to `useAsyncCheckPermissions(PermissionAction.ANALYTICS_READ, 'logflare')`. - Every other guard already matched its annotation: - `auth_signing_keys_read`/`_write` for signing keys - `auth_config_read`/`_write` for third-party auth ## Testing - Data layer: `jwt-signing-keys.test.ts`, `legacy-api-keys.test.ts`, and `third-party-auth.test.ts` cover every migrated fetcher, check that factories stay disabled without a grant, and cover legacy-key 404 vs. 500. - `jwt-secret-keys-table/index.platform.test.tsx`: - Legacy status denied: the table still renders, and revoking the legacy key shows only the warning. - Legacy status known enabled or disabled. - Signing keys read denied. - Legacy key 404 vs. 500. - `create-key-dialog.platform.test.tsx`: triggering create without a grant shows the toast and sends no request. - `ToggleLegacyApiKeys.platform.test.tsx`, `ThirdPartyAuthForm.platform.test.tsx`, and `settings/jwt/index.platform.test.tsx`: granted, denied, error, and partial-permission cases. - `lib/grants.test.ts`: the tooltip and toast helpers. 🤖 Generated with [Claude Code](https://claude.com/claude-code) |
||
|
|
1353178ac9 |
feat(studio): add read/write grant variants for pg-meta query (#53185)
Resolves FE-4729. First PR of the SQL grants series (FE-4697).
## What
Adds the mechanism for read and write grants on `POST
/platform/pg-meta/{ref}/query`. Every caller keeps `unguarded.migrating`
until its domain PR.
- `fga-refinements.ts`: `read` (`database_read`) and `write`
(`database_write`) variants, with `variantRequired`.
- `@supabase/pg-meta`: a `WriteSqlFragment` brand and `asWriteSql()`.
`safeSql` and `joinSqlFragments` return `WriteSqlFragment` when any
input is one, so composing write SQL keeps the brand.
- `executeSql`: overloads tie the grant to the SQL type. Write SQL needs
a write grant; other SQL takes a read or write grant.
## Notes
- The write check is type-only. Nothing in a pg-meta query request marks
it as a write, so the development-only `assertGrant` can't detect one.
The branch variants make the same trade-off, and the backend enforces
permissions either way.
- SQL written from scratch still needs `asWriteSql` where it's built.
Domain PRs mark their builders.
- Server-side callers (AI tools) will use `unguarded.byDesign`: they
forward the user's token, so the platform API enforces permissions.
FE-4750 applies this.
## Testing
- Type tests: grant/raw-client equality for both variants, rejection of
plain and unknown-variant grants, read/write brand invariance,
`executeSql` and `mutate()` rejecting write SQL with a read grant, and
brand propagation through `safeSql` and `joinSqlFragments`.
- `unguarded.migrating` count unchanged.
|
||
|
|
4d28d1a809 |
feat(studio): throw MalformedResponse for empty JSON GET bodies (#53182)
Follows supabase/supabase#53048. Part of [FE-4772](https://linear.app/supabase/issue/FE-4772/error-core-tagged-error-types-and-rough-fault-classification-in). ## What `normalizeEmptyBodyResponse` already tries to recover empty success bodies (original body, then one `no-store` refetch). When a JSON `GET` is still empty after that, it now throws `MalformedResponseError` (reason `empty_body`) carrying `endpoint`, `method`, `requestId` and status, instead of resolving with `{}`, which crashes components. * Unchanged: 204s, `HEAD`, non-`GET` requests and empty non-JSON responses keep the `Content-Length: 0` normalization. * Reporting: the error rejects like a network failure, so React Query gets the tagged instance and `reportQueryError` reports it once after the last retry. The refetch diagnostics are attached as Sentry context, and the standalone empty-body diagnostic event is skipped for this case to avoid double reporting. Recovered cases still send the diagnostic. * Routing: `MalformedResponse` moves to `SAMPLE_ALWAYS`. It is rare, and while we confirm the recovery path is sufficient every unrecovered case should be visible. * An abort during recovery throws `RequestAborted`, not `MalformedResponse` ## Notes * Callers using `get()` directly outside React Query are not reported automatically, same as network errors. * No GET endpoint showed up as legitimately returning an empty JSON body in the existing empty-body diagnostics. ## Testing * `pnpm vitest run data lib components/interfaces/ErrorHandling state` passes. * Lint ratchet passes; `tsc` shows only a pre-existing error in `packages/ui-patterns` (`InstructionBlocks.tsx`). |
||
|
|
653dfb7104 |
Fix client crash when landing on new project page (#53206)
## Why it's happening
Opening `/new/[slug]` on the TanStack/Vite dev server crashes with
`TypeError: Cannot read properties of undefined (reading 'from')`. It is
thrown from `.vite/deps/randombytes.js`, inside a `<Lazy>` boundary.
From what I understand it's happening as:
- `lib/project.tsx` imports `generate-password-browser`, which imports
`randombytes`, which imports `safe-buffer`.
- `safe-buffer` calls `require('buffer').Buffer.from`.
- In dev, Vite swaps the Node `buffer` built-in for an empty stub, so
`Buffer` is `undefined`.
Fix is to alias `buffer` to the `buffer` npm package in
`vite.config.ts`, and add `buffer` as a direct Studio dependency.
It's oddly only happening on local but not staging/prod which I'm not
too sure why honestly. Afaict from investigating with Claude, prod
builds already bundle the real `buffer` package, so `Buffer.from` exists
there, but not exactly sure how the build finds it, since nothing in the
repo declared it.
## To test
Only on local:
- [ ] First verify if the client crashes when landing on `/new/[slug]`
- Please let me know if this isn't happening on your end in which case
it might be something on my machine then perhaps
- [ ] Then checkout this branch and verify that client doesnt crash when
landing on `/new/[slug]`
---------
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
|
||
|
|
2ce7f1f33c |
experiment(studio): expanded onboarding survey (#45707)
Adds an optional onboarding survey to the new-organization form, so we
learn who new orgs are for and what they are building. Users in the
`org_form` arm of the `onboardingSurveyPlacement` PostHog flag see a
**Help improve Supabase** section. Users in `control` get today's form
unchanged and still record exposure, so the two arms can be compared;
users the flag doesn't assign get the existing form and record nothing.
**Changed:**
- **Survey on the new-org form**: asks **Who is this org for?** (plus
**How many people?** for companies) and **What are you building?** (AI
assistant or agent, AI search or knowledge base, B2B SaaS, internal
tool, consumer app, social or community, marketplace or booking,
e-commerce, developer tool or app builder, analytics or reporting,
other). Every question ends with **Prefer not to say**. Answers go to
`POST /platform/organizations/onboarding-survey` as `kind`, `size` and
`building`.
- **Follow-up card for a blank survey**: if the creator answers nothing,
a card in the bottom-right asks the same questions for 5 minutes after
the org is created (not on project creation pages). Only the creator
sees it, once, tracked in localStorage. A blank form sends nothing at
creation, because the platform keeps only the first survey response per
user and org. Skipping the card, closing it, or letting the 5 minutes
run out still saves the org type and size picked on the form.
- **Telemetry**: exposure for both arms, plus submit, submit failed,
dismissed (including `follow_up_expired` when the card times out) and
Answer clicked events with `surface` set to `org_form` or `follow_up`.
**Note:** I cut **How comfortable are you working with code?** from v1.
The survey endpoint doesn't accept `coding_experience` yet, and the
question is planned to move to the user level later.
## To test
Setup: override `onboardingSurveyPlacement` to `org_form` in the dev
toolbar. Close the Terms of Service banner first, since the follow-up
card shares its slot.
Tested on the PR preview:
- [x] Create an org with **Who is this org for?** and **What are you
building?** answered, expect one `POST
/platform/organizations/onboarding-survey` carrying `kind` and
`building` (plus `size` for companies), no `coding_experience` key, and
no `kind` or `size` in the org-create request. Observed: 204 with
`{"slug":"<slug>","kind":"COMPANY","size":"10","building":"b2b_saas"}`;
org-create body was `{"name":"<name>","tier":"tier_free"}`
- [x] Create an org with the survey left blank, then open its projects
page, expect the follow-up card; answer it, expect the same survey
request and a "Thanks for sharing" toast. Observed: no survey request at
creation; after answering, 204 with
`{"slug":"<slug>","kind":"PERSONAL","building":"consumer_app"}` and the
toast
- [x] Override to `control`, open the new-org form, expect the same form
as master (Name, Type, Company size with "How many people are in your
company?" for Company, then Plan), no survey section, and an
`onboarding_survey_placement_experiment_exposed` event with `variant:
control`. Observed: screenshots match master's form field for field; the
exposure arrived in PostHog with `variant: control`
- [x] Create an org with the survey left blank and don't act on the
follow-up card for 5 minutes, expect the card to disappear, one `POST
/platform/organizations/onboarding-survey` carrying the form's `kind`
(plus `size` for companies) and no `building`, and an
`onboarding_survey_dismissed` event with `reason: follow_up_expired`.
Observed (stored follow-up time moved to near expiry instead of
waiting): the card disappeared at the 5-minute mark with one 204
carrying `{"slug":"<slug>","kind":"AGENCY"}` and the `follow_up_expired`
event; an already-expired follow-up sends on page load; with the dialog
open past expiry nothing is sent until it is closed
## Linear
- fixes GROWTH-771
- part of GROWTH-1463
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Jonathan Summers-Muir <MildTomato@users.noreply.github.com>
Co-authored-by: Pamela Chia <pamelachiamayyee@gmail.com>
Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
|