@arvyx/mcp 0.0.0-stage → 0.4.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 +77 -2
- package/cli.js +87 -0
- package/index.js +303 -0
- package/package.json +30 -4
- package/rules/arvyx.yml +393 -0
- package/scan.js +571 -0
package/scan.js
ADDED
|
@@ -0,0 +1,571 @@
|
|
|
1
|
+
// Arvyx code scanner. Runs where the code lives (a developer's machine via the MCP server, or CI),
|
|
2
|
+
// so the customer's code never leaves their environment: only normalized, redacted RESULTS are uploaded.
|
|
3
|
+
//
|
|
4
|
+
// Engines (each optional; a missing one is reported as "missing", never silently skipped):
|
|
5
|
+
// trivy dependencies (lockfiles) + infrastructure config (Dockerfile, Terraform, K8s...) [+ secrets
|
|
6
|
+
// when gitleaks is absent]; also the dependency inventory (SBOM components)
|
|
7
|
+
// gitleaks secrets in the working tree and in git history
|
|
8
|
+
// opengrep insecure code patterns, with Arvyx's own rule pack (rules/arvyx.yml)
|
|
9
|
+
// zizmor GitHub Actions workflow security (template injection, pull_request_target, permissions...)
|
|
10
|
+
// sentinel built-in checks for the stacks AI-built apps use (Supabase RLS, Firebase rules, .env
|
|
11
|
+
// hygiene, secrets in browser-exposed env vars, missing security headers). No install needed.
|
|
12
|
+
//
|
|
13
|
+
// What is uploaded per result: tool, rule, severity, title/message (tool text), path, line, commit,
|
|
14
|
+
// package/versions, CVE/CWE ids, and a short hash used to tell results apart. Never a code snippet,
|
|
15
|
+
// a matched secret, a file body, or commit author details.
|
|
16
|
+
import { execFile } from "node:child_process";
|
|
17
|
+
import crypto from "node:crypto";
|
|
18
|
+
import fss from "node:fs";
|
|
19
|
+
import fs from "node:fs/promises";
|
|
20
|
+
import os from "node:os";
|
|
21
|
+
import path from "node:path";
|
|
22
|
+
import { fileURLToPath } from "node:url";
|
|
23
|
+
|
|
24
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
25
|
+
export const RULES_FILE = path.join(HERE, "rules", "arvyx.yml");
|
|
26
|
+
export const INSTALL_HINTS = {
|
|
27
|
+
trivy: "brew install trivy (Linux: https://trivy.dev/latest/getting-started/installation/)",
|
|
28
|
+
gitleaks: "brew install gitleaks (Linux: https://github.com/gitleaks/gitleaks/releases)",
|
|
29
|
+
opengrep: "curl -fsSL https://raw.githubusercontent.com/opengrep/opengrep/main/install.sh | bash",
|
|
30
|
+
zizmor: "brew install zizmor (or: pipx install zizmor)",
|
|
31
|
+
};
|
|
32
|
+
const SKIP_DIRS = new Set(["node_modules", ".git", "dist", "build", ".next", ".nuxt", ".svelte-kit", ".output",
|
|
33
|
+
"vendor", "venv", ".venv", "__pycache__", ".turbo", ".vercel", "coverage", "target"]);
|
|
34
|
+
const MAX_FILE = 512 * 1024;
|
|
35
|
+
|
|
36
|
+
const sha = (s) => crypto.createHash("sha256").update(String(s)).digest("hex").slice(0, 16);
|
|
37
|
+
|
|
38
|
+
function run(cmd, args, { cwd, timeout = 600000, env } = {}) {
|
|
39
|
+
return new Promise((resolve) => {
|
|
40
|
+
execFile(cmd, args, { cwd, timeout, maxBuffer: 512 * 1024 * 1024, env: { ...process.env, ...env } },
|
|
41
|
+
(err, stdout, stderr) => resolve({ code: err ? (typeof err.code === "number" ? err.code : 1) : 0,
|
|
42
|
+
stdout: String(stdout || ""), stderr: String(stderr || ""), killed: !!err?.killed }));
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// ARVYX_<name>, falling back to the pre-rename SENTINEL_<name>.
|
|
47
|
+
export const envOf = (name) => process.env[`ARVYX_${name}`] ?? process.env[`SENTINEL_${name}`];
|
|
48
|
+
|
|
49
|
+
export function which(bin) {
|
|
50
|
+
const override = envOf(bin.toUpperCase());
|
|
51
|
+
if (override) return fss.existsSync(override) ? override : null;
|
|
52
|
+
for (const dir of (process.env.PATH || "").split(path.delimiter)) {
|
|
53
|
+
const p = path.join(dir, bin);
|
|
54
|
+
try { fss.accessSync(p, fss.constants.X_OK); if (fss.statSync(p).isFile()) return p; } catch { /* next */ }
|
|
55
|
+
}
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const git = async (root, args) => {
|
|
60
|
+
const r = await run("git", args, { cwd: root, timeout: 60000 });
|
|
61
|
+
return r.code === 0 ? r.stdout.trim() : null;
|
|
62
|
+
};
|
|
63
|
+
const zsplit = (s) => (s ? s.split("\0").filter(Boolean) : []);
|
|
64
|
+
|
|
65
|
+
// ------------------------------------------------------------------ repo context
|
|
66
|
+
export function repoFromRemote(url) {
|
|
67
|
+
if (!url) return null;
|
|
68
|
+
const m = url.trim().replace(/\.git$/, "").match(/[:/]([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/);
|
|
69
|
+
return m ? `${m[1]}/${m[2]}` : null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function context(dir) {
|
|
73
|
+
const root = (await git(dir, ["rev-parse", "--show-toplevel"])) || path.resolve(dir);
|
|
74
|
+
const isGit = !!(await git(root, ["rev-parse", "--git-dir"]));
|
|
75
|
+
const env = process.env;
|
|
76
|
+
let repo = envOf("REPO") || env.GITHUB_REPOSITORY || (isGit && repoFromRemote(await git(root, ["remote", "get-url", "origin"])));
|
|
77
|
+
if (!repo) repo = "local/" + (path.basename(root).replace(/[^A-Za-z0-9_.-]/g, "-").slice(0, 100) || "project");
|
|
78
|
+
let branch = envOf("BRANCH") || env.GITHUB_HEAD_REF || env.GITHUB_REF_NAME ||
|
|
79
|
+
(isGit ? await git(root, ["rev-parse", "--abbrev-ref", "HEAD"]) : null);
|
|
80
|
+
if (branch === "HEAD") branch = null; // detached
|
|
81
|
+
let defaultBranch = envOf("DEFAULT_BRANCH") || null;
|
|
82
|
+
if (!defaultBranch && isGit) {
|
|
83
|
+
const ref = await git(root, ["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"]);
|
|
84
|
+
if (ref) defaultBranch = ref.replace(/^origin\//, "");
|
|
85
|
+
else for (const b of ["main", "master"]) if (await git(root, ["rev-parse", "--verify", "--quiet", `refs/heads/${b}`])) { defaultBranch = b; break; }
|
|
86
|
+
}
|
|
87
|
+
const commit = env.GITHUB_SHA || (isGit ? await git(root, ["rev-parse", "HEAD"]) : null);
|
|
88
|
+
let files, tracked = new Set(), unignored = new Set();
|
|
89
|
+
if (isGit) {
|
|
90
|
+
files = zsplit(await git(root, ["ls-files", "-co", "--exclude-standard", "-z"]));
|
|
91
|
+
tracked = new Set(zsplit(await git(root, ["ls-files", "-z"])));
|
|
92
|
+
unignored = new Set(zsplit(await git(root, ["ls-files", "-o", "--exclude-standard", "-z"])));
|
|
93
|
+
} else {
|
|
94
|
+
files = await walk(root);
|
|
95
|
+
}
|
|
96
|
+
files = files.filter((f) => !f.split("/").some((p) => SKIP_DIRS.has(p)) && fss.existsSync(path.join(root, f)));
|
|
97
|
+
return { root, isGit, repo, branch, defaultBranch, commit, files, fileSet: new Set(files), tracked, unignored };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async function walk(root, rel = "", out = []) {
|
|
101
|
+
if (out.length > 50000) return out;
|
|
102
|
+
for (const e of await fs.readdir(path.join(root, rel), { withFileTypes: true }).catch(() => [])) {
|
|
103
|
+
if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name)) await walk(root, path.join(rel, e.name), out); }
|
|
104
|
+
else if (e.isFile()) out.push(path.join(rel, e.name).split(path.sep).join("/"));
|
|
105
|
+
}
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function read(root, f) {
|
|
110
|
+
try {
|
|
111
|
+
const p = path.join(root, f);
|
|
112
|
+
if ((await fs.stat(p)).size > MAX_FILE) return null;
|
|
113
|
+
return await fs.readFile(p, "utf8");
|
|
114
|
+
} catch { return null; }
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const lineOf = (text, index) => text.slice(0, index).split("\n").length;
|
|
118
|
+
|
|
119
|
+
// ------------------------------------------------------------------ trivy
|
|
120
|
+
async function runTrivy(ctx, bin, withSecrets, tmp) {
|
|
121
|
+
const out = path.join(tmp, "trivy.json");
|
|
122
|
+
const scanners = withSecrets ? "vuln,misconfig,secret" : "vuln,misconfig";
|
|
123
|
+
const r = await run(bin, ["fs", "--quiet", "--format", "json", "--output", out, "--scanners", scanners,
|
|
124
|
+
"--list-all-pkgs", "--skip-dirs", "**/node_modules", ctx.root], { timeout: 1200000 });
|
|
125
|
+
if (r.code !== 0) return { status: { status: "error", detail: (r.stderr || "trivy failed").slice(-280) } };
|
|
126
|
+
const data = JSON.parse(await fs.readFile(out, "utf8"));
|
|
127
|
+
const findings = [], components = [];
|
|
128
|
+
const inScope = (t) => !ctx.isGit || ctx.fileSet.has(t);
|
|
129
|
+
for (const res of data.Results || []) {
|
|
130
|
+
const target = res.Target;
|
|
131
|
+
for (const p of res.Packages || []) {
|
|
132
|
+
components.push({ name: p.Name, version: p.Version, ecosystem: res.Type, purl: p.Identifier?.PURL });
|
|
133
|
+
}
|
|
134
|
+
if (!inScope(target)) continue;
|
|
135
|
+
for (const v of res.Vulnerabilities || []) {
|
|
136
|
+
findings.push({ tool: "trivy", kind: "vuln", rule: v.VulnerabilityID, severity: v.Severity, title: v.Title,
|
|
137
|
+
package: v.PkgName, installed_version: v.InstalledVersion, fixed_version: v.FixedVersion || undefined,
|
|
138
|
+
vuln_id: v.VulnerabilityID, path: target, cwe: (v.CweIDs || []).slice(0, 5),
|
|
139
|
+
refs: [v.PrimaryURL].filter(Boolean) });
|
|
140
|
+
}
|
|
141
|
+
for (const m of res.Misconfigurations || []) {
|
|
142
|
+
if (m.Status && m.Status !== "FAIL") continue;
|
|
143
|
+
findings.push({ tool: "trivy", kind: "misconfig", rule: m.AVDID || m.ID, severity: m.Severity, title: m.Title,
|
|
144
|
+
message: [m.Message, m.Resolution].filter(Boolean).join(" — "), path: target,
|
|
145
|
+
line: m.CauseMetadata?.StartLine || undefined, refs: [m.PrimaryURL].filter(Boolean) });
|
|
146
|
+
}
|
|
147
|
+
for (const s of res.Secrets || []) { // only when gitleaks is not available
|
|
148
|
+
findings.push({ tool: "trivy", kind: "secret", rule: s.RuleID, title: s.Title, path: target,
|
|
149
|
+
line: s.StartLine, key: sha(`${s.RuleID}|${s.Match}`) }); // Match is masked by trivy; hashed anyway
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return { status: { status: "ok", version: data.Trivy?.Version }, findings, components };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// ------------------------------------------------------------------ gitleaks
|
|
156
|
+
// JWTs in .env.example-style files are almost always Supabase's public local-dev demo keys. Other
|
|
157
|
+
// secrets in example files (real API keys pasted by mistake) are still reported.
|
|
158
|
+
const isTemplateJwt = (l) => l.RuleID === "jwt" && ENV_FILE.test(l.File) && ENV_TEMPLATE.test(l.File);
|
|
159
|
+
async function gitleaksRun(bin, mode, target, out) {
|
|
160
|
+
const r = await run(bin, [mode, "--redact", "--no-banner", "--log-level", "error", "--exit-code", "0",
|
|
161
|
+
"--report-format", "json", "--report-path", out, target], { timeout: 900000 });
|
|
162
|
+
if (r.code !== 0) throw new Error((r.stderr || `gitleaks ${mode} failed`).slice(-280));
|
|
163
|
+
return JSON.parse((await fs.readFile(out, "utf8")) || "[]") || [];
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function runGitleaks(ctx, bin, tmp) {
|
|
167
|
+
try {
|
|
168
|
+
const key = (l) => sha(`${l.RuleID}|${Number(l.Entropy || 0).toFixed(3)}`);
|
|
169
|
+
const current = (await gitleaksRun(bin, "dir", ctx.root, path.join(tmp, "gl-dir.json")))
|
|
170
|
+
.map((l) => ({ ...l, File: path.relative(ctx.root, path.resolve(ctx.root, l.File)).split(path.sep).join("/") }))
|
|
171
|
+
.filter((l) => !ctx.isGit || ctx.fileSet.has(l.File)) // a gitignored local .env is correct practice
|
|
172
|
+
.filter((l) => !isTemplateJwt(l));
|
|
173
|
+
const findings = current.map((l) => ({ tool: "gitleaks", kind: "secret", rule: l.RuleID, title: l.RuleID,
|
|
174
|
+
message: l.Description, path: l.File, line: l.StartLine, key: key(l) }));
|
|
175
|
+
if (ctx.isGit) {
|
|
176
|
+
const now = new Set(findings.map((f) => `${f.path}|${f.rule}|${f.key}`));
|
|
177
|
+
const seen = new Set();
|
|
178
|
+
for (const l of await gitleaksRun(bin, "git", ctx.root, path.join(tmp, "gl-git.json"))) {
|
|
179
|
+
if (isTemplateJwt(l)) continue;
|
|
180
|
+
const id = `${l.File}|${l.RuleID}|${key(l)}`;
|
|
181
|
+
if (now.has(id) || seen.has(id)) continue; // still in the tree (reported above) or a repeat
|
|
182
|
+
seen.add(id);
|
|
183
|
+
findings.push({ tool: "gitleaks", kind: "history-secret", rule: l.RuleID, title: l.RuleID,
|
|
184
|
+
message: l.Description, path: l.File, line: l.StartLine, commit: (l.Commit || "").slice(0, 40) || undefined,
|
|
185
|
+
key: key(l) }); // author, email and commit message are deliberately not sent
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
const v = await run(bin, ["version"], { timeout: 30000 });
|
|
189
|
+
return { status: { status: "ok", version: v.stdout.trim().slice(0, 40) }, findings };
|
|
190
|
+
} catch (e) {
|
|
191
|
+
return { status: { status: "error", detail: String(e.message).slice(0, 280) } };
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// ------------------------------------------------------------------ opengrep
|
|
196
|
+
async function runOpengrep(ctx, bin) {
|
|
197
|
+
const r = await run(bin, ["scan", "--config", RULES_FILE, "--json", "--quiet", ctx.root], { cwd: ctx.root, timeout: 900000 });
|
|
198
|
+
let data;
|
|
199
|
+
try { data = JSON.parse(r.stdout); } catch {
|
|
200
|
+
return { status: { status: "error", detail: (r.stderr || "opengrep produced no JSON").slice(-280) } };
|
|
201
|
+
}
|
|
202
|
+
const fatal = (data.errors || []).filter((e) => e.level === "error" && !e.path);
|
|
203
|
+
if (fatal.length && !(data.results || []).length) {
|
|
204
|
+
return { status: { status: "error", detail: String(fatal[0].message || fatal[0].type).slice(0, 280) } };
|
|
205
|
+
}
|
|
206
|
+
const findings = [];
|
|
207
|
+
// A taint rule and a pattern rule can flag the same bug, sometimes on adjacent lines of one
|
|
208
|
+
// multi-line call: report one finding per bug class (CWE) within a few lines.
|
|
209
|
+
// ponytail: line-window heuristic; use opengrep's dataflow trace ranges if it merges real neighbours.
|
|
210
|
+
const seenAt = new Map();
|
|
211
|
+
for (const res of data.results || []) {
|
|
212
|
+
const rel = path.relative(ctx.root, path.resolve(ctx.root, res.path)).split(path.sep).join("/");
|
|
213
|
+
if (ctx.isGit && !ctx.fileSet.has(rel)) continue;
|
|
214
|
+
const meta = res.extra?.metadata || {};
|
|
215
|
+
const rule = String(res.check_id || "").split(".").pop();
|
|
216
|
+
const bugClass = `${rel}|${String([].concat(meta.cwe || [rule])[0]).split(":")[0]}`;
|
|
217
|
+
const line = res.start?.line || 0;
|
|
218
|
+
const near = seenAt.get(bugClass) || [];
|
|
219
|
+
if (near.some((l) => Math.abs(l - line) <= 3)) continue;
|
|
220
|
+
seenAt.set(bugClass, [...near, line]);
|
|
221
|
+
findings.push({ tool: "opengrep", kind: "sast", rule, severity: res.extra?.severity, title: meta.title || rule,
|
|
222
|
+
message: res.extra?.message, path: rel, line: res.start?.line,
|
|
223
|
+
cwe: [].concat(meta.cwe || []).map((c) => String(c).split(":")[0]).slice(0, 5),
|
|
224
|
+
refs: [].concat(meta.references || []).slice(0, 3),
|
|
225
|
+
key: sha(`${rule}|${(res.extra?.lines || "").replace(/\s+/g, " ").trim()}`) });
|
|
226
|
+
}
|
|
227
|
+
const v = await run(bin, ["--version"], { timeout: 30000 });
|
|
228
|
+
return { status: { status: "ok", version: v.stdout.trim().slice(0, 40) }, findings };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// ------------------------------------------------------------------ zizmor
|
|
232
|
+
const WORKFLOW_FILE = /^\.github\/workflows\/[^/]+\.ya?ml$/;
|
|
233
|
+
async function runZizmor(ctx, bin) {
|
|
234
|
+
const r = await run(bin, ["--offline", "--no-exit-codes", "--format", "json", "--quiet", "."], { cwd: ctx.root, timeout: 600000 });
|
|
235
|
+
let data;
|
|
236
|
+
try { data = JSON.parse(r.stdout || "[]"); } catch {
|
|
237
|
+
return { status: { status: "error", detail: (r.stderr || "zizmor produced no JSON").slice(-280) } };
|
|
238
|
+
}
|
|
239
|
+
const findings = [];
|
|
240
|
+
for (const res of Array.isArray(data) ? data : []) {
|
|
241
|
+
if (res.ignored) continue;
|
|
242
|
+
const loc = (res.locations || []).find((l) => l.symbolic?.kind === "Primary") || res.locations?.[0];
|
|
243
|
+
const raw = loc?.symbolic?.key?.Local?.verbatim_path;
|
|
244
|
+
if (!raw) continue;
|
|
245
|
+
const rel = path.relative(ctx.root, path.resolve(ctx.root, raw)).split(path.sep).join("/");
|
|
246
|
+
if (ctx.isGit && !ctx.fileSet.has(rel)) continue;
|
|
247
|
+
const route = (loc.symbolic.route?.route || []).map((k) => k.Key ?? k.Index).join(".");
|
|
248
|
+
const row = loc.concrete?.location?.start_point?.row;
|
|
249
|
+
// Rule, severity, location and zizmor's own description only: the workflow text itself
|
|
250
|
+
// (zizmor's "feature" field) is never uploaded.
|
|
251
|
+
findings.push({ tool: "zizmor", kind: "workflow", rule: String(res.ident || "zizmor").slice(0, 200),
|
|
252
|
+
severity: res.determinations?.severity, title: res.desc, message: loc.symbolic.annotation, path: rel,
|
|
253
|
+
line: typeof row === "number" ? row + 1 : undefined, refs: res.url ? [res.url] : [],
|
|
254
|
+
key: sha(`${res.ident}|${rel}|${route}`) });
|
|
255
|
+
}
|
|
256
|
+
const v = await run(bin, ["--version"], { timeout: 30000 });
|
|
257
|
+
return { status: { status: "ok", version: v.stdout.trim().slice(0, 40) }, findings };
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// ------------------------------------------------------------------ change intelligence
|
|
261
|
+
// Classify changed PATHS (never contents) and pick the engines a change can affect. Engines are chosen
|
|
262
|
+
// whole: one either scans the whole repository or is reported "skipped", so an engine that did not run
|
|
263
|
+
// never closes an issue (the server only resolves issues for engines whose status is "ok").
|
|
264
|
+
const CHANGE_RULES = [
|
|
265
|
+
["docs", /\.(md|mdx|txt|rst|png|jpe?g|gif|svg|webp|ico)$/i],
|
|
266
|
+
["workflows", /^\.github\/(workflows\/[^/]+\.ya?ml|actions\/.+\/action\.ya?ml)$|(^|\/)action\.ya?ml$/],
|
|
267
|
+
["dependencies", /(^|\/)(package(-lock)?\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?|requirements[^/]*\.txt|pyproject\.toml|poetry\.lock|uv\.lock|Pipfile(\.lock)?|go\.(mod|sum)|Cargo\.(toml|lock)|Gemfile(\.lock)?|composer\.(json|lock)|pom\.xml|build\.gradle(\.kts)?)$/],
|
|
268
|
+
["iac", /\.(tf|tfvars)$|(^|\/)(Dockerfile[^/]*|docker-compose[^/]*\.ya?ml|compose\.ya?ml)$|(^|\/)(k8s|kubernetes|helm|charts)\//],
|
|
269
|
+
["database", /\.sql$|(^|\/)(firestore|storage|database)\.rules$|\.rules\.json$|schema\.prisma$/],
|
|
270
|
+
["config", /(^|\/)\.env[^/]*$|(^|\/)(next|nuxt|vite|astro|svelte|remix)\.config\.[cm]?[jt]s$|(^|\/)(vercel\.json|netlify\.toml|_headers|\.gitignore|firebase\.json)$/],
|
|
271
|
+
["api", /(^|\/)app\/(.+\/)?api\/.+\/route\.[cm]?[jt]sx?$|(^|\/)pages\/api\/|(^|\/)(routes?|controllers?|handlers?)\/|(^|\/)(api|views|urls)\.py$|(^|\/)supabase\/functions\//],
|
|
272
|
+
["auth", /(auth|login|signin|signup|session|middleware|permission|rls|polic(y|ies)|oauth|jwt|password)/i],
|
|
273
|
+
];
|
|
274
|
+
const CODE_FILE = /\.(js|jsx|ts|tsx|mjs|cjs|vue|svelte|astro|py|rb|go|java|kt|php|cs|rs|swift)$/;
|
|
275
|
+
|
|
276
|
+
export function classifyChange(files) {
|
|
277
|
+
const categories = new Set(), sensitive = [];
|
|
278
|
+
for (const f of files) {
|
|
279
|
+
const hits = CHANGE_RULES.filter(([, rx]) => rx.test(f)).map(([c]) => c);
|
|
280
|
+
// A file name like "auth" only marks auth CODE; a docs page about auth is still docs.
|
|
281
|
+
const cats = hits.includes("docs") ? ["docs"] : hits.filter((c) => c !== "auth" || CODE_FILE.test(f));
|
|
282
|
+
if (!cats.length && CODE_FILE.test(f)) cats.push("source");
|
|
283
|
+
if (cats.some((c) => c === "auth" || c === "api") && CODE_FILE.test(f) && !cats.includes("source")) cats.push("source");
|
|
284
|
+
if (!cats.length) cats.push("source"); // unknown file kinds: scan as code, never skip silently
|
|
285
|
+
cats.forEach((c) => categories.add(c));
|
|
286
|
+
if (cats.includes("auth") || cats.includes("api")) sensitive.push(f);
|
|
287
|
+
}
|
|
288
|
+
const order = ["dependencies", "iac", "workflows", "database", "config", "auth", "api", "source", "docs"];
|
|
289
|
+
return { categories: order.filter((c) => categories.has(c)), sensitive_paths: sensitive.slice(0, 50) };
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// Secrets can be in any file and Arvyx's checks are instant, so gitleaks and sentinel always run.
|
|
293
|
+
const ENGINES_FOR = { dependencies: ["trivy"], iac: ["trivy"], workflows: ["zizmor"], database: [], config: [],
|
|
294
|
+
auth: ["opengrep"], api: ["opengrep"], source: ["opengrep"], docs: [] };
|
|
295
|
+
export function enginesFor(categories) {
|
|
296
|
+
return new Set(["gitleaks", "sentinel", ...categories.flatMap((c) => ENGINES_FOR[c] || [])]);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// Files changed on this branch relative to its base (merge-base, so the base's own new commits are
|
|
300
|
+
// ignored), plus local uncommitted and untracked files. null = no usable base: scan everything.
|
|
301
|
+
async function changedFiles(ctx) {
|
|
302
|
+
if (!ctx.isGit) return null;
|
|
303
|
+
const base = process.env.GITHUB_BASE_REF || ctx.defaultBranch;
|
|
304
|
+
if (!base || ctx.branch === base) return null; // the default branch itself is always scanned in full
|
|
305
|
+
for (const ref of [`origin/${base}`, base]) {
|
|
306
|
+
const mb = await git(ctx.root, ["merge-base", ref, "HEAD"]);
|
|
307
|
+
if (!mb) continue;
|
|
308
|
+
const committed = zsplit(await git(ctx.root, ["diff", "--name-only", "-z", mb, "HEAD"]));
|
|
309
|
+
const local = zsplit(await git(ctx.root, ["diff", "--name-only", "-z", "HEAD"]));
|
|
310
|
+
return { base, files: [...new Set([...committed, ...local, ...ctx.unignored])] };
|
|
311
|
+
}
|
|
312
|
+
return null;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function prNumber() {
|
|
316
|
+
if (envOf("PR_NUMBER")) return Number(envOf("PR_NUMBER")) || undefined;
|
|
317
|
+
try {
|
|
318
|
+
const ev = JSON.parse(fss.readFileSync(process.env.GITHUB_EVENT_PATH, "utf8"));
|
|
319
|
+
return ev.pull_request?.number || undefined;
|
|
320
|
+
} catch { return undefined; }
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// ------------------------------------------------------------------ Arvyx built-in checks
|
|
324
|
+
// Wire value tool/kind "sentinel" is kept: the server's issue fingerprints include it.
|
|
325
|
+
const ENV_FILE = /(^|\/)\.env(\.[A-Za-z0-9_.-]+)?$/;
|
|
326
|
+
const ENV_TEMPLATE = /\.(example|sample|template|tpl|dist)$/i;
|
|
327
|
+
const PUBLIC_VAR = /\b((?:NEXT_PUBLIC|VITE|EXPO_PUBLIC|REACT_APP|NUXT_PUBLIC|GATSBY|PUBLIC)_[A-Z0-9_]+)/g;
|
|
328
|
+
const SECRET_NAME = /(SERVICE_ROLE|SERVICE_KEY|SECRET|PRIVATE|PASSWORD|PASSWD|SK_LIVE|OPENAI|ANTHROPIC|GEMINI_API|GROQ_API|DATABASE_URL|DB_URL|POSTGRES_URL|MONGODB_URI|AWS_SECRET|ADMIN_KEY|RESEND_API|SENDGRID|TWILIO_AUTH|CLERK_SECRET)/;
|
|
329
|
+
const SOURCE = /\.(js|jsx|ts|tsx|mjs|cjs|vue|svelte|astro)$/;
|
|
330
|
+
const IDENT = String.raw`(?:"?[A-Za-z_][\w$]*"?\.)?"?[A-Za-z_][\w$]*"?`;
|
|
331
|
+
|
|
332
|
+
function tableName(raw) {
|
|
333
|
+
const parts = raw.replace(/"/g, "").toLowerCase().split(".");
|
|
334
|
+
return parts.length === 2 ? { schema: parts[0], name: parts[1] } : { schema: "public", name: parts[0] };
|
|
335
|
+
}
|
|
336
|
+
const stripSqlComments = (s) => s.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, " ")).replace(/--[^\n]*/g, (m) => " ".repeat(m.length));
|
|
337
|
+
|
|
338
|
+
async function supabaseChecks(ctx) {
|
|
339
|
+
const sqlFiles = ctx.files.filter((f) => /\.sql$/i.test(f) && /(^|\/)(supabase|migrations|db)\//i.test(f)).sort();
|
|
340
|
+
if (!sqlFiles.length) return [];
|
|
341
|
+
const tables = new Map(); // name -> {path, line, rls}
|
|
342
|
+
const policies = new Map(); // table:policy -> {path, line}
|
|
343
|
+
const events = new RegExp(String.raw`create\s+(?:unlogged\s+)?table\s+(?:if\s+not\s+exists\s+)?(${IDENT})` +
|
|
344
|
+
String.raw`|alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?(${IDENT})\s+(enable|disable)\s+row\s+level\s+security` +
|
|
345
|
+
String.raw`|drop\s+table\s+(?:if\s+exists\s+)?(${IDENT})` +
|
|
346
|
+
String.raw`|create\s+policy\s+("[^"]+"|\w+)\s+on\s+(?:table\s+)?(${IDENT})([\s\S]*?);` +
|
|
347
|
+
String.raw`|drop\s+policy\s+(?:if\s+exists\s+)?("[^"]+"|\w+)\s+on\s+(?:table\s+)?(${IDENT})`, "gi");
|
|
348
|
+
for (const f of sqlFiles) {
|
|
349
|
+
const raw = await read(ctx.root, f);
|
|
350
|
+
if (!raw) continue;
|
|
351
|
+
const text = stripSqlComments(raw);
|
|
352
|
+
for (const m of text.matchAll(events)) {
|
|
353
|
+
const line = lineOf(text, m.index);
|
|
354
|
+
if (m[1]) { const t = tableName(m[1]); if (t.schema === "public") tables.set(t.name, { path: f, line, rls: false }); }
|
|
355
|
+
else if (m[2]) { const t = tableName(m[2]); if (tables.has(t.name)) tables.get(t.name).rls = m[3].toLowerCase() === "enable"; }
|
|
356
|
+
else if (m[4]) tables.delete(tableName(m[4]).name);
|
|
357
|
+
else if (m[5]) {
|
|
358
|
+
const t = tableName(m[6]).name, body = m[7] || "";
|
|
359
|
+
const id = `${t}:${m[5].replace(/"/g, "")}`;
|
|
360
|
+
// Public READ of catalog-style data is a normal design (and the live scan proves what anon can
|
|
361
|
+
// actually read); `true` on a policy that can insert/update/delete lets anyone change data.
|
|
362
|
+
const readOnly = /\bfor\s+select\b/i.test(body);
|
|
363
|
+
if (!readOnly && /\busing\s*\(\s*true\s*\)|\bwith\s+check\s*\(\s*true\s*\)/i.test(body)) policies.set(id, { path: f, line });
|
|
364
|
+
else policies.delete(id);
|
|
365
|
+
} else if (m[8]) policies.delete(`${tableName(m[9]).name}:${m[8].replace(/"/g, "")}`);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
const out = [];
|
|
369
|
+
for (const [name, t] of tables) {
|
|
370
|
+
if (!t.rls) out.push({ tool: "sentinel", kind: "sentinel", rule: "CODE_SUPABASE_TABLE_NO_RLS", path: t.path, line: t.line, key: name });
|
|
371
|
+
}
|
|
372
|
+
for (const [id, p] of policies) {
|
|
373
|
+
out.push({ tool: "sentinel", kind: "sentinel", rule: "CODE_SUPABASE_POLICY_PERMISSIVE", path: p.path, line: p.line, key: id });
|
|
374
|
+
}
|
|
375
|
+
return out;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
async function firebaseChecks(ctx) {
|
|
379
|
+
const out = [];
|
|
380
|
+
for (const f of ctx.files.filter((f) => /(^|\/)(firestore|storage)\.rules$|\.rules$/.test(f) || /(^|\/)database\.rules\.json$/.test(f))) {
|
|
381
|
+
const text = await read(ctx.root, f);
|
|
382
|
+
if (!text) continue;
|
|
383
|
+
const open = f.endsWith(".json")
|
|
384
|
+
? /"\.(read|write)"\s*:\s*(true|"true")/g
|
|
385
|
+
: /^\s*allow\s+[a-z,\s]+(?::\s*if\s+true\s*;|;)/gim;
|
|
386
|
+
for (const m of text.matchAll(open)) {
|
|
387
|
+
out.push({ tool: "sentinel", kind: "sentinel", rule: "CODE_FIREBASE_RULES_OPEN", path: f, line: lineOf(text, m.index),
|
|
388
|
+
key: sha(m[0].replace(/\s+/g, " ").trim()) });
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
return out;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
async function envChecks(ctx) {
|
|
395
|
+
const out = [];
|
|
396
|
+
const envFiles = ctx.files.filter((f) => ENV_FILE.test(f));
|
|
397
|
+
if (ctx.isGit) {
|
|
398
|
+
for (const f of envFiles.filter((f) => !ENV_TEMPLATE.test(f))) {
|
|
399
|
+
if (ctx.tracked.has(f)) out.push({ tool: "sentinel", kind: "sentinel", rule: "CODE_ENV_FILE_COMMITTED", path: f, key: f });
|
|
400
|
+
else if (ctx.unignored.has(f)) out.push({ tool: "sentinel", kind: "sentinel", rule: "CODE_ENV_NOT_GITIGNORED", path: f, key: f });
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
// Secret-looking names in browser-exposed env vars: env files (incl. templates) and source code.
|
|
404
|
+
const named = new Map();
|
|
405
|
+
for (const f of [...envFiles, ...ctx.files.filter((f) => SOURCE.test(f) && !/\.min\.js$/.test(f)).slice(0, 8000)]) {
|
|
406
|
+
const text = await read(ctx.root, f);
|
|
407
|
+
if (!text) continue;
|
|
408
|
+
for (const m of text.matchAll(PUBLIC_VAR)) {
|
|
409
|
+
const name = m[1];
|
|
410
|
+
if (SECRET_NAME.test(name) && !named.has(name)) {
|
|
411
|
+
named.set(name, { path: f, line: lineOf(text, m.index) });
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
for (const [name, at] of named) out.push({ tool: "sentinel", kind: "sentinel", rule: "CODE_SECRET_IN_PUBLIC_ENV", path: at.path, line: at.line, key: name });
|
|
416
|
+
return out;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
async function headersCheck(ctx) {
|
|
420
|
+
const cfg = ctx.files.find((f) => /^(?:[^/]+\/)?(next|vite)\.config\.(js|mjs|ts|cjs)$/.test(f));
|
|
421
|
+
if (!cfg) return [];
|
|
422
|
+
const has = async (f, re) => { const t = ctx.fileSet.has(f) ? await read(ctx.root, f) : null; return !!(t && re.test(t)); };
|
|
423
|
+
const dir = cfg.includes("/") ? cfg.slice(0, cfg.lastIndexOf("/") + 1) : "";
|
|
424
|
+
const HEADER = /Content-Security-Policy|Strict-Transport-Security|X-Frame-Options|frame-ancestors/i;
|
|
425
|
+
const checks = [
|
|
426
|
+
has(cfg, /\bheaders\s*\(|\bheaders\s*:/), has(`${dir}vercel.json`, /"headers"\s*:/), has("vercel.json", /"headers"\s*:/),
|
|
427
|
+
has(`${dir}netlify.toml`, /\[\[headers\]\]/), has("netlify.toml", /\[\[headers\]\]/),
|
|
428
|
+
Promise.resolve(ctx.fileSet.has(`${dir}public/_headers`) || ctx.fileSet.has(`${dir}_headers`) || ctx.fileSet.has("public/_headers")),
|
|
429
|
+
...["middleware.ts", "middleware.js", "src/middleware.ts", "src/middleware.js"].map((m) => has(`${dir}${m}`, HEADER)),
|
|
430
|
+
];
|
|
431
|
+
if ((await Promise.all(checks)).some(Boolean)) return [];
|
|
432
|
+
return [{ tool: "sentinel", kind: "sentinel", rule: "CODE_SECURITY_HEADERS_MISSING", path: cfg, key: cfg }];
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
export async function arvyxChecks(ctx) {
|
|
436
|
+
return (await Promise.all([supabaseChecks(ctx), firebaseChecks(ctx), envChecks(ctx), headersCheck(ctx)])).flat();
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
// ------------------------------------------------------------------ orchestration
|
|
440
|
+
export async function scan(dir = process.cwd(), { trigger = "cli", log = () => {}, changed = false } = {}) {
|
|
441
|
+
const ctx = await context(dir);
|
|
442
|
+
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), "arvyx-"));
|
|
443
|
+
const tools = {}, findings = [];
|
|
444
|
+
let components = [], change;
|
|
445
|
+
const diff = changed ? await changedFiles(ctx) : null;
|
|
446
|
+
let need = null;
|
|
447
|
+
if (diff) {
|
|
448
|
+
const c = classifyChange(diff.files);
|
|
449
|
+
need = enginesFor(c.categories);
|
|
450
|
+
change = { base: diff.base, categories: c.categories, files_changed: diff.files.length, sensitive_paths: c.sensitive_paths };
|
|
451
|
+
log(`change vs ${diff.base}: ${diff.files.length} file(s) — ${c.categories.join(", ") || "none"}`);
|
|
452
|
+
}
|
|
453
|
+
const skip = (t) => need && !need.has(t) ? (tools[t] = { status: "skipped", detail: "not affected by this change" }, true) : false;
|
|
454
|
+
try {
|
|
455
|
+
const bins = { trivy: which("trivy"), gitleaks: which("gitleaks"), opengrep: which("opengrep"), zizmor: which("zizmor") };
|
|
456
|
+
const jobs = [];
|
|
457
|
+
if (skip("trivy")) { /* not affected */ } else if (bins.trivy) {
|
|
458
|
+
log("trivy: dependencies + infrastructure config…");
|
|
459
|
+
jobs.push(runTrivy(ctx, bins.trivy, !bins.gitleaks, tmp).then((r) => { tools.trivy = r.status; findings.push(...(r.findings || [])); components = r.components || []; }));
|
|
460
|
+
} else tools.trivy = { status: "missing", detail: INSTALL_HINTS.trivy };
|
|
461
|
+
if (skip("gitleaks")) { /* not affected */ } else if (bins.gitleaks) {
|
|
462
|
+
log("gitleaks: secrets in files and git history…");
|
|
463
|
+
jobs.push(runGitleaks(ctx, bins.gitleaks, tmp).then((r) => { tools.gitleaks = r.status; findings.push(...(r.findings || [])); }));
|
|
464
|
+
} else tools.gitleaks = { status: "missing", detail: INSTALL_HINTS.gitleaks };
|
|
465
|
+
if (skip("opengrep")) { /* not affected */ } else if (bins.opengrep) {
|
|
466
|
+
log("opengrep: insecure code patterns…");
|
|
467
|
+
jobs.push(runOpengrep(ctx, bins.opengrep).then((r) => { tools.opengrep = r.status; findings.push(...(r.findings || [])); }));
|
|
468
|
+
} else tools.opengrep = { status: "missing", detail: INSTALL_HINTS.opengrep };
|
|
469
|
+
if (!ctx.files.some((f) => WORKFLOW_FILE.test(f))) tools.zizmor = { status: "skipped", detail: "no GitHub workflows" };
|
|
470
|
+
else if (skip("zizmor")) { /* not affected */ } else if (bins.zizmor) {
|
|
471
|
+
log("zizmor: GitHub Actions workflows…");
|
|
472
|
+
jobs.push(runZizmor(ctx, bins.zizmor).then((r) => { tools.zizmor = r.status; findings.push(...(r.findings || [])); }));
|
|
473
|
+
} else tools.zizmor = { status: "missing", detail: INSTALL_HINTS.zizmor };
|
|
474
|
+
log("arvyx checks: Supabase, Firebase, env files, headers…");
|
|
475
|
+
jobs.push(arvyxChecks(ctx).then((f) => { tools.sentinel = { status: "ok" }; findings.push(...f); },
|
|
476
|
+
(e) => { tools.sentinel = { status: "error", detail: String(e.message).slice(0, 280) }; }));
|
|
477
|
+
await Promise.all(jobs.map((j) => j.catch((e) => log(`engine failed: ${e.message}`))));
|
|
478
|
+
} finally {
|
|
479
|
+
await fs.rm(tmp, { recursive: true, force: true });
|
|
480
|
+
}
|
|
481
|
+
const manifest = ctx.files.filter((f) => f.split("/").length <= 4).sort((a, b) => a.split("/").length - b.split("/").length).slice(0, 400);
|
|
482
|
+
return {
|
|
483
|
+
repo: ctx.repo, branch: ctx.branch || undefined, default_branch: ctx.defaultBranch || undefined,
|
|
484
|
+
commit: ctx.commit || undefined, trigger, tools, findings: findings.slice(0, 5000),
|
|
485
|
+
components: dedupe(components).slice(0, 10000), manifest_paths: manifest,
|
|
486
|
+
...(change ? { change } : {}), ...(prNumber() ? { pr_number: prNumber() } : {}),
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
function dedupe(components) {
|
|
491
|
+
const seen = new Set();
|
|
492
|
+
return components.filter((c) => {
|
|
493
|
+
const k = `${c.ecosystem}|${c.name}|${c.version}`;
|
|
494
|
+
if (!c.name || seen.has(k)) return false;
|
|
495
|
+
seen.add(k);
|
|
496
|
+
return true;
|
|
497
|
+
});
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
// ------------------------------------------------------------------ upload
|
|
501
|
+
export async function upload(payload, { base, key, log = () => {} }) {
|
|
502
|
+
const url = base.replace(/\/$/, "") + "/api/mcp/code-scan";
|
|
503
|
+
let last;
|
|
504
|
+
for (let attempt = 0; attempt < 4; attempt++) { // the free-tier API can be cold-starting (~50 s)
|
|
505
|
+
try {
|
|
506
|
+
const res = await fetch(url, { method: "POST", signal: AbortSignal.timeout(120000),
|
|
507
|
+
headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" }, body: JSON.stringify(payload) });
|
|
508
|
+
const text = await res.text();
|
|
509
|
+
let data; try { data = JSON.parse(text); } catch { data = { detail: text.slice(0, 300) }; }
|
|
510
|
+
if (res.ok) return data;
|
|
511
|
+
const detail = typeof data.detail === "string" ? data.detail : JSON.stringify(data.detail);
|
|
512
|
+
if (![502, 503, 504].includes(res.status)) throw Object.assign(new Error(detail || `Upload failed (${res.status})`), { fatal: true });
|
|
513
|
+
last = new Error(detail || `Upload failed (${res.status})`);
|
|
514
|
+
} catch (e) {
|
|
515
|
+
if (e.fatal) throw e;
|
|
516
|
+
last = e;
|
|
517
|
+
}
|
|
518
|
+
log(`upload attempt ${attempt + 1} failed (${last.message}); retrying…`);
|
|
519
|
+
await new Promise((r) => setTimeout(r, 5000 * (attempt + 1)));
|
|
520
|
+
}
|
|
521
|
+
throw last;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
// ------------------------------------------------------------------ report
|
|
525
|
+
const where = (i) => {
|
|
526
|
+
const l = i.location || {};
|
|
527
|
+
if (l.path) return l.path + (l.line ? `:${l.line}` : "");
|
|
528
|
+
return i.domain || l.domain || "";
|
|
529
|
+
};
|
|
530
|
+
|
|
531
|
+
export function report(result, payload) {
|
|
532
|
+
const lines = [];
|
|
533
|
+
const mode = result.preview
|
|
534
|
+
? `PREVIEW of branch ${result.branch} (default branch is ${result.default_branch}; issue status changes only when the default branch is scanned)`
|
|
535
|
+
: result.baseline ? "baseline (first scan of this repo)" : "issues updated";
|
|
536
|
+
lines.push(`Arvyx code scan of ${result.repo} — ${mode}.`);
|
|
537
|
+
if (payload.change) lines.push(`What changed vs ${payload.change.base}: ${payload.change.files_changed} file(s) — ${payload.change.categories.join(", ") || "nothing"}.`);
|
|
538
|
+
const sev = result.open_by_severity || {};
|
|
539
|
+
lines.push(`${result.open} open issue(s) [critical ${sev.critical || 0}, high ${sev.high || 0}, medium ${sev.medium || 0}, low ${sev.low || 0}] · ${result.new} new · ${result.fixed} ${result.preview ? "would be fixed" : "fixed"} · ${result.reopened} reopened` +
|
|
540
|
+
(result.regressions ? ` (${result.regressions} REGRESSION${result.regressions === 1 ? "" : "S"}: fixed before, back again)` : "") + ".");
|
|
541
|
+
const missing = Object.entries(payload.tools).filter(([, s]) => s.status !== "ok");
|
|
542
|
+
for (const [t, s] of missing) lines.push(` ! ${t} ${s.status}${s.detail ? `: ${s.detail}` : ""}`);
|
|
543
|
+
if (missing.length) lines.push(" (Checks from a missing or failed engine are not assessed, and its existing issues stay open.)");
|
|
544
|
+
if (result.fixed_issues?.length) {
|
|
545
|
+
lines.push("", result.preview ? "Would fix (verified when the default branch is scanned):" : "Verified fixed:");
|
|
546
|
+
for (const i of result.fixed_issues.slice(0, 15)) lines.push(` ✓ [${i.severity}] ${i.title} ${where(i)}`);
|
|
547
|
+
}
|
|
548
|
+
if (result.new_issues?.length) {
|
|
549
|
+
lines.push("", "New:");
|
|
550
|
+
for (const i of result.new_issues.slice(0, 20))
|
|
551
|
+
lines.push(` ${i.regression ? "↺ REGRESSION" : "+"} [${i.severity}] ${i.title} ${where(i)}${i.id ? ` (id ${i.id})` : ""}`);
|
|
552
|
+
}
|
|
553
|
+
const top = (result.issues || []).filter((i) => !(result.new_issues || []).some((n) => n.id && n.id === i.id)).slice(0, 15);
|
|
554
|
+
if (top.length) {
|
|
555
|
+
lines.push("", "Open:");
|
|
556
|
+
for (const i of top) lines.push(` - [${i.severity}] ${i.title} ${where(i)}${i.id ? ` (id ${i.id})` : ""}`);
|
|
557
|
+
}
|
|
558
|
+
if (result.brief?.items?.length) {
|
|
559
|
+
lines.push("", `AI summary (${result.brief.model}; explains the issues above, never changes their status):`, ` ${result.brief.headline}`);
|
|
560
|
+
result.brief.items.forEach((it, n) => lines.push(` ${n + 1}. ${it.title} — ${it.why_now} First step: ${it.fix_hint}`));
|
|
561
|
+
}
|
|
562
|
+
if (result.dashboard_url) lines.push("", `Dashboard: ${result.dashboard_url}`);
|
|
563
|
+
return lines.join("\n");
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
const RANK = ["informational", "low", "medium", "high", "critical"];
|
|
567
|
+
export function shouldFail(result, threshold) {
|
|
568
|
+
if (!threshold || threshold === "none") return false;
|
|
569
|
+
const min = RANK.indexOf(threshold);
|
|
570
|
+
return (result.new_issues || []).some((i) => RANK.indexOf(i.severity) >= min);
|
|
571
|
+
}
|