skillscout 0.0.0-stage → 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.
@@ -0,0 +1,243 @@
1
+ import { describeInvisible, INVISIBLE, sanitize } from "../sanitize.js";
2
+ import { parseFrontmatter } from "../fetchSkill.js";
3
+ import { SEVERITY_ORDER } from "../types.js";
4
+ const URLISH = /:\/\/|\b[a-z0-9-]+\.(sh|io|com|dev|org|net|ai|app|run|xyz|top|ru|cn)\b/i;
5
+ const RAW_IP = /\b(\d{1,3}\.){3}\d{1,3}\b/;
6
+ const SHADY_HOST = /:\/\/[^\s/]*\.(xyz|top|tk|ml|ga|cf|gq|ru|cn|zip|click|icu)\b|webhook\.site|pastebin|transfer\.sh|ngrok|raw\.githubusercontent\.com\/[^\s/]+\/[^\s/]+\/[0-9a-f]{7,}/i;
7
+ const RUNS_CODE = /\b(curl|wget|nc|ncat|base64|eval|bash -c|sh -c|python3? -c|node -e)\b|\/tmp\//i;
8
+ /** curl ... | sh: documented vendor installers over https are common in docs; still worth a look. */
9
+ function gradePipe(line, isMd) {
10
+ if (/\\\|/.test(line) || !URLISH.test(line))
11
+ return null; // table cell or prose like "curl|wget|bash"
12
+ if (!isMd || /:\/\/(?!localhost)[^\s]*http:|\bhttp:\/\//i.test(line) || RAW_IP.test(line) || SHADY_HOST.test(line))
13
+ return "critical";
14
+ return "medium";
15
+ }
16
+ /**
17
+ * Line-level rules. These are deliberately conservative patterns: they flag
18
+ * things worth a human look, not proof of malice. Security-focused skills
19
+ * will legitimately trip some of them; that is what "review" is for.
20
+ */
21
+ export const LINE_RULES = [
22
+ // --- Remote code execution / droppers ---
23
+ { id: "pipe-to-shell", severity: "critical", message: "Downloads and pipes remote content into a shell", pattern: /\b(curl|wget)\b[^\n|]*\|\s*(sudo\s+)?(ba|z|da)?sh\b/i, adjust: gradePipe },
24
+ { id: "pipe-to-interpreter", severity: "critical", message: "Downloads and pipes remote content into an interpreter", pattern: /\b(curl|wget)\b[^\n|]*\|\s*(sudo\s+)?(python3?|node|perl|ruby|php)\b/i, adjust: gradePipe },
25
+ { id: "powershell-iex", severity: "critical", message: "PowerShell download-and-execute", pattern: /\b(iex|Invoke-Expression)\b.*\b(DownloadString|iwr|Invoke-WebRequest|irm)\b|\b(iwr|irm|Invoke-WebRequest)\b.*\|\s*iex\b/i },
26
+ { id: "decode-and-exec", severity: "critical", message: "Decodes base64 and executes the result", pattern: /base64\s+(-d|--decode|-D)\b[^\n]*\|\s*(ba|z)?sh\b|eval\s*\(\s*(atob|Buffer\.from|base64\.b64decode|bytes\.fromhex)|exec\s*\(\s*(base64\.b64decode|zlib\.decompress|codecs\.decode)/i },
27
+ { id: "reverse-shell", severity: "critical", message: "Reverse-shell pattern", pattern: /\/dev\/(tcp|udp)\/(?!127\.0\.0\.1\/|localhost\/)[\w.$]|\bnc(at)?\b[^\n]*\s-(e|c)\s|\bsocat\b[^\n]*exec:|pty\.spawn\(|\bmkfifo\b[^\n]*\bnc\b/i },
28
+ // --- Prompt injection / agent manipulation (instructions) ---
29
+ { id: "ignore-instructions", severity: "high", message: "Tries to override prior instructions", pattern: /\b(ignore|disregard|forget|override)\b[^\n.]{0,40}\b(previous|prior|above|earlier|system|all)\b[^\n.]{0,20}\b(instructions?|prompts?|rules|guidelines)\b/i, adjust: (_l, isMd) => (isMd ? "high" : "medium") },
30
+ {
31
+ id: "conceal-from-user",
32
+ severity: "high",
33
+ message: "Tells the agent to hide actions from the user",
34
+ pattern: /\b(do not|don't|never|without)\b[^\n.]{0,30}\b(tell(ing)?|inform(ing)?|mention(ing)?|notify(ing)?|show(ing)?|alert(ing)?|reveal(ing)?)\b[^\n.]{0,20}\b(the )?user\b(?! to\b)|\b(hide|conceal|keep)\b[^\n.]{0,30}\bfrom the user\b|without the user (knowing|noticing)|(?<!not |never |don't )\bsilently\b[^\n.]{0,40}\b(run|execute|send|upload|install|delete)\b/i,
35
+ scope: "markdown",
36
+ },
37
+ { id: "skip-user-confirmation", severity: "low", message: "Tells the agent to act without asking the user", pattern: /\b(do not|don't|never|without)\b[^\n.]{0,30}\b(ask(ing)?|confirm(ing|ation)?|prompt(ing)?)\b[^\n.]{0,20}\b(the )?user\b/i, scope: "markdown" },
38
+ { id: "persona-hijack", severity: "medium", message: "Attempts to redefine the agent's identity or authority", pattern: /\byou are now\b|\bnew system prompt\b|\b(act|behave) as (an? )?(unrestricted|jailbroken|developer mode)\b|<\/?\s*(system|assistant)\s*>/i, scope: "markdown" },
39
+ { id: "bypass-safety", severity: "high", message: "Asks to bypass permissions, sandboxing or confirmation", pattern: /--dangerously-skip-permissions|bypassPermissions|\b(bypass|disable|skip|turn off)\b[^\n.]{0,30}\b(permission|confirmation|sandbox|approval|safety|guardrail)s?\b/i,
40
+ adjust: (line) => /--dangerously-skip-permissions|bypassPermissions|\b(bypass|disable|turn off)\b[^\n.]{0,30}\b(safety|guardrail|permission)s?\b/i.test(line) && !/--(no|disable-setuid)-sandbox/.test(line)
41
+ ? "high"
42
+ : "low",
43
+ },
44
+ // --- Credential / sensitive file access ---
45
+ { id: "credential-paths", severity: "medium", message: "References credential or secret locations", pattern: /~\/\.ssh|\bid_(rsa|ed25519|ecdsa)\b|\.aws\/credentials|\.config\/gh\/hosts|\.netrc\b|\.npmrc\b|\.pypirc\b|\.docker\/config\.json|\bKeychain\b|security find-(generic|internet)-password|\bgh auth token\b|\.git-credentials/i },
46
+ { id: "secret-env", severity: "low", message: "Reads secret-looking environment variables", pattern: /\b(ANTHROPIC|OPENAI|AWS_SECRET|GITHUB|GH|NPM|SLACK|STRIPE)_[A-Z_]*(KEY|TOKEN|SECRET)\b/ },
47
+ { id: "browser-data", severity: "high", message: "References browser profile/cookie stores", pattern: /(Chrome|Chromium|Firefox|Brave|Edge)[^\n]{0,40}(Cookies|Login Data|Local State|cookies\.sqlite|logins\.json)/i },
48
+ // --- Agent configuration tampering / persistence ---
49
+ { id: "agent-config-tamper", severity: "high", message: "Modifies agent configuration, hooks, or other skills", pattern: /(>>?|write|edit|modify|append|overwrite|tee|cp|mv|sed -i)[^\n]{0,60}(\.claude\/(settings|hooks|skills|agents)|settings(\.local)?\.json|CLAUDE\.md|AGENTS\.md|\.mcp\.json|\.cursorrules)/i,
50
+ adjust: (line) => /(>>?|\btee\b|\bcp\b|\bmv\b|sed -i|writeFile|open\([^)]*['"][wa])[^\n]{0,60}(~\/\.claude|\$HOME\/\.claude|\.claude\/(settings|hooks)|\.claude\.json|hooks\.json)/i.test(line) ? "high" : "medium",
51
+ },
52
+ { id: "shell-persistence", severity: "high", message: "Installs persistence (shell rc, cron, launchd, systemd)", pattern: /(>>?|tee -a)\s*~?\/?[^\n]{0,20}\.(bashrc|zshrc|profile|bash_profile|zprofile)\b|\bcrontab\b|\blaunchctl\s+(load|bootstrap)|LaunchAgents\/|systemctl\s+(--user\s+)?enable/i,
53
+ adjust: (line, isMd) => {
54
+ if (/\bcrontab\s+-l\b/.test(line) && !/\|\s*crontab\b/.test(line))
55
+ return null;
56
+ if (RUNS_CODE.test(line))
57
+ return "high";
58
+ return isMd ? "medium" : "high";
59
+ },
60
+ },
61
+ // --- Destructive / privilege ---
62
+ { id: "destructive-rm", severity: "high", message: "Recursive delete of home or root paths", pattern: /\brm\s+-[a-z]*r[a-z]*f?[a-z]*\s+(-[a-z]+\s+)*(\/(?!tmp\b|var\/lib\/apt\/lists|var\/cache\/|root\/\.cache)|~\/?(\s|$)|\$HOME\/?(\s|$)|\/\*)/i },
63
+ { id: "privilege", severity: "medium", message: "Uses sudo or world-writable permissions", pattern: /\bsudo\s+(?!-n\s+true)|\bchmod\s+(-R\s+)?(777|a\+w|o\+w)\b/i },
64
+ { id: "disable-security", severity: "high", message: "Disables OS security controls", pattern: /\bspctl\s+--master-disable|\bcsrutil\s+disable|xattr\s+-[a-z]*d[a-z]*\s+com\.apple\.quarantine|Set-MpPreference\s+-Disable|setenforce\s+0/i },
65
+ // --- Network / exfiltration indicators (combined later) ---
66
+ { id: "network", severity: "info", message: "Makes network requests", pattern: /\b(curl|wget)\s|\bfetch\(|\brequests\.(get|post|put)\(|\burllib\.request|\bhttp\.request\(|\baxios\b|\bInvoke-WebRequest\b|\bhttpx\./i, scope: "code" },
67
+ { id: "exfil-endpoint", severity: "high", message: "Uses a common exfiltration/paste/webhook endpoint", pattern: /\b(webhook\.site|requestbin|pipedream\.net|ngrok\.io|ngrok-free\.app|pastebin\.com|transfer\.sh|discord(app)?\.com\/api\/webhooks|hooks\.slack\.com\/services|api\.telegram\.org\/bot|interact\.sh|burpcollaborator|oast\.(fun|me|pro|live|site))\b/i },
68
+ { id: "raw-ip-url", severity: "medium", message: "Contacts a raw IP address", pattern: /\bhttps?:\/\/(?!127\.0\.0\.1|0\.0\.0\.0)(\d{1,3}\.){3}\d{1,3}(?::\d+)?/ },
69
+ // --- Payload indicators ---
70
+ { id: "crypto-miner", severity: "high", message: "Cryptocurrency-miner indicators", pattern: /\bxmrig\b|stratum\+(tcp|ssl):\/\/|\bcryptonight\b|\bminerd\b|\bnicehash\b|\b(crypto)?mining (binary|process|pool|parameters)\b|\bmonero\b[^\n]{0,40}\b(wallet|pool|mine)/i },
71
+ { id: "exec-from-tmp", severity: "high", message: "Runs a program out of a temp directory", pattern: /(\/tmp|\/var\/tmp|\/dev\/shm|%TEMP%|\$TMPDIR)\/?[^\n]{0,40}(&&|;|\|)\s*\.\/[\w.-]+|\bchmod\s+\+?[0-7x]+\s+(\/tmp|\/dev\/shm)\/|(\/tmp|\/dev\/shm)\/[\w.-]+\s*(&|$)/i, scope: "code" },
72
+ { id: "env-dump", severity: "high", message: "Serializes the whole environment (all secrets at once)", pattern: /\b(dict|json\.dumps)\(\s*os\.environ\b|os\.environ\.copy\(\)|JSON\.stringify\(\s*process\.env\s*\)|\{\s*\.\.\.process\.env\s*\}[^\n]{0,40}(body|send|post)|\bprintenv\b[^\n]*\|\s*(curl|nc|base64)|\benv\s*\|\s*(curl|nc|base64)/i },
73
+ { id: "host-fingerprint", severity: "medium", message: "Collects host identity or public IP", pattern: /\b(ipinfo\.io|ifconfig\.me|api\.ipify\.org|icanhazip\.com|checkip\.amazonaws\.com|ip-api\.com)\b|socket\.gethostname\(\)|platform\.node\(\)|getpass\.getuser\(\)|os\.hostname\(\)|os\.userInfo\(\)/i, scope: "code" },
74
+ { id: "boot-persistence", severity: "high", message: "Runs something at boot or login", pattern: /@reboot\b|\/etc\/(rc\.local|init\.d\/|systemd\/system\/)|HKCU\\\\?Software\\\\?Microsoft\\\\?Windows\\\\?CurrentVersion\\\\?Run|\bschtasks\s+\/create\b/i },
75
+ // --- Obfuscation ---
76
+ { id: "long-base64", severity: "medium", message: "Large embedded base64 blob", pattern: /[A-Za-z0-9+/]{400,}={0,2}/ },
77
+ { id: "hex-escapes", severity: "medium", message: "Long run of hex/unicode escapes (possible obfuscation)", pattern: /(\\x[0-9a-f]{2}){24,}|(\\u[0-9a-f]{4}){16,}/i },
78
+ { id: "charcode-build", severity: "medium", message: "Builds strings from character codes (possible obfuscation)", pattern: /String\.fromCharCode\(\s*(\d+\s*,\s*){15,}|chr\(\d+\)\s*\+\s*chr\(\d+\)\s*\+\s*chr\(\d+\)\s*\+\s*chr\(\d+\)/i },
79
+ // --- Supply chain ---
80
+ { id: "global-install", severity: "low", message: "Installs packages globally or from a URL", pattern: /\bnpm\s+(i|install)\s+(-g|--global)\b|\bpip3?\s+install\s+(?!-r\b)[^\n]*(git\+|https?:\/\/)|\bnpx\s+-y\s+[a-z@]/i },
81
+ ];
82
+ const MARKDOWN = /\.(md|mdx|markdown|txt)$/i;
83
+ const BINARY_MAGIC = [
84
+ ["ELF executable", Buffer.from([0x7f, 0x45, 0x4c, 0x46])],
85
+ ["Mach-O executable", Buffer.from([0xcf, 0xfa, 0xed, 0xfe])],
86
+ ["Mach-O executable", Buffer.from([0xfe, 0xed, 0xfa, 0xcf])],
87
+ ["Mach-O universal binary", Buffer.from([0xca, 0xfe, 0xba, 0xbe])],
88
+ ["Windows PE executable", Buffer.from([0x4d, 0x5a])],
89
+ ["WebAssembly module", Buffer.from([0x00, 0x61, 0x73, 0x6d])],
90
+ ];
91
+ const ARCHIVE_EXT = /\.(zip|tar|tgz|gz|bz2|xz|7z|rar|jar|whl|dmg|pkg|exe|dll|so|dylib|bin)$/i;
92
+ const MEDIA_EXT = /\.(png|jpe?g|gif|webp|ico|pdf|woff2?|ttf|otf)$/i;
93
+ function isProbablyText(buf) {
94
+ const n = Math.min(buf.length, 8000);
95
+ for (let i = 0; i < n; i++)
96
+ if (buf[i] === 0)
97
+ return false;
98
+ return true;
99
+ }
100
+ export function scanFiles(files) {
101
+ const findings = [];
102
+ const networkFiles = new Set();
103
+ const secretFiles = new Set();
104
+ for (const f of files) {
105
+ // Binaries and archives cannot be reviewed, so they are flagged as such.
106
+ const magic = BINARY_MAGIC.find(([, m]) => f.content.subarray(0, m.length).equals(m));
107
+ if (magic && !(magic[0] === "Windows PE executable" && isProbablyText(f.content))) {
108
+ findings.push({ rule: "bundled-binary", severity: "high", file: f.path, message: `Bundled ${magic[0]}; cannot be reviewed` });
109
+ continue;
110
+ }
111
+ if (ARCHIVE_EXT.test(f.path) || !isProbablyText(f.content)) {
112
+ if (!MEDIA_EXT.test(f.path)) {
113
+ findings.push({ rule: "opaque-file", severity: "medium", file: f.path, message: "Binary or archive file; contents not reviewed" });
114
+ }
115
+ continue;
116
+ }
117
+ const text = f.content.toString("utf8");
118
+ const isMd = MARKDOWN.test(f.path);
119
+ // Hidden characters: the classic way to smuggle instructions past a human reviewer.
120
+ const invisible = describeInvisible(text.replace(/^/, ""));
121
+ if (invisible.length) {
122
+ const sev = invisible.some((c) => /^U\+(202[A-E]|206[6-9]|E00)/.test(c)) ? "high" : "medium";
123
+ findings.push({ rule: "hidden-unicode", severity: sev, file: f.path, message: "Contains invisible/bidi control characters", excerpt: invisible.slice(0, 8).join(" ") });
124
+ }
125
+ if (isMd) {
126
+ for (const m of text.matchAll(/<!--([\s\S]*?)-->/g)) {
127
+ const body = m[1] ?? "";
128
+ if (/\b(ignore|disregard|instructions?|system prompt|assistant|claude|execute|curl|wget|exfiltrat\w*|password|secret|api[ _-]?key|credentials?|do not (tell|mention|inform))\b|https?:\/\/|\byou (must|should|will|are now)\b|\b(run|send|upload)\b[^\n]{0,40}\b(to|command|script)\b/i.test(body)) {
129
+ findings.push({
130
+ rule: "hidden-html-comment",
131
+ severity: "high",
132
+ file: f.path,
133
+ line: lineOf(text, m.index ?? 0),
134
+ message: "HTML comment (invisible when rendered) contains instruction-like text",
135
+ excerpt: sanitize(body, 100),
136
+ });
137
+ }
138
+ }
139
+ if (/(^|\/)SKILL\.md$/.test(f.path))
140
+ findings.push(...frontmatterFindings(f.path, text));
141
+ }
142
+ const lines = text.split(/\r?\n/);
143
+ for (const rule of LINE_RULES) {
144
+ if (rule.scope === "markdown" && !isMd)
145
+ continue;
146
+ if (rule.scope === "code" && isMd)
147
+ continue;
148
+ let worst; // one finding per rule per file: the most severe hit
149
+ for (let i = 0; i < lines.length; i++) {
150
+ const line = lines[i];
151
+ if (line.length > 20_000)
152
+ continue; // minified blobs are reported by other checks
153
+ const clean = line.replace(INVISIBLE, "");
154
+ if (!rule.pattern.test(clean))
155
+ continue;
156
+ if (rule.id === "network") {
157
+ networkFiles.add(f.path);
158
+ break;
159
+ }
160
+ const severity = rule.adjust ? rule.adjust(clean, isMd) : rule.severity;
161
+ if (severity === null)
162
+ continue;
163
+ if (!worst || SEVERITY_ORDER[severity] > SEVERITY_ORDER[worst.severity]) {
164
+ worst = { rule: rule.id, severity, file: f.path, line: i + 1, message: rule.message, excerpt: sanitize(line, 120) };
165
+ if (severity === rule.severity)
166
+ break;
167
+ }
168
+ }
169
+ if (worst) {
170
+ if (["credential-paths", "secret-env", "browser-data", "host-fingerprint", "env-dump"].includes(rule.id))
171
+ secretFiles.add(f.path);
172
+ findings.push(worst);
173
+ }
174
+ }
175
+ if (/(^|\/)package\.json$/.test(f.path)) {
176
+ try {
177
+ const scripts = JSON.parse(text).scripts ?? {};
178
+ for (const k of ["preinstall", "install", "postinstall", "prepare"]) {
179
+ if (scripts[k])
180
+ findings.push({ rule: "package-install-script", severity: "medium", file: f.path, message: `package.json defines a "${k}" script that runs on npm install`, excerpt: sanitize(scripts[k], 120) });
181
+ }
182
+ }
183
+ catch {
184
+ /* not JSON */
185
+ }
186
+ }
187
+ if (f.executable && isMd) {
188
+ findings.push({ rule: "odd-exec-bit", severity: "low", file: f.path, message: "Markdown file marked executable" });
189
+ }
190
+ }
191
+ for (const file of networkFiles) {
192
+ if (secretFiles.has(file)) {
193
+ findings.push({ rule: "possible-exfiltration", severity: "high", file, message: "Same file reads credentials/secrets and makes network requests" });
194
+ }
195
+ else {
196
+ findings.push({ rule: "network", severity: "info", file, message: "Script makes network requests" });
197
+ }
198
+ }
199
+ return findings.sort((a, b) => SEVERITY_ORDER[b.severity] - SEVERITY_ORDER[a.severity]);
200
+ }
201
+ function frontmatterFindings(path, text) {
202
+ const out = [];
203
+ const fm = parseFrontmatter(text);
204
+ if (!fm.name || !fm.description) {
205
+ out.push({ rule: "frontmatter", severity: "low", file: path, message: "SKILL.md is missing name or description frontmatter" });
206
+ }
207
+ const tools = fm["allowed-tools"] ?? fm.allowed_tools;
208
+ const list = Array.isArray(tools) ? tools.map(String) : typeof tools === "string" ? tools.split(/[,\s]+/) : [];
209
+ if (list.some((t) => /^Bash(\(\s*\*(\s*:\s*\*)?\s*\))?$/.test(t.trim()))) {
210
+ out.push({ rule: "broad-allowed-tools", severity: "medium", file: path, message: "Pre-approves unrestricted Bash via allowed-tools", excerpt: sanitize(list.join(", "), 120) });
211
+ }
212
+ if (list.some((t) => /^(WebFetch|WebSearch)/.test(t.trim())) && list.some((t) => /^Bash/.test(t.trim()))) {
213
+ out.push({ rule: "allowed-tools-network-shell", severity: "low", file: path, message: "Pre-approves both shell and web access", excerpt: sanitize(list.join(", "), 120) });
214
+ }
215
+ const desc = String(fm.description ?? "");
216
+ if (desc.length > 1024) {
217
+ out.push({ rule: "long-description", severity: "low", file: path, message: `Description is ${desc.length} chars (it is always loaded into context)` });
218
+ }
219
+ return out;
220
+ }
221
+ function lineOf(text, index) {
222
+ let n = 1;
223
+ for (let i = 0; i < index && i < text.length; i++)
224
+ if (text.charCodeAt(i) === 10)
225
+ n++;
226
+ return n;
227
+ }
228
+ export function maxSeverity(findings) {
229
+ let best;
230
+ for (const f of findings)
231
+ if (!best || SEVERITY_ORDER[f.severity] > SEVERITY_ORDER[best])
232
+ best = f.severity;
233
+ return best;
234
+ }
235
+ /**
236
+ * Lower a finding that sits in a file the agent never loads or runs (package docs,
237
+ * a plugin's tests). Kept visible, but it cannot block on its own.
238
+ */
239
+ export function capFinding(f, where) {
240
+ const capped = f.severity === "critical" ? "medium" : f.severity === "high" || f.severity === "medium" ? "low" : f.severity;
241
+ return capped === f.severity ? f : { ...f, severity: capped, message: `${f.message} (in ${where}, which the agent does not load)` };
242
+ }
243
+ //# sourceMappingURL=rules.js.map
package/dist/search.js ADDED
@@ -0,0 +1,179 @@
1
+ import { sanitize } from "./sanitize.js";
2
+ import { githubToken, searchPluginManifests, searchSkillFiles } from "./sources/github.js";
3
+ import { searchMcpRegistry } from "./sources/mcpRegistry.js";
4
+ import { npmWeeklyDownloads } from "./sources/packages.js";
5
+ import { partnerRiskSummary, searchSkillsSh } from "./sources/skillssh.js";
6
+ import { mapLimit } from "./fetchSkill.js";
7
+ import { projectTechSet, relevance, skillDescription, topicKey } from "./relevance.js";
8
+ export async function search(opts) {
9
+ const errors = [];
10
+ const kinds = new Set(opts.kinds ?? ["skill", "mcp", "plugin"]);
11
+ if (kinds.has("plugin") && !(await githubToken())) {
12
+ kinds.delete("plugin");
13
+ if (opts.kinds?.includes("plugin"))
14
+ errors.push("Plugin search needs a GitHub token (GITHUB_TOKEN or `gh auth login`).");
15
+ }
16
+ const queries = [...new Set(opts.queries.map((q) => q.trim()).filter(Boolean))].slice(0, 20);
17
+ const exclude = new Set((opts.exclude ?? []).map((s) => s.toLowerCase()));
18
+ const byRef = new Map();
19
+ const add = (c, origin, q) => {
20
+ const key = `${c.kind}:${c.ref.toLowerCase()}`;
21
+ const existing = byRef.get(key);
22
+ if (existing) {
23
+ if (!existing.matchedQueries.includes(q))
24
+ existing.matchedQueries.push(q);
25
+ if (!existing.origin.includes(origin))
26
+ existing.origin.push(origin);
27
+ existing.installs = Math.max(existing.installs ?? 0, c.installs ?? 0) || existing.installs;
28
+ existing.description ??= c.description;
29
+ return;
30
+ }
31
+ byRef.set(key, { ...c, origin: [origin], matchedQueries: [q], score: 0 });
32
+ };
33
+ await Promise.all(queries.map(async (q) => {
34
+ const jobs = [];
35
+ if (kinds.has("skill")) {
36
+ jobs.push(searchSkillsSh(q)
37
+ .then((hits) => hits.slice(0, 12).forEach((h) => add({ kind: "skill", ref: h.id, name: h.name, installs: h.installs }, "skills.sh", q)))
38
+ .catch((e) => void errors.push(`skills.sh "${q}": ${e.message}`)));
39
+ if (opts.includeGithub) {
40
+ jobs.push(searchSkillFiles(q, 8)
41
+ .then((hits) => hits.forEach((h) => {
42
+ const dir = h.path.replace(/\/?SKILL\.md$/, "");
43
+ const name = dir.split("/").pop() || h.repo;
44
+ add({ kind: "skill", ref: `${h.owner}/${h.repo}:${dir}`, name }, "github", q);
45
+ }))
46
+ .catch((e) => void errors.push(`github "${q}": ${e.message}`)));
47
+ }
48
+ }
49
+ if (kinds.has("plugin")) {
50
+ jobs.push(searchPluginManifests(q, 10)
51
+ .then((hits) => hits.forEach((h) => add({ kind: "plugin", ref: `${h.owner}/${h.repo}:${h.path}`, name: h.path.split("/").pop() || h.repo }, "github", q)))
52
+ .catch((e) => void errors.push(`github plugins "${q}": ${e.message}`)));
53
+ }
54
+ if (kinds.has("mcp")) {
55
+ jobs.push(searchMcpRegistry(q, 15)
56
+ .then((servers) => servers.forEach((s) => add({
57
+ kind: "mcp",
58
+ ref: s.name,
59
+ name: s.name,
60
+ description: sanitize(s.description, 200),
61
+ distribution: [...new Set([...(s.packages ?? []).map((p) => p.registryType), ...((s.remotes?.length ?? 0) ? ["remote"] : [])])],
62
+ npmPackage: s.packages?.find((p) => p.registryType === "npm")?.identifier,
63
+ }, "mcp-registry", q)))
64
+ .catch((e) => void errors.push(`mcp-registry "${q}": ${e.message}`)));
65
+ }
66
+ await Promise.all(jobs);
67
+ }));
68
+ let candidates = [...byRef.values()].filter((c) => !exclude.has(c.name.toLowerCase()) && !exclude.has(c.ref.toLowerCase()));
69
+ for (const c of candidates)
70
+ c.score = score(c);
71
+ // The MCP registry has no popularity data; use npm weekly downloads for the strongest candidates.
72
+ const mcpTop = candidates.filter((c) => c.kind === "mcp" && c.npmPackage).sort((a, b) => b.score - a.score).slice(0, 30);
73
+ await Promise.all(mcpTop.map(async (c) => {
74
+ c.weeklyDownloads = await npmWeeklyDownloads(c.npmPackage);
75
+ c.score = score(c);
76
+ }));
77
+ if (opts.project)
78
+ await applyRelevance(candidates, opts.project);
79
+ candidates = fold(candidates);
80
+ candidates.sort((a, b) => b.score - a.score);
81
+ // Scores are not comparable across kinds (skills have install counts, MCP entries do not),
82
+ // so the limit applies per kind.
83
+ const perKind = opts.limit ?? 15;
84
+ const counts = new Map();
85
+ candidates = candidates.filter((c) => {
86
+ const n = (counts.get(c.kind) ?? 0) + 1;
87
+ counts.set(c.kind, n);
88
+ return n <= perKind;
89
+ });
90
+ // Attach skills.sh partner risk (Gen / Socket / Snyk) for the skills we return.
91
+ const bySource = new Map();
92
+ for (const c of candidates) {
93
+ if (c.kind !== "skill" || !c.origin.includes("skills.sh"))
94
+ continue;
95
+ const [o, r] = c.ref.split("/");
96
+ const src = `${o}/${r}`;
97
+ bySource.set(src, [...(bySource.get(src) ?? []), c]);
98
+ }
99
+ await Promise.all([...bySource.entries()].map(async ([src, cs]) => {
100
+ const risk = await partnerRiskSummary(src, cs.map((c) => c.ref.split("/")[2]));
101
+ for (const c of cs)
102
+ c.partnerRisk = risk[c.ref.split("/")[2]];
103
+ }));
104
+ return { candidates, errors };
105
+ }
106
+ function score(c) {
107
+ let s = c.matchedQueries.length * 2;
108
+ if (c.installs)
109
+ s += Math.log10(c.installs + 1);
110
+ if (c.origin.length > 1)
111
+ s += 1;
112
+ if (c.kind === "mcp") {
113
+ // The registry has many near-duplicate entries; prefer ones whose name matches a query term,
114
+ // and installable package distributions over unknown remotes.
115
+ const n = c.name.toLowerCase();
116
+ if (c.matchedQueries.some((q) => n.includes(q.toLowerCase().replace(/\s+/g, "-"))))
117
+ s += 2;
118
+ if (c.distribution?.includes("npm") || c.distribution?.includes("pypi"))
119
+ s += 1;
120
+ if (/^io\.github\./.test(n))
121
+ s += 0.5;
122
+ if (c.weeklyDownloads)
123
+ s += Math.log10(c.weeklyDownloads + 1);
124
+ }
125
+ return Math.round(s * 100) / 100;
126
+ }
127
+ async function applyRelevance(cands, project) {
128
+ const tech = projectTechSet(project, project.languages);
129
+ // Descriptions for the strongest skill candidates (frontmatter only, sanitized).
130
+ const skills = cands.filter((c) => c.kind === "skill" && !c.description).sort((a, b) => b.score - a.score).slice(0, 30);
131
+ await mapLimit(skills, 8, async (c) => {
132
+ const [owner, repo, skill] = c.ref.includes(":") ? [] : c.ref.split("/");
133
+ if (owner && repo && skill)
134
+ c.description = await skillDescription(owner, repo, skill);
135
+ });
136
+ for (const c of cands) {
137
+ const r = relevance(c.name, c.description, tech, project.intent);
138
+ c.score = Math.round((c.score + r.score) * 100) / 100;
139
+ if (r.why.length)
140
+ c.why = r.why;
141
+ }
142
+ }
143
+ /**
144
+ * Fold near-duplicates (same topic name) and cap skills per source repo, so one
145
+ * prolific repo or a pile of clones does not crowd out everything else.
146
+ */
147
+ export function fold(cands, perRepo = 3) {
148
+ const sorted = [...cands].sort((a, b) => b.score - a.score);
149
+ const byTopic = new Map();
150
+ const repoCount = new Map();
151
+ const repoN = new Map();
152
+ const out = [];
153
+ for (const c of sorted) {
154
+ const topic = `${c.kind}:${topicKey(c.name.split("/").pop() ?? c.name)}`;
155
+ const lead = topic.endsWith(":") ? undefined : byTopic.get(topic);
156
+ if (lead) {
157
+ (lead.alternatives ??= []).push(c.ref);
158
+ continue;
159
+ }
160
+ if (c.kind === "skill") {
161
+ const repo = c.ref.split(/[/:]/).slice(0, 2).join("/");
162
+ const n = (repoN.get(repo) ?? 0) + 1;
163
+ repoN.set(repo, n);
164
+ if (n > perRepo) {
165
+ (repoCount.get(repo).alternatives ??= []).push(c.ref);
166
+ continue;
167
+ }
168
+ if (n === 1)
169
+ repoCount.set(repo, c);
170
+ }
171
+ byTopic.set(topic, c);
172
+ out.push(c);
173
+ }
174
+ for (const c of out)
175
+ if (c.alternatives)
176
+ c.alternatives = c.alternatives.slice(0, 5);
177
+ return out;
178
+ }
179
+ //# sourceMappingURL=search.js.map
@@ -0,0 +1,111 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { getBytes, getJson, HttpError } from "./http.js";
4
+ const exec = promisify(execFile);
5
+ const API = "https://api.github.com";
6
+ let tokenPromise;
7
+ /** GITHUB_TOKEN / GH_TOKEN, else `gh auth token`, else unauthenticated (60 req/h). */
8
+ export function githubToken() {
9
+ tokenPromise ??= (async () => {
10
+ const env = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
11
+ if (env)
12
+ return env;
13
+ try {
14
+ const { stdout } = await exec("gh", ["auth", "token"], { timeout: 5000 });
15
+ return stdout.trim() || undefined;
16
+ }
17
+ catch {
18
+ return undefined;
19
+ }
20
+ })();
21
+ return tokenPromise;
22
+ }
23
+ async function headers() {
24
+ const h = {
25
+ accept: "application/vnd.github+json",
26
+ "x-github-api-version": "2022-11-28",
27
+ };
28
+ const t = await githubToken();
29
+ if (t)
30
+ h.authorization = `Bearer ${t}`;
31
+ return h;
32
+ }
33
+ export async function gh(path) {
34
+ try {
35
+ return await getJson(`${API}${path}`, { headers: await headers() });
36
+ }
37
+ catch (e) {
38
+ if (e instanceof HttpError && (e.status === 403 || e.status === 429)) {
39
+ throw new Error(`GitHub rate limit or permission error on ${path}. Set GITHUB_TOKEN or run \`gh auth login\` for higher limits.`);
40
+ }
41
+ throw e;
42
+ }
43
+ }
44
+ export async function resolveCommit(owner, repo, ref) {
45
+ if (ref && /^[0-9a-f]{40}$/.test(ref))
46
+ return ref; // already a commit: immutable, no lookup needed
47
+ const c = await gh(`/repos/${owner}/${repo}/commits/${encodeURIComponent(ref ?? "HEAD")}`);
48
+ return c.sha;
49
+ }
50
+ export async function getTree(owner, repo, sha) {
51
+ const t = await gh(`/repos/${owner}/${repo}/git/trees/${sha}?recursive=1`);
52
+ return t.tree;
53
+ }
54
+ export async function getRawFile(owner, repo, sha, path, maxBytes) {
55
+ const url = `https://raw.githubusercontent.com/${owner}/${repo}/${sha}/${path.split("/").map(encodeURIComponent).join("/")}`;
56
+ const t = await githubToken();
57
+ return getBytes(url, t ? { headers: { authorization: `Bearer ${t}` } } : {}, maxBytes);
58
+ }
59
+ export async function repoProvenance(owner, repo) {
60
+ try {
61
+ const m = await gh(`/repos/${owner}/${repo}`);
62
+ const notes = [];
63
+ const ageDays = (Date.now() - Date.parse(m.created_at)) / 86_400_000;
64
+ if (ageDays < 30)
65
+ notes.push(`Repository is new (${Math.floor(ageDays)} days old).`);
66
+ if (m.stargazers_count < 5)
67
+ notes.push(`Repository has few stars (${m.stargazers_count}).`);
68
+ if (m.archived)
69
+ notes.push("Repository is archived.");
70
+ if (!m.license)
71
+ notes.push("No license declared.");
72
+ return {
73
+ stars: m.stargazers_count,
74
+ forks: m.forks_count,
75
+ createdAt: m.created_at,
76
+ pushedAt: m.pushed_at,
77
+ archived: m.archived,
78
+ license: m.license?.spdx_id ?? null,
79
+ ownerType: m.owner.type,
80
+ notes,
81
+ };
82
+ }
83
+ catch (e) {
84
+ return { notes: [`Could not load repository metadata: ${e.message}`] };
85
+ }
86
+ }
87
+ /** GitHub code search for SKILL.md files. Requires a token. */
88
+ export async function searchSkillFiles(query, perPage = 10) {
89
+ if (!(await githubToken()))
90
+ return [];
91
+ const q = encodeURIComponent(`${query} filename:SKILL.md`);
92
+ const res = await gh(`/search/code?q=${q}&per_page=${perPage}`);
93
+ return res.items.map((i) => {
94
+ const [owner, repo] = i.repository.full_name.split("/");
95
+ return { owner, repo, path: i.path };
96
+ });
97
+ }
98
+ /** GitHub code search for Claude Code plugin manifests. Requires a token. Returns plugin root dirs. */
99
+ export async function searchPluginManifests(query, perPage = 10) {
100
+ if (!(await githubToken()))
101
+ return [];
102
+ const q = encodeURIComponent(`${query} filename:plugin.json path:.claude-plugin`);
103
+ const res = await gh(`/search/code?q=${q}&per_page=${perPage}`);
104
+ return res.items
105
+ .filter((i) => /(^|\/)\.claude-plugin\/plugin\.json$/.test(i.path))
106
+ .map((i) => {
107
+ const [owner, repo] = i.repository.full_name.split("/");
108
+ return { owner, repo, path: i.path.replace(/\/?\.claude-plugin\/plugin\.json$/, "") };
109
+ });
110
+ }
111
+ //# sourceMappingURL=github.js.map
@@ -0,0 +1,47 @@
1
+ const UA = "skillscout/0.1";
2
+ export class HttpError extends Error {
3
+ status;
4
+ url;
5
+ constructor(status, url, message) {
6
+ super(message);
7
+ this.status = status;
8
+ this.url = url;
9
+ }
10
+ }
11
+ export async function getJson(url, init = {}, timeoutMs = 15000) {
12
+ const res = await fetchWithTimeout(url, init, timeoutMs);
13
+ if (!res.ok)
14
+ throw new HttpError(res.status, url, `GET ${redact(url)} -> HTTP ${res.status}`);
15
+ return (await res.json());
16
+ }
17
+ export async function getBytes(url, init = {}, maxBytes = 2_000_000, timeoutMs = 20000) {
18
+ const res = await fetchWithTimeout(url, init, timeoutMs);
19
+ if (!res.ok)
20
+ throw new HttpError(res.status, url, `GET ${redact(url)} -> HTTP ${res.status}`);
21
+ const len = Number(res.headers.get("content-length") ?? "0");
22
+ if (len > maxBytes)
23
+ throw new Error(`Response too large (${len} bytes) from ${redact(url)}`);
24
+ const buf = Buffer.from(await res.arrayBuffer());
25
+ if (buf.length > maxBytes)
26
+ throw new Error(`Response too large (${buf.length} bytes) from ${redact(url)}`);
27
+ return buf;
28
+ }
29
+ async function fetchWithTimeout(url, init, timeoutMs) {
30
+ const controller = new AbortController();
31
+ const t = setTimeout(() => controller.abort(), timeoutMs);
32
+ try {
33
+ return await fetch(url, {
34
+ ...init,
35
+ redirect: "follow",
36
+ signal: controller.signal,
37
+ headers: { "user-agent": UA, ...init.headers },
38
+ });
39
+ }
40
+ finally {
41
+ clearTimeout(t);
42
+ }
43
+ }
44
+ function redact(url) {
45
+ return url.replace(/([?&](?:token|key|access_token)=)[^&]+/gi, "$1***");
46
+ }
47
+ //# sourceMappingURL=http.js.map
@@ -0,0 +1,26 @@
1
+ import { getJson } from "./http.js";
2
+ const BASE = process.env.MCP_REGISTRY_URL || "https://registry.modelcontextprotocol.io";
3
+ function unwrap(e) {
4
+ const meta = e._meta?.["io.modelcontextprotocol.registry/official"] ?? {};
5
+ return {
6
+ ...e.server,
7
+ status: meta.status,
8
+ publishedAt: meta.publishedAt,
9
+ updatedAt: meta.updatedAt,
10
+ isLatest: meta.isLatest ?? true,
11
+ };
12
+ }
13
+ export async function searchMcpRegistry(query, limit = 20) {
14
+ const data = await getJson(`${BASE}/v0/servers?${new URLSearchParams({ search: query, limit: String(limit), version: "latest" })}`);
15
+ return (data.servers ?? []).map(unwrap).filter((s) => s.isLatest && s.status !== "deleted");
16
+ }
17
+ /** Fetch one server by registry name, at a specific version or the latest. */
18
+ export async function getMcpServer(name, version) {
19
+ const enc = encodeURIComponent(name);
20
+ const path = version
21
+ ? `/v0/servers/${enc}/versions/${encodeURIComponent(version)}`
22
+ : `/v0/servers/${enc}/versions/latest`;
23
+ const data = await getJson(`${BASE}${path}`);
24
+ return unwrap(data);
25
+ }
26
+ //# sourceMappingURL=mcpRegistry.js.map