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(['starting', 'qr', 'scanned', 'reusing', 'success', 'expired', 'failed', 'closed']) function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value) } export async function startDingtalkSession(space?: string): Promise { 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 { 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 { 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, } }