Files
knowledge-governance/web/src/dingtalkSession.ts
T
2026-09-30 10:54:07 +08:00

107 lines
4.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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)
}
export interface RegisteredDingtalkSpace {
connection_id: string
name: string
}
export class DingtalkRequestError extends Error {
constructor(
message: string,
public readonly code: string,
public readonly status: number,
) {
super(message)
this.name = 'DingtalkRequestError'
}
}
// Register a DingTalk knowledge-base space (URL or bare space id) as a new
// source connection. Errors carry the sidecar's machine codes so the UI can
// explain them: login_required, space_not_found, name_conflict.
export async function registerDingtalkSpace(url: string): Promise<RegisteredDingtalkSpace> {
const response = await fetch('/api/v1/dingtalk-spaces', {
method: 'POST',
headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-Governance-Action': 'dingtalk-space', 'Idempotency-Key': newOperationID() },
body: JSON.stringify({ url }),
})
if (!response.ok) {
let code = ''
try {
const parsed = await response.json() as unknown
if (isRecord(parsed) && typeof parsed.error === 'string') code = parsed.error
} catch { /* status-only */ }
const friendly: Record<string, string> = {
login_required: '钉钉扫码会话无效或已过期,请先在钉钉来源卡片上「扫码刷新会话」',
space_not_found: '未找到该知识库空间:请确认空间链接正确且当前账号有阅读权限',
name_conflict: '该空间与已登记的来源同名',
invalid_space_url: '链接不是有效的钉钉知识库空间地址(应形如 alidocs.dingtalk.com/i/spaces/…)',
}
throw new DingtalkRequestError(
friendly[code] || `登记钉钉知识库失败(HTTP ${response.status}${code ? ':' + code : ''})`,
code,
response.status,
)
}
const value = await response.json() as unknown
if (!isRecord(value) || !isRecord(value.data)) throw new Error('invalid dingtalk space response')
const data = value.data
if (typeof data.connection_id !== 'string' || typeof data.name !== 'string') throw new Error('invalid dingtalk space response')
return { connection_id: data.connection_id, name: data.name }
}
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,
}
}