import { z } from 'zod' import { DesktopClientError } from './contract.mjs' export const feedbackIdSchema = z.string().uuid().transform(value => value.toLowerCase()) const schemaVersion = z.union([z.literal(1), z.literal(2), z.literal(3)]) const feedbackInput = z.object({ feedbackId: feedbackIdSchema, schemaVersion: schemaVersion.optional(), summary: z.string().trim().refine(value => value.length > 0 && Array.from(value).length <= 2000), projectId: z.string().nullish(), taskId: z.string().nullish(), requestId: z.string().nullish(), context: z.record(z.unknown()).nullish(), }) const contextFields = new Set([ 'client', 'clientVersion', 'appVersion', 'version', 'platform', 'os', 'arch', 'capturedAt', 'online', 'project', 'projectId', 'projectName', 'task', 'taskId', 'request', 'requestId', 'materialId', 'traceId', 'deliveryId', 'knowledgeVersion', 'id', 'name', 'title', 'kind', 'type', 'status', 'stage', 'model', 'timestamp', 'createdAt', 'durationMs', 'code', 'errorCode', 'error', 'errors', 'message', 'diagnostics', 'events', 'commit', 'channel', 'builtAt', 'page', 'view', 'currentError', 'notices', 'recentErrors', 'agentDaemon', 'available', 'ready', 'spawnCount', 'activeRuns', 'heartbeatAgeMs', 'exitCode', 'lastError', 'stderrSummary', 'models', 'chatModel', 'copyModel', 'imageModel', 'hasPersonalKey', 'knowledgeMode', 'canvas', 'render', 'renderPath', 'gpuFallback', 'gpuFallbackKind', 'documentWidth', 'documentHeight', 'layerCount', 'outputId', 'activeOutput', 'variantId', 'templateHash', 'revision', 'dirty', 'professionalMode', 'multiProject', 'runningCount', 'queuedCount', 'pausedCount', 'storage', 'usingCustomRoot', 'migrationPhase', 'freeBytes', 'recentLogs', ]) const imageFields = new Set(['image', 'images', 'screenshot', 'screenshots', 'preview', 'thumbnail']) const privateV3Fields = new Set(['name', 'title', 'projectName', 'notices', 'events', 'variantId', 'stderrSummary']) const removedImage = '[图片已移除]' const removedCredential = '[敏感信息已移除]' const safeLogKvPattern = /\b(?:project_id|slot_id|material_id|trace_id|delivery_id|request_id|task_id|output_id|knowledge_version|code)=[A-Za-z0-9_.:-]{1,39}(?=\s|$)/gi export function redactText(value: string, max: number, rich = false): string { const text = Array.from(value).filter(character => !/^[\u0000-\u0008\u000b\u000c\u000e-\u001f\ud800-\udfff]$/.test(character)).join('').trim() // Scan the complete input before truncating so a secret or data URL cannot be split at the limit. const scan = text.normalize('NFKC').replace(/%([\da-f]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16))) if (/\bdata\s*:/i.test(scan)) return removedImage if (scan.length > 4096) return '[内容过长,已移除]' const secretScan = scan.replace(safeLogKvPattern, m => { const val = m.slice(m.indexOf('=') + 1) return /^(?:dcs_|dca_|sk[-_]|rk[-_]|gh[pousr]_|github_pat_|xox[baprs]-|AKIA|ASIA|eyJ)/i.test(val) ? m : 'kv=ok' }) if ( /\beyJ[\w-]+\.[\w-]+\.[\w-]+|[A-Za-z0-9+/_=-]{40,}/.test(secretScan) || /\b(?:authorization|(?:set[-_ ]?)?cookie|[\w-]*(?:api|access|auth|private)[-_ ]?key(?:[-_ ]?id)?|[\w-]*token|[\w-]*secret|[\w-]*pass(?:word|wd|phrase)?|credentials?|[\w-]*session(?:[-_ ]?id)?|sid(?:\.sig)?|[\w-]*signature)["']?\s*[:=]/i.test(secretScan) || /(?:--(?:api[-_]?key|token|password|secret)\s+|\bcookie\s+\S+=)/i.test(secretScan) || /\b(?:bearer|basic)\s+\S|-----BEGIN [^-]+-----/i.test(secretScan) || /\b[a-z][a-z\d+.-]{0,24}:\/\/|\b[\w.%-]{1,64}:[^\s@]{1,256}@\S|\b[\w.+-]{1,64}@[A-Za-z\d-]+(?:\.[A-Za-z\d-]+)+\b/i.test(secretScan) || /\b(?:dcs_|dca_|sk[-_]|rk[-_]|gh[pousr]_|github_pat_|xox[baprs]-|AKIA|ASIA)[\w-]+/i.test(secretScan) ) return removedCredential if (rich && /\b[a-z]:[\\/]|\\\\[^\\\s]+\\|\/(?:users|home|root|private\/var)\/|~[\\/]/i.test(scan)) { return '[本地路径已移除]' } return Array.from(text).slice(0, max).join('') } export type Diagnostic = string | number | boolean | Diagnostic[] | { [field: string]: Diagnostic } function sanitizeDiagnostic(value: unknown, depth: number, rich = false): Diagnostic | undefined { if (typeof value === 'string') return redactText(value, 1000, rich) if (typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value))) return value if (!value || typeof value !== 'object' || depth === 0) return undefined if (Array.isArray(value)) { return value.slice(0, 12).flatMap(item => { if (typeof item !== 'string' && typeof item !== 'object') return [] const clean = sanitizeDiagnostic(item, depth - 1, rich) return clean === undefined ? [] : [clean] }) } const result: Record = {} for (const [field, item] of Object.entries(value)) { if (Object.keys(result).length === 24) break if (rich && privateV3Fields.has(field)) continue if (imageFields.has(field)) result[field] = removedImage else if (field === 'recentLogs' && Array.isArray(item)) { if (depth > 1) { result[field] = item .filter((entry): entry is string => typeof entry === 'string') .slice(0, 25) .map(entry => redactText(entry, 240, rich)) } } else if (contextFields.has(field) || (rich && field === 'hasStderr')) { if (rich && field === 'hasPersonalKey' && typeof item !== 'boolean') continue const clean = sanitizeDiagnostic(item, depth - 1, rich) if (clean !== undefined) result[field] = clean } } return result } const richArrayLimits = { breadcrumbs: 25, recentToolFailures: 10, recentErrors: 20, recentLogs: 80 } type RichFields = { readonly [field: string]: true | RichFields | readonly [RichFields, number] } const operationFields = { operation: true, category: true, message: true, code: true } as const const toolFields = { toolName: true, status: true, category: true, code: true, durationMs: true, timestampMs: true, ageMs: true } as const const modelFields = { modelId: true, providerId: true, routeId: true, protocol: true, ready: true } as const const richSections: Record = { workspaceState: { activeScreen: true, activeTab: true, mode: true, projectCount: true, openProjectCount: true, openDocumentCount: true, recentNoticeCount: true, hasActiveProject: true, canvasReady: true, documentReady: true, activeTaskStatus: true }, errors: { activeBanners: [operationFields, 12], lastFailedOperation: { ...operationFields, ...toolFields } }, modelConfig: { chat: modelFields, copy: modelFields, image: modelFields, routingMode: true, hasPersonalKey: true }, updateState: { channel: true, currentVersion: true, latestVersion: true, status: true, checkedAt: true, checkFailed: true, error: operationFields }, display: { logicalWidth: true, logicalHeight: true, physicalWidth: true, physicalHeight: true, scaleFactor: true, nativeScaleFactor: true, gpu: { adapter: true, backend: true, deviceType: true, driver: true, videoMemoryMb: true } }, } const richEventFields: Record = { breadcrumbs: { action: true, source: true, timestampMs: true }, recentToolFailures: toolFields, } function sanitizeRichRecord(value: unknown, fields: RichFields): Record | undefined { if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined const result: Record = {} for (const [field, item] of Object.entries(value)) { if (!Object.hasOwn(fields, field)) { if (imageFields.has(field)) result[field] = removedImage continue } const rule = fields[field] if (rule === true) { if (field === 'hasPersonalKey' && typeof item !== 'boolean') continue if (typeof item === 'string') result[field] = redactText(item, 240, true) else if (typeof item === 'boolean' || (typeof item === 'number' && Number.isFinite(item))) result[field] = item } else if (Array.isArray(rule)) { if (Array.isArray(item)) result[field] = item.slice(0, rule[1]).flatMap(row => sanitizeRichRecord(row, rule[0]) ?? []) } else { const clean = sanitizeRichRecord(item, rule as RichFields) if (clean) result[field] = clean } } return result } function normalizeModelConfig(value: unknown): unknown { if (!value || typeof value !== 'object' || Array.isArray(value)) return value const record = value as Record const normalized: Record = { ...record } for (const [canonical, alias] of [['chat', 'chatModel'], ['copy', 'copyModel'], ['image', 'imageModel']] as const) { if (normalized[canonical] === undefined && record[alias] !== undefined) normalized[canonical] = record[alias] } return normalized } function sanitizeRichSnapshot(context: Record): Record { const legacyFields = Object.fromEntries(Object.entries(context) .filter(([field]) => !Object.hasOwn(richSections, field) && !Object.hasOwn(richArrayLimits, field))) const snapshot: Record = { ...(sanitizeDiagnostic(legacyFields, 4, true) as Record), schemaVersion: 3, } for (const [field, fields] of Object.entries(richSections)) { const rawSection = field === 'modelConfig' ? normalizeModelConfig(context[field]) : context[field] const clean = sanitizeRichRecord(rawSection, fields) if (clean) snapshot[field] = clean } for (const [field, limit] of Object.entries(richArrayLimits)) { const rows = context[field] if (!Array.isArray(rows)) continue const clean: Diagnostic[] = [] const fields = richEventFields[field] for (const row of rows) { if (fields) { const entry = sanitizeRichRecord(row, fields) if (entry && Object.keys(entry).length) clean.push(entry) } else if (typeof row === 'string') clean.push(redactText(row, 240, true)) if (clean.length === limit) break } snapshot[field] = clean } return snapshot } export function parseDesktopFeedback(raw: string) { let json: unknown try { json = JSON.parse(raw) } catch { throw new DesktopClientError('反馈资料格式不正确') } const result = feedbackInput.safeParse(json) if (!result.success) { throw new DesktopClientError(result.error.issues.some(issue => issue.path[0] === 'summary') ? '请填写 2000 字以内的问题说明' : '反馈资料格式不正确') } const { feedbackId, summary, projectId, taskId, requestId, context } = result.data const contextVersion = schemaVersion.optional().safeParse(context?.schemaVersion) if (!contextVersion.success || (result.data.schemaVersion !== undefined && contextVersion.data !== undefined && result.data.schemaVersion !== contextVersion.data)) { throw new DesktopClientError('反馈资料格式不正确') } const rich = (result.data.schemaVersion ?? contextVersion.data) === 3 const cleanSummary = redactText(summary, 2000, rich) if (!cleanSummary) throw new DesktopClientError('请填写 2000 字以内的问题说明') return { feedbackId, summary: cleanSummary, projectId: projectId ? redactText(projectId, 180, rich) || null : null, taskId: taskId ? redactText(taskId, 180, rich) || null : null, requestId: requestId ? redactText(requestId, 180, rich) || null : null, snapshot: rich ? sanitizeRichSnapshot(context ?? {}) : sanitizeDiagnostic(context ?? {}, 4) as Record, } }