aistorehub 0.0.0-stage → 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 CHANGED
@@ -1,3 +1,51 @@
1
- # Temporary Holding Version
1
+ # aistorehub (Node.js CLI)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Zero-dependency Node.js / TypeScript CLI for [AIStoreHub](https://www.aistorehub.in) with full command parity to the Python CLI (`pip install aistorehub`). Search, inspect, pull, download ZIPs, lint MCP configs, security-scan, publish, and 1-click install AI agents, skills, prompts, and MCP servers directly via `npx`.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ # Zero-install (recommended)
9
+ npx aistorehub --help
10
+
11
+ # Or install globally
12
+ npm install -g aistorehub
13
+ ```
14
+
15
+ ## Full Command Reference
16
+
17
+ ```bash
18
+ # Authentication
19
+ aistorehub login --token-stdin
20
+ aistorehub whoami
21
+ aistorehub logout
22
+
23
+ # Discovery & Inspection
24
+ aistorehub search "aws agent" --limit 10
25
+ aistorehub info community/context-mode
26
+
27
+ # Pull / Clone / Download ZIP
28
+ aistorehub pull community/context-mode
29
+ aistorehub clone community/context-mode --dest ./my-dir
30
+ aistorehub download community/context-mode --zip
31
+
32
+ # 1-Click MCP Auto-Configuration & Diagnostics
33
+ aistorehub mcp install community/context-mode --client cursor
34
+ aistorehub mcp install community/context-mode --client all
35
+ aistorehub mcp remove community/context-mode --client cursor
36
+ aistorehub list
37
+ aistorehub doctor --fix
38
+ aistorehub lint --client all --fix
39
+
40
+ # Local Inspection, Security Gate & Publishing
41
+ aistorehub inspect ./my-agent
42
+ aistorehub scan ./my-agent
43
+ aistorehub publish ./my-agent --type agent
44
+
45
+ # Telemetry
46
+ aistorehub telemetry status
47
+ ```
48
+
49
+ ## Requirements
50
+
51
+ - Node.js 18 or higher (zero runtime npm dependencies)
package/dist/api.js ADDED
@@ -0,0 +1,166 @@
1
+ import { loadConfig } from "./config.js";
2
+ export function getApiBase() {
3
+ return loadConfig().api_url;
4
+ }
5
+ async function fetchWithRetry(url, init = {}, timeoutMs = 35000, retries = 1) {
6
+ let lastError;
7
+ for (let attempt = 0; attempt <= retries; attempt += 1) {
8
+ try {
9
+ const res = await fetch(url, {
10
+ ...init,
11
+ signal: init.signal || AbortSignal.timeout(timeoutMs),
12
+ });
13
+ if ((res.status === 502 || res.status === 503 || res.status === 504) && attempt < retries) {
14
+ await new Promise((r) => setTimeout(r, 2000));
15
+ continue;
16
+ }
17
+ return res;
18
+ }
19
+ catch (err) {
20
+ lastError = err;
21
+ if (attempt < retries) {
22
+ await new Promise((r) => setTimeout(r, 1500));
23
+ continue;
24
+ }
25
+ }
26
+ }
27
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
28
+ }
29
+ function authHeaders(explicitToken, hasBody = false) {
30
+ const token = explicitToken || loadConfig().token;
31
+ const h = {
32
+ Accept: "application/json",
33
+ "User-Agent": "aistorehub-cli-js/0.2.0",
34
+ };
35
+ if (hasBody) {
36
+ h["Content-Type"] = "application/json";
37
+ }
38
+ if (token) {
39
+ h["Authorization"] = `Bearer ${token}`;
40
+ }
41
+ return h;
42
+ }
43
+ export function parseSystemRef(raw) {
44
+ const cleaned = raw.trim().replace(/^@/, "").replace(/^\/+|\/+$/g, "");
45
+ const parts = cleaned.split("/").filter(Boolean);
46
+ if (parts.length >= 3) {
47
+ return { owner: parts[0], repo: parts[1], slug: parts[2] };
48
+ }
49
+ if (parts.length === 2) {
50
+ return { owner: parts[0], repo: "catalog", slug: parts[1] };
51
+ }
52
+ return { owner: "community", repo: "catalog", slug: parts[0] || cleaned };
53
+ }
54
+ export async function getWhoAmI(explicitToken) {
55
+ const res = await fetchWithRetry(`${getApiBase()}/users/me`, {
56
+ headers: authHeaders(explicitToken),
57
+ });
58
+ if (!res.ok) {
59
+ throw new Error(`Authentication failed (HTTP ${res.status}). Run 'aistorehub login' to sign in.`);
60
+ }
61
+ return (await res.json());
62
+ }
63
+ export async function searchSystems(query, options = {}) {
64
+ const params = new URLSearchParams();
65
+ if (query)
66
+ params.set("q", query);
67
+ if (options.type)
68
+ params.set("type", options.type);
69
+ if (options.sort)
70
+ params.set("sort", options.sort);
71
+ params.set("page", "1");
72
+ params.set("page_size", String(Math.min(Math.max(options.limit || 10, 1), 30)));
73
+ const res = await fetchWithRetry(`${getApiBase()}/search?${params.toString()}`, {
74
+ headers: authHeaders(),
75
+ });
76
+ if (!res.ok) {
77
+ throw new Error(`Search failed (HTTP ${res.status}): ${await res.text()}`);
78
+ }
79
+ const data = (await res.json());
80
+ return {
81
+ items: Array.isArray(data.items) ? data.items : [],
82
+ total: Number(data.total || 0),
83
+ };
84
+ }
85
+ export async function getSystemDetail(rawRef) {
86
+ const { owner, repo, slug } = parseSystemRef(rawRef);
87
+ const directUrl = `${getApiBase()}/systems/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/${encodeURIComponent(slug)}`;
88
+ const res = await fetchWithRetry(directUrl, { headers: authHeaders() });
89
+ if (res.ok) {
90
+ return (await res.json());
91
+ }
92
+ const found = await searchSystems(slug, { limit: 10 });
93
+ const exact = found.items.find((i) => i.slug.toLowerCase() === slug.toLowerCase()) || found.items[0];
94
+ if (!exact) {
95
+ throw new Error(`System '${rawRef}' not found on AIStoreHub.`);
96
+ }
97
+ const resolvedOwner = exact.owner_username || owner;
98
+ const resolvedRepo = exact.repository_slug || repo;
99
+ const retryRes = await fetchWithRetry(`${getApiBase()}/systems/${encodeURIComponent(resolvedOwner)}/${encodeURIComponent(resolvedRepo)}/${encodeURIComponent(exact.slug)}`, { headers: authHeaders() });
100
+ if (!retryRes.ok) {
101
+ throw new Error(`Failed to fetch system detail for ${resolvedOwner}/${resolvedRepo}/${exact.slug} (HTTP ${retryRes.status})`);
102
+ }
103
+ return (await retryRes.json());
104
+ }
105
+ export async function getSecurityReport(owner, repo, slug) {
106
+ try {
107
+ const res = await fetchWithRetry(`${getApiBase()}/systems/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/${encodeURIComponent(slug)}/security-report`, { headers: authHeaders() }, 10000, 0);
108
+ if (!res.ok)
109
+ return null;
110
+ return (await res.json());
111
+ }
112
+ catch {
113
+ return null;
114
+ }
115
+ }
116
+ export async function getRepoTree(owner, repo, slug, forceSync = false) {
117
+ const url = `${getApiBase()}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/tree?subpath=${encodeURIComponent(`packages/${slug}`)}&system_slug=${encodeURIComponent(slug)}${forceSync ? "&force_sync=true" : ""}`;
118
+ const res = await fetchWithRetry(url, { headers: authHeaders() }, 25000, 1);
119
+ if (!res.ok)
120
+ return [];
121
+ const data = await res.json();
122
+ return Array.isArray(data) ? data : [];
123
+ }
124
+ export async function getRepoBlob(owner, repo, filePath) {
125
+ const url = `${getApiBase()}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/blob?path=${encodeURIComponent(filePath)}`;
126
+ const res = await fetchWithRetry(url, { headers: authHeaders() }, 15000, 1);
127
+ if (!res.ok)
128
+ return null;
129
+ const data = (await res.json());
130
+ return typeof data.content === "string" ? data.content : null;
131
+ }
132
+ export async function getPackageZipBuffer(systemId) {
133
+ const tokenRes = await fetchWithRetry(`${getApiBase()}/marketplace/artifacts/${encodeURIComponent(systemId)}/download-token`, { method: "POST", headers: authHeaders(undefined, true) }, 35000, 1);
134
+ let downloadUrl = `${getApiBase()}/marketplace/artifacts/${encodeURIComponent(systemId)}/download`;
135
+ if (tokenRes.ok) {
136
+ const data = (await tokenRes.json());
137
+ if (data.download_url) {
138
+ downloadUrl = data.download_url;
139
+ }
140
+ }
141
+ const zipRes = await fetchWithRetry(downloadUrl, { headers: authHeaders() }, 45000, 1);
142
+ if (!zipRes.ok) {
143
+ throw new Error(`Failed to download package ZIP (HTTP ${zipRes.status})`);
144
+ }
145
+ const ab = await zipRes.arrayBuffer();
146
+ return Buffer.from(ab);
147
+ }
148
+ export async function createSystemPublish(payload) {
149
+ const res = await fetchWithRetry(`${getApiBase()}/systems`, {
150
+ method: "POST",
151
+ headers: authHeaders(undefined, true),
152
+ body: JSON.stringify(payload),
153
+ }, 35000, 0);
154
+ if (!res.ok) {
155
+ const txt = await res.text();
156
+ let msg = txt;
157
+ try {
158
+ const parsed = JSON.parse(txt);
159
+ if (parsed.detail)
160
+ msg = parsed.detail;
161
+ }
162
+ catch { }
163
+ throw new Error(`Publish failed (HTTP ${res.status}): ${msg}`);
164
+ }
165
+ return (await res.json());
166
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,354 @@
1
+ #!/usr/bin/env node
2
+ import readline from "node:readline";
3
+ import { getSecurityReport, getSystemDetail, getWhoAmI, searchSystems } from "./api.js";
4
+ import { clearToken, getConfigPath, loadConfig, saveConfig } from "./config.js";
5
+ import { inspectLocalDirectory, publishLocalDirectory } from "./inspect.js";
6
+ import { installMcpClientConfig, lintMcpConfigs, listInstalledMcpServers, removeMcpClientConfig, } from "./mcp.js";
7
+ import { pullSystemPackage } from "./pull.js";
8
+ import { scanLocalDirectory } from "./scanner.js";
9
+ const VERSION = "0.2.0";
10
+ function printHelp() {
11
+ console.log(`AIStoreHub CLI (Node.js) v${VERSION}
12
+
13
+ Usage:
14
+ aistorehub login [--token <pat> | --token-stdin] [--url <api_url>]
15
+ aistorehub logout
16
+ aistorehub whoami
17
+ aistorehub search <query> [--type <type>] [--sort <sort>] [--limit <n>]
18
+ aistorehub info <owner/slug>
19
+ aistorehub pull|clone|download <owner/slug> [--dest <path>] [--zip]
20
+ aistorehub mcp [install|add|remove|list] <owner/slug> [--client cursor|claude|windsurf|zed|all] [--remove]
21
+ aistorehub list [--client all|cursor|claude|windsurf|zed]
22
+ aistorehub lint|validate|doctor [--client all|cursor|claude|windsurf|zed] [--file <path>] [--fix]
23
+ aistorehub inspect [directory]
24
+ aistorehub scan [directory]
25
+ aistorehub publish [directory] [--name <name>] [--slug <slug>] [--type <type>] [--private]
26
+ aistorehub telemetry [status|enable|disable]
27
+ aistorehub --version | --help
28
+
29
+ Examples:
30
+ npx aistorehub search "aws agent"
31
+ npx aistorehub info community/context-mode
32
+ npx aistorehub pull community/context-mode
33
+ npx aistorehub download community/context-mode --zip
34
+ npx aistorehub mcp install community/context-mode --client cursor
35
+ npx aistorehub doctor --fix
36
+ npx aistorehub scan ./my-agent
37
+ `);
38
+ }
39
+ function getFlag(args, ...flags) {
40
+ for (const flag of flags) {
41
+ const idx = args.indexOf(flag);
42
+ if (idx !== -1 && idx + 1 < args.length) {
43
+ return args[idx + 1];
44
+ }
45
+ }
46
+ return undefined;
47
+ }
48
+ function hasFlag(args, ...flags) {
49
+ return flags.some((f) => args.includes(f));
50
+ }
51
+ async function readStdinText() {
52
+ const chunks = [];
53
+ for await (const chunk of process.stdin) {
54
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
55
+ }
56
+ return Buffer.concat(chunks).toString("utf-8").trim();
57
+ }
58
+ async function promptToken() {
59
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
60
+ return new Promise((resolve) => {
61
+ rl.question("Enter your AIStoreHub Personal Access Token (from aistorehub.in/settings): ", (ans) => {
62
+ rl.close();
63
+ resolve(ans.trim());
64
+ });
65
+ });
66
+ }
67
+ async function main() {
68
+ const args = process.argv.slice(2);
69
+ if (args.length === 0 || args.includes("-h") || args.includes("--help")) {
70
+ printHelp();
71
+ return;
72
+ }
73
+ if (args.includes("-v") || args.includes("--version")) {
74
+ console.log(`aistorehub ${VERSION}`);
75
+ return;
76
+ }
77
+ const cmd = args[0].toLowerCase();
78
+ if (cmd === "login") {
79
+ const cfg = loadConfig();
80
+ const customUrl = getFlag(args, "--url");
81
+ if (customUrl) {
82
+ cfg.api_url = customUrl.replace(/\/$/, "");
83
+ }
84
+ let token = getFlag(args, "--token") || "";
85
+ if (!token && hasFlag(args, "--token-stdin")) {
86
+ token = await readStdinText();
87
+ }
88
+ if (!token) {
89
+ token = await promptToken();
90
+ }
91
+ if (!token) {
92
+ console.error("Error: No token provided.");
93
+ process.exit(1);
94
+ }
95
+ saveConfig({ ...cfg, token });
96
+ try {
97
+ const user = await getWhoAmI(token);
98
+ console.log(`Logged in as @${user.username} (${user.email || "verified"})`);
99
+ console.log(`Credentials saved to ${getConfigPath()}`);
100
+ }
101
+ catch (err) {
102
+ clearToken();
103
+ throw err;
104
+ }
105
+ return;
106
+ }
107
+ if (cmd === "logout") {
108
+ clearToken();
109
+ console.log("Logged out. Local credentials cleared.");
110
+ return;
111
+ }
112
+ if (cmd === "whoami") {
113
+ const user = await getWhoAmI();
114
+ console.log(`Authenticated as @${user.username}`);
115
+ if (user.display_name)
116
+ console.log(` Name: ${user.display_name}`);
117
+ if (user.email)
118
+ console.log(` Email: ${user.email}`);
119
+ console.log(` Role: ${user.is_admin ? "Admin" : "Creator"}`);
120
+ console.log(` Verified: ${user.is_verified ? "Yes" : "No"}`);
121
+ return;
122
+ }
123
+ if (cmd === "search") {
124
+ const typeFlag = getFlag(args, "--type");
125
+ const limitFlag = getFlag(args, "--limit");
126
+ const sortFlag = getFlag(args, "--sort");
127
+ const queryParts = [];
128
+ for (let i = 1; i < args.length; i += 1) {
129
+ if (args[i] === "--type" || args[i] === "--limit" || args[i] === "--sort") {
130
+ i += 1;
131
+ continue;
132
+ }
133
+ queryParts.push(args[i]);
134
+ }
135
+ const query = queryParts.join(" ").trim();
136
+ const { items, total } = await searchSystems(query, {
137
+ type: typeFlag,
138
+ sort: sortFlag,
139
+ limit: limitFlag ? Number(limitFlag) : 10,
140
+ });
141
+ console.log(`Found ${total} matching AI systems (showing ${items.length}):\n`);
142
+ for (const item of items) {
143
+ const owner = item.owner_username || "community";
144
+ const sec = item.security_scan_status || "not_run";
145
+ console.log(` @${owner}/${item.slug} [${item.type}] (security: ${sec})`);
146
+ if (item.description) {
147
+ console.log(` ${item.description.slice(0, 110)}${item.description.length > 110 ? "..." : ""}`);
148
+ }
149
+ }
150
+ return;
151
+ }
152
+ if (cmd === "info") {
153
+ const ref = args[1];
154
+ if (!ref) {
155
+ console.error("Error: Missing system reference. Example: aistorehub info community/context-mode");
156
+ process.exit(1);
157
+ }
158
+ const detail = await getSystemDetail(ref);
159
+ const owner = detail.repository?.owner?.username || detail.owner_username || "community";
160
+ const repo = detail.repository?.slug || detail.repository_slug || "catalog";
161
+ const ver = detail.current_version?.version || detail.latest_version || "1.0.0";
162
+ const secReport = await getSecurityReport(owner, repo, detail.slug);
163
+ const sec = secReport?.status || detail.current_version?.security_scan_status || detail.security_scan_status || "not_run";
164
+ console.log(`${detail.name} (@${owner}/${repo}/${detail.slug})`);
165
+ console.log(` Type: ${detail.type}`);
166
+ console.log(` Version: v${ver}`);
167
+ console.log(` Security: ${sec}${secReport?.score !== undefined && secReport?.score !== null ? ` (${secReport.score}/100, ${secReport.scanned_files || 0} files)` : ""}`);
168
+ if (detail.license_name)
169
+ console.log(` License: ${detail.license_name}`);
170
+ if (detail.github_repo_url)
171
+ console.log(` GitHub: ${detail.github_repo_url}`);
172
+ console.log(` URL: https://www.aistorehub.in/${owner}/${repo}/${detail.slug}`);
173
+ if (detail.description)
174
+ console.log(`\n${detail.description}`);
175
+ return;
176
+ }
177
+ if (cmd === "pull" || cmd === "clone" || cmd === "download") {
178
+ const ref = args[1];
179
+ if (!ref || ref.startsWith("-")) {
180
+ console.error(`Error: Missing system reference. Example: aistorehub ${cmd} community/context-mode`);
181
+ process.exit(1);
182
+ }
183
+ const outDir = getFlag(args, "--dest", "--dir");
184
+ const asZip = hasFlag(args, "--zip");
185
+ console.log(`${asZip ? "Downloading ZIP" : "Pulling"} ${ref} from AIStoreHub...`);
186
+ const result = await pullSystemPackage(ref, { outDir, asZip });
187
+ if (result.zipPath) {
188
+ console.log(`Downloaded '${result.name}' archive to ${result.zipPath}`);
189
+ }
190
+ else {
191
+ console.log(`Pulled '${result.name}' (${result.filesWritten} files) into ${result.targetDir}`);
192
+ }
193
+ return;
194
+ }
195
+ if (cmd === "list") {
196
+ const client = (getFlag(args, "--client", "-c") || "all");
197
+ const rows = listInstalledMcpServers(client);
198
+ for (const row of rows) {
199
+ console.log(`${row.client} (${row.configPath})`);
200
+ if (!row.exists) {
201
+ console.log(" Not configured yet");
202
+ }
203
+ else if (row.servers.length === 0) {
204
+ console.log(" No MCP servers installed");
205
+ }
206
+ else {
207
+ for (const s of row.servers) {
208
+ console.log(` - ${s}`);
209
+ }
210
+ }
211
+ }
212
+ return;
213
+ }
214
+ if (cmd === "mcp") {
215
+ const client = (getFlag(args, "--client", "-c") || "all");
216
+ const removeFlag = hasFlag(args, "--remove", "-r");
217
+ const positional = args.slice(1).filter((a, idx, arr) => {
218
+ if (a.startsWith("-"))
219
+ return false;
220
+ if (idx > 0 && (arr[idx - 1] === "--client" || arr[idx - 1] === "-c"))
221
+ return false;
222
+ return true;
223
+ });
224
+ if (positional.length === 0 || positional[0].toLowerCase() === "list") {
225
+ const rows = listInstalledMcpServers(client);
226
+ for (const row of rows) {
227
+ console.log(`${row.client} (${row.configPath})`);
228
+ if (!row.exists || row.servers.length === 0) {
229
+ console.log(" No MCP servers configured");
230
+ }
231
+ else {
232
+ for (const s of row.servers)
233
+ console.log(` - ${s}`);
234
+ }
235
+ }
236
+ return;
237
+ }
238
+ const first = positional[0].toLowerCase();
239
+ const isRemove = removeFlag || first === "remove" || first === "rm" || first === "uninstall";
240
+ const isInstallVerb = first === "install" || first === "add";
241
+ const ref = isRemove || isInstallVerb ? positional[1] : positional[0];
242
+ if (!ref) {
243
+ console.error("Error: Usage: aistorehub mcp [install|remove|list] <owner/slug> [--client cursor|claude|windsurf|zed|all]");
244
+ process.exit(1);
245
+ }
246
+ if (isRemove) {
247
+ const slug = ref.split("/").pop() || ref;
248
+ const results = removeMcpClientConfig(slug, client);
249
+ if (results.length === 0) {
250
+ console.log(`No matching MCP server '${slug}' found in ${client} configs.`);
251
+ return;
252
+ }
253
+ for (const r of results) {
254
+ console.log(`${r.success ? "[OK]" : "[FAIL]"} ${r.client}: ${r.message} (${r.configPath})`);
255
+ }
256
+ return;
257
+ }
258
+ const detail = await getSystemDetail(ref);
259
+ const results = installMcpClientConfig(detail.slug, client);
260
+ if (results.length === 0) {
261
+ console.error(`Error: Unknown client '${client}'. Use cursor, claude, windsurf, zed, or all.`);
262
+ process.exit(1);
263
+ }
264
+ for (const r of results) {
265
+ console.log(`${r.success ? "[OK]" : "[FAIL]"} ${r.client}: ${r.configPath} — ${r.message}`);
266
+ }
267
+ return;
268
+ }
269
+ if (cmd === "lint" || cmd === "validate" || cmd === "doctor") {
270
+ const client = (getFlag(args, "--client", "-c") || "all");
271
+ const customFile = getFlag(args, "--file", "-f");
272
+ const fix = hasFlag(args, "--fix");
273
+ const { checked, issues } = lintMcpConfigs({ client, customFile, fix });
274
+ console.log(`AIStoreHub MCP Diagnostics (${checked} config file(s) checked)`);
275
+ if (issues.length === 0) {
276
+ console.log(" All detected AI editor MCP configurations are valid.");
277
+ return;
278
+ }
279
+ for (const issue of issues) {
280
+ console.log(` [${issue.severity.toUpperCase()}] ${issue.client}: ${issue.message}`);
281
+ }
282
+ if (issues.some((i) => i.severity === "error")) {
283
+ process.exit(1);
284
+ }
285
+ return;
286
+ }
287
+ if (cmd === "inspect") {
288
+ const targetDir = args[1] || ".";
289
+ const info = inspectLocalDirectory(targetDir);
290
+ console.log(`AIStoreHub Package Inspector (${info.directory})`);
291
+ console.log(` Name: ${info.name}`);
292
+ console.log(` Slug: ${info.slug}`);
293
+ console.log(` Type: ${info.detectedType}`);
294
+ console.log(` Files: ${info.files.length} eligible source files`);
295
+ console.log(` README: ${info.readme ? `Found (${info.readme.length} chars)` : "Not found"}`);
296
+ console.log(` Instructions: ${info.instructions ? `Found (${info.instructions.length} chars)` : "Not found"}`);
297
+ return;
298
+ }
299
+ if (cmd === "scan") {
300
+ const targetDir = args[1] || ".";
301
+ const report = scanLocalDirectory(targetDir);
302
+ console.log(`AIStoreHub Security Scan (${report.scannedFiles} files scanned)`);
303
+ console.log(` Status: ${report.status.toUpperCase()}`);
304
+ console.log(` Score: ${report.score}/100`);
305
+ if (report.findings.length > 0) {
306
+ console.log("\nFindings:");
307
+ for (const f of report.findings) {
308
+ console.log(` [${f.severity.toUpperCase()}] ${f.ruleId} ${f.title} (${f.file}:${f.line}) -> ${f.snippet}`);
309
+ }
310
+ }
311
+ else {
312
+ console.log(" No hardcoded secrets, exfiltration patterns, or prompt injection directives detected.");
313
+ }
314
+ if (report.status === "blocked") {
315
+ process.exit(1);
316
+ }
317
+ return;
318
+ }
319
+ if (cmd === "publish") {
320
+ const targetDir = args[1] && !args[1].startsWith("-") ? args[1] : ".";
321
+ const name = getFlag(args, "--name");
322
+ const slug = getFlag(args, "--slug");
323
+ const type = getFlag(args, "--type");
324
+ const visibility = hasFlag(args, "--private") ? "private" : "public";
325
+ console.log(`Scanning and publishing ${targetDir} to AIStoreHub...`);
326
+ const created = await publishLocalDirectory(targetDir, { name, slug, type, visibility });
327
+ const owner = created.repository?.owner?.username || created.owner_username || "me";
328
+ const repo = created.repository?.slug || created.repository_slug || "systems";
329
+ console.log(`Published '${created.name}' -> https://www.aistorehub.in/${owner}/${repo}/${created.slug}`);
330
+ return;
331
+ }
332
+ if (cmd === "telemetry") {
333
+ const action = (args[1] || "status").toLowerCase();
334
+ const cfg = loadConfig();
335
+ if (action === "enable") {
336
+ saveConfig({ ...cfg, telemetry_enabled: true });
337
+ console.log("Anonymous CLI pull telemetry enabled.");
338
+ }
339
+ else if (action === "disable") {
340
+ saveConfig({ ...cfg, telemetry_enabled: false });
341
+ console.log("Anonymous CLI pull telemetry disabled.");
342
+ }
343
+ else {
344
+ console.log(`Anonymous CLI pull telemetry is currently: ${cfg.telemetry_enabled ? "ENABLED" : "DISABLED"}`);
345
+ }
346
+ return;
347
+ }
348
+ console.error(`Unknown command: '${cmd}'. Run 'aistorehub --help' for usage.`);
349
+ process.exit(1);
350
+ }
351
+ main().catch((err) => {
352
+ console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
353
+ process.exit(1);
354
+ });
package/dist/config.js ADDED
@@ -0,0 +1,62 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ export const DEFAULT_PRODUCTION_API = "https://aistorehub-be-cgsu.onrender.com/api/v1";
5
+ const CONFIG_DIR = path.join(os.homedir(), ".aistorehub");
6
+ const CONFIG_FILE = path.join(CONFIG_DIR, "config.json");
7
+ function isDefunctUrl(url) {
8
+ const lower = url.toLowerCase();
9
+ return (lower.includes("aistorehub-be.onrender.com") ||
10
+ lower.includes("aistorehub-be-3weo") ||
11
+ lower.includes("aistorehub-be-5dwr") ||
12
+ lower.includes("aistorehub-be-z2m1"));
13
+ }
14
+ export function loadConfig() {
15
+ const envUrl = process.env.AISTOREHUB_API_URL?.replace(/\/$/, "");
16
+ const defaults = {
17
+ api_url: envUrl || DEFAULT_PRODUCTION_API,
18
+ telemetry_enabled: true,
19
+ };
20
+ if (!fs.existsSync(CONFIG_FILE)) {
21
+ return defaults;
22
+ }
23
+ try {
24
+ const raw = fs.readFileSync(CONFIG_FILE, "utf-8");
25
+ const parsed = JSON.parse(raw);
26
+ let apiUrl = envUrl || parsed.api_url || DEFAULT_PRODUCTION_API;
27
+ let mutated = false;
28
+ if (!envUrl && isDefunctUrl(apiUrl)) {
29
+ apiUrl = DEFAULT_PRODUCTION_API;
30
+ mutated = true;
31
+ }
32
+ const cfg = {
33
+ api_url: apiUrl.replace(/\/$/, ""),
34
+ token: process.env.AISTOREHUB_TOKEN || parsed.token,
35
+ telemetry_enabled: parsed.telemetry_enabled !== false,
36
+ };
37
+ if (mutated) {
38
+ saveConfig(cfg);
39
+ }
40
+ return cfg;
41
+ }
42
+ catch {
43
+ return defaults;
44
+ }
45
+ }
46
+ export function saveConfig(cfg) {
47
+ fs.mkdirSync(CONFIG_DIR, { recursive: true });
48
+ const payload = JSON.stringify({
49
+ api_url: cfg.api_url,
50
+ ...(cfg.token ? { token: cfg.token } : {}),
51
+ telemetry_enabled: cfg.telemetry_enabled,
52
+ }, null, 2);
53
+ fs.writeFileSync(CONFIG_FILE, payload + "\n", { encoding: "utf-8", mode: 0o600 });
54
+ }
55
+ export function clearToken() {
56
+ const cfg = loadConfig();
57
+ delete cfg.token;
58
+ saveConfig(cfg);
59
+ }
60
+ export function getConfigPath() {
61
+ return CONFIG_FILE;
62
+ }
@@ -0,0 +1,144 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { createSystemPublish } from "./api.js";
4
+ import { scanLocalDirectory } from "./scanner.js";
5
+ const SKIP_DIRS = new Set([".git", "node_modules", "__pycache__", ".venv", "venv", "dist", "build", ".next"]);
6
+ const SECRET_FILES = new Set([".env", ".env.local", ".env.production", "credentials.json"]);
7
+ const TEXT_EXTS = new Set([
8
+ ".md", ".txt", ".prompt", ".json", ".yaml", ".yml", ".toml",
9
+ ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".py", ".sh", ".sql",
10
+ ]);
11
+ function slugify(name) {
12
+ return (name
13
+ .toLowerCase()
14
+ .replace(/[^a-z0-9]+/g, "-")
15
+ .replace(/^-+|-+$/g, "") || "ai-system");
16
+ }
17
+ export function inspectLocalDirectory(dirInput) {
18
+ const absDir = path.resolve(dirInput || ".");
19
+ if (!fs.existsSync(absDir) || !fs.statSync(absDir).isDirectory()) {
20
+ throw new Error(`Directory not found: ${absDir}`);
21
+ }
22
+ const baseName = path.basename(absDir);
23
+ let name = baseName
24
+ .split(/[-_]+/)
25
+ .filter(Boolean)
26
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
27
+ .join(" ");
28
+ let slug = slugify(baseName);
29
+ let description = `AI system packaged from ${baseName}`;
30
+ let readme = "";
31
+ let instructions = "";
32
+ let detectedType = "agent";
33
+ const files = [];
34
+ const artifacts = [];
35
+ const walk = (dir) => {
36
+ if (files.length >= 80)
37
+ return;
38
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
39
+ if (files.length >= 80)
40
+ break;
41
+ const full = path.join(dir, entry.name);
42
+ if (entry.isDirectory()) {
43
+ if (!SKIP_DIRS.has(entry.name))
44
+ walk(full);
45
+ continue;
46
+ }
47
+ const lower = entry.name.toLowerCase();
48
+ if (SECRET_FILES.has(lower) || lower.endsWith(".pem") || lower.endsWith(".key")) {
49
+ continue;
50
+ }
51
+ const rel = path.relative(absDir, full).replace(/\\/g, "/");
52
+ files.push(rel);
53
+ const ext = path.extname(entry.name).toLowerCase();
54
+ const stat = fs.statSync(full);
55
+ if (stat.size === 0 || stat.size > 150 * 1024 || !TEXT_EXTS.has(ext))
56
+ continue;
57
+ const content = fs.readFileSync(full, "utf-8");
58
+ if (lower === "readme.md" && !readme) {
59
+ readme = content;
60
+ }
61
+ else if ((lower === "skill.md" || lower === "instructions.md" || lower === "instructions.txt" || lower === "prompt.md") && !instructions) {
62
+ instructions = content;
63
+ }
64
+ else if (lower === "aistorehub.json" || lower === "manifest.json") {
65
+ try {
66
+ const parsed = JSON.parse(content);
67
+ if (typeof parsed.name === "string" && parsed.name.trim())
68
+ name = parsed.name.trim();
69
+ if (typeof parsed.slug === "string" && parsed.slug.trim())
70
+ slug = slugify(parsed.slug);
71
+ if (typeof parsed.description === "string" && parsed.description.trim())
72
+ description = parsed.description.trim();
73
+ if (typeof parsed.type === "string") {
74
+ const t = parsed.type.toLowerCase();
75
+ if (t === "mcp_server" || t === "agent" || t === "skill" || t === "workflow" || t === "prompt") {
76
+ detectedType = t;
77
+ }
78
+ }
79
+ }
80
+ catch { }
81
+ }
82
+ if (artifacts.length < 25) {
83
+ const kind = lower.includes("skill") ? "skill" :
84
+ lower.includes("prompt") || lower.includes("instruction") ? "prompt" :
85
+ lower.includes("workflow") ? "workflow" :
86
+ "code";
87
+ artifacts.push({ name: entry.name, path: rel, kind, content_text: content });
88
+ }
89
+ }
90
+ };
91
+ walk(absDir);
92
+ // Heuristic archetype detection if not explicitly overridden in manifest
93
+ const joinedLower = files.join(" ").toLowerCase();
94
+ if (joinedLower.includes("mcp") || joinedLower.includes("modelcontextprotocol")) {
95
+ detectedType = "mcp_server";
96
+ }
97
+ else if (joinedLower.includes("skill.md")) {
98
+ detectedType = "skill";
99
+ }
100
+ else if (joinedLower.includes("workflow.json") || joinedLower.includes("langgraph")) {
101
+ detectedType = "workflow";
102
+ }
103
+ else if (files.every((f) => f.endsWith(".md") || f.endsWith(".txt") || f.endsWith(".prompt"))) {
104
+ detectedType = "prompt";
105
+ }
106
+ return {
107
+ directory: absDir,
108
+ name,
109
+ slug,
110
+ detectedType,
111
+ description,
112
+ files,
113
+ readme,
114
+ instructions,
115
+ artifacts,
116
+ };
117
+ }
118
+ export async function publishLocalDirectory(dirInput, options = {}) {
119
+ const scan = scanLocalDirectory(dirInput);
120
+ if (scan.status === "blocked") {
121
+ const first = scan.findings[0];
122
+ throw new Error(`Security gate blocked publish: ${first?.title || "Critical secret leak"} in ${first?.file}:${first?.line}. Remove secrets and retry.`);
123
+ }
124
+ const info = inspectLocalDirectory(dirInput);
125
+ const payload = {
126
+ name: options.name || info.name,
127
+ slug: options.slug ? slugify(options.slug) : info.slug,
128
+ description: info.description,
129
+ type: options.type || info.detectedType,
130
+ visibility: options.visibility || "public",
131
+ version: {
132
+ version: "1.0.0",
133
+ readme: info.readme || `# ${options.name || info.name}\n\n${info.description}`,
134
+ instructions: info.instructions || undefined,
135
+ artifacts: info.artifacts.map((a) => ({
136
+ name: a.name,
137
+ path: a.path,
138
+ kind: a.kind,
139
+ content_text: a.content_text,
140
+ })),
141
+ },
142
+ };
143
+ return await createSystemPublish(payload);
144
+ }
package/dist/mcp.js ADDED
@@ -0,0 +1,253 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ function getClaudeConfigPath() {
5
+ const home = os.homedir();
6
+ if (process.platform === "win32") {
7
+ const appData = process.env.APPDATA || path.join(home, "AppData", "Roaming");
8
+ return path.join(appData, "Claude", "claude_desktop_config.json");
9
+ }
10
+ if (process.platform === "darwin") {
11
+ return path.join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json");
12
+ }
13
+ return path.join(home, ".config", "Claude", "claude_desktop_config.json");
14
+ }
15
+ function getCursorConfigPath() {
16
+ return path.join(os.homedir(), ".cursor", "mcp.json");
17
+ }
18
+ function getWindsurfConfigPath() {
19
+ return path.join(os.homedir(), ".codeium", "windsurf", "mcp_config.json");
20
+ }
21
+ function getZedConfigPath() {
22
+ const home = os.homedir();
23
+ if (process.platform === "win32") {
24
+ const appData = process.env.APPDATA || path.join(home, "AppData", "Roaming");
25
+ return path.join(appData, "Zed", "settings.json");
26
+ }
27
+ return path.join(home, ".config", "zed", "settings.json");
28
+ }
29
+ export function getClientTargets(targetClient = "all") {
30
+ const all = [
31
+ { id: "cursor", label: "Cursor", configPath: getCursorConfigPath(), rootKey: "mcpServers" },
32
+ { id: "claude", label: "Claude Desktop", configPath: getClaudeConfigPath(), rootKey: "mcpServers" },
33
+ { id: "windsurf", label: "Windsurf", configPath: getWindsurfConfigPath(), rootKey: "mcpServers" },
34
+ { id: "zed", label: "Zed", configPath: getZedConfigPath(), rootKey: "context_servers" },
35
+ ];
36
+ const norm = targetClient.toLowerCase();
37
+ if (norm === "all")
38
+ return all;
39
+ return all.filter((t) => t.id === norm || (norm === "claude-desktop" && t.id === "claude"));
40
+ }
41
+ function mergeJsonConfig(configPath, rootKey, serverName, serverConfig) {
42
+ fs.mkdirSync(path.dirname(configPath), { recursive: true });
43
+ let data = {};
44
+ if (fs.existsSync(configPath)) {
45
+ try {
46
+ const raw = fs.readFileSync(configPath, "utf-8");
47
+ data = JSON.parse(raw);
48
+ fs.copyFileSync(configPath, `${configPath}.bak`);
49
+ }
50
+ catch {
51
+ data = {};
52
+ }
53
+ }
54
+ if (!data[rootKey] || typeof data[rootKey] !== "object" || Array.isArray(data[rootKey])) {
55
+ data[rootKey] = {};
56
+ }
57
+ data[rootKey][serverName] = serverConfig;
58
+ fs.writeFileSync(configPath, JSON.stringify(data, null, 2) + "\n", "utf-8");
59
+ }
60
+ export function buildMcpServerConfig(slug) {
61
+ const sseUrl = `https://www.aistorehub.in/api/v1/mcp/vault/sse?package=${encodeURIComponent(slug)}`;
62
+ return {
63
+ url: sseUrl,
64
+ transport: "sse",
65
+ };
66
+ }
67
+ export function installMcpClientConfig(serverSlug, targetClient = "cursor") {
68
+ const results = [];
69
+ const serverName = `aistorehub-${serverSlug.replace(/[^a-zA-Z0-9_-]/g, "-")}`;
70
+ const serverConfig = buildMcpServerConfig(serverSlug);
71
+ for (const t of getClientTargets(targetClient)) {
72
+ try {
73
+ mergeJsonConfig(t.configPath, t.rootKey, serverName, serverConfig);
74
+ results.push({
75
+ client: t.label,
76
+ configPath: t.configPath,
77
+ success: true,
78
+ message: `Configured '${serverName}' (backup saved if file existed)`,
79
+ });
80
+ }
81
+ catch (err) {
82
+ results.push({
83
+ client: t.label,
84
+ configPath: t.configPath,
85
+ success: false,
86
+ message: err instanceof Error ? err.message : String(err),
87
+ });
88
+ }
89
+ }
90
+ return results;
91
+ }
92
+ export function removeMcpClientConfig(serverSlug, targetClient = "all") {
93
+ const results = [];
94
+ const cleanSlug = serverSlug.replace(/[^a-zA-Z0-9_-]/g, "-");
95
+ const candidateNames = [cleanSlug, `aistorehub-${cleanSlug}`];
96
+ for (const t of getClientTargets(targetClient)) {
97
+ if (!fs.existsSync(t.configPath))
98
+ continue;
99
+ try {
100
+ const raw = fs.readFileSync(t.configPath, "utf-8");
101
+ const data = JSON.parse(raw);
102
+ const servers = data[t.rootKey];
103
+ if (!servers || typeof servers !== "object")
104
+ continue;
105
+ let removedName = null;
106
+ for (const name of candidateNames) {
107
+ if (name in servers) {
108
+ delete servers[name];
109
+ removedName = name;
110
+ break;
111
+ }
112
+ }
113
+ if (removedName) {
114
+ fs.copyFileSync(t.configPath, `${t.configPath}.bak`);
115
+ fs.writeFileSync(t.configPath, JSON.stringify(data, null, 2) + "\n", "utf-8");
116
+ results.push({
117
+ client: t.label,
118
+ configPath: t.configPath,
119
+ success: true,
120
+ message: `Removed '${removedName}'`,
121
+ });
122
+ }
123
+ }
124
+ catch (err) {
125
+ results.push({
126
+ client: t.label,
127
+ configPath: t.configPath,
128
+ success: false,
129
+ message: err instanceof Error ? err.message : String(err),
130
+ });
131
+ }
132
+ }
133
+ return results;
134
+ }
135
+ export function listInstalledMcpServers(targetClient = "all") {
136
+ const out = [];
137
+ for (const t of getClientTargets(targetClient)) {
138
+ if (!fs.existsSync(t.configPath)) {
139
+ out.push({ client: t.label, configPath: t.configPath, exists: false, servers: [] });
140
+ continue;
141
+ }
142
+ try {
143
+ const data = JSON.parse(fs.readFileSync(t.configPath, "utf-8"));
144
+ const block = data[t.rootKey];
145
+ const servers = block && typeof block === "object" && !Array.isArray(block) ? Object.keys(block) : [];
146
+ out.push({ client: t.label, configPath: t.configPath, exists: true, servers });
147
+ }
148
+ catch {
149
+ out.push({ client: t.label, configPath: t.configPath, exists: true, servers: ["<invalid JSON>"] });
150
+ }
151
+ }
152
+ return out;
153
+ }
154
+ function sanitizeJsonText(raw) {
155
+ // Strip single-line // comments (outside strings) and trailing commas before } or ]
156
+ const withoutComments = raw.replace(/^\s*\/\/.*$/gm, "");
157
+ return withoutComments.replace(/,\s*([}\]])/g, "$1");
158
+ }
159
+ export function lintMcpConfigs(options) {
160
+ const targets = options.customFile
161
+ ? [{ id: "cursor", label: "Custom File", configPath: path.resolve(options.customFile), rootKey: "mcpServers" }]
162
+ : getClientTargets(options.client || "all");
163
+ const issues = [];
164
+ let checked = 0;
165
+ for (const t of targets) {
166
+ if (!fs.existsSync(t.configPath))
167
+ continue;
168
+ checked += 1;
169
+ const raw = fs.readFileSync(t.configPath, "utf-8");
170
+ let parsed = null;
171
+ try {
172
+ parsed = JSON.parse(raw);
173
+ }
174
+ catch (parseErr) {
175
+ if (options.fix) {
176
+ try {
177
+ const cleaned = sanitizeJsonText(raw);
178
+ parsed = JSON.parse(cleaned);
179
+ fs.copyFileSync(t.configPath, `${t.configPath}.bak`);
180
+ fs.writeFileSync(t.configPath, JSON.stringify(parsed, null, 2) + "\n", "utf-8");
181
+ issues.push({
182
+ client: t.label,
183
+ configPath: t.configPath,
184
+ severity: "fixed",
185
+ message: "Auto-repaired invalid JSON syntax (trailing commas/comments removed, .bak saved)",
186
+ });
187
+ }
188
+ catch {
189
+ issues.push({
190
+ client: t.label,
191
+ configPath: t.configPath,
192
+ severity: "error",
193
+ message: `Invalid JSON (auto-fix failed): ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`,
194
+ });
195
+ continue;
196
+ }
197
+ }
198
+ else {
199
+ issues.push({
200
+ client: t.label,
201
+ configPath: t.configPath,
202
+ severity: "error",
203
+ message: `Invalid JSON: ${parseErr instanceof Error ? parseErr.message : String(parseErr)} (run with --fix to repair)`,
204
+ });
205
+ continue;
206
+ }
207
+ }
208
+ const block = parsed?.[t.rootKey];
209
+ if (!block || typeof block !== "object" || Array.isArray(block)) {
210
+ issues.push({
211
+ client: t.label,
212
+ configPath: t.configPath,
213
+ severity: "warning",
214
+ message: `Missing '${t.rootKey}' object in config`,
215
+ });
216
+ continue;
217
+ }
218
+ for (const [name, cfg] of Object.entries(block)) {
219
+ if (!cfg || typeof cfg !== "object") {
220
+ issues.push({
221
+ client: t.label,
222
+ configPath: t.configPath,
223
+ severity: "error",
224
+ message: `Server '${name}' config must be a JSON object`,
225
+ });
226
+ continue;
227
+ }
228
+ const c = cfg;
229
+ if (!c.url && !c.command) {
230
+ issues.push({
231
+ client: t.label,
232
+ configPath: t.configPath,
233
+ severity: "error",
234
+ message: `Server '${name}' is missing both 'url' (SSE) and 'command' (stdio)`,
235
+ });
236
+ }
237
+ if (c.env && typeof c.env === "object") {
238
+ for (const [k, v] of Object.entries(c.env)) {
239
+ const val = String(v || "").toLowerCase();
240
+ if (val.includes("your_") || val.includes("replace_me") || val === "" || val.includes("<your")) {
241
+ issues.push({
242
+ client: t.label,
243
+ configPath: t.configPath,
244
+ severity: "warning",
245
+ message: `Server '${name}' env '${k}' still contains an unconfigured placeholder value`,
246
+ });
247
+ }
248
+ }
249
+ }
250
+ }
251
+ }
252
+ return { checked, issues };
253
+ }
package/dist/pull.js ADDED
@@ -0,0 +1,99 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { getPackageZipBuffer, getRepoBlob, getRepoTree, getSystemDetail } from "./api.js";
4
+ export async function pullSystemPackage(rawRef, options = {}) {
5
+ const detail = await getSystemDetail(rawRef);
6
+ const owner = detail.repository?.owner?.username || detail.owner_username || "community";
7
+ const repo = detail.repository?.slug || detail.repository_slug || "catalog";
8
+ const slug = detail.slug;
9
+ if (options.asZip) {
10
+ const zipFile = path.resolve(options.outDir || `${slug}.zip`);
11
+ fs.mkdirSync(path.dirname(zipFile), { recursive: true });
12
+ const zipBuf = await getPackageZipBuffer(detail.id);
13
+ fs.writeFileSync(zipFile, zipBuf);
14
+ return {
15
+ targetDir: path.dirname(zipFile),
16
+ filesWritten: 1,
17
+ slug,
18
+ name: detail.name,
19
+ zipPath: zipFile,
20
+ };
21
+ }
22
+ const targetDir = path.resolve(options.outDir || slug);
23
+ fs.mkdirSync(targetDir, { recursive: true });
24
+ const tree = await getRepoTree(owner, repo, slug, false);
25
+ const upstreamUrl = detail.github_repo_url ||
26
+ (typeof detail.manifest_data?.original_repo_url === "string"
27
+ ? detail.manifest_data.original_repo_url
28
+ : "");
29
+ let filesWritten = 0;
30
+ if (tree.length > 0) {
31
+ const batchSize = 6;
32
+ for (let i = 0; i < tree.length; i += batchSize) {
33
+ const batch = tree.slice(i, i + batchSize);
34
+ await Promise.all(batch.map(async (entry) => {
35
+ const relPath = entry.path
36
+ .replace(new RegExp(`^packages/${slug}/`, "i"), "")
37
+ .replace(/^\/+/, "");
38
+ if (!relPath || relPath.includes(".."))
39
+ return;
40
+ let content = await getRepoBlob(owner, repo, entry.path);
41
+ if (content === null && upstreamUrl && upstreamUrl.includes("github.com/")) {
42
+ const rawBase = upstreamUrl
43
+ .replace(/\/$/, "")
44
+ .replace(/\.git$/i, "")
45
+ .replace("github.com", "raw.githubusercontent.com");
46
+ for (const branch of ["main", "master"]) {
47
+ try {
48
+ const r = await fetch(`${rawBase}/${branch}/${relPath}`, {
49
+ signal: AbortSignal.timeout(8000),
50
+ });
51
+ if (r.ok) {
52
+ content = await r.text();
53
+ break;
54
+ }
55
+ }
56
+ catch {
57
+ // try next branch
58
+ }
59
+ }
60
+ }
61
+ if (content !== null) {
62
+ const dest = path.join(targetDir, relPath);
63
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
64
+ fs.writeFileSync(dest, content, "utf-8");
65
+ filesWritten += 1;
66
+ }
67
+ }));
68
+ }
69
+ }
70
+ const manifestPath = path.join(targetDir, "aistorehub.json");
71
+ if (!fs.existsSync(manifestPath)) {
72
+ const manifest = {
73
+ name: detail.name,
74
+ slug: detail.slug,
75
+ type: detail.type,
76
+ version: detail.current_version?.version || detail.latest_version || "1.0.0",
77
+ owner,
78
+ repository: repo,
79
+ upstream: upstreamUrl || undefined,
80
+ pulled_via: "aistorehub-cli-js",
81
+ };
82
+ fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + "\n", "utf-8");
83
+ filesWritten += 1;
84
+ }
85
+ if (detail.current_version?.readme && !fs.existsSync(path.join(targetDir, "README.md"))) {
86
+ fs.writeFileSync(path.join(targetDir, "README.md"), detail.current_version.readme, "utf-8");
87
+ filesWritten += 1;
88
+ }
89
+ if (detail.current_version?.instructions && !fs.existsSync(path.join(targetDir, "instructions.txt"))) {
90
+ fs.writeFileSync(path.join(targetDir, "instructions.txt"), detail.current_version.instructions, "utf-8");
91
+ filesWritten += 1;
92
+ }
93
+ return {
94
+ targetDir,
95
+ filesWritten,
96
+ slug,
97
+ name: detail.name,
98
+ };
99
+ }
@@ -0,0 +1,89 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ const RULES = [
4
+ { id: "SEC001", category: "secret_leak", severity: "critical", title: "Hardcoded OpenAI API Key", pattern: /\bsk-(?:proj-)?[A-Za-z0-9_-]{24,}\b/ },
5
+ { id: "SEC002", category: "secret_leak", severity: "critical", title: "Hardcoded Anthropic API Key", pattern: /\bsk-ant-api\d{2}-[A-Za-z0-9_-]{20,}\b/ },
6
+ { id: "SEC003", category: "secret_leak", severity: "critical", title: "Hardcoded GitHub PAT", pattern: /\b(?:ghp_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,})\b/ },
7
+ { id: "SEC004", category: "secret_leak", severity: "critical", title: "Hardcoded AWS Access Key ID", pattern: /\bAKIA[0-9A-Z]{16}\b/ },
8
+ { id: "SEC005", category: "secret_leak", severity: "critical", title: "Hardcoded Google API Key", pattern: /\bAIza[0-9A-Za-z_-]{35}\b/ },
9
+ { id: "SEC006", category: "secret_leak", severity: "critical", title: "Hardcoded Stripe Live Key", pattern: /\bsk_live_[0-9a-zA-Z]{24,}\b/ },
10
+ { id: "SEC007", category: "secret_leak", severity: "critical", title: "Hardcoded Slack Token", pattern: /\bxox[baprs]-[0-9A-Za-z-]{16,}\b/ },
11
+ { id: "SEC008", category: "secret_leak", severity: "critical", title: "Embedded Private Key Block", pattern: /-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----/ },
12
+ { id: "EXF001", category: "exfiltration", severity: "high", title: "Remote Script Piped to Shell", pattern: /\b(?:curl|wget)\b[^\n|]{0,180}\|\s*(?:sudo\s+)?(?:bash|sh|zsh)\b/i },
13
+ { id: "DNG001", category: "dangerous_exec", severity: "high", title: "Destructive Root rm -rf Command", pattern: /\brm\s+-[a-zA-Z]*r[a-zA-Z]*f[a-zA-Z]*\s+(?:\/(?:\s|$|\*)|~(?:\s|$|\/))/ },
14
+ { id: "INJ001", category: "prompt_injection", severity: "medium", title: "Prompt Injection Override Directive", pattern: /(?:ignore\s+all\s+previous\s+instructions|disregard\s+(?:all\s+)?(?:prior|previous|system)\s+(?:instructions|prompts)|exfiltrate\s+(?:all\s+)?(?:api\s+keys|secrets|credentials|tokens))/i },
15
+ ];
16
+ const PLACEHOLDERS = [
17
+ "your_api_key", "your-api-key", "placeholder", "example", "dummy",
18
+ "sk-xxxx", "sk-test", "process.env", "os.environ", "${", "{{",
19
+ ];
20
+ const SKIP_DIRS = new Set([".git", "node_modules", "__pycache__", ".venv", "venv", "dist", "build", ".next"]);
21
+ const SCAN_EXTS = new Set([
22
+ ".py", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs",
23
+ ".json", ".yaml", ".yml", ".toml", ".ini", ".env", ".sh", ".bash", ".md", ".txt", ".prompt",
24
+ ]);
25
+ function redact(val) {
26
+ if (val.length <= 10)
27
+ return "[redacted]";
28
+ return `${val.slice(0, 4)}...${val.slice(-4)}`;
29
+ }
30
+ export function scanLocalDirectory(rootDir) {
31
+ const absRoot = path.resolve(rootDir);
32
+ const findings = [];
33
+ let scannedFiles = 0;
34
+ const walk = (dir) => {
35
+ if (scannedFiles >= 200 || findings.length >= 50)
36
+ return;
37
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
38
+ for (const entry of entries) {
39
+ if (scannedFiles >= 200 || findings.length >= 50)
40
+ break;
41
+ const fullPath = path.join(dir, entry.name);
42
+ if (entry.isDirectory()) {
43
+ if (!SKIP_DIRS.has(entry.name))
44
+ walk(fullPath);
45
+ continue;
46
+ }
47
+ const ext = path.extname(entry.name).toLowerCase();
48
+ if (!SCAN_EXTS.has(ext) && !["dockerfile", "makefile"].includes(entry.name.toLowerCase())) {
49
+ continue;
50
+ }
51
+ const stat = fs.statSync(fullPath);
52
+ if (stat.size === 0 || stat.size > 256 * 1024)
53
+ continue;
54
+ const content = fs.readFileSync(fullPath, "utf-8");
55
+ const rel = path.relative(absRoot, fullPath).replace(/\\/g, "/");
56
+ scannedFiles += 1;
57
+ const lines = content.split(/\r?\n/);
58
+ for (let i = 0; i < lines.length; i += 1) {
59
+ const line = lines[i];
60
+ if (!line.trim() || line.length > 4000)
61
+ continue;
62
+ for (const rule of RULES) {
63
+ const m = rule.pattern.exec(line);
64
+ if (!m)
65
+ continue;
66
+ const lower = `${line} ${m[0]}`.toLowerCase();
67
+ if (rule.category === "secret_leak" && PLACEHOLDERS.some((p) => lower.includes(p))) {
68
+ continue;
69
+ }
70
+ findings.push({
71
+ ruleId: rule.id,
72
+ severity: rule.severity,
73
+ title: rule.title,
74
+ file: rel,
75
+ line: i + 1,
76
+ snippet: rule.category === "secret_leak" ? redact(m[0]) : m[0].slice(0, 80),
77
+ });
78
+ }
79
+ }
80
+ }
81
+ };
82
+ walk(absRoot);
83
+ const crit = findings.filter((f) => f.severity === "critical").length;
84
+ const high = findings.filter((f) => f.severity === "high").length;
85
+ const med = findings.filter((f) => f.severity === "medium").length;
86
+ const score = Math.max(0, 100 - crit * 45 - high * 20 - med * 10);
87
+ const status = crit > 0 ? "blocked" : high > 0 || med > 0 ? "review_required" : "passed";
88
+ return { status, score, scannedFiles, findings };
89
+ }
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "aistorehub",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Official Node.js / TypeScript CLI for AIStoreHub - search, pull, scan, and 1-click install AI systems, skills, and MCP servers into Cursor, Claude Desktop, Windsurf, and Zed.",
5
+ "type": "module",
6
+ "bin": {
7
+ "aistorehub": "dist/cli.js",
8
+ "aihub-js": "dist/cli.js"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "README.md"
13
+ ],
14
+ "engines": {
15
+ "node": ">=18.0.0"
16
+ },
17
+ "scripts": {
18
+ "build": "tsc",
19
+ "dev": "tsc --watch",
20
+ "prepublishOnly": "npm run build"
21
+ },
22
+ "keywords": [
23
+ "aistorehub",
24
+ "mcp",
25
+ "ai-agents",
26
+ "claude",
27
+ "cursor",
28
+ "windsurf",
29
+ "skills",
30
+ "cli"
31
+ ],
32
+ "author": "AIStoreHub",
33
+ "license": "MIT",
34
+ "homepage": "https://www.aistorehub.in",
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/abhinavm945/AISTOREHUB-CLI.git"
38
+ },
39
+ "devDependencies": {
40
+ "@types/node": "^22.0.0",
41
+ "typescript": "^5.7.0"
42
+ }
43
+ }