@agenticcli/shipguard 0.1.0 → 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
@@ -4,24 +4,52 @@ CLI-first release gate for AI-built apps.
4
4
 
5
5
  Catches secrets leaks, auth gaps, payment webhook risks, destructive migrations, and deployment misconfigurations — before your code ships.
6
6
 
7
- ## Install
7
+ ## 30-second quickstart
8
8
 
9
9
  ```bash
10
+ # Zero install — scan right now
11
+ npx @agenticcli/shipguard scan
12
+
13
+ # Or install globally
10
14
  npm install -g @agenticcli/shipguard
15
+
16
+ # Then run from any project directory
17
+ shipguard scan
11
18
  ```
12
19
 
20
+ > **PATH gotcha:** `npm install` (without `-g`) does NOT put `shipguard` on your PATH.
21
+ > Use `npx @agenticcli/shipguard scan` or install with `npm install -g @agenticcli/shipguard`.
22
+
13
23
  ## Usage
14
24
 
15
25
  ```bash
16
- shipguard init # Initialize policy file
17
- shipguard scan # Run all checks
18
- shipguard scan --strict # Fail on high-risk issues (for CI)
19
- shipguard scan --json # Machine-readable output
26
+ shipguard scan # Scan current project (rich output)
27
+ shipguard scan --strict # CI mode: exit 1 on blocking findings
28
+ shipguard scan --json # Machine-readable output for agents/CI
29
+ shipguard scan --quiet # One-line verdict only
30
+ shipguard scan --pro # Pro rules — requires login
31
+ shipguard login # Authenticate for Pro rules
32
+ shipguard init # Generate .shipguard.yml policy file
20
33
  ```
21
34
 
35
+ ## Exit codes
36
+
37
+ | Code | Meaning |
38
+ |------|---------|
39
+ | `0` | Safe — no blocking findings |
40
+ | `1` | Blocked — `--strict` mode + blocking findings |
41
+ | `2` | Config error / degraded scan |
42
+ | `3` | Runtime error |
43
+
44
+ ## Telemetry
45
+
46
+ ShipGuard sends an anonymous usage ping on each scan (verdict bucket, duration, CLI version, CI flag — never file contents, paths, or user identity). Opt out: `SHIPGUARD_TELEMETRY=0` or `DO_NOT_TRACK=1`.
47
+
48
+ Details: [agenticcli.dev/docs#telemetry](https://agenticcli.dev/docs#telemetry)
49
+
22
50
  ## Documentation
23
51
 
24
- See [full docs](https://agenticcli.dev/shipguard) for policy configuration, CI setup, and agent integration.
52
+ See [full docs](https://agenticcli.dev/docs) for policy configuration, CI setup, and agent integration.
25
53
 
26
54
  ## License
27
55
 
@@ -0,0 +1,115 @@
1
+ // src/utils/fs.ts
2
+ import fg from "fast-glob";
3
+ import { readFile, stat } from "fs/promises";
4
+ import { join } from "path";
5
+ var DEFAULT_MAX_FILE_SIZE_BYTES = 512 * 1024;
6
+ var DEFAULT_MAX_TOTAL_BYTES = 256 * 1024 * 1024;
7
+ var DEFAULT_MAX_FILES = 5e3;
8
+ var BINARY_CHECK_BYTES = 8192;
9
+ var DEFAULT_IGNORE = [
10
+ "node_modules/**",
11
+ "dist/**",
12
+ "build/**",
13
+ ".next/**",
14
+ "coverage/**",
15
+ ".git/**",
16
+ "*.lock",
17
+ "pnpm-lock.yaml",
18
+ "package-lock.json",
19
+ // Extended — large artifact directories
20
+ ".cache/**",
21
+ ".turbo/**",
22
+ ".venv/**",
23
+ "venv/**",
24
+ "vendor/**",
25
+ "tmp/**",
26
+ "out/**",
27
+ // Large file extensions — binary and generated
28
+ "*.log",
29
+ "*.min.js",
30
+ "*.map",
31
+ "*.png",
32
+ "*.jpg",
33
+ "*.jpeg",
34
+ "*.gif",
35
+ "*.webp",
36
+ "*.ico",
37
+ "*.pdf",
38
+ "*.zip",
39
+ "*.gz",
40
+ "*.tar",
41
+ "*.mp4",
42
+ "*.mov",
43
+ "*.wasm",
44
+ "*.node",
45
+ ".DS_Store",
46
+ // ShipGuard's own report output — never scan the tool's own artifacts
47
+ ".shipguard/**"
48
+ ];
49
+ async function readFiles(rootDir, patterns = ["**/*"], ignorePatterns = [], options = {}) {
50
+ const maxFileSizeBytes = options.maxFileSizeBytes ?? DEFAULT_MAX_FILE_SIZE_BYTES;
51
+ const maxTotalBytes = options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES;
52
+ const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES;
53
+ const { onProgress } = options;
54
+ const allIgnore = [...DEFAULT_IGNORE, ...ignorePatterns];
55
+ const filePaths = await fg(patterns, {
56
+ cwd: rootDir,
57
+ ignore: allIgnore,
58
+ dot: true,
59
+ absolute: false,
60
+ onlyFiles: true
61
+ });
62
+ const total = filePaths.length;
63
+ const files = [];
64
+ let skippedTooLarge = 0;
65
+ let skippedBinary = 0;
66
+ let truncated = false;
67
+ let totalBytes = 0;
68
+ let processed = 0;
69
+ for (const fp of filePaths) {
70
+ if (files.length >= maxFiles || totalBytes >= maxTotalBytes) {
71
+ truncated = true;
72
+ break;
73
+ }
74
+ const fullPath = join(rootDir, fp);
75
+ try {
76
+ const fileStat = await stat(fullPath);
77
+ if (fileStat.size > maxFileSizeBytes) {
78
+ skippedTooLarge++;
79
+ onProgress?.(++processed, total, fp);
80
+ continue;
81
+ }
82
+ const buffer = await readFile(fullPath);
83
+ const checkLen = Math.min(buffer.length, BINARY_CHECK_BYTES);
84
+ let isBinary = false;
85
+ for (let i = 0; i < checkLen; i++) {
86
+ if (buffer[i] === 0) {
87
+ isBinary = true;
88
+ break;
89
+ }
90
+ }
91
+ if (isBinary) {
92
+ skippedBinary++;
93
+ onProgress?.(++processed, total, fp);
94
+ continue;
95
+ }
96
+ const content = buffer.toString("utf-8");
97
+ totalBytes += buffer.length;
98
+ files.push({
99
+ path: fullPath,
100
+ content,
101
+ relativePath: fp
102
+ });
103
+ } catch {
104
+ }
105
+ onProgress?.(++processed, total, fp);
106
+ }
107
+ return { files, skippedTooLarge, skippedBinary, truncated };
108
+ }
109
+
110
+ export {
111
+ DEFAULT_MAX_FILE_SIZE_BYTES,
112
+ DEFAULT_MAX_TOTAL_BYTES,
113
+ DEFAULT_MAX_FILES,
114
+ readFiles
115
+ };
@@ -58,9 +58,12 @@ async function getAuthToken() {
58
58
  // src/core/crypto.ts
59
59
  import { hkdf } from "@noble/hashes/hkdf.js";
60
60
  import { sha256 } from "@noble/hashes/sha2.js";
61
- var FALLBACK_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
61
+ var PINNED_KEYS = {
62
+ "k1-2026": `-----BEGIN PUBLIC KEY-----
62
63
  MCowBQYDK2VwAyEAkpeX0A3zIOttGn8t+jagJHLRTv5Q809vqIZU37lE6xQ=
63
- -----END PUBLIC KEY-----`;
64
+ -----END PUBLIC KEY-----`
65
+ };
66
+ var DEFAULT_KID = "k1-2026";
64
67
  var HKDF_INFO = "shipguard-rules-v1";
65
68
  function pemToArrayBuffer(pem) {
66
69
  const b64 = pem.replace(/-----BEGIN PUBLIC KEY-----/, "").replace(/-----END PUBLIC KEY-----/, "").replace(/\s/g, "");
@@ -70,7 +73,14 @@ function pemToArrayBuffer(pem) {
70
73
  async function verifyAndDecryptBundle(bundleB64, accessToken) {
71
74
  const bundleJson = Buffer.from(bundleB64, "base64").toString("utf-8");
72
75
  const bundle = JSON.parse(bundleJson);
73
- const pem = process.env.SHIPGUARD_PUBLIC_KEY ?? FALLBACK_PUBLIC_KEY;
76
+ const kid = bundle.payload.kid ?? DEFAULT_KID;
77
+ const resolvedPem = PINNED_KEYS[kid];
78
+ if (!resolvedPem && !process.env.SHIPGUARD_PUBLIC_KEY) {
79
+ throw new Error(
80
+ `Unknown signing key "${kid}" \u2014 rule bundle rejected (fail closed). Upgrade shipguard to a version that supports this key id.`
81
+ );
82
+ }
83
+ const pem = process.env.SHIPGUARD_PUBLIC_KEY ?? resolvedPem;
74
84
  const cryptoKey = await globalThis.crypto.subtle.importKey(
75
85
  "spki",
76
86
  pemToArrayBuffer(pem),
@@ -115,7 +125,7 @@ async function verifyAndDecryptBundle(bundleB64, accessToken) {
115
125
  }
116
126
  async function verifyRuleBundle(token) {
117
127
  const { importSPKI: importKey, jwtVerify } = await import("jose");
118
- const pem = process.env.SHIPGUARD_PUBLIC_KEY ?? FALLBACK_PUBLIC_KEY;
128
+ const pem = process.env.SHIPGUARD_PUBLIC_KEY ?? PINNED_KEYS[DEFAULT_KID];
119
129
  const publicKey = await importKey(pem, "EdDSA");
120
130
  const { payload } = await jwtVerify(token, publicKey);
121
131
  return payload;
@@ -145,6 +155,7 @@ var SECRET_PATTERNS = [
145
155
  name: "OpenAI API Key",
146
156
  regex: /['"]?(sk-proj-[a-zA-Z0-9_\-]{20,})['"]?/m,
147
157
  severity: "high",
158
+ confidence: "HIGH",
148
159
  explanation: "Hardcoded OpenAI API key detected. Leaking this key allows unauthorized use of your OpenAI account, incurring charges.",
149
160
  recommendation: "Remove the key from source code. Use process.env.OPENAI_API_KEY and store the value in a .env file that is gitignored."
150
161
  },
@@ -154,6 +165,7 @@ var SECRET_PATTERNS = [
154
165
  name: "OpenAI Legacy API Key",
155
166
  regex: /(?:openai[_\-]?(?:api[_\-]?)?key|OPENAI[_\-]?(?:API[_\-]?)?KEY)\s*[=:]\s*['"]?(sk-[a-zA-Z0-9]{20,})['"]?/im,
156
167
  severity: "high",
168
+ confidence: "HIGH",
157
169
  explanation: "Hardcoded OpenAI API key detected. Leaking this key allows unauthorized use of your OpenAI account, incurring charges.",
158
170
  recommendation: "Remove the key from source code. Use process.env.OPENAI_API_KEY and store the value in a .env file that is gitignored."
159
171
  },
@@ -163,6 +175,7 @@ var SECRET_PATTERNS = [
163
175
  name: "Anthropic API Key",
164
176
  regex: /['"]?(sk-ant-(?:api\d+-)?[a-zA-Z0-9_\-]{20,})['"]?/im,
165
177
  severity: "high",
178
+ confidence: "HIGH",
166
179
  explanation: "Hardcoded Anthropic API key detected. Leaking this key allows unauthorized use of Anthropic Claude, incurring charges.",
167
180
  recommendation: "Remove the key from source code. Use process.env.ANTHROPIC_API_KEY and store the value in a .env file that is gitignored."
168
181
  },
@@ -172,6 +185,7 @@ var SECRET_PATTERNS = [
172
185
  name: "Stripe Live Secret Key",
173
186
  regex: /['"]?(sk_live_[a-zA-Z0-9]{24,})['"]?/im,
174
187
  severity: "critical",
188
+ confidence: "HIGH",
175
189
  explanation: "Hardcoded Stripe live secret key detected. This key can be used to make charges, refunds, and access customer data in your live Stripe account.",
176
190
  recommendation: "Remove immediately. Use process.env.STRIPE_SECRET_KEY. Rotate the key in the Stripe Dashboard."
177
191
  },
@@ -181,6 +195,7 @@ var SECRET_PATTERNS = [
181
195
  name: "Stripe Test Secret Key",
182
196
  regex: /['"]?(sk_test_[a-zA-Z0-9]{24,})['"]?/im,
183
197
  severity: "medium",
198
+ confidence: "HIGH",
184
199
  explanation: "Hardcoded Stripe test secret key detected. While test keys cannot process real payments, committing them is a bad practice that often leads to live key exposure.",
185
200
  recommendation: "Remove from source code. Use process.env.STRIPE_SECRET_KEY with a .env file that is gitignored."
186
201
  },
@@ -190,6 +205,7 @@ var SECRET_PATTERNS = [
190
205
  name: "AWS Access Key ID",
191
206
  regex: /['"]?(AKIA[0-9A-Z]{16})['"]?/m,
192
207
  severity: "high",
208
+ confidence: "HIGH",
193
209
  explanation: "Hardcoded AWS Access Key ID detected. Combined with the secret key, this allows full AWS API access under your account.",
194
210
  recommendation: "Remove and rotate immediately via IAM. Use environment variables or AWS credential profiles instead."
195
211
  },
@@ -199,6 +215,7 @@ var SECRET_PATTERNS = [
199
215
  name: "AWS Secret Access Key",
200
216
  regex: /(?:aws[_\-]?secret[_\-]?(?:access[_\-]?)?key|AWS_SECRET_ACCESS_KEY)\s*[=:]\s*['"]?([a-zA-Z0-9\/+]{40})['"]?/im,
201
217
  severity: "high",
218
+ confidence: "HIGH",
202
219
  explanation: "Hardcoded AWS Secret Access Key detected. This credential enables full programmatic access to AWS services.",
203
220
  recommendation: "Remove and rotate immediately via IAM. Use environment variables or AWS credential profiles instead."
204
221
  },
@@ -208,6 +225,7 @@ var SECRET_PATTERNS = [
208
225
  name: "Google API Key",
209
226
  regex: /['"]?(AIza[0-9A-Za-z\-_]{35})['"]?/m,
210
227
  severity: "high",
228
+ confidence: "HIGH",
211
229
  explanation: "Hardcoded Google API key detected. This key can be used to access Google Cloud services or Google Maps, incurring charges.",
212
230
  recommendation: "Remove from source code. Restrict key usage in the Google Cloud Console and use environment variables."
213
231
  },
@@ -217,6 +235,7 @@ var SECRET_PATTERNS = [
217
235
  name: "GitHub Personal Access Token",
218
236
  regex: /['"]?(ghp_[a-zA-Z0-9]{36}|github_pat_[a-zA-Z0-9_]{82})['"]?/m,
219
237
  severity: "high",
238
+ confidence: "HIGH",
220
239
  explanation: "Hardcoded GitHub Personal Access Token detected. This token grants access to GitHub repositories and actions under your account.",
221
240
  recommendation: "Remove and revoke the token at github.com/settings/tokens. Use environment variables."
222
241
  },
@@ -226,6 +245,7 @@ var SECRET_PATTERNS = [
226
245
  name: "Razorpay Secret Key",
227
246
  regex: /(?:razorpay[_\-]?(?:key[_\-]?)?secret|RAZORPAY_KEY_SECRET)\s*[=:]\s*['"]?([a-zA-Z0-9]{20,})['"]?/im,
228
247
  severity: "high",
248
+ confidence: "HIGH",
229
249
  explanation: "Hardcoded Razorpay secret key detected. This allows unauthorized access to your Razorpay payment account.",
230
250
  recommendation: "Remove from source code. Use process.env.RAZORPAY_KEY_SECRET and store in a gitignored .env file."
231
251
  },
@@ -235,6 +255,7 @@ var SECRET_PATTERNS = [
235
255
  name: "JWT Secret",
236
256
  regex: /(?:jwt[_\-]?secret|JWT_SECRET)\s*[=:]\s*['"]([^'"]{16,})['"]?/im,
237
257
  severity: "high",
258
+ confidence: "HIGH",
238
259
  explanation: "Hardcoded JWT secret detected. Exposing this allows attackers to forge valid JWT tokens and bypass authentication.",
239
260
  recommendation: "Remove from source code. Generate a strong random secret, store it in environment variables."
240
261
  },
@@ -245,6 +266,7 @@ var SECRET_PATTERNS = [
245
266
  name: "Database URL with Credentials",
246
267
  regex: /(?:(?:database[_\-]?url|DATABASE_URL|db[_\-]?url|DB_URL|connection[_\-]?string|CONNECTION_STRING)\s*[=:]\s*)?['"]?((?:postgres|postgresql|mysql|mongodb|mongodb\+srv|redis|amqp|rabbitmq):\/\/[^:'"]+:[^@'"]+@[^'"]+)['"]?/im,
247
268
  severity: "critical",
269
+ confidence: "HIGH",
248
270
  explanation: "Database URL with embedded credentials detected. This exposes the database host, username, and password directly.",
249
271
  recommendation: "Remove credentials from the URL. Use environment variables and ensure the .env file is gitignored."
250
272
  },
@@ -255,6 +277,7 @@ var SECRET_PATTERNS = [
255
277
  name: "High-Entropy Secret String",
256
278
  regex: /(?:api[_\-]?key|secret|token|password|passwd|auth[_\-]?key|access[_\-]?key)\s*[=:]\s*['"]([a-zA-Z0-9\/+_\-]{32,64})['"](?!\s*\+|\.)/im,
257
279
  severity: "medium",
280
+ confidence: "MEDIUM",
258
281
  explanation: "A variable with a secret-sounding name is assigned a long literal string that resembles an API key or token.",
259
282
  recommendation: "Move this value to a .env file and reference it via process.env. Never hardcode credentials."
260
283
  }
@@ -274,6 +297,7 @@ function checkSecrets(files, policy) {
274
297
  severity: "high",
275
298
  category: "secrets",
276
299
  file: relativePath,
300
+ confidence: "HIGH",
277
301
  explanation: "A .env file is tracked in the repository. These files often contain secrets such as API keys, database credentials, and tokens that should never be committed.",
278
302
  recommendation: "Add .env (and its variants like .env.local, .env.production) to .gitignore. Remove the file from git history using `git rm --cached .env`.",
279
303
  blocking: policy.block.includes(id)
@@ -291,6 +315,7 @@ function checkSecrets(files, policy) {
291
315
  file: relativePath,
292
316
  line: lineNum,
293
317
  evidence: pkMatch[0].trim(),
318
+ confidence: "HIGH",
294
319
  explanation: "A PEM private key block is embedded in the source file. This exposes cryptographic material that can be used to impersonate services, decrypt data, or forge signatures.",
295
320
  recommendation: "Remove the private key from the codebase immediately. Store keys in a secrets manager (e.g., AWS Secrets Manager, Vault) or as environment variables.",
296
321
  blocking: policy.block.includes(id)
@@ -311,6 +336,7 @@ function checkSecrets(files, policy) {
311
336
  file: relativePath,
312
337
  line: i + 1,
313
338
  evidence: `${line.split("=")[0].trim()}=${redact(match[1])}`,
339
+ confidence: "HIGH",
314
340
  explanation: "An environment variable with NEXT_PUBLIC_ prefix containing a secret-sounding name is used in a frontend file. NEXT_PUBLIC_ variables are bundled into client-side JavaScript and exposed to all users.",
315
341
  recommendation: "Move secret API calls to a server-side route (e.g., Next.js API route or Server Action). Never use NEXT_PUBLIC_ for keys, tokens, or secrets.",
316
342
  blocking: policy.block.includes(id)
@@ -336,6 +362,7 @@ function checkSecrets(files, policy) {
336
362
  file: relativePath,
337
363
  line: i + 1,
338
364
  evidence: `...${redact(secretValue)}...`,
365
+ confidence: pattern.confidence,
339
366
  explanation: pattern.explanation,
340
367
  recommendation: pattern.recommendation,
341
368
  blocking: policy.block.includes(pattern.id)
@@ -422,6 +449,7 @@ var authCheck = {
422
449
  severity: "high",
423
450
  category: "auth",
424
451
  file: "middleware.ts",
452
+ confidence: "MEDIUM",
425
453
  explanation: "No middleware.ts file was found. Next.js App Router relies on middleware to enforce route-level auth for admin, dashboard, and billing routes. Without it, protection depends entirely on individual Server Components and Route Handlers, which is error-prone.",
426
454
  recommendation: "Create middleware.ts at the project root (or src/middleware.ts) and add a matcher that covers /admin, /dashboard, and /billing. Use auth() from next-auth/auth.js or clerkMiddleware() to redirect unauthenticated requests.",
427
455
  blocking: policy.block.includes("public_admin_route")
@@ -433,6 +461,7 @@ var authCheck = {
433
461
  severity: "high",
434
462
  category: "auth",
435
463
  file: middlewareFile.relativePath,
464
+ confidence: "MEDIUM",
436
465
  explanation: "A middleware.ts file exists but its content does not reference admin, dashboard, billing, account, or management routes. Sensitive routes may not be protected at the edge/middleware layer.",
437
466
  recommendation: 'Add a matcher config to middleware.ts that covers protected route prefixes:\n export const config = { matcher: ["/admin/:path*", "/dashboard/:path*"] }',
438
467
  blocking: policy.block.includes("public_admin_route")
@@ -453,6 +482,7 @@ var authCheck = {
453
482
  severity: "high",
454
483
  category: "auth",
455
484
  file: rp,
485
+ confidence: "MEDIUM",
456
486
  explanation: wasRemoved ? `${rp} previously had an auth call that appears to have been commented out. This page is now accessible without authentication.` : `${rp} is in a sensitive route segment (admin/dashboard/billing) but contains no active auth call (auth(), getServerSession(), requireAuth(), etc.). Server Components must verify the session even when middleware is in place \u2014 middleware is not a security boundary (see CVE-2025-29927).`,
457
487
  recommendation: 'Add `const session = await auth()` at the top of the Server Component and redirect unauthenticated users with `if (!session) redirect("/login")`.',
458
488
  blocking: policy.block.includes("public_admin_route")
@@ -469,6 +499,7 @@ var authCheck = {
469
499
  severity: "high",
470
500
  category: "auth",
471
501
  file: rp,
502
+ confidence: "MEDIUM",
472
503
  explanation: wasRemoved ? `${rp} previously had an auth call that appears to have been commented out. This API route now responds to requests without verifying the caller.` : `${rp} is an API Route Handler under a sensitive path (admin/users/billing) but contains no auth guard. Any caller \u2014 including unauthenticated requests \u2014 can invoke it.`,
473
504
  recommendation: "Add `const session = await auth()` (next-auth) or `const { userId } = await currentUser()` (Clerk) at the start of each exported HTTP handler. Return a 401 if no session.",
474
505
  blocking: policy.block.includes("auth_route_without_guard")
@@ -484,6 +515,7 @@ var authCheck = {
484
515
  severity: "medium",
485
516
  category: "auth",
486
517
  file: rp,
518
+ confidence: "LOW",
487
519
  explanation: `${rp} registers a route on a sensitive URL segment (admin/users/billing) without an apparent auth middleware guard. In Express, protect routes by passing auth middleware before the handler or by calling router.use(authMiddleware) above the sensitive routes.`,
488
520
  recommendation: 'Use `router.use(requireAuth)` before sensitive routes, or pass it inline:\n router.get("/admin/users", requireAuth, handler)\nFor Fastify, use a `preHandler` hook or `onRequest` hook.',
489
521
  blocking: policy.block.includes("auth_route_without_guard")
@@ -532,6 +564,7 @@ var SQL_PATTERNS = [
532
564
  id: "db-drop-table",
533
565
  title: "Destructive migration: DROP TABLE",
534
566
  severity: "critical",
567
+ confidence: "HIGH",
535
568
  explanation: "DROP TABLE permanently deletes a table and all its data. In production this causes irreversible data loss and immediate application failure for any query targeting that table.",
536
569
  recommendation: "Never drop a table in the same migration that removes code references. Use an expand-contract strategy: deprecate code first, then drop in a later release after confirming no traffic.",
537
570
  pattern: /\bDROP\s+TABLE\b/i
@@ -540,6 +573,7 @@ var SQL_PATTERNS = [
540
573
  id: "db-drop-column",
541
574
  title: "Destructive migration: DROP COLUMN",
542
575
  severity: "high",
576
+ confidence: "HIGH",
543
577
  explanation: "DROP COLUMN removes a column and its data permanently. Running this while old application code still reads the column causes immediate query failures.",
544
578
  recommendation: "Deprecate the column in code first, deploy, confirm no usage, then run the drop in a separate migration.",
545
579
  pattern: /\bDROP\s+COLUMN\b/i
@@ -548,6 +582,7 @@ var SQL_PATTERNS = [
548
582
  id: "db-truncate",
549
583
  title: "Destructive migration: TRUNCATE",
550
584
  severity: "high",
585
+ confidence: "HIGH",
551
586
  explanation: "TRUNCATE deletes all rows in a table instantly without logging individual row deletions, making it very fast but also unrecoverable without a full backup restore.",
552
587
  recommendation: "Remove TRUNCATE from migration files. Data wipes should be explicit operational procedures, not automatic schema changes.",
553
588
  pattern: /\bTRUNCATE\b/i
@@ -556,6 +591,7 @@ var SQL_PATTERNS = [
556
591
  id: "db-delete-without-where",
557
592
  title: "Unsafe migration: DELETE FROM without WHERE clause",
558
593
  severity: "high",
594
+ confidence: "HIGH",
559
595
  explanation: "DELETE FROM without a WHERE clause deletes every row in the table. In a migration file this almost always indicates a copy-paste error or oversight.",
560
596
  recommendation: "Add a WHERE clause, or replace with TRUNCATE (and add a review gate) if a full wipe is truly intended.",
561
597
  pattern: /\bDELETE\s+FROM\b/i,
@@ -565,6 +601,7 @@ var SQL_PATTERNS = [
565
601
  id: "db-alter-drop",
566
602
  title: "Potentially destructive migration: ALTER TABLE DROP",
567
603
  severity: "medium",
604
+ confidence: "MEDIUM",
568
605
  explanation: "ALTER TABLE \u2026 DROP (other than DROP COLUMN, which is flagged separately) can drop constraints, indexes, or partitions. Dropping a NOT NULL constraint or unique index affects data integrity and query plans.",
569
606
  recommendation: "Review what exactly is being dropped. Ensure application code is already compatible with the removed constraint before deploying.",
570
607
  // Avoid double-flagging lines that already match DROP COLUMN (handled above)
@@ -612,6 +649,7 @@ function checkSqlFile(file, findings) {
612
649
  file: file.relativePath,
613
650
  line: lineNumber,
614
651
  evidence: evidenceLine,
652
+ confidence: pattern.confidence,
615
653
  explanation: pattern.explanation,
616
654
  recommendation: pattern.recommendation,
617
655
  blocking: pattern.severity === "critical" || pattern.severity === "high"
@@ -641,6 +679,7 @@ function checkPackageJson(file, findings) {
641
679
  category: "database",
642
680
  file: file.relativePath,
643
681
  evidence: `"${scriptName}": "${scriptValue.slice(0, 120)}"`,
682
+ confidence: "HIGH",
644
683
  explanation: `The "${tool}" command bypasses migration files and applies schema changes directly to the database without an audit trail. In production or CI this can silently drop columns, tables, or constraints with no rollback path.`,
645
684
  recommendation: 'Replace with "prisma migrate deploy" (Prisma) or "drizzle-kit migrate" (Drizzle) in all non-local scripts. Reserve db push for local prototype databases only.',
646
685
  blocking: false
@@ -661,6 +700,7 @@ function checkPrismaSchemaWithoutMigration(files, findings) {
661
700
  severity: "medium",
662
701
  category: "database",
663
702
  file: schemaFile.relativePath,
703
+ confidence: "MEDIUM",
664
704
  explanation: 'The Prisma schema was modified but no migration file appears in the changed file set. In production you must run "prisma migrate dev" to generate a migration, then commit it before deploying.',
665
705
  recommendation: 'Run "npx prisma migrate dev --name <description>" locally, commit the generated migration file in prisma/migrations/, and re-scan.',
666
706
  blocking: false
@@ -714,6 +754,7 @@ function checkNextConfig(file) {
714
754
  file: relativePath,
715
755
  line,
716
756
  evidence: "Access-Control-Allow-Origin: *",
757
+ confidence: "HIGH",
717
758
  explanation: "A wildcard CORS policy allows any origin to read responses from your API. Combined with credentials, this can expose user data to malicious sites.",
718
759
  recommendation: "Replace the wildcard with an explicit list of trusted origins in the headers() configuration.",
719
760
  blocking: true
@@ -730,6 +771,7 @@ function checkNextConfig(file) {
730
771
  file: relativePath,
731
772
  line,
732
773
  evidence: "productionBrowserSourceMaps: true",
774
+ confidence: "HIGH",
733
775
  explanation: "Enabling production source maps exposes your original application source code to anyone inspecting browser devtools, aiding reverse engineering and vulnerability discovery.",
734
776
  recommendation: "Remove productionBrowserSourceMaps: true or set it to false for production builds.",
735
777
  blocking: false
@@ -745,6 +787,7 @@ function checkNextConfig(file) {
745
787
  severity: "medium",
746
788
  category: "deployment",
747
789
  file: relativePath,
790
+ confidence: "MEDIUM",
748
791
  explanation: "X-Frame-Options prevents your site from being embedded in an iframe, protecting users against clickjacking attacks.",
749
792
  recommendation: "Add { key: 'X-Frame-Options', value: 'DENY' } to your headers() configuration in next.config.js.",
750
793
  blocking: false
@@ -757,6 +800,7 @@ function checkNextConfig(file) {
757
800
  severity: "medium",
758
801
  category: "deployment",
759
802
  file: relativePath,
803
+ confidence: "MEDIUM",
760
804
  explanation: "X-Content-Type-Options: nosniff prevents MIME-type sniffing attacks where browsers execute content as a different type than declared.",
761
805
  recommendation: "Add { key: 'X-Content-Type-Options', value: 'nosniff' } to your headers() configuration.",
762
806
  blocking: false
@@ -778,6 +822,7 @@ function checkDockerfile(file) {
778
822
  severity: "medium",
779
823
  category: "deployment",
780
824
  file: relativePath,
825
+ confidence: "MEDIUM",
781
826
  explanation: "Running containers as root amplifies the blast radius of a container escape. A non-root user limits what an attacker can do if they gain code execution inside the container.",
782
827
  recommendation: "Add a USER directive with a non-root user (e.g., USER node or create a dedicated user with addgroup/adduser).",
783
828
  blocking: false
@@ -802,6 +847,7 @@ function checkDockerfile(file) {
802
847
  file: relativePath,
803
848
  line: lineNum,
804
849
  evidence: line.trim(),
850
+ confidence: "HIGH",
805
851
  explanation: "Using :latest or no tag means the base image can change silently between builds, introducing unreviewed dependency updates or security regressions.",
806
852
  recommendation: `Pin the image to a specific digest or version tag (e.g., ${image.split(":")[0]}:20-alpine or with a SHA digest).`,
807
853
  blocking: false
@@ -828,6 +874,7 @@ function checkDockerCompose(file) {
828
874
  category: "deployment",
829
875
  file: relativePath,
830
876
  evidence: line.trim(),
877
+ confidence: "HIGH",
831
878
  explanation: "Unpinned images in docker-compose can silently pull breaking or vulnerable upstream changes.",
832
879
  recommendation: `Pin to a specific version tag or SHA digest for ${image.split(":")[0]}.`,
833
880
  blocking: false
@@ -849,6 +896,7 @@ function checkVercelConfig(file) {
849
896
  category: "deployment",
850
897
  file: relativePath,
851
898
  line,
899
+ confidence: "MEDIUM",
852
900
  explanation: "Catch-all rewrite rules can accidentally expose internal routes or proxy unintended paths, creating an open redirect or SSRF surface.",
853
901
  recommendation: "Narrow the source pattern to only the specific paths that need rewriting.",
854
902
  blocking: false
@@ -862,6 +910,7 @@ function checkVercelConfig(file) {
862
910
  severity: "medium",
863
911
  category: "deployment",
864
912
  file: relativePath,
913
+ confidence: "MEDIUM",
865
914
  explanation: "Without explicit headers in vercel.json, responses lack security headers like X-Frame-Options, X-Content-Type-Options, and CSP, leaving users exposed to clickjacking and XSS.",
866
915
  recommendation: 'Add a "headers" block to vercel.json or configure security headers in next.config.js instead.',
867
916
  blocking: false
@@ -880,6 +929,7 @@ function checkNetlifyConfig(file) {
880
929
  severity: "medium",
881
930
  category: "deployment",
882
931
  file: relativePath,
932
+ confidence: "MEDIUM",
883
933
  explanation: "Without a [[headers]] block, Netlify deployments lack security headers, exposing the app to clickjacking and content-type sniffing attacks.",
884
934
  recommendation: "Add a [[headers]] section to netlify.toml with X-Frame-Options, X-Content-Type-Options, and other security headers.",
885
935
  blocking: false
@@ -900,6 +950,7 @@ function checkEnvFiles(files) {
900
950
  severity: "low",
901
951
  category: "deployment",
902
952
  file: envFile.relativePath,
953
+ confidence: "HIGH",
903
954
  explanation: "Without a .env.example, new contributors have no template for required environment variables, increasing the risk of misconfigured deployments.",
904
955
  recommendation: "Create a .env.example file with all required variable keys (and safe placeholder values) so the team can onboard without guessing configuration.",
905
956
  blocking: false
@@ -930,6 +981,7 @@ function checkEnvFiles(files) {
930
981
  category: "deployment",
931
982
  file: envFile.relativePath,
932
983
  evidence: undocumentedKeys.join(", "),
984
+ confidence: "HIGH",
933
985
  explanation: "Keys present in .env but missing from .env.example leave teammates and deployment pipelines without the full required configuration, causing runtime failures.",
934
986
  recommendation: `Add the following keys to .env.example: ${undocumentedKeys.join(", ")}`,
935
987
  blocking: false
@@ -960,6 +1012,7 @@ function checkPackageJson2(file) {
960
1012
  category: "deployment",
961
1013
  file: relativePath,
962
1014
  evidence: `"${name}": "${value}"`,
1015
+ confidence: "HIGH",
963
1016
  explanation: "Running with NODE_ENV=development in production disables performance optimisations and may enable verbose error output, leaking stack traces to end users.",
964
1017
  recommendation: `Remove NODE_ENV=development from the "${name}" script or set NODE_ENV=production explicitly.`,
965
1018
  blocking: true
@@ -973,6 +1026,7 @@ function checkPackageJson2(file) {
973
1026
  category: "deployment",
974
1027
  file: relativePath,
975
1028
  evidence: `"${name}": "${value}"`,
1029
+ confidence: "HIGH",
976
1030
  explanation: "DEBUG=true or DEBUG=* enables verbose logging in many Node.js libraries, which can leak internal paths, secrets, and request details in production logs.",
977
1031
  recommendation: `Remove the DEBUG flag from the "${name}" script.`,
978
1032
  blocking: true
@@ -995,6 +1049,7 @@ function checkGeneralConfigs(file) {
995
1049
  file: relativePath,
996
1050
  line,
997
1051
  evidence: "origin: *",
1052
+ confidence: "MEDIUM",
998
1053
  explanation: "Setting CORS origin to * allows any website to make credentialed requests to your API, bypassing Same-Origin Policy protections.",
999
1054
  recommendation: "Replace the wildcard origin with an explicit allowlist of trusted domains.",
1000
1055
  blocking: true
@@ -1011,6 +1066,7 @@ function checkGeneralConfigs(file) {
1011
1066
  file: relativePath,
1012
1067
  line,
1013
1068
  evidence: "debug: true",
1069
+ confidence: "MEDIUM",
1014
1070
  explanation: "Debug mode in production configs exposes verbose logs, internal stack traces, and configuration details that aid attackers.",
1015
1071
  recommendation: "Set debug: false or remove the debug flag from production configuration.",
1016
1072
  blocking: true
@@ -1112,6 +1168,7 @@ var payments = {
1112
1168
  category: "payments",
1113
1169
  file: relativePath,
1114
1170
  evidence: "No call to stripe.webhooks.constructEvent() found",
1171
+ confidence: "MEDIUM",
1115
1172
  explanation: "Without calling stripe.webhooks.constructEvent(), the webhook endpoint cannot verify that requests originate from Stripe. Attackers can send forged events to trigger payment logic (e.g., fake payment_intent.succeeded) without making a real payment.",
1116
1173
  recommendation: "Verify every incoming webhook with stripe.webhooks.constructEvent(rawBody, sig, webhookSecret). Pass the raw request body \u2014 not a parsed JSON object \u2014 to prevent HMAC mismatch.",
1117
1174
  blocking: isBlocking(id, policy)
@@ -1126,6 +1183,7 @@ var payments = {
1126
1183
  category: "payments",
1127
1184
  file: relativePath,
1128
1185
  evidence: "No reference to stripe-signature header found",
1186
+ confidence: "MEDIUM",
1129
1187
  explanation: "The Stripe-Signature header carries the HMAC timestamp+hash that proves the request originated from Stripe. Without reading it, signature verification is impossible.",
1130
1188
  recommendation: 'Read the header with request.headers.get("stripe-signature") (Next.js) or req.headers["stripe-signature"] (Express) before calling constructEvent().',
1131
1189
  blocking: isBlocking(id, policy)
@@ -1142,6 +1200,7 @@ var payments = {
1142
1200
  category: "payments",
1143
1201
  file: relativePath,
1144
1202
  evidence: "No call to validateWebhookSignature() found",
1203
+ confidence: "MEDIUM",
1145
1204
  explanation: "Without validateWebhookSignature(), the webhook endpoint cannot verify that requests originate from Razorpay. An attacker can send forged payment confirmation events without completing an actual payment.",
1146
1205
  recommendation: "Use Razorpay.validateWebhookSignature(rawBody, signature, webhookSecret) where signature is taken from the x-razorpay-signature header. Always pass the raw (unparsed) body.",
1147
1206
  blocking: isBlocking(id, policy)
@@ -1160,6 +1219,7 @@ var payments = {
1160
1219
  category: "payments",
1161
1220
  file: relativePath,
1162
1221
  evidence: "Reference to STRIPE_SECRET_KEY found in a client-bundle file",
1222
+ confidence: "MEDIUM",
1163
1223
  explanation: "STRIPE_SECRET_KEY is a server-only secret. If it is bundled into client-side code it will be exposed in the browser, allowing anyone to make API calls on your behalf \u2014 creating charges, accessing customer data, or issuing refunds.",
1164
1224
  recommendation: "Move Stripe secret key usage exclusively to API routes (app/api/ or pages/api/). Use NEXT_PUBLIC_ prefix only for the Stripe publishable key.",
1165
1225
  blocking: isBlocking(id, policy)
@@ -1174,6 +1234,7 @@ var payments = {
1174
1234
  category: "payments",
1175
1235
  file: relativePath,
1176
1236
  evidence: "Reference to RAZORPAY_KEY_SECRET found in a client-bundle file",
1237
+ confidence: "MEDIUM",
1177
1238
  explanation: "RAZORPAY_KEY_SECRET is a server-only secret. Exposure in client-side code allows attackers to forge payment signatures and verify payments without completing them.",
1178
1239
  recommendation: "Use RAZORPAY_KEY_SECRET only in server-side API routes. For the client, only use the Razorpay key_id (public).",
1179
1240
  blocking: isBlocking(id, policy)
@@ -1190,6 +1251,7 @@ var payments = {
1190
1251
  category: "payments",
1191
1252
  file: relativePath,
1192
1253
  evidence: "No idempotency key, event.id check, or duplicate-detection logic found",
1254
+ confidence: "LOW",
1193
1255
  explanation: "Payment providers may deliver the same webhook event more than once (retries after network failure, provider-side bugs). Without idempotency guards, duplicate deliveries can cause double-charges, double-fulfillments, or double-refunds.",
1194
1256
  recommendation: "Record processed event IDs (e.g., store event.id in a database) before acting on the event. If the ID already exists, return 200 immediately without reprocessing.",
1195
1257
  blocking: isBlocking(id, policy)
@@ -1206,6 +1268,7 @@ var payments = {
1206
1268
  category: "payments",
1207
1269
  file: relativePath,
1208
1270
  evidence: "No try/catch block found in payment-related route",
1271
+ confidence: "LOW",
1209
1272
  explanation: "Unhandled exceptions in payment routes can leak stack traces to the client, cause silent failures in payment processing, and make debugging production incidents harder.",
1210
1273
  recommendation: "Wrap payment logic in try/catch. Return a structured error response (e.g., 500 with a generic message) and log the full error server-side.",
1211
1274
  blocking: isBlocking(id, policy)