feat(settings): refresh DingTalk scan sessions from the data-source page
DingTalk source scanning depends on a shared browser session whose capture file had to be replaced by hand whenever it expired (every scan 401s). - services/dingtalk-login: admin-triggered Playwright sidecar that opens the space page in a persistent headless Chromium, publishes the QR through session polling, verifies the first authenticated XHR against the box API, then writes the capture in place (same inode keeps the worker's ro bind mount current); tokens never leave the sidecar - api: POST/GET/DELETE /api/v1/dingtalk-session authenticated relay; QR is a login artifact, so the whole prefix is admin-only in classifyRole; OpenAPI contract and proxy/503/hostile-ID tests included - web: 系统设置 → 数据源配置 钉钉卡片新增扫码刷新会话(仅管理员可见), QR 弹窗 + 1.5s 轮询 + 成功/过期/失败状态 - compose: sidecar service owns the ONLY rw mount of secrets/; worker keeps ro
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe,expect,it,vi } from 'vitest'
|
||||
import { DingtalkSessionControl } from './DingtalkSessionControl'
|
||||
|
||||
describe('DingtalkSessionControl',()=>{
|
||||
it('renders the admin scan button without firing any request',()=>{
|
||||
const fetchMock=vi.fn()
|
||||
vi.stubGlobal('fetch',fetchMock)
|
||||
const markup=renderToStaticMarkup(<DingtalkSessionControl />)
|
||||
expect(markup).toContain('扫码刷新会话')
|
||||
expect(markup).not.toContain('modal-backdrop')
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,72 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
|
||||
import { cancelDingtalkSession, fetchDingtalkSession, startDingtalkSession } from './dingtalkSession'
|
||||
import type { DingtalkSessionView } from './dingtalkSession'
|
||||
|
||||
// Admin-only card control: "扫码刷新会话" opens a login session against the
|
||||
// dingtalk-login sidecar, shows its QR, and reports the capture result. The
|
||||
// token never reaches this component — only state and the QR image.
|
||||
|
||||
const finished = new Set(['success', 'expired', 'failed', 'closed'])
|
||||
|
||||
export function DingtalkSessionControl() {
|
||||
const [session, setSession] = useState<DingtalkSessionView | null>(null)
|
||||
const [failure, setFailure] = useState<string | null>(null)
|
||||
const [starting, setStarting] = useState(false)
|
||||
const idRef = useRef<string | null>(null)
|
||||
|
||||
useEffect(() => () => { if (idRef.current) void cancelDingtalkSession(idRef.current) }, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!session || finished.has(session.state)) return
|
||||
const timer = setInterval(() => {
|
||||
fetchDingtalkSession(session.id).then(setSession).catch(() => undefined)
|
||||
}, 1500)
|
||||
return () => clearInterval(timer)
|
||||
}, [session?.id, session?.state])
|
||||
|
||||
const start = async () => {
|
||||
setStarting(true); setFailure(null)
|
||||
try {
|
||||
const fresh = await startDingtalkSession()
|
||||
idRef.current = fresh.id
|
||||
setSession(fresh)
|
||||
} catch (cause) {
|
||||
setFailure(cause instanceof Error ? cause.message : '发起扫码会话失败')
|
||||
} finally {
|
||||
setStarting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const close = () => {
|
||||
if (idRef.current) void cancelDingtalkSession(idRef.current)
|
||||
idRef.current = null
|
||||
setSession(null)
|
||||
}
|
||||
|
||||
const stateLabel: Record<string, string> = {
|
||||
starting: '正在打开登录页…', qr: '请用钉钉 App 扫码登录', scanned: '已扫码,正在获取会话…',
|
||||
reusing: '检测到有效浏览器会话,正在验证…', success: '✅ 钉钉扫码会话已刷新,扫描任务可继续使用',
|
||||
expired: '二维码已过期,请重新发起', failed: '会话验证失败,请重试或联系管理员', closed: '会话已关闭',
|
||||
}
|
||||
|
||||
return <div className="dingtalk-session-control">
|
||||
<button className="secondary" disabled={starting || (session ? !finished.has(session.state) : false)} onClick={() => void start()}>
|
||||
{session && !finished.has(session.state) ? '扫码进行中…' : '扫码刷新会话'}
|
||||
</button>
|
||||
{failure ? <p className="error-message" role="alert">{failure}</p> : null}
|
||||
{session ? <div className="modal-backdrop" role="dialog" aria-modal="true" aria-label="钉钉扫码登录">
|
||||
<div className="modal-card dingtalk-qr-card">
|
||||
<h3>刷新钉钉扫码会话</h3>
|
||||
<p className="dingtalk-qr-hint">{stateLabel[session.state] ?? session.state}</p>
|
||||
{session.qr_png && session.state === 'qr' ? <img className="dingtalk-qr-image" src={`data:image/png;base64,${session.qr_png}`} alt="钉钉登录二维码" /> : null}
|
||||
{session.error ? <p className="error-message" role="alert">{session.error}</p> : null}
|
||||
<div className="modal-actions">
|
||||
{finished.has(session.state)
|
||||
? <button className="secondary" onClick={close}>关闭</button>
|
||||
: <button className="danger" onClick={close}>取消扫码</button>}
|
||||
</div>
|
||||
</div>
|
||||
</div> : null}
|
||||
</div>
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
|
||||
import { MembersSection } from './MembersSection'
|
||||
import { DingtalkSessionControl } from './DingtalkSessionControl'
|
||||
import { RoutingBindingsSection } from './RoutingBindingsSection'
|
||||
import { useOptionalAuth } from './auth'
|
||||
import { fetchMonitorOverview } from './monitor'
|
||||
@@ -61,6 +62,8 @@ function formatHorizon(value: string | null): string {
|
||||
}
|
||||
|
||||
function SourceSettingsCard({ connection, onSourcesChanged }: { connection: SourceConnectionListItem; onSourcesChanged: () => void }) {
|
||||
const auth = useOptionalAuth()
|
||||
const isAdmin = auth?.identity?.role === 'admin'
|
||||
const [interval, setInterval] = useState<number>(() => {
|
||||
if (!connection.next_refresh_at) return 0
|
||||
const remaining = new Date(connection.next_refresh_at).getTime() - Date.now()
|
||||
@@ -117,6 +120,7 @@ function SourceSettingsCard({ connection, onSourcesChanged }: { connection: Sour
|
||||
? <div className="source-schedule-actions"><button className="secondary" disabled={!canApply || (scheduled && interval === 0 && !connection.schedule_configured)} onClick={() => void submit(true)}>{busy ? '正在验证并启用…' : '保存并启用调度'}</button>
|
||||
<button className="danger" disabled={!canApply} onClick={() => setPendingDisable(true)}>停用来源</button></div>
|
||||
: <div className="source-schedule-actions"><button className="secondary" disabled={!canApply} onClick={() => void submit(true)}>保存并启用</button></div>}
|
||||
{connection.source_type === "dingtalk" && isAdmin ? <DingtalkSessionControl /> : null}
|
||||
<button className="link" onClick={() => void loadHistory()}>{showHistory ? '收起修订历史' : '查看修订历史'}</button>
|
||||
</div>
|
||||
{message ? <p className="success-message" role="status">{message}</p> : null}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { newOperationID } from './operationKey'
|
||||
|
||||
// Client for the admin-only DingTalk scan-code session (系统设置 → 数据源配置).
|
||||
// The API proxies to the dingtalk-login sidecar; this module never sees the
|
||||
// token itself — only the base64 QR image and a terminal state.
|
||||
|
||||
export type DingtalkSessionState = 'starting' | 'qr' | 'scanned' | 'reusing' | 'success' | 'expired' | 'failed' | 'closed'
|
||||
|
||||
export interface DingtalkSessionView {
|
||||
id: string
|
||||
state: DingtalkSessionState
|
||||
created_at: number
|
||||
expires_at: number
|
||||
qr_png?: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
const sessionStates = new Set<string>(['starting', 'qr', 'scanned', 'reusing', 'success', 'expired', 'failed', 'closed'])
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
export async function startDingtalkSession(space?: string): Promise<DingtalkSessionView> {
|
||||
const response = await fetch('/api/v1/dingtalk-session', {
|
||||
method: 'POST',
|
||||
headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-Governance-Action': 'dingtalk-session', 'Idempotency-Key': newOperationID() },
|
||||
body: JSON.stringify(space ? { space } : {}),
|
||||
})
|
||||
if (!response.ok) throw new Error(`发起钉钉扫码会话失败(HTTP ${response.status})`)
|
||||
return parseSession(await response.json())
|
||||
}
|
||||
|
||||
export async function fetchDingtalkSession(id: string, signal?: AbortSignal): Promise<DingtalkSessionView> {
|
||||
const response = await fetch(`/api/v1/dingtalk-session/${encodeURIComponent(id)}`, { headers: { Accept: 'application/json' }, signal })
|
||||
if (!response.ok) throw new Error(`读取钉钉扫码会话失败(HTTP ${response.status})`)
|
||||
return parseSession(await response.json())
|
||||
}
|
||||
|
||||
export async function cancelDingtalkSession(id: string): Promise<void> {
|
||||
await fetch(`/api/v1/dingtalk-session/${encodeURIComponent(id)}`, { method: 'DELETE', headers: { Accept: 'application/json' } }).catch(() => undefined)
|
||||
}
|
||||
|
||||
function parseSession(value: unknown): DingtalkSessionView {
|
||||
if (!isRecord(value) || typeof value.id !== 'string' || typeof value.state !== 'string' || !sessionStates.has(value.state)) {
|
||||
throw new Error('invalid dingtalk session response')
|
||||
}
|
||||
return {
|
||||
id: value.id,
|
||||
state: value.state as DingtalkSessionState,
|
||||
created_at: typeof value.created_at === 'number' ? value.created_at : 0,
|
||||
expires_at: typeof value.expires_at === 'number' ? value.expires_at : 0,
|
||||
qr_png: typeof value.qr_png === 'string' ? value.qr_png : undefined,
|
||||
error: typeof value.error === 'string' ? value.error : undefined,
|
||||
}
|
||||
}
|
||||
@@ -27,3 +27,8 @@ button.link{background:none;border:none;color:var(--c-run);cursor:pointer;text-d
|
||||
.modal-actions{display:flex;gap:10px;justify-content:flex-end;margin-top:14px}
|
||||
@media (max-width:900px){.settings-layout{grid-template-columns:1fr}.settings-nav{position:static;flex-direction:row;flex-wrap:wrap}}
|
||||
.kb-binding-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin:12px 0}.kb-binding-side{display:grid;gap:4px;border:1px solid var(--border-base);border-radius:9px;padding:11px;background:var(--bg-soft)}.kb-binding-side.bound{border-color:var(--c-done)}.kb-binding-side.warn{border-color:var(--c-fail)}.kb-binding-side b{color:var(--ink-base);font-size:11px}.kb-binding-side span{color:var(--c-done);font-size:11px;word-break:break-all}.kb-binding-side.warn span{color:var(--c-fail)}.kb-binding-side small{color:var(--ink-mute);font-size:9px}.kb-binding-editor{display:grid;gap:10px;border-top:1px dashed var(--border-base);margin-top:8px;padding-top:12px}.kb-binding-editor label{display:grid;gap:6px;color:var(--ink-mute);font-size:10px}.kb-binding-editor select,.kb-binding-editor input{border:1px solid var(--border-strong);border-radius:7px;padding:8px;background:var(--bg-panel);color:var(--ink-base)}.kb-binding-editor button{justify-self:start;padding:7px 10px}@media(max-width:650px){.kb-binding-grid{grid-template-columns:1fr}}.hint{color:var(--ink-mute);font-size:10px;margin:4px 0}
|
||||
.dingtalk-session-control{display:flex;flex-direction:column;gap:4px;align-self:end}
|
||||
.dingtalk-qr-card{max-width:360px;text-align:center}
|
||||
.dingtalk-qr-hint{color:var(--ink-mute);font-size:13px;min-height:20px}
|
||||
.dingtalk-qr-image{display:block;margin:10px auto;width:240px;height:240px;image-rendering:pixelated;border:1px solid var(--border-base);border-radius:10px;background:#fff}
|
||||
.dingtalk-qr-card .modal-actions{justify-content:center}
|
||||
|
||||
Reference in New Issue
Block a user