Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
chore(dco): 落地 DCO 签名基础设施(App 门禁 + 本地 hook + 自查脚本) (#396)
Dash2dd1600f3ee4
diff --git a/.gitattributes b/.gitattributesindex 77befb3221..4c18db896c 100644--- a/.gitattributes+++ b/.gitattributes@@ -3,6 +3,9 @@# vitest(vite 转换链)加载「CRLF + shebang」组合会直接 SyntaxError,unix 下直接执行也会坏,# 与 *.sh 同理固定 LF 检出。*.mjs text eol=lf+# git hook 没有扩展名,命不中上面两条。Windows autocrlf 检出成 CRLF 后 `#!/bin/sh\r`+# 无法执行,git commit 会直接 `fatal: cannot exec`——装了 hook 的人从此提交不了。+.githooks/** text eol=lf# SQLite migration 内容参与用户数据库 drift hash;跨平台统一 LF。apps/desktop/drizzle/**/*.sql text eol=lf# sqlite-vec 扩展二进制(平台特定 .dylib / .dll)—— 走 Git LFSdiff --git a/.githooks/prepare-commit-msg b/.githooks/prepare-commit-msgnew file mode 100755index 0000000000..d80125a20f--- /dev/null+++ b/.githooks/prepare-commit-msg@@ -0,0 +1,59 @@+#!/bin/sh+# cindy-dco-signoff-hook: appends the DCO Signed-off-by trailer to local commits.+# See the DCO file at the repository root for what the trailer certifies.+#+# Install with `pnpm dco:install-hook` (copies this file into your hooks directory,+# see scripts/install-dco-hook.mjs), or point Git at this directory yourself with+# `git config core.hooksPath .githooks`. Delete the installed copy to uninstall.+#+# Why a hook is needed: Git has no option that signs commits off automatically.+# format.signOff only affects git format-patch / git am, and commit.signoff does+# not exist. Unsigned commits are rejected by the DCO check on every pull request+# (the DCO GitHub App, configured in .github/dco.yml), and fixing them afterwards+# means rewriting commits. scripts/check-dco.mjs is the local pre-commit+# self-check for the same rules; the App's check is the authority.++MSG_FILE="$1"+MSG_SOURCE="$2"++# Merge commits are exempt from the DCO check, so never sign them off here.+case "$MSG_SOURCE" in+ merge) exit 0 ;;+esac++# Use the COMMITTER ident, exactly like `git commit -s` does. A sign-off is a+# statement by whoever runs the commit, so it must never be generated from the+# author ident: with `git commit --author=...`, or while cherry-picking or+# rebasing somebody else's patch, the author is a different person and signing+# on their behalf would forge their DCO certification. The check accepts a+# sign-off matching either the author or the committer, so using the committer+# ident still passes.+IDENT=$(git var GIT_COMMITTER_IDENT) || exit 0+SIGNOFF=$(printf '%s\n' "$IDENT" | sed -n 's/^\(.*>\).*$/\1/p')+[ -n "$SIGNOFF" ] || exit 0++# Already signed off (git commit -s, a cherry-pick carrying our own sign-off, or+# a second pass during --amend): leave the message alone.+if grep -qxF "Signed-off-by: $SIGNOFF" "$MSG_FILE"; then+ exit 0+fi++# During an interactive commit the message body is still empty (comments only).+# interpret-trailers would put the sign-off on line 2, so once the author types a+# subject on line 1 the result is "subject immediately followed by trailer" with+# no blank line between them. Build the layout `git commit -s` uses instead:+# an empty subject line, a blank line, then the sign-off.+if [ -z "$(sed -e 's/^[[:space:]]*#.*$//' -e '/^[[:space:]]*$/d' "$MSG_FILE")" ]; then+ DCO_TMP="$MSG_FILE.dco-signoff"+ { printf '\n\nSigned-off-by: %s\n\n' "$SIGNOFF"; sed '/./,$!d' "$MSG_FILE"; } > "$DCO_TMP" || exit 0+ mv "$DCO_TMP" "$MSG_FILE" || exit 0+ exit 0+fi++# The message already has a body: let interpret-trailers place the sign-off in+# the trailer block. Pass --if-exists / --if-missing explicitly — their defaults+# come from trailer.ifExists / trailer.ifMissing, and a developer who set those+# to doNothing would silently get unsigned commits whenever a message already+# carries somebody else's sign-off.+git interpret-trailers --if-exists addIfDifferent --if-missing add \+ --trailer "Signed-off-by: $SIGNOFF" --in-place "$MSG_FILE"diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.mdindex 22f6fd73ee..01758a0ea7 100644--- a/.github/PULL_REQUEST_TEMPLATE.md+++ b/.github/PULL_REQUEST_TEMPLATE.md@@ -86,6 +86,7 @@ branch/worktree、Metro 归属与 __DEV__ build label 证据。 -->### 提交前检查- [ ] 已 review 完整 diff+- [ ] 每个 commit 都带 DCO 签名(`git commit -s`,见 [DCO](../DCO))- [ ] UI 改动已在「UI 变化」注明引用的设计规范章节(不涉及 UI 则跳过)- [ ] 未提交凭证、令牌或授权文件- [ ] 已补充必要文档diff --git a/.github/dco.yml b/.github/dco.ymlnew file mode 100644index 0000000000..520acb4a6a--- /dev/null+++ b/.github/dco.yml@@ -0,0 +1,12 @@+# DCO App 配置(github.com/apps/dco)。只有默认分支上的这份文件生效。+#+# 允许 remediation commit:贡献者可以推一个后续 commit,用固定格式的正文为先前的+# commit 补上签名,不必改写历史 force-push(否则已有的 review 评论会全部 outdated)。+# 格式与用法写在 CONTRIBUTING.en.md / CONTRIBUTING.md 的 DCO 一节。+# thirdParty 依赖 individual,必须一起开。+allowRemediationCommits:+ individual: true+ thirdParty: true+# 刻意不设 require.members: false。那个开关会跳过「org 成员且 GPG 签名」的提交,+# 但本仓没有强制 GPG 签名,配上去要么不起作用,要么正好在内部提交上留下签名缺口——+# 而开源客户端做 DCO 的目的就是留完整的贡献来源记录。diff --git a/AGENTS.md b/AGENTS.mdindex 40e818d798..0d54d65e22 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -89,6 +89,12 @@- commit、push 和创建 PR 的执行时机由开发者或 Codex、Claude Code、Cindy 等宿主工作流决定;仓库规则本身不额外授权外部写操作。- 提交 PR 时遵循 `.github/PULL_REQUEST_TEMPLATE.md`,如实说明改动、验证和风险。+- **DCO 签名(硬性要求)**:本仓每个 commit 都必须带 `Signed-off-by` trailer,且其中的+ 名字与邮箱都要与 commit 的 author(或 committer)一致,用 `git commit -s` 生成;+ agent 的自动提交同样适用。PR 上的 DCO check(DCO GitHub App,配置见+ `.github/dco.yml`)会拦下漏签的 commit。`git commit` 没有自动签名的配置项,一次配好+ 可跑 `pnpm dco:install-hook` 装 `.githooks/prepare-commit-msg`;提交前自查用+ `pnpm check:dco`。DCO 全文见根目录 `DCO`,贡献者说明见 `CONTRIBUTING.md`。- **提交前测试门禁(硬性要求)**:无论是提 PR 还是直接 commit,提交前都必须在本地跑完仓库根 `pnpm test:unit`(全部单元测试),并对本次改动涉及的每个 package 跑`pnpm --filter <包名> run --if-present typecheck`(`<包名>` 用该 package 在diff --git a/CONTRIBUTING.en.md b/CONTRIBUTING.en.mdindex 3ad69319dc..9169903a00 100644--- a/CONTRIBUTING.en.md+++ b/CONTRIBUTING.en.md@@ -77,11 +77,70 @@ license, any contribution you intentionally submit for inclusion is acceptedunder the Apache-2.0 terms — no separate CLA is required.We do require every commit to carry a-[Developer Certificate of Origin](https://developercertificate.org/) sign-off:+[Developer Certificate of Origin](https://developercertificate.org/) sign-off+(DCO 1.1; the full text is in the [`DCO`](DCO) file at the repository root):commit with `git commit -s`, which appends a`Signed-off-by: Your Name <your@email>` trailer stating that you have the right-to submit the contribution under these terms. Do not submit code you are not-entitled to license (for example proprietary code copied without permission).+to submit the contribution under these terms. Both the name and the address in+the trailer must match the commit's author (or committer) — the trailer is a+statement about yourself and cannot be made on someone else's behalf. Do not+submit code you are not entitled to license (for example proprietary code copied+without permission).++The **DCO check** on every pull request (the+[DCO GitHub App](https://github.com/apps/dco)) validates each commit in the pull+request; merge commits and bot commits are exempt, and history from before the+DCO requirement is never examined. Check yourself locally with `pnpm check:dco`.+If a commit is missing its sign-off:++```bash+# only the most recent commit is missing a sign-off+git commit --amend -s --no-edit++# several commits are missing sign-offs (<base> is the pull request base commit)+git rebase --signoff <base>++# update the pull request afterwards+git push --force-with-lease+```++If you would rather not rewrite history — say the pull request already carries+review discussion worth keeping — push a **remediation commit** instead. Its+message must contain the following line verbatim, where the sha is the full+40-character sha of the commit being signed off, and the remediation commit+itself must also carry your sign-off:++```text+I, Your Name <your@email>, hereby add my Signed-off-by to this commit: <full 40-char sha>++Signed-off-by: Your Name <your@email>+```++The author of both commits, and the name and address on that line, all have to+match exactly. To sign off on someone else's commit:++```text+On behalf of Author Name <author@email>, I, Your Name <your@email>, hereby add my Signed-off-by to this commit: <full 40-char sha>++Signed-off-by: Your Name <your@email>+```++Note that `pnpm check:dco` is deliberately more conservative than the gate on the+pull request: it only recognises direct sign-offs (not remediation commits) and it+does not exempt bot commits, since bot status depends on the GitHub account type+and cannot be determined offline. Passing locally therefore implies passing on the+pull request, but not the other way round — when using remediation, or when the+range contains bot commits, the DCO check on the pull request is the authority.++Git has no configuration option that signs commits off automatically+(`format.signOff` only affects `git format-patch` / `git am`). To set it up once,+install the prepare-commit-msg hook shipped with this repository. The hook itself+is [`.githooks/prepare-commit-msg`](.githooks/prepare-commit-msg) — an ordinary+shell script, so read it before installing. `pnpm dco:install-hook` copies it into+your local hooks directory; nothing is changed on the remote, and deleting the+installed copy uninstalls it. You can also point Git at the directory yourself+with `git config core.hooksPath .githooks` (that takes over the whole hooks+directory).## Security issuesdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex b9152bf700..aae574de3e 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -62,9 +62,55 @@ Git LFS 和依赖安装。该文档是安装命令的唯一权威说明;本指贡献,默认按 Apache-2.0 的条款并入并对外分发,无需额外签署 CLA。我们要求每个 commit 通过 [Developer Certificate of Origin](https://developercertificate.org/)-声明来源合法:提交时使用 `git commit -s`,在 commit message 末尾生成-`Signed-off-by: 你的名字 <你的邮箱>` 行,表示你有权按上述条款提交这份贡献。-请不要提交你无权授权的代码(例如未经许可复制的专有代码)。+声明来源合法(DCO 1.1 全文见仓库根的 [`DCO`](DCO) 文件):提交时使用 `git commit -s`,+在 commit message 末尾生成 `Signed-off-by: 你的名字 <你的邮箱>` 行,表示你有权按上述+条款提交这份贡献。签名里的**名字和邮箱都**必须与该 commit 的 author(或 committer)+一致——这一行是本人声明,不能替别人签。请不要提交你无权授权的代码(例如未经许可+复制的专有代码)。++PR 上的 **DCO check**([DCO GitHub App](https://github.com/apps/dco))会校验这个 PR+的每个 commit,merge commit 与 bot 提交豁免,不追溯 DCO 生效前的历史提交。本地可以+提前自查:`pnpm check:dco`。漏签时补签:++```bash+# 只有最新一个 commit 漏签+git commit --amend -s --no-edit++# 多个 commit 漏签(<base> 用 PR 的 base commit)+git rebase --signoff <base>++# 改完后更新 PR+git push --force-with-lease+```++如果不想改写历史(例如 PR 上已经有想保留的 review 讨论),可以改推一个+**remediation commit**:正文里包含下面这行原样格式,其中 sha 是被补签 commit 的完整+40 位 sha,并且这个 commit 自己也要带签名。++```text+I, 你的名字 <你的邮箱>, hereby add my Signed-off-by to this commit: <40 位完整 sha>++Signed-off-by: 你的名字 <你的邮箱>+```++两个 commit 的 author 以及这行里的名字、邮箱必须完全一致。替别人的 commit 补签用:++```text+On behalf of 原作者 <原作者邮箱>, I, 你的名字 <你的邮箱>, hereby add my Signed-off-by to this commit: <40 位完整 sha>++Signed-off-by: 你的名字 <你的邮箱>+```++注意 `pnpm check:dco` 刻意比 PR 上的门禁保守:它只认直接签名、不识别 remediation+commit,也不豁免 bot 提交(bot 身份取决于 GitHub 账号类型,本地判不了)。因此本地通过则+PR 上必过,反之不然——用了 remediation、或范围里含 bot 提交时,以 PR 上的 DCO check 为准。++`git commit` 本身没有「自动签名」的配置项(`format.signOff` 只作用于+`git format-patch` / `git am`)。想一次配好,可以装上本仓的 prepare-commit-msg hook——+正本是 [`.githooks/prepare-commit-msg`](.githooks/prepare-commit-msg),一个普通 shell+脚本,建议装之前先自己读一遍:`pnpm dco:install-hook` 会把它复制进本地 hooks 目录,+不改远端,删掉已安装的那份即卸载;也可以直接 `git config core.hooksPath .githooks`+(这会接管整个 hooks 目录)。## 安全问题diff --git a/DCO b/DCOnew file mode 100644index 0000000000..fed7119fca--- /dev/null+++ b/DCO@@ -0,0 +1,38 @@+Developer Certificate of Origin+Version 1.1++Copyright (C) 2004, 2006 The Linux Foundation and its contributors.++1 Letterman Drive+Suite D4700+San Francisco, CA, 94129++Everyone is permitted to copy and distribute verbatim copies of this+license document, but changing it is not allowed.+++Developer's Certificate of Origin 1.1++By making a contribution to this project, I certify that:++(a) The contribution was created in whole or in part by me and I+ have the right to submit it under the open source license+ indicated in the file; or++(b) The contribution is based upon previous work that, to the best+ of my knowledge, is covered under an appropriate open source+ license and I have the right under that license to submit that+ work with modifications, whether created in whole or in part+ by me, under the same open source license (unless I am+ permitted to submit under a different license), as indicated+ in the file; or++(c) The contribution was provided directly to me by some other+ person who certified (a), (b) or (c) and I have not modified+ it.++(d) I understand and agree that this project and the contribution+ are public and that a record of the contribution (including all+ personal information I submit with it, including my sign-off) is+ maintained indefinitely and may be redistributed consistent with+ this project or the open source license(s) involved.diff --git a/README.md b/README.mdindex ffc0235d4c..83737d3b5d 100644--- a/README.md+++ b/README.md@@ -144,6 +144,9 @@ servers.Contributions go through pull requests into `main`. Read[`CONTRIBUTING.en.md`](CONTRIBUTING.en.md) first, then use[`.github/PULL_REQUEST_TEMPLATE.md`](.github/PULL_REQUEST_TEMPLATE.md).+Every commit needs a [Developer Certificate of Origin](DCO) sign-off+(`git commit -s`); a DCO check on each pull request enforces it, and no CLA is+required.Please also follow [`CODE_OF_CONDUCT.en.md`](CODE_OF_CONDUCT.en.md). For ordinaryusage questions, see [`SUPPORT.en.md`](SUPPORT.en.md); report security issuesprivately through [`SECURITY.en.md`](SECURITY.en.md).diff --git a/README.zh-CN.md b/README.zh-CN.mdindex 9fb9e45a91..d67746a192 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -129,6 +129,8 @@ agent 的模式。依赖服务端的能力在该模式下不可用。改动通过 pull request 合入 `main`。请先阅读[`CONTRIBUTING.md`](CONTRIBUTING.md),再按[`.github/PULL_REQUEST_TEMPLATE.md`](.github/PULL_REQUEST_TEMPLATE.md) 提交。+每个 commit 需带 [DCO](DCO) 签名(`git commit -s`),由 PR 上的 DCO check 校验;+不需要签 CLA。同时请遵守 [`CODE_OF_CONDUCT.md`](CODE_OF_CONDUCT.md);普通使用问题见[`SUPPORT.md`](SUPPORT.md),安全问题仍按 [`SECURITY.md`](SECURITY.md) 私下报告。diff --git a/docs/dev-rules/development-workflow.md b/docs/dev-rules/development-workflow.mdindex 401197a9f8..aab880fdfb 100644--- a/docs/dev-rules/development-workflow.md+++ b/docs/dev-rules/development-workflow.md@@ -44,6 +44,19 @@ worktree 会话契约、直推 `main` 的额外门禁与 review 严重度口径design-rules 文档,或「不涉及:<理由>」豁免;判定逻辑见`scripts/check-pr-design-basis.mjs`),但通过 CI 不代表内容合格,质量仍由review 把关。Reviewer 只看 Title + Description 决定要不要 review,写不清直接退回。+- **DCO 签名门禁(硬性要求)**:每个 commit 都必须带 `Signed-off-by` trailer,其中的名字+ 与邮箱都要与 commit 的 author(或 committer)一致——`git commit -s`,或先跑一次+ `pnpm dco:install-hook` 装上 hook 让后续提交自动补签(正本 `.githooks/prepare-commit-msg`;+ `git commit` 本身没有自动签名的配置项,`format.signOff` 只作用于 `git format-patch` /+ `git am`)。这条对 agent 自动提交、worktree 会话内的收尾 commit 一律适用。+ - PR 上的权威门禁是 **DCO GitHub App** 的 check:它校验该 PR 的每个 commit,豁免+ merge 与 bot,不追溯历史;`.github/dco.yml` 开了 remediation commit,因此漏签也可以+ 不改写历史(格式见 `CONTRIBUTING.md`)。+ - 提交前自查用 `pnpm check:dco`(`scripts/check-dco.mjs`,范围 `merge-base..head`)。+ 它的判定刻意对齐 App 但**不识别 remediation commit**:本地通过则 App 必过,反之不然。+ 改这个脚本时不要放宽 name/邮箱比对,否则会出现「本地绿、PR 红」。+ - 漏签不要重新造一份提交:用 `git commit --amend -s --no-edit` 或+ `git rebase --signoff <base>` 补签后 `git push --force-with-lease`。- **提交前测试门禁(硬性要求)**:无论是提 PR 还是直接 commit,提交前都必须在本地跑完仓库根 `pnpm test:unit`(全部单元测试),并对本次改动涉及的每个 package 跑`pnpm --filter <包名> run --if-present typecheck`(`<包名>` 用该 package 在diff --git a/package.json b/package.jsonindex dc888edb4c..5e02143d4c 100644--- a/package.json+++ b/package.json@@ -100,10 +100,12 @@"check:brand-terminology": "node scripts/brand-terminology-guard.mjs","check:endpoints": "node scripts/check-endpoint-literals.mjs","check:dev-docs": "node --test scripts/__tests__/dev-docs-contract.test.mjs",+ "check:dco": "node scripts/check-dco.mjs",+ "dco:install-hook": "node scripts/install-dco-hook.mjs","licenses:generate": "node scripts/generate-third-party-notices.mjs","lint": "pnpm -r lint","format": "pnpm -r format",- "test:runner": "node --test scripts/__tests__/test-workspaces.test.mjs scripts/__tests__/dev-docs-contract.test.mjs scripts/__tests__/restart-desktop-remote.test.mjs scripts/__tests__/dev-migration-policy.test.mjs scripts/__tests__/ensure-deps.test.mjs scripts/__tests__/client-endpoint-build-env.test.mjs scripts/__tests__/endpoint-consistency.test.mjs scripts/__tests__/endpoint-local-file.test.mjs scripts/__tests__/ensure-agent-binaries.test.mjs scripts/__tests__/fetch-with-timeout.test.mjs scripts/__tests__/agent-binary-cdn-fallback.test.mjs scripts/__tests__/ensure-binary-fallback.test.mjs scripts/__tests__/verify-sha256.test.mjs scripts/__tests__/migration-freeze.test.mjs scripts/__tests__/third-party-notices.test.mjs scripts/__tests__/brand-identity-sync.test.mjs",+ "test:runner": "node --test scripts/__tests__/test-workspaces.test.mjs scripts/__tests__/dev-docs-contract.test.mjs scripts/__tests__/restart-desktop-remote.test.mjs scripts/__tests__/dev-migration-policy.test.mjs scripts/__tests__/ensure-deps.test.mjs scripts/__tests__/client-endpoint-build-env.test.mjs scripts/__tests__/endpoint-consistency.test.mjs scripts/__tests__/endpoint-local-file.test.mjs scripts/__tests__/ensure-agent-binaries.test.mjs scripts/__tests__/fetch-with-timeout.test.mjs scripts/__tests__/agent-binary-cdn-fallback.test.mjs scripts/__tests__/ensure-binary-fallback.test.mjs scripts/__tests__/verify-sha256.test.mjs scripts/__tests__/migration-freeze.test.mjs scripts/__tests__/third-party-notices.test.mjs scripts/__tests__/brand-identity-sync.test.mjs scripts/__tests__/check-dco.test.mjs","test:unit": "pnpm test:runner && node scripts/test-workspaces.mjs --tier unit","test:all": "pnpm test:runner && node scripts/test-workspaces.mjs --all","test:db": "pnpm test:runner && node scripts/test-workspaces.mjs --tier db",diff --git a/scripts/__tests__/check-dco.test.mjs b/scripts/__tests__/check-dco.test.mjsnew file mode 100644index 0000000000..117211edf9--- /dev/null+++ b/scripts/__tests__/check-dco.test.mjs@@ -0,0 +1,642 @@+// check-dco.test.mjs — DCO 门禁的判定契约与端到端行为。+//+// 纯函数部分断言判定规则(签名解析、author 比对、merge 豁免、git log 解析);+// 端到端部分在 os.tmpdir 里造一个真 git 仓库,跑 CLI 与 prepare-commit-msg hook——+// 格式串、范围解析、hook 里的 sh/sed 写错都只能在真 git 上暴露。++import assert from 'node:assert/strict';+import { execFileSync } from 'node:child_process';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import test from 'node:test';+import { fileURLToPath } from 'node:url';++import {+ exemptReason,+ looksLikeBotAddress,+ looksLikeEmail,+ parseGitLog,+ parseSignOffs,+ validateCommit,+ validateCommits,+} from '../check-dco.mjs';+import {+ HOOK_MARKER,+ HOOK_NAME,+ HOOK_SOURCE_PATH,+ classifyHook,+ isExecutable,+ readHookSource,+ resolveHooksDir,+ resolveHooksPathFrom,+} from '../install-dco-hook.mjs';++const ROOT = path.resolve(fileURLToPath(new URL('../..', import.meta.url)));+const CHECK_DCO = path.join(ROOT, 'scripts', 'check-dco.mjs');+const INSTALL_HOOK = path.join(ROOT, 'scripts', 'install-dco-hook.mjs');++const AUTHOR = { name: 'Contributor', email: '[email protected]' };++function commitFixture(overrides = {}) {+ return {+ sha: '1111111111111111111111111111111111111111',+ parents: ['0000000000000000000000000000000000000000'],+ authorName: AUTHOR.name,+ authorEmail: AUTHOR.email,+ committerName: AUTHOR.name,+ committerEmail: AUTHOR.email,+ message: 'feat: subject\n',+ ...overrides,+ };+}++test('parseSignOffs picks up every sign-off line and ignores other trailers', () => {+ const signOffs = parseSignOffs(+ [+ 'fix: something',+ '',+ 'Co-authored-by: Someone <[email protected]>',+ 'signed-off-by: Lower Case <[email protected]> ',+ 'Signed-off-by: Contributor <[email protected]>',+ ].join('\n')+ );+ // 大小写不敏感、`>` 后的尾随空白允许(App 的 `\s*$` 亦然)。+ assert.deepEqual(signOffs, [+ { name: 'Lower Case', email: '[email protected]' },+ { name: 'Contributor', email: '[email protected]' },+ ]);+ assert.deepEqual(parseSignOffs('docs: no trailer here'), []);+ // 「提到」sign-off 不等于签署:正文里的散句不构成 trailer 行。+ assert.deepEqual(parseSignOffs('chore: mention Signed-off-by: nobody in prose'), []);+});++test('sign-off parsing stays as strict as the App on line shape', () => {+ // App 的匹配器锚在行首,缩进过的「签名」在它眼里不存在 —— 本地必须一样看不见它,+ // 否则就是本地绿、PR 红。+ assert.deepEqual(parseSignOffs(` Signed-off-by: ${AUTHOR.name} <${AUTHOR.email}>`), []);+ assert.deepEqual(parseSignOffs(`\tSigned-off-by: ${AUTHOR.name} <${AUTHOR.email}>`), []);++ // 冒号后写两个空格:App 会把多出来的空格算进 name,于是与 author 比不上。这里同样+ // 要判失败 —— 解析得到的 name 带前导空格,比对时不 trim。+ const twoSpaces = parseSignOffs(`Signed-off-by: ${AUTHOR.name} <${AUTHOR.email}>`);+ assert.deepEqual(twoSpaces, [{ name: ` ${AUTHOR.name}`, email: AUTHOR.email }]);+ const rejected = validateCommit(+ commitFixture({ message: `feat: x\n\nSigned-off-by: ${AUTHOR.name} <${AUTHOR.email}>\n` })+ );+ assert.equal(rejected.length, 1);+ assert.match(rejected[0], /match one of them as a whole/i);++ // name 尾部多空格同理。+ assert.equal(+ validateCommit(+ commitFixture({ message: `feat: x\n\nSigned-off-by: ${AUTHOR.name} <${AUTHOR.email}>\n` })+ ).length,+ 1+ );++ // 规范写法必须通过,别把严格做成一刀切。+ assert.deepEqual(validateCommit(commitFixture({ message: signedOff() })), []);+});++const signedOff = (subject = 'feat: x') =>+ `${subject}\n\nSigned-off-by: ${AUTHOR.name} <${AUTHOR.email}>\n`;++test('validateCommit accepts a sign-off matching author or committer', () => {+ assert.deepEqual(validateCommit(commitFixture({ message: signedOff() })), []);+ // rebase / apply 他人 patch 时 author 与 committer 不同,committer 的签名也算。+ assert.deepEqual(+ validateCommit(commitFixture({ authorEmail: '[email protected]', message: signedOff() })),+ []+ );+ // 大小写与空白不应造成误报。+ assert.deepEqual(+ validateCommit(+ commitFixture({ message: `feat: x\n\nSigned-off-by: CONTRIBUTOR <[email protected]> \n` })+ ),+ []+ );+});++test('validateCommit rejects a missing or mismatched sign-off', () => {+ const missing = validateCommit(commitFixture());+ assert.equal(missing.length, 1);+ assert.match(missing[0], /No Signed-off-by trailer/);++ const mismatched = validateCommit(+ commitFixture({ message: 'feat: x\n\nSigned-off-by: Other <[email protected]>\n' })+ );+ assert.equal(mismatched.length, 1);+ assert.match(mismatched[0], /other@example\.com/);+ assert.match(mismatched[0], /Expected a sign-off from/);+});++test('validateCommit matches the DCO App on names and address shape', () => {+ // 只查 email 会比 PR 门禁宽松,导致本地绿、CI 红。+ const wrongName = validateCommit(+ commitFixture({ message: `feat: x\n\nSigned-off-by: Someone Else <${AUTHOR.email}>\n` })+ );+ assert.equal(wrongName.length, 1);+ assert.match(wrongName[0], /match one of them as a whole/i);++ const badEmail = validateCommit(+ commitFixture({+ authorEmail: 'contributor@localhost',+ committerEmail: 'contributor@localhost',+ message: 'feat: x\n\nSigned-off-by: Contributor <contributor@localhost>\n',+ })+ );+ assert.equal(badEmail.length, 1);+ assert.match(badEmail[0], /not a valid email address/);+});++test('a sign-off has to match one identity as a whole, not a mix of two', () => {+ // author=Alice<alice@>、committer=Bob<bob@> 时,`Alice <bob@…>` 谁都不是。App 把+ // name 与 email 拆成两个集合,会放过这种组合;本地刻意更严(偏严只会本地红、PR 绿)。+ const crossed = validateCommit(+ commitFixture({+ authorName: 'Alice',+ authorEmail: '[email protected]',+ committerName: 'Bob',+ committerEmail: '[email protected]',+ message: 'feat: x\n\nSigned-off-by: Alice <[email protected]>\n',+ })+ );+ assert.equal(crossed.length, 1);+ assert.match(crossed[0], /match one of them as a whole/i);++ // 同一组身份下,author 与 committer 各自的完整签名都要接受。+ for (const signOff of ['Alice <[email protected]>', 'Bob <[email protected]>']) {+ assert.deepEqual(+ validateCommit(+ commitFixture({+ authorName: 'Alice',+ authorEmail: '[email protected]',+ committerName: 'Bob',+ committerEmail: '[email protected]',+ message: `feat: x\n\nSigned-off-by: ${signOff}\n`,+ })+ ),+ []+ );+ }+});++test('looksLikeEmail rejects everything validator.isEmail would reject', () => {+ for (const good of [+ '[email protected]',+ '[email protected]',+ '[email protected]',+ "o'[email protected]",+ '[email protected]',+ ]) {+ assert.equal(looksLikeEmail(good), true, `should accept ${good}`);+ }+ // 放行任何一个 App 会拒的地址就会变成「本地绿、PR 红」。+ for (const bad of [+ '[email protected]',+ '[email protected]',+ '[email protected]',+ '[email protected]',+ 'alice@exam_ple.com',+ '[email protected]', // 域名 label 不能以连字符开头+ '[email protected]', // 也不能以连字符结尾+ 'a(b)@example.com', // 括号不在 atext 内+ 'a<b>@example.com',+ 'a [email protected]',+ 'contributor@localhost',+ 'contributor@example',+ 'no-at-sign.example.com',+ '@example.com',+ 'alice@',+ '',+ // 方括号同样不在 atext 内,validator 也拒。bot 地址不再被本地豁免(账号类型离线+ // 判不了),所以这类提交会在这里失败——方向安全:本地红、PR 绿,失败输出里有解释。+ '49699333+dependabot[bot]@users.noreply.github.com',+ // 长度上限(validator 同样拒):local part > 64、单个域名 label > 63、域名 > 254。+ `${'a'.repeat(65)}@example.com`,+ `a@${'b'.repeat(64)}.com`,+ `a@${`${'b'.repeat(60)}.`.repeat(5)}com`,+ // 各段都合规、整体仍超 254:整体上限必须单独查一遍。+ `${'a'.repeat(64)}@${'b'.repeat(63)}.${'c'.repeat(63)}.${'d'.repeat(61)}.com`,+ ]) {+ assert.equal(looksLikeEmail(bad), false, `should reject ${bad}`);+ }+ // 恰好在上限上要放行,别把边界一起误杀。+ assert.equal(looksLikeEmail(`${'a'.repeat(64)}@example.com`), true);+ assert.equal(looksLikeEmail(`a@${'b'.repeat(63)}.com`), true);+ const at254 = `${'a'.repeat(64)}@${'b'.repeat(63)}.${'c'.repeat(63)}.${'d'.repeat(57)}.com`;+ assert.equal(at254.length, 254, '这个用例的意义就在于长度恰好是 254');+ assert.equal(looksLikeEmail(at254), true);+ assert.equal(looksLikeEmail(`a${at254}`), false, '255 就该拒');+});++test('only merge commits are exempt — bot status is not decidable offline', () => {+ // 父提交数量是唯一能离线可靠判定的豁免依据。+ assert.equal(exemptReason(commitFixture({ parents: ['a'.repeat(40), 'b'.repeat(40)] })), 'merge commit');+ assert.equal(exemptReason(commitFixture()), null);++ // author 邮箱同样是自由填写的:`999999+not-a-real-account[bot]@users.noreply.github.com`+ // 谁都能设,而 App 认的是 GitHub 账号类型。按邮箱豁免就是一个可伪造的后门,+ // 方向还是最坏的「本地绿、PR 红」,所以这里一律不豁免。+ for (const email of [+ '49699333+dependabot[bot]@users.noreply.github.com',+ '999999+not-a-real-account[bot]@users.noreply.github.com',+ '[email protected]',+ ]) {+ assert.equal(+ exemptReason(+ commitFixture({ authorEmail: email, committerEmail: email, message: 'chore: unsigned\n' })+ ),+ null,+ `${email} 不该被豁免`+ );+ }++ // 只保留「看起来像 bot 地址」这个判断,用途仅限失败输出里的解释。+ assert.ok(looksLikeBotAddress('49699333+dependabot[bot]@users.noreply.github.com'));+ assert.ok(looksLikeBotAddress('[email protected]'));+ assert.equal(looksLikeBotAddress('[email protected]'), false);+ assert.equal(looksLikeBotAddress('[email protected]'), false);+});++test('a bot-looking unsigned commit is reported, with an explanation', () => {+ const botEmail = '49699333+dependabot[bot]@users.noreply.github.com';+ const result = validateCommits([+ commitFixture({+ authorName: 'dependabot[bot]',+ authorEmail: botEmail,+ committerName: 'dependabot[bot]',+ committerEmail: botEmail,+ message: 'chore(deps): bump something\n',+ }),+ ]);+ // 不再豁免:算进 checked 并报为失败。+ assert.equal(result.exempted.length, 0);+ assert.equal(result.checked, 1);+ assert.equal(result.failures.length, 1);+ // 这类地址不合 atext,所以先在邮箱形状上失败——App 那边则因为账号是 Bot 直接跳过,+ // 两者结论不同但方向安全(本地红、PR 绿)。+ assert.match(result.failures[0].errors[0], /not a valid email address|No Signed-off-by/);+});++test('validateCommits separates failures from exemptions', () => {+ const result = validateCommits([+ commitFixture({ sha: 'a'.repeat(40) }),+ commitFixture({ sha: 'b'.repeat(40), message: signedOff('fix: y') }),+ commitFixture({ sha: 'c'.repeat(40), parents: ['x'.repeat(40), 'y'.repeat(40)] }),+ ]);+ assert.equal(result.checked, 2);+ assert.equal(result.failures.length, 1);+ assert.equal(result.failures[0].commit.sha, 'a'.repeat(40));+ assert.equal(result.exempted.length, 1);+});++test('parseGitLog keeps multi-line messages and parent lists intact', () => {+ const FIELD = '\u001f';+ const RECORD = '\u001e';+ const record = (fields) => fields.join(FIELD) + RECORD + '\n';+ const stdout =+ record([+ 'a'.repeat(40),+ `${'p'.repeat(40)} ${'q'.repeat(40)}`,+ 'Bot',+ '[email protected]',+ 'Bot',+ '[email protected]',+ 'chore: merge\n\nbody line\n',+ ]) ++ record([+ 'b'.repeat(40),+ 'p'.repeat(40),+ '贡献者',+ AUTHOR.email,+ '贡献者',+ AUTHOR.email,+ `feat: 中文标题\n\nSigned-off-by: 贡献者 <${AUTHOR.email}>\n`,+ ]);++ const commits = parseGitLog(stdout);+ assert.equal(commits.length, 2);+ assert.equal(commits[0].parents.length, 2);+ assert.match(commits[0].message, /body line/);+ assert.equal(commits[1].authorName, '贡献者');+ assert.deepEqual(validateCommit(commits[1]), []);+});++test('classifyHook never marks a changed hook as safe to overwrite', () => {+ const source = readHookSource();++ // 不传 expectedContent 时按源文件判定;missing 分支不读磁盘(懒求值,见实现注释——+ // 「没读文件」这件事从外部观测需要 mock fs,不值当,这里只钉行为契约)。+ assert.equal(classifyHook(null), 'missing');+ assert.equal(classifyHook(null, 'anything'), 'missing');+ assert.equal(classifyHook(source), 'installed');+ assert.equal(classifyHook('#!/bin/sh\necho unrelated\n'), 'foreign');++ // 复合 hook 有两种来法,两者都不能被当成「可以直接覆盖」:+ // 1. 把本仓逻辑合并进自己的 hook(我们的注释在文件中间)+ const merged = ['#!/bin/sh', 'echo "my own hook"', ...source.split('\n').slice(1)].join('\n');+ // 2. 在本仓装好的 hook 后面追加自己的逻辑(开头几行仍是我们的)+ const appended = `${source}\necho custom\n`;+ for (const composite of [merged, appended]) {+ assert.ok(composite.includes(HOOK_MARKER));+ assert.equal(classifyHook(composite), 'modified');+ }++ // 旧版本 hook 与「被本人改过」在磁盘上分辨不出来,一律 modified 而非可覆盖状态。+ assert.equal(classifyHook(`${source.split('\n').slice(0, 2).join('\n')}\nold body\n`), 'modified');+});++test('legacy hooks-path fallback resolves against the caller cwd', () => {+ // git < 2.31 的回落分支。--git-path 的相对路径基准是执行 git 时的 cwd;用仓库根去解析+ // 会向上多走几级,把 hook 装进别的仓库。CI 上的 git 走不到这个分支,所以直接断言纯函数。+ assert.equal(+ resolveHooksPathFrom(path.join('..', '..', '.git', 'hooks'), '/repo/apps/desktop'),+ path.resolve('/repo/.git/hooks')+ );+ assert.equal(resolveHooksPathFrom(path.join('.git', 'hooks'), '/repo'), path.resolve('/repo/.git/hooks'));+ // 已经是绝对路径时原样返回。+ assert.equal(resolveHooksPathFrom(path.resolve('/abs/.git/hooks'), '/anywhere'), path.resolve('/abs/.git/hooks'));+});++test('the hook source is a POSIX sh script that pins its trailer behaviour', () => {+ const source = readHookSource();+ assert.match(source, /^#!\/bin\/sh\n/);+ assert.ok(source.includes(HOOK_MARKER), 'hook 必须带 marker,否则安装器无法认领它');+ // 必须签 committer:签 author 会在 --author / cherry-pick / rebase 他人 patch 时+ // 伪造别人的 DCO 声明。native `git commit -s` 同样用 committer。+ assert.match(source, /GIT_COMMITTER_IDENT/);+ assert.doesNotMatch(source, /GIT_AUTHOR_IDENT/);+ // 这两个开关的默认值可被开发者的 trailer.ifExists / trailer.ifMissing 配置改掉,+ // 配成 doNothing 时 hook 会在已有他人签名的提交上静默漏签,必须显式钉住。+ assert.match(source, /--if-exists addIfDifferent/);+ assert.match(source, /--if-missing add/);+ // 语法必须是 POSIX sh:hook 由 git 用 /bin/sh 执行,bashism 在 dash 上会直接失败。+ execFileSync('sh', ['-n', path.join(ROOT, HOOK_SOURCE_PATH)]);+});++// --- 端到端:真 git 仓库 ---++const canRunGitFixture = process.platform !== 'win32';++function createRepo() {+ const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-dco-')));+ // 隔离全局/系统 git 配置,避免宿主机的 hooksPath、gpgsign、template 影响结果。+ const env = { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_SYSTEM: '/dev/null' };+ const run = (args, options = {}) =>+ execFileSync(args[0], args.slice(1), { cwd: dir, env, encoding: 'utf8', ...options });++ run(['git', 'init', '--quiet', '--initial-branch=main', '.']);+ run(['git', 'config', 'user.name', AUTHOR.name]);+ run(['git', 'config', 'user.email', AUTHOR.email]);+ run(['git', 'config', 'commit.gpgsign', 'false']);++ const write = (name, content) => fs.writeFileSync(path.join(dir, name), content);+ const commit = (name, message, extraArgs = []) => {+ write(name, `${name}\n`);+ run(['git', 'add', name]);+ run(['git', 'commit', '--quiet', ...extraArgs, '-m', message]);+ };+ const checkDco = (args, extraEnv = {}) => {+ try {+ const stdout = run(['node', CHECK_DCO, ...args], {+ stdio: ['ignore', 'pipe', 'pipe'],+ env: { ...env, ...extraEnv },+ });+ return { code: 0, output: stdout };+ } catch (error) {+ return { code: error.status ?? 1, output: `${error.stdout ?? ''}${error.stderr ?? ''}` };+ }+ };+ const sha = (ref) => run(['git', 'rev-parse', ref]).trim();+ /** 写一份 pull_request 事件 payload,模拟 CI 里的 GITHUB_EVENT_PATH。 */+ const writeEvent = (baseSha, headSha) => {+ const eventPath = path.join(dir, 'event.json');+ fs.writeFileSync(+ eventPath,+ JSON.stringify({ pull_request: { base: { sha: baseSha }, head: { sha: headSha } } })+ );+ return eventPath;+ };++ return { dir, run, commit, checkDco, sha, writeEvent };+}++test('CLI fails on an unsigned commit and passes once it is signed off', { skip: !canRunGitFixture }, (t) => {+ const repo = createRepo();+ t.after(() => fs.rmSync(repo.dir, { recursive: true, force: true }));++ // 历史提交故意不签名:门禁只看范围内的新 commit,不追溯历史。+ repo.commit('history.txt', 'chore: pre-DCO history');+ repo.run(['git', 'checkout', '--quiet', '-b', 'feature']);+ repo.commit('feature.txt', 'feat: unsigned work');++ const failed = repo.checkDco(['--base', 'main']);+ assert.equal(failed.code, 1);+ assert.match(failed.output, /DCO check failed/);+ assert.match(failed.output, /No Signed-off-by trailer/);+ assert.match(failed.output, /git rebase --signoff/);++ repo.run(['git', 'commit', '--quiet', '--amend', '-s', '--no-edit']);+ const passed = repo.checkDco(['--base', 'main']);+ assert.equal(passed.code, 0);+ assert.match(passed.output, /DCO check passed/);+});++test('installed hook signs off subsequent commits automatically', { skip: !canRunGitFixture }, (t) => {+ const repo = createRepo();+ t.after(() => fs.rmSync(repo.dir, { recursive: true, force: true }));++ repo.commit('history.txt', 'chore: pre-DCO history');+ repo.run(['git', 'checkout', '--quiet', '-b', 'feature']);+ repo.run(['node', INSTALL_HOOK]);++ const hookPath = path.join(repo.dir, '.git', 'hooks', HOOK_NAME);+ assert.equal(classifyHook(fs.readFileSync(hookPath, 'utf8')), 'installed');++ // 注意这里没有 -s:hook 必须自己补上签名。+ repo.commit('feature.txt', 'feat: work committed without -s');+ const message = repo.run(['git', 'log', '-1', '--format=%B']);+ assert.match(message, new RegExp(`Signed-off-by: ${AUTHOR.name} <${AUTHOR.email}>`));++ // 已带签名时不重复追加。+ repo.commit('second.txt', `fix: already signed\n\nSigned-off-by: ${AUTHOR.name} <${AUTHOR.email}>`);+ const secondMessage = repo.run(['git', 'log', '-1', '--format=%B']);+ assert.equal(secondMessage.match(/Signed-off-by:/g).length, 1);++ // 开发者把 trailer.ifExists 配成 doNothing(interpret-trailers 的默认值可被覆盖)时,+ // 带着他人签名的提交仍必须补上本人签名,否则门禁会红而 hook 一声不响。+ repo.run(['git', 'config', 'trailer.ifExists', 'doNothing']);+ repo.commit('third.txt', 'fix: carries someone elses sign-off\n\nSigned-off-by: Other <[email protected]>');+ const thirdMessage = repo.run(['git', 'log', '-1', '--format=%B']);+ assert.match(thirdMessage, new RegExp(`Signed-off-by: ${AUTHOR.name} <${AUTHOR.email}>`));+ repo.run(['git', 'config', '--unset', 'trailer.ifExists']);++ assert.equal(repo.checkDco(['--base', 'main']).code, 0);+});++test('hook signs off the committer, never the overridden author', { skip: !canRunGitFixture }, (t) => {+ const repo = createRepo();+ t.after(() => fs.rmSync(repo.dir, { recursive: true, force: true }));++ repo.commit('history.txt', 'chore: pre-DCO history');+ repo.run(['git', 'checkout', '--quiet', '-b', 'feature']);+ repo.run(['node', INSTALL_HOOK]);++ // 用 --author 假冒他人:hook 绝不能替 Alice 签名,那是伪造她的 DCO 声明。+ fs.writeFileSync(path.join(repo.dir, 'feature.txt'), 'feature\n');+ repo.run(['git', 'add', 'feature.txt']);+ repo.run([+ 'git',+ 'commit',+ '--quiet',+ '--author=Alice <[email protected]>',+ '-m',+ 'feat: committed on behalf of Alice',+ ]);++ const message = repo.run(['git', 'log', '-1', '--format=%B']);+ assert.match(message, new RegExp(`Signed-off-by: ${AUTHOR.name} <${AUTHOR.email}>`));+ assert.doesNotMatch(message, /Signed-off-by: Alice/);++ // 与原生 `git commit -s` 的结果一致。+ fs.writeFileSync(path.join(repo.dir, 'native.txt'), 'native\n');+ repo.run(['git', 'add', 'native.txt']);+ repo.run(['git', 'commit', '--quiet', '-s', '--author=Alice <[email protected]>', '-m', 'feat: native -s']);+ assert.match(+ repo.run(['git', 'log', '-1', '--format=%B']),+ new RegExp(`Signed-off-by: ${AUTHOR.name} <${AUTHOR.email}>`)+ );++ // committer 的签名同样满足门禁(App 与本脚本都接受 author 或 committer)。+ assert.equal(repo.checkDco(['--base', 'main']).code, 0);+});++test('installer refuses to clobber an edited hook without --force', { skip: !canRunGitFixture }, (t) => {+ const repo = createRepo();+ t.after(() => fs.rmSync(repo.dir, { recursive: true, force: true }));++ repo.commit('history.txt', 'chore: pre-DCO history');+ repo.run(['node', INSTALL_HOOK]);+ const hookPath = path.join(repo.dir, '.git', 'hooks', HOOK_NAME);+ assert.equal(fs.readFileSync(hookPath, 'utf8'), readHookSource());++ // resolveHooksDir 必须给出绝对路径,且从子目录调用时也要落在本仓库的 hooks 目录。+ // 回落分支(旧版 git)解析相对路径的基准必须是调用时的 cwd:拿仓库根去解析会向上多走+ // 几级,写进隔壁仓库的 .git/hooks。+ const expectedHooksDir = path.join(repo.dir, '.git', 'hooks');+ assert.equal(resolveHooksDir(repo.dir), expectedHooksDir);+ const subDir = path.join(repo.dir, 'nested', 'deeper');+ fs.mkdirSync(subDir, { recursive: true });+ assert.equal(resolveHooksDir(subDir), expectedHooksDir);++ // 装完之后开发者又追加了自己的逻辑。+ const edited = `${readHookSource()}\necho "my own extra step"\n`;+ fs.writeFileSync(hookPath, edited);++ let refused;+ try {+ repo.run(['node', INSTALL_HOOK], { stdio: ['ignore', 'pipe', 'pipe'] });+ refused = null;+ } catch (error) {+ refused = `${error.stdout ?? ''}${error.stderr ?? ''}`;+ }+ assert.ok(refused, '没有 --force 时必须失败退出');+ assert.match(refused, /Not overwriting it/);+ assert.equal(fs.readFileSync(hookPath, 'utf8'), edited, '拒绝时绝不能改动文件');++ // 显式 --force 才覆盖。+ repo.run(['node', INSTALL_HOOK, '--force']);+ assert.equal(fs.readFileSync(hookPath, 'utf8'), readHookSource());+});++test('installer restores a lost executable bit', { skip: !canRunGitFixture }, (t) => {+ const repo = createRepo();+ t.after(() => fs.rmSync(repo.dir, { recursive: true, force: true }));++ repo.commit('history.txt', 'chore: pre-DCO history');+ repo.run(['git', 'checkout', '--quiet', '-b', 'feature']);+ repo.run(['node', INSTALL_HOOK]);+ const hookPath = path.join(repo.dir, '.git', 'hooks', HOOK_NAME);++ // 内容逐字一致但不可执行(手动复制、备份恢复、chmod 0644):git 会静默忽略这个 hook,+ // 提交照样不带签名,而只看内容的安装器会报「已是最新」把人骗过去。+ fs.chmodSync(hookPath, 0o644);+ assert.equal(isExecutable(hookPath), false);+ assert.equal(classifyHook(fs.readFileSync(hookPath, 'utf8')), 'installed');++ // --check 要点出这个状态,而不是笼统报 installed。+ assert.match(repo.run(['node', INSTALL_HOOK, '--check']), /NOT executable/);++ const output = repo.run(['node', INSTALL_HOOK]);+ assert.match(output, /Restored the executable bit/);+ assert.equal(isExecutable(hookPath), true);++ // 修好之后 hook 真的生效(没有 -s 也自动补签)。+ repo.commit('feature.txt', 'feat: work committed without -s');+ assert.match(+ repo.run(['git', 'log', '-1', '--format=%B']),+ new RegExp(`Signed-off-by: ${AUTHOR.name} <${AUTHOR.email}>`)+ );+ assert.equal(repo.checkDco(['--base', 'main']).code, 0);+});++test('hook keeps the native `commit -s` layout for interactive commits', { skip: !canRunGitFixture }, (t) => {+ const repo = createRepo();+ t.after(() => fs.rmSync(repo.dir, { recursive: true, force: true }));++ repo.commit('history.txt', 'chore: pre-DCO history');+ repo.run(['git', 'checkout', '--quiet', '-b', 'feature']);+ repo.run(['node', INSTALL_HOOK]);++ // 模拟交互式提交:编辑器把标题写到消息首行,此时 hook 早已跑过。+ const editor = path.join(repo.dir, 'editor.sh');+ fs.writeFileSync(+ editor,+ ['#!/bin/sh', 'printf "feat: interactive title\\n" > "$1.tmp"', 'cat "$1" >> "$1.tmp"', 'mv "$1.tmp" "$1"', ''].join('\n')+ );+ fs.chmodSync(editor, 0o755);++ fs.writeFileSync(path.join(repo.dir, 'feature.txt'), 'feature\n');+ repo.run(['git', 'add', 'feature.txt']);+ repo.run(['git', 'commit', '--quiet'], { env: { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_SYSTEM: '/dev/null', GIT_EDITOR: editor } });++ // 标题与签名之间必须有空行——这正是 `git commit -s` 的模板格式。+ assert.equal(+ repo.run(['git', 'log', '-1', '--format=%B']).trim(),+ `feat: interactive title\n\nSigned-off-by: ${AUTHOR.name} <${AUTHOR.email}>`+ );+ assert.equal(repo.run(['git', 'log', '-1', '--format=%s']).trim(), 'feat: interactive title');+ assert.equal(repo.checkDco(['--base', 'main']).code, 0);+});++test('CLI takes its range from the pull_request payload in CI', { skip: !canRunGitFixture }, (t) => {+ const repo = createRepo();+ t.after(() => fs.rmSync(repo.dir, { recursive: true, force: true }));++ repo.commit('history.txt', 'chore: pre-DCO history');+ const prBase = repo.sha('HEAD');+ repo.run(['git', 'checkout', '--quiet', '-b', 'feature']);+ repo.commit('feature.txt', 'feat: signed work', ['-s']);+ const prHead = repo.sha('HEAD');++ const fromPayload = repo.checkDco([], {+ GITHUB_EVENT_PATH: repo.writeEvent(prBase, prHead),+ });+ assert.equal(fromPayload.code, 0);+ assert.match(fromPayload.output, /DCO check passed: 1 commit signed off/);++ // base 分支在 PR 开着期间前进,且新提交没有签名:merge-base 必须把它排除在范围外,+ // 否则每个 PR 都会因为别人推到 main 的提交无端变红。+ repo.run(['git', 'checkout', '--quiet', 'main']);+ repo.commit('other.txt', 'chore: unsigned commit pushed to main by someone else');+ const movedBase = repo.sha('HEAD');+ repo.run(['git', 'checkout', '--quiet', 'feature']);++ const afterBaseMoved = repo.checkDco([], {+ GITHUB_EVENT_PATH: repo.writeEvent(movedBase, prHead),+ });+ assert.equal(afterBaseMoved.code, 0);+ assert.match(afterBaseMoved.output, /DCO check passed: 1 commit signed off/);+});diff --git a/scripts/check-dco.mjs b/scripts/check-dco.mjsnew file mode 100644index 0000000000..176b75e863--- /dev/null+++ b/scripts/check-dco.mjs@@ -0,0 +1,347 @@+#!/usr/bin/env node+// DCO(Developer Certificate of Origin)门禁:校验一段 commit 范围里每个非豁免 commit+// 都带有与其 author(或 committer)一致的 Signed-off-by trailer。DCO 全文见仓库根+// 的 DCO 文件,贡献者侧说明见 CONTRIBUTING.md「贡献的许可与署名(DCO)」。+//+// 只检查 PR 引入的新 commit(merge-base..head),不追溯仓库历史,因此对 DCO 生效前+// 的既有提交无影响。只读 git 元数据,不访问网络、不读任何私有配置或凭证。+//+// PR 上的权威门禁是 DCO GitHub App 的 check(配置见 .github/dco.yml),本脚本是提交前+// 的本地自查,判定刻意与 App 对齐或更严,好让本地通过一定意味着 App 通过。+//+// 本地用法:+// pnpm check:dco 校验 origin/main..HEAD+// node scripts/check-dco.mjs --base <ref> --head <ref>+// 在 pull_request 事件下运行时(GITHUB_EVENT_PATH 存在)自动从 payload 取+// base.sha 与 head.sha 作为范围。++import { execFileSync } from 'node:child_process';+import { readFileSync } from 'node:fs';+import { pathToFileURL } from 'node:url';++import { isSignOffHookInstalled } from './install-dco-hook.mjs';++// git log 的字段/记录分隔符:用 ASCII 控制字符,避免与 commit message 内容碰撞。+const FIELD_SEP = '\u001f';+const RECORD_SEP = '\u001e';+const LOG_FORMAT = ['%H', '%P', '%an', '%ae', '%cn', '%ce', '%B'].join(FIELD_SEP) + RECORD_SEP;++// 与 DCO App 的匹配器逐字对齐(dcoapp/app 的 `lib/dco.js`:+// `/^Signed-off-by: (.*) <(.*)>\s*$/gim`)。逐行匹配而不强求在 message 末尾:trailer+// 之后常见还有 Co-authored-by 等其他 trailer。+//+// 刻意不放宽这三处,它们都会造成「本地绿、PR 红」:+// - 不允许行首空白:App 的 `^Signed-off-by:` 锚在行首,缩进过的行在它眼里根本不是签名。+// - `Signed-off-by:` 后只允许一个空格:写两个空格时 App 会把多出来的空格算进 name,+// 于是 name 与 author 比不上。+// - 捕获值不 trim(见 validateCommit):App 拿原样捕获去比,`Alice ` 不等于 `Alice`。+const SIGN_OFF_LINE = /^Signed-off-by: (.*) <(.*)>\s*$/i;++// bot 地址的形状特征:dependabot 等用 `<name>[bot]@users.noreply.github.com`,+// GitHub Web UI 用 web-flow 的 [email protected]。+//+// **这只用于在失败输出里提示,不用于豁免。** App 判定 bot 的依据是 GitHub 账号类型+// (`author.type === "Bot"`),离线拿不到也伪造不了;而 author 邮箱谁都能设成+// `999999+not-a-real-account[bot]@users.noreply.github.com`。按邮箱豁免就等于给本地检查+// 留一个可伪造的后门,方向还是最坏的那种——「本地绿、PR 红」。所以本地一律检查,+// 只在输出里说明「若它真是 bot,PR 上的 App 会豁免」。+const BOT_EMAILS = new Set(['[email protected]']);+const BOT_EMAIL_SUFFIX = '[bot]@users.noreply.github.com';++// 本地默认基准。upstream/main 排在前面:从 fork 干活时 origin/main 可能领先于上游,+// 拿它当基准会把 fork 自己那些未签名的提交排除在范围外,而 PR 的真实 base 是上游。+// 这只是本地自查的启发式——真实 base 以 PR 上的 DCO check 为准,所以通过时会把实际用的+// 基准打印出来。+const DEFAULT_BASE_CANDIDATES = ['upstream/main', 'origin/main', 'main'];++const git = (args, options = {}) =>+ execFileSync('git', args, { encoding: 'utf8', ...options }).trim();++export function normalizeEmail(email) {+ return String(email ?? '').trim().toLowerCase();+}++export function normalizeName(name) {+ return String(name ?? '').trim().toLowerCase();+}++// 邮箱形状:对齐 DCO App 用的 validator.isEmail 的默认规则。+// - local part 限定为 RFC 5322 的 atext 字符集,点分隔且不允许连续点或首尾点。+// 注意 atext 不含括号、方括号、引号等,所以 `a(b)@x.com` 会被拒——validator 也拒。+// - 域名每个 label 不能以连字符开头或结尾,不允许下划线,且必须有字母 TLD(于是 git 未配+// user.email 时自动生成的 `user@hostname` 会被拒)。+// 无法逐条复刻 validator,取舍上刻意偏严:宁可本地误报,也不要放行一个 App 会拒的地址,+// 那才会变成「本地绿、PR 红」。含方括号的 bot 邮箱(dependabot 等)同样不符合 atext,+// 于是这类提交在本地会被报出来——而 App 因为账号是 Bot 直接跳过。结论不同但方向安全+// (本地红、PR 绿),失败输出里会说明这一点。+const ATEXT = "[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]";+const DOMAIN_LABEL = '[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?';+const EMAIL_LOCAL_PART = new RegExp(`^${ATEXT}+(?:\\.${ATEXT}+)*$`);+const EMAIL_DOMAIN = new RegExp(`^${DOMAIN_LABEL}(?:\\.${DOMAIN_LABEL})*\\.[A-Za-z]{2,}$`);+// validator.isEmail 的长度上限,超出即拒。整体上限单独存在:local part 与 domain 各自+// 合规、加起来仍可能超过 254。+const MAX_TOTAL = 254;+const MAX_LOCAL_PART = 64;+const MAX_DOMAIN = 254;+const MAX_DOMAIN_LABEL = 63;++export function looksLikeEmail(email) {+ const value = String(email ?? '').trim();+ if (value.length > MAX_TOTAL) return false;+ const at = value.lastIndexOf('@');+ if (at <= 0 || at === value.length - 1) return false;++ const localPart = value.slice(0, at);+ const domain = value.slice(at + 1);+ if (localPart.length > MAX_LOCAL_PART || domain.length > MAX_DOMAIN) return false;+ if (domain.split('.').some((label) => label.length > MAX_DOMAIN_LABEL)) return false;++ return EMAIL_LOCAL_PART.test(localPart) && EMAIL_DOMAIN.test(domain);+}++/**+ * 提取 message 里所有 Signed-off-by 行。捕获值原样保留、不 trim——App 也不 trim,+ * 多出来的空白会让它与 author 比对失败,这里跟着一起失败才不会「本地绿、PR 红」。+ */+export function parseSignOffs(message) {+ const signOffs = [];+ for (const line of String(message ?? '').split(/\r?\n/)) {+ const match = SIGN_OFF_LINE.exec(line);+ if (match) signOffs.push({ name: match[1], email: match[2] });+ }+ return signOffs;+}++/** 只判断「地址长得像 bot」,供失败输出提示用;不构成豁免,理由见上面的注释。 */+export function looksLikeBotAddress(email) {+ const normalizedEmail = normalizeEmail(email);+ return BOT_EMAILS.has(normalizedEmail) || normalizedEmail.endsWith(BOT_EMAIL_SUFFIX);+}++/**+ * 返回豁免原因,不豁免则返回 null。+ *+ * 只有 merge commit 能离线可靠判定(父提交数量),所以只豁免它。bot 提交交给 App 按账号+ * 类型豁免——本地宁可多报一条,也不放过一个可伪造的身份。+ */+export function exemptReason(commit) {+ if (commit.parents.length > 1) return 'merge commit';+ return null;+}++/**+ * 返回错误列表;空列表即通过。判定与 DCO App(dcoapp/app 的 lib/dco.js)对齐,两处+ * 刻意更严——偏严只会「本地红、PR 绿」,偏宽才会「本地绿、PR 红」,后者才是要避免的:+ *+ * 1. 签名必须整体匹配 author 或 committer 这一个身份。App 是把 name 与 email 拆成两个+ * 集合分别判断,于是 author=Alice<a@x>、committer=Bob<b@x> 时 `Alice <b@x>` 也能过,+ * 尽管这个身份并不存在——这里按 name+email 成对比较。+ * 2. 邮箱形状见 looksLikeEmail。+ *+ * 本脚本同样不识别 remediation commit(App 侧由 .github/dco.yml 开启),也是同一取舍。+ * 面向贡献者的文案统一用英文。+ */+export function validateCommit(commit) {+ const signOffs = parseSignOffs(commit.message);+ if (signOffs.length === 0) {+ return ['No Signed-off-by trailer.'];+ }++ // 与 App 一致:只看 author.email(缺失时回落 committer.email)。改成「两者都非法才+ // 失败」会比 App 宽松,反而制造本地绿、PR 红。+ const email = commit.authorEmail || commit.committerEmail;+ if (!looksLikeEmail(email)) {+ return [`${email} is not a valid email address.`];+ }++ const identities = [+ { name: normalizeName(commit.authorName), email: normalizeEmail(commit.authorEmail) },+ { name: normalizeName(commit.committerName), email: normalizeEmail(commit.committerEmail) },+ ];+ // 签名侧只 lowercase、不 trim(App 亦然);commit 侧 trim 是安全的,git ident 本身+ // 不带前后空白。两边处理方式刻意不同,正是为了让「Alice 」这种写法在本地也失败。+ const matches = (signOff) =>+ identities.some(+ (identity) =>+ identity.name === String(signOff.name).toLowerCase() &&+ identity.email === String(signOff.email).toLowerCase()+ );+ if (signOffs.some(matches)) return [];++ const got = signOffs.map((signOff) => `"${signOff.name} <${signOff.email}>"`).join(', ');+ return [+ `Expected a sign-off from "${commit.authorName} <${commit.authorEmail}>" or ` ++ `"${commit.committerName} <${commit.committerEmail}>", got ${got}. ` ++ 'The name and the address have to match one of them as a whole.',+ ];+}++export function validateCommits(commits) {+ const failures = [];+ const exempted = [];+ let checked = 0;++ for (const commit of commits) {+ const reason = exemptReason(commit);+ if (reason) {+ exempted.push({ commit, reason });+ continue;+ }+ checked += 1;+ const errors = validateCommit(commit);+ if (errors.length > 0) failures.push({ commit, errors });+ }++ return { failures, exempted, checked };+}++export function parseGitLog(stdout) {+ return String(stdout)+ .split(RECORD_SEP)+ .map((record) => record.replace(/^\r?\n/, ''))+ .filter((record) => record.trim() !== '')+ .map((record) => {+ const [sha, parents, authorName, authorEmail, committerName, committerEmail, message] =+ record.split(FIELD_SEP);+ return {+ sha: (sha ?? '').trim(),+ parents: (parents ?? '').trim() ? parents.trim().split(/\s+/) : [],+ authorName: authorName ?? '',+ authorEmail: authorEmail ?? '',+ committerName: committerName ?? '',+ committerEmail: committerEmail ?? '',+ message: message ?? '',+ };+ });+}++export function shortSha(sha) {+ return String(sha ?? '').slice(0, 8);+}++export function subjectOf(commit) {+ return String(commit.message ?? '').split(/\r?\n/, 1)[0].trim();+}++function readArg(name) {+ const index = process.argv.indexOf(name);+ return index !== -1 ? process.argv[index + 1] : undefined;+}++function revParse(ref) {+ try {+ return git(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`], { stdio: ['ignore', 'pipe', 'ignore'] });+ } catch {+ return null;+ }+}++/** 解析待校验范围。返回的 start 是排除端点(start..head)。 */+function resolveRange() {+ const explicitBase = readArg('--base');+ const explicitHead = readArg('--head');+ const eventPath = process.env.GITHUB_EVENT_PATH;++ let base = explicitBase;+ let head = explicitHead ?? 'HEAD';++ if (!base && eventPath) {+ const event = JSON.parse(readFileSync(eventPath, 'utf8'));+ const pr = event.pull_request;+ if (!pr) throw new Error('Event payload has no pull_request; check the workflow trigger.');+ base = pr.base?.sha;+ head = explicitHead ?? pr.head?.sha ?? 'HEAD';+ if (!base) throw new Error('Event payload is missing pull_request.base.sha.');+ }++ if (!base) {+ base = DEFAULT_BASE_CANDIDATES.find((candidate) => revParse(candidate));+ if (!base) {+ throw new Error(+ `No default base ref found (${DEFAULT_BASE_CANDIDATES.join(' / ')}); pass --base <ref>.`+ );+ }+ }++ const baseSha = revParse(base);+ if (!baseSha) throw new Error(`Cannot resolve base ref: ${base} (fetch it first if missing).`);+ const headSha = revParse(head);+ if (!headSha) throw new Error(`Cannot resolve head ref: ${head}.`);++ // 用 merge-base 而不是 base 本身:base 分支在 PR 开着期间会前进,直接用+ // base.sha..head 会把 base 侧的他人提交也算进来,造成误报。+ let start = baseSha;+ try {+ start = git(['merge-base', baseSha, headSha]);+ } catch {+ // 没有共同祖先(例如孤立分支)时退回 base 本身。+ }++ return { start, head: headSha, baseRef: base };+}++function reportFailures({ failures, start }) {+ const plural = failures.length === 1 ? 'commit' : 'commits';+ console.error(`DCO check failed: ${failures.length} ${plural} without a valid Signed-off-by.\n`);+ for (const { commit, errors } of failures) {+ console.error(`- ${shortSha(commit.sha)} ${subjectOf(commit)}`);+ for (const error of errors) console.error(` ${error}`);+ // 地址像 bot 时给一句解释,免得有人以为门禁在为难 dependabot:真 bot 由 App 按 GitHub+ // 账号类型豁免,而账号类型离线取不到,所以本地照常报。+ if (looksLikeBotAddress(commit.authorEmail)) {+ console.error(' This looks like a bot address. Bot commits are exempt on the pull request,');+ console.error(' where the DCO App can check the GitHub account type — this check cannot,');+ console.error(' so it reports them rather than trusting a forgeable address.');+ }+ }+ // 用完整 sha:短 sha 在大仓里可能歧义,让复制粘贴的命令直接失败。+ console.error('\nHow to fix, on your pull request branch:');+ console.error(' most recent commit only: git commit --amend -s --no-edit');+ console.error(` several commits: git rebase --signoff ${start}`);+ console.error(' then update the PR: git push --force-with-lease');+ console.error('\nTo stop forgetting, commit with `git commit -s`, or install the hook shipped');+ console.error('with this repository once: `pnpm dco:install-hook` (.githooks/prepare-commit-msg).');+ console.error('The DCO file at the repository root states what the sign-off certifies;');+ console.error('CONTRIBUTING.en.md explains the requirement in full.');+}++function main() {+ const { start, head, baseRef } = resolveRange();+ const stdout = execFileSync('git', ['log', `--format=${LOG_FORMAT}`, `${start}..${head}`], {+ encoding: 'utf8',+ maxBuffer: 64 * 1024 * 1024,+ });+ const commits = parseGitLog(stdout);++ if (commits.length === 0) {+ console.log(`No new commits in ${shortSha(start)}..${shortSha(head)}; nothing to check.`);+ return;+ }++ const { failures, exempted, checked } = validateCommits(commits);+ if (failures.length > 0) {+ reportFailures({ failures, start });+ process.exit(1);+ }++ const exemptNote = exempted.length > 0 ? `, ${exempted.length} exempt (merge commits)` : '';+ console.log(+ `DCO check passed: ${checked} ${checked === 1 ? 'commit' : 'commits'} signed off${exemptNote} ` ++ `— range ${shortSha(start)}..${shortSha(head)} (base ${baseRef}).`+ );++ if (!process.env.GITHUB_EVENT_PATH && !isSignOffHookInstalled()) {+ console.log('Tip: `pnpm dco:install-hook` signs off local commits automatically.');+ }+}++// 仅作为入口执行时运行;被 import 时只导出纯函数,便于单测。+const isDirectRun = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;+if (isDirectRun) {+ try {+ main();+ } catch (error) {+ console.error(String(error?.message ?? error));+ process.exit(1);+ }+}diff --git a/scripts/install-dco-hook.mjs b/scripts/install-dco-hook.mjsnew file mode 100644index 0000000000..76501d83a3--- /dev/null+++ b/scripts/install-dco-hook.mjs@@ -0,0 +1,187 @@+#!/usr/bin/env node+// 本地 DCO 签名 hook 安装器:把仓库里的 .githooks/prepare-commit-msg 复制进当前仓库的+// hooks 目录,让此后每次 `git commit`(含 agent 自动提交)都自动追加 Signed-off-by+// trailer——签的是 commit 的 committer,与原生 `git commit -s` 一致。这样可以避免 PR 被+// DCO check(DCO GitHub App,配置见 .github/dco.yml)拦下后返工;本地提交前的自查是+// scripts/check-dco.mjs,PR 上的权威结论则以 App 的 check 为准。+//+// 用法:+// pnpm dco:install-hook 安装 hook(已存在且被改过时会拒绝,见下)+// node scripts/install-dco-hook.mjs --check 只报告状态,不写文件+// node scripts/install-dco-hook.mjs --force 覆盖一份源自本仓但已被改动的 hook+//+// hook 的正本是 .githooks/prepare-commit-msg(普通 shell 脚本,可直接 review 与+// shellcheck);本脚本只负责复制、判断能否安全覆盖,不生成脚本内容。想跳过安装器的+// 开发者可以直接 `git config core.hooksPath .githooks`——但那会接管整个 hooks 目录,+// 所以默认走复制,与开发者已有的其他 hook 共存。+//+// hook 是纯本地便利设施:不改远端、不改 core.hooksPath,删掉已安装的文件即卸载。++import { execFileSync } from 'node:child_process';+import { chmodSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';+import { dirname, isAbsolute, join, resolve } from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';++const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');++/** 用于识别「这个 hook 是本仓装的」,据此判断可否安全覆盖。与 hook 源文件里的注释一致。 */+export const HOOK_MARKER = 'cindy-dco-signoff-hook';+export const HOOK_NAME = 'prepare-commit-msg';+export const HOOK_SOURCE_PATH = join('.githooks', HOOK_NAME);++/** hook 内容的单一事实源。 */+export function readHookSource() {+ return readFileSync(join(REPO_ROOT, HOOK_SOURCE_PATH), 'utf8');+}++/**+ * 把 `git rev-parse --git-path hooks` 的返回值化成绝对路径。+ *+ * 关键点:它给的相对路径是相对于**执行 git 时的 cwd**,不是仓库根。从子目录调用时返回的+ * 是形如 `../../.git/hooks` 的路径,若拿仓库根去解析就会向上多走几级,把 hook 写进隔壁+ * 或上层仓库的 .git/hooks——所以基准必须是同一个 cwd。单独抽出来是为了能直接断言这点:+ * 走到这个分支需要 git < 2.31,CI 上跑不到。+ */+export function resolveHooksPathFrom(hooksPath, cwd) {+ return isAbsolute(hooksPath) ? hooksPath : resolve(cwd, hooksPath);+}++/**+ * hooks 目录:走 `git rev-parse --git-path hooks`,因此自动尊重已设置的 core.hooksPath;+ * 多 worktree 共享 common dir,装一次全部 worktree 生效。--path-format 要 git 2.31+,+ * 旧版回落到 resolveHooksPathFrom。+ */+export function resolveHooksDir(cwd = process.cwd()) {+ const git = (args) => execFileSync('git', args, { cwd, encoding: 'utf8' }).trim();+ try {+ return git(['rev-parse', '--path-format=absolute', '--git-path', 'hooks']);+ } catch {+ // --path-format 要 git 2.31+,旧版回落到这里。+ return resolveHooksPathFrom(git(['rev-parse', '--git-path', 'hooks']), cwd);+ }+}++/**+ * 返回 `missing`(没有)/ `installed`(内容与源文件逐字一致)/ `modified`(认得出源自本仓,+ * 但内容已经不同)/ `foreign`(完全不是本仓的东西)。+ *+ * 只有 `installed` 与 `missing` 允许无条件写入。刻意不去区分「本仓装的旧版本」与「装完+ * 之后被人改过」——这两者在磁盘上无法可靠分辨:无论是把本仓逻辑合并进自己的 hook,还是+ * 在本仓装好的 hook 后面追加几行,得到的都是「像本仓的、但不等于源文件」。任何试图靠开头+ * 几行或 marker 位置来认领它们的判定,都会在某一种组合上误判并整份覆盖,抹掉开发者的+ * 逻辑。所以这里一律要求显式 --force 才覆盖。+ */+export function classifyHook(existingContent, expectedContent) {+ // 先判 missing 再取源文件:默认参数会在调用时就求值,那样 `classifyHook(null)` 也要读一次+ // 磁盘,还把「没装 hook」这个判断绑到源文件可读上。+ if (existingContent === null) return 'missing';+ const expected = expectedContent ?? readHookSource();+ if (existingContent === expected) return 'installed';+ return existingContent.includes(HOOK_MARKER) ? 'modified' : 'foreign';+}++export function readHook(hookPath) {+ try {+ return readFileSync(hookPath, 'utf8');+ } catch (error) {+ if (error?.code === 'ENOENT') return null;+ throw error;+ }+}++/** git 只执行带 owner 执行位的 hook;缺了它内容再对也不会生效。 */+export function isExecutable(hookPath) {+ try {+ return (statSync(hookPath).mode & 0o100) !== 0;+ } catch {+ return false;+ }+}++/** 供 check-dco.mjs 在本地校验通过后决定是否提示安装。探测失败一律当「已装」处理,不打扰。 */+export function isSignOffHookInstalled(cwd = process.cwd()) {+ try {+ const hookPath = join(resolveHooksDir(cwd), HOOK_NAME);+ return classifyHook(readHook(hookPath)) !== 'missing';+ } catch {+ return true;+ }+}++function main() {+ const checkOnly = process.argv.includes('--check');+ const force = process.argv.includes('--force');+ const hooksDir = resolveHooksDir();+ const hookPath = join(hooksDir, HOOK_NAME);+ const source = readHookSource();+ const state = classifyHook(readHook(hookPath), source);++ // --check 只报告,不写文件、不因状态失败:调用方要的是事实,不是门禁。+ if (checkOnly) {+ const executableNote =+ state === 'installed' && !isExecutable(hookPath) ? ', but NOT executable — Git will ignore it' : '';+ const label = {+ installed: `installed, matching ${HOOK_SOURCE_PATH}${executableNote}`,+ modified: "present but differs from this repo's version (older, or edited locally)",+ missing: 'not installed',+ foreign: 'a different prepare-commit-msg hook is present; not taken over',+ }[state];+ console.log(`DCO sign-off hook: ${label} (${hookPath})`);+ return;+ }++ if (state === 'installed') {+ // 内容一致但丢了可执行位(手动复制、备份恢复、chmod 0644 都会这样)时 git 会直接+ // 忽略这个 hook,提交照样不带签名——而安装器如果只看内容就会报「已是最新」,把人骗过去。+ if (!isExecutable(hookPath)) {+ chmodSync(hookPath, 0o755);+ console.log(`Restored the executable bit on ${hookPath}`);+ console.log('(Git silently ignores hooks that are not executable, so commits were unsigned.)');+ return;+ }+ console.log(`DCO sign-off hook already up to date: ${hookPath}`);+ return;+ }++ if (state === 'foreign') {+ console.error(`A ${HOOK_NAME} hook not managed by this repository already exists:`);+ console.error(` ${hookPath}`);+ console.error(`Leaving it untouched. Either merge the logic from ${HOOK_SOURCE_PATH} into it`);+ console.error('— this installer will then keep its hands off that file, so you own keeping the');+ console.error('merged copy in sync — or use `git config core.hooksPath .githooks` instead.');+ process.exit(1);+ }++ // modified:可能是本仓的旧版本,也可能是装完之后你自己加过东西。磁盘上分辨不出来,+ // 所以不猜,要求显式 --force——猜错的代价是删掉别人的 hook 逻辑。+ if (state === 'modified' && !force) {+ console.error(`${hookPath} came from this repository but no longer matches ${HOOK_SOURCE_PATH}.`);+ console.error('It is either an older version of the hook, or a copy you have edited since.');+ console.error('Not overwriting it. Compare first, then decide:');+ // 用 git diff 而不是 diff(1):git 本来就是本仓的前置依赖,而 diff 在部分 Windows+ // 环境里没有。+ console.error(` git diff --no-index ${hookPath} ${join(REPO_ROOT, HOOK_SOURCE_PATH)}`);+ console.error(' node scripts/install-dco-hook.mjs --force # overwrite with this repo\'s version');+ process.exit(1);+ }++ mkdirSync(hooksDir, { recursive: true });+ writeFileSync(hookPath, source, 'utf8');+ chmodSync(hookPath, 0o755);+ console.log(`${state === 'modified' ? 'Overwrote' : 'Installed'} DCO sign-off hook: ${hookPath}`);+ console.log(+ `Copied from ${HOOK_SOURCE_PATH}. git commit will now append Signed-off-by; ` ++ 'delete the installed file to uninstall.'+ );+}++// 仅作为入口执行时运行;被 import 时只导出纯函数与探测函数。+const isDirectRun = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;+if (isDirectRun) {+ try {+ main();+ } catch (error) {+ console.error(String(error?.message ?? error));+ process.exit(1);+ }+}