ghostimport 0.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/README.md +240 -0
- package/dist/cache.d.ts +4 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +587 -0
- package/dist/config.d.ts +3 -0
- package/dist/files.d.ts +3 -0
- package/dist/imports.d.ts +1 -0
- package/dist/index.cjs +476 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +431 -0
- package/dist/npm.d.ts +3 -0
- package/dist/scan.d.ts +2 -0
- package/dist/types.d.ts +70 -0
- package/package.json +61 -0
package/dist/cli.js
ADDED
|
@@ -0,0 +1,587 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import path5 from "path";
|
|
5
|
+
import { readFileSync } from "fs";
|
|
6
|
+
import { fileURLToPath } from "url";
|
|
7
|
+
|
|
8
|
+
// src/scan.ts
|
|
9
|
+
import fs4 from "fs";
|
|
10
|
+
import path4 from "path";
|
|
11
|
+
|
|
12
|
+
// src/imports.ts
|
|
13
|
+
var IMPORT_PATTERNS = [
|
|
14
|
+
/import\s+(?:[\w*{}\s,]+\s+from\s+)?['"]([^'".\n][^'"]*)['"]/g,
|
|
15
|
+
/require\s*\(\s*['"]([^'".\n][^'"]*)['"]\s*\)/g,
|
|
16
|
+
/import\s*\(\s*['"]([^'".\n][^'"]*)['"]\s*\)/g,
|
|
17
|
+
/export\s+(?:[\w*{}\s,]+\s+from\s+)?['"]([^'".\n][^'"]*)['"]/g
|
|
18
|
+
];
|
|
19
|
+
var BUILTIN_MODULES = /* @__PURE__ */ new Set([
|
|
20
|
+
"assert",
|
|
21
|
+
"assert/strict",
|
|
22
|
+
"async_hooks",
|
|
23
|
+
"buffer",
|
|
24
|
+
"child_process",
|
|
25
|
+
"cluster",
|
|
26
|
+
"console",
|
|
27
|
+
"constants",
|
|
28
|
+
"crypto",
|
|
29
|
+
"dgram",
|
|
30
|
+
"diagnostics_channel",
|
|
31
|
+
"dns",
|
|
32
|
+
"dns/promises",
|
|
33
|
+
"domain",
|
|
34
|
+
"events",
|
|
35
|
+
"fs",
|
|
36
|
+
"fs/promises",
|
|
37
|
+
"http",
|
|
38
|
+
"http2",
|
|
39
|
+
"https",
|
|
40
|
+
"inspector",
|
|
41
|
+
"inspector/promises",
|
|
42
|
+
"module",
|
|
43
|
+
"net",
|
|
44
|
+
"os",
|
|
45
|
+
"path",
|
|
46
|
+
"path/posix",
|
|
47
|
+
"path/win32",
|
|
48
|
+
"perf_hooks",
|
|
49
|
+
"process",
|
|
50
|
+
"punycode",
|
|
51
|
+
"querystring",
|
|
52
|
+
"readline",
|
|
53
|
+
"readline/promises",
|
|
54
|
+
"repl",
|
|
55
|
+
"sea",
|
|
56
|
+
"stream",
|
|
57
|
+
"stream/consumers",
|
|
58
|
+
"stream/promises",
|
|
59
|
+
"stream/web",
|
|
60
|
+
"string_decoder",
|
|
61
|
+
"sys",
|
|
62
|
+
"test",
|
|
63
|
+
"timers",
|
|
64
|
+
"timers/promises",
|
|
65
|
+
"tls",
|
|
66
|
+
"trace_events",
|
|
67
|
+
"tty",
|
|
68
|
+
"url",
|
|
69
|
+
"util",
|
|
70
|
+
"util/types",
|
|
71
|
+
"v8",
|
|
72
|
+
"vm",
|
|
73
|
+
"wasi",
|
|
74
|
+
"worker_threads",
|
|
75
|
+
"zlib"
|
|
76
|
+
]);
|
|
77
|
+
function isBuiltin(name) {
|
|
78
|
+
if (name.startsWith("node:")) return true;
|
|
79
|
+
return BUILTIN_MODULES.has(name);
|
|
80
|
+
}
|
|
81
|
+
function toPackageName(importPath) {
|
|
82
|
+
if (importPath.startsWith("@")) {
|
|
83
|
+
const parts = importPath.split("/");
|
|
84
|
+
if (parts.length < 2) return null;
|
|
85
|
+
return `${parts[0]}/${parts[1]}`;
|
|
86
|
+
}
|
|
87
|
+
return importPath.split("/")[0];
|
|
88
|
+
}
|
|
89
|
+
function extractImports(code) {
|
|
90
|
+
const found = /* @__PURE__ */ new Set();
|
|
91
|
+
for (const pattern of IMPORT_PATTERNS) {
|
|
92
|
+
pattern.lastIndex = 0;
|
|
93
|
+
let match;
|
|
94
|
+
while ((match = pattern.exec(code)) !== null) {
|
|
95
|
+
const raw = match[1];
|
|
96
|
+
const pkg = toPackageName(raw);
|
|
97
|
+
if (pkg && !isBuiltin(raw) && !isBuiltin(pkg)) {
|
|
98
|
+
found.add(pkg);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return [...found];
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// src/cache.ts
|
|
106
|
+
import fs from "fs";
|
|
107
|
+
import path from "path";
|
|
108
|
+
import os from "os";
|
|
109
|
+
var CACHE_TTL = 24 * 60 * 60 * 1e3;
|
|
110
|
+
function getCacheDir() {
|
|
111
|
+
const dir = path.join(os.homedir(), ".ghostimport");
|
|
112
|
+
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
|
113
|
+
return dir;
|
|
114
|
+
}
|
|
115
|
+
function getCachePath() {
|
|
116
|
+
return path.join(getCacheDir(), "registry-cache.json");
|
|
117
|
+
}
|
|
118
|
+
function loadCache() {
|
|
119
|
+
const cachePath = getCachePath();
|
|
120
|
+
if (!fs.existsSync(cachePath)) return {};
|
|
121
|
+
try {
|
|
122
|
+
return JSON.parse(fs.readFileSync(cachePath, "utf8"));
|
|
123
|
+
} catch {
|
|
124
|
+
return {};
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
function saveCache(cache) {
|
|
128
|
+
fs.writeFileSync(getCachePath(), JSON.stringify(cache, null, 2), "utf8");
|
|
129
|
+
}
|
|
130
|
+
function getCached(cache, pkgName) {
|
|
131
|
+
const entry = cache[pkgName];
|
|
132
|
+
if (!entry) return null;
|
|
133
|
+
if (Date.now() - entry.ts > CACHE_TTL) return null;
|
|
134
|
+
return entry;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// src/config.ts
|
|
138
|
+
import fs2 from "fs";
|
|
139
|
+
import path2 from "path";
|
|
140
|
+
var defaults = { ignore: [], includeUndeclared: true };
|
|
141
|
+
function loadConfig(dir) {
|
|
142
|
+
const configPath = path2.join(dir, ".ghostimportrc.json");
|
|
143
|
+
if (!fs2.existsSync(configPath)) return { ...defaults };
|
|
144
|
+
try {
|
|
145
|
+
const raw = JSON.parse(fs2.readFileSync(configPath, "utf8"));
|
|
146
|
+
return { ...defaults, ...raw };
|
|
147
|
+
} catch {
|
|
148
|
+
return { ...defaults };
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
function matchesIgnore(pkg, patterns) {
|
|
152
|
+
for (const pattern of patterns) {
|
|
153
|
+
if (pattern === pkg) return true;
|
|
154
|
+
if (pattern.endsWith("/*")) {
|
|
155
|
+
const prefix = pattern.slice(0, -1);
|
|
156
|
+
if (pkg.startsWith(prefix)) return true;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return false;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// src/npm.ts
|
|
163
|
+
import https from "https";
|
|
164
|
+
function httpGetJson(url) {
|
|
165
|
+
return new Promise((resolve, reject) => {
|
|
166
|
+
const req = https.get(url, { headers: { Accept: "application/json" }, timeout: 8e3 }, (res) => {
|
|
167
|
+
let data = "";
|
|
168
|
+
res.on("data", (chunk) => {
|
|
169
|
+
data += chunk;
|
|
170
|
+
});
|
|
171
|
+
res.on("end", () => {
|
|
172
|
+
if (res.statusCode === 200) {
|
|
173
|
+
try {
|
|
174
|
+
resolve(JSON.parse(data));
|
|
175
|
+
} catch {
|
|
176
|
+
reject(new Error("Invalid JSON"));
|
|
177
|
+
}
|
|
178
|
+
} else if (res.statusCode === 404) {
|
|
179
|
+
resolve(null);
|
|
180
|
+
} else {
|
|
181
|
+
reject(new Error(`HTTP ${res.statusCode}`));
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
});
|
|
185
|
+
req.on("timeout", () => {
|
|
186
|
+
req.destroy();
|
|
187
|
+
reject(new Error("timeout"));
|
|
188
|
+
});
|
|
189
|
+
req.on("error", reject);
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
function encodePackageName(pkgName) {
|
|
193
|
+
return pkgName.startsWith("@") ? "@" + encodeURIComponent(pkgName.slice(1)) : encodeURIComponent(pkgName);
|
|
194
|
+
}
|
|
195
|
+
function checkNpm(pkgName) {
|
|
196
|
+
return new Promise((resolve) => {
|
|
197
|
+
const options = {
|
|
198
|
+
hostname: "registry.npmjs.org",
|
|
199
|
+
path: `/${encodePackageName(pkgName)}`,
|
|
200
|
+
method: "GET",
|
|
201
|
+
headers: { Accept: "application/json" },
|
|
202
|
+
timeout: 8e3
|
|
203
|
+
};
|
|
204
|
+
const req = https.request(options, (res) => {
|
|
205
|
+
res.resume();
|
|
206
|
+
if (res.statusCode === 200) {
|
|
207
|
+
resolve({ exists: true });
|
|
208
|
+
} else if (res.statusCode === 404) {
|
|
209
|
+
resolve({ exists: false });
|
|
210
|
+
} else {
|
|
211
|
+
resolve({ exists: null, error: `HTTP ${res.statusCode}` });
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
req.on("timeout", () => {
|
|
215
|
+
req.destroy();
|
|
216
|
+
resolve({ exists: null, error: "timeout" });
|
|
217
|
+
});
|
|
218
|
+
req.on("error", (err) => {
|
|
219
|
+
resolve({ exists: null, error: err.message });
|
|
220
|
+
});
|
|
221
|
+
req.end();
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
async function checkScary(pkgName) {
|
|
225
|
+
const encoded = encodePackageName(pkgName);
|
|
226
|
+
try {
|
|
227
|
+
const meta = await httpGetJson(`https://registry.npmjs.org/${encoded}`);
|
|
228
|
+
if (!meta) return { exists: false, squatRisk: "available" };
|
|
229
|
+
const created = meta.time?.created ? new Date(meta.time.created) : null;
|
|
230
|
+
const ageMs = created ? Date.now() - created.getTime() : Infinity;
|
|
231
|
+
const ageDays = Math.floor(ageMs / (1e3 * 60 * 60 * 24));
|
|
232
|
+
let downloads = null;
|
|
233
|
+
try {
|
|
234
|
+
const dl = await httpGetJson(`https://api.npmjs.org/downloads/point/last-week/${encoded}`);
|
|
235
|
+
downloads = dl?.downloads ?? null;
|
|
236
|
+
} catch {
|
|
237
|
+
}
|
|
238
|
+
const flags2 = [];
|
|
239
|
+
if (ageDays < 30) flags2.push(`created ${ageDays} days ago`);
|
|
240
|
+
if (downloads !== null && downloads < 50) flags2.push(`${downloads} weekly downloads`);
|
|
241
|
+
if (meta.versions && Object.keys(meta.versions).length <= 1) flags2.push("single version published");
|
|
242
|
+
const risk = flags2.length >= 2 ? "high" : flags2.length === 1 ? "medium" : "low";
|
|
243
|
+
return {
|
|
244
|
+
exists: true,
|
|
245
|
+
created: created?.toISOString().slice(0, 10) ?? "unknown",
|
|
246
|
+
downloads,
|
|
247
|
+
versions: meta.versions ? Object.keys(meta.versions).length : 0,
|
|
248
|
+
risk,
|
|
249
|
+
flags: flags2
|
|
250
|
+
};
|
|
251
|
+
} catch (err) {
|
|
252
|
+
return { exists: null, error: err.message };
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// src/files.ts
|
|
257
|
+
import fs3 from "fs";
|
|
258
|
+
import path3 from "path";
|
|
259
|
+
var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", "dist", "build", ".next", "coverage", ".cache"]);
|
|
260
|
+
var CODE_EXTS = /* @__PURE__ */ new Set([".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs"]);
|
|
261
|
+
function walkFiles(dir) {
|
|
262
|
+
const results2 = [];
|
|
263
|
+
function walk(current) {
|
|
264
|
+
let entries;
|
|
265
|
+
try {
|
|
266
|
+
entries = fs3.readdirSync(current, { withFileTypes: true });
|
|
267
|
+
} catch {
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
for (const entry of entries) {
|
|
271
|
+
if (entry.isDirectory()) {
|
|
272
|
+
if (!SKIP_DIRS.has(entry.name)) walk(path3.join(current, entry.name));
|
|
273
|
+
} else if (entry.isFile()) {
|
|
274
|
+
if (CODE_EXTS.has(path3.extname(entry.name))) results2.push(path3.join(current, entry.name));
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
walk(dir);
|
|
279
|
+
return results2;
|
|
280
|
+
}
|
|
281
|
+
function readPackageJsonDeps(dir) {
|
|
282
|
+
const pkgPath = path3.join(dir, "package.json");
|
|
283
|
+
if (!fs3.existsSync(pkgPath)) return /* @__PURE__ */ new Set();
|
|
284
|
+
try {
|
|
285
|
+
const pkg = JSON.parse(fs3.readFileSync(pkgPath, "utf8"));
|
|
286
|
+
return /* @__PURE__ */ new Set([
|
|
287
|
+
...Object.keys(pkg.dependencies ?? {}),
|
|
288
|
+
...Object.keys(pkg.devDependencies ?? {}),
|
|
289
|
+
...Object.keys(pkg.peerDependencies ?? {}),
|
|
290
|
+
...Object.keys(pkg.optionalDependencies ?? {})
|
|
291
|
+
]);
|
|
292
|
+
} catch {
|
|
293
|
+
return /* @__PURE__ */ new Set();
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
function readWorkspacePackages(dir) {
|
|
297
|
+
const names = /* @__PURE__ */ new Set();
|
|
298
|
+
try {
|
|
299
|
+
const pkg = JSON.parse(fs3.readFileSync(path3.join(dir, "package.json"), "utf8"));
|
|
300
|
+
const workspaces = Array.isArray(pkg.workspaces) ? pkg.workspaces : pkg.workspaces?.packages ?? [];
|
|
301
|
+
for (const pattern of workspaces) {
|
|
302
|
+
const base = pattern.replace(/\/?\*$/, "");
|
|
303
|
+
const wsDir = path3.join(dir, base);
|
|
304
|
+
if (!fs3.existsSync(wsDir)) continue;
|
|
305
|
+
for (const entry of fs3.readdirSync(wsDir, { withFileTypes: true })) {
|
|
306
|
+
if (!entry.isDirectory()) continue;
|
|
307
|
+
const wsPkgPath = path3.join(wsDir, entry.name, "package.json");
|
|
308
|
+
if (!fs3.existsSync(wsPkgPath)) continue;
|
|
309
|
+
try {
|
|
310
|
+
const wsPkg = JSON.parse(fs3.readFileSync(wsPkgPath, "utf8"));
|
|
311
|
+
if (wsPkg.name) names.add(wsPkg.name);
|
|
312
|
+
} catch {
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
} catch {
|
|
317
|
+
}
|
|
318
|
+
const pnpmPath = path3.join(dir, "pnpm-workspace.yaml");
|
|
319
|
+
if (!fs3.existsSync(pnpmPath)) return names;
|
|
320
|
+
try {
|
|
321
|
+
const content = fs3.readFileSync(pnpmPath, "utf8");
|
|
322
|
+
for (const m of content.matchAll(/- ['"]?([^'"\n]+)['"]?/g)) {
|
|
323
|
+
const base = m[1].replace(/\/?\*$/, "");
|
|
324
|
+
const wsDir = path3.join(dir, base);
|
|
325
|
+
if (!fs3.existsSync(wsDir)) continue;
|
|
326
|
+
for (const entry of fs3.readdirSync(wsDir, { withFileTypes: true })) {
|
|
327
|
+
if (!entry.isDirectory()) continue;
|
|
328
|
+
const wsPkgPath = path3.join(wsDir, entry.name, "package.json");
|
|
329
|
+
if (!fs3.existsSync(wsPkgPath)) continue;
|
|
330
|
+
try {
|
|
331
|
+
const wsPkg = JSON.parse(fs3.readFileSync(wsPkgPath, "utf8"));
|
|
332
|
+
if (wsPkg.name) names.add(wsPkg.name);
|
|
333
|
+
} catch {
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
} catch {
|
|
338
|
+
}
|
|
339
|
+
return names;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// src/scan.ts
|
|
343
|
+
var CONCURRENCY = 10;
|
|
344
|
+
async function scan(targetDir2, { onProgress, useCache = true, scary = false, config: config2 } = {}) {
|
|
345
|
+
const conf = config2 ?? loadConfig(targetDir2);
|
|
346
|
+
const files = walkFiles(targetDir2);
|
|
347
|
+
const declaredDeps = readPackageJsonDeps(targetDir2);
|
|
348
|
+
const workspacePkgs = readWorkspacePackages(targetDir2);
|
|
349
|
+
const cache = useCache ? loadCache() : {};
|
|
350
|
+
let cacheHits = 0;
|
|
351
|
+
const importMap = /* @__PURE__ */ new Map();
|
|
352
|
+
for (const file of files) {
|
|
353
|
+
let code;
|
|
354
|
+
try {
|
|
355
|
+
code = fs4.readFileSync(file, "utf8");
|
|
356
|
+
} catch {
|
|
357
|
+
continue;
|
|
358
|
+
}
|
|
359
|
+
for (const pkg of extractImports(code)) {
|
|
360
|
+
if (!importMap.has(pkg)) importMap.set(pkg, []);
|
|
361
|
+
importMap.get(pkg).push(path4.relative(targetDir2, file));
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
const allPkgs = [...importMap.keys()].filter(
|
|
365
|
+
(pkg) => !matchesIgnore(pkg, conf.ignore) && !workspacePkgs.has(pkg)
|
|
366
|
+
);
|
|
367
|
+
const results2 = {
|
|
368
|
+
scanned: files.length,
|
|
369
|
+
packages: allPkgs.length,
|
|
370
|
+
hallucinated: [],
|
|
371
|
+
notInPackageJson: [],
|
|
372
|
+
errors: [],
|
|
373
|
+
scary: [],
|
|
374
|
+
cacheHits: 0
|
|
375
|
+
};
|
|
376
|
+
for (let i = 0; i < allPkgs.length; i += CONCURRENCY) {
|
|
377
|
+
const batch = allPkgs.slice(i, i + CONCURRENCY);
|
|
378
|
+
const checks = await Promise.all(
|
|
379
|
+
batch.map((pkg) => {
|
|
380
|
+
const cached = getCached(cache, pkg);
|
|
381
|
+
if (cached) {
|
|
382
|
+
cacheHits++;
|
|
383
|
+
return Promise.resolve({ exists: cached.exists });
|
|
384
|
+
}
|
|
385
|
+
return checkNpm(pkg);
|
|
386
|
+
})
|
|
387
|
+
);
|
|
388
|
+
for (let j = 0; j < batch.length; j++) {
|
|
389
|
+
const pkg = batch[j];
|
|
390
|
+
const { exists, error } = checks[j];
|
|
391
|
+
const matchedFiles = importMap.get(pkg);
|
|
392
|
+
if (exists !== null && useCache) {
|
|
393
|
+
cache[pkg] = { exists, ts: Date.now() };
|
|
394
|
+
}
|
|
395
|
+
onProgress?.({ pkg, exists, error, total: allPkgs.length, done: i + j + 1 });
|
|
396
|
+
if (exists === false) {
|
|
397
|
+
results2.hallucinated.push({ pkg, files: matchedFiles });
|
|
398
|
+
} else if (exists === null && error) {
|
|
399
|
+
results2.errors.push({ pkg, error, files: matchedFiles });
|
|
400
|
+
} else if (exists === true && !declaredDeps.has(pkg)) {
|
|
401
|
+
results2.notInPackageJson.push({ pkg, files: matchedFiles });
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
if (useCache) saveCache(cache);
|
|
406
|
+
results2.cacheHits = cacheHits;
|
|
407
|
+
if (scary) {
|
|
408
|
+
for (const { pkg, files: matchedFiles } of results2.hallucinated) {
|
|
409
|
+
results2.scary.push({ pkg, files: matchedFiles, type: "available" });
|
|
410
|
+
}
|
|
411
|
+
for (const { pkg, files: matchedFiles } of results2.notInPackageJson) {
|
|
412
|
+
const info = await checkScary(pkg);
|
|
413
|
+
if (info.exists === true && info.risk !== "low") {
|
|
414
|
+
results2.scary.push({
|
|
415
|
+
pkg,
|
|
416
|
+
files: matchedFiles,
|
|
417
|
+
type: "suspicious",
|
|
418
|
+
exists: true,
|
|
419
|
+
created: info.created,
|
|
420
|
+
downloads: info.downloads,
|
|
421
|
+
versions: info.versions,
|
|
422
|
+
risk: info.risk,
|
|
423
|
+
flags: info.flags
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
return results2;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
// src/cli.ts
|
|
432
|
+
var __dirname = path5.dirname(fileURLToPath(import.meta.url));
|
|
433
|
+
var { version } = JSON.parse(
|
|
434
|
+
readFileSync(path5.join(__dirname, "..", "package.json"), "utf8")
|
|
435
|
+
);
|
|
436
|
+
var c = {
|
|
437
|
+
red: (s) => `\x1B[31m${s}\x1B[0m`,
|
|
438
|
+
yellow: (s) => `\x1B[33m${s}\x1B[0m`,
|
|
439
|
+
green: (s) => `\x1B[32m${s}\x1B[0m`,
|
|
440
|
+
cyan: (s) => `\x1B[36m${s}\x1B[0m`,
|
|
441
|
+
gray: (s) => `\x1B[90m${s}\x1B[0m`,
|
|
442
|
+
bold: (s) => `\x1B[1m${s}\x1B[0m`,
|
|
443
|
+
dim: (s) => `\x1B[2m${s}\x1B[0m`,
|
|
444
|
+
magenta: (s) => `\x1B[35m${s}\x1B[0m`
|
|
445
|
+
};
|
|
446
|
+
var args = process.argv.slice(2);
|
|
447
|
+
var targetDir = path5.resolve(args.find((a) => !a.startsWith("--") && !a.startsWith("-")) ?? ".");
|
|
448
|
+
var flags = {
|
|
449
|
+
quiet: args.includes("--quiet") || args.includes("-q"),
|
|
450
|
+
json: args.includes("--json"),
|
|
451
|
+
noUndeclared: args.includes("--no-undeclared"),
|
|
452
|
+
noCache: args.includes("--no-cache"),
|
|
453
|
+
scary: args.includes("--scary"),
|
|
454
|
+
help: args.includes("--help") || args.includes("-h"),
|
|
455
|
+
version: args.includes("--version") || args.includes("-v")
|
|
456
|
+
};
|
|
457
|
+
if (flags.version) {
|
|
458
|
+
console.log(`ghostimport v${version}`);
|
|
459
|
+
process.exit(0);
|
|
460
|
+
}
|
|
461
|
+
if (flags.help) {
|
|
462
|
+
console.log(`
|
|
463
|
+
${c.bold("ghostimport")} \u2014 detect hallucinated npm packages in your code
|
|
464
|
+
|
|
465
|
+
${c.bold("Usage:")}
|
|
466
|
+
ghostimport [dir] [options]
|
|
467
|
+
|
|
468
|
+
${c.bold("Options:")}
|
|
469
|
+
--quiet, -q Only show problems (no progress)
|
|
470
|
+
--json Output results as JSON
|
|
471
|
+
--no-undeclared Skip "imported but not in package.json" warnings
|
|
472
|
+
--scary Check for supply chain attack risk (squatting)
|
|
473
|
+
--no-cache Skip the local registry cache
|
|
474
|
+
--version, -v Show version
|
|
475
|
+
--help, -h Show this help
|
|
476
|
+
|
|
477
|
+
${c.bold("Config:")}
|
|
478
|
+
Create ${c.cyan(".ghostimportrc.json")} in your project root:
|
|
479
|
+
{
|
|
480
|
+
"ignore": ["@company/*", "internal-lib"],
|
|
481
|
+
"includeUndeclared": true
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
${c.bold("Examples:")}
|
|
485
|
+
ghostimport scan current directory
|
|
486
|
+
ghostimport ./src scan specific folder
|
|
487
|
+
ghostimport --quiet only show issues
|
|
488
|
+
ghostimport --scary check supply chain risk
|
|
489
|
+
ghostimport --json machine-readable output
|
|
490
|
+
`);
|
|
491
|
+
process.exit(0);
|
|
492
|
+
}
|
|
493
|
+
var config = loadConfig(targetDir);
|
|
494
|
+
if (!flags.quiet && !flags.json) {
|
|
495
|
+
console.log(`
|
|
496
|
+
${c.bold("ghostimport")} ${c.gray(`v${version}`)}`);
|
|
497
|
+
console.log(c.gray(`Scanning ${targetDir}`));
|
|
498
|
+
if (flags.scary) console.log(c.magenta(" \u26A0 Scary mode: checking supply chain risk"));
|
|
499
|
+
console.log();
|
|
500
|
+
}
|
|
501
|
+
var lastProgress = "";
|
|
502
|
+
var results = await scan(targetDir, {
|
|
503
|
+
useCache: !flags.noCache,
|
|
504
|
+
scary: flags.scary,
|
|
505
|
+
config,
|
|
506
|
+
onProgress: flags.json || flags.quiet ? void 0 : ({ pkg, done, total }) => {
|
|
507
|
+
const pct = Math.round(done / total * 100);
|
|
508
|
+
const bar = "\u2588".repeat(Math.floor(pct / 5)) + "\u2591".repeat(20 - Math.floor(pct / 5));
|
|
509
|
+
const line = ` ${c.gray(bar)} ${pct}% ${c.dim(pkg.slice(0, 30))}`;
|
|
510
|
+
process.stdout.write("\r" + line + " ".repeat(Math.max(0, lastProgress.length - line.length)));
|
|
511
|
+
lastProgress = line;
|
|
512
|
+
}
|
|
513
|
+
});
|
|
514
|
+
if (!flags.json && !flags.quiet && lastProgress) {
|
|
515
|
+
process.stdout.write("\r" + " ".repeat(lastProgress.length + 5) + "\r");
|
|
516
|
+
}
|
|
517
|
+
if (flags.json) {
|
|
518
|
+
console.log(JSON.stringify(results, null, 2));
|
|
519
|
+
process.exit(results.hallucinated.length > 0 ? 1 : 0);
|
|
520
|
+
}
|
|
521
|
+
var totalIssues = results.hallucinated.length + (flags.noUndeclared ? 0 : results.notInPackageJson.length);
|
|
522
|
+
console.log(
|
|
523
|
+
` ${c.gray("Scanned")} ${c.cyan(results.scanned + " files")} \xB7 ${c.cyan(results.packages + " unique packages")} checked` + (results.cacheHits > 0 ? ` ${c.gray(`(${results.cacheHits} cached)`)}` : "") + "\n"
|
|
524
|
+
);
|
|
525
|
+
if (results.hallucinated.length === 0) {
|
|
526
|
+
console.log(c.green(" \u2713 No hallucinated packages found"));
|
|
527
|
+
} else {
|
|
528
|
+
console.log(c.bold(c.red(` \u2717 ${results.hallucinated.length} hallucinated package${results.hallucinated.length > 1 ? "s" : ""} (do not exist on npm):
|
|
529
|
+
`)));
|
|
530
|
+
for (const { pkg, files } of results.hallucinated) {
|
|
531
|
+
console.log(` ${c.red("\u25CF")} ${c.bold(pkg)}`);
|
|
532
|
+
for (const f of files.slice(0, 3)) console.log(` ${c.gray("\u21B3")} ${c.dim(f)}`);
|
|
533
|
+
if (files.length > 3) console.log(` ${c.gray(`\u21B3 ...and ${files.length - 3} more files`)}`);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
if (flags.scary && results.scary.length > 0) {
|
|
537
|
+
console.log();
|
|
538
|
+
const available = results.scary.filter((s) => s.type === "available");
|
|
539
|
+
const suspicious = results.scary.filter((s) => s.type === "suspicious");
|
|
540
|
+
if (available.length > 0) {
|
|
541
|
+
console.log(c.bold(c.magenta(` \u{1F480} ${available.length} package name${available.length > 1 ? "s" : ""} available for malicious registration:
|
|
542
|
+
`)));
|
|
543
|
+
for (const { pkg } of available) {
|
|
544
|
+
console.log(` ${c.magenta("\u25CF")} ${c.bold(pkg)}`);
|
|
545
|
+
console.log(` ${c.red("\u21B3 Anyone can register this name with a malicious postinstall script")}`);
|
|
546
|
+
console.log(` ${c.red("\u21B3 If installed, it could exfiltrate .env, tokens, SSH keys")}`);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
if (suspicious.length > 0) {
|
|
550
|
+
console.log();
|
|
551
|
+
console.log(c.bold(c.magenta(` \u{1F575}\uFE0F ${suspicious.length} suspicious package${suspicious.length > 1 ? "s" : ""} (potential squats):
|
|
552
|
+
`)));
|
|
553
|
+
for (const entry of suspicious) {
|
|
554
|
+
if (entry.type !== "suspicious") continue;
|
|
555
|
+
console.log(` ${c.magenta("\u25CF")} ${c.bold(entry.pkg)} ${c.gray(`(created ${entry.created}, ${entry.downloads ?? "?"} downloads/week)`)}`);
|
|
556
|
+
for (const flag of entry.flags) console.log(` ${c.yellow("\u21B3")} ${flag}`);
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
if (!flags.noUndeclared && results.notInPackageJson.length > 0) {
|
|
561
|
+
console.log();
|
|
562
|
+
console.log(c.bold(c.yellow(` \u26A0 ${results.notInPackageJson.length} package${results.notInPackageJson.length > 1 ? "s" : ""} imported but missing from package.json:
|
|
563
|
+
`)));
|
|
564
|
+
for (const { pkg, files } of results.notInPackageJson.slice(0, 10)) {
|
|
565
|
+
console.log(` ${c.yellow("\u25CF")} ${c.bold(pkg)}`);
|
|
566
|
+
for (const f of files.slice(0, 2)) console.log(` ${c.gray("\u21B3")} ${c.dim(f)}`);
|
|
567
|
+
}
|
|
568
|
+
if (results.notInPackageJson.length > 10) {
|
|
569
|
+
console.log(` ${c.gray(` ...and ${results.notInPackageJson.length - 10} more`)}`);
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
if (results.errors.length > 0) {
|
|
573
|
+
console.log();
|
|
574
|
+
console.log(c.gray(` \u26A1 ${results.errors.length} package(s) could not be checked (network/timeout)`));
|
|
575
|
+
}
|
|
576
|
+
console.log();
|
|
577
|
+
if (totalIssues === 0 && results.scary.length === 0) {
|
|
578
|
+
console.log(c.green(c.bold(" All good! \u2713\n")));
|
|
579
|
+
} else if (flags.scary && results.scary.length > 0) {
|
|
580
|
+
const scaryCount = results.scary.filter((s) => s.type === "available").length;
|
|
581
|
+
console.log(c.red(c.bold(` Found ${totalIssues} issue${totalIssues > 1 ? "s" : ""} \xB7 ${scaryCount} supply chain risk${scaryCount > 1 ? "s" : ""}
|
|
582
|
+
`)));
|
|
583
|
+
} else {
|
|
584
|
+
console.log(c.red(c.bold(` Found ${totalIssues} issue${totalIssues > 1 ? "s" : ""}.
|
|
585
|
+
`)));
|
|
586
|
+
}
|
|
587
|
+
process.exit(results.hallucinated.length > 0 ? 1 : 0);
|
package/dist/config.d.ts
ADDED
package/dist/files.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function extractImports(code: string): string[];
|