dsh-git-push 0.0.0-stage → 2.8.4
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/.auditignore +30 -0
- package/.gitignore +39 -0
- package/LICENSE +21 -0
- package/README.md +1482 -2
- package/cli.mjs +360 -0
- package/cordis.patch.yml +14 -0
- package/lib/ARCHITECTURE.md +34 -0
- package/lib/BUGFIX-NOTES-2026-09-14.md +278 -0
- package/lib/app/apply.js +275 -0
- package/lib/app/audit-api.js +158 -0
- package/lib/app/command-registry.js +262 -0
- package/lib/app/constants.js +16 -0
- package/lib/app/handlers/account.js +166 -0
- package/lib/app/handlers/clone.js +168 -0
- package/lib/app/handlers/http-constants.js +9 -0
- package/lib/app/handlers/identity-rewrite.js +94 -0
- package/lib/app/handlers/meta.js +175 -0
- package/lib/app/handlers/npm.js +169 -0
- package/lib/app/handlers/repo-actions.js +143 -0
- package/lib/app/handlers/repos.js +231 -0
- package/lib/app/handlers/settings.js +62 -0
- package/lib/app/host-doc-checks.js +25 -0
- package/lib/app/http-handlers.js +131 -0
- package/lib/app/index.js +30 -0
- package/lib/app/inject-text.js +191 -0
- package/lib/app/scan-root.js +23 -0
- package/lib/app/schema.js +150 -0
- package/lib/app/settings-bridge.js +167 -0
- package/lib/app/slash-commands.js +395 -0
- package/lib/app/slot-stats.js +35 -0
- package/lib/app/tool-call.js +662 -0
- package/lib/app/tools.js +40 -0
- package/lib/ast/brace.js +105 -0
- package/lib/ast/callgraph.js +135 -0
- package/lib/ast/code-lines.js +114 -0
- package/lib/ast/consts.js +12 -0
- package/lib/ast/control-flow.js +461 -0
- package/lib/ast/credential.js +199 -0
- package/lib/ast/dataflow.js +274 -0
- package/lib/ast/dup-code.js +165 -0
- package/lib/ast/index.js +36 -0
- package/lib/ast/io-risk-const.js +95 -0
- package/lib/ast/io-risk-fn.js +208 -0
- package/lib/ast/io-risk-loop.js +308 -0
- package/lib/ast/io-risk.js +314 -0
- package/lib/ast/lang.js +156 -0
- package/lib/ast/line-count.js +52 -0
- package/lib/ast/magic-number.js +272 -0
- package/lib/ast/naming.js +284 -0
- package/lib/ast/perf.js +472 -0
- package/lib/ast/scope.js +241 -0
- package/lib/ast/shell.js +131 -0
- package/lib/ast/size.js +378 -0
- package/lib/ast/symbol-index.js +399 -0
- package/lib/ast/tokenizer.js +341 -0
- package/lib/audit/analysis-coverage.js +98 -0
- package/lib/audit/audit-file.js +182 -0
- package/lib/audit/checks.js +17 -0
- package/lib/audit/client-entry.js +93 -0
- package/lib/audit/collector.js +477 -0
- package/lib/audit/ext-runner.js +80 -0
- package/lib/audit/file-context.js +138 -0
- package/lib/audit/finding.js +50 -0
- package/lib/audit/gitignore-match.js +113 -0
- package/lib/audit/glob.js +63 -0
- package/lib/audit/history-report.js +100 -0
- package/lib/audit/history.js +126 -0
- package/lib/audit/ignore-blind.js +101 -0
- package/lib/audit/index.js +33 -0
- package/lib/audit/orchestrate.js +476 -0
- package/lib/audit/public.js +24 -0
- package/lib/audit/repo-level.js +30 -0
- package/lib/audit/report-yaml.js +86 -0
- package/lib/audit/slot.js +65 -0
- package/lib/audit-defaults.js +18 -0
- package/lib/audit-rules/audit-rules-comment.yml +247 -0
- package/lib/audit-rules/audit-rules-cpp.yml +22 -0
- package/lib/audit-rules/audit-rules-docs.yml +32 -0
- package/lib/audit-rules/audit-rules-dsh.yml +162 -0
- package/lib/audit-rules/audit-rules-filehealth.yml +42 -0
- package/lib/audit-rules/audit-rules-folder.yml +99 -0
- package/lib/audit-rules/audit-rules-frontend.yml +335 -0
- package/lib/audit-rules/audit-rules-go.yml +22 -0
- package/lib/audit-rules/audit-rules-i18n.yml +45 -0
- package/lib/audit-rules/audit-rules-java.yml +105 -0
- package/lib/audit-rules/audit-rules-nodejs.yml +647 -0
- package/lib/audit-rules/audit-rules-npm.yml +187 -0
- package/lib/audit-rules/audit-rules-paths.yml +92 -0
- package/lib/audit-rules/audit-rules-performance.yml +207 -0
- package/lib/audit-rules/audit-rules-php.yml +22 -0
- package/lib/audit-rules/audit-rules-private.yml +24 -0
- package/lib/audit-rules/audit-rules-python.yml +106 -0
- package/lib/audit-rules/audit-rules-robustness.yml +27 -0
- package/lib/audit-rules/audit-rules-rust.yml +22 -0
- package/lib/audit-rules/audit-rules-structure.yml +159 -0
- package/lib/audit-rules/audit-rules-swift.yml +22 -0
- package/lib/audit-rules/audit-rules-template.yml +108 -0
- package/lib/checks/button-bind.js +276 -0
- package/lib/checks/common.js +170 -0
- package/lib/checks/credential-file.js +43 -0
- package/lib/checks/dataflow.js +40 -0
- package/lib/checks/dispatch.js +112 -0
- package/lib/checks/dup-code.js +69 -0
- package/lib/checks/dup-const.js +232 -0
- package/lib/checks/file-health.js +150 -0
- package/lib/checks/filter.js +131 -0
- package/lib/checks/folder.js +173 -0
- package/lib/checks/hardcoded-path.js +98 -0
- package/lib/checks/index.js +46 -0
- package/lib/checks/io.js +66 -0
- package/lib/checks/magic-number.js +42 -0
- package/lib/checks/npm-json.js +273 -0
- package/lib/checks/private.js +63 -0
- package/lib/checks/regex.js +256 -0
- package/lib/checks/semantic.js +134 -0
- package/lib/checks/structural.js +274 -0
- package/lib/cli/commands-account.mjs +107 -0
- package/lib/cli/commands-audit.mjs +144 -0
- package/lib/cli/commands-doc.mjs +127 -0
- package/lib/cli/commands-vcs.mjs +175 -0
- package/lib/client/index.js +162 -0
- package/lib/client-parts/00-loader.js +33 -0
- package/lib/client-parts/01-const.js +207 -0
- package/lib/client-parts/02-utils.js +62 -0
- package/lib/client-parts/03-icons.js +12 -0
- package/lib/client-parts/10-account.js +83 -0
- package/lib/client-parts/11-browser.js +95 -0
- package/lib/client-parts/20-repo.js +374 -0
- package/lib/client-parts/21-audit.js +301 -0
- package/lib/client-parts/22-settings.js +146 -0
- package/lib/client-parts/23-npm.js +383 -0
- package/lib/client-parts/30-page.js +56 -0
- package/lib/client-parts/40-controller.js +1092 -0
- package/lib/client-parts/41-actions.js +279 -0
- package/lib/client-parts/99-apply.js +72 -0
- package/lib/client.js +3195 -0
- package/lib/commit-push.js +144 -0
- package/lib/context/index.js +363 -0
- package/lib/core/atomic-json.js +98 -0
- package/lib/core/config.js +40 -0
- package/lib/core/credentials.js +274 -0
- package/lib/core/endpoints.js +109 -0
- package/lib/core/exec.js +162 -0
- package/lib/exempt/index.js +292 -0
- package/lib/fs/edit-after-read.js +103 -0
- package/lib/fsx.js +87 -0
- package/lib/git/account-status.js +140 -0
- package/lib/git/account.js +233 -0
- package/lib/git/api.js +136 -0
- package/lib/git/atomic-json.js +6 -0
- package/lib/git/browse.js +38 -0
- package/lib/git/clone-download.js +397 -0
- package/lib/git/clone-history-mode.js +143 -0
- package/lib/git/clone-history.js +175 -0
- package/lib/git/clone-jobs.js +250 -0
- package/lib/git/clone-replay-io.js +172 -0
- package/lib/git/clone-replay.js +275 -0
- package/lib/git/clone.js +445 -0
- package/lib/git/cloud.js +46 -0
- package/lib/git/commit-message.js +141 -0
- package/lib/git/config.js +6 -0
- package/lib/git/cred-env.js +88 -0
- package/lib/git/credentials.js +6 -0
- package/lib/git/endpoints.js +6 -0
- package/lib/git/exec.js +6 -0
- package/lib/git/identity-rewrite.js +297 -0
- package/lib/git/identity.js +150 -0
- package/lib/git/ignore.js +69 -0
- package/lib/git/index.js +41 -0
- package/lib/git/module-splitter.js +47 -0
- package/lib/git/post-push.js +101 -0
- package/lib/git/push-diagnose.js +142 -0
- package/lib/git/push.js +470 -0
- package/lib/git/remote-resolve.js +146 -0
- package/lib/git/remote.js +128 -0
- package/lib/git/repo-index.js +512 -0
- package/lib/git/repos.js +235 -0
- package/lib/git/scan-runner.js +159 -0
- package/lib/git/sensitive.js +134 -0
- package/lib/git/transport.js +430 -0
- package/lib/git/visibility.js +35 -0
- package/lib/git/wrapped-git.js +68 -0
- package/lib/http/index.js +170 -0
- package/lib/index.js +24 -0
- package/lib/link-check/index.js +187 -0
- package/lib/npm/account.js +64 -0
- package/lib/npm/install.js +211 -0
- package/lib/npm/npmrc.js +56 -0
- package/lib/npm/publish.js +167 -0
- package/lib/npm/registry.js +147 -0
- package/lib/plugin/auto-detect.js +92 -0
- package/lib/plugin/auto-push.js +154 -0
- package/lib/plugin/index.js +250 -0
- package/lib/readme-templates/readme.yml +38 -0
- package/lib/rule/compilers/credential.js +62 -0
- package/lib/rule/compilers/dataflow.js +38 -0
- package/lib/rule/compilers/file-health.js +75 -0
- package/lib/rule/compilers/frontend.js +86 -0
- package/lib/rule/compilers/func.js +35 -0
- package/lib/rule/compilers/helpers.js +71 -0
- package/lib/rule/compilers/index.js +29 -0
- package/lib/rule/compilers/link-semantic.js +45 -0
- package/lib/rule/compilers/list-kinds.js +12 -0
- package/lib/rule/compilers/numeric-kinds.js +66 -0
- package/lib/rule/compilers/regex.js +78 -0
- package/lib/rule/compilers/structure.js +80 -0
- package/lib/rule/compilers.js +17 -0
- package/lib/rule/homoglyph.js +45 -0
- package/lib/rule/loader.js +270 -0
- package/lib/rule/registry.js +115 -0
- package/lib/rule/scope.js +67 -0
- package/lib/score/docs-score.js +166 -0
- package/lib/score/index.js +140 -0
- package/lib/self/index.js +193 -0
- package/lib/skip-dirs.js +64 -0
- package/lib/tool-probes.json +50 -0
- package/lib/user-requirements.json +14 -0
- package/lib/vendor/js-yaml/LICENSE +21 -0
- package/lib/vendor/js-yaml/js-yaml.mjs +3073 -0
- package/package.json +95 -4
- package/scripts/__pycache__/module-splitter.cpython-38.pyc +0 -0
- package/scripts/audit-ext/_example-readme-present.mjs +34 -0
- package/scripts/audit-ext/variable-min-length.mjs +102 -0
- package/scripts/audit-runner.mjs +35 -0
- package/scripts/audit-runtime-check.mjs +129 -0
- package/scripts/browser-page-probe.mjs +271 -0
- package/scripts/build-client.mjs +119 -0
- package/scripts/check.mjs +88 -0
- package/scripts/clean-date-comments.py +102 -0
- package/scripts/doc-drift.mjs +200 -0
- package/scripts/doc-func.mjs +212 -0
- package/scripts/doc-tree.mjs +456 -0
- package/scripts/doc-version.mjs +220 -0
- package/scripts/frontend-preview-check.mjs +124 -0
- package/scripts/hot-path-probe-cjs.cjs +71 -0
- package/scripts/hot-path-probe-fs-shim.mjs +28 -0
- package/scripts/hot-path-probe-fsp-shim.mjs +31 -0
- package/scripts/hot-path-probe.mjs +153 -0
- package/scripts/module-splitter.py +800 -0
- package/scripts/platform-scan.mjs +168 -0
- package/scripts/preview-gen.mjs +489 -0
- package/scripts/preview-local-runner.mjs +55 -0
- package/scripts/preview-server-direct.mjs +116 -0
- package/scripts/preview-server.mjs +305 -0
- package/scripts/preview-slot-data.mjs +123 -0
- package/scripts/probe-recheck.mjs +47 -0
- package/scripts/readme-gen.mjs +268 -0
- package/scripts/rename-locator.mjs +97 -0
- package/scripts/rule-switch.mjs +97 -0
- package/scripts/rules-solo-audit.mjs +173 -0
- package/scripts/scan-file-io.mjs +713 -0
- package/scripts/scan-hardcoded-paths.mjs +125 -0
- package/scripts/scan-repos.mjs +167 -0
- package/scripts/scan-version.mjs +122 -0
- package/scripts/scrub-user-wording.mjs +420 -0
- package/scripts/symbol-index.mjs +85 -0
- package/scripts/sync-plugin-install.mjs +223 -0
- package/scripts/sync-plugin.mjs +279 -0
- package/scripts/verify-prestep.mjs +100 -0
- package/skills/dev/audit-rule-authoring.md +58 -0
- package/skills/dev/dsh-git-push.md +323 -0
- package/skills/dev/git-push-live-fix.md +45 -0
- package/skills/dsh-repo-index.md +35 -0
- package/skills/guide/guide-audit.md +167 -0
- package/skills/guide/guide-cli-scripts.md +104 -0
- package/skills/guide/guide-clone-repos.md +173 -0
- package/skills/guide/guide-commit-push.md +156 -0
- package/skills/guide/guide-inject-ui.md +166 -0
- package/skills/guide/guide-slash-completion.md +118 -0
- package/skills/workflow/README.md +21 -0
- package/skills/workflow/git-commit-discipline.md +68 -0
- package/skills/workflow/git-project-startup.md +85 -0
- package/skills/workflow/git-rebuild-process.md +57 -0
- package/skills/workflow/github-operations.md +91 -0
- package/skills/workflow/readme-sync-git-md.md +28 -0
- package/skills/workflow/task-completion-report.md +73 -0
- package/skills/workflow/tool-json-add-ask.md +35 -0
- package/skills/workflow/versioning-rule.md +211 -0
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-git-push HTTP 总入口(鉴权中间件纯函数 + 端点处理器骨架)
|
|
3
|
+
* dsh-skip-i18n: 插件为中文零依赖 CLI(无 i18n 框架需求),用户可见文案硬编码为产品设计
|
|
4
|
+
*
|
|
5
|
+
* 0.1.7:HTTP 写端点鉴权逻辑抽为纯函数(不依赖真实服务器,可单测),
|
|
6
|
+
* 1.0.0 接线时直接注入 req/res 使用:
|
|
7
|
+
* - Origin 校验:写请求(POST/PUT/PATCH/DELETE)无 Origin 或跨源 → 403
|
|
8
|
+
* - 写确认(confirm):破坏性操作(rebuild/rollback 等)body 必须显式 confirm:true,否则 400
|
|
9
|
+
* - 413:请求体过大拒绝(5MB 上限,防恶意大 body 打爆内存)
|
|
10
|
+
* - GET 只读端点免 Origin 校验(CSRF 攻击面只存在于写请求)
|
|
11
|
+
*/
|
|
12
|
+
export const MAX_BODY_BYTES = 5 * 1024 * 1024; // 5MB 上限
|
|
13
|
+
|
|
14
|
+
/** 写方法集合(CSRF/Origin 校验仅作用于写方法)。 */
|
|
15
|
+
export const WRITE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
|
|
16
|
+
|
|
17
|
+
/** 常用读方法。 */
|
|
18
|
+
export const READ_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
|
|
19
|
+
|
|
20
|
+
export const ALLOWED_ORIGINS = new Set(['http://127.0.0.1', 'http://localhost', 'http://[::1]']);
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Origin 校验:写请求必须带同源 Origin(可信页面来源),否则 403(防 CSRF)。
|
|
24
|
+
* GET/OPTIONS 等只读请求免校验(读不产生副作用)。
|
|
25
|
+
*
|
|
26
|
+
* 1.0.5 侧边栏按钮(账号检查/生成 SSH 密钥):客户端 fetch 写端点需要放行
|
|
27
|
+
* **部署环境真实 Origin**——本机回环白名单只覆盖 127.0.0.1/localhost,局域网
|
|
28
|
+
* GUI(如 http://10.10.10.4:3080)下会误 403。改为 CSRF 防护的标准语义:
|
|
29
|
+
* Origin 主机与请求 Host 头一致 = 同源可信来源 → 放行(跨站 Origin 仍拒)。
|
|
30
|
+
* 本机回环白名单保留兜底(无 Host 头/解析失败时仍可用)。
|
|
31
|
+
* @param {string} method HTTP 方法(大写)
|
|
32
|
+
* @param {string} [origin] Origin 请求头值(可能 undefined)
|
|
33
|
+
* @param {Set<string>} [allowed] 允许的源集合(默认本机回环,测试可注入)
|
|
34
|
+
* @param {string} [host] 请求 Host 头值(如 "10.10.10.4:3080";同源放行依据)
|
|
35
|
+
* @returns {{ok: boolean, status?: number, code?: string, message?: string}}
|
|
36
|
+
* ok=true 放行;ok=false 时带 status/code/message
|
|
37
|
+
*/
|
|
38
|
+
export function checkOrigin(method = '', origin = '', allowed = ALLOWED_ORIGINS, host = '') {
|
|
39
|
+
const methodUpper = String(method || '').toUpperCase();
|
|
40
|
+
if (!WRITE_METHODS.has(methodUpper) && !READ_METHODS.has(methodUpper)) {
|
|
41
|
+
return { ok: false, status: 405, code: 'METHOD', message: `不支持的 HTTP 方法: ${method}` };
|
|
42
|
+
}
|
|
43
|
+
if (READ_METHODS.has(methodUpper)) return { ok: true }; // 只读免校验
|
|
44
|
+
const originStr = String(origin || '').trim();
|
|
45
|
+
if (!originStr) {
|
|
46
|
+
return { ok: false, status: 403, code: 'NO_ORIGIN', message: '写请求缺少 Origin 头——拒绝(防 CSRF)' };
|
|
47
|
+
}
|
|
48
|
+
// 主机名解析:兼容带协议(Origin)与不带协议(Host 头)两种输入,忽略端口
|
|
49
|
+
const hostOf = (u) => {
|
|
50
|
+
const s = String(u || '').trim().replace(/^https?:\/\//i, '');
|
|
51
|
+
const match = /^([^/:]+)(?::\d+)?/.exec(s);
|
|
52
|
+
return match ? match[1] : '';
|
|
53
|
+
};
|
|
54
|
+
const oHost = hostOf(originStr);
|
|
55
|
+
// 同源放行(1.0.5):Origin 主机与请求 Host 一致 = 可信页面自身发起的请求(防跨站 CSRF 的核心)
|
|
56
|
+
const hHost = hostOf(host);
|
|
57
|
+
if (oHost && hHost && oHost === hHost) return { ok: true };
|
|
58
|
+
// 白名单兜底(本机回环;无 Host 头或解析失败场景)
|
|
59
|
+
const allowedHit = !!oHost && [...allowed].some((a) => hostOf(a) === oHost);
|
|
60
|
+
if (!allowedHit) {
|
|
61
|
+
return { ok: false, status: 403, code: 'CROSS_ORIGIN', message: `跨源写请求被拒绝: ${originStr}` };
|
|
62
|
+
}
|
|
63
|
+
return { ok: true };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* 写确认校验:破坏性操作端点(rebuild/rollback/drop-versions 等)body 必须显式 confirm:true。
|
|
68
|
+
* @param {object} body 已解析的请求体
|
|
69
|
+
* @param {boolean} [forceHttpSafe] 测试可注入:false 时非 confirm 拒绝(默认按真实逻辑)
|
|
70
|
+
* @returns {{ok: boolean, status?: number, code?: string, message?: string}}
|
|
71
|
+
*/
|
|
72
|
+
export function checkWriteConfirm(body = {}) {
|
|
73
|
+
if (body && body.confirm === true) return { ok: true };
|
|
74
|
+
return {
|
|
75
|
+
ok: false, status: 400, code: 'NEED_CONFIRM',
|
|
76
|
+
message: '破坏性操作需 body 显式 confirm:true(防误触)',
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 请求体大小校验:超 5MB → 413(防恶意大 body 打爆内存)。
|
|
82
|
+
* @param {number} byteLength 请求体字节数
|
|
83
|
+
* @param {number} [limit] 上限(默认 MAX_BODY_BYTES)
|
|
84
|
+
* @returns {{ok: boolean, status?: number, code?: string, message?: string, limit?: number}}
|
|
85
|
+
*/
|
|
86
|
+
export function checkBodySize(byteLength = 0, limit = MAX_BODY_BYTES) {
|
|
87
|
+
if (typeof byteLength !== 'number' || Number.isNaN(byteLength) || byteLength < 0) {
|
|
88
|
+
return { ok: false, status: 400, code: 'BAD_LENGTH', message: '请求体长度非法' };
|
|
89
|
+
}
|
|
90
|
+
if (byteLength > limit) {
|
|
91
|
+
return { ok: false, status: 413, code: 'TOO_LARGE', message: `请求体超过 ${Math.round(limit / 1024 / 1024)}MB 上限`, limit };
|
|
92
|
+
}
|
|
93
|
+
return { ok: true };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* 组装端点响应体 JSON(统一形状)。
|
|
98
|
+
* @param {boolean} ok
|
|
99
|
+
* @param {object} [extra] 附加字段
|
|
100
|
+
* @returns {object}
|
|
101
|
+
*/
|
|
102
|
+
export function httpOk(ok = true, extra = {}) {
|
|
103
|
+
return { ok, ...extra };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* 统一鉴权流水线:Origin → 方法 → 写确认 → 体大小,全部通过返回 {ok:true}。
|
|
108
|
+
* @param {object} req { method, origin, contentLength, isWriteConfirmOp }
|
|
109
|
+
* @param {object} [opts] { allowedOrigins, bodyLimit, isWriteConfirmOp }
|
|
110
|
+
* @returns {{ok: boolean, status?: number, code?: string, message?: string}}
|
|
111
|
+
*/
|
|
112
|
+
export function authPipeline({ method = '', origin = '', contentLength = 0, isWriteConfirmOp = false } = {}, opts = {}) {
|
|
113
|
+
const originCheck = checkOrigin(method, origin, opts.allowedOrigins);
|
|
114
|
+
if (!originCheck.ok) return originCheck;
|
|
115
|
+
if (opts.isWriteConfirmOp ?? isWriteConfirmOp) {
|
|
116
|
+
// 写确认由调用方在解析 body 后判定(body.confirm),这里只占位返回 ok
|
|
117
|
+
}
|
|
118
|
+
const sizeCheck = checkBodySize(contentLength, opts.bodyLimit);
|
|
119
|
+
if (!sizeCheck.ok) return sizeCheck;
|
|
120
|
+
return { ok: true };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* 读取请求体并做 413 防护(流式累计,超限即终止)。
|
|
125
|
+
* @param {object} req 可读流(.on/.destroy)
|
|
126
|
+
* @param {function} resolve 完成回调(解析失败给 null)
|
|
127
|
+
* @param {number} [limit]
|
|
128
|
+
*/
|
|
129
|
+
export function readJsonBody(req, resolve = () => {}, limit = MAX_BODY_BYTES) {
|
|
130
|
+
let bodyText = '';
|
|
131
|
+
let over = false;
|
|
132
|
+
const done = () => {
|
|
133
|
+
if (over) return resolve(null);
|
|
134
|
+
try { resolve(JSON.parse(bodyText || '{}')); } catch { resolve({}); }
|
|
135
|
+
};
|
|
136
|
+
req.on('data', (c) => {
|
|
137
|
+
bodyText += c;
|
|
138
|
+
if (bodyText.length > limit) {
|
|
139
|
+
over = true;
|
|
140
|
+
bodyText = '';
|
|
141
|
+
try { req.destroy(); } catch { /* 已断开 */ }
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
req.on('end', done);
|
|
145
|
+
req.on('error', () => resolve({}));
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* 端点处理器骨架:按方法 + 路径分发,先跑鉴权再执行。
|
|
150
|
+
* 1.0.0 接线真实 server 时作为路由,测试直接构造 req 对象调用。
|
|
151
|
+
* @param {object} req 简化请求对象 { method, url, origin, headers }
|
|
152
|
+
* @param {object} handlers 路由表 { 'GET /api/x': fn, 'POST /api/y': fn, ... }
|
|
153
|
+
* @returns {{status: number, body: object}}
|
|
154
|
+
*/
|
|
155
|
+
export function routeRequest(req = {}, handlers = {}) {
|
|
156
|
+
const method = String(req.method || 'GET').toUpperCase();
|
|
157
|
+
const url = String(req.url || '/');
|
|
158
|
+
const path = url.split('?')[0];
|
|
159
|
+
const key = `${method} ${path}`;
|
|
160
|
+
const handler = handlers[key];
|
|
161
|
+
if (!handler) {
|
|
162
|
+
return { status: 404, body: { ok: false, code: 'NOT_FOUND', message: `无此端点: ${method} ${path}` } };
|
|
163
|
+
}
|
|
164
|
+
const originCheck = checkOrigin(method, req.origin);
|
|
165
|
+
if (!originCheck.ok) return { status: originCheck.status, body: { ok: false, ...originCheck } };
|
|
166
|
+
const sizeCheck = checkBodySize(Number(req.headers?.['content-length']) || 0);
|
|
167
|
+
if (!sizeCheck.ok) return { status: sizeCheck.status, body: { ok: false, ...sizeCheck } };
|
|
168
|
+
const handlerOut = handler({ req, url, method });
|
|
169
|
+
return { status: 200, body: handlerOut };
|
|
170
|
+
}
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-git-push 插件入口(DSH 接线,1.0.0)
|
|
3
|
+
* dsh-skip-i18n: 插件为中文零依赖 CLI(无 i18n 框架需求),用户可见文案硬编码为产品设计
|
|
4
|
+
*
|
|
5
|
+
* 形态:`apply(ctx, config)`,接线全部走 lib/plugin/(Host 侧注册层)。
|
|
6
|
+
* 职责:把 v2 十大总入口接到 DSH 运行时——
|
|
7
|
+
* 1) 工具注册:ctx.inject(['tools']) → get('tools').register(defineTool(...))
|
|
8
|
+
* 2) 上下文注入:ctx.inject(['systemPrompt']) → section({name, order, text:()=>同步})
|
|
9
|
+
* 3) HTTP API:ctx.inject(['webServer']) → register({kind:'prefix', path, handler})
|
|
10
|
+
* 4) 客户端(设置卡片/侧边栏):**不在此注册**,由 package.json 的 dsh.client
|
|
11
|
+
* + exports["./client"] 自动发现(client.js)
|
|
12
|
+
*
|
|
13
|
+
* 本文件是**宿主 main 指向的入口**(package.json "main": "lib/index.js"),
|
|
14
|
+
* 1.1.4 起只做再导出:实现全在 lib/app/*.js(schema / constants / slot-stats /
|
|
15
|
+
* tools / inject-text / tool-call / http-handlers / apply),本文件不含实现。
|
|
16
|
+
* 业务能力仍全部在 lib/<入口>/:
|
|
17
|
+
* rule / audit / git / self / score / exempt / context / http / client / link-check。
|
|
18
|
+
* 引擎可脱离 DSH 独立运行:`node cli.mjs <子命令>`。
|
|
19
|
+
*
|
|
20
|
+
* 为什么用 `export *` 而非逐名再导出:入口只负责「把 lib/app/ 的公开面原样转出去」,
|
|
21
|
+
* 逐名列举会随功能新增而漂移(漏一个符号宿主就报 apply 缺失);公开面由
|
|
22
|
+
* lib/app/index.js 单点定义。
|
|
23
|
+
*/
|
|
24
|
+
export * from './app/index.js';
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-git-push 链接判断总入口(link-check kind,0.2.0)
|
|
3
|
+
*
|
|
4
|
+
* 分级扣分(只 warning,**永不 blocker**——网络不可靠不应拦提交):
|
|
5
|
+
* 404 / 403 / 410 → 大扣分(-3,链接确实失效)
|
|
6
|
+
* DNS 失败 → 中扣分(-2,域名解析不了,多半是死链接)
|
|
7
|
+
* 超时 / 连接失败 → 小扣分(-1,可能只是网络抖动)
|
|
8
|
+
* 5xx → 小扣分(-1,服务端临时故障)
|
|
9
|
+
* flaky 域名(github.com / api.github.com / raw.githubusercontent.com / npmjs 系):
|
|
10
|
+
* 网络类错误(DNS/超时/连接)扣分 ×0.2(这些站点在受限网络下常误报)
|
|
11
|
+
*
|
|
12
|
+
* 检查对象:md 文档里的 http(s) 链接;去重后并发探测(默认并发 10、超时 5s,
|
|
13
|
+
* 100 链接 ≤30 秒)。断网/无网络时全部判为网络类错误 → 只降级 warning,不拦提交。
|
|
14
|
+
*/
|
|
15
|
+
export const LINK_SEVERITY_SCORE = { dead: -3, dns: -2, transient: -1, ok: 0 };
|
|
16
|
+
|
|
17
|
+
/** flaky 域名后缀(网络错误扣分打折 ×0.2)。 */
|
|
18
|
+
export const FLAKY_HOSTS = [
|
|
19
|
+
'github.com', 'api.github.com', 'raw.githubusercontent.com', 'objects.githubusercontent.com',
|
|
20
|
+
'codeload.github.com', 'npmjs.com', 'registry.npmjs.org', 'npm.im',
|
|
21
|
+
];
|
|
22
|
+
|
|
23
|
+
/** 大扣分状态码(链接确实失效)。 */
|
|
24
|
+
export const DEAD_STATUSES = [404, 403, 410, 451];
|
|
25
|
+
|
|
26
|
+
/** 小扣分状态码(服务端临时故障)。 */
|
|
27
|
+
export const TRANSIENT_STATUSES = [408, 425, 429, 500, 502, 503, 504];
|
|
28
|
+
|
|
29
|
+
/** 默认检查参数(可被调用方 opts 覆盖)。 */
|
|
30
|
+
const DEFAULT_CONCURRENCY = 10;
|
|
31
|
+
const DEFAULT_TIMEOUT_MS = 5000;
|
|
32
|
+
const DEFAULT_MAX_LINKS = 200;
|
|
33
|
+
export const DEFAULT_OPTS = { concurrency: DEFAULT_CONCURRENCY, timeoutMs: DEFAULT_TIMEOUT_MS, maxLinks: DEFAULT_MAX_LINKS };
|
|
34
|
+
|
|
35
|
+
/** flaky 主机(网络抖动)的严重度折扣系数:临时故障在 flaky 域名上进一步打折。 */
|
|
36
|
+
const FLAKY_SCORE_DISCOUNT = 0.2;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 判定主机是否 flaky(网络错误打折)。
|
|
40
|
+
* @param {string} host 主机名(可含端口)
|
|
41
|
+
* @returns {boolean}
|
|
42
|
+
*/
|
|
43
|
+
export function isFlakyHost(host = '') {
|
|
44
|
+
const hostNorm = String(host).toLowerCase().split(':')[0].replace(/^www\./, '');
|
|
45
|
+
return FLAKY_HOSTS.some((f) => hostNorm === f || hostNorm.endsWith('.' + f));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* 从文本提取 http(s) 链接(去重、去尾部标点、跳过锚点/占位符)。
|
|
50
|
+
* @param {string} text 文件全文
|
|
51
|
+
* @returns {Array<{url: string, line: number}>}
|
|
52
|
+
*/
|
|
53
|
+
export function extractLinks(text = '') {
|
|
54
|
+
const out = [];
|
|
55
|
+
const seen = new Set();
|
|
56
|
+
const lines = String(text).split('\n');
|
|
57
|
+
for (let i = 0; i < lines.length; i++) {
|
|
58
|
+
for (const match of lines[i].matchAll(/https?:\/\/[^\s)\]}"'`<>,。;]+/g)) {
|
|
59
|
+
let url = match[0].replace(/[.,;:!?)]+$/, '');
|
|
60
|
+
if (/[<>{}$]/.test(url)) continue; // 占位符/模板链接跳过
|
|
61
|
+
if (seen.has(url)) continue;
|
|
62
|
+
seen.add(url);
|
|
63
|
+
out.push({ url, line: i + 1 });
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* 按探测结果分级(纯函数,便于单测)。
|
|
71
|
+
* @param {object} r { status?, error?: 'dns'|'timeout'|'conn'|'other' }
|
|
72
|
+
* @param {string} url 原始 URL(用于 flaky 判定)
|
|
73
|
+
* @returns {{level: 'ok'|'dead'|'dns'|'transient', score: number, reason: string, flaky: boolean}}
|
|
74
|
+
*/
|
|
75
|
+
export function gradeResult(url = '', r = {}) {
|
|
76
|
+
let host = '';
|
|
77
|
+
try { host = new URL(url).hostname; } catch { host = ''; }
|
|
78
|
+
const flaky = isFlakyHost(host);
|
|
79
|
+
const status = Number(r.status || 0);
|
|
80
|
+
if (status >= 200 && status < 400) {
|
|
81
|
+
return { level: 'ok', score: 0, reason: `HTTP ${status}`, flaky };
|
|
82
|
+
}
|
|
83
|
+
if (DEAD_STATUSES.includes(status)) {
|
|
84
|
+
return { level: 'dead', score: LINK_SEVERITY_SCORE.dead, reason: `HTTP ${status}(链接已失效)`, flaky };
|
|
85
|
+
}
|
|
86
|
+
if (TRANSIENT_STATUSES.includes(status)) {
|
|
87
|
+
// 5xx/429 属"服务端临时故障":flaky 域名打折
|
|
88
|
+
const base = LINK_SEVERITY_SCORE.transient;
|
|
89
|
+
const score = flaky ? Number((base * FLAKY_SCORE_DISCOUNT).toFixed(2)) : base;
|
|
90
|
+
return { level: 'transient', score, reason: `HTTP ${status}(服务端临时故障)`, flaky };
|
|
91
|
+
}
|
|
92
|
+
if (status >= 400) {
|
|
93
|
+
const score = flaky ? Number((LINK_SEVERITY_SCORE.dead * FLAKY_SCORE_DISCOUNT).toFixed(2)) : LINK_SEVERITY_SCORE.dead;
|
|
94
|
+
return { level: 'dead', score, reason: `HTTP ${status}`, flaky };
|
|
95
|
+
}
|
|
96
|
+
// 无状态码 → 网络类错误
|
|
97
|
+
const kind = r.error || 'other';
|
|
98
|
+
const base = kind === 'dns' ? LINK_SEVERITY_SCORE.dns
|
|
99
|
+
: (kind === 'timeout' || kind === 'conn') ? LINK_SEVERITY_SCORE.transient
|
|
100
|
+
: LINK_SEVERITY_SCORE.transient;
|
|
101
|
+
const score = flaky ? Number((base * FLAKY_SCORE_DISCOUNT).toFixed(2)) : base;
|
|
102
|
+
const level = kind === 'dns' ? 'dns' : 'transient';
|
|
103
|
+
return { level, score, reason: kind === 'dns' ? 'DNS 解析失败' : kind === 'timeout' ? '请求超时' : '连接失败', flaky };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* 单链接探测(可注入 fetcher 单测;真实实现用 globalThis.fetch + AbortSignal.timeout)。
|
|
108
|
+
* @param {string} url
|
|
109
|
+
* @param {object} [opts] { timeoutMs, fetcher }
|
|
110
|
+
* @returns {Promise<object>} gradeResult 输出 + url/status/error
|
|
111
|
+
*/
|
|
112
|
+
export async function probeLink(url, { timeoutMs = DEFAULT_OPTS.timeoutMs, fetcher } = {}) {
|
|
113
|
+
const fetchImpl = fetcher || globalThis.fetch;
|
|
114
|
+
if (typeof fetchImpl !== 'function') {
|
|
115
|
+
return { url, status: 0, error: 'other', ...gradeResult(url, { error: 'other' }) };
|
|
116
|
+
}
|
|
117
|
+
try {
|
|
118
|
+
const headResp = await fetchImpl(url, { method: 'HEAD', redirect: 'follow', signal: AbortSignal.timeout(timeoutMs) });
|
|
119
|
+
return { url, status: headResp.status, ...gradeResult(url, { status: headResp.status }) };
|
|
120
|
+
} catch (e) {
|
|
121
|
+
const msg = String(e?.message || e).toLowerCase();
|
|
122
|
+
const name = String(e?.name || '');
|
|
123
|
+
const error = /timeout|abort|timed out/.test(msg) || name === 'TimeoutError' ? 'timeout'
|
|
124
|
+
: /enotfound|dns|getaddrinfo/.test(msg) ? 'dns'
|
|
125
|
+
: /econnrefused|econnreset|fetch failed|network/.test(msg) ? 'conn'
|
|
126
|
+
: 'other';
|
|
127
|
+
return { url, status: 0, error, ...gradeResult(url, { error }) };
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* 批量探测(并发受限),保持输入顺序返回。
|
|
133
|
+
* @param {Array<{url:string,line:number}>} links
|
|
134
|
+
* @param {object} [opts] { concurrency, timeoutMs, fetcher }
|
|
135
|
+
* @returns {Promise<Array<object>>}
|
|
136
|
+
*/
|
|
137
|
+
export async function probeLinks(links = [], { concurrency = DEFAULT_OPTS.concurrency, timeoutMs = DEFAULT_OPTS.timeoutMs, fetcher } = {}) {
|
|
138
|
+
const results = new Array(links.length);
|
|
139
|
+
let next = 0;
|
|
140
|
+
const workers = new Array(Math.max(1, Math.min(concurrency, links.length || 1))).fill(0).map(async () => {
|
|
141
|
+
for (;;) {
|
|
142
|
+
const i = next++;
|
|
143
|
+
if (i >= links.length) return;
|
|
144
|
+
const linkEntry = links[i];
|
|
145
|
+
const r = await probeLink(linkEntry.url, { timeoutMs, fetcher });
|
|
146
|
+
results[i] = { ...r, line: linkEntry.line };
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
await Promise.all(workers);
|
|
150
|
+
return results.filter(Boolean);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* 检查文本中的链接 → 统一问题对象(只 warning/notice,永不 blocker)。
|
|
155
|
+
* @param {object} p { file, text, fetcher, concurrency, timeoutMs, maxLinks }
|
|
156
|
+
* @returns {Promise<Array>} findings
|
|
157
|
+
*/
|
|
158
|
+
export async function checkLinks({ file = '', text = '', fetcher, concurrency, timeoutMs, maxLinks = DEFAULT_OPTS.maxLinks } = {}) {
|
|
159
|
+
let links = extractLinks(text);
|
|
160
|
+
if (links.length > maxLinks) links = links.slice(0, maxLinks);
|
|
161
|
+
if (links.length === 0) return [];
|
|
162
|
+
const probed = await probeLinks(links, { concurrency, timeoutMs, fetcher });
|
|
163
|
+
const findings = [];
|
|
164
|
+
for (const r of probed) {
|
|
165
|
+
if (r.level === 'ok') continue;
|
|
166
|
+
findings.push({
|
|
167
|
+
file,
|
|
168
|
+
line: r.line,
|
|
169
|
+
rule: 'link-check',
|
|
170
|
+
kind: 'link-check',
|
|
171
|
+
severity: 'warning', // 永不 blocker:网络不可靠不应拦提交
|
|
172
|
+
message: `链接检查:${r.reason}(扣分 ${Math.abs(r.score)}${r.flaky ? ',flaky 域名已打折' : ''})`,
|
|
173
|
+
dimensions: ['文档', '可维护性'],
|
|
174
|
+
exemptHint: 'dsh-skip-doc(文件头=整文件免链接检查)',
|
|
175
|
+
scoreImpact: Math.abs(r.score),
|
|
176
|
+
url: r.url,
|
|
177
|
+
linkLevel: r.level,
|
|
178
|
+
flaky: r.flaky,
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
return findings;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** 汇总扣分(评分总入口消费)。 */
|
|
185
|
+
export function sumLinkPenalty(findings = []) {
|
|
186
|
+
return Number(findings.reduce((n, f) => n + (f.scoreImpact || 0), 0).toFixed(2));
|
|
187
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* npm 账号状态快照(与 `lib/git/account-status.js` **完全对称**)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么要有快照:GitHub 账号那套是「离线读快照秒回 + 点按钮才在线校验」;
|
|
5
|
+
* npm 上一版是「每次打开都跑 npm whoami」✗ —— 联网慢、与 GitHub 不同源。
|
|
6
|
+
* 这里补齐对称结构:`readNpmAccountStatus`(离线)+ `writeNpmAccountStatus`(在线校验后落盘)。
|
|
7
|
+
* 落盘位置:凭据目录(0600)下的 `npm-account-status.json`,不写仓库、不含明文 token。
|
|
8
|
+
*/
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
|
|
11
|
+
import { credentialsDir } from '../core/credentials.js';
|
|
12
|
+
import { readJson, writeJsonAtomic } from '../core/atomic-json.js';
|
|
13
|
+
|
|
14
|
+
export const STATUS_FILE = 'npm-account-status.json';
|
|
15
|
+
|
|
16
|
+
/** 快照文件路径(凭据目录内)。 */
|
|
17
|
+
export function npmAccountStatusFile({ workspaceRoot = '' } = {}) {
|
|
18
|
+
return join(credentialsDir({ workspaceRoot }), STATUS_FILE);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** 离线读快照(不存在/损坏 ⇒ 空对象,不抛错)。 */
|
|
22
|
+
export function readNpmAccountStatus({ workspaceRoot = '' } = {}) {
|
|
23
|
+
try {
|
|
24
|
+
return readJson(npmAccountStatusFile({ workspaceRoot })) || {};
|
|
25
|
+
} catch {
|
|
26
|
+
return {};
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** 写快照(原子写 + 0600)。 */
|
|
31
|
+
export function writeNpmAccountStatus(status = {}, { workspaceRoot = '' } = {}) {
|
|
32
|
+
try {
|
|
33
|
+
return writeJsonAtomic(npmAccountStatusFile({ workspaceRoot }), { ...status, checkedAt: new Date().toISOString() }, { mode: 0o600 });
|
|
34
|
+
} catch (e) {
|
|
35
|
+
return { ok: false, error: String(e?.message || e) };
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 由在线校验结果构造快照对象(与 GitHub 的 `buildAccountStatus` 同构)。 */
|
|
40
|
+
export function buildNpmAccountStatus({ user = '', registry = '', ok = false, error = '' } = {}) {
|
|
41
|
+
return { ok: !!ok, user: user || '', registry: registry || '', error: error || '', checkedAt: new Date().toISOString() };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* 渲染账号块文本——与 GitHub 凭据块**同规格的逐行 ✅/⚠️**(前端直接塞进 `<pre class="dshgp_acctblock2">`)。
|
|
46
|
+
* @param {object} snap 快照
|
|
47
|
+
* @param {{configured:boolean, maskedToken:string, registry:string}} o 凭据文件真源 + registry
|
|
48
|
+
* @returns {string} 多行文本
|
|
49
|
+
*/
|
|
50
|
+
export function renderNpmAccountBlock(snap = {}, { configured = false, maskedToken = '', registry = '' } = {}) {
|
|
51
|
+
const reg = registry || snap.registry || '';
|
|
52
|
+
const at = snap.checkedAt ? String(snap.checkedAt).slice(0, 16).replace('T', ' ') : '';
|
|
53
|
+
if (!configured) {
|
|
54
|
+
return ['⚠️ 未配置 npm token', `⚠️ registry:${reg}`, '⚠️ 到「设置 → 凭据与密钥」填写 npm token 后即可显示登录态'].join('\n');
|
|
55
|
+
}
|
|
56
|
+
if (snap.ok && snap.user) {
|
|
57
|
+
return [
|
|
58
|
+
'✅ 凭据可用',
|
|
59
|
+
`✅ npm token:${snap.user}${maskedToken ? `(${maskedToken})` : ''}|registry ${reg}`,
|
|
60
|
+
`✅ 登录态:npm whoami 通过${at ? `|校验于 ${at}` : ''}`,
|
|
61
|
+
].join('\n');
|
|
62
|
+
}
|
|
63
|
+
return ['⚠️ npm token 已配置,尚未通过校验', `⚠️ registry:${reg}`, `⚠️ ${snap.error || '点「刷新」做一次在线校验'}`].join('\n');
|
|
64
|
+
}
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* npm 安装编排(Step 3):校验 → 加锁 → 调 npm install → 回执 + 日志留痕。
|
|
3
|
+
*
|
|
4
|
+
* 安全默认(用户确认方案时定):**默认加 `--ignore-scripts`**(装包会执行 postinstall 任意代码),
|
|
5
|
+
* UI 必须显式勾选才关闭;默认**不全局**(避免污染宿主 node 环境),全局需显式勾选;
|
|
6
|
+
* registry 与凭据一律走我们自己的 npmrc(--userconfig),不碰用户全局配置。
|
|
7
|
+
*/
|
|
8
|
+
import { appendFileSync } from 'node:fs';
|
|
9
|
+
import { existsSync, statSync } from 'node:fs';
|
|
10
|
+
import { spawn } from 'node:child_process';
|
|
11
|
+
import { join } from 'node:path';
|
|
12
|
+
|
|
13
|
+
import { credentialsDir } from '../core/credentials.js';
|
|
14
|
+
import { DEFAULT_REGISTRY, NPM_TIMEOUT_MS, normalizeRegistry, resolveNpmBin, runNpm } from './registry.js';
|
|
15
|
+
import { npmArgs, writeNpmrc } from './npmrc.js';
|
|
16
|
+
|
|
17
|
+
export const INSTALL_LOG_FILE = 'npm-install.log';
|
|
18
|
+
export const INSTALL_TIMEOUT_MS = 300_000; // 装包比只读探测慢得多(默认 5 分钟;可传参覆盖)
|
|
19
|
+
|
|
20
|
+
/** 进行中的安装键集合(同一目标 + 同名包集合 ⇒ 视为同一个任务,避免并发重入)。 */
|
|
21
|
+
const inFlight = new Set();
|
|
22
|
+
|
|
23
|
+
/** 供测试/UI 查询:当前是否有安装在跑(返回键列表)。 */
|
|
24
|
+
export function installingKeys() {
|
|
25
|
+
return [...inFlight];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** 包名校验(纯函数):允许 scope 与 @tag/@version;拒绝空、空白、以 - 开头(防选项注入)、路径穿越。 */
|
|
29
|
+
export function validatePackageNames(names = []) {
|
|
30
|
+
const list = (Array.isArray(names) ? names : String(names || '').split(/[\s,]+/)).map((s) => String(s).trim()).filter(Boolean);
|
|
31
|
+
if (!list.length) return { ok: false, error: '未指定包名' };
|
|
32
|
+
const NAME_RE = /^(?:@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*(?:@[^\s/]+)?$/i;
|
|
33
|
+
for (const n of list) {
|
|
34
|
+
if (n.startsWith('-')) return { ok: false, error: `包名不能以 - 开头(防选项注入):${n}` };
|
|
35
|
+
if (n.includes('..') || n.includes('/../')) return { ok: false, error: `包名含路径穿越:${n}` };
|
|
36
|
+
if (!NAME_RE.test(n)) return { ok: false, error: `包名不合法:${n}` };
|
|
37
|
+
}
|
|
38
|
+
return { ok: true, names: list };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 目标目录校验(纯函数 + 一次 stat):必须存在且是目录。 */
|
|
42
|
+
export function validateDest(dest = '') {
|
|
43
|
+
const d = String(dest || '').trim();
|
|
44
|
+
if (!d) return { ok: false, error: '未指定安装目录' };
|
|
45
|
+
try {
|
|
46
|
+
if (!existsSync(d)) return { ok: false, error: `目录不存在:${d}` };
|
|
47
|
+
if (!statSync(d).isDirectory()) return { ok: false, error: `不是目录:${d}` };
|
|
48
|
+
} catch (e) {
|
|
49
|
+
return { ok: false, error: String(e?.message || e) };
|
|
50
|
+
}
|
|
51
|
+
return { ok: true, dest: d };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** 拼 npm install 参数(纯函数,便于测试断言安全默认值)。 */
|
|
55
|
+
export function buildInstallArgs({ names = [], global = false, dest = '', ignoreScripts = true } = {}) {
|
|
56
|
+
const args = ['install', ...names, '--no-audit', '--no-fund'];
|
|
57
|
+
if (ignoreScripts) args.push('--ignore-scripts'); // 安全默认:不执行 postinstall
|
|
58
|
+
if (global) args.push('-g');
|
|
59
|
+
else if (dest) args.push('--prefix', dest);
|
|
60
|
+
return args;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** 追加安装日志(0600 目录内,留痕不落库)。 */
|
|
64
|
+
function appendInstallLog(line, { workspaceRoot = '' } = {}) {
|
|
65
|
+
try {
|
|
66
|
+
const file = join(credentialsDir({ workspaceRoot }), INSTALL_LOG_FILE);
|
|
67
|
+
appendFileSync(file, `${new Date().toISOString()} ${line}\n`, { mode: 0o600 });
|
|
68
|
+
return file;
|
|
69
|
+
} catch {
|
|
70
|
+
return '';
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* 安装一个或多个包。
|
|
76
|
+
* @param {object} o { names, dest, global, ignoreScripts, registry, workspaceRoot, timeoutMs }
|
|
77
|
+
* @returns {{ok:boolean, code?:number, names?:string[], dest?:string, global?:boolean, ignoreScripts?:boolean,
|
|
78
|
+
* stdout?:string, stderr?:string, logPath?:string, error?:string}}
|
|
79
|
+
*/
|
|
80
|
+
export function installPackages({
|
|
81
|
+
names = [], dest = '', global = false, ignoreScripts = true,
|
|
82
|
+
registry = DEFAULT_REGISTRY, workspaceRoot = '', timeoutMs = INSTALL_TIMEOUT_MS, env = {},
|
|
83
|
+
} = {}) {
|
|
84
|
+
const v = validatePackageNames(names);
|
|
85
|
+
if (!v.ok) return { ok: false, error: v.error };
|
|
86
|
+
if (!global) {
|
|
87
|
+
const d = validateDest(dest);
|
|
88
|
+
if (!d.ok) return { ok: false, error: d.error };
|
|
89
|
+
}
|
|
90
|
+
const reg = normalizeRegistry(registry);
|
|
91
|
+
const key = `${global ? 'global' : dest}|${v.names.slice().sort().join(',')}`;
|
|
92
|
+
if (inFlight.has(key)) return { ok: false, error: `同一目标正在安装中:${v.names.join(', ')}` };
|
|
93
|
+
|
|
94
|
+
inFlight.add(key);
|
|
95
|
+
try {
|
|
96
|
+
const rc = writeNpmrc({ workspaceRoot, registry: reg });
|
|
97
|
+
if (!rc.ok) return { ok: false, error: rc.error || 'npmrc 写入失败' };
|
|
98
|
+
const args = [...npmArgs({ npmrcFile: rc.file, registry: reg }),
|
|
99
|
+
...buildInstallArgs({ names: v.names, global, dest, ignoreScripts })];
|
|
100
|
+
const logPath = appendInstallLog(`install START names=${v.names.join(',')} global=${global} ignoreScripts=${ignoreScripts} dest=${global ? '(global)' : dest}`, { workspaceRoot });
|
|
101
|
+
const r = runNpm(args, { timeoutMs, env: { NO_UPDATE_NOTIFIER: '1', ...env } });
|
|
102
|
+
appendInstallLog(`install END ok=${r.ok} code=${r.code} err=${(r.error || '').slice(0, 200)}`, { workspaceRoot });
|
|
103
|
+
return {
|
|
104
|
+
ok: !!r.ok,
|
|
105
|
+
code: r.code,
|
|
106
|
+
names: v.names,
|
|
107
|
+
dest: global ? '' : dest,
|
|
108
|
+
global: !!global,
|
|
109
|
+
ignoreScripts: !!ignoreScripts,
|
|
110
|
+
stdout: String(r.stdout || '').slice(-4000),
|
|
111
|
+
stderr: String(r.stderr || '').slice(-4000),
|
|
112
|
+
logPath,
|
|
113
|
+
error: r.ok ? '' : (r.error || 'npm install 失败'),
|
|
114
|
+
};
|
|
115
|
+
} finally {
|
|
116
|
+
inFlight.delete(key);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** 当前可用的 npm 超时(导出便于 UI/测试引用同一常量)。 */
|
|
121
|
+
export { NPM_TIMEOUT_MS };
|
|
122
|
+
|
|
123
|
+
/* ═══════════ 异步安装 + 进度(照 GitHub 克隆的进度模型:后台跑 + 前端轮询取进度/终态)═══════════ */
|
|
124
|
+
|
|
125
|
+
/** 进行中的异步安装状态(内存单例:同一时刻只跟一个,避免输出串台)。 */
|
|
126
|
+
let asyncInstall = null;
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* 启动异步安装(spawn,不阻塞事件循环 ⇒ 前端可以边跑边轮询进度)。
|
|
130
|
+
* 与 `installPackages`(同步版,工具/CLI 用)并存:HTTP/UI 走本函数,工具走同步版。
|
|
131
|
+
* @returns {{ok:boolean, started?:boolean, name?:string, logPath?:string, error?:string, hint?:string}}
|
|
132
|
+
*/
|
|
133
|
+
export function startInstall({
|
|
134
|
+
names = [], dest = '', global = false, ignoreScripts = true,
|
|
135
|
+
registry = DEFAULT_REGISTRY, workspaceRoot = '', timeoutMs = INSTALL_TIMEOUT_MS,
|
|
136
|
+
} = {}) {
|
|
137
|
+
const v = validatePackageNames(names);
|
|
138
|
+
if (!v.ok) return { ok: false, error: v.error };
|
|
139
|
+
if (!global) {
|
|
140
|
+
const d = validateDest(dest);
|
|
141
|
+
if (!d.ok) return { ok: false, error: d.error };
|
|
142
|
+
}
|
|
143
|
+
if (asyncInstall && asyncInstall.state === 'running') {
|
|
144
|
+
return { ok: false, error: `已有安装在运行:${asyncInstall.name}(可先用 /npm-install-progress 看进度)` };
|
|
145
|
+
}
|
|
146
|
+
const reg = normalizeRegistry(registry);
|
|
147
|
+
const rc = writeNpmrc({ workspaceRoot, registry: reg });
|
|
148
|
+
if (!rc.ok) return { ok: false, error: rc.error || 'npmrc 写入失败' };
|
|
149
|
+
const args = [
|
|
150
|
+
...npmArgs({ npmrcFile: rc.file, registry: reg }),
|
|
151
|
+
...buildInstallArgs({ names: v.names, global, dest, ignoreScripts }),
|
|
152
|
+
];
|
|
153
|
+
const bin = resolveNpmBin({ env: process.env });
|
|
154
|
+
const logPath = appendInstallLog(`install(async) START names=${v.names.join(',')} global=${global} dest=${global ? '(global)' : dest} ignoreScripts=${ignoreScripts}`, { workspaceRoot });
|
|
155
|
+
let child;
|
|
156
|
+
try {
|
|
157
|
+
child = spawn(bin, args, { env: { ...process.env, NO_UPDATE_NOTIFIER: '1' }, cwd: global ? undefined : dest });
|
|
158
|
+
} catch (e) {
|
|
159
|
+
return { ok: false, error: String(e?.message || e) };
|
|
160
|
+
}
|
|
161
|
+
asyncInstall = {
|
|
162
|
+
name: v.names.join(', '), dest, global: !!global, ignoreScripts: !!ignoreScripts,
|
|
163
|
+
startedAt: Date.now(), state: 'running', lines: [], code: null, error: '', logPath,
|
|
164
|
+
};
|
|
165
|
+
const push = (buf) => {
|
|
166
|
+
for (const raw of String(buf).split('\n')) {
|
|
167
|
+
const t = raw.trim();
|
|
168
|
+
if (!t) continue;
|
|
169
|
+
asyncInstall.lines.push(t);
|
|
170
|
+
if (asyncInstall.lines.length > 300) asyncInstall.lines.shift(); // 环形缓冲,防长输出吃内存
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
child.stdout?.on('data', push);
|
|
174
|
+
child.stderr?.on('data', push);
|
|
175
|
+
const timer = setTimeout(() => {
|
|
176
|
+
try { child.kill('SIGTERM'); } catch { /* 已退出 */ }
|
|
177
|
+
if (asyncInstall) { asyncInstall.state = 'timeout'; asyncInstall.error = `安装超时(${timeoutMs}ms)已终止`; }
|
|
178
|
+
}, timeoutMs);
|
|
179
|
+
child.on('close', (code) => {
|
|
180
|
+
clearTimeout(timer);
|
|
181
|
+
if (!asyncInstall || asyncInstall.state === 'timeout') return;
|
|
182
|
+
asyncInstall.state = code === 0 ? 'done' : 'failed';
|
|
183
|
+
asyncInstall.code = typeof code === 'number' ? code : -1;
|
|
184
|
+
if (code !== 0) asyncInstall.error = `npm install 退出码 ${code}`;
|
|
185
|
+
appendInstallLog(`install(async) END state=${asyncInstall.state} code=${asyncInstall.code}`, { workspaceRoot });
|
|
186
|
+
});
|
|
187
|
+
child.on('error', (e) => {
|
|
188
|
+
clearTimeout(timer);
|
|
189
|
+
if (!asyncInstall) return;
|
|
190
|
+
asyncInstall.state = 'failed';
|
|
191
|
+
asyncInstall.error = String(e?.message || e);
|
|
192
|
+
});
|
|
193
|
+
return { ok: true, started: true, name: asyncInstall.name, logPath, hint: '已开始安装;轮询 /api/git-push/npm-install-progress 取进度与终态(consume:true 取走后复位)' };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* 读取安装进度(对应 GitHub 克隆的 `/clone-progress`)。
|
|
198
|
+
* @param {{consume?:boolean}} o consume=true 且已到终态 ⇒ 返回后复位(下次为 idle)
|
|
199
|
+
*/
|
|
200
|
+
export function installProgress({ consume = false } = {}) {
|
|
201
|
+
if (!asyncInstall) return { ok: true, state: 'idle' };
|
|
202
|
+
const a = asyncInstall;
|
|
203
|
+
const progress = {
|
|
204
|
+
state: a.state, name: a.name, dest: a.dest, global: a.global, ignoreScripts: a.ignoreScripts,
|
|
205
|
+
startedAt: a.startedAt, elapsedMs: Date.now() - a.startedAt,
|
|
206
|
+
lines: a.lines.slice(-40), tail: a.lines.slice(-6).join('\n'),
|
|
207
|
+
code: a.code, error: a.error, logPath: a.logPath,
|
|
208
|
+
};
|
|
209
|
+
if (a.state !== 'running' && consume) asyncInstall = null;
|
|
210
|
+
return { ok: true, progress };
|
|
211
|
+
}
|