Files
Alaister Young 45ffa97240 [FE-3096] feat(studio): split edge function secrets into custom and default sections (#45355)
Splits the Edge Function secrets page into two sections so reserved
Supabase env vars are always visible, even on new projects without any
user secrets created.

<img width="1605" height="1006" alt="Screenshot 2026-04-29 at 12 20
43 PM"
src="https://github.com/user-attachments/assets/fc74f10e-557d-45bb-b0f0-66a706a9facb"
/>

**Added:**
- `DefaultEdgeFunctionSecrets` component — a read-only reference list
(Name + Description) of every `SUPABASE_*`, `SB_*`, and `DENO_*` env var
available in every project, sourced from [the
docs](https://supabase.com/docs/guides/functions/secrets#default-secrets)
- `isInternalEdgeFunctionSecret` helper used to filter the custom
secrets table

**Changed:**
- The custom secrets section now renders first (more actionable), with
the educational default secrets section below it
- Custom secrets table now filters out anything matching `SUPABASE_*` or
any of the hardcoded default names

**Removed:**
- `isReservedSecret` regex check + its tooltip branches in
`EdgeFunctionSecret.tsx` — dead code now that the custom table never
receives an internal secret

Addresses
[FE-3096](https://linear.app/supabase/issue/FE-3096/split-edge-function-secrets-into-internal-and-user-defined-views).

## To test

- Open `/project/_/functions/secrets` on a fresh project (no custom
secrets)
- "Default secrets" section is visible and lists all 9 env vars with
descriptions
  - "Custom secrets" section shows the empty state
- Create a custom secret — appears in the Custom section, not the
Default section
- Edit/delete dropdown still works on custom secrets
- Search input only filters the custom secrets table

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Added a "Default secrets" section showing built-in edge-function
secrets with names, descriptions, and a "Deprecated" badge where
applicable.
* Secret names are clickable to copy to clipboard with a success
notification; secret names/values use inline code styling.
* UI now separates "Custom secrets" and "Default secrets" with distinct
empty states.

* **Bug Fixes**
* Edit/Delete controls reflect actual permission state (no longer
disabled for default/reserved secrets).

* **Tests**
  * Added tests for default-secret detection and visibility rules.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
2026-04-29 18:08:32 +08:00

298 lines
9.4 KiB
TypeScript

import { zodResolver } from '@hookform/resolvers/zod'
import { useParams } from 'common'
import { Eye, EyeOff, MinusCircle } from 'lucide-react'
import { useState } from 'react'
import { SubmitHandler, useFieldArray, useForm } from 'react-hook-form'
import { toast } from 'sonner'
import {
Button,
Card,
CardContent,
CardFooter,
CardHeader,
CardTitle,
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from 'ui'
import { Input } from 'ui-patterns/DataInputs/Input'
import z from 'zod'
import { DuplicateSecretWarningModal } from './DuplicateSecretWarningModal'
import { useSecretsCreateMutation } from '@/data/secrets/secrets-create-mutation'
import { useSecretsQuery } from '@/data/secrets/secrets-query'
type SecretPair = {
name: string
value: string
}
const FormSchema = z.object({
secrets: z.array(
z.object({
name: z
.string()
.min(1, 'Please provide a name for your secret')
.refine((value) => !value.match(/^(SUPABASE_).*/), {
message: 'Name must not start with the SUPABASE_ prefix',
}),
value: z.string().min(1, 'Please provide a value for your secret'),
})
),
})
const defaultValues = {
secrets: [{ name: '', value: '' }],
}
const removeWrappingQuotes = (str: string): string => {
if ((str.startsWith('"') && str.endsWith('"')) || (str.startsWith("'") && str.endsWith("'"))) {
return str.slice(1, -1)
}
return str
}
export const AddNewSecretForm = () => {
const { ref: projectRef } = useParams()
const [visibleSecrets, setVisibleSecrets] = useState<Set<string>>(new Set())
const [duplicateSecretName, setDuplicateSecretName] = useState<string>('')
const [pendingSecrets, setPendingSecrets] = useState<z.infer<typeof FormSchema> | null>(null)
const form = useForm({
resolver: zodResolver(FormSchema),
defaultValues,
})
const { fields, append, remove } = useFieldArray({
control: form.control,
name: 'secrets',
})
const { data: existingSecrets } = useSecretsQuery({
projectRef: projectRef,
})
function handlePaste(e: ClipboardEvent) {
e.preventDefault()
const text = e.clipboardData?.getData('text')
if (!text) return
// If text doesn't contain '=' and is being pasted into a specific field, handle as single value
if (!text.includes('=')) {
const inputName = (e.target as HTMLInputElement).name
if (inputName?.includes('secrets')) {
const [_, indexStr, field] = inputName.match(/secrets\.(\d+)\.(\w+)/) || []
if (indexStr && field) {
const index = parseInt(indexStr)
form.setValue(
`secrets.${index}.${field}` as `secrets.${number}.name` | `secrets.${number}.value`,
text.trim()
)
return
}
}
}
const pairs: Array<SecretPair> = []
try {
const jsonData = JSON.parse(text)
Object.entries(jsonData).forEach(([key, value]) => {
pairs.push({ name: key, value: String(value) })
})
} catch {
// Try KEY=VALUE format (multiple lines)
const lines = text.split(/\n/)
lines.forEach((line) => {
const [key, ...valueParts] = line.split('=')
if (key && valueParts.length) {
const valueStr = valueParts.join('=').trim()
pairs.push({
name: key.trim(),
value: removeWrappingQuotes(valueStr),
})
}
})
}
if (pairs.length) {
const currentSecrets = form.getValues('secrets')
// Filter out any empty pairs before combining
const nonEmptySecrets = currentSecrets.filter((secret) => secret.name || secret.value)
form.setValue('secrets', [...nonEmptySecrets, ...pairs])
}
}
const { mutate: createSecret, isPending: isCreating } = useSecretsCreateMutation({
onSuccess: (_, variables) => {
toast.success(`Successfully created new secret "${variables.secrets[0].name}"`)
// RHF recommends using setTimeout/useEffect to reset the form
setTimeout(() => {
form.reset()
setVisibleSecrets(new Set())
}, 0)
},
})
const onSubmit: SubmitHandler<z.infer<typeof FormSchema>> = async (data) => {
// Check for duplicate secret names
const existingSecretNames = existingSecrets?.map((secret) => secret.name) || []
const duplicateSecret = data.secrets.find((secret) => existingSecretNames.includes(secret.name))
if (duplicateSecret) {
setDuplicateSecretName(duplicateSecret.name)
setPendingSecrets(data)
return
}
createSecret({ projectRef, secrets: data.secrets })
}
const handleConfirmDuplicate = () => {
if (pendingSecrets) {
createSecret({ projectRef, secrets: pendingSecrets.secrets })
setDuplicateSecretName('')
setPendingSecrets(null)
}
}
const handleCancelDuplicate = () => {
setDuplicateSecretName('')
setPendingSecrets(null)
}
const handleToggleSecretVisibility = (fieldId: string) => {
setVisibleSecrets((prev) => {
const visibleSet = new Set(prev)
if (visibleSet.has(fieldId)) {
visibleSet.delete(fieldId)
} else {
visibleSet.add(fieldId)
}
return visibleSet
})
}
const handleRemoveSecret = (fieldId: string, index: number) => {
if (fields.length > 1) {
setVisibleSecrets((prev) => {
const visibleSet = new Set(prev)
visibleSet.delete(fieldId)
return visibleSet
})
remove(index)
} else {
form.reset(defaultValues)
setVisibleSecrets(new Set())
}
}
const handleAddAnotherSecret = () => {
append({ name: '', value: '' })
}
const isSecretVisible = (fieldId: string) => visibleSecrets.has(fieldId)
return (
<>
<Form {...form}>
<form className="w-full" onSubmit={form.handleSubmit(onSubmit)}>
<Card>
<CardHeader>
<CardTitle>Add or replace secrets</CardTitle>
</CardHeader>
<CardContent>
{fields.map((fieldItem, index) => (
<div key={fieldItem.id} className="grid grid-cols-[1fr_1fr_auto] gap-4 mb-4">
<FormField
control={form.control}
name={`secrets.${index}.name`}
render={({ field }) => (
<FormItem className="w-full">
<FormLabel>Name</FormLabel>
<FormControl>
<Input
{...field}
placeholder="e.g. CLIENT_KEY"
data-1p-ignore
data-lpignore="true"
data-form-type="other"
data-bwignore
onPaste={(e) => handlePaste(e.nativeEvent)}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name={`secrets.${index}.value`}
render={({ field }) => (
<FormItem className="w-full relative">
<FormLabel>Value</FormLabel>
<FormControl>
<Input
{...field}
type={isSecretVisible(fieldItem.id) ? 'text' : 'password'}
data-1p-ignore
data-lpignore="true"
data-form-type="other"
data-bwignore
actions={
<div className="mr-1">
<Button
type="text"
className="px-1"
icon={isSecretVisible(fieldItem.id) ? <EyeOff /> : <Eye />}
onClick={() => handleToggleSecretVisibility(fieldItem.id)}
/>
</div>
}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button
type="default"
className="h-[34px] mt-6"
icon={<MinusCircle />}
disabled={fields.length <= 1}
onClick={() => handleRemoveSecret(fieldItem.id, index)}
/>
</div>
))}
<Button type="default" onClick={handleAddAnotherSecret}>
Add another
</Button>
</CardContent>
<CardFooter className="justify-between space-x-2">
<p className="text-sm text-foreground-muted">
Insert or update multiple secrets at once by pasting key-value pairs
</p>
<Button type="primary" htmlType="submit" disabled={isCreating} loading={isCreating}>
{isCreating ? 'Saving...' : fields.length > 1 ? 'Bulk save' : 'Save'}
</Button>
</CardFooter>
</Card>
</form>
</Form>
<DuplicateSecretWarningModal
visible={!!duplicateSecretName}
onCancel={handleCancelDuplicate}
onConfirm={handleConfirmDuplicate}
isCreating={isCreating}
secretName={duplicateSecretName}
/>
</>
)
}