dsh-plugin-explorer 0.1.2 → 0.2.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/README.md +48 -15
- package/client.js +397 -21
- package/index.js +64 -9
- package/lib/gate/LICENSE +21 -0
- package/lib/gate/osv.js +116 -0
- package/lib/gate/rules.js +628 -0
- package/lib/gate/scan.js +609 -0
- package/lib/gate/targz.js +146 -0
- package/lib/gate-scan.js +144 -0
- package/lib/installed.js +86 -0
- package/lib/npm.js +109 -0
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +2 -2
- package/scripts/verify.mjs +64 -6
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-plugin-gate — minimal in-memory .tar.gz extraction.
|
|
3
|
+
*
|
|
4
|
+
* Pure module (node:zlib only). Used to scan npm tarballs without touching
|
|
5
|
+
* disk and without spawning any process. Supports the classic ustar format
|
|
6
|
+
* plus GNU long-name ('L') headers; PAX headers ('x'/'g') are skipped.
|
|
7
|
+
* Path traversal entries are dropped and counted.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { gunzipSync } from "node:zlib";
|
|
11
|
+
|
|
12
|
+
const BLOCK = 512;
|
|
13
|
+
|
|
14
|
+
/** Round a byte length up to the next 512-byte block. */
|
|
15
|
+
function padded(size) {
|
|
16
|
+
return Math.ceil(size / BLOCK) * BLOCK;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function isZeroBlock(buf) {
|
|
20
|
+
for (let i = 0; i < BLOCK; i++) {
|
|
21
|
+
if (buf[i] !== 0) return false;
|
|
22
|
+
}
|
|
23
|
+
return true;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Read a null-terminated (or space-padded) ASCII field. */
|
|
27
|
+
function readField(buf, offset, length) {
|
|
28
|
+
let end = offset;
|
|
29
|
+
const stop = offset + length;
|
|
30
|
+
while (end < stop && buf[end] !== 0 && buf[end] !== 32) end += 1;
|
|
31
|
+
return buf.subarray(offset, end).toString("utf8");
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Parse an octal field (some writers use base-256 for big sizes). */
|
|
35
|
+
function parseOctal(buf, offset, length) {
|
|
36
|
+
const raw = buf.subarray(offset, offset + length);
|
|
37
|
+
if (raw.length > 0 && (raw[0] & 0x80) !== 0) {
|
|
38
|
+
let value = 0;
|
|
39
|
+
for (let i = 0; i < raw.length; i++) {
|
|
40
|
+
value = value * 256 + (i === 0 ? raw[i] & 0x7f : raw[i]);
|
|
41
|
+
}
|
|
42
|
+
return value;
|
|
43
|
+
}
|
|
44
|
+
const text = readField(buf, offset, length).trim();
|
|
45
|
+
return text.length === 0 ? 0 : parseInt(text, 8);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Is this raw archive path a traversal or absolute escape attempt? */
|
|
49
|
+
function isUnsafePath(raw) {
|
|
50
|
+
return raw.startsWith("/") || raw.startsWith("../") || raw.includes("/../") || raw.includes("\\");
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Normalize an archive path to a safe relative POSIX-style path. */
|
|
54
|
+
function normalizePath(name) {
|
|
55
|
+
let p = String(name).replace(/\\/g, "/");
|
|
56
|
+
p = p.replace(/^\.[\\/]/g, "").replace(/^[a-zA-Z]:\//, "").replace(/^\/+/, "");
|
|
57
|
+
const parts = [];
|
|
58
|
+
for (const part of p.split("/")) {
|
|
59
|
+
if (part === "" || part === ".") continue;
|
|
60
|
+
if (part === "..") {
|
|
61
|
+
if (parts.length > 0) parts.pop();
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
parts.push(part);
|
|
65
|
+
}
|
|
66
|
+
return parts.join("/");
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Extract a .tar.gz buffer into an in-memory file list.
|
|
71
|
+
* @param {Buffer} buffer - gzipped tarball bytes.
|
|
72
|
+
* @param {{maxBytes?:number, maxFiles?:number}} [opts]
|
|
73
|
+
* @returns {{files:Array<{path:string,size:number,data:Buffer}>, truncated:{files:number, bytes:number, traversal:number, pax:number}}}
|
|
74
|
+
* @throws when the gzip stream cannot be decompressed within maxBytes.
|
|
75
|
+
*/
|
|
76
|
+
export function extractTarball(buffer, opts = {}) {
|
|
77
|
+
const { maxBytes = 64 * 1024 * 1024, maxFiles = 2000 } = opts;
|
|
78
|
+
let data;
|
|
79
|
+
try {
|
|
80
|
+
data = gunzipSync(buffer, { maxOutputLength: maxBytes });
|
|
81
|
+
} catch (e) {
|
|
82
|
+
throw new Error("targz: gunzip failed: " + e.message);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const files = [];
|
|
86
|
+
const truncated = { files: 0, bytes: 0, traversal: 0, pax: 0 };
|
|
87
|
+
let offset = 0;
|
|
88
|
+
let longName = null;
|
|
89
|
+
|
|
90
|
+
while (offset + BLOCK <= data.length) {
|
|
91
|
+
const header = data.subarray(offset, offset + BLOCK);
|
|
92
|
+
if (isZeroBlock(header)) break;
|
|
93
|
+
|
|
94
|
+
const name = readField(header, 0, 100);
|
|
95
|
+
const size = parseOctal(header, 124, 12);
|
|
96
|
+
const type = String.fromCharCode(header[156] || 0x30);
|
|
97
|
+
const prefix = readField(header, 345, 155);
|
|
98
|
+
|
|
99
|
+
if (type === "L") {
|
|
100
|
+
const nameBytes = data.subarray(offset + BLOCK, offset + BLOCK + size);
|
|
101
|
+
longName = nameBytes.toString("utf8").replace(/\0.*$/, "");
|
|
102
|
+
offset += BLOCK + padded(size);
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
if (type === "x" || type === "g") {
|
|
106
|
+
truncated.pax += 1;
|
|
107
|
+
offset += BLOCK + padded(size);
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const raw = longName !== null ? longName : (prefix.length > 0 ? prefix + "/" + name : name);
|
|
112
|
+
longName = null;
|
|
113
|
+
const payloadLen = padded(size);
|
|
114
|
+
|
|
115
|
+
if (type === "0" || type === "\u0000") {
|
|
116
|
+
if (isUnsafePath(raw)) {
|
|
117
|
+
truncated.traversal += 1;
|
|
118
|
+
offset += BLOCK + payloadLen;
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
const safe = normalizePath(raw);
|
|
122
|
+
if (safe.length === 0) {
|
|
123
|
+
truncated.traversal += 1;
|
|
124
|
+
offset += BLOCK + payloadLen;
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
if (files.length >= maxFiles) {
|
|
128
|
+
truncated.files += 1;
|
|
129
|
+
offset += BLOCK + payloadLen;
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
const payloadStart = offset + BLOCK;
|
|
133
|
+
const payloadEnd = payloadStart + size;
|
|
134
|
+
offset += BLOCK + payloadLen;
|
|
135
|
+
if (payloadEnd > data.length) {
|
|
136
|
+
truncated.bytes += 1;
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
files.push({ path: safe, size, data: data.subarray(payloadStart, payloadEnd) });
|
|
140
|
+
} else {
|
|
141
|
+
offset += BLOCK + payloadLen;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
return { files, truncated };
|
|
146
|
+
}
|
package/lib/gate-scan.js
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pre-install scanner for dsh-plugin-explorer.
|
|
3
|
+
*
|
|
4
|
+
* Port of the scan flow from dsh-plugin-gate 1.3.2 (MIT, vendored under
|
|
5
|
+
* ./gate/). Differences from upstream `scanNpmPackage`:
|
|
6
|
+
* - registry resolution tries registry.npmmirror.com before registry.npmjs.org;
|
|
7
|
+
* - results are trimmed before they cross the Web boundary;
|
|
8
|
+
* - successful scans are cached in memory for ten minutes.
|
|
9
|
+
*
|
|
10
|
+
* Reads only: the tarball is decompressed in memory, nothing is executed and
|
|
11
|
+
* nothing is written to disk.
|
|
12
|
+
*/
|
|
13
|
+
import { CATEGORY } from './gate/rules.js'
|
|
14
|
+
import { buildResult, scanTarballFiles } from './gate/scan.js'
|
|
15
|
+
import { extractTarball } from './gate/targz.js'
|
|
16
|
+
import { downloadTarball, fetchPackument, selectVersion } from './npm.js'
|
|
17
|
+
|
|
18
|
+
const MAX_TARBALL_BYTES = 32 * 1024 * 1024
|
|
19
|
+
const MAX_EXTRACT_BYTES = 64 * 1024 * 1024
|
|
20
|
+
const MAX_FILE_BYTES = 2 * 1024 * 1024
|
|
21
|
+
const MAX_FILES = 2000
|
|
22
|
+
const MAX_HITS = 80
|
|
23
|
+
const MAX_HOSTS = 30
|
|
24
|
+
const CACHE_TTL_MS = 10 * 60 * 1000
|
|
25
|
+
const CACHE_MAX = 40
|
|
26
|
+
|
|
27
|
+
/** name@version -> { result, at }. */
|
|
28
|
+
const cache = new Map()
|
|
29
|
+
|
|
30
|
+
function cacheGet(key) {
|
|
31
|
+
const hit = cache.get(key)
|
|
32
|
+
if (hit === undefined) return undefined
|
|
33
|
+
if (Date.now() - hit.at > CACHE_TTL_MS) {
|
|
34
|
+
cache.delete(key)
|
|
35
|
+
return undefined
|
|
36
|
+
}
|
|
37
|
+
return hit.result
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function cacheSet(key, result) {
|
|
41
|
+
if (cache.size >= CACHE_MAX) {
|
|
42
|
+
const oldest = cache.keys().next().value
|
|
43
|
+
if (oldest !== undefined) cache.delete(oldest)
|
|
44
|
+
}
|
|
45
|
+
cache.set(key, { result, at: Date.now() })
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function lifecycleHits(scripts) {
|
|
49
|
+
const hits = []
|
|
50
|
+
const entries = scripts === null || typeof scripts !== 'object' ? {} : scripts
|
|
51
|
+
for (const script of Object.keys(entries)) {
|
|
52
|
+
if (!/^(pre|post)?(install|uninstall|prepare|prepublish|publish|link)\b/.test(script)) continue
|
|
53
|
+
const body = String(entries[script]).slice(0, 500)
|
|
54
|
+
const high = /(curl|wget|download|powershell|cmd|exec|eval|http)/i.test(body)
|
|
55
|
+
hits.push({
|
|
56
|
+
rule: 'lifecycle_script',
|
|
57
|
+
category: CATEGORY.SCRIPTS,
|
|
58
|
+
severity: high ? 'high' : 'medium',
|
|
59
|
+
file: 'package.json',
|
|
60
|
+
line: 1,
|
|
61
|
+
count: 1,
|
|
62
|
+
evidence: `${script}: ${body.slice(0, 180)}`,
|
|
63
|
+
hint: 'npm runs lifecycle scripts during install; execute only what you have audited.',
|
|
64
|
+
})
|
|
65
|
+
}
|
|
66
|
+
return hits
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function trimHit(hit) {
|
|
70
|
+
return {
|
|
71
|
+
rule: hit.rule,
|
|
72
|
+
category: hit.category,
|
|
73
|
+
severity: hit.severity,
|
|
74
|
+
file: hit.file,
|
|
75
|
+
line: hit.line,
|
|
76
|
+
evidence: String(hit.evidence ?? '').slice(0, 240),
|
|
77
|
+
hint: hit.hint,
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function publicResult(result, extra) {
|
|
82
|
+
return {
|
|
83
|
+
verdict: result.verdict,
|
|
84
|
+
score: result.score,
|
|
85
|
+
filesScanned: result.filesScanned,
|
|
86
|
+
filesTotal: result.filesTotal,
|
|
87
|
+
summary: result.summary,
|
|
88
|
+
network: {
|
|
89
|
+
hosts: (result.network?.hosts ?? []).slice(0, MAX_HOSTS),
|
|
90
|
+
unallowlisted: (result.network?.unallowlisted ?? []).slice(0, MAX_HOSTS),
|
|
91
|
+
readAndSendFiles: (result.network?.readAndSendFiles ?? []).slice(0, 10),
|
|
92
|
+
},
|
|
93
|
+
notes: Array.isArray(result.notes) ? result.notes.length : 0,
|
|
94
|
+
hits: (result.hits ?? []).slice(0, MAX_HITS).map(trimHit),
|
|
95
|
+
recommendations: (result.recommendations ?? []).slice(0, 8),
|
|
96
|
+
package: result.package,
|
|
97
|
+
...extra,
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Scan the published tarball of one npm package.
|
|
103
|
+
* @param {string} name - package name.
|
|
104
|
+
* @param {string} [version] - requested version; defaults to the latest tag.
|
|
105
|
+
* @returns {Promise<object>} trimmed gate result plus `name`, `version`, `cached`, `scannedAt`, `tookMs`.
|
|
106
|
+
*/
|
|
107
|
+
export async function scanPackage(name, version) {
|
|
108
|
+
const key = `${name}@${version ?? 'latest'}`
|
|
109
|
+
const cached = cacheGet(key)
|
|
110
|
+
if (cached !== undefined) return { ...cached, cached: true }
|
|
111
|
+
|
|
112
|
+
const started = Date.now()
|
|
113
|
+
const document = await fetchPackument(name)
|
|
114
|
+
const selected = selectVersion(document, version)
|
|
115
|
+
const tarball = await downloadTarball(selected.tarball)
|
|
116
|
+
if (tarball.byteLength > MAX_TARBALL_BYTES) {
|
|
117
|
+
throw new Error(`tarball too large (${String(tarball.byteLength)} bytes)`)
|
|
118
|
+
}
|
|
119
|
+
const { files, truncated } = extractTarball(tarball, { maxBytes: MAX_EXTRACT_BYTES, maxFiles: MAX_FILES })
|
|
120
|
+
|
|
121
|
+
const scanned = scanTarballFiles(files, { maxFileBytes: MAX_FILE_BYTES, allowlistHosts: [] })
|
|
122
|
+
scanned.target = `${name}@${selected.version}`
|
|
123
|
+
if (truncated.files > 0 || truncated.traversal > 0 || truncated.pax > 0) {
|
|
124
|
+
scanned.notes.push({ file: 'tarball', kind: 'truncated', detail: JSON.stringify(truncated) })
|
|
125
|
+
}
|
|
126
|
+
scanned.hits.push(...lifecycleHits(selected.scripts))
|
|
127
|
+
scanned.package = {
|
|
128
|
+
name,
|
|
129
|
+
version: selected.version,
|
|
130
|
+
lifecycleCount: lifecycleHits(selected.scripts).length,
|
|
131
|
+
fileCount: files.length,
|
|
132
|
+
}
|
|
133
|
+
const result = buildResult({ ...scanned, hosts: scanned.network?.hosts ?? [] }, { allowlistHosts: [] })
|
|
134
|
+
|
|
135
|
+
const payload = publicResult(result, {
|
|
136
|
+
name,
|
|
137
|
+
version: selected.version,
|
|
138
|
+
cached: false,
|
|
139
|
+
scannedAt: new Date().toISOString(),
|
|
140
|
+
tookMs: Date.now() - started,
|
|
141
|
+
})
|
|
142
|
+
cacheSet(key, payload)
|
|
143
|
+
return payload
|
|
144
|
+
}
|
package/lib/installed.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Installed-plugin inventory for the running profile.
|
|
3
|
+
*
|
|
4
|
+
* The Host half lives at `<profile>/node_modules/<plugin>/` (or a link there),
|
|
5
|
+
* so the profile directory is three levels above this file. Only dependencies
|
|
6
|
+
* that declare a `dsh` manifest field are reported; built-in plugins live in
|
|
7
|
+
* the application bundle, not in the profile.
|
|
8
|
+
*/
|
|
9
|
+
import { readFileSync } from 'node:fs'
|
|
10
|
+
import path from 'node:path'
|
|
11
|
+
import { fileURLToPath } from 'node:url'
|
|
12
|
+
import { latestVersion } from './npm.js'
|
|
13
|
+
|
|
14
|
+
const PROFILE_DIR = process.env.DSH_PROFILE_DIR !== undefined && process.env.DSH_PROFILE_DIR !== ''
|
|
15
|
+
? path.resolve(process.env.DSH_PROFILE_DIR)
|
|
16
|
+
: path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..')
|
|
17
|
+
|
|
18
|
+
function parseSemver(text) {
|
|
19
|
+
if (typeof text !== 'string') return undefined
|
|
20
|
+
const match = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(text.trim())
|
|
21
|
+
if (match === null) return undefined
|
|
22
|
+
return { major: Number(match[1]), minor: Number(match[2]), patch: Number(match[3]), pre: match[4] ?? null }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Is `candidate` a strictly newer version than `current`? */
|
|
26
|
+
export function isNewer(candidate, current) {
|
|
27
|
+
if (candidate === undefined || current === undefined) return false
|
|
28
|
+
if (candidate === current) return false
|
|
29
|
+
const left = parseSemver(candidate)
|
|
30
|
+
const right = parseSemver(current)
|
|
31
|
+
if (left === undefined || right === undefined) return candidate !== current
|
|
32
|
+
if (left.major !== right.major) return left.major > right.major
|
|
33
|
+
if (left.minor !== right.minor) return left.minor > right.minor
|
|
34
|
+
if (left.patch !== right.patch) return left.patch > right.patch
|
|
35
|
+
if (left.pre === null) return right.pre !== null
|
|
36
|
+
if (right.pre === null) return false
|
|
37
|
+
return left.pre > right.pre
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Read the profile dependency list and the installed version of each bundle.
|
|
42
|
+
* @returns {{profile: string, plugins: Array<{name: string, version?: string}>}}
|
|
43
|
+
*/
|
|
44
|
+
export function listInstalled() {
|
|
45
|
+
let document
|
|
46
|
+
try {
|
|
47
|
+
document = JSON.parse(readFileSync(path.join(PROFILE_DIR, 'package.json'), 'utf8'))
|
|
48
|
+
} catch {
|
|
49
|
+
return { profile: PROFILE_DIR, plugins: [] }
|
|
50
|
+
}
|
|
51
|
+
const dependencies = document !== null && typeof document === 'object' && document.dependencies !== null && typeof document.dependencies === 'object'
|
|
52
|
+
? document.dependencies
|
|
53
|
+
: {}
|
|
54
|
+
const plugins = []
|
|
55
|
+
for (const name of Object.keys(dependencies)) {
|
|
56
|
+
let manifest
|
|
57
|
+
try {
|
|
58
|
+
manifest = JSON.parse(readFileSync(path.join(PROFILE_DIR, 'node_modules', name, 'package.json'), 'utf8'))
|
|
59
|
+
} catch {
|
|
60
|
+
continue
|
|
61
|
+
}
|
|
62
|
+
const dsh = manifest !== null && typeof manifest === 'object' ? manifest.dsh : undefined
|
|
63
|
+
const isBundle = dsh !== null && typeof dsh === 'object' && (dsh.bundle !== undefined || dsh.client !== undefined)
|
|
64
|
+
if (!isBundle) continue
|
|
65
|
+
plugins.push({ name, version: typeof manifest.version === 'string' ? manifest.version : undefined })
|
|
66
|
+
}
|
|
67
|
+
plugins.sort((left, right) => left.name.localeCompare(right.name))
|
|
68
|
+
return { profile: PROFILE_DIR, plugins }
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Installed bundles with their registry latest version.
|
|
73
|
+
* @returns {Promise<{profile: string, generatedAt: string, plugins: Array<{name: string, version?: string, latest?: string, hasUpdate: boolean}>}>}
|
|
74
|
+
*/
|
|
75
|
+
export async function installedWithLatest() {
|
|
76
|
+
const base = listInstalled()
|
|
77
|
+
const plugins = await Promise.all(base.plugins.map(async (plugin) => {
|
|
78
|
+
const latest = await latestVersion(plugin.name)
|
|
79
|
+
return {
|
|
80
|
+
...plugin,
|
|
81
|
+
latest,
|
|
82
|
+
hasUpdate: isNewer(latest, plugin.version),
|
|
83
|
+
}
|
|
84
|
+
}))
|
|
85
|
+
return { profile: base.profile, generatedAt: new Date().toISOString(), plugins }
|
|
86
|
+
}
|
package/lib/npm.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Small npm registry client shared by the scanner and the installed-plugin checks.
|
|
3
|
+
*
|
|
4
|
+
* The Chinese mirror answers first because the Web GUI mostly runs in mainland
|
|
5
|
+
* China; npmjs.com is the fallback. Both return the same packument shape.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** Mirrors tried in order when no explicit registry is given. */
|
|
9
|
+
export const REGISTRIES = ['https://registry.npmmirror.com', 'https://registry.npmjs.org']
|
|
10
|
+
|
|
11
|
+
const PACKUMENT_TIMEOUT_MS = 12_000
|
|
12
|
+
const TARBALL_TIMEOUT_MS = 30_000
|
|
13
|
+
|
|
14
|
+
/** Hard ceiling for one downloaded tarball. */
|
|
15
|
+
export const MAX_TARBALL_BYTES = 32 * 1024 * 1024
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Fetch one package document.
|
|
19
|
+
* @param {string} name - package name.
|
|
20
|
+
* @param {{registry?: string, timeoutMs?: number}} [options] - optional registry override.
|
|
21
|
+
* @returns {Promise<object>} packument.
|
|
22
|
+
*/
|
|
23
|
+
export async function fetchPackument(name, options = {}) {
|
|
24
|
+
const { registry, timeoutMs = PACKUMENT_TIMEOUT_MS } = options
|
|
25
|
+
const bases = registry === undefined ? REGISTRIES : [registry]
|
|
26
|
+
let lastError
|
|
27
|
+
for (const base of bases) {
|
|
28
|
+
try {
|
|
29
|
+
const response = await fetch(`${base}/${encodeURIComponent(name)}`, {
|
|
30
|
+
headers: { accept: 'application/json' },
|
|
31
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
32
|
+
})
|
|
33
|
+
if (!response.ok) {
|
|
34
|
+
lastError = new Error(`${base} answered HTTP ${String(response.status)} for ${name}`)
|
|
35
|
+
continue
|
|
36
|
+
}
|
|
37
|
+
const document = await response.json()
|
|
38
|
+
if (document === null || typeof document !== 'object') {
|
|
39
|
+
lastError = new Error(`${base} returned a non-object document for ${name}`)
|
|
40
|
+
continue
|
|
41
|
+
}
|
|
42
|
+
return document
|
|
43
|
+
} catch (error) {
|
|
44
|
+
lastError = error instanceof Error ? error : new Error(String(error))
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
throw lastError ?? new Error(`cannot resolve ${name}`)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Pick one version record out of a packument.
|
|
52
|
+
* @param {object} document - packument.
|
|
53
|
+
* @param {string} [version] - requested version; defaults to dist-tags.latest.
|
|
54
|
+
* @returns {{version: string, tarball: string, scripts: object|undefined, name: string}}
|
|
55
|
+
*/
|
|
56
|
+
export function selectVersion(document, version) {
|
|
57
|
+
const wanted = version ?? document['dist-tags']?.latest
|
|
58
|
+
if (typeof wanted !== 'string' || wanted === '') {
|
|
59
|
+
throw new Error(`no version to scan for ${String(document.name)}`)
|
|
60
|
+
}
|
|
61
|
+
const meta = document.versions?.[wanted]
|
|
62
|
+
if (meta === undefined || meta === null) {
|
|
63
|
+
throw new Error(`version ${wanted} not found for ${String(document.name)}`)
|
|
64
|
+
}
|
|
65
|
+
const tarball = meta.dist?.tarball
|
|
66
|
+
if (typeof tarball !== 'string' || tarball === '') {
|
|
67
|
+
throw new Error(`no tarball for ${String(document.name)}@${wanted}`)
|
|
68
|
+
}
|
|
69
|
+
return { version: wanted, tarball, scripts: meta.scripts, name: document.name }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Download a tarball into memory, bounded by {@link MAX_TARBALL_BYTES}.
|
|
74
|
+
* @param {string} url - tarball URL.
|
|
75
|
+
* @param {{timeoutMs?: number}} [options] - optional timeout.
|
|
76
|
+
* @returns {Promise<Buffer>} compressed bytes.
|
|
77
|
+
*/
|
|
78
|
+
export async function downloadTarball(url, options = {}) {
|
|
79
|
+
const { timeoutMs = TARBALL_TIMEOUT_MS } = options
|
|
80
|
+
const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs), redirect: 'follow' })
|
|
81
|
+
if (!response.ok) throw new Error(`tarball answered HTTP ${String(response.status)}`)
|
|
82
|
+
const buffer = Buffer.from(await response.arrayBuffer())
|
|
83
|
+
if (buffer.byteLength > MAX_TARBALL_BYTES) {
|
|
84
|
+
throw new Error(`tarball too large (${String(buffer.byteLength)} bytes)`)
|
|
85
|
+
}
|
|
86
|
+
return buffer
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const latestCache = new Map()
|
|
90
|
+
const LATEST_TTL_MS = 10 * 60 * 1000
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Latest published version, cached briefly; resolves to undefined on failure.
|
|
94
|
+
* @param {string} name - package name.
|
|
95
|
+
* @returns {Promise<string|undefined>} latest version.
|
|
96
|
+
*/
|
|
97
|
+
export async function latestVersion(name) {
|
|
98
|
+
const hit = latestCache.get(name)
|
|
99
|
+
if (hit !== undefined && Date.now() - hit.at < LATEST_TTL_MS) return hit.version
|
|
100
|
+
try {
|
|
101
|
+
const document = await fetchPackument(name)
|
|
102
|
+
const latest = document['dist-tags']?.latest
|
|
103
|
+
const version = typeof latest === 'string' && latest !== '' ? latest : undefined
|
|
104
|
+
latestCache.set(name, { version, at: Date.now() })
|
|
105
|
+
return version
|
|
106
|
+
} catch {
|
|
107
|
+
return undefined
|
|
108
|
+
}
|
|
109
|
+
}
|
package/locale/en.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"meta": {
|
|
3
3
|
"title": "Plugin search",
|
|
4
|
-
"description": "Adds a Search tab to the Plugins page:
|
|
4
|
+
"description": "Adds a Search tab to the Plugins page: search 7,000+ community plugins by name, author, or keyword with category filters and sorting. Installs run a pre-install static safety scan (BLOCK/WARN/PASS), installed bundles are detected with update hints, and the catalog ships with the plugin so searching needs no network."
|
|
5
5
|
}
|
|
6
6
|
}
|
package/locale/zh.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"meta": {
|
|
3
3
|
"title": "插件搜索",
|
|
4
|
-
"description": "
|
|
4
|
+
"description": "在插件页新增「搜索」标签页:按名称、作者或关键词检索 7000+ 个社区插件,支持分类筛选与排序;安装前自动做静态安全扫描(BLOCK/WARN/PASS),并识别已安装插件、提示更新。目录随插件内置,搜索无需联网;点「刷新目录」可读取最新社区索引。"
|
|
5
5
|
}
|
|
6
6
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-plugin-explorer",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Search the community plugin catalog
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Search the community plugin catalog, run a pre-install safety scan, filter by category and update installed bundles from the Plugins page.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
package/scripts/verify.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
// Verification: Host catalog
|
|
2
|
-
// Usage: node scripts/verify.mjs [--refresh]
|
|
1
|
+
// Verification: Host routes (catalog/scan/installed) + client search and filter pipeline.
|
|
2
|
+
// Usage: node scripts/verify.mjs [--refresh] [--scan]
|
|
3
3
|
import { apply } from '../index.js'
|
|
4
4
|
|
|
5
5
|
let failures = 0
|
|
@@ -15,10 +15,41 @@ const scope = {
|
|
|
15
15
|
connection: { fetch: { register(route) { routes.push(route); return async () => {} } } },
|
|
16
16
|
}
|
|
17
17
|
apply({ inject(_deps, callback) { callback(scope) } })
|
|
18
|
-
check('host registers
|
|
19
|
-
check('route
|
|
18
|
+
check('host registers three GET routes', routes.length === 3 && routes.every(route => route.methods.join() === 'GET'))
|
|
19
|
+
check('catalog route is absolute below /api', routes.some(route => route.path === '/api/plugin-finder/catalog.json'))
|
|
20
|
+
check('scan route is absolute below /api', routes.some(route => route.path === '/api/plugin-finder/scan.json'))
|
|
21
|
+
check('installed route is absolute below /api', routes.some(route => route.path === '/api/plugin-finder/installed.json'))
|
|
20
22
|
|
|
21
|
-
const
|
|
23
|
+
const catalogRoute = routes.find(route => route.path === '/api/plugin-finder/catalog.json')
|
|
24
|
+
const scanRoute = routes.find(route => route.path === '/api/plugin-finder/scan.json')
|
|
25
|
+
const installedRoute = routes.find(route => route.path === '/api/plugin-finder/installed.json')
|
|
26
|
+
|
|
27
|
+
const installedResponse = await installedRoute.fetch(new Request('http://127.0.0.1:1/api/plugin-finder/installed.json'))
|
|
28
|
+
const installedBody = JSON.parse(await installedResponse.text())
|
|
29
|
+
check('installed route answers 200 with a plugins array', installedResponse.status === 200 && Array.isArray(installedBody.plugins))
|
|
30
|
+
check('installed entries carry name and hasUpdate', installedBody.plugins.every(p => typeof p.name === 'string' && typeof p.hasUpdate === 'boolean'))
|
|
31
|
+
|
|
32
|
+
const badScan = await scanRoute.fetch(new Request('http://127.0.0.1:1/api/plugin-finder/scan.json'))
|
|
33
|
+
check('scan route rejects a missing package name', badScan.status === 400)
|
|
34
|
+
|
|
35
|
+
if (process.argv.includes('--scan')) {
|
|
36
|
+
const target = 'dsh-plugin-explorer@0.1.2'
|
|
37
|
+
const scanned = await scanRoute.fetch(new Request('http://127.0.0.1:1/api/plugin-finder/scan.json?name=dsh-plugin-explorer&version=0.1.2'))
|
|
38
|
+
const text = await scanned.text()
|
|
39
|
+
let payload
|
|
40
|
+
try { payload = JSON.parse(text) } catch { payload = undefined }
|
|
41
|
+
check(`scan ${target} answers 200 json`, scanned.status === 200 && payload !== undefined)
|
|
42
|
+
if (scanned.status !== 200) console.log(' scan error:', text.slice(0, 300))
|
|
43
|
+
else {
|
|
44
|
+
console.log(' verdict:', payload.verdict, 'high/medium/low:', payload.summary.high, payload.summary.medium, payload.summary.low,
|
|
45
|
+
'files:', payload.filesScanned + '/' + payload.filesTotal, 'hits:', payload.hits.length)
|
|
46
|
+
check('scan verdict is PASS, WARN or BLOCK', ['PASS', 'WARN', 'BLOCK'].includes(payload.verdict))
|
|
47
|
+
check('scan reports scanned files', payload.filesScanned > 0)
|
|
48
|
+
check('scan result has a package version', payload.package?.version === '0.1.2')
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const bundledResponse = await catalogRoute.fetch(new Request('http://127.0.0.1:1/api/plugin-finder/catalog.json'))
|
|
22
53
|
const bundled = JSON.parse(await bundledResponse.text())
|
|
23
54
|
check('bundled route answers 200 json', bundledResponse.status === 200 && bundledResponse.headers.get('content-type').startsWith('application/json'))
|
|
24
55
|
check('bundled payload has 7000+ plugins', Array.isArray(bundled.plugins) && bundled.plugins.length > 7000)
|
|
@@ -26,7 +57,7 @@ check('every bundled entry has name and version', bundled.plugins.every(p => typ
|
|
|
26
57
|
check('entries are sorted by downloads', bundled.plugins.every((p, i) => i === 0 || (bundled.plugins[i - 1].downloads ?? 0) >= (p.downloads ?? 0)))
|
|
27
58
|
|
|
28
59
|
if (process.argv.includes('--refresh')) {
|
|
29
|
-
const refreshed = await
|
|
60
|
+
const refreshed = await catalogRoute.fetch(new Request('http://127.0.0.1:1/api/plugin-finder/catalog.json?refresh=1'))
|
|
30
61
|
const text = await refreshed.text()
|
|
31
62
|
let payload
|
|
32
63
|
try { payload = JSON.parse(text) } catch { payload = undefined }
|
|
@@ -87,6 +118,13 @@ check('theme category results are ranked', themed.length > 0 && themed[0].catego
|
|
|
87
118
|
// Empty query enumerates the catalog.
|
|
88
119
|
check('empty query enumerates every entry', plugin.__test.searchEntries(entries, []).length === entries.length)
|
|
89
120
|
|
|
121
|
+
// Category filter and sort options.
|
|
122
|
+
const themeOnly = plugin.__test.applyFilters(entries, { category: 'theme', sort: 'hot' })
|
|
123
|
+
check('category filter keeps only theme entries', themeOnly.length > 0 && themeOnly.every(entry => entry.category === 'theme'))
|
|
124
|
+
const sortedByName = plugin.__test.applyFilters(entries, { category: 'all', sort: 'name' })
|
|
125
|
+
check('name sort is alphabetical', sortedByName.every((entry, i) => i === 0 || sortedByName[i - 1].name.localeCompare(entry.name) <= 0))
|
|
126
|
+
check('filter helper is exposed for verification', typeof plugin.__test.applyFilters === 'function')
|
|
127
|
+
|
|
90
128
|
// Descriptions are kept for both languages where the source has them.
|
|
91
129
|
const bilingual = bundled.plugins.filter(p => p.description && p.description.zh && p.description.en).length
|
|
92
130
|
check(`bilingual descriptions present (${bilingual})`, bilingual > 6000)
|
|
@@ -97,6 +135,26 @@ const tab = plugin.__test.FinderTab({ t: translate, install: () => {} })
|
|
|
97
135
|
check('tab renders its root', tab?.props?.className === 'pf-root')
|
|
98
136
|
const row = plugin.__test.FinderRow({ entry: entries[0], install: () => {}, language: 'zh', t: translate })
|
|
99
137
|
check('row renders its root', row?.props?.className === 'pf-row')
|
|
138
|
+
const installedRow = plugin.__test.FinderRow({
|
|
139
|
+
entry: entries[0], install: () => {}, language: 'zh', t: translate,
|
|
140
|
+
installed: { plugins: [{ name: entries[0].name, version: '0.0.1', latest: '0.0.2', hasUpdate: true }] },
|
|
141
|
+
})
|
|
142
|
+
const side = installedRow?.children?.find(child => child?.props?.className === 'pf-side')
|
|
143
|
+
check('installed row shows an update button', JSON.stringify(side).includes('pf-install') && JSON.stringify(side).includes('pf-badge-new'))
|
|
144
|
+
|
|
145
|
+
const dialog = plugin.__test.ScanDialog({
|
|
146
|
+
scan: {
|
|
147
|
+
entry: entries[0], version: '1.0.0', status: 'ready',
|
|
148
|
+
result: {
|
|
149
|
+
verdict: 'WARN', summary: { high: 0, medium: 1, low: 2 }, filesScanned: 10, filesTotal: 12,
|
|
150
|
+
network: { hosts: ['example.com'] }, hits: [{ rule: 'shell_true', severity: 'medium', file: 'a.js', line: 3, evidence: 'shell: true' }],
|
|
151
|
+
recommendations: ['review'], notes: 1,
|
|
152
|
+
},
|
|
153
|
+
},
|
|
154
|
+
t: (key, vars) => key + (vars === undefined ? '' : JSON.stringify(vars)),
|
|
155
|
+
onCancel: () => {}, onConfirm: () => {},
|
|
156
|
+
})
|
|
157
|
+
check('scan dialog renders a modal', dialog?.props?.className === 'pf-overlay' && JSON.stringify(dialog).includes('pf-verdict-warn'))
|
|
100
158
|
|
|
101
159
|
console.log(failures === 0 ? '\nALL CHECKS PASSED' : `\n${failures} CHECK(S) FAILED`)
|
|
102
160
|
process.exit(failures === 0 ? 0 : 1)
|