数据源配置可发起钉钉官方设备授权、重新授权和取消,完成后刷新共享账号状态并独立检查目录权限。 授权会话限定发起的管理员登录会话,令牌由现有 CLI 存储,取消等待子进程退出。 验证:完整 make verify 通过;前端 582 项、Go 1545 项通过,487 项声明的可选集成未运行。 授权处理器与 HTTP 边界通过 race 检查;本人钉钉授权仍由管理员在官方页面完成。
This commit is contained in:
@@ -0,0 +1,167 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { DWSAccount } from './DWSAccount'
|
||||
const id = 'a'.repeat(32)
|
||||
const session = {
|
||||
id,
|
||||
state: 'waiting',
|
||||
verification_url: 'https://login.dingtalk.com/oauth2/device/verify.htm?user_code=TEST-CODE',
|
||||
user_code: 'TEST-CODE',
|
||||
expires_at: '2099-01-01T01:00:00Z',
|
||||
}
|
||||
const json = (data: unknown, status = 200) => new Response(JSON.stringify({ data }), { status })
|
||||
let root: Root
|
||||
let container: HTMLDivElement
|
||||
let fetcher: ReturnType<typeof vi.fn<(path: string, init?: RequestInit) => Promise<Response>>>
|
||||
const flush = async () => {
|
||||
await act(async () => {
|
||||
await Promise.resolve()
|
||||
})
|
||||
}
|
||||
const click = async (label: string) => {
|
||||
const button = Array.from(container.querySelectorAll('button')).find((x) => x.textContent === label)
|
||||
expect(button, label).toBeTruthy()
|
||||
await act(async () => button!.click())
|
||||
}
|
||||
beforeEach(() => {
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
|
||||
vi.useFakeTimers()
|
||||
container = document.createElement('div')
|
||||
document.body.append(container)
|
||||
root = createRoot(container)
|
||||
fetcher = vi.fn((path: string, init?: RequestInit) => {
|
||||
if (path.endsWith('credential-status'))
|
||||
return Promise.resolve(json({ authenticated: false, refresh_token_valid: false }))
|
||||
if (path === '/api/v1/dws-login') return Promise.resolve(json(session, 202))
|
||||
if (path.startsWith('/api/v1/dws-login/'))
|
||||
return Promise.resolve(json({ ...session, state: init?.method === 'DELETE' ? 'cancelled' : 'waiting' }))
|
||||
if (path.endsWith('/available'))
|
||||
return Promise.resolve(json({ knowledge_bases: [], drive_spaces: [], fetched_at: '2026-11-17T09:00:00Z' }))
|
||||
throw new Error(`unexpected ${path}`)
|
||||
})
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
})
|
||||
afterEach(async () => {
|
||||
await act(async () => root.unmount())
|
||||
container.remove()
|
||||
vi.useRealTimers()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
const mount = async () => {
|
||||
await act(async () => root.render(<DWSAccount />))
|
||||
await flush()
|
||||
}
|
||||
|
||||
describe('DWS device authorization', () => {
|
||||
it('opens the official challenge and cancellation removes it', async () => {
|
||||
await mount()
|
||||
await click('登录授权')
|
||||
expect(container.querySelector('[role="dialog"]')).not.toBeNull()
|
||||
expect(container.querySelector('a')?.href).toBe(session.verification_url)
|
||||
expect(container.textContent).toContain('TEST-CODE')
|
||||
await click('取消授权')
|
||||
expect(container.querySelector('[role="dialog"]')).toBeNull()
|
||||
expect(fetcher.mock.calls.some(([path, init]) => path.endsWith(id) && init?.method === 'DELETE')).toBe(true)
|
||||
})
|
||||
it('refreshes identity after login and independently reports failed directory access', async () => {
|
||||
let authorized = false
|
||||
fetcher.mockImplementation((path: string, init?: RequestInit) => {
|
||||
if (path.endsWith('credential-status'))
|
||||
return Promise.resolve(
|
||||
json({
|
||||
authenticated: authorized,
|
||||
refresh_token_valid: authorized,
|
||||
corp_name: '测试组织',
|
||||
user_name: '测试账号',
|
||||
})
|
||||
)
|
||||
if (path === '/api/v1/dws-login') return Promise.resolve(json(session, 202))
|
||||
if (path.endsWith('/available'))
|
||||
return Promise.resolve(new Response(JSON.stringify({ error: '目录权限不足' }), { status: 503 }))
|
||||
if (init?.method === 'DELETE') return Promise.resolve(json({ ...session, state: 'cancelled' }))
|
||||
authorized = true
|
||||
return Promise.resolve(json({ ...session, state: 'succeeded', verification_url: '', user_code: '' }))
|
||||
})
|
||||
await mount()
|
||||
await click('登录授权')
|
||||
await act(async () => vi.advanceTimersByTimeAsync(1500))
|
||||
await flush()
|
||||
expect(container.querySelector('[role="dialog"]')).toBeNull()
|
||||
expect(container.textContent).toContain('DWS 登录成功')
|
||||
expect(container.textContent).toContain('测试账号 · 测试组织')
|
||||
expect(container.textContent).toContain('目录连接检查未通过:目录权限不足')
|
||||
expect(container.textContent).not.toContain('目录连接正常')
|
||||
})
|
||||
it('reports partial directory access without claiming full connection success', async () => {
|
||||
const fallback = fetcher.getMockImplementation()!
|
||||
fetcher.mockImplementation((path: string, init?: RequestInit) =>
|
||||
path.endsWith('/available')
|
||||
? Promise.resolve(
|
||||
json({
|
||||
knowledge_bases: [{}],
|
||||
drive_spaces: [],
|
||||
knowledge_notice: '个人知识库权限不足',
|
||||
fetched_at: '2026-11-17T09:00:00Z',
|
||||
})
|
||||
)
|
||||
: fallback(path, init)
|
||||
)
|
||||
await mount()
|
||||
await click('检查连接')
|
||||
expect(container.textContent).toContain('目录部分可用')
|
||||
expect(container.textContent).toContain('个人知识库权限不足')
|
||||
expect(container.textContent).not.toContain('目录连接正常')
|
||||
expect(fetcher.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false)
|
||||
})
|
||||
it('shows backend startup errors and provides retry', async () => {
|
||||
const fallback = fetcher.getMockImplementation()!
|
||||
fetcher.mockImplementation((path: string, init?: RequestInit) =>
|
||||
path === '/api/v1/dws-login'
|
||||
? Promise.resolve(new Response(JSON.stringify({ error: '另一位管理员正在授权' }), { status: 409 }))
|
||||
: fallback(path, init)
|
||||
)
|
||||
await mount()
|
||||
await click('登录授权')
|
||||
expect(container.textContent).toContain('另一位管理员正在授权')
|
||||
expect(Array.from(container.querySelectorAll('button')).some((x) => x.textContent === '重试')).toBe(true)
|
||||
})
|
||||
it('cancels a session returned after its dialog was closed during startup', async () => {
|
||||
let resolve!: (response: Response) => void
|
||||
const fallback = fetcher.getMockImplementation()!
|
||||
fetcher.mockImplementation((path: string, init?: RequestInit) =>
|
||||
path === '/api/v1/dws-login'
|
||||
? new Promise<Response>((done) => {
|
||||
resolve = done
|
||||
})
|
||||
: fallback(path, init)
|
||||
)
|
||||
await mount()
|
||||
await click('登录授权')
|
||||
await click('取消授权')
|
||||
await act(async () => resolve(json(session, 202)))
|
||||
await flush()
|
||||
expect(container.querySelector('[role="dialog"]')).toBeNull()
|
||||
expect(fetcher.mock.calls.some(([path, init]) => path.endsWith(id) && init?.method === 'DELETE')).toBe(true)
|
||||
})
|
||||
it('does not reopen a cancelled dialog when a late poll succeeds', async () => {
|
||||
let resolve!: (response: Response) => void
|
||||
const fallback = fetcher.getMockImplementation()!
|
||||
fetcher.mockImplementation((path: string, init?: RequestInit) =>
|
||||
path.endsWith(id) && init?.method === 'GET'
|
||||
? new Promise<Response>((done) => {
|
||||
resolve = done
|
||||
})
|
||||
: fallback(path, init)
|
||||
)
|
||||
await mount()
|
||||
await click('登录授权')
|
||||
await act(async () => vi.advanceTimersByTimeAsync(1500))
|
||||
await click('取消授权')
|
||||
await act(async () => resolve(json({ ...session, state: 'succeeded' })))
|
||||
await flush()
|
||||
expect(container.querySelector('[role="dialog"]')).toBeNull()
|
||||
expect(container.textContent).not.toContain('DWS 登录成功')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,12 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { DingtalkAccountStatus } from './SourceManagement'
|
||||
|
||||
describe('DWS account entry', () => {
|
||||
it('offers device login and a separate connection check beside account status', () => {
|
||||
const html = renderToStaticMarkup(<DingtalkAccountStatus />)
|
||||
expect(html).toContain('登录授权')
|
||||
expect(html).toContain('检查连接')
|
||||
expect(html).not.toContain('扫码刷新会话')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,286 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
cancelDWSLogin,
|
||||
checkDWSConnection,
|
||||
dwsLoginActive,
|
||||
fetchDWSCredentials,
|
||||
fetchDWSLogin,
|
||||
startDWSLogin,
|
||||
} from './dwsLogin'
|
||||
import type { DWSCredentials, DWSLogin } from './dwsLogin'
|
||||
|
||||
const messageOf = (cause: unknown) => (cause instanceof Error ? cause.message : '请求失败,请重试')
|
||||
const moment = (value: string) => new Date(value).toLocaleString('zh-CN', { hour12: false })
|
||||
|
||||
export function DWSAccount() {
|
||||
const [credentials, setCredentials] = useState<DWSCredentials | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState('')
|
||||
const [notice, setNotice] = useState('')
|
||||
const [connection, setConnection] = useState<Awaited<ReturnType<typeof checkDWSConnection>> | null>(null)
|
||||
const [checking, setChecking] = useState(false)
|
||||
const [session, setSession] = useState<DWSLogin | null>(null)
|
||||
const [open, setOpen] = useState(false)
|
||||
const [starting, setStarting] = useState(false)
|
||||
const [loginError, setLoginError] = useState('')
|
||||
const id = useRef('')
|
||||
const generation = useRef(0)
|
||||
const mounted = useRef(false)
|
||||
const handled = useRef('')
|
||||
const action = useRef<AbortController | null>(null)
|
||||
const checkAction = useRef<AbortController | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
mounted.current = true
|
||||
const controller = new AbortController()
|
||||
void fetchDWSCredentials(controller.signal)
|
||||
.then(setCredentials)
|
||||
.catch((cause) => {
|
||||
if (!controller.signal.aborted) setError(messageOf(cause))
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) setLoading(false)
|
||||
})
|
||||
return () => {
|
||||
mounted.current = false
|
||||
controller.abort()
|
||||
action.current?.abort()
|
||||
checkAction.current?.abort()
|
||||
generation.current++
|
||||
if (id.current) void cancelDWSLogin(id.current).catch(() => undefined)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const check = useCallback(async () => {
|
||||
checkAction.current?.abort()
|
||||
const controller = new AbortController()
|
||||
checkAction.current = controller
|
||||
setChecking(true)
|
||||
setConnection(null)
|
||||
setError('')
|
||||
try {
|
||||
const result = await checkDWSConnection(controller.signal)
|
||||
const fresh = await fetchDWSCredentials(controller.signal)
|
||||
if (!controller.signal.aborted && mounted.current) {
|
||||
setConnection(result)
|
||||
setCredentials(fresh)
|
||||
}
|
||||
} catch (cause) {
|
||||
if (!controller.signal.aborted && mounted.current) setError(`目录连接检查未通过:${messageOf(cause)}`)
|
||||
} finally {
|
||||
if (!controller.signal.aborted && mounted.current) setChecking(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const start = async () => {
|
||||
const current = ++generation.current
|
||||
action.current?.abort()
|
||||
checkAction.current?.abort()
|
||||
setChecking(false)
|
||||
const controller = new AbortController()
|
||||
action.current = controller
|
||||
setOpen(true)
|
||||
setStarting(true)
|
||||
setSession(null)
|
||||
setLoginError('')
|
||||
setNotice('')
|
||||
setConnection(null)
|
||||
setError('')
|
||||
try {
|
||||
const next = await startDWSLogin(controller.signal)
|
||||
if (!mounted.current || current !== generation.current) {
|
||||
void cancelDWSLogin(next.id).catch(() => undefined)
|
||||
return
|
||||
}
|
||||
id.current = next.id
|
||||
setSession(next)
|
||||
} catch (cause) {
|
||||
if (mounted.current && current === generation.current) setLoginError(messageOf(cause))
|
||||
} finally {
|
||||
if (mounted.current && current === generation.current) setStarting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const close = async () => {
|
||||
const current = generation.current
|
||||
const sessionID = id.current
|
||||
setLoginError('')
|
||||
if (!sessionID && starting) {
|
||||
// Keep the POST alive so its returned session can be cancelled by ID.
|
||||
++generation.current
|
||||
setOpen(false)
|
||||
setStarting(false)
|
||||
return
|
||||
}
|
||||
if (sessionID && session && dwsLoginActive(session.state)) {
|
||||
try {
|
||||
await cancelDWSLogin(sessionID)
|
||||
} catch (cause) {
|
||||
if (mounted.current && generation.current === current) setLoginError(`取消未完成:${messageOf(cause)}`)
|
||||
return
|
||||
}
|
||||
}
|
||||
if (mounted.current && generation.current === current) {
|
||||
++generation.current
|
||||
id.current = ''
|
||||
setOpen(false)
|
||||
setSession(null)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!session || !dwsLoginActive(session.state) || loginError) return
|
||||
const controller = new AbortController()
|
||||
const current = generation.current
|
||||
const timer = window.setTimeout(() => {
|
||||
void fetchDWSLogin(session.id, controller.signal)
|
||||
.then((next) => {
|
||||
if (!controller.signal.aborted && current === generation.current) setSession(next)
|
||||
})
|
||||
.catch((cause) => {
|
||||
if (!controller.signal.aborted && current === generation.current) setLoginError(messageOf(cause))
|
||||
})
|
||||
}, 1500)
|
||||
return () => {
|
||||
window.clearTimeout(timer)
|
||||
controller.abort()
|
||||
}
|
||||
}, [session, loginError])
|
||||
|
||||
useEffect(() => {
|
||||
if (session?.state !== 'succeeded' || handled.current === session.id) return
|
||||
handled.current = session.id
|
||||
const current = generation.current
|
||||
id.current = ''
|
||||
setOpen(false)
|
||||
setNotice('DWS 登录成功,正在检查目录连接…')
|
||||
void fetchDWSCredentials()
|
||||
.then((fresh) => {
|
||||
if (!mounted.current || current !== generation.current) return
|
||||
setCredentials(fresh)
|
||||
setNotice('DWS 登录成功')
|
||||
void check()
|
||||
})
|
||||
.catch((cause) => {
|
||||
if (mounted.current && current === generation.current) setError(`授权成功,状态刷新失败:${messageOf(cause)}`)
|
||||
})
|
||||
}, [session, check])
|
||||
|
||||
const status = loading
|
||||
? '读取中…'
|
||||
: error && !credentials
|
||||
? '状态读取失败'
|
||||
: !credentials?.status_known
|
||||
? '登录状态待核验'
|
||||
: !credentials.authenticated
|
||||
? '未登录'
|
||||
: credentials.refresh_token_valid
|
||||
? '已登录'
|
||||
: '凭证需更新'
|
||||
const busy = starting || Boolean(session && dwsLoginActive(session.state))
|
||||
const labels: Record<DWSLogin['state'], string> = {
|
||||
starting: '正在生成授权入口…',
|
||||
waiting: '请打开钉钉授权页,确认本次登录。完成后此页会自动更新。',
|
||||
verifying: '已收到授权,正在验证并保存登录状态…',
|
||||
succeeded: '登录成功',
|
||||
expired: '授权已过期,请重新发起。',
|
||||
failed: '授权未完成,请重试。',
|
||||
cancelled: '授权已取消。',
|
||||
}
|
||||
return (
|
||||
<section className="source-account" aria-label="钉钉账号(DWS)">
|
||||
<div className="dws-account-heading">
|
||||
<div>
|
||||
<strong>钉钉账号(DWS) · {status}</strong>
|
||||
{credentials?.authenticated ? (
|
||||
<div>
|
||||
{[credentials.user_name, credentials.corp_name].filter(Boolean).join(' · ') || '账号信息暂未返回'}
|
||||
</div>
|
||||
) : null}
|
||||
{credentials?.authenticated && credentials.refresh_expires_at ? (
|
||||
<small>授权有效期至 {moment(credentials.refresh_expires_at)}</small>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="row-actions">
|
||||
<button onClick={() => void start()} disabled={busy}>
|
||||
{busy ? '授权进行中…' : credentials?.authenticated ? '重新授权' : '登录授权'}
|
||||
</button>
|
||||
<button className="secondary" onClick={() => void check()} disabled={checking || busy}>
|
||||
{checking ? '检查中…' : '检查连接'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<small>所有钉钉来源共用此账号。登录后检查知识库与钉盘的实际访问权限。</small>
|
||||
{notice ? (
|
||||
<p role="status" className="success-message">
|
||||
{notice}
|
||||
</p>
|
||||
) : null}
|
||||
{error ? (
|
||||
<p role="alert" className="error-message">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
{connection ? (
|
||||
<div role="status">
|
||||
<p className={connection.notices.length ? 'hint' : 'success-message'}>
|
||||
{connection.notices.length ? '目录部分可用' : '目录连接正常'}:{connection.message} · 检查于{' '}
|
||||
{moment(connection.checkedAt)}
|
||||
</p>
|
||||
{connection.notices.map((value) => (
|
||||
<p className="hint" key={value}>
|
||||
{value}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
{open ? (
|
||||
<div className="modal-backdrop" role="dialog" aria-modal="true" aria-label="DWS 登录授权">
|
||||
<div className="modal-card dws-login-card">
|
||||
<h3>DWS 登录授权</h3>
|
||||
<p role="status">{starting ? '正在生成授权入口…' : session ? labels[session.state] : '授权入口生成失败'}</p>
|
||||
{session?.state === 'waiting' && session.verification_url ? (
|
||||
<>
|
||||
<a
|
||||
className="primary-action dws-authorize-link"
|
||||
href={session.verification_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
referrerPolicy="no-referrer"
|
||||
>
|
||||
打开钉钉授权页
|
||||
</a>
|
||||
<p>
|
||||
若授权页要求输入授权码:<code className="dws-user-code">{session.user_code}</code>
|
||||
</p>
|
||||
<small>本次授权有效期至 {moment(session.expires_at)}</small>
|
||||
</>
|
||||
) : null}
|
||||
{session?.error ? (
|
||||
<p role="alert" className="error-message">
|
||||
{session.error}
|
||||
</p>
|
||||
) : null}
|
||||
{loginError ? (
|
||||
<p role="alert" className="error-message">
|
||||
{loginError}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="row-actions">
|
||||
{session && !dwsLoginActive(session.state) ? (
|
||||
<button onClick={() => void start()}>重新发起授权</button>
|
||||
) : null}
|
||||
{loginError && session && dwsLoginActive(session.state) ? (
|
||||
<button onClick={() => setLoginError('')}>重试读取状态</button>
|
||||
) : null}
|
||||
{!starting && !session ? <button onClick={() => void start()}>重试</button> : null}
|
||||
<button className="secondary" onClick={() => void close()}>
|
||||
{busy ? '取消授权' : '关闭'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -23,9 +23,32 @@
|
||||
margin: 0 0 14px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.source-account > button {
|
||||
padding: 5px 0;
|
||||
color: var(--ink-mute);
|
||||
.dws-account-heading {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.dws-account-heading strong {
|
||||
display: block;
|
||||
margin-bottom: 6px;
|
||||
font-size: 14px;
|
||||
}
|
||||
.dws-login-card {
|
||||
width: min(480px, calc(100vw - 40px));
|
||||
}
|
||||
.dws-authorize-link {
|
||||
display: inline-block;
|
||||
margin: 8px 0;
|
||||
}
|
||||
.dws-user-code {
|
||||
font-size: 18px;
|
||||
letter-spacing: 2px;
|
||||
}
|
||||
.dws-login-card .row-actions {
|
||||
margin-top: 20px;
|
||||
}
|
||||
.source-account-detail {
|
||||
padding: 12px 16px;
|
||||
|
||||
@@ -21,42 +21,7 @@ const choices = [
|
||||
]
|
||||
const errorText = (error: unknown) => (error instanceof Error ? error.message : '操作失败,请重试')
|
||||
|
||||
export function DingtalkAccountStatus() {
|
||||
const [status, setStatus] = useState('读取中…')
|
||||
const [expires, setExpires] = useState('')
|
||||
useEffect(() => {
|
||||
const controller = new AbortController()
|
||||
void fetch('/api/v1/dingtalk-spaces/credential-status', {
|
||||
headers: { Accept: 'application/json' },
|
||||
signal: controller.signal,
|
||||
})
|
||||
.then(async (response) => {
|
||||
if (!response.ok) throw new Error('读取失败')
|
||||
const value = await response.json()
|
||||
const data = value.data
|
||||
if (!data || typeof data.authenticated !== 'boolean' || typeof data.refresh_token_valid !== 'boolean')
|
||||
throw new Error('状态格式错误')
|
||||
if (controller.signal.aborted) return
|
||||
setStatus(!data.authenticated ? '未登录' : data.refresh_token_valid ? '已登录' : '凭证需更新')
|
||||
setExpires(data.authenticated && typeof data.refresh_expires_at === 'string' ? data.refresh_expires_at : '')
|
||||
})
|
||||
.catch(() => {
|
||||
if (!controller.signal.aborted) setStatus('状态读取失败')
|
||||
})
|
||||
return () => controller.abort()
|
||||
}, [])
|
||||
return (
|
||||
<div className="source-account" role="status">
|
||||
<span>DWS 凭证 · {status}</span>
|
||||
{expires ? (
|
||||
<small> · 续期凭证有效期至 {new Date(expires).toLocaleString('zh-CN', { hour12: false })}</small>
|
||||
) : null}
|
||||
<div>
|
||||
<small>仅显示本地凭证状态,不检测目录权限或业务接口。</small>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export { DWSAccount as DingtalkAccountStatus } from './DWSAccount'
|
||||
|
||||
export function SourceSettingsCard({
|
||||
connection,
|
||||
|
||||
@@ -574,7 +574,9 @@ describe('SystemSettingsView 数据源配置的默认清单', () => {
|
||||
expect(html).toContain('aria-expanded="false"')
|
||||
expect(html).toContain('仅手动刷新')
|
||||
expect(html).toContain('数据源设置审计')
|
||||
expect((html.match(/DWS 凭证 ·/g) ?? []).length).toBe(1)
|
||||
expect((html.match(/aria-label="钉钉账号(DWS)"/g) ?? []).length).toBe(1)
|
||||
expect(html).toContain('登录授权')
|
||||
expect(html).toContain('检查连接')
|
||||
for (const removed of ['+ 新增钉钉知识库', '文件格式筛选']) expect(html).not.toContain(removed)
|
||||
// 文档工程师看不到添加向导与「去掉来源」:两者都是管理员动作。
|
||||
const engineer = view('engineer')
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { checkDWSConnection, fetchDWSCredentials, startDWSLogin, validDWSAuthorizationURL } from './dwsLogin'
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
describe('DWS transport boundaries', () => {
|
||||
it('accepts only the official device verification URL', () => {
|
||||
expect(validDWSAuthorizationURL('https://login.dingtalk.com/oauth2/device/verify.htm?user_code=TEST')).toBe(true)
|
||||
for (const value of [
|
||||
'javascript:alert(1)',
|
||||
'http://login.dingtalk.com/oauth2/device/verify.htm',
|
||||
'https://login.dingtalk.com.evil.invalid/oauth2/device/verify.htm',
|
||||
'https://login.dingtalk.com/other',
|
||||
])
|
||||
expect(validDWSAuthorizationURL(value)).toBe(false)
|
||||
})
|
||||
it('keeps backend errors from a real single-use response', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(new Response(JSON.stringify({ error: 'DWS 登录服务未接通' }), { status: 503 }))
|
||||
)
|
||||
await expect(startDWSLogin()).rejects.toThrow('DWS 登录服务未接通')
|
||||
})
|
||||
it('rejects missing or hostile session data', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
data: {
|
||||
id: 'a'.repeat(32),
|
||||
state: 'waiting',
|
||||
expires_at: '2099-01-01T00:00:00Z',
|
||||
verification_url: 'https://evil.invalid/',
|
||||
},
|
||||
})
|
||||
)
|
||||
)
|
||||
)
|
||||
await expect(startDWSLogin()).rejects.toThrow('不是钉钉官方地址')
|
||||
})
|
||||
it('does not treat an invalid directory envelope as a successful empty result', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: {} }))))
|
||||
await expect(checkDWSConnection()).rejects.toThrow('未取得有效目录检查结果')
|
||||
})
|
||||
it('returns only safe credential metadata', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
data: {
|
||||
authenticated: true,
|
||||
refresh_token_valid: true,
|
||||
corp_name: '测试组织',
|
||||
user_name: '测试账号',
|
||||
access_token: 'do-not-return',
|
||||
},
|
||||
})
|
||||
)
|
||||
)
|
||||
)
|
||||
const result = await fetchDWSCredentials()
|
||||
expect(result.corp_name).toBe('测试组织')
|
||||
expect(JSON.stringify(result)).not.toContain('do-not-return')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,101 @@
|
||||
export interface DWSCredentials {
|
||||
authenticated: boolean
|
||||
refresh_token_valid: boolean
|
||||
status_known: boolean
|
||||
corp_name: string
|
||||
user_name: string
|
||||
refresh_expires_at: string
|
||||
}
|
||||
export type DWSLoginState = 'starting' | 'waiting' | 'verifying' | 'succeeded' | 'failed' | 'expired' | 'cancelled'
|
||||
export interface DWSLogin {
|
||||
id: string
|
||||
state: DWSLoginState
|
||||
verification_url: string
|
||||
user_code: string
|
||||
expires_at: string
|
||||
error: string
|
||||
}
|
||||
const states = new Set(['starting', 'waiting', 'verifying', 'succeeded', 'failed', 'expired', 'cancelled'])
|
||||
export const dwsLoginActive = (state: DWSLoginState) => ['starting', 'waiting', 'verifying'].includes(state)
|
||||
const record = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null
|
||||
const text = (value: unknown) => (typeof value === 'string' ? value : '')
|
||||
export function validDWSAuthorizationURL(value: string) {
|
||||
try {
|
||||
const url = new URL(value)
|
||||
return (
|
||||
url.protocol === 'https:' &&
|
||||
url.host === 'login.dingtalk.com' &&
|
||||
!url.username &&
|
||||
!url.password &&
|
||||
!url.hash &&
|
||||
url.pathname === '/oauth2/device/verify.htm'
|
||||
)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
async function request(path: string, signal?: AbortSignal, method = 'GET') {
|
||||
const response = await fetch(path, {
|
||||
method,
|
||||
signal,
|
||||
headers: { Accept: 'application/json', ...(method !== 'GET' ? { 'X-Governance-Action': 'dws-login' } : {}) },
|
||||
})
|
||||
const payload: unknown = await response.json().catch(() => null)
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
record(payload) && typeof payload.error === 'string' ? payload.error : `DWS 请求失败(HTTP ${response.status})`
|
||||
)
|
||||
if (!record(payload) || !record(payload.data)) throw new Error('DWS 返回的数据格式不正确,请重试')
|
||||
return payload.data
|
||||
}
|
||||
export async function fetchDWSCredentials(signal?: AbortSignal): Promise<DWSCredentials> {
|
||||
const data = await request('/api/v1/dingtalk-spaces/credential-status', signal)
|
||||
if (typeof data.authenticated !== 'boolean' || typeof data.refresh_token_valid !== 'boolean')
|
||||
throw new Error('无法判断 DWS 登录状态')
|
||||
return {
|
||||
authenticated: data.authenticated,
|
||||
refresh_token_valid: data.refresh_token_valid,
|
||||
status_known: data.status_known !== false,
|
||||
corp_name: text(data.corp_name),
|
||||
user_name: text(data.user_name),
|
||||
refresh_expires_at: text(data.refresh_expires_at),
|
||||
}
|
||||
}
|
||||
function parseLogin(data: Record<string, unknown>): DWSLogin {
|
||||
if (
|
||||
typeof data.id !== 'string' ||
|
||||
!/^[a-f0-9]{32}$/.test(data.id) ||
|
||||
typeof data.state !== 'string' ||
|
||||
!states.has(data.state) ||
|
||||
!Number.isFinite(Date.parse(text(data.expires_at)))
|
||||
)
|
||||
throw new Error('授权会话格式不正确,请重新发起')
|
||||
const url = text(data.verification_url)
|
||||
if (url && !validDWSAuthorizationURL(url)) throw new Error('授权链接不是钉钉官方地址,请重新发起')
|
||||
return {
|
||||
id: data.id,
|
||||
state: data.state as DWSLoginState,
|
||||
verification_url: url,
|
||||
user_code: text(data.user_code),
|
||||
expires_at: text(data.expires_at),
|
||||
error: text(data.error),
|
||||
}
|
||||
}
|
||||
export async function startDWSLogin(signal?: AbortSignal) {
|
||||
return parseLogin(await request('/api/v1/dws-login', signal, 'POST'))
|
||||
}
|
||||
export async function fetchDWSLogin(id: string, signal?: AbortSignal) {
|
||||
return parseLogin(await request(`/api/v1/dws-login/${encodeURIComponent(id)}`, signal))
|
||||
}
|
||||
export async function cancelDWSLogin(id: string) {
|
||||
return parseLogin(await request(`/api/v1/dws-login/${encodeURIComponent(id)}`, undefined, 'DELETE'))
|
||||
}
|
||||
export async function checkDWSConnection(signal?: AbortSignal) {
|
||||
const data = await request('/api/v1/dingtalk-spaces/available', signal)
|
||||
if (!('knowledge_bases' in data) || !('drive_spaces' in data) || !text(data.fetched_at))
|
||||
throw new Error('未取得有效目录检查结果,请重试')
|
||||
const knowledge = Array.isArray(data.knowledge_bases) ? data.knowledge_bases.length : 0
|
||||
const drive = Array.isArray(data.drive_spaces) ? data.drive_spaces.length : 0
|
||||
const notices = [text(data.knowledge_notice), text(data.drive_notice)].filter(Boolean)
|
||||
return { message: `已读取 ${knowledge} 个知识库、${drive} 个钉盘空间`, notices, checkedAt: text(data.fetched_at) }
|
||||
}
|
||||
Reference in New Issue
Block a user