perf(代码审查落地): 后端 A1-A8 与前端 C1-C8 加固,retention 清理补索引(V141)

A 组(backend-java):
- A1 载荷引用计数不再无条件回落全表 COUNT
- A2 结果行读取由 LIMIT 1 改整页
- A3 ziniao 索引缓存过期判断下推 SQL
- A4 循环子任务认领改 CAS,失败一律抛
- A5 建单事务里不碰外部 IO
- A6 连接池补网络层超时(connectTimeout/socketTimeout,env 可覆盖)
- A7 日志留现场 + 异步落盘
- A8 其余:货源图片预取、结果工作簿装配等
- V141:三条 retention DELETE 的可用索引,其中 biz_price_track_loop_run
  用 STORED 生成列承载 COALESCE 时间线(该表实测 881 行/17MB,COPY 秒级)

C 组(frontend-vue):URL 取值走 safe-url、行号取值走 row-id、
交付视频任务状态抽成 delivery-video-task-state.ts,各补用例。
This commit is contained in:
2026-10-03 12:24:16 +08:00
parent fd9aa2caa5
commit 37592a3b62
32 changed files with 1065 additions and 292 deletions
+115 -11
View File
@@ -10,32 +10,120 @@
import type { DesktopConfig, DesktopConfigUpdate, PywebviewApi } from './pywebview'
import { extractErrorMessage, http } from '@/shared/api/http'
/** 虚拟路径 → 浏览器 File 对象(虚拟路径仅存活于当前页面会话,刷新即失效) */
/**
* 虚拟路径 → 浏览器 File 对象(虚拟路径仅存活于当前页面会话,刷新即失效)
*
* 桌面 WebView 常驻不刷新,整份 Excel File(数 MB)会一直被 Map 持有,所以这里做双重有界化:
* 1. 上传成功即 delete(文件已进服务端,页面后续只用返回的 fileKey,不再需要本地 File);
* 2. 只选不传(用户放弃提交)的条目按 FIFO 淘汰,容量上限见 MAX_TRACKED_WEB_FILES。
*/
const webFileMap = new Map<string, File>()
let webFileSeq = 0
const MAX_TRACKED_WEB_FILES = 8
/** 放入新的 File 前先按 FIFO 淘汰最旧条目,保证 Map 不会随选文件次数无界增长。 */
function rememberWebFile(id: string, file: File) {
while (webFileMap.size >= MAX_TRACKED_WEB_FILES) {
const oldest = webFileMap.keys().next()
if (oldest.done) break
webFileMap.delete(oldest.value)
}
webFileMap.set(id, file)
}
const CONFIG_STORAGE_KEY = 'web_desktop_config'
function readStoredConfig(): DesktopConfig {
/**
* 敏感配置字段(口令/密钥类)判定:沿用 bridges/pywebview.ts 中 DesktopConfig /
* DesktopConfigUpdate 已声明的字段命名(aliprice_pwd 这类 *_pwd 口令后缀),
* 再覆盖同族写法 passwd/password 与密钥/令牌(secret/token/api_key)。
*
* 不含用户名(aliprice_usename)与代理地址(proxy_url):页面要用它们做回填与展示,
* 收紧这两类字段会改变既有可见行为。
*/
const SENSITIVE_CONFIG_KEY_RE = /(?:^|[_-])(?:pwd|passwd|password|secret|token|api[_-]?key)$/i
function isSensitiveConfigKey(key: string) {
return SENSITIVE_CONFIG_KEY_RE.test(key)
}
/**
* 敏感字段在本会话内的内存副本:浏览器形态不落 localStorage(同页 XSS / 共用机器读不到明文),
* 但 read_config 仍能取回刚保存的值,页面「保存 → 回显 → 提交」链路行为不变。
* 桌面形态(pywebview)走原生桥的 app.json,代码根本不经过本文件。
*/
const webMemoryConfig: Record<string, unknown> = {}
/** 读磁盘原始副本(不含内存值) */
function readDiskConfig(): DesktopConfig {
try {
const raw = window.localStorage.getItem(CONFIG_STORAGE_KEY) || ''
return raw ? (JSON.parse(raw) as DesktopConfig) : {}
if (!raw) return {}
const parsed = JSON.parse(raw) as DesktopConfig
// 历史版本把口令明文写进过 localStorage:读到时一并丢弃
const out: Record<string, unknown> = {}
for (const [key, value] of Object.entries(parsed || {})) {
if (isSensitiveConfigKey(key)) continue
out[key] = value
}
return out as DesktopConfig
} catch {
return {}
}
}
function writeStoredConfig(data: DesktopConfigUpdate): DesktopConfig {
const merged: DesktopConfig = { ...readStoredConfig(), ...data }
let storedSensitivePurged = false
/** 首次读写时把磁盘上已有的敏感字段抹掉一次(之后写入路径不再产生敏感字段) */
function purgeStoredSensitiveOnce() {
if (storedSensitivePurged || typeof window === 'undefined') return
storedSensitivePurged = true
try {
window.localStorage.setItem(CONFIG_STORAGE_KEY, JSON.stringify(merged))
const raw = window.localStorage.getItem(CONFIG_STORAGE_KEY) || ''
if (!raw) return
const parsed = JSON.parse(raw) as Record<string, unknown>
if (!Object.keys(parsed || {}).some(isSensitiveConfigKey)) return
const cleaned: Record<string, unknown> = {}
for (const [key, value] of Object.entries(parsed)) {
if (isSensitiveConfigKey(key)) continue
cleaned[key] = value
}
window.localStorage.setItem(CONFIG_STORAGE_KEY, JSON.stringify(cleaned))
} catch {
/* 清理失败不阻断主流程:读取侧同样会丢弃敏感字段 */
}
}
function readStoredConfig(): DesktopConfig {
purgeStoredSensitiveOnce()
return { ...readDiskConfig(), ...webMemoryConfig } as DesktopConfig
}
function writeStoredConfig(data: DesktopConfigUpdate): DesktopConfig {
purgeStoredSensitiveOnce()
const persistable: Record<string, unknown> = {}
for (const [key, value] of Object.entries(data || {})) {
if (isSensitiveConfigKey(key)) {
// 口令/密钥类:只进内存,绝不落盘
webMemoryConfig[key] = value
continue
}
persistable[key] = value
}
const persisted: DesktopConfig = { ...readDiskConfig(), ...persistable } as DesktopConfig
try {
window.localStorage.setItem(CONFIG_STORAGE_KEY, JSON.stringify(persisted))
} catch {
/* 本地存储异常时忽略:配置读取仍是空对象 */
}
return merged
// 返回结构与桌面桥一致(含本次保存的敏感字段),页面按原样使用
return { ...persisted, ...webMemoryConfig } as DesktopConfig
}
/** 打开浏览器文件选择框;用户取消时返回空数组(不阻塞后续选择) */
/** 文件选择框挂起兜底超时:旧内核取消时不触发 cancel 事件,Promise 会永远挂起 */
const FILE_PICK_TIMEOUT_MS = 10 * 60 * 1000
/** 打开浏览器文件选择框;用户取消/超时都返回空数组(不阻塞后续选择) */
function pickBrowserFiles(accept = '', multiple = false): Promise<File[]> {
return new Promise((resolve) => {
const input = document.createElement('input')
@@ -44,11 +132,21 @@ function pickBrowserFiles(accept = '', multiple = false): Promise<File[]> {
input.multiple = multiple
input.style.display = 'none'
document.body.appendChild(input)
let settled = false
// 统一 cleanup:无论 change / cancel / 超时,都摘掉临时 DOM 节点并清掉计时器
// (此前取消路径只 remove 一次,挂起路径上 DOM 节点永不摘除)
const cleanup = () => {
if (settled) return
settled = true
window.clearTimeout(guardTimer)
input.remove()
}
const guardTimer = window.setTimeout(() => {
cleanup()
resolve([])
}, FILE_PICK_TIMEOUT_MS)
input.addEventListener('cancel', () => {
// 现代浏览器支持 file input 的 cancel 事件;旧浏览器取消时 Promise 保持挂起(下次选择会覆盖 UI,无副作用)
// 现代浏览器支持 file input 的 cancel 事件;旧浏览器取消时不触发,由上面的超时兜底
cleanup()
resolve([])
})
@@ -68,7 +166,7 @@ function pickBrowserFiles(accept = '', multiple = false): Promise<File[]> {
function registerWebFiles(files: File[]): string[] {
return files.map((file) => {
const id = `web-file:${++webFileSeq}/${file.name}`
webFileMap.set(id, file)
rememberWebFile(id, file)
return id
})
}
@@ -143,6 +241,11 @@ export const webFallbackApi: PywebviewApi = {
try {
// http 实例对 /newApi 前缀自动附带 Bearer;FormData 的 Content-Type 交由浏览器自动生成(含 boundary)
const response = await http.post('/newApi/api/files/upload', form, { timeout: 120000 })
// 消费完即释放:文件已落到服务端,页面后续只用返回的 fileKey/url,不再需要这份本地 File。
// 失败分支保留条目,让用户能在不重新选文件的情况下重试(超量时由 rememberWebFile 的 FIFO 淘汰兜底)。
if (response.data?.success) {
webFileMap.delete(filePath)
}
return response.data
} catch (error) {
return { success: false, error: extractErrorMessage(error) }
@@ -161,11 +264,12 @@ export const webFallbackApi: PywebviewApi = {
return downloadTemplateFile(`/static/${encodeURIComponent(name)}`, name)
},
/** 代理等桌面配置降级到 localStorage(Web 环境与桌面端配置相互独立) */
/** 代理等桌面配置降级:非敏感字段落 localStorage,口令/密钥类只存内存(见 writeStoredConfig) */
async read_config() {
return readStoredConfig()
},
/** 浏览器形态的桌面配置写入:敏感字段拒绝持久化,仅保留在会话内存中 */
async save_config(data) {
return writeStoredConfig(data)
},
@@ -4,6 +4,8 @@
* - 服务端(/api/user-secrets)是唯一权威:按登录用户绑定,客户端只缓存元数据与最近输入的值;
* - `getStoredApiSecret` / `getStoredApiSecretSnapshot` 保持同步读语义(提交任务瞬间立即取用),
* 读取顺序:内存 → 本地镜像 → 旧版 v1 记录(`brand:api-secret:{uid}:{moduleKey}`);
* - 本地镜像(localStorage)在浏览器形态只存脱敏值与状态位,明文只活在本页内存;
* 桌面形态(有 window.pywebview.api 原生存储)维持原有整条镜像,不动既有流程;
* - 保存/清空/检测走异步接口;服务端拉取失败一律软失败(返回 unknown,不阻断使用);
* - 旧版本地密钥在首次加载时自动迁移到服务端(只填空缺、不覆盖)。
*/
@@ -28,7 +30,10 @@ export type { UserApiSecretCheckResult }
export type ApiSecretLoadState = 'complete' | 'incomplete' | 'unknown'
export interface ApiSecretSnapshot {
/** 本地明文缓存(来自用户输入或旧记录迁移);服务端不回传明文,换机后可能为空。 */
/**
* 本地明文(来自用户输入或旧记录迁移),只存内存 Map;
* 浏览器形态的磁盘镜像不含此字段,服务端不回传明文,换机/刷新后可能为空。
*/
value: string
/** 服务端脱敏值(权威展示,如 sk-a****1234)。 */
masked: string
@@ -93,6 +98,19 @@ function buildLegacyKey(moduleKey: string) {
return `${LEGACY_PREFIX}:${currentUid()}:${moduleKey}`
}
/**
* 形态判定:桌面客户端(pywebview)会注入 window.pywebview.api 并提供原生 app.json 存储,
* 其本地明文缓存是既有任务链路依赖(重启后仍能取用);纯浏览器形态没有原生存储,
* localStorage 是同页脚本可直接读到的明文落点,必须收紧。
*
* 这里刻意用内联的 window 断言而不是 import hasPywebview():静态引入 bridges/pywebview
* 会把 web-fallback → http 拉进 node 测试环境(本模块被单测直接 import)。
*/
function isNativeDesktopStorage(): boolean {
if (typeof window === 'undefined') return false
return Boolean((window as unknown as { pywebview?: { api?: unknown } }).pywebview?.api)
}
function emptyEntry(): ApiSecretCacheEntry {
return {
schema: 2,
@@ -128,7 +146,7 @@ function readMirror(moduleKey: string): ApiSecretCacheEntry | null {
if (!raw) return null
const parsed = JSON.parse(raw) as Partial<ApiSecretCacheEntry>
if (parsed.schema !== 2) return null
return {
const entry: ApiSecretCacheEntry = {
schema: 2,
value: typeof parsed.value === 'string' ? parsed.value : '',
masked: typeof parsed.masked === 'string' ? parsed.masked : '',
@@ -141,15 +159,23 @@ function readMirror(moduleKey: string): ApiSecretCacheEntry | null {
checkedAt: typeof parsed.checkedAt === 'number' ? parsed.checkedAt : null,
updatedAt: typeof parsed.updatedAt === 'number' ? parsed.updatedAt : null,
}
// 浏览器形态:历史版本可能已把明文写进磁盘,读到就顺手抹掉(明文只留内存)
if (entry.value && !isNativeDesktopStorage()) {
entry.value = ''
writeMirror(moduleKey, entry)
}
return entry
} catch {
return null
}
}
/** 磁盘镜像写入:浏览器形态只写脱敏值与状态位,明文不落地;桌面形态维持既有整条镜像。 */
function writeMirror(moduleKey: string, entry: ApiSecretCacheEntry) {
if (typeof window === 'undefined') return
const persisted: ApiSecretCacheEntry = isNativeDesktopStorage() ? entry : { ...entry, value: '' }
try {
window.localStorage.setItem(buildMirrorKey(moduleKey), JSON.stringify(entry))
window.localStorage.setItem(buildMirrorKey(moduleKey), JSON.stringify(persisted))
} catch {
/* 本地镜像写入失败不影响主流程 */
}
+23
View File
@@ -0,0 +1,23 @@
/**
* 列表行稳定 key(审查 C6)。
*
* `v-for` 用 index 当 :key 时,删除中间行会让后续行的组件实例被错位复用
* (上传槽/日期选择器的内部状态跟着串行)。这里给状态对象发一个整页会话内唯一的 id。
*
* crypto.randomUUID 只在安全上下文可用;桌面客户端 WebView2 走 https 加载页面时有,
* 但为兼容 http/旧内核仍保留「时间戳 + 进程内自增 + 随机数」的降级实现(同页会话内唯一即可)。
*/
let rowSeq = 0
export function createRowId(prefix = 'row'): string {
const randomUuid = typeof crypto !== 'undefined' ? crypto.randomUUID : undefined
if (randomUuid) {
try {
return `${prefix}:${randomUuid.call(crypto)}`
} catch {
/* 非安全上下文 Some WebView 实现会抛,走降级分支 */
}
}
rowSeq += 1
return `${prefix}:${Date.now().toString(36)}-${rowSeq.toString(36)}-${Math.random().toString(36).slice(2, 10)}`
}
+23
View File
@@ -0,0 +1,23 @@
/**
* 外链白名单(审查 C6):渲染成 a[href] / window.open 之前过滤协议。
*
* 结果文件地址、task_data 里的 file_url 等都是客户端/服务端原样透传的开放字段
* (见 shared/bridges/pywebview.ts 对 task_data 的说明),页面直接绑到 :href 上时,
* `javascript:` / `data:` 这类伪协议会在当前文档上下文里执行。这里只放行 http/https。
*/
const ALLOWED_PROTOCOLS = new Set(['http:', 'https:'])
/** 非 http(s) 或无法解析的地址一律返回 '#',其余原样返回(相对路径按当前页面补全后判定)。 */
export function safeHttpUrl(raw?: string | null): string {
const value = typeof raw === 'string' ? raw.trim() : ''
if (!value) return '#'
const base = typeof window !== 'undefined' && window.location?.href ? window.location.href : 'http://localhost/'
let parsed: URL
try {
parsed = new URL(value, base)
} catch {
return '#'
}
return ALLOWED_PROTOCOLS.has(parsed.protocol) ? value : '#'
}