Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { COUNT_DOWN_KEY, COUNT_DOWN_TIME_MS } from '@/app/components/signin/storage'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import MailAndCodeAuth from '../mail-and-code-auth'
type TurnstileOptions = {
sitekey: string
action: string
callback: (token: string) => void
'error-callback': (errorCode: string) => boolean
'expired-callback': () => void
'timeout-callback': () => void
}
const mocks = vi.hoisted(() => ({
push: vi.fn(),
remove: vi.fn(),
render: vi.fn(),
sendEMailLoginCode: vi.fn(),
turnstileSiteKey: 'site-key-for-tests',
}))
let turnstileOptions: TurnstileOptions | undefined
const renderMailAndCodeAuth = (deploymentEdition: 'CLOUD' | 'COMMUNITY' = 'CLOUD') =>
renderWithConsoleQuery(<MailAndCodeAuth isInvite={false} />, {
systemFeatures: { deployment_edition: deploymentEdition },
})
vi.mock('@/next/script', async () => {
const { useEffect } = await vi.importActual<typeof import('react')>('react')
function ScriptMock({ onReady }: { onReady?: () => void }) {
useEffect(() => {
onReady?.()
}, [onReady])
return null
}
return {
default: ScriptMock,
}
})
vi.mock('@/next/navigation', () => ({
useRouter: () => ({ push: mocks.push }),
useSearchParams: () => new URLSearchParams(),
}))
vi.mock('@/config', async () => {
const actual = await vi.importActual<typeof import('@/config')>('@/config')
return {
...actual,
get TURNSTILE_SITE_KEY() {
return mocks.turnstileSiteKey
},
}
})
vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
const { withConsoleClientResponses } = await import('@/test/console/service-responses')
return {
...actual,
consoleClient: withConsoleClientResponses(actual.consoleClient, {
'emailCodeLogin.post': mocks.sendEMailLoginCode,
}),
}
})
describe('MailAndCodeAuth', () => {
beforeEach(() => {
vi.resetAllMocks()
localStorage.removeItem(COUNT_DOWN_KEY)
turnstileOptions = undefined
mocks.turnstileSiteKey = 'site-key-for-tests'
mocks.render.mockImplementation((_container: HTMLElement, options: TurnstileOptions) => {
turnstileOptions = options
return 'widget-id'
})
mocks.sendEMailLoginCode.mockResolvedValue({ result: 'success', data: 'login-token' })
vi.stubGlobal('turnstile', { remove: mocks.remove, render: mocks.render })
})
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
localStorage.removeItem(COUNT_DOWN_KEY)
})
it('enables SaaS email-code login only while Turnstile verification is valid', async () => {
const user = userEvent.setup()
renderMailAndCodeAuth()
await user.type(screen.getByRole('textbox', { name: 'login.email' }), '[email protected]')
const continueButton = screen.getByRole('button', { name: 'login.signup.verifyMail' })
await waitFor(() => {
expect(mocks.render).toHaveBeenCalledTimes(1)
})
expect(turnstileOptions).toMatchObject({
sitekey: 'site-key-for-tests',
action: 'signin_code',
})
expect(continueButton).toBeDisabled()
act(() => {
turnstileOptions?.callback('turnstile-token')
})
expect(continueButton).toBeEnabled()
act(() => {
turnstileOptions?.['expired-callback']()
})
expect(continueButton).toBeDisabled()
act(() => {
turnstileOptions?.callback('fresh-turnstile-token')
turnstileOptions?.['error-callback']('network-error')
})
expect(continueButton).toBeDisabled()
act(() => {
turnstileOptions?.callback('another-turnstile-token')
turnstileOptions?.['timeout-callback']()
})
expect(continueButton).toBeDisabled()
})
it('submits the SaaS email-code login after Turnstile verification succeeds', async () => {
const user = userEvent.setup()
renderMailAndCodeAuth()
await user.type(screen.getByRole('textbox', { name: 'login.email' }), '[email protected]')
await waitFor(() => {
expect(turnstileOptions).toBeDefined()
})
act(() => {
turnstileOptions?.callback('turnstile-token')
})
await user.click(screen.getByRole('button', { name: 'login.signup.verifyMail' }))
await waitFor(() => {
expect(mocks.sendEMailLoginCode).toHaveBeenCalledWith({
body: { email: '[email protected]', language: 'en-US', turnstile_token: 'turnstile-token' },
})
})
expect(localStorage.getItem(COUNT_DOWN_KEY)).toBe(String(COUNT_DOWN_TIME_MS))
const destination = new URL(mocks.push.mock.calls[0]![0], 'https://dify.test')
expect(destination.pathname).toBe('/signin/check-code')
expect(decodeURIComponent(destination.searchParams.get('email')!)).toBe('[email protected]')
})
it('requires a fresh Turnstile token after an email-code request fails', async () => {
const user = userEvent.setup()
vi.spyOn(console, 'error').mockImplementation(() => {})
mocks.sendEMailLoginCode
.mockRejectedValueOnce(new Error('email send failed'))
.mockResolvedValueOnce({ result: 'success', data: 'login-token' })
renderMailAndCodeAuth()
await user.type(screen.getByRole('textbox', { name: 'login.email' }), '[email protected]')
await waitFor(() => {
expect(turnstileOptions).toBeDefined()
})
act(() => {
turnstileOptions?.callback('consumed-turnstile-token')
})
const continueButton = screen.getByRole('button', { name: 'login.signup.verifyMail' })
await user.click(continueButton)
await waitFor(() => {
expect(mocks.sendEMailLoginCode).toHaveBeenCalledWith({
body: {
email: '[email protected]',
language: 'en-US',
turnstile_token: 'consumed-turnstile-token',
},
})
})
await waitFor(() => {
expect(continueButton).toBeDisabled()
expect(mocks.render).toHaveBeenCalledTimes(2)
})
act(() => {
turnstileOptions?.callback('fresh-turnstile-token')
})
expect(continueButton).toBeEnabled()
await user.click(continueButton)
await waitFor(() => {
expect(mocks.sendEMailLoginCode).toHaveBeenLastCalledWith({
body: {
email: '[email protected]',
language: 'en-US',
turnstile_token: 'fresh-turnstile-token',
},
})
})
expect(mocks.push).toHaveBeenCalledWith(expect.stringContaining('/signin/check-code?'))
})
it('keeps non-SaaS email-code login independent of Turnstile', async () => {
const user = userEvent.setup()
renderMailAndCodeAuth('COMMUNITY')
await user.type(screen.getByRole('textbox', { name: 'login.email' }), '[email protected]')
expect(screen.getByRole('button', { name: 'login.signup.verifyMail' })).toBeEnabled()
expect(mocks.render).not.toHaveBeenCalled()
})
it('associates one localized error with an invalid email', async () => {
const user = userEvent.setup()
renderMailAndCodeAuth('COMMUNITY')
const emailInput = screen.getByRole('textbox', { name: 'login.email' })
await user.type(emailInput, 'invalid-email{Enter}')
const errors = await screen.findAllByText('login.error.emailInValid')
expect(errors).toHaveLength(1)
expect(emailInput).toHaveAttribute('aria-invalid', 'true')
expect(emailInput).toHaveAccessibleDescription('login.error.emailInValid')
expect(mocks.sendEMailLoginCode).not.toHaveBeenCalled()
})
it('keeps SaaS email-code login disabled when the Turnstile site key is missing', async () => {
const user = userEvent.setup()
mocks.turnstileSiteKey = ''
renderMailAndCodeAuth()
await user.type(screen.getByRole('textbox', { name: 'login.email' }), '[email protected]')
expect(screen.getByRole('button', { name: 'login.signup.verifyMail' })).toBeDisabled()
expect(mocks.render).not.toHaveBeenCalled()
})
})