From 8160a7b7347201a92a07f8786d496e99cb3375b0 Mon Sep 17 00:00:00 2001 From: hyt315 <251666986+hyt315@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:07:21 +0000 Subject: [PATCH] =?UTF-8?q?fix:=20v3.3.3=20=E2=80=94=20=E6=89=AB=E6=8F=8F?= =?UTF-8?q?=E5=99=A8=E6=A0=A1=E5=87=86=EF=BC=9A=E5=8D=A0=E4=BD=8D=E7=AC=A6?= =?UTF-8?q?=E4=B8=8D=E5=86=8D=E9=98=BB=E6=96=AD=E3=80=81=E8=A1=A5=E4=B8=AA?= =?UTF-8?q?=E4=BA=BA=E9=82=AE=E7=AE=B1=E4=B8=8E=E6=89=8B=E6=9C=BA=E5=8F=B7?= =?UTF-8?q?=E3=80=81=E5=8E=86=E5=8F=B2=20P1=20=E5=8F=AA=E6=8A=A5=E5=91=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/validate.yml | 6 +-- CHANGELOG.md | 18 +++++++ README.en.md | 6 +-- README.md | 6 +-- SKILL.md | 6 +-- manifest.json | 4 +- references/github-oss-prep-pitfalls.md | 2 +- references/privacy-scan.md | 7 +-- scripts/secret-rules.json | 30 ++++++++--- scripts/selftest.py | 56 ++++++++++++++++++++- scripts/validate_repo.py | 70 ++++++++++++++------------ 11 files changed, 149 insertions(+), 62 deletions(-) diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index f13bc72..0df61b9 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -28,7 +28,5 @@ jobs: run: python scripts/selftest.py - name: Unit tests (stdlib unittest, no extra deps) run: python -m unittest discover -s tests -p "test_*.py" -v - - name: Repository checks - run: python scripts/validate_repo.py --strict - - name: History scan (P0 in any past commit blocks) - run: python scripts/validate_repo.py --history + - name: Release gate (current tree P0/P1 and history P0 block; history P1 is reported) + run: python scripts/validate_repo.py --strict --history diff --git a/CHANGELOG.md b/CHANGELOG.md index d080546..8e60baf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 _No unreleased changes._ +## [3.3.3] - 2026-11-12 + +Patch release: scanner calibration. The release gate `validate_repo.py --strict --history` now passes on clean projects and catches personal data it used to miss. + +### Fixed + +- **Placeholders no longer block a release.** The ``/`` rule raised P0 even inside code blocks, although SKILL.md treats placeholders as safe. It is removed; `{owner}`/`{repo}` left in shipped docs are still caught by `placeholder-unresolved`. +- **Path rules ignore placeholders and system folders.** `windows-user-profile-path` skips ``, `YourName`, `username`, `%USERNAME%`, `Public`, `Default` and similar; `unix-home-path` skips `user`, `you`, `runner` and similar. `windows-absolute-path` is now P2 (informational) and ignores `C:\Windows`, `C:\ProgramData`, `C:\Program Files`. On a real Windows-tooling project, strict tree P1 dropped from 92 to 1. +- **`--strict` no longer fails on history it cannot fix.** P1 found only in git history is reported but does not block; P0 in history still blocks. The documented gate `--strict --history` failed on this repository itself (24 history P1); CI now runs it as one step. + +### Added + +- `personal_patterns` in `secret-rules.json`: personal mailbox addresses (qq, 163, 126, foxmail, gmail, outlook, …) and mainland China mobile numbers, both P1. SKILL.md has always required both to be absent; until now neither was scanned. +- A non-noreply commit email on a personal mailbox domain is now P1 in the history scan (was P2). +- Tree, `.git/config` and history scans share one matcher (`_match_line`), so a rule behaves the same everywhere. +- Selftest: placeholder/system-path calibration, personal data detection, history P1 report-only. +- README (zh/en): security feature row and the history-scan limitation describe the new behaviour; install `--pin` is v3.3.3. + ## [3.3.2] - 2026-11-08 Patch release: fixes and tightening only, no new workflow steps. diff --git a/README.en.md b/README.en.md index eb5f6b2..992c287 100644 --- a/README.en.md +++ b/README.en.md @@ -38,7 +38,7 @@ When open-sourcing projects on GitHub, developers frequently hit these hurdles: | **Taxonomy Router + 10 README Skeletons** | `references/category-map.md` is the single classification source (12 archetypes, three axes, flags, decision algorithm); `readme-template.md` adds a 12-section base and per-blank acceptance criteria | Classify first, then pick a skeleton; every blank states what "done" looks like | | **10 Universal Archetype Engines** | Tailored, copy-paste-ready Markdown skeletons for AI Skills, MCP Servers, Models/GGUF, CLI tools, Multimedia, SDKs, Extensions, IaC, Web Apps, Awesome Lists | Replaces generic templates with concrete structures and package manager matrices | | **Progressive Disclosure Architecture** | Loads only the specific archetype template matched in Step 1 | Eliminates context bloat and prevents cross-archetype pollution | -| **Layered Security Scan** | Credentials/PATs/PEM keys, path, private-network and local-proxy fingerprints, `.git/config` remote credentials, commit history and author emails, committed build caches (agent session markers stay a manual check); single source of truth in `scripts/secret-rules.json` | Blocks current credential formats; coverage and known blind spots are documented in `privacy-scan.md` | +| **Layered Security Scan** | Credentials/PATs/PEM keys, path, private-network and local-proxy fingerprints, personal mailboxes and phone numbers (placeholders and system folders are not flagged), `.git/config` remote credentials, commit history and author emails, committed build caches (agent session markers stay a manual check); single source of truth in `scripts/secret-rules.json` | Blocks current credential formats; coverage and known blind spots are documented in `privacy-scan.md` | | **2026 Community & CI Profile Pack** | Interactive YAML Issue Forms, PR template, `SECURITY.md`, Node/Python matrix CI (SHA-pinned, read-only token) and Dependabot config | Covers the official health-file baseline and hardens the CI supply chain | | **All-Ecosystem Distribution Guides** | Practical publishing workflows for uv/PyPI, npm, Hugging Face, Chrome Web Store, Docker, Homebrew, Crates.io, Release Checksums | End-to-end guidance from local source to global package registries | | **Verifiable Architecture** | Validator works on any target directory (`validate_repo.py `), severity-graded findings, fixture regressions (real positives caught, clean sample stays clean) | Every claim is reproducible by command; nothing is reported green unless measured | @@ -90,7 +90,7 @@ Send this to your AI assistant and it will detect the platform and clone to the ### Option B: GitHub CLI 2.90+ (one command) ```bash -gh skill install hyt315/github-oss-prep github-oss-prep --agent claude-code --scope user --pin v3.3.2 +gh skill install hyt315/github-oss-prep github-oss-prep --agent claude-code --scope user --pin v3.3.3 # SKILL.md sits at the repo root; if gh cannot find the skill, use Option C ``` @@ -242,7 +242,7 @@ A complete, production-ready toolchain for open-source maintainers and contribut ## ⚠️ Known Limitations - **Scripts do not verify runtime behaviour**: the bundled scripts prepare files, scan credentials and check links/versions, but do not install your package or run your tests; the agent running the skill does that in Step 3, or your CI does. -- **History scan is pattern-based**: `validate_repo.py --history` scans every line ever added plus commit emails, without entropy detection; add `gitleaks`/`trufflehog` for stronger checks. Forks and caches of the remote are out of reach. +- **History scan is pattern-based**: `validate_repo.py --history` scans every line ever added plus commit emails, without entropy detection; P0 in history blocks, P1 is reported only (it can only be cleared by rewriting history); add `gitleaks`/`trufflehog` for stronger checks. Forks and caches of the remote are out of reach. - **Classification has edges**: 12 archetypes today; desktop/mobile/hardware/games/research artifacts have **no dedicated skeleton** — use the base plus category deltas and mark `template=missing` instead of forcing a near-miss template. - **Credential detection is pattern-based** (`scripts/secret-rules.json`), not entropy-based; every suppression is reported as P2 and a human pass is still required. - **Licensing guidance is not legal advice**; model/dataset license chains need your own confirmation. diff --git a/README.md b/README.md index d75cbfc..34dd671 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ |---|---|---| | **分类主表 + 品类 README 引擎** | `references/category-map.md` 用 12 类主表 + 三轴 + 旗标做判定(唯一分类源);`readme-template.md` 提供 10 份骨架、通用底座 12 节与**逐空判据**(``/``/``) | 先定类再取模板;填空处同时给出"怎样算写好",避免只套格式不判断 | | **渐进式披露执行铁律** | 依据品类判定结果定向调阅专属规范,严格隔离无关品类 | 减少上下文膨胀与跨品类交叉污染 | -| **五重深度隐私安全网** | 凭据/PAT/PEM 私钥、路径与私网指纹、会话标记、Git Remote 凭据、构建缓存;规则唯一真相源 `scripts/secret-rules.json` | 拦住现行格式的凭据泄露;覆盖范围与已知盲区在 `privacy-scan.md` 明示 | +| **五重深度隐私安全网** | 凭据/PAT/PEM 私钥、路径与私网指纹、个人邮箱与手机号、Git Remote 凭据、提交历史与提交邮箱、构建缓存(会话标记仍靠人工);占位符与系统目录不误报;规则唯一真相源 `scripts/secret-rules.json` | 拦住现行格式的凭据泄露;覆盖范围与已知盲区在 `privacy-scan.md` 明示 | | **2026 社区与 CI 自动化库** | 交互式 YAML Issue Forms、PR 模板、`SECURITY.md`、**Node/Python 矩阵 CI(锁 SHA + 顶层只读)** 与 **Dependabot 配置** | 社区健康文件按官方口径齐备;CI 供应链加固、依赖自动更新 | | **全生态分发与发版实操** | **uv/PyPI、npm、Hugging Face、Chrome Web Store、Docker、Homebrew、Crates.io** 具体发版指南与 Release Checksums | 提供从本地代码到全球各大分发中心的全流程发版指令 | | **可验证工程架构** | 校验器可指向任意项目(`validate_repo.py `)、分级 finding、fixture 回归(真阳必检、干净样例不误报) | 门禁可复核:每条结论都能用命令复现,未测量不出口绿灯 | @@ -92,7 +92,7 @@ ```bash # gh skill 目前为 Public Preview(命令与 flag 可能变动),先 `gh skill --help` 确认 -gh skill install hyt315/github-oss-prep github-oss-prep --agent claude-code --scope user --pin v3.3.2 +gh skill install hyt315/github-oss-prep github-oss-prep --agent claude-code --scope user --pin v3.3.3 # 本仓库的 SKILL.md 在根目录;若 gh 提示找不到技能,改用方式 C ``` @@ -248,7 +248,7 @@ github-oss-prep/ 按本技能自己的"§9 已知限制"标准,如实列出它做不到的事: - **脚本不验证运行期行为**:自带脚本只整理文件、扫描凭据、检查链接与版本一致性,不会安装你的包或跑你的测试;"干净环境跑通"由执行技能的 Agent 按 Step 3 去做,或交给你的 CI。 -- **历史扫描是模式匹配**:`validate_repo.py --history` 会扫历史中新增的每一行和提交邮箱,但不做高熵检测;要求更高时再加 `gitleaks`/`trufflehog`。远程仓库的 fork 与缓存不在扫描范围内。 +- **历史扫描是模式匹配**:`validate_repo.py --history` 会扫历史中新增的每一行和提交邮箱,但不做高熵检测;历史里的 P0 阻断,P1 只报告(只能靠改写历史清除);要求更高时再加 `gitleaks`/`trufflehog`。远程仓库的 fork 与缓存不在扫描范围内。 - **分类有边界**:主表当前 12 类;桌面 App、移动 App、硬件、游戏、研究复现等**没有专属骨架**,此时按底座 12 节 + 品类增量写,并在事实卡标 `template=missing`,不会硬套模板冒充专属。 - **凭据检测有盲区**:规则是模式匹配(`scripts/secret-rules.json`),不是高熵检测;自定义格式或已泄露进历史的密钥仍可能漏,故所有豁免会以 P2 明示、发布前仍需人工复核。 - **许可建议不是法律意见**:分许可表帮你想清"什么资产配什么许可",重大选择请找法务;模型/数据类还需自行确认上游许可链。 diff --git a/SKILL.md b/SKILL.md index 4fbcaea..b609d8f 100644 --- a/SKILL.md +++ b/SKILL.md @@ -3,7 +3,7 @@ name: github-oss-prep description: "Use when preparing, publishing, launching, or improving a project for open-source adoption on GitHub. Triggers include GitHub 开源准备、准备发布到 GitHub、美化项目准备开源、开源化、开源推广、oss prep、publish to GitHub, launch an open-source project, and prepare for open source." license: MIT metadata: - version: "3.3.2" + version: "3.3.3" --- # GitHub 开源准备 @@ -59,7 +59,7 @@ Step 0 定位 → Step 1 扫描 →【闸 1】→ Step 2 整理 → Step 3 验 1. **判定类型**:按 `references/category-map.md` §3 执行(指纹 → 候选集 → 主产物一问 → 旗标 → 生命周期),产出**一个** `category_id`;落不进就记 `general` + `router=unresolved`,不硬套。 2. **核对社区健康文件**:README、LICENSE、CODE_OF_CONDUCT、CONTRIBUTING、SECURITY(根目录、`.github/` 或 `docs/`),Issue 表单与 PR 模板(`.github/`)。`LICENSE` 不能由组织级 `.github` 仓库兜底;Description 与 Topics 不是文件,但发布时必须设置。 -3. **跑一次基线扫描**:`python scripts/validate_repo.py <项目目录> --strict --history`,记下 P0/P1 命中。 +3. **跑一次基线扫描**:`python scripts/validate_repo.py <项目目录> --strict --history`,记下 P0/P1 命中。`--strict` 只让**当前树**的 P1 失败;历史里的 P1 照常列出但不阻断(只能靠改写历史清除,要不要改由用户决定)。 ### Step 2:整理 @@ -147,7 +147,7 @@ Step 0 定位 → Step 1 扫描 →【闸 1】→ Step 2 整理 → Step 3 验 | 层级 | 检查项 | 测量值 | 命令(附执行时间) | 判定 | |---|---|---|---|:---:| | L1 隐私安全 | 当前树 P0 / P1 命中数 | {P0} / {P1} | `python scripts/validate_repo.py --strict`({RUN_AT}) | {VERDICT} | -| L1 隐私安全 | 历史提交与提交邮箱 | {HISTORY} | `python scripts/validate_repo.py --history`;可加 `gitleaks git`({RUN_AT}) | {VERDICT} | +| L1 隐私安全 | 历史提交与提交邮箱(P0 阻断,P1 只报告) | {HISTORY} | `python scripts/validate_repo.py --history`;可加 `gitleaks git`({RUN_AT}) | {VERDICT} | | L2 社区健康 | 健康文件与 Issue/PR 模板 | {FILES} | `validate_repo.py` 文件清单({RUN_AT}) | {VERDICT} | | L3 供应链 | workflow 顶层 permissions 与 Action SHA 锁定 | {CI_PIN} | `validate_repo.py` 规则 `ci-pin-*`({RUN_AT}) | {VERDICT} | | L3 自动化 | 项目自带测试 / 本技能 selftest | {TESTS} | 项目测试命令或 `python scripts/selftest.py`({RUN_AT}) | {VERDICT} | diff --git a/manifest.json b/manifest.json index 7b96cf3..9e38cd3 100644 --- a/manifest.json +++ b/manifest.json @@ -1,8 +1,8 @@ { "name": "github-oss-prep", - "version": "3.3.2", + "version": "3.3.3", "owner": "hyt315", - "updated_at": "2026-11-08", + "updated_at": "2026-11-12", "description": "Comprehensive GitHub open-source preparation skill: 7-step workflow, type-adaptive README/community files, single-source secret scanning, environment-adaptive publishing with approval gates, and multi-channel distribution.", "license": "MIT", "requires": { diff --git a/references/github-oss-prep-pitfalls.md b/references/github-oss-prep-pitfalls.md index a888789..6e02140 100644 --- a/references/github-oss-prep-pitfalls.md +++ b/references/github-oss-prep-pitfalls.md @@ -110,7 +110,7 @@ - 文档或脚本里写着作者自己的代理地址和端口(如 `http.proxy=…127.0.0.1:<端口>`)、"本机实测"之类的环境快照、token 放在哪个环境变量里、哪个域名直连不通,都会暴露作者的网络环境;回环地址外人连不上,但它仍是个人信息,也会让别人照抄后失败。 - 一律改成占位符(``)加"按探测结果套用"的条件写法;`scripts/secret-rules.json` 的 `local_env_patterns` 会拦截常见代理端口与"本机实测"类表述。 - **提交元数据里的邮箱**: - - 删文件不会删提交作者信息。不想公开真实邮箱时,提交前把 `user.email` 设为 GitHub 的 noreply 地址;`validate_repo.py --history` 会列出历史里出现过的非 noreply 邮箱。 + - 删文件不会删提交作者信息。不想公开真实邮箱时,提交前把 `user.email` 设为 GitHub 的 noreply 地址;`validate_repo.py --history` 会列出历史里出现过的非 noreply 邮箱,个人邮箱域(qq、163、gmail 等)标为 P1。 - **`.git/config` 内嵌明文 Token 泄漏**: - 开发者通过带有 Token 的 URL(如 `https://@github.com/org/repo.git`)克隆或推送代码; - 克隆时写进 URL 的 Token 会以明文形式永久固化在本地 `.git/config` 中;推送时临时写进 URL 也会出现在进程列表里,若后续打包整个项目(如 ZIP)交付或误将 `.git` 文件夹公开,特权 Token 就会直接泄露。 diff --git a/references/privacy-scan.md b/references/privacy-scan.md index 69b0142..27d93f0 100644 --- a/references/privacy-scan.md +++ b/references/privacy-scan.md @@ -35,12 +35,12 @@ | 重 | 自动化 | 命令 / 规则组 | 仍需人工 | |---|---|---|---| | 1 凭据 | ✅ | `validate_repo.py`:`credential_patterns`、`blocked_filenames` | 新格式或自定义格式的密钥 | -| 2 机器指纹 | ✅ | `path_patterns`、`private_ip_patterns`、`local_env_patterns` | 文中提到的真实用户名、主机名、公司名 | +| 2 机器指纹与个人信息 | ✅ | `path_patterns`、`private_ip_patterns`、`local_env_patterns`、`personal_patterns`(个人邮箱、大陆手机号) | 文中提到的真实用户名、主机名、公司名;证件号、境外手机号 | | 3 Agent 会话标记 | ❌ | 暂无规则 | 全部人工:会话 ID、内部 Agent 名、私有工作区别名 | | 4 Git 凭据与历史 | ✅ | `validate_repo.py --history`(历史中新增的每一行 + 提交邮箱) | `.git/config` 的 remote URL:`git remote -v` 看一眼 | | 5 构建产物与缓存 | ⚠️ 部分 | 扫描时跳过这些目录,但**不报错** | 用 `git ls-files` 确认它们没被提交 | -> 发布前用 `--strict` 运行:私有路径、内网 IP 和本机环境指纹都是 P1,只有 `--strict` 才会让检查失败。 +> 发布前用 `--strict --history` 运行:带真实用户名的路径、内网 IP、本机环境指纹、个人邮箱和手机号都是 P1,只有 `--strict` 才会让检查失败,且只针对**当前树**;历史里的 P1 只报告不阻断。盘符绝对路径(如 `D:\Projects\`)只作 P2 提示;`C:\Windows`、`C:\ProgramData` 等系统目录和 ``、`YourName`、`%USERNAME%` 这类占位用户名不报。 --- @@ -52,7 +52,8 @@ - 凭据:GitHub Classic / Fine-grained PAT、OpenAI 系(含 `sk-proj-`/`sk-ant-`)、Anthropic、Stripe、AWS(`AKIA`/`ASIA`)、Google API Key、Hugging Face、npm、PyPI、Slack、SendGrid、Telegram、JWT、Azure 存储密钥、URL 内嵌凭据 - 私钥:PEM 私钥块(含无算法前缀的 PKCS#8) -- 路径与网络:Windows 任意用户名(含非 ASCII)、Unix 家目录、WSL/挂载路径、RFC1918 私网 IP +- 路径与网络:Windows 用户目录(任意真实用户名,含非 ASCII;占位用户名除外)、Unix 家目录、WSL/挂载路径、RFC1918 私网 IP +- 个人信息:常见个人邮箱域(qq、163、126、foxmail、gmail、outlook 等)的地址、中国大陆手机号;提交邮箱属个人邮箱域时在历史扫描里升为 P1 - 本机环境:回环地址上的代理配置、代理客户端常用端口、"本机实测"类环境快照 - 文件名级拦截:`.env`、`.env.*`(`.env.example` 等模板除外)、`credentials.json`、`*.pem`、`*.key`、`*.p12`、`*.pfx`、`id_rsa`/`id_ed25519`/`id_ecdsa`/`id_dsa` - 不读的文件:图片、压缩包、模型权重与数据文件(`.gguf`、`.safetensors`、`.parquet` 等)和超过 5 MB 的文件,后者会以 P2 列出 diff --git a/scripts/secret-rules.json b/scripts/secret-rules.json index 69b431a..182ff88 100644 --- a/scripts/secret-rules.json +++ b/scripts/secret-rules.json @@ -1,9 +1,9 @@ { - "version": "1.1.0", + "version": "1.2.0", "note": "Single source of truth for secret/path scanning. Used by scripts/validate_repo.py and scripts/selftest.py. Do not duplicate these patterns anywhere else; docs must reference this file instead of re-listing regexes.", "severity_legend": { "P0": "fails the scan (blocks release)", - "P1": "fails only with --strict; printed otherwise (private paths, local environment fingerprints)", + "P1": "fails only with --strict, and only for the current tree; P1 hits in git history are reported but never block (they can only be removed by rewriting history)", "P2": "informational only (process hygiene)" }, "credential_patterns": [ @@ -107,21 +107,21 @@ "path_patterns": [ { "id": "windows-user-profile-path", - "label": "Windows user profile path (any user name, incl. non-ASCII)", + "label": "Windows user profile path with a real-looking user name (placeholders such as , YourName, %USERNAME%, Public are ignored)", "severity": "P1", - "regex": "[A-Za-z]:[\\\\/]{1,2}Users[\\\\/]{1,2}[^\\s\\\\/\"'`]+" + "regex": "[A-Za-z]:[\\\\/]{1,2}Users[\\\\/]{1,2}(?![<%$\\[{]|(?:YourName|yourname|YOURNAME|UserName|username|USERNAME|user|User|USER|Public|Default|All Users|xxx|XXX|用户名|你的用户名|张三)(?![^\\s\\\\/\\\"'`]))[^\\s\\\\/\\\"'`]+" }, { "id": "windows-absolute-path", - "label": "Windows absolute path on a local drive", - "severity": "P1", - "regex": "(?:^|[\\s(\"'`])[A-Za-z]:[\\\\/](?:[^\\s\\\\/:*?\"<>|]+[\\\\/]){1,8}" + "label": "Absolute path on a local drive (informational: may reveal the author's folder layout; system folders are ignored)", + "severity": "P2", + "regex": "(?:^|[\\s(\\\"'`])[A-Za-z]:[\\\\/](?!(?:Windows|WINDOWS|ProgramData|Program Files|Users)(?:[\\\\/\\s\\\"'`]|$))(?:[^\\s\\\\/:*?\\\"<>|]+[\\\\/]){1,8}" }, { "id": "unix-home-path", "label": "Unix home/root path with a real user name", "severity": "P1", - "regex": "/(?:home|Users|root)/[A-Za-z0-9_.-]+/" + "regex": "/(?:home|Users|root)/(?!(?:user|username|you|yourname|me|name|runner|ubuntu|example|USER|USERNAME)/)[A-Za-z0-9_.-]+/" }, { "id": "wsl-or-mount-path", @@ -158,6 +158,20 @@ "regex": "本机(?:实测|事实|环境快照|复核|定稿|同时装有)" } ], + "personal_patterns": [ + { + "id": "personal-email", + "label": "Personal mailbox address (qq/163/gmail/outlook…); use a noreply or example.com address", + "severity": "P1", + "regex": "(? None: signatures = ["gh[pousr]_[A-Za-z0-9]{36", "AKIA|ASIA", "pypi-AgEIcHlwaS5vcmc", "BEGIN (?:[A-Z0-9]+ )?PRIVATE KEY"] offenders = [] for path in ROOT.rglob("*"): - if not path.is_file() or ".git" in path.parts or path.name == "secret-rules.json": + if not path.is_file() or {".git", "__pycache__"} & set(path.parts) or path.name == "secret-rules.json": continue if path.name == Path(__file__).name: # this test names the signatures on purpose continue @@ -144,7 +144,7 @@ def test_anchor_slug_matches_github() -> None: def test_scanner_regressions() -> None: - """v3.3.2 fixes: target under build/, sk- word boundary, local proxy, .env variants, .git/config.""" + """v3.3.2 regressions: target under build/, sk- word boundary, local proxy, .env variants, .git/config.""" import tempfile rules = validate_repo.load_rules() with tempfile.TemporaryDirectory() as tmp: @@ -187,6 +187,58 @@ def test_history_scan_finds_removed_leak() -> None: assert "history-author-email" not in ids, ids +def test_calibration_placeholders_and_personal_data() -> None: + """v3.3.3: placeholders and system folders stay quiet; real names, personal mail and phone numbers are caught.""" + import tempfile + rules = validate_repo.load_rules() + quiet = ( + "```bash\ngh repo clone /\n```\n" + "Copy to C:\\Users\\\\AppData and C:\\Users\\YourName\\x and C:\\Users\\%USERNAME%\\y\n" + "System: C:\\Windows\\System32\\ and C:\\ProgramData\\Foo\\ and C:\\Users\\Public\\z\n" + "Unix: /home/user/proj/ and /Users/you/code/ and /home/runner/work/\n" + "Mail security@example.com or someone@users.noreply.github.com; order 202611120001234; sha 1a13812345678b\n" + ) + loud = ( + "C:\\Users\\" + "zhangwei\\Desktop\n" + "/home/" + "zhangwei/proj/\n" + "Contact zhang.san@" + "163.com or 1381234" + "5678\n" + ) + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + (root / "quiet.md").write_text(quiet, encoding="utf-8") + (root / "loud.md").write_text(loud, encoding="utf-8") + found = validate_repo.scan_tree(root, rules) + noisy = [(f["id"], f["evidence"]) for f in found if f["file"].endswith("quiet.md") and f["severity"] in {"P0", "P1"}] + assert not noisy, f"placeholders/system folders flagged: {noisy}" + ids = {f["id"] for f in found if f["file"].endswith("loud.md") and f["severity"] == "P1"} + expected = {"windows-user-profile-path", "unix-home-path", "personal-email", "cn-mobile-number"} + assert expected <= ids, f"missed {expected - ids}; got {ids}" + + +def test_history_p1_is_report_only() -> None: + """--strict blocks P1 in the current tree only; P1 that lives only in history is printed, not blocking.""" + import shutil + import tempfile + if not shutil.which("git"): + return + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + run = lambda *a: subprocess.run(["git", "-C", tmp, *a], check=True, capture_output=True) # noqa: E731 + run("init", "-q") + run("config", "user.name", "t") + run("config", "user.email", "t@users.noreply.github.com") + (root / "x.md").write_text("see /home/" + "zhangwei/proj/\n", encoding="utf-8") + run("add", ".") + run("commit", "-qm", "a") + (root / "x.md").write_text("clean\n", encoding="utf-8") + run("commit", "-qam", "b") + result = subprocess.run([sys.executable, str(ROOT / "scripts" / "validate_repo.py"), tmp, "--strict", "--history", "--json"], + capture_output=True, text=True) + payload = json.loads(result.stdout) + assert any(f["id"] == "unix-home-path" for f in payload["findings"]), payload + assert payload["status"] == "PASS" and result.returncode == 0, payload + + def main() -> int: checks = [value for name, value in sorted(globals().items()) if name.startswith("test_") and callable(value)] failed = [] diff --git a/scripts/validate_repo.py b/scripts/validate_repo.py index f2c46a0..6ae478a 100644 --- a/scripts/validate_repo.py +++ b/scripts/validate_repo.py @@ -3,7 +3,7 @@ Usable on this skill's own repository (default) or on any target directory: - python scripts/validate_repo.py [TARGET_DIR] [--json] [--format text|json|md] [--strict] + python scripts/validate_repo.py [TARGET_DIR] [--json] [--format text|json|md] [--strict] [--history] Rules (secrets, private paths, blocked filenames) live in scripts/secret-rules.json and are the single source of truth — tests import them from here, docs must not @@ -32,7 +32,6 @@ "references/discovery-and-promotion.md", ] -PLACEHOLDER_RE = re.compile(r"<(?:owner|repo)>") UNRESOLVED_RE = re.compile(r"\{(owner|repo)\}") SUPPRESSION_RE = re.compile( r"" @@ -210,10 +209,8 @@ def scan_tree(root: Path, rules: dict | None = None) -> list[dict]: rules = rules or load_rules() findings: list[dict] = [] - cred = [(p["id"], p["severity"], re.compile(p["regex"]), p["label"]) for p in rules["credential_patterns"]] - paths = [(p["id"], p["severity"], re.compile(p["regex"]), p["label"]) for p in rules.get("path_patterns", [])] - ips = [(p["id"], p["severity"], re.compile(p["regex"]), p["label"]) for p in rules.get("private_ip_patterns", [])] - envs = [(p["id"], p["severity"], re.compile(p["regex"]), p["label"]) for p in rules.get("local_env_patterns", [])] + cred = _compiled(rules, ("credential_patterns",)) + patterns = _compiled(rules) allow = set(rules.get("filename_allowlist", [])) max_bytes = rules["scan_scope"].get("max_file_bytes", 0) @@ -251,23 +248,15 @@ def scan_tree(root: Path, rules: dict | None = None) -> list[dict]: "inline suppression for " + (",".join(rule_ids) if rule_ids else "skill-doctor") + (f" ({reason})" if reason else ""), ) - for fid, sev, rx, label in cred + paths + ips + envs: - if fid in suppressed or "all" in suppressed: - continue - hit = rx.search(line) - if hit: - _finding(findings, fid, sev, path, lineno, label, hit.group(0)) - for match in PLACEHOLDER_RE.finditer(line): - _finding(findings, "unresolved-placeholder", "P0", path, lineno, "unresolved placeholder", match.group(0)) + for fid, sev, label, hit in _match_line(line, patterns, suppressed): + _finding(findings, fid, sev, path, lineno, label, hit) # .git/config is skipped with .git/, but a token-bearing remote URL there leaks with any ZIP of the folder git_config = root / ".git" / "config" if git_config.is_file(): for lineno, line in enumerate(_read(git_config).splitlines(), 1): - for fid, sev, rx, label in cred: - hit = rx.search(line) - if hit: - _finding(findings, fid, sev, git_config, lineno, label + " (in .git/config)", hit.group(0)) + for fid, sev, label, hit in _match_line(line, cred, set()): + _finding(findings, fid, sev, git_config, lineno, label + " (in .git/config)", hit) # build caches and dependency folders are skipped above; report any that are actually tracked by git _report_tracked_artifacts(root, rules, findings) @@ -299,13 +288,26 @@ def scan_tree(root: Path, rules: dict | None = None) -> list[dict]: return findings -def _compiled(rules: dict): +PATTERN_GROUPS = ("credential_patterns", "path_patterns", "private_ip_patterns", "local_env_patterns", "personal_patterns") + + +def _compiled(rules: dict, groups: tuple[str, ...] = PATTERN_GROUPS): out = [] - for key in ("credential_patterns", "path_patterns", "private_ip_patterns", "local_env_patterns"): + for key in groups: out += [(p["id"], p["severity"], re.compile(p["regex"]), p["label"]) for p in rules.get(key, [])] return out +def _match_line(text: str, patterns, suppressed: set[str]): + """The one matcher shared by the tree, .git/config and history scans: (id, severity, label, evidence).""" + for fid, sev, rx, label in patterns: + if fid in suppressed or "all" in suppressed: + continue + hit = rx.search(text) + if hit: + yield fid, sev, label, hit.group(0) + + DUMMY_RE = re.compile(r"(?i)example|test|dummy|fake|placeholder|x{4,}|1234567890|abcdef") @@ -338,8 +340,10 @@ def scan_history(root: Path, rules: dict | None = None) -> list[dict]: for email in parts[2:]: if email and not noreply.search(email) and ("email", email) not in seen: seen.add(("email", email)) - _finding(findings, "history-author-email", "P2", Path(f"history:{commit}"), 0, - "commit metadata exposes a non-noreply email (consider the GitHub noreply address)", email) + personal = any(fid == "personal-email" for fid, *_ in _match_line(email, patterns, set())) + _finding(findings, "history-author-email", "P1" if personal else "P2", Path(f"history:{commit}"), 0, + "commit metadata exposes a " + ("personal mailbox" if personal else "non-noreply email") + + "; set user.email to your GitHub noreply address for future commits", email) continue if line.startswith("+++ b/"): current = line[6:] @@ -348,16 +352,14 @@ def scan_history(root: Path, rules: dict | None = None) -> list[dict]: continue text = line[1:] suppressed = {r.strip() for m in SUPPRESSION_RE.finditer(text) for r in (m.group(1) or "").split(",") if r.strip()} - for fid, sev, rx, label in patterns: - if fid in suppressed: + for fid, sev, label, hit in _match_line(text, patterns, suppressed): + if (fid, hit) in seen: continue - hit = rx.search(text) - if hit and (fid, hit.group(0)) not in seen: - seen.add((fid, hit.group(0))) - if sev == "P0" and DUMMY_RE.search(hit.group(0)): - sev = "P2" # obvious placeholder (example/test/123456…): show it, don't block - _finding(findings, fid, sev, Path(f"history:{commit}:{current}"), 0, - label + " (in git history; removing it now does not erase it)", hit.group(0)) + seen.add((fid, hit)) + if sev == "P0" and DUMMY_RE.search(hit): + sev = "P2" # obvious placeholder (example/test/123456…): show it, don't block + _finding(findings, fid, sev, Path(f"history:{commit}:{current}"), 0, + label + " (in git history; removing it now does not erase it)", hit) return findings @@ -434,7 +436,8 @@ def main() -> int: parser.add_argument("target", nargs="?", default=None, help="directory to check (default: this skill)") parser.add_argument("--json", action="store_true", help="output as JSON (shortcut for --format json)") parser.add_argument("--format", choices=["text", "json", "md"], default=None) - parser.add_argument("--strict", action="store_true", help="treat P1 findings as failures (use before publishing)") + parser.add_argument("--strict", action="store_true", + help="treat P1 findings in the current tree as failures (use before publishing); history P1 stays report-only") parser.add_argument("--history", action="store_true", help="also scan every line ever committed and commit emails") args = parser.parse_args() @@ -449,7 +452,8 @@ def main() -> int: findings.extend(scan_history(root)) blocking = [f for f in findings if f["severity"] == "P0"] - strict_hits = [f for f in findings if f["severity"] == "P1"] + # P1 in history is report-only: it can only be cleared by rewriting history, which is the user's call + strict_hits = [f for f in findings if f["severity"] == "P1" and not str(f["file"]).startswith("history:")] failed = bool(blocking) or (args.strict and bool(strict_hits)) for f in findings: