dsh-git-push 2.18.0 → 2.18.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -17,7 +17,7 @@ DSH 的 git 提交推送与代码审计插件:提交前自动过审计门禁
17
17
  | 改名 | 给远程仓库改名(dryRun 默认开,列出旧名出现位置) | `git_remote_rename` / `rename` |
18
18
  | 凭据与账号 | 校验 GitHub token 与 SSH 公钥、生成密钥对 | `git_account_check` / `git_gen_ssh_key` |
19
19
  | 身份改写 | 把历史提交身份统一成登录账号 | `git_identity_rewrite` / `identity-rewrite` |
20
- | 发布 | 发布 npm 包(dryRun 默认只体检;含发布前冒烟) | `npm_publish` / — |
20
+ | 发布 | 发布 npm 包(dryRun 默认只体检;凭据由插件托管,无需 npm login) | `npm_publish` / `npm-publish` |
21
21
  | 撤包 | 从 registry 撤版本(默认 dryRun 预检,不可逆) | `npm_unpublish` / `unpublish` |
22
22
  | 豁免标记 | 给文件加/删豁免注释并校验是否真生效 | `exempt` |
23
23
  | I/O 风险扫描 | 扫描读写操作的风险分级 | `io_scan` / `file-io` |
@@ -134,7 +134,7 @@ export const TOOL_REGISTRY = [
134
134
  },
135
135
  {
136
136
  name: 'npm_publish', cli: 'npm-publish',
137
- description: 'npm 发包(后台 job + dryRun):默认 dryRun=true 只做体检与 npm publish --dry-run(不写 registry);真发必须同时 confirm=true 且 dryRun=false。dir=目标包目录(缺省工作区)、tag=发布 tag(默认 latest)、otp=2FA 一次性口令(可选)。前置体检:private:true 拦截、同名版本占用检测、npm pack 文件清单',
137
+ description: 'npm 发包(后台 job + dryRun):默认 dryRun=true 只做体检与 npm publish --dry-run(不写 registry);真发必须同时 confirm=true 且 dryRun=false。dir=目标包目录(缺省工作区)、tag=发布 tag(默认 latest)、otp=2FA 一次性口令(可选)。前置体检:private:true 拦截、同名版本占用检测、npm pack 文件清单。凭据由插件托管(config.json 的 npmToken),无需 npm login、也无需向用户索要 token;缺凭据时工具会明确报错',
138
138
  params: [
139
139
  { flag: 'dir', type: 'string', positional: 0, desc: '目标包目录(缺省工作区)' },
140
140
  { flag: 'dryRun', type: 'boolean', desc: '只预演(默认 true,不写 registry)' },
@@ -20,6 +20,9 @@ metadata:
20
20
 
21
21
  rules:
22
22
  - id: documentation/comment-suspicious-detection
23
+ # 归档/笔记类目录整规则跳过:这些文件**本来就是**在记录会话与决策(会话 ID、用户确认、讨论过程),
24
+ # 按「公开文档只写做了什么」去拦是纯误伤(实测某归档库命中 138 条全集中在此类目录)。
25
+ exclude_paths: ["开发者文档/", "sessions/", "worklogs/", "会话/"]
23
26
  exts: ["js", "mjs", "cjs", "ts", "tsx", "jsx", "html", "htm"]
24
27
  name: "检测 AI 用户交流可疑注释"
25
28
  category: "documentation"
@@ -89,8 +92,13 @@ rules:
89
92
  - pattern: "用户服务"
90
93
  - pattern: "用户模块"
91
94
  - pattern: "用户旅程"
95
+ # 功能描述而非协作残留:工具作用就是「按用户原话」裁断日志(该措辞实测被误拦)
96
+ - pattern: "按用户原话"
92
97
 
93
98
  - id: conv-session-ref
99
+ # 归档/笔记类目录整规则跳过:这些文件**本来就是**在记录会话与决策(会话 ID、用户确认、讨论过程),
100
+ # 按「公开文档只写做了什么」去拦是纯误伤(实测某归档库命中 138 条全集中在此类目录)。
101
+ exclude_paths: ["开发者文档/", "sessions/", "worklogs/", "会话/"]
94
102
  exts: ["js", "mjs", "cjs", "ts", "tsx", "jsx", "html", "htm", "md", "markdown", "txt"]
95
103
  name: "文档引用会话"
96
104
  category: "documentation"
@@ -103,6 +111,9 @@ rules:
103
111
  # 负责(它带 blacklist + AST 精筛,能区分注释与字符串字面量)。
104
112
  # 此前本规则 exts 里含代码扩展名 ⇒ 与前者报同一批位置:实测 archify 上两条各报 7 条、
105
113
  # (file:line) 交集 5 条,同一条注释被两个 blocker 各拦一次。
114
+ # 归档/笔记类目录整规则跳过:这些文件**本来就是**在记录会话与决策(会话 ID、用户确认、讨论过程),
115
+ # 按「公开文档只写做了什么」去拦是纯误伤(实测某归档库命中 138 条全集中在此类目录)。
116
+ exclude_paths: ["开发者文档/", "sessions/", "worklogs/", "会话/"]
106
117
  exts: ["md", "markdown", "txt"]
107
118
  name: "文档引用用户决策"
108
119
  category: "documentation"
@@ -111,6 +122,9 @@ rules:
111
122
  pattern: "用户(同意|许可|确认|约定|指定|已定调|拍板|让我|要求我|跟我说)"
112
123
  fixable: false
113
124
  - id: conv-ai-permit
125
+ # 归档/笔记类目录整规则跳过:这些文件**本来就是**在记录会话与决策(会话 ID、用户确认、讨论过程),
126
+ # 按「公开文档只写做了什么」去拦是纯误伤(实测某归档库命中 138 条全集中在此类目录)。
127
+ exclude_paths: ["开发者文档/", "sessions/", "worklogs/", "会话/"]
114
128
  exts: ["js", "mjs", "cjs", "ts", "tsx", "jsx", "html", "htm", "md", "markdown", "txt"]
115
129
  name: "文档 AI 承诺措辞"
116
130
  category: "documentation"
@@ -119,6 +133,9 @@ rules:
119
133
  pattern: "我(同意|许可|确认|答应|承诺|已按你)"
120
134
  fixable: false
121
135
  - id: conv-negotiate
136
+ # 归档/笔记类目录整规则跳过:这些文件**本来就是**在记录会话与决策(会话 ID、用户确认、讨论过程),
137
+ # 按「公开文档只写做了什么」去拦是纯误伤(实测某归档库命中 138 条全集中在此类目录)。
138
+ exclude_paths: ["开发者文档/", "sessions/", "worklogs/", "会话/"]
122
139
  exts: ["js", "mjs", "cjs", "ts", "tsx", "jsx", "html", "htm", "md", "markdown", "txt"]
123
140
  name: "文档协商措辞"
124
141
  category: "documentation"
@@ -127,6 +144,9 @@ rules:
127
144
  pattern: "我们(商量|讨论|约定|沟通|说好|议定)"
128
145
  fixable: false
129
146
  - id: conv-log
147
+ # 归档/笔记类目录整规则跳过:这些文件**本来就是**在记录会话与决策(会话 ID、用户确认、讨论过程),
148
+ # 按「公开文档只写做了什么」去拦是纯误伤(实测某归档库命中 138 条全集中在此类目录)。
149
+ exclude_paths: ["开发者文档/", "sessions/", "worklogs/", "会话/"]
130
150
  exts: ["js", "mjs", "cjs", "ts", "tsx", "jsx", "html", "htm", "md", "markdown", "txt"]
131
151
  name: "文档对话记录引用"
132
152
  category: "documentation"
@@ -76,6 +76,35 @@ export async function fetchPublishedVersions({ name, registry = DEFAULT_REGISTRY
76
76
  }
77
77
  }
78
78
 
79
+ /**
80
+ * 从 `npm pack --json` 的输出里取出 JSON(**容忍前置的脚本输出**)。
81
+ *
82
+ * 为什么不能「找第一个 [ 或 { 就截取」:`npm pack` 会先跑包里的 `prepack` 脚本,
83
+ * 脚本任何 stdout 都会排在 JSON 之前。实测某仓 prepack 首行是 `[build] lib/client.js …`,
84
+ * 于是 `search(/[[{]/)` 命中那个 `[`,切片后 JSON.parse 抛错 → 被当成「清单为空」,
85
+ * 好包被判死(真实文件 56 个)。
86
+ *
87
+ * 做法:遍历文本里每个 `[` / `{` 位置,从该位置尝试解析,**第一个解析成功且不是标量**的即为结果。
88
+ * 对任意 prepack 输出免疫;候选数设上限,避免超长输出退化成 O(n²)。
89
+ * @param {string} text 原始 stdout
90
+ * @returns {{ok:true, value:any, at:number}|{ok:false}}
91
+ */
92
+ export function parsePackOutput(text = '', { maxCandidates = 200 } = {}) {
93
+ const raw = String(text || '');
94
+ const candidates = [];
95
+ for (let i = 0; i < raw.length && candidates.length < maxCandidates; i++) {
96
+ const ch = raw[i];
97
+ if (ch === '[' || ch === '{') candidates.push(i);
98
+ }
99
+ for (const at of candidates) {
100
+ try {
101
+ const value = JSON.parse(raw.slice(at));
102
+ if (value !== null && typeof value === 'object') return { ok: true, value, at };
103
+ } catch { /* 这个位置不是合法 JSON 起点,继续往后找 */ }
104
+ }
105
+ return { ok: false };
106
+ }
107
+
79
108
  /** 打包预演:`npm pack --dry-run --json`(拿到真实打进包的文件清单与体积)。 */
80
109
  export function packDryRun({ dir, registry = DEFAULT_REGISTRY, workspaceRoot = '', token = '', timeoutMs = PUBLISH_TIMEOUT_MS } = {}) {
81
110
  try {
@@ -85,16 +114,26 @@ export function packDryRun({ dir, registry = DEFAULT_REGISTRY, workspaceRoot = '
85
114
  // cwd 必须显式给:npm pack 以「工作目录」为目标包,继承宿主 cwd 会去错目录
86
115
  // (实测:宿主 cwd 无 package.json ⇒ ENOENT;有 ⇒ 打包整棵树 ⇒ ENOBUFS)
87
116
  const r = runNpm(['pack', '--dry-run', '--json', ...npmArgs({ npmrcFile: rc.file, registry })], { timeoutMs, env: merged, cwd: dir });
88
- if (!r.ok) return { ok: false, error: r.error || 'npm pack --dry-run 失败', stdout: r.stdout };
89
- let info = null;
90
- try {
91
- // npm 可能先打 notice 行再打 JSON ⇒ 从第一个 [ / { 处截取,稳健解析(实测 --json 会夹 notice)
92
- const text = String(r.stdout || '');
93
- const at = text.search(/[[{]/);
94
- const j = JSON.parse(at >= 0 ? text.slice(at) : text);
95
- info = Array.isArray(j) ? j[0] : j;
96
- } catch { /* 非 JSON 输出:保留 stdout 供排查 */ }
97
- return { ok: true, files: (info && Array.isArray(info.files)) ? info.files.map((f) => f.path) : [], size: (info && info.size) || 0, filename: (info && info.filename) || '' };
117
+ if (!r.ok) return { ok: false, error: r.error || 'npm pack --dry-run 失败', stdout: r.stdout, stderr: r.stderr };
118
+ const text = String(r.stdout || '');
119
+ const parsed = parsePackOutput(text);
120
+ if (!parsed.ok) {
121
+ // 解析失败 ≠ 清单为空:把 stdout/stderr 尾部一起带上,下次一眼看出是被脚本输出污染
122
+ return {
123
+ ok: false,
124
+ blocked: 'pack-parse-failed',
125
+ error: 'npm pack 输出无法解析为 JSON(可能被 prepack 等脚本的 stdout 污染)',
126
+ packStdoutTail: text.slice(-800),
127
+ packStderrTail: String(r.stderr || '').slice(-800),
128
+ };
129
+ }
130
+ const info = Array.isArray(parsed.value) ? parsed.value[0] : parsed.value;
131
+ return {
132
+ ok: true,
133
+ files: (info && Array.isArray(info.files)) ? info.files.map((f) => f.path) : [],
134
+ size: (info && info.size) || 0,
135
+ filename: (info && info.filename) || '',
136
+ };
98
137
  } catch (e) {
99
138
  return { ok: false, error: String((e && e.message) || e) };
100
139
  }
@@ -152,7 +191,18 @@ export async function publishPackage({
152
191
  }
153
192
  // 体检③:打包预演(真实文件清单)
154
193
  const pack = packDryRun({ dir: info.dir, registry: reg, workspaceRoot, token, timeoutMs });
155
- if (!pack.ok) return { ok: false, blocked: 'pack-failed', name: info.name, version: info.version, error: pack.error, packStdout: String(pack.stdout || '').slice(-2000) };
194
+ if (!pack.ok) {
195
+ // 区分「pack 命令失败」与「输出解析失败」:后者通常是 prepack 之类脚本的 stdout 污染,
196
+ // 包本身没问题;把两类尾部输出都带上,便于一眼定位(历史实现只说「清单为空」,误导排查方向)。
197
+ return {
198
+ ok: false,
199
+ blocked: pack.blocked || 'pack-failed',
200
+ name: info.name, version: info.version,
201
+ error: pack.error,
202
+ packStdout: String(pack.stdout || pack.packStdoutTail || '').slice(-2000),
203
+ packStderr: String(pack.stderr || pack.packStderrTail || '').slice(-2000),
204
+ };
205
+ }
156
206
  if (!pack.files.length) return { ok: false, blocked: 'empty-pack', name: info.name, version: info.version, error: 'npm pack 清单为空(检查 files 字段)' };
157
207
 
158
208
  // 体检④:**发布前冒烟**——真装一次并加载公开面。失败直接拦,不写 registry。
package/lib/npm/smoke.js CHANGED
@@ -16,6 +16,10 @@
16
16
  * 不做的事:不跑单测、不启宿主。它只回答「包本身能不能被正常消费」;
17
17
  * 「宿主能不能加载插件」属于隔离实例验证(test_env)的范畴,成本高得多,不做进默认门禁。
18
18
  */
19
+ import { extname } from "node:path";
20
+
21
+ /** 能被 Node 直接当模块加载的扩展名(空扩展名按无后缀 ESM/CJS 处理)。 */
22
+ const MODULE_EXTS = new Set(['', '.js', '.mjs', '.cjs', '.jsx', '.ts', '.tsx']);
19
23
  import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
20
24
  import { join } from 'node:path';
21
25
  import { tmpdir } from 'node:os';
@@ -31,6 +35,68 @@ const SMOKE_TIMEOUT_MS = 240000;
31
35
  * 没有 exports 时退化为包名根入口。
32
36
  */
33
37
  /** 浏览器端入口(如 `./client`):只能在宿主前端环境加载,Node 里 import 必然失败,冒烟时跳过。 */
38
+ /**
39
+ * 从 package.json 里挑出「本次冒烟该 import 哪些公开面」。
40
+ *
41
+ * 【判据】
42
+ * · `exports` 的点出口(`"."`)= 主入口,**必须测**;没有 main/exports 的纯 CLI 包没有库入口,跳过
43
+ * · 子出口里只挑能当模块加载的目标:`.yml`/`.json`/`.css`/图片等资源虽然也登记在 exports,
44
+ * 但对它们 import 会得到 ERR_UNKNOWN_FILE_EXTENSION —— 那是误判,不是包的问题
45
+ * · 浏览器专属出口(前端 bundle)不在这里加载,单独归到 browserEntries 只是为了让报告如实列出
46
+ *
47
+ * @param {object} pkg package.json 内容
48
+ * @returns {{nodeEntries: string[], browserEntries: string[]}} 可直接交给 `import(spec)` 的规格名
49
+ */
50
+ export function selectImportSpecs(pkg) {
51
+ const name = String(pkg?.name || '');
52
+ const nodeEntries = [];
53
+ const browserEntries = [];
54
+ if (!name) return { nodeEntries, browserEntries };
55
+ const hasLibraryEntry = Boolean(pkg?.main) || Boolean(pkg?.exports);
56
+ const exportMap = (pkg?.exports && typeof pkg.exports === 'object') ? pkg.exports : { '.': null };
57
+ for (const key of Object.keys(exportMap)) {
58
+ // 清单不是模块;对它 import 没有意义
59
+ if (key === './package.json') continue;
60
+ const spec = key === '.' ? name : `${name}/${key.slice(2)}`;
61
+ if (key !== '.' && isBrowserEntry(key)) { browserEntries.push(spec); continue; }
62
+ if (key === '.' && !hasLibraryEntry) continue;
63
+ const target = exportMap[key] === undefined || exportMap[key] === null
64
+ ? (key === '.' ? pkg.main : key)
65
+ : exportMap[key];
66
+ if (!isModuleTarget(target)) continue;
67
+ nodeEntries.push(spec);
68
+ }
69
+ return { nodeEntries, browserEntries };
70
+ }
71
+
72
+ /**
73
+ * 判断一个 exports 目标是否可能是「可被 Node 加载的模块」。
74
+ *
75
+ * 【为什么需要】exports 不只为 JS 服务:资源文件(.yml/.json/.css/图片)也常登记在
76
+ * exports 里供消费方按子路径取用。冒烟若对这些子路径执行 import,会得到
77
+ * ERR_UNKNOWN_FILE_EXTENSION —— 那是包被误判,不是包有问题。
78
+ *
79
+ * @param {unknown} value exports 的值(字符串、条件对象,或 null)
80
+ * @returns {boolean} 是否值得尝试 import
81
+ */
82
+ function isModuleTarget(value) {
83
+ // 没有显式目标(如 {'.': null}):按包名 import 主入口,交给 Node 判定
84
+ if (value === undefined || value === null) return true;
85
+ if (typeof value === 'string') {
86
+ if (value.endsWith('/')) return true; // 目录映射
87
+ const ext = extname(value).toLowerCase();
88
+ return MODULE_EXTS.has(ext);
89
+ }
90
+ if (typeof value === 'object') {
91
+ // 条件导出:取第一个存在的条件继续判断(import 优先,其次 default/require/node)
92
+ for (const condition of ['import', 'default', 'require', 'node']) {
93
+ if (value[condition] !== undefined) return isModuleTarget(value[condition]);
94
+ }
95
+ return false;
96
+ }
97
+ return false;
98
+ }
99
+
34
100
  export function isBrowserEntry(key) {
35
101
  // `./client`、`./client/index`、`./lib/client.js` 都算浏览器端入口
36
102
  return /(^|\/)client(\/|\.js)?(\/|$)|browser/i.test(String(key).replace(/^\.\//, ''));
@@ -128,14 +194,7 @@ export async function smokeTestPackage({ dir = '', workspaceRoot = '', registry
128
194
  const probe = join(consumer, 'probe.mjs');
129
195
  const deps = Object.keys(pkg.dependencies || {});
130
196
  // nodeEntries = 可在 Node 里加载的公开面;browserEntries = 仅前端可加载(跳过但如实列出)
131
- const nodeEntries = [];
132
- const browserEntries = [];
133
- for (const key of Object.keys(pkg.exports && typeof pkg.exports === 'object' ? pkg.exports : { '.': null })) {
134
- const spec = key === '.' ? name : `${name}/${key.slice(2)}`;
135
- if (key !== '.' && isBrowserEntry(key)) browserEntries.push(spec);
136
- else if (!key.startsWith('./') || key === './package.json') continue;
137
- else nodeEntries.push(spec);
138
- }
197
+ const { nodeEntries, browserEntries } = selectImportSpecs(pkg);
139
198
  writeFileSync(probe, [
140
199
  'import { createRequire } from "node:module";',
141
200
  'import { existsSync } from "node:fs";',
@@ -96,8 +96,10 @@ export async function unpublishPackage({
96
96
  name = '', version = '', wholePackage = false,
97
97
  registry = DEFAULT_REGISTRY, workspaceRoot = '',
98
98
  dryRun = true, confirm = false, timeoutMs = 120000,
99
+ // 可注入(测试用):npm 执行器、registry 查询、凭据
100
+ runNpmImpl = runNpm, fetchImpl = globalThis.fetch, token = '',
99
101
  } = {}) {
100
- const pre = await preflightUnpublish({ name, version, wholePackage, registry });
102
+ const pre = await preflightUnpublish({ name, version, wholePackage, registry, fetchImpl });
101
103
  if (!pre.ok) return { ok: false, blocked: 'preflight-failed', error: pre.error };
102
104
  if (dryRun) {
103
105
  return {
@@ -109,17 +111,39 @@ export async function unpublishPackage({
109
111
  if (confirm !== true) {
110
112
  return { ok: false, blocked: 'need-confirm', ...pre, error: '真实撤包不可逆:需同时传 dryRun:false 与 confirm:true' };
111
113
  }
112
- const token = (() => { try { return readNpmToken({ workspaceRoot }); } catch { return ''; } })();
113
- const rc = writeNpmrc({ workspaceRoot, registry, token });
114
+ const tokenValue = token || (() => { try { return readNpmToken({ workspaceRoot }); } catch { return ''; } })();
115
+ // 没有凭据必须当场拒绝:实测 npm 在**无认证**时会对 unpublish 发 PUT 拿到 404,
116
+ // 但**退出码仍是 0** 并打印「- pkg@ver」,看起来像撤成功(历史假成功就是这么来的)。
117
+ if (!tokenValue) {
118
+ return { ...pre, ok: false, blocked: 'no-token', error: '插件配置里没有可用的 npmToken(或未生效),无法撤包;请先配置 npm 凭据' };
119
+ }
120
+ const rc = writeNpmrc({ workspaceRoot, registry, token: tokenValue });
114
121
  if (!rc.ok) return { ok: false, error: rc.error || 'npmrc 写入失败' };
115
122
  const args = ['unpublish', wholePackage ? name : `${name}@${pre.version}`, ...npmArgs({ npmrcFile: rc.file, registry })];
116
123
  if (wholePackage) args.push('--force');
117
- const r = runNpm(args, { timeoutMs, env: { NO_UPDATE_NOTIFIER: '1' } });
124
+ const r = runNpmImpl(args, { timeoutMs, env: { NO_UPDATE_NOTIFIER: '1' } });
125
+ const npmText = String(r.error || r.stderr || r.stdout || '');
118
126
  if (!r.ok) {
127
+ // granular token 的 2FA 限制是最常见的硬阻塞,单独给出可执行指引
128
+ const twoFactorBlocked = /granular access token/i.test(npmText) || /bypass two-factor/i.test(npmText);
129
+ return {
130
+ ...pre, ok: false,
131
+ error: `npm unpublish 失败:${npmText.slice(0, 400)}`,
132
+ ...(twoFactorBlocked
133
+ ? { hint: '该 token 是「绕过 2FA 的 granular token」,npm 禁止它执行撤包。改用:① npm 网站手动撤(需 2FA);② 换 classic token 并带 --otp;③ 本机 npm login 后执行' }
134
+ : { hint: '若提示 72h/依赖者/下载量限制,说明不满足官方撤包条件——改用 npm deprecate 让使用者看到警告而不破坏构建' }),
135
+ };
136
+ }
137
+ // **关键**:npm 的 unpublish 在若干失败情形下仍会 exit 0 并打印「- pkg@ver」。
138
+ // 唯一可信的判据是回读 registry:版本真的没了才算成功。
139
+ const after = await preflightUnpublish({ name, version: pre.version, wholePackage, registry, fetchImpl });
140
+ const stillThere = after.ok && !wholePackage && Array.isArray(after.versions) && after.versions.includes(pre.version);
141
+ if (stillThere) {
119
142
  return {
120
- ok: false, ...pre,
121
- error: `npm unpublish 失败:${String(r.error || r.stderr || r.stdout || '').slice(0, 400)}`,
122
- hint: '若提示 72h/依赖者/下载量限制,说明不满足官方撤包条件——改用 npm deprecate 让使用者看到警告而不破坏构建',
143
+ ...pre, ok: false, verified: false,
144
+ error: `npm 退出码为 0,但 registry 里 ${name}@${pre.version} 仍在——撤包未生效`,
145
+ npmOutput: npmText.slice(-600),
146
+ hint: '常见原因:token 无权限/需 2FA/被 granular token 策略禁止。请改用 npm 网站或 classic token + --otp',
123
147
  };
124
148
  }
125
149
  return {
@@ -24,6 +24,9 @@ registerCompiler(
24
24
  message: r.description || r.name || '注释措辞审查',
25
25
  dimensions: pickDimensions(r, [DIMENSIONS.文档]),
26
26
  extra: {
27
+ // 路径级排除必须放进 extra:ruleOut 只透传固定顶层字段 + extra,
28
+ // 顶层塞 excludePaths 会被静默丢弃(实测:声明了却仍照报归档目录)。
29
+ excludePaths: Array.isArray(r.exclude_paths) ? r.exclude_paths.map(String) : undefined,
27
30
  blacklist: Array.isArray(r.blacklist) ? r.blacklist.map((b) => ({ pattern: b.pattern, ...(b.weight !== undefined ? { weight: Number(b.weight) || 0 } : {}) })) : [],
28
31
  whitelist: Array.isArray(r.whitelist) ? r.whitelist.map((w) => ({ pattern: w.pattern, ...(w.penalty !== undefined ? { penalty: Number(w.penalty) || 0 } : {}) })) : [],
29
32
  additionalFeatures: Array.isArray(r.additional_features) ? r.additional_features.map((a) => ({ pattern: a.pattern, weight: Number(a.weight) || 0 })) : [],
package/lib/self/index.js CHANGED
@@ -9,7 +9,7 @@
9
9
  */
10
10
 
11
11
 
12
- export const VERSION = '2.18.0'; // 2.18.0:新增 npm_unpublish(撤包)。撤包不可逆——同一 `包@版本` 撤掉后永久不能再发,撤掉 latest 会让 `npm i <包>` 悬空——所以默认 dryRun:预检版本是否存在、是否被 dist-tag 指向、发布距今是否在官方 72h 窗口内、是否该包唯一版本(撤光会冷却 24h),并说明撤掉后的后果;真撤必须 dryRun:false + confirm:true 双确认。超出 72h 只有「无依赖者 + 周下载<300 + 单一维护者」三条件同时满足才允许,否则只能 deprecate——预检会把这条政策原文写进 policyHint。历史:2.17.0 推送后等 CI。
12
+ export const VERSION = '2.18.2'; // 2.18.2:审计扩展新增两条 DSH 插件 blocker 规则(访问 ctx 服务但未 inject / 入口 default 导出覆盖命名导出)。历史 —— 2.18.1:修发布前冒烟的两个选项目缺陷——① `exports` 里的非 JS 资源(.yml/.json 等)曾被当模块 import,对正常包抛 ERR_UNKNOWN_FILE_EXTENSION,把好包拦在发布前;② 点出口 `"."` 曾被跳过,导致主入口从来没被测过、门禁形同虚设。现在按目标扩展名与条件导出挑出「真正能被 Node 加载」的入口,并给两侧行为补了单测。历史:2.18.0 新增 npm_unpublish(撤包,默认 dryRun)。
13
13
  // 实测后果:该目录有 package.json ⇒ npm 去打包整棵 DSH 树、输出 2.1MB > spawnSync 默认 maxBuffer 1MB ⇒ ENOBUFS(npm_publish 的体检与真发全部失败);
14
14
  // 该目录没有 package.json 时报 ENOENT。现 publish 的两个调用点显式传 cwd=目标包目录,并给 runNpm 加 16MB maxBuffer。
15
15
  // 2.8.3:文案修正——「零改动 / 无新提交」明确为**正常成功路径**(注入用法、工具描述、README、skill 同批改),并修 job 输出自相矛盾(cleanSkipCommit 路径补 committed:false,不再显示「已提交,未推送」)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-git-push",
3
- "version": "2.18.0",
3
+ "version": "2.18.2",
4
4
  "description": "DSH git 自动提交推送插件——统一函数入口架构(规则/审计/git/自身/侧边栏/评分/豁免/上下文/HTTP/测试十大总入口)",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -0,0 +1,209 @@
1
+ /**
2
+ * DSH 插件审计扩展:inject 声明与导出面。
3
+ *
4
+ * 与 dsh-useful-tools 的 verify_plugin(lib/core/verify-plugin/dsh-rules.mjs)**同源规则、独立实现**:
5
+ * 两个插件不互相 import,各自维护判定逻辑;规则增删改要两边同步(见 useful-tools 的 CONTRACT C-114)。
6
+ *
7
+ * 为什么用扩展脚本而不是 YAML 正则:这两条都需要**跨行读 inject 声明**(`export const inject = [...]`),
8
+ * 纯逐行正则做不到 —— 只能看「有没有 ctx.xxx」,无法判断 xxx 是否已经声明。
9
+ *
10
+ * 两条规则:
11
+ * dsh/ctx-service-not-injected (blocker)访问 ctx.<服务> 但 inject 没声明该服务
12
+ * dsh/plugin-default-export-hides-inject(blocker)入口同时有 default 与命名 inject/apply
13
+ */
14
+ import { readdirSync, readFileSync, statSync } from 'node:fs';
15
+ import { extname, join, relative } from 'node:path';
16
+
17
+ /** 参与扫描的扩展名。 */
18
+ const JS_EXTS = new Set(['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts']);
19
+ /** 不扫描的目录(第三方依赖、产物、测试夹具、回收站)。 */
20
+ const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', '.trash', 'test', 'tests', 'audit-history']);
21
+ /** 扫描上限:单仓库最多看这么多文件,避免大仓拖慢审计。 */
22
+ const MAX_FILES = 400;
23
+ /** 单文件大小上限。 */
24
+ const MAX_FILE_BYTES = 512 * 1024;
25
+
26
+ /**
27
+ * cordis Context 自身的内建成员(不是"服务"):访问它们不需要 inject 声明。
28
+ * 只收确定不会误伤的:事件 API、effect、logger、依赖注入原语、fiber/scope 等。
29
+ */
30
+ const CORDIS_BUILTIN_MEMBERS = new Set([
31
+ 'on', 'once', 'off', 'emit', 'effect', 'logger', 'inject', 'plugin', 'get', 'set', 'provide',
32
+ 'accessor', 'root', 'scope', 'fiber', 'reflect', 'registry', 'runtime', 'dispose', 'extend',
33
+ 'isolate', 'waterfall', 'bail', 'parallel', 'serial', 'ctx', 'setTimeout', 'clearTimeout',
34
+ 'setInterval', 'clearInterval', 'name', 'config', 'options', 'state',
35
+ ]);
36
+
37
+ /** 已知的「错误字段名」:不是 cordis 服务,由 YAML 规则 dsh/ctx-undeclared-property-read 负责。 */
38
+ const KNOWN_BAD_CTX_FIELDS = new Set([
39
+ 'sessionId', 'sessionID', 'conversationId', 'agentId', 'workspaceRoot', 'dshHome', 'DSH_HOME',
40
+ ]);
41
+
42
+ /**
43
+ * 真实存在、通过 ctx 暴露的 cordis 服务(保守清单)。
44
+ * 为什么需要:`ctx` 是极常见的参数名——HTTP 请求、工具执行上下文、遍历累加器都可能叫 ctx,
45
+ * 只靠 `ctx.xxx` 的写法无法区分语义(实测:真实插件被误报 20 条 / 仓库)。只报清单里的服务名。
46
+ */
47
+ const KNOWN_CORDIS_SERVICES = new Set([
48
+ 'tools', 'fs', 'sessions', 'llm', 'credentials', 'webServer', 'slots', 'locale',
49
+ 'storageDomain', 'workspaceRegistry', 'commands', 'sandbox', 'models', 'settings',
50
+ 'jobs', 'subagents', 'skills', 'schedule', 'terminals', 'systemPrompt', 'spillStore',
51
+ 'pluginManager', 'pluginInventory', 'approval', 'sessionQuery', 'agentLoop',
52
+ ]);
53
+
54
+ /** 该文件是不是插件入口:只有入口手里那个 ctx 才确定是 cordis Context。 */
55
+ function isPluginEntry(text) {
56
+ return /export\s+(async\s+)?function\s+apply\b/.test(text)
57
+ || /export\s+const\s+inject\b/.test(text);
58
+ }
59
+
60
+ /** 递归列待扫描的 JS 文件(相对仓库根的路径)。 */
61
+ function collectFiles(repo) {
62
+ const out = [];
63
+ const walk = (dir) => {
64
+ if (out.length >= MAX_FILES) return;
65
+ let entries;
66
+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
67
+ for (const entry of entries) {
68
+ if (out.length >= MAX_FILES) return;
69
+ if (SKIP_DIRS.has(entry.name)) continue;
70
+ const full = join(dir, entry.name);
71
+ if (entry.isDirectory()) { walk(full); continue; }
72
+ if (!JS_EXTS.has(extname(entry.name))) continue;
73
+ try { if (statSync(full).size > MAX_FILE_BYTES) continue; } catch { continue; }
74
+ out.push({ abs: full, rel: relative(repo, full).replace(/\\/g, '/') });
75
+ }
76
+ };
77
+ walk(repo);
78
+ return out;
79
+ }
80
+
81
+ /**
82
+ * 取 `export const inject = [...]` 声明的服务名。
83
+ * 用括号配对而非单行正则:兼容多行数组与 `[{ required: [...], optional: [...] }]` 形态。
84
+ */
85
+ function declaredInjectNames(text) {
86
+ const names = new Set();
87
+ const anchor = /export\s+const\s+inject\s*=\s*/.exec(text);
88
+ if (!anchor) return names;
89
+ const start = anchor.index + anchor[0].length;
90
+ let depth = 0;
91
+ let end = -1;
92
+ for (let i = start; i < text.length; i += 1) {
93
+ const ch = text[i];
94
+ if (ch === '[' || ch === '{') depth += 1;
95
+ else if (ch === ']' || ch === '}') {
96
+ depth -= 1;
97
+ if (depth === 0) { end = i; break; }
98
+ } else if (ch === ';' && depth === 0) { end = i; break; }
99
+ }
100
+ const block = text.slice(start, end === -1 ? Math.min(start + 600, text.length) : end + 1);
101
+ for (const quoted of block.matchAll(/['"`]([^'"`]+)['"`]/g)) names.add(quoted[1]);
102
+ return names;
103
+ }
104
+
105
+ /** 去掉行内注释,保留字符串内容(字符串里的 `//` 不能当注释起点)。 */
106
+ function stripTrailingComment(line) {
107
+ let out = '';
108
+ let quote = '';
109
+ for (let i = 0; i < line.length; i += 1) {
110
+ const ch = line[i];
111
+ if (quote) {
112
+ out += ch;
113
+ if (ch === '\\') { out += line[i + 1] || ''; i += 1; continue; }
114
+ if (ch === quote) quote = '';
115
+ continue;
116
+ }
117
+ if (ch === "'" || ch === '"' || ch === '`') { quote = ch; out += ch; continue; }
118
+ if (ch === '/' && line[i + 1] === '/') break;
119
+ if (ch === '/' && line[i + 1] === '*') {
120
+ const close = line.indexOf('*/', i + 2);
121
+ if (close < 0) break;
122
+ i = close + 1;
123
+ out += ' ';
124
+ continue;
125
+ }
126
+ out += ch;
127
+ }
128
+ return out;
129
+ }
130
+
131
+ /** 规则 A:访问 ctx.<服务> 但没在 inject 里声明。返回命中行号数组。 */
132
+ function ctxServiceNotInjectedHits(text) {
133
+ // 只在插件入口检查:非入口文件里的 ctx 多半是别的语义(HTTP 请求 / 工具上下文 / 累加器),
134
+ // 逐一判断不了,宁可漏报也不误报。
135
+ if (!isPluginEntry(text)) return [];
136
+ const declared = declaredInjectNames(text);
137
+ const hits = [];
138
+ const lines = text.split('\n');
139
+ for (let i = 0; i < lines.length; i += 1) {
140
+ const raw = lines[i];
141
+ if (/^\s*(\/\/|\*|\/\*)/.test(raw)) continue;
142
+ const code = stripTrailingComment(raw);
143
+ if (!code.includes('ctx')) continue;
144
+ for (const match of code.matchAll(/\bctx\s*\??\.\s*([A-Za-z_$][\w$]*)/g)) {
145
+ const member = match[1];
146
+ if (CORDIS_BUILTIN_MEMBERS.has(member)) continue;
147
+ if (KNOWN_BAD_CTX_FIELDS.has(member)) continue;
148
+ if (!KNOWN_CORDIS_SERVICES.has(member)) continue;
149
+ if (declared.has(member)) continue;
150
+ hits.push({ line: i + 1, text: raw.trim().slice(0, 200) });
151
+ break;
152
+ }
153
+ }
154
+ return hits;
155
+ }
156
+
157
+ /** 规则 B:同时有 export default 与命名 inject/apply(DSH 取 default 后命名导出失效)。 */
158
+ function defaultExportConflictLine(text) {
159
+ const hasDefault = /(^|\n)\s*export\s+default\b/.test(text);
160
+ const hasNamedInject = /(^|\n)\s*export\s+(const|let|var)\s+inject\b/.test(text);
161
+ const hasNamedApply = /(^|\n)\s*export\s+(async\s+)?function\s+apply\b/.test(text);
162
+ if (!hasDefault || !(hasNamedInject || hasNamedApply)) return 0;
163
+ const lines = text.split('\n');
164
+ for (let i = 0; i < lines.length; i += 1) {
165
+ if (/^\s*(\/\/|\*|\/\*)/.test(lines[i])) continue;
166
+ if (/(^|\n)\s*export\s+default\b/.test(lines[i])) return i + 1;
167
+ }
168
+ return 1;
169
+ }
170
+
171
+ export const auditExt = {
172
+ name: 'dsh-inject-declarations',
173
+ match: (repo) => Boolean(repo && repo !== '.'),
174
+ run: async (repo) => {
175
+ const findings = [];
176
+ for (const file of collectFiles(repo)) {
177
+ let text = '';
178
+ try { text = readFileSync(file.abs, 'utf8'); } catch { continue; }
179
+
180
+ for (const hit of ctxServiceNotInjectedHits(text)) {
181
+ findings.push({
182
+ file: file.rel,
183
+ line: hit.line,
184
+ rule: 'dsh/ctx-service-not-injected',
185
+ severity: 'blocker',
186
+ scoreImpact: 0,
187
+ message: '访问 ctx 上未 inject 的服务:cordis 会直接抛 cannot get property … without inject,插件整条不激活;'
188
+ + '需模块级 export const inject = [\'服务名\'],或改用 ctx.get(\'服务名\')',
189
+ dimensions: ['健壮性'],
190
+ });
191
+ }
192
+
193
+ const conflictLine = defaultExportConflictLine(text);
194
+ if (conflictLine) {
195
+ findings.push({
196
+ file: file.rel,
197
+ line: conflictLine,
198
+ rule: 'dsh/plugin-default-export-hides-inject',
199
+ severity: 'blocker',
200
+ scoreImpact: 0,
201
+ message: '入口同时存在 export default 与命名 inject/apply:DSH 装载取 module.default || module,'
202
+ + '有 default 时命名 inject/name 全部失效 ⇒ 访问服务直接抛错、插件不激活;入口只保留命名导出',
203
+ dimensions: ['健壮性'],
204
+ });
205
+ }
206
+ }
207
+ return findings;
208
+ },
209
+ };