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,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