92 lines
4.4 KiB
TypeScript
92 lines
4.4 KiB
TypeScript
import { z } from 'zod'
|
|
import { DesktopClientError } from './contract.mjs'
|
|
|
|
export const feedbackIdSchema = z.string().uuid().transform(value => value.toLowerCase())
|
|
|
|
const feedbackInput = z.object({
|
|
feedbackId: feedbackIdSchema,
|
|
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', 'id', 'name', 'title',
|
|
'kind', 'type', 'status', 'stage', 'model', 'timestamp', 'createdAt', 'durationMs', 'code', 'errorCode',
|
|
'error', 'errors', 'message', 'diagnostics', 'events',
|
|
])
|
|
const imageFields = new Set(['image', 'images', 'screenshot', 'screenshots', 'preview', 'thumbnail'])
|
|
const removedImage = '[图片已移除]'
|
|
const removedCredential = '[敏感信息已移除]'
|
|
|
|
function redactText(value: string, max: number): 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 '[内容过长,已移除]'
|
|
if (
|
|
/\beyJ[\w-]+\.[\w-]+\.[\w-]+|[A-Za-z0-9+/_=-]{40,}/.test(scan)
|
|
|| /\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(scan)
|
|
|| /(?:--(?:api[-_]?key|token|password|secret)\s+|\bcookie\s+\S+=)/i.test(scan)
|
|
|| /\b(?:bearer|basic)\s+\S|-----BEGIN [^-]+-----/i.test(scan)
|
|
|| /\b[a-z][a-z\d+.-]{0,24}:\/\/|\b[\w.%-]{1,64}:[^\s@]{1,256}@\S/i.test(scan)
|
|
|| /\b(?:dcs_|dca_|sk[-_]|rk[-_]|gh[pousr]_|github_pat_|xox[baprs]-|AKIA|ASIA)[\w-]+/i.test(scan)
|
|
) return removedCredential
|
|
return Array.from(text).slice(0, max).join('')
|
|
}
|
|
|
|
type Diagnostic = string | number | boolean | Diagnostic[] | { [field: string]: Diagnostic }
|
|
|
|
function sanitizeDiagnostic(value: unknown, depth: number): Diagnostic | undefined {
|
|
if (typeof value === 'string') return redactText(value, 1000)
|
|
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)
|
|
return clean === undefined ? [] : [clean]
|
|
})
|
|
}
|
|
const result: Record<string, Diagnostic> = {}
|
|
for (const [field, item] of Object.entries(value)) {
|
|
if (Object.keys(result).length === 16) break
|
|
if (imageFields.has(field)) result[field] = removedImage
|
|
else if (contextFields.has(field)) {
|
|
const clean = sanitizeDiagnostic(item, depth - 1)
|
|
if (clean !== undefined) result[field] = clean
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
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 cleanSummary = redactText(summary, 2000)
|
|
if (!cleanSummary) throw new DesktopClientError('请填写 2000 字以内的问题说明')
|
|
return {
|
|
feedbackId,
|
|
summary: cleanSummary,
|
|
projectId: projectId ? redactText(projectId, 180) || null : null,
|
|
taskId: taskId ? redactText(taskId, 180) || null : null,
|
|
requestId: requestId ? redactText(requestId, 180) || null : null,
|
|
snapshot: sanitizeDiagnostic(context ?? {}, 4) as Record<string, Diagnostic>,
|
|
}
|
|
}
|