@arvyx/sentinel-mcp 0.0.0-stage → 0.2.1

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,66 @@
1
- # Temporary Holding Version
1
+ # Sentinel MCP & scanner — `@arvyx/sentinel-mcp`
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
+ Security for the apps you build with AI, inside Claude Code, Codex and CI.
4
+
5
+ **The loop:** your agent builds → Sentinel scans (code + live site) → the agent fixes → Sentinel verifies.
6
+
7
+ ## What it scans
8
+
9
+ | Engine | Finds | Install |
10
+ |---|---|---|
11
+ | Sentinel checks (built in) | Supabase tables without RLS and policies that let anyone change data (`using (true)` on insert/update/delete), open Firebase rules, committed / un-ignored `.env` files, secrets in `NEXT_PUBLIC_` / `VITE_` / `EXPO_PUBLIC_` variables, missing security headers | nothing |
12
+ | [Trivy](https://github.com/aquasecurity/trivy) | Vulnerable dependencies (grouped per package, with the upgrade target), Dockerfile / Terraform / Kubernetes misconfig, dependency inventory | `brew install trivy` |
13
+ | [Gitleaks](https://github.com/gitleaks/gitleaks) | Secrets in files **and in git history** | `brew install gitleaks` |
14
+ | [Opengrep](https://github.com/opengrep/opengrep) | Insecure code (Sentinel's own rules in `rules/sentinel.yml`): request input flowing into SQL, shell commands, eval or deserialization (taint tracking, JS/TS + Python), unsafe HTML, open redirects, hard-coded / unverified JWTs, Supabase service key in client code, CORS, weak hashes | see Opengrep's install script |
15
+
16
+ Scanning runs **on your machine or CI runner**. Only results are uploaded — tool, rule, file, line, package
17
+ and versions. Never your code, never a secret value, never commit author details. A missing engine is
18
+ reported as "not installed" and its existing issues are left open (never silently passed).
19
+
20
+ Results become **issues** in Sentinel. An issue keeps its history, closes automatically when a scan of the
21
+ default branch no longer sees it, and reopens if it returns. Scans of other branches (PRs, feature
22
+ branches) are **previews**: they report what would be new or fixed without changing anything.
23
+
24
+ ## Setup
25
+
26
+ Create an API key in Sentinel → **Settings → API keys** (shown once).
27
+
28
+ **Claude Code**
29
+ ```bash
30
+ claude mcp add sentinel --env SENTINEL_API_KEY=YOUR_KEY -- npx -y @arvyx/sentinel-mcp
31
+ ```
32
+
33
+ **Codex** (`~/.codex/config.toml`)
34
+ ```toml
35
+ [mcp_servers.sentinel]
36
+ command = "npx"
37
+ args = ["-y", "@arvyx/sentinel-mcp"]
38
+ env = { SENTINEL_API_KEY = "YOUR_KEY" }
39
+ ```
40
+
41
+ **Terminal / any CI**
42
+ ```bash
43
+ SENTINEL_API_KEY=YOUR_KEY npx -y -p @arvyx/sentinel-mcp sentinel-scan [path] [--fail-on high] [--json] [--no-upload]
44
+ ```
45
+ Exit codes: `0` ok · `1` new issues at/above `--fail-on` · `2` error.
46
+
47
+ **GitHub Actions:** copy the workflow from Sentinel → Settings → Connect → CI. It installs pinned,
48
+ checksum-verified scanners; pushes to the default branch update issues, pull requests get a preview and
49
+ fail only on new high/critical issues, and a weekly run catches newly published CVEs.
50
+
51
+ ## Tools
52
+
53
+ | Tool | What it does |
54
+ |---|---|
55
+ | `sentinel_code_scan` | Scan this repo (dependencies, secrets incl. history, code, config) and update issues |
56
+ | `sentinel_issues` | Open issues for this repo — code plus the live domains linked to its project |
57
+ | `sentinel_issue` | One issue in full: evidence, impact, exact fix |
58
+ | `sentinel_mark_fix_submitted` | Tell Sentinel you fixed it; the next scan confirms or reopens |
59
+ | `sentinel_scan` / `sentinel_verify` | Scan / re-scan a verified live domain (add `active_testing` for SQLi probes) |
60
+ | `sentinel_findings` / `sentinel_fix` | Findings of a live scan and their detail |
61
+ | `sentinel_report_events` | Send app security events for abuse detection |
62
+ | `sentinel_deepconfirm` | Sandbox exploit confirmation of a connected repo |
63
+
64
+ Env: `SENTINEL_API_KEY` (required), `SENTINEL_API_URL` (default: hosted API),
65
+ `SENTINEL_TRIVY` / `SENTINEL_GITLEAKS` / `SENTINEL_OPENGREP` (binary paths), `SENTINEL_REPO`,
66
+ `SENTINEL_BRANCH`, `SENTINEL_DEFAULT_BRANCH` (overrides for unusual setups). Node 18+.
package/cli.js ADDED
@@ -0,0 +1,56 @@
1
+ #!/usr/bin/env node
2
+ // sentinel-scan: scan a repository on this machine and upload the results to Sentinel.
3
+ // npx -y -p @arvyx/sentinel-mcp sentinel-scan [path] [--fail-on high] [--trigger ci] [--json] [--no-upload]
4
+ // Exit codes: 0 ok · 1 new issues at/above --fail-on · 2 error.
5
+ import { report, scan, shouldFail, upload } from "./scan.js";
6
+
7
+ const args = process.argv.slice(2);
8
+ const flag = (name) => args.includes(`--${name}`);
9
+ const opt = (name, dflt) => { const i = args.indexOf(`--${name}`); return i >= 0 && args[i + 1] ? args[i + 1] : dflt; };
10
+ const valued = new Set(["--fail-on", "--trigger"]);
11
+ const dir = args.find((a, i) => !a.startsWith("--") && !valued.has(args[i - 1])) || process.cwd();
12
+
13
+ if (flag("help")) {
14
+ console.log(`sentinel-scan [path] [options]
15
+
16
+ Scans dependencies (trivy), secrets incl. git history (gitleaks), code patterns (opengrep) and
17
+ Sentinel's own checks (Supabase RLS, Firebase rules, .env hygiene, public env secrets, headers),
18
+ then uploads results (never code or secret values) to your Sentinel organization.
19
+
20
+ --fail-on <sev> exit 1 if the scan finds NEW issues at or above: critical|high|medium|low|none (default none)
21
+ --trigger <t> cli | ci | mcp (default cli)
22
+ --json print the raw JSON response
23
+ --no-upload scan only, print the local results as JSON
24
+
25
+ Env: SENTINEL_API_KEY (required to upload), SENTINEL_API_URL, SENTINEL_TRIVY/GITLEAKS/OPENGREP (binary paths)`);
26
+ process.exit(0);
27
+ }
28
+
29
+ const log = (m) => console.error(`[sentinel] ${m}`);
30
+
31
+ // Returns the exit code. The caller sets process.exitCode (never process.exit), so piped stdout is
32
+ // fully flushed before Node exits.
33
+ async function main() {
34
+ const payload = await scan(dir, { trigger: opt("trigger", process.env.CI ? "ci" : "cli"), log });
35
+ if (flag("no-upload")) {
36
+ console.log(JSON.stringify(payload, null, 2));
37
+ return 0;
38
+ }
39
+ const key = process.env.SENTINEL_API_KEY;
40
+ if (!key) {
41
+ log("SENTINEL_API_KEY is not set. Create one in Sentinel (Settings → API keys), or use --no-upload.");
42
+ return 2;
43
+ }
44
+ const base = process.env.SENTINEL_API_URL || "https://sentinel-api-maa1.onrender.com";
45
+ log(`uploading ${payload.findings.length} result(s) for ${payload.repo}…`);
46
+ const result = await upload(payload, { base, key, log });
47
+ console.log(flag("json") ? JSON.stringify(result, null, 2) : report(result, payload));
48
+ const failOn = opt("fail-on", "none");
49
+ if (shouldFail(result, failOn)) {
50
+ log(`failing: new issue(s) at or above "${failOn}".`);
51
+ return 1;
52
+ }
53
+ return 0;
54
+ }
55
+
56
+ process.exitCode = await main().catch((e) => { log(`error: ${e.message}`); return 2; });
package/index.js ADDED
@@ -0,0 +1,258 @@
1
+ #!/usr/bin/env node
2
+ // Sentinel MCP server. Gives Claude Code / Codex tools to scan the code they are working on
3
+ // (dependencies, secrets, code patterns, config — scanned locally, only results uploaded), scan
4
+ // the live domains the user has verified, read persistent issues with their fixes, and verify.
5
+ // Auth is a single per-organization API key (SENTINEL_API_KEY); it can reach only the
6
+ // /api/mcp/* endpoints, and only the caller's own organization.
7
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
8
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
9
+ import { z } from "zod";
10
+ import { repoFromRemote, report, scan, upload } from "./scan.js";
11
+ import { execFileSync } from "node:child_process";
12
+
13
+ const BASE = (process.env.SENTINEL_API_URL || "https://sentinel-api-maa1.onrender.com").replace(/\/$/, "");
14
+ const KEY = process.env.SENTINEL_API_KEY;
15
+ if (!KEY) {
16
+ console.error("SENTINEL_API_KEY is not set. Create one in the Sentinel dashboard (Settings → API keys) and pass it as an environment variable.");
17
+ process.exit(1);
18
+ }
19
+
20
+ async function call(method, path, body) {
21
+ const res = await fetch(BASE + path, {
22
+ method,
23
+ headers: { Authorization: `Bearer ${KEY}`, ...(body ? { "Content-Type": "application/json" } : {}) },
24
+ body: body ? JSON.stringify(body) : undefined,
25
+ });
26
+ const text = await res.text();
27
+ let data;
28
+ try { data = text ? JSON.parse(text) : {}; } catch { data = { detail: text }; }
29
+ if (!res.ok) {
30
+ const d = data.detail;
31
+ throw new Error(typeof d === "string" ? d : d ? JSON.stringify(d) : `Request failed (${res.status})`);
32
+ }
33
+ return data;
34
+ }
35
+
36
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
37
+
38
+ // Start a scan (or verify), then poll until the assessment finishes.
39
+ async function runScan(path, target, active = false) {
40
+ const { scan_id } = await call("POST", path, { target, active_testing: active });
41
+ const deadline = Date.now() + (active ? 300000 : 120000); // active scans crawl + probe inputs
42
+ while (Date.now() < deadline) {
43
+ const s = await call("GET", `/api/mcp/scan/${scan_id}`);
44
+ if (s.status === "completed") {
45
+ return { scan_id, summary: s.summary, findings: await call("GET", `/api/mcp/scan/${scan_id}/findings`) };
46
+ }
47
+ if (s.status === "failed") throw new Error(s.error || "The scan failed.");
48
+ await sleep(2500);
49
+ }
50
+ throw new Error(`Scan ${scan_id} is still running. Call sentinel_findings with this scan_id in a moment.`);
51
+ }
52
+
53
+ function summarize({ scan_id, summary, findings }) {
54
+ const sev = summary?.findings_by_severity || {};
55
+ const head =
56
+ `Scan ${scan_id} — grade ${summary?.grade ?? "?"} (${summary?.score ?? "?"}/100). ` +
57
+ `${summary?.total_findings ?? findings.length} findings ` +
58
+ `[critical ${sev.critical || 0}, high ${sev.high || 0}, medium ${sev.medium || 0}, low ${sev.low || 0}].`;
59
+ const lines = findings.map((f) => `- [${f.severity}] ${f.title} (id ${f.id})\n Fix: ${f.remediation}`);
60
+ return head + (lines.length ? "\n\n" + lines.join("\n") : "\n\nNo findings.");
61
+ }
62
+
63
+ const ok = (text) => ({ content: [{ type: "text", text }] });
64
+ const err = (text) => ({ content: [{ type: "text", text }], isError: true });
65
+
66
+ const server = new McpServer({ name: "sentinel", version: "0.2.0" }, {
67
+ instructions: "Sentinel finds security problems in the app you are building. Workflow: run sentinel_code_scan " +
68
+ "after changing dependencies, auth, database migrations, env/config files or API routes, and before finishing a " +
69
+ "task. Fix the issues it reports (sentinel_issue gives the evidence and the fix), call " +
70
+ "sentinel_mark_fix_submitted for each, then run sentinel_code_scan again: only a scan marks an issue fixed. " +
71
+ "For the deployed site use sentinel_scan / sentinel_verify on the verified domain. Never print or commit secret values.",
72
+ });
73
+
74
+ const where = (i) => {
75
+ const l = i.location || {};
76
+ return l.path ? l.path + (l.line ? `:${l.line}` : "") : (i.domain || l.domain || "");
77
+ };
78
+
79
+ function currentRepo() {
80
+ try {
81
+ const url = execFileSync("git", ["remote", "get-url", "origin"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
82
+ return repoFromRemote(url);
83
+ } catch { return null; }
84
+ }
85
+
86
+ server.registerTool(
87
+ "sentinel_scan",
88
+ {
89
+ description: "Run a Sentinel security assessment of a domain or URL your organization has verified. Returns a letter grade and findings with concrete fixes. Set active_testing to also run active checks (e.g. SQL injection probes that send crafted input) — non-destructive, proof-of-exposure only.",
90
+ inputSchema: {
91
+ target: z.string().describe("A domain or URL you have verified in Sentinel, e.g. example.com"),
92
+ active_testing: z.boolean().optional().describe("Also run active checks such as SQL injection detection (sends crafted input). Default false."),
93
+ },
94
+ },
95
+ async ({ target, active_testing }) => {
96
+ try { return ok(summarize(await runScan("/api/mcp/scan", target, !!active_testing))); }
97
+ catch (e) { return err(`Sentinel scan failed: ${e.message}`); }
98
+ },
99
+ );
100
+
101
+ server.registerTool(
102
+ "sentinel_findings",
103
+ {
104
+ description: "List the findings (with fixes) for a previous Sentinel scan id.",
105
+ inputSchema: { scan_id: z.string() },
106
+ },
107
+ async ({ scan_id }) => {
108
+ try {
109
+ const f = await call("GET", `/api/mcp/scan/${scan_id}/findings`);
110
+ return ok(f.length ? f.map((x) => `- [${x.severity}] ${x.title} (id ${x.id})\n Fix: ${x.remediation}`).join("\n") : "No findings for this scan.");
111
+ } catch (e) { return err(`Could not read findings: ${e.message}`); }
112
+ },
113
+ );
114
+
115
+ server.registerTool(
116
+ "sentinel_fix",
117
+ {
118
+ description: "Get the full detail, evidence and remediation for one Sentinel finding so you can fix it in the codebase.",
119
+ inputSchema: { finding_id: z.string() },
120
+ },
121
+ async ({ finding_id }) => {
122
+ try {
123
+ const f = await call("GET", `/api/mcp/findings/${finding_id}`);
124
+ return ok(`[${f.severity}] ${f.title}\n\nWhat it is: ${f.description}\n\nWhy it matters: ${f.business_impact}\n\nFix: ${f.remediation}\n\nEvidence: ${JSON.stringify(f.evidence)}`);
125
+ } catch (e) { return err(`Could not read finding: ${e.message}`); }
126
+ },
127
+ );
128
+
129
+ server.registerTool(
130
+ "sentinel_verify",
131
+ {
132
+ description: "Re-scan a verified domain to confirm that fixes landed. Returns the new grade and any remaining findings. Set active_testing to re-run active checks (e.g. to confirm a SQL injection fix).",
133
+ inputSchema: {
134
+ target: z.string().describe("A domain or URL you have verified in Sentinel"),
135
+ active_testing: z.boolean().optional().describe("Also re-run active checks such as SQL injection detection. Default false."),
136
+ },
137
+ },
138
+ async ({ target, active_testing }) => {
139
+ try { return ok(summarize(await runScan("/api/mcp/verify", target, !!active_testing))); }
140
+ catch (e) { return err(`Sentinel verify failed: ${e.message}`); }
141
+ },
142
+ );
143
+
144
+ server.registerTool(
145
+ "sentinel_report_events",
146
+ {
147
+ description: "Report security events from your app (failed logins, requests) so Sentinel can detect abuse — credential stuffing and abnormal request volume from one source — and alert you. Source IPs are hashed; no request bodies or secrets are stored.",
148
+ inputSchema: {
149
+ target: z.string().describe("A domain you have verified in Sentinel"),
150
+ events: z.array(z.object({
151
+ type: z.string().describe("Event type: failed_login, request, error, …"),
152
+ ip: z.string().optional().describe("Source IP (stored only as a hash)"),
153
+ endpoint: z.string().optional().describe("Request path"),
154
+ status: z.number().optional().describe("HTTP status code"),
155
+ at: z.string().optional().describe("ISO timestamp; defaults to now"),
156
+ })).describe("A batch of events (max 500)"),
157
+ },
158
+ },
159
+ async ({ target, events }) => {
160
+ try {
161
+ const r = await call("POST", "/api/mcp/events", { target, events });
162
+ return ok(`Reported ${r.ingested} event(s); ${r.alerts} new alert(s) raised.`);
163
+ } catch (e) { return err(`Could not report events: ${e.message}`); }
164
+ },
165
+ );
166
+
167
+ server.registerTool(
168
+ "sentinel_deepconfirm",
169
+ {
170
+ description: "Deep-confirm a connected GitHub repo in an isolated sandbox VM: Sentinel boots your app, provisions a synthetic database with a hidden canary, and PROVES whether a SQL injection can actually read data — then destroys the VM. Read-only, synthetic data only, never your production. Connect your GitHub in Sentinel first.",
171
+ inputSchema: { repo: z.string().describe("owner/name of a repo on your connected GitHub, e.g. alice/myapp") },
172
+ },
173
+ async ({ repo }) => {
174
+ try {
175
+ const { run_id } = await call("POST", "/api/mcp/deepconfirm", { repo });
176
+ const deadline = Date.now() + 420000; // sandbox runs take minutes
177
+ while (Date.now() < deadline) {
178
+ const s = await call("GET", `/api/mcp/deepconfirm/${run_id}`);
179
+ if (s.status === "completed") {
180
+ const v = s.verdict || {};
181
+ return ok(v.confirmed
182
+ ? `CONFIRMED exploitable on ${repo}: ${v.technique || "SQL injection"}. ${v.evidence || ""}`
183
+ : `Not confirmed on ${repo}: ${v.evidence || "no exploitable path found in the sandbox"}.`);
184
+ }
185
+ if (s.status === "failed") throw new Error(s.error || "the deep-confirm run failed");
186
+ await sleep(6000);
187
+ }
188
+ return ok(`Deep-confirm ${run_id} is still running; try again shortly.`);
189
+ } catch (e) { return err(`Deep-confirm failed: ${e.message}`); }
190
+ },
191
+ );
192
+
193
+ server.registerTool(
194
+ "sentinel_code_scan",
195
+ {
196
+ description: "Scan the code in this repository for security issues: vulnerable dependencies (trivy), secrets in files and git history (gitleaks), insecure code patterns (opengrep), and Sentinel's checks for AI-built stacks (Supabase tables without RLS, open Firebase rules, committed .env files, secrets in NEXT_PUBLIC_/VITE_ variables, missing security headers). Runs locally; only results (never code or secret values) are sent to Sentinel, which tracks them as issues. Re-run after fixing to verify — issues close only when a scan no longer sees them. Scans of a non-default branch are previews.",
197
+ inputSchema: { path: z.string().optional().describe("Repository directory. Default: the current project.") },
198
+ },
199
+ async ({ path }) => {
200
+ try {
201
+ const payload = await scan(path || process.cwd(), { trigger: "mcp" });
202
+ const result = await upload(payload, { base: BASE, key: KEY });
203
+ return ok(report(result, payload) + "\n\nUse sentinel_issue <id> for evidence and the exact fix.");
204
+ } catch (e) { return err(`Sentinel code scan failed: ${e.message}`); }
205
+ },
206
+ );
207
+
208
+ server.registerTool(
209
+ "sentinel_issues",
210
+ {
211
+ description: "List the open Sentinel issues for this repository — code issues plus live-site issues of the domains linked to its project — most severe first.",
212
+ inputSchema: {
213
+ repo: z.string().optional().describe("owner/name. Default: this repository's git remote."),
214
+ status: z.string().optional().describe("Comma-separated: open, fix_submitted, fixed, accepted_risk, false_positive. Default open,fix_submitted."),
215
+ },
216
+ },
217
+ async ({ repo, status }) => {
218
+ try {
219
+ const r = repo || currentRepo();
220
+ const q = new URLSearchParams({ ...(r ? { repo: r } : {}), ...(status ? { status } : {}) });
221
+ const list = await call("GET", `/api/mcp/issues?${q}`);
222
+ if (!list.length) return ok(`No ${status || "open"} issues${r ? ` for ${r}` : ""}.`);
223
+ return ok(list.map((i) => `- [${i.severity}] ${i.title} ${where(i)} (${i.status}, id ${i.id})`).join("\n"));
224
+ } catch (e) { return err(`Could not list issues: ${e.message}`); }
225
+ },
226
+ );
227
+
228
+ server.registerTool(
229
+ "sentinel_issue",
230
+ {
231
+ description: "Get one Sentinel issue in full — what it is, why it matters, the evidence and exactly how to fix it — so you can fix it in the codebase.",
232
+ inputSchema: { issue_id: z.string() },
233
+ },
234
+ async ({ issue_id }) => {
235
+ try {
236
+ const i = await call("GET", `/api/mcp/issues/${issue_id}`);
237
+ return ok(`[${i.severity}, ${i.status}] ${i.title}\nWhere: ${where(i)}\n\nWhat it is: ${i.description}\n\n` +
238
+ `Why it matters: ${i.business_impact}\n\nFix: ${i.remediation}\n\nLocation: ${JSON.stringify(i.location)}\n` +
239
+ `Evidence: ${JSON.stringify(i.evidence)}\nFirst seen ${i.first_seen_at}, last seen ${i.last_seen_at}.`);
240
+ } catch (e) { return err(`Could not read issue: ${e.message}`); }
241
+ },
242
+ );
243
+
244
+ server.registerTool(
245
+ "sentinel_mark_fix_submitted",
246
+ {
247
+ description: "Tell Sentinel you have fixed an open issue. It moves to 'fix submitted'; the next scan confirms it (fixed) or reopens it. Only call this after making the change.",
248
+ inputSchema: { issue_id: z.string() },
249
+ },
250
+ async ({ issue_id }) => {
251
+ try {
252
+ await call("POST", `/api/mcp/issues/${issue_id}/fix-submitted`);
253
+ return ok(`Issue ${issue_id} marked fix submitted. Run sentinel_code_scan (code) or sentinel_verify (live site) to confirm.`);
254
+ } catch (e) { return err(`Could not update issue: ${e.message}`); }
255
+ },
256
+ );
257
+
258
+ await server.connect(new StdioServerTransport());
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "@arvyx/sentinel-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.1",
4
+ "description": "Sentinel by Arvyx \u2014 security scanning for the apps you build with AI, inside Claude Code / Codex and CI.",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "bin": {
8
+ "sentinel-mcp": "index.js",
9
+ "sentinel-scan": "cli.js"
10
+ },
11
+ "files": [
12
+ "index.js",
13
+ "cli.js",
14
+ "scan.js",
15
+ "rules/",
16
+ "README.md"
17
+ ],
18
+ "engines": {
19
+ "node": ">=18"
20
+ },
21
+ "license": "UNLICENSED",
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "dependencies": {
26
+ "@modelcontextprotocol/sdk": "^1.18.0",
27
+ "zod": "^3.23.8"
28
+ },
29
+ "scripts": {
30
+ "test:rules": "node test/score_rules.mjs"
31
+ }
32
+ }
@@ -0,0 +1,393 @@
1
+ # Sentinel SAST rules (Opengrep / Semgrep-compatible syntax). Written by Arvyx for Sentinel; no
2
+ # third-party rule registry content. Focus: the high-impact mistakes common in AI-generated apps.
3
+ # Severity: ERROR = high, WARNING = medium, INFO = low (capped server-side by CODE_INSECURE_PATTERN).
4
+ rules:
5
+ # ------------------------------------------------------------------ SQL injection
6
+ - id: sql-built-from-template-literal
7
+ languages: [javascript, typescript]
8
+ severity: ERROR
9
+ message: >-
10
+ SQL is built by interpolating values into a template string. If any value comes from the request,
11
+ an attacker can change the query. Pass values as parameters ($1 / ?) or use the query builder.
12
+ metadata: {title: "SQL query built with string interpolation", cwe: ["CWE-89"]}
13
+ patterns:
14
+ - pattern-either:
15
+ - pattern: $DB.query(`...${$X}...`, ...)
16
+ - pattern: $DB.execute(`...${$X}...`, ...)
17
+ - pattern: $DB.$queryRawUnsafe(`...${$X}...`, ...)
18
+ - pattern: $DB.$executeRawUnsafe(`...${$X}...`, ...)
19
+ - pattern: $DB.raw(`...${$X}...`, ...)
20
+ - pattern: $DB.unsafe(`...${$X}...`, ...)
21
+ - id: sql-built-by-concatenation
22
+ languages: [javascript, typescript]
23
+ severity: ERROR
24
+ message: >-
25
+ SQL is built by concatenating strings. If any part comes from the request, an attacker can change the
26
+ query. Pass values as parameters ($1 / ?) instead.
27
+ metadata: {title: "SQL query built by string concatenation", cwe: ["CWE-89"]}
28
+ patterns:
29
+ - pattern-either:
30
+ - pattern: $DB.query($Q, ...)
31
+ - pattern: $DB.execute($Q, ...)
32
+ - pattern: $DB.raw($Q, ...)
33
+ - pattern: $DB.$queryRawUnsafe($Q, ...)
34
+ - pattern: $DB.$executeRawUnsafe($Q, ...)
35
+ - metavariable-pattern:
36
+ metavariable: $Q
37
+ patterns:
38
+ - pattern-either:
39
+ - pattern: '"..." + $X'
40
+ - pattern: '$X + "..."'
41
+ - pattern-not: '"..." + "..."'
42
+ - id: python-sql-formatted
43
+ languages: [python]
44
+ severity: ERROR
45
+ message: >-
46
+ SQL is built with an f-string, % or + formatting. If any value comes from the request, an attacker can
47
+ change the query. Use parameters: cursor.execute("... WHERE id = %s", (value,)).
48
+ metadata: {title: "SQL query built with string formatting", cwe: ["CWE-89"]}
49
+ pattern-either:
50
+ - pattern: $C.execute(f"...", ...)
51
+ - pattern: $C.execute("..." % $X, ...)
52
+ - pattern: $C.execute("..." + $X, ...)
53
+ - pattern: $C.execute("...".format(...), ...)
54
+ - pattern: $C.executemany(f"...", ...)
55
+ - pattern: sqlalchemy.text(f"...")
56
+ - pattern: text(f"...")
57
+
58
+ # ------------------------------------------------------------------ command / code injection
59
+ - id: shell-command-from-string
60
+ languages: [javascript, typescript]
61
+ severity: ERROR
62
+ message: >-
63
+ A shell command is built from a string with interpolated values. If a value comes from a user, they can
64
+ run arbitrary commands on your server. Use execFile/spawn with an argument array.
65
+ metadata: {title: "Shell command built from a string", cwe: ["CWE-78"]}
66
+ pattern-either:
67
+ - pattern: $CP.exec(`...${$X}...`, ...)
68
+ - pattern: $CP.execSync(`...${$X}...`, ...)
69
+ - pattern: $CP.exec("..." + $X, ...)
70
+ - pattern: $CP.execSync("..." + $X, ...)
71
+ - pattern: exec(`...${$X}...`, ...)
72
+ - pattern: execSync(`...${$X}...`, ...)
73
+ - id: python-shell-true
74
+ languages: [python]
75
+ severity: ERROR
76
+ message: >-
77
+ subprocess runs with shell=True. If any part of the command comes from a user, they can run arbitrary
78
+ commands. Pass an argument list and drop shell=True.
79
+ metadata: {title: "subprocess with shell=True", cwe: ["CWE-78"]}
80
+ pattern-either:
81
+ - pattern: subprocess.$F(..., shell=True, ...)
82
+ - pattern: os.system($X)
83
+ - id: eval-of-dynamic-code
84
+ languages: [javascript, typescript]
85
+ severity: ERROR
86
+ message: >-
87
+ eval / new Function runs a string as code. If the string can contain user input, an attacker can run
88
+ code in your app. Parse data with JSON.parse or use a lookup table instead.
89
+ metadata: {title: "Dynamic code evaluation", cwe: ["CWE-94"]}
90
+ patterns:
91
+ - pattern-either:
92
+ - pattern: eval($X)
93
+ - pattern: new Function(..., $X)
94
+ - pattern-not: eval("...")
95
+ - pattern-not: new Function("...")
96
+ - id: python-unsafe-deserialization
97
+ languages: [python]
98
+ severity: ERROR
99
+ message: >-
100
+ pickle / yaml.load can execute code while loading. Never load untrusted data with them; use json, or
101
+ yaml.safe_load.
102
+ metadata: {title: "Unsafe deserialization", cwe: ["CWE-502"]}
103
+ pattern-either:
104
+ - pattern: pickle.loads(...)
105
+ - pattern: pickle.load(...)
106
+ - patterns:
107
+ - pattern: yaml.load(...)
108
+ - pattern-not: yaml.load(..., Loader=yaml.SafeLoader, ...)
109
+ - pattern-not: yaml.load(..., Loader=SafeLoader, ...)
110
+
111
+ # ------------------------------------------------------------------ XSS / redirects
112
+ - id: react-dangerously-set-inner-html
113
+ languages: [javascript, typescript]
114
+ severity: WARNING
115
+ message: >-
116
+ HTML from a variable is rendered with dangerouslySetInnerHTML. If it can contain user content, it can
117
+ run scripts in your users' browsers (stealing sessions). Sanitize it (DOMPurify) or render text.
118
+ metadata: {title: "Unsanitized HTML rendered in React", cwe: ["CWE-79"]}
119
+ patterns:
120
+ - pattern: '<$EL dangerouslySetInnerHTML={{__html: $X}} />'
121
+ - pattern-not: '<$EL dangerouslySetInnerHTML={{__html: "..."}} />'
122
+ - pattern-not: '<$EL dangerouslySetInnerHTML={{__html: DOMPurify.sanitize(...)}} />'
123
+ - pattern-not: '<$EL dangerouslySetInnerHTML={{__html: sanitize(...)}} />'
124
+ - id: open-redirect-from-request
125
+ languages: [javascript, typescript]
126
+ severity: WARNING
127
+ message: >-
128
+ The app redirects to a URL taken from the request. Attackers use this to send your users to phishing
129
+ pages under your domain. Only redirect to relative paths or an allow-list.
130
+ metadata: {title: "Open redirect", cwe: ["CWE-601"]}
131
+ pattern-either:
132
+ - pattern: $RES.redirect($REQ.query.$P)
133
+ - pattern: $RES.redirect($REQ.body.$P)
134
+ - pattern: redirect($REQ.nextUrl.searchParams.get(...))
135
+ - pattern: NextResponse.redirect(new URL($REQ.nextUrl.searchParams.get(...), ...))
136
+
137
+ # ------------------------------------------------------------------ auth & secrets in code
138
+ - id: jwt-hardcoded-secret
139
+ languages: [javascript, typescript]
140
+ severity: ERROR
141
+ message: >-
142
+ A JWT is signed or verified with a secret written in the code. Anyone who reads the code can forge
143
+ tokens and log in as any user. Load the secret from an environment variable.
144
+ metadata: {title: "JWT secret hard-coded", cwe: ["CWE-798"]}
145
+ pattern-either:
146
+ - pattern: $JWT.sign($P, "...", ...)
147
+ - pattern: $JWT.verify($T, "...", ...)
148
+ - id: jwt-decode-without-verify
149
+ languages: [javascript, typescript]
150
+ severity: WARNING
151
+ message: >-
152
+ jwt.decode() reads a token without checking its signature, so anyone can craft one. Use jwt.verify()
153
+ (or your auth provider's server helper) before trusting the token's claims.
154
+ metadata: {title: "JWT used without signature verification", cwe: ["CWE-347"]}
155
+ patterns:
156
+ - pattern: $JWT.decode($T, ...)
157
+ - metavariable-regex:
158
+ metavariable: $JWT
159
+ regex: ^(jwt|jws|jsonwebtoken|jose|JWT)$
160
+ - pattern-not-inside: $V.verify(...) && $JWT.decode(...)
161
+ - pattern-not-inside: |
162
+ $V.verify($T, ...);
163
+ ...
164
+ - pattern-not-inside: |
165
+ $X = $V.verify($T, ...);
166
+ ...
167
+ - pattern-not-inside: |
168
+ if (<... $V.verify(...) ...>) { ... }
169
+ - id: supabase-service-role-client-in-browser-code
170
+ languages: [javascript, typescript]
171
+ severity: ERROR
172
+ message: >-
173
+ A Supabase client is created with a service-role key in a file marked "use client". That key bypasses
174
+ Row Level Security and would ship to every visitor. Use the anon key in the browser; keep the service
175
+ key in server-only code.
176
+ metadata: {title: "Supabase service-role key used in client code", cwe: ["CWE-200"]}
177
+ patterns:
178
+ - pattern-inside: |
179
+ "use client";
180
+ ...
181
+ - pattern: createClient($URL, $KEY, ...)
182
+ - metavariable-regex:
183
+ metavariable: $KEY
184
+ regex: (?i).*service.?role.*
185
+ - id: cors-any-origin-with-credentials
186
+ languages: [javascript, typescript]
187
+ severity: WARNING
188
+ message: >-
189
+ CORS allows any origin while also allowing credentials. Browsers combined with origin reflection let any
190
+ website make logged-in requests to your API. List your trusted origins explicitly.
191
+ metadata: {title: "CORS allows any origin with credentials", cwe: ["CWE-942"]}
192
+ pattern-either:
193
+ - pattern: |
194
+ {..., "Access-Control-Allow-Origin": "*", ..., "Access-Control-Allow-Credentials": "true", ...}
195
+ - pattern: |
196
+ cors({..., origin: true, ..., credentials: true, ...})
197
+ - pattern: |
198
+ cors({..., origin: "*", ..., credentials: true, ...})
199
+
200
+ # ------------------------------------------------------------------ crypto
201
+ - id: weak-password-hash
202
+ languages: [javascript, typescript, python]
203
+ severity: WARNING
204
+ message: >-
205
+ MD5 / SHA-1 are fast hashes and unsafe for passwords or tokens. Use bcrypt, scrypt or argon2 for
206
+ passwords, and SHA-256+ elsewhere.
207
+ metadata: {title: "Weak hash algorithm", cwe: ["CWE-328"]}
208
+ pattern-either:
209
+ - pattern: crypto.createHash("md5")
210
+ - pattern: crypto.createHash("sha1")
211
+ - pattern: hashlib.md5(...)
212
+ - pattern: hashlib.sha1(...)
213
+
214
+ # ------------------------------------------------------------------ taint: request input -> dangerous call
215
+ # Follows user input through variables and string building (the usual shape of generated code:
216
+ # build a string first, run it later). Only the dangerous argument counts, so a parameterized
217
+ # query that receives user input as a bound value is not flagged.
218
+ - id: js-sql-injection-from-request
219
+ mode: taint
220
+ languages: [javascript, typescript]
221
+ severity: ERROR
222
+ message: >-
223
+ Request input reaches a SQL query string. An attacker can rewrite the query to read or change any data.
224
+ Pass the value as a bound parameter ($1 / ?) instead of building the SQL string.
225
+ metadata: {title: "SQL injection from request input", cwe: ["CWE-89"]}
226
+ pattern-sources:
227
+ - pattern-either:
228
+ - pattern: $REQ.body
229
+ - pattern: $REQ.query
230
+ - pattern: $REQ.params
231
+ - pattern: $REQ.cookies
232
+ - pattern: $REQ.headers
233
+ - pattern: $REQ.files
234
+ - pattern: await $REQ.json()
235
+ - pattern: $REQ.nextUrl.searchParams.get(...)
236
+ - pattern: $FORM.get(...)
237
+ pattern-sinks:
238
+ - patterns:
239
+ - pattern-either:
240
+ - pattern: $DB.query($Q, ...)
241
+ - pattern: $DB.execute($Q, ...)
242
+ - pattern: $DB.raw($Q, ...)
243
+ - pattern: $DB.unsafe($Q, ...)
244
+ - pattern: $DB.$queryRawUnsafe($Q, ...)
245
+ - pattern: $DB.$executeRawUnsafe($Q, ...)
246
+ - focus-metavariable: $Q
247
+ - id: js-command-injection-from-request
248
+ mode: taint
249
+ languages: [javascript, typescript]
250
+ severity: ERROR
251
+ message: >-
252
+ Request input reaches a shell command. An attacker can run any command on your server. Use
253
+ execFile/spawn with an argument array and validate the input.
254
+ metadata: {title: "Command injection from request input", cwe: ["CWE-78"]}
255
+ pattern-sources:
256
+ - pattern-either:
257
+ - pattern: $REQ.body
258
+ - pattern: $REQ.query
259
+ - pattern: $REQ.params
260
+ - pattern: $REQ.cookies
261
+ - pattern: $REQ.headers
262
+ - pattern: $REQ.files
263
+ - pattern: await $REQ.json()
264
+ - pattern: $REQ.nextUrl.searchParams.get(...)
265
+ - pattern: $FORM.get(...)
266
+ pattern-sinks:
267
+ - patterns:
268
+ - pattern-either:
269
+ - pattern: exec($CMD, ...)
270
+ - pattern: execSync($CMD, ...)
271
+ - pattern: $CP.exec($CMD, ...)
272
+ - pattern: $CP.execSync($CMD, ...)
273
+ - focus-metavariable: $CMD
274
+ - id: js-code-injection-from-request
275
+ mode: taint
276
+ languages: [javascript, typescript]
277
+ severity: ERROR
278
+ message: >-
279
+ Request input is evaluated or deserialized as code (eval, Function, vm, math evaluators,
280
+ node-serialize). An attacker can run code inside your app. Never evaluate user input; parse data with
281
+ JSON.parse.
282
+ metadata: {title: "Code injection from request input", cwe: ["CWE-94"]}
283
+ pattern-sources:
284
+ - pattern-either:
285
+ - pattern: $REQ.body
286
+ - pattern: $REQ.query
287
+ - pattern: $REQ.params
288
+ - pattern: $REQ.cookies
289
+ - pattern: $REQ.headers
290
+ - pattern: $REQ.files
291
+ - pattern: await $REQ.json()
292
+ - pattern: $REQ.nextUrl.searchParams.get(...)
293
+ - pattern: $FORM.get(...)
294
+ pattern-sinks:
295
+ - patterns:
296
+ - pattern-either:
297
+ - pattern: eval($X)
298
+ - pattern: new Function(..., $X)
299
+ - pattern: $M.eval($X, ...)
300
+ - pattern: $M.evaluate($X, ...)
301
+ - pattern: vm.$RUN($X, ...)
302
+ - pattern: $S.unserialize($X, ...)
303
+ - focus-metavariable: $X
304
+ - id: python-sql-injection-from-request
305
+ mode: taint
306
+ languages: [python]
307
+ severity: ERROR
308
+ message: >-
309
+ Request input reaches a SQL query string. An attacker can rewrite the query to read or change any data.
310
+ Use parameters: cursor.execute("... WHERE id = %s", (value,)) or the ORM's filters.
311
+ metadata: {title: "SQL injection from request input", cwe: ["CWE-89"]}
312
+ pattern-sources:
313
+ - pattern-either:
314
+ - pattern: request.GET
315
+ - pattern: request.POST
316
+ - pattern: request.args
317
+ - pattern: request.form
318
+ - pattern: request.values
319
+ - pattern: request.json
320
+ - pattern: request.data
321
+ - pattern: request.body
322
+ - pattern: request.cookies
323
+ - pattern: request.headers
324
+ - pattern: request.get_json(...)
325
+ - pattern: request.query_params
326
+ pattern-sinks:
327
+ - patterns:
328
+ - pattern-either:
329
+ - pattern: $C.execute($Q, ...)
330
+ - pattern: $C.executemany($Q, ...)
331
+ - pattern: $C.executescript($Q, ...)
332
+ - pattern: $M.objects.raw($Q, ...)
333
+ - pattern: $M.extra(where=$Q, ...)
334
+ - pattern: text($Q)
335
+ - focus-metavariable: $Q
336
+ - id: python-command-injection-from-request
337
+ mode: taint
338
+ languages: [python]
339
+ severity: ERROR
340
+ message: >-
341
+ Request input reaches a shell command. An attacker can run any command on your server. Pass an argument
342
+ list without shell=True and validate the input.
343
+ metadata: {title: "Command injection from request input", cwe: ["CWE-78"]}
344
+ pattern-sources:
345
+ - pattern-either:
346
+ - pattern: request.GET
347
+ - pattern: request.POST
348
+ - pattern: request.args
349
+ - pattern: request.form
350
+ - pattern: request.values
351
+ - pattern: request.json
352
+ - pattern: request.data
353
+ - pattern: request.body
354
+ - pattern: request.cookies
355
+ - pattern: request.headers
356
+ - pattern: request.get_json(...)
357
+ - pattern: request.query_params
358
+ pattern-sinks:
359
+ - patterns:
360
+ - pattern-either:
361
+ - pattern: os.system($CMD)
362
+ - pattern: os.popen($CMD, ...)
363
+ - pattern: subprocess.$F($CMD, ..., shell=True, ...)
364
+ - focus-metavariable: $CMD
365
+ - id: python-code-injection-from-request
366
+ mode: taint
367
+ languages: [python]
368
+ severity: ERROR
369
+ message: >-
370
+ Request input is evaluated as Python code or deserialized unsafely. An attacker can run code on your
371
+ server. Never eval user input; use json / ast.literal_eval / yaml.safe_load.
372
+ metadata: {title: "Code injection from request input", cwe: ["CWE-94"]}
373
+ pattern-sources:
374
+ - pattern-either:
375
+ - pattern: request.GET
376
+ - pattern: request.POST
377
+ - pattern: request.args
378
+ - pattern: request.form
379
+ - pattern: request.values
380
+ - pattern: request.json
381
+ - pattern: request.data
382
+ - pattern: request.body
383
+ - pattern: request.cookies
384
+ - pattern: request.headers
385
+ - pattern: request.get_json(...)
386
+ - pattern: request.query_params
387
+ pattern-sinks:
388
+ - patterns:
389
+ - pattern-either:
390
+ - pattern: eval($X, ...)
391
+ - pattern: exec($X, ...)
392
+ - pattern: render_template_string($X, ...)
393
+ - focus-metavariable: $X
package/scan.js ADDED
@@ -0,0 +1,451 @@
1
+ // Sentinel 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 Sentinel's own rule pack (rules/sentinel.yml)
9
+ // sentinel built-in checks for the stacks AI-built apps use (Supabase RLS, Firebase rules, .env
10
+ // hygiene, secrets in browser-exposed env vars, missing security headers). No install needed.
11
+ //
12
+ // What is uploaded per result: tool, rule, severity, title/message (tool text), path, line, commit,
13
+ // package/versions, CVE/CWE ids, and a short hash used to tell results apart. Never a code snippet,
14
+ // a matched secret, a file body, or commit author details.
15
+ import { execFile } from "node:child_process";
16
+ import crypto from "node:crypto";
17
+ import fss from "node:fs";
18
+ import fs from "node:fs/promises";
19
+ import os from "node:os";
20
+ import path from "node:path";
21
+ import { fileURLToPath } from "node:url";
22
+
23
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
24
+ export const RULES_FILE = path.join(HERE, "rules", "sentinel.yml");
25
+ export const INSTALL_HINTS = {
26
+ trivy: "brew install trivy (Linux: https://trivy.dev/latest/getting-started/installation/)",
27
+ gitleaks: "brew install gitleaks (Linux: https://github.com/gitleaks/gitleaks/releases)",
28
+ opengrep: "curl -fsSL https://raw.githubusercontent.com/opengrep/opengrep/main/install.sh | bash",
29
+ };
30
+ const SKIP_DIRS = new Set(["node_modules", ".git", "dist", "build", ".next", ".nuxt", ".svelte-kit", ".output",
31
+ "vendor", "venv", ".venv", "__pycache__", ".turbo", ".vercel", "coverage", "target"]);
32
+ const MAX_FILE = 512 * 1024;
33
+
34
+ const sha = (s) => crypto.createHash("sha256").update(String(s)).digest("hex").slice(0, 16);
35
+
36
+ function run(cmd, args, { cwd, timeout = 600000, env } = {}) {
37
+ return new Promise((resolve) => {
38
+ execFile(cmd, args, { cwd, timeout, maxBuffer: 512 * 1024 * 1024, env: { ...process.env, ...env } },
39
+ (err, stdout, stderr) => resolve({ code: err ? (typeof err.code === "number" ? err.code : 1) : 0,
40
+ stdout: String(stdout || ""), stderr: String(stderr || ""), killed: !!err?.killed }));
41
+ });
42
+ }
43
+
44
+ export function which(bin) {
45
+ const override = process.env[`SENTINEL_${bin.toUpperCase()}`];
46
+ if (override) return fss.existsSync(override) ? override : null;
47
+ for (const dir of (process.env.PATH || "").split(path.delimiter)) {
48
+ const p = path.join(dir, bin);
49
+ try { fss.accessSync(p, fss.constants.X_OK); if (fss.statSync(p).isFile()) return p; } catch { /* next */ }
50
+ }
51
+ return null;
52
+ }
53
+
54
+ const git = async (root, args) => {
55
+ const r = await run("git", args, { cwd: root, timeout: 60000 });
56
+ return r.code === 0 ? r.stdout.trim() : null;
57
+ };
58
+ const zsplit = (s) => (s ? s.split("\0").filter(Boolean) : []);
59
+
60
+ // ------------------------------------------------------------------ repo context
61
+ export function repoFromRemote(url) {
62
+ if (!url) return null;
63
+ const m = url.trim().replace(/\.git$/, "").match(/[:/]([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/);
64
+ return m ? `${m[1]}/${m[2]}` : null;
65
+ }
66
+
67
+ async function context(dir) {
68
+ const root = (await git(dir, ["rev-parse", "--show-toplevel"])) || path.resolve(dir);
69
+ const isGit = !!(await git(root, ["rev-parse", "--git-dir"]));
70
+ const env = process.env;
71
+ let repo = env.SENTINEL_REPO || env.GITHUB_REPOSITORY || (isGit && repoFromRemote(await git(root, ["remote", "get-url", "origin"])));
72
+ if (!repo) repo = "local/" + (path.basename(root).replace(/[^A-Za-z0-9_.-]/g, "-").slice(0, 100) || "project");
73
+ let branch = env.SENTINEL_BRANCH || env.GITHUB_HEAD_REF || env.GITHUB_REF_NAME ||
74
+ (isGit ? await git(root, ["rev-parse", "--abbrev-ref", "HEAD"]) : null);
75
+ if (branch === "HEAD") branch = null; // detached
76
+ let defaultBranch = env.SENTINEL_DEFAULT_BRANCH || null;
77
+ if (!defaultBranch && isGit) {
78
+ const ref = await git(root, ["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"]);
79
+ if (ref) defaultBranch = ref.replace(/^origin\//, "");
80
+ else for (const b of ["main", "master"]) if (await git(root, ["rev-parse", "--verify", "--quiet", `refs/heads/${b}`])) { defaultBranch = b; break; }
81
+ }
82
+ const commit = env.GITHUB_SHA || (isGit ? await git(root, ["rev-parse", "HEAD"]) : null);
83
+ let files, tracked = new Set(), unignored = new Set();
84
+ if (isGit) {
85
+ files = zsplit(await git(root, ["ls-files", "-co", "--exclude-standard", "-z"]));
86
+ tracked = new Set(zsplit(await git(root, ["ls-files", "-z"])));
87
+ unignored = new Set(zsplit(await git(root, ["ls-files", "-o", "--exclude-standard", "-z"])));
88
+ } else {
89
+ files = await walk(root);
90
+ }
91
+ files = files.filter((f) => !f.split("/").some((p) => SKIP_DIRS.has(p)) && fss.existsSync(path.join(root, f)));
92
+ return { root, isGit, repo, branch, defaultBranch, commit, files, fileSet: new Set(files), tracked, unignored };
93
+ }
94
+
95
+ async function walk(root, rel = "", out = []) {
96
+ if (out.length > 50000) return out;
97
+ for (const e of await fs.readdir(path.join(root, rel), { withFileTypes: true }).catch(() => [])) {
98
+ if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name)) await walk(root, path.join(rel, e.name), out); }
99
+ else if (e.isFile()) out.push(path.join(rel, e.name).split(path.sep).join("/"));
100
+ }
101
+ return out;
102
+ }
103
+
104
+ async function read(root, f) {
105
+ try {
106
+ const p = path.join(root, f);
107
+ if ((await fs.stat(p)).size > MAX_FILE) return null;
108
+ return await fs.readFile(p, "utf8");
109
+ } catch { return null; }
110
+ }
111
+
112
+ const lineOf = (text, index) => text.slice(0, index).split("\n").length;
113
+
114
+ // ------------------------------------------------------------------ trivy
115
+ async function runTrivy(ctx, bin, withSecrets, tmp) {
116
+ const out = path.join(tmp, "trivy.json");
117
+ const scanners = withSecrets ? "vuln,misconfig,secret" : "vuln,misconfig";
118
+ const r = await run(bin, ["fs", "--quiet", "--format", "json", "--output", out, "--scanners", scanners,
119
+ "--list-all-pkgs", "--skip-dirs", "**/node_modules", ctx.root], { timeout: 1200000 });
120
+ if (r.code !== 0) return { status: { status: "error", detail: (r.stderr || "trivy failed").slice(-280) } };
121
+ const data = JSON.parse(await fs.readFile(out, "utf8"));
122
+ const findings = [], components = [];
123
+ const inScope = (t) => !ctx.isGit || ctx.fileSet.has(t);
124
+ for (const res of data.Results || []) {
125
+ const target = res.Target;
126
+ for (const p of res.Packages || []) {
127
+ components.push({ name: p.Name, version: p.Version, ecosystem: res.Type, purl: p.Identifier?.PURL });
128
+ }
129
+ if (!inScope(target)) continue;
130
+ for (const v of res.Vulnerabilities || []) {
131
+ findings.push({ tool: "trivy", kind: "vuln", rule: v.VulnerabilityID, severity: v.Severity, title: v.Title,
132
+ package: v.PkgName, installed_version: v.InstalledVersion, fixed_version: v.FixedVersion || undefined,
133
+ vuln_id: v.VulnerabilityID, path: target, cwe: (v.CweIDs || []).slice(0, 5),
134
+ refs: [v.PrimaryURL].filter(Boolean) });
135
+ }
136
+ for (const m of res.Misconfigurations || []) {
137
+ if (m.Status && m.Status !== "FAIL") continue;
138
+ findings.push({ tool: "trivy", kind: "misconfig", rule: m.AVDID || m.ID, severity: m.Severity, title: m.Title,
139
+ message: [m.Message, m.Resolution].filter(Boolean).join(" — "), path: target,
140
+ line: m.CauseMetadata?.StartLine || undefined, refs: [m.PrimaryURL].filter(Boolean) });
141
+ }
142
+ for (const s of res.Secrets || []) { // only when gitleaks is not available
143
+ findings.push({ tool: "trivy", kind: "secret", rule: s.RuleID, title: s.Title, path: target,
144
+ line: s.StartLine, key: sha(`${s.RuleID}|${s.Match}`) }); // Match is masked by trivy; hashed anyway
145
+ }
146
+ }
147
+ return { status: { status: "ok", version: data.Trivy?.Version }, findings, components };
148
+ }
149
+
150
+ // ------------------------------------------------------------------ gitleaks
151
+ // JWTs in .env.example-style files are almost always Supabase's public local-dev demo keys. Other
152
+ // secrets in example files (real API keys pasted by mistake) are still reported.
153
+ const isTemplateJwt = (l) => l.RuleID === "jwt" && ENV_FILE.test(l.File) && ENV_TEMPLATE.test(l.File);
154
+ async function gitleaksRun(bin, mode, target, out) {
155
+ const r = await run(bin, [mode, "--redact", "--no-banner", "--log-level", "error", "--exit-code", "0",
156
+ "--report-format", "json", "--report-path", out, target], { timeout: 900000 });
157
+ if (r.code !== 0) throw new Error((r.stderr || `gitleaks ${mode} failed`).slice(-280));
158
+ return JSON.parse((await fs.readFile(out, "utf8")) || "[]") || [];
159
+ }
160
+
161
+ async function runGitleaks(ctx, bin, tmp) {
162
+ try {
163
+ const key = (l) => sha(`${l.RuleID}|${Number(l.Entropy || 0).toFixed(3)}`);
164
+ const current = (await gitleaksRun(bin, "dir", ctx.root, path.join(tmp, "gl-dir.json")))
165
+ .map((l) => ({ ...l, File: path.relative(ctx.root, path.resolve(ctx.root, l.File)).split(path.sep).join("/") }))
166
+ .filter((l) => !ctx.isGit || ctx.fileSet.has(l.File)) // a gitignored local .env is correct practice
167
+ .filter((l) => !isTemplateJwt(l));
168
+ const findings = current.map((l) => ({ tool: "gitleaks", kind: "secret", rule: l.RuleID, title: l.RuleID,
169
+ message: l.Description, path: l.File, line: l.StartLine, key: key(l) }));
170
+ if (ctx.isGit) {
171
+ const now = new Set(findings.map((f) => `${f.path}|${f.rule}|${f.key}`));
172
+ const seen = new Set();
173
+ for (const l of await gitleaksRun(bin, "git", ctx.root, path.join(tmp, "gl-git.json"))) {
174
+ if (isTemplateJwt(l)) continue;
175
+ const id = `${l.File}|${l.RuleID}|${key(l)}`;
176
+ if (now.has(id) || seen.has(id)) continue; // still in the tree (reported above) or a repeat
177
+ seen.add(id);
178
+ findings.push({ tool: "gitleaks", kind: "history-secret", rule: l.RuleID, title: l.RuleID,
179
+ message: l.Description, path: l.File, line: l.StartLine, commit: (l.Commit || "").slice(0, 40) || undefined,
180
+ key: key(l) }); // author, email and commit message are deliberately not sent
181
+ }
182
+ }
183
+ const v = await run(bin, ["version"], { timeout: 30000 });
184
+ return { status: { status: "ok", version: v.stdout.trim().slice(0, 40) }, findings };
185
+ } catch (e) {
186
+ return { status: { status: "error", detail: String(e.message).slice(0, 280) } };
187
+ }
188
+ }
189
+
190
+ // ------------------------------------------------------------------ opengrep
191
+ async function runOpengrep(ctx, bin) {
192
+ const r = await run(bin, ["scan", "--config", RULES_FILE, "--json", "--quiet", ctx.root], { cwd: ctx.root, timeout: 900000 });
193
+ let data;
194
+ try { data = JSON.parse(r.stdout); } catch {
195
+ return { status: { status: "error", detail: (r.stderr || "opengrep produced no JSON").slice(-280) } };
196
+ }
197
+ const fatal = (data.errors || []).filter((e) => e.level === "error" && !e.path);
198
+ if (fatal.length && !(data.results || []).length) {
199
+ return { status: { status: "error", detail: String(fatal[0].message || fatal[0].type).slice(0, 280) } };
200
+ }
201
+ const findings = [];
202
+ // A taint rule and a pattern rule can flag the same bug, sometimes on adjacent lines of one
203
+ // multi-line call: report one finding per bug class (CWE) within a few lines.
204
+ // ponytail: line-window heuristic; use opengrep's dataflow trace ranges if it merges real neighbours.
205
+ const seenAt = new Map();
206
+ for (const res of data.results || []) {
207
+ const rel = path.relative(ctx.root, path.resolve(ctx.root, res.path)).split(path.sep).join("/");
208
+ if (ctx.isGit && !ctx.fileSet.has(rel)) continue;
209
+ const meta = res.extra?.metadata || {};
210
+ const rule = String(res.check_id || "").split(".").pop();
211
+ const bugClass = `${rel}|${String([].concat(meta.cwe || [rule])[0]).split(":")[0]}`;
212
+ const line = res.start?.line || 0;
213
+ const near = seenAt.get(bugClass) || [];
214
+ if (near.some((l) => Math.abs(l - line) <= 3)) continue;
215
+ seenAt.set(bugClass, [...near, line]);
216
+ findings.push({ tool: "opengrep", kind: "sast", rule, severity: res.extra?.severity, title: meta.title || rule,
217
+ message: res.extra?.message, path: rel, line: res.start?.line,
218
+ cwe: [].concat(meta.cwe || []).map((c) => String(c).split(":")[0]).slice(0, 5),
219
+ refs: [].concat(meta.references || []).slice(0, 3),
220
+ key: sha(`${rule}|${(res.extra?.lines || "").replace(/\s+/g, " ").trim()}`) });
221
+ }
222
+ const v = await run(bin, ["--version"], { timeout: 30000 });
223
+ return { status: { status: "ok", version: v.stdout.trim().slice(0, 40) }, findings };
224
+ }
225
+
226
+ // ------------------------------------------------------------------ Sentinel built-in checks
227
+ const ENV_FILE = /(^|\/)\.env(\.[A-Za-z0-9_.-]+)?$/;
228
+ const ENV_TEMPLATE = /\.(example|sample|template|tpl|dist)$/i;
229
+ const PUBLIC_VAR = /\b((?:NEXT_PUBLIC|VITE|EXPO_PUBLIC|REACT_APP|NUXT_PUBLIC|GATSBY|PUBLIC)_[A-Z0-9_]+)/g;
230
+ 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)/;
231
+ const SOURCE = /\.(js|jsx|ts|tsx|mjs|cjs|vue|svelte|astro)$/;
232
+ const IDENT = String.raw`(?:"?[A-Za-z_][\w$]*"?\.)?"?[A-Za-z_][\w$]*"?`;
233
+
234
+ function tableName(raw) {
235
+ const parts = raw.replace(/"/g, "").toLowerCase().split(".");
236
+ return parts.length === 2 ? { schema: parts[0], name: parts[1] } : { schema: "public", name: parts[0] };
237
+ }
238
+ const stripSqlComments = (s) => s.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, " ")).replace(/--[^\n]*/g, (m) => " ".repeat(m.length));
239
+
240
+ async function supabaseChecks(ctx) {
241
+ const sqlFiles = ctx.files.filter((f) => /\.sql$/i.test(f) && /(^|\/)(supabase|migrations|db)\//i.test(f)).sort();
242
+ if (!sqlFiles.length) return [];
243
+ const tables = new Map(); // name -> {path, line, rls}
244
+ const policies = new Map(); // table:policy -> {path, line}
245
+ const events = new RegExp(String.raw`create\s+(?:unlogged\s+)?table\s+(?:if\s+not\s+exists\s+)?(${IDENT})` +
246
+ String.raw`|alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?(${IDENT})\s+(enable|disable)\s+row\s+level\s+security` +
247
+ String.raw`|drop\s+table\s+(?:if\s+exists\s+)?(${IDENT})` +
248
+ String.raw`|create\s+policy\s+("[^"]+"|\w+)\s+on\s+(?:table\s+)?(${IDENT})([\s\S]*?);` +
249
+ String.raw`|drop\s+policy\s+(?:if\s+exists\s+)?("[^"]+"|\w+)\s+on\s+(?:table\s+)?(${IDENT})`, "gi");
250
+ for (const f of sqlFiles) {
251
+ const raw = await read(ctx.root, f);
252
+ if (!raw) continue;
253
+ const text = stripSqlComments(raw);
254
+ for (const m of text.matchAll(events)) {
255
+ const line = lineOf(text, m.index);
256
+ if (m[1]) { const t = tableName(m[1]); if (t.schema === "public") tables.set(t.name, { path: f, line, rls: false }); }
257
+ else if (m[2]) { const t = tableName(m[2]); if (tables.has(t.name)) tables.get(t.name).rls = m[3].toLowerCase() === "enable"; }
258
+ else if (m[4]) tables.delete(tableName(m[4]).name);
259
+ else if (m[5]) {
260
+ const t = tableName(m[6]).name, body = m[7] || "";
261
+ const id = `${t}:${m[5].replace(/"/g, "")}`;
262
+ // Public READ of catalog-style data is a normal design (and the live scan proves what anon can
263
+ // actually read); `true` on a policy that can insert/update/delete lets anyone change data.
264
+ const readOnly = /\bfor\s+select\b/i.test(body);
265
+ if (!readOnly && /\busing\s*\(\s*true\s*\)|\bwith\s+check\s*\(\s*true\s*\)/i.test(body)) policies.set(id, { path: f, line });
266
+ else policies.delete(id);
267
+ } else if (m[8]) policies.delete(`${tableName(m[9]).name}:${m[8].replace(/"/g, "")}`);
268
+ }
269
+ }
270
+ const out = [];
271
+ for (const [name, t] of tables) {
272
+ if (!t.rls) out.push({ tool: "sentinel", kind: "sentinel", rule: "CODE_SUPABASE_TABLE_NO_RLS", path: t.path, line: t.line, key: name });
273
+ }
274
+ for (const [id, p] of policies) {
275
+ out.push({ tool: "sentinel", kind: "sentinel", rule: "CODE_SUPABASE_POLICY_PERMISSIVE", path: p.path, line: p.line, key: id });
276
+ }
277
+ return out;
278
+ }
279
+
280
+ async function firebaseChecks(ctx) {
281
+ const out = [];
282
+ for (const f of ctx.files.filter((f) => /(^|\/)(firestore|storage)\.rules$|\.rules$/.test(f) || /(^|\/)database\.rules\.json$/.test(f))) {
283
+ const text = await read(ctx.root, f);
284
+ if (!text) continue;
285
+ const open = f.endsWith(".json")
286
+ ? /"\.(read|write)"\s*:\s*(true|"true")/g
287
+ : /^\s*allow\s+[a-z,\s]+(?::\s*if\s+true\s*;|;)/gim;
288
+ for (const m of text.matchAll(open)) {
289
+ out.push({ tool: "sentinel", kind: "sentinel", rule: "CODE_FIREBASE_RULES_OPEN", path: f, line: lineOf(text, m.index),
290
+ key: sha(m[0].replace(/\s+/g, " ").trim()) });
291
+ }
292
+ }
293
+ return out;
294
+ }
295
+
296
+ async function envChecks(ctx) {
297
+ const out = [];
298
+ const envFiles = ctx.files.filter((f) => ENV_FILE.test(f));
299
+ if (ctx.isGit) {
300
+ for (const f of envFiles.filter((f) => !ENV_TEMPLATE.test(f))) {
301
+ if (ctx.tracked.has(f)) out.push({ tool: "sentinel", kind: "sentinel", rule: "CODE_ENV_FILE_COMMITTED", path: f, key: f });
302
+ else if (ctx.unignored.has(f)) out.push({ tool: "sentinel", kind: "sentinel", rule: "CODE_ENV_NOT_GITIGNORED", path: f, key: f });
303
+ }
304
+ }
305
+ // Secret-looking names in browser-exposed env vars: env files (incl. templates) and source code.
306
+ const named = new Map();
307
+ for (const f of [...envFiles, ...ctx.files.filter((f) => SOURCE.test(f) && !/\.min\.js$/.test(f)).slice(0, 8000)]) {
308
+ const text = await read(ctx.root, f);
309
+ if (!text) continue;
310
+ for (const m of text.matchAll(PUBLIC_VAR)) {
311
+ const name = m[1];
312
+ if (SECRET_NAME.test(name) && !named.has(name)) {
313
+ named.set(name, { path: f, line: lineOf(text, m.index) });
314
+ }
315
+ }
316
+ }
317
+ 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 });
318
+ return out;
319
+ }
320
+
321
+ async function headersCheck(ctx) {
322
+ const cfg = ctx.files.find((f) => /^(?:[^/]+\/)?(next|vite)\.config\.(js|mjs|ts|cjs)$/.test(f));
323
+ if (!cfg) return [];
324
+ const has = async (f, re) => { const t = ctx.fileSet.has(f) ? await read(ctx.root, f) : null; return !!(t && re.test(t)); };
325
+ const dir = cfg.includes("/") ? cfg.slice(0, cfg.lastIndexOf("/") + 1) : "";
326
+ const HEADER = /Content-Security-Policy|Strict-Transport-Security|X-Frame-Options|frame-ancestors/i;
327
+ const checks = [
328
+ has(cfg, /\bheaders\s*\(|\bheaders\s*:/), has(`${dir}vercel.json`, /"headers"\s*:/), has("vercel.json", /"headers"\s*:/),
329
+ has(`${dir}netlify.toml`, /\[\[headers\]\]/), has("netlify.toml", /\[\[headers\]\]/),
330
+ Promise.resolve(ctx.fileSet.has(`${dir}public/_headers`) || ctx.fileSet.has(`${dir}_headers`) || ctx.fileSet.has("public/_headers")),
331
+ ...["middleware.ts", "middleware.js", "src/middleware.ts", "src/middleware.js"].map((m) => has(`${dir}${m}`, HEADER)),
332
+ ];
333
+ if ((await Promise.all(checks)).some(Boolean)) return [];
334
+ return [{ tool: "sentinel", kind: "sentinel", rule: "CODE_SECURITY_HEADERS_MISSING", path: cfg, key: cfg }];
335
+ }
336
+
337
+ export async function sentinelChecks(ctx) {
338
+ return (await Promise.all([supabaseChecks(ctx), firebaseChecks(ctx), envChecks(ctx), headersCheck(ctx)])).flat();
339
+ }
340
+
341
+ // ------------------------------------------------------------------ orchestration
342
+ export async function scan(dir = process.cwd(), { trigger = "cli", log = () => {} } = {}) {
343
+ const ctx = await context(dir);
344
+ const tmp = await fs.mkdtemp(path.join(os.tmpdir(), "sentinel-"));
345
+ const tools = {}, findings = [];
346
+ let components = [];
347
+ try {
348
+ const bins = { trivy: which("trivy"), gitleaks: which("gitleaks"), opengrep: which("opengrep") };
349
+ const jobs = [];
350
+ if (bins.trivy) {
351
+ log("trivy: dependencies + infrastructure config…");
352
+ jobs.push(runTrivy(ctx, bins.trivy, !bins.gitleaks, tmp).then((r) => { tools.trivy = r.status; findings.push(...(r.findings || [])); components = r.components || []; }));
353
+ } else tools.trivy = { status: "missing", detail: INSTALL_HINTS.trivy };
354
+ if (bins.gitleaks) {
355
+ log("gitleaks: secrets in files and git history…");
356
+ jobs.push(runGitleaks(ctx, bins.gitleaks, tmp).then((r) => { tools.gitleaks = r.status; findings.push(...(r.findings || [])); }));
357
+ } else tools.gitleaks = { status: "missing", detail: INSTALL_HINTS.gitleaks };
358
+ if (bins.opengrep) {
359
+ log("opengrep: insecure code patterns…");
360
+ jobs.push(runOpengrep(ctx, bins.opengrep).then((r) => { tools.opengrep = r.status; findings.push(...(r.findings || [])); }));
361
+ } else tools.opengrep = { status: "missing", detail: INSTALL_HINTS.opengrep };
362
+ log("sentinel: Supabase, Firebase, env files, headers…");
363
+ jobs.push(sentinelChecks(ctx).then((f) => { tools.sentinel = { status: "ok" }; findings.push(...f); },
364
+ (e) => { tools.sentinel = { status: "error", detail: String(e.message).slice(0, 280) }; }));
365
+ await Promise.all(jobs.map((j) => j.catch((e) => log(`engine failed: ${e.message}`))));
366
+ } finally {
367
+ await fs.rm(tmp, { recursive: true, force: true });
368
+ }
369
+ const manifest = ctx.files.filter((f) => f.split("/").length <= 4).sort((a, b) => a.split("/").length - b.split("/").length).slice(0, 400);
370
+ return {
371
+ repo: ctx.repo, branch: ctx.branch || undefined, default_branch: ctx.defaultBranch || undefined,
372
+ commit: ctx.commit || undefined, trigger, tools, findings: findings.slice(0, 5000),
373
+ components: dedupe(components).slice(0, 10000), manifest_paths: manifest,
374
+ };
375
+ }
376
+
377
+ function dedupe(components) {
378
+ const seen = new Set();
379
+ return components.filter((c) => {
380
+ const k = `${c.ecosystem}|${c.name}|${c.version}`;
381
+ if (!c.name || seen.has(k)) return false;
382
+ seen.add(k);
383
+ return true;
384
+ });
385
+ }
386
+
387
+ // ------------------------------------------------------------------ upload
388
+ export async function upload(payload, { base, key, log = () => {} }) {
389
+ const url = base.replace(/\/$/, "") + "/api/mcp/code-scan";
390
+ let last;
391
+ for (let attempt = 0; attempt < 4; attempt++) { // the free-tier API can be cold-starting (~50 s)
392
+ try {
393
+ const res = await fetch(url, { method: "POST", signal: AbortSignal.timeout(120000),
394
+ headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" }, body: JSON.stringify(payload) });
395
+ const text = await res.text();
396
+ let data; try { data = JSON.parse(text); } catch { data = { detail: text.slice(0, 300) }; }
397
+ if (res.ok) return data;
398
+ const detail = typeof data.detail === "string" ? data.detail : JSON.stringify(data.detail);
399
+ if (![502, 503, 504].includes(res.status)) throw Object.assign(new Error(detail || `Upload failed (${res.status})`), { fatal: true });
400
+ last = new Error(detail || `Upload failed (${res.status})`);
401
+ } catch (e) {
402
+ if (e.fatal) throw e;
403
+ last = e;
404
+ }
405
+ log(`upload attempt ${attempt + 1} failed (${last.message}); retrying…`);
406
+ await new Promise((r) => setTimeout(r, 5000 * (attempt + 1)));
407
+ }
408
+ throw last;
409
+ }
410
+
411
+ // ------------------------------------------------------------------ report
412
+ const where = (i) => {
413
+ const l = i.location || {};
414
+ if (l.path) return l.path + (l.line ? `:${l.line}` : "");
415
+ return i.domain || l.domain || "";
416
+ };
417
+
418
+ export function report(result, payload) {
419
+ const lines = [];
420
+ const mode = result.preview
421
+ ? `PREVIEW of branch ${result.branch} (default branch is ${result.default_branch}; issue status changes only when the default branch is scanned)`
422
+ : result.baseline ? "baseline (first scan of this repo)" : "issues updated";
423
+ lines.push(`Sentinel code scan of ${result.repo} — ${mode}.`);
424
+ const sev = result.open_by_severity || {};
425
+ 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} fixed · ${result.reopened} reopened.`);
426
+ const missing = Object.entries(payload.tools).filter(([, s]) => s.status !== "ok");
427
+ for (const [t, s] of missing) lines.push(` ! ${t} ${s.status}${s.detail ? `: ${s.detail}` : ""}`);
428
+ if (missing.length) lines.push(" (Checks from a missing or failed engine are not assessed, and its existing issues stay open.)");
429
+ if (result.fixed_issues?.length) {
430
+ lines.push("", "Fixed:");
431
+ for (const i of result.fixed_issues.slice(0, 15)) lines.push(` ✓ [${i.severity}] ${i.title} ${where(i)}`);
432
+ }
433
+ if (result.new_issues?.length) {
434
+ lines.push("", "New:");
435
+ for (const i of result.new_issues.slice(0, 20)) lines.push(` + [${i.severity}] ${i.title} ${where(i)}${i.id ? ` (id ${i.id})` : ""}`);
436
+ }
437
+ const top = (result.issues || []).filter((i) => !(result.new_issues || []).some((n) => n.id && n.id === i.id)).slice(0, 15);
438
+ if (top.length) {
439
+ lines.push("", "Open:");
440
+ for (const i of top) lines.push(` - [${i.severity}] ${i.title} ${where(i)}${i.id ? ` (id ${i.id})` : ""}`);
441
+ }
442
+ if (result.dashboard_url) lines.push("", `Dashboard: ${result.dashboard_url}`);
443
+ return lines.join("\n");
444
+ }
445
+
446
+ const RANK = ["informational", "low", "medium", "high", "critical"];
447
+ export function shouldFail(result, threshold) {
448
+ if (!threshold || threshold === "none") return false;
449
+ const min = RANK.indexOf(threshold);
450
+ return (result.new_issues || []).some((i) => RANK.indexOf(i.severity) >= min);
451
+ }