@myckasp/agent-permit 0.0.0-stage → 0.1.3

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/src/scan.js ADDED
@@ -0,0 +1,312 @@
1
+ import { promises as fs } from "node:fs";
2
+ import path from "node:path";
3
+ import { RULES, RULE_BY_ID, SEVERITY_RANK } from "./rules.js";
4
+ import { summarize } from "./report.js";
5
+ import { VERSION } from "./version.js";
6
+
7
+ const SKIP_DIRS = new Set([
8
+ "node_modules", ".git", "dist", "build", ".next", "coverage",
9
+ "__pycache__", ".venv", "venv", "vendor", "target", "out", ".cache",
10
+ ".idea", ".vscode",
11
+ ]);
12
+
13
+ const TEXT_EXTENSIONS = new Set([
14
+ ".md", ".mdx", ".mdc", ".txt", ".json", ".jsonc", ".yaml", ".yml",
15
+ ".toml", ".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx", ".py",
16
+ ".sh", ".bash", ".zsh", ".ps1", ".bat", ".cmd", ".rb", ".go",
17
+ ".rs", ".php", ".html", ".css", ".example",
18
+ ]);
19
+
20
+ // Never read these: their whole content is a secret, and a review that
21
+ // prints file contents should not become the leak.
22
+ const SECRET_FILE = /(^|[\\/])(\.env(\..*)?|.*\.(pem|key|p12|pfx)|id_rsa|id_ed25519|credentials\.json|\.npmrc)$/i;
23
+
24
+ const MCP_CONFIG = /^(?:\.mcp|mcp|mcp-servers|claude_desktop_config)\.json$/i;
25
+
26
+ const MAX_FILE_BYTES = 512 * 1024;
27
+ const MAX_FILES = 5000;
28
+ const MAX_HITS_PER_RULE_PER_FILE = 3;
29
+ const MAX_LINE_CHARS = 200_000;
30
+
31
+ const LAUNCHER_SUBCOMMANDS = new Set(["run", "exec", "dlx", "x"]);
32
+
33
+ async function walk(dir, files, skipped) {
34
+ let entries;
35
+ try {
36
+ entries = await fs.readdir(dir, { withFileTypes: true });
37
+ } catch {
38
+ skipped.count += 1;
39
+ return;
40
+ }
41
+ entries.sort((a, b) => a.name.localeCompare(b.name));
42
+ for (const entry of entries) {
43
+ if (files.length >= MAX_FILES) return;
44
+ const full = path.join(dir, entry.name);
45
+ if (entry.isSymbolicLink()) {
46
+ skipped.count += 1;
47
+ continue;
48
+ }
49
+ if (entry.isDirectory()) {
50
+ if (SKIP_DIRS.has(entry.name)) {
51
+ skipped.count += 1;
52
+ continue;
53
+ }
54
+ await walk(full, files, skipped);
55
+ continue;
56
+ }
57
+ if (!entry.isFile()) continue;
58
+ if (SECRET_FILE.test(entry.name)) {
59
+ skipped.count += 1;
60
+ continue;
61
+ }
62
+ const ext = path.extname(entry.name).toLowerCase();
63
+ if (!TEXT_EXTENSIONS.has(ext)) {
64
+ skipped.count += 1;
65
+ continue;
66
+ }
67
+ files.push(full);
68
+ }
69
+ }
70
+
71
+ function relative(root, file) {
72
+ return path.relative(root, file).split(path.sep).join("/") || path.basename(file);
73
+ }
74
+
75
+ function snippetOf(line) {
76
+ const clean = line.replace(/\s+/g, " ").trim();
77
+ return clean.length > 140 ? `${clean.slice(0, 137)}...` : clean;
78
+ }
79
+
80
+ function matchSnippet(subject, match) {
81
+ if (subject.length <= 200) return subject;
82
+ const start = Math.max(0, match.index - 60);
83
+ const end = Math.min(subject.length, match.index + match[0].length + 60);
84
+ return `${start > 0 ? "..." : ""}${subject.slice(start, end)}${end < subject.length ? "..." : ""}`;
85
+ }
86
+
87
+ function addFinding(findings, rule, file, line, text) {
88
+ findings.push({
89
+ ruleId: rule.id,
90
+ title: rule.title,
91
+ severity: rule.severity,
92
+ capability: rule.capability,
93
+ file,
94
+ line,
95
+ snippet: snippetOf(text),
96
+ why: rule.why,
97
+ fix: rule.fix,
98
+ });
99
+ }
100
+
101
+ function scanLines(lines, relFile, findings) {
102
+ for (const rule of RULES) {
103
+ if (rule.special) continue;
104
+ if (rule.only && !rule.only(relFile)) continue;
105
+ let hits = 0;
106
+ for (let index = 0; index < lines.length && hits < MAX_HITS_PER_RULE_PER_FILE; index += 1) {
107
+ const line = lines[index];
108
+ if (!line) continue;
109
+ // Minified installers live on one very long line. Scan them too, with a
110
+ // hard ceiling so a pathological file cannot stall the reviewer.
111
+ const subject = line.length > MAX_LINE_CHARS ? line.slice(0, MAX_LINE_CHARS) : line;
112
+ const match = rule.re.exec(subject);
113
+ if (match) {
114
+ addFinding(findings, rule, relFile, index + 1, matchSnippet(subject, match));
115
+ hits += 1;
116
+ }
117
+ }
118
+ }
119
+ }
120
+
121
+ function scanInstallHooks(lines, content, relFile, findings, rule) {
122
+ if (path.basename(relFile) !== "package.json") return;
123
+ let pkg;
124
+ try {
125
+ pkg = JSON.parse(content);
126
+ } catch {
127
+ return;
128
+ }
129
+ const scripts = pkg && typeof pkg.scripts === "object" ? pkg.scripts : null;
130
+ if (!scripts) return;
131
+ for (const hook of ["preinstall", "install", "postinstall", "prepare"]) {
132
+ if (typeof scripts[hook] !== "string") continue;
133
+ const index = lines.findIndex((line) => line.includes(`"${hook}"`));
134
+ addFinding(findings, rule, relFile, index === -1 ? 1 : index + 1, `"${hook}": "${scripts[hook]}"`);
135
+ }
136
+ }
137
+
138
+ function scanEncodedBlobs(lines, relFile, findings, rule) {
139
+ for (let index = 0; index < lines.length; index += 1) {
140
+ const line = lines[index];
141
+ if (line.length < 180) continue;
142
+ if (/data:image\//i.test(line)) continue;
143
+ if (/(["'`])[A-Za-z0-9+/]{180,}={0,2}\1/.test(line)) {
144
+ addFinding(findings, rule, relFile, index + 1, line);
145
+ return;
146
+ }
147
+ }
148
+ }
149
+
150
+ function isPinned(args) {
151
+ const specifier = args.find(
152
+ (arg) => !arg.startsWith("-") && !LAUNCHER_SUBCOMMANDS.has(arg),
153
+ );
154
+ if (!specifier) return false;
155
+ if (/@\d/.test(specifier)) return true;
156
+ return /:v?\d/.test(specifier) && !/:latest$/i.test(specifier);
157
+ }
158
+
159
+ function looksLikeFetchedServer(commandLine) {
160
+ return /(?:^|\s)(?:npx|bunx|uvx)(?:\s|$)|(?:pnpm|yarn)\s+dlx|npm\s+exec|docker\s+run/i.test(commandLine);
161
+ }
162
+
163
+ function redactUrl(url) {
164
+ try {
165
+ const parsed = new URL(url);
166
+ parsed.username = "";
167
+ parsed.password = "";
168
+ parsed.search = "";
169
+ parsed.hash = "";
170
+ return parsed.toString().replace(/\/$/, "");
171
+ } catch {
172
+ return url.replace(/\/\/[^/@]*@/, "//").replace(/[?#].*$/, "");
173
+ }
174
+ }
175
+
176
+ function scanMcpConfig(lines, relFile, findings) {
177
+ if (!MCP_CONFIG.test(path.basename(relFile))) return;
178
+ let parsed;
179
+ try {
180
+ parsed = JSON.parse(lines.join("\n"));
181
+ } catch {
182
+ return;
183
+ }
184
+ const servers = parsed && (parsed.mcpServers ?? parsed.servers);
185
+ if (!servers || typeof servers !== "object") return;
186
+
187
+ const commandRule = RULE_BY_ID.get("mcp-server-command");
188
+ const unpinnedRule = RULE_BY_ID.get("mcp-unpinned-server");
189
+ const remoteRule = RULE_BY_ID.get("mcp-remote-server");
190
+ let reported = 0;
191
+
192
+ for (const [name, server] of Object.entries(servers)) {
193
+ if (reported >= 5) return;
194
+ if (!server || typeof server !== "object") continue;
195
+
196
+ if (typeof server.command === "string") {
197
+ const args = Array.isArray(server.args) ? server.args.map(String) : [];
198
+ const commandLine = [server.command, ...args].join(" ");
199
+ const index = lines.findIndex((line) => line.includes(server.command));
200
+ const line = index === -1 ? 1 : index + 1;
201
+
202
+ addFinding(findings, commandRule, relFile, line, `${name}: ${commandLine}`);
203
+ if (looksLikeFetchedServer(commandLine) && !isPinned(args)) {
204
+ addFinding(findings, unpinnedRule, relFile, line, `${name}: ${commandLine}`);
205
+ }
206
+ reported += 1;
207
+ continue;
208
+ }
209
+
210
+ if (typeof server.url === "string") {
211
+ const index = lines.findIndex((line) => line.includes(server.url));
212
+ addFinding(
213
+ findings,
214
+ remoteRule,
215
+ relFile,
216
+ index === -1 ? 1 : index + 1,
217
+ `${name}: ${redactUrl(server.url)}`,
218
+ );
219
+ reported += 1;
220
+ }
221
+ }
222
+ }
223
+
224
+ function capabilitiesOf(findings) {
225
+ const map = new Map();
226
+ for (const finding of findings) {
227
+ const current = map.get(finding.capability);
228
+ if (!current) {
229
+ map.set(finding.capability, { name: finding.capability, severity: finding.severity, count: 1 });
230
+ continue;
231
+ }
232
+ current.count += 1;
233
+ if (SEVERITY_RANK[finding.severity] < SEVERITY_RANK[current.severity]) {
234
+ current.severity = finding.severity;
235
+ }
236
+ }
237
+ return [...map.values()].sort(
238
+ (a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity] || a.name.localeCompare(b.name),
239
+ );
240
+ }
241
+
242
+ export async function scan(target) {
243
+ const root = path.resolve(target);
244
+ const stat = await fs.stat(root);
245
+ const files = [];
246
+ const skipped = { count: 0 };
247
+
248
+ if (stat.isDirectory()) {
249
+ await walk(root, files, skipped);
250
+ } else {
251
+ if (SECRET_FILE.test(path.basename(root))) {
252
+ throw new Error(`refusing to read a secret file: ${path.basename(root)}`);
253
+ }
254
+ files.push(root);
255
+ }
256
+
257
+ const findings = [];
258
+ const base = stat.isDirectory() ? root : path.dirname(root);
259
+ let scanned = 0;
260
+
261
+ for (const file of files) {
262
+ let fileStat;
263
+ try {
264
+ fileStat = await fs.stat(file);
265
+ } catch {
266
+ skipped.count += 1;
267
+ continue;
268
+ }
269
+ if (fileStat.size > MAX_FILE_BYTES) {
270
+ skipped.count += 1;
271
+ continue;
272
+ }
273
+ const relFile = relative(base, file);
274
+ let content;
275
+ try {
276
+ content = await fs.readFile(file, "utf8");
277
+ } catch {
278
+ skipped.count += 1;
279
+ continue;
280
+ }
281
+ if (content.includes("\u0000")) {
282
+ skipped.count += 1;
283
+ continue;
284
+ }
285
+ scanned += 1;
286
+ const lines = content.split(/\r?\n/);
287
+ scanLines(lines, relFile, findings);
288
+ scanMcpConfig(lines, relFile, findings);
289
+ for (const rule of RULES) {
290
+ if (rule.special === "install-hook") scanInstallHooks(lines, content, relFile, findings, rule);
291
+ if (rule.special === "encoded-blob") scanEncodedBlobs(lines, relFile, findings, rule);
292
+ }
293
+ }
294
+
295
+ findings.sort(
296
+ (a, b) =>
297
+ SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity] ||
298
+ a.file.localeCompare(b.file) ||
299
+ a.line - b.line,
300
+ );
301
+
302
+ const summary = summarize(findings);
303
+ return {
304
+ tool: "agent-permit",
305
+ version: VERSION,
306
+ target,
307
+ files: { scanned, skipped: skipped.count },
308
+ findings,
309
+ ...summary,
310
+ capabilities: capabilitiesOf(findings),
311
+ };
312
+ }
package/src/version.js ADDED
@@ -0,0 +1 @@
1
+ export const VERSION = "0.1.3";