mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 07:29:16 +00:00
## Context Grant-gated query factories returned `queryFn: skipToken` when the caller had no grant. TanStack Query keeps one options object per cache entry, overwritten by whichever observer rendered last. When that was a grant-less observer, invalidation refetched with `skipToken` and failed with `Missing queryFn`, breaking the query for every other observer on the key. #53075 patched two call sites; this fixes the factories. ## Changes - New `grantedQueryOptions` helper (`data/granted-query-options.ts`). Without a grant, the factory sets `queryFn: undefined` instead of `skipToken`, so TanStack borrows the query function from a subscribed observer that has one. The caller's `enabled` applies only when the factory has a query function. - `apiKeysQueryOptions`, `revealedApiKeysQueryOptions`, `branchesQueryOptions`, `branchQueryOptions` and `branchDiffQueryOptions` take caller options as a second argument. Call sites change from `useQuery({ ...f(vars), enabled })` to `useQuery(f(vars, { enabled }))`, so callers can't override the grant gate. - New type-aware `fga/no-spread-granted-query-options` lint rule (error). `grantedQueryOptions` returns a type-only brand, and the rule flags any spread or `Object.assign` of a branded value, however it was built or named. - Restores typed linting as a separate pass (`eslint.type-checks.config.cjs`, run by `pnpm lint` via `lint:type-checks`), as #44678 did. Enabling type info in the main config changes what other plugins report, so it stays separate. - `studio-queries` skill documents the pattern. Callers still pass their own grant, so the UI gates on the same grant the request carries. ## Testing - `data/api-keys/api-keys-query.test.tsx`: a granted and a grant-less component share the key, with the grant-less one rendering last; invalidation via the delete mutation refetches successfully. Fails on master with `Missing queryFn`. - `data/granted-query-options.test.ts`: `enabled` gating, factory fields win over caller fields, `select` type inference. - Lint rule cases in `scripts/__tests__/fga-eslint-rules.test.ts`. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
170 lines
5.8 KiB
TypeScript
170 lines
5.8 KiB
TypeScript
import { useQuery } from '@tanstack/react-query'
|
|
import { useParams } from 'common'
|
|
import { useCallback, useEffect, useRef, useState } from 'react'
|
|
|
|
import { useRevealedSecret } from '@/components/interfaces/APIKeys/useRevealedSecret'
|
|
import { apiKeysQueryOptions, getKeys } from '@/data/api-keys/api-keys-query'
|
|
import { useProjectApiUrl } from '@/data/config/project-endpoint-query'
|
|
import { useLatest } from '@/hooks/misc/useLatest'
|
|
import { useGrant } from '@/lib/grants'
|
|
|
|
const AUTO_HIDE_MS = 10_000
|
|
const SECRET_MASK = '••••••••••••••••••••'
|
|
|
|
export const SERVER_ENV_VARS = {
|
|
url: 'SUPABASE_URL',
|
|
publishableKey: 'SUPABASE_PUBLISHABLE_KEY',
|
|
secretKey: 'SUPABASE_SECRET_KEY',
|
|
jwksUrl: 'SUPABASE_JWKS_URL',
|
|
} as const
|
|
|
|
const JWKS_DISCOVERY_PATH = '/auth/v1/.well-known/jwks.json'
|
|
|
|
export interface ConnectServerEnvSecret {
|
|
exists: boolean
|
|
canReveal: boolean
|
|
isRevealed: boolean
|
|
isRevealing: boolean
|
|
maskedValue: string
|
|
displayValue: string
|
|
toggle: () => Promise<void>
|
|
getValue: () => Promise<string>
|
|
}
|
|
|
|
export interface UseConnectServerEnvResult {
|
|
isLoading: boolean
|
|
canReadAPIKeys: boolean
|
|
/** Result of the api-keys grant, for rendering denied and error states. */
|
|
apiKeysGrant: ReturnType<typeof useGrant<'GET /v1/projects/{ref}/api-keys'>>
|
|
apiUrl: string
|
|
publishableKey: string
|
|
|
|
// Public JWKS discovery endpoint, used to verify user JWTs.
|
|
jwksUrl: string
|
|
secret: ConnectServerEnvSecret
|
|
|
|
// Builds the full .env text, revealing the secret key on demand.
|
|
buildEnv: () => Promise<string>
|
|
}
|
|
|
|
export function useConnectServerEnv(): UseConnectServerEnvResult {
|
|
const { ref: projectRef } = useParams()
|
|
|
|
const apiKeysGrant = useGrant('GET /v1/projects/{ref}/api-keys', { projectRef })
|
|
const canReadAPIKeys = apiKeysGrant.status === 'granted'
|
|
const isLoadingPermission = apiKeysGrant.status === 'loading'
|
|
|
|
const [isRevealed, setIsRevealed] = useState(false)
|
|
// So async callbacks below can check the current reveal state after an
|
|
// await, instead of the value closed over when they started.
|
|
const isRevealedRef = useLatest(isRevealed)
|
|
|
|
const { data: apiUrl, isPending: isLoadingUrl } = useProjectApiUrl({ projectRef })
|
|
const resolvedUrl = apiUrl || 'your-project-url'
|
|
const jwksUrl = apiUrl
|
|
? new URL(JWKS_DISCOVERY_PATH, apiUrl).href
|
|
: `your-project-url${JWKS_DISCOVERY_PATH}`
|
|
|
|
const { data: keys, isLoading: isLoadingKeys } = useQuery(
|
|
apiKeysQueryOptions({ projectRef, grant: apiKeysGrant.grant }, { select: getKeys })
|
|
)
|
|
const publishableKey = keys?.publishableKey?.api_key ?? keys?.anonKey?.api_key ?? ''
|
|
const secretKey = keys?.secretKey ?? keys?.serviceKey
|
|
const maskedValue = secretKey?.api_key
|
|
? `${secretKey.api_key.slice(0, 15)}${SECRET_MASK}`
|
|
: 'your-secret-key'
|
|
|
|
const {
|
|
data: revealedSecret,
|
|
isLoading: isRevealing,
|
|
reveal,
|
|
clear,
|
|
revealGrant,
|
|
} = useRevealedSecret({ projectRef, id: secretKey?.id ?? undefined })
|
|
|
|
// toggle() and getSecretValue() can both decide to reveal before either
|
|
// resolves (e.g. clicking "Reveal" and "Copy" in quick succession); share
|
|
// one in-flight request rather than firing two and racing to set state.
|
|
const revealPromiseRef = useRef<ReturnType<typeof reveal> | null>(null)
|
|
const revealOnce = useCallback(() => {
|
|
if (!revealPromiseRef.current) {
|
|
revealPromiseRef.current = reveal().finally(() => {
|
|
revealPromiseRef.current = null
|
|
})
|
|
}
|
|
return revealPromiseRef.current
|
|
}, [reveal])
|
|
|
|
// clear() invalidates the in-flight reveal request (by request id) but
|
|
// doesn't know about revealPromiseRef, so a hide immediately followed by
|
|
// another reveal would otherwise reuse that now-invalidated promise
|
|
// instead of firing a fresh request.
|
|
const clearReveal = useCallback(() => {
|
|
revealPromiseRef.current = null
|
|
clear()
|
|
}, [clear])
|
|
|
|
const toggle = useCallback(async () => {
|
|
if (!secretKey || !canReadAPIKeys) return
|
|
if (isRevealed) {
|
|
setIsRevealed(false)
|
|
clearReveal()
|
|
} else {
|
|
setIsRevealed(true)
|
|
try {
|
|
await revealOnce()
|
|
} catch (error) {
|
|
setIsRevealed(false)
|
|
throw new Error('Failed to reveal secret API key', { cause: error })
|
|
}
|
|
}
|
|
}, [secretKey, canReadAPIKeys, isRevealed, clearReveal, revealOnce])
|
|
|
|
const getSecretValue = useCallback(async () => {
|
|
if (!secretKey || !canReadAPIKeys) return 'your-secret-key'
|
|
if (revealedSecret) return revealedSecret
|
|
const value = await revealOnce()
|
|
if (!isRevealedRef.current) clearReveal()
|
|
return value ?? 'your-secret-key'
|
|
}, [secretKey, canReadAPIKeys, revealedSecret, revealOnce, clearReveal])
|
|
|
|
const buildEnv = useCallback(async () => {
|
|
const secretValue = await getSecretValue()
|
|
return [
|
|
`${SERVER_ENV_VARS.url}=${resolvedUrl}`,
|
|
`${SERVER_ENV_VARS.publishableKey}=${publishableKey || 'your-publishable-key'}`,
|
|
`${SERVER_ENV_VARS.secretKey}=${secretValue}`,
|
|
`${SERVER_ENV_VARS.jwksUrl}=${jwksUrl}`,
|
|
].join('\n')
|
|
}, [resolvedUrl, publishableKey, jwksUrl, getSecretValue])
|
|
|
|
useEffect(() => {
|
|
if (!isRevealed || !revealedSecret) return
|
|
const timer = setTimeout(() => {
|
|
setIsRevealed(false)
|
|
clearReveal()
|
|
}, AUTO_HIDE_MS)
|
|
return () => clearTimeout(timer)
|
|
}, [isRevealed, revealedSecret, clearReveal])
|
|
|
|
return {
|
|
isLoading: isLoadingUrl || isLoadingKeys || isLoadingPermission,
|
|
canReadAPIKeys,
|
|
apiKeysGrant,
|
|
apiUrl: resolvedUrl,
|
|
publishableKey: publishableKey || 'your-publishable-key',
|
|
jwksUrl,
|
|
secret: {
|
|
exists: !!secretKey,
|
|
canReveal: canReadAPIKeys && revealGrant.status === 'granted',
|
|
isRevealed,
|
|
isRevealing,
|
|
maskedValue,
|
|
displayValue: isRevealed && revealedSecret ? revealedSecret : maskedValue,
|
|
toggle,
|
|
getValue: getSecretValue,
|
|
},
|
|
buildEnv,
|
|
}
|
|
}
|