chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动

演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-11-18 13:59:25 +08:00
1 parent 60158935f4
commit 6519682885
15831 files changed
+3063428

No files matched your search

@@ -0,0 +1,19 @@
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { describe, expect, it, vi } from 'vite-plus/test'
import AuthorizedInDataSourceNode from '../authorized-in-data-source-node'
describe('AuthorizedInDataSourceNode', () => {
it.each([
[1, 'plugin.auth.authorization'],
[3, 'plugin.auth.authorizations'],
] as const)('opens datasource settings with %s authorizations', async (count, name) => {
const user = userEvent.setup()
const onJump = vi.fn()
render(<AuthorizedInDataSourceNode authorizationsNum={count} onJumpToDataSourcePage={onJump} />)
await user.click(screen.getByRole('button', { name }))
expect(onJump).toHaveBeenCalledOnce()
})
})
@@ -0,0 +1,247 @@
import type { ReactNode } from 'react'
import type { Credential, PluginPayload } from '../types'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { render } from '@/test/console/render'
import { AuthCategory, CredentialTypeEnum } from '../types'
// ==================== Mock Setup ====================
const mockGetPluginCredentialInfo = vi.fn()
const mockIsPluginCredentialInfoLoading = vi.fn()
const mockGetPluginOAuthClientSchema = vi.fn()
vi.mock('@/context/workspace-state', async () => {
const { createWorkspaceStateModuleMock } = await import('@/test/console/state-fixture')
return createWorkspaceStateModuleMock(() => ({
currentWorkspace: { id: 'workspace-1' },
}))
})
vi.mock('@/service/use-plugins-auth', () => ({
useGetPluginCredentialInfo: (url: string) => ({
data: url ? mockGetPluginCredentialInfo() : undefined,
isLoading: mockIsPluginCredentialInfoLoading(),
}),
useDeletePluginCredential: () => ({ mutateAsync: vi.fn() }),
useSetPluginDefaultCredential: () => ({ mutateAsync: vi.fn() }),
useUpdatePluginCredential: () => ({ mutateAsync: vi.fn() }),
useInvalidPluginCredentialInfo: () => vi.fn(),
useGetPluginOAuthUrl: () => ({ mutateAsync: vi.fn() }),
useGetPluginOAuthClientSchema: () => ({
data: mockGetPluginOAuthClientSchema(),
isLoading: false,
}),
useSetPluginOAuthCustomClient: () => ({ mutateAsync: vi.fn() }),
useDeletePluginOAuthCustomClient: () => ({ mutateAsync: vi.fn() }),
useInvalidPluginOAuthClientSchema: () => vi.fn(),
useAddPluginCredential: () => ({ mutateAsync: vi.fn() }),
useGetPluginCredentialSchema: () => ({ data: undefined, isLoading: false }),
}))
vi.mock('@/hooks/use-oauth', () => ({
openOAuthPopup: vi.fn(),
}))
vi.mock('@/service/use-triggers', () => ({
useTriggerPluginDynamicOptions: () => ({ data: { options: [] }, isLoading: false }),
}))
// ==================== Test Utilities ====================
const createConsoleQueryClient = () =>
new QueryClient({
defaultOptions: {
queries: { retry: false, gcTime: 0 },
},
})
const createWrapper = () => {
const testQueryClient = createConsoleQueryClient()
return ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={testQueryClient}>{children}</QueryClientProvider>
)
}
const createPluginPayload = (overrides: Partial<PluginPayload> = {}): PluginPayload => ({
category: AuthCategory.tool,
provider: 'test-provider',
...overrides,
})
const createCredential = (overrides: Partial<Credential> = {}): Credential => ({
id: 'test-credential-id',
name: 'Test Credential',
provider: 'test-provider',
credential_type: CredentialTypeEnum.API_KEY,
is_default: false,
credentials: { api_key: 'test-key' },
...overrides,
})
// ==================== Tests ====================
vi.mock('@/context/permission-state', async () => {
const { createPermissionStateModuleMock } = await import('@/test/console/state-fixture')
return createPermissionStateModuleMock(() => ({
workspacePermissionKeys: [],
}))
})
describe('AuthorizedInNode Component', () => {
beforeEach(() => {
vi.clearAllMocks()
mockIsPluginCredentialInfoLoading.mockReturnValue(false)
mockGetPluginCredentialInfo.mockReturnValue({
credentials: [createCredential({ is_default: true })],
supported_credential_types: [CredentialTypeEnum.API_KEY],
allow_custom_token: true,
})
mockGetPluginOAuthClientSchema.mockReturnValue({
schema: [],
is_oauth_custom_client_enabled: false,
is_system_oauth_params_exists: false,
})
})
it('should expose the workspace default credential id when requested', async () => {
const AuthorizedInNode = (await import('../authorized-in-node')).default
const onDefaultCredentialChange = vi.fn()
const pluginPayload = createPluginPayload()
render(
<AuthorizedInNode
pluginPayload={pluginPayload}
onAuthorizationItemClick={vi.fn()}
onDefaultCredentialChange={onDefaultCredentialChange}
/>,
{ wrapper: createWrapper() },
)
expect(screen.getByText('plugin.auth.workspaceDefault')).toBeInTheDocument()
await waitFor(() => {
expect(onDefaultCredentialChange).toHaveBeenCalledWith('test-credential-id')
})
})
it('should render credential name when credentialId matches', async () => {
const AuthorizedInNode = (await import('../authorized-in-node')).default
const credential = createCredential({ id: 'selected-id', name: 'My Credential' })
mockGetPluginCredentialInfo.mockReturnValue({
credentials: [credential],
supported_credential_types: [CredentialTypeEnum.API_KEY],
allow_custom_token: true,
})
const pluginPayload = createPluginPayload()
render(
<AuthorizedInNode
pluginPayload={pluginPayload}
onAuthorizationItemClick={vi.fn()}
credentialId="selected-id"
/>,
{ wrapper: createWrapper() },
)
expect(screen.getByText('My Credential'))!.toBeInTheDocument()
})
it('should show auth removed when credentialId not found', async () => {
const AuthorizedInNode = (await import('../authorized-in-node')).default
mockGetPluginCredentialInfo.mockReturnValue({
credentials: [createCredential()],
supported_credential_types: [CredentialTypeEnum.API_KEY],
allow_custom_token: true,
})
const pluginPayload = createPluginPayload()
render(
<AuthorizedInNode
pluginPayload={pluginPayload}
onAuthorizationItemClick={vi.fn()}
credentialId="non-existent"
/>,
{ wrapper: createWrapper() },
)
expect(screen.getByText('plugin.auth.authRemoved'))!.toBeInTheDocument()
})
it('should not show auth removed while credential info is loading', async () => {
const AuthorizedInNode = (await import('../authorized-in-node')).default
mockIsPluginCredentialInfoLoading.mockReturnValue(true)
mockGetPluginCredentialInfo.mockReturnValue(undefined)
const pluginPayload = createPluginPayload()
render(
<AuthorizedInNode
pluginPayload={pluginPayload}
onAuthorizationItemClick={vi.fn()}
credentialId="new-credential-id"
/>,
{ wrapper: createWrapper() },
)
expect(screen.queryByText('plugin.auth.authRemoved')).not.toBeInTheDocument()
expect(screen.getByText('common.loading')).toBeInTheDocument()
})
it('should show unavailable when credential is not allowed', async () => {
const AuthorizedInNode = (await import('../authorized-in-node')).default
const credential = createCredential({
id: 'unavailable-id',
not_allowed_to_use: true,
from_enterprise: false,
})
mockGetPluginCredentialInfo.mockReturnValue({
credentials: [credential],
supported_credential_types: [CredentialTypeEnum.API_KEY],
allow_custom_token: true,
})
const pluginPayload = createPluginPayload()
render(
<AuthorizedInNode
pluginPayload={pluginPayload}
onAuthorizationItemClick={vi.fn()}
credentialId="unavailable-id"
/>,
{ wrapper: createWrapper() },
)
const button = screen.getByRole('button')
expect(button.textContent).toContain('plugin.auth.unavailable')
})
it('should show unavailable when default credential is not allowed', async () => {
const AuthorizedInNode = (await import('../authorized-in-node')).default
const credential = createCredential({
is_default: true,
not_allowed_to_use: true,
})
mockGetPluginCredentialInfo.mockReturnValue({
credentials: [credential],
supported_credential_types: [CredentialTypeEnum.API_KEY],
allow_custom_token: true,
})
const pluginPayload = createPluginPayload()
render(<AuthorizedInNode pluginPayload={pluginPayload} onAuthorizationItemClick={vi.fn()} />, {
wrapper: createWrapper(),
})
const button = screen.getByRole('button')
expect(button.textContent).toContain('plugin.auth.unavailable')
})
it('should show unavailable when workspace default credential is missing', async () => {
const AuthorizedInNode = (await import('../authorized-in-node')).default
mockGetPluginCredentialInfo.mockReturnValue({
credentials: [],
supported_credential_types: [CredentialTypeEnum.API_KEY],
allow_custom_token: true,
})
const pluginPayload = createPluginPayload()
render(<AuthorizedInNode pluginPayload={pluginPayload} onAuthorizationItemClick={vi.fn()} />, {
wrapper: createWrapper(),
})
const button = screen.getByRole('button')
expect(button.textContent).toContain('plugin.auth.workspaceDefault')
expect(button.textContent).toContain('plugin.auth.unavailable')
})
})
@@ -0,0 +1,243 @@
import type { ReactNode } from 'react'
import type { Credential, PluginPayload } from '../types'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { seedAccountProfileQuery } from '@/test/console/account-profile'
import { render } from '@/test/console/render'
import { AuthCategory, CredentialTypeEnum } from '../types'
// ==================== Mock Setup ====================
const mockGetPluginCredentialInfo = vi.fn()
const mockGetPluginOAuthClientSchema = vi.fn()
vi.mock('@/service/use-plugins-auth', () => ({
useGetPluginCredentialInfo: (url: string) => ({
data: url ? mockGetPluginCredentialInfo() : undefined,
isLoading: false,
}),
useDeletePluginCredential: () => ({ mutateAsync: vi.fn() }),
useSetPluginDefaultCredential: () => ({ mutateAsync: vi.fn() }),
useUpdatePluginCredential: () => ({ mutateAsync: vi.fn() }),
useInvalidPluginCredentialInfo: () => vi.fn(),
useGetPluginOAuthUrl: () => ({ mutateAsync: vi.fn() }),
useGetPluginOAuthClientSchema: () => ({
data: mockGetPluginOAuthClientSchema(),
isLoading: false,
}),
useSetPluginOAuthCustomClient: () => ({ mutateAsync: vi.fn() }),
useDeletePluginOAuthCustomClient: () => ({ mutateAsync: vi.fn() }),
useInvalidPluginOAuthClientSchema: () => vi.fn(),
useAddPluginCredential: () => ({ mutateAsync: vi.fn() }),
useGetPluginCredentialSchema: () => ({ data: undefined, isLoading: false }),
}))
const mockIsCurrentWorkspaceManager = vi.fn()
const mockUserProfile = {
id: 'test-user',
name: 'Test User',
email: 'test@example.com',
avatar_url: '',
}
vi.mock('@/context/workspace-state', async () => {
const { createWorkspaceStateModuleMock } = await import('@/test/console/state-fixture')
return createWorkspaceStateModuleMock(() => ({
userProfile: mockUserProfile,
isCurrentWorkspaceManager: mockIsCurrentWorkspaceManager(),
workspacePermissionKeys: ['credential.use', 'credential.create', 'credential.manage'],
}))
})
vi.mock('@/context/permission-state', async () => {
const { createPermissionStateModuleMock } = await import('@/test/console/state-fixture')
return createPermissionStateModuleMock(() => ({
userProfile: mockUserProfile,
isCurrentWorkspaceManager: mockIsCurrentWorkspaceManager(),
workspacePermissionKeys: ['credential.use', 'credential.create', 'credential.manage'],
}))
})
vi.mock('@/hooks/use-oauth', () => ({
openOAuthPopup: vi.fn(),
}))
vi.mock('@/service/use-triggers', () => ({
useTriggerPluginDynamicOptions: () => ({ data: { options: [] }, isLoading: false }),
}))
// ==================== Test Utilities ====================
const createConsoleQueryClient = () =>
new QueryClient({
defaultOptions: {
queries: { retry: false, gcTime: Infinity, staleTime: Infinity },
},
})
const createWrapper = () => {
const testQueryClient = createConsoleQueryClient()
seedAccountProfileQuery(testQueryClient, mockUserProfile)
return ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={testQueryClient}>{children}</QueryClientProvider>
)
}
const createPluginPayload = (overrides: Partial<PluginPayload> = {}): PluginPayload => ({
category: AuthCategory.tool,
provider: 'test-provider',
...overrides,
})
const createCredential = (overrides: Partial<Credential> = {}): Credential => ({
id: 'test-credential-id',
name: 'Test Credential',
provider: 'test-provider',
credential_type: CredentialTypeEnum.API_KEY,
is_default: false,
credentials: { api_key: 'test-key' },
...overrides,
})
// ==================== Tests ====================
describe('PluginAuthInAgent Component', () => {
beforeEach(() => {
vi.clearAllMocks()
mockIsCurrentWorkspaceManager.mockReturnValue(true)
mockGetPluginCredentialInfo.mockReturnValue({
credentials: [createCredential()],
supported_credential_types: [CredentialTypeEnum.API_KEY],
allow_custom_token: true,
})
mockGetPluginOAuthClientSchema.mockReturnValue({
schema: [],
is_oauth_custom_client_enabled: false,
is_system_oauth_params_exists: false,
})
})
it('should render Authorize when not authorized', async () => {
const PluginAuthInAgent = (await import('../plugin-auth-in-agent')).default
mockGetPluginCredentialInfo.mockReturnValue({
credentials: [],
supported_credential_types: [CredentialTypeEnum.API_KEY],
allow_custom_token: true,
})
const pluginPayload = createPluginPayload()
render(<PluginAuthInAgent pluginPayload={pluginPayload} />, { wrapper: createWrapper() })
expect(screen.getByRole('button', { name: 'plugin.auth.useApiAuth' })).toBeEnabled()
})
it('should render Authorized with workspace default when authorized', async () => {
const PluginAuthInAgent = (await import('../plugin-auth-in-agent')).default
const pluginPayload = createPluginPayload()
render(<PluginAuthInAgent pluginPayload={pluginPayload} />, { wrapper: createWrapper() })
expect(screen.getByText('plugin.auth.workspaceDefault'))!.toBeInTheDocument()
})
it('should show credential name when credentialId is provided', async () => {
const PluginAuthInAgent = (await import('../plugin-auth-in-agent')).default
const credential = createCredential({ id: 'selected-id', name: 'Selected Credential' })
mockGetPluginCredentialInfo.mockReturnValue({
credentials: [credential],
supported_credential_types: [CredentialTypeEnum.API_KEY],
allow_custom_token: true,
})
const pluginPayload = createPluginPayload()
render(<PluginAuthInAgent pluginPayload={pluginPayload} credentialId="selected-id" />, {
wrapper: createWrapper(),
})
expect(screen.getByText('Selected Credential'))!.toBeInTheDocument()
})
it('should show auth removed when credential not found', async () => {
const PluginAuthInAgent = (await import('../plugin-auth-in-agent')).default
mockGetPluginCredentialInfo.mockReturnValue({
credentials: [createCredential()],
supported_credential_types: [CredentialTypeEnum.API_KEY],
allow_custom_token: true,
})
const pluginPayload = createPluginPayload()
render(<PluginAuthInAgent pluginPayload={pluginPayload} credentialId="non-existent-id" />, {
wrapper: createWrapper(),
})
expect(screen.getByText('plugin.auth.authRemoved'))!.toBeInTheDocument()
})
it('should show unavailable when credential is not allowed to use', async () => {
const PluginAuthInAgent = (await import('../plugin-auth-in-agent')).default
const credential = createCredential({
id: 'unavailable-id',
name: 'Unavailable Credential',
not_allowed_to_use: true,
from_enterprise: false,
})
mockGetPluginCredentialInfo.mockReturnValue({
credentials: [credential],
supported_credential_types: [CredentialTypeEnum.API_KEY],
allow_custom_token: true,
})
const pluginPayload = createPluginPayload()
render(<PluginAuthInAgent pluginPayload={pluginPayload} credentialId="unavailable-id" />, {
wrapper: createWrapper(),
})
const button = screen.getByRole('button')
expect(button.textContent).toContain('plugin.auth.unavailable')
})
it('should trigger handleAuthorizationItemClick and close popup when item is clicked', async () => {
const PluginAuthInAgent = (await import('../plugin-auth-in-agent')).default
const onAuthorizationItemClick = vi.fn()
const credential = createCredential({ id: 'test-cred-id', name: 'Test Credential' })
mockGetPluginCredentialInfo.mockReturnValue({
credentials: [credential],
supported_credential_types: [CredentialTypeEnum.API_KEY],
allow_custom_token: true,
})
const pluginPayload = createPluginPayload()
render(
<PluginAuthInAgent
pluginPayload={pluginPayload}
onAuthorizationItemClick={onAuthorizationItemClick}
/>,
{ wrapper: createWrapper() },
)
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'plugin.auth.workspaceDefault' }))
await user.click(
within(await screen.findByRole('dialog')).getByText('plugin.auth.workspaceDefault'),
)
expect(onAuthorizationItemClick).toHaveBeenCalledExactlyOnceWith('')
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
})
it('should call onAuthorizationItemClick with credential id when specific credential is clicked', async () => {
const PluginAuthInAgent = (await import('../plugin-auth-in-agent')).default
const onAuthorizationItemClick = vi.fn()
const credential = createCredential({
id: 'specific-cred-id',
name: 'Specific Credential',
credential_type: CredentialTypeEnum.API_KEY,
})
mockGetPluginCredentialInfo.mockReturnValue({
credentials: [credential],
supported_credential_types: [CredentialTypeEnum.API_KEY],
allow_custom_token: true,
})
const pluginPayload = createPluginPayload()
render(
<PluginAuthInAgent
pluginPayload={pluginPayload}
onAuthorizationItemClick={onAuthorizationItemClick}
/>,
{ wrapper: createWrapper() },
)
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'plugin.auth.workspaceDefault' }))
await user.click(within(await screen.findByRole('dialog')).getByText('Specific Credential'))
expect(onAuthorizationItemClick).toHaveBeenCalledExactlyOnceWith('specific-cred-id')
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
})
})
@@ -0,0 +1,34 @@
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { describe, expect, it, vi } from 'vite-plus/test'
import PluginAuthInDataSourceNode from '../plugin-auth-in-datasource-node'
describe('PluginAuthInDataSourceNode', () => {
it('offers navigation to connect while hiding authorized content', async () => {
const user = userEvent.setup()
const onJump = vi.fn()
render(
<PluginAuthInDataSourceNode onJumpToDataSourcePage={onJump}>
Data Source Connected
</PluginAuthInDataSourceNode>,
)
expect(screen.queryByText('Data Source Connected')).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'common.integrations.connect' }))
expect(onJump).toHaveBeenCalledOnce()
})
it('replaces the connect action with authorized content', () => {
render(
<PluginAuthInDataSourceNode isAuthorized onJumpToDataSourcePage={vi.fn()}>
Data Source Connected
</PluginAuthInDataSourceNode>,
)
expect(
screen.queryByRole('button', { name: 'common.integrations.connect' }),
).not.toBeInTheDocument()
expect(screen.getByText('Data Source Connected')).toBeInTheDocument()
})
})
@@ -0,0 +1,109 @@
import type { Credential } from '../types'
import type { ConsoleQueryTestOptions } from '@/test/console/query-data'
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import PluginAuth from '../plugin-auth'
import { AuthCategory, CredentialTypeEnum } from '../types'
const requests = vi.hoisted(() => ({ credentials: vi.fn() }))
vi.mock('@/service/base', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/base')>()),
get: requests.credentials,
}))
const defaultPayload = { category: AuthCategory.tool, provider: 'test-provider' }
const credential: Credential = {
id: 'key-1',
name: 'Production key',
provider: 'test-provider',
credential_type: CredentialTypeEnum.API_KEY,
is_default: true,
credentials: { api_key: 'masked-secret' },
}
const credentialInfo = (credentials: Credential[] = [], allowCustomToken = true) => ({
credentials,
supported_credential_types: [CredentialTypeEnum.API_KEY],
allow_custom_token: allowCustomToken,
is_oauth_custom_client_enabled: false,
})
const onUrlUpdate = vi.fn()
const renderAuth = (
options: ConsoleQueryTestOptions = {},
props: Partial<React.ComponentProps<typeof PluginAuth>> = {},
) =>
renderWithConsoleQuery(
<NuqsTestingAdapter onUrlUpdate={onUrlUpdate}>
<PluginAuth pluginPayload={defaultPayload} {...props} />
</NuqsTestingAdapter>,
{
workspacePermissionKeys: ['credential.use', 'credential.create', 'credential.manage'],
systemFeatures: { rbac_enabled: true },
...options,
},
)
beforeEach(() => {
requests.credentials.mockResolvedValue(credentialInfo())
})
it('offers API authorization when the provider has no saved credentials', async () => {
renderAuth()
expect(await screen.findByRole('button', { name: 'plugin.auth.useApiAuth' })).toBeEnabled()
expect(requests.credentials).toHaveBeenCalledWith(
'/workspaces/current/tool-provider/builtin/test-provider/credential/info',
)
expect(screen.queryByText('plugin.auth.permissionHint.title')).not.toBeInTheDocument()
expect(
screen.queryByRole('button', { name: /plugin.auth.authorization$/ }),
).not.toBeInTheDocument()
})
it('opens the saved credentials when the provider is authorized', async () => {
const user = userEvent.setup()
requests.credentials.mockResolvedValue(credentialInfo([credential]))
renderAuth()
const trigger = await screen.findByRole('button', { name: /1.*plugin.auth.authorization/ })
expect(screen.queryByRole('button', { name: 'plugin.auth.useApiAuth' })).not.toBeInTheDocument()
await user.click(trigger)
expect(await screen.findByText('Production key')).toBeVisible()
})
it('renders the caller content when the provider is authorized', async () => {
requests.credentials.mockResolvedValue(credentialInfo([credential]))
renderAuth({}, { children: <div>Custom Content</div> })
expect(await screen.findByText('Custom Content')).toBeVisible()
expect(
screen.queryByRole('button', { name: /plugin.auth.authorization$/ }),
).not.toBeInTheDocument()
})
it('disables authorization without credential.create and links to members settings', async () => {
const user = userEvent.setup()
renderAuth({ workspacePermissionKeys: ['credential.use'] })
expect(await screen.findByRole('button', { name: 'plugin.auth.useApiAuth' })).toBeDisabled()
expect(screen.getByText('plugin.auth.permissionHint.title')).toBeVisible()
expect(screen.getByText('plugin.auth.permissionHint.description')).toBeVisible()
await user.click(screen.getByRole('button', { name: 'plugin.auth.permissionHint.action' }))
await waitFor(() =>
expect(onUrlUpdate.mock.lastCall?.[0].searchParams.get('settings')).toBe('members'),
)
})
it('does not offer tool credential permissions for a datasource', () => {
renderAuth(
{ workspacePermissionKeys: ['credential.use'] },
{ pluginPayload: { ...defaultPayload, category: AuthCategory.datasource } },
)
expect(screen.queryByText('plugin.auth.permissionHint.title')).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'plugin.auth.useApiAuth' })).not.toBeInTheDocument()
expect(requests.credentials).not.toHaveBeenCalled()
})
it('disables custom credentials without a permission hint when the provider forbids them', async () => {
requests.credentials.mockResolvedValue(credentialInfo([], false))
renderAuth({ workspacePermissionKeys: ['credential.use'] })
expect(await screen.findByRole('button', { name: 'plugin.auth.useApiAuth' })).toBeDisabled()
expect(screen.queryByText('plugin.auth.permissionHint.title')).not.toBeInTheDocument()
})
@@ -0,0 +1,398 @@
import type { ReactElement } from 'react'
import type { FormSchema } from '@/app/components/base/form/types'
import { act, fireEvent, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import { AuthCategory } from '../../types'
import AddOAuthButton from '../add-oauth-button'
const mockGetPluginOAuthUrl = vi
.fn()
.mockResolvedValue({ authorization_url: 'https://auth.example.com' })
const mockOpenOAuthPopup = vi.fn()
const mockWriteText = vi.fn()
const mockSaveClient = vi.fn()
vi.mock('@/hooks/use-i18n', () => ({
useRenderI18nObject: () => (obj: Record<string, string> | string) =>
typeof obj === 'string' ? obj : obj.en_US || '',
}))
vi.mock('@/hooks/use-oauth', () => ({
openOAuthPopup: (...args: unknown[]) => mockOpenOAuthPopup(...args),
}))
vi.mock('@/service/base', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/base')>()),
request: async (url: string, _init: RequestInit, options: { request: Request }) => {
const target = new URL(url)
const path = target.pathname.replace('/console/api', '')
if (path.endsWith('/oauth/client-schema'))
return Response.json({
schema: [],
is_oauth_custom_client_enabled: false,
is_system_oauth_params_exists: true,
client_params: {},
redirect_uri: '',
})
if (options.request.method === 'POST')
return Response.json(await mockSaveClient(path, { body: await options.request.json() }))
return Response.json(
await mockGetPluginOAuthUrl(path, {
params: { visibility: target.searchParams.get('visibility') ?? undefined },
}),
)
},
}))
vi.mock('@/app/notifications', () => ({ toast: { success: vi.fn() } }))
// Give every category explicit configuration; datasource/trigger have no schema endpoint.
const renderWithAccountProfile = (element: ReactElement) => renderWithConsoleQuery(element)
const configuredOAuthData = {
schema: [],
is_oauth_custom_client_enabled: false,
is_system_oauth_params_exists: true,
client_params: {},
}
const toolAuthUrl = '/oauth/plugin/test-provider/tool/authorization-url'
const basePayload = {
category: AuthCategory.tool,
provider: 'test-provider',
}
describe('AddOAuthButton', () => {
beforeEach(() => {
vi.clearAllMocks()
mockSaveClient.mockResolvedValue({ result: 'success' })
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { writeText: mockWriteText },
})
})
it('opens real OAuth settings and dismisses without saving', async () => {
const user = userEvent.setup()
renderWithAccountProfile(<AddOAuthButton pluginPayload={basePayload} buttonText="Use OAuth" />)
await user.click(await screen.findByRole('button', { name: 'plugin.auth.oauthClientSettings' }))
const dialog = await screen.findByRole('dialog', { name: 'plugin.auth.oauthClientSettings' })
await user.click(within(dialog).getByRole('button', { name: 'common.operation.close' }))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
expect(mockSaveClient).not.toHaveBeenCalled()
})
it('should trigger OAuth flow on main button click', async () => {
const mockOnUpdate = vi.fn()
renderWithAccountProfile(
<AddOAuthButton
pluginPayload={basePayload}
buttonText="Use OAuth"
onUpdate={mockOnUpdate}
renderTrigger={({ trigger }) => <section aria-label="External owner">{trigger}</section>}
/>,
)
fireEvent.click(await screen.findByRole('button', { name: 'Use OAuth' }))
// Confirm the visibility picker to actually kick off OAuth
const confirmButton = await screen.findByText('plugin.auth.authorize')
fireEvent.click(confirmButton)
await waitFor(() => {
expect(mockOpenOAuthPopup).toHaveBeenCalledWith(
'https://auth.example.com',
expect.any(Function),
)
})
const handleOAuthSuccess = mockOpenOAuthPopup.mock.calls[0]?.[1]
act(() => handleOAuthSuccess())
expect(mockOnUpdate).toHaveBeenCalled()
})
it('should not open OAuth popup when authorization URL is missing', async () => {
const user = userEvent.setup()
mockGetPluginOAuthUrl.mockResolvedValueOnce({})
renderWithAccountProfile(<AddOAuthButton pluginPayload={basePayload} buttonText="Use OAuth" />)
await user.click(await screen.findByRole('button', { name: 'Use OAuth' }))
const dialog = await screen.findByRole('dialog', { name: 'plugin.auth.whoCanUse' })
expect(dialog).toHaveAccessibleDescription('plugin.auth.oauthCredentialPermissionDescription')
const confirmButton = within(dialog).getByRole('button', { name: 'plugin.auth.authorize' })
await user.click(confirmButton)
await waitFor(() => {
expect(mockGetPluginOAuthUrl).toHaveBeenCalled()
})
expect(mockOpenOAuthPopup).not.toHaveBeenCalled()
expect(dialog).toBeInTheDocument()
expect(confirmButton).toBeEnabled()
})
it('should lock the visibility dialog while requesting an OAuth URL', async () => {
const user = userEvent.setup()
let resolveOAuthRequest: ((value: { authorization_url: string }) => void) | undefined
mockGetPluginOAuthUrl.mockImplementationOnce(
() =>
new Promise((resolve) => {
resolveOAuthRequest = resolve
}),
)
renderWithAccountProfile(<AddOAuthButton pluginPayload={basePayload} buttonText="Use OAuth" />)
await user.click(await screen.findByRole('button', { name: 'Use OAuth' }))
const dialog = await screen.findByRole('dialog', { name: 'plugin.auth.whoCanUse' })
const confirmButton = within(dialog).getByRole('button', { name: 'plugin.auth.authorize' })
await user.click(confirmButton)
await waitFor(() => {
expect(confirmButton).toHaveAttribute('aria-disabled', 'true')
})
expect(within(dialog).getByRole('button', { name: 'common.operation.cancel' })).toBeDisabled()
expect(
within(dialog).getByRole('button', {
name: /datasetSettings\.form\.permissionsOnlyMe/,
}),
).toBeDisabled()
expect(within(dialog).getByRole('button', { name: 'common.operation.close' })).toBeDisabled()
await act(async () => {
resolveOAuthRequest?.({ authorization_url: 'https://auth.example.com' })
})
await waitFor(() => {
expect(
screen.queryByRole('dialog', { name: 'plugin.auth.whoCanUse' }),
).not.toBeInTheDocument()
})
expect(mockOpenOAuthPopup).toHaveBeenCalledWith(
'https://auth.example.com',
expect.any(Function),
)
})
it('should preserve the visibility selection when the OAuth URL request fails', async () => {
const user = userEvent.setup()
mockGetPluginOAuthUrl.mockRejectedValueOnce(new Error('OAuth URL request failed'))
renderWithAccountProfile(<AddOAuthButton pluginPayload={basePayload} buttonText="Use OAuth" />)
await user.click(await screen.findByRole('button', { name: 'Use OAuth' }))
const dialog = await screen.findByRole('dialog', { name: 'plugin.auth.whoCanUse' })
await user.click(
within(dialog).getByRole('button', {
name: /datasetSettings\.form\.permissionsOnlyMe/,
}),
)
await user.click(
screen.getByRole('menuitemradio', {
name: 'datasetSettings.form.permissionsAllMember',
}),
)
const confirmButton = within(dialog).getByRole('button', { name: 'plugin.auth.authorize' })
await user.click(confirmButton)
await waitFor(() => {
expect(confirmButton).toBeEnabled()
})
expect(mockGetPluginOAuthUrl).toHaveBeenCalledWith(toolAuthUrl, {
params: { visibility: 'all_team_members' },
})
expect(mockOpenOAuthPopup).not.toHaveBeenCalled()
expect(dialog).toBeInTheDocument()
expect(
within(dialog).getByRole('button', {
name: /datasetSettings\.form\.permissionsAllMember/,
}),
).toBeEnabled()
await user.click(confirmButton)
await waitFor(() => expect(mockOpenOAuthPopup).toHaveBeenCalledOnce())
expect(mockGetPluginOAuthUrl).toHaveBeenLastCalledWith(toolAuthUrl, {
params: { visibility: 'all_team_members' },
})
})
it('should skip visibility picker for categories without backend visibility support', async () => {
// This shared hook has no endpoint for trigger/model OAuth.
const triggerPayload = { category: AuthCategory.trigger, provider: 'test-trigger' }
renderWithAccountProfile(
<AddOAuthButton
pluginPayload={triggerPayload}
buttonText="Use OAuth"
oAuthData={configuredOAuthData}
/>,
)
fireEvent.click(await screen.findByRole('button', { name: 'Use OAuth' }))
expect(mockGetPluginOAuthUrl).not.toHaveBeenCalled()
expect(mockOpenOAuthPopup).not.toHaveBeenCalled()
// No pre-OAuth visibility modal should ever appear for unsupported categories.
expect(screen.queryByText('plugin.auth.authorize')).not.toBeInTheDocument()
})
it('should show visibility picker for datasource category (backend now supports it)', async () => {
const datasourcePayload = { category: AuthCategory.datasource, provider: 'test-datasource' }
renderWithAccountProfile(
<AddOAuthButton
pluginPayload={datasourcePayload}
buttonText="Use OAuth"
oAuthData={configuredOAuthData}
/>,
)
fireEvent.click(await screen.findByRole('button', { name: 'Use OAuth' }))
// Visibility picker appears for datasource just like it does for tool.
const confirmButton = await screen.findByText('plugin.auth.authorize')
fireEvent.click(confirmButton)
await waitFor(() => {
expect(mockGetPluginOAuthUrl).toHaveBeenCalledWith(
'/oauth/plugin/test-datasource/datasource/get-authorization-url',
{ params: { visibility: 'only_me' } },
)
})
})
it('should discard a cancelled visibility selection before the next OAuth attempt', async () => {
const user = userEvent.setup()
renderWithAccountProfile(<AddOAuthButton pluginPayload={basePayload} buttonText="Use OAuth" />)
await user.click(await screen.findByRole('button', { name: 'Use OAuth' }))
await user.click(
screen.getByRole('button', { name: /datasetSettings\.form\.permissionsOnlyMe/ }),
)
await user.click(
screen.getByRole('menuitemradio', {
name: 'datasetSettings.form.permissionsAllMember',
}),
)
await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
await user.click(await screen.findByRole('button', { name: 'Use OAuth' }))
await user.click(screen.getByRole('button', { name: 'plugin.auth.authorize' }))
await waitFor(() => {
expect(mockGetPluginOAuthUrl).toHaveBeenCalledWith(toolAuthUrl, {
params: { visibility: 'only_me' },
})
})
})
it('disables both authorization and client settings entry points', () => {
renderWithAccountProfile(
<AddOAuthButton
pluginPayload={basePayload}
buttonText="Use OAuth"
oAuthData={configuredOAuthData}
disabled
/>,
)
expect(screen.getByRole('button', { name: 'Use OAuth' })).toBeDisabled()
expect(screen.getByRole('button', { name: 'plugin.auth.oauthClientSettings' })).toBeDisabled()
})
it('should choose visibility after saving custom OAuth settings for authorization', async () => {
const user = userEvent.setup()
renderWithAccountProfile(
<AddOAuthButton
pluginPayload={basePayload}
oAuthData={{
schema: [],
is_oauth_custom_client_enabled: false,
is_system_oauth_params_exists: false,
client_params: {},
}}
/>,
)
await user.click(screen.getByText('plugin.auth.setupOAuth'))
await user.click(
within(screen.getByRole('dialog', { name: 'plugin.auth.oauthClientSettings' })).getByRole(
'button',
{
name: 'plugin.auth.saveAndAuth',
},
),
)
await screen.findByRole('dialog', { name: 'plugin.auth.whoCanUse' })
expect(mockSaveClient).toHaveBeenCalledWith(
'/workspaces/current/tool-provider/builtin/test-provider/oauth/custom-client',
{ body: { client_params: {}, enable_oauth_custom_client: true } },
)
expect(mockGetPluginOAuthUrl).not.toHaveBeenCalled()
expect(screen.getByText('plugin.auth.oauthCredentialPermissionDescription')).toBeInTheDocument()
await user.click(
screen.getByRole('button', { name: /datasetSettings\.form\.permissionsOnlyMe/ }),
)
await user.click(
screen.getByRole('menuitemradio', {
name: 'datasetSettings.form.permissionsAllMember',
}),
)
await user.click(screen.getByRole('button', { name: 'plugin.auth.authorize' }))
await waitFor(() => {
expect(mockGetPluginOAuthUrl).toHaveBeenCalledWith(toolAuthUrl, {
params: { visibility: 'all_team_members' },
})
})
})
it('edits the stored custom client and copies its redirect URL through real settings', async () => {
const user = userEvent.setup()
const writeText = vi.spyOn(navigator.clipboard, 'writeText').mockResolvedValue()
const schema = [
{
name: 'client_id',
label: { en_US: 'Client ID' },
type: 'text-input',
required: true,
default: 'schema-client-id',
},
] as FormSchema[]
renderWithAccountProfile(
<AddOAuthButton
pluginPayload={basePayload}
buttonText="Use OAuth"
oAuthData={{
schema,
is_oauth_custom_client_enabled: true,
is_system_oauth_params_exists: true,
client_params: { client_id: 'stored-client-id' },
redirect_uri: 'https://redirect.example.com',
}}
/>,
)
expect(screen.getByRole('button', { name: /Use OAuth/ })).toHaveTextContent(
'plugin.auth.custom',
)
await user.click(screen.getByRole('button', { name: 'plugin.auth.oauthClientSettings' }))
const input = screen.getByRole('textbox', { name: /Client ID/ })
expect(input).toHaveValue('stored-client-id')
expect(screen.getByRole('button', { name: 'common.operation.remove' })).toBeEnabled()
await user.click(screen.getByRole('button', { name: 'common.operation.copy' }))
expect(writeText).toHaveBeenCalledExactlyOnceWith('https://redirect.example.com')
await user.clear(input)
await user.type(input, 'updated-client-id')
await user.click(screen.getByRole('button', { name: 'plugin.auth.saveOnly' }))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
expect(mockSaveClient).toHaveBeenCalledExactlyOnceWith(
'/workspaces/current/tool-provider/builtin/test-provider/oauth/custom-client',
{
body: {
client_params: { client_id: 'updated-client-id' },
enable_oauth_custom_client: true,
},
},
)
})
})
@@ -0,0 +1,122 @@
import type { FormSchema } from '@/app/components/base/form/types'
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
import { screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import { FormTypeEnum } from '@/app/components/base/form/types'
import { renderWithAccountProfile as render } from '@/test/console/account-profile'
import { createDeferred } from '@/test/deferred'
import { AuthCategory } from '../../types'
import ApiKeyModal from '../api-key-modal'
const commands = vi.hoisted(() => ({ add: vi.fn(), update: vi.fn() }))
const schemas: FormSchema[] = [
{ name: 'api_key', label: 'API Key', type: FormTypeEnum.secretInput, required: true },
]
// Credential routing has separate hook tests; this suite owns form validation and submitted values.
vi.mock('../../hooks/use-credential', () => ({
useAddPluginCredentialHook: () => ({ mutateAsync: commands.add }),
useUpdatePluginCredentialHook: () => ({ mutateAsync: commands.update }),
useGetPluginCredentialSchemaHook: () => ({ data: schemas, isLoading: false }),
}))
const payload = { category: AuthCategory.tool, provider: 'test-provider' }
beforeEach(() => {
commands.add.mockResolvedValue({})
commands.update.mockResolvedValue({})
})
it('validates the API key and submits the entered name, secret and selected visibility', async () => {
const user = userEvent.setup()
const onClose = vi.fn()
render(<ApiKeyModal pluginPayload={payload} onClose={onClose} />)
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
expect(commands.add).not.toHaveBeenCalled()
await user.type(screen.getByLabelText(/API Key/), 'sk-123')
await user.type(screen.getByRole('textbox', { name: 'plugin.auth.authorizationName' }), 'My Key')
await user.click(screen.getByRole('button', { name: /permissionsAllMember/ }))
await user.click(
within(screen.getByRole('menu', { name: /auth.whoCanUse/ })).getByRole('menuitemradio', {
name: /permissionsOnlyMe/,
}),
)
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
await waitFor(() => expect(onClose).toHaveBeenCalledOnce())
expect(commands.add).toHaveBeenCalledExactlyOnceWith({
credentials: { api_key: 'sk-123' },
name: 'My Key',
type: 'api-key',
visibility: 'only_me',
})
})
it('uses the existing credential identity and preserves an unchanged secret on edit', async () => {
const user = userEvent.setup()
render(
<ApiKeyModal
pluginPayload={payload}
editValues={{ api_key: '[__HIDDEN__]', __credential_id__: 'cred-1', __name__: 'Existing' }}
/>,
)
const name = screen.getByRole('textbox', { name: 'plugin.auth.authorizationName' })
expect(name).toHaveValue('Existing')
await user.clear(name)
await user.type(name, 'Renamed')
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
await waitFor(() =>
expect(commands.update).toHaveBeenCalledExactlyOnceWith({
credentials: { api_key: '[__HIDDEN__]' },
credential_id: 'cred-1',
name: 'Renamed',
}),
)
expect(commands.add).not.toHaveBeenCalled()
})
it('prevents duplicate submissions while the credential command is pending', async () => {
const user = userEvent.setup()
const request = createDeferred<object>()
commands.add.mockReturnValue(request.promise)
const onClose = vi.fn()
render(<ApiKeyModal pluginPayload={payload} onClose={onClose} />)
await user.type(screen.getByLabelText(/API Key/), 'secret')
const save = screen.getByRole('button', { name: 'common.operation.save' })
await user.dblClick(save)
expect(save).toBeDisabled()
expect(commands.add).toHaveBeenCalledOnce()
expect(onClose).not.toHaveBeenCalled()
request.resolve({})
await waitFor(() => expect(onClose).toHaveBeenCalledOnce())
})
it('keeps the credentials popover open while editing inside its nested modal', async () => {
const user = userEvent.setup()
const onClose = vi.fn()
const onPopoverClose = vi.fn()
const Harness = () => {
const [open, setOpen] = useState(true)
return (
<Popover
open={open}
onOpenChange={(next) => {
setOpen(next)
if (!next) onPopoverClose()
}}
>
<PopoverTrigger render={<button>Credentials</button>} />
<PopoverContent>
<ApiKeyModal
pluginPayload={payload}
open={open}
onOpenChange={setOpen}
onClose={onClose}
/>
</PopoverContent>
</Popover>
)
}
render(<Harness />)
await user.type(await screen.findByLabelText(/API Key/), 'secret')
expect(screen.getByLabelText(/API Key/)).toHaveValue('secret')
expect(onClose).not.toHaveBeenCalled()
expect(onPopoverClose).not.toHaveBeenCalled()
})
@@ -0,0 +1,91 @@
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { FormTypeEnum } from '@/app/components/base/form/types'
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import { AuthCategory } from '../../types'
import AddApiKeyButton from '../add-api-key-button'
import AddOAuthButton from '../add-oauth-button'
const commands = vi.hoisted(() => ({
add: vi.fn(),
saveOAuth: vi.fn(),
authorize: vi.fn(),
invalidate: vi.fn(),
}))
vi.mock('../../hooks/use-credential', () => ({
useAddPluginCredentialHook: () => ({ mutateAsync: commands.add }),
useUpdatePluginCredentialHook: () => ({ mutateAsync: vi.fn() }),
useGetPluginCredentialSchemaHook: () => ({
data: [{ name: 'api_key', label: 'API Key', type: FormTypeEnum.secretInput, required: true }],
isLoading: false,
}),
useGetPluginOAuthClientSchemaHook: () => ({ data: {}, isLoading: false }),
useGetPluginOAuthUrlHook: () => ({ mutateAsync: commands.authorize, isPending: false }),
useSetPluginOAuthCustomClientHook: () => ({ mutateAsync: commands.saveOAuth }),
useDeletePluginOAuthCustomClientHook: () => ({ mutateAsync: vi.fn() }),
useInvalidPluginOAuthClientSchemaHook: () => commands.invalidate,
}))
const payload = { category: AuthCategory.tool, provider: 'test-provider' }
beforeEach(() => {
commands.add.mockResolvedValue({})
commands.saveOAuth.mockResolvedValue({})
})
it('opens an API key form and closes it after creating a credential', async () => {
const user = userEvent.setup()
const onUpdate = vi.fn()
render(<AddApiKeyButton pluginPayload={payload} onUpdate={onUpdate} />)
await user.click(screen.getByRole('button', { name: 'Use Api Key' }))
await user.type(await screen.findByLabelText(/API Key/), 'new-secret')
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
expect(commands.add).toHaveBeenCalledWith(
expect.objectContaining({ credentials: { api_key: 'new-secret' } }),
)
expect(onUpdate).toHaveBeenCalledOnce()
})
it('opens settings for an unconfigured OAuth provider and saves the entered client', async () => {
const user = userEvent.setup()
render(
<AddOAuthButton
pluginPayload={payload}
oAuthData={{
schema: [
{
name: 'client_id',
label: { en_US: 'Client ID', zh_Hans: '客户端 ID' },
type: FormTypeEnum.textInput,
required: true,
},
],
}}
/>,
)
await user.click(screen.getByRole('button', { name: /plugin.auth.setupOAuth/ }))
await user.type(await screen.findByRole('textbox', { name: /Client ID/ }), 'client-123')
await user.click(screen.getByRole('button', { name: 'plugin.auth.saveOnly' }))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
expect(commands.saveOAuth).toHaveBeenCalledWith({
client_params: { client_id: 'client-123' },
enable_oauth_custom_client: true,
})
expect(commands.authorize).not.toHaveBeenCalled()
})
it('keeps a disabled API key action closed and allows cancellation once enabled', async () => {
const user = userEvent.setup()
const { rerender } = render(
<AddApiKeyButton pluginPayload={payload} buttonText="Add key" disabled />,
)
const button = screen.getByRole('button', { name: 'Add key' })
expect(button).toBeDisabled()
await user.click(button)
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
rerender(<AddApiKeyButton pluginPayload={payload} buttonText="Add key" />)
await user.click(button)
expect(await screen.findByRole('dialog')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
expect(commands.add).not.toHaveBeenCalled()
})
@@ -0,0 +1,128 @@
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import { AuthCategory } from '../../types'
import Authorize from '../index'
const requests = vi.hoisted(() => ({ authorize: vi.fn(), popup: vi.fn() }))
vi.mock('@/service/base', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/base')>()),
request: async (url: string) => {
const target = new URL(url)
const path = target.pathname.replace('/console/api', '')
if (path.endsWith('/oauth/client-schema'))
return Response.json({
schema: [],
is_system_oauth_params_exists: true,
is_oauth_custom_client_enabled: false,
redirect_uri: '',
})
return Response.json(
await requests.authorize(path, {
params: { visibility: target.searchParams.get('visibility') ?? undefined },
}),
)
},
}))
vi.mock('@/hooks/use-oauth', () => ({ openOAuthPopup: requests.popup }))
const pluginPayload = { category: AuthCategory.tool, provider: 'test-provider' }
const permissions = ['credential.use', 'credential.create', 'credential.manage']
beforeEach(() =>
requests.authorize.mockResolvedValue({ authorization_url: 'https://auth.example.test' }),
)
it.each([
[false, false, null, null],
[true, false, 'plugin.auth.useOAuthAuth', null],
[false, true, null, 'plugin.auth.useApiAuth'],
[true, true, 'plugin.auth.addOAuth', 'plugin.auth.addApi'],
] as const)(
'exposes the supported authorization methods (OAuth=%s, API key=%s)',
async (canOAuth, canApiKey, oauthLabel, apiLabel) => {
render(<Authorize pluginPayload={pluginPayload} canOAuth={canOAuth} canApiKey={canApiKey} />, {
workspacePermissionKeys: permissions,
})
if (oauthLabel) expect(await screen.findByRole('button', { name: oauthLabel })).toBeEnabled()
else
expect(
screen.queryByRole('button', { name: /plugin.auth.(useOAuthAuth|addOAuth|setupOAuth)/ }),
).not.toBeInTheDocument()
if (apiLabel) expect(screen.getByRole('button', { name: apiLabel })).toBeEnabled()
else
expect(
screen.queryByRole('button', { name: /plugin.auth.(useApiAuth|addApi)/ }),
).not.toBeInTheDocument()
},
)
it.each([
[false, false],
[true, true],
[false, true],
])(
'blocks authorization when credential.create=%s and unavailable=%s',
async (canCreate, unavailable) => {
const user = userEvent.setup()
const onApiKeyClick = vi.fn()
render(
<Authorize
pluginPayload={pluginPayload}
canOAuth
canApiKey
notAllowCustomCredential={unavailable}
onApiKeyClick={onApiKeyClick}
/>,
{
workspacePermissionKeys: canCreate ? permissions : ['credential.use'],
},
)
const oauth = await screen.findByRole('button', { name: 'plugin.auth.addOAuth' })
const api = screen.getByRole('button', { name: 'plugin.auth.addApi' })
expect(oauth).toBeDisabled()
expect(api).toBeDisabled()
expect(screen.getByRole('button', { name: 'plugin.auth.oauthClientSettings' })).toBeDisabled()
await user.click(oauth)
await user.click(api)
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
expect(onApiKeyClick).not.toHaveBeenCalled()
expect(requests.authorize).not.toHaveBeenCalled()
},
)
it('delegates API key opening to its parent once credentials become available', async () => {
const user = userEvent.setup()
const onApiKeyClick = vi.fn()
const { rerender } = render(
<Authorize
pluginPayload={pluginPayload}
canApiKey
notAllowCustomCredential
onApiKeyClick={onApiKeyClick}
/>,
{ workspacePermissionKeys: permissions },
)
expect(screen.getByRole('button', { name: 'plugin.auth.useApiAuth' })).toBeDisabled()
rerender(<Authorize pluginPayload={pluginPayload} canApiKey onApiKeyClick={onApiKeyClick} />)
await user.click(screen.getByRole('button', { name: 'plugin.auth.useApiAuth' }))
expect(onApiKeyClick).toHaveBeenCalledOnce()
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
it('passes the selected provider and visibility through authorization and reports completion', async () => {
const user = userEvent.setup()
const onUpdate = vi.fn()
render(<Authorize pluginPayload={pluginPayload} canOAuth onUpdate={onUpdate} />, {
workspacePermissionKeys: permissions,
})
await user.click(await screen.findByRole('button', { name: 'plugin.auth.useOAuthAuth' }))
await user.click(screen.getByRole('button', { name: 'plugin.auth.authorize' }))
await waitFor(() => expect(requests.popup).toHaveBeenCalledOnce())
expect(requests.authorize).toHaveBeenCalledExactlyOnceWith(
'/oauth/plugin/test-provider/tool/authorization-url',
{ params: { visibility: 'only_me' } },
)
expect(onUpdate).not.toHaveBeenCalled()
requests.popup.mock.calls[0]![1]()
expect(onUpdate).toHaveBeenCalledOnce()
})
@@ -0,0 +1,119 @@
import type { FormSchema } from '@/app/components/base/form/types'
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import { FormTypeEnum } from '@/app/components/base/form/types'
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import { createDeferred } from '@/test/deferred'
import { AuthCategory } from '../../types'
import OAuthClientSettings from '../oauth-client-settings'
const commands = vi.hoisted(() => ({ save: vi.fn(), remove: vi.fn(), invalidate: vi.fn() }))
vi.mock('../../hooks/use-credential', () => ({
useSetPluginOAuthCustomClientHook: () => ({ mutateAsync: commands.save }),
useDeletePluginOAuthCustomClientHook: () => ({ mutateAsync: commands.remove }),
useInvalidPluginOAuthClientSchemaHook: () => commands.invalidate,
}))
vi.mock('@/app/notifications', () => ({ toast: { success: vi.fn() } }))
const payload = { category: AuthCategory.tool, provider: 'test-provider' }
const schemas: FormSchema[] = [
{
name: '__oauth_client__',
label: 'Client type',
type: FormTypeEnum.textInput,
default: 'custom',
required: true,
},
{ name: 'client_id', label: 'Client ID', type: FormTypeEnum.textInput, required: true },
]
beforeEach(() => {
commands.save.mockResolvedValue({})
commands.remove.mockResolvedValue({})
})
it('validates client fields and requests authorization only after a successful save', async () => {
const user = userEvent.setup()
const authorize = vi.fn()
const onClose = vi.fn()
render(
<OAuthClientSettings
pluginPayload={payload}
schemas={schemas}
onRequestAuthorization={authorize}
onClose={onClose}
/>,
)
await user.click(screen.getByRole('button', { name: 'plugin.auth.saveAndAuth' }))
expect(commands.save).not.toHaveBeenCalled()
await user.type(screen.getByRole('textbox', { name: /Client ID/ }), 'new-client')
commands.save.mockRejectedValueOnce(new Error('Save failed'))
await user.click(screen.getByRole('button', { name: 'plugin.auth.saveAndAuth' }))
await waitFor(() => expect(commands.save).toHaveBeenCalledOnce())
expect(authorize).not.toHaveBeenCalled()
expect(onClose).not.toHaveBeenCalled()
await user.click(screen.getByRole('button', { name: 'plugin.auth.saveAndAuth' }))
await waitFor(() => expect(authorize).toHaveBeenCalledOnce())
expect(commands.save).toHaveBeenLastCalledWith({
client_params: { client_id: 'new-client' },
enable_oauth_custom_client: true,
})
expect(commands.invalidate).toHaveBeenCalledOnce()
})
it('prevents duplicate saves and supports removing the existing custom client', async () => {
const user = userEvent.setup()
const request = createDeferred<object>()
commands.save.mockReturnValue(request.promise)
const onUpdate = vi.fn()
render(
<OAuthClientSettings
pluginPayload={payload}
schemas={schemas}
editValues={{ __oauth_client__: 'custom', client_id: 'saved-id' }}
hasOriginalClientParams
onUpdate={onUpdate}
/>,
)
await user.dblClick(screen.getByRole('button', { name: 'plugin.auth.saveOnly' }))
expect(commands.save).toHaveBeenCalledOnce()
expect(screen.getByRole('button', { name: 'common.operation.remove' })).toBeDisabled()
request.resolve({})
await waitFor(() => expect(onUpdate).toHaveBeenCalledOnce())
await user.click(screen.getByRole('button', { name: 'common.operation.remove' }))
await waitFor(() => expect(commands.remove).toHaveBeenCalledOnce())
expect(onUpdate).toHaveBeenCalledTimes(2)
})
it('keeps the source popover open when typing in the OAuth settings dialog', async () => {
const user = userEvent.setup()
const onClose = vi.fn()
const onPopoverClose = vi.fn()
const Harness = () => {
const [open, setOpen] = useState(true)
return (
<Popover
open={open}
onOpenChange={(next) => {
setOpen(next)
if (!next) onPopoverClose()
}}
>
<PopoverTrigger render={<button>OAuth</button>} />
<PopoverContent>
<OAuthClientSettings
open={open}
onOpenChange={setOpen}
pluginPayload={payload}
schemas={schemas}
onClose={onClose}
/>
</PopoverContent>
</Popover>
)
}
render(<Harness />)
await user.type(await screen.findByRole('textbox', { name: /Client ID/ }), 'new-client')
expect(onClose).not.toHaveBeenCalled()
expect(onPopoverClose).not.toHaveBeenCalled()
})
@@ -0,0 +1,63 @@
import type { ButtonProps } from '@langgenius/dify-ui/button'
import type { PluginPayload } from '../types'
import type { FormSchema } from '@/app/components/base/form/types'
import { Button } from '@langgenius/dify-ui/button'
import { memo, useState } from 'react'
import ApiKeyModal from './api-key-modal'
export type AddApiKeyButtonProps = {
pluginPayload: PluginPayload
buttonVariant?: ButtonProps['variant']
buttonText?: string
disabled?: boolean
onUpdate?: () => void
formSchemas?: FormSchema[]
/**
* If provided, clicking the button calls this callback instead of mounting
* the modal inline. Use this when the button lives inside a Popover that
* would unmount the modal on outside-click; the parent should render the
* ApiKeyModal at a level above the Popover.
*/
onClick?: () => void
}
const AddApiKeyButton = ({
pluginPayload,
buttonVariant = 'secondary-accent',
buttonText = 'Use Api Key',
disabled,
onUpdate,
formSchemas = [],
onClick,
}: AddApiKeyButtonProps) => {
const [isApiKeyModalOpen, setIsApiKeyModalOpen] = useState(false)
const [isApiKeyModalMounted, setIsApiKeyModalMounted] = useState(false)
const handleClick =
onClick ??
(() => {
setIsApiKeyModalMounted(true)
setIsApiKeyModalOpen(true)
})
return (
<>
<Button className="w-full" variant={buttonVariant} onClick={handleClick} disabled={disabled}>
{buttonText}
</Button>
{
// Only mount the modal here when in uncontrolled mode (no onClick prop).
!onClick && isApiKeyModalMounted && (
<ApiKeyModal
open={isApiKeyModalOpen}
onOpenChange={setIsApiKeyModalOpen}
pluginPayload={pluginPayload}
onClose={() => setIsApiKeyModalOpen(false)}
onUpdate={onUpdate}
formSchemas={formSchemas}
/>
)
}
</>
)
}
export default memo(AddApiKeyButton)
@@ -0,0 +1,331 @@
import type { ButtonProps } from '@langgenius/dify-ui/button'
import type { PluginPayload } from '../types'
import type { FormSchema } from '@/app/components/base/form/types'
import type { CredentialPermission } from '@/models/permission'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { memo, useCallback, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Badge from '@/app/components/base/badge'
import { FormTypeEnum } from '@/app/components/base/form/types'
import { useRenderI18nObject } from '@/hooks/use-i18n'
import { openOAuthPopup } from '@/hooks/use-oauth'
import { PermissionLevel } from '@/models/permission'
import {
useGetPluginOAuthClientSchemaHook,
useGetPluginOAuthUrlHook,
} from '../hooks/use-credential'
import { AuthCategory } from '../types'
import OAuthClientSettings from './oauth-client-settings'
import OAuthVisibilityDialog from './oauth-visibility-dialog'
export type AddOAuthButtonProps = {
pluginPayload: PluginPayload
buttonVariant?: NonNullable<ButtonProps['variant']>
buttonText?: string
className?: string
buttonLeftClassName?: string
buttonRightClassName?: string
dividerClassName?: string
disabled?: boolean
onUpdate?: () => void
renderTrigger?: (props: {
disabled?: boolean
isConfigured: boolean
onClick: () => void
trigger: React.ReactNode
}) => React.ReactNode
oAuthData?: {
schema?: FormSchema[]
is_oauth_custom_client_enabled?: boolean
is_system_oauth_params_exists?: boolean
client_params?: Record<string, unknown>
redirect_uri?: string
}
}
type OAuthData = NonNullable<AddOAuthButtonProps['oAuthData']>
const AddOAuthButton = ({
pluginPayload,
buttonVariant = 'primary',
buttonText = 'use oauth',
className,
buttonLeftClassName,
buttonRightClassName,
dividerClassName,
disabled,
onUpdate,
renderTrigger,
oAuthData,
}: AddOAuthButtonProps) => {
const { t } = useTranslation(['common', 'plugin'])
const renderI18nObject = useRenderI18nObject()
const [isOAuthSettingsOpen, setIsOAuthSettingsOpen] = useState(false)
const [isOAuthSettingsMounted, setIsOAuthSettingsMounted] = useState(false)
// Only expose the picker where the OAuth callback persists the selection.
const isVisibilityPickerSupported =
pluginPayload.category === AuthCategory.tool ||
pluginPayload.category === AuthCategory.datasource
const [isVisibilityModalOpen, setIsVisibilityModalOpen] = useState(false)
const [pendingVisibility, setPendingVisibility] = useState<CredentialPermission>(
PermissionLevel.onlyMe,
)
const { mutateAsync: getPluginOAuthUrl, isPending: isGettingOAuthUrl } =
useGetPluginOAuthUrlHook(pluginPayload)
const { data, isLoading } = useGetPluginOAuthClientSchemaHook(pluginPayload, !oAuthData)
const mergedOAuthData = useMemo<OAuthData>(() => {
if (oAuthData) return oAuthData
return data || {}
}, [oAuthData, data])
const {
schema = [],
is_oauth_custom_client_enabled = false,
is_system_oauth_params_exists = false,
client_params = {},
redirect_uri,
} = mergedOAuthData
const isConfigured = is_system_oauth_params_exists || is_oauth_custom_client_enabled
const openOAuthSettings = useCallback(() => {
setIsOAuthSettingsMounted(true)
setIsOAuthSettingsOpen(true)
}, [])
const handleOAuth = useCallback(async () => {
try {
const { authorization_url } = await getPluginOAuthUrl(
isVisibilityPickerSupported ? { visibility: pendingVisibility } : undefined,
)
if (!authorization_url) return false
openOAuthPopup(authorization_url, () => onUpdate?.())
return true
} catch {
// The request layer surfaces the error. Keep the current UI state so the
// user can retry without losing their visibility selection.
return false
}
}, [getPluginOAuthUrl, onUpdate, pendingVisibility, isVisibilityPickerSupported])
// Providers without a usable OAuth client first open settings. Once those
// settings are saved, authorization continues through the same visibility
// dialog used by configured providers.
const openVisibilityModal = useCallback(() => {
if (!isVisibilityPickerSupported) {
if (isConfigured) void handleOAuth()
else openOAuthSettings()
return
}
if (isConfigured) {
setPendingVisibility(PermissionLevel.onlyMe)
setIsVisibilityModalOpen(true)
} else {
openOAuthSettings()
}
}, [isConfigured, isVisibilityPickerSupported, openOAuthSettings, handleOAuth])
const handleAuthorizationRequest = useCallback(async () => {
if (!isVisibilityPickerSupported) {
await handleOAuth()
return
}
setPendingVisibility(PermissionLevel.onlyMe)
setIsVisibilityModalOpen(true)
}, [handleOAuth, isVisibilityPickerSupported])
const handleVisibilityConfirm = useCallback(async () => {
const didOpenOAuthPopup = await handleOAuth()
if (didOpenOAuthPopup) setIsVisibilityModalOpen(false)
}, [handleOAuth])
const renderCustomLabel = useCallback(
(item: FormSchema) => {
return (
<div className="w-full">
<div className="mb-4 flex rounded-xl bg-background-section-burn p-4">
<div className="mr-3 flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border-[0.5px] border-components-card-border bg-components-card-bg shadow-lg">
<span className="i-ri-information-2-fill size-5 text-text-accent" />
</div>
<div className="w-0 grow">
<div className="mb-1.5 system-sm-regular">
{t(($) => $['auth.clientInfo'], { ns: 'plugin' })}
</div>
{redirect_uri && (
<div className="flex w-full py-0.5 system-sm-medium">
<div className="w-0 grow wrap-break-word break-all">{redirect_uri}</div>
<IconButton
aria-label={t(($) => $['operation.copy'], { ns: 'common' })}
className="shrink-0"
onClick={() => {
navigator.clipboard.writeText(redirect_uri || '')
}}
>
<span aria-hidden className="i-ri-clipboard-line size-4" />
</IconButton>
</div>
)}
</div>
</div>
<div className="flex h-6 items-center system-sm-medium text-text-secondary">
{renderI18nObject(item.label as Record<string, string>)}
{item.required && <span className="ml-1 text-text-destructive-secondary">*</span>}
</div>
</div>
)
},
[t, redirect_uri, renderI18nObject],
)
const memorizedSchemas = useMemo(() => {
const result: FormSchema[] = schema.map((item, index) => {
return {
...item,
label: index === 0 ? renderCustomLabel(item) : item.label,
labelClassName: index === 0 ? 'h-auto' : undefined,
}
})
if (is_system_oauth_params_exists) {
result.unshift({
name: '__oauth_client__',
label: t(($) => $['auth.oauthClient'], { ns: 'plugin' }),
type: FormTypeEnum.radio,
options: [
{
label: t(($) => $['auth.default'], { ns: 'plugin' }),
value: 'default',
},
{
label: t(($) => $['auth.custom'], { ns: 'plugin' }),
value: 'custom',
},
],
required: false,
default: is_oauth_custom_client_enabled ? 'custom' : 'default',
} as FormSchema)
result.forEach((item, index) => {
if (index > 0) {
item.show_on = [
{
variable: '__oauth_client__',
value: 'custom',
},
]
if (client_params) item.default = client_params[item.name] || item.default
}
})
}
return result
}, [
schema,
renderCustomLabel,
t,
is_system_oauth_params_exists,
is_oauth_custom_client_enabled,
client_params,
])
const __auth_client__ = useMemo(() => {
if (isConfigured) {
if (is_oauth_custom_client_enabled) return 'custom'
return 'default'
} else {
if (is_system_oauth_params_exists) return 'default'
return 'custom'
}
}, [isConfigured, is_oauth_custom_client_enabled, is_system_oauth_params_exists])
const trigger = isConfigured ? (
<div className={cn('flex w-full', className)}>
<Button
variant={buttonVariant}
className={cn(
'h-8 min-w-0 flex-1 rounded-r-none p-0 hover:bg-components-button-primary-bg-hover',
buttonLeftClassName,
)}
disabled={disabled}
onClick={openVisibilityModal}
>
<div className="truncate">{buttonText}</div>
{is_oauth_custom_client_enabled && (
<Badge
className={cn(
'mr-0.5',
buttonVariant === 'primary' &&
'border-text-primary-on-surface bg-components-badge-bg-dimm text-text-primary-on-surface',
)}
>
{t(($) => $['auth.custom'], { ns: 'plugin' })}
</Badge>
)}
</Button>
<div
className={cn(
'h-4 w-px shrink-0 self-center bg-text-primary-on-surface opacity-[0.15]',
dividerClassName,
)}
></div>
<IconButton
variant={buttonVariant}
aria-label={t(($) => $['auth.oauthClientSettings'], { ns: 'plugin' })}
size="lg"
className={cn(
'shrink-0 rounded-l-none hover:bg-components-button-primary-bg-hover',
buttonRightClassName,
)}
disabled={disabled}
onClick={openOAuthSettings}
>
<span className="i-ri-equalizer-2-line size-4" aria-hidden="true" />
</IconButton>
</div>
) : (
<Button
variant={buttonVariant}
onClick={openVisibilityModal}
disabled={disabled}
className="w-full"
>
<span className="i-ri-equalizer-2-line size-4" />
{t(($) => $['auth.setupOAuth'], { ns: 'plugin' })}
</Button>
)
return (
<>
{renderTrigger
? renderTrigger({
disabled,
isConfigured,
onClick: openVisibilityModal,
trigger,
})
: trigger}
{isOAuthSettingsMounted && (
<OAuthClientSettings
open={isOAuthSettingsOpen}
onOpenChange={setIsOAuthSettingsOpen}
pluginPayload={pluginPayload}
onClose={() => setIsOAuthSettingsOpen(false)}
disabled={disabled || isLoading}
schemas={memorizedSchemas}
onRequestAuthorization={handleAuthorizationRequest}
editValues={{
...client_params,
__oauth_client__: __auth_client__,
}}
hasOriginalClientParams={Object.keys(client_params || {}).length > 0}
onUpdate={onUpdate}
/>
)}
<OAuthVisibilityDialog
open={isVisibilityModalOpen}
onOpenChange={setIsVisibilityModalOpen}
permission={pendingVisibility}
onPermissionChange={setPendingVisibility}
onConfirm={handleVisibilityConfirm}
loading={isGettingOAuthUrl}
/>
</>
)
}
export default memo(AddOAuthButton)
@@ -0,0 +1,218 @@
import type { PluginPayload } from '../types'
import type { FormRefObject, FormSchema } from '@/app/components/base/form/types'
import type { CredentialPermission } from '@/models/permission'
import { Button } from '@langgenius/dify-ui/button'
import {
Dialog,
DialogBody,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogHeaderCloseButton,
DialogTitle,
} from '@langgenius/dify-ui/dialog'
import { memo, useCallback, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { EncryptedBottom } from '@/app/components/base/encrypted-bottom'
import AuthForm from '@/app/components/base/form/form-scenarios/auth'
import { FormTypeEnum } from '@/app/components/base/form/types'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import { PermissionLevel } from '@/models/permission'
import { ReadmeEntrance } from '../../readme-panel/entrance'
import {
useAddPluginCredentialHook,
useGetPluginCredentialSchemaHook,
useUpdatePluginCredentialHook,
} from '../hooks/use-credential'
import { CredentialTypeEnum } from '../types'
import PermissionSelector from './permission-selector'
type ApiKeyModalProps = {
pluginPayload: PluginPayload
open?: boolean
onOpenChange?: (open: boolean) => void
onClose?: () => void
editValues?: Record<string, unknown>
onRemove?: () => void
disabled?: boolean
onUpdate?: () => void
formSchemas?: FormSchema[]
}
const ApiKeyModal = ({
pluginPayload,
open = true,
onOpenChange,
onClose,
editValues,
onRemove,
disabled,
onUpdate,
formSchemas: formSchemasFromProps = [],
}: ApiKeyModalProps) => {
const { t } = useTranslation(['common', 'plugin'])
const [doingAction, setDoingAction] = useState(false)
const doingActionRef = useRef(doingAction)
const handleSetDoingAction = useCallback((value: boolean) => {
doingActionRef.current = value
setDoingAction(value)
}, [])
const { data = [], isLoading } = useGetPluginCredentialSchemaHook(
pluginPayload,
CredentialTypeEnum.API_KEY,
)
const [permission, setPermission] = useState<CredentialPermission>(
editValues?.__visibility__ === PermissionLevel.onlyMe
? PermissionLevel.onlyMe
: PermissionLevel.allTeamMembers,
)
const mergedData = useMemo(() => {
if (formSchemasFromProps?.length) return formSchemasFromProps
return data
}, [formSchemasFromProps, data])
const formSchemas = useMemo(() => {
return [
{
type: FormTypeEnum.textInput,
name: '__name__',
label: t(($) => $['auth.authorizationName'], { ns: 'plugin' }),
required: false,
},
...mergedData,
]
}, [mergedData, t])
const defaultValues = formSchemas.reduce(
(acc, schema) => {
if (schema.default) acc[schema.name] = schema.default
return acc
},
{} as Record<string, unknown>,
)
const { mutateAsync: addPluginCredential } = useAddPluginCredentialHook(pluginPayload)
const { mutateAsync: updatePluginCredential } = useUpdatePluginCredentialHook(pluginPayload)
const formRef = useRef<FormRefObject>(null)
const handleConfirm = useCallback(async () => {
if (doingActionRef.current) return
const { isCheckValidated, values } = formRef.current?.getFormValues({
needCheckValidatedValues: true,
needTransformWhenSecretFieldIsPristine: true,
}) || { isCheckValidated: false, values: {} }
if (!isCheckValidated) return
try {
const {
__name__,
__credential_id__,
__visibility__,
__partial_member_list__,
__created_by__,
...restValues
} = values
handleSetDoingAction(true)
// Visibility is settable only at creation. On edit we don't send it.
if (editValues) {
await updatePluginCredential({
credentials: restValues,
credential_id: __credential_id__,
name: __name__ || '',
})
} else {
await addPluginCredential({
credentials: restValues,
type: CredentialTypeEnum.API_KEY,
name: __name__ || '',
visibility: permission,
})
}
onOpenChange?.(false)
onClose?.()
onUpdate?.()
} finally {
handleSetDoingAction(false)
}
}, [
addPluginCredential,
onClose,
onOpenChange,
onUpdate,
updatePluginCredential,
editValues,
handleSetDoingAction,
permission,
])
const isDisabled = disabled || isLoading || doingAction
const handleOpenChange = useCallback(
(nextOpen: boolean) => {
onOpenChange?.(nextOpen)
if (!nextOpen) onClose?.()
},
[onClose, onOpenChange],
)
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent backdropProps={{ forceRender: true }} className="w-160">
<DialogHeader>
<DialogTitle>{t(($) => $['auth.useApiAuth'], { ns: 'plugin' })}</DialogTitle>
<DialogDescription>
{t(($) => $['auth.useApiAuthDesc'], { ns: 'plugin' })}
</DialogDescription>
<DialogHeaderCloseButton aria-label={t(($) => $['operation.close'], { ns: 'common' })} />
</DialogHeader>
<DialogBody>
{pluginPayload.detail && (
<ReadmeEntrance pluginDetail={pluginPayload.detail} presentation="dialog" />
)}
{isLoading && (
<div className="flex h-40 items-center justify-center">
<LoadingPlaceholder />
</div>
)}
{!isLoading && !!mergedData.length && (
<AuthForm
ref={formRef}
formSchemas={formSchemas}
defaultValues={editValues || defaultValues}
disabled={disabled}
/>
)}
{!isLoading && !editValues && (
<div className="mt-4 px-1">
<div className="mb-1 system-sm-semibold text-text-secondary">
{t(($) => $['auth.whoCanUse'], { ns: 'plugin' })}
</div>
<PermissionSelector
disabled={disabled}
permission={permission}
onChange={setPermission}
/>
</div>
)}
</DialogBody>
<DialogFooter>
{editValues && (
<>
<Button variant="primary" onClick={onRemove} disabled={isDisabled}>
{t(($) => $['operation.remove'], { ns: 'common' })}
</Button>
<div className="mx-1 h-4 w-px bg-divider-regular"></div>
</>
)}
<Button onClick={() => handleOpenChange(false)} disabled={isDisabled}>
{t(($) => $['operation.cancel'], { ns: 'common' })}
</Button>
<Button variant="primary" onClick={handleConfirm} disabled={isDisabled}>
{t(($) => $['operation.save'], { ns: 'common' })}
</Button>
</DialogFooter>
<EncryptedBottom />
</DialogContent>
</Dialog>
)
}
export default memo(ApiKeyModal)
@@ -0,0 +1,150 @@
import type { PluginPayload } from '../types'
import type { AddApiKeyButtonProps } from './add-api-key-button'
import type { AddOAuthButtonProps } from './add-oauth-button'
import { cn } from '@langgenius/dify-ui/cn'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
import { memo, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { useCredentialPermissions } from '@/hooks/use-credential-permissions'
import AddApiKeyButton from './add-api-key-button'
import AddOAuthButton from './add-oauth-button'
type AuthorizeProps = {
pluginPayload: PluginPayload
theme?: 'primary' | 'secondary'
showDivider?: boolean
canOAuth?: boolean
canApiKey?: boolean
onUpdate?: () => void
notAllowCustomCredential?: boolean
/**
* If provided, the API-key button delegates modal-opening to the parent
* instead of rendering it inline. Used when this Authorize is mounted
* inside a Popover whose outside-click handler would otherwise unmount
* the modal.
*/
onApiKeyClick?: () => void
}
const Authorize = ({
pluginPayload,
theme = 'primary',
showDivider = true,
canOAuth,
canApiKey,
onUpdate,
notAllowCustomCredential,
onApiKeyClick,
}: AuthorizeProps) => {
const { t } = useTranslation(['plugin'])
const { canCreateCredential } = useCredentialPermissions()
const oAuthButtonProps: AddOAuthButtonProps = useMemo(() => {
if (theme === 'secondary') {
return {
buttonText: !canApiKey
? t(($) => $['auth.useOAuthAuth'], { ns: 'plugin' })
: t(($) => $['auth.addOAuth'], { ns: 'plugin' }),
buttonVariant: 'secondary',
className: 'hover:bg-components-button-secondary-bg',
buttonLeftClassName: 'hover:bg-components-button-secondary-bg-hover',
buttonRightClassName: 'hover:bg-components-button-secondary-bg-hover',
dividerClassName: 'bg-divider-regular opacity-100',
pluginPayload,
}
}
return {
buttonText: !canApiKey
? t(($) => $['auth.useOAuthAuth'], { ns: 'plugin' })
: t(($) => $['auth.addOAuth'], { ns: 'plugin' }),
pluginPayload,
}
}, [canApiKey, theme, pluginPayload, t])
const apiKeyButtonProps: AddApiKeyButtonProps = useMemo(() => {
if (theme === 'secondary') {
return {
pluginPayload,
buttonVariant: 'secondary',
buttonText: !canOAuth
? t(($) => $['auth.useApiAuth'], { ns: 'plugin' })
: t(($) => $['auth.addApi'], { ns: 'plugin' }),
onClick: onApiKeyClick,
}
}
return {
pluginPayload,
buttonText: !canOAuth
? t(($) => $['auth.useApiAuth'], { ns: 'plugin' })
: t(($) => $['auth.addApi'], { ns: 'plugin' }),
buttonVariant: !canOAuth ? 'primary' : 'secondary-accent',
onClick: onApiKeyClick,
}
}, [canOAuth, theme, pluginPayload, t, onApiKeyClick])
const OAuthButton = useMemo(() => {
const Item = (
<div className={cn('min-w-0 flex-1', notAllowCustomCredential && 'opacity-50')}>
<AddOAuthButton
{...oAuthButtonProps}
disabled={!canCreateCredential || notAllowCustomCredential}
onUpdate={onUpdate}
/>
</div>
)
if (notAllowCustomCredential) {
return (
<Tooltip>
<TooltipTrigger render={Item} />
<TooltipContent>
{t(($) => $['auth.credentialUnavailable'], { ns: 'plugin' })}
</TooltipContent>
</Tooltip>
)
}
return Item
}, [notAllowCustomCredential, oAuthButtonProps, canCreateCredential, onUpdate, t])
const ApiKeyButton = useMemo(() => {
const Item = (
<div className={cn('min-w-0 flex-1', notAllowCustomCredential && 'opacity-50')}>
<AddApiKeyButton
{...apiKeyButtonProps}
disabled={!canCreateCredential || notAllowCustomCredential}
onUpdate={onUpdate}
/>
</div>
)
if (notAllowCustomCredential) {
return (
<Tooltip>
<TooltipTrigger render={Item} />
<TooltipContent>
{t(($) => $['auth.credentialUnavailable'], { ns: 'plugin' })}
</TooltipContent>
</Tooltip>
)
}
return Item
}, [notAllowCustomCredential, apiKeyButtonProps, canCreateCredential, onUpdate, t])
return (
<>
<div className="flex items-center space-x-1.5">
{canOAuth && OAuthButton}
{showDivider && canOAuth && canApiKey && (
<div className="flex shrink-0 flex-col items-center justify-between system-2xs-medium-uppercase text-text-tertiary">
<div className="h-2 w-px bg-divider-subtle"></div>
or
<div className="h-2 w-px bg-divider-subtle"></div>
</div>
)}
{canApiKey && ApiKeyButton}
</div>
</>
)
}
export default memo(Authorize)
@@ -0,0 +1,196 @@
import type { PluginPayload } from '../types'
import type { FormRefObject, FormSchema } from '@/app/components/base/form/types'
import { Button } from '@langgenius/dify-ui/button'
import {
Dialog,
DialogBody,
DialogContent,
DialogFooter,
DialogHeader,
DialogHeaderCloseButton,
DialogTitle,
} from '@langgenius/dify-ui/dialog'
import { useForm, useSelector } from '@tanstack/react-form'
import { memo, useCallback, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import AuthForm from '@/app/components/base/form/form-scenarios/auth'
import { toast } from '@/app/notifications'
import { ReadmeEntrance } from '../../readme-panel/entrance'
import {
useDeletePluginOAuthCustomClientHook,
useInvalidPluginOAuthClientSchemaHook,
useSetPluginOAuthCustomClientHook,
} from '../hooks/use-credential'
type OAuthClientSettingsProps = {
pluginPayload: PluginPayload
open?: boolean
onOpenChange?: (open: boolean) => void
onClose?: () => void
editValues?: Record<string, unknown>
disabled?: boolean
schemas: FormSchema[]
onRequestAuthorization?: () => Promise<void> | void
hasOriginalClientParams?: boolean
onUpdate?: () => void
}
const OAuthClientSettings = ({
pluginPayload,
open = true,
onOpenChange,
onClose,
editValues,
disabled,
schemas,
onRequestAuthorization,
hasOriginalClientParams,
onUpdate,
}: OAuthClientSettingsProps) => {
const { t } = useTranslation(['common', 'plugin'])
const [doingAction, setDoingAction] = useState(false)
const doingActionRef = useRef(doingAction)
const handleSetDoingAction = useCallback((value: boolean) => {
doingActionRef.current = value
setDoingAction(value)
}, [])
const handleOpenChange = useCallback(
(nextOpen: boolean) => {
onOpenChange?.(nextOpen)
if (!nextOpen) onClose?.()
},
[onClose, onOpenChange],
)
const defaultValues = schemas.reduce(
(acc, schema) => {
if (schema.default) acc[schema.name] = schema.default
return acc
},
{} as Record<string, unknown>,
)
const { mutateAsync: setPluginOAuthCustomClient } =
useSetPluginOAuthCustomClientHook(pluginPayload)
const invalidPluginOAuthClientSchema = useInvalidPluginOAuthClientSchemaHook(pluginPayload)
const formRef = useRef<FormRefObject>(null)
const handleConfirm = useCallback(async () => {
if (doingActionRef.current) return false
try {
const { isCheckValidated, values } = formRef.current?.getFormValues({
needCheckValidatedValues: true,
needTransformWhenSecretFieldIsPristine: true,
}) || { isCheckValidated: false, values: {} }
if (!isCheckValidated) throw new Error('error')
const { __oauth_client__, ...restValues } = values
handleSetDoingAction(true)
await setPluginOAuthCustomClient({
client_params: restValues,
enable_oauth_custom_client: __oauth_client__ === 'custom',
})
toast.success(t(($) => $['api.actionSuccess'], { ns: 'common' }))
onOpenChange?.(false)
onClose?.()
onUpdate?.()
invalidPluginOAuthClientSchema()
return true
} finally {
handleSetDoingAction(false)
}
}, [
onClose,
onOpenChange,
onUpdate,
invalidPluginOAuthClientSchema,
setPluginOAuthCustomClient,
t,
handleSetDoingAction,
])
const handleConfirmAndAuthorize = useCallback(async () => {
try {
const isSaved = await handleConfirm()
if (isSaved) await onRequestAuthorization?.()
} catch {
// The request layer reports the save error. Keep settings open and stop
// before opening the permission dialog.
}
}, [handleConfirm, onRequestAuthorization])
const { mutateAsync: deletePluginOAuthCustomClient } =
useDeletePluginOAuthCustomClientHook(pluginPayload)
const handleRemove = useCallback(async () => {
if (doingActionRef.current) return
try {
handleSetDoingAction(true)
await deletePluginOAuthCustomClient()
toast.success(t(($) => $['api.actionSuccess'], { ns: 'common' }))
onOpenChange?.(false)
onClose?.()
onUpdate?.()
invalidPluginOAuthClientSchema()
} finally {
handleSetDoingAction(false)
}
}, [
onUpdate,
invalidPluginOAuthClientSchema,
deletePluginOAuthCustomClient,
t,
handleSetDoingAction,
onClose,
onOpenChange,
])
const form = useForm({
defaultValues: editValues || defaultValues,
})
const __oauth_client__ = useSelector(form.store, (s) => s.values.__oauth_client__)
const isDisabled = disabled || doingAction
return (
<Dialog open={open} disablePointerDismissal onOpenChange={handleOpenChange}>
<DialogContent backdropProps={{ forceRender: true }}>
<DialogHeader>
<DialogTitle>{t(($) => $['auth.oauthClientSettings'], { ns: 'plugin' })}</DialogTitle>
<DialogHeaderCloseButton aria-label={t(($) => $['operation.close'], { ns: 'common' })} />
</DialogHeader>
<DialogBody>
{pluginPayload.detail && (
<ReadmeEntrance pluginDetail={pluginPayload.detail} presentation="dialog" />
)}
<AuthForm
formFromProps={form}
ref={formRef}
formSchemas={schemas}
defaultValues={editValues || defaultValues}
disabled={disabled}
/>
</DialogBody>
<DialogFooter>
{__oauth_client__ === 'custom' && hasOriginalClientParams && (
<Button
variant="secondary"
className="me-auto text-components-button-destructive-secondary-text"
disabled={isDisabled || !editValues}
onClick={handleRemove}
>
{t(($) => $['operation.remove'], { ns: 'common' })}
</Button>
)}
<Button variant="secondary" onClick={() => handleOpenChange(false)} disabled={isDisabled}>
{t(($) => $['operation.cancel'], { ns: 'common' })}
</Button>
<div className="mx-1 h-4 w-px bg-divider-regular"></div>
<Button onClick={handleConfirm} disabled={isDisabled}>
{t(($) => $['auth.saveOnly'], { ns: 'plugin' })}
</Button>
<Button variant="primary" onClick={handleConfirmAndAuthorize} disabled={isDisabled}>
{t(($) => $['auth.saveAndAuth'], { ns: 'plugin' })}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
export default memo(OAuthClientSettings)
@@ -0,0 +1,73 @@
import type { CredentialPermission } from '@/models/permission'
import { Button } from '@langgenius/dify-ui/button'
import {
Dialog,
DialogBody,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogHeaderCloseButton,
DialogTitle,
} from '@langgenius/dify-ui/dialog'
import { memo } from 'react'
import { useTranslation } from 'react-i18next'
import PermissionSelector from './permission-selector'
type OAuthVisibilityDialogProps = {
open: boolean
onOpenChange: (open: boolean) => void
permission: CredentialPermission
onPermissionChange: (permission: CredentialPermission) => void
onConfirm: () => Promise<void> | void
loading?: boolean
}
const OAuthVisibilityDialog = ({
open,
onOpenChange,
permission,
onPermissionChange,
onConfirm,
loading = false,
}: OAuthVisibilityDialogProps) => {
const { t } = useTranslation(['common', 'plugin'])
const handleOpenChange = (nextOpen: boolean) => {
if (loading && !nextOpen) return
onOpenChange(nextOpen)
}
return (
<Dialog open={open} onOpenChange={handleOpenChange} disablePointerDismissal={loading}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t(($) => $['auth.whoCanUse'], { ns: 'plugin' })}</DialogTitle>
<DialogDescription>
{t(($) => $['auth.oauthCredentialPermissionDescription'], { ns: 'plugin' })}
</DialogDescription>
<DialogHeaderCloseButton
aria-label={t(($) => $['operation.close'], { ns: 'common' })}
disabled={loading}
/>
</DialogHeader>
<DialogBody>
<PermissionSelector
disabled={loading}
permission={permission}
onChange={onPermissionChange}
/>
</DialogBody>
<DialogFooter>
<Button disabled={loading} onClick={() => handleOpenChange(false)}>
{t(($) => $['operation.cancel'], { ns: 'common' })}
</Button>
<Button variant="primary" loading={loading} onClick={onConfirm}>
{t(($) => $['auth.authorize'], { ns: 'plugin' })}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
export default memo(OAuthVisibilityDialog)
@@ -0,0 +1,117 @@
import type { CredentialPermission } from '@/models/permission'
import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'
import { cn } from '@langgenius/dify-ui/cn'
import {
Menu,
MenuContent,
MenuRadioGroup,
MenuRadioItem,
MenuRadioItemIndicator,
MenuTrigger,
} from '@langgenius/dify-ui/menu'
import { useSuspenseQuery } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import { PermissionLevel } from '@/models/permission'
import { getAvatarInitial } from '@/utils/avatar'
type PermissionSelectorProps = {
disabled?: boolean
permission: CredentialPermission
onChange: (permission: CredentialPermission) => void
}
const PermissionSelector = ({ disabled, permission, onChange }: PermissionSelectorProps) => {
const { t } = useTranslation(['datasetSettings', 'plugin'])
const { data: userProfile } = useSuspenseQuery({
...userProfileQueryOptions(),
select: (data) => data.profile,
})
const isOnlyMe = permission === PermissionLevel.onlyMe
const isAllTeamMembers = permission === PermissionLevel.allTeamMembers
const permissionLabel = t(($) => $['auth.whoCanUse'], { ns: 'plugin' })
const onlyMeLabel = t(($) => $['form.permissionsOnlyMe'], { ns: 'datasetSettings' })
const allTeamMembersLabel = t(($) => $['form.permissionsAllMember'], {
ns: 'datasetSettings',
})
const selectedPermissionLabel = isOnlyMe ? onlyMeLabel : allTeamMembersLabel
return (
<Menu>
<MenuTrigger
aria-label={`${permissionLabel}: ${selectedPermissionLabel}`}
disabled={disabled}
className={cn(
'group/permission-trigger flex w-full cursor-pointer touch-manipulation items-center gap-x-0.5 rounded-lg bg-components-input-bg-normal px-2 py-1 text-left hover:bg-state-base-hover-alt data-popup-open:bg-state-base-hover-alt',
'data-disabled:cursor-not-allowed! data-disabled:bg-components-input-bg-disabled! data-disabled:hover:bg-components-input-bg-disabled!',
)}
>
{isOnlyMe && (
<>
<div className="flex size-6 shrink-0 items-center justify-center">
<Avatar size="xs" aria-hidden="true">
<AvatarFallback>{getAvatarInitial(userProfile.name)}</AvatarFallback>
<AvatarImage src={userProfile.avatar_url || undefined} alt="" />
</Avatar>
</div>
<div className="grow p-1 system-sm-regular text-components-input-text-filled">
{onlyMeLabel}
</div>
</>
)}
{isAllTeamMembers && (
<>
<div className="flex size-6 shrink-0 items-center justify-center">
<span aria-hidden="true" className="i-ri-group-2-line size-4 text-text-secondary" />
</div>
<div className="grow p-1 system-sm-regular text-components-input-text-filled">
{allTeamMembersLabel}
</div>
</>
)}
<span
aria-hidden="true"
className="i-ri-arrow-down-s-line size-4 shrink-0 text-text-quaternary group-data-disabled/permission-trigger:text-components-input-text-placeholder! group-data-popup-open/permission-trigger:text-text-secondary"
/>
</MenuTrigger>
<MenuContent align="start" className="w-(--anchor-width) max-w-(--available-width)">
<MenuRadioGroup<CredentialPermission>
value={permission}
onValueChange={onChange}
aria-label={permissionLabel}
>
<MenuRadioItem<CredentialPermission>
aria-label={onlyMeLabel}
value={PermissionLevel.onlyMe}
closeOnClick
className="touch-manipulation"
>
<Avatar className="shrink-0" size="sm" aria-hidden="true">
<AvatarFallback>{getAvatarInitial(userProfile.name)}</AvatarFallback>
<AvatarImage src={userProfile.avatar_url || undefined} alt="" />
</Avatar>
<div className="min-w-0 grow px-1 system-md-regular text-text-secondary">
{onlyMeLabel}
</div>
<MenuRadioItemIndicator />
</MenuRadioItem>
<MenuRadioItem<CredentialPermission>
value={PermissionLevel.allTeamMembers}
closeOnClick
className="touch-manipulation"
>
<div className="flex size-6 shrink-0 items-center justify-center">
<span aria-hidden="true" className="i-ri-group-2-line size-4 text-text-secondary" />
</div>
<div className="min-w-0 grow px-1 system-md-regular text-text-secondary">
{allTeamMembersLabel}
</div>
<MenuRadioItemIndicator />
</MenuRadioItem>
</MenuRadioGroup>
</MenuContent>
</Menu>
)
}
export default PermissionSelector
@@ -0,0 +1,29 @@
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { StatusDot } from '@langgenius/dify-ui/status-dot'
import { RiEqualizer2Line } from '@remixicon/react'
import { memo } from 'react'
import { useTranslation } from 'react-i18next'
type AuthorizedInDataSourceNodeProps = {
authorizationsNum: number
onJumpToDataSourcePage: () => void
}
const AuthorizedInDataSourceNode = ({
authorizationsNum,
onJumpToDataSourcePage,
}: AuthorizedInDataSourceNodeProps) => {
const { t } = useTranslation(['plugin'])
return (
<Button size="small" onClick={onJumpToDataSourcePage}>
<StatusDot status="success" />
{authorizationsNum > 1
? t(($) => $['auth.authorizations'], { ns: 'plugin' })
: t(($) => $['auth.authorization'], { ns: 'plugin' })}
<RiEqualizer2Line className={cn('size-3.5 text-components-button-ghost-text')} />
</Button>
)
}
export default memo(AuthorizedInDataSourceNode)
@@ -0,0 +1,153 @@
import type { StatusDotStatus } from '@langgenius/dify-ui/status-dot'
import type { ComponentPropsWithRef } from 'react'
import type { Credential, PluginPayload } from './types'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { StatusDot } from '@langgenius/dify-ui/status-dot'
import { RiArrowDownSLine } from '@remixicon/react'
import { memo, useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Authorized, usePluginAuth } from '.'
type AuthorizedInNodeProps = {
pluginPayload: PluginPayload
onAuthorizationItemClick: (id: string) => void
credentialId?: string
onDefaultCredentialChange?: (id?: string) => void
}
const AuthorizedInNode = ({
pluginPayload,
onAuthorizationItemClick,
credentialId,
onDefaultCredentialChange,
}: AuthorizedInNodeProps) => {
const { t } = useTranslation(['common', 'plugin'])
const [isOpen, setIsOpen] = useState(false)
const {
canApiKey,
canOAuth,
credentials,
isLoading,
invalidPluginCredentialInfo,
notAllowCustomCredential,
} = usePluginAuth(pluginPayload, true, credentialId ? [credentialId] : undefined)
const defaultCredentialId = credentials.find((c) => c.is_default)?.id
useEffect(() => {
onDefaultCredentialChange?.(defaultCredentialId)
}, [defaultCredentialId, onDefaultCredentialChange])
const renderTrigger = useCallback(
(open: boolean, triggerProps: ComponentPropsWithRef<'button'>) => {
let label = ''
let removed = false
let unavailable = false
let color: StatusDotStatus = 'success'
let defaultUnavailable = false
if (!credentialId) {
label = t(($) => $['auth.workspaceDefault'], { ns: 'plugin' })
const defaultCredential = credentials.find((c) => c.is_default)
if (isLoading) {
color = 'disabled'
} else if (!defaultCredential) {
color = 'error'
defaultUnavailable = true
} else if (defaultCredential.not_allowed_to_use) {
color = 'disabled'
defaultUnavailable = true
}
} else {
const credential = credentials.find((c) => c.id === credentialId)
if (credential) label = credential.name
else if (isLoading) {
label = t(($) => $.loading, { ns: 'common' })
color = 'disabled'
} else {
label = t(($) => $['auth.authRemoved'], { ns: 'plugin' })
removed = true
}
unavailable = !!credential?.not_allowed_to_use && !credential?.from_enterprise
if (removed) color = 'error'
else if (unavailable) color = 'disabled'
}
return (
<Button
{...triggerProps}
size="small"
className={cn(
triggerProps.className,
open && !removed && 'bg-components-button-ghost-bg-hover',
removed && 'bg-transparent text-text-destructive',
)}
variant={defaultUnavailable || unavailable ? 'ghost' : 'secondary'}
>
<StatusDot status={color} />
{label}
{(unavailable || defaultUnavailable) && (
<>
&nbsp;
{t(($) => $['auth.unavailable'], { ns: 'plugin' })}
</>
)}
<RiArrowDownSLine
className={cn(
'size-3.5 text-components-button-ghost-text',
removed && 'text-text-destructive',
)}
/>
</Button>
)
},
[credentialId, credentials, isLoading, t],
)
const defaultUnavailable = credentials.find((c) => c.is_default)?.not_allowed_to_use
const extraAuthorizationItems: Credential[] = [
{
id: '__workspace_default__',
name: t(($) => $['auth.workspaceDefault'], { ns: 'plugin' }),
provider: '',
is_default: !credentialId,
isWorkspaceDefault: true,
not_allowed_to_use: defaultUnavailable,
},
]
const handleAuthorizationItemClick = useCallback(
(id: string) => {
onAuthorizationItemClick(
id === '__workspace_default__' && onDefaultCredentialChange
? defaultCredentialId || id
: id,
)
setIsOpen(false)
},
[defaultCredentialId, onDefaultCredentialChange, onAuthorizationItemClick, setIsOpen],
)
return (
<Authorized
pluginPayload={pluginPayload}
credentials={credentials}
canOAuth={canOAuth}
canApiKey={canApiKey}
renderTrigger={renderTrigger}
isOpen={isOpen}
onOpenChange={setIsOpen}
sideOffset={4}
align="end"
triggerPopupSameWidth={false}
popupClassName="w-[360px]"
disableSetDefault
onItemClick={handleAuthorizationItemClick}
extraAuthorizationItems={extraAuthorizationItems}
showItemSelectedIcon
selectedCredentialId={credentialId || '__workspace_default__'}
onUpdate={invalidPluginCredentialInfo}
notAllowCustomCredential={notAllowCustomCredential}
/>
)
}
export default memo(AuthorizedInNode)
@@ -0,0 +1,346 @@
import type { ComponentProps } from 'react'
import type { Credential } from '../../types'
import { act, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { FormTypeEnum } from '@/app/components/base/form/types'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import { createDeferred } from '@/test/deferred'
import { AuthCategory, CredentialTypeEnum } from '../../types'
import Authorized from '../index'
const requests = vi.hoisted(() => ({ get: vi.fn(), post: vi.fn() }))
vi.mock('@/service/base', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/base')>()
return {
...actual,
request: async (url: string, _init: RequestInit, options: { request: Request }) => {
const path = new URL(url).pathname.replace('/console/api', '')
return Response.json(
options.request.method === 'GET'
? await requests.get(path)
: await requests.post(path, { body: await options.request.json() }),
)
},
}
})
const permissions = vi.hoisted(() => ({
keys: ['credential.use', 'credential.create', 'credential.manage'],
}))
vi.mock('@/context/permission-state', async () => {
const { createPermissionStateModuleMock } = await import('@/test/console/state-fixture')
return createPermissionStateModuleMock(() => ({ workspacePermissionKeys: permissions.keys }))
})
const baseUrl = '/workspaces/current/tool-provider/builtin/test-provider'
const payload = { category: AuthCategory.tool, provider: 'test-provider' }
const credential = (overrides: Partial<Credential> = {}): Credential => ({
id: 'credential-a',
name: 'Primary key',
provider: 'test-provider',
credential_type: CredentialTypeEnum.API_KEY,
is_default: false,
credentials: { api_key: 'first-secret' },
...overrides,
})
const defaults = { pluginPayload: payload, credentials: [credential()] }
const trigger = () => screen.getByRole('button', { name: /plugin.auth.authorization/ })
const confirmDialog = () =>
screen.findByRole('alertdialog', { name: 'datasetDocuments.list.delete.title' })
const editDialog = () => screen.findByRole('dialog', { name: 'plugin.auth.useApiAuth' })
const renderAuthorized = (props: Partial<ComponentProps<typeof Authorized>> = {}) =>
renderWithConsoleQuery(<Authorized {...defaults} {...props} />)
beforeEach(() => {
vi.clearAllMocks()
permissions.keys = ['credential.use', 'credential.create', 'credential.manage']
requests.post.mockResolvedValue({})
requests.get.mockImplementation((url: string) => {
if (url.endsWith('/credential/schema/api-key'))
return Promise.resolve([
{
name: 'api_key',
label: { en_US: 'API Key' },
type: FormTypeEnum.secretInput,
required: true,
},
])
if (url.endsWith('/oauth/client-schema'))
return Promise.resolve({
schema: [],
is_oauth_custom_client_enabled: false,
is_system_oauth_params_exists: true,
})
throw new Error(`Unexpected credential request: ${url}`)
})
})
describe('Authorized credential management', () => {
it('groups API keys and OAuth credentials, reports unavailable entries, and selects the workspace default', async () => {
const user = userEvent.setup()
const onItemClick = vi.fn()
renderAuthorized({
credentials: [
credential(),
credential({
id: 'oauth',
name: 'OAuth account',
credential_type: CredentialTypeEnum.OAUTH2,
not_allowed_to_use: true,
}),
],
extraAuthorizationItems: [
credential({ id: '__workspace_default__', name: 'Workspace default' }),
],
onItemClick,
disableSetDefault: true,
})
expect(trigger()).toHaveTextContent('2 plugin.auth.authorizations (1 plugin.auth.unavailable)')
await user.click(trigger())
expect(await screen.findByText('API Keys')).toBeInTheDocument()
expect(screen.getByText('OAuth')).toBeInTheDocument()
await user.click(screen.getByText('OAuth account'))
expect(onItemClick).not.toHaveBeenCalled()
await user.click(screen.getByText('Primary key'))
expect(onItemClick).toHaveBeenLastCalledWith('credential-a')
await user.click(screen.getByText('Workspace default'))
expect(onItemClick).toHaveBeenLastCalledWith('')
expect(screen.queryByRole('button', { name: 'plugin.auth.setDefault' })).not.toBeInTheDocument()
})
it('uses the controlled open state and reports dismissal to its owner', async () => {
const user = userEvent.setup()
const onOpenChange = vi.fn()
const props = {
...defaults,
onOpenChange,
renderTrigger: (open: boolean, triggerProps: React.ComponentPropsWithRef<'button'>) => (
<button {...triggerProps} type="button">
{open ? 'Hide credentials' : 'Show credentials'}
</button>
),
}
const { rerender } = renderWithConsoleQuery(<Authorized {...props} isOpen />)
await user.click(screen.getByRole('button', { name: 'Hide credentials' }))
expect(onOpenChange).toHaveBeenCalledWith(false)
rerender(<Authorized {...props} isOpen={false} />)
await waitFor(() => expect(screen.queryByText('API Keys')).not.toBeInTheDocument())
expect(screen.getByRole('button', { name: 'Show credentials' })).toBeInTheDocument()
})
it('cancels one deletion, then deletes the newly selected credential only once while pending', async () => {
const user = userEvent.setup()
const onUpdate = vi.fn()
const pending = createDeferred<object>()
requests.post.mockReturnValue(pending.promise)
const { rerender } = renderAuthorized({ onUpdate })
await user.click(trigger())
await user.click(await screen.findByRole('button', { name: 'common.operation.delete' }))
await user.click(
within(await confirmDialog()).getByRole('button', { name: 'common.operation.cancel' }),
)
await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
expect(requests.post).not.toHaveBeenCalled()
rerender(
<Authorized
{...defaults}
credentials={[credential({ id: 'credential-b', name: 'Backup key' })]}
onUpdate={onUpdate}
/>,
)
await user.click(trigger())
await user.click(await screen.findByRole('button', { name: 'common.operation.delete' }))
const confirm = within(await confirmDialog()).getByRole('button', {
name: 'common.operation.confirm',
})
await user.click(confirm)
expect(confirm).toBeDisabled()
await user.click(confirm)
await waitFor(() => {
expect(requests.post).toHaveBeenCalledExactlyOnceWith(`${baseUrl}/delete`, {
body: { credential_id: 'credential-b' },
})
})
expect(onUpdate).not.toHaveBeenCalled()
await act(async () => {
pending.resolve({})
})
await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
expect(onUpdate).toHaveBeenCalledOnce()
})
it('serializes set-default operations and allows another action after completion', async () => {
const user = userEvent.setup()
const onUpdate = vi.fn()
const pending = createDeferred<object>()
requests.post.mockReturnValueOnce(pending.promise)
renderAuthorized({ onUpdate })
await user.click(trigger())
const setDefault = await screen.findByRole('button', { name: 'plugin.auth.setDefault' })
await user.click(setDefault)
await user.click(setDefault)
expect(requests.post).toHaveBeenCalledExactlyOnceWith(`${baseUrl}/default-credential`, {
body: { id: 'credential-a' },
})
expect(onUpdate).not.toHaveBeenCalled()
await act(async () => {
pending.resolve({})
})
await waitFor(() => expect(onUpdate).toHaveBeenCalledOnce())
await user.click(setDefault)
await waitFor(() => expect(onUpdate).toHaveBeenCalledTimes(2))
expect(requests.post).toHaveBeenCalledTimes(2)
})
it('renames OAuth credentials and ignores another save until the first update completes', async () => {
const user = userEvent.setup()
const onUpdate = vi.fn()
const pending = createDeferred<object>()
requests.post.mockReturnValueOnce(pending.promise)
renderAuthorized({
credentials: [credential({ credential_type: CredentialTypeEnum.OAUTH2 })],
onUpdate,
})
await user.click(trigger())
await user.click(await screen.findByRole('button', { name: 'common.operation.rename' }))
const name = screen.getByRole('textbox', { name: 'common.operation.rename' })
await user.clear(name)
await user.type(name, 'Renamed account')
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
await user.click(screen.getByRole('button', { name: 'common.operation.rename' }))
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
expect(requests.post).toHaveBeenCalledExactlyOnceWith(`${baseUrl}/update`, {
body: { credential_id: 'credential-a', name: 'Renamed account' },
})
expect(onUpdate).not.toHaveBeenCalled()
await act(async () => {
pending.resolve({})
})
await waitFor(() => expect(onUpdate).toHaveBeenCalledOnce())
})
it('reopens the edit form for a different credential with its own values and deletion target', async () => {
const user = userEvent.setup()
const onUpdate = vi.fn()
const { rerender } = renderAuthorized({ onUpdate })
await user.click(trigger())
await user.click(await screen.findByRole('button', { name: 'common.operation.edit' }))
const first = await editDialog()
expect(await within(first).findByLabelText(/API Key/)).toHaveValue('first-secret')
await user.clear(within(first).getByRole('textbox', { name: 'plugin.auth.authorizationName' }))
await user.type(
within(first).getByRole('textbox', { name: 'plugin.auth.authorizationName' }),
'Unsaved name',
)
await user.click(within(first).getByRole('button', { name: 'common.operation.cancel' }))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
rerender(
<Authorized
{...defaults}
credentials={[
credential({
id: 'credential-b',
name: 'Backup key',
credentials: { api_key: 'second-secret' },
}),
]}
onUpdate={onUpdate}
/>,
)
await user.click(trigger())
await user.click(await screen.findByRole('button', { name: 'common.operation.edit' }))
const second = await editDialog()
expect(await within(second).findByLabelText(/API Key/)).toHaveValue('second-secret')
expect(
within(second).getByRole('textbox', { name: 'plugin.auth.authorizationName' }),
).toHaveValue('Backup key')
await user.click(within(second).getByRole('button', { name: 'common.operation.remove' }))
await user.click(
within(await confirmDialog()).getByRole('button', { name: 'common.operation.confirm' }),
)
await waitFor(() => expect(onUpdate).toHaveBeenCalledOnce())
expect(requests.post).toHaveBeenCalledExactlyOnceWith(`${baseUrl}/delete`, {
body: { credential_id: 'credential-b' },
})
})
it('saves edited key values with their credential identity', async () => {
const user = userEvent.setup()
const onUpdate = vi.fn()
renderAuthorized({ onUpdate })
await user.click(trigger())
await user.click(await screen.findByRole('button', { name: 'common.operation.edit' }))
const modal = await editDialog()
const key = await within(modal).findByLabelText(/API Key/)
await user.clear(key)
await user.type(key, 'replacement-secret')
await user.click(within(modal).getByRole('button', { name: 'common.operation.save' }))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
expect(requests.post).toHaveBeenCalledExactlyOnceWith(`${baseUrl}/update`, {
body: {
credential_id: 'credential-a',
name: 'Primary key',
credentials: { api_key: 'replacement-secret' },
},
})
expect(onUpdate).toHaveBeenCalledOnce()
})
it('keeps the add-key dialog usable after its credential popover closes', async () => {
const user = userEvent.setup()
const onUpdate = vi.fn()
renderAuthorized({ credentials: [], canApiKey: true, onUpdate })
await user.click(trigger())
await user.click(await screen.findByRole('button', { name: 'plugin.auth.useApiAuth' }))
const modal = await editDialog()
await user.type(await within(modal).findByLabelText(/API Key/), 'new-secret')
await user.click(within(modal).getByRole('button', { name: 'common.operation.save' }))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
expect(requests.post).toHaveBeenCalledWith(`${baseUrl}/add`, {
body: {
credentials: { api_key: 'new-secret' },
type: CredentialTypeEnum.API_KEY,
name: '',
visibility: 'all_team_members',
},
})
expect(onUpdate).toHaveBeenCalledOnce()
})
it.each([
{ keys: ['credential.use'], canUse: true, canManage: false, canCreate: false },
{ keys: ['credential.manage'], canUse: false, canManage: true, canCreate: false },
{ keys: ['credential.create'], canUse: false, canManage: false, canCreate: true },
{ keys: [], canUse: false, canManage: false, canCreate: false },
])(
'respects independent credential permissions: $keys',
async ({ keys, canUse, canManage, canCreate }) => {
const user = userEvent.setup()
permissions.keys = keys
renderAuthorized({ canApiKey: true })
await user.click(trigger())
const setDefault = await screen.findByRole('button', { name: 'plugin.auth.setDefault' })
expect(setDefault.hasAttribute('disabled')).toBe(!canUse)
expect(
screen.getByRole('button', { name: 'common.operation.edit' }).hasAttribute('disabled'),
).toBe(!canManage)
expect(
screen.getByRole('button', { name: 'common.operation.delete' }).hasAttribute('disabled'),
).toBe(!canManage)
expect(
screen.getByRole('button', { name: 'plugin.auth.useApiAuth' }).hasAttribute('disabled'),
).toBe(!canCreate)
await user.click(setDefault)
expect(requests.post).toHaveBeenCalledTimes(canUse ? 1 : 0)
},
)
it('omits creation actions when custom credentials are disallowed', async () => {
const user = userEvent.setup()
renderAuthorized({ canApiKey: true, canOAuth: true, notAllowCustomCredential: true })
await user.click(trigger())
await screen.findByText('API Keys')
expect(screen.queryByRole('button', { name: 'plugin.auth.addApi' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: /plugin.auth.addOAuth/ })).not.toBeInTheDocument()
})
})
@@ -0,0 +1,128 @@
import type { ComponentProps } from 'react'
import type { Credential } from '../../types'
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import { CredentialTypeEnum } from '../../types'
import Item from '../item'
const createCredential = (overrides: Partial<Credential> = {}): Credential => ({
id: 'credential-id',
name: 'Test Credential',
provider: 'test-provider',
credential_type: CredentialTypeEnum.API_KEY,
is_default: false,
credentials: { api_key: 'test-key' },
...overrides,
})
const renderItem = (props: Partial<ComponentProps<typeof Item>> = {}) =>
renderWithConsoleQuery(<Item credential={createCredential()} {...props} />, {
workspacePermissionKeys: ['credential.use', 'credential.create', 'credential.manage'],
})
it.each([
['credential-id', 'credential-id'],
['__workspace_default__', ''],
])('selects %s with the corresponding credential reference', async (id, expected) => {
const user = userEvent.setup()
const onItemClick = vi.fn()
renderItem({ credential: createCredential({ id }), onItemClick })
await user.click(screen.getByText('Test Credential'))
expect(onItemClick).toHaveBeenCalledExactlyOnceWith(expected)
})
it.each([{ disabled: true }, { credential: createCredential({ not_allowed_to_use: true }) }])(
'does not select a disabled credential (%j)',
async (props) => {
const user = userEvent.setup()
const onItemClick = vi.fn()
renderItem({ ...props, onItemClick })
await user.click(screen.getByText('Test Credential'))
expect(onItemClick).not.toHaveBeenCalled()
},
)
it('discards a cancelled rename and saves the new name without selecting the row', async () => {
const user = userEvent.setup()
const onRename = vi.fn()
const onItemClick = vi.fn()
renderItem({ onRename, onItemClick })
await user.click(screen.getByRole('button', { name: 'common.operation.rename' }))
const input = screen.getByRole('textbox', { name: 'common.operation.rename' })
await user.clear(input)
await user.type(input, 'Discarded name')
await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
expect(onRename).not.toHaveBeenCalled()
await user.click(screen.getByRole('button', { name: 'common.operation.rename' }))
const reopened = screen.getByRole('textbox', { name: 'common.operation.rename' })
expect(reopened).toHaveValue('Test Credential')
await user.clear(reopened)
await user.type(reopened, 'New name')
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
expect(onRename).toHaveBeenCalledExactlyOnceWith({
credential_id: 'credential-id',
name: 'New name',
})
expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
expect(onItemClick).not.toHaveBeenCalled()
})
it('routes default, edit and delete actions without selecting the credential', async () => {
const user = userEvent.setup()
const onSetDefault = vi.fn()
const onEdit = vi.fn()
const onDelete = vi.fn()
const onItemClick = vi.fn()
renderItem({ onSetDefault, onEdit, onDelete, onItemClick })
await user.click(screen.getByRole('button', { name: 'plugin.auth.setDefault' }))
expect(onSetDefault).toHaveBeenCalledExactlyOnceWith('credential-id')
await user.click(screen.getByRole('button', { name: 'common.operation.edit' }))
expect(onEdit).toHaveBeenCalledExactlyOnceWith('credential-id', {
api_key: 'test-key',
__name__: 'Test Credential',
__credential_id__: 'credential-id',
})
await user.click(screen.getByRole('button', { name: 'common.operation.delete' }))
expect(onDelete).toHaveBeenCalledExactlyOnceWith('credential-id')
expect(onItemClick).not.toHaveBeenCalled()
})
it('marks the default credential and omits its redundant set-default action', () => {
renderItem({ credential: createCredential({ is_default: true }) })
expect(screen.getByText('plugin.auth.default')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'plugin.auth.setDefault' })).not.toBeInTheDocument()
})
it('shows enterprise ownership and omits local management actions', () => {
renderItem({ credential: createCredential({ from_enterprise: true }) })
expect(screen.getByText('plugin.auth.enterprise')).toBeInTheDocument()
for (const action of ['rename', 'edit', 'delete'])
expect(
screen.queryByRole('button', { name: `common.operation.${action}` }),
).not.toBeInTheDocument()
})
it('keeps OAuth credentials renameable and removable without exposing secret editing', () => {
renderItem({ credential: createCredential({ credential_type: CredentialTypeEnum.OAUTH2 }) })
expect(screen.queryByRole('button', { name: 'common.operation.edit' })).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: 'common.operation.rename' })).toBeEnabled()
expect(screen.getByRole('button', { name: 'common.operation.delete' })).toBeEnabled()
})
it('lets an unavailable credential be removed but not renamed, edited or made default', () => {
renderItem({ credential: createCredential({ not_allowed_to_use: true }) })
for (const name of ['common.operation.rename', 'common.operation.edit', 'plugin.auth.setDefault'])
expect(screen.queryByRole('button', { name })).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: 'common.operation.delete' })).toBeEnabled()
})
it('omits actions explicitly disabled by the owning selector', () => {
renderItem({
disableRename: true,
disableEdit: true,
disableDelete: true,
disableSetDefault: true,
})
expect(screen.queryByRole('button')).not.toBeInTheDocument()
})
@@ -0,0 +1,378 @@
import type { PopoverContentProps } from '@langgenius/dify-ui/popover'
import type { ComponentPropsWithRef, ReactElement } from 'react'
import type { Credential, PluginPayload } from '../types'
import {
AlertDialog,
AlertDialogCancelButton,
AlertDialogConfirmButton,
AlertDialogContent,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@langgenius/dify-ui/alert-dialog'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
import { StatusDot } from '@langgenius/dify-ui/status-dot'
import { memo, useCallback, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { useCredentialPermissions } from '@/hooks/use-credential-permissions'
import Authorize from '../authorize'
import ApiKeyModal from '../authorize/api-key-modal'
import {
useDeletePluginCredentialHook,
useSetPluginDefaultCredentialHook,
useUpdatePluginCredentialHook,
} from '../hooks/use-credential'
import { CredentialTypeEnum } from '../types'
import Item from './item'
type AuthorizedProps = Pick<PopoverContentProps, 'side' | 'align' | 'sideOffset'> & {
pluginPayload: PluginPayload
credentials: Credential[]
canOAuth?: boolean
canApiKey?: boolean
renderTrigger?: (open: boolean, props: ComponentPropsWithRef<'button'>) => ReactElement
isOpen?: boolean
onOpenChange?: (open: boolean) => void
triggerPopupSameWidth?: boolean
popupClassName?: string
disableSetDefault?: boolean
onItemClick?: (id: string) => void
extraAuthorizationItems?: Credential[]
showItemSelectedIcon?: boolean
selectedCredentialId?: string
onUpdate?: () => void
notAllowCustomCredential?: boolean
}
const Authorized = ({
pluginPayload,
credentials,
canOAuth,
canApiKey,
renderTrigger,
isOpen,
onOpenChange,
sideOffset,
side,
align = 'start',
triggerPopupSameWidth = true,
popupClassName,
disableSetDefault,
onItemClick,
extraAuthorizationItems,
showItemSelectedIcon,
selectedCredentialId,
onUpdate,
notAllowCustomCredential,
}: AuthorizedProps) => {
const { t } = useTranslation(['common', 'datasetDocuments', 'plugin'])
const { canUseCredential, canCreateCredential, canManageCredential } = useCredentialPermissions()
const [isLocalOpen, setIsLocalOpen] = useState(false)
const mergedIsOpen = isOpen ?? isLocalOpen
const setMergedIsOpen = useCallback(
(open: boolean) => {
if (onOpenChange) onOpenChange(open)
setIsLocalOpen(open)
},
[onOpenChange],
)
const oAuthCredentials = credentials.filter(
(credential) => credential.credential_type === CredentialTypeEnum.OAUTH2,
)
const apiKeyCredentials = credentials.filter(
(credential) => credential.credential_type === CredentialTypeEnum.API_KEY,
)
const pendingOperationCredentialIdRef = useRef<string | null>(null)
const [deleteCredentialId, setDeleteCredentialId] = useState<string | null>(null)
const { mutateAsync: deletePluginCredential } = useDeletePluginCredentialHook(pluginPayload)
const openConfirm = useCallback(
(credentialId?: string) => {
if (!canManageCredential) return
setMergedIsOpen(false)
if (credentialId) pendingOperationCredentialIdRef.current = credentialId
setDeleteCredentialId(pendingOperationCredentialIdRef.current)
},
[canManageCredential, setMergedIsOpen],
)
const closeConfirm = useCallback(() => {
setDeleteCredentialId(null)
pendingOperationCredentialIdRef.current = null
}, [])
const [doingAction, setDoingAction] = useState(false)
const doingActionRef = useRef(doingAction)
const handleSetDoingAction = useCallback((doing: boolean) => {
doingActionRef.current = doing
setDoingAction(doing)
}, [])
const handleConfirm = useCallback(async () => {
if (doingActionRef.current || !canManageCredential) return
if (!pendingOperationCredentialIdRef.current) {
setDeleteCredentialId(null)
return
}
try {
handleSetDoingAction(true)
await deletePluginCredential({ credential_id: pendingOperationCredentialIdRef.current })
toast.success(t(($) => $['api.actionSuccess'], { ns: 'common' }))
onUpdate?.()
setDeleteCredentialId(null)
pendingOperationCredentialIdRef.current = null
} finally {
handleSetDoingAction(false)
}
}, [canManageCredential, deletePluginCredential, onUpdate, t, handleSetDoingAction])
const [editValues, setEditValues] = useState<Record<string, unknown> | null>(null)
const [isApiKeyModalOpen, setIsApiKeyModalOpen] = useState(false)
const handleEdit = useCallback(
(id: string, values: Record<string, unknown>) => {
if (!canManageCredential) return
setMergedIsOpen(false)
pendingOperationCredentialIdRef.current = id
setEditValues(values)
setIsApiKeyModalOpen(true)
},
[canManageCredential, setMergedIsOpen],
)
const handleApiKeyModalOpenChange = useCallback((open: boolean) => {
setIsApiKeyModalOpen(open)
if (!open) pendingOperationCredentialIdRef.current = null
}, [])
// Lifted state for the "+ Add API Key" modal so it isn't unmounted when the
// popover closes due to outside-click detection on the modal's portal.
const [isAddApiKeyOpen, setIsAddApiKeyOpen] = useState(false)
const handleAddApiKeyClick = useCallback(() => {
if (!canCreateCredential) return
setMergedIsOpen(false)
setIsAddApiKeyOpen(true)
}, [canCreateCredential, setMergedIsOpen])
const handleRemove = useCallback(() => {
if (!canManageCredential) return
setDeleteCredentialId(pendingOperationCredentialIdRef.current)
}, [canManageCredential])
const { mutateAsync: setPluginDefaultCredential } =
useSetPluginDefaultCredentialHook(pluginPayload)
const handleSetDefault = useCallback(
async (id: string) => {
if (doingActionRef.current || !canUseCredential) return
try {
handleSetDoingAction(true)
await setPluginDefaultCredential(id)
toast.success(t(($) => $['api.actionSuccess'], { ns: 'common' }))
onUpdate?.()
} finally {
handleSetDoingAction(false)
}
},
[canUseCredential, setPluginDefaultCredential, onUpdate, t, handleSetDoingAction],
)
const { mutateAsync: updatePluginCredential } = useUpdatePluginCredentialHook(pluginPayload)
const handleRename = useCallback(
async (payload: { credential_id: string; name: string }) => {
if (doingActionRef.current || !canManageCredential) return
try {
handleSetDoingAction(true)
await updatePluginCredential(payload)
toast.success(t(($) => $['api.actionSuccess'], { ns: 'common' }))
onUpdate?.()
} finally {
handleSetDoingAction(false)
}
},
[canManageCredential, updatePluginCredential, t, handleSetDoingAction, onUpdate],
)
const unavailableCredentials = credentials.filter((credential) => credential.not_allowed_to_use)
const unavailableCredential = credentials.find(
(credential) => credential.not_allowed_to_use && credential.is_default,
)
return (
<>
<Popover open={mergedIsOpen} onOpenChange={setMergedIsOpen}>
<PopoverTrigger
className={triggerPopupSameWidth ? 'w-full' : undefined}
render={(props, state) =>
renderTrigger ? (
renderTrigger(state.open, props)
) : (
<Button
{...props}
className={cn(
props.className,
state.open && 'bg-components-button-secondary-bg-hover',
)}
>
<StatusDot status={unavailableCredential ? 'disabled' : 'success'} />
{credentials.length}
&nbsp;
{credentials.length > 1
? t(($) => $['auth.authorizations'], { ns: 'plugin' })
: t(($) => $['auth.authorization'], { ns: 'plugin' })}
{!!unavailableCredentials.length &&
` (${unavailableCredentials.length} ${t(($) => $['auth.unavailable'], { ns: 'plugin' })})`}
<span className="i-ri-arrow-down-s-line size-4" />
</Button>
)
}
/>
<PopoverContent
aria-label={t(($) => $['auth.authorizations'], { ns: 'plugin' })}
side={side}
align={align}
sideOffset={sideOffset}
className={cn(
'border-0 bg-transparent p-0 shadow-none backdrop-blur-none',
triggerPopupSameWidth && 'w-(--anchor-width)',
)}
>
<div
className={cn(
'max-h-90 overflow-y-auto rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg',
popupClassName,
)}
>
<div className="py-1">
{!!extraAuthorizationItems?.length && (
<div className="p-1">
{extraAuthorizationItems.map((credential) => (
<Item
key={credential.id}
credential={credential}
onItemClick={onItemClick}
disableRename
disableEdit
disableDelete
disableSetDefault
showSelectedIcon={showItemSelectedIcon}
selectedCredentialId={selectedCredentialId}
/>
))}
</div>
)}
{!!oAuthCredentials.length && (
<div className="p-1">
<div
className={cn(
'px-3 pt-1 pb-0.5 system-xs-medium text-text-tertiary',
showItemSelectedIcon && 'pl-7',
)}
>
OAuth
</div>
{oAuthCredentials.map((credential) => (
<Item
key={credential.id}
credential={credential}
disableEdit
onDelete={openConfirm}
onSetDefault={handleSetDefault}
onRename={handleRename}
disableSetDefault={disableSetDefault}
onItemClick={onItemClick}
showSelectedIcon={showItemSelectedIcon}
selectedCredentialId={selectedCredentialId}
/>
))}
</div>
)}
{!!apiKeyCredentials.length && (
<div className="p-1">
<div
className={cn(
'px-3 pt-1 pb-0.5 system-xs-medium text-text-tertiary',
showItemSelectedIcon && 'pl-7',
)}
>
API Keys
</div>
{apiKeyCredentials.map((credential) => (
<Item
key={credential.id}
credential={credential}
onDelete={openConfirm}
onEdit={handleEdit}
onSetDefault={handleSetDefault}
disableSetDefault={disableSetDefault}
disableRename
onItemClick={onItemClick}
onRename={handleRename}
showSelectedIcon={showItemSelectedIcon}
selectedCredentialId={selectedCredentialId}
/>
))}
</div>
)}
</div>
{!notAllowCustomCredential && (
<>
<div className="h-px bg-divider-subtle"></div>
<div className="p-2">
<Authorize
pluginPayload={pluginPayload}
theme="secondary"
showDivider={false}
canOAuth={canOAuth}
canApiKey={canApiKey}
onUpdate={onUpdate}
onApiKeyClick={handleAddApiKeyClick}
/>
</div>
</>
)}
</div>
</PopoverContent>
</Popover>
<AlertDialog open={!!deleteCredentialId} onOpenChange={(open) => !open && closeConfirm()}>
<AlertDialogContent backdropProps={{ forceRender: true }}>
<AlertDialogHeader>
<AlertDialogTitle>
{t(($) => $['list.delete.title'], { ns: 'datasetDocuments' })}
</AlertDialogTitle>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancelButton>
{t(($) => $['operation.cancel'], { ns: 'common' })}
</AlertDialogCancelButton>
<AlertDialogConfirmButton
disabled={!canManageCredential || doingAction}
onClick={handleConfirm}
>
{t(($) => $['operation.confirm'], { ns: 'common' })}
</AlertDialogConfirmButton>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{!!editValues && (
<ApiKeyModal
open={isApiKeyModalOpen}
onOpenChange={handleApiKeyModalOpenChange}
pluginPayload={pluginPayload}
editValues={editValues}
onClose={() => handleApiKeyModalOpenChange(false)}
onRemove={handleRemove}
disabled={!canManageCredential || doingAction}
onUpdate={onUpdate}
/>
)}
{isAddApiKeyOpen && (
<ApiKeyModal
open={isAddApiKeyOpen}
onOpenChange={setIsAddApiKeyOpen}
pluginPayload={pluginPayload}
onClose={() => setIsAddApiKeyOpen(false)}
disabled={!canCreateCredential || doingAction}
onUpdate={onUpdate}
/>
)}
</>
)
}
export default memo(Authorized)
@@ -0,0 +1,273 @@
import type { Credential } from '../types'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Input } from '@langgenius/dify-ui/input'
import { StatusDot } from '@langgenius/dify-ui/status-dot'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
import { RiInformationLine } from '@remixicon/react'
import { useSuspenseQuery } from '@tanstack/react-query'
import { memo, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Badge from '@/app/components/base/badge'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import { useCredentialPermissions } from '@/hooks/use-credential-permissions'
import { CredentialTypeEnum } from '../types'
type ItemProps = {
credential: Credential
onDelete?: (id: string) => void
onEdit?: (id: string, values: Record<string, unknown>) => void
onSetDefault?: (id: string) => void
onRename?: (payload: { credential_id: string; name: string }) => void
disableRename?: boolean
disableEdit?: boolean
disableDelete?: boolean
disableSetDefault?: boolean
onItemClick?: (id: string) => void
showSelectedIcon?: boolean
selectedCredentialId?: string
disabled?: boolean
}
const Item = ({
credential,
onDelete,
onEdit,
onSetDefault,
onRename,
disableRename,
disableEdit,
disableDelete,
disableSetDefault,
onItemClick,
showSelectedIcon,
selectedCredentialId,
disabled,
}: ItemProps) => {
const { t } = useTranslation(['common', 'plugin'])
const [renaming, setRenaming] = useState(false)
const [renameValue, setRenameValue] = useState(credential.name)
const { canUseCredential, canManageCredential } = useCredentialPermissions()
const isOAuth = credential.credential_type === CredentialTypeEnum.OAUTH2
const isPersonal = credential.visibility === 'only_me'
const { data: currentUserId } = useSuspenseQuery({
...userProfileQueryOptions(),
select: (data) => data.profile.id,
})
// Borrowed-from-teammate: the backend explicitly flagged this row as another member's
// only_me credential, returned only because the current node still references it.
// Fallback heuristic (created_by mismatch on a selected row) is kept for backends
// that don't yet emit the flag.
const isSelected = showSelectedIcon && selectedCredentialId === credential.id
const isConfiguredByOther =
!!credential.created_by && !!currentUserId && credential.created_by !== currentUserId
const isBorrowed =
!!credential.from_other_member || (isSelected && isConfiguredByOther && isPersonal)
const showSwitchAwayHint = isBorrowed
const showAction = useMemo(() => {
return !(disableRename && disableEdit && disableDelete && disableSetDefault)
}, [disableRename, disableEdit, disableDelete, disableSetDefault])
const CredentialItem = (
<div
key={credential.id}
className={cn(
'group flex h-8 items-center rounded-lg p-1 hover:bg-state-base-hover',
renaming && 'bg-state-base-hover',
(disabled || !canUseCredential || credential.not_allowed_to_use) &&
'cursor-not-allowed opacity-50',
)}
onClick={() => {
if (disabled || credential.not_allowed_to_use || !canUseCredential) return
onItemClick?.(credential.id === '__workspace_default__' ? '' : credential.id)
}}
>
{renaming && (
<div className="flex w-full items-center space-x-1">
<Input
aria-label={t(($) => $['operation.rename'], { ns: 'common' })}
className="h-6 grow"
value={renameValue}
onValueChange={setRenameValue}
placeholder={t(($) => $['placeholder.input'], { ns: 'common' })}
onClick={(e) => e.stopPropagation()}
/>
<Button
size="small"
variant="primary"
onClick={(e) => {
e.stopPropagation()
onRename?.({
credential_id: credential.id,
name: renameValue,
})
setRenaming(false)
}}
>
{t(($) => $['operation.save'], { ns: 'common' })}
</Button>
<Button
size="small"
onClick={(e) => {
e.stopPropagation()
setRenaming(false)
}}
>
{t(($) => $['operation.cancel'], { ns: 'common' })}
</Button>
</div>
)}
{!renaming && (
<div className="flex w-0 grow items-center space-x-1.5">
{showSelectedIcon && (
<div className="size-4">
{selectedCredentialId === credential.id && (
<span className="i-ri-check-line size-4 text-text-accent" />
)}
</div>
)}
<StatusDot
className="mr-1.5 ml-2 shrink-0"
status={credential.not_allowed_to_use ? 'disabled' : 'success'}
/>
<div className="truncate system-md-regular text-text-secondary" title={credential.name}>
{credential.name}
</div>
{credential.is_default && (
<Badge className="shrink-0">{t(($) => $['auth.default'], { ns: 'plugin' })}</Badge>
)}
</div>
)}
{showSwitchAwayHint && (
<Tooltip>
<TooltipTrigger
render={
<div className="ml-2 flex shrink-0 cursor-help items-center text-text-tertiary">
<RiInformationLine className="size-4" />
</div>
}
/>
<TooltipContent>
{t(($) => $['auth.onlyAtCreationHintTooltip'], { ns: 'plugin' })}
</TooltipContent>
</Tooltip>
)}
{!showSwitchAwayHint && credential.from_enterprise && (
<Badge className="shrink-0">{t(($) => $['auth.enterprise'], { ns: 'plugin' })}</Badge>
)}
{showAction && !renaming && (
<div className="ml-2 flex shrink-0 items-center">
{!credential.is_default &&
!disableSetDefault &&
!credential.not_allowed_to_use &&
!isBorrowed && (
<Button
size="small"
disabled={disabled || !canUseCredential}
onClick={(e) => {
e.stopPropagation()
onSetDefault?.(credential.id)
}}
>
{t(($) => $['auth.setDefault'], { ns: 'plugin' })}
</Button>
)}
{!disableRename &&
!credential.from_enterprise &&
!credential.not_allowed_to_use &&
!isBorrowed && (
<Tooltip>
<TooltipTrigger
render={
<IconButton
aria-label={t(($) => $['operation.rename'], { ns: 'common' })}
disabled={disabled || !canManageCredential}
onClick={(e) => {
e.stopPropagation()
setRenaming(true)
setRenameValue(credential.name)
}}
>
<span
aria-hidden="true"
className="i-ri-edit-line size-4 text-text-tertiary"
/>
</IconButton>
}
/>
<TooltipContent>{t(($) => $['operation.rename'], { ns: 'common' })}</TooltipContent>
</Tooltip>
)}
{!isOAuth &&
!disableEdit &&
!credential.from_enterprise &&
!credential.not_allowed_to_use &&
!isBorrowed && (
<Tooltip>
<TooltipTrigger
render={
<IconButton
aria-label={t(($) => $['operation.edit'], { ns: 'common' })}
disabled={disabled || !canManageCredential}
onClick={(e) => {
e.stopPropagation()
onEdit?.(credential.id, {
...credential.credentials,
__name__: credential.name,
__credential_id__: credential.id,
})
}}
>
<span
aria-hidden="true"
className="i-ri-equalizer-2-line size-4 text-text-tertiary"
/>
</IconButton>
}
/>
<TooltipContent>{t(($) => $['operation.edit'], { ns: 'common' })}</TooltipContent>
</Tooltip>
)}
{!disableDelete && !credential.from_enterprise && !isBorrowed && (
<Tooltip>
<TooltipTrigger
render={
<IconButton
aria-label={t(($) => $['operation.delete'], { ns: 'common' })}
className="hover:bg-transparent"
disabled={disabled || !canManageCredential}
onClick={(e) => {
e.stopPropagation()
onDelete?.(credential.id)
}}
>
<span
aria-hidden="true"
className="i-ri-delete-bin-line size-4 text-text-tertiary hover:text-text-destructive"
/>
</IconButton>
}
/>
<TooltipContent>{t(($) => $['operation.delete'], { ns: 'common' })}</TooltipContent>
</Tooltip>
)}
</div>
)}
</div>
)
if (credential.not_allowed_to_use) {
return (
<Tooltip>
<TooltipTrigger render={CredentialItem} />
<TooltipContent>
{t(($) => $['auth.customCredentialUnavailable'], { ns: 'plugin' })}
</TooltipContent>
</Tooltip>
)
}
return CredentialItem
}
export default memo(Item)
@@ -0,0 +1,15 @@
import { AuthCategory } from '../../types'
import { getApi } from '../get-api'
it('keeps the legacy credential-info endpoint for tools', () => {
expect(getApi({ category: AuthCategory.tool, provider: 'test-provider' }).getCredentialInfo).toBe(
'/workspaces/current/tool-provider/builtin/test-provider/credential/info',
)
})
it.each([AuthCategory.datasource, AuthCategory.model, AuthCategory.trigger])(
'does not request legacy credential info for %s',
(category) => {
expect(getApi({ category, provider: 'test-provider' }).getCredentialInfo).toBe('')
},
)
@@ -0,0 +1,187 @@
import type { PluginPayload } from '../../types'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { renderHook } from '@testing-library/react'
import { createElement } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { consoleQuery } from '@/service/console'
import { AuthCategory, CredentialTypeEnum } from '../../types'
import {
useAddPluginCredentialHook,
useDeletePluginCredentialHook,
useDeletePluginOAuthCustomClientHook,
useGetPluginCredentialInfoHook,
useGetPluginCredentialSchemaHook,
useGetPluginOAuthClientSchemaHook,
useGetPluginOAuthUrlHook,
useInvalidPluginCredentialInfoHook,
useInvalidPluginOAuthClientSchemaHook,
useSetPluginDefaultCredentialHook,
useSetPluginOAuthCustomClientHook,
useUpdatePluginCredentialHook,
} from '../use-credential'
// Mock service hooks
const mockUseGetPluginCredentialInfo = vi.fn().mockReturnValue({ data: null, isLoading: false })
const mockUseDeletePluginCredential = vi.fn().mockReturnValue({ mutateAsync: vi.fn() })
const mockUseInvalidPluginCredentialInfo = vi.fn().mockReturnValue(vi.fn())
const mockUseSetPluginDefaultCredential = vi.fn().mockReturnValue({ mutateAsync: vi.fn() })
const mockUseGetPluginCredentialSchema = vi.fn().mockReturnValue({ data: [], isLoading: false })
const mockUseAddPluginCredential = vi.fn().mockReturnValue({ mutateAsync: vi.fn() })
const mockUseUpdatePluginCredential = vi.fn().mockReturnValue({ mutateAsync: vi.fn() })
const mockUseGetPluginOAuthUrl = vi.fn().mockReturnValue({ mutateAsync: vi.fn() })
const mockUseGetPluginOAuthClientSchema = vi.fn().mockReturnValue({ data: null, isLoading: false })
const mockUseInvalidPluginOAuthClientSchema = vi.fn().mockReturnValue(vi.fn())
const mockUseSetPluginOAuthCustomClient = vi.fn().mockReturnValue({ mutateAsync: vi.fn() })
const mockUseDeletePluginOAuthCustomClient = vi.fn().mockReturnValue({ mutateAsync: vi.fn() })
vi.mock('@/service/use-plugins-auth', () => ({
useGetPluginCredentialInfo: (...args: unknown[]) => mockUseGetPluginCredentialInfo(...args),
useDeletePluginCredential: (...args: unknown[]) => mockUseDeletePluginCredential(...args),
useInvalidPluginCredentialInfo: (...args: unknown[]) =>
mockUseInvalidPluginCredentialInfo(...args),
useSetPluginDefaultCredential: (...args: unknown[]) => mockUseSetPluginDefaultCredential(...args),
useGetPluginCredentialSchema: (...args: unknown[]) => mockUseGetPluginCredentialSchema(...args),
useAddPluginCredential: (...args: unknown[]) => mockUseAddPluginCredential(...args),
useUpdatePluginCredential: (...args: unknown[]) => mockUseUpdatePluginCredential(...args),
useGetPluginOAuthUrl: (...args: unknown[]) => mockUseGetPluginOAuthUrl(...args),
useGetPluginOAuthClientSchema: (...args: unknown[]) => mockUseGetPluginOAuthClientSchema(...args),
useInvalidPluginOAuthClientSchema: (...args: unknown[]) =>
mockUseInvalidPluginOAuthClientSchema(...args),
useSetPluginOAuthCustomClient: (...args: unknown[]) => mockUseSetPluginOAuthCustomClient(...args),
useDeletePluginOAuthCustomClient: (...args: unknown[]) =>
mockUseDeletePluginOAuthCustomClient(...args),
}))
const toolPayload = {
category: AuthCategory.tool,
provider: 'test-provider',
providerType: 'builtin',
} satisfies PluginPayload
describe('use-credential hooks', () => {
beforeEach(() => {
vi.clearAllMocks()
})
describe('useGetPluginCredentialInfoHook', () => {
it('should call service with correct URL when enabled', () => {
renderHook(() => useGetPluginCredentialInfoHook(toolPayload, true))
expect(mockUseGetPluginCredentialInfo).toHaveBeenCalledWith(
`/workspaces/current/tool-provider/builtin/${toolPayload.provider}/credential/info`,
)
})
it('should pass empty string when disabled', () => {
renderHook(() => useGetPluginCredentialInfoHook(toolPayload, false))
expect(mockUseGetPluginCredentialInfo).toHaveBeenCalledWith('')
})
})
describe('useDeletePluginCredentialHook', () => {
it('should call service with correct URL', () => {
renderHook(() => useDeletePluginCredentialHook(toolPayload))
expect(mockUseDeletePluginCredential).toHaveBeenCalledWith(toolPayload)
})
})
describe('useInvalidPluginCredentialInfoHook', () => {
it('should return a function that invalidates both credential info and tools', () => {
const queryClient = new QueryClient()
const builtInToolsKey = consoleQuery.workspaces.current.tools.builtin.get.queryKey()
const customToolsKey = consoleQuery.workspaces.current.tools.api.get.queryKey()
queryClient.setQueryData(builtInToolsKey, [])
queryClient.setQueryData(customToolsKey, [])
const { result } = renderHook(() => useInvalidPluginCredentialInfoHook(toolPayload), {
wrapper: ({ children }) =>
createElement(QueryClientProvider, { client: queryClient }, children),
})
result.current()
const invalidFn = mockUseInvalidPluginCredentialInfo.mock.results[0]!.value
expect(invalidFn).toHaveBeenCalled()
expect(queryClient.getQueryState(builtInToolsKey)?.isInvalidated).toBe(true)
expect(queryClient.getQueryState(customToolsKey)?.isInvalidated).toBe(false)
})
})
describe('useSetPluginDefaultCredentialHook', () => {
it('should call service with correct URL', () => {
renderHook(() => useSetPluginDefaultCredentialHook(toolPayload))
expect(mockUseSetPluginDefaultCredential).toHaveBeenCalledWith(toolPayload)
})
})
describe('useGetPluginCredentialSchemaHook', () => {
it('should call service with correct schema URL for API_KEY', () => {
renderHook(() => useGetPluginCredentialSchemaHook(toolPayload, CredentialTypeEnum.API_KEY))
expect(mockUseGetPluginCredentialSchema).toHaveBeenCalledWith(
toolPayload,
CredentialTypeEnum.API_KEY,
)
})
it('should call service with correct schema URL for OAUTH2', () => {
renderHook(() => useGetPluginCredentialSchemaHook(toolPayload, CredentialTypeEnum.OAUTH2))
expect(mockUseGetPluginCredentialSchema).toHaveBeenCalledWith(
toolPayload,
CredentialTypeEnum.OAUTH2,
)
})
})
describe('useAddPluginCredentialHook', () => {
it('should call service with correct URL', () => {
renderHook(() => useAddPluginCredentialHook(toolPayload))
expect(mockUseAddPluginCredential).toHaveBeenCalledWith(toolPayload)
})
})
describe('useUpdatePluginCredentialHook', () => {
it('should call service with correct URL', () => {
renderHook(() => useUpdatePluginCredentialHook(toolPayload))
expect(mockUseUpdatePluginCredential).toHaveBeenCalledWith(toolPayload)
})
})
describe('useGetPluginOAuthUrlHook', () => {
it('should call service with correct URL', () => {
renderHook(() => useGetPluginOAuthUrlHook(toolPayload))
expect(mockUseGetPluginOAuthUrl).toHaveBeenCalledWith(toolPayload)
})
})
describe('useGetPluginOAuthClientSchemaHook', () => {
it('should call service with correct URL', () => {
renderHook(() => useGetPluginOAuthClientSchemaHook(toolPayload))
expect(mockUseGetPluginOAuthClientSchema).toHaveBeenCalledWith(toolPayload, true)
})
it('should disable the service query when OAuth data is provided by the caller', () => {
renderHook(() => useGetPluginOAuthClientSchemaHook(toolPayload, false))
expect(mockUseGetPluginOAuthClientSchema).toHaveBeenCalledWith(toolPayload, false)
})
})
describe('useInvalidPluginOAuthClientSchemaHook', () => {
it('should call service with correct URL', () => {
renderHook(() => useInvalidPluginOAuthClientSchemaHook(toolPayload))
expect(mockUseInvalidPluginOAuthClientSchema).toHaveBeenCalledWith(toolPayload)
})
})
describe('useSetPluginOAuthCustomClientHook', () => {
it('should call service with correct URL', () => {
renderHook(() => useSetPluginOAuthCustomClientHook(toolPayload))
expect(mockUseSetPluginOAuthCustomClient).toHaveBeenCalledWith(toolPayload)
})
})
describe('useDeletePluginOAuthCustomClientHook', () => {
it('should call service with correct URL', () => {
renderHook(() => useDeletePluginOAuthCustomClientHook(toolPayload))
expect(mockUseDeletePluginOAuthCustomClient).toHaveBeenCalledWith(toolPayload)
})
})
})
@@ -0,0 +1,200 @@
import type { ReactNode } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, renderHook } from '@testing-library/react'
import * as React from 'react'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { createDeferred } from '@/test/deferred'
import { usePluginAuthAction } from '../../hooks/use-plugin-auth-action'
import { AuthCategory } from '../../types'
const mockDeletePluginCredential = vi.fn().mockResolvedValue({})
const mockSetPluginDefaultCredential = vi.fn().mockResolvedValue({})
const mockUpdatePluginCredential = vi.fn().mockResolvedValue({})
const toastMocks = vi.hoisted(() => ({
call: vi.fn(),
dismiss: vi.fn(),
update: vi.fn(),
promise: vi.fn(),
}))
vi.mock('@/app/notifications', () => ({
toast: Object.assign(toastMocks.call, {
success: vi.fn((message: string, options?: Record<string, unknown>) =>
toastMocks.call({ type: 'success', message, ...options }),
),
error: vi.fn((message: string, options?: Record<string, unknown>) =>
toastMocks.call({ type: 'error', message, ...options }),
),
warning: vi.fn((message: string, options?: Record<string, unknown>) =>
toastMocks.call({ type: 'warning', message, ...options }),
),
info: vi.fn((message: string, options?: Record<string, unknown>) =>
toastMocks.call({ type: 'info', message, ...options }),
),
dismiss: toastMocks.dismiss,
update: toastMocks.update,
promise: toastMocks.promise,
}),
}))
vi.mock('../../hooks/use-credential', () => ({
useDeletePluginCredentialHook: () => ({
mutateAsync: mockDeletePluginCredential,
}),
useSetPluginDefaultCredentialHook: () => ({
mutateAsync: mockSetPluginDefaultCredential,
}),
useUpdatePluginCredentialHook: () => ({
mutateAsync: mockUpdatePluginCredential,
}),
}))
const pluginPayload = {
category: AuthCategory.tool,
provider: 'test-provider',
}
function createWrapper() {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
})
return function Wrapper({ children }: { children: ReactNode }) {
return React.createElement(QueryClientProvider, { client: queryClient }, children)
}
}
describe('usePluginAuthAction', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('should open and close confirm dialog', () => {
const { result } = renderHook(() => usePluginAuthAction(pluginPayload), {
wrapper: createWrapper(),
})
act(() => {
result.current.openConfirm('cred-1')
})
expect(result.current.deleteCredentialId).toBe('cred-1')
act(() => {
result.current.closeConfirm()
})
expect(result.current.deleteCredentialId).toBeNull()
})
it('opens deletion confirmation for the credential being edited', () => {
const { result } = renderHook(() => usePluginAuthAction(pluginPayload), {
wrapper: createWrapper(),
})
act(() => {
result.current.handleEdit('cred-1', { key: 'value' })
})
expect(result.current.editValues).toEqual({ key: 'value' })
act(() => {
result.current.handleRemove()
})
expect(result.current.deleteCredentialId).toBe('cred-1')
})
it('should handle confirm delete', async () => {
const mockOnUpdate = vi.fn()
const { result } = renderHook(() => usePluginAuthAction(pluginPayload, mockOnUpdate), {
wrapper: createWrapper(),
})
act(() => {
result.current.openConfirm('cred-1')
})
await act(async () => {
await result.current.handleConfirm()
})
expect(mockDeletePluginCredential).toHaveBeenCalledWith({ credential_id: 'cred-1' })
expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({ type: 'success' }))
expect(mockOnUpdate).toHaveBeenCalled()
expect(result.current.deleteCredentialId).toBeNull()
})
it('should handle set default credential', async () => {
const mockOnUpdate = vi.fn()
const { result } = renderHook(() => usePluginAuthAction(pluginPayload, mockOnUpdate), {
wrapper: createWrapper(),
})
await act(async () => {
await result.current.handleSetDefault('cred-1')
})
expect(mockSetPluginDefaultCredential).toHaveBeenCalledWith('cred-1')
expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({ type: 'success' }))
expect(mockOnUpdate).toHaveBeenCalled()
})
it('should handle rename credential', async () => {
const mockOnUpdate = vi.fn()
const { result } = renderHook(() => usePluginAuthAction(pluginPayload, mockOnUpdate), {
wrapper: createWrapper(),
})
await act(async () => {
await result.current.handleRename({
credential_id: 'cred-1',
name: 'New Name',
})
})
expect(mockUpdatePluginCredential).toHaveBeenCalledWith({
credential_id: 'cred-1',
name: 'New Name',
})
expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({ type: 'success' }))
expect(mockOnUpdate).toHaveBeenCalled()
})
it('prevents concurrent actions until the pending deletion completes', async () => {
const deletion = createDeferred<object>()
mockDeletePluginCredential.mockReturnValueOnce(deletion.promise)
const { result } = renderHook(() => usePluginAuthAction(pluginPayload), {
wrapper: createWrapper(),
})
act(() => result.current.openConfirm('cred-1'))
let pending: Promise<void>
act(() => {
pending = result.current.handleConfirm()
})
expect(result.current.doingAction).toBe(true)
await act(async () => {
await result.current.handleConfirm()
await result.current.handleSetDefault('cred-2')
await result.current.handleRename({ credential_id: 'cred-2', name: 'New name' })
})
expect(mockDeletePluginCredential).toHaveBeenCalledExactlyOnceWith({ credential_id: 'cred-1' })
expect(mockSetPluginDefaultCredential).not.toHaveBeenCalled()
expect(mockUpdatePluginCredential).not.toHaveBeenCalled()
await act(async () => {
deletion.resolve({})
await pending
})
expect(result.current.doingAction).toBe(false)
expect(result.current.deleteCredentialId).toBeNull()
})
it('should handle confirm without pending credential ID', async () => {
const { result } = renderHook(() => usePluginAuthAction(pluginPayload), {
wrapper: createWrapper(),
})
await act(async () => {
await result.current.handleConfirm()
})
expect(mockDeletePluginCredential).not.toHaveBeenCalled()
expect(result.current.deleteCredentialId).toBeNull()
})
})
@@ -0,0 +1,82 @@
import { renderHook } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { AuthCategory, CredentialTypeEnum } from '../../types'
import { usePluginAuth } from '../use-plugin-auth'
// Mock dependencies
const mockCredentials = [
{ id: '1', credential_type: CredentialTypeEnum.API_KEY, is_default: false },
{ id: '2', credential_type: CredentialTypeEnum.OAUTH2, is_default: true },
]
const mockCredentialInfo = vi.fn().mockReturnValue({
credentials: mockCredentials,
supported_credential_types: [CredentialTypeEnum.API_KEY, CredentialTypeEnum.OAUTH2],
allow_custom_token: true,
})
const mockInvalidate = vi.fn()
vi.mock('../use-credential', () => ({
useGetPluginCredentialInfoHook: (_payload: unknown, enable?: boolean) => ({
data: enable ? mockCredentialInfo() : undefined,
isLoading: false,
}),
useInvalidPluginCredentialInfoHook: () => mockInvalidate,
}))
const basePayload = {
category: AuthCategory.tool,
provider: 'test-provider',
}
describe('usePluginAuth', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('should return authorized state when credentials exist', () => {
const { result } = renderHook(() => usePluginAuth(basePayload, true))
expect(result.current.isAuthorized).toBe(true)
expect(result.current.credentials).toEqual(mockCredentials)
expect(result.current.canOAuth).toBe(true)
expect(result.current.canApiKey).toBe(true)
expect(result.current.notAllowCustomCredential).toBe(false)
})
it('should return unauthorized when enable is false', () => {
const { result } = renderHook(() => usePluginAuth(basePayload, false))
expect(result.current.isAuthorized).toBe(false)
expect(result.current.credentials).toEqual([])
})
it('should handle empty credentials', () => {
mockCredentialInfo.mockReturnValueOnce({
credentials: [],
supported_credential_types: [],
allow_custom_token: false,
})
const { result } = renderHook(() => usePluginAuth(basePayload, true))
expect(result.current.isAuthorized).toBe(false)
expect(result.current.canOAuth).toBe(false)
expect(result.current.canApiKey).toBe(false)
expect(result.current.notAllowCustomCredential).toBe(true)
})
it('should handle only API Key support', () => {
mockCredentialInfo.mockReturnValueOnce({
credentials: [{ id: '1' }],
supported_credential_types: [CredentialTypeEnum.API_KEY],
allow_custom_token: true,
})
const { result } = renderHook(() => usePluginAuth(basePayload, true))
expect(result.current.canApiKey).toBe(true)
expect(result.current.canOAuth).toBe(false)
})
})
@@ -0,0 +1,9 @@
import type { PluginPayload } from '../types'
import { AuthCategory } from '../types'
export const getApi = ({ category = AuthCategory.tool, provider }: PluginPayload) => ({
getCredentialInfo:
category === AuthCategory.tool
? `/workspaces/current/tool-provider/builtin/${provider}/credential/info`
: '',
})
@@ -0,0 +1,89 @@
import type { CredentialTypeEnum, PluginPayload } from '../types'
import { useQueryClient } from '@tanstack/react-query'
import { getToolListQueryKey } from '@/app/components/tools/utils/tool-list-query-key'
import {
useAddPluginCredential,
useDeletePluginCredential,
useDeletePluginOAuthCustomClient,
useGetPluginCredentialInfo,
useGetPluginCredentialSchema,
useGetPluginOAuthClientSchema,
useGetPluginOAuthUrl,
useInvalidPluginCredentialInfo,
useInvalidPluginOAuthClientSchema,
useSetPluginDefaultCredential,
useSetPluginOAuthCustomClient,
useUpdatePluginCredential,
} from '@/service/use-plugins-auth'
import { getApi } from './get-api'
export const useGetPluginCredentialInfoHook = (
pluginPayload: PluginPayload,
enable?: boolean,
includeCredentialIds?: string[],
) => {
const apiMap = getApi(pluginPayload)
const ids = (includeCredentialIds ?? []).filter(Boolean)
let url = enable ? apiMap.getCredentialInfo : ''
if (url && ids.length > 0) {
const qs = new URLSearchParams()
for (const id of ids) qs.append('include_credential_ids', id)
url = url + (url.includes('?') ? '&' : '?') + qs.toString()
}
return useGetPluginCredentialInfo(url)
}
export const useDeletePluginCredentialHook = (pluginPayload: PluginPayload) => {
return useDeletePluginCredential(pluginPayload)
}
export const useInvalidPluginCredentialInfoHook = (pluginPayload: PluginPayload) => {
const apiMap = getApi(pluginPayload)
const invalidPluginCredentialInfo = useInvalidPluginCredentialInfo(apiMap.getCredentialInfo)
const queryClient = useQueryClient()
const toolListQueryKey = getToolListQueryKey(pluginPayload.providerType)
return () => {
invalidPluginCredentialInfo()
if (toolListQueryKey) queryClient.invalidateQueries({ queryKey: toolListQueryKey })
}
}
export const useSetPluginDefaultCredentialHook = (pluginPayload: PluginPayload) => {
return useSetPluginDefaultCredential(pluginPayload)
}
export const useGetPluginCredentialSchemaHook = (
pluginPayload: PluginPayload,
credentialType: CredentialTypeEnum,
) => {
return useGetPluginCredentialSchema(pluginPayload, credentialType)
}
export const useAddPluginCredentialHook = (pluginPayload: PluginPayload) => {
return useAddPluginCredential(pluginPayload)
}
export const useUpdatePluginCredentialHook = (pluginPayload: PluginPayload) => {
return useUpdatePluginCredential(pluginPayload)
}
export const useGetPluginOAuthUrlHook = (pluginPayload: PluginPayload) => {
return useGetPluginOAuthUrl(pluginPayload)
}
export const useGetPluginOAuthClientSchemaHook = (pluginPayload: PluginPayload, enabled = true) => {
return useGetPluginOAuthClientSchema(pluginPayload, enabled)
}
export const useInvalidPluginOAuthClientSchemaHook = (pluginPayload: PluginPayload) => {
return useInvalidPluginOAuthClientSchema(pluginPayload)
}
export const useSetPluginOAuthCustomClientHook = (pluginPayload: PluginPayload) => {
return useSetPluginOAuthCustomClient(pluginPayload)
}
export const useDeletePluginOAuthCustomClientHook = (pluginPayload: PluginPayload) => {
return useDeletePluginOAuthCustomClient(pluginPayload)
}
@@ -0,0 +1,105 @@
import type { PluginPayload } from '../types'
import { useCallback, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import {
useDeletePluginCredentialHook,
useSetPluginDefaultCredentialHook,
useUpdatePluginCredentialHook,
} from '../hooks/use-credential'
export const usePluginAuthAction = (pluginPayload: PluginPayload, onUpdate?: () => void) => {
const { t } = useTranslation(['common'])
const pendingOperationCredentialId = useRef<string | null>(null)
const [deleteCredentialId, setDeleteCredentialId] = useState<string | null>(null)
const { mutateAsync: deletePluginCredential } = useDeletePluginCredentialHook(pluginPayload)
const openConfirm = useCallback((credentialId?: string) => {
if (credentialId) pendingOperationCredentialId.current = credentialId
setDeleteCredentialId(pendingOperationCredentialId.current)
}, [])
const closeConfirm = useCallback(() => {
setDeleteCredentialId(null)
pendingOperationCredentialId.current = null
}, [])
const [doingAction, setDoingAction] = useState(false)
const doingActionRef = useRef(doingAction)
const handleSetDoingAction = useCallback((doing: boolean) => {
doingActionRef.current = doing
setDoingAction(doing)
}, [])
const [editValues, setEditValues] = useState<Record<string, unknown> | null>(null)
const handleConfirm = useCallback(async () => {
if (doingActionRef.current) return
if (!pendingOperationCredentialId.current) {
setDeleteCredentialId(null)
return
}
try {
handleSetDoingAction(true)
await deletePluginCredential({ credential_id: pendingOperationCredentialId.current })
toast.success(t(($) => $['api.actionSuccess'], { ns: 'common' }))
onUpdate?.()
setDeleteCredentialId(null)
pendingOperationCredentialId.current = null
setEditValues(null)
} finally {
handleSetDoingAction(false)
}
}, [deletePluginCredential, onUpdate, t, handleSetDoingAction])
const handleEdit = useCallback((id: string, values: Record<string, unknown>) => {
pendingOperationCredentialId.current = id
setEditValues(values)
}, [])
const handleRemove = useCallback(() => {
setDeleteCredentialId(pendingOperationCredentialId.current)
}, [])
const { mutateAsync: setPluginDefaultCredential } =
useSetPluginDefaultCredentialHook(pluginPayload)
const handleSetDefault = useCallback(
async (id: string) => {
if (doingActionRef.current) return
try {
handleSetDoingAction(true)
await setPluginDefaultCredential(id)
toast.success(t(($) => $['api.actionSuccess'], { ns: 'common' }))
onUpdate?.()
} finally {
handleSetDoingAction(false)
}
},
[setPluginDefaultCredential, onUpdate, t, handleSetDoingAction],
)
const { mutateAsync: updatePluginCredential } = useUpdatePluginCredentialHook(pluginPayload)
const handleRename = useCallback(
async (payload: { credential_id: string; name: string }) => {
if (doingActionRef.current) return
try {
handleSetDoingAction(true)
await updatePluginCredential(payload)
toast.success(t(($) => $['api.actionSuccess'], { ns: 'common' }))
onUpdate?.()
} finally {
handleSetDoingAction(false)
}
},
[updatePluginCredential, t, handleSetDoingAction, onUpdate],
)
return {
doingAction,
handleSetDoingAction,
openConfirm,
closeConfirm,
deleteCredentialId,
setDeleteCredentialId,
handleConfirm,
editValues,
setEditValues,
handleEdit,
handleRemove,
handleSetDefault,
handleRename,
pendingOperationCredentialId,
}
}
@@ -0,0 +1,32 @@
import type { PluginPayload } from '../types'
import { CredentialTypeEnum } from '../types'
import {
useGetPluginCredentialInfoHook,
useInvalidPluginCredentialInfoHook,
} from './use-credential'
export const usePluginAuth = (
pluginPayload: PluginPayload,
enable?: boolean,
includeCredentialIds?: string[],
) => {
const { data, isLoading } = useGetPluginCredentialInfoHook(
pluginPayload,
enable,
includeCredentialIds,
)
const isAuthorized = !!data?.credentials.length
const canOAuth = data?.supported_credential_types.includes(CredentialTypeEnum.OAUTH2)
const canApiKey = data?.supported_credential_types.includes(CredentialTypeEnum.API_KEY)
const invalidPluginCredentialInfo = useInvalidPluginCredentialInfoHook(pluginPayload)
return {
isAuthorized,
canOAuth,
canApiKey,
isLoading,
credentials: data?.credentials || [],
notAllowCustomCredential: data?.allow_custom_token === false,
invalidPluginCredentialInfo,
}
}
@@ -0,0 +1,12 @@
export { default as AddApiKeyButton } from './authorize/add-api-key-button'
export { default as AddOAuthButton } from './authorize/add-oauth-button'
export { default as ApiKeyModal } from './authorize/api-key-modal'
export { default as Authorized } from './authorized'
export { default as AuthorizedInDataSourceNode } from './authorized-in-data-source-node'
export { default as AuthorizedInNode } from './authorized-in-node'
export { usePluginAuth } from './hooks/use-plugin-auth'
export * from './hooks/use-plugin-auth-action'
export { default as PluginAuth } from './plugin-auth'
export { default as PluginAuthInAgent } from './plugin-auth-in-agent'
export { default as PluginAuthInDataSourceNode } from './plugin-auth-in-datasource-node'
export * from './types'
@@ -0,0 +1,122 @@
import type { StatusDotStatus } from '@langgenius/dify-ui/status-dot'
import type { ComponentPropsWithRef } from 'react'
import type { Credential, PluginPayload } from './types'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { StatusDot } from '@langgenius/dify-ui/status-dot'
import { RiArrowDownSLine } from '@remixicon/react'
import { memo, useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Authorize from './authorize'
import Authorized from './authorized'
import { usePluginAuth } from './hooks/use-plugin-auth'
type PluginAuthInAgentProps = {
pluginPayload: PluginPayload
credentialId?: string
onAuthorizationItemClick?: (id: string) => void
}
const PluginAuthInAgent = ({
pluginPayload,
credentialId,
onAuthorizationItemClick,
}: PluginAuthInAgentProps) => {
const { t } = useTranslation(['plugin'])
const [isOpen, setIsOpen] = useState(false)
const {
isAuthorized,
canOAuth,
canApiKey,
credentials,
invalidPluginCredentialInfo,
notAllowCustomCredential,
} = usePluginAuth(pluginPayload, true, credentialId ? [credentialId] : undefined)
const extraAuthorizationItems: Credential[] = [
{
id: '__workspace_default__',
name: t(($) => $['auth.workspaceDefault'], { ns: 'plugin' }),
provider: '',
is_default: !credentialId,
isWorkspaceDefault: true,
},
]
const handleAuthorizationItemClick = useCallback(
(id: string) => {
onAuthorizationItemClick?.(id)
setIsOpen(false)
},
[onAuthorizationItemClick, setIsOpen],
)
const renderTrigger = useCallback(
(isOpen: boolean, triggerProps: ComponentPropsWithRef<'button'>) => {
let label = ''
let removed = false
let unavailable = false
let color: StatusDotStatus = 'success'
if (!credentialId) {
label = t(($) => $['auth.workspaceDefault'], { ns: 'plugin' })
} else {
const credential = credentials.find((c) => c.id === credentialId)
label = credential ? credential.name : t(($) => $['auth.authRemoved'], { ns: 'plugin' })
removed = !credential
unavailable = !!credential?.not_allowed_to_use && !credential?.from_enterprise
if (removed) color = 'error'
else if (unavailable) color = 'disabled'
}
return (
<Button
{...triggerProps}
className={cn(
triggerProps.className,
'w-full',
isOpen && 'bg-components-button-secondary-bg-hover',
removed && 'text-text-destructive',
)}
>
<StatusDot status={color} />
{label}
{unavailable && t(($) => $['auth.unavailable'], { ns: 'plugin' })}
<RiArrowDownSLine className="size-4" />
</Button>
)
},
[credentialId, credentials, t],
)
return (
<>
{!isAuthorized && (
<Authorize
pluginPayload={pluginPayload}
canOAuth={canOAuth}
canApiKey={canApiKey}
onUpdate={invalidPluginCredentialInfo}
notAllowCustomCredential={notAllowCustomCredential}
/>
)}
{isAuthorized && (
<Authorized
pluginPayload={pluginPayload}
credentials={credentials}
canOAuth={canOAuth}
canApiKey={canApiKey}
disableSetDefault
onItemClick={handleAuthorizationItemClick}
extraAuthorizationItems={extraAuthorizationItems}
showItemSelectedIcon
renderTrigger={renderTrigger}
isOpen={isOpen}
onOpenChange={setIsOpen}
selectedCredentialId={credentialId || '__workspace_default__'}
onUpdate={invalidPluginCredentialInfo}
notAllowCustomCredential={notAllowCustomCredential}
/>
)}
</>
)
}
export default memo(PluginAuthInAgent)
@@ -0,0 +1,33 @@
import type { ReactNode } from 'react'
import { Button } from '@langgenius/dify-ui/button'
import { RiAddLine } from '@remixicon/react'
import { memo } from 'react'
import { useTranslation } from 'react-i18next'
type PluginAuthInDataSourceNodeProps = {
children?: ReactNode
isAuthorized?: boolean
onJumpToDataSourcePage: () => void
}
const PluginAuthInDataSourceNode = ({
children,
isAuthorized,
onJumpToDataSourcePage,
}: PluginAuthInDataSourceNodeProps) => {
const { t } = useTranslation(['common'])
return (
<>
{!isAuthorized && (
<div className="px-4 pb-2">
<Button className="w-full" variant="primary" onClick={onJumpToDataSourcePage}>
<RiAddLine className="size-4" />
{t(($) => $['integrations.connect'], { ns: 'common' })}
</Button>
</div>
)}
{isAuthorized && children}
</>
)
}
export default memo(PluginAuthInDataSourceNode)
@@ -0,0 +1,98 @@
import type { PluginPayload } from './types'
import { cn } from '@langgenius/dify-ui/cn'
import { useQueryState } from 'nuqs'
import { memo } from 'react'
import { useTranslation } from 'react-i18next'
import {
settingsQueryParamName,
settingsQueryParser,
} from '@/app/components/header/account-setting/query-params'
import { useCredentialPermissions } from '@/hooks/use-credential-permissions'
import Authorize from './authorize'
import Authorized from './authorized'
import { usePluginAuth } from './hooks/use-plugin-auth'
import { AuthCategory } from './types'
type PluginAuthProps = {
pluginPayload: PluginPayload
children?: React.ReactNode
className?: string
}
const PluginAuth = ({ pluginPayload, children, className }: PluginAuthProps) => {
const { t } = useTranslation(['plugin'])
const [, setSettingsDestination] = useQueryState(settingsQueryParamName, settingsQueryParser)
const { canCreateCredential } = useCredentialPermissions()
const {
isAuthorized,
canOAuth,
canApiKey,
credentials,
invalidPluginCredentialInfo,
notAllowCustomCredential,
} = usePluginAuth(pluginPayload, !!pluginPayload.provider)
const showPermissionHint =
!isAuthorized &&
!canCreateCredential &&
!notAllowCustomCredential &&
pluginPayload.category === AuthCategory.tool &&
(canOAuth || canApiKey)
const authorizeContent = (
<Authorize
pluginPayload={pluginPayload}
canOAuth={canOAuth}
canApiKey={canApiKey}
onUpdate={invalidPluginCredentialInfo}
notAllowCustomCredential={notAllowCustomCredential}
/>
)
return (
<div className={cn(!isAuthorized && className)}>
{!isAuthorized && (
<>
{authorizeContent}
{showPermissionHint && (
<div className="mt-2 rounded-lg border border-divider-subtle bg-background-section-burn px-2.5 py-2">
<div className="flex items-start gap-2">
<span
aria-hidden
className="mt-0.5 i-ri-lock-2-line size-3.5 shrink-0 text-text-tertiary"
/>
<div className="min-w-0 grow">
<div className="system-xs-medium text-text-secondary">
{t(($) => $['auth.permissionHint.title'], { ns: 'plugin' })}
</div>
<div className="mt-0.5 system-xs-regular text-text-tertiary">
{t(($) => $['auth.permissionHint.description'], { ns: 'plugin' })}
</div>
<div className="mt-1.5">
<button
type="button"
className="-ml-1.5 rounded-md px-1.5 py-0.5 system-xs-medium text-text-accent hover:bg-state-base-hover focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden"
onClick={() => setSettingsDestination('members')}
>
{t(($) => $['auth.permissionHint.action'], { ns: 'plugin' })}
</button>
</div>
</div>
</div>
</div>
)}
</>
)}
{isAuthorized && !children && (
<Authorized
pluginPayload={pluginPayload}
credentials={credentials}
canOAuth={canOAuth}
canApiKey={canApiKey}
onUpdate={invalidPluginCredentialInfo}
notAllowCustomCredential={notAllowCustomCredential}
/>
)}
{isAuthorized && children}
</div>
)
}
export default memo(PluginAuth)
@@ -0,0 +1,50 @@
import type { CollectionProviderType } from '../../tools/types'
import type { PluginDetail } from '../types'
export type { AddApiKeyButtonProps } from './authorize/add-api-key-button'
export type { AddOAuthButtonProps } from './authorize/add-oauth-button'
export const AuthCategory = {
tool: 'tool',
datasource: 'datasource',
model: 'model',
trigger: 'trigger',
} as const
export type AuthCategory = (typeof AuthCategory)[keyof typeof AuthCategory]
export type PluginPayload = {
category: AuthCategory
provider: string
providerType?: CollectionProviderType
detail?: PluginDetail
}
export const CredentialTypeEnum = {
OAUTH2: 'oauth2',
API_KEY: 'api-key',
} as const
export type CredentialTypeEnum = (typeof CredentialTypeEnum)[keyof typeof CredentialTypeEnum]
export type Credential = {
id: string
name: string
provider: string
credential_type?: CredentialTypeEnum
is_default: boolean
credentials?: Record<string, unknown>
isWorkspaceDefault?: boolean
from_enterprise?: boolean
not_allowed_to_use?: boolean
visibility?: string
created_by?: string
partial_member_list?: string[]
/**
* True when the backend returned this credential only because the current node
* still references it, but the visibility filter would normally hide it
* (another member's `only_me` credential). The row warns that switching away
* prevents reselecting it and locks rename/edit/delete/set-default actions.
*/
from_other_member?: boolean
}