@iyowei/sweep-node-modules-cli 0.2.1 → 0.4.0

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/bin/sweep-nm.mjs CHANGED
@@ -1,52 +1,62 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * npm 安装场景的启动器: 挑选运行时 (Bun 优先, 其次 Node) 后启动真实入口。
4
- * 与 bin/sweep-nm (sh) / bin/sweep-nm.cmd (cmd) 职责同逻辑 (挑选运行时: Bun 优先, Node 回退),
5
- * 差异在宿主与本文件多加的入口选择 (优先跑编译产物 dist/cli.js, 无产物则回退源码 src/cli.ts;
6
- * 包内只有产物, 开发态通常无产物):
7
- * 本文件同时承担 Unix 与 Windows 的 npm shim 目标 (shebang 必须是 node, 否则
8
- * npm 的 cmd-shim 会按 shebang 解释器生成 Windows 上不存在的调用)。
3
+ * npm 安装场景的启动器: 挑选运行时 (Bun 优先, 其次 Node >= 22.18) 后启动真实入口。
9
4
  *
10
- * 运行时解析防劫持 (安全审计项 runtime-resolution:bare-name-cwd-precedence-windows):
11
- * Windows 上裸名执行会先搜当前工作目录 (CreateProcessW 的搜索序里「parent 的当前目录」居第 2 位;
12
- * 本文件走的 Node spawn 亦然 —— libuv 的 search_path 以 NeedCurrentDirectoryForExePathW 门控
13
- * 先试 cwd 再扫 PATH), 而本工具的调用现场恰是「在被扫目录里执行」, 目录内放一个同名
14
- * bun.exe / bun.com 即可顶替真实运行时进入执行链。故 win32 下先按 PATH 解析出绝对路径
15
- * (空条目与相对条目都会把解析引回当前目录, 一并跳过) 再探测与执行, 解析面与执行面都不再
16
- * 触发任何搜索序; POSIX 侧 Node 走 execvp 只搜 PATH, 维持裸名原样。
17
- *
18
- * 产物自证 (审计项「发行面 dist/cli.js 与源码和提交无身份绑定」的运行时防线): 决定跑
19
- * dist/cli.js 之前必须与随附的 dist/manifest.json 对账 (形状版本受支持, 且清单记的 cliSha256
20
- * 必须等于实测摘要), 清单缺失 / 损坏 / 版本不支持 / 摘要不符一律拒收产物并给出指引, 不静默回退
21
- * 源码 (静默回退会把产物漂移藏起来, 包内也没有源码可回退); 拒收指引按宿主分流 (仓库检出态给
22
- * 源码入口与重构建, 包态给重装本包)。工作树脏净不进本判定 (开发态常脏), 那是发布闸门
23
- * scripts/verify-release.ts 的职责; 清单字段契约见 scripts/release-artifact.ts (包内无法
24
- * 跨语言复用该模块, 两边口径由 src/npm-launcher.smoke.test.ts 的集成用例钉住)。
25
- *
26
- * 退出码原样透传; 两个运行时都缺席时给出可操作提示并非零退出。
5
+ * 安全防线与进程模型:
6
+ * 1. 运行时解析防劫持: win32 与 POSIX 均按 PATH 解析绝对路径并跳过空/相对条目
7
+ * (win32 严判盘符或 UNC 绝对路径, 拦截 Git Bash 注入的 `/usr/bin` 盘根相对路径),
8
+ * 绝不从当前被扫目录解析同名 bun/node;
9
+ * 2. Bun 工作目录配置隔离: 选中 Bun 时强制附加 --config=<pkg>/bin/bunfig.toml 与
10
+ * --no-env-file (隔离配置缺失即报错拒绝, 不静默退回无隔离态), 并透传 CLIS_BUN_ISOLATED=1;
11
+ * 3. 产物自证: 执行 dist/cli.js 前必先与 dist/manifest.json 校验 SHA-256;
12
+ * 4. 零多余派生 + 信号收口: 当前进程已是隔离 Bun 或满足 >= 22.18 的纯 Node 时直接同进程
13
+ * import 入口 (保留原始 argv[1]); 需跨运行时切换时以异步 spawn 派发, 运行期父进程忽略
14
+ * SIGINT 防杀父留孤儿, 子进程退出后解挂并透传信号或退出码。
27
15
  */
28
- import { spawnSync } from 'node:child_process';
16
+ import { spawn, spawnSync } from 'node:child_process';
29
17
  import { createHash } from 'node:crypto';
30
18
  import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
31
- import { dirname, join, win32 } from 'node:path';
32
- import { fileURLToPath } from 'node:url';
19
+ import { basename, dirname, join, posix, win32 } from 'node:path';
20
+ import { fileURLToPath, pathToFileURL } from 'node:url';
33
21
 
34
- /** 产物与清单的文件名 (与 scripts/release-artifact.ts 的 CLI_FILE / MANIFEST_FILE 同值) */
35
22
  const CLI_FILE = 'cli.js';
36
23
  const MANIFEST_FILE = 'manifest.json';
37
-
38
- /**
39
- * win32 的候选可执行扩展名, 顺序与 Node 实际走的 libuv 搜索一致 (.com 先于 .exe)。
40
- * 不展开 PATHEXT: .bat / .cmd 无法被 Node 无 shell 直接执行, 展开只会把不可执行的命中当成功;
41
- * 保持该面与 libuv 等价也意味着本次收紧不改动 win32 上「哪些安装形态能命中」的既有行为。
42
- */
43
24
  const WIN32_EXEC_EXTS = ['.com', '.exe'];
25
+ const WIN32_ABS_DIR_RE = /^(?:[A-Za-z]:[/\\]|\\\\[^\\]+\\[^\\]+)/;
26
+ const MIN_NODE_MAJOR = 22;
27
+ const MIN_NODE_MINOR = 18;
28
+
29
+ /** 校验 Node.js 版本是否满足 >= 22.18.0 下限 */
30
+ export const isSupportedNodeVersion = (rawVersion) => {
31
+ if (typeof rawVersion !== 'string') return false;
32
+ const match = /^v?(\d+)\.(\d+)/.exec(rawVersion.trim());
33
+ if (match === null) return false;
34
+ const major = Number(match[1]);
35
+ const minor = Number(match[2]);
36
+ return (
37
+ major > MIN_NODE_MAJOR ||
38
+ (major === MIN_NODE_MAJOR && minor >= MIN_NODE_MINOR)
39
+ );
40
+ };
41
+
42
+ /** 判定解析出的运行时是否为 Bun */
43
+ const isBunRuntime = (runtime) => {
44
+ const name = basename(runtime).toLowerCase();
45
+ return name === 'bun' || name === 'bun.exe' || name === 'bun.com';
46
+ };
44
47
 
45
- /** 探测命令是否可执行 (以 --version 的实际退出码为准, 不依赖 shell 内建) */
46
- const available = (command) =>
47
- spawnSync(command, ['--version'], { stdio: 'ignore' }).status === 0;
48
+ /** 探测命令是否可执行 (Bun 看退出码 0, Node 另校验 >= 22.18.0) */
49
+ const available = (command) => {
50
+ const res = spawnSync(command, ['--version'], {
51
+ encoding: 'utf8',
52
+ stdio: ['ignore', 'pipe', 'ignore'],
53
+ });
54
+ if (res.status !== 0) return false;
55
+ if (isBunRuntime(command)) return true;
56
+ return isSupportedNodeVersion(res.stdout);
57
+ };
48
58
 
49
- /** 路径处是否为普通文件 (探针读不到即 false, 不抛; 目录名撞上候选名时不得当选) */
59
+ /** 路径处是否为普通文件 */
50
60
  const isFileAt = (path) => {
51
61
  try {
52
62
  return statSync(path).isFile();
@@ -55,54 +65,56 @@ const isFileAt = (path) => {
55
65
  }
56
66
  };
57
67
 
58
- /**
59
- * 在 PATH 中解析命令的绝对路径 (win32 语义), 找不到返回 null。
60
- * 只供 win32 分支调用: CreateProcessW 与 libuv 的裸名搜索序都会先搜当前目录, 本函数把
61
- * 「当前目录」从解析面整个摘掉 —— 空条目 (Windows 上表示当前目录) 与相对条目 (同样按当前
62
- * 目录解析) 一律跳过, 只认绝对目录; 条目两侧的引号按 libuv 同款剥掉 (Windows PATH 允许
63
- * 引号包裹含空格的目录)。注入 pathEnv / fileProbe 供测试在非 win32 宿主上覆盖本函数。
64
- */
65
- export const resolveWin32Executable = (name, pathEnv, fileProbe) => {
68
+ /** 在 PATH 中解析命令的全部候选绝对路径 (win32 语义), 严格拦截空、相对与盘根相对条目 */
69
+ export const resolveWin32Executables = (name, pathEnv, fileProbe) => {
70
+ const found = [];
66
71
  for (const raw of pathEnv.split(';')) {
67
- const dir =
68
- raw.length > 1 && raw.startsWith('"') && raw.endsWith('"')
69
- ? raw.slice(1, -1)
70
- : raw;
71
- if (dir === '' || !win32.isAbsolute(dir)) continue;
72
+ const trimmed = raw.trim();
73
+ const unquoted =
74
+ trimmed.length > 1 && trimmed.startsWith('"') && trimmed.endsWith('"')
75
+ ? trimmed.slice(1, -1).trim()
76
+ : trimmed;
77
+ if (unquoted === '' || !WIN32_ABS_DIR_RE.test(unquoted)) continue;
72
78
  for (const ext of WIN32_EXEC_EXTS) {
73
- const candidate = win32.join(dir, name + ext);
74
- if (fileProbe(candidate)) return candidate;
79
+ const candidate = win32.join(unquoted, name + ext);
80
+ if (fileProbe(candidate)) found.push(candidate);
75
81
  }
76
82
  }
77
- return null;
83
+ return found;
78
84
  };
79
85
 
80
- /**
81
- * 挑选运行时: Bun 优先, 其次 Node; 皆无则 null (由调用处报错退出)。
82
- * win32 下先按 PATH 解析绝对路径再探测 (理由见文件头「运行时解析防劫持」), POSIX 下维持
83
- * 裸名 (execvp 只搜 PATH); 各参数显式传入供测试注入, 生产调用不传。
84
- */
86
+ /** 在 PATH 中解析命令的全部候选绝对路径 (POSIX 语义), 跳过空与相对条目 */
87
+ export const resolvePosixExecutables = (name, pathEnv, fileProbe) => {
88
+ const found = [];
89
+ for (const dir of pathEnv.split(':')) {
90
+ if (dir === '' || !dir.startsWith('/')) continue;
91
+ const candidate = posix.join(dir, name);
92
+ if (fileProbe(candidate)) found.push(candidate);
93
+ }
94
+ return found;
95
+ };
96
+
97
+ /** 挑选运行时: 缺省 Bun 优先、其次 Node (>= 22.18); 皆无则 null */
85
98
  export const pickRuntime = ({
86
99
  platform = process.platform,
87
- pathEnv = process.env.PATH ?? '',
100
+ pathEnv = process.env.PATH ?? process.env.Path ?? '',
88
101
  fileProbe = isFileAt,
89
102
  probe = available,
103
+ names = ['bun', 'node'],
90
104
  } = {}) => {
91
- for (const name of ['bun', 'node']) {
92
- const resolved =
105
+ for (const name of names) {
106
+ const candidates =
93
107
  platform === 'win32'
94
- ? resolveWin32Executable(name, pathEnv, fileProbe)
95
- : name;
96
- if (resolved !== null && probe(resolved)) return resolved;
108
+ ? resolveWin32Executables(name, pathEnv, fileProbe)
109
+ : resolvePosixExecutables(name, pathEnv, fileProbe);
110
+ for (const candidate of candidates) {
111
+ if (probe(candidate)) return candidate;
112
+ }
97
113
  }
98
114
  return null;
99
115
  };
100
116
 
101
- /**
102
- * 产物自证: 核对 dist/cli.js 与 dist/manifest.json 的摘要是否同源。
103
- * 通过返回 null, 否则返回人话原因; 原因串全是本文件固定措辞, 不回显清单内容 (清单是外部
104
- * 文件, 其文本不受控, 不落进输出面)。
105
- */
117
+ /** 产物自证: 核对 dist/cli.js 与 dist/manifest.json 的摘要是否同源 */
106
118
  const artifactProblem = (distDir) => {
107
119
  const manifestPath = join(distDir, MANIFEST_FILE);
108
120
  if (!existsSync(manifestPath)) return `缺少产物清单 (dist/${MANIFEST_FILE})`;
@@ -112,8 +124,6 @@ const artifactProblem = (distDir) => {
112
124
  } catch {
113
125
  return `产物清单 (dist/${MANIFEST_FILE}) 损坏, 不是合法 JSON`;
114
126
  }
115
- // 形状版本先对: 异版本的字段语义无保证, 宁可拒收 (字面量 1 与 scripts/release-artifact.ts 的
116
- // MANIFEST_SCHEMA_VERSION 同值, 改动须两处同步; 启动器随包分发, 包内无法 import 该模块)
117
127
  if (manifest?.schemaVersion !== 1) {
118
128
  return `产物清单 (dist/${MANIFEST_FILE}) 的 schemaVersion 不是受支持的版本 (期望 1)`;
119
129
  }
@@ -129,62 +139,156 @@ const artifactProblem = (distDir) => {
129
139
  } catch {
130
140
  return `产物 (dist/${CLI_FILE}) 读不出来, 摘要算不出`;
131
141
  }
132
- if (recorded !== actual)
142
+ if (recorded !== actual) {
133
143
  return `产物 (dist/${CLI_FILE}) 的摘要与清单记录不符`;
144
+ }
134
145
  return null;
135
146
  };
136
147
 
137
- /**
138
- * 本文件是否作为入口被直接执行。
139
- * 经 realpath 比对而非字面路径: npm 在 Unix 上以符号链接 (或经 shim) 落 bin, 此时 argv[1] 是
140
- * 链接路径而 import.meta.url 是解析后的真实路径。main 守卫只为让测试 import 本模块取函数时
141
- * 不触发主流程, 判定失配的后果是入口静默不跑, 故除字面相等外只在 realpath 成功时采信。
142
- */
148
+ /** 本文件是否作为入口被直接执行 (双端 realpath.native 展开 win32 8.3 短路径 + 大小写归一) */
143
149
  const isEntry = () => {
144
150
  const entry = process.argv[1];
145
151
  if (typeof entry !== 'string' || entry === '') return false;
146
152
  const self = fileURLToPath(import.meta.url);
147
- if (entry === self) return true;
153
+ const norm = (value) =>
154
+ process.platform === 'win32' ? value.toLowerCase() : value;
155
+ if (norm(entry) === norm(self)) return true;
148
156
  try {
149
- return realpathSync(entry) === self;
157
+ const realpath = realpathSync.native ?? realpathSync;
158
+ const realSelf = realpath(self);
159
+ return norm(realpath(entry)) === norm(realSelf);
150
160
  } catch {
151
161
  return false;
152
162
  }
153
163
  };
154
164
 
155
- const main = () => {
165
+ /** 跨运行时异步派生子进程: 运行期父进程忽略 SIGINT 防孤儿, 退出后卸载监听并透传信号或退出码 */
166
+ const runChild = (command, args, extraEnv) =>
167
+ new Promise((resolve) => {
168
+ const ignoreSigint = () => {};
169
+ process.on('SIGINT', ignoreSigint);
170
+ const child = spawn(command, args, {
171
+ stdio: 'inherit',
172
+ env: extraEnv ? { ...process.env, ...extraEnv } : process.env,
173
+ });
174
+ const cleanup = () => {
175
+ process.off('SIGINT', ignoreSigint);
176
+ };
177
+ child.on('error', (error) => {
178
+ cleanup();
179
+ process.stderr.write(`sweep-nm: 启动运行时失败 (${error.message})\n`);
180
+ process.exit(1);
181
+ });
182
+ child.on('exit', (code, signal) => {
183
+ cleanup();
184
+ if (signal) {
185
+ try {
186
+ process.kill(process.pid, signal);
187
+ } catch {
188
+ process.exit(1);
189
+ }
190
+ resolve();
191
+ return;
192
+ }
193
+ process.exit(code ?? 1);
194
+ });
195
+ });
196
+
197
+ const main = async () => {
156
198
  const root = dirname(dirname(fileURLToPath(import.meta.url)));
157
199
  const distDir = join(root, 'dist');
158
200
  const built = join(distDir, CLI_FILE);
201
+ const source = join(root, 'src', 'cli.ts');
159
202
  const hasBuilt = existsSync(built);
160
- // 有产物就得先自证 (与随附清单对账); 不通过即拒收, 退出码与「无运行时」同一档: 1
203
+ const hasSource = existsSync(source);
204
+
205
+ if (!hasBuilt && !hasSource) {
206
+ process.stderr.write(
207
+ `sweep-nm: 缺少可执行入口 (dist/${CLI_FILE} 与 src/cli.ts 均不存在)。\n` +
208
+ ' 处置: 重装本包换一份完好分发 (npm install -g @iyowei/sweep-node-modules-cli); 本仓开发态请先执行 bun run build。\n',
209
+ );
210
+ process.exit(1);
211
+ }
212
+
161
213
  const problem = hasBuilt ? artifactProblem(distDir) : null;
162
214
  if (problem !== null) {
163
- // 处置指引按宿主分流: 仓库检出态 (有源码) 可走源码入口或重构建; 包态 (无源码) 只能重装本包
164
- const advice = existsSync(join(root, 'src', 'cli.ts'))
165
- ? '用源码入口跑 (bun src/cli.ts 或 node src/cli.ts), 或重新构建 (bun run build)'
166
- : '重装本包换一份完好分发 (npm install -g @iyowei/sweep-node-modules); 重装无效则说明该版本包有缺陷, 需发布者重新构建后再发';
215
+ const advice = hasSource
216
+ ? '用源码入口跑 (bun packages/sweep-node-modules-cli/src/cli.ts 或 node packages/sweep-node-modules-cli/src/cli.ts), 或重新构建 (bun run build)'
217
+ : '重装本包换一份完好分发 (npm install -g @iyowei/sweep-node-modules-cli); 重装无效则说明该版本包有缺陷, 需发布者重新构建后再发';
167
218
  process.stderr.write(
168
219
  `sweep-nm: ${problem}, 已拒绝执行该产物 (无法证明它与构建清单同源)。\n` +
169
220
  ` 处置: ${advice}。\n`,
170
221
  );
171
222
  process.exit(1);
172
223
  }
173
- // npm 包内是编译产物 (node 拒绝对 node_modules 内的 TS 做类型剥离, 见 package.json 的 build 脚本);
174
- // 仓库开发态无 dist, 回退直跑源码 (bun / node 皆可)
175
- const entry = hasBuilt ? built : join(root, 'src', 'cli.ts');
176
- const runtime = pickRuntime();
177
224
 
178
- if (runtime === null) {
179
- process.stderr.write('sweep-nm: 未找到 bun 或 node, 请至少安装其一\n');
225
+ const entry = hasBuilt ? built : source;
226
+ const isolatedBunfig = join(root, 'bin', 'bunfig.toml');
227
+ const ensureIsolatedBunfig = () => {
228
+ if (existsSync(isolatedBunfig)) return;
229
+ process.stderr.write(
230
+ 'sweep-nm: 缺少启动器隔离配置 (bin/bunfig.toml), 为防工作目录 bunfig.toml 劫持已拒绝执行。\n',
231
+ );
180
232
  process.exit(1);
233
+ };
234
+
235
+ // 当前已是 Bun: 隔离态直接同进程 import, 非隔离态直接用 process.execPath 重派隔离态 Bun (不扫 PATH)
236
+ if (typeof process.versions.bun === 'string') {
237
+ ensureIsolatedBunfig();
238
+ if (process.env.CLIS_BUN_ISOLATED === '1') {
239
+ await import(pathToFileURL(entry).href);
240
+ return;
241
+ }
242
+ await runChild(
243
+ process.execPath,
244
+ [
245
+ `--config=${isolatedBunfig}`,
246
+ '--no-env-file',
247
+ entry,
248
+ ...process.argv.slice(2),
249
+ ],
250
+ { CLIS_BUN_ISOLATED: '1' },
251
+ );
252
+ return;
181
253
  }
182
254
 
183
- const { status } = spawnSync(runtime, [entry, ...process.argv.slice(2)], {
184
- stdio: 'inherit',
185
- });
255
+ const isCurrentNodeSupported = isSupportedNodeVersion(process.versions.node);
256
+
257
+ // 当前进程已是合格 Node 时仅探 Bun: 命中切 Bun, 未命中直接同进程 import (零额外派生)
258
+ const runtime = pickRuntime(
259
+ isCurrentNodeSupported ? { names: ['bun'] } : undefined,
260
+ );
261
+ if (runtime !== null && isBunRuntime(runtime)) {
262
+ ensureIsolatedBunfig();
263
+ await runChild(
264
+ runtime,
265
+ [
266
+ `--config=${isolatedBunfig}`,
267
+ '--no-env-file',
268
+ entry,
269
+ ...process.argv.slice(2),
270
+ ],
271
+ { CLIS_BUN_ISOLATED: '1' },
272
+ );
273
+ return;
274
+ }
275
+
276
+ if (isCurrentNodeSupported) {
277
+ await import(pathToFileURL(entry).href);
278
+ return;
279
+ }
280
+
281
+ if (runtime !== null) {
282
+ await runChild(runtime, [entry, ...process.argv.slice(2)]);
283
+ return;
284
+ }
186
285
 
187
- process.exit(status ?? 1);
286
+ process.stderr.write(
287
+ `sweep-nm: 未找到可用的 bun 或 node (>= ${MIN_NODE_MAJOR}.${MIN_NODE_MINOR}.0; 当前 node 为 ${process.versions.node ?? '未知'})\n`,
288
+ );
289
+ process.exit(1);
188
290
  };
189
291
 
190
- if (isEntry()) main();
292
+ if (isEntry()) {
293
+ await main();
294
+ }