dsh-git-push 0.0.0-stage → 2.8.6
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 +1486 -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 +266 -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 +192 -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 +672 -0
- package/lib/app/tools.js +34 -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 +215 -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 +137 -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 +148 -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 +476 -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 +171 -0
- package/lib/npm/registry.js +168 -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 +196 -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/cpu-sample.mjs +188 -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,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP 处理层 · 克隆端点(repo-clone / clone-logs / clone-abort / clone-preview / clone-progress)
|
|
3
|
+
*
|
|
4
|
+
* 从 http-handlers.js 的 handleHttp 拆分而来。
|
|
5
|
+
* 统一签名:handleXxx(ctx) → { status, body };ctx = { req, query, body, env, cfg, path, method }。
|
|
6
|
+
*/
|
|
7
|
+
import {
|
|
8
|
+
startCloneJob, updateCloneJob, finishCloneJob, setCloneJobPhase,
|
|
9
|
+
cloneJobStatus, clearCloneJobResult, getPreview, setPreview, cloneLog, cloneLogs, abortCloneJob,
|
|
10
|
+
snapshot,
|
|
11
|
+
} from '../../git/clone-jobs.js';
|
|
12
|
+
import { resolveToken, cloneViaApi, previewClone, parseGithubOwnerRepo, resolveMaxCloneFileMB, isPartialCloneDir } from '../../git/index.js';
|
|
13
|
+
import { join } from 'node:path';
|
|
14
|
+
|
|
15
|
+
/* ───────── 克隆端点常量 ───────── */
|
|
16
|
+
const JOB_ID_RADIX = 36; // clone 任务 id 的 36 进制(短 id)
|
|
17
|
+
const LOG_LIMIT_DEFAULT = 200; // clone-logs 默认条数上限
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* 校验并解析 repo-clone 入参 → { error } 或 { target, dir, pr, dest }。
|
|
21
|
+
* 抽成 helper 是为了把分支从 handleRepoClone 挪走(圈复杂度治理)。
|
|
22
|
+
*/
|
|
23
|
+
function parseCloneRequest(body) {
|
|
24
|
+
const target = String(body.target || '').trim();
|
|
25
|
+
const dir = String(body.dir || '').trim();
|
|
26
|
+
if (!target) return { error: { status: 400, body: { ok: false, error: '缺少 target(owner/repo 或 GitHub URL)' } } };
|
|
27
|
+
if (!dir) return { error: { status: 400, body: { ok: false, error: '缺少目标目录 dir(先用目录选择器选父目录)' } } };
|
|
28
|
+
const pr = parseGithubOwnerRepo(target);
|
|
29
|
+
if (!pr) return { error: { status: 400, body: { ok: false, error: `无法解析 target(${target}):需要 owner/repo 或 GitHub URL` } } };
|
|
30
|
+
return { target, dir, pr, dest: join(dir, pr.repo) };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 全局占用互斥:已有任何克隆在跑就返回 409 响应,否则 null。
|
|
35
|
+
* 用**全局** snapshot(任何克隆在跑都算占用)而不是 isCloneInFlight(dest)——
|
|
36
|
+
* 后者只判「同一 dest」,换个目录就绕过了互斥(实测被 test-clone-concurrency 抓出)。
|
|
37
|
+
*/
|
|
38
|
+
function busyResponse(target, dest) {
|
|
39
|
+
const runningJob = snapshot();
|
|
40
|
+
if (!runningJob) return null;
|
|
41
|
+
cloneLog('refuse', { target, dest, reason: 'another-clone-running', runningDest: runningJob.dest });
|
|
42
|
+
return {
|
|
43
|
+
status: 409,
|
|
44
|
+
body: {
|
|
45
|
+
ok: false,
|
|
46
|
+
cause: 'busy',
|
|
47
|
+
retriable: false,
|
|
48
|
+
error: `已有克隆正在进行(${runningJob.dest || '未知目录'})——请等它结束再试,`
|
|
49
|
+
+ '避免两个克隆同时写同一目录。',
|
|
50
|
+
running: runningJob,
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** POST /api/git-push/repo-clone —— 手动克隆(后台 job)。 */
|
|
56
|
+
export async function handleRepoClone(ctx) {
|
|
57
|
+
const { body, env } = ctx;
|
|
58
|
+
const parsed = parseCloneRequest(body);
|
|
59
|
+
if (parsed.error) return parsed.error;
|
|
60
|
+
const { target, dest } = parsed;
|
|
61
|
+
const cfg = env.cfg || {};
|
|
62
|
+
// 「占用中」互斥必须在预览之前判:previewClone 要联网(查仓库 meta + 拉 tree),
|
|
63
|
+
// 限流/网络异常时会先返回 400,让 409 busy 永远走不到——实测 test-clone-concurrency
|
|
64
|
+
// 期望 409、实际 400(403 限流抢先)。先判占用既省一次网络,也让互斥语义与网络状态无关。
|
|
65
|
+
const busy = busyResponse(target, dest);
|
|
66
|
+
if (busy) return busy;
|
|
67
|
+
// 体积上限统一解析(与工具路径共用同一默认值——此前这里回落 10、工具路径回落 50,
|
|
68
|
+
// 导致同一仓库两个入口克隆结果不同,>10MB 的文件在 HTTP 路径被静默跳过)
|
|
69
|
+
const maxFileMB = resolveMaxCloneFileMB(cfg);
|
|
70
|
+
const concurrency = Number.isFinite(cfg.cloneConcurrency) ? cfg.cloneConcurrency : 6;
|
|
71
|
+
const pre = await previewClone({ target, token: resolveToken({ workspaceRoot: env.workspaceRoot }).token, maxFileMB });
|
|
72
|
+
if (!pre.ok) return { status: 400, body: pre };
|
|
73
|
+
const started = startCloneJob({ target, dest, totalFiles: pre.downloadCount, totalBytes: pre.downloadBytes });
|
|
74
|
+
if (!started.ok) {
|
|
75
|
+
cloneLog('reject-busy', { target, dest, runningDest: started.running?.dest });
|
|
76
|
+
return {
|
|
77
|
+
status: 409,
|
|
78
|
+
body: {
|
|
79
|
+
ok: false,
|
|
80
|
+
cause: 'busy',
|
|
81
|
+
retriable: false,
|
|
82
|
+
error: `已有克隆正在进行(${started.running?.dest || '未知目录'})——请等它结束再试,`
|
|
83
|
+
+ '避免两个克隆同时写同一目录。',
|
|
84
|
+
running: started.running || null,
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
const jobId = 'clone-' + Date.now().toString(JOB_ID_RADIX);
|
|
89
|
+
(async () => {
|
|
90
|
+
let r;
|
|
91
|
+
try {
|
|
92
|
+
r = await cloneViaApi({
|
|
93
|
+
target, dest,
|
|
94
|
+
// 真实历史模式:**默认开**(只读访问默认走 gh-proxy 镜像,取原始对象已足够快;
|
|
95
|
+
// 带真实历史的克隆可推回远端、可 git log 读演进)。显式传 history=false/0 退回整树快照。
|
|
96
|
+
history: body?.history === undefined ? true
|
|
97
|
+
: !(body.history === false || body.history === 0 || body.history === '0' || body.history === 'false'),
|
|
98
|
+
historyDepth: Number(body?.historyDepth) > 0 ? Number(body.historyDepth) : undefined,
|
|
99
|
+
// 前端在「发现不完整克隆」弹窗里选「重来」时传 restart:true —— 服务端据此清掉分片、从零重下;
|
|
100
|
+
// 不传即默认续传(保留已下文件与断点)。
|
|
101
|
+
restart: body?.restart === true,
|
|
102
|
+
token: resolveToken({ workspaceRoot: env.workspaceRoot }).token,
|
|
103
|
+
maxFileMB, concurrency,
|
|
104
|
+
onProgress: (p) => updateCloneJob(p),
|
|
105
|
+
});
|
|
106
|
+
} catch (e) {
|
|
107
|
+
cloneLog('clone-throw', { target, dest, error: e?.message || String(e) });
|
|
108
|
+
r = { ok: false, error: `克隆异常: ${e?.message || e}`, cause: 'unknown', retriable: true };
|
|
109
|
+
} finally {
|
|
110
|
+
setCloneJobPhase('done');
|
|
111
|
+
}
|
|
112
|
+
finishCloneJob(r);
|
|
113
|
+
})().catch((e) => {
|
|
114
|
+
cloneLog('clone-bg-throw', { target, dest, error: e?.message || String(e) });
|
|
115
|
+
try { setCloneJobPhase('done'); } catch { /* 忽略 */ }
|
|
116
|
+
try { finishCloneJob({ ok: false, error: `克隆后台异常: ${e?.message || e}`, cause: 'unknown', retriable: true }); } catch { /* 忽略 */ }
|
|
117
|
+
});
|
|
118
|
+
return {
|
|
119
|
+
status: 202,
|
|
120
|
+
body: {
|
|
121
|
+
ok: true, async: true, jobId, target, dest,
|
|
122
|
+
totalFiles: pre.downloadCount, totalBytes: pre.downloadBytes,
|
|
123
|
+
hint: '克隆已在后台运行,轮询 /clone-progress 取进度与终态',
|
|
124
|
+
},
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** GET|POST /api/git-push/clone-logs —— 克隆结构化日志。 */
|
|
129
|
+
export function handleCloneLogs(ctx) {
|
|
130
|
+
const { body } = ctx;
|
|
131
|
+
const limit = Number.isFinite(body.limit) ? body.limit : LOG_LIMIT_DEFAULT;
|
|
132
|
+
return { status: 200, body: { ok: true, logs: cloneLogs(limit) } };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** POST /api/git-push/clone-abort —— 手动中止当前克隆。 */
|
|
136
|
+
export function handleCloneAbort() {
|
|
137
|
+
const aborted = abortCloneJob('manual');
|
|
138
|
+
return { status: 200, body: { ok: true, aborted } };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** POST /api/git-push/clone-preview —— 克隆前预览(下载量/超大文件)。 */
|
|
142
|
+
export async function handleClonePreview(ctx) {
|
|
143
|
+
const { body, env } = ctx;
|
|
144
|
+
const target = String(body.target || '').trim();
|
|
145
|
+
if (!target) return { status: 400, body: { ok: false, error: '缺少 target(owner/repo 或 GitHub URL)' } };
|
|
146
|
+
// body 显式传值优先;否则与工具路径共用同一解析(默认值一致,避免两个入口结果不同)
|
|
147
|
+
const maxFileMB = Number.isFinite(body.maxFileMB) ? body.maxFileMB : resolveMaxCloneFileMB(env.cfg);
|
|
148
|
+
// 目标目录的**实时**「已存在且不完整」状态(前端据此弹「续传 / 重来」):
|
|
149
|
+
// 必须绕开下面的预览缓存——partial 由本地目录状态决定、随下载进度变化,
|
|
150
|
+
// 而缓存键只含 target|maxFileMB;若塞进缓存响应,用户下到一半再打开面板会看到过期状态。
|
|
151
|
+
// 判据直接复用 isPartialCloneDir(有标记 + HEAD 无效;用户自有目录绝不会被判为残留)。
|
|
152
|
+
const dir = String(body.dir || '').trim();
|
|
153
|
+
const partial = dir ? isPartialCloneDir(dir) : false;
|
|
154
|
+
const cacheKey = target + '|' + maxFileMB;
|
|
155
|
+
const cached = getPreview(cacheKey);
|
|
156
|
+
if (cached) return { status: 200, body: { ...cached, dir, partial } };
|
|
157
|
+
const r = await previewClone({ target, token: resolveToken({ workspaceRoot: env.workspaceRoot }).token, maxFileMB });
|
|
158
|
+
if (r.ok) setPreview(cacheKey, r);
|
|
159
|
+
return { status: r.ok ? 200 : 400, body: { ...r, dir, partial } };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** GET|POST /api/git-push/clone-progress —— 轮询克隆进度。 */
|
|
163
|
+
export function handleCloneProgress(ctx) {
|
|
164
|
+
const { body } = ctx;
|
|
165
|
+
const st = cloneJobStatus();
|
|
166
|
+
if (st.state === 'done' && body.consume) clearCloneJobResult();
|
|
167
|
+
return { status: 200, body: { ok: true, ...st } };
|
|
168
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP 处理层 · 共享常量(从 http-handlers.js 拆分:list 预算/探测并发/扫描等待)
|
|
3
|
+
*/
|
|
4
|
+
/** 本地列表 SSH live 探测整表共享预算(并发异步后为**上界**,超预算即跳过标 liveSkipped)。 */
|
|
5
|
+
export const LIST_LIVE_BUDGET_MS = 15_000;
|
|
6
|
+
/** 远端探测并发度。与 SSH 默认 MaxSessions 兼容,且不超过 GitHub 连接容忍度。 */
|
|
7
|
+
export const PROBE_CONCURRENCY = 4;
|
|
8
|
+
/** 本地扫描等待超时(毫秒)。 */
|
|
9
|
+
export const SCAN_WAIT_TIMEOUT_MS = 60_000;
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 工具/CLI 处理层 · git_identity_rewrite(提交身份历史改写)
|
|
3
|
+
*
|
|
4
|
+
* 三条面(工具 / CLI / 后续 HTTP)共用同一份实现:真正的识别→改写→自检→安全强推在
|
|
5
|
+
* lib/git/identity-rewrite.js,本文件只做参数归一化 + 「只处理本人远端仓库」的过滤 + 报告文本。
|
|
6
|
+
*
|
|
7
|
+
* 默认 dryRun(只报告,不写任何东西);要真改写必须显式 dryRun:false 或 write:true;
|
|
8
|
+
* push 再叠加一层(默认 false,改写自检通过后才 force-with-lease 推)。
|
|
9
|
+
*/
|
|
10
|
+
import { runGit } from '../../git/exec.js';
|
|
11
|
+
import { scanRepos } from '../../git/repos.js';
|
|
12
|
+
import { readAccountStatus, refreshAccountStatus } from '../../git/account-status.js';
|
|
13
|
+
import { resolveCommitIdentity } from '../../git/identity.js';
|
|
14
|
+
import { buildWrappedGitEnv } from '../../git/wrapped-git.js';
|
|
15
|
+
import { formatIdentityRewriteReport, parseGithubRepo, rewriteIdentities, wrongIdentityEmails } from '../../git/identity-rewrite.js';
|
|
16
|
+
import { getDefaultScanRoot } from '../scan-root.js';
|
|
17
|
+
|
|
18
|
+
/** 布尔归一化(工具层可能传 true/false 字符串;CLI 传 --write/--push)。 */
|
|
19
|
+
function bool(v) {
|
|
20
|
+
return v === true || v === 'true' || v === 1 || v === '1';
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* @param {object} args `{ paths?, root?, dryRun?, write?, push?, extraEmails? }`
|
|
25
|
+
* @param {object} env 运行环境 `{ workspaceRoot, extraRepos?, extraReposFile? }`
|
|
26
|
+
* @param {object} cfg 插件配置
|
|
27
|
+
*/
|
|
28
|
+
export async function callIdentityRewrite(args = {}, env = {}, cfg = {}) {
|
|
29
|
+
const workspaceRoot = env.workspaceRoot || '';
|
|
30
|
+
let st = readAccountStatus({ workspaceRoot });
|
|
31
|
+
// 老快照可能没存数字 id(拼 noreply 邮箱要用 `<id>+<login>@…`):刷一次账号状态补齐(约 1~4s,一次性)。
|
|
32
|
+
if (st?.token?.valid && !st.token.id) {
|
|
33
|
+
try { await refreshAccountStatus({ workspaceRoot }); } catch { /* 刷新失败就用现有信息,下面按 id 缺失处理 */ }
|
|
34
|
+
st = readAccountStatus({ workspaceRoot });
|
|
35
|
+
}
|
|
36
|
+
const account = st?.token?.valid
|
|
37
|
+
? { login: st.token.login || st.username || '', id: st.token.id || '' }
|
|
38
|
+
: null;
|
|
39
|
+
if (!account?.login) {
|
|
40
|
+
return {
|
|
41
|
+
ok: false,
|
|
42
|
+
error: '账号未登录/未探测到:先跑 git_account_check(需要登录账号作为规范身份,改写才有依据)',
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
const canonical = resolveCommitIdentity({ account });
|
|
46
|
+
const extra = String(args.extraEmails || cfg?.identityRewrite?.extraEmails || '')
|
|
47
|
+
.split(/[,\s]+/).filter(Boolean);
|
|
48
|
+
const wrongEmails = wrongIdentityEmails({ account, extra });
|
|
49
|
+
// 默认预演:dryRun 未显式给 false、且没开 write 时,一律只报告
|
|
50
|
+
const dryRun = !(args.dryRun === false || args.dryRun === 'false' || bool(args.write));
|
|
51
|
+
const push = bool(args.push);
|
|
52
|
+
|
|
53
|
+
let paths = String(args.paths || '').split(',').map((s) => s.trim()).filter(Boolean);
|
|
54
|
+
if (!paths.length) {
|
|
55
|
+
const root = args.root || getDefaultScanRoot(env, { defaultScanRoot: String(cfg.defaultScanRoot || '') });
|
|
56
|
+
paths = scanRepos(root, {
|
|
57
|
+
extraRepos: env.extraRepos || [],
|
|
58
|
+
extraReposFile: env.extraReposFile || '',
|
|
59
|
+
}).map((r) => r.path).filter(Boolean);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// 只处理 origin 属于登录账号的仓库(别人的仓库一个都不碰);其余如实报告跳过原因
|
|
63
|
+
const mine = [];
|
|
64
|
+
const notMine = [];
|
|
65
|
+
for (const p of paths) {
|
|
66
|
+
const url = String((runGit(['remote', 'get-url', 'origin'], { cwd: p }) || {}).stdout || '').trim();
|
|
67
|
+
const g = parseGithubRepo(url);
|
|
68
|
+
if (g && g.owner.toLowerCase() === account.login.toLowerCase()) mine.push(p);
|
|
69
|
+
else notMine.push({ repo: p, reason: url ? `origin 不属于 ${account.login}` : '无 origin 远端' });
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const summary = rewriteIdentities(mine, {
|
|
73
|
+
runGit,
|
|
74
|
+
canonical: { name: canonical.name, email: canonical.email },
|
|
75
|
+
wrongEmails,
|
|
76
|
+
dryRun,
|
|
77
|
+
push,
|
|
78
|
+
credEnv: buildWrappedGitEnv({ workspaceRoot }),
|
|
79
|
+
});
|
|
80
|
+
const text = formatIdentityRewriteReport(summary)
|
|
81
|
+
+ (notMine.length
|
|
82
|
+
? `\n跳过非本人远端仓库 ${notMine.length} 个:${notMine.map((x) => `${x.repo.split('/').pop()}(${x.reason})`).join('、')}`
|
|
83
|
+
: '');
|
|
84
|
+
return {
|
|
85
|
+
ok: true,
|
|
86
|
+
dryRun,
|
|
87
|
+
canonical: { name: canonical.name, email: canonical.email, source: canonical.source },
|
|
88
|
+
wrongEmails,
|
|
89
|
+
totals: summary.totals,
|
|
90
|
+
repos: summary.repos,
|
|
91
|
+
skippedNotMine: notMine,
|
|
92
|
+
text,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP 处理层 · 元信息/只读端点(status/scan/browse/tools/tool-probes/rule-slots/rule-detail/audit/toggle-rule)
|
|
3
|
+
*
|
|
4
|
+
* 从 http-handlers.js 的 handleHttp 巨型 switch 拆分而来。
|
|
5
|
+
* 统一签名:handleXxx(ctx) → { status, body };ctx = { req, query, body, env, cfg, path, method }。
|
|
6
|
+
*/
|
|
7
|
+
import { VERSION } from '../../self/index.js';
|
|
8
|
+
import { scanRepos, browseDir } from '../../git/index.js';
|
|
9
|
+
import { getDefaultScanRoot } from '../scan-root.js';
|
|
10
|
+
import { collectToolPaths } from '../../context/index.js';
|
|
11
|
+
import { redactConfig } from '../schema.js';
|
|
12
|
+
import { getLastSlotHitStats } from '../slot-stats.js';
|
|
13
|
+
import { listTools } from '../tools.js';
|
|
14
|
+
import { discoverRuleSlots, loadYamlRuleFile, resolveSlotOrder, setSlotDisabled, RULE_YAML_DIR } from '../../rule/loader.js';
|
|
15
|
+
import { name } from '../constants.js';
|
|
16
|
+
import { readAccountStatus } from '../../git/account-status.js';
|
|
17
|
+
import { identityHintText, resolveCommitIdentity } from '../../git/identity.js';
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* 当前提交身份(未配身份的仓库会用到的那个):登录账号可用 → 账号身份;
|
|
21
|
+
* 否则兜底 DSH Agent。供 UI 与 AI 查询「到底该用什么身份」。
|
|
22
|
+
*/
|
|
23
|
+
function currentCommitIdentity() {
|
|
24
|
+
const st = readAccountStatus();
|
|
25
|
+
const account = st?.token?.valid
|
|
26
|
+
? { login: st.token.login || st.username || '', id: st.token.id || '' }
|
|
27
|
+
: null;
|
|
28
|
+
const id = resolveCommitIdentity({ account });
|
|
29
|
+
return {
|
|
30
|
+
name: id.name,
|
|
31
|
+
email: id.email,
|
|
32
|
+
source: id.source,
|
|
33
|
+
label: `${id.name} <${id.email}>`,
|
|
34
|
+
hint: identityHintText(id),
|
|
35
|
+
account: account ? { login: account.login, id: account.id || '' } : null,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** GET /api/git-push/status —— 插件信息 + 脱敏配置(token/ssh 打码)+ 当前提交身份。 */
|
|
40
|
+
export function handleStatus(ctx) {
|
|
41
|
+
const { env, cfg } = ctx;
|
|
42
|
+
return {
|
|
43
|
+
status: 200,
|
|
44
|
+
body: {
|
|
45
|
+
ok: true,
|
|
46
|
+
plugin: name,
|
|
47
|
+
version: VERSION,
|
|
48
|
+
workspaceRoot: env.workspaceRoot,
|
|
49
|
+
config: redactConfig(cfg),
|
|
50
|
+
// 提交身份:让 AI/UI 明确「未配身份的仓库会用哪个身份提交」,免得自己猜
|
|
51
|
+
commitIdentity: currentCommitIdentity(),
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** GET /api/git-push/scan —— 本地仓库扫描清单。 */
|
|
57
|
+
export function handleScan(ctx) {
|
|
58
|
+
const { env } = ctx;
|
|
59
|
+
return { status: 200, body: { ok: true, repos: scanRepos(env.workspaceRoot || '.', { extraRepos: env.extraRepos }) } };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** GET /api/git-push/browse —— 目录浏览(路径选择器)。 */
|
|
63
|
+
export function handleBrowse(ctx) {
|
|
64
|
+
const { query, env } = ctx;
|
|
65
|
+
const r = browseDir(String(query.path || ''), { root: env.workspaceRoot });
|
|
66
|
+
return { status: r.ok ? 200 : 400, body: r.ok ? { ok: true, path: r.path, parent: r.parent, dirs: r.dirs } : { ok: false, error: r.error } };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** GET /api/git-push/tools —— 插件自身工具定义清单(agent 工具)。 */
|
|
70
|
+
export function handleTools() {
|
|
71
|
+
return { status: 200, body: { ok: true, tools: listTools() } };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** GET /api/git-push/tool-probes —— 本机各工具实测路径/版本(真实探测)。 */
|
|
75
|
+
export function handleToolProbes() {
|
|
76
|
+
return { status: 200, body: { ok: true, probes: collectToolPaths(null) } };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* 由规则包 yml 解析结果算该槽位的规则条数统计。
|
|
81
|
+
*
|
|
82
|
+
* 为什么单独成函数:这段(rules 过滤 + private_files 计数 + pass 推导)原先内联在
|
|
83
|
+
* listRuleSlots 的循环里,与「槽位元数据组装」混在一起,把该函数圈复杂度推到 15
|
|
84
|
+
* (阈值 10,自审 max-cyclomatic-complexity)——拆开后统计口径可单独阅读与复用。
|
|
85
|
+
* 清单驱动槽位(private)用 private_files 条目数计(它们不在 rules 数组里)。
|
|
86
|
+
*/
|
|
87
|
+
function ruleSlotStats(r) {
|
|
88
|
+
const rules = Array.isArray(r.data.rules) ? r.data.rules : [];
|
|
89
|
+
const listed = Array.isArray(r.data.private_files) ? r.data.private_files.length : 0;
|
|
90
|
+
const total = rules.length + listed;
|
|
91
|
+
const blocker = rules.filter((x) => x && (x.severity === 'blocker' || x.severity === 'error')).length + listed;
|
|
92
|
+
const warning = rules.filter((x) => x && x.severity === 'warning').length;
|
|
93
|
+
return { blocker, warning, pass: Math.max(0, total - blocker - warning), total, source: 'rules' };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** 规则包清单(按规则条数统计;hitStats 参数保留兼容但不再参与计算)。 */
|
|
97
|
+
export function listRuleSlots(order, disabledSlots = [], hitStats = null) {
|
|
98
|
+
const discovered = discoverRuleSlots(RULE_YAML_DIR);
|
|
99
|
+
const slotMeta = {};
|
|
100
|
+
for (const slot of discovered) {
|
|
101
|
+
const r = loadYamlRuleFile(slot, RULE_YAML_DIR);
|
|
102
|
+
if (r.ok && r.data?.metadata) {
|
|
103
|
+
slotMeta[slot] = {
|
|
104
|
+
name: r.data.metadata.name || slot,
|
|
105
|
+
description: r.data.metadata.description || '',
|
|
106
|
+
author: r.data.metadata.author || '',
|
|
107
|
+
stats: ruleSlotStats(r),
|
|
108
|
+
disabled: r.data.disabled === true || disabledSlots.includes(slot),
|
|
109
|
+
};
|
|
110
|
+
} else {
|
|
111
|
+
slotMeta[slot] = { name: slot, description: '', author: '', stats: { blocker: 0, warning: 0, pass: 0, total: 0, source: 'rules' }, disabled: disabledSlots.includes(slot) };
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
const eff = resolveSlotOrder(order && order.length ? order : undefined, { dir: RULE_YAML_DIR });
|
|
115
|
+
return { discovered, order: eff, meta: slotMeta, forced: ['private'] };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** GET /api/git-push/rule-slots —— 规则包按包规则条数统计。 */
|
|
119
|
+
export function handleRuleSlots(ctx) {
|
|
120
|
+
const { cfg } = ctx;
|
|
121
|
+
return { status: 200, body: { ok: true, slots: listRuleSlots(cfg.auditRuleOrder, Array.isArray(cfg.auditDisabledSlots) ? cfg.auditDisabledSlots : [], getLastSlotHitStats()) } };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** GET /api/git-push/rule-detail —— 单个规则包的规则明细 + severity 统计。 */
|
|
125
|
+
export function handleRuleDetail(ctx) {
|
|
126
|
+
const { query } = ctx;
|
|
127
|
+
const slot = String(query.slot || '');
|
|
128
|
+
if (!slot) return { status: 400, body: { ok: false, code: 'SLOT_REQUIRED', error: '缺少规则包名 slot' } };
|
|
129
|
+
const r = loadYamlRuleFile(slot, RULE_YAML_DIR);
|
|
130
|
+
if (!r.ok) return { status: 404, body: { ok: false, code: 'SLOT_NOT_FOUND', error: r.error } };
|
|
131
|
+
const rules = Array.isArray(r.data?.rules) ? r.data.rules : [];
|
|
132
|
+
const detail = rules.map((rule) => ({
|
|
133
|
+
id: rule.id || '',
|
|
134
|
+
name: rule.name || rule.id || '',
|
|
135
|
+
category: rule.category || '',
|
|
136
|
+
severity: rule.severity || 'notice',
|
|
137
|
+
description: rule.description || '',
|
|
138
|
+
author: rule.author || r.data.metadata?.author || '',
|
|
139
|
+
}));
|
|
140
|
+
const count = (sev) => detail.filter((x) => x.severity === sev).length;
|
|
141
|
+
const stats = {
|
|
142
|
+
blocker: count('blocker') + count('error'),
|
|
143
|
+
warning: count('warning'),
|
|
144
|
+
pass: rules.length - count('blocker') - count('error') - count('warning'),
|
|
145
|
+
total: rules.length,
|
|
146
|
+
};
|
|
147
|
+
return { status: 200, body: { ok: true, slot, meta: { name: r.data?.metadata?.name || slot, description: r.data?.metadata?.description || '', author: r.data?.metadata?.author || '' }, stats, rules: detail } };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** POST/GET /api/git-push/audit —— 审计结果 API(请求时聚合)。 */
|
|
151
|
+
export async function handleAudit(ctx) {
|
|
152
|
+
const { query, body, env, cfg } = ctx;
|
|
153
|
+
const { runAuditApi } = await import('../audit-api.js');
|
|
154
|
+
const params = { ...query, ...body };
|
|
155
|
+
const repo = String(params.repo || '').trim()
|
|
156
|
+
|| getDefaultScanRoot(env, { defaultScanRoot: String(cfg.defaultScanRoot || '') });
|
|
157
|
+
if (!repo) return { status: 400, body: { ok: false, code: 'REPO_REQUIRED', error: '缺 repo 参数且无法推断默认扫描根' } };
|
|
158
|
+
try {
|
|
159
|
+
const r = await runAuditApi(repo, params, cfg);
|
|
160
|
+
return { status: 200, body: r };
|
|
161
|
+
} catch (e) {
|
|
162
|
+
return { status: 500, body: { ok: false, code: 'AUDIT_FAIL', error: `审计失败: ${e?.message || e}` } };
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** POST /api/git-push/toggle-rule —— 启用/禁用规则包(改 yml disabled)。 */
|
|
167
|
+
export function handleToggleRule(ctx) {
|
|
168
|
+
const { body } = ctx;
|
|
169
|
+
const slot = String(body.slot || '');
|
|
170
|
+
const want = body.disabled === true;
|
|
171
|
+
if (!slot) return { status: 400, body: { ok: false, code: 'SLOT_REQUIRED', error: '缺少规则包名 slot' } };
|
|
172
|
+
const r = setSlotDisabled(slot, want);
|
|
173
|
+
if (!r.ok) return { status: 400, body: { ok: false, code: 'SLOT_TOGGLE_FAIL', error: r.error || '切换失败' } };
|
|
174
|
+
return { status: 200, body: { ok: true, slot, disabled: r.disabled, message: want ? '已禁用' : '已启用' } };
|
|
175
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* npm 账号 handler(Step 2):`/npm-account` —— 登录态 + registry + 凭据配置状态。
|
|
3
|
+
*
|
|
4
|
+
* 安全:**绝不回吐 token 明文**——只回 `configured` 布尔与 `maskedToken`(脱敏);
|
|
5
|
+
* 调用 npm 时把 token 物化成 0600 的独立 npmrc(`--userconfig`),不碰用户全局 ~/.npmrc。
|
|
6
|
+
*/
|
|
7
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
|
|
10
|
+
import { readNpmToken, maskToken } from '../../core/credentials.js';
|
|
11
|
+
import { normalizeRegistry, whoami, listOwnedPackages } from '../../npm/registry.js';
|
|
12
|
+
import { npmArgs, writeNpmrc } from '../../npm/npmrc.js';
|
|
13
|
+
import { installPackages, startInstall, validateDest } from '../../npm/install.js';
|
|
14
|
+
import { publishPackage } from '../../npm/publish.js';
|
|
15
|
+
import { readNpmAccountStatus, writeNpmAccountStatus, buildNpmAccountStatus, renderNpmAccountBlock } from '../../npm/account.js';
|
|
16
|
+
|
|
17
|
+
/** 账号态公共装配(离线,不跑 npm):凭据文件真源 + registry + 快照 ⇒ 供三个端点复用。 */
|
|
18
|
+
function npmAccountState(ctx) {
|
|
19
|
+
const { env, cfg } = ctx;
|
|
20
|
+
const workspaceRoot = env?.workspaceRoot || '';
|
|
21
|
+
const registry = normalizeRegistry(cfg?.npmRegistry);
|
|
22
|
+
let token = '';
|
|
23
|
+
try { token = readNpmToken({ workspaceRoot }); } catch { token = ''; }
|
|
24
|
+
const configured = !!(token && token.trim());
|
|
25
|
+
const masked = configured ? maskToken(token) : '';
|
|
26
|
+
const snap = readNpmAccountStatus({ workspaceRoot });
|
|
27
|
+
const loggedIn = !!(snap.ok && snap.user);
|
|
28
|
+
const error = configured
|
|
29
|
+
? (loggedIn ? '' : (snap.error || '尚未校验:点「刷新」做一次在线校验'))
|
|
30
|
+
: '未配置 npm token(在设置里填写后即可显示登录态)';
|
|
31
|
+
return {
|
|
32
|
+
workspaceRoot, registry, token, configured, snap,
|
|
33
|
+
body: {
|
|
34
|
+
ok: true,
|
|
35
|
+
configured,
|
|
36
|
+
maskedToken: masked,
|
|
37
|
+
registry,
|
|
38
|
+
user: snap.user || '',
|
|
39
|
+
loggedIn,
|
|
40
|
+
checkedAt: snap.checkedAt || '',
|
|
41
|
+
error,
|
|
42
|
+
block: renderNpmAccountBlock(snap, { configured, maskedToken: masked, registry }),
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** `/npm-account`:**离线**读快照(对齐 GitHub 的 `/account-status`;秒级、不联网)。 */
|
|
48
|
+
export function handleNpmAccount(ctx) {
|
|
49
|
+
return { status: 200, body: npmAccountState(ctx).body };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** `/npm-check`:在线跑 `npm whoami` 并写快照(对齐 GitHub 的 `/account-check`;「刷新」按钮走这里)。 */
|
|
53
|
+
export function handleNpmCheck(ctx) {
|
|
54
|
+
const st = npmAccountState(ctx);
|
|
55
|
+
if (!st.configured) return { status: 200, body: st.body };
|
|
56
|
+
const rc = writeNpmrc({ workspaceRoot: st.workspaceRoot, registry: st.registry, token: st.token });
|
|
57
|
+
if (!rc.ok) return { status: 200, body: { ...st.body, loggedIn: false, error: rc.error || 'npmrc 写入失败' } };
|
|
58
|
+
const w = whoami({ npmArgs: npmArgs({ npmrcFile: rc.file, registry: st.registry }) });
|
|
59
|
+
const snap = buildNpmAccountStatus({ user: w.user, registry: st.registry, ok: !!w.ok, error: w.error || '' });
|
|
60
|
+
writeNpmAccountStatus(snap, { workspaceRoot: st.workspaceRoot });
|
|
61
|
+
const loggedIn = !!(snap.ok && snap.user);
|
|
62
|
+
return {
|
|
63
|
+
status: 200,
|
|
64
|
+
body: {
|
|
65
|
+
...st.body,
|
|
66
|
+
user: snap.user,
|
|
67
|
+
loggedIn,
|
|
68
|
+
checkedAt: snap.checkedAt,
|
|
69
|
+
error: loggedIn ? '' : (snap.error || 'npm whoami 未通过'),
|
|
70
|
+
block: renderNpmAccountBlock(snap, { configured: true, maskedToken: st.body.maskedToken, registry: st.registry }),
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** `/npm-owned`:登录账号名下的包列表(对齐 GitHub 云端仓库列表;只读 + 可降级)。 */
|
|
76
|
+
export async function handleNpmOwned(ctx) {
|
|
77
|
+
const st = npmAccountState(ctx);
|
|
78
|
+
if (!st.body.loggedIn) {
|
|
79
|
+
return {
|
|
80
|
+
status: 200,
|
|
81
|
+
body: { ok: true, user: '', results: [], error: st.configured ? '尚未校验登录态:先点「刷新」' : '未配置 npm token' },
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
const r = await listOwnedPackages(st.body.user, { registry: st.registry });
|
|
85
|
+
return { status: 200, body: { ok: true, user: st.body.user, results: r.results, error: r.error || '' } };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* `/npm-packages`:列出某目录的已装依赖(读 package.json,不跑 npm、不联网)。
|
|
90
|
+
* 入参:dir(可选,默认工作区)。返回 dependencies/devDependencies 与是否已有 node_modules。
|
|
91
|
+
*/
|
|
92
|
+
export function handleNpmPackages(ctx) {
|
|
93
|
+
const { env, query, body } = ctx;
|
|
94
|
+
const dir = String(query?.dir || body?.dir || env?.workspaceRoot || '');
|
|
95
|
+
const d = validateDest(dir);
|
|
96
|
+
if (!d.ok) return { status: 400, body: { ok: false, error: d.error, dir } };
|
|
97
|
+
try {
|
|
98
|
+
const pkgPath = join(dir, 'package.json');
|
|
99
|
+
const pkg = existsSync(pkgPath) ? JSON.parse(readFileSync(pkgPath, 'utf8')) : {};
|
|
100
|
+
const deps = { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) };
|
|
101
|
+
return {
|
|
102
|
+
status: 200,
|
|
103
|
+
body: {
|
|
104
|
+
ok: true,
|
|
105
|
+
dir,
|
|
106
|
+
name: pkg.name || '',
|
|
107
|
+
version: pkg.version || '',
|
|
108
|
+
hasPackageJson: existsSync(pkgPath),
|
|
109
|
+
nodeModules: existsSync(join(dir, 'node_modules')),
|
|
110
|
+
dependencies: Object.entries(deps).map(([name, range]) => ({ name, range })),
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
} catch (e) {
|
|
114
|
+
return { status: 500, body: { ok: false, error: String(e?.message || e) } };
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* `/npm-install`:安装包(POST)。**必须显式 confirm:true**(第二次确认);
|
|
120
|
+
* 默认 `ignoreScripts:true`(不执行 postinstall)、默认非全局。
|
|
121
|
+
*/
|
|
122
|
+
export function handleNpmInstall(ctx) {
|
|
123
|
+
const { env, body, cfg } = ctx;
|
|
124
|
+
if (body?.confirm !== true) {
|
|
125
|
+
return { status: 400, body: { ok: false, error: '安装需要显式二次确认(confirm: true)' } };
|
|
126
|
+
}
|
|
127
|
+
const names = Array.isArray(body?.names) ? body.names : String(body?.name || '').split(/[\s,]+/).filter(Boolean);
|
|
128
|
+
const global = body?.global === true;
|
|
129
|
+
const opts = {
|
|
130
|
+
names,
|
|
131
|
+
dest: String(body?.dest || ''),
|
|
132
|
+
global,
|
|
133
|
+
ignoreScripts: body?.ignoreScripts !== false, // 默认 true(安全默认)
|
|
134
|
+
registry: cfg?.npmRegistry || '',
|
|
135
|
+
workspaceRoot: env?.workspaceRoot || '',
|
|
136
|
+
};
|
|
137
|
+
// async=true:走异步安装 + /npm-install-progress 轮询(UI 进度框用;对应 GitHub 克隆的进度模型)
|
|
138
|
+
if (body?.async === true) {
|
|
139
|
+
const started = startInstall(opts);
|
|
140
|
+
return { status: started.ok ? 200 : 400, body: started };
|
|
141
|
+
}
|
|
142
|
+
const res = installPackages(opts);
|
|
143
|
+
return { status: res.ok ? 200 : 400, body: res };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* `/npm-publish`:发包。**默认 dry-run**(只体检 + `npm publish --dry-run`,不写 registry ✗);
|
|
148
|
+
* 真发必须同时 `confirm:true` **且** `dryRun:false`(双闸门,防误发不可撤销)。
|
|
149
|
+
*/
|
|
150
|
+
export async function handleNpmPublish(ctx) {
|
|
151
|
+
const { env, cfg, body } = ctx;
|
|
152
|
+
const dryRun = body?.dryRun !== false;
|
|
153
|
+
if (!dryRun && body?.confirm !== true) {
|
|
154
|
+
return {
|
|
155
|
+
status: 400,
|
|
156
|
+
body: { ok: false, blocked: 'need-confirm', error: '真实发布会写入 registry 且不可撤销:需同时传 confirm:true 与 dryRun:false(默认只做 dry-run)' },
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
const r = await publishPackage({
|
|
160
|
+
dir: String(body?.dir || env?.workspaceRoot || ''),
|
|
161
|
+
registry: cfg?.npmRegistry || '',
|
|
162
|
+
workspaceRoot: env?.workspaceRoot || '',
|
|
163
|
+
dryRun,
|
|
164
|
+
tag: body?.tag || 'latest',
|
|
165
|
+
otp: body?.otp || '',
|
|
166
|
+
confirm: body?.confirm === true,
|
|
167
|
+
});
|
|
168
|
+
return { status: r.ok ? 200 : 400, body: r };
|
|
169
|
+
}
|