@arvyx/sentinel-mcp 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,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 `using (true)` policies, 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 patterns (Sentinel's own rules in `rules/sentinel.yml`: SQL / command injection, eval, XSS, open redirect, hard-coded JWT secrets, service-role key in client code, CORS) | 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,53 @@
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
+ try {
31
+ const payload = await scan(dir, { trigger: opt("trigger", process.env.CI ? "ci" : "cli"), log });
32
+ if (flag("no-upload")) {
33
+ console.log(JSON.stringify(payload, null, 2));
34
+ process.exit(0);
35
+ }
36
+ const key = process.env.SENTINEL_API_KEY;
37
+ if (!key) {
38
+ log("SENTINEL_API_KEY is not set. Create one in Sentinel (Settings → API keys), or use --no-upload.");
39
+ process.exit(2);
40
+ }
41
+ const base = process.env.SENTINEL_API_URL || "https://sentinel-api-maa1.onrender.com";
42
+ log(`uploading ${payload.findings.length} result(s) for ${payload.repo}…`);
43
+ const result = await upload(payload, { base, key, log });
44
+ console.log(flag("json") ? JSON.stringify(result, null, 2) : report(result, payload));
45
+ const failOn = opt("fail-on", "none");
46
+ if (shouldFail(result, failOn)) {
47
+ log(`failing: new issue(s) at or above "${failOn}".`);
48
+ process.exit(1);
49
+ }
50
+ } catch (e) {
51
+ log(`error: ${e.message}`);
52
+ process.exit(2);
53
+ }
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,16 @@
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.0",
4
+ "description": "Sentinel by Arvyx — security scanning for the apps you build with AI, inside Claude Code / Codex and CI.",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "bin": { "sentinel-mcp": "index.js", "sentinel-scan": "cli.js" },
8
+ "files": ["index.js", "cli.js", "scan.js", "rules/", "README.md"],
9
+ "engines": { "node": ">=18" },
10
+ "license": "UNLICENSED",
11
+ "publishConfig": { "access": "public" },
12
+ "dependencies": {
13
+ "@modelcontextprotocol/sdk": "^1.18.0",
14
+ "zod": "^3.23.8"
15
+ }
16
+ }
@@ -0,0 +1,191 @@
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("..." + $X, ...)
31
+ - pattern: $DB.execute("..." + $X, ...)
32
+ - pattern: $DB.raw("..." + $X, ...)
33
+ - pattern: $DB.$queryRawUnsafe("..." + $X, ...)
34
+ - id: python-sql-formatted
35
+ languages: [python]
36
+ severity: ERROR
37
+ message: >-
38
+ SQL is built with an f-string, % or + formatting. If any value comes from the request, an attacker can
39
+ change the query. Use parameters: cursor.execute("... WHERE id = %s", (value,)).
40
+ metadata: {title: "SQL query built with string formatting", cwe: ["CWE-89"]}
41
+ pattern-either:
42
+ - pattern: $C.execute(f"...", ...)
43
+ - pattern: $C.execute("..." % $X, ...)
44
+ - pattern: $C.execute("..." + $X, ...)
45
+ - pattern: $C.execute("...".format(...), ...)
46
+ - pattern: $C.executemany(f"...", ...)
47
+ - pattern: sqlalchemy.text(f"...")
48
+ - pattern: text(f"...")
49
+
50
+ # ------------------------------------------------------------------ command / code injection
51
+ - id: shell-command-from-string
52
+ languages: [javascript, typescript]
53
+ severity: ERROR
54
+ message: >-
55
+ A shell command is built from a string with interpolated values. If a value comes from a user, they can
56
+ run arbitrary commands on your server. Use execFile/spawn with an argument array.
57
+ metadata: {title: "Shell command built from a string", cwe: ["CWE-78"]}
58
+ pattern-either:
59
+ - pattern: $CP.exec(`...${$X}...`, ...)
60
+ - pattern: $CP.execSync(`...${$X}...`, ...)
61
+ - pattern: $CP.exec("..." + $X, ...)
62
+ - pattern: $CP.execSync("..." + $X, ...)
63
+ - pattern: exec(`...${$X}...`, ...)
64
+ - pattern: execSync(`...${$X}...`, ...)
65
+ - id: python-shell-true
66
+ languages: [python]
67
+ severity: ERROR
68
+ message: >-
69
+ subprocess runs with shell=True. If any part of the command comes from a user, they can run arbitrary
70
+ commands. Pass an argument list and drop shell=True.
71
+ metadata: {title: "subprocess with shell=True", cwe: ["CWE-78"]}
72
+ pattern-either:
73
+ - pattern: subprocess.$F(..., shell=True, ...)
74
+ - pattern: os.system($X)
75
+ - id: eval-of-dynamic-code
76
+ languages: [javascript, typescript]
77
+ severity: ERROR
78
+ message: >-
79
+ eval / new Function runs a string as code. If the string can contain user input, an attacker can run
80
+ code in your app. Parse data with JSON.parse or use a lookup table instead.
81
+ metadata: {title: "Dynamic code evaluation", cwe: ["CWE-95"]}
82
+ patterns:
83
+ - pattern-either:
84
+ - pattern: eval($X)
85
+ - pattern: new Function(..., $X)
86
+ - pattern-not: eval("...")
87
+ - pattern-not: new Function("...")
88
+ - id: python-unsafe-deserialization
89
+ languages: [python]
90
+ severity: ERROR
91
+ message: >-
92
+ pickle / yaml.load can execute code while loading. Never load untrusted data with them; use json, or
93
+ yaml.safe_load.
94
+ metadata: {title: "Unsafe deserialization", cwe: ["CWE-502"]}
95
+ pattern-either:
96
+ - pattern: pickle.loads(...)
97
+ - pattern: pickle.load(...)
98
+ - patterns:
99
+ - pattern: yaml.load(...)
100
+ - pattern-not: yaml.load(..., Loader=yaml.SafeLoader, ...)
101
+ - pattern-not: yaml.load(..., Loader=SafeLoader, ...)
102
+
103
+ # ------------------------------------------------------------------ XSS / redirects
104
+ - id: react-dangerously-set-inner-html
105
+ languages: [javascript, typescript]
106
+ severity: WARNING
107
+ message: >-
108
+ HTML from a variable is rendered with dangerouslySetInnerHTML. If it can contain user content, it can
109
+ run scripts in your users' browsers (stealing sessions). Sanitize it (DOMPurify) or render text.
110
+ metadata: {title: "Unsanitized HTML rendered in React", cwe: ["CWE-79"]}
111
+ patterns:
112
+ - pattern: <$EL dangerouslySetInnerHTML={{__html: $X}} />
113
+ - pattern-not: <$EL dangerouslySetInnerHTML={{__html: "..."}} />
114
+ - pattern-not: <$EL dangerouslySetInnerHTML={{__html: DOMPurify.sanitize(...)}} />
115
+ - pattern-not: <$EL dangerouslySetInnerHTML={{__html: sanitize(...)}} />
116
+ - id: open-redirect-from-request
117
+ languages: [javascript, typescript]
118
+ severity: WARNING
119
+ message: >-
120
+ The app redirects to a URL taken from the request. Attackers use this to send your users to phishing
121
+ pages under your domain. Only redirect to relative paths or an allow-list.
122
+ metadata: {title: "Open redirect", cwe: ["CWE-601"]}
123
+ pattern-either:
124
+ - pattern: $RES.redirect($REQ.query.$P)
125
+ - pattern: $RES.redirect($REQ.body.$P)
126
+ - pattern: redirect($REQ.nextUrl.searchParams.get(...))
127
+ - pattern: NextResponse.redirect(new URL($REQ.nextUrl.searchParams.get(...), ...))
128
+
129
+ # ------------------------------------------------------------------ auth & secrets in code
130
+ - id: jwt-hardcoded-secret
131
+ languages: [javascript, typescript]
132
+ severity: ERROR
133
+ message: >-
134
+ A JWT is signed or verified with a secret written in the code. Anyone who reads the code can forge
135
+ tokens and log in as any user. Load the secret from an environment variable.
136
+ metadata: {title: "JWT secret hard-coded", cwe: ["CWE-798"]}
137
+ pattern-either:
138
+ - pattern: $JWT.sign($P, "...", ...)
139
+ - pattern: $JWT.verify($T, "...", ...)
140
+ - id: jwt-decode-without-verify
141
+ languages: [javascript, typescript]
142
+ severity: WARNING
143
+ message: >-
144
+ jwt.decode() reads a token without checking its signature, so anyone can craft one. Use jwt.verify()
145
+ (or your auth provider's server helper) before trusting the token's claims.
146
+ metadata: {title: "JWT used without signature verification", cwe: ["CWE-347"]}
147
+ pattern: $JWT.decode($T, ...)
148
+ - id: supabase-service-role-client-in-browser-code
149
+ languages: [javascript, typescript]
150
+ severity: ERROR
151
+ message: >-
152
+ A Supabase client is created with a service-role key in a file marked "use client". That key bypasses
153
+ Row Level Security and would ship to every visitor. Use the anon key in the browser; keep the service
154
+ key in server-only code.
155
+ metadata: {title: "Supabase service-role key used in client code", cwe: ["CWE-200"]}
156
+ patterns:
157
+ - pattern-inside: |
158
+ "use client";
159
+ ...
160
+ - pattern: createClient($URL, $KEY, ...)
161
+ - metavariable-regex:
162
+ metavariable: $KEY
163
+ regex: (?i).*service.?role.*
164
+ - id: cors-any-origin-with-credentials
165
+ languages: [javascript, typescript]
166
+ severity: WARNING
167
+ message: >-
168
+ CORS allows any origin while also allowing credentials. Browsers combined with origin reflection let any
169
+ website make logged-in requests to your API. List your trusted origins explicitly.
170
+ metadata: {title: "CORS allows any origin with credentials", cwe: ["CWE-942"]}
171
+ pattern-either:
172
+ - pattern: |
173
+ {..., "Access-Control-Allow-Origin": "*", ..., "Access-Control-Allow-Credentials": "true", ...}
174
+ - pattern: |
175
+ cors({..., origin: true, ..., credentials: true, ...})
176
+ - pattern: |
177
+ cors({..., origin: "*", ..., credentials: true, ...})
178
+
179
+ # ------------------------------------------------------------------ crypto
180
+ - id: weak-password-hash
181
+ languages: [javascript, typescript, python]
182
+ severity: WARNING
183
+ message: >-
184
+ MD5 / SHA-1 are fast hashes and unsafe for passwords or tokens. Use bcrypt, scrypt or argon2 for
185
+ passwords, and SHA-256+ elsewhere.
186
+ metadata: {title: "Weak hash algorithm", cwe: ["CWE-328"]}
187
+ pattern-either:
188
+ - pattern: crypto.createHash("md5")
189
+ - pattern: crypto.createHash("sha1")
190
+ - pattern: hashlib.md5(...)
191
+ - pattern: hashlib.sha1(...)
package/scan.js ADDED
@@ -0,0 +1,434 @@
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
+ async function gitleaksRun(bin, mode, target, out) {
152
+ const r = await run(bin, [mode, "--redact", "--no-banner", "--log-level", "error", "--exit-code", "0",
153
+ "--report-format", "json", "--report-path", out, target], { timeout: 900000 });
154
+ if (r.code !== 0) throw new Error((r.stderr || `gitleaks ${mode} failed`).slice(-280));
155
+ return JSON.parse((await fs.readFile(out, "utf8")) || "[]") || [];
156
+ }
157
+
158
+ async function runGitleaks(ctx, bin, tmp) {
159
+ try {
160
+ const key = (l) => sha(`${l.RuleID}|${Number(l.Entropy || 0).toFixed(3)}`);
161
+ const current = (await gitleaksRun(bin, "dir", ctx.root, path.join(tmp, "gl-dir.json")))
162
+ .map((l) => ({ ...l, File: path.relative(ctx.root, path.resolve(ctx.root, l.File)).split(path.sep).join("/") }))
163
+ .filter((l) => !ctx.isGit || ctx.fileSet.has(l.File)); // a gitignored local .env is correct practice
164
+ const findings = current.map((l) => ({ tool: "gitleaks", kind: "secret", rule: l.RuleID, title: l.RuleID,
165
+ message: l.Description, path: l.File, line: l.StartLine, key: key(l) }));
166
+ if (ctx.isGit) {
167
+ const now = new Set(findings.map((f) => `${f.path}|${f.rule}|${f.key}`));
168
+ const seen = new Set();
169
+ for (const l of await gitleaksRun(bin, "git", ctx.root, path.join(tmp, "gl-git.json"))) {
170
+ const id = `${l.File}|${l.RuleID}|${key(l)}`;
171
+ if (now.has(id) || seen.has(id)) continue; // still in the tree (reported above) or a repeat
172
+ seen.add(id);
173
+ findings.push({ tool: "gitleaks", kind: "history-secret", rule: l.RuleID, title: l.RuleID,
174
+ message: l.Description, path: l.File, line: l.StartLine, commit: (l.Commit || "").slice(0, 40) || undefined,
175
+ key: key(l) }); // author, email and commit message are deliberately not sent
176
+ }
177
+ }
178
+ const v = await run(bin, ["version"], { timeout: 30000 });
179
+ return { status: { status: "ok", version: v.stdout.trim().slice(0, 40) }, findings };
180
+ } catch (e) {
181
+ return { status: { status: "error", detail: String(e.message).slice(0, 280) } };
182
+ }
183
+ }
184
+
185
+ // ------------------------------------------------------------------ opengrep
186
+ async function runOpengrep(ctx, bin) {
187
+ const r = await run(bin, ["scan", "--config", RULES_FILE, "--json", "--quiet", ctx.root], { cwd: ctx.root, timeout: 900000 });
188
+ let data;
189
+ try { data = JSON.parse(r.stdout); } catch {
190
+ return { status: { status: "error", detail: (r.stderr || "opengrep produced no JSON").slice(-280) } };
191
+ }
192
+ const fatal = (data.errors || []).filter((e) => e.level === "error" && !e.path);
193
+ if (fatal.length && !(data.results || []).length) {
194
+ return { status: { status: "error", detail: String(fatal[0].message || fatal[0].type).slice(0, 280) } };
195
+ }
196
+ const findings = [];
197
+ for (const res of data.results || []) {
198
+ const rel = path.relative(ctx.root, path.resolve(ctx.root, res.path)).split(path.sep).join("/");
199
+ if (ctx.isGit && !ctx.fileSet.has(rel)) continue;
200
+ const meta = res.extra?.metadata || {};
201
+ const rule = String(res.check_id || "").split(".").pop();
202
+ findings.push({ tool: "opengrep", kind: "sast", rule, severity: res.extra?.severity, title: meta.title || rule,
203
+ message: res.extra?.message, path: rel, line: res.start?.line,
204
+ cwe: [].concat(meta.cwe || []).map((c) => String(c).split(":")[0]).slice(0, 5),
205
+ refs: [].concat(meta.references || []).slice(0, 3),
206
+ key: sha(`${rule}|${(res.extra?.lines || "").replace(/\s+/g, " ").trim()}`) });
207
+ }
208
+ const v = await run(bin, ["--version"], { timeout: 30000 });
209
+ return { status: { status: "ok", version: v.stdout.trim().slice(0, 40) }, findings };
210
+ }
211
+
212
+ // ------------------------------------------------------------------ Sentinel built-in checks
213
+ const ENV_FILE = /(^|\/)\.env(\.[A-Za-z0-9_.-]+)?$/;
214
+ const ENV_TEMPLATE = /\.(example|sample|template|tpl|dist)$/i;
215
+ const PUBLIC_VAR = /\b((?:NEXT_PUBLIC|VITE|EXPO_PUBLIC|REACT_APP|NUXT_PUBLIC|GATSBY|PUBLIC)_[A-Z0-9_]+)/g;
216
+ 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)/;
217
+ const SOURCE = /\.(js|jsx|ts|tsx|mjs|cjs|vue|svelte|astro)$/;
218
+ const IDENT = String.raw`(?:"?[A-Za-z_][\w$]*"?\.)?"?[A-Za-z_][\w$]*"?`;
219
+
220
+ function tableName(raw) {
221
+ const parts = raw.replace(/"/g, "").toLowerCase().split(".");
222
+ return parts.length === 2 ? { schema: parts[0], name: parts[1] } : { schema: "public", name: parts[0] };
223
+ }
224
+ const stripSqlComments = (s) => s.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, " ")).replace(/--[^\n]*/g, (m) => " ".repeat(m.length));
225
+
226
+ async function supabaseChecks(ctx) {
227
+ const sqlFiles = ctx.files.filter((f) => /\.sql$/i.test(f) && /(^|\/)(supabase|migrations|db)\//i.test(f)).sort();
228
+ if (!sqlFiles.length) return [];
229
+ const tables = new Map(); // name -> {path, line, rls}
230
+ const policies = new Map(); // table:policy -> {path, line}
231
+ const events = new RegExp(String.raw`create\s+(?:unlogged\s+)?table\s+(?:if\s+not\s+exists\s+)?(${IDENT})` +
232
+ String.raw`|alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?(${IDENT})\s+(enable|disable)\s+row\s+level\s+security` +
233
+ String.raw`|drop\s+table\s+(?:if\s+exists\s+)?(${IDENT})` +
234
+ String.raw`|create\s+policy\s+("[^"]+"|\w+)\s+on\s+(?:table\s+)?(${IDENT})([\s\S]*?);` +
235
+ String.raw`|drop\s+policy\s+(?:if\s+exists\s+)?("[^"]+"|\w+)\s+on\s+(?:table\s+)?(${IDENT})`, "gi");
236
+ for (const f of sqlFiles) {
237
+ const raw = await read(ctx.root, f);
238
+ if (!raw) continue;
239
+ const text = stripSqlComments(raw);
240
+ for (const m of text.matchAll(events)) {
241
+ const line = lineOf(text, m.index);
242
+ if (m[1]) { const t = tableName(m[1]); if (t.schema === "public") tables.set(t.name, { path: f, line, rls: false }); }
243
+ else if (m[2]) { const t = tableName(m[2]); if (tables.has(t.name)) tables.get(t.name).rls = m[3].toLowerCase() === "enable"; }
244
+ else if (m[4]) tables.delete(tableName(m[4]).name);
245
+ else if (m[5]) {
246
+ const t = tableName(m[6]).name, body = m[7] || "";
247
+ const id = `${t}:${m[5].replace(/"/g, "")}`;
248
+ if (/\busing\s*\(\s*true\s*\)|\bwith\s+check\s*\(\s*true\s*\)/i.test(body)) policies.set(id, { path: f, line });
249
+ else policies.delete(id);
250
+ } else if (m[8]) policies.delete(`${tableName(m[9]).name}:${m[8].replace(/"/g, "")}`);
251
+ }
252
+ }
253
+ const out = [];
254
+ for (const [name, t] of tables) {
255
+ if (!t.rls) out.push({ tool: "sentinel", kind: "sentinel", rule: "CODE_SUPABASE_TABLE_NO_RLS", path: t.path, line: t.line, key: name });
256
+ }
257
+ for (const [id, p] of policies) {
258
+ out.push({ tool: "sentinel", kind: "sentinel", rule: "CODE_SUPABASE_POLICY_PERMISSIVE", path: p.path, line: p.line, key: id });
259
+ }
260
+ return out;
261
+ }
262
+
263
+ async function firebaseChecks(ctx) {
264
+ const out = [];
265
+ for (const f of ctx.files.filter((f) => /(^|\/)(firestore|storage)\.rules$|\.rules$/.test(f) || /(^|\/)database\.rules\.json$/.test(f))) {
266
+ const text = await read(ctx.root, f);
267
+ if (!text) continue;
268
+ const open = f.endsWith(".json")
269
+ ? /"\.(read|write)"\s*:\s*(true|"true")/g
270
+ : /^\s*allow\s+[a-z,\s]+(?::\s*if\s+true\s*;|;)/gim;
271
+ for (const m of text.matchAll(open)) {
272
+ out.push({ tool: "sentinel", kind: "sentinel", rule: "CODE_FIREBASE_RULES_OPEN", path: f, line: lineOf(text, m.index),
273
+ key: sha(m[0].replace(/\s+/g, " ").trim()) });
274
+ }
275
+ }
276
+ return out;
277
+ }
278
+
279
+ async function envChecks(ctx) {
280
+ const out = [];
281
+ const envFiles = ctx.files.filter((f) => ENV_FILE.test(f));
282
+ if (ctx.isGit) {
283
+ for (const f of envFiles.filter((f) => !ENV_TEMPLATE.test(f))) {
284
+ if (ctx.tracked.has(f)) out.push({ tool: "sentinel", kind: "sentinel", rule: "CODE_ENV_FILE_COMMITTED", path: f, key: f });
285
+ else if (ctx.unignored.has(f)) out.push({ tool: "sentinel", kind: "sentinel", rule: "CODE_ENV_NOT_GITIGNORED", path: f, key: f });
286
+ }
287
+ }
288
+ // Secret-looking names in browser-exposed env vars: env files (incl. templates) and source code.
289
+ const named = new Map();
290
+ for (const f of [...envFiles, ...ctx.files.filter((f) => SOURCE.test(f) && !/\.min\.js$/.test(f)).slice(0, 8000)]) {
291
+ const text = await read(ctx.root, f);
292
+ if (!text) continue;
293
+ for (const m of text.matchAll(PUBLIC_VAR)) {
294
+ const name = m[1];
295
+ if (SECRET_NAME.test(name) && !named.has(name)) {
296
+ named.set(name, { path: f, line: lineOf(text, m.index) });
297
+ }
298
+ }
299
+ }
300
+ 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 });
301
+ return out;
302
+ }
303
+
304
+ async function headersCheck(ctx) {
305
+ const cfg = ctx.files.find((f) => /^(?:[^/]+\/)?(next|vite)\.config\.(js|mjs|ts|cjs)$/.test(f));
306
+ if (!cfg) return [];
307
+ const has = async (f, re) => { const t = ctx.fileSet.has(f) ? await read(ctx.root, f) : null; return !!(t && re.test(t)); };
308
+ const dir = cfg.includes("/") ? cfg.slice(0, cfg.lastIndexOf("/") + 1) : "";
309
+ const HEADER = /Content-Security-Policy|Strict-Transport-Security|X-Frame-Options|frame-ancestors/i;
310
+ const checks = [
311
+ has(cfg, /\bheaders\s*\(|\bheaders\s*:/), has(`${dir}vercel.json`, /"headers"\s*:/), has("vercel.json", /"headers"\s*:/),
312
+ has(`${dir}netlify.toml`, /\[\[headers\]\]/), has("netlify.toml", /\[\[headers\]\]/),
313
+ Promise.resolve(ctx.fileSet.has(`${dir}public/_headers`) || ctx.fileSet.has(`${dir}_headers`) || ctx.fileSet.has("public/_headers")),
314
+ ...["middleware.ts", "middleware.js", "src/middleware.ts", "src/middleware.js"].map((m) => has(`${dir}${m}`, HEADER)),
315
+ ];
316
+ if ((await Promise.all(checks)).some(Boolean)) return [];
317
+ return [{ tool: "sentinel", kind: "sentinel", rule: "CODE_SECURITY_HEADERS_MISSING", path: cfg, key: cfg }];
318
+ }
319
+
320
+ export async function sentinelChecks(ctx) {
321
+ return (await Promise.all([supabaseChecks(ctx), firebaseChecks(ctx), envChecks(ctx), headersCheck(ctx)])).flat();
322
+ }
323
+
324
+ // ------------------------------------------------------------------ orchestration
325
+ export async function scan(dir = process.cwd(), { trigger = "cli", log = () => {} } = {}) {
326
+ const ctx = await context(dir);
327
+ const tmp = await fs.mkdtemp(path.join(os.tmpdir(), "sentinel-"));
328
+ const tools = {}, findings = [];
329
+ let components = [];
330
+ try {
331
+ const bins = { trivy: which("trivy"), gitleaks: which("gitleaks"), opengrep: which("opengrep") };
332
+ const jobs = [];
333
+ if (bins.trivy) {
334
+ log("trivy: dependencies + infrastructure config…");
335
+ jobs.push(runTrivy(ctx, bins.trivy, !bins.gitleaks, tmp).then((r) => { tools.trivy = r.status; findings.push(...(r.findings || [])); components = r.components || []; }));
336
+ } else tools.trivy = { status: "missing", detail: INSTALL_HINTS.trivy };
337
+ if (bins.gitleaks) {
338
+ log("gitleaks: secrets in files and git history…");
339
+ jobs.push(runGitleaks(ctx, bins.gitleaks, tmp).then((r) => { tools.gitleaks = r.status; findings.push(...(r.findings || [])); }));
340
+ } else tools.gitleaks = { status: "missing", detail: INSTALL_HINTS.gitleaks };
341
+ if (bins.opengrep) {
342
+ log("opengrep: insecure code patterns…");
343
+ jobs.push(runOpengrep(ctx, bins.opengrep).then((r) => { tools.opengrep = r.status; findings.push(...(r.findings || [])); }));
344
+ } else tools.opengrep = { status: "missing", detail: INSTALL_HINTS.opengrep };
345
+ log("sentinel: Supabase, Firebase, env files, headers…");
346
+ jobs.push(sentinelChecks(ctx).then((f) => { tools.sentinel = { status: "ok" }; findings.push(...f); },
347
+ (e) => { tools.sentinel = { status: "error", detail: String(e.message).slice(0, 280) }; }));
348
+ await Promise.all(jobs.map((j) => j.catch((e) => log(`engine failed: ${e.message}`))));
349
+ } finally {
350
+ await fs.rm(tmp, { recursive: true, force: true });
351
+ }
352
+ const manifest = ctx.files.filter((f) => f.split("/").length <= 4).sort((a, b) => a.split("/").length - b.split("/").length).slice(0, 400);
353
+ return {
354
+ repo: ctx.repo, branch: ctx.branch || undefined, default_branch: ctx.defaultBranch || undefined,
355
+ commit: ctx.commit || undefined, trigger, tools, findings: findings.slice(0, 5000),
356
+ components: dedupe(components).slice(0, 10000), manifest_paths: manifest,
357
+ };
358
+ }
359
+
360
+ function dedupe(components) {
361
+ const seen = new Set();
362
+ return components.filter((c) => {
363
+ const k = `${c.ecosystem}|${c.name}|${c.version}`;
364
+ if (!c.name || seen.has(k)) return false;
365
+ seen.add(k);
366
+ return true;
367
+ });
368
+ }
369
+
370
+ // ------------------------------------------------------------------ upload
371
+ export async function upload(payload, { base, key, log = () => {} }) {
372
+ const url = base.replace(/\/$/, "") + "/api/mcp/code-scan";
373
+ let last;
374
+ for (let attempt = 0; attempt < 4; attempt++) { // the free-tier API can be cold-starting (~50 s)
375
+ try {
376
+ const res = await fetch(url, { method: "POST", signal: AbortSignal.timeout(120000),
377
+ headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" }, body: JSON.stringify(payload) });
378
+ const text = await res.text();
379
+ let data; try { data = JSON.parse(text); } catch { data = { detail: text.slice(0, 300) }; }
380
+ if (res.ok) return data;
381
+ const detail = typeof data.detail === "string" ? data.detail : JSON.stringify(data.detail);
382
+ if (![502, 503, 504].includes(res.status)) throw Object.assign(new Error(detail || `Upload failed (${res.status})`), { fatal: true });
383
+ last = new Error(detail || `Upload failed (${res.status})`);
384
+ } catch (e) {
385
+ if (e.fatal) throw e;
386
+ last = e;
387
+ }
388
+ log(`upload attempt ${attempt + 1} failed (${last.message}); retrying…`);
389
+ await new Promise((r) => setTimeout(r, 5000 * (attempt + 1)));
390
+ }
391
+ throw last;
392
+ }
393
+
394
+ // ------------------------------------------------------------------ report
395
+ const where = (i) => {
396
+ const l = i.location || {};
397
+ if (l.path) return l.path + (l.line ? `:${l.line}` : "");
398
+ return i.domain || l.domain || "";
399
+ };
400
+
401
+ export function report(result, payload) {
402
+ const lines = [];
403
+ const mode = result.preview
404
+ ? `PREVIEW of branch ${result.branch} (default branch is ${result.default_branch}; issue status changes only when the default branch is scanned)`
405
+ : result.baseline ? "baseline (first scan of this repo)" : "issues updated";
406
+ lines.push(`Sentinel code scan of ${result.repo} — ${mode}.`);
407
+ const sev = result.open_by_severity || {};
408
+ 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.`);
409
+ const missing = Object.entries(payload.tools).filter(([, s]) => s.status !== "ok");
410
+ for (const [t, s] of missing) lines.push(` ! ${t} ${s.status}${s.detail ? `: ${s.detail}` : ""}`);
411
+ if (missing.length) lines.push(" (Checks from a missing or failed engine are not assessed, and its existing issues stay open.)");
412
+ if (result.fixed_issues?.length) {
413
+ lines.push("", "Fixed:");
414
+ for (const i of result.fixed_issues.slice(0, 15)) lines.push(` ✓ [${i.severity}] ${i.title} ${where(i)}`);
415
+ }
416
+ if (result.new_issues?.length) {
417
+ lines.push("", "New:");
418
+ for (const i of result.new_issues.slice(0, 20)) lines.push(` + [${i.severity}] ${i.title} ${where(i)}${i.id ? ` (id ${i.id})` : ""}`);
419
+ }
420
+ const top = (result.issues || []).filter((i) => !(result.new_issues || []).some((n) => n.id && n.id === i.id)).slice(0, 15);
421
+ if (top.length) {
422
+ lines.push("", "Open:");
423
+ for (const i of top) lines.push(` - [${i.severity}] ${i.title} ${where(i)}${i.id ? ` (id ${i.id})` : ""}`);
424
+ }
425
+ if (result.dashboard_url) lines.push("", `Dashboard: ${result.dashboard_url}`);
426
+ return lines.join("\n");
427
+ }
428
+
429
+ const RANK = ["informational", "low", "medium", "high", "critical"];
430
+ export function shouldFail(result, threshold) {
431
+ if (!threshold || threshold === "none") return false;
432
+ const min = RANK.indexOf(threshold);
433
+ return (result.new_issues || []).some((i) => RANK.indexOf(i.severity) >= min);
434
+ }