# ============================================================
# Node.js 后端代码审计规则集
# 作者：DeepSeek
# 版本：1.0.0
# 适用：Node.js / JavaScript / TypeScript 后端项目
# 描述：基于优秀代码评估标准转换的自动化审计规则
# 最后更新：2026-09-08
# ============================================================

metadata:
  name: "Node.js 后端审计规则集"
  version: "1.0.0"
  language: "javascript"
  author: "DeepSeek"
  description: "覆盖命名规范、代码结构、安全性、健壮性、性能、测试、依赖等维度"
  last_updated: "2026-09-08"

rules:
  # ----- 1. 可读性 -----
  # exts 说明（2026-09-13）：代码结构类规则（命名/嵌套/长度）只对**代码文件**生效。
  #   不声明 exts 时会对 md/json/yml 也生效——markdown 文档里的示例代码块
  #   （如 python 块里的 `PY`、JSON 结构里的缩进）会被当成代码误报。
  #   本质：这类规则的判定对象是「代码」，文档不是代码（文档里的示例是文本内容）。
  - id: readability/function-name-camelcase
    name: "函数名使用 camelCase"
    category: "readability"
    severity: "warning"
    description: "函数名应使用 camelCase 命名规范"
    pattern: "^[a-z][a-zA-Z0-9]*$"
    exts: ["js", "mjs", "cjs", "ts", "tsx", "jsx"]
    fixable: false
    examples:
      bad: "function get_user_by_id() {}"
      good: "function getUserById() {}"

  - id: readability/variable-name-camelcase
    name: "变量名使用 camelCase"
    category: "readability"
    severity: "warning"
    description: "变量名应使用 camelCase，避免使用缩写或拼音"
    pattern: "^[a-z][a-zA-Z0-9]*$"
    exts: ["js", "mjs", "cjs", "ts", "tsx", "jsx"]
    fixable: false

  - id: readability/variable-min-length
    external: variable-min-length # 2026-10-05：external 字段 = 具体标识（归属的 audit-ext 扩展脚本名；布尔 true 不合法）——内置停跑，由该 ext 脚本经统一动态入口执行
    name: "变量名长度不少于 2 个字符"
    category: "readability"
    severity: "warning"
    description: "过短的变量名（如 a, b, x）降低代码可读性"
    min_length: 2
    exts: ["js", "mjs", "cjs", "ts", "tsx", "jsx"]
    exceptions: ["i", "j", "k", "n", "e", "cb"]
    # token 级判定层的惯用短名按层豁免：lib/ast/* 与 lib/checks/* 是 token/行级扫描代码，
    #   m（正则匹配）、c/d（token）、q（query）等单字母名作用域极小且是该层通行写法，
    #   改名是高 churn 且易改错 ⇒ 归为误报（自审实测命中 8 条），不按缺陷计
    exclude_paths: ["lib/ast", "lib/checks"]
    fixable: false

  # 坏命名检出增强（bad-naming 样本实测补全）——函数名缩写/万能词/通用词/魔数/嵌套深度
  - id: readability/function-name-too-short
    name: "函数名过短（缩写，无法猜出含义）"
    category: "readability"
    severity: "warning"
    description: "函数名 ≤2 字符是缩写（如 gU），无法从名字猜出含义"
    pattern: "\\bfunction\\s+[a-zA-Z_$][a-zA-Z0-9_$]{0,1}\\s*\\("
    # 2026-09-13 误报修复（正则初筛 → AST 精筛）：i18n 领域标准缩写（tr/t/L 等翻译、
    #   字典函数名）长度 ≤2 但含义公认，纯正则命中即报会把它们当「无法猜出含义」报掉。
    #   astConfirmKind: short-func-name → token 级判定（checkShortFunctionNameAst）：
    #   长度 ≤2 且不在公认缩写白名单（tr/t/L/i18n/db/fs/...）里才报。
    astConfirm: true
    astConfirmKind: short-func-name
    fixable: false
    mitigation: "函数名用有含义的完整单词：getUser / sumArray / buildReport"

  - id: readability/vague-function-name
    name: "函数名万能词（doIt/handle/process 等）"
    category: "readability"
    severity: "warning"
    description: "doIt/handle/process/run/do/exec/doEverything 等万能动词函数名无法表达具体职责，应从名字看出做什么"
    pattern: "\\bfunction\\s+(doIt|doItAll|doEverything|handle|process|run|do|exec|deal|make|thing)\\b\\s*\\("
    fixable: false
    mitigation: "换成具体动作：doIt→submitOrder、handle→handleOrderCancellation、process→parsePayload"

  - id: readability/vague-variable-name
    name: "变量名通用词（data/obj/flag/tmp 等）"
    category: "readability"
    severity: "warning"
    description: "data/obj/flag/tmp/temp/val/value/item/thing 等通用词变量名信息量低，看不出具体内容"
    # 2026-09-27：词表剔除 res——HTTP/git 操作的「Response」标准缩写（res.json / await fetch 的
    #   const res = await ...），语义从上下文清晰，不属 vague。保留 result（信息量确实低）。
    pattern: "\\b(?:const|let|var)\\s+(data|obj|object|flag|tmp|temp|val|value|item|thing|stuff|result)\\b"
    fixable: false
    mitigation: "用内容命名：data→userList、flag→isAdmin、tmp→tempFile"

  # 2026-09-16 合并：readability/magic-number（regex 通道）已并入 readability/magic-number-smart——
  #   smart（AST token 级）覆盖全部数字字面量形态（含运算 `base * 0.2`、比较 `score > 1.5` 里的数字），
  #   regex 通道双报且豁免弱（此前靠 astConfirm 复用 smart 判定），删除避免同一魔数报两条。
  #   命名常量判定已放宽（lib/ast/magic-number.js isNamedConstantValue）：dshgp_*/DEFAULT_*/MAX_* 前缀
  #   常量与含 timeout/limit/size/ms 等语义词尾的常量名不再误报。

  - id: readability/magic-number-smart
    name: "硬编码魔数检测（版本号豁免版）"
    kind: "magic-number-smart"
    category: "readability"
    severity: "warning"
    description: "检测硬编码魔数（\\b\\d{2,}\\b / \\b0x[0-9a-fA-F]+\\b / \\b\\d+\\.\\d+\\b），但自动豁免：版本号（v1.2.3/1.2.3/VERSION 常量）、日期时间（2026-09-12/时间戳/时间）、HTTP 状态码（100-504 清单）、常见合法常量（0/1/-1/60/100/1000/1024/3600/86400 等）、状态枚举（pending/completed 等字符串）；上下文关键字分流——magic_number_hints（timeout/retry/max/min/limit/size/count/port/interval/delay/duration/threshold/buffer/chunk）内的数字报魔数，legitimate_hints（version/date/year/month/day/hour/minute/second/http/status）内的数字豁免；同一数字文件内出现 ≥3 次强制标记"
    magic_number_hints: ["timeout", "retry", "max", "min", "limit", "size", "count", "port", "interval", "delay", "duration", "threshold", "buffer", "chunk"]
    legitimate_hints: ["version", "date", "year", "month", "day", "hour", "minute", "second", "http", "status"]
    force_count: 3
    # 2026-09-13 误报修复：只对代码文件生效（README 版本表 / CSS 尺寸 / config.json 端口不报）
    exts: ["js", "mjs", "cjs", "ts", "tsx", "jsx"]
    fixable: true
    mitigation: "提取命名常量并注释含义：const MAX_RETRY = 3; const API_TIMEOUT_MS = 30000; 版本号/日期/HTTP 状态码/常见常量/状态枚举自动豁免"

  - id: readability/max-nesting-depth
    name: "嵌套过深（缩进层级 > 3）"
    category: "readability"
    severity: "warning"
    description: "代码缩进嵌套超过 3 层（如 for→for→if→if），可读性灾难，应提前 return 或抽函数"
    max_depth: 4
    exts: ["js", "mjs", "cjs", "ts", "tsx", "jsx"]
    fixable: false

  - id: readability/max-function-length
    name: "函数长度不超过 50 行"
    category: "readability"
    severity: "warning"
    description: "过长的函数难以理解和维护"
    max_lines: 50
    exts: ["js", "mjs", "cjs", "ts", "tsx", "jsx"]
    # 2026-09-23 作用域（P1）：启动路径初始化函数（apply/init/main/bootstrap/setup 等）豁免
    # 2026-10-05 作用域（评审规则③）：序列化/反序列化职责函数（serialize/to_json/from_json/
    #   dumps/loads/parse 等）——意义明确、变量生命周期仅当前会话时代码常超百行，过度拆分反而
    #   复杂化数据传递与生命周期处理（得不偿失），豁免函数长度（classifyFunctionPath 返回
    #   serialization 路径）。
    scope_rules:
      - scope: "startup"
        action: "exempt"
        reason: "启动路径初始化函数（一次性执行），阈值不适用"
      - scope: "serialization"
        action: "exempt"
        reason: "序列化/反序列化职责函数：意义明确且变量生命周期仅当前会话，超百行是职责自然形态，过度拆分得不偿失"
    fixable: true

  - id: readability/max-file-length
    name: "文件代码行数不超过 400 行"
    category: "readability"
    severity: "warning"
    description: "单文件代码行超过 400 行时应拆分模块（存量超大文件为已知债务，仅提醒不拦截；D1 重构已拆分核心文件）。代码行口径见 lib/ast/line-count.js（总行 − 纯注释行 − 空行）"
    max_lines: 400
    # 2026-09-23：只对**代码文件**生效——md/yml/json 文档天然长（README/docs 详解/规则包），
    #   文件行数拆分规则针对代码模块；此前无 exts 导致 README 1058 行/docs 详解被误报。
    exts: ["js", "mjs", "cjs", "ts", "tsx", "jsx"]
    # 平台约束降级（DSH 插件专属）：DSH 要求插件的**运行态客户端**是单文件
    #   （dsh.client + exports["./client"] 指向同一文件）——那是**产物**，不是源码形态：
    #   源码可以按分片维护 + 构建拼接（本仓库 lib/client-parts/** → lib/client.js）。
    #   故按两档作用域分别降级（仍出现在报告里，降为 info 且不扣分；
    #   不用 exempt——静默排除会让这个事实从报告里消失）：
    #     · dsh-client-entry    ：那份**产物**本身（运行态单文件，行数天然超长）
    #     · dsh-client-fragment ：**分片源码**（片段：单文件语法不成立，独立看行数超阈值不代表可拆分）
    #   作用域值由 lib/audit/client-entry.js 推导（读 package.json，非写死文件名）。
    #   注意：必须声明在**规则原槽位**——loader 是拼接而非覆盖，写到别的槽位不会生效。
    scope_rules:
      - scope: "dsh-client-entry"
        action: "downgrade"
        reason: "运行态客户端产物本身就是单文件（源码已分片维护 + 构建拼接，见 lib/client-parts/）——降级为提示，仍报不排除"
      - scope: "dsh-client-fragment"
        action: "downgrade"
        reason: "客户端分片是构建片段（拼接后才是完整文件）——单看行数超阈值不构成可拆分问题，降级为提示、仍报不排除"
    fixable: false

  - id: readability/comment-density
    name: "行注释密度过高（注释复述代码）"
    category: "readability"
    severity: "warning"
    description: "变量即注释——语义明确的代码里变量名已表达内容，额外的行注释不加深理解；只保留具有隐性约束、复杂设计、外部契约、非显然决策的块注释，注释应解释「为什么」而非复述「做了什么」"
    threshold: 0.4
    exts: ["js", "mjs", "cjs", "ts", "tsx", "jsx"]
    fixable: false

  # ----- 2. 可维护性 -----
  # 2026-10-05：激活原「死规则」——此前无 kind/检查器，从未执行。
  #   现在由 lib/checks/dup-code.js 消费：跨文件 AST 归一化哈希找「同一函数结构 ≥3 处」。
  #   判定标准（评审确立，量化版）：重复 ≥3 处 + 函数体 ≥5 行 即报；排除参数>5 /
  #   布尔 flag 参数 / test 夹具 / 纯语法糖。severity 恒 warning（只提示不拦截）。
  - id: maintainability/no-duplicate-code
    name: "检测重复代码块（该抽公共函数）"
    category: "maintainability"
    severity: "warning"
    description: "同一逻辑结构在多处重复（≥3 处 + ≥5 行），应抽取公共函数"
    kind: "duplicate-code"
    min_lines: 5
    min_occurrences: 3
    exts: ["js", "mjs", "cjs", "ts", "tsx", "jsx"]
    fixable: true

  # 2026-10-02：同名常量跨文件重复定义（DRY——阈值/长度/窗口等魔数散落多处难维护）。
  #   场景实测：MAX_MSG_PREVIEW=80 在 audit-api/tool-call/commit-push 三处各自定义，
  #   改一处漏三处。规则跨文件聚合 `const NAME = <值>`（同名校同值 ≥2 文件）→ 提示统一单一来源。
  - id: maintainability/duplicate-constant-def
    name: "同名常量跨文件重复定义（应统一单一来源）"
    category: "maintainability"
    severity: "warning"
    description: "同一命名常量（const NAME = 值）在多个文件重复定义——阈值/长度/窗口等魔数散落多处难维护、改一处漏多处；应统一到公共常量模块或配置文件单处定义（DRY）"
    kind: "duplicate-const"
    exts: ["js", "mjs", "cjs", "ts", "tsx", "jsx", "py", "java", "kt", "go", "rs", "swift", "php", "rb"]
    fixable: false
    mitigation: "把重复定义提到公共常量模块（如 lib/app/constants.js）导出，各文件 import 复用"

  - id: maintainability/max-cyclomatic-complexity
    name: "圈复杂度不超过 10（50 以上 blocker）"
    category: "maintainability"
    severity: "blocker"
    description: "圈复杂度评级（2026-10-02 用户口径）：1~10 良好、11~20 中等（warning）、21~50 高风险（warning，应拆分）、50+ 极难维护（blocker 拦提交）——分支点：if/else if 每分支、for/while/do-while、case 每分支、catch、&&/||/??、三元 ?、带标签 break/continue"
    max_complexity: 10
    block_complexity: 50
    # 2026-09-23 作用域（P1）：启动路径初始化函数豁免圈复杂度
    scope_rules:
      - scope: "startup"
        action: "exempt"
        reason: "启动路径初始化函数（一次性执行），阈值不适用"
    fixable: false

  # ----- 3. 健壮性 -----
  # 2026-09-17：由 quality/sync-fs 升级为分级版 io-risk。
  #   旧检查只判「异步函数内的同步 IO」；本检查是其超集，另覆盖：
  #     循环内 I/O（逐次阻塞）、请求处理路径、启动路径，
  #     并区分读/写/删/改名（写删类加权）。两者并存会对同一处重复报，故旧规则已移除。
  #   L1 正则初筛只负责「哪些文件可能含 fs 调用」，定级由 lib/ast/io-risk.js 完成。
  #   展示口径（2026-09-18）：high/medium → warning 且计分（2/1）；low/safe → info 且不计分。
  #     低风险是「启动路径上的一次性同步 I/O」这类提示，不影响并发、不随数据量放大；
  #     按 warning 展示会把 161 条提示与真实高危（仅 12 条）混在一起，淹没重点。
  #     规则级 severity 仍为 warning，具体降级由 lib/checks/regex.js 按 AST 定级覆盖。
  - id: robustness/io-risk
    name: "I/O 风险分级（同步阻塞 / 循环内 / 关键路径）"
    category: "robustness"
    severity: "warning"
    description: "按上下文与操作类别对文件 I/O 分级：异步路径中的同步 I/O、循环内 I/O 为高风险；写/删/改名类加权一档"
    # 维度归属：I/O 风险是性能与健壮性问题，**不是可读性**。
    #   不声明会落到 regex 编译器的默认 [可读性]（实测 190 条全记在可读性上，
    #   把可读性维度从 10 拖到 2.7——而真正的性能/健壮性维度却显示满分，评分失真）。
    dimensions: ["性能", "健壮性"]
    # 2026-09-27：仅代码文件（md 文档的代码块示例是讲解文本，不是运行代码——
    #   README 版本表 / docs 方案文的 fs.readFileSync 示例曾被当真实代码报 io-risk 误报）
    # 2026-10-05：exts 移除 py——io-risk 的 AST 检查器是 JS/Node fs 语法特定
    #   （scanIoRiskAst 只认 fs.xxx / require('node:fs')），Python 的 open/with 不识别；
    #   声明 py 是误导（对 py 文件永不命中）。Python 文件 I/O 由语言规则集另行覆盖。
    exts: ["js", "mjs", "cjs", "ts", "tsx", "jsx"]
    # 三段式：正则初筛（哪些文件可能含 fs 调用）→ AST 精筛（注释/字符串里的示例剔除）
    #   → 分级由 lib/ast/io-risk.js 完成，finding 由 lib/checks/io.js 产出
    astConfirm: true
    astConfirmKind: "io-risk"
    patterns:
      # ① 带 fs. 前缀：fs.readFileSync(...)、fsp.readFile(...)
      - "(fs|fsp|fsPromises)\\.(promises\\.)?(readFile|writeFile|appendFile|stat|lstat|readdir|mkdir|rmdir|rm|unlink|rename|copyFile|chmod|open|close|read|write|truncate|realpath|createReadStream|createWriteStream)(Sync)?\\s*\\("
      # ② 裸调用（具名导入后直调）：import { mkdirSync } from 'node:fs' → mkdirSync(...)
      #    这是最常见写法，此前 patterns 只覆盖带前缀形态，导致大量真实 I/O 漏初筛
      - "(?<![\\w$.])(readFileSync|writeFileSync|appendFileSync|existsSync|statSync|lstatSync|readdirSync|mkdirSync|rmdirSync|rmSync|unlinkSync|renameSync|copyFileSync|chmodSync|openSync|closeSync|readSync|writeSync|truncateSync|realpathSync)\\s*\\("
      # ③ fs 模块导入语句（兜底：文件级信号，具体行由 AST 精筛定位）
      - "(require\\([\"']node:fs[\"']?\\)|from\\s+[\"']node:fs(/promises)?[\"'])"
    fixable: true
    mitigation: "🔴 高风险改用 fs.promises.xxx + await，循环内改为 Promise.all 并发；🟡 启动路径的一次性读取可豁免"

  # 【已撤销】robustness/no-empty-catch —— 与内置 AST 检查器重复报同一批位置。
  #   原规则：pattern "catch\s*\([^)]*\)\s*\{\s*\}"，kind=regex，warning。
  #   撤销理由（实测）：在 archify（641 文件）上，本规则报 1902 条、内置 quality/empty-catch
  #   （lib/checks/structural.js 的 checkEmptyCatchAst，kind=empty-catch）报 1926 条，
  #   两者 (file:line) 交集 1899 条 ⇒ 同一批空 catch 被两条规则各报一遍（合计占总量 24.6%）。
  #   按架构（yml 只声明、判定落 lib/ast）保留**AST 版**：它能识别注释占位/换行/嵌套形态，
  #   正则版只匹配「catch(...){ }」同行闭合，既漏报又重复计数。
  #   如需恢复：把下面三行取消注释即可（保留原字段）。
  #   name: "禁止空的 catch 块" ｜ severity: warning ｜ description: "空的 catch 块会静默吞掉错误"
  #   pattern: "catch\\s*\\([^)]*\\)\\s*\\{\\s*\\}" ｜ mitigation: "至少添加 console.error(e)"

  - id: robustness/input-validation-required
    name: "外部输入必须验证"
    category: "robustness"
    severity: "warning"
    description: "用户输入可能包含恶意数据"
    patterns:
      - "req\\.(params|query|body)"
      - "ctx\\.(params|query|body)"
    fixable: false

  - id: robustness/timeout-on-external-api
    name: "外部 API 调用必须设置超时"
    category: "robustness"
    severity: "warning"
    description: "外部请求无超时设置会导致请求永久挂起"
    # 2026-10-02：限定 js 系代码文件——fetch/axios 是 Node/前端运行时 API，
    #   md/json 等文档/配置里的「外部请求」字样与代码示例不应被扫（Pawchive docs md 实测误报）
    exts: ["js", "mjs", "cjs", "ts", "tsx", "jsx"]
    # 负向后瞻排除自定义封装名（apiFetch/githubFetch 等）——"fetch(" 子串会把
    #   封装调用误报成无超时裸 fetch；封装内部的超时由 file-context.js
    #   hasExternalCallTimeout 语义豁免（行内/行前/行后 12 行含 signal/timeout 即豁免）
    patterns:
      - "(?<![\\w$])(fetch|axios\\.|got\\.|request\\.)\\s*\\("
    fixable: false
    mitigation: "设置 timeout 或 AbortController"

  # ----- 4. 安全性 -----
  # 重复硬编码字符串（repeated-string 类型）——字符串字面量在同文件出现 ≥3 次且不在白名单 → 建议配置化
  - id: security/no-repeated-hardcoded-literals
    name: "检测重复出现的硬编码文本"
    category: "security"
    severity: "warning"
    description: "如果一个字符串（路径、域名、用户名、token、端口、URL 等）在代码中重复出现 3 次或以上，建议提取为常量或配置变量"
    fixable: true
    min_occurrences: 3
    ignore_patterns:
      - "^\\d+$"
      - "^(true|false|null|undefined)$"
      - "^[{}[\\]]$"
      - "^[+\\-*/=]$"
      - "^['\"`]$"
      - "^\\s*$"
      - "^\\\\n$"
      - "^\\d+\\.\\d+$"
      - "^\\.(json|txt|log|md|yaml|yml|html|css|js|mjs|ts|png|jpg|jpeg|gif|svg)$"
      - "^utf-?8$"
      - "^utf-?16le?$"
    ignore_values:
      - "0"
      - "1"
      - "-1"
      - "true"
      - "false"
      - "null"
      - "undefined"
      - "''"
      - '""'
    mitigation: "提取为常量（UPPER_SNAKE_CASE）放入 config/constant.js 或通过环境变量注入"

  - id: security/no-hardcoded-credentials
    name: "禁止硬编码凭据"
    category: "security"
    severity: "error"
    description: "凭据不应硬编码在源代码中"
    # astConfirmKind: credential-value → 正则初筛后由 token 级精筛（checkCredentialRefAst）确认，
    #   只报「凭据标识符右侧直接是有效字符串字面量」的行。豁免：类型/存在性检查
    #   （typeof cfg.githubToken === 'string'）、字段透传（cfg.token = init.token）、
    #   取环境变量/配置（process.env.KEY / options.token）、占位符与空串。
    # 2026-09-21 误报修复（start-preview.mjs 反代服务器场景）：
    #   · 正则加 `(?<![?&/])` 负向断言——排除 `?token=` / `&token=` / `/token=` 这类
    #     **URL 参数名**（如 '/?token=' + encodeURIComponent(token)），URL 带凭据名是
    #     泄露风险但**不是硬编码**，单列 security/no-credential-in-url（warning）覆盖；
    #   · 引号内内容收紧为 `[^'"\s]{8,}`——真实凭据较长，短占位/空串不参与初筛
    #     （AST 精筛仍按 isMeaningfulCredentialValue 判占位符，双层不矛盾）。
    astConfirmKind: credential-value
    patterns:
      - "(?<![?&/])password\\s*[=:]+\\s*['\"][^'\"\\s]{8,}['\"]"
      - "(?<![?&/])secret\\s*[=:]+\\s*['\"][^'\"\\s]{8,}['\"]"
      - "(?<![?&/])api[_-]?key\\s*[=:]+\\s*['\"][^'\"\\s]{8,}['\"]"
      - "(?<![?&/])token\\s*[=:]+\\s*['\"][^'\"\\s]{8,}['\"]"
      - "(?<![?&/])cookie\\s*[=:]+\\s*['\"][^'\"\\s]{8,}['\"]"
    # 2026-09-13 误报修复：正则把「凭据字段引用/API 名/字符串字面量」误判为「凭据值硬编码」。
    #   白名单行豁免——命中以下任一模子的行不报：
    #   · GM_cookie（油猴 GM_cookie API 名，非硬编码值）
    #   · gbCookie / userAgent 等请求字段名（对象字段引用，非值）
    #   · .cookie（对象属性访问 o.cookie / c.cookie，非赋值）
    #   · "Cookie=" 字符串字面量（解析 cookie 头的分隔符，非值）
    #   真凭据（cookie = "sess=..." 赋值）仍正常报出。
    whitelist_patterns:
      - "\\bGM_cookie\\b"
      - "\\bgbCookie\\b"
      - "\\bcookie\\s*[=:]+\\s*(?:[a-zA-Z_$][\\w$]*\\.)?[a-zA-Z_$][\\w$]*\\s*(?:[);,]|$)"  # cookie: o.cookie 属性引用
      - "\\.[a-zA-Z_$][\\w$]*\\.cookie\\b"
      - "\\b[a-zA-Z_$][\\w$]*\\.cookie\\b"
      - "\"Cookie=\""
      - "['\"]Cookie=['\"]"
      - "cookieChars|cookieItems|cookieCount"
      - "mock 密码用变量承载"
      - "完整 Cookie"
    fixable: false
    mitigation: "使用环境变量 process.env.XXX"

  - id: security/no-credential-in-url
    name: "URL 中不应携带凭据参数名"
    category: "security"
    severity: "warning"
    description: "URL 参数/路径中含 token/secret/password 等敏感字段名——凭据可能被浏览器历史/代理日志/Referer 头泄露；非硬编码（硬编码凭据由 no-hardcoded-credentials 管），仅提示"
    # 2026-09-21：从 no-hardcoded-credentials 拆出——`?token=` / `&key=` 这类 URL 参数名
    #   此前被硬编码凭据正则误报（如 '/?token=' + encodeURIComponent(token)，反代服务器认证路径）；
    #   URL 带凭据名本身有泄露风险（日志/历史/Referer），但**不是硬编码**，单列 warning 提示，
    #   与「右值是否为字符串字面量」的硬编码判据彻底分开（见 lib/ast/credential.js scanCredentialTokens）。
    patterns:
      - "[?&](?:token|key|secret|password|passwd|api[_-]?key|cookie|credential|access[_-]?key)=[^&\\s'\"]*"
    fixable: false
    mitigation: "改用 Authorization 头或 POST body 传递凭据，避免出现在 URL（防日志/历史/Referer 泄露）"

  # security/no-path-traversal 已于 2026-10-11 **迁移到 lib/audit-rules/audit-rules-paths.yml**
  #   （路径类规则集中一处；规则 id 与语义未变，此处不再保留副本）。
  # credref-legacy-path 同样迁移至该槽位（见下方原位置指针）。

  # ----- 凭据入库门禁 -----
  # 提交门禁安全底线：新增行命中即拦截提交；severity=error → blocker
  - id: secret-github-pat
    # 占位符精筛：剥掉 ghp_/sk-/AKIA 前缀后再判是否为演示/占位值
    #   （文档里写「测试用占位符 ghp_testtokenplaceholder123」、演示页假数据不应报泄漏）
    astConfirmKind: "placeholder-credential"
    name: "疑似 GitHub PAT 硬编码"
    category: "security"
    severity: "error"
    description: "疑似 GitHub Personal Access Token 硬编码，请确认是否真实凭据"
    pattern: "\\bghp_[A-Za-z0-9]{20,}\\b"
    fixable: false
  - id: secret-openai-key
    # 占位符精筛：剥掉 ghp_/sk-/AKIA 前缀后再判是否为演示/占位值
    #   （文档里写「测试用占位符 ghp_testtokenplaceholder123」、演示页假数据不应报泄漏）
    astConfirmKind: "placeholder-credential"
    name: "疑似 API key 硬编码"
    category: "security"
    severity: "error"
    description: "疑似 OpenAI/API key 硬编码，请确认是否真实凭据"
    pattern: "\\bsk-(proj-)?[A-Za-z0-9-]{16,}\\b"
    fixable: false
  - id: secret-keyvalue
    name: "疑似敏感信息键值对"
    category: "security"
    severity: "error"
    description: "疑似敏感信息（键值对）硬编码，请确认（值捕获组供占位符/假值豁免）"
    pattern: "\\b(api[_-]?key|api[_-]?secret|secret|password|passwd|client[_-]?secret|access[_-]?token|auth[_-]?token|private[_-]?key|bearer|cookie|session[_-]?key)\\b\\s*[:=]\\s*[\"']([^\"'\\s]{8,})[\"']"
    fixable: false
    mitigation: "使用环境变量 process.env.XXX"
  - id: secret-email
    name: "真实邮箱入库（隐私泄漏）"
    category: "security"
    severity: "error"
    description: "疑似真实个人邮箱硬编码/入库（隐私信息），请确认——示例域（example.com）、GitHub 匿名邮箱（users.noreply.github.com）、SSH 地址（git@github.com / git@ssh.github.com）、GitHub token 前缀用户名（ghp_/gho_/ghu_/ghs_/ghr_/github_pat_ 开头的用户名 + github.com 域；token 本体由 secret-github-pat 规则拦截）、本地虚拟域（.local/.lan/.internal/.test）豁免；真实邮箱（如 QQ 号@qq.com 等）一旦进公开仓库可被爬取，招致营销骚扰/社工；确需提交（公开联系方式/测试夹具/版权声明等）时可临时关闭审计再推送（插件设置 →「提交前审计」auditEnabled=false）"
    pattern: "\\b(?!git@(?:ssh\\.)?github\\.com\\b|(?:gh[opsur]_|github_pat_)[A-Za-z0-9_]+@github\\.com\\b)[A-Za-z0-9._%+-]+@(?!example\\.com\\b|users\\.noreply\\.github\\.com\\b|[A-Za-z0-9-]+\\.(?:local|lan|internal|test|invalid|localhost)\\b|[A-Za-z0-9-]+\\.(?:png|jpe?g|gif|webp|svg|avif|ico|bmp|js|mjs|cjs|ts|tsx|jsx|css|scss|less|html?|json|ya?ml|md|markdown|txt|zip|gz|tgz|mp[34]|webm|pdf|woff2?|ttf|eot)\\b)[A-Za-z0-9-]+\\.[A-Za-z]{2,}\\b"
    fixable: false
    mitigation: "真实邮箱不写进代码/文档；示例一律用 your-name@example.com 占位；GitHub 匿名邮箱 users.noreply.github.com 豁免（git 提交默认 author）；已入库的用 git filter 清历史"
  - id: credfile-common
    name: "凭据/密钥文件入库"
    category: "security"
    severity: "error"
    description: "凭据/密钥文件出现在变更中，禁止提交"
    path_pattern: "(^|[\\\\/])(\\.credentials[^\\\\/]*|\\.env|\\.env\\.[a-z]+|github-token|data[\\\\/]sensitive[\\\\/][^\\\\/]*|\\.dsh[\\\\/]git-push[\\\\/])"
    fixable: false
  - id: credfile-token-private
    name: "敏感目录入库"
    category: "security"
    severity: "error"
    description: "敏感配置/私钥目录入库，禁止提交"
    path_pattern: "(^|[\\\\/])(data[\\\\/]sensitive[\\\\/]|dsh-private-configs[\\\\/]|\\.ssh[\\\\/]|private)[\\\\/][^\\\\/]*"
    fixable: false
  # credref-legacy-path 已于 2026-10-11 **迁移到 lib/audit-rules/audit-rules-paths.yml**
  #   （路径类规则集中一处；规则 id 与语义未变，此处不再保留副本）。
  - id: credref-plain-secret
    name: "文档疑似凭据明文"
    category: "security"
    severity: "warning"
    description: "文档疑似含凭据明文：凭据统一存插件配置目录，不在文档写明文"
    # 2026-09-14 误报修复：pattern 只做「正则初筛」，命中后必须经 AST 精筛确认（astConfirmKind）。
    #   旧写法只有 pattern、没有精筛，导致下列**非凭据明文**场景全被报出（实测 5/5 误报）：
    #     - 类型/存在性检查：`typeof cfg.githubToken === 'string'`——旧 pattern 的 `[:：=]`
    #       会命中 `===` 的第 3 个 `=`，再把被比较的字符串字面量 `'string'` 当成明文凭据；
    #       又因 safeRe 默认带 i 标志，`githubToken` 的大写 T 也照样命中。
    #     - 字段透传/引用：`cfg.githubToken = next.githubToken`（右侧是变量，不是字面量）
    #     - 类型注解：JSDoc `@returns {{token: string}}`、`{ token: string }`
    #   credential-value 精筛（lib/ast/credential.js 的 checkCredentialRefAst）在 token 级
    #   只认「凭据语义标识符 + 严格 `=` 或对象字段 `:` + 右侧**字符串字面量** + 非占位符」，
    #   上面三类天然落空；真明文（`password: "hunter2xyz"`）照报。
    #   判据只有一份：同一函数也被 no-hardcoded-credentials 使用，不会出现两规则自相矛盾。
    pattern: "(密码|password|passwd|token|cookie|账号)\\s*[:：=]\\s*['\"]?[A-Za-z0-9_@.\\-]{6,}['\"]?"
    astConfirm: true
    astConfirmKind: "credential-value"
    fixable: false

  - id: security/cookie-secure-flag
    name: "Cookie 必须包含 Secure 和 HttpOnly"
    category: "security"
    severity: "error"
    description: "生产环境 Cookie 必须带 Secure 和 HttpOnly"
    patterns:
      - "Set-Cookie:(?!.*Secure)"
      - "Set-Cookie:(?!.*HttpOnly)"
    # 2026-09-13 误报修复：客户端/油猴脚本里 Set-Cookie: 出现在正则字面量
    #   （match(/Set-Cookie:.../) 读取响应头）或字符串样例，不是服务端写 cookie——
    #   只有「实际设置 cookie 的调用」（setHeader('Set-Cookie' 等）才需要带 Secure/HttpOnly。
    #
    # 2026-09-18 两处修正（误报 + 漏报各一）：
    #   ① 误报：Python/Go 等**读取响应头**的写法没被覆盖，实测
    #      `line.lower().startswith("set-cookie:")` 会报 blocker（真实误报，已在
    #      scripts/migrate-session/lib/follow.py 遇到）。补 startswith/in/headers.get。
    #   ② 漏报（更严重）：原白名单 `['"]Set-Cookie['"]` 只认「字符串里出现 Set-Cookie」，
    #      而**设置**与**读取**都用字符串，于是把真风险 `setHeader("Set-Cookie", ...)`
    #      一并豁免了——与规则本意（只有设置 cookie 才要求 Secure/HttpOnly）正好相反。
    #      改为只豁免「读取语境」：动词为 get/read/startswith/in/match/parse 等。
    #      注意 JS 的 `.get("Set-Cookie")` 与 Node 的 `res.setHeader(...)` 靠动词区分。
    whitelist_patterns:
      # JS：正则字面量读取响应头
      - "match\\s*\\(\\s*/Set-Cookie"
      # 字符串里的转义形态（样例/日志文案）
      - "Set-Cookie:\\\\s"
      # 读取语境（跨语言）：动词在前、Set-Cookie 在后。
      #   注意：白名单**不带 i 标志**（lib/checks/regex.js 用 new RegExp(w) 编译），
      #   而规则 pattern 走 safeRe **带 i**。因此这里用字符类 [Ss] 显式兼容两种大小写，
      #   否则 `startswith("Set-Cookie:")` 会漏网（实测踩到）。
      - "startswith\\s*\\(\\s*['\"][Ss]et-[Cc]ookie"
      - "headers?\\s*\\.\\s*get\\s*\\(\\s*['\"][Ss]et-[Cc]ookie"
      - "\\.\\s*get\\s*\\(\\s*['\"][Ss]et-[Cc]ookie"
      - "getheader\\s*\\(\\s*['\"][Ss]et-[Cc]ookie"
      - "\\.\\s*getall\\s*\\(\\s*['\"][Ss]et-[Cc]ookie"
      # 集合成员判定 / 字典取值（读取响应头）
      - "['\"][Ss]et-[Cc]ookie['\"]\\s+in\\s"
      - "in\\s+\\w+\\.\\s*headers"
      # 解析/日志文案语境（动词为 parse/split/console/log）
      - "(?:parse|[Ss]plit|console|log|print|echo|debug)\\w*\\s*\\([^)]*['\"][Ss]et-[Cc]ookie"
    fixable: true

  - id: security/no-eval
    name: "禁止使用 eval"
    category: "security"
    severity: "error"
    description: "eval 执行任意代码，存在严重安全风险"
    patterns:
      - "(?<![\\w$.])eval\\s*\\("
      - "new Function\\s*\\("
    fixable: false

  # ----- 5. 性能 -----
  - id: performance/no-o-n-squared
    name: "避免 O(n²) 循环嵌套"
    category: "performance"
    severity: "warning"
    description: "嵌套循环可能导致性能问题"
    # astConfirm: true → 正则初筛后由 token 级精筛剔除注释/字符串行。
    #   正则只看字符：注释里写「两种形态：for (...) { ... for (」这类说明会被命中
    #   （实测 lib/ast/io-risk.js 的文档注释被报 O(n²)），精筛按 token 判定修正。
    astConfirm: true
    patterns:
      - "for\\s*\\([^)]*\\)\\s*{[^}]*for\\s*\\("
    fixable: false

  - id: performance/no-json-full-save
    name: "禁止频繁全量 JSON 写盘"
    category: "performance"
    severity: "info"
    description: "大对象频繁 JSON.stringify 消耗 CPU 和磁盘 IO"
    patterns:
      - "JSON\\.stringify\\s*\\([^)]+\\)\\s*,\\s*['\"]?.*\\.json['\"]?"
    fixable: false
    mitigation: "使用增量写入或内存缓存"

  - id: performance/config-cache-needed
    name: "配置文件应使用内存缓存"
    category: "performance"
    severity: "info"
    description: "频繁 readFileSync 读取 config 影响性能"
    patterns:
      - "readFileSync\\s*\\(\\s*['\"].*config.*\\.json['\"]"
    fixable: false
    mitigation: "添加 TTL 缓存，如 5 秒刷新"

  # ----- 6. 测试 -----
  - id: testing/test-file-exists
    name: "核心文件应有对应测试"
    category: "testing"
    severity: "warning"
    description: "关键模块应有 .test.js 文件"
    fixable: false

  # ----- 7. 依赖 -----
  - id: dependency/known-vulnerability
    name: "无已知漏洞依赖"
    category: "dependency"
    severity: "error"
    description: "npm audit 不应有 critical/high 漏洞"
    fixable: false

# ----- 严重级别映射 -----

  # ── v2 独有能力（1.0.3 合并自原 v2 示范槽位，防旧包覆盖丢失）──
  - id: secret-aws-access-key
    # 占位符精筛：剥掉 ghp_/sk-/AKIA 前缀后再判是否为演示/占位值
    #   （文档里写「测试用占位符 ghp_testtokenplaceholder123」、演示页假数据不应报泄漏）
    astConfirmKind: "placeholder-credential"
    name: "AWS Access Key 疑似泄露"
    category: "security"
    severity: "error"
    description: "检测 AWS 访问密钥格式（AKIA 开头 16-20 位）"
    pattern: "AKIA[0-9A-Z]{16}"

  - id: secret-generic-token
    name: "通用令牌疑似泄露"
    category: "security"
    severity: "error"
    description: "检测常见 token 赋值的硬编码"
    # astConfirmKind: credential-value → 正则初筛后由 token 级精筛确认，只报
    #   「凭据标识符右侧直接是有效字符串字面量」的行。与 security/no-hardcoded-credentials
    #   同用一套判据（lib/ast/credential.js），避免两规则宽严不一。
    #   正则只看字符：注释里举例的 `TOKEN="$(read_token)"`、规则描述文本都会被命中，
    #   精筛按 token 判定并豁免运行时求值形态（$(cmd)/${VAR}/$VAR），误报在此修正。
    astConfirmKind: credential-value
    patterns:
      - "\\btoken\\s*=\\s*['\"][^'\"]{12,}['\"]"
      - "\\bapi[_-]?key\\s*=\\s*['\"][^'\"]{12,}['\"]"

  # ── 三层审计 L2：数据流检查（2026-09-14）──
  # L1 由 filterRulesByFileText 消费 file_patterns：文件文本含「清空/重置动作」或
  #   「访问动作」才进 L2 AST 精查；两者都没有的文件连 tokenize 都不跑（成本极低）。
  - id: dataflow/clear-then-access
    kind: "dataflow"
    name: "清空后访问（同函数数据流）"
    category: "robustness"
    severity: "warning"
    description: "同一函数内对象先被清空（clear()/reset()/splice(0)/=[]/=null/length=0）后被访问（.get()/[下标]/.length）——可能读到已清空对象（undefined/空值）"
    # L1 文件级初筛：命中任一即候选文件（纯正则，非 token 级，成本极低）
    file_patterns:
      - "\\b(?:clear|reset|flush|purge|splice)\\(0?\\s*\\)"
      - "\\b\\w+\\s*=\\s*(?:\\[\\]|null|undefined)"
      - "\\b\\w+\\.length\\s*=\\s*0"
      - "\\b(?:get|at|first|last|peek|head)\\(0?"
severity_map:
  error: "error"
  warning: "warning"
  info: "info"

# ----- 阈值 -----
thresholds:
  max_warnings: 20
  max_errors: 0
  max_info: 50

# ----- 忽略规则 -----
ignore:
  - pattern: "**/*.{test,spec}.{js,ts}"
    rules: ["*"]
  # 第三方内置代码（vendor）——构建产物、非本项目编写，不参与风格/规模类审计。
  #   js/mjs/cjs 全覆盖：此前只写 *.js，导致内置的 js-yaml.mjs 被
  #   readability/max-function-length 报 3 个 blocker（1370 行的 parser 函数）。
  - pattern: "**/vendor/**/*.{js,mjs,cjs}"
    rules: ["*"]
  - pattern: "**/vendor/**"
    rules: ["*"]
  - pattern: "**/dist/**/*.js"
    rules: ["*"]
  - pattern: "**/legacy/**/*.js"
    rules: ["readability/*", "maintainability/*"]

# ----- 输出 -----
output:
  format: "json"
  include_suggestions: true
  include_fix_instructions: true