Files
supabase/apps/studio/components/ui/ProjectSettings/DisplayApiSettings.tsx
Alaister YoungandAlaister Young 0a4cec0464 [FE-5108] (part 1) refactor(studio): migrate core UI & prefetchers off next/link (#54304)
Part 1 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 ← this PR** |
**`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 | Remove `compat/next/link.tsx` shim, Vite alias, and
update basePath tests/docs |

Migrates `data/prefetchers/PrefetchableLink.tsx` and all shared
`components/ui/**` components off `next/link`.

**Added:**

- `apps/studio/components/ui/DynamicLink.tsx` (with unit tests) — shared
`forwardRef` link wrapper for dynamic URL strings that runs
`splitInternalUrl` and renders a plain `<a>` for external URLs (or
same-origin URLs outside the app's `basePath`) vs TanStack `<Link>` for
internal paths

**Changed:**

- Replaced `next/link` in
`apps/studio/data/prefetchers/PrefetchableLink.tsx` and all 30 importing
components under `apps/studio/components/ui/**` (`InlineLink`,
`CardButton`, `CommandItemLink`, `ObservabilityLink`, `ProductMenuItem`,
`ResourceItem`, `UpgradePlanButton`, `ToggleSpendCapButton`, banners, AI
assistant panel links, etc.)
- Used typed `<Link to="..." params={...} search={...} hash="..." />`
for known internal routes, `<DynamicLink href={...} />` for
dynamic/untyped URL strings (whether internal with query/hash or
external), and plain `<a>` for known external links
- Updated `apps/studio/routes/index.tsx` `validateSearch` return type to
`{ next?: string }` so `<Link to="/">` compiles without requiring
`search={{ next: undefined }}`
- Updated
`hooks/misc/__tests__/useTableEditorFiltersSort.navigation.test.tsx`,
`PolicyTableRow.utils.test.ts`, `SupportAssistantSuccessCard.test.tsx`,
and `useOrganizationRestrictions.test.tsx` to render inside a TanStack
Router context (`customRender` / `RouterContextProvider`)

Addresses
[FE-5108](https://linear.app/supabase/issue/FE-5108/replace-the-nextlink-shim-with-tanstack-link)

## To test

- [ ] Click internal and external `InlineLink`, `CardButton`,
`ProductMenuItem`, and `PrefetchableLink` targets and verify client-side
navigation vs external anchors
- [ ] Verify banner links (upgrade, resource exhaustion, queue
operations) preserve query params and hashes
- [ ] Confirm Studio typecheck, lint, and unit tests pass

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-12-01 16:23:48 +08:00

254 lines
9.8 KiB
TypeScript

import { JwtSecretUpdateStatus } from '@supabase/shared-types/out/events'
import { Link } from '@tanstack/react-router'
import { IS_PLATFORM, useFlag, useParams } from 'common'
import { AlertCircleIcon, Loader2Icon } from 'lucide-react'
import { useMemo, useRef } from 'react'
import { toast } from 'sonner'
import { Input } from 'ui-patterns/DataInputs/Input'
import { FormLayout } from 'ui-patterns/form/Layout/FormLayout'
import { getLastUsedAPIKeys, getLegacyApiKeyType } from './DisplayApiSettings.utils'
import Panel from '@/components/ui/Panel'
import { useApiKeysLastUsedQuery } from '@/data/analytics/api-keys-last-used-query'
import { useJwtSecretUpdatingStatusQuery } from '@/data/config/jwt-secret-updating-status-query'
import { useProjectSettingsV2Query } from '@/data/config/project-settings-v2-query'
import { FGA_PERMISSIONS, useAsyncCheckPermissionsV2 } from '@/hooks/misc/useCheckPermissionsV2'
import { useTrack } from '@/lib/telemetry/track'
export const DisplayApiSettings = ({
showTitle = true,
showNotice = true,
showLegacyText = true,
}: {
showTitle?: boolean
showNotice?: boolean
showLegacyText?: boolean
}) => {
const { ref: projectRef } = useParams()
const track = useTrack()
const {
data: settings,
isError: isProjectSettingsError,
isPending: isProjectSettingsLoading,
} = useProjectSettingsV2Query({ projectRef })
const {
data,
isError: isJwtSecretUpdateStatusError,
isPending: isJwtSecretUpdateStatusLoading,
} = useJwtSecretUpdatingStatusQuery({ projectRef })
const jwtSecretUpdateStatus = data?.jwtSecretUpdateStatus
const { isLoading: isLoadingPermissions, can: canReadAPIKeys } = useAsyncCheckPermissionsV2(
FGA_PERMISSIONS.PROJECT.API_GATEWAY_KEYS_READ
)
const isLoading = isProjectSettingsLoading || isLoadingPermissions
const isNotUpdatingJwtSecret =
jwtSecretUpdateStatus === undefined || jwtSecretUpdateStatus === JwtSecretUpdateStatus.Updated
const apiKeys = useMemo(() => settings?.service_api_keys ?? [], [settings])
// api keys should not be empty. However it can be populated with a delay on project creation
const isApiKeysEmpty = apiKeys.length === 0
const now = useRef(new Date()).current
const showApiKeysLastUsed = useFlag('showApiKeysLastUsed')
const {
isLoading: isLoadingLastUsed,
isError: isLastUsedError,
data: lastUsedLogData,
} = useApiKeysLastUsedQuery(
{
projectRef,
isoTimestampStart: new Date(now.getTime() - 24 * 60 * 60 * 1000).toISOString(),
isoTimestampEnd: now.toISOString(),
},
{ enabled: canReadAPIKeys && showApiKeysLastUsed }
)
const lastUsedAPIKeys = useMemo(() => {
if (apiKeys.length < 1 || !lastUsedLogData || lastUsedLogData.length < 1) {
return {}
}
try {
return getLastUsedAPIKeys(apiKeys, lastUsedLogData)
} catch (e: any) {
toast.error('Failed to identify when the anon and service_role keys were last used')
console.error(e)
return {}
}
}, [lastUsedLogData, apiKeys])
return (
<Panel
noMargin
title={
showTitle && (
<div className="space-y-3">
<h5 className="text-base">Project API Keys</h5>
<p className="text-sm text-foreground-light">
Your API is secured behind an API gateway which requires an API Key for every request.
<br />
You can use the keys below in the Supabase client libraries.
<br />
</p>
</div>
)
}
>
{isLoading ? (
<div className="flex items-center justify-center py-8 space-x-2">
<Loader2Icon className="animate-spin" size={16} strokeWidth={1.5} />
<p className="text-sm text-foreground-light">Retrieving API keys</p>
</div>
) : !canReadAPIKeys ? (
<div className="flex items-center py-8 px-8 space-x-2">
<AlertCircleIcon size={16} strokeWidth={1.5} />
<p className="text-sm text-foreground-light">
You don't have permission to view API keys. These keys restricted to users with higher
access levels.
</p>
</div>
) : isProjectSettingsError || isJwtSecretUpdateStatusError ? (
<div className="flex items-center justify-center py-8 space-x-2">
<AlertCircleIcon size={16} strokeWidth={1.5} />
<p className="text-sm text-foreground-light">
{isProjectSettingsError ? 'Failed to retrieve API keys' : 'Failed to update JWT secret'}
</p>
</div>
) : isApiKeysEmpty || isProjectSettingsLoading || isJwtSecretUpdateStatusLoading ? (
<div className="flex items-center justify-center py-8 space-x-2">
<Loader2Icon className="animate-spin" size={16} strokeWidth={1.5} />
<p className="text-sm text-foreground-light">
{isProjectSettingsLoading || isApiKeysEmpty
? 'Retrieving API keys'
: 'JWT secret is being updated'}
</p>
</div>
) : (
apiKeys.map((x, i: number) => (
<Panel.Content
key={x.api_key}
className={
i >= 1 &&
'border-t border-panel-border-interior-light in-data-[theme*=dark]:border-panel-border-interior-dark'
}
>
<FormLayout
layout="horizontal"
label={
<div className="flex items-center space-x-1">
{x.tags?.split(',').map((x, i: number) => (
<code key={`${x}${i}`}>{x}</code>
))}
{x.tags === 'service_role' && (
<>
<code className="bg-destructive! text-destructive-foreground! border-destructive!">
secret
</code>
</>
)}
{x.tags === 'anon' && <code>public</code>}
</div>
}
description={
x.tags === 'service_role' ? (
<>
This key has the ability to bypass Row Level Security. Never share it publicly.
If leaked, generate a new JWT secret immediately.{' '}
{showLegacyText && (
<span>
Prefer using{' '}
<Link
to="/project/$ref/settings/api-keys"
params={{ ref: projectRef ?? '_' }}
className="text-link underline"
>
Secret API keys
</Link>{' '}
instead.
</span>
)}
</>
) : (
<>
This key is safe to use in a browser if you have enabled Row Level Security for
your tables and configured policies.{' '}
{showLegacyText && (
<span>
Prefer using{' '}
<Link
to="/project/$ref/settings/api-keys"
params={{ ref: projectRef ?? '_' }}
className="text-link underline"
>
Publishable API keys
</Link>{' '}
instead.
</span>
)}
</>
)
}
>
<Input
readOnly
className="font-mono"
copy={canReadAPIKeys && isNotUpdatingJwtSecret}
reveal={x.tags !== 'anon' && canReadAPIKeys && isNotUpdatingJwtSecret}
value={
!canReadAPIKeys
? 'You need additional permissions to view API keys'
: jwtSecretUpdateStatus === JwtSecretUpdateStatus.Failed
? 'JWT secret update failed, new API key may have issues'
: jwtSecretUpdateStatus === JwtSecretUpdateStatus.Updating
? 'Updating JWT secret...'
: (x?.api_key ?? 'You need additional permissions to view API keys')
}
onChange={() => {}}
// Only the Copy button counts, to match the new API keys page. Keyboard copies don't.
onCopied={() => {
const keyType = getLegacyApiKeyType(x.tags)
if (keyType) track('api_key_copied', { keyType })
}}
onReveal={() => {
if (getLegacyApiKeyType(x.tags) === 'legacy_service_role') {
track('api_key_reveal_clicked', { keyType: 'legacy_service_role' })
}
}}
/>
</FormLayout>
{IS_PLATFORM && showApiKeysLastUsed && (
<div
className="pt-2 text-foreground-lighter w-full text-sm data-[invisible=true]:invisible"
data-invisible={isLoadingLastUsed}
>
{isLastUsedError
? 'Unable to load requests from the past 24 hours.'
: lastUsedAPIKeys[x.api_key]
? `Last request was ${lastUsedAPIKeys[x.api_key]} ago.`
: 'No requests in the past 24 hours.'}
</div>
)}
</Panel.Content>
))
)}
{showNotice ? (
<Panel.Notice
className="border-t"
title="API keys have moved"
badgeLabel="Changelog"
description={`
\`anon\` and \`service_role\` API keys can now be replaced with \`publishable\` and \`secret\` API keys.
`}
href="https://github.com/orgs/supabase/discussions/29260"
buttonText="Read the announcement"
/>
) : null}
</Panel>
)
}