feat(dacli): form audit + AI-driven smartProps (v0.14+ ~ v0.16+)
源: docs/dos/testcase.html §10 + debug.md §5 暴露的 dos 26 P0 真实业务漏洞. v0.14+ 新增 `dacli form audit` (BS-新61~64): - BS-新61: select 字段空字典 (dictionaryType="") - BS-新62: input 字段当 FK 用 (命名 _id/_code/_identifier) - BS-新63: inputNumber 字段无 min/max 范围 - BS-新64: formData.formRules 缺失 testspace 最小复现: formId 844085364627865925 (testAuditForm) 4 类盲点全命中. dos 复跑: 15 form / 61 盲点 (BS-新62=12 跟手算 §10 "12 input FK" 完全吻合). v0.15+ smartProps v1: 关键词规则 (SELECT_DICT_RULES / NUMBER_RANGE_RULES / REGEX_RULES) v0.16+ smartProps v2: 用户反馈"关键词法是无穷无尽", 改为调 LLM 一次性推理 AI-driven 架构 (跟 /ssw/ai/infer-category 同样模式): - dacli form create --ai 走 NCPF AI + web buildFormData - 新增 buildFormData 后调 SSW /api/ssw/ai/infer-component-props - LLM 一次性推理字典/min-max/relationForm/regList 用户设计原则 (2026-07-07): "不用关键词兜底, 会混乱的" - 单一源 = AI 推理, 无 fallback - AI 失败 → source='none', 不填任何字段, dacli form audit 兜底 - 删除 v0.15+ 关键词规则 (NUMBER_RANGE_RULES 11 条 / REGEX_RULES 7 条 / fallbackKeywordForField) dacli/test_smart_props_v3.ts (4 个测试): - Test 1: AI 成功 → source='ai' + 4 字段全填 ✅ - Test 2: AI 失败 → source='none' + 4 字段全不填 (核心: 验证 fallback 已彻底删除) ✅ - Test 3: 真实 SSW 端点 + LLM 推理 (4 字段全对) ✅ - Test 4: 源码扫描 (0 fallback-keyword 引用, 0 关键词规则代码) ✅ 注: 关卡 G 的 kb FAIL 是预先存在 (stash 前后都有), 跟本次改动无关, 不阻塞. Co-Authored-By: Claude <[email protected]>
This commit is contained in:
1 parent
4bcea922c2
commit
75d73a8e53
2 files changed
+689
No files matched your search
@@ -0,0 +1,256 @@
|
||||
/**
|
||||
* commands/form/_smart_props.ts — AI 组件属性智能选配 (v0.16+ NEW, 2026-07-07)
|
||||
*
|
||||
* **背景**: dacli form create --ai 走 NCPF AI + web buildFormData, 但 buildFormData 只填
|
||||
* 字段名 + jnpfKey + label, 不填组件属性 (dictionaryType/min-max/modelId/regList).
|
||||
* 这是 dacli form audit (BS-新61~64) 暴露的盲点根因.
|
||||
*
|
||||
* **v0.16+ 设计原则** (用户反馈 2026-07-07):
|
||||
* **单一源 = AI 推理, 无 fallback**. 用户明确指出 v0.15+ 关键词法 + AI 双系统并存会混乱 (调试噩梦).
|
||||
* AI 失败 → 不填, 留 audit 兜底. 单一系统, 行为可预测.
|
||||
*
|
||||
* **vs _relationForm_auto.ts**: 已存在, 单点启发式 (input FK→relationForm).
|
||||
* smartProps 是其超集, 包含 BS-新61/63/64.
|
||||
*
|
||||
* **合规**: 不改 jnpf/NCPF/web (CLAUDE.md §11.5). AI 推理走 ssw-common 扩展层.
|
||||
*
|
||||
* **用法** (在 form/create.ts --ai 路径):
|
||||
* const ctx = await loadSmartPropsContext(c)
|
||||
* const { formData, applied } = await applySmartProps(formData, ctx, { verbose: true })
|
||||
* // AI 失败时 applied=[] , 不填, 留 audit 兜底
|
||||
*/
|
||||
import { log } from '../../core/log.ts'
|
||||
import { initWebapi, loadDict } from '../../webapi/dict.ts'
|
||||
import { initWebapi as initWebapiVisual, loadVisualDev } from '../../webapi/visualDev.ts'
|
||||
import type { JnpfClient } from '../../core/client.ts'
|
||||
|
||||
// ============================================================================
|
||||
// 类型
|
||||
// ============================================================================
|
||||
|
||||
export interface SmartPropsContext {
|
||||
/** 已有字典 (enCode + fullName + id) */
|
||||
dicts: Array<{ id: string; enCode: string; fullName: string }>
|
||||
/** 已有 form (enCode + fullName + id) */
|
||||
forms: Array<{ id: string; enCode: string; fullName: string }>
|
||||
}
|
||||
|
||||
export interface SmartPropsApplied {
|
||||
field: string
|
||||
bs: string
|
||||
rule: string
|
||||
matched: string // LLM 推理理由 (reason)
|
||||
}
|
||||
|
||||
export interface SmartPropsOptions {
|
||||
verbose?: boolean
|
||||
}
|
||||
|
||||
export interface SmartPropsResult {
|
||||
formData: any
|
||||
applied: SmartPropsApplied[]
|
||||
/** 'ai' = LLM 推理成功, 'none' = AI 失败/无字段, 不填 (audit 兜底) */
|
||||
source: 'ai' | 'none'
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 上下文加载 (跟 v0.15+ 一样)
|
||||
// ============================================================================
|
||||
|
||||
export async function loadSmartPropsContext(c: JnpfClient): Promise<SmartPropsContext> {
|
||||
let dicts: Array<{ id: string; enCode: string; fullName: string }> = []
|
||||
try {
|
||||
await initWebapi(c)
|
||||
const r = (await loadDict.getDictionaryAll()) as any
|
||||
const allList = Array.isArray(r) ? r : (r?.data?.list || r?.list || [])
|
||||
const recurse = (n: any) => {
|
||||
if (n?.enCode) dicts.push({ id: n.id, enCode: n.enCode, fullName: n.fullName || '' })
|
||||
if (Array.isArray(n?.children)) n.children.forEach(recurse)
|
||||
}
|
||||
allList.forEach(recurse)
|
||||
} catch (e) {
|
||||
log.warn(`smartProps: 加载字典失败 (${(e as Error).message.slice(0, 60)})`)
|
||||
}
|
||||
|
||||
let forms: Array<{ id: string; enCode: string; fullName: string }> = []
|
||||
try {
|
||||
await initWebapiVisual(c)
|
||||
const r = (await loadVisualDev.getVisualDevList({ currentPage: 1, pageSize: 500 })) as any
|
||||
const list = Array.isArray(r?.data?.list) ? r.data.list : Array.isArray(r?.list) ? r.list : []
|
||||
for (const f of list) {
|
||||
if (f?.enCode) forms.push({ id: String(f.id), enCode: f.enCode, fullName: f.fullName || '' })
|
||||
}
|
||||
} catch (e) {
|
||||
log.warn(`smartProps: 加载 form 列表失败 (${(e as Error).message.slice(0, 60)})`)
|
||||
}
|
||||
|
||||
return { dicts, forms }
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// v0.16+ 主路径 (单一 AI 推理, 无 fallback)
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* 调 SSW /ssw/ai/infer-component-props 端点, 让 LLM 推理每个字段的组件属性.
|
||||
*
|
||||
* 失败返回 null (调用方不填任何字段, 留 audit 兜底).
|
||||
*/
|
||||
async function callAiInferComponentProps(
|
||||
fieldsJson: string,
|
||||
dictsJson: string,
|
||||
formsJson: string,
|
||||
): Promise<Array<{
|
||||
vModel: string
|
||||
dictionaryType?: string | null
|
||||
min?: number | null
|
||||
max?: number | null
|
||||
modelId?: string | null
|
||||
regList?: Array<{ pattern: string; message: string }> | null
|
||||
reason?: string
|
||||
}> | null> {
|
||||
try {
|
||||
const { JnpfClient } = await import('../../core/client.ts')
|
||||
const c = await JnpfClient.fromToken()
|
||||
const r = (await c.postJson('/ssw/ai/infer-component-props', {
|
||||
fields: fieldsJson,
|
||||
dicts: dictsJson,
|
||||
forms: formsJson,
|
||||
})) as { code: number; data?: { props?: any[] }; msg?: string }
|
||||
|
||||
if (r.code !== 200 || !r.data?.props) {
|
||||
log.warn(`AI 推理失败: code=${r.code} msg=${r.msg?.slice(0, 80)}`)
|
||||
return null
|
||||
}
|
||||
return r.data.props
|
||||
} catch (e) {
|
||||
log.warn(`AI 推理异常: ${(e as Error).message.slice(0, 80)}`)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 主函数: applySmartProps (AI 单一源, 无关键词 fallback)
|
||||
// ============================================================================
|
||||
|
||||
export async function applySmartProps(
|
||||
formData: any,
|
||||
ctx: SmartPropsContext,
|
||||
options?: SmartPropsOptions,
|
||||
): Promise<SmartPropsResult> {
|
||||
const applied: SmartPropsApplied[] = []
|
||||
const verbose = options?.verbose ?? false
|
||||
|
||||
let fields: any[] = []
|
||||
if (typeof formData?.fields === 'string') {
|
||||
try { fields = JSON.parse(formData.fields) } catch { /* keep */ }
|
||||
} else if (Array.isArray(formData?.fields)) {
|
||||
fields = formData.fields
|
||||
}
|
||||
|
||||
if (fields.length === 0) {
|
||||
return { formData, applied, source: 'none' }
|
||||
}
|
||||
|
||||
// === 1) 准备 AI 输入 ===
|
||||
const aiFieldsInput = fields.map((f: any) => ({
|
||||
vModel: f.__vModel__ || '',
|
||||
jnpfKey: f.__config__?.jnpfKey || '',
|
||||
label: f.__config__?.label || f.__vModel__ || '',
|
||||
})).filter((x: any) => x.vModel)
|
||||
|
||||
// === 2) 调 AI 推理 (单一路径) ===
|
||||
const aiProps = await callAiInferComponentProps(
|
||||
JSON.stringify(aiFieldsInput),
|
||||
JSON.stringify(ctx.dicts),
|
||||
JSON.stringify(ctx.forms),
|
||||
)
|
||||
|
||||
// AI 失败 → 不填任何字段, source='none', audit 兜底 (用户原则)
|
||||
if (!aiProps) {
|
||||
if (verbose) log.warn(`smartProps: AI 失败, 不填任何组件属性 (audit 兜底)`)
|
||||
return { formData, applied, source: 'none' }
|
||||
}
|
||||
if (verbose) log.info(`smartProps: AI 推理 ${aiProps.length} 字段 props`)
|
||||
|
||||
const aiByVModel: Record<string, any> = {}
|
||||
for (const p of aiProps) {
|
||||
if (p.vModel) aiByVModel[p.vModel] = p
|
||||
}
|
||||
|
||||
// === 3) 应用 AI 结果 (唯一来源) ===
|
||||
for (const field of fields) {
|
||||
const cfg = field.__config__ || {}
|
||||
const vm = field.__vModel__ || ''
|
||||
const jk = cfg.jnpfKey || ''
|
||||
if (!vm) continue
|
||||
|
||||
const aiProp = aiByVModel[vm]
|
||||
if (!aiProp) continue
|
||||
|
||||
// BS-新61: select 字段字典
|
||||
if (jk === 'select' && aiProp.dictionaryType && !cfg.dictionaryType) {
|
||||
cfg.dictionaryType = aiProp.dictionaryType
|
||||
cfg.dataType = 'dictionary'
|
||||
const matched = ctx.dicts.find((d: any) => d.id === aiProp.dictionaryType)
|
||||
applied.push({
|
||||
field: vm,
|
||||
bs: 'BS-新61',
|
||||
rule: `select 字典 = ${matched?.enCode || aiProp.dictionaryType}`,
|
||||
matched: aiProp.reason || 'AI 推理',
|
||||
})
|
||||
if (verbose) log.info(`✓ [BS-新61] ${vm}: select 字典 → ${matched?.enCode}`)
|
||||
}
|
||||
|
||||
// BS-新63: inputNumber 范围
|
||||
if (jk === 'inputNumber') {
|
||||
const hasMin = cfg.min !== undefined && cfg.min !== null && cfg.min !== ''
|
||||
const hasMax = cfg.max !== undefined && cfg.max !== null && cfg.max !== ''
|
||||
if (!hasMin && !hasMax && (aiProp.min !== null || aiProp.max !== null)) {
|
||||
if (aiProp.min !== undefined && aiProp.min !== null) cfg.min = aiProp.min
|
||||
if (aiProp.max !== undefined && aiProp.max !== null) cfg.max = aiProp.max
|
||||
applied.push({
|
||||
field: vm,
|
||||
bs: 'BS-新63',
|
||||
rule: `inputNumber (${cfg.min ?? '-'} ~ ${cfg.max ?? '∞'})`,
|
||||
matched: aiProp.reason || 'AI 推理',
|
||||
})
|
||||
if (verbose) log.info(`✓ [BS-新63] ${vm}: inputNumber (${cfg.min ?? '-'} ~ ${cfg.max ?? '∞'})`)
|
||||
}
|
||||
}
|
||||
|
||||
// BS-新62: input FK → relationForm
|
||||
if (jk === 'input' && /(_id|_fk|_code|identifier)$/i.test(vm) && aiProp.modelId) {
|
||||
cfg.jnpfKey = 'relationForm'
|
||||
cfg.modelId = aiProp.modelId
|
||||
applied.push({
|
||||
field: vm,
|
||||
bs: 'BS-新62',
|
||||
rule: `relationForm → ${aiProp.modelId}`,
|
||||
matched: aiProp.reason || 'AI 推理',
|
||||
})
|
||||
if (verbose) log.info(`✓ [BS-新62] ${vm}: relationForm → ${aiProp.modelId}`)
|
||||
}
|
||||
|
||||
// BS-新64: input regList
|
||||
if (jk === 'input' && aiProp.regList?.length && !cfg.regList?.length) {
|
||||
cfg.regList = aiProp.regList
|
||||
applied.push({
|
||||
field: vm,
|
||||
bs: 'BS-新64',
|
||||
rule: `regList = ${aiProp.regList[0].message}`,
|
||||
matched: aiProp.reason || 'AI 推理',
|
||||
})
|
||||
if (verbose) log.info(`✓ [BS-新64] ${vm}: regList = ${aiProp.regList[0].message}`)
|
||||
}
|
||||
}
|
||||
|
||||
// 写回 formData
|
||||
if (typeof formData?.fields === 'string') {
|
||||
formData.fields = JSON.stringify(fields)
|
||||
} else {
|
||||
formData.fields = fields
|
||||
}
|
||||
|
||||
return { formData, applied, source: 'ai' }
|
||||
}
|
||||
@@ -0,0 +1,433 @@
|
||||
/**
|
||||
* commands/form/audit.ts — `dacli form audit` 业务盲点审计 (v0.14+ NEW, 2026-07-07)
|
||||
*
|
||||
* **4 步法源头** (dacli-ts/references/dacli-dev-workflow.md):
|
||||
* 1. 读源码: form/_validate.ts + _blindspot_guards.ts + web Form.vue (web 端源文件)
|
||||
* 2. 理解意图: dos 26 P0 业务漏洞 (testspace 复现坐实, 2026-07-07)
|
||||
* 3. 镜像设计: 不改 JNPF 后端, 在 dacli 检测 schema 层盲点, 输出 fix 建议
|
||||
* 4. 实现: 4 类盲点 + JSON 输出 + 退出码 (0=clean, 1=有盲点)
|
||||
*
|
||||
* **4 类盲点** (源: docs/dos/debug.md §5.2 真实业务漏洞测试):
|
||||
* BS-新61: select 字段空字典 (dictionaryType="") → 字典枚举丢失
|
||||
* BS-新62: input 字段命名像 FK (_id/_code/_identifier) 但 jnpfKey=input
|
||||
* → 应 relationForm, 当前写死字符串
|
||||
* BS-新63: inputNumber 字段无 min/max 范围 → 负数/超大值可写入
|
||||
* BS-新64: formData.formRules 字段缺失或空模板 → 业务校验整体缺失
|
||||
*
|
||||
* **vs _blindspot_guards.ts** (16 条运行时 guard):
|
||||
* - _blindspot_guards: 创建时 guard (在 form create / dm create / menu create 触发)
|
||||
* - form audit: 审计已存在 form 的 schema 盲点 (post-hoc 检测)
|
||||
*
|
||||
* **用法**:
|
||||
* dacli form audit --formId=844085364627865925 # 单 form
|
||||
* dacli form audit --enCode=testAuditForm # 按 enCode
|
||||
* dacli form audit --all # 当前 app 全 form
|
||||
* dacli form audit --all --check=select-dict # 只查空字典
|
||||
* dacli form audit --all --json # JSON 输出
|
||||
*
|
||||
* **退出码**:
|
||||
* 0 = 无盲点
|
||||
* 1 = 有盲点
|
||||
* 2 = 命令错误
|
||||
*
|
||||
* **镜像 web 端**:
|
||||
* - 字段渲染: formData.fields (主+子表) - 镜像 web FormGenerator.vue (drawingList L256-258)
|
||||
* - 字典: formData.fields[].__config__.dictionaryType - 镜像 web Select 控件 (RSelect.vue:201)
|
||||
* - 数字范围: formData.fields[].__config__.min/max - 镜像 web InputNumber (RInputNumber.vue:50)
|
||||
* - 校验: formData.formRules - 镜像 web FormGenerator.getData() validate (L289-310)
|
||||
* - columnList 完整性: columnData.columnList[].prop - 镜像 web ColumnDesign/Main.vue (L222-247)
|
||||
*
|
||||
* **镜像后端**:
|
||||
* - GET /visualdev/Base/{id} → 返回 formData/columnData/tables (jnpf/jnpf/VisualdevController.java:L57 getInfo)
|
||||
* - GET /visualdev/Base (list) → 返回 form 列表 (jnpf/jnpf/VisualdevController.java:L168 list)
|
||||
* - 注: webapi 镜像层在 dacli/src/webapi/visualDev.ts:36 getInfo / :30 create
|
||||
*/
|
||||
import { Command } from 'commander'
|
||||
import { JnpfClient } from '../../core/client.ts'
|
||||
import { installAiHelpHook } from '../../core/help.ts'
|
||||
import { log, printJson } from '../../core/log.ts'
|
||||
import { initWebapi, loadVisualDev } from '../../webapi/visualDev.ts'
|
||||
|
||||
// ============================================================================
|
||||
// 盲点类型 (v0.14+ BS-新61~64)
|
||||
// ============================================================================
|
||||
|
||||
interface AuditIssue {
|
||||
/** 盲点编号 (BS-新61/62/63/64) */
|
||||
bs: string
|
||||
/** 严重度: ERROR=阻塞, WARN=警告 */
|
||||
level: 'ERROR' | 'WARN'
|
||||
/** 字段 vModel (form-level 盲点此字段空) */
|
||||
field: string
|
||||
/** 字段 label (人类可读) */
|
||||
label: string
|
||||
/** 描述 */
|
||||
message: string
|
||||
/** 修复建议 (命令级) */
|
||||
fix: string
|
||||
}
|
||||
|
||||
interface AuditResult {
|
||||
formId: string
|
||||
enCode: string
|
||||
fullName: string
|
||||
issues: AuditIssue[]
|
||||
/** 各盲点计数 */
|
||||
summary: { 'BS-新61': number; 'BS-新62': number; 'BS-新63': number; 'BS-新64': number }
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 盲点检测函数
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* BS-新61: select 字段空字典
|
||||
* 检测 formData.fields[].__config__.jnpfKey='select' && dictionaryType='' (空字符串)
|
||||
*/
|
||||
function checkEmptyDictField(fields: any[]): AuditIssue[] {
|
||||
const issues: AuditIssue[] = []
|
||||
const loop = (items: any[], prefix = '') => {
|
||||
if (!Array.isArray(items)) return
|
||||
for (const f of items) {
|
||||
const cfg = f?.__config__ || {}
|
||||
const vm = f?.__vModel__ || ''
|
||||
const label = cfg?.label || vm
|
||||
const jk = cfg?.jnpfKey || ''
|
||||
const dictType = cfg?.dictionaryType || ''
|
||||
|
||||
if (jk === 'select' && !dictType) {
|
||||
issues.push({
|
||||
bs: 'BS-新61',
|
||||
level: 'ERROR',
|
||||
field: prefix + vm,
|
||||
label,
|
||||
message: `select 字段 dictionaryType="" (空字典, 浏览器下拉 0 选项, 任意 int 可写入)`,
|
||||
fix: `SQL: UPDATE j62.base_visual_release.f_form_data SET f_form_data = REPLACE(f_form_data, '"dictionaryType":""', '"dictionaryType":"<s52.xxx>"') WHERE f_id=<formId>; 或 dacli dict typeCreate + dacli form update 字段配置`,
|
||||
})
|
||||
}
|
||||
|
||||
// 递归子表
|
||||
if (cfg?.jnpfKey === 'table' && Array.isArray(cfg?.children)) {
|
||||
loop(cfg.children, prefix + vm + '.')
|
||||
} else if (Array.isArray(cfg?.children) && cfg?.jnpfKey !== 'table') {
|
||||
loop(cfg.children, prefix)
|
||||
}
|
||||
}
|
||||
}
|
||||
loop(fields)
|
||||
return issues
|
||||
}
|
||||
|
||||
/**
|
||||
* BS-新62: input 字段命名像 FK 但 jnpfKey=input
|
||||
* 检测 vModel 匹配 /_id$|_fk$|_code$|identifier$/i 但 jnpfKey='input'
|
||||
* 期望 jnpfKey='relationForm' (但实际可能没设 modelId)
|
||||
*/
|
||||
function checkInputAsFkField(fields: any[]): AuditIssue[] {
|
||||
const issues: AuditIssue[] = []
|
||||
const FK_PATTERN = /(_id|_fk|_code|identifier|关联.*id)$/i
|
||||
const loop = (items: any[], prefix = '') => {
|
||||
if (!Array.isArray(items)) return
|
||||
for (const f of items) {
|
||||
const cfg = f?.__config__ || {}
|
||||
const vm = f?.__vModel__ || ''
|
||||
const label = cfg?.label || vm
|
||||
const jk = cfg?.jnpfKey || ''
|
||||
|
||||
if (jk === 'input' && FK_PATTERN.test(vm)) {
|
||||
issues.push({
|
||||
bs: 'BS-新62',
|
||||
level: 'ERROR',
|
||||
field: prefix + vm,
|
||||
label,
|
||||
message: `input 字段命名像 FK (匹配 ${FK_PATTERN}) 但 jnpfKey=input, 应改 jnpfKey='relationForm' + modelId=<关联表 enCode>`,
|
||||
fix: `dacli form update <formId> --field ${vm}=relationForm --modelId=<关联表 enCode>; 注意 columnOptions ≤ 5 列`,
|
||||
})
|
||||
}
|
||||
|
||||
if (cfg?.jnpfKey === 'table' && Array.isArray(cfg?.children)) {
|
||||
loop(cfg.children, prefix + vm + '.')
|
||||
} else if (Array.isArray(cfg?.children) && cfg?.jnpfKey !== 'table') {
|
||||
loop(cfg.children, prefix)
|
||||
}
|
||||
}
|
||||
}
|
||||
loop(fields)
|
||||
return issues
|
||||
}
|
||||
|
||||
/**
|
||||
* BS-新63: inputNumber 字段无 min/max 范围
|
||||
* 检测 jnpfKey='inputNumber' 但 __config__ 无 min/max 或 controls.min/max
|
||||
*/
|
||||
function checkNumberRangeField(fields: any[]): AuditIssue[] {
|
||||
const issues: AuditIssue[] = []
|
||||
const loop = (items: any[], prefix = '') => {
|
||||
if (!Array.isArray(items)) return
|
||||
for (const f of items) {
|
||||
const cfg = f?.__config__ || {}
|
||||
const vm = f?.__vModel__ || ''
|
||||
const label = cfg?.label || vm
|
||||
const jk = cfg?.jnpfKey || ''
|
||||
|
||||
if (jk === 'inputNumber') {
|
||||
const hasMin = cfg?.min !== undefined && cfg?.min !== null && cfg?.min !== ''
|
||||
const hasMax = cfg?.max !== undefined && cfg?.max !== null && cfg?.max !== ''
|
||||
// JNPF 实际: min/max 在 cfg 或 controls (vxe-input-number)
|
||||
const controls = cfg?.controls || f?.controls || {}
|
||||
const cMin = controls.min ?? cfg?.min
|
||||
const cMax = controls.max ?? cfg?.max
|
||||
if ((cMin === undefined || cMin === null || cMin === '') && (cMax === undefined || cMax === null || cMax === '')) {
|
||||
// 不阻断 (inputNumber 业务上可能不需要范围, 如 id 自增), 但 WARN
|
||||
issues.push({
|
||||
bs: 'BS-新63',
|
||||
level: 'WARN',
|
||||
field: prefix + vm,
|
||||
label,
|
||||
message: `inputNumber 字段无 min/max 范围 (负数/超大值可写入, 业务规则缺失)`,
|
||||
fix: `dacli form update <formId> --field ${vm}=inputNumber --min=<n> --max=<n>; 或 ssw-dos 加 @Min @Max 注解 (CLAUDE.md §11)`,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (cfg?.jnpfKey === 'table' && Array.isArray(cfg?.children)) {
|
||||
loop(cfg.children, prefix + vm + '.')
|
||||
} else if (Array.isArray(cfg?.children) && cfg?.jnpfKey !== 'table') {
|
||||
loop(cfg.children, prefix)
|
||||
}
|
||||
}
|
||||
}
|
||||
loop(fields)
|
||||
return issues
|
||||
}
|
||||
|
||||
/**
|
||||
* BS-新64: formData.formRules 字段缺失或空模板
|
||||
* 检测 formData.formRules 未填具体规则 (只是 'rules' 字符串模板)
|
||||
*/
|
||||
function checkFormRules(formData: any): AuditIssue[] {
|
||||
const issues: AuditIssue[] = []
|
||||
const rules = formData?.formRules
|
||||
// JNPF 默认 formRules 是字符串 'rules' (Vue form 变量名), 实际校验在 formData.fields[].__config__.regList
|
||||
// 业务校验应填: formData.fields[].__config__.regList: [{pattern, message}]
|
||||
// 这里粗略判定: 如果 formRules 是 'rules' 占位符, 触发 WARN
|
||||
if (!rules || rules === 'rules' || (typeof rules === 'string' && rules.length < 20)) {
|
||||
issues.push({
|
||||
bs: 'BS-新64',
|
||||
level: 'WARN',
|
||||
field: '',
|
||||
label: '<form-level>',
|
||||
message: `formData.formRules 缺失或空模板 (字符串 "${rules}"), 业务校验整体缺失`,
|
||||
fix: `对每个 formData.fields[].__config__.regList 加 [{pattern, message}], 或 ssw-dos 业务包加 @Min @Max @Pattern 注解`,
|
||||
})
|
||||
}
|
||||
return issues
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 主命令
|
||||
// ============================================================================
|
||||
|
||||
export function buildFormAuditCommand(): Command {
|
||||
const cmd = new Command('audit')
|
||||
.description('审计表单业务盲点 (BS-新61~64, v0.14+ NEW, 镜像 web FormGenerator schema 检测 dos 26 P0 + testspace 复现坐实)')
|
||||
.option('--formId <id>', '审计单 form (按 formId, 优先于 --enCode)')
|
||||
.option('--enCode <code>', '审计单 form (按 enCode, 用当前 app 列表查 formId)')
|
||||
.option('--all', '审计当前 app 所有已发布 form', false)
|
||||
.option('--check <type>', '只查指定类型 (select-dict | input-fk | number-range | form-rules), 默认全查')
|
||||
.option('--json', 'JSON 输出 (供脚本处理)', false)
|
||||
.action(async (opts: {
|
||||
formId?: string
|
||||
enCode?: string
|
||||
all?: boolean
|
||||
check?: string
|
||||
json?: boolean
|
||||
}) => {
|
||||
const c = await JnpfClient.fromToken()
|
||||
await initWebapi(c)
|
||||
|
||||
let formIds: string[] = []
|
||||
|
||||
if (opts.formId) {
|
||||
formIds = [opts.formId]
|
||||
} else if (opts.enCode) {
|
||||
// 通过 form list 找 enCode
|
||||
const list = (await loadVisualDev.getVisualDevList({ currentPage: 1, pageSize: 200 })) as any
|
||||
const records = Array.isArray(list?.data?.list) ? list.data.list : Array.isArray(list?.list) ? list.list : []
|
||||
const match = records.find((r: any) => r?.enCode === opts.enCode)
|
||||
if (!match) {
|
||||
log.error(`enCode="${opts.enCode}" 不在当前 app 的 form 列表中`)
|
||||
process.exit(2)
|
||||
}
|
||||
formIds = [String(match.id)]
|
||||
} else if (opts.all) {
|
||||
const list = (await loadVisualDev.getVisualDevList({ currentPage: 1, pageSize: 500 })) as any
|
||||
const records = Array.isArray(list?.data?.list) ? list.data.list : Array.isArray(list?.list) ? list.list : []
|
||||
formIds = records.map((r: any) => String(r.id))
|
||||
if (formIds.length === 0) {
|
||||
log.warn('当前 app 没有任何 form')
|
||||
if (opts.json) printJson({ totalForms: 0, totalIssues: 0, results: [] })
|
||||
process.exit(0)
|
||||
}
|
||||
} else {
|
||||
log.error('必传 --formId / --enCode / --all 之一')
|
||||
process.exit(2)
|
||||
}
|
||||
|
||||
// 决定要跑哪些 check
|
||||
const checkMap: Record<string, boolean> = {
|
||||
'select-dict': true,
|
||||
'input-fk': true,
|
||||
'number-range': true,
|
||||
'form-rules': true,
|
||||
}
|
||||
if (opts.check) {
|
||||
for (const k of Object.keys(checkMap)) checkMap[k] = false
|
||||
if (opts.check in checkMap) checkMap[opts.check] = true
|
||||
else {
|
||||
log.error(`--check 必须是 select-dict / input-fk / number-range / form-rules 之一`)
|
||||
process.exit(2)
|
||||
}
|
||||
}
|
||||
|
||||
// 跑审计
|
||||
const allResults: AuditResult[] = []
|
||||
let totalIssues = 0
|
||||
|
||||
for (const formId of formIds) {
|
||||
let detail: any
|
||||
try {
|
||||
detail = (await loadVisualDev.getInfo(formId)) as any
|
||||
} catch (e) {
|
||||
log.error(`getInfo 失败 (formId=${formId}): ${(e as Error).message}`)
|
||||
continue
|
||||
}
|
||||
if (!detail || (detail.code !== undefined && detail.code !== 200)) {
|
||||
log.error(`form schema 异常 (formId=${formId}): ${JSON.stringify(detail).slice(0, 100)}`)
|
||||
continue
|
||||
}
|
||||
|
||||
// 解码 formData escaped JSON
|
||||
let formData: any = detail.formData
|
||||
if (typeof formData === 'string') {
|
||||
try { formData = JSON.parse(formData) } catch { /* keep */ }
|
||||
}
|
||||
if (!formData || typeof formData !== 'object') {
|
||||
log.warn(`formData 解析失败 (formId=${formId}), 跳过`)
|
||||
continue
|
||||
}
|
||||
|
||||
const fields = formData.fields || []
|
||||
const issues: AuditIssue[] = []
|
||||
if (checkMap['select-dict']) issues.push(...checkEmptyDictField(fields))
|
||||
if (checkMap['input-fk']) issues.push(...checkInputAsFkField(fields))
|
||||
if (checkMap['number-range']) issues.push(...checkNumberRangeField(fields))
|
||||
if (checkMap['form-rules']) issues.push(...checkFormRules(formData))
|
||||
|
||||
const summary = {
|
||||
'BS-新61': issues.filter(i => i.bs === 'BS-新61').length,
|
||||
'BS-新62': issues.filter(i => i.bs === 'BS-新62').length,
|
||||
'BS-新63': issues.filter(i => i.bs === 'BS-新63').length,
|
||||
'BS-新64': issues.filter(i => i.bs === 'BS-新64').length,
|
||||
}
|
||||
|
||||
allResults.push({
|
||||
formId: String(formId),
|
||||
enCode: detail.enCode || '',
|
||||
fullName: detail.fullName || '',
|
||||
issues,
|
||||
summary,
|
||||
})
|
||||
totalIssues += issues.length
|
||||
}
|
||||
|
||||
// 输出
|
||||
if (opts.json) {
|
||||
printJson({
|
||||
totalForms: allResults.length,
|
||||
totalIssues,
|
||||
results: allResults,
|
||||
})
|
||||
process.exit(totalIssues > 0 ? 1 : 0)
|
||||
}
|
||||
|
||||
// Markdown 报告
|
||||
const md: string[] = []
|
||||
md.push('# dacli form audit 业务盲点审计报告\n')
|
||||
md.push(`> **v0.14+ NEW (2026-07-07)** — 源: dos 26 P0 真实业务漏洞测试 + testspace 复现坐实 (CLAUDE.md §13)\n`)
|
||||
md.push(`审计 form 数: **${allResults.length}** | 盲点总数: **${totalIssues}**\n`)
|
||||
md.push(`\n## BS 编号映射\n`)
|
||||
md.push(`| BS | 含义 | 严重度 |`)
|
||||
md.push(`|----|------|--------|`)
|
||||
md.push(`| BS-新61 | select 字段空字典 | ERROR |`)
|
||||
md.push(`| BS-新62 | input 字段当 FK 用 | ERROR |`)
|
||||
md.push(`| BS-新63 | inputNumber 无范围 | WARN |`)
|
||||
md.push(`| BS-新64 | formRules 缺失 | WARN |`)
|
||||
md.push(`\n## per-form 结果\n`)
|
||||
md.push(`| formId | enCode | fullName | BS-新61 | BS-新62 | BS-新63 | BS-新64 | 总数 |`)
|
||||
md.push(`|--------|--------|----------|--------|--------|--------|--------|------|`)
|
||||
for (const r of allResults) {
|
||||
md.push(`| ${r.formId} | ${r.enCode} | ${r.fullName} | ${r.summary['BS-新61']} | ${r.summary['BS-新62']} | ${r.summary['BS-新63']} | ${r.summary['BS-新64']} | ${r.issues.length} |`)
|
||||
}
|
||||
|
||||
const formsWithIssues = allResults.filter(r => r.issues.length > 0)
|
||||
if (formsWithIssues.length > 0) {
|
||||
md.push(`\n## 详细盲点 (${formsWithIssues.length} 个 form)\n`)
|
||||
for (const r of formsWithIssues) {
|
||||
md.push(`\n### ${r.fullName} (\`${r.enCode}\`, formId=${r.formId})\n`)
|
||||
md.push(`| BS | 严重度 | 字段 | label | 描述 |`)
|
||||
md.push(`|----|--------|------|-------|------|`)
|
||||
for (const i of r.issues) {
|
||||
md.push(`| ${i.bs} | ${i.level} | ${i.field || '<form>'} | ${i.label} | ${i.message} |`)
|
||||
}
|
||||
md.push(`\n**修复建议**:`)
|
||||
// 去重 fix (相同 BS+field 只列一次)
|
||||
const seenFix = new Set<string>()
|
||||
for (const i of r.issues) {
|
||||
const k = `${i.bs}-${i.field}`
|
||||
if (!seenFix.has(k)) {
|
||||
seenFix.add(k)
|
||||
md.push(`- [${i.bs}] \`${i.field}\`: ${i.fix}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
md.push(`\n## ✓ 全部 form 通过审计 (4 类盲点全清)\n`)
|
||||
}
|
||||
|
||||
console.log(md.join('\n'))
|
||||
|
||||
// 退出码: 有盲点 = 1 (供 CI 检测)
|
||||
process.exit(totalIssues > 0 ? 1 : 0)
|
||||
})
|
||||
|
||||
installAiHelpHook(cmd, {
|
||||
purpose: '审计表单业务盲点 (BS-新61~64: select 空字典 / input FK / 数字范围 / formRules 缺失) — 镜像 web FormGenerator + JNPF VisualdevController 后端 schema 检测',
|
||||
required: { '--formId / --enCode / --all': '三选一' },
|
||||
optional: {
|
||||
'--check': 'select-dict / input-fk / number-range / form-rules (默认全查)',
|
||||
'--json': 'JSON 输出 (供脚本处理)',
|
||||
},
|
||||
example: [
|
||||
'dacli form audit --formId=844085364627865925 # 审计单 form',
|
||||
'dacli form audit --enCode=testAuditForm # 按 enCode',
|
||||
'dacli form audit --all # 当前 app 全部已发布 form',
|
||||
'dacli form audit --all --check=select-dict # 只查空字典',
|
||||
'dacli form audit --all --json | jq .results[].issues # JSON 聚合',
|
||||
],
|
||||
source: {
|
||||
blindspot: 'docs/dos/debug.md §5.2 (dos 26 P0 漏洞) + docs/dos/TC_C_SOURCE_IMPORT.md (testspace 复现)',
|
||||
web: 'web/.../FormGenerator/FormGenerator.vue (字段渲染) + web/.../onlineDev/Form.vue (formRules 配置)',
|
||||
api: '/visualdev/Base/{id} (webapi 镜像 formData/columnData/tables)',
|
||||
},
|
||||
notes: [
|
||||
'**v0.14+ NEW (2026-07-07)**: 沉淀自 dos 数据交付系统真实业务漏洞测试, 4 类盲点 BS-新61~64',
|
||||
'**vs form/_validate.ts**: form create 时校验 (前向), form audit 是后向审计 (已存在 form)',
|
||||
'**vs _blindspot_guards.ts**: 16 条运行时 guard (创建时), form audit 是 schema 级别 audit',
|
||||
'**退出码**: 0=clean, 1=有盲点 (供 CI pipeline 检测)',
|
||||
'**修复优先级**: BS-新61/62 ERROR 必须修, BS-新63/64 WARN 可后置',
|
||||
'**testspace 复现**: formId=844085364627865925 (testAuditForm) 4 类盲点全命中',
|
||||
],
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
Reference in new issue
Block a user