Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Add hide/show anon key button to edge function details page (#39384)

Joshen Lim10d75def88cb
diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.constants.ts b/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.constants.ts
index 505a373fa6f..f8492a1c694 100644
--- a/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.constants.ts
+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.constants.ts
@@ -3,7 +3,12 @@ interface InvocationTab {
label: string
language: 'bash' | 'js' | 'ts' | 'dart' | 'python'
hideLineNumbers?: boolean
- code: (functionUrl: string, functionName: string, apiKey: string) => string
+ code: (props: {
+ showKey: boolean
+ functionUrl: string
+ functionName: string
+ apiKey: string
+ }) => string
}
export const INVOCATION_TABS: InvocationTab[] = [
@@ -11,17 +16,24 @@ export const INVOCATION_TABS: InvocationTab[] = [
id: 'curl',
label: 'cURL',
language: 'bash',
- code: (functionUrl, _, apiKey) => `curl -L -X POST '${functionUrl}' \\
- -H 'Authorization: Bearer ${apiKey}' \\${apiKey.includes('publishable') ? `\n -H 'apikey: ${apiKey}' \\` : ''}
+ code: ({ showKey, functionUrl, apiKey }) => {
+ const obfuscatedName = apiKey.includes('publishable')
+ ? 'SUPABASE_PUBLISHABLE_DEFAULT_KEY'
+ : 'SUPABASE_ANON_KEY'
+ const keyValue = showKey ? apiKey : obfuscatedName
+
+ return `curl -L -X POST '${functionUrl}' \\
+ -H 'Authorization: Bearer ${keyValue}' \\${apiKey.includes('publishable') ? `\n -H 'apikey: ${keyValue}' \\` : ''}
-H 'Content-Type: application/json' \\
- --data '{"name":"Functions"}'`,
+ --data '{"name":"Functions"}'`
+ },
},
{
id: 'supabase-js',
label: 'JavaScript',
language: 'js',
hideLineNumbers: true,
- code: (_, functionName) => `import { createClient } from '@supabase/supabase-js'
+ code: ({ functionName }) => `import { createClient } from '@supabase/supabase-js'
const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_ANON_KEY)
const { data, error } = await supabase.functions.invoke('${functionName}', {
body: { name: 'Functions' },
@@ -32,7 +44,7 @@ const { data, error } = await supabase.functions.invoke('${functionName}', {
label: 'Swift',
language: 'ts',
hideLineNumbers: true,
- code: (_, functionName) => `struct Response: Decodable {
+ code: ({ functionName }) => `struct Response: Decodable {
// Expected response definition
}
@@ -49,10 +61,9 @@ let response: Response = try await supabase.functions
label: 'Flutter',
language: 'dart',
hideLineNumbers: true,
- code: (
- _,
- functionName
- ) => `final res = await supabase.functions.invoke('${functionName}', body: {'name': 'Functions'});
+ code: ({
+ functionName,
+ }) => `final res = await supabase.functions.invoke('${functionName}', body: {'name': 'Functions'});
final data = res.data;`,
},
{
@@ -60,7 +71,7 @@ final data = res.data;`,
label: 'Python',
language: 'python',
hideLineNumbers: true,
- code: (_, functionName) => `response = supabase.functions.invoke(
+ code: ({ functionName }) => `response = supabase.functions.invoke(
"${functionName}",
invoke_options={"body": {"name": "Functions"}}
)`,
diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx b/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx
index 2d3f39195b0..f3d6ebe6438 100644
--- a/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx
+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx
@@ -33,6 +33,7 @@ import {
CardTitle,
cn,
CodeBlock,
+ copyToClipboard,
CriticalIcon,
Form_Shadcn_,
FormControl_Shadcn_,
@@ -60,11 +61,6 @@ const FormSchema = z.object({
export const EdgeFunctionDetails = () => {
const router = useRouter()
const { ref: projectRef, functionSlug } = useParams()
- const [showDeleteModal, setShowDeleteModal] = useState(false)
- const { can: canUpdateEdgeFunction } = useAsyncCheckPermissions(
- PermissionAction.FUNCTIONS_WRITE,
- '*'
- )
const showAllEdgeFunctionInvocationExamples = useIsFeatureEnabled(
'edge_functions:show_all_edge_function_invocation_examples'
@@ -74,6 +70,15 @@ export const EdgeFunctionDetails = () => {
return INVOCATION_TABS.filter((tab) => tab.id === 'curl' || tab.id === 'supabase-js')
}, [showAllEdgeFunctionInvocationExamples])
+ const [showKey, setShowKey] = useState(false)
+ const [selectedTab, setSelectedTab] = useState(invocationTabs[0].id)
+ const [showDeleteModal, setShowDeleteModal] = useState(false)
+
+ const { can: canUpdateEdgeFunction } = useAsyncCheckPermissions(
+ PermissionAction.FUNCTIONS_WRITE,
+ '*'
+ )
+
const { data: apiKeys } = useAPIKeysQuery({ projectRef })
const { data: settings } = useProjectSettingsV2Query({ projectRef })
const { data: customDomainData } = useCustomDomainsQuery({ projectRef })
@@ -231,34 +236,69 @@ export const EdgeFunctionDetails = () => {
</form>
</Form_Shadcn_>
</ScaffoldSection>
+
<ScaffoldSection isFullWidth>
<ScaffoldSectionTitle className="mb-4">Invoke function</ScaffoldSectionTitle>
<Card>
- <CardContent>
- <Tabs defaultValue="curl" className="w-full">
- <TabsList className="flex flex-wrap gap-4">
+ <CardContent className="px-0">
+ <Tabs
+ className="w-full"
+ defaultValue="curl"
+ value={selectedTab}
+ onValueChange={setSelectedTab}
+ >
+ <TabsList className="flex flex-wrap gap-4 px-6">
{invocationTabs.map((tab) => (
<TabsTrigger key={tab.id} value={tab.id}>
{tab.label}
</TabsTrigger>
))}
+ {selectedTab === 'curl' && (
+ <Button
+ type="default"
+ className="ml-auto -translate-y-2 translate-x-3"
+ onClick={() => setShowKey(!showKey)}
+ >
+ {showKey ? 'Hide' : 'Show'} anon key
+ </Button>
+ )}
</TabsList>
- {invocationTabs.map((tab) => (
- <TabsContent key={tab.id} value={tab.id} className="mt-4">
- <div className="overflow-x-auto">
- <CodeBlock
- language={tab.language}
- hideLineNumbers={tab.hideLineNumbers}
- className="p-0 text-xs !mt-0 border-none"
- value={tab.code(functionUrl, selectedFunction?.name ?? '', apiKey)}
- />
- </div>
- </TabsContent>
- ))}
+ {invocationTabs.map((tab) => {
+ const code = tab.code({
+ showKey,
+ functionUrl,
+ functionName: selectedFunction?.name ?? '',
+ apiKey,
+ })
+
+ return (
+ <TabsContent key={tab.id} value={tab.id} className="mt-4 px-6">
+ <div className="overflow-x-auto">
+ <CodeBlock
+ value={code}
+ className="p-0 text-xs !mt-0 border-none"
+ language={tab.language}
+ hideLineNumbers={tab.hideLineNumbers}
+ handleCopy={() => {
+ copyToClipboard(
+ tab.code({
+ showKey: true,
+ functionUrl,
+ functionName: selectedFunction?.name ?? '',
+ apiKey,
+ })
+ )
+ }}
+ />
+ </div>
+ </TabsContent>
+ )
+ })}
</Tabs>
</CardContent>
</Card>
</ScaffoldSection>
+
<ScaffoldSection isFullWidth>
<ScaffoldSectionTitle className="mb-4">Develop locally</ScaffoldSectionTitle>
<div className="rounded border bg-surface-100 px-6 py-4 drop-shadow-sm">
diff --git a/apps/studio/components/interfaces/QueryPerformance/SqlMonacoBlock.tsx b/apps/studio/components/interfaces/QueryPerformance/SqlMonacoBlock.tsx
index 853d32bcfc8..9aab8444bff 100644
--- a/apps/studio/components/interfaces/QueryPerformance/SqlMonacoBlock.tsx
+++ b/apps/studio/components/interfaces/QueryPerformance/SqlMonacoBlock.tsx
@@ -1,9 +1,8 @@
import Editor from '@monaco-editor/react'
import { Check, Copy } from 'lucide-react'
import { useMemo, useState } from 'react'
-import { CopyToClipboard } from 'react-copy-to-clipboard'
-import { Button, cn } from 'ui'
+import { Button, cn, copyToClipboard } from 'ui'
type SqlMonacoBlockProps = {
value?: string
@@ -28,8 +27,9 @@ export const SqlMonacoBlock = ({
const content = useMemo(() => value ?? '', [value])
- const handleCopy = () => {
+ const handleCopy = (value: string) => {
setCopied(true)
+ copyToClipboard(value)
setTimeout(() => setCopied(false), 1000)
}
@@ -73,16 +73,14 @@ export const SqlMonacoBlock = ({
{!hideCopy && (
<div className="absolute right-2 top-2 opacity-0 group-hover:opacity-100 transition-opacity">
- <CopyToClipboard text={content}>
- <Button
- type="default"
- className="px-1.5"
- icon={copied ? <Check /> : <Copy />}
- onClick={handleCopy}
- >
- {copied ? 'Copied' : ''}
- </Button>
- </CopyToClipboard>
+ <Button
+ type="default"
+ className="px-1.5"
+ icon={copied ? <Check /> : <Copy />}
+ onClick={() => handleCopy(content)}
+ >
+ {copied ? 'Copied' : ''}
+ </Button>
</div>
)}
</div>
diff --git a/apps/studio/package.json b/apps/studio/package.json
index 51d8466275e..c0ef84e19fe 100644
--- a/apps/studio/package.json
+++ b/apps/studio/package.json
@@ -110,7 +110,6 @@
"react": "catalog:",
"react-beautiful-dnd": "^13.1.0",
"react-contexify": "^5.0.0",
- "react-copy-to-clipboard": "^5.1.0",
"react-data-grid": "7.0.0-beta.41",
"react-datepicker": "^4.18.0",
"react-day-picker": "^8.8.0",
@@ -172,7 +171,6 @@
"@types/randombytes": "^2.0.3",
"@types/react": "catalog:",
"@types/react-beautiful-dnd": "^13.1.2",
- "@types/react-copy-to-clipboard": "^5.0.4",
"@types/react-datepicker": "^4.3.4",
"@types/react-dom": "catalog:",
"@types/react-grid-layout": "^1.3.0",
diff --git a/packages/ui/src/components/CodeBlock/CodeBlock.tsx b/packages/ui/src/components/CodeBlock/CodeBlock.tsx
index 56322df9d6a..039763e51a5 100644
--- a/packages/ui/src/components/CodeBlock/CodeBlock.tsx
+++ b/packages/ui/src/components/CodeBlock/CodeBlock.tsx
@@ -4,9 +4,9 @@ import { noop } from 'lodash'
import { Check, Copy } from 'lucide-react'
import { useTheme } from 'next-themes'
import { Children, ReactNode, useState } from 'react'
-import { CopyToClipboard } from 'react-copy-to-clipboard'
import { Light as SyntaxHighlighter, SyntaxHighlighterProps } from 'react-syntax-highlighter'
+import { copyToClipboard } from '../../lib/utils'
import { cn } from '../../lib/utils/cn'
import { Button } from '../Button/Button'
import { monokaiCustomTheme } from './CodeBlock.utils'
@@ -20,13 +20,13 @@ import http from 'react-syntax-highlighter/dist/cjs/languages/hljs/http'
import js from 'react-syntax-highlighter/dist/cjs/languages/hljs/javascript'
import json from 'react-syntax-highlighter/dist/cjs/languages/hljs/json'
import kotlin from 'react-syntax-highlighter/dist/cjs/languages/hljs/kotlin'
+import pgsql from 'react-syntax-highlighter/dist/cjs/languages/hljs/pgsql'
import php from 'react-syntax-highlighter/dist/cjs/languages/hljs/php'
import {
default as py,
default as python,
} from 'react-syntax-highlighter/dist/cjs/languages/hljs/python'
import sql from 'react-syntax-highlighter/dist/cjs/languages/hljs/sql'
-import pgsql from 'react-syntax-highlighter/dist/cjs/languages/hljs/pgsql'
import ts from 'react-syntax-highlighter/dist/cjs/languages/hljs/typescript'
export type CodeBlockLang =
@@ -63,10 +63,11 @@ export interface CodeBlockProps {
value?: string
theme?: any
children?: string
- renderer?: SyntaxHighlighterProps['renderer']
+ wrapLines?: boolean
focusable?: boolean
+ renderer?: SyntaxHighlighterProps['renderer']
+ handleCopy?: (value?: string) => void
onCopyCallback?: () => void
- wrapLines?: boolean
}
/**
@@ -85,6 +86,7 @@ export interface CodeBlockProps {
* @param {boolean} [props.hideLineNumbers=false] - Whether to hide line numbers.
* @param {SyntaxHighlighterProps['renderer']} [props.renderer] - Custom renderer for syntax highlighting.
* @param {boolean} [props.focusable=true] - Whether the code block is focusable. When true, users can focus the code block to select text or use ⌘A (Cmd+A) to select all. This is so we don't need to load Monaco Editor.
+ * @param {function} [props.handleCopy] - Optional override behaviour for copying value. For e.g if the code block contains obfuscated values, but the copy behaviour should reveal those values instead.
*/
export const CodeBlock = ({
title,
@@ -103,6 +105,7 @@ export const CodeBlock = ({
renderer,
focusable = true,
onCopyCallback = noop,
+ handleCopy,
}: CodeBlockProps) => {
const { resolvedTheme } = useTheme()
const isDarkTheme = resolvedTheme?.includes('dark')!
@@ -110,12 +113,17 @@ export const CodeBlock = ({
const [copied, setCopied] = useState(false)
- const handleCopy = () => {
+ const onSelectCopy = (value?: string) => {
+ if (value) {
+ if (!!handleCopy) {
+ handleCopy(value)
+ } else {
+ copyToClipboard(value)
+ }
+ }
setCopied(true)
onCopyCallback()
- setTimeout(() => {
- setCopied(false)
- }, 1000)
+ setTimeout(() => setCopied(false), 1000)
}
// Extract string when `children` has a single string node
@@ -240,18 +248,14 @@ export const CodeBlock = ({
`${isDarkTheme ? 'dark' : ''}`,
].join(' ')}
>
- {/* //
- @ts-ignore */}
- <CopyToClipboard text={value || children}>
- <Button
- type="default"
- className="px-1.5"
- icon={copied ? <Check /> : <Copy />}
- onClick={() => handleCopy()}
- >
- {copied ? 'Copied' : ''}
- </Button>
- </CopyToClipboard>
+ <Button
+ type="default"
+ className="px-1.5"
+ icon={copied ? <Check /> : <Copy />}
+ onClick={() => onSelectCopy(value || children)}
+ >
+ {copied ? 'Copied' : ''}
+ </Button>
</div>
) : null}
</div>
diff --git a/packages/ui/src/components/SimpleCodeBlock/SimpleCodeBlock.tsx b/packages/ui/src/components/SimpleCodeBlock/SimpleCodeBlock.tsx
index cb84acae791..109a9590dbf 100644
--- a/packages/ui/src/components/SimpleCodeBlock/SimpleCodeBlock.tsx
+++ b/packages/ui/src/components/SimpleCodeBlock/SimpleCodeBlock.tsx
@@ -26,14 +26,17 @@ interface SimpleCodeBlockProps {
className?: string
showCopy?: boolean
onCopy?: () => void
+ handleCopy?: (value: string) => void
}
+// [Joshen] Refactor: De-dupe with CodeBlock.tsx
export const SimpleCodeBlock = ({
children,
parentClassName,
className: languageClassName,
showCopy = true,
onCopy,
+ handleCopy,
}: PropsWithChildren<SimpleCodeBlockProps>) => {
const { resolvedTheme } = useTheme()
const [showCopied, setShowCopied] = useState(false)
@@ -53,7 +56,12 @@ export const SimpleCodeBlock = ({
}
const handleCopyCode = (code: any) => {
- copyToClipboard(code, () => setShowCopied(true))
+ if (!!handleCopy) {
+ handleCopy(code)
+ } else {
+ copyToClipboard(code)
+ }
+ setShowCopied(true)
onCopy?.()
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4944220ab4d..c7f586086bd 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -972,9 +972,6 @@ importers:
react-contexify:
specifier: ^5.0.0
- react-copy-to-clipboard:
- specifier: ^5.1.0
- version: 5.1.0([email protected])
react-data-grid:
specifier: 7.0.0-beta.41
@@ -1153,9 +1150,6 @@ importers:
'@types/react-beautiful-dnd':
specifier: ^13.1.2
version: 13.1.5
- '@types/react-copy-to-clipboard':
- specifier: ^5.0.4
- version: 5.0.5
'@types/react-datepicker':
specifier: ^4.3.4