dsh-git-push 2.18.2 → 2.20.17
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/.gitignore +4 -0
- package/README.md +12 -5
- package/cli-audit.mjs +141 -0
- package/cli-tool.mjs +86 -0
- package/cli.mjs +116 -324
- package/lib/ARCHITECTURE.md +3 -0
- package/lib/app/audit-api.js +1 -1
- package/lib/app/command-registry.js +16 -3
- package/lib/app/constants.js +9 -0
- package/lib/app/handlers/clone.js +12 -3
- package/lib/app/handlers/http-constants.js +11 -2
- package/lib/app/handlers/npm.js +4 -2
- package/lib/app/handlers/repos.js +10 -1
- package/lib/app/handlers/settings.js +9 -1
- package/lib/app/http-handlers.js +24 -3
- package/lib/app/inject-text.js +1 -0
- package/lib/app/schema-audit.js +42 -0
- package/lib/app/schema.js +19 -19
- package/lib/app/scope-check.js +69 -0
- package/lib/app/settings-bridge.js +51 -0
- package/lib/app/tool-call.js +56 -7
- package/lib/ast/credential.js +130 -14
- package/lib/ast/dataflow.js +127 -10
- package/lib/ast/index.js +2 -0
- package/lib/ast/naming.js +9 -1
- package/lib/ast/scope-collisions.js +228 -0
- package/lib/ast/treesitter.js +142 -1
- package/lib/audit/history.js +1 -1
- package/lib/audit/orchestrate.js +93 -6
- package/lib/audit/scope-policy.js +110 -0
- package/lib/audit-rules/audit-rules-dsh.yml +16 -1
- package/lib/audit-rules/audit-rules-nodejs.yml +21 -6
- package/lib/audit-rules/audit-rules-paths.yml +7 -1
- package/lib/audit-ui-sdk/contract.js +117 -0
- package/lib/audit-ui-sdk/index.js +17 -0
- package/lib/checks/common.js +4 -4
- package/lib/checks/dispatch.js +5 -0
- package/lib/checks/index.js +2 -0
- package/lib/checks/regex.js +8 -3
- package/lib/checks/scope-collision.js +68 -0
- package/lib/cli/commands-audit.mjs +13 -18
- package/lib/cli/commands-tool.mjs +93 -0
- package/lib/cli/commands-vcs.mjs +2 -1
- package/lib/cli/shared.mjs +448 -0
- package/lib/client-parts/{account.js → git/account.js} +1 -1
- package/lib/client-parts/{actions.js → git/actions.js} +26 -11
- package/lib/client-parts/{apply.js → git/apply.js} +1 -1
- package/lib/client-parts/{browser.js → git/browser.js} +1 -1
- package/lib/client-parts/{const.js → git/const.js} +6 -1
- package/lib/client-parts/{controller.js → git/controller.js} +23 -11
- package/lib/client-parts/{icons.js → git/icons.js} +1 -1
- package/lib/client-parts/{loader.js → git/loader.js} +1 -1
- package/lib/client-parts/{npm.js → git/npm.js} +1 -1
- package/lib/client-parts/{page.js → git/page.js} +11 -21
- package/lib/client-parts/{repo.js → git/repo.js} +1 -1
- package/lib/client-parts/{settings.js → git/settings.js} +1 -1
- package/lib/client-parts/{utils.js → git/utils.js} +1 -1
- package/lib/client.js +75 -354
- package/lib/commit-push/pre-commit-engine.js +388 -0
- package/lib/commit-push.js +44 -17
- package/lib/exempt/index.js +5 -2
- package/lib/git/ignore.js +6 -4
- package/lib/git/init-compat.js +83 -4
- package/lib/git/push.js +25 -2
- package/lib/git/sensitive.js +30 -1
- package/lib/git/transport.js +31 -10
- package/lib/http/index.js +82 -10
- package/lib/lint-adapter/detect.js +161 -0
- package/lib/lint-adapter/index.js +50 -0
- package/lib/lint-adapter/runner.js +133 -0
- package/lib/npm/npmrc.js +22 -5
- package/lib/rule/compilers/structure.js +24 -0
- package/lib/score/index.js +36 -4
- package/lib/self/index.js +1 -1
- package/package.json +25 -2
- package/scripts/audit-gate.mjs +235 -0
- package/scripts/build-client.mjs +15 -8
- package/scripts/bump-version.mjs +20 -5
- package/scripts/check-js-scope.mjs +87 -0
- package/scripts/check.mjs +51 -4
- package/scripts/scan-file-io.mjs +5 -1
- package/scripts/scan-version.mjs +10 -7
- package/skills/dev/dsh-git-push.md +70 -2
- package/skills/guide/guide-audit.md +11 -11
- package/skills/guide/guide-cli-scripts.md +3 -3
- package/skills/guide/guide-commit-push.md +2 -2
- package/skills/guide/guide-inject-ui.md +0 -16
- package/assets/start.sh +0 -396
- package/scripts/scan-hardcoded-paths.mjs +0 -125
- /package/lib/client-parts/{audit.js → audit/audit.js} +0 -0
package/lib/app/handlers/npm.js
CHANGED
|
@@ -131,7 +131,9 @@ export function handleNpmInstall(ctx) {
|
|
|
131
131
|
dest: String(body?.dest || ''),
|
|
132
132
|
global,
|
|
133
133
|
ignoreScripts: body?.ignoreScripts !== false, // 默认 true(安全默认)
|
|
134
|
-
|
|
134
|
+
// 未配置时必须传 undefined,不能传空串:`registry=''` 会被当成显式值一路写进 npmrc
|
|
135
|
+
// (`registry=` 空行),npm 解析空 URL 直接 ERR_INVALID_URL 崩掉。
|
|
136
|
+
registry: cfg?.npmRegistry || undefined,
|
|
135
137
|
workspaceRoot: env?.workspaceRoot || '',
|
|
136
138
|
};
|
|
137
139
|
// async=true:走异步安装 + /npm-install-progress 轮询(UI 进度框用;对应 GitHub 克隆的进度模型)
|
|
@@ -158,7 +160,7 @@ export async function handleNpmPublish(ctx) {
|
|
|
158
160
|
}
|
|
159
161
|
const r = await publishPackage({
|
|
160
162
|
dir: String(body?.dir || env?.workspaceRoot || ''),
|
|
161
|
-
registry: cfg?.npmRegistry ||
|
|
163
|
+
registry: cfg?.npmRegistry || undefined,
|
|
162
164
|
workspaceRoot: env?.workspaceRoot || '',
|
|
163
165
|
dryRun,
|
|
164
166
|
tag: body?.tag || 'latest',
|
|
@@ -92,7 +92,16 @@ async function applyLiveRemote(list, deadline) {
|
|
|
92
92
|
}
|
|
93
93
|
const t0 = Date.now();
|
|
94
94
|
let live = { ok: false, sha: '' };
|
|
95
|
-
|
|
95
|
+
// 把**剩余预算**传进单次探测:它内部会摊到每步 git 调用上。
|
|
96
|
+
// 只靠上面的 isProbeOverBudget 不够——那只在「调用前」检查,
|
|
97
|
+
// 单次探测里若有一步不带超时的 git 调用,整个请求仍会穿透整表预算
|
|
98
|
+
// (实测:DSH 启动后首开「本地」页 → 前端 30s fetch 超时 → signal timed out)。
|
|
99
|
+
const remainBudget = Number.isFinite(deadline) ? Math.max(0, deadline - Date.now()) : 0;
|
|
100
|
+
try {
|
|
101
|
+
live = await liveRemoteHeadAsync({
|
|
102
|
+
repoPath: repoProbe.path, branch: repoProbe.branch || '', budgetMs: remainBudget,
|
|
103
|
+
});
|
|
104
|
+
} catch { /* 忽略 */ }
|
|
96
105
|
results.set(repoProbe.name, { live, elapsed: Date.now() - t0 });
|
|
97
106
|
}
|
|
98
107
|
});
|
|
@@ -18,6 +18,9 @@ export function handleSettingsGet(ctx) {
|
|
|
18
18
|
return { status: 200, body: { ok: true, settings: redactConfig(snap || {}) } };
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
+
/** 凭据类设置键:写成功后的回显值必须脱敏(明文只留在 config.json 0600 与凭据文件)。 */
|
|
22
|
+
const SENSITIVE_SETTING_KEYS = new Set(['githubToken', 'sshPub', 'npmToken']);
|
|
23
|
+
|
|
21
24
|
/** POST /api/git-push/settings-set —— 写单个设置键(白名单防越权)。 */
|
|
22
25
|
export async function handleSettingsSet(ctx) {
|
|
23
26
|
const { body, env, cfg } = ctx;
|
|
@@ -58,5 +61,10 @@ export async function handleSettingsSet(ctx) {
|
|
|
58
61
|
} catch (e) {
|
|
59
62
|
log?.warn?.(`settings-set cfg 同步跳过:${e?.message || e}`);
|
|
60
63
|
}
|
|
61
|
-
|
|
64
|
+
// 回显脱敏:凭据类键**不回传明文**(与 README「接口不回传明文」一致)。
|
|
65
|
+
// 写成功与否由 ok 字段表达;前端 save() 只看 ok,不依赖回显值回填输入框。
|
|
66
|
+
const echoValue = SENSITIVE_SETTING_KEYS.has(key)
|
|
67
|
+
? (String(body.value ?? '').trim() ? '(已保存)' : '(空)')
|
|
68
|
+
: body.value;
|
|
69
|
+
return { status: 200, body: { ok: true, key, value: echoValue, note: '设置已写入插件私有配置(config.json)' } };
|
|
62
70
|
}
|
package/lib/app/http-handlers.js
CHANGED
|
@@ -33,6 +33,7 @@ import {
|
|
|
33
33
|
import {
|
|
34
34
|
handleNpmAccount, handleNpmCheck, handleNpmOwned, handleNpmPackages, handleNpmInstall, handleNpmPublish,
|
|
35
35
|
} from './handlers/npm.js';
|
|
36
|
+
import { appendHttpRejectLog } from './settings-bridge.js';
|
|
36
37
|
/** 规则槽位清单对外导出(实现迁至 handlers/meta.js)。 */
|
|
37
38
|
export { listRuleSlots } from './handlers/meta.js';
|
|
38
39
|
|
|
@@ -47,7 +48,11 @@ export async function adaptHttpHandler(req, res, env, cfg) {
|
|
|
47
48
|
body = await new Promise((resolve) => readJsonBody(req, resolve));
|
|
48
49
|
}
|
|
49
50
|
const httpResult = await handleHttp(
|
|
50
|
-
{
|
|
51
|
+
{
|
|
52
|
+
method: req?.method, url: req?.url, origin: req?.headers?.origin, headers: req?.headers, body,
|
|
53
|
+
// TCP 对端地址:无 Origin 判据以它定论(Host 头可伪造、且转发链路可能丢 Host)
|
|
54
|
+
remoteAddress: req?.socket?.remoteAddress || '',
|
|
55
|
+
},
|
|
51
56
|
env,
|
|
52
57
|
cfg,
|
|
53
58
|
);
|
|
@@ -91,8 +96,24 @@ function buildCtx(req, method, env, cfg, query, body, path) {
|
|
|
91
96
|
*/
|
|
92
97
|
export async function handleHttp(req = {}, env = {}, cfg = defaultConfig()) {
|
|
93
98
|
const method = String(req.method || 'GET').toUpperCase();
|
|
94
|
-
|
|
95
|
-
|
|
99
|
+
// content-type 一并传入:桌面端(dsh-app://)转发**显式剥离 Origin**(桌面壳
|
|
100
|
+
// forwardWebRequest 里 headers.delete('origin')),只补 cookie。若不把 Content-Type
|
|
101
|
+
// 传进来,设置页的所有保存/开关/按钮在桌面版恒 403,而 GET 免校验照常——
|
|
102
|
+
// 表现为「页面能打开、保存永不生效」,且拒绝发生在 handler 之前连日志都不留。
|
|
103
|
+
// 放行判据见 checkOrigin:无 Origin 时要求 JSON CT + 回环 Host 同时成立。
|
|
104
|
+
// remoteAddress 一并传入:无 Origin 时的「是否本机」判定**以 TCP 对端地址为准**
|
|
105
|
+
// —— Host 头可被客户端伪造(`Host: 127.0.0.1`),socket 地址不可伪造。
|
|
106
|
+
const remoteAddress = req.remoteAddress || req.socket?.remoteAddress || '';
|
|
107
|
+
const originCheck = checkOrigin(method, req.origin, undefined, req.headers?.host, req.headers?.['content-type'], remoteAddress);
|
|
108
|
+
if (!originCheck.ok) {
|
|
109
|
+
// 拒绝留痕:403 发生在任何 handler 之前,不写这条日志就完全静默——
|
|
110
|
+
// 用户只看到「保存失败」,排查者也没有任何线索(外部 issue 正是这么卡住的)。
|
|
111
|
+
appendHttpRejectLog({
|
|
112
|
+
method, url: req.url, origin: req.origin, host: req.headers?.host,
|
|
113
|
+
code: originCheck.code, status: originCheck.status,
|
|
114
|
+
}, env);
|
|
115
|
+
return { status: originCheck.status, body: { ok: false, ...originCheck } };
|
|
116
|
+
}
|
|
96
117
|
const sizeCheck = checkBodySize(Number(req.headers?.['content-length']) || 0);
|
|
97
118
|
if (!sizeCheck.ok) return { status: sizeCheck.status, body: { ok: false, ...sizeCheck } };
|
|
98
119
|
const path = String(req.url || '/').split('?')[0];
|
package/lib/app/inject-text.js
CHANGED
|
@@ -36,6 +36,7 @@ export const FUNCTION_USAGE_HINT = [
|
|
|
36
36
|
'· git_set_visibility —— 切换仓库 public/private。',
|
|
37
37
|
'· git_clone —— 从 GitHub clone 到本地(走 GitHub API,不直连 github.com)。',
|
|
38
38
|
'· link_check —— 检查文档内链接有效性(只报 warning,不拦截)。',
|
|
39
|
+
'· scope_check —— 检查 JS **拼接产物**的作用域撞名(多段 JS 拼进同一作用域时,同一函数帧内 var/function/const/let/class 重名会让后者静默顶掉前者、运行期毫无报错线索;判定按真实作用域帧,两个不同函数里的同名局部变量不算撞名)。参数:files(逗号分隔,缺省读项目 package.json 的 dshScopeCheck.files)/ repo / prefix / allowlist / topLevelMustBeEmpty。**通用**:没声明 dshScopeCheck 的项目只查同帧重名,不会拿本项目的 dshgp_ 前缀去要求别人;拼接产物做提交前自检、或给别的项目接门禁时用它(CLI 等价命令 git-sluice scope-check)。',
|
|
39
40
|
'· npm_publish —— npm 发包(**后台 job**,返回 jobId 可用 job_output 查):默认 dryRun=true 只体检 + `npm publish --dry-run`(不写 registry ✗);真发必须同时传 confirm=true 与 dryRun=false(不可撤销,先 dryRun 看包内容)。参数:dir(目标包目录,缺省工作区)/ tag(默认 latest)/ otp(2FA)/ dryRun / confirm。',
|
|
40
41
|
'· git_sluice —— 浅包装 git 透传工具(AI 直接调用任意 git 命令,凭据自动注入):args 传与 git 完全一致的参数串(空格分隔,路径含空格用引号);例:git_sluice({args:"status --short"}) / git_sluice({args:"log --oneline -5"}) / git_sluice({args:"branch -a"})。返回 status + stdout/stderr。git 的其余能力(log/diff/branch/tag/remote 等)用它;高频写操作仍走 git_commit_push/git_clone 等专用工具(自带审计/门禁)。',
|
|
41
42
|
'【凭据由插件托管,不要到处找凭据】GitHub token 与 SSH 公钥存放在插件 config.json(git-push/config.json 的 githubToken、sshPub 键,0600);SSH 私钥仍为文件(git-push/id_rsa),由插件的推送/校验流程自动读取与选择通道(默认 SSH,token 401 回退 SSH)。',
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 插件入口层 · 配置 schema(审计侧)
|
|
3
|
+
*
|
|
4
|
+
* 为什么单独成文件(2026-11-08 UI 与审计解耦 · 文件隔离阶段):
|
|
5
|
+
* 审计与 git 侧计划重构成两个独立项目,本阶段先把**文件边界**划清——
|
|
6
|
+
* 审计相关设置键集中在本文件,git / 发布侧的键留在 `schema.js`。
|
|
7
|
+
* 行为完全不变:`schema.js` 用 `...auditConfigShape(Schema)` 展开合并,
|
|
8
|
+
* 产出的仍是同一个 Config 对象(同一批键、同一批默认值)。
|
|
9
|
+
*
|
|
10
|
+
* 边界判据:键的语义属于「静态检查 / 规则 / 评分 / 措辞」即归审计侧;
|
|
11
|
+
* 属于「扫描仓库 / 克隆 / 推送 / 凭据 / 注入」留在 schema.js。
|
|
12
|
+
* `injectRequirements` 归审计侧:它是「提交前审计」的子开关(注入开发者要求清单)。
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** 全量审计文件数上限默认值(0=不限)。 */
|
|
16
|
+
const DEFAULT_MAX_SCAN_FILES = 3000;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* 审计侧配置键形状。
|
|
20
|
+
* @param {object} Schema schemastery(或 makeFallbackSchema 兜底实现)
|
|
21
|
+
* @returns {object} 键名 → schema 字段
|
|
22
|
+
*/
|
|
23
|
+
export function auditConfigShape(Schema) {
|
|
24
|
+
return {
|
|
25
|
+
auditEnabled: Schema.boolean().default(false).description('提交前审计(默认关)'),
|
|
26
|
+
// 提交前审计的子开关:开启后在系统提示词注入「开发者特殊要求」清单全文,AI 常驻可见、
|
|
27
|
+
// 不必等门禁拦截才去读清单(省一次失败的工具往返)。auditEnabled 关闭时本项不生效。
|
|
28
|
+
maxScanFiles: Schema.number().default(DEFAULT_MAX_SCAN_FILES).description('全量审计文件数上限(0=不限);超限按变动文件优先截断,防止弱机扫大仓卡死'),
|
|
29
|
+
injectRequirements: Schema.boolean().default(false).description('注入开发者要求清单到系统提示词(可直接勾选;父开关「提交前审计」关闭时置灰且不注入,勾选保留;默认关)'),
|
|
30
|
+
auditScanScope: Schema.string().default('diff').description('diff | full'),
|
|
31
|
+
auditRuleOrder: Schema.array(Schema.string()).default([]).description('规则槽位加载顺序(后加载覆盖先加载;空=默认偏好顺序;private 恒末尾强制)'),
|
|
32
|
+
auditDisabledSlots: Schema.array(Schema.string()).default([]).description('UI 禁用的规则槽位(设置页单击切换;nodejs/private 安全红线不可禁用)'),
|
|
33
|
+
weightOverrides: Schema.string().default('').description('权重覆盖 JSON(如 {"安全性":100},空=默认权重表)'),
|
|
34
|
+
linkCheckEnabled: Schema.boolean().default(false).description('链接检查(默认关,需网络)'),
|
|
35
|
+
commentWordingEnabled: Schema.boolean().default(true).description('提交信息措辞检查'),
|
|
36
|
+
commentWordingCustom: Schema.string().default('').description('自定义措辞规则'),
|
|
37
|
+
commentWordingRulesFile: Schema.string().default('').description('措辞规则文件路径'),
|
|
38
|
+
commentWordingRulesUrl: Schema.string().default('').description('措辞规则 URL'),
|
|
39
|
+
auditRuleWeights: Schema.dict(Schema.any()).default({}).description('规则权重({ blacklist: { pattern: weight } })'),
|
|
40
|
+
qualityWeights: Schema.dict(Schema.number()).default({}).description('质量维度权重覆盖({ 维度名: weight })'),
|
|
41
|
+
};
|
|
42
|
+
}
|
package/lib/app/schema.js
CHANGED
|
@@ -9,6 +9,11 @@
|
|
|
9
9
|
|
|
10
10
|
import { createRequire } from 'node:module';
|
|
11
11
|
|
|
12
|
+
// 审计侧设置键单独成文件(文件隔离阶段;展开合并后仍是同一个 Config 对象)
|
|
13
|
+
import { auditConfigShape } from './schema-audit.js';
|
|
14
|
+
// 引擎默认超时取单一来源(与运行期兜底共用),避免 schema 默认值漂移
|
|
15
|
+
import { PRE_COMMIT_TIMEOUT_MS_DEFAULT } from './constants.js';
|
|
16
|
+
|
|
12
17
|
/**
|
|
13
18
|
* schemastery 条件加载(peerDependency 由 DSH 宿主提供):
|
|
14
19
|
* - DSH 插件运行期:宿主 node_modules 提供 → 用真实 Schema(Standard Schema v1)
|
|
@@ -17,9 +22,6 @@ import { createRequire } from 'node:module';
|
|
|
17
22
|
*/
|
|
18
23
|
const require2 = createRequire(import.meta.url);
|
|
19
24
|
|
|
20
|
-
/* ───────── 配置默认值常量 ───────── */
|
|
21
|
-
const DEFAULT_MAX_SCAN_FILES = 3000; // 全量审计文件数上限默认值
|
|
22
|
-
|
|
23
25
|
let Schema = null;
|
|
24
26
|
|
|
25
27
|
try {
|
|
@@ -52,6 +54,10 @@ function makeFallbackSchema() {
|
|
|
52
54
|
type: 'object',
|
|
53
55
|
refs: Object.entries(shape).map(([k, s]) => ({ key: k, meta: s?.meta || {} })),
|
|
54
56
|
});
|
|
57
|
+
// 嵌套对象也要能链 .description():真实 schemastery 的 object 支持链式描述,
|
|
58
|
+
// 兜底实现缺这一条时,任何「嵌套对象 + 描述」的 schema 定义(如 preCommit)都会在
|
|
59
|
+
// 缺依赖环境里抛 TypeError: fn.description is not a function —— 整个插件直接起不来。
|
|
60
|
+
fn.description = (d) => { fn.meta = { ...(fn.meta || {}), description: d }; return fn; };
|
|
55
61
|
// 【修复 】fallback schema 必须带 ~standard 标记,否则 DSH cordis 的
|
|
56
62
|
// resolveConfig 读 Config['~standard'].validate 时 undefined 崩溃
|
|
57
63
|
// ("Cannot read properties of undefined (reading 'validate')")。
|
|
@@ -81,18 +87,18 @@ export const Config = Schema.object({
|
|
|
81
87
|
workspaceRoot: Schema.string().default('').description('扫描根目录(空=DSH workspaceRoot)'),
|
|
82
88
|
extraRepos: Schema.array(Schema.string()).default([]).description('额外仓库路径(数组)'),
|
|
83
89
|
extraReposFile: Schema.string().default('').description('额外仓库清单文件(每行一个绝对路径,# 注释;运行时实时读取)'),
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
// 不必等门禁拦截才去读清单(省一次失败的工具往返)。auditEnabled 关闭时本项不生效。
|
|
87
|
-
maxScanFiles: Schema.number().default(DEFAULT_MAX_SCAN_FILES).description('全量审计文件数上限(0=不限);超限按变动文件优先截断,防止弱机扫大仓卡死'),
|
|
88
|
-
injectRequirements: Schema.boolean().default(false).description('注入开发者要求清单到系统提示词(可直接勾选;父开关「提交前审计」关闭时置灰且不注入,勾选保留;默认关)'),
|
|
89
|
-
auditScanScope: Schema.string().default('diff').description('diff | full'),
|
|
90
|
+
// —— 审计侧设置键(集中在 lib/app/schema-audit.js,此处展开合并)——
|
|
91
|
+
...auditConfigShape(Schema),
|
|
90
92
|
maxCloneFileMB: Schema.number().default(10).description('clone 单文件体积上限(MB),0=不限'),
|
|
91
93
|
cloneConcurrency: Schema.number().default(6).description('clone 并发下载数'),
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
94
|
+
// —— 提交前预处理引擎(可替换审计引擎,解耦方案 §2.1)——
|
|
95
|
+
// 三项刻意都是「空 = 内置」而不是「空 = 关闭」:门禁不能因为漏配字段就悄悄不审计。
|
|
96
|
+
// 注意本项是**高级文件配置**,不进 UI 设置项;解析顺序见 pre-commit-engine.js 的 resolvePreCommitConfig。
|
|
97
|
+
preCommit: Schema.object({
|
|
98
|
+
command: Schema.string().default('').description('审计引擎命令(空=内置 node;走 PATH 自探测,找不到会显式报错而不是静默降级)'),
|
|
99
|
+
args: Schema.array(Schema.string()).default([]).description('引擎参数(空=内置 scripts/audit-gate.mjs);相对路径按插件根解析'),
|
|
100
|
+
timeoutMs: Schema.number().default(PRE_COMMIT_TIMEOUT_MS_DEFAULT).description('引擎超时毫秒(超时按执行失败处理,fail-closed)'),
|
|
101
|
+
}).description('提交前预处理引擎(空=内置;换引擎只改这里)'),
|
|
96
102
|
pushMethod: Schema.string().default('ssh').description('推送通道:ssh(默认,推本地 HEAD、远端 sha 与本地一致)| api(Git Data API 重建提交)| auto(有私钥走 ssh,否则 api)'),
|
|
97
103
|
// 推送门禁(类似会话指挥家写操作拦截)——开启后 AI 推送必须带 pushConfirmed:true
|
|
98
104
|
// (已显式放行 pushConfirmed:true),否则 git_commit_push 拦截推送步骤(commit 可做,push 被挡)。
|
|
@@ -111,12 +117,6 @@ export const Config = Schema.object({
|
|
|
111
117
|
sshPub: Schema.string().description('SSH 公钥整行(存同级仓 *.pub)'),
|
|
112
118
|
npmToken: Schema.string().role('secret').description('npm token(存插件配置目录 0600;明文不下发浏览器;与 githubToken 同文件,写入走原子读改写)'),
|
|
113
119
|
npmRegistry: Schema.string().default('https://registry.npmjs.org/').description('npm registry 地址(默认官方源;用私有源时改这里)'),
|
|
114
|
-
commentWordingEnabled: Schema.boolean().default(true).description('提交信息措辞检查'),
|
|
115
|
-
commentWordingCustom: Schema.string().default('').description('自定义措辞规则'),
|
|
116
|
-
commentWordingRulesFile: Schema.string().default('').description('措辞规则文件路径'),
|
|
117
|
-
commentWordingRulesUrl: Schema.string().default('').description('措辞规则 URL'),
|
|
118
|
-
auditRuleWeights: Schema.dict(Schema.any()).default({}).description('规则权重({ blacklist: { pattern: weight } })'),
|
|
119
|
-
qualityWeights: Schema.dict(Schema.number()).default({}).description('质量维度权重覆盖({ 维度名: weight })'),
|
|
120
120
|
// 注入总开关(侧边栏可勾)。拆分两通道:
|
|
121
121
|
// systemPrompt 注入三段(功能用法/skill 入口/要求清单);环境信息(工作区目录 + 工具
|
|
122
122
|
// 安装路径)改走上下文注入(agent/pre-step 首次注入)。工具探测清单 = lib/tool-probes.json
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 「拼接产物作用域检查」的**共享执行器**(工具 / 独立脚本 / 审计规则共用一份判定)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么要有这一层:同一件事有三个入口(`scope_check` 工具、`scripts/check-js-scope.mjs`、
|
|
5
|
+
* 审计规则 kind=scope-collision),执行流程一旦各写一份就会漂移。这里只做
|
|
6
|
+
* 「找契约 → 逐文件分析 → 汇总」,真正的判定在 `lib/ast/scope-collisions.js`,
|
|
7
|
+
* 「按文件所属项目取契约」在 `lib/audit/scope-policy.js`(中立模块,审计侧也用它)。
|
|
8
|
+
*
|
|
9
|
+
* 契约适用口径(与审计侧**故意不同**,各有各的输入面):
|
|
10
|
+
* · 本执行器:目标文件是调用方**显式点名**的 ⇒ 视为产物;项目给了 `files` 清单
|
|
11
|
+
* 且不含该文件时仍不套契约(典型场景:分片源码不是产物,套前缀会把局部变量
|
|
12
|
+
* 全判成缺前缀)。
|
|
13
|
+
* · 审计侧(lib/checks/scope-collision.js):那是**全仓扫描**,必须严格按
|
|
14
|
+
* `files` 清单命中,否则每个 js 文件都会被套上前缀契约。
|
|
15
|
+
*/
|
|
16
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
17
|
+
import { resolve } from 'node:path';
|
|
18
|
+
|
|
19
|
+
import { analyzeScopeCollisions } from '../ast/scope-collisions.js';
|
|
20
|
+
import { POLICY_SOURCE, readProjectScopePolicy } from '../audit/scope-policy.js';
|
|
21
|
+
|
|
22
|
+
export { POLICY_SOURCE };
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* 找出某个文件所属项目的契约配置(兼容旧名,实现在中立模块)。
|
|
26
|
+
* @param {string} file 目标文件绝对路径
|
|
27
|
+
*/
|
|
28
|
+
export function policyForFile(file) {
|
|
29
|
+
return readProjectScopePolicy(file);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* 逐文件跑检查。
|
|
34
|
+
* @param {{files:string[], prefix?:string, allowlist?:string[], topLevelMustBeEmpty?:boolean}} o
|
|
35
|
+
* prefix/allowlist/topLevelMustBeEmpty 显式给出时覆盖项目配置(顶层零声明需显式 true/false)。
|
|
36
|
+
* @returns {{ok:boolean, reports:Array<object>, policySources:string[]}}
|
|
37
|
+
*/
|
|
38
|
+
export function runScopeCheck({ files = [], prefix = '', allowlist = [], topLevelMustBeEmpty } = {}) {
|
|
39
|
+
const reports = [];
|
|
40
|
+
const policySources = new Set();
|
|
41
|
+
for (const raw of files) {
|
|
42
|
+
const file = resolve(raw);
|
|
43
|
+
const own = readProjectScopePolicy(file);
|
|
44
|
+
// 项目没给 files 清单时,点名文件即产物;给了清单就只认清单内的文件
|
|
45
|
+
const contractApplies = own.declared && (own.files.length === 0 || own.isDeclaredArtifact);
|
|
46
|
+
const explicit = [];
|
|
47
|
+
if (prefix) explicit.push('prefix');
|
|
48
|
+
if (Array.isArray(allowlist) && allowlist.length) explicit.push('allowlist');
|
|
49
|
+
if (typeof topLevelMustBeEmpty === 'boolean') explicit.push('topLevel');
|
|
50
|
+
const policy = {
|
|
51
|
+
prefix: prefix || (contractApplies ? own.prefix : ''),
|
|
52
|
+
allowlist: Array.isArray(allowlist) && allowlist.length ? allowlist : (contractApplies ? own.allowlist : []),
|
|
53
|
+
topLevelMustBeEmpty: typeof topLevelMustBeEmpty === 'boolean'
|
|
54
|
+
? topLevelMustBeEmpty
|
|
55
|
+
: (contractApplies && own.topLevelMustBeEmpty),
|
|
56
|
+
};
|
|
57
|
+
const source = explicit.length
|
|
58
|
+
? `${POLICY_SOURCE.CLI}(${explicit.join('/')})`
|
|
59
|
+
: `${own.source}${own.configPath ? `:${own.configPath}` : ''}`;
|
|
60
|
+
policySources.add(source);
|
|
61
|
+
if (!existsSync(file)) {
|
|
62
|
+
reports.push({ file, ok: false, missing: true, violations: [`文件不存在:${file}`], declarations: [], duplicates: [] });
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
const result = analyzeScopeCollisions(readFileSync(file, 'utf8'), policy);
|
|
66
|
+
reports.push({ file, ...result, policy });
|
|
67
|
+
}
|
|
68
|
+
return { ok: reports.every((r) => r.ok), reports, policySources: [...policySources] };
|
|
69
|
+
}
|
|
@@ -139,6 +139,57 @@ export function appendSettingsLog(entry, env = {}) {
|
|
|
139
139
|
}
|
|
140
140
|
}
|
|
141
141
|
|
|
142
|
+
/**
|
|
143
|
+
* HTTP 拒绝日志文件(与 settings-ui.log 同级,0600)。
|
|
144
|
+
* 用途:写请求被鉴权前置拒掉时留痕——这类拒绝发生在 handler 之前,
|
|
145
|
+
* settings-ui.log 里本来一条都不会有,用户只看到「保存失败」而查不到原因。
|
|
146
|
+
* @param {{workspaceRoot?:string}} [env]
|
|
147
|
+
*/
|
|
148
|
+
export function httpRejectLogFilePath({ workspaceRoot = '' } = {}) {
|
|
149
|
+
return join(settingsLogFilePath({ workspaceRoot }), '..', 'http-rejects.log');
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* 追加一条 HTTP 拒绝日志(失败静默,绝不阻断请求处理)。
|
|
154
|
+
*
|
|
155
|
+
* 打码口径:query 里凡键名疑似凭据(token / secret / password / key / auth)一律替换为
|
|
156
|
+
* `(已省略)`——拒绝日志是给用户/排查者看的,不能反过来成为泄漏通道。
|
|
157
|
+
* @param {{method?:string, url?:string, origin?:string, host?:string, code?:string, status?:number}} entry
|
|
158
|
+
* @param {{workspaceRoot?:string}} [env]
|
|
159
|
+
*/
|
|
160
|
+
export function appendHttpRejectLog(entry = {}, env = {}) {
|
|
161
|
+
try {
|
|
162
|
+
const file = httpRejectLogFilePath(env);
|
|
163
|
+
mkdirSync(join(file, '..'), { recursive: true, mode: 0o700 });
|
|
164
|
+
const SECRET_KEY_RE = /(token|secret|passwd|password|key|auth|cookie)/i;
|
|
165
|
+
const rawUrl = String(entry.url || '');
|
|
166
|
+
const [pathOnly, queryText = ''] = rawUrl.split('?');
|
|
167
|
+
let query = '';
|
|
168
|
+
if (queryText) {
|
|
169
|
+
const pairs = queryText.split('&').map((pair) => {
|
|
170
|
+
const eq = pair.indexOf('=');
|
|
171
|
+
const rawKey = eq >= 0 ? pair.slice(0, eq) : pair;
|
|
172
|
+
const decodedKey = (() => { try { return decodeURIComponent(rawKey); } catch { return rawKey; } })();
|
|
173
|
+
return SECRET_KEY_RE.test(decodedKey) ? `${rawKey}=(已省略)` : pair;
|
|
174
|
+
});
|
|
175
|
+
query = `?${pairs.join('&')}`;
|
|
176
|
+
}
|
|
177
|
+
const line = JSON.stringify({
|
|
178
|
+
ts: new Date().toISOString(),
|
|
179
|
+
method: String(entry.method || ''),
|
|
180
|
+
url: pathOnly + query,
|
|
181
|
+
origin: String(entry.origin || '(无)'),
|
|
182
|
+
host: String(entry.host || '(无)'),
|
|
183
|
+
code: String(entry.code || ''),
|
|
184
|
+
status: Number(entry.status) || 0,
|
|
185
|
+
});
|
|
186
|
+
appendFileSync(file, line + '\n', { mode: 0o600 });
|
|
187
|
+
return true;
|
|
188
|
+
} catch {
|
|
189
|
+
return false; // 日志失败绝不阻断请求处理
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
142
193
|
/**
|
|
143
194
|
* 读当前设置快照(config.json;文件不存在/坏 JSON 返回 null,不抛)。
|
|
144
195
|
* @param {{workspaceRoot?:string}} [env]
|
package/lib/app/tool-call.js
CHANGED
|
@@ -10,7 +10,7 @@ import { existsSync, readFileSync, appendFileSync } from 'node:fs';
|
|
|
10
10
|
import { MAX_MSG_PREVIEW } from './constants.js';
|
|
11
11
|
import { access } from 'node:fs/promises';
|
|
12
12
|
/** blocked 消息预览截断长度(工具返回精简——完整 message 走审计明细)。 */
|
|
13
|
-
import { join } from 'node:path';
|
|
13
|
+
import { join, resolve, dirname } from 'node:path';
|
|
14
14
|
import { fileURLToPath } from 'node:url';
|
|
15
15
|
import { spawnSync } from 'node:child_process';
|
|
16
16
|
import './host-doc-checks.js'; // 审计包边界:文档漂移检查器由宿主注入(导入即接线,见 lib/app/host-doc-checks.js)
|
|
@@ -77,6 +77,8 @@ async function pushWithPostSteps(args, env, cfg) {
|
|
|
77
77
|
ciTimeoutSec: Number(args.ciTimeoutSec) > 0 ? Number(args.ciTimeoutSec) : 900,
|
|
78
78
|
// 精确 add 路径(逗号分隔,相对 repo);空 = git add -A 全量
|
|
79
79
|
paths: String(args.paths || ''),
|
|
80
|
+
// 敏感文件扫描与审计同一开关:审计关闭 ⇒ 不扫(此前无条件全仓扫,属特权步骤)
|
|
81
|
+
scanSensitive: cfg.auditEnabled !== false,
|
|
80
82
|
});
|
|
81
83
|
// ── 鼓励使用结构化提交信息(messageItems):提醒 + 采用率留痕 ──────────────────
|
|
82
84
|
// 为什么需要:默认路径(单串 message)更省事,结构化参数长期无人用 ⇒ 两件事互补:
|
|
@@ -292,7 +294,7 @@ async function callNpmPublishJob(args = {}, jobs, exec, log, env = {}, cfg = {})
|
|
|
292
294
|
const { publishPackage } = await import('../npm/publish.js');
|
|
293
295
|
const doPublish = () => publishPackage({
|
|
294
296
|
dir: String(args.dir || env.workspaceRoot || ''),
|
|
295
|
-
registry: cfg?.npmRegistry ||
|
|
297
|
+
registry: cfg?.npmRegistry || undefined,
|
|
296
298
|
workspaceRoot: env.workspaceRoot || '',
|
|
297
299
|
dryRun,
|
|
298
300
|
tag: args.tag || 'latest',
|
|
@@ -523,7 +525,7 @@ async function runStandardAuditTool(args, env, cfg, log, weights) {
|
|
|
523
525
|
: await auditWithScope(repo, auditOpts);
|
|
524
526
|
const summary = summarize(auditResult.findings);
|
|
525
527
|
// 0 文件(空目录/diff 0 变动)不评分——scoreQuality 返回 emptyResult 防满分
|
|
526
|
-
const quality = scoreQuality(auditResult.findings, weights, { files: auditResult.files, dimFileCounts: auditResult.dimFileCounts });
|
|
528
|
+
const quality = scoreQuality(auditResult.findings, weights, { files: auditResult.files, dimFileCounts: auditResult.dimFileCounts, dimRuleCounts: auditResult.dimRuleCounts });
|
|
527
529
|
// 审计后直接输出豁免类型统计 + 聚合类型 + 拦截列表(blocker 详情不用查 API)
|
|
528
530
|
const exemptStats = exemptStatsOf(auditResult.findings);
|
|
529
531
|
const blocked = auditResult.findings
|
|
@@ -539,9 +541,10 @@ async function runStandardAuditTool(args, env, cfg, log, weights) {
|
|
|
539
541
|
// 缓存按规则包命中数供给 HTTP /rule-slots(侧边栏规则包列表显示实际命中数)
|
|
540
542
|
if (auditResult.slotStats) setLastSlotHitStats(auditResult.slotStats, repo);
|
|
541
543
|
log?.info?.(`code_audit ${repo} → ${quality.emptyResult ? '未评分(0 文件)' : quality.score + '/' + quality.level}(blocker ${summary.blocker} / warning ${summary.warning} / notice ${summary.notice})`);
|
|
542
|
-
//
|
|
543
|
-
//
|
|
544
|
-
|
|
544
|
+
// 默认**返回全量审计结果**(findings + yaml):调用方(AI/脚本)拿到的就该是能直接读的问题明细,
|
|
545
|
+
// 而不是只有分数再自己去查聚合 API —— 多一跳就多一次漏看的可能。
|
|
546
|
+
// 需要精简(大仓库结果过大、或只要结论)时显式传 includeFindings=false / summaryOnly=true。
|
|
547
|
+
const withFindings = args.includeFindings !== false && args.summaryOnly !== true;
|
|
545
548
|
const out = { ok: true, scope: auditResult.scope, files: auditResult.files, summary, quality, exemptStats, blocked, groupByTypes: GROUP_BY_KEYS, apiGuide, slotStats: auditResult.slotStats };
|
|
546
549
|
if (analysisCoverage) {
|
|
547
550
|
out.analysisCoverage = analysisCoverage;
|
|
@@ -610,7 +613,8 @@ export async function callTool(toolName, args = {}, env = {}, cfg = defaultConfi
|
|
|
610
613
|
name: String(args.name || args.pkg || ''),
|
|
611
614
|
version: String(args.version || ''),
|
|
612
615
|
wholePackage: args.wholePackage === true,
|
|
613
|
-
registry
|
|
616
|
+
// 同 handlers/npm.js:空串会让 npmrc 写出 `registry=`,npm 解析空 URL 直接崩
|
|
617
|
+
registry: cfg?.npmRegistry || undefined,
|
|
614
618
|
workspaceRoot: env.workspaceRoot || '',
|
|
615
619
|
dryRun,
|
|
616
620
|
confirm: args.confirm === true,
|
|
@@ -748,6 +752,51 @@ export async function callTool(toolName, args = {}, env = {}, cfg = defaultConfi
|
|
|
748
752
|
}, env, cfg);
|
|
749
753
|
return { ok: out?.status === 200 && out?.body?.ok !== false, status: out?.status, endpoint: ep, result: out?.body };
|
|
750
754
|
}
|
|
755
|
+
case 'scope_check': {
|
|
756
|
+
// 拼接产物作用域撞名:判定在 lib/ast/scope-collisions.js、契约在 lib/audit/scope-policy.js、
|
|
757
|
+
// 执行流程在 lib/app/scope-check.js —— 与 scripts/check-js-scope.mjs、审计规则
|
|
758
|
+
// kind=scope-collision 三方共用同一份实现,此处只做参数映射与结果整形。
|
|
759
|
+
const { runScopeCheck } = await import('./scope-check.js');
|
|
760
|
+
const { readProjectScopePolicy } = await import('../audit/scope-policy.js');
|
|
761
|
+
const repoRoot = resolve(String(args.repo || env.workspaceRoot || process.cwd()));
|
|
762
|
+
const splitList = (value) => String(value || '').split(/[,;\s]+/).map((s) => s.trim()).filter(Boolean);
|
|
763
|
+
let targets = splitList(args.files).map((f) => resolve(repoRoot, f));
|
|
764
|
+
if (!targets.length) {
|
|
765
|
+
// 缺省取项目自己声明的产物清单(dshScopeCheck.files)——不猜文件名,
|
|
766
|
+
// 否则「哪些文件是拼接产物」这件事会散成两处判断(本文件 + package.json)。
|
|
767
|
+
const policy = readProjectScopePolicy(join(repoRoot, 'package.json'));
|
|
768
|
+
const base = policy.configPath ? dirname(policy.configPath) : repoRoot;
|
|
769
|
+
targets = policy.files.map((f) => resolve(base, f));
|
|
770
|
+
if (!targets.length) {
|
|
771
|
+
return { ok: false, error: `未指定 files,且 ${join(repoRoot, 'package.json')} 未声明 dshScopeCheck.files` };
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
const result = runScopeCheck({
|
|
775
|
+
files: targets,
|
|
776
|
+
prefix: String(args.prefix || ''),
|
|
777
|
+
allowlist: splitList(args.allowlist),
|
|
778
|
+
...(typeof args.topLevelMustBeEmpty === 'boolean' ? { topLevelMustBeEmpty: args.topLevelMustBeEmpty } : {}),
|
|
779
|
+
});
|
|
780
|
+
const lines = result.policySources.map((src) => `策略来源:${src}`);
|
|
781
|
+
for (const report of result.reports) {
|
|
782
|
+
const rel = report.file.startsWith(`${repoRoot}/`) ? report.file.slice(repoRoot.length + 1) : report.file;
|
|
783
|
+
if (report.ok) {
|
|
784
|
+
lines.push(`✔ ${rel}:${(report.declarations || []).length} 个声明,无同帧重名`);
|
|
785
|
+
continue;
|
|
786
|
+
}
|
|
787
|
+
lines.push(`✗ ${rel}:`);
|
|
788
|
+
for (const violation of report.violations || []) lines.push(` - ${violation}`);
|
|
789
|
+
}
|
|
790
|
+
const violationCount = result.reports.reduce((sum, report) => sum + (report.violations || []).length, 0);
|
|
791
|
+
return {
|
|
792
|
+
ok: result.ok,
|
|
793
|
+
count: result.reports.length,
|
|
794
|
+
violations: violationCount,
|
|
795
|
+
policySources: result.policySources,
|
|
796
|
+
reports: result.reports,
|
|
797
|
+
lines,
|
|
798
|
+
};
|
|
799
|
+
}
|
|
751
800
|
default:
|
|
752
801
|
return { ok: false, error: `未知工具: ${toolName}` };
|
|
753
802
|
}
|