@wkgeo/cli 1.0.0 → 1.1.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/CHANGELOG.md +223 -208
- package/lib/commands/index.mjs +13 -0
- package/lib/commands/template.mjs +258 -0
- package/lib/tar.mjs +207 -0
- package/lib/template-package.mjs +522 -0
- package/package.json +1 -1
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `wkgeo template init` —— 一条命令把基础库(`@wkgeo/base-template`)从 npm 下到本地。
|
|
3
|
+
*
|
|
4
|
+
* ## 老板的原话与定调(2026-10-30)
|
|
5
|
+
* 「基础模版可以开源到 github,或者国内的哪里吗,这样别人 init 初始化的时候就可以下载整套内容」
|
|
6
|
+
* → 「还是放 npm」。所以这里走 **npm 公开包 + npmmirror 镜像**,不做 GitHub 拉源码。
|
|
7
|
+
*
|
|
8
|
+
* ## 一条命令干的事
|
|
9
|
+
* 读 registry 元数据 → 选版本(`dist-tags.latest` 或 `--version`)→ 下 `dist.tarball`
|
|
10
|
+
* → **校验 `dist.integrity`(sha512)** → 解包(防路径穿越)→ 只取白名单
|
|
11
|
+
* → 落 `--to/<模板目录>`(默认 `./_base`)→ 跑包内 `tools/check-base.mjs` 自检。
|
|
12
|
+
*
|
|
13
|
+
* ## 缓存
|
|
14
|
+
* `~/.wkgeo/cache/base/<version>/`(`WKGEO_TEMPLATE_CACHE` 可改)。第二次 init **不发网络请求**;
|
|
15
|
+
* `--force` 强制重下;`--offline` 只读缓存,没缓存就报"哪两个 URL 该能访问"。
|
|
16
|
+
*
|
|
17
|
+
* ## 为什么不复用 `npm install`
|
|
18
|
+
* 1. 不装新依赖、不写 node_modules,也不让用户机器上的 `.npmrc`(可能有公司源/镜像 token)参与;
|
|
19
|
+
* 2. integrity 校验与解包安全策略要**由我们说了算**(拒绝符号链接、只落白名单);
|
|
20
|
+
* 3. 语义是"拷一套模板出来",不是"装一个库进来"——落地目录要能直接 `wkgeo template push`。
|
|
21
|
+
*
|
|
22
|
+
* 相关文档:`docs/功能-基础库分发.md`、`docs/规范-基础库开源内容边界.md`。
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import fs from 'node:fs';
|
|
26
|
+
import path from 'node:path';
|
|
27
|
+
|
|
28
|
+
import { CliError, UsageError } from '../errors.mjs';
|
|
29
|
+
import {
|
|
30
|
+
PACKAGE_NAME,
|
|
31
|
+
cacheRootOf,
|
|
32
|
+
copyTree,
|
|
33
|
+
downloadToCache,
|
|
34
|
+
listCachedVersions,
|
|
35
|
+
packageDirName,
|
|
36
|
+
readCache,
|
|
37
|
+
readLatestPointer,
|
|
38
|
+
registryPlan,
|
|
39
|
+
metadataUrl,
|
|
40
|
+
selfCheck,
|
|
41
|
+
} from '../template-package.mjs';
|
|
42
|
+
|
|
43
|
+
function fmtBytes(n) {
|
|
44
|
+
if (!Number.isFinite(n)) return '?';
|
|
45
|
+
if (n < 1024) return `${n}B`;
|
|
46
|
+
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)}KB`;
|
|
47
|
+
return `${(n / 1024 / 1024).toFixed(2)}MB`;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function readJsonSafe(file) {
|
|
51
|
+
try {
|
|
52
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
53
|
+
} catch {
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** 目标目录:`--to` 是**父目录**,落 `<to>/<模板目录名>`;`--to` 本身已是该名字时直接用 */
|
|
59
|
+
export function resolveTarget(toFlag, dirName, cwd = process.cwd()) {
|
|
60
|
+
const parent = path.resolve(cwd, toFlag || '.');
|
|
61
|
+
if (path.basename(parent) === dirName) return { parent, target: parent, nested: false };
|
|
62
|
+
return { parent, target: path.join(parent, dirName), nested: true };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export const templateInitCommand = {
|
|
66
|
+
name: 'template init',
|
|
67
|
+
summary: '一条命令下载整套基础库(npm 公开包 @wkgeo/base-template,带 integrity 校验与本地缓存)',
|
|
68
|
+
usage:
|
|
69
|
+
'wkgeo template init [--to <父目录>] [--version <x.y.z>] [--registry npm|npmmirror] [--offline] [--force] [--json]\n' +
|
|
70
|
+
'wkgeo template init --to . # 落到 ./_base\n' +
|
|
71
|
+
'wkgeo template init --to templates # 落到 templates/_base',
|
|
72
|
+
args: [],
|
|
73
|
+
flags: {
|
|
74
|
+
to: { type: 'string', desc: '落到哪个**父目录**下(默认当前目录;最终目录是 <父目录>/_base)' },
|
|
75
|
+
version: { type: 'string', desc: '包版本 x.y.z(默认 dist-tags.latest;不带值的 --version 是全局「打印 CLI 版本」)' },
|
|
76
|
+
registry: { type: 'string', desc: '优先源:npm(=官方 registry.npmjs.org,默认)/ npmmirror(国内镜像);失败都自动回落另一个' },
|
|
77
|
+
offline: { type: 'boolean', desc: '只读本地缓存,不联网(没缓存就报错并贴出该访问的 URL)' },
|
|
78
|
+
force: { type: 'boolean', desc: '强制重下并覆盖已存在的目标目录' },
|
|
79
|
+
},
|
|
80
|
+
examples: [
|
|
81
|
+
'wkgeo template init',
|
|
82
|
+
'wkgeo template init --to templates',
|
|
83
|
+
'wkgeo template init --registry npmmirror',
|
|
84
|
+
'wkgeo template init --version 1.0.0 --force',
|
|
85
|
+
'wkgeo template init --offline --json',
|
|
86
|
+
],
|
|
87
|
+
notes: [
|
|
88
|
+
`包名固定 \`${PACKAGE_NAME}\`(scoped 公开包,MIT);镜像为 registry.npmmirror.com。`,
|
|
89
|
+
'下载后会校验 `dist.integrity`(sha512),不符**立即失败并删临时文件**,不会"换个源再试试"。',
|
|
90
|
+
'解包拒绝 `..` / 绝对路径 / 盘符 / 符号链接,且只落白名单条目(assets / starter / tools + 元数据)。',
|
|
91
|
+
'缓存 `~/.wkgeo/cache/base/<version>/`;第二次 init 命中缓存不发请求,`--force` 强制重下。',
|
|
92
|
+
'`--offline` 无缓存时退出码 1,错误里会贴出该能访问的两个 registry URL 与本地缓存路径。',
|
|
93
|
+
'装完自动跑包内 `tools/check-base.mjs starter`(自检不过 = 退出码 1,目录会留着便于排查)。',
|
|
94
|
+
'小坑:`--version` **必须带值**(`--version 1.0.0`);只写 `--version` 是全局行为「打印 CLI 版本」。',
|
|
95
|
+
],
|
|
96
|
+
async run(ctx) {
|
|
97
|
+
const { out, flags } = ctx;
|
|
98
|
+
const t0 = Date.now();
|
|
99
|
+
const log = (s) => out.line(String(s));
|
|
100
|
+
|
|
101
|
+
const cacheRoot = cacheRootOf(ctx.env || process.env);
|
|
102
|
+
const plan = registryPlan(flags.registry === undefined ? null : String(flags.registry), ctx.env || process.env);
|
|
103
|
+
const wanted = flags.version ? String(flags.version).trim() : null;
|
|
104
|
+
const offline = flags.offline === true;
|
|
105
|
+
const force = flags.force === true;
|
|
106
|
+
|
|
107
|
+
if (!out.json) {
|
|
108
|
+
out.head(`基础库模板下载(${PACKAGE_NAME})`);
|
|
109
|
+
log(` 缓存目录 ${cacheRoot}${offline ? ' · 离线模式(只读缓存)' : ''}`);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
let record = null;
|
|
113
|
+
let cacheHit = false;
|
|
114
|
+
|
|
115
|
+
// ---- 1) 离线:只读缓存 ----
|
|
116
|
+
if (offline) {
|
|
117
|
+
const versions = listCachedVersions(cacheRoot);
|
|
118
|
+
const pick = wanted || readLatestPointer(cacheRoot) || versions[versions.length - 1] || null;
|
|
119
|
+
const hit = pick ? readCache(cacheRoot, pick) : null;
|
|
120
|
+
if (!hit) {
|
|
121
|
+
const urls = plan.map((r) => metadataUrl(r.base)).join('\n - ');
|
|
122
|
+
throw new CliError(
|
|
123
|
+
`离线模式没有可用缓存${wanted ? `(要 ${wanted})` : ''}:${cacheRoot} 下没有完整版本。\n` +
|
|
124
|
+
` 可用版本:${versions.length ? versions.join(', ') : '(空)'}\n` +
|
|
125
|
+
` 联网执行一次即可填充缓存:wkgeo template init${wanted ? ` --version ${wanted}` : ''}\n` +
|
|
126
|
+
` 该能访问的 registry:\n - ${urls}`,
|
|
127
|
+
{ kind: 'cache', code: 'ECACHEMISS', hint: '去掉 --offline 重跑,或换 --registry npmmirror' },
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
cacheHit = true;
|
|
131
|
+
record = { ...hit.meta, cache: { hit: true, dir: hit.dir, pkgDir: hit.pkgDir }, timings: { totalMs: 0 }, registryLabel: hit.meta.registry_base };
|
|
132
|
+
if (!out.json) log(` ✓ 命中缓存 ${pick}(${hit.counted.files} 文件 / ${fmtBytes(hit.counted.bytes)})`);
|
|
133
|
+
} else {
|
|
134
|
+
// ---- 2) 在线:先看缓存(`--version` 指定版本,或缓存里的 latest 指针)----
|
|
135
|
+
if (!force) {
|
|
136
|
+
const candidate = wanted || readLatestPointer(cacheRoot);
|
|
137
|
+
const hit = candidate ? readCache(cacheRoot, candidate) : null;
|
|
138
|
+
if (hit) {
|
|
139
|
+
cacheHit = true;
|
|
140
|
+
record = { ...hit.meta, cache: { hit: true, dir: hit.dir, pkgDir: hit.pkgDir }, timings: { totalMs: 0 }, registryLabel: hit.meta.registry_base };
|
|
141
|
+
if (!out.json) log(` ✓ 命中缓存 ${candidate}(${hit.counted.files} 文件 / ${fmtBytes(hit.counted.bytes)})· 未联网(--force 可强制重下)`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
if (!record) {
|
|
145
|
+
if (!out.json) log(' 正在读 registry 元数据…');
|
|
146
|
+
record = await downloadToCache({
|
|
147
|
+
fetchImpl: ctx.fetchImpl,
|
|
148
|
+
plan,
|
|
149
|
+
wanted,
|
|
150
|
+
cacheRoot,
|
|
151
|
+
timeoutMs: Number(ctx.flags['http-timeout'] || 30000),
|
|
152
|
+
log: out.json ? null : log,
|
|
153
|
+
});
|
|
154
|
+
if (!out.json) {
|
|
155
|
+
log(` 来源 ${record.registryLabel} · ${record.version} · ${fmtBytes(record.size_bytes)} · ${record.file_count} 文件`);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// ---- 3) 落地 ----
|
|
161
|
+
const dirName = packageDirName(record.cache.pkgDir);
|
|
162
|
+
const { target } = resolveTarget(flags.to === undefined ? null : String(flags.to), dirName, process.cwd());
|
|
163
|
+
|
|
164
|
+
const existed = fs.existsSync(target) && fs.readdirSync(target).length > 0;
|
|
165
|
+
if (existed && !force) {
|
|
166
|
+
throw new CliError(`目标目录已存在且不为空:${target}`, {
|
|
167
|
+
kind: 'usage',
|
|
168
|
+
code: 'EEXIST',
|
|
169
|
+
exitCode: 2,
|
|
170
|
+
hint: '加 `--force` 覆盖,或换一个 `--to <父目录>`',
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
if (existed && force) {
|
|
174
|
+
if (!out.json) log(` 覆盖已有目录 ${target}`);
|
|
175
|
+
fs.rmSync(target, { recursive: true, force: true });
|
|
176
|
+
}
|
|
177
|
+
copyTree(record.cache.pkgDir, target);
|
|
178
|
+
|
|
179
|
+
const installed = (() => {
|
|
180
|
+
let files = 0;
|
|
181
|
+
let bytes = 0;
|
|
182
|
+
const walk = (d) => {
|
|
183
|
+
for (const it of fs.readdirSync(d, { withFileTypes: true })) {
|
|
184
|
+
const p = path.join(d, it.name);
|
|
185
|
+
if (it.isDirectory()) walk(p);
|
|
186
|
+
else if (it.isFile()) {
|
|
187
|
+
files += 1;
|
|
188
|
+
bytes += fs.statSync(p).size;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
walk(target);
|
|
193
|
+
return { files, bytes };
|
|
194
|
+
})();
|
|
195
|
+
|
|
196
|
+
// ---- 4) 自检 ----
|
|
197
|
+
const finalCheck = selfCheck(target);
|
|
198
|
+
|
|
199
|
+
const versionsFile = readJsonSafe(path.join(target, 'versions.json')) || {};
|
|
200
|
+
const versionFile = (() => {
|
|
201
|
+
try {
|
|
202
|
+
return fs.readFileSync(path.join(target, 'VERSION'), 'utf8').trim();
|
|
203
|
+
} catch {
|
|
204
|
+
return '';
|
|
205
|
+
}
|
|
206
|
+
})();
|
|
207
|
+
|
|
208
|
+
if (!out.json) {
|
|
209
|
+
if (!finalCheck.ok) {
|
|
210
|
+
out.warn(`自检未通过(${finalCheck.mode}):${finalCheck.detail}`);
|
|
211
|
+
}
|
|
212
|
+
out.ok(
|
|
213
|
+
`已安装到 ${target}(${installed.files} 文件 / ${fmtBytes(installed.bytes)})` +
|
|
214
|
+
`${cacheHit ? ' · 缓存命中' : ''}`,
|
|
215
|
+
);
|
|
216
|
+
log(` VERSION ${versionFile || '?'} · 内容版本 ${versionsFile.contentVersion || '?'} · 来自 ${record.registry_base || record.registry}`);
|
|
217
|
+
log(` 自检 ${finalCheck.mode}:${finalCheck.ok ? 'PASS' : 'FAIL'} — ${finalCheck.detail}`);
|
|
218
|
+
log(` 耗时 ${Date.now() - t0}ms`);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const payload = {
|
|
222
|
+
package: PACKAGE_NAME,
|
|
223
|
+
version: record.version,
|
|
224
|
+
content_version: versionsFile.contentVersion || null,
|
|
225
|
+
version_file: versionFile || null,
|
|
226
|
+
registry: record.registry || null,
|
|
227
|
+
registry_base: record.registry_base || record.registryLabel || null,
|
|
228
|
+
tarball: record.tarball || null,
|
|
229
|
+
integrity: record.integrity || null,
|
|
230
|
+
size_bytes: record.size_bytes || null,
|
|
231
|
+
file_count: record.file_count || null,
|
|
232
|
+
target,
|
|
233
|
+
files_written: installed.files,
|
|
234
|
+
bytes_written: installed.bytes,
|
|
235
|
+
cache_hit: cacheHit,
|
|
236
|
+
cache_dir: record.cache.dir,
|
|
237
|
+
self_check: {
|
|
238
|
+
ok: finalCheck.ok,
|
|
239
|
+
mode: finalCheck.mode,
|
|
240
|
+
detail: finalCheck.detail,
|
|
241
|
+
exit_code: finalCheck.exitCode,
|
|
242
|
+
},
|
|
243
|
+
elapsed_ms: Date.now() - t0,
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
// 自检不过:目录留着便于排查,但**退出码必须非 0**(否则"装坏了"在 CI 里看不出来)
|
|
247
|
+
if (!finalCheck.ok) {
|
|
248
|
+
throw new CliError(`安装完成但自检未通过(${finalCheck.mode}):${finalCheck.detail}`, {
|
|
249
|
+
kind: 'verify',
|
|
250
|
+
code: 'ECHECKFAIL',
|
|
251
|
+
hint: `目录已保留在 ${target},可手工跑 \`node ${path.join(target, 'tools', 'check-base.mjs')} starter\` 看明细`,
|
|
252
|
+
raw: payload,
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
ctx.done(payload);
|
|
257
|
+
},
|
|
258
|
+
};
|
package/lib/tar.mjs
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 极简 tar.gz 读取器(node 内置 zlib,**零第三方依赖**)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么手写:`wkgeo template init` 要从 registry 下 `.tgz` 并解包,而 CLI 的硬约定是
|
|
5
|
+
* **零依赖**(见 cli/README)。tar 格式本身只有 512 字节定长头 + 512 对齐的数据块,
|
|
6
|
+
* 只需要支持 npm pack 实际会产出的三种记录:
|
|
7
|
+
* * `0` / `\0` —— 普通文件
|
|
8
|
+
* * `5` —— 目录
|
|
9
|
+
* * `x` / `g` / `L` / `K` —— PAX 扩展头 / GNU 长名(npm 打包长路径时会出现)
|
|
10
|
+
* 符号链接 / 硬链接 / 设备文件**一律拒绝**(防止压缩包把文件写到目标目录外面去)。
|
|
11
|
+
*
|
|
12
|
+
* 安全边界都收在 `safeEntryPath()` 一处:绝对路径、盘符(`C:`)、任何 `..` 段、
|
|
13
|
+
* 反斜杠路径穿越,统统抛错;解包时再 `resolve()` 复核一次目标仍在根目录内。
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import zlib from 'node:zlib';
|
|
19
|
+
|
|
20
|
+
const BLOCK = 512;
|
|
21
|
+
|
|
22
|
+
function cstr(buf, off, len) {
|
|
23
|
+
const slice = buf.subarray(off, off + len);
|
|
24
|
+
const end = slice.indexOf(0);
|
|
25
|
+
return slice.toString('utf8', 0, end === -1 ? slice.length : end);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function octal(buf, off, len) {
|
|
29
|
+
const raw = cstr(buf, off, len).trim();
|
|
30
|
+
if (!raw) return 0;
|
|
31
|
+
// base-256(大文件用):首字节最高位为 1
|
|
32
|
+
if (buf[off] & 0x80) {
|
|
33
|
+
let n = 0;
|
|
34
|
+
for (let i = off + 1; i < off + len; i += 1) n = n * 256 + buf[i];
|
|
35
|
+
return n;
|
|
36
|
+
}
|
|
37
|
+
const n = parseInt(raw.replace(/[^0-7]/g, ''), 8);
|
|
38
|
+
return Number.isFinite(n) ? n : 0;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** PAX 记录:`<len> <key>=<value>\n` 串联 */
|
|
42
|
+
function parsePax(data) {
|
|
43
|
+
const out = {};
|
|
44
|
+
let pos = 0;
|
|
45
|
+
while (pos < data.length) {
|
|
46
|
+
const sp = data.indexOf(0x20, pos);
|
|
47
|
+
if (sp === -1) break;
|
|
48
|
+
const len = parseInt(data.toString('latin1', pos, sp), 10);
|
|
49
|
+
if (!Number.isFinite(len) || len <= 0) break;
|
|
50
|
+
const record = data.toString('utf8', sp + 1, pos + len - 1); // 去掉尾部 \n
|
|
51
|
+
const eq = record.indexOf('=');
|
|
52
|
+
if (eq > 0) out[record.slice(0, eq)] = record.slice(eq + 1);
|
|
53
|
+
pos += len;
|
|
54
|
+
}
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 读 tar.gz,返回条目数组(**只含普通文件与目录**,带数据)。
|
|
60
|
+
* @param {Buffer} gzBuffer .tgz 原始字节
|
|
61
|
+
* @returns {Array<{path:string,type:'file'|'dir',mode:number,size:number,data:Buffer|null}>}
|
|
62
|
+
*/
|
|
63
|
+
export function readTarGz(gzBuffer) {
|
|
64
|
+
const buf = zlib.gunzipSync(gzBuffer);
|
|
65
|
+
const entries = [];
|
|
66
|
+
let pos = 0;
|
|
67
|
+
let pendingLongName = null;
|
|
68
|
+
let pendingPax = null;
|
|
69
|
+
|
|
70
|
+
while (pos + BLOCK <= buf.length) {
|
|
71
|
+
const header = buf.subarray(pos, pos + BLOCK);
|
|
72
|
+
// 全零块 = 结束(正常会有两块,一块也照停)
|
|
73
|
+
if (header.every((b) => b === 0)) break;
|
|
74
|
+
|
|
75
|
+
const name = cstr(header, 0, 100);
|
|
76
|
+
const mode = octal(header, 100, 8);
|
|
77
|
+
const size = octal(header, 124, 12);
|
|
78
|
+
const typeflag = String.fromCharCode(header[156] || 0x30);
|
|
79
|
+
const prefix = cstr(header, 345, 155);
|
|
80
|
+
const dataStart = pos + BLOCK;
|
|
81
|
+
const dataEnd = dataStart + size;
|
|
82
|
+
|
|
83
|
+
// 校验和(只用来发现"这不是 tar",不用于安全)
|
|
84
|
+
let sum = 0;
|
|
85
|
+
for (let i = 0; i < BLOCK; i += 1) sum += i >= 148 && i < 156 ? 0x20 : header[i];
|
|
86
|
+
const want = octal(header, 148, 8);
|
|
87
|
+
if (want && sum !== want) {
|
|
88
|
+
throw new Error(`tar 头校验和不符(偏移 ${pos}):可能是文件损坏,拒绝解包`);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const data = buf.subarray(dataStart, Math.min(dataEnd, buf.length));
|
|
92
|
+
const next = dataStart + Math.ceil(size / BLOCK) * BLOCK;
|
|
93
|
+
|
|
94
|
+
if (typeflag === 'x' || typeflag === 'g') {
|
|
95
|
+
pendingPax = { ...(pendingPax || {}), ...parsePax(data) };
|
|
96
|
+
pos = next;
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (typeflag === 'L') {
|
|
100
|
+
pendingLongName = cstr(data, 0, data.length);
|
|
101
|
+
pos = next;
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
if (typeflag === 'K') {
|
|
105
|
+
// GNU longlink:目标名,只在链接条目上有意义 —— 链接本身下面会被拒
|
|
106
|
+
pos = next;
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
let entryPath = pendingPax?.path || pendingLongName || (prefix ? `${prefix}/${name}` : name);
|
|
111
|
+
pendingPax = null;
|
|
112
|
+
pendingLongName = null;
|
|
113
|
+
|
|
114
|
+
if (typeflag === '0' || typeflag === '\0' || typeflag === '7') {
|
|
115
|
+
entries.push({ path: entryPath, type: 'file', mode, size, data });
|
|
116
|
+
} else if (typeflag === '5') {
|
|
117
|
+
entries.push({ path: entryPath.replace(/\/+$/, ''), type: 'dir', mode, size: 0, data: null });
|
|
118
|
+
} else if (typeflag === '1' || typeflag === '2') {
|
|
119
|
+
throw new Error(
|
|
120
|
+
`压缩包含符号/硬链接条目(${entryPath}),已拒绝解包(防止越界写入)。` +
|
|
121
|
+
'正常 npm 包里不会有链接,这通常意味着包被篡改。',
|
|
122
|
+
);
|
|
123
|
+
} else {
|
|
124
|
+
throw new Error(`压缩包含不支持的条目类型 ${JSON.stringify(typeflag)}(${entryPath}),已拒绝解包`);
|
|
125
|
+
}
|
|
126
|
+
pos = next;
|
|
127
|
+
}
|
|
128
|
+
return entries;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* 把条目路径变成安全的相对路径(**所有越界判定只在这里**)。
|
|
133
|
+
* @param {string} raw tar 里的路径
|
|
134
|
+
* @param {string} [stripPrefix] 去掉的前缀(npm 包是 `package/`)
|
|
135
|
+
*/
|
|
136
|
+
export function safeEntryPath(raw, stripPrefix = '') {
|
|
137
|
+
let p = String(raw || '');
|
|
138
|
+
if (stripPrefix && p.startsWith(stripPrefix)) p = p.slice(stripPrefix.length);
|
|
139
|
+
p = p.replace(/^\.\//, '');
|
|
140
|
+
if (!p) return '';
|
|
141
|
+
if (p.includes('\\')) throw new Error(`压缩包路径含反斜杠(${raw}),拒绝解包`);
|
|
142
|
+
if (/^[a-zA-Z]:/.test(p)) throw new Error(`压缩包路径含盘符(${raw}),拒绝解包`);
|
|
143
|
+
if (p.startsWith('/')) throw new Error(`压缩包路径是绝对路径(${raw}),拒绝解包`);
|
|
144
|
+
const parts = p.split('/');
|
|
145
|
+
if (parts.some((s) => s === '..')) throw new Error(`压缩包路径含 ..(${raw}),拒绝解包`);
|
|
146
|
+
if (parts.some((s) => s === '.' && parts.length > 1) || parts.includes('')) {
|
|
147
|
+
// 空的中间段(`a//b`)只是写法怪,抹平即可,不算攻击
|
|
148
|
+
p = parts.filter((s) => s && s !== '.').join('/');
|
|
149
|
+
}
|
|
150
|
+
return p;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* 解包到目录。**先校验全部条目再落盘**:一个坏条目都不写。
|
|
155
|
+
* @returns {{files:number,dirs:number,bytes:number}}
|
|
156
|
+
*/
|
|
157
|
+
export function extractTarGz(gzBuffer, destDir, { stripPrefix = 'package/', allowTop = null } = {}) {
|
|
158
|
+
const entries = readTarGz(gzBuffer);
|
|
159
|
+
const root = path.resolve(destDir);
|
|
160
|
+
const allow = Array.isArray(allowTop) ? new Set(allowTop) : null;
|
|
161
|
+
const plan = [];
|
|
162
|
+
const skipped = [];
|
|
163
|
+
let bytes = 0;
|
|
164
|
+
let fileCount = 0;
|
|
165
|
+
|
|
166
|
+
for (const one of entries) {
|
|
167
|
+
const rel = safeEntryPath(one.path, stripPrefix);
|
|
168
|
+
if (!rel) continue;
|
|
169
|
+
if (allow) {
|
|
170
|
+
const top = rel.split('/')[0];
|
|
171
|
+
if (!allow.has(top)) {
|
|
172
|
+
// 白名单外的东西**不落盘**,但记下来(报告里要能看见"包里多了什么")
|
|
173
|
+
skipped.push(rel);
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
const abs = path.resolve(root, rel);
|
|
178
|
+
if (abs !== root && !abs.startsWith(root + path.sep)) {
|
|
179
|
+
throw new Error(`压缩包条目越界(${one.path}),拒绝解包`);
|
|
180
|
+
}
|
|
181
|
+
if (one.type === 'file') {
|
|
182
|
+
bytes += one.size;
|
|
183
|
+
fileCount += 1;
|
|
184
|
+
}
|
|
185
|
+
plan.push({ ...one, rel, abs });
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
fs.mkdirSync(root, { recursive: true });
|
|
189
|
+
let dirCount = 0;
|
|
190
|
+
for (const one of plan) {
|
|
191
|
+
if (one.type === 'dir') {
|
|
192
|
+
fs.mkdirSync(one.abs, { recursive: true });
|
|
193
|
+
dirCount += 1;
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
fs.mkdirSync(path.dirname(one.abs), { recursive: true });
|
|
197
|
+
fs.writeFileSync(one.abs, one.data);
|
|
198
|
+
if (one.mode) {
|
|
199
|
+
try {
|
|
200
|
+
fs.chmodSync(one.abs, one.mode & 0o777);
|
|
201
|
+
} catch {
|
|
202
|
+
/* Windows 上 chmod 基本无效,忽略 */
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return { files: fileCount, dirs: dirCount, bytes, skipped };
|
|
207
|
+
}
|