The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(studio): switch TanStack skew protection to ?dpl= query params (#48008)
Alaister Young58621818d0f2
diff --git a/apps/studio/data/utils/deployment-commit-query.ts b/apps/studio/data/utils/deployment-commit-query.tsindex 8729bd57cfd..8fe1f972feb 100644--- a/apps/studio/data/utils/deployment-commit-query.ts+++ b/apps/studio/data/utils/deployment-commit-query.ts@@ -5,15 +5,13 @@ import { BASE_PATH } from '@/lib/constants'import type { ResponseError, UseCustomQueryOptions } from '@/types'export async function getDeploymentCommit() {- // `credentials: 'omit'` drops cookies for this one request — including the- // `__vdpl` skew-protection pin (TanStack, see router.tsx). With no pin cookie,- // Vercel's edge routes it to the LATEST deployment, so this check can detect a- // newer version even while the rest of the session stays pinned. The endpoint- // is public (no auth needed), and we keep the basePath URL so it still routes- // to studio in production (root `/api/*` there is the marketing site).- const response = await fetchHandler(`${BASE_PATH}/api/get-deployment-commit`, {- credentials: 'omit',- })+ // Deliberately unpinned: API fetches never carry the `?dpl=` skew-protection+ // pin — only built asset URLs do (TanStack, see skewProtectionDpl in+ // vite.config.ts) — so Vercel's edge routes this to the LATEST deployment+ // and the check can detect a newer version while the session's assets stay+ // pinned. We keep the basePath URL so it still routes to studio in+ // production (root `/api/*` there is the marketing site).+ const response = await fetchHandler(`${BASE_PATH}/api/get-deployment-commit`)return (await response.json()) as { commitSha: string; commitTime: string }}diff --git a/apps/studio/hooks/use-check-latest-deploy.tsx b/apps/studio/hooks/use-check-latest-deploy.tsxindex 8e1d4a073a7..3240dce6cd8 100644--- a/apps/studio/hooks/use-check-latest-deploy.tsx+++ b/apps/studio/hooks/use-check-latest-deploy.tsx@@ -6,7 +6,6 @@ import { toast } from 'sonner'import { Button, StatusIcon } from 'ui'import { useDeploymentCommitQuery } from '@/data/utils/deployment-commit-query'-import { BASE_PATH } from '@/lib/constants'const DeployCheckToast = ({ id }: { id: string | number }) => {const router = useRouter()@@ -27,9 +26,9 @@ const DeployCheckToast = ({ id }: { id: string | number }) => {</Button><ButtononClick={() => {- // Clear the deployment pin so the reload lands on the latest- // version. No-op on Next (the cookie isn't set there).- document.cookie = `__vdpl=; Path=${BASE_PATH || '/'}; Max-Age=0`+ // Document requests carry no skew-protection pin (only built+ // asset URLs do — see skewProtectionDpl in vite.config.ts), so a+ // plain reload lands on the latest deployment.router.reload()}}>diff --git a/apps/studio/package.json b/apps/studio/package.jsonindex 547bc0a3c54..2b403ab6629 100644--- a/apps/studio/package.json+++ b/apps/studio/package.json@@ -183,6 +183,7 @@"@types/react-grid-layout": "^1.3.0","@types/react-simple-maps": "^3.0.1","@types/zxcvbn": "^4.4.1",+ "@jridgewell/remapping": "^2.3.5","@vercel/config": "^0.2.1","@vitejs/plugin-react": "catalog:","@vitest/coverage-v8": "catalog:",@@ -200,6 +201,7 @@"import-in-the-middle": "^2.0.0","jsdom-testing-mocks": "^1.13.1","libpg-query": "17.6.0",+ "magic-string": "^0.30.21","msw": "^2.3.0","next-router-mock": "^0.9.13","node-mocks-http": "^1.17.2",diff --git a/apps/studio/router.tsx b/apps/studio/router.tsxindex 81f101d4c91..29cca6de141 100644--- a/apps/studio/router.tsx+++ b/apps/studio/router.tsx@@ -5,37 +5,20 @@ import { setupRouterSsrQueryIntegration } from '@tanstack/react-router-ssr-queryimport { routeTree } from './routeTree.gen'import { initSentryTanStackClient } from './sentry.tanstack'import { getQueryClient } from '@/data/query-client'-import { BASE_PATH, IS_PLATFORM } from '@/lib/constants'import { parseSearch, stringifySearch } from '@/lib/router-search-params'export interface RouterContext {queryClient: QueryClient}-// Skew protection: pin this browser session to the deployment that served it,-// so a long-lived dashboard session never 404s on a lazily-loaded JS chunk or-// gets a surprise version change mid-session. It's a session cookie (no-// expiry) — cleared when the tab/window closes, so the next visit gets the-// latest deploy. Scoped to BASE_PATH so the version check (hit at the root-// `/api/...`, outside this Path) stays unpinned and can still detect new-// deploys; the "Refresh" toast clears it before reloading (see-// use-check-latest-deploy). No-op unless we're on a Vercel deploy with Skew-// Protection enabled.-function pinDeploymentForSession() {- if (typeof document === 'undefined') return- if (!IS_PLATFORM) return- if (process.env.NEXT_PUBLIC_VERCEL_SKEW_PROTECTION_ENABLED !== '1') return- const deploymentId = process.env.NEXT_PUBLIC_VERCEL_DEPLOYMENT_ID- if (!deploymentId) return- if (document.cookie.includes('__vdpl=')) return- document.cookie = `__vdpl=${deploymentId}; Path=${BASE_PATH || '/'}; SameSite=Lax; Secure`-}--// Backstop for the pin above: if a lazily-loaded chunk 404s — most likely the-// pinned deployment aged out of Skew Protection's Maximum Age, so its hashed-// chunks are gone — Vite emits `vite:preloadError`. Drop the pin and reload so-// we land on the latest deployment (a plain reload wouldn't recover, since the-// cookie would just re-pin to the dead deployment). A short time-window guard+// Skew protection: every asset URL in the built bundle carries a+// `?dpl=<deployment-id>` pin (see skewProtectionDpl in vite.config.ts), so a+// long-lived dashboard session keeps loading lazily-imported chunks from the+// deployment it was built by instead of 404ing after a redeploy. Backstop: if+// a lazily-loaded chunk still 404s — most likely the pinned deployment aged+// out of Skew Protection's Maximum Age, so Vercel refuses the `?dpl=` request+// — Vite emits `vite:preloadError`. Reload so we land on the latest+// deployment, whose asset URLs pin to itself. A short time-window guard// prevents a reload loop if the latest deployment is itself broken.function registerChunkErrorBackstop() {if (typeof window === 'undefined') return@@ -55,7 +38,6 @@ function registerChunkErrorBackstop() {} catch {// ignore — worst case we lose loop protection for this reload.}- document.cookie = `__vdpl=; Path=${BASE_PATH || '/'}; Max-Age=0`window.location.reload()})}@@ -67,7 +49,6 @@ function getContext(): RouterContext {}export function getRouter() {- pinDeploymentForSession()registerChunkErrorBackstop()const context = getContext()diff --git a/apps/studio/vercel.ts b/apps/studio/vercel.tsindex ba264d65924..712c5358ccf 100644--- a/apps/studio/vercel.ts+++ b/apps/studio/vercel.ts@@ -45,8 +45,9 @@ const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? ''// gets HTML for a `.js` request and throws "Failed to load module script …// MIME type text/html" (and, because /assets/* is cached immutable, that HTML// poisons the edge cache under the asset URL). A clean 404 instead lets skew-// protection's `__vdpl` routing serve the chunk from the deployment that still-// has it, or the client's `vite:preloadError` backstop recover.+// protection's `?dpl=` routing (baked into asset URLs at build time — see+// skewProtectionDpl in vite.config.ts) serve the chunk from the deployment+// that still has it, or the client's `vite:preloadError` backstop recover.function routesFor(prefix: string) {return {rewrites: [diff --git a/apps/studio/vite.config.ts b/apps/studio/vite.config.tsindex 0ddb1e5f2ca..58ac32eb907 100644--- a/apps/studio/vite.config.ts+++ b/apps/studio/vite.config.ts@@ -3,11 +3,13 @@import fs from 'node:fs'import path from 'node:path'import { fileURLToPath } from 'node:url'+import remapping, { type SourceMapInput } from '@jridgewell/remapping'import { sentryTanstackStart } from '@sentry/tanstackstart-react/vite'import tailwindcss from '@tailwindcss/vite'import { devtools } from '@tanstack/devtools-vite'import { tanstackStart } from '@tanstack/react-start/plugin/vite'import viteReact from '@vitejs/plugin-react'+import MagicString from 'magic-string'import { defineConfig, loadEnv, type Plugin } from 'vite'const rootDir = path.dirname(fileURLToPath(import.meta.url))@@ -335,6 +337,159 @@ function assertNoChunkCycles(): Plugin {}}+// Skew protection (vercel.com/docs/skew-protection): bake `?dpl=<deployment+// id>` into every asset URL the client bundle can request, so every hashed+// chunk resolves against the deployment that referenced it. Vercel's edge+// routes any request carrying `?dpl=` to that exact deployment, so a+// long-lived dashboard session keeps loading its own deployment's hashed+// chunks after a redeploy, while document navigations (which carry no pin)+// always land on the latest deployment. If the pinned deployment ages out of+// Skew Protection's Maximum Age, Vercel 404s the chunk and the+// `vite:preloadError` backstop in router.tsx reloads onto the latest deploy.+// API / server-function fetches are deliberately unpinned — that is what+// lets use-check-latest-deploy detect newer deploys mid-session.+//+// Three mechanisms are needed for full coverage:+// 1. `experimental.renderBuiltUrl` (in the config below) — asset and+// public-file URLs referenced from JS/CSS/HTML, including the+// `__vite__mapDeps` preload lists for dynamic imports.+// 2. The `generateBundle` hook here — chunk-to-chunk `import`/`from`+// specifiers. Rolldown renders these as bare relative paths that+// `renderBuiltUrl` never sees (vitejs/vite#13834), and they're what the+// browser actually fetches; the preload list alone would just warm a+// cache entry under a different URL. Module identity is keyed by URL, so+// the rewrite must cover EVERY specifier or a chunk could load twice+// (pinned + unpinned) and break singleton module state.+// 3. The `buildApp` hook here — `_shell.html` is prerendered by TanStack's+// own post-order `buildApp` hook from the router manifest, outside+// Vite's asset pipeline, so its <script>/<link> URLs and the embedded+// route-preload manifest are patched on disk afterwards. Without this,+// the shell's unpinned modulepreload URLs and the pinned import URLs are+// different cache keys and the whole entry graph downloads twice.+function skewProtectionDpl(opts: { dplSearch: string; assetsUrlPrefix: string }): Plugin {+ const { dplSearch, assetsUrlPrefix } = opts+ return {+ name: 'studio-skew-protection-dpl',+ apply: 'build',+ // TanStack's `tanstack-start-core:post-build` plugin is `enforce: 'post'`;+ // matching it keeps THIS plugin sorted after it (same enforce group,+ // registration order wins), which the buildApp hook below relies on.+ enforce: 'post',+ transform: {+ handler(code, id) {+ if (id !== '\0vite/preload-helper.js') return+ // Vite's preload helper decides stylesheet-vs-modulepreload with+ // `dep.endsWith(".css")`. The `?dpl=` suffix makes that false for+ // every CSS dep, so lazy chunks' CSS would be injected as a script+ // modulepreload — a console MIME error, and the stylesheet never+ // applies. Make the check query-aware. Hard-fail if the helper's+ // shape ever changes so a Vite upgrade can't silently regress this.+ const cssCheck = 'dep.endsWith(".css")'+ if (!code.includes(cssCheck)) {+ this.error(+ `studio-skew-protection-dpl: expected \`${cssCheck}\` in vite's preload helper — ` ++ `vite changed its preload-helper shape; update this patch to match.`+ )+ }+ return { code: code.replaceAll(cssCheck, '/\\.css(\\?|$)/.test(dep)'), map: null }+ },+ },+ generateBundle: {+ // `order: 'post'` so this runs AFTER `vite:build-import-analysis`'s+ // normal-order generateBundle. That hook maps each dynamic-import+ // specifier back to a bundle key — with no query stripping — to collect+ // the chunk's CSS/preload deps; a `?dpl` suffix added any earlier makes+ // the lookup miss and silently drops CSS preloading for lazy chunks.+ order: 'post',+ handler(_options, bundle) {+ // Server chunks import each other via Node's filesystem resolution —+ // only the browser-facing client build gets the query pin.+ if (this.environment.name !== 'client') return+ for (const chunk of Object.values(bundle)) {+ if (chunk.type !== 'chunk') continue+ const importees = new Set([...chunk.imports, ...chunk.dynamicImports])+ if (importees.size === 0) continue+ const chunkDir = path.posix.dirname(chunk.fileName)+ let edits: MagicString | undefined+ for (const importee of importees) {+ const rel = path.posix.relative(chunkDir, importee)+ const spec = rel.startsWith('.') ? rel : `./${rel}`+ // Rolldown quotes static import specifiers with `"` and dynamic+ // ones with backticks; cover `'` too for safety. Matching the+ // exact quoted specifier of a known importee (hashed filename)+ // can't collide with app string literals.+ for (const quote of ['"', "'", '`']) {+ const target = `${quote}${spec}${quote}`+ for (+ let at = chunk.code.indexOf(target);+ at !== -1;+ at = chunk.code.indexOf(target, at + target.length)+ ) {+ edits ??= new MagicString(chunk.code)+ edits.appendLeft(at + target.length - 1, dplSearch)+ }+ }+ }+ if (!edits) continue+ chunk.code = edits.toString()+ // Recombine the sourcemap so the columns Sentry maps stay accurate+ // — every insertion shifts the rest of the minified line. Like+ // vite:build-import-analysis's own generateBundle edits, updating+ // `chunk.map` isn't enough: the `.js.map` file already exists in+ // the bundle as an emitted asset by this point, so the combined map+ // has to be written into that asset too.+ if (chunk.map) {+ const editMap = edits.generateMap({ source: chunk.fileName, hires: 'boundary' })+ const original = chunk.map as unknown as SourceMapInput & {+ file?: string+ debugId?: string+ }+ const combined = {+ ...remapping([editMap as SourceMapInput, original], () => null),+ // Preserve fields remapping drops but the toolchain relies on+ // (`debugId` is how Sentry pairs the uploaded map to the chunk).+ file: original.file,+ ...(original.debugId && { debugId: original.debugId }),+ }+ chunk.map = combined as unknown as typeof chunk.map+ const mapAsset = bundle[`${chunk.fileName}.map`]+ if (mapAsset && mapAsset.type === 'asset') {+ mapAsset.source = JSON.stringify(combined)+ }+ }+ }+ },+ },+ buildApp: {+ // TanStack's `tanstack-start-core:post-build` prerenders `_shell.html`+ // in its own post-order buildApp hook. This hook must run after it, so+ // this plugin must sort after that one: same hook order + same plugin+ // `enforce` group (see above) + registered after `tanstackStart()` in+ // the plugins array.+ order: 'post',+ async handler(builder) {+ const clientEnv = builder.environments.client+ if (!clientEnv) return+ const outDir = path.resolve(builder.config.root, clientEnv.config.build.outDir)+ const escapedPrefix = assetsUrlPrefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')+ // Quoted `/assets/...` URLs: <script src>/<link href> attributes and+ // the serialized router manifest's preload lists. `[^"'`?]` keeps the+ // match inside one URL and skips any that already carry a query.+ const assetUrl = new RegExp(`(["'\`])(${escapedPrefix}[^"'\`?]+)\\1`, 'g')+ for (const entry of fs.readdirSync(outDir, { recursive: true, withFileTypes: true })) {+ if (!entry.isFile() || !entry.name.endsWith('.html')) continue+ const filePath = path.join(entry.parentPath, entry.name)+ const html = fs.readFileSync(filePath, 'utf-8')+ const patched = html.replace(assetUrl, (_match, quote, url) => {+ return `${quote}${url}${dplSearch}${quote}`+ })+ if (patched !== html) fs.writeFileSync(filePath, patched)+ }+ },+ },+ }+}+export default defineConfig(({ command, mode }) => {// Match Next's "always production-NODE_ENV during build" behaviour.// `pnpm run e2e:setup:selfhosted` invokes the build with a shell@@ -369,10 +524,6 @@ export default defineConfig(({ command, mode }) => {const vercelPublicVars = ['VERCEL_ENV','VERCEL_BRANCH_URL',- // Skew protection: the client pins its session to this deployment (see- // router.tsx). Both are build-time system env vars on Vercel.- 'VERCEL_DEPLOYMENT_ID',- 'VERCEL_SKEW_PROTECTION_ENABLED',// Sentry release (sentry.tanstack.ts): the SDK silently drops session// envelopes when the client has no release, so Release Health would send// nothing. The commit SHA is also what withSentryConfig resolves the Next@@ -424,6 +575,13 @@ export default defineConfig(({ command, mode }) => {// Leaving the var empty keeps the app at `/` as today.const basePath = env.NEXT_PUBLIC_BASE_PATH || undefined+ // Skew protection — see the skewProtectionDpl comment above. Both are+ // build-time system env vars on Vercel; unset on local/self-hosted builds,+ // which disables the whole mechanism.+ const skewDeploymentId =+ env.VERCEL_SKEW_PROTECTION_ENABLED === '1' ? env.VERCEL_DEPLOYMENT_ID : undefined+ const dplSearch = skewDeploymentId ? `?dpl=${encodeURIComponent(skewDeploymentId)}` : ''+// Substitutions that have to apply to *both* our app source (via Vite's// `define`) and any pre-bundled dependencies (via esbuild's optimizeDeps).// The two pipelines don't share config — Vite's `define` only touches@@ -468,6 +626,19 @@ export default defineConfig(({ command, mode }) => {],},...(basePath && { base: basePath }),+ // Skew protection part 1 (see skewProtectionDpl above): every asset /+ // public-file URL rendered into the bundle — CSS url()s, images, worker+ // URLs, `__vite__mapDeps` preload lists — gets the `?dpl=` pin. Returning+ // a string opts out of Vite's base handling, so the base path is joined+ // here. Left unset when the pin is off so Vite keeps its default+ // base-relative URL rendering.+ ...(dplSearch && {+ experimental: {+ renderBuiltUrl(filename: string) {+ return `${basePath ?? ''}/${filename}${dplSearch}`+ },+ },+ }),optimizeDeps: {// graphiql's Vite worker setup (swapped in for the webpack one by the// `graphiqlViteWorkers` plugin above) imports Monaco's workers with@@ -592,6 +763,12 @@ export default defineConfig(({ command, mode }) => {...(basePath && { router: { basepath: basePath } }),}),viteReact(),+ // Skew protection parts 2 + 3. Registered after tanstackStart() so the+ // shell-patching buildApp hook runs after TanStack's prerender — see+ // the skewProtectionDpl comment.+ ...(dplSearch+ ? [skewProtectionDpl({ dplSearch, assetsUrlPrefix: `${basePath ?? ''}/assets/` })]+ : []),// Sentry's TanStack Start plugin(s) MUST be last so source maps reflect// every prior transform. `sentryTanstackStart` returns an ARRAY of// plugins (route patterns, source-map upload, middleware auto-wrap), sodiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex af20adfc683..41aa3f38b54 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1246,6 +1246,9 @@ importers:'@graphql-typed-document-node/core':specifier: ^3.2.0version: 3.2.0([email protected])+ '@jridgewell/remapping':+ specifier: ^2.3.5+ version: 2.3.5'@radix-ui/react-use-escape-keydown':specifier: ^1.1.1version: 1.1.1(@types/[email protected])([email protected])@@ -1360,6 +1363,9 @@ importers:libpg-query:specifier: 17.6.0version: 17.6.0+ magic-string:+ specifier: ^0.30.21+ version: 0.30.21msw:specifier: ^2.3.0version: 2.11.3(@types/[email protected])([email protected])