dsh-modpack-kit 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,223 @@
1
+ /**
2
+ * dsh-modpack —— 从 npm / 插件市场源取包。
3
+ *
4
+ * 只信任 https;主机名必须在 allowHosts 里;重定向每一跳都重新校验
5
+ * (不然一个 302 就能把请求带到任意地址)。下载有体积上限,拿到 tarball
6
+ * 后先核对 registry 给的 sha512,再解包。
7
+ */
8
+ import { createHash } from 'node:crypto'
9
+ import { readTarball, stripPackagePrefix } from './tar.mjs'
10
+ import { parseVersion, satisfies, compareVersions } from './semver.mjs'
11
+
12
+ const NAME_RE = /^(?:@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/iu
13
+ const TIMEOUT_MS = 30000
14
+
15
+ export function assertAllowedUrl(url, config) {
16
+ let parsed
17
+ try {
18
+ parsed = new URL(url)
19
+ } catch {
20
+ throw new Error('地址无法解析:' + String(url).slice(0, 200))
21
+ }
22
+ if (parsed.protocol !== 'https:') throw new Error('只允许 https 地址:' + parsed.protocol)
23
+ const host = parsed.hostname.toLowerCase()
24
+ const allowed = Array.isArray(config?.allowHosts) && config.allowHosts.length > 0 ? config.allowHosts : ['registry.npmjs.org']
25
+ if (!allowed.some((h) => host === h.toLowerCase() || host.endsWith('.' + h.toLowerCase()))) {
26
+ throw new Error('主机不在允许列表:' + host + '(可在设置里添加)')
27
+ }
28
+ return parsed
29
+ }
30
+
31
+ /** 手工跟重定向,每一跳都校验主机与协议。 */
32
+ export async function fetchLimited(url, config, options = {}) {
33
+ const maxBytes = options.maxBytes ?? config?.maxDownloadBytes ?? 128 * 1024 * 1024
34
+ let current = url
35
+ for (let hop = 0; hop < 6; hop += 1) {
36
+ assertAllowedUrl(current, config)
37
+ const res = await fetch(current, {
38
+ redirect: 'manual',
39
+ signal: AbortSignal.timeout(options.timeoutMs ?? TIMEOUT_MS),
40
+ headers: { 'user-agent': 'dsh-modpack', accept: options.accept ?? '*/*' },
41
+ })
42
+ if (res.status >= 300 && res.status < 400) {
43
+ const location = res.headers.get('location')
44
+ if (!location) throw new Error('重定向没有 location:' + current)
45
+ current = new URL(location, current).href
46
+ continue
47
+ }
48
+ if (!res.ok) throw new Error('HTTP ' + res.status + ':' + current)
49
+ const length = Number(res.headers.get('content-length') || '0')
50
+ if (length > maxBytes) throw new Error('响应体过大(' + length + ' 字节)')
51
+ if (!res.body) return Buffer.alloc(0)
52
+ const chunks = []
53
+ let total = 0
54
+ const reader = res.body.getReader()
55
+ for (;;) {
56
+ const { done, value } = await reader.read()
57
+ if (done) break
58
+ total += value.length
59
+ if (total > maxBytes) {
60
+ try { await reader.cancel() } catch {}
61
+ throw new Error('下载超过上限(' + maxBytes + ' 字节)')
62
+ }
63
+ chunks.push(Buffer.from(value))
64
+ }
65
+ return Buffer.concat(chunks)
66
+ }
67
+ throw new Error('重定向次数过多:' + url)
68
+ }
69
+
70
+ export async function fetchJson(url, config, options = {}) {
71
+ const buf = await fetchLimited(url, config, { ...options, maxBytes: options.maxBytes ?? 16 * 1024 * 1024, accept: 'application/json' })
72
+ try {
73
+ return JSON.parse(buf.toString('utf8'))
74
+ } catch {
75
+ throw new Error('返回内容不是 JSON:' + url)
76
+ }
77
+ }
78
+
79
+ export function validatePackageName(name) {
80
+ if (typeof name !== 'string' || name.length > 214 || !NAME_RE.test(name)) {
81
+ throw new Error('不是合法的 npm 包名:' + String(name).slice(0, 80))
82
+ }
83
+ return name
84
+ }
85
+
86
+ /** 依次尝试每个 registry,第一个成功的算。 */
87
+ export async function npmMetadata(name, config) {
88
+ validatePackageName(name)
89
+ const registries = Array.isArray(config?.registries) && config.registries.length > 0
90
+ ? config.registries
91
+ : ['https://registry.npmjs.org']
92
+ const errors = []
93
+ for (const base of registries) {
94
+ try {
95
+ const url = base.replace(/\/+$/u, '') + '/' + encodeURIComponent(name).replace(/^%40/u, '@')
96
+ const meta = await fetchJson(url, config, { accept: 'application/json' })
97
+ if (!meta || typeof meta !== 'object' || !meta.versions) throw new Error('元数据缺少 versions')
98
+ return { meta, registry: base.replace(/\/+$/u, '') }
99
+ } catch (error) {
100
+ errors.push(base + ' → ' + String(error?.message || error))
101
+ }
102
+ }
103
+ throw new Error('registry 都失败了:' + errors.join(';'))
104
+ }
105
+
106
+ /** 选版本:精确版 > dist-tags.latest > 范围里最高的稳定版。 */
107
+ export function pickVersion(meta, spec) {
108
+ const versions = Object.keys(meta.versions || {})
109
+ if (versions.length === 0) throw new Error('该包没有任何版本')
110
+ const wanted = typeof spec === 'string' && spec.trim() !== '' && spec !== 'latest' ? spec.trim() : ''
111
+ if (wanted && meta.versions[wanted]) return wanted
112
+ if (!wanted) {
113
+ const latest = meta['dist-tags'] && meta['dist-tags'].latest
114
+ if (latest && meta.versions[latest]) return latest
115
+ }
116
+ const candidates = versions
117
+ .filter((v) => (wanted ? satisfies(v, wanted) === true : true))
118
+ .sort((a, b) => (compareVersions(b, a) ?? 0))
119
+ if (candidates.length === 0) throw new Error('没有版本满足「' + (wanted || 'latest') + '」')
120
+ const stable = candidates.find((v) => !parseVersion(v)?.pre)
121
+ return stable || candidates[0]
122
+ }
123
+
124
+ export function relativeTime(iso) {
125
+ const t = Date.parse(iso)
126
+ if (!Number.isFinite(t)) return ''
127
+ const days = Math.round((Date.now() - t) / 86400000)
128
+ return days <= 0 ? '今天' : days + ' 天前'
129
+ }
130
+
131
+ /**
132
+ * 下载并解析一个 npm 包。
133
+ * @returns {Promise<{name, version, registry, tarball, integrity, sha256, license, repository, pkg, entries, files, unpackedBytes}>}
134
+ */
135
+ export async function downloadPackage(name, spec, config) {
136
+ const { meta, registry } = await npmMetadata(name, config)
137
+ const version = pickVersion(meta, spec)
138
+ const manifest = meta.versions[version]
139
+ if (!manifest || !manifest.dist || !manifest.dist.tarball) throw new Error('版本 ' + version + ' 没有 tarball')
140
+ const tarballUrl = new URL(manifest.dist.tarball, registry + '/').href
141
+ assertAllowedUrl(tarballUrl, config)
142
+ const tgz = await fetchLimited(tarballUrl, config, { maxBytes: config?.maxDownloadBytes })
143
+ const expected = typeof manifest.dist.integrity === 'string' ? manifest.dist.integrity : ''
144
+ if (expected.startsWith('sha512-')) {
145
+ const actual = 'sha512-' + createHash('sha512').update(tgz).digest('base64')
146
+ if (actual !== expected) throw new Error('tarball 校验失败(sha512 不符):' + name + '@' + version)
147
+ }
148
+ const entries = stripPackagePrefix(readTarball(tgz))
149
+ const pkgEntry = entries.find((e) => e.name === 'package.json')
150
+ if (!pkgEntry) throw new Error('包里没有 package.json:' + name)
151
+ let pkg
152
+ try {
153
+ pkg = JSON.parse(pkgEntry.data.toString('utf8'))
154
+ } catch {
155
+ throw new Error('package.json 不是合法 JSON:' + name)
156
+ }
157
+ return {
158
+ name: pkg.name || name,
159
+ version: pkg.version || version,
160
+ registry,
161
+ tarball: tarballUrl,
162
+ integrity: expected,
163
+ sha256: 'sha256-' + createHash('sha256').update(tgz).digest('hex'),
164
+ license: typeof pkg.license === 'string' ? pkg.license : (pkg.license && pkg.license.type) || '',
165
+ repository: typeof pkg.repository === 'string' ? pkg.repository : (pkg.repository && pkg.repository.url) || '',
166
+ pkg,
167
+ entries,
168
+ unpackedBytes: entries.reduce((sum, e) => sum + e.data.length, 0),
169
+ }
170
+ }
171
+
172
+ /** 市场目录(awesome-dsh-plugin.com),失败就返回空——它只是锦上添花。 */
173
+ /**
174
+ * 插件市场目录。官方站点在国内经常连不上或极慢,所以:
175
+ * 先试官方 JSON(短超时,不让页面干等),失败就退回 npm 搜索。
176
+ * 两条路都失败时返回空数组,调用方展示"目录不可用"而不是白屏。
177
+ */
178
+ export async function fetchCatalog(config) {
179
+ try {
180
+ const data = await fetchJson('https://awesome-dsh-plugin.com/plugins.json', config, {
181
+ maxBytes: 8 * 1024 * 1024,
182
+ timeoutMs: 8000,
183
+ })
184
+ const list = Array.isArray(data) ? data : (Array.isArray(data?.plugins) ? data.plugins : [])
185
+ if (list.length > 0) return list
186
+ } catch {
187
+ // 站点慢/被挡,走 npm 兜底
188
+ }
189
+ return npmSearchCatalog(config)
190
+ }
191
+
192
+ /** npm 搜索兜底:以 keywords 找同类插件,字段摊平成官方目录的近似形状。 */
193
+ export async function npmSearchCatalog(config) {
194
+ const queries = ['keywords:dsh-plugin', 'keywords:dsh-bundle']
195
+ const seen = new Map()
196
+ for (const text of queries) {
197
+ const url = 'https://registry.npmjs.org/-/v1/search?size=250&text=' + encodeURIComponent(text)
198
+ try {
199
+ const data = await fetchJson(url, config, { maxBytes: 8 * 1024 * 1024, timeoutMs: 20000 })
200
+ const objects = Array.isArray(data?.objects) ? data.objects : []
201
+ for (const entry of objects) {
202
+ const pkg = entry && entry.package
203
+ if (!pkg || !pkg.name || seen.has(pkg.name)) continue
204
+ const repo = pkg.links?.repository || (pkg.repository && (pkg.repository.url || pkg.repository)) || ''
205
+ const author = pkg.author && typeof pkg.author === 'object' ? pkg.author.name || '' : pkg.author || ''
206
+ seen.set(pkg.name, {
207
+ name: pkg.name,
208
+ title: pkg.name,
209
+ description: String(pkg.description || ''),
210
+ version: String(pkg.version || ''),
211
+ author: String(author || ''),
212
+ repository: String(repo || ''),
213
+ license: String(pkg.license || ''),
214
+ tags: Array.isArray(pkg.keywords) ? pkg.keywords.slice(0, 10) : [],
215
+ source: 'npm-search',
216
+ })
217
+ }
218
+ } catch {
219
+ // 单个查询失败不影响另一个
220
+ }
221
+ }
222
+ return [...seen.values()]
223
+ }
package/lib/scan.mjs ADDED
@@ -0,0 +1,278 @@
1
+ /**
2
+ * dsh-modpack —— 安全检测:敏感信息与恶意代码痕迹。
3
+ *
4
+ * 三条硬规矩(也写进 README 给使用者看):
5
+ * 1. 检测在内存里完成,命中的原文**不写盘、不回传**;报告里只有规则名、
6
+ * 文件、行号和打码片段。
7
+ * 2. 只做静态特征匹配,不是杀毒引擎;结论是「发现可疑」而不是「保证安全」。
8
+ * 3. 高风险默认阻断打包/安装,必须使用者显式确认才继续,确认会记进报告。
9
+ *
10
+ * 规则表是数据,扩展接口 `registerScanner` 可以往里加规则,不用改这个文件。
11
+ */
12
+
13
+ const TEXT_EXT = new Set([
14
+ '.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx', '.json', '.yml', '.yaml', '.toml', '.ini', '.cfg',
15
+ '.md', '.txt', '.sh', '.bash', '.ps1', '.bat', '.cmd', '.py', '.html', '.css', '.xml', '.env',
16
+ '.lock', '.gitignore', '.npmrc', '.vue', '.svelte',
17
+ ])
18
+
19
+ const BINARY_EXT = new Set(['.exe', '.dll', '.scr', '.msi', '.com', '.sys', '.drv', '.so', '.dylib', '.node'])
20
+ const IMAGE_EXT = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.ico', '.bmp', '.avif'])
21
+ const SCRIPT_EXT = new Set(['.ps1', '.bat', '.cmd', '.vbs', '.hta', '.jar'])
22
+
23
+ const MAX_SCAN_BYTES = 2 * 1024 * 1024
24
+
25
+ /** @typedef {'high'|'medium'|'low'} Severity */
26
+
27
+ const SECRET_RULES = [
28
+ { id: 'secret.private-key', severity: 'high', category: 'secret', label: '私钥文件内容', re: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY-----/gu },
29
+ { id: 'secret.aws-key', severity: 'high', category: 'secret', label: 'AWS 访问密钥', re: /\bAKIA[0-9A-Z]{16}\b/gu },
30
+ { id: 'secret.github-token', severity: 'high', category: 'secret', label: 'GitHub 令牌', re: /\bgh[pousr]_[A-Za-z0-9]{36,}\b/gu },
31
+ { id: 'secret.github-pat', severity: 'high', category: 'secret', label: 'GitHub 细粒度令牌', re: /\bgithub_pat_[A-Za-z0-9_]{20,}\b/gu },
32
+ { id: 'secret.slack-token', severity: 'high', category: 'secret', label: 'Slack 令牌', re: /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/gu },
33
+ { id: 'secret.api-key', severity: 'high', category: 'secret', label: 'API Key(sk- 形式)', re: /\bsk-[A-Za-z0-9_-]{20,}\b/gu },
34
+ { id: 'secret.jwt', severity: 'high', category: 'secret', label: 'JWT', re: /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/gu },
35
+ // 只认“字段 = 真实值”:代码里的属性访问(cookie.bili_jct、raw.SESSDATA)不算,避免把正常插件误判成夹带 Cookie
36
+ { id: 'secret.bili-cookie', severity: 'high', category: 'secret', label: 'B站登录 Cookie', re: /\b(?:SESSDATA|bili_jct|DedeUserID|buvid3|buvid4|ac_time_value)\b\s*[=:]\s*(?:["'][^"'\n]{8,}["']|[A-Za-z0-9%_-]{8,})/gu },
37
+ { id: 'secret.cookie-header', severity: 'high', category: 'secret', label: 'Cookie 请求头', re: /\bcookie\s*[:=]\s*["']?[A-Za-z0-9_%-]{6,}=[^\s"']{8,}/giu },
38
+ { id: 'secret.generic-assign', severity: 'medium', category: 'secret', label: '疑似密钥赋值', re: /\b(?:api[_-]?key|secret|password|passwd|access[_-]?token|auth[_-]?token)\b\s*[:=]\s*["'][^"'\n]{8,}["']/giu },
39
+ { id: 'secret.private-path', severity: 'medium', category: 'privacy', label: '本机用户目录路径', re: /[A-Za-z]:\\Users\\[^\\\s"']+/gu },
40
+ { id: 'privacy.email', severity: 'medium', category: 'privacy', label: '电子邮箱', re: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/gu },
41
+ { id: 'privacy.cn-phone', severity: 'medium', category: 'privacy', label: '手机号', re: /(?<!\d)1[3-9]\d{9}(?!\d)/gu },
42
+ { id: 'privacy.cn-id', severity: 'high', category: 'privacy', label: '身份证号', re: /(?<!\d)[1-9]\d{5}(?:19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dXx](?!\d)/gu },
43
+ { id: 'privacy.private-ip', severity: 'low', category: 'privacy', label: '内网地址', re: /\b(?:10\.\d{1,3}|192\.168|172\.(?:1[6-9]|2\d|3[01]))\.\d{1,3}\.\d{1,3}\b/gu },
44
+ ]
45
+
46
+ const MALWARE_RULES = [
47
+ { id: 'malware.remote-pipe', severity: 'high', label: '远程脚本直接执行', re: /\b(?:curl|wget)\b[^\n|]{0,200}\|\s*(?:sudo\s+)?(?:ba|z)?sh\b/gu },
48
+ { id: 'malware.powershell-iex', severity: 'high', label: '下载后 iex 执行', re: /\b(?:Invoke-Expression|iex)\b[^\n]{0,120}(?:DownloadString|Invoke-WebRequest|iwr|curl)/giu },
49
+ { id: 'malware.powershell-encoded', severity: 'high', label: 'PowerShell 编码命令', re: /(?:-enc(?:odedcommand)?\s+)[A-Za-z0-9+/=]{40,}/giu },
50
+ { id: 'malware.eval', severity: 'medium', label: '动态执行代码', re: /\b(?:eval|new\s+Function)\s*\(/gu },
51
+ { id: 'malware.child-process', severity: 'medium', label: '调用子进程', re: /\b(?:child_process|execSync|spawnSync|execFileSync|exec)\s*[(`]/gu },
52
+ { id: 'malware.obfuscation', severity: 'medium', label: '疑似混淆(长 base64)', re: /["'][A-Za-z0-9+/]{600,}={0,2}["']/gu },
53
+ { id: 'malware.hex-escape', severity: 'low', label: '大量十六进制转义', re: /(?:\\x[0-9a-fA-F]{2}){20,}/gu },
54
+ { id: 'malware.disabled-tls', severity: 'medium', label: '关闭 TLS 校验', re: /rejectUnauthorized\s*:\s*false|NODE_TLS_REJECT_UNAUTHORIZED\s*=\s*["']?0/gu },
55
+ { id: 'malware.process-env-dump', severity: 'low', label: '读取全部环境变量', re: /JSON\.stringify\s*\(\s*process\.env\s*\)/gu },
56
+ ]
57
+
58
+ const FILE_NAME_RULES = [
59
+ { id: 'file.private-key', severity: 'high', category: 'secret', label: '私钥/证书文件', re: /(?:^|[\\/])(?:id_(?:rsa|ed25519|ecdsa)|[^\\/]+\.(?:pem|key|p12|pfx|jks|keystore))$/iu },
60
+ { id: 'file.env', severity: 'high', category: 'secret', label: '.env 环境文件', re: /(?:^|[\\/])\.env(?:\.local|\.production|\.development)?$/iu },
61
+ { id: 'file.credential', severity: 'high', category: 'secret', label: '凭证/登录态文件', re: /(?:^|[\\/])[^\\/]*(?:credential|cookie|token|session|auth)[^\\/]*\.(?:json|txt|dat)$/iu },
62
+ ]
63
+
64
+ /** 名字里的命中不看内容,避免把「凭证文件」本身漏掉。 */
65
+ export function scanFileName(name) {
66
+ const hits = []
67
+ for (const rule of FILE_NAME_RULES) {
68
+ rule.re.lastIndex = 0
69
+ if (rule.re.test(name)) hits.push(findingOf(rule, name, 0, ''))
70
+ }
71
+ return hits
72
+ }
73
+
74
+ function maskSecret(text) {
75
+ const s = String(text)
76
+ if (s.length <= 4) return '****'
77
+ return s.slice(0, 2) + '****' + `(${s.length} 字符已隐藏)`
78
+ }
79
+
80
+ function maskAll(text) {
81
+ const s = String(text)
82
+ return s.length > 0 ? '***' : ''
83
+ }
84
+
85
+ function findingOf(rule, file, line, masked) {
86
+ return {
87
+ rule: rule.id,
88
+ severity: rule.severity,
89
+ category: rule.category || 'malware',
90
+ label: rule.label,
91
+ file,
92
+ line,
93
+ masked,
94
+ }
95
+ }
96
+
97
+ export function looksBinary(buf) {
98
+ const n = Math.min(buf.length, 4096)
99
+ for (let i = 0; i < n; i += 1) if (buf[i] === 0) return true
100
+ return false
101
+ }
102
+
103
+ function extOf(name) {
104
+ const base = name.split('/').pop() || ''
105
+ const dot = base.lastIndexOf('.')
106
+ return dot <= 0 ? '' : base.slice(dot).toLowerCase()
107
+ }
108
+
109
+ function lineAt(text, index) {
110
+ let line = 1
111
+ for (let i = 0; i < index && i < text.length; i += 1) if (text.charCodeAt(i) === 10) line += 1
112
+ return line
113
+ }
114
+
115
+ /**
116
+ * 扫一个文件。
117
+ * @param {string} name 相对路径
118
+ * @param {Buffer} data
119
+ * @returns {{findings: object[], skipped?: string}}
120
+ */
121
+ export function scanFile(name, data) {
122
+ const findings = scanFileName(name)
123
+ const ext = extOf(name)
124
+ if (BINARY_EXT.has(ext)) {
125
+ findings.push({ rule: 'file.binary-executable', severity: 'high', category: 'malware', label: '可执行二进制', file: name, line: 0, masked: '' })
126
+ return { findings }
127
+ }
128
+ if (SCRIPT_EXT.has(ext) && !data.toString('utf8', 0, 64).startsWith('#!/usr/bin/env node')) {
129
+ findings.push({ rule: 'file.script', severity: 'low', category: 'malware', label: '脚本文件(请人工确认)', file: name, line: 0, masked: '' })
130
+ }
131
+ if (data.length > MAX_SCAN_BYTES) return { findings, skipped: '文件超过 2MB,仅按文件名检测' }
132
+ if (IMAGE_EXT.has(ext)) return { findings }
133
+ if (looksBinary(data)) {
134
+ findings.push({ rule: 'file.binary', severity: 'medium', category: 'malware', label: '二进制内容', file: name, line: 0, masked: '' })
135
+ return { findings }
136
+ }
137
+ if (!TEXT_EXT.has(ext) && ext !== '') return { findings, skipped: '非文本扩展名,仅按文件名检测' }
138
+
139
+ const text = data.toString('utf8')
140
+ const seen = new Set()
141
+ for (const rule of [...SECRET_RULES, ...MALWARE_RULES]) {
142
+ rule.re.lastIndex = 0
143
+ let match
144
+ let guard = 0
145
+ while ((match = rule.re.exec(text)) !== null && guard < 50) {
146
+ guard += 1
147
+ const category = rule.category || 'malware'
148
+ const masked = category === 'secret' || category === 'privacy' ? maskSecret(match[0]) : maskAll(match[0])
149
+ const line = lineAt(text, match.index)
150
+ // 同一行同一规则只记一次:一个文件里几十处 require('child_process') 不该刷出几十条
151
+ const key = rule.id + ':' + line
152
+ if (!seen.has(key)) {
153
+ seen.add(key)
154
+ findings.push(findingOf(rule, name, line, masked))
155
+ }
156
+ if (match[0].length === 0) rule.re.lastIndex += 1
157
+ }
158
+ }
159
+
160
+ if (/(?:^|\/)(?:package|plugin)\.json$/u.test(name)) {
161
+ try {
162
+ const pkg = JSON.parse(text)
163
+ const scripts = pkg && typeof pkg === 'object' ? pkg.scripts : null
164
+ if (scripts && typeof scripts === 'object') {
165
+ for (const key of Object.keys(scripts)) {
166
+ if (/^(?:pre|post)?install$/u.test(key)) {
167
+ findings.push({
168
+ rule: 'json.install-script', severity: 'high', category: 'malware',
169
+ label: '安装时执行的脚本(' + key + ')', file: name, line: 0, masked: maskAll(scripts[key]),
170
+ })
171
+ }
172
+ }
173
+ }
174
+ const bin = pkg && pkg.bin
175
+ if (bin && typeof bin === 'object' && Object.keys(bin).length > 0) {
176
+ findings.push({ rule: 'json.bin', severity: 'low', category: 'malware', label: '声明了命令行入口', file: name, line: 0, masked: '' })
177
+ }
178
+ } catch {
179
+ // 包清单坏掉会在后面校验里报,不在扫描里重复报
180
+ }
181
+ }
182
+ return { findings }
183
+ }
184
+
185
+ const SEVERITY_ORDER = { high: 0, medium: 1, low: 2 }
186
+
187
+ export function severityRank(severity) {
188
+ return SEVERITY_ORDER[severity] ?? 3
189
+ }
190
+
191
+ /**
192
+ * 扫一批文件(内存内)。
193
+ * @param {{name: string, data: Buffer}[]} entries
194
+ * @param {{extraRules?: object[]}} [options]
195
+ */
196
+ export function scanEntries(entries, options = {}) {
197
+ const findings = []
198
+ let scannedBytes = 0
199
+ const skipped = []
200
+ const rules = Array.isArray(options.extraRules) ? options.extraRules : []
201
+ const extra = rules
202
+ .filter((r) => r && typeof r.id === 'string' && r.re instanceof RegExp)
203
+ .map((r) => ({ id: 'ext.' + r.id, severity: r.severity || 'medium', category: r.category || 'malware', label: r.label || r.id, re: new RegExp(r.re.source, r.re.flags.includes('g') ? r.re.flags : r.re.flags + 'g') }))
204
+
205
+ for (const entry of entries) {
206
+ scannedBytes += entry.data.length
207
+ const result = scanFile(entry.name, entry.data)
208
+ findings.push(...result.findings)
209
+ if (result.skipped) skipped.push({ file: entry.name, reason: result.skipped })
210
+ }
211
+ for (const rule of extra) {
212
+ for (const entry of entries) {
213
+ if (looksBinary(entry.data) || entry.data.length > MAX_SCAN_BYTES) continue
214
+ const text = entry.data.toString('utf8')
215
+ rule.re.lastIndex = 0
216
+ let match
217
+ let guard = 0
218
+ while ((match = rule.re.exec(text)) !== null && guard < 50) {
219
+ guard += 1
220
+ findings.push({ rule: rule.id, severity: rule.severity, category: rule.category, label: rule.label, file: entry.name, line: lineAt(text, match.index), masked: maskAll(match[0]) })
221
+ if (match[0].length === 0) rule.re.lastIndex += 1
222
+ }
223
+ }
224
+ }
225
+
226
+ findings.sort((a, b) => severityRank(a.severity) - severityRank(b.severity) || a.file.localeCompare(b.file) || a.line - b.line)
227
+ const counts = { high: 0, medium: 0, low: 0 }
228
+ for (const f of findings) counts[f.severity] = (counts[f.severity] || 0) + 1
229
+ return {
230
+ findings,
231
+ counts,
232
+ scannedFiles: entries.length,
233
+ scannedBytes,
234
+ skipped,
235
+ redacted: true,
236
+ note: '命中原文只在内存里用于判定,未写入任何文件;报告中的片段已打码。',
237
+ }
238
+ }
239
+
240
+ /**
241
+ * 生成给人看的扫描报告(纯文本)。只使用已打码的片段。
242
+ */
243
+ export function renderScanReport(title, scan, options = {}) {
244
+ const lines = []
245
+ lines.push('安全检测报告 —— ' + title)
246
+ lines.push('生成时间:' + new Date().toISOString())
247
+ lines.push('扫描文件:' + scan.scannedFiles + ',字节:' + scan.scannedBytes)
248
+ lines.push('结果:高风险 ' + scan.counts.high + ' / 中风险 ' + scan.counts.medium + ' / 低风险 ' + scan.counts.low)
249
+ lines.push('')
250
+ lines.push('说明:检测在本机内存中完成,命中的原文没有落盘,也无法从本报告还原。')
251
+ lines.push('检测是静态特征匹配,不是杀毒引擎;「未发现」不等于「保证安全」。')
252
+ if (options.approvedRisk) {
253
+ lines.push('')
254
+ lines.push('⚠ 打包者/安装者在存在高风险项的情况下明确选择了继续,风险由使用者承担。')
255
+ }
256
+ lines.push('')
257
+ if (scan.findings.length === 0) {
258
+ lines.push('未发现敏感信息或恶意代码特征。')
259
+ } else {
260
+ const byFile = new Map()
261
+ for (const f of scan.findings) {
262
+ if (!byFile.has(f.file)) byFile.set(f.file, [])
263
+ byFile.get(f.file).push(f)
264
+ }
265
+ for (const [file, items] of byFile) {
266
+ lines.push('· ' + file)
267
+ for (const f of items) {
268
+ lines.push(' [' + f.severity + '] ' + f.label + (f.line ? ' 第 ' + f.line + ' 行' : '') + (f.masked ? ' ' + f.masked : ''))
269
+ }
270
+ }
271
+ }
272
+ if (scan.skipped && scan.skipped.length > 0) {
273
+ lines.push('')
274
+ lines.push('未完整扫描:')
275
+ for (const s of scan.skipped.slice(0, 50)) lines.push(' · ' + s.file + '(' + s.reason + ')')
276
+ }
277
+ return lines.join('\n')
278
+ }
package/lib/semver.mjs ADDED
@@ -0,0 +1,143 @@
1
+ /**
2
+ * dsh-modpack —— 极小 semver(够判兼容性,不做完整实现)。
3
+ *
4
+ * 支持:`1.2.3`、`^`、`~`、`>= <= > <`、`*`/`x`、逗号或空格分隔的与、`||` 分隔的或。
5
+ * 不支持:hyphen range、预发布标签的优先级细节。判断插件 peer 兼容够用,
6
+ * 遇到看不懂的范围一律返回 `unknown`,不假装通过。
7
+ */
8
+
9
+ const VERSION_RE = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/u
10
+
11
+ export function parseVersion(input) {
12
+ if (input === null || input === undefined) return null
13
+ const m = VERSION_RE.exec(String(input).trim())
14
+ if (!m) return null
15
+ return { major: Number(m[1]), minor: Number(m[2]), patch: Number(m[3]), pre: m[4] || '' }
16
+ }
17
+
18
+ export function compareVersions(a, b) {
19
+ const pa = parseVersion(a)
20
+ const pb = parseVersion(b)
21
+ if (!pa || !pb) return null
22
+ for (const key of ['major', 'minor', 'patch']) {
23
+ if (pa[key] !== pb[key]) return pa[key] < pb[key] ? -1 : 1
24
+ }
25
+ if (pa.pre === pb.pre) return 0
26
+ if (pa.pre === '') return 1
27
+ if (pb.pre === '') return -1
28
+ return pa.pre < pb.pre ? -1 : 1
29
+ }
30
+
31
+ const isWild = (part) => part === undefined || part === '' || part === '*' || part === 'x' || part === 'X'
32
+
33
+ function bound(major, minor, patch, pre, op) {
34
+ return { major, minor, patch, pre: pre || '', op }
35
+ }
36
+
37
+ /** 把一个比较符句子(如 `^1.2.3`、`>=1.0.0 <2.0.0`)展开成下界/上界。 */
38
+ function parseComparatorSet(text) {
39
+ const parts = String(text).trim().split(/\s+/u).filter(Boolean)
40
+ if (parts.length === 0) return { any: true }
41
+ const bounds = []
42
+ for (const part of parts) {
43
+ const m = /^(\^|~|>=|<=|>|<|=)?\s*(.*)$/u.exec(part)
44
+ const op = m[1] || ''
45
+ const rest = m[2]
46
+ if (rest === '' || rest === '*' || rest === 'x') {
47
+ if (op === '' || op === '=' || op === '>=') continue
48
+ if (op === '<' || op === '<=') return { impossible: true }
49
+ continue
50
+ }
51
+ const nums = rest.split('.').map((s) => s.trim())
52
+ const majorRaw = nums[0]
53
+ const minorRaw = nums[1]
54
+ const patchRaw = nums[2]
55
+ if (isWild(majorRaw)) {
56
+ if (op === '' || op === '=' || op === '>=' || op === '^' || op === '~') continue
57
+ if (op === '<' || op === '<=') return { impossible: true }
58
+ continue
59
+ }
60
+ if (!/^\d+$/u.test(majorRaw)) return null
61
+ const major = Number(majorRaw)
62
+ const minorWild = isWild(minorRaw)
63
+ const patchWild = isWild((patchRaw || '').split('-')[0])
64
+ const minor = minorWild ? 0 : Number(minorRaw)
65
+ const patchPart = (patchRaw || '0').split('-')
66
+ const patch = patchWild ? 0 : Number(patchPart[0])
67
+ const pre = patchPart.slice(1).join('-')
68
+ if (Number.isNaN(minor) || Number.isNaN(patch)) return null
69
+
70
+ if (op === '^') {
71
+ bounds.push(bound(major, minor, patch, pre, '>='))
72
+ if (major > 0) bounds.push(bound(major + 1, 0, 0, '', '<'))
73
+ else if (minorWild) bounds.push(bound(1, 0, 0, '', '<'))
74
+ else if (patchWild) bounds.push(bound(0, minor + 1, 0, '', '<'))
75
+ // ^0.0.3 只允许 0.0.3 本身(npm 语义:上界 0.0.4),^0.x 上界 0.(x+1).0
76
+ else if (minor === 0) bounds.push(bound(0, 0, patch + 1, '', '<'))
77
+ else bounds.push(bound(0, minor + 1, 0, '', '<'))
78
+ continue
79
+ }
80
+ if (op === '~') {
81
+ bounds.push(bound(major, minor, patch, pre, '>='))
82
+ bounds.push(minorWild ? bound(major + 1, 0, 0, '', '<') : bound(major, minor + 1, 0, '', '<'))
83
+ continue
84
+ }
85
+ if (op === '>' || op === '>=' || op === '<' || op === '<=') {
86
+ bounds.push(bound(major, minor, patch, pre, op))
87
+ continue
88
+ }
89
+ // 裸版本 / `=`:x.y.z 精确;x.y 视为 ~x.y;x 视为 ^x
90
+ if (minorWild) {
91
+ bounds.push(bound(major, 0, 0, '', '>='))
92
+ bounds.push(bound(major + 1, 0, 0, '', '<'))
93
+ } else if (patchWild) {
94
+ bounds.push(bound(major, minor, 0, '', '>='))
95
+ bounds.push(bound(major, minor + 1, 0, '', '<'))
96
+ } else {
97
+ bounds.push(bound(major, minor, patch, pre, '='))
98
+ }
99
+ }
100
+ return { bounds }
101
+ }
102
+
103
+ function testBounds(version, bounds) {
104
+ for (const b of bounds) {
105
+ const cmp = compareVersions(version, `${b.major}.${b.minor}.${b.patch}${b.pre ? '-' + b.pre : ''}`)
106
+ if (cmp === null) return null
107
+ if (b.op === '=' && cmp !== 0) return false
108
+ if (b.op === '>' && cmp <= 0) return false
109
+ if (b.op === '>=' && cmp < 0) return false
110
+ if (b.op === '<' && cmp >= 0) return false
111
+ if (b.op === '<=' && cmp > 0) return false
112
+ }
113
+ return true
114
+ }
115
+
116
+ /**
117
+ * @returns {boolean|null} null = 范围看不懂 / 版本非法,不要当成通过。
118
+ */
119
+ export function satisfies(version, range) {
120
+ if (!parseVersion(version)) return null
121
+ if (range === undefined || range === null) return true
122
+ const text = String(range).trim()
123
+ if (text === '' || text === '*' || text === 'x') return true
124
+ const sets = text.split('||')
125
+ let sawUnknown = false
126
+ for (const set of sets) {
127
+ const parsed = parseComparatorSet(set)
128
+ if (!parsed) { sawUnknown = true; continue }
129
+ if (parsed.impossible) continue
130
+ if (parsed.any) return true
131
+ const ok = testBounds(version, parsed.bounds)
132
+ if (ok === true) return true
133
+ if (ok === null) sawUnknown = true
134
+ }
135
+ return sawUnknown ? null : false
136
+ }
137
+
138
+ /** 从依赖表里挑一个字符串范围。 */
139
+ export function rangeOf(range) {
140
+ if (typeof range === 'string') return range
141
+ if (range && typeof range === 'object' && typeof range.version === 'string') return range.version
142
+ return '*'
143
+ }