The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Fix more consistent error handling in project API settings page
Joshen Limc2e32cfb9b37
diff --git a/studio/components/interfaces/Settings/API/JWTSettings.tsx b/studio/components/interfaces/Settings/API/JWTSettings.tsxnew file mode 100644index 00000000000..231505492fb--- /dev/null+++ b/studio/components/interfaces/Settings/API/JWTSettings.tsx@@ -0,0 +1,321 @@+import { FC, useState, Dispatch, SetStateAction } from 'react'+import { useRouter } from 'next/router'+import * as Tooltip from '@radix-ui/react-tooltip'+import {+ Alert,+ Button,+ Dropdown,+ Input,+ Modal,+ IconEye,+ IconEyeOff,+ IconKey,+ IconLoader,+ IconChevronDown,+ IconRefreshCw,+ IconPenTool,+ IconAlertCircle,+} from '@supabase/ui'+import {+ JwtSecretUpdateError,+ JwtSecretUpdateProgress,+ JwtSecretUpdateStatus,+} from '@supabase/shared-types/out/events'+import { PermissionAction } from '@supabase/shared-types/out/constants'++import { uuidv4 } from 'lib/helpers'+import {+ useStore,+ useJwtSecretUpdateStatus,+ useProjectPostgrestConfig,+ checkPermissions,+} from 'hooks'+import { API_URL } from 'lib/constants'+import {+ JWT_SECRET_UPDATE_ERROR_MESSAGES,+ JWT_SECRET_UPDATE_PROGRESS_MESSAGES,+} from './API.constants'+import Panel from 'components/ui/Panel'+import ConfirmModal from 'components/ui/Dialogs/ConfirmDialog'+import { patch } from 'lib/common/fetch'++interface Props {}++const JWTSettings: FC<Props> = ({}) => {+ const { ui } = useStore()+ const router = useRouter()+ const { ref } = router.query++ const [customToken, setCustomToken] = useState<string>('')+ const [showCustomTokenInput, setShowCustomTokenInput] = useState(false)+ const [isCreatingKey, setIsCreatingKey] = useState<boolean>(false)+ const [isRegeneratingKey, setIsGeneratingKey] = useState<boolean>(false)+ const [isSubmittingJwtSecretUpdateRequest, setIsSubmittingJwtSecretUpdateRequest] =+ useState<boolean>(false)++ const canReadJWTSecret = checkPermissions(PermissionAction.READ, 'postgrest_config')+ const canGenerateNewJWTSecret = checkPermissions(+ PermissionAction.INFRA_EXECUTE,+ 'queue_job.projects.update_jwt'+ )++ const {+ changeTrackingId,+ jwtSecretUpdateError,+ jwtSecretUpdateProgress,+ jwtSecretUpdateStatus,+ mutateJwtSecretUpdateStatus,+ }: any = useJwtSecretUpdateStatus(ref)++ const { config, isError } = useProjectPostgrestConfig(ref as string | undefined)++ const { Failed, Updated, Updating } = JwtSecretUpdateStatus++ const isJwtSecretUpdateFailed = jwtSecretUpdateStatus === Failed+ const isNotUpdatingJwtSecret =+ jwtSecretUpdateStatus === undefined || jwtSecretUpdateStatus === Updated+ const isUpdatingJwtSecret = jwtSecretUpdateStatus === Updating+ const jwtSecretUpdateErrorMessage =+ JWT_SECRET_UPDATE_ERROR_MESSAGES[jwtSecretUpdateError as JwtSecretUpdateError]+ const jwtSecretUpdateProgressMessage =+ JWT_SECRET_UPDATE_PROGRESS_MESSAGES[jwtSecretUpdateProgress as JwtSecretUpdateProgress]++ async function handleJwtSecretUpdate(+ jwt_secret: string,+ setModalVisibility: Dispatch<SetStateAction<boolean>>+ ) {+ setIsSubmittingJwtSecretUpdateRequest(true)+ try {+ const trackingId = uuidv4()+ const res = await patch(`${API_URL}/projects/${ref}/config/secrets`, {+ jwt_secret,+ change_tracking_id: trackingId,+ })+ if (res.error) throw res.error+ setModalVisibility(false)+ mutateJwtSecretUpdateStatus()+ ui.setNotification({+ category: 'info',+ message:+ 'Successfully submitted JWT secret update request. Please wait while your project is updated.',+ })+ } catch (error: any) {+ ui.setNotification({ category: 'error', message: error.message })+ } finally {+ setIsSubmittingJwtSecretUpdateRequest(false)+ }+ }++ return (+ <>+ <Panel title={<h5 className="mb-0">JWT Settings</h5>}>+ <Panel.Content className="border-panel-border-interior-light dark:border-panel-border-interior-dark space-y-6 border-t">+ {isError ? (+ <div className="py-8 flex items-center justify-center space-x-2">+ <IconAlertCircle size={16} strokeWidth={1.5} />+ <p className="text-sm text-scale-1100">Failed to retrieve JWT settings</p>+ </div>+ ) : (+ <>+ <Input+ label="JWT Secret"+ readOnly+ copy={canReadJWTSecret && isNotUpdatingJwtSecret}+ reveal={canReadJWTSecret && isNotUpdatingJwtSecret}+ disabled+ value={+ !canReadJWTSecret+ ? 'You need additional permissions to view the JWT secret'+ : isJwtSecretUpdateFailed+ ? 'JWT secret update failed'+ : isUpdatingJwtSecret+ ? 'Updating JWT secret...'+ : config?.jwt_secret || ''+ }+ className="input-mono"+ descriptionText={+ 'Used to decode your JWTs. You can also use this to mint your own JWTs.'+ }+ layout="horizontal"+ />+ <div className="space-y-3">+ <div className="dark:bg-bg-alt-dark bg-bg-alt-light dark:border-dark rounded-md border p-3 px-6 shadow-sm">+ {isUpdatingJwtSecret ? (+ <div className="flex items-center space-x-2">+ <IconLoader className="animate-spin" size={14} />+ <p className="text-sm">+ Updating JWT secret: {jwtSecretUpdateProgressMessage}+ </p>+ </div>+ ) : (+ <div className="w-full space-y-2">+ <div className="flex w-full items-center justify-between">+ <div className="flex flex-col space-y-1">+ <p>Generate a new JWT secret</p>+ <p className="text-sm opacity-50">+ A random secret will be created, or you can create your own.+ </p>+ </div>+ <div className="flex flex-col items-end">+ {isUpdatingJwtSecret ? (+ <Button loading type="secondary">+ Updating JWT secret...+ </Button>+ ) : !canGenerateNewJWTSecret ? (+ <Tooltip.Root delayDuration={0}>+ <Tooltip.Trigger>+ <Button+ disabled+ as="span"+ type="default"+ iconRight={<IconChevronDown />}+ >+ Generate a new secret+ </Button>+ </Tooltip.Trigger>+ <Tooltip.Content side="bottom">+ <Tooltip.Arrow className="radix-tooltip-arrow" />+ <div+ className={[+ 'bg-scale-100 rounded py-1 px-2 leading-none shadow',+ 'border-scale-200 border',+ ].join(' ')}+ >+ <span className="text-scale-1200 text-xs">+ You need additional permissions to generate a new JWT secret+ </span>+ </div>+ </Tooltip.Content>+ </Tooltip.Root>+ ) : (+ <Dropdown+ align="end"+ side="bottom"+ overlay={+ <>+ <Dropdown.Item+ onClick={() => setIsGeneratingKey(true)}+ icon={<IconRefreshCw size={16} />}+ >+ Generate a random secret+ </Dropdown.Item>+ <Dropdown.Seperator />+ <Dropdown.Item+ onClick={() => setIsCreatingKey(true)}+ icon={<IconPenTool size={16} />}+ >+ Create my own secret+ </Dropdown.Item>+ </>+ }+ >+ <Button as="span" type="default" iconRight={<IconChevronDown />}>+ Generate a new secret+ </Button>+ </Dropdown>+ )}+ </div>+ </div>+ </div>+ )}+ </div>+ {isJwtSecretUpdateFailed ? (+ <Alert withIcon variant="warning" title="Failed to update JWT secret">+ Please try again. If the failures persist, please contact Supabase support with+ the following details: <br />+ Change tracking ID: {changeTrackingId} <br />+ Error message: {jwtSecretUpdateErrorMessage}+ </Alert>+ ) : canGenerateNewJWTSecret ? (+ <Alert+ withIcon+ variant="warning"+ title="This will invalidate all existing API keys!"+ >+ Generating a new JWT secret will invalidate <u>all</u> of your API keys,+ including your <code>service_role</code> and <code>anon</code> keys. Your+ project will also be restarted during this process, which will terminate any+ existing connections.+ </Alert>+ ) : (+ <></>+ )}+ </div>+ </>+ )}+ </Panel.Content>+ </Panel>+ <ConfirmModal+ danger+ visible={isRegeneratingKey}+ title="Are you absolutely sure?"+ description="This action cannot be undone and the old JWT secret will be lost. All existing API keys+ will be invalidated, and any open connections will be terminated."+ buttonLabel="Generate new secret"+ buttonLoadingLabel="Generating"+ onSelectCancel={() => setIsGeneratingKey(false)}+ onSelectConfirm={() => handleJwtSecretUpdate('ROLL', setIsGeneratingKey)}+ />++ <Modal+ closable+ header="Create a custom JWT secret"+ visible={isCreatingKey}+ size="medium"+ variant="danger"+ loading={isSubmittingJwtSecretUpdateRequest}+ customFooter={+ <div className="space-x-2">+ <Button type="default" onClick={() => setIsCreatingKey(false)}>+ Cancel+ </Button>+ <Button+ type="primary"+ disabled={+ customToken.length < 32 || customToken.includes('@') || customToken.includes('$')+ }+ loading={isSubmittingJwtSecretUpdateRequest}+ onClick={() => handleJwtSecretUpdate(customToken, setIsCreatingKey)}+ >+ Apply new JWT secret+ </Button>+ </div>+ }+ >+ <Modal.Content>+ <div className="space-y-2 py-4">+ <p className="text-scale-1100 text-sm">+ Create a custom JWT secret. Make sure it is a strong combination of characters that+ cannot be guessed easily.+ </p>+ <Alert+ withIcon+ variant="warning"+ title="All existing API keys will be invalidated, and any open connections will be terminated."+ />+ <Input+ onChange={(e: any) => setCustomToken(e.target.value)}+ value={customToken}+ icon={<IconKey />}+ type={showCustomTokenInput ? 'text' : 'password'}+ className="w-full text-left"+ label="Custom JWT secret"+ descriptionText="Minimally 32 characters long, '@' and '$' are not allowed."+ actions={+ <div className="mr-1 flex items-center justify-center">+ <Button+ type="default"+ icon={showCustomTokenInput ? <IconEye /> : <IconEyeOff />}+ onClick={() => setShowCustomTokenInput(!showCustomTokenInput)}+ />+ </div>+ }+ />+ </div>+ </Modal.Content>+ </Modal>+ </>+ )+}++export default JWTSettingsdiff --git a/studio/components/interfaces/Settings/API/PostgrestConfig.tsx b/studio/components/interfaces/Settings/API/PostgrestConfig.tsxindex 5df3e8f9a85..24b02df89df 100644--- a/studio/components/interfaces/Settings/API/PostgrestConfig.tsx+++ b/studio/components/interfaces/Settings/API/PostgrestConfig.tsx@@ -1,10 +1,11 @@-import { useContext, useState } from 'react'+import { useContext, useState, FC } from 'react'import { indexOf } from 'lodash'+import { useRouter } from 'next/router'import { AutoField } from 'uniforms-bootstrap4'import { observer } from 'mobx-react-lite'import { IconAlertCircle } from '@supabase/ui'-import { checkPermissions, useStore } from 'hooks'+import { checkPermissions, useStore, useProjectPostgrestConfig } from 'hooks'import { API_URL } from 'lib/constants'import { patch } from 'lib/common/fetch'import SchemaFormPanel from 'components/to-be-cleaned/forms/SchemaFormPanel'@@ -14,15 +15,22 @@ import { PermissionAction } from '@supabase/shared-types/out/constants'// [Joshen TODO] Refactor to use supabase form component and FormPanel component-const PostgrestConfig = observer(({ config, projectRef }: any) => {+interface Props {}++const PostgrestConfig: FC<Props> = ({}) => {const PageState: any = useContext(PageContext)const { ui } = useStore()const { meta } = PageState+ const router = useRouter()+ const { ref } = router.query++ const { config, isError } = useProjectPostgrestConfig(ref as string | undefined)+const [updates, setUpdates] = useState({- db_schema: config.db_schema,- max_rows: config.max_rows,- db_extra_search_path: config.db_extra_search_path || '',+ db_schema: config?.db_schema,+ max_rows: config?.max_rows,+ db_extra_search_path: config?.db_extra_search_path ?? '',})const canUpdatePostgrestConfig = checkPermissions(@@ -32,10 +40,7 @@ const PostgrestConfig = observer(({ config, projectRef }: any) => {const updateConfig = async (updatedConfig: any) => {try {- const response = await patch(- `${API_URL}/projects/${projectRef}/config/postgrest`,- updatedConfig- )+ const response = await patch(`${API_URL}/projects/${ref}/config/postgrest`, updatedConfig)if (response.error) {throw response.error} else {@@ -107,57 +112,64 @@ const PostgrestConfig = observer(({ config, projectRef }: any) => {onSubmit={(model: any) => updateConfig(model)}onReset={() => setUpdates(config)}>- <div className="space-y-6 py-4">- {schema.length >= 1 && (- <MultiSelect+ {isError ? (+ <div className="py-8 flex items-center justify-center space-x-2">+ <IconAlertCircle size={16} strokeWidth={1.5} />+ <p className="text-sm text-scale-1100">Failed to retrieve API settings</p>+ </div>+ ) : (+ <div className="space-y-6 py-4">+ {schema.length >= 1 && (+ <MultiSelect+ disabled={!canUpdatePostgrestConfig}+ options={schema}+ // value must be passed as array of strings+ value={updates.db_schema.replace(/ /g, '').split(',')}+ // onChange returns array of strings+ onChange={(event) => {+ let payload = updates+ payload.db_schema = event.join(', ') // permanentSchema.concat(event).join(', ')+ setUpdates({ ...payload })+ updateConfig({ ...payload })+ }}+ label={'Schema'}+ descriptionText={+ <>+ The schema to expose in your API. Tables, views and stored procedures in this+ schema will get API endpoints.<code>public</code> and <code>storage</code> are+ protected by default.+ </>+ }+ emptyMessage={+ <>+ <IconAlertCircle strokeWidth={2} />+ <div className="mt-2 flex flex-col text-center">+ <p className="text-sm align-center">No schema available to choose</p>+ <p className="text-xs opacity-50">New schemas you create will appear here</p>+ </div>+ </>+ }+ />+ )}+ <AutoField+ disabled={!canUpdatePostgrestConfig}+ name="db_extra_search_path"+ showInlineError+ errorMessage="Must be a string."+ className={`${!canUpdatePostgrestConfig ? 'opacity-50' : ''}`}+ />+ <AutoFielddisabled={!canUpdatePostgrestConfig}- options={schema}- // value must be passed as array of strings- value={updates.db_schema.replace(/ /g, '').split(',')}- // onChange returns array of strings- onChange={(event) => {- let payload = updates- payload.db_schema = event.join(', ') // permanentSchema.concat(event).join(', ')- setUpdates({ ...payload })- updateConfig({ ...payload })- }}- label={'Schema'}- descriptionText={- <>- The schema to expose in your API. Tables, views and stored procedures in this- schema will get API endpoints.<code>public</code> and <code>storage</code> are- protected by default.- </>- }- emptyMessage={- <>- <IconAlertCircle strokeWidth={2} />- <div className="mt-2 flex flex-col text-center">- <p className="text-sm align-center">No schema available to choose</p>- <p className="text-xs opacity-50">New schemas you create will appear here</p>- </div>- </>- }+ name="max_rows"+ showInlineError+ errorMessage="Must be a number."+ className={`${!canUpdatePostgrestConfig ? 'opacity-50' : ''}`}/>- )}- <AutoField- disabled={!canUpdatePostgrestConfig}- name="db_extra_search_path"- showInlineError- errorMessage="Must be a string."- className={`${!canUpdatePostgrestConfig ? 'opacity-50' : ''}`}- />- <AutoField- disabled={!canUpdatePostgrestConfig}- name="max_rows"- showInlineError- errorMessage="Must be a number."- className={`${!canUpdatePostgrestConfig ? 'opacity-50' : ''}`}- />- </div>+ </div>+ )}</SchemaFormPanel></>)-})+}-export default PostgrestConfig+export default observer(PostgrestConfig)diff --git a/studio/components/interfaces/Settings/API/ServiceList.tsx b/studio/components/interfaces/Settings/API/ServiceList.tsxindex 70b292d74e8..76e3ef87b63 100644--- a/studio/components/interfaces/Settings/API/ServiceList.tsx+++ b/studio/components/interfaces/Settings/API/ServiceList.tsx@@ -1,42 +1,23 @@import useSWR from 'swr'-import { Dispatch, FC, SetStateAction, useEffect, useRef, useState } from 'react'+import { FC, useEffect, useRef } from 'react'import { useRouter } from 'next/router'-import * as Tooltip from '@radix-ui/react-tooltip'-import {- JwtSecretUpdateError,- JwtSecretUpdateProgress,- JwtSecretUpdateStatus,-} from '@supabase/shared-types/out/events'-import {- Alert,- Typography,- Input,- Modal,- IconKey,- Button,- Dropdown,- IconPenTool,- IconRefreshCw,- IconChevronDown,- IconLoader,- IconEye,- IconEyeOff,-} from '@supabase/ui'+import { JwtSecretUpdateError, JwtSecretUpdateStatus } from '@supabase/shared-types/out/events'+import { IconAlertCircle, Input } from '@supabase/ui'import { API_URL } from 'lib/constants'-import { uuidv4 } from 'lib/helpers'-import { patch, get } from 'lib/common/fetch'-import { useStore, useJwtSecretUpdateStatus, checkPermissions } from 'hooks'+import { get } from 'lib/common/fetch'+import {+ useStore,+ useProjectSettings,+ useProjectPostgrestConfig,+ useJwtSecretUpdateStatus,+} from 'hooks'import Panel from 'components/ui/Panel'-import ConfirmModal from 'components/ui/Dialogs/ConfirmDialog'import PostgrestConfig from './PostgrestConfig'import { DisplayApiSettings } from 'components/ui/ProjectSettings'-import {- JWT_SECRET_UPDATE_ERROR_MESSAGES,- JWT_SECRET_UPDATE_PROGRESS_MESSAGES,-} from './API.constants'-import { PermissionAction } from '@supabase/shared-types/out/constants'+import { JWT_SECRET_UPDATE_ERROR_MESSAGES } from './API.constants'+import JWTSettings from './JWTSettings'interface Props {projectRef: string@@ -47,50 +28,14 @@ const ServiceList: FC<Props> = ({ projectRef }) => {const router = useRouter()const { ref } = router.query- const [showCustomTokenInput, setShowCustomTokenInput] = useState(false)- const [customToken, setCustomToken] = useState<string>('')- const [isRegeneratingKey, setIsGeneratingKey] = useState<boolean>(false)- const [isCreatingKey, setIsCreatingKey] = useState<boolean>(false)- const [isSubmittingJwtSecretUpdateRequest, setIsSubmittingJwtSecretUpdateRequest] =- useState<boolean>(false)-- const {- data,- error,- mutate: mutateSettings,- }: any = useSWR(`${API_URL}/props/project/${projectRef}/settings`, get)- const { data: config, mutate: mutateConfig }: any = useSWR(- `${API_URL}/projects/${projectRef}/config/postgrest`,- get- )- const {- changeTrackingId,- isError: isJwtSecretUpdateStatusError,- isLoading: isJwtSecretUpdateStatusLoading,- jwtSecretUpdateError,- jwtSecretUpdateProgress,- jwtSecretUpdateStatus,- mutateJwtSecretUpdateStatus,- }: any = useJwtSecretUpdateStatus(ref)+ const { services, isError, mutateSettings } = useProjectSettings(ref as string | undefined)+ const { mutateConfig } = useProjectPostgrestConfig(ref as string | undefined)+ const { jwtSecretUpdateError, jwtSecretUpdateStatus }: any = useJwtSecretUpdateStatus(ref)+ const previousJwtSecretUpdateStatus = useRef()const { Failed, Updated, Updating } = JwtSecretUpdateStatus-- const isJwtSecretUpdateFailed = jwtSecretUpdateStatus === Failed- const isNotUpdatingJwtSecret =- jwtSecretUpdateStatus === undefined || jwtSecretUpdateStatus === Updated- const isUpdatingJwtSecret = jwtSecretUpdateStatus === Updatingconst jwtSecretUpdateErrorMessage =JWT_SECRET_UPDATE_ERROR_MESSAGES[jwtSecretUpdateError as JwtSecretUpdateError]- const jwtSecretUpdateProgressMessage =- JWT_SECRET_UPDATE_PROGRESS_MESSAGES[jwtSecretUpdateProgress as JwtSecretUpdateProgress]-- const previousJwtSecretUpdateStatus = useRef()-- const canReadJWTSecret = checkPermissions(PermissionAction.READ, 'postgrest_config')- const canGenerateNewJWTSecret = checkPermissions(- PermissionAction.INFRA_EXECUTE,- 'queue_job.projects.update_jwt'- )useEffect(() => {if (previousJwtSecretUpdateStatus.current === Updating) {@@ -112,76 +57,34 @@ const ServiceList: FC<Props> = ({ projectRef }) => {previousJwtSecretUpdateStatus.current = jwtSecretUpdateStatus}, [jwtSecretUpdateStatus])- if (error || isJwtSecretUpdateStatusError) {- return (- <div className="mx-auto p-6 text-center sm:w-full md:w-3/4">- <Typography.Title level={3}>Error loading API settings</Typography.Title>- </div>- )- }- if (!data || isJwtSecretUpdateStatusLoading) {- return (- <div className="mx-auto p-6 text-center sm:w-full md:w-3/4">- <Typography.Title level={3}>Loading...</Typography.Title>- </div>- )- }-- const { services } = data-// Get the API serviceconst API_SERVICE_ID = 1- const apiService = services.find((x: any) => x.app.id == API_SERVICE_ID)+ const apiService = services ? services.find((x: any) => x.app.id == API_SERVICE_ID) : {}const apiConfig = apiService?.app_config- async function handleJwtSecretUpdate(- jwt_secret: string,- setModalVisibility: Dispatch<SetStateAction<boolean>>- ) {- setIsSubmittingJwtSecretUpdateRequest(true)- try {- const trackingId = uuidv4()- const res = await patch(`${API_URL}/projects/${ref}/config/secrets`, {- jwt_secret,- change_tracking_id: trackingId,- })- if (res.error) throw res.error- setModalVisibility(false)- mutateJwtSecretUpdateStatus()- ui.setNotification({- category: 'info',- message:- 'Successfully submitted JWT secret update request. Please wait while your project is updated.',- })- } catch (error: any) {- ui.setNotification({ category: 'error', message: error.message })- } finally {- setIsSubmittingJwtSecretUpdateRequest(false)- }- }-return (<><div className="max-w-4xl p-4"><section>- <Panel- title={- <Typography.Title level={5} className="mb-0">- Project URL- </Typography.Title>- }- >+ <Panel title={<h5 className="mb-0">Project URL</h5>}><Panel.Content>- <Input- copy- label="URL"- readOnly- disabled- className="input-mono"- value={`https://${apiConfig?.endpoint ?? '-'}`}- descriptionText="A RESTful endpoint for querying and managing your database."- layout="horizontal"- />+ {isError ? (+ <div className="py-4 flex items-center justify-center space-x-2">+ <IconAlertCircle size={16} strokeWidth={1.5} />+ <p className="text-sm text-scale-1100">Failed to retrieve project URL</p>+ </div>+ ) : (+ <Input+ copy+ label="URL"+ readOnly+ disabled+ className="input-mono"+ value={`https://${apiConfig?.endpoint ?? '-'}`}+ descriptionText="A RESTful endpoint for querying and managing your database."+ layout="horizontal"+ />+ )}</Panel.Content></Panel></section>@@ -191,214 +94,13 @@ const ServiceList: FC<Props> = ({ projectRef }) => {</section><section>- <Panel- title={- <Typography.Title level={5} className="mb-0">- JWT Settings- </Typography.Title>- }- >- <Panel.Content className="border-panel-border-interior-light dark:border-panel-border-interior-dark space-y-6 border-t">- <Input- label="JWT Secret"- readOnly- copy={canReadJWTSecret && isNotUpdatingJwtSecret}- reveal={canReadJWTSecret && isNotUpdatingJwtSecret}- disabled- value={- !canReadJWTSecret- ? 'You need additional permissions to view the JWT secret'- : isJwtSecretUpdateFailed- ? 'JWT secret update failed'- : isUpdatingJwtSecret- ? 'Updating JWT secret...'- : config?.jwt_secret || ''- }- className="input-mono"- descriptionText={- 'Used to decode your JWTs. You can also use this to mint your own JWTs.'- }- layout="horizontal"- />- <div className="space-y-3">- <div className="dark:bg-bg-alt-dark bg-bg-alt-light dark:border-dark rounded-md border p-3 px-6 shadow-sm">- {isUpdatingJwtSecret ? (- <div className="flex items-center space-x-2">- <IconLoader className="animate-spin" size={14} />- <p className="text-sm">- Updating JWT secret: {jwtSecretUpdateProgressMessage}- </p>- </div>- ) : (- <div className="w-full space-y-2">- <div className="flex w-full items-center justify-between">- <div className="flex flex-col space-y-1">- <p>Generate a new JWT secret</p>- <p className="text-sm opacity-50">- A random secret will be created, or you can create your own.- </p>- </div>- <div className="flex flex-col items-end">- {isUpdatingJwtSecret ? (- <Button loading type="secondary">- Updating JWT secret...- </Button>- ) : !canGenerateNewJWTSecret ? (- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger>- <Button- disabled- as="span"- type="default"- iconRight={<IconChevronDown />}- >- Generate a new secret- </Button>- </Tooltip.Trigger>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'bg-scale-100 rounded py-1 px-2 leading-none shadow',- 'border-scale-200 border',- ].join(' ')}- >- <span className="text-scale-1200 text-xs">- You need additional permissions to generate a new JWT secret- </span>- </div>- </Tooltip.Content>- </Tooltip.Root>- ) : (- <Dropdown- align="end"- side="bottom"- overlay={- <>- <Dropdown.Item- onClick={() => setIsGeneratingKey(true)}- icon={<IconRefreshCw size={16} />}- >- Generate a random secret- </Dropdown.Item>- <Dropdown.Seperator />- <Dropdown.Item- onClick={() => setIsCreatingKey(true)}- icon={<IconPenTool size={16} />}- >- Create my own secret- </Dropdown.Item>- </>- }- >- <Button as="span" type="default" iconRight={<IconChevronDown />}>- Generate a new secret- </Button>- </Dropdown>- )}- </div>- </div>- </div>- )}- </div>- {isJwtSecretUpdateFailed ? (- <Alert withIcon variant="warning" title="Failed to update JWT secret">- Please try again. If the failures persist, please contact Supabase support with- the following details: <br />- Change tracking ID: {changeTrackingId} <br />- Error message: {jwtSecretUpdateErrorMessage}- </Alert>- ) : canGenerateNewJWTSecret ? (- <Alert- withIcon- variant="warning"- title="This will invalidate all existing API keys!"- >- Generating a new JWT secret will invalidate <u>all</u> of your API keys,- including your <code>service_role</code> and <code>anon</code> keys. Your- project will also be restarted during this process, which will terminate any- existing connections.- </Alert>- ) : (- <></>- )}- </div>- </Panel.Content>- </Panel>+ <JWTSettings /></section>- <section>{config && <PostgrestConfig config={config} projectRef={projectRef} />}</section>+ <section>+ <PostgrestConfig />+ </section></div>-- <ConfirmModal- danger- visible={isRegeneratingKey}- title="Are you absolutely sure?"- description="This action cannot be undone and the old JWT secret will be lost. All existing API keys- will be invalidated, and any open connections will be terminated."- buttonLabel="Generate new secret"- buttonLoadingLabel="Generating"- onSelectCancel={() => setIsGeneratingKey(false)}- onSelectConfirm={() => handleJwtSecretUpdate('ROLL', setIsGeneratingKey)}- />-- <Modal- closable- header="Create a custom JWT secret"- visible={isCreatingKey}- size="medium"- variant="danger"- loading={isSubmittingJwtSecretUpdateRequest}- customFooter={- <div className="space-x-2">- <Button type="default" onClick={() => setIsCreatingKey(false)}>- Cancel- </Button>- <Button- type="primary"- disabled={- customToken.length < 32 || customToken.includes('@') || customToken.includes('$')- }- loading={isSubmittingJwtSecretUpdateRequest}- onClick={() => handleJwtSecretUpdate(customToken, setIsCreatingKey)}- >- Apply new JWT secret- </Button>- </div>- }- >- <Modal.Content>- <div className="space-y-2 py-4">- <p className="text-scale-1100 text-sm">- Create a custom JWT secret. Make sure it is a strong combination of characters that- cannot be guessed easily.- </p>- <Alert- withIcon- variant="warning"- title="All existing API keys will be invalidated, and any open connections will be terminated."- />- <Input- onChange={(e: any) => setCustomToken(e.target.value)}- value={customToken}- icon={<IconKey />}- type={showCustomTokenInput ? 'text' : 'password'}- className="w-full text-left"- label="Custom JWT secret"- descriptionText="Minimally 32 characters long, '@' and '$' are not allowed."- actions={- <div className="mr-1 flex items-center justify-center">- <Button- type="default"- icon={showCustomTokenInput ? <IconEye /> : <IconEyeOff />}- onClick={() => setShowCustomTokenInput(!showCustomTokenInput)}- />- </div>- }- />- </div>- </Modal.Content>- </Modal></>)}diff --git a/studio/components/ui/ProjectSettings/DisplayApiSettings.tsx b/studio/components/ui/ProjectSettings/DisplayApiSettings.tsxindex 140f21f907f..5f19a2ce73d 100644--- a/studio/components/ui/ProjectSettings/DisplayApiSettings.tsx+++ b/studio/components/ui/ProjectSettings/DisplayApiSettings.tsx@@ -1,25 +1,26 @@import { useRouter } from 'next/router'-import { Input } from '@supabase/ui'+import { IconAlertCircle, IconLoader, Input } from '@supabase/ui'import { JwtSecretUpdateStatus } from '@supabase/shared-types/out/events'import { PermissionAction } from '@supabase/shared-types/out/constants'import { checkPermissions, useJwtSecretUpdateStatus, useProjectSettings } from 'hooks'import { DEFAULT_PROJECT_API_SERVICE_ID } from 'lib/constants'import Panel from 'components/ui/Panel'-import { SettingsLoadingState } from './SettingsLoadingState'const DisplayApiSettings = () => {const router = useRouter()const { ref } = router.query+const {services,- isLoading: isProjectSettingsLoading,+ error: projectSettingsError,isError: isProjectSettingsError,+ isLoading: isProjectSettingsLoading,} = useProjectSettings(ref as string | undefined)const {+ jwtSecretUpdateStatus,isError: isJwtSecretUpdateStatusError,isLoading: isJwtSecretUpdateStatusLoading,- jwtSecretUpdateStatus,}: any = useJwtSecretUpdateStatus(ref)const canReadAPIKeys = checkPermissions(PermissionAction.READ, 'service_api_keys')@@ -30,7 +31,7 @@ const DisplayApiSettings = () => {const apiService = (services ?? []).find((x: any) => x.app.id == DEFAULT_PROJECT_API_SERVICE_ID)const apiKeys = apiService?.service_api_keys ?? []// api keys should not be empty. However it can be populated with a delay on project creation- const isApikeysEmpty = apiKeys.length === 0+ const isApiKeysEmpty = apiKeys.length === 0return (<Panel@@ -45,11 +46,22 @@ const DisplayApiSettings = () => {</div>}>- {isProjectSettingsLoading || isJwtSecretUpdateStatusLoading || isApikeysEmpty ? (- <SettingsLoadingState- isError={isProjectSettingsError || isJwtSecretUpdateStatusError}- errorMessage="Failed to fetch API keys"- />+ {isProjectSettingsError || isJwtSecretUpdateStatusError ? (+ <div className="py-8 flex items-center justify-center space-x-2">+ <IconAlertCircle size={16} strokeWidth={1.5} />+ <p className="text-sm text-scale-1100">+ {isProjectSettingsError ? 'Failed to retrieve API keys' : 'Failed to update JWT secret'}+ </p>+ </div>+ ) : isApiKeysEmpty || isProjectSettingsLoading || isJwtSecretUpdateStatusLoading ? (+ <div className="py-8 flex items-center justify-center space-x-2">+ <IconLoader className="animate-spin" size={16} strokeWidth={1.5} />+ <p className="text-sm text-scale-1100">+ {isProjectSettingsLoading || isApiKeysEmpty+ ? 'Retrieving API keys'+ : 'JWT secret is being updated'}+ </p>+ </div>) : (apiKeys.map((x: any, i: number) => (<Panel.Contentdiff --git a/studio/components/ui/ProjectSettings/DisplayConfigSettings.tsx b/studio/components/ui/ProjectSettings/DisplayConfigSettings.tsxindex b106361439c..ffb3b76f0e2 100644--- a/studio/components/ui/ProjectSettings/DisplayConfigSettings.tsx+++ b/studio/components/ui/ProjectSettings/DisplayConfigSettings.tsx@@ -1,9 +1,8 @@import { FC } from 'react'import { useRouter } from 'next/router'-import { Input } from '@supabase/ui'+import { Input, IconAlertCircle, IconLoader } from '@supabase/ui'import { JwtSecretUpdateStatus } from '@supabase/shared-types/out/events'import { useJwtSecretUpdateStatus, useProjectSettings } from 'hooks'-import { SettingsLoadingState } from './SettingsLoadingState'import { DEFAULT_PROJECT_API_SERVICE_ID } from 'lib/constants'import Panel from 'components/ui/Panel'@@ -31,11 +30,22 @@ const DisplayConfigSettings = () => {return (<ConfigContentWrapper>- {isProjectSettingsLoading || isJwtSecretUpdateStatusLoading ? (- <SettingsLoadingState- isError={isProjectSettingsError || isJwtSecretUpdateStatusError}- errorMessage="Failed to fetch project configuration"- />+ {isProjectSettingsError || isJwtSecretUpdateStatusError ? (+ <div className="py-8 flex items-center justify-center space-x-2">+ <IconAlertCircle size={16} strokeWidth={1.5} />+ <p className="text-sm text-scale-1100">+ {isProjectSettingsError+ ? 'Failed to retrieve configuration'+ : 'Failed to update JWT secret'}+ </p>+ </div>+ ) : isProjectSettingsLoading || isJwtSecretUpdateStatusLoading ? (+ <div className="py-8 flex items-center justify-center space-x-2">+ <IconLoader className="animate-spin" size={16} strokeWidth={1.5} />+ <p className="text-sm text-scale-1100">+ {isProjectSettingsLoading ? 'Retrieving API keys' : 'JWT secret is being updated'}+ </p>+ </div>) : (<><Panel.Content>diff --git a/studio/components/ui/ProjectSettings/SettingsLoadingState.tsx b/studio/components/ui/ProjectSettings/SettingsLoadingState.tsxdeleted file mode 100644index b35f19cd42e..00000000000--- a/studio/components/ui/ProjectSettings/SettingsLoadingState.tsx+++ /dev/null@@ -1,24 +0,0 @@-import { FC } from 'react'-import { IconAlertCircle, Loading, Typography } from '@supabase/ui'-import { SettingsLoadingStateProps } from './SettingsLoadingState.types'-import Panel from 'components/ui/Panel'--export const SettingsLoadingState: FC<SettingsLoadingStateProps> = ({ isError, errorMessage }) => {- return (- <Panel.Content className="py-8">- {isError ? (- <div className="flex items-center space-x-2">- <Typography.Text type="secondary">- <IconAlertCircle strokeWidth={2} />- </Typography.Text>- <Typography.Text type="secondary">{errorMessage}</Typography.Text>- </div>- ) : (- <div className="py-4">- {/* @ts-ignore */}- <Loading active={true} />- </div>- )}- </Panel.Content>- )-}diff --git a/studio/components/ui/ProjectSettings/SettingsLoadingState.types.tsx b/studio/components/ui/ProjectSettings/SettingsLoadingState.types.tsxdeleted file mode 100644index b3c9248594d..00000000000--- a/studio/components/ui/ProjectSettings/SettingsLoadingState.types.tsx+++ /dev/null@@ -1,4 +0,0 @@-export interface SettingsLoadingStateProps {- isError: boolean- errorMessage: string-}diff --git a/studio/hooks/queries/index.ts b/studio/hooks/queries/index.tsindex d4a6f35db2f..46b5b4d525d 100644--- a/studio/hooks/queries/index.ts+++ b/studio/hooks/queries/index.ts@@ -8,3 +8,4 @@ export * from './useProjectPaygStatistics'export * from './useProjectSettings'export * from './useProjectSubscription'export * from './useSubscriptionStats'+export * from './useProjectPostgrestConfig'diff --git a/studio/hooks/queries/useJwtSecretUpdateStatus.ts b/studio/hooks/queries/useJwtSecretUpdateStatus.tsindex 898ca22c93a..11cb7dc31ca 100644--- a/studio/hooks/queries/useJwtSecretUpdateStatus.ts+++ b/studio/hooks/queries/useJwtSecretUpdateStatus.ts@@ -13,6 +13,7 @@ export function useJwtSecretUpdateStatus(projectRef: string | string[] | undefinconst meta = data?.jwtSecretUpdateStatus?.metareturn {changeTrackingId: meta?.change_tracking_id,+ error,isError: !!anyError,isLoading: !anyError && !data,jwtSecretUpdateError: meta?.error,diff --git a/studio/hooks/queries/useProjectPostgrestConfig.ts b/studio/hooks/queries/useProjectPostgrestConfig.tsnew file mode 100644index 00000000000..a18768bbb75--- /dev/null+++ b/studio/hooks/queries/useProjectPostgrestConfig.ts@@ -0,0 +1,17 @@+import useSWR from 'swr'+import { get } from 'lib/common/fetch'+import { API_URL } from 'lib/constants'++export function useProjectPostgrestConfig(ref?: string) {+ const url = `${API_URL}/projects/${ref}/config/postgrest`+ const { data, error, mutate } = useSWR<any>(ref ? url : null, get)+ const anyError = data?.error || error++ return {+ config: anyError ? undefined : data,+ error: anyError,+ isLoading: !anyError && !data,+ isError: !!anyError,+ mutateConfig: mutate,+ }+}diff --git a/studio/hooks/queries/useProjectSettings.ts b/studio/hooks/queries/useProjectSettings.tsindex 946c4cc074d..cccebec4bb1 100644--- a/studio/hooks/queries/useProjectSettings.ts+++ b/studio/hooks/queries/useProjectSettings.ts@@ -4,7 +4,7 @@ import useSWR from 'swr'export function useProjectSettings(ref?: string) {const url = `${API_URL}/props/project/${ref}/settings`- const { data, error } = useSWR<any>(ref ? url : null, get, {+ const { data, error, mutate } = useSWR<any>(ref ? url : null, get, {/*** on project creation, the service_api_keys will be populated with a delay* check for data.services.service_api_keys, return a valid refresh interval if it's empty@@ -21,6 +21,7 @@ export function useProjectSettings(ref?: string) {const anyError = data?.error || errorreturn {+ mutateSettings: mutate,project: anyError ? undefined : data?.project,services: anyError ? undefined : data?.services,error: anyError,