@agenticcli/shipguard 0.2.0 → 0.3.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.
@@ -1,1507 +0,0 @@
1
- // src/core/auth.ts
2
- import { readFileSync, writeFileSync, mkdirSync, rmSync, existsSync } from "fs";
3
- import { join, dirname } from "path";
4
- import { homedir } from "os";
5
- function getCredentialsPath() {
6
- return join(homedir(), ".config", "shipguard", "credentials.json");
7
- }
8
- function loadCredentials() {
9
- const p = getCredentialsPath();
10
- if (!existsSync(p)) return null;
11
- try {
12
- return JSON.parse(readFileSync(p, "utf-8"));
13
- } catch {
14
- console.warn("[shipguard] credentials file is corrupt \u2014 run `shipguard login` again");
15
- return null;
16
- }
17
- }
18
- async function saveCredentials(creds) {
19
- const p = getCredentialsPath();
20
- mkdirSync(dirname(p), { recursive: true });
21
- writeFileSync(p, JSON.stringify(creds, null, 2), { mode: 384 });
22
- }
23
- function clearCredentials() {
24
- const p = getCredentialsPath();
25
- if (existsSync(p)) rmSync(p);
26
- }
27
- function isTokenExpired(creds) {
28
- return creds.expiresAt < Date.now();
29
- }
30
- async function getAuthToken() {
31
- if (process.env.SHIPGUARD_API_KEY) return process.env.SHIPGUARD_API_KEY;
32
- const creds = loadCredentials();
33
- if (!creds) return null;
34
- if (!isTokenExpired(creds)) return creds.accessToken;
35
- if (creds.refreshToken && creds.apiUrl) {
36
- try {
37
- const res = await fetch(`${creds.apiUrl}/api/auth/device/refresh`, {
38
- method: "POST",
39
- headers: { "Content-Type": "application/json" },
40
- body: JSON.stringify({ refresh_token: creds.refreshToken })
41
- });
42
- if (res.ok) {
43
- const { access_token, refresh_token, expires_in } = await res.json();
44
- await saveCredentials({
45
- accessToken: access_token,
46
- refreshToken: refresh_token ?? creds.refreshToken,
47
- expiresAt: Date.now() + (expires_in ?? 900) * 1e3,
48
- apiUrl: creds.apiUrl
49
- });
50
- return access_token;
51
- }
52
- } catch {
53
- }
54
- }
55
- return null;
56
- }
57
-
58
- // src/core/crypto.ts
59
- import { hkdf } from "@noble/hashes/hkdf.js";
60
- import { sha256 } from "@noble/hashes/sha2.js";
61
- var PINNED_KEYS = {
62
- "k1-2026": `-----BEGIN PUBLIC KEY-----
63
- MCowBQYDK2VwAyEAkpeX0A3zIOttGn8t+jagJHLRTv5Q809vqIZU37lE6xQ=
64
- -----END PUBLIC KEY-----`
65
- };
66
- var DEFAULT_KID = "k1-2026";
67
- var HKDF_INFO = "shipguard-rules-v1";
68
- function pemToArrayBuffer(pem) {
69
- const b64 = pem.replace(/-----BEGIN PUBLIC KEY-----/, "").replace(/-----END PUBLIC KEY-----/, "").replace(/\s/g, "");
70
- const binary = Buffer.from(b64, "base64");
71
- return binary.buffer.slice(binary.byteOffset, binary.byteOffset + binary.byteLength);
72
- }
73
- async function verifyAndDecryptBundle(bundleB64, accessToken) {
74
- const bundleJson = Buffer.from(bundleB64, "base64").toString("utf-8");
75
- const bundle = JSON.parse(bundleJson);
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;
84
- const cryptoKey = await globalThis.crypto.subtle.importKey(
85
- "spki",
86
- pemToArrayBuffer(pem),
87
- { name: "Ed25519" },
88
- false,
89
- ["verify"]
90
- );
91
- const payloadBytes = new TextEncoder().encode(JSON.stringify(bundle.payload));
92
- const signatureBytes = Buffer.from(bundle.signature, "base64");
93
- const valid = await globalThis.crypto.subtle.verify("Ed25519", cryptoKey, signatureBytes, payloadBytes);
94
- if (!valid) {
95
- throw new Error("Rule bundle signature verification failed \u2014 possible tampering");
96
- }
97
- if (bundle.payload.expiresAt < Date.now()) {
98
- throw new Error("Rule bundle has expired");
99
- }
100
- const salt = Buffer.from(bundle.payload.salt, "base64");
101
- const ikm = new TextEncoder().encode(accessToken);
102
- const info = new TextEncoder().encode(HKDF_INFO);
103
- const aesKeyBytes = hkdf(sha256, ikm, salt, info, 32);
104
- const aesKey = await globalThis.crypto.subtle.importKey(
105
- "raw",
106
- aesKeyBytes,
107
- { name: "AES-GCM" },
108
- false,
109
- ["decrypt"]
110
- );
111
- const iv = Buffer.from(bundle.payload.iv, "base64");
112
- const ciphertext = Buffer.from(bundle.payload.ciphertext, "base64");
113
- const decrypted = await globalThis.crypto.subtle.decrypt(
114
- { name: "AES-GCM", iv },
115
- aesKey,
116
- ciphertext
117
- );
118
- const rulesJson = new TextDecoder().decode(decrypted);
119
- const rules = JSON.parse(rulesJson);
120
- return {
121
- rules,
122
- watermark: bundle.payload.watermark,
123
- expiresAt: bundle.payload.expiresAt
124
- };
125
- }
126
- async function verifyRuleBundle(token) {
127
- const { importSPKI: importKey, jwtVerify } = await import("jose");
128
- const pem = process.env.SHIPGUARD_PUBLIC_KEY ?? PINNED_KEYS[DEFAULT_KID];
129
- const publicKey = await importKey(pem, "EdDSA");
130
- const { payload } = await jwtVerify(token, publicKey);
131
- return payload;
132
- }
133
-
134
- // src/core/pro-scanner.ts
135
- import { minimatch } from "minimatch";
136
-
137
- // src/checks/secrets.ts
138
- function redact(value) {
139
- if (value.length <= 8) return "***";
140
- return value.slice(0, 8) + "***";
141
- }
142
- function isDotEnvFile(relativePath) {
143
- const basename2 = relativePath.split("/").pop() ?? relativePath;
144
- if (!basename2.startsWith(".env")) return false;
145
- const safeExclusions = /\.(example|sample|template|dist|tmpl|test)$/i;
146
- return !safeExclusions.test(basename2);
147
- }
148
- function isFrontendFile(relativePath) {
149
- return /^(app|pages|components|src\/(app|pages|components))\//.test(relativePath);
150
- }
151
- var SECRET_PATTERNS = [
152
- // OpenAI — sk-proj-... (new format) detected by prefix regardless of variable name
153
- {
154
- id: "hardcoded_secret",
155
- name: "OpenAI API Key",
156
- regex: /['"]?(sk-proj-[a-zA-Z0-9_\-]{20,})['"]?/m,
157
- severity: "high",
158
- confidence: "HIGH",
159
- explanation: "Hardcoded OpenAI API key detected. Leaking this key allows unauthorized use of your OpenAI account, incurring charges.",
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."
161
- },
162
- // OpenAI — sk-... (legacy format) via variable name context to avoid false positives
163
- {
164
- id: "hardcoded_secret",
165
- name: "OpenAI Legacy API Key",
166
- regex: /(?:openai[_\-]?(?:api[_\-]?)?key|OPENAI[_\-]?(?:API[_\-]?)?KEY)\s*[=:]\s*['"]?(sk-[a-zA-Z0-9]{20,})['"]?/im,
167
- severity: "high",
168
- confidence: "HIGH",
169
- explanation: "Hardcoded OpenAI API key detected. Leaking this key allows unauthorized use of your OpenAI account, incurring charges.",
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."
171
- },
172
- // Anthropic — sk-ant-api03-...
173
- {
174
- id: "hardcoded_secret",
175
- name: "Anthropic API Key",
176
- regex: /['"]?(sk-ant-(?:api\d+-)?[a-zA-Z0-9_\-]{20,})['"]?/im,
177
- severity: "high",
178
- confidence: "HIGH",
179
- explanation: "Hardcoded Anthropic API key detected. Leaking this key allows unauthorized use of Anthropic Claude, incurring charges.",
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."
181
- },
182
- // Stripe live secret key
183
- {
184
- id: "hardcoded_secret",
185
- name: "Stripe Live Secret Key",
186
- regex: /['"]?(sk_live_[a-zA-Z0-9]{24,})['"]?/im,
187
- severity: "critical",
188
- confidence: "HIGH",
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.",
190
- recommendation: "Remove immediately. Use process.env.STRIPE_SECRET_KEY. Rotate the key in the Stripe Dashboard."
191
- },
192
- // Stripe test secret key
193
- {
194
- id: "hardcoded_secret",
195
- name: "Stripe Test Secret Key",
196
- regex: /['"]?(sk_test_[a-zA-Z0-9]{24,})['"]?/im,
197
- severity: "medium",
198
- confidence: "HIGH",
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.",
200
- recommendation: "Remove from source code. Use process.env.STRIPE_SECRET_KEY with a .env file that is gitignored."
201
- },
202
- // AWS access key ID
203
- {
204
- id: "hardcoded_secret",
205
- name: "AWS Access Key ID",
206
- regex: /['"]?(AKIA[0-9A-Z]{16})['"]?/m,
207
- severity: "high",
208
- confidence: "HIGH",
209
- explanation: "Hardcoded AWS Access Key ID detected. Combined with the secret key, this allows full AWS API access under your account.",
210
- recommendation: "Remove and rotate immediately via IAM. Use environment variables or AWS credential profiles instead."
211
- },
212
- // AWS secret access key
213
- {
214
- id: "hardcoded_secret",
215
- name: "AWS Secret Access Key",
216
- regex: /(?:aws[_\-]?secret[_\-]?(?:access[_\-]?)?key|AWS_SECRET_ACCESS_KEY)\s*[=:]\s*['"]?([a-zA-Z0-9\/+]{40})['"]?/im,
217
- severity: "high",
218
- confidence: "HIGH",
219
- explanation: "Hardcoded AWS Secret Access Key detected. This credential enables full programmatic access to AWS services.",
220
- recommendation: "Remove and rotate immediately via IAM. Use environment variables or AWS credential profiles instead."
221
- },
222
- // Google API key
223
- {
224
- id: "hardcoded_secret",
225
- name: "Google API Key",
226
- regex: /['"]?(AIza[0-9A-Za-z\-_]{35})['"]?/m,
227
- severity: "high",
228
- confidence: "HIGH",
229
- explanation: "Hardcoded Google API key detected. This key can be used to access Google Cloud services or Google Maps, incurring charges.",
230
- recommendation: "Remove from source code. Restrict key usage in the Google Cloud Console and use environment variables."
231
- },
232
- // GitHub personal access token (classic ghp_ and fine-grained github_pat_)
233
- {
234
- id: "hardcoded_secret",
235
- name: "GitHub Personal Access Token",
236
- regex: /['"]?(ghp_[a-zA-Z0-9]{36}|github_pat_[a-zA-Z0-9_]{82})['"]?/m,
237
- severity: "high",
238
- confidence: "HIGH",
239
- explanation: "Hardcoded GitHub Personal Access Token detected. This token grants access to GitHub repositories and actions under your account.",
240
- recommendation: "Remove and revoke the token at github.com/settings/tokens. Use environment variables."
241
- },
242
- // Razorpay live secret key
243
- {
244
- id: "hardcoded_secret",
245
- name: "Razorpay Secret Key",
246
- regex: /(?:razorpay[_\-]?(?:key[_\-]?)?secret|RAZORPAY_KEY_SECRET)\s*[=:]\s*['"]?([a-zA-Z0-9]{20,})['"]?/im,
247
- severity: "high",
248
- confidence: "HIGH",
249
- explanation: "Hardcoded Razorpay secret key detected. This allows unauthorized access to your Razorpay payment account.",
250
- recommendation: "Remove from source code. Use process.env.RAZORPAY_KEY_SECRET and store in a gitignored .env file."
251
- },
252
- // JWT secret
253
- {
254
- id: "hardcoded_secret",
255
- name: "JWT Secret",
256
- regex: /(?:jwt[_\-]?secret|JWT_SECRET)\s*[=:]\s*['"]([^'"]{16,})['"]?/im,
257
- severity: "high",
258
- confidence: "HIGH",
259
- explanation: "Hardcoded JWT secret detected. Exposing this allows attackers to forge valid JWT tokens and bypass authentication.",
260
- recommendation: "Remove from source code. Generate a strong random secret, store it in environment variables."
261
- },
262
- // Database URL with embedded credentials — var-name prefix is optional so bare
263
- // assignments like `const uri = "mongodb://admin:pass@host/db"` are also caught.
264
- {
265
- id: "hardcoded_secret",
266
- name: "Database URL with Credentials",
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,
268
- severity: "critical",
269
- confidence: "HIGH",
270
- explanation: "Database URL with embedded credentials detected. This exposes the database host, username, and password directly.",
271
- recommendation: "Remove credentials from the URL. Use environment variables and ensure the .env file is gitignored."
272
- },
273
- // Generic assignment: VAR = "long-base64/alphanumeric string"
274
- // Only flags quoted values that look like secrets (not hex commit hashes, not paths)
275
- {
276
- id: "hardcoded_secret",
277
- name: "High-Entropy Secret String",
278
- regex: /(?:api[_\-]?key|secret|token|password|passwd|auth[_\-]?key|access[_\-]?key)\s*[=:]\s*['"]([a-zA-Z0-9\/+_\-]{32,64})['"](?!\s*\+|\.)/im,
279
- severity: "medium",
280
- confidence: "MEDIUM",
281
- explanation: "A variable with a secret-sounding name is assigned a long literal string that resembles an API key or token.",
282
- recommendation: "Move this value to a .env file and reference it via process.env. Never hardcode credentials."
283
- }
284
- ];
285
- var PRIVATE_KEY_PATTERN = /-----BEGIN\s(?:RSA\s|EC\s|DSA\s|OPENSSH\s|ENCRYPTED\s)?PRIVATE KEY-----/m;
286
- var NEXT_PUBLIC_SECRET_PATTERN = /NEXT_PUBLIC_(?:[A-Z_]*(?:KEY|SECRET|TOKEN|PASSWORD|AUTH)[A-Z_]*)=['"']?([a-zA-Z0-9\/+_\-]{16,})['"']?/m;
287
- var ENV_REFERENCE_ONLY = /process\.env\.[A-Z_]+/;
288
- function checkSecrets(files, policy) {
289
- const findings = [];
290
- for (const file of files) {
291
- const { content, relativePath } = file;
292
- if (isDotEnvFile(relativePath)) {
293
- const id = "exposed_env";
294
- findings.push({
295
- id,
296
- title: ".env file tracked in git",
297
- severity: "high",
298
- category: "secrets",
299
- file: relativePath,
300
- confidence: "HIGH",
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.",
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`.",
303
- blocking: policy.block.includes(id)
304
- });
305
- }
306
- const pkMatch = PRIVATE_KEY_PATTERN.exec(content);
307
- if (pkMatch) {
308
- const lineNum = content.slice(0, pkMatch.index).split("\n").length;
309
- const id = "hardcoded_secret";
310
- findings.push({
311
- id,
312
- title: "Private key block in source",
313
- severity: "critical",
314
- category: "secrets",
315
- file: relativePath,
316
- line: lineNum,
317
- evidence: pkMatch[0].trim(),
318
- confidence: "HIGH",
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.",
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.",
321
- blocking: policy.block.includes(id)
322
- });
323
- }
324
- if (isFrontendFile(relativePath)) {
325
- const lines2 = content.split("\n");
326
- for (let i = 0; i < lines2.length; i++) {
327
- const line = lines2[i];
328
- const match = NEXT_PUBLIC_SECRET_PATTERN.exec(line);
329
- if (match && match[1]) {
330
- const id = "exposed_env";
331
- findings.push({
332
- id,
333
- title: "Secret exposed via NEXT_PUBLIC_ prefix",
334
- severity: "critical",
335
- category: "secrets",
336
- file: relativePath,
337
- line: i + 1,
338
- evidence: `${line.split("=")[0].trim()}=${redact(match[1])}`,
339
- confidence: "HIGH",
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.",
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.",
342
- blocking: policy.block.includes(id)
343
- });
344
- }
345
- }
346
- }
347
- const lines = content.split("\n");
348
- for (const pattern of SECRET_PATTERNS) {
349
- if (!pattern.regex.test(content)) continue;
350
- for (let i = 0; i < lines.length; i++) {
351
- const line = lines[i];
352
- if (ENV_REFERENCE_ONLY.test(line) && !/=\s*['"]/.test(line)) continue;
353
- if (/^\s*(\/\/|#)/.test(line)) continue;
354
- const lineMatch = pattern.regex.exec(line);
355
- if (lineMatch) {
356
- const secretValue = lineMatch[1] ?? lineMatch[0];
357
- findings.push({
358
- id: pattern.id,
359
- title: pattern.name,
360
- severity: pattern.severity,
361
- category: "secrets",
362
- file: relativePath,
363
- line: i + 1,
364
- evidence: `...${redact(secretValue)}...`,
365
- confidence: pattern.confidence,
366
- explanation: pattern.explanation,
367
- recommendation: pattern.recommendation,
368
- blocking: policy.block.includes(pattern.id)
369
- });
370
- }
371
- }
372
- }
373
- }
374
- return findings;
375
- }
376
- var secretsCheck = {
377
- id: "secrets",
378
- name: "Secrets & Environment Leaks",
379
- run: checkSecrets
380
- };
381
-
382
- // src/checks/auth.ts
383
- var SENSITIVE_NEXTJS_PAGE_PATTERN = /^(?:src\/)?app\/(admin|dashboard|billing|account|settings|management)(\/|$)/;
384
- var SENSITIVE_API_ROUTE_PATTERN = /^(?:src\/)?app\/api\/(admin|users|billing|account|management)(\/|$)/;
385
- var EXPRESS_ROUTE_DEFINITION = /(?:router|app)\.(get|post|put|patch|delete|all)\s*\(\s*['"`]([^'"`,)]+)['"`]/gi;
386
- var SENSITIVE_EXPRESS_PATHS = /\/(admin|users|billing|account|management)(\/|$)/;
387
- var WEBHOOK_PATH_PATTERN = /\/webhooks?\//;
388
- var AUTH_CALL_PATTERN = /(?<!\/{2}.*?)(?<!\*.*?)(?:auth|getServerSession|requireAuth|verifyToken|withAuth|clerkMiddleware|authMiddleware)\s*\(/;
389
- var COMMENTED_AUTH_PATTERN = /^\s*(?:\/\/|\/\*|\*)[^\n]*(?:auth|getServerSession|requireAuth|verifyToken)\s*\(/m;
390
- var EXPRESS_AUTH_MIDDLEWARE_PATTERN = /(?:router|app)\.use\s*\([^)]*(?:auth|requireAuth|verifyToken|isAuth|isLogged|passport)\w*/i;
391
- var MIDDLEWARE_FILE_PATTERN = /^(?:src\/)?middleware\.[tj]s$/;
392
- var MIDDLEWARE_ADMIN_COVERAGE = /(?:admin|dashboard|billing|account|management)/;
393
- var NEXT_APP_ROUTER_PATH = /^(?:src\/)?(?:app\/|app$)/;
394
- var NEXT_CONFIG_FILE = /^(?:src\/)?next\.config\.[cm]?[jt]s$/;
395
- function isNextjsProject(files) {
396
- for (const f of files) {
397
- if (NEXT_APP_ROUTER_PATH.test(f.relativePath)) return true;
398
- if (NEXT_CONFIG_FILE.test(f.relativePath)) return true;
399
- if (f.relativePath === "package.json" || f.relativePath.endsWith("/package.json")) {
400
- try {
401
- const pkg = JSON.parse(f.content);
402
- const deps = { ...pkg.dependencies, ...pkg.devDependencies };
403
- if ("next" in deps) return true;
404
- } catch {
405
- }
406
- }
407
- }
408
- return false;
409
- }
410
- function hasActiveAuthCall(content) {
411
- const stripped = content.split("\n").map((line) => line.replace(/(?<![:/])\/\/.*$/, "")).join("\n");
412
- return AUTH_CALL_PATTERN.test(stripped);
413
- }
414
- function hasCommentedAuthCall(content) {
415
- return COMMENTED_AUTH_PATTERN.test(content);
416
- }
417
- function hasUnsecuredExpressRoute(content) {
418
- if (EXPRESS_AUTH_MIDDLEWARE_PATTERN.test(content)) {
419
- return false;
420
- }
421
- EXPRESS_ROUTE_DEFINITION.lastIndex = 0;
422
- let match;
423
- while ((match = EXPRESS_ROUTE_DEFINITION.exec(content)) !== null) {
424
- const routePath = match[2];
425
- if (SENSITIVE_EXPRESS_PATHS.test(routePath) && !WEBHOOK_PATH_PATTERN.test(routePath)) {
426
- const routeCallStart = match.index;
427
- const routeCall = content.slice(routeCallStart, routeCallStart + 300);
428
- const hasInlineAuth = /requireAuth|verifyToken|isAuth|isLogged|passport\.authenticate/i.test(
429
- routeCall
430
- );
431
- if (!hasInlineAuth) {
432
- return true;
433
- }
434
- }
435
- }
436
- return false;
437
- }
438
- var authCheck = {
439
- id: "auth",
440
- name: "Auth & Session Protection",
441
- run(files, policy) {
442
- const findings = [];
443
- const middlewareFile = files.find((f) => MIDDLEWARE_FILE_PATTERN.test(f.relativePath));
444
- if (isNextjsProject(files)) {
445
- if (!middlewareFile) {
446
- findings.push({
447
- id: "public_admin_route",
448
- title: "No Next.js middleware.ts found",
449
- severity: "high",
450
- category: "auth",
451
- file: "middleware.ts",
452
- confidence: "MEDIUM",
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.",
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.",
455
- blocking: policy.block.includes("public_admin_route")
456
- });
457
- } else if (!MIDDLEWARE_ADMIN_COVERAGE.test(middlewareFile.content)) {
458
- findings.push({
459
- id: "public_admin_route",
460
- title: "middleware.ts does not cover admin/dashboard routes",
461
- severity: "high",
462
- category: "auth",
463
- file: middlewareFile.relativePath,
464
- confidence: "MEDIUM",
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.",
466
- recommendation: 'Add a matcher config to middleware.ts that covers protected route prefixes:\n export const config = { matcher: ["/admin/:path*", "/dashboard/:path*"] }',
467
- blocking: policy.block.includes("public_admin_route")
468
- });
469
- }
470
- }
471
- for (const file of files) {
472
- const { relativePath: rp, content } = file;
473
- if (WEBHOOK_PATH_PATTERN.test(rp)) {
474
- continue;
475
- }
476
- if (SENSITIVE_NEXTJS_PAGE_PATTERN.test(rp)) {
477
- if (!hasActiveAuthCall(content)) {
478
- const wasRemoved = hasCommentedAuthCall(content);
479
- findings.push({
480
- id: "public_admin_route",
481
- title: `Unprotected admin/dashboard page: ${rp}`,
482
- severity: "high",
483
- category: "auth",
484
- file: rp,
485
- confidence: "MEDIUM",
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).`,
487
- recommendation: 'Add `const session = await auth()` at the top of the Server Component and redirect unauthenticated users with `if (!session) redirect("/login")`.',
488
- blocking: policy.block.includes("public_admin_route")
489
- });
490
- }
491
- continue;
492
- }
493
- if (SENSITIVE_API_ROUTE_PATTERN.test(rp)) {
494
- if (!hasActiveAuthCall(content)) {
495
- const wasRemoved = hasCommentedAuthCall(content);
496
- findings.push({
497
- id: "auth_route_without_guard",
498
- title: `Unprotected API route handler: ${rp}`,
499
- severity: "high",
500
- category: "auth",
501
- file: rp,
502
- confidence: "MEDIUM",
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.`,
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.",
505
- blocking: policy.block.includes("auth_route_without_guard")
506
- });
507
- }
508
- continue;
509
- }
510
- if (/\.(ts|js)$/.test(rp) && !SENSITIVE_NEXTJS_PAGE_PATTERN.test(rp) && !SENSITIVE_API_ROUTE_PATTERN.test(rp)) {
511
- if (hasUnsecuredExpressRoute(content)) {
512
- findings.push({
513
- id: "auth_route_without_guard",
514
- title: `Express route exposes sensitive path without auth middleware: ${rp}`,
515
- severity: "medium",
516
- category: "auth",
517
- file: rp,
518
- confidence: "LOW",
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.`,
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.',
521
- blocking: policy.block.includes("auth_route_without_guard")
522
- });
523
- }
524
- }
525
- }
526
- return findings;
527
- }
528
- };
529
-
530
- // src/checks/database.ts
531
- var MIGRATION_PATTERNS = [
532
- /^prisma\/migrations\/.+\.sql$/i,
533
- /^drizzle\/.+\.sql$/i,
534
- /^migrations\/.+\.sql$/i,
535
- /^db\/.+\.sql$/i,
536
- /^[^/]+\.sql$/i
537
- // root-level .sql files
538
- ];
539
- function isMigrationFile(relativePath) {
540
- return MIGRATION_PATTERNS.some((p) => p.test(relativePath));
541
- }
542
- function stripSqlComments(sql) {
543
- return sql.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/--[^\n]*/g, "");
544
- }
545
- function splitStatements(sql) {
546
- const statements = [];
547
- const parts = sql.split(";");
548
- let currentLine = 1;
549
- for (const part of parts) {
550
- const trimmed = part.trim();
551
- if (trimmed.length > 0) {
552
- statements.push({ text: trimmed, startLine: currentLine });
553
- }
554
- currentLine += (part.match(/\n/g) || []).length;
555
- }
556
- return statements;
557
- }
558
- function findLineNumber(content, matchIndex) {
559
- const before = content.slice(0, matchIndex);
560
- return (before.match(/\n/g) || []).length + 1;
561
- }
562
- var SQL_PATTERNS = [
563
- {
564
- id: "db-drop-table",
565
- title: "Destructive migration: DROP TABLE",
566
- severity: "critical",
567
- confidence: "HIGH",
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.",
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.",
570
- pattern: /\bDROP\s+TABLE\b/i
571
- },
572
- {
573
- id: "db-drop-column",
574
- title: "Destructive migration: DROP COLUMN",
575
- severity: "high",
576
- confidence: "HIGH",
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.",
578
- recommendation: "Deprecate the column in code first, deploy, confirm no usage, then run the drop in a separate migration.",
579
- pattern: /\bDROP\s+COLUMN\b/i
580
- },
581
- {
582
- id: "db-truncate",
583
- title: "Destructive migration: TRUNCATE",
584
- severity: "high",
585
- confidence: "HIGH",
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.",
587
- recommendation: "Remove TRUNCATE from migration files. Data wipes should be explicit operational procedures, not automatic schema changes.",
588
- pattern: /\bTRUNCATE\b/i
589
- },
590
- {
591
- id: "db-delete-without-where",
592
- title: "Unsafe migration: DELETE FROM without WHERE clause",
593
- severity: "high",
594
- confidence: "HIGH",
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.",
596
- recommendation: "Add a WHERE clause, or replace with TRUNCATE (and add a review gate) if a full wipe is truly intended.",
597
- pattern: /\bDELETE\s+FROM\b/i,
598
- requiresNoWhere: true
599
- },
600
- {
601
- id: "db-alter-drop",
602
- title: "Potentially destructive migration: ALTER TABLE DROP",
603
- severity: "medium",
604
- confidence: "MEDIUM",
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.",
606
- recommendation: "Review what exactly is being dropped. Ensure application code is already compatible with the removed constraint before deploying.",
607
- // Avoid double-flagging lines that already match DROP COLUMN (handled above)
608
- pattern: /\bALTER\s+TABLE\b[^;]*\bDROP\b/i,
609
- skipIfSiblingMatched: "db-drop-column"
610
- }
611
- ];
612
- var PUSH_PATTERNS = [
613
- /prisma\s+db\s+push/i,
614
- /drizzle-kit\s+push/i
615
- ];
616
- function checkSqlFile(file, findings) {
617
- const raw = file.content;
618
- const stripped = stripSqlComments(raw);
619
- const statements = splitStatements(stripped);
620
- const matchedLinesById = /* @__PURE__ */ new Map();
621
- for (const pattern of SQL_PATTERNS) {
622
- for (const stmt of statements) {
623
- if (!pattern.pattern.test(stmt.text)) continue;
624
- if (pattern.requiresNoWhere) {
625
- const hasWhere = /\bWHERE\b/i.test(stmt.text);
626
- if (hasWhere) continue;
627
- }
628
- if (pattern.skipIfSiblingMatched) {
629
- const siblingId = pattern.skipIfSiblingMatched;
630
- const siblingPattern = SQL_PATTERNS.find((p) => p.id === siblingId);
631
- if (siblingPattern && siblingPattern.pattern.test(stmt.text)) continue;
632
- }
633
- const matchInStripped = pattern.pattern.exec(stmt.text);
634
- const matchIndex = matchInStripped ? raw.indexOf(stmt.text.slice(0, 40)) : 0;
635
- const lineNumber = matchIndex >= 0 ? findLineNumber(raw, matchIndex) : stmt.startLine;
636
- if (!matchedLinesById.has(pattern.id)) {
637
- matchedLinesById.set(pattern.id, /* @__PURE__ */ new Set());
638
- }
639
- const lines = matchedLinesById.get(pattern.id);
640
- if (lines.has(lineNumber)) continue;
641
- lines.add(lineNumber);
642
- const rawLines = raw.split("\n");
643
- const evidenceLine = rawLines[lineNumber - 1]?.trim().slice(0, 120) ?? stmt.text.slice(0, 120);
644
- findings.push({
645
- id: pattern.id,
646
- title: pattern.title,
647
- severity: pattern.severity,
648
- category: "database",
649
- file: file.relativePath,
650
- line: lineNumber,
651
- evidence: evidenceLine,
652
- confidence: pattern.confidence,
653
- explanation: pattern.explanation,
654
- recommendation: pattern.recommendation,
655
- blocking: pattern.severity === "critical" || pattern.severity === "high"
656
- });
657
- }
658
- }
659
- }
660
- function checkPackageJson(file, findings) {
661
- if (!file.relativePath.endsWith("package.json")) return;
662
- let parsed;
663
- try {
664
- parsed = JSON.parse(file.content);
665
- } catch {
666
- return;
667
- }
668
- const scripts = parsed["scripts"];
669
- if (!scripts || typeof scripts !== "object") return;
670
- for (const [scriptName, scriptValue] of Object.entries(scripts)) {
671
- if (typeof scriptValue !== "string") continue;
672
- for (const pushPattern of PUSH_PATTERNS) {
673
- if (!pushPattern.test(scriptValue)) continue;
674
- const tool = /prisma/i.test(scriptValue) ? "prisma db push" : "drizzle-kit push";
675
- findings.push({
676
- id: "db-push-in-scripts",
677
- title: `Dangerous command in package.json scripts: ${tool}`,
678
- severity: "medium",
679
- category: "database",
680
- file: file.relativePath,
681
- evidence: `"${scriptName}": "${scriptValue.slice(0, 120)}"`,
682
- confidence: "HIGH",
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.`,
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.',
685
- blocking: false
686
- });
687
- break;
688
- }
689
- }
690
- }
691
- function checkPrismaSchemaWithoutMigration(files, findings) {
692
- const hasSchemaChange = files.some((f) => f.relativePath === "prisma/schema.prisma");
693
- if (!hasSchemaChange) return;
694
- const hasMigration = files.some((f) => /^prisma\/migrations\/.+\.sql$/i.test(f.relativePath));
695
- if (hasMigration) return;
696
- const schemaFile = files.find((f) => f.relativePath === "prisma/schema.prisma");
697
- findings.push({
698
- id: "db-schema-without-migration",
699
- title: "Prisma schema changed without a migration file",
700
- severity: "medium",
701
- category: "database",
702
- file: schemaFile.relativePath,
703
- confidence: "MEDIUM",
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.',
705
- recommendation: 'Run "npx prisma migrate dev --name <description>" locally, commit the generated migration file in prisma/migrations/, and re-scan.',
706
- blocking: false
707
- });
708
- }
709
- var databaseCheck = {
710
- id: "database",
711
- name: "Database & Migration Safety",
712
- run(files, _policy) {
713
- const findings = [];
714
- for (const file of files) {
715
- if (isMigrationFile(file.relativePath)) {
716
- checkSqlFile(file, findings);
717
- } else if (file.relativePath.endsWith("package.json")) {
718
- checkPackageJson(file, findings);
719
- }
720
- }
721
- checkPrismaSchemaWithoutMigration(files, findings);
722
- return findings;
723
- }
724
- };
725
-
726
- // src/checks/deployment.ts
727
- import { basename } from "path";
728
- function makeId(suffix) {
729
- return `deployment_${suffix}`;
730
- }
731
- function findLine(content, pattern) {
732
- const lines = content.split("\n");
733
- for (let i = 0; i < lines.length; i++) {
734
- if (pattern.test(lines[i])) return i + 1;
735
- }
736
- return void 0;
737
- }
738
- function checkNextConfig(file) {
739
- const findings = [];
740
- const { content, relativePath } = file;
741
- const corsPatterns = [
742
- /Access-Control-Allow-Origin['"]\s*,\s*value\s*:\s*['"]?\s*\*\s*['"]?/i,
743
- /Access-Control-Allow-Origin['"]?\s*:\s*['"]\s*\*\s*['"]/i
744
- ];
745
- const corsWildcardPattern = corsPatterns[0];
746
- if (corsPatterns.some((p) => p.test(content))) {
747
- const matchedPattern = corsPatterns.find((p) => p.test(content));
748
- const line = findLine(content, matchedPattern);
749
- findings.push({
750
- id: makeId("cors_wildcard"),
751
- title: "Permissive CORS: Access-Control-Allow-Origin set to wildcard (*)",
752
- severity: "high",
753
- category: "deployment",
754
- file: relativePath,
755
- line,
756
- evidence: "Access-Control-Allow-Origin: *",
757
- confidence: "HIGH",
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.",
759
- recommendation: "Replace the wildcard with an explicit list of trusted origins in the headers() configuration.",
760
- blocking: true
761
- });
762
- }
763
- const sourceMapsPattern = /productionBrowserSourceMaps\s*:\s*true/;
764
- if (sourceMapsPattern.test(content)) {
765
- const line = findLine(content, sourceMapsPattern);
766
- findings.push({
767
- id: makeId("source_maps_exposed"),
768
- title: "Production source maps are enabled (productionBrowserSourceMaps: true)",
769
- severity: "medium",
770
- category: "deployment",
771
- file: relativePath,
772
- line,
773
- evidence: "productionBrowserSourceMaps: true",
774
- confidence: "HIGH",
775
- explanation: "Enabling production source maps exposes your original application source code to anyone inspecting browser devtools, aiding reverse engineering and vulnerability discovery.",
776
- recommendation: "Remove productionBrowserSourceMaps: true or set it to false for production builds.",
777
- blocking: false
778
- });
779
- }
780
- const hasHeadersFunction = /headers\s*\(\s*\)/.test(content) || /async\s+headers/.test(content);
781
- const hasXFrameOptions = /X-Frame-Options/i.test(content);
782
- const hasXContentType = /X-Content-Type-Options/i.test(content);
783
- if (hasHeadersFunction && !hasXFrameOptions) {
784
- findings.push({
785
- id: makeId("missing_x_frame_options"),
786
- title: "Missing security header: X-Frame-Options not configured",
787
- severity: "medium",
788
- category: "deployment",
789
- file: relativePath,
790
- confidence: "MEDIUM",
791
- explanation: "X-Frame-Options prevents your site from being embedded in an iframe, protecting users against clickjacking attacks.",
792
- recommendation: "Add { key: 'X-Frame-Options', value: 'DENY' } to your headers() configuration in next.config.js.",
793
- blocking: false
794
- });
795
- }
796
- if (hasHeadersFunction && !hasXContentType) {
797
- findings.push({
798
- id: makeId("missing_x_content_type"),
799
- title: "Missing security header: X-Content-Type-Options not configured",
800
- severity: "medium",
801
- category: "deployment",
802
- file: relativePath,
803
- confidence: "MEDIUM",
804
- explanation: "X-Content-Type-Options: nosniff prevents MIME-type sniffing attacks where browsers execute content as a different type than declared.",
805
- recommendation: "Add { key: 'X-Content-Type-Options', value: 'nosniff' } to your headers() configuration.",
806
- blocking: false
807
- });
808
- }
809
- return findings;
810
- }
811
- function checkDockerfile(file) {
812
- const findings = [];
813
- const { content, relativePath } = file;
814
- const userDirectives = content.split("\n").filter((line) => /^\s*USER\s+/i.test(line)).map((line) => line.trim());
815
- const hasNonRootUser = userDirectives.some(
816
- (line) => !/^USER\s+(root|0)\s*$/i.test(line)
817
- );
818
- if (!hasNonRootUser) {
819
- findings.push({
820
- id: makeId("docker_root_user"),
821
- title: "Dockerfile runs container as root (no non-root USER directive)",
822
- severity: "medium",
823
- category: "deployment",
824
- file: relativePath,
825
- confidence: "MEDIUM",
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.",
827
- recommendation: "Add a USER directive with a non-root user (e.g., USER node or create a dedicated user with addgroup/adduser).",
828
- blocking: false
829
- });
830
- }
831
- const fromLines = content.split("\n").filter((line) => /^\s*FROM\s+/i.test(line));
832
- for (const line of fromLines) {
833
- const stripped = line.replace(/\s+AS\s+\w+/i, "").trim();
834
- const match = stripped.match(/^FROM\s+(?:--platform=\S+\s+)?(\S+)/i);
835
- if (!match) continue;
836
- const image = match[1];
837
- if (image.toLowerCase() === "scratch") continue;
838
- const hasTag = image.includes(":");
839
- const isLatest = image.toLowerCase().endsWith(":latest");
840
- if (!hasTag || isLatest) {
841
- const lineNum = findLine(content, new RegExp(line.trim().replace(/[.*+?^${}()|[\]\\]/g, "\\$&")));
842
- findings.push({
843
- id: makeId("docker_unpinned_image"),
844
- title: `Dockerfile uses unpinned base image: ${image}`,
845
- severity: "medium",
846
- category: "deployment",
847
- file: relativePath,
848
- line: lineNum,
849
- evidence: line.trim(),
850
- confidence: "HIGH",
851
- explanation: "Using :latest or no tag means the base image can change silently between builds, introducing unreviewed dependency updates or security regressions.",
852
- recommendation: `Pin the image to a specific digest or version tag (e.g., ${image.split(":")[0]}:20-alpine or with a SHA digest).`,
853
- blocking: false
854
- });
855
- }
856
- }
857
- return findings;
858
- }
859
- function checkDockerCompose(file) {
860
- const findings = [];
861
- const { content, relativePath } = file;
862
- const imageLines = content.split("\n").filter((line) => /^\s+image:\s+\S+/.test(line));
863
- for (const line of imageLines) {
864
- const match = line.match(/image:\s+(\S+)/);
865
- if (!match) continue;
866
- const image = match[1];
867
- const hasTag = image.includes(":");
868
- const isLatest = image.toLowerCase().endsWith(":latest");
869
- if (!hasTag || isLatest) {
870
- findings.push({
871
- id: makeId("compose_unpinned_image"),
872
- title: `docker-compose uses unpinned image: ${image}`,
873
- severity: "medium",
874
- category: "deployment",
875
- file: relativePath,
876
- evidence: line.trim(),
877
- confidence: "HIGH",
878
- explanation: "Unpinned images in docker-compose can silently pull breaking or vulnerable upstream changes.",
879
- recommendation: `Pin to a specific version tag or SHA digest for ${image.split(":")[0]}.`,
880
- blocking: false
881
- });
882
- }
883
- }
884
- return findings;
885
- }
886
- function checkVercelConfig(file) {
887
- const findings = [];
888
- const { content, relativePath } = file;
889
- const broadRewritePattern = /["']source["']\s*:\s*["']\/?\*\*?\/?["']/;
890
- if (broadRewritePattern.test(content)) {
891
- const line = findLine(content, broadRewritePattern);
892
- findings.push({
893
- id: makeId("vercel_broad_rewrite"),
894
- title: "vercel.json has overly broad rewrite/redirect rule (wildcard source)",
895
- severity: "medium",
896
- category: "deployment",
897
- file: relativePath,
898
- line,
899
- confidence: "MEDIUM",
900
- explanation: "Catch-all rewrite rules can accidentally expose internal routes or proxy unintended paths, creating an open redirect or SSRF surface.",
901
- recommendation: "Narrow the source pattern to only the specific paths that need rewriting.",
902
- blocking: false
903
- });
904
- }
905
- const hasHeaders = /"headers"\s*:/.test(content);
906
- if (!hasHeaders) {
907
- findings.push({
908
- id: makeId("vercel_missing_headers"),
909
- title: "vercel.json has no security headers configuration",
910
- severity: "medium",
911
- category: "deployment",
912
- file: relativePath,
913
- confidence: "MEDIUM",
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.",
915
- recommendation: 'Add a "headers" block to vercel.json or configure security headers in next.config.js instead.',
916
- blocking: false
917
- });
918
- }
919
- return findings;
920
- }
921
- function checkNetlifyConfig(file) {
922
- const findings = [];
923
- const { content, relativePath } = file;
924
- const hasHeaders = /\[headers\]/.test(content);
925
- if (!hasHeaders) {
926
- findings.push({
927
- id: makeId("netlify_missing_headers"),
928
- title: "netlify.toml has no [[headers]] security configuration",
929
- severity: "medium",
930
- category: "deployment",
931
- file: relativePath,
932
- confidence: "MEDIUM",
933
- explanation: "Without a [[headers]] block, Netlify deployments lack security headers, exposing the app to clickjacking and content-type sniffing attacks.",
934
- recommendation: "Add a [[headers]] section to netlify.toml with X-Frame-Options, X-Content-Type-Options, and other security headers.",
935
- blocking: false
936
- });
937
- }
938
- return findings;
939
- }
940
- function checkEnvFiles(files) {
941
- const findings = [];
942
- const envFile = files.find((f) => basename(f.relativePath) === ".env");
943
- const envExampleFile = files.find(
944
- (f) => basename(f.relativePath) === ".env.example" || basename(f.relativePath) === ".env.sample"
945
- );
946
- if (envFile && !envExampleFile) {
947
- findings.push({
948
- id: makeId("missing_env_example"),
949
- title: ".env file exists but .env.example is missing",
950
- severity: "low",
951
- category: "deployment",
952
- file: envFile.relativePath,
953
- confidence: "HIGH",
954
- explanation: "Without a .env.example, new contributors have no template for required environment variables, increasing the risk of misconfigured deployments.",
955
- recommendation: "Create a .env.example file with all required variable keys (and safe placeholder values) so the team can onboard without guessing configuration.",
956
- blocking: false
957
- });
958
- return findings;
959
- }
960
- if (envFile && envExampleFile) {
961
- const parseKeys = (content) => {
962
- const keys = /* @__PURE__ */ new Set();
963
- for (const line of content.split("\n")) {
964
- const trimmed = line.trim();
965
- if (!trimmed || trimmed.startsWith("#")) continue;
966
- const eqIdx = trimmed.indexOf("=");
967
- if (eqIdx > 0) {
968
- keys.add(trimmed.slice(0, eqIdx).trim());
969
- }
970
- }
971
- return keys;
972
- };
973
- const envKeys = parseKeys(envFile.content);
974
- const exampleKeys = parseKeys(envExampleFile.content);
975
- const undocumentedKeys = [...envKeys].filter((k) => !exampleKeys.has(k));
976
- if (undocumentedKeys.length > 0) {
977
- findings.push({
978
- id: makeId("env_undocumented_keys"),
979
- title: `.env has keys not present in .env.example: ${undocumentedKeys.join(", ")}`,
980
- severity: "low",
981
- category: "deployment",
982
- file: envFile.relativePath,
983
- evidence: undocumentedKeys.join(", "),
984
- confidence: "HIGH",
985
- explanation: "Keys present in .env but missing from .env.example leave teammates and deployment pipelines without the full required configuration, causing runtime failures.",
986
- recommendation: `Add the following keys to .env.example: ${undocumentedKeys.join(", ")}`,
987
- blocking: false
988
- });
989
- }
990
- }
991
- return findings;
992
- }
993
- function checkPackageJson2(file) {
994
- const findings = [];
995
- const { content, relativePath } = file;
996
- let parsed;
997
- try {
998
- parsed = JSON.parse(content);
999
- } catch {
1000
- return findings;
1001
- }
1002
- const scripts = parsed["scripts"];
1003
- if (!scripts || typeof scripts !== "object") return findings;
1004
- const scriptEntries = Object.entries(scripts);
1005
- for (const [name, value] of scriptEntries) {
1006
- if (typeof value !== "string") continue;
1007
- if (/NODE_ENV=development/i.test(value)) {
1008
- findings.push({
1009
- id: makeId(`pkg_node_env_dev_${name}`),
1010
- title: `package.json script "${name}" sets NODE_ENV=development`,
1011
- severity: "high",
1012
- category: "deployment",
1013
- file: relativePath,
1014
- evidence: `"${name}": "${value}"`,
1015
- confidence: "HIGH",
1016
- explanation: "Running with NODE_ENV=development in production disables performance optimisations and may enable verbose error output, leaking stack traces to end users.",
1017
- recommendation: `Remove NODE_ENV=development from the "${name}" script or set NODE_ENV=production explicitly.`,
1018
- blocking: true
1019
- });
1020
- }
1021
- if (/DEBUG\s*=\s*true/i.test(value) || /DEBUG\s*=\s*\*/i.test(value)) {
1022
- findings.push({
1023
- id: makeId(`pkg_debug_true_${name}`),
1024
- title: `package.json script "${name}" enables DEBUG mode`,
1025
- severity: "high",
1026
- category: "deployment",
1027
- file: relativePath,
1028
- evidence: `"${name}": "${value}"`,
1029
- confidence: "HIGH",
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.",
1031
- recommendation: `Remove the DEBUG flag from the "${name}" script.`,
1032
- blocking: true
1033
- });
1034
- }
1035
- }
1036
- return findings;
1037
- }
1038
- function checkGeneralConfigs(file) {
1039
- const findings = [];
1040
- const { content, relativePath } = file;
1041
- const corsOriginWildcard = /["']?origin["']?\s*:\s*["']?\*["']?/i;
1042
- if (corsOriginWildcard.test(content)) {
1043
- const line = findLine(content, corsOriginWildcard);
1044
- findings.push({
1045
- id: makeId("config_cors_wildcard_origin"),
1046
- title: `CORS origin wildcard (*) detected in ${relativePath}`,
1047
- severity: "high",
1048
- category: "deployment",
1049
- file: relativePath,
1050
- line,
1051
- evidence: "origin: *",
1052
- confidence: "MEDIUM",
1053
- explanation: "Setting CORS origin to * allows any website to make credentialed requests to your API, bypassing Same-Origin Policy protections.",
1054
- recommendation: "Replace the wildcard origin with an explicit allowlist of trusted domains.",
1055
- blocking: true
1056
- });
1057
- }
1058
- const debugModePattern = /["']?debug["']?\s*:\s*true/i;
1059
- if (debugModePattern.test(content)) {
1060
- const line = findLine(content, debugModePattern);
1061
- findings.push({
1062
- id: makeId("config_debug_mode"),
1063
- title: `Debug mode enabled in ${relativePath}`,
1064
- severity: "high",
1065
- category: "deployment",
1066
- file: relativePath,
1067
- line,
1068
- evidence: "debug: true",
1069
- confidence: "MEDIUM",
1070
- explanation: "Debug mode in production configs exposes verbose logs, internal stack traces, and configuration details that aid attackers.",
1071
- recommendation: "Set debug: false or remove the debug flag from production configuration.",
1072
- blocking: true
1073
- });
1074
- }
1075
- return findings;
1076
- }
1077
- var deploymentCheck = {
1078
- id: "deployment",
1079
- name: "Deployment & Configuration",
1080
- run(files, _policy) {
1081
- const findings = [];
1082
- for (const file of files) {
1083
- const base = basename(file.relativePath);
1084
- if (["next.config.js", "next.config.mjs", "next.config.ts"].includes(base)) {
1085
- findings.push(...checkNextConfig(file));
1086
- continue;
1087
- }
1088
- if (base === "Dockerfile" || base.startsWith("Dockerfile.")) {
1089
- findings.push(...checkDockerfile(file));
1090
- continue;
1091
- }
1092
- if (base === "docker-compose.yml" || base === "docker-compose.yaml") {
1093
- findings.push(...checkDockerCompose(file));
1094
- continue;
1095
- }
1096
- if (base === "vercel.json") {
1097
- findings.push(...checkVercelConfig(file));
1098
- continue;
1099
- }
1100
- if (base === "netlify.toml") {
1101
- findings.push(...checkNetlifyConfig(file));
1102
- continue;
1103
- }
1104
- if (base === "package.json") {
1105
- findings.push(...checkPackageJson2(file));
1106
- continue;
1107
- }
1108
- findings.push(...checkGeneralConfigs(file));
1109
- }
1110
- findings.push(...checkEnvFiles(files));
1111
- return findings;
1112
- }
1113
- };
1114
-
1115
- // src/checks/payments.ts
1116
- function isStripeWebhookRoute(relativePath) {
1117
- const p = relativePath.toLowerCase();
1118
- if (!p.includes("api/") && !p.includes("api\\")) return false;
1119
- return p.includes("webhook") || p.includes("stripe");
1120
- }
1121
- function isRazorpayWebhookRoute(relativePath) {
1122
- const p = relativePath.toLowerCase();
1123
- if (!p.includes("api/") && !p.includes("api\\")) return false;
1124
- return p.includes("razorpay") || p.includes("webhook") && p.includes("razorpay");
1125
- }
1126
- function isPaymentRoute(relativePath) {
1127
- const p = relativePath.toLowerCase();
1128
- if (!p.includes("api/") && !p.includes("api\\")) return false;
1129
- return p.includes("checkout") || p.includes("billing") || p.includes("subscription") || p.includes("payment");
1130
- }
1131
- function isClientSideFile(relativePath) {
1132
- const p = relativePath.toLowerCase().replace(/\\/g, "/");
1133
- if (p.startsWith("app/api/") || p.startsWith("pages/api/")) return false;
1134
- return p.startsWith("app/") || p.startsWith("pages/") || p.startsWith("components/");
1135
- }
1136
- function hasStripeConstructEvent(content) {
1137
- return /stripe\.webhooks\.constructEvent/i.test(content) || /Stripe\.webhooks\.constructEvent/i.test(content);
1138
- }
1139
- function hasStripeSignatureHeader(content) {
1140
- return /stripe-signature/i.test(content);
1141
- }
1142
- function hasRazorpayValidateWebhook(content) {
1143
- return /validateWebhookSignature/i.test(content);
1144
- }
1145
- function hasIdempotencyHandling(content) {
1146
- return /idempoten(cy|t)/i.test(content) || /event\.id/i.test(content) || /processedEvents/i.test(content) || /alreadyProcessed/i.test(content);
1147
- }
1148
- function hasErrorHandling(content) {
1149
- return /\btry\b/.test(content) && /\bcatch\b/.test(content);
1150
- }
1151
- function isBlocking(id, policy) {
1152
- return policy.block.includes(id);
1153
- }
1154
- var payments = {
1155
- id: "payments",
1156
- name: "Payment & Webhook Security",
1157
- run(files, policy) {
1158
- const findings = [];
1159
- for (const file of files) {
1160
- const { relativePath, content } = file;
1161
- if (isStripeWebhookRoute(relativePath)) {
1162
- if (!hasStripeConstructEvent(content)) {
1163
- const id = "payment_webhook_without_signature_check";
1164
- findings.push({
1165
- id,
1166
- title: "Stripe webhook missing signature verification",
1167
- severity: "critical",
1168
- category: "payments",
1169
- file: relativePath,
1170
- evidence: "No call to stripe.webhooks.constructEvent() found",
1171
- confidence: "MEDIUM",
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.",
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.",
1174
- blocking: isBlocking(id, policy)
1175
- });
1176
- }
1177
- if (!hasStripeSignatureHeader(content)) {
1178
- const id = "payment_webhook_without_signature_check";
1179
- findings.push({
1180
- id,
1181
- title: "Stripe webhook does not read stripe-signature header",
1182
- severity: "critical",
1183
- category: "payments",
1184
- file: relativePath,
1185
- evidence: "No reference to stripe-signature header found",
1186
- confidence: "MEDIUM",
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.",
1188
- recommendation: 'Read the header with request.headers.get("stripe-signature") (Next.js) or req.headers["stripe-signature"] (Express) before calling constructEvent().',
1189
- blocking: isBlocking(id, policy)
1190
- });
1191
- }
1192
- }
1193
- if (isRazorpayWebhookRoute(relativePath)) {
1194
- if (!hasRazorpayValidateWebhook(content)) {
1195
- const id = "payment_webhook_without_signature_check";
1196
- findings.push({
1197
- id,
1198
- title: "Razorpay webhook missing signature verification",
1199
- severity: "critical",
1200
- category: "payments",
1201
- file: relativePath,
1202
- evidence: "No call to validateWebhookSignature() found",
1203
- confidence: "MEDIUM",
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.",
1205
- recommendation: "Use Razorpay.validateWebhookSignature(rawBody, signature, webhookSecret) where signature is taken from the x-razorpay-signature header. Always pass the raw (unparsed) body.",
1206
- blocking: isBlocking(id, policy)
1207
- });
1208
- }
1209
- }
1210
- if (isClientSideFile(relativePath)) {
1211
- const stripeSecretInFile = /STRIPE_SECRET_KEY/i.test(content);
1212
- const razorpaySecretInFile = /RAZORPAY_KEY_SECRET/i.test(content);
1213
- if (stripeSecretInFile) {
1214
- const id = "exposed_env";
1215
- findings.push({
1216
- id,
1217
- title: "STRIPE_SECRET_KEY referenced in client-side file",
1218
- severity: "critical",
1219
- category: "payments",
1220
- file: relativePath,
1221
- evidence: "Reference to STRIPE_SECRET_KEY found in a client-bundle file",
1222
- confidence: "MEDIUM",
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.",
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.",
1225
- blocking: isBlocking(id, policy)
1226
- });
1227
- }
1228
- if (razorpaySecretInFile) {
1229
- const id = "exposed_env";
1230
- findings.push({
1231
- id,
1232
- title: "RAZORPAY_KEY_SECRET referenced in client-side file",
1233
- severity: "critical",
1234
- category: "payments",
1235
- file: relativePath,
1236
- evidence: "Reference to RAZORPAY_KEY_SECRET found in a client-bundle file",
1237
- confidence: "MEDIUM",
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.",
1239
- recommendation: "Use RAZORPAY_KEY_SECRET only in server-side API routes. For the client, only use the Razorpay key_id (public).",
1240
- blocking: isBlocking(id, policy)
1241
- });
1242
- }
1243
- }
1244
- if (isStripeWebhookRoute(relativePath) || isRazorpayWebhookRoute(relativePath)) {
1245
- if (!hasIdempotencyHandling(content)) {
1246
- const id = "missing_idempotency";
1247
- findings.push({
1248
- id,
1249
- title: "Webhook handler lacks idempotency protection",
1250
- severity: "medium",
1251
- category: "payments",
1252
- file: relativePath,
1253
- evidence: "No idempotency key, event.id check, or duplicate-detection logic found",
1254
- confidence: "LOW",
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.",
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.",
1257
- blocking: isBlocking(id, policy)
1258
- });
1259
- }
1260
- }
1261
- if (isPaymentRoute(relativePath)) {
1262
- if (!hasErrorHandling(content)) {
1263
- const id = "missing_error_handling";
1264
- findings.push({
1265
- id,
1266
- title: "Payment route lacks error handling",
1267
- severity: "low",
1268
- category: "payments",
1269
- file: relativePath,
1270
- evidence: "No try/catch block found in payment-related route",
1271
- confidence: "LOW",
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.",
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.",
1274
- blocking: isBlocking(id, policy)
1275
- });
1276
- }
1277
- }
1278
- }
1279
- return findings;
1280
- }
1281
- };
1282
-
1283
- // src/core/coderef-dispatch.ts
1284
- import { createRequire } from "module";
1285
- import { fileURLToPath } from "url";
1286
- import { dirname as dirname2, join as join2 } from "path";
1287
- var DEFAULT_DISPATCH_TABLE = {
1288
- "secrets:secretsCheck": secretsCheck,
1289
- "auth:authCheck": authCheck,
1290
- "database:databaseCheck": databaseCheck,
1291
- "deployment:deploymentCheck": deploymentCheck,
1292
- "payments:payments": payments
1293
- };
1294
- function parseSemver(v) {
1295
- const [major = 0, minor = 0, patch = 0] = v.split(".").map(Number);
1296
- return [major, minor, patch];
1297
- }
1298
- function semverLt(a, b) {
1299
- const [aMaj, aMin, aPatch] = parseSemver(a);
1300
- const [bMaj, bMin, bPatch] = parseSemver(b);
1301
- if (aMaj !== bMaj) return aMaj < bMaj;
1302
- if (aMin !== bMin) return aMin < bMin;
1303
- return aPatch < bPatch;
1304
- }
1305
- function runCoderefRules(rules, files, policy, cliVersion = CLI_VERSION, table = DEFAULT_DISPATCH_TABLE, manifest) {
1306
- const findings = [];
1307
- let degraded = false;
1308
- const warnings = [];
1309
- const augmented = rules;
1310
- const coderefs = augmented.filter((r) => r.implType === "coderef");
1311
- for (const rule of coderefs) {
1312
- const ref = rule.codeRef;
1313
- if (!ref) {
1314
- warnings.push(
1315
- `[shipguard] coderef rule ${rule.id} has implType:"coderef" but no codeRef pointer \u2014 skipping`
1316
- );
1317
- continue;
1318
- }
1319
- if (semverLt(cliVersion, ref.minCliVersion)) {
1320
- warnings.push(
1321
- `[shipguard] Skipping coderef rule ${rule.id}: requires CLI \u2265${ref.minCliVersion}, installed ${cliVersion}`
1322
- );
1323
- degraded = true;
1324
- continue;
1325
- }
1326
- if (manifest) {
1327
- const expected = manifest[ref.moduleId];
1328
- if (expected !== void 0 && expected !== ref.checksum) {
1329
- warnings.push(
1330
- `[shipguard] Skipping coderef rule ${rule.id}: checksum mismatch for module "${ref.moduleId}"`
1331
- );
1332
- continue;
1333
- }
1334
- }
1335
- const dispatchKey = `${ref.moduleId}:${ref.exportName}`;
1336
- const mod = table[dispatchKey];
1337
- if (!mod) {
1338
- warnings.push(
1339
- `[shipguard] Unknown coderef "${dispatchKey}" for rule ${rule.id} \u2014 skipping (not a crash)`
1340
- );
1341
- degraded = true;
1342
- continue;
1343
- }
1344
- const moduleFindings = mod.run(files, policy);
1345
- findings.push(...moduleFindings);
1346
- }
1347
- return { findings, degraded, warnings };
1348
- }
1349
- var _require = createRequire(import.meta.url);
1350
- var _pkgPath = join2(dirname2(fileURLToPath(import.meta.url)), "../../package.json");
1351
- var CLI_VERSION;
1352
- try {
1353
- const pkg = _require(_pkgPath);
1354
- CLI_VERSION = typeof pkg.version === "string" ? pkg.version : "0.0.0";
1355
- } catch {
1356
- CLI_VERSION = "0.0.0";
1357
- }
1358
-
1359
- // src/core/pro-scanner.ts
1360
- async function fetchProRules(frameworks, categories, apiUrl) {
1361
- const token = await getAuthToken();
1362
- if (!token) throw new Error("Not authenticated. Run `shipguard login` first.");
1363
- const res = await fetch(`${apiUrl}/api/rules/fetch`, {
1364
- method: "POST",
1365
- headers: {
1366
- "Authorization": `Bearer ${token}`,
1367
- "Content-Type": "application/json"
1368
- },
1369
- body: JSON.stringify({ frameworks, categories })
1370
- });
1371
- if (res.status === 401) throw new Error("Auth expired. Run `shipguard login` again.");
1372
- if (res.status === 402) throw new Error("No credits. Buy at https://agenticcli.dev/dashboard/billing");
1373
- if (!res.ok) throw new Error(`Rule fetch failed: ${res.statusText}`);
1374
- const { signedBundle } = await res.json();
1375
- const credits = parseInt(res.headers.get("X-Credits-Remaining") ?? "0", 10);
1376
- const rulesVersion = res.headers.get("X-Rules-Version") ?? void 0;
1377
- let payload;
1378
- try {
1379
- payload = await verifyAndDecryptBundle(signedBundle, token);
1380
- } catch (err) {
1381
- if (!(err instanceof SyntaxError)) {
1382
- throw err;
1383
- }
1384
- payload = await verifyRuleBundle(signedBundle);
1385
- }
1386
- return { rules: payload.rules, creditsRemaining: credits, rulesVersion };
1387
- }
1388
- function compileRules(rules) {
1389
- const compiled = [];
1390
- for (const rule of rules) {
1391
- const patterns = [];
1392
- const antiPatterns = [];
1393
- const flags = rule.matcher.flags ?? "";
1394
- for (const p of rule.matcher.patterns) {
1395
- try {
1396
- patterns.push(new RegExp(p, flags));
1397
- } catch (err) {
1398
- console.warn(`[shipguard] Skipping invalid pattern in rule ${rule.id}: ${p}`);
1399
- }
1400
- }
1401
- for (const p of rule.matcher.antiPatterns) {
1402
- try {
1403
- antiPatterns.push(new RegExp(p, flags));
1404
- } catch (err) {
1405
- console.warn(`[shipguard] Skipping invalid anti-pattern in rule ${rule.id}: ${p}`);
1406
- }
1407
- }
1408
- if (patterns.length > 0) {
1409
- compiled.push({ rule, patterns, antiPatterns });
1410
- }
1411
- }
1412
- return compiled;
1413
- }
1414
- var SUPPRESS_RE = /\/\/\s*shipguard-ignore:\s*([\w.-]+)\s*--\s*(.+)/;
1415
- function isLineSuppressed(lines, lineIndex, ruleId) {
1416
- const sameLine = lines[lineIndex];
1417
- const sameMatch = SUPPRESS_RE.exec(sameLine);
1418
- if (sameMatch && sameMatch[1] === ruleId) return true;
1419
- if (lineIndex > 0) {
1420
- const aboveLine = lines[lineIndex - 1];
1421
- const aboveMatch = SUPPRESS_RE.exec(aboveLine);
1422
- if (aboveMatch && aboveMatch[1] === ruleId) return true;
1423
- }
1424
- return false;
1425
- }
1426
- function deriveBlocking(rule) {
1427
- if (rule.action === "block") return true;
1428
- if (rule.action === "warn" || rule.action === "monitor") return false;
1429
- if (rule.confidence === "HIGH") return true;
1430
- return rule.severity === "critical" || rule.severity === "high";
1431
- }
1432
- function runProRules(rules, files, _policy) {
1433
- const findings = [];
1434
- const compiled = compileRules(rules);
1435
- for (const { rule, patterns, antiPatterns } of compiled) {
1436
- const matched = files.filter((f) => minimatch(f.relativePath, rule.matcher.fileGlob));
1437
- for (const file of matched) {
1438
- const hit = patterns.some((re) => re.test(file.content));
1439
- if (!hit) continue;
1440
- const negated = antiPatterns.some((re) => re.test(file.content));
1441
- if (negated) continue;
1442
- const lines = file.content.split("\n");
1443
- let line;
1444
- for (let i = 0; i < lines.length; i++) {
1445
- if (patterns.some((re) => re.test(lines[i]))) {
1446
- line = i + 1;
1447
- break;
1448
- }
1449
- }
1450
- const suppressed = line !== void 0 && isLineSuppressed(lines, line - 1, rule.id);
1451
- findings.push({
1452
- id: rule.id,
1453
- title: rule.explanation.split(".")[0],
1454
- severity: rule.severity,
1455
- category: rule.category,
1456
- file: file.relativePath,
1457
- line,
1458
- explanation: rule.explanation,
1459
- recommendation: rule.recommendation,
1460
- blocking: suppressed ? false : deriveBlocking(rule),
1461
- suppressed,
1462
- // New fields from spec
1463
- fix: rule.fix,
1464
- confidence: rule.confidence,
1465
- aiCodeTarget: rule.aiCodeTarget,
1466
- cwe: rule.cwe
1467
- });
1468
- }
1469
- }
1470
- return findings;
1471
- }
1472
- function runProRulesWithDispatch(rules, files, policy, cliVersion, table, manifest) {
1473
- const augmented = rules;
1474
- const coderefs = augmented.filter((r) => r.implType === "coderef");
1475
- const declaratives = augmented.filter((r) => r.implType !== "coderef");
1476
- const declarativeFindings = declaratives.length > 0 ? runProRules(declaratives, files, policy) : [];
1477
- const dispatchArgs = [
1478
- coderefs,
1479
- files,
1480
- policy
1481
- ];
1482
- if (cliVersion !== void 0) dispatchArgs.push(cliVersion);
1483
- if (table !== void 0) dispatchArgs.push(table);
1484
- if (manifest !== void 0) dispatchArgs.push(manifest);
1485
- const { findings: coderefFindings, degraded, warnings } = runCoderefRules(...dispatchArgs);
1486
- return {
1487
- findings: [...declarativeFindings, ...coderefFindings],
1488
- degraded,
1489
- warnings
1490
- };
1491
- }
1492
-
1493
- export {
1494
- secretsCheck,
1495
- authCheck,
1496
- databaseCheck,
1497
- payments,
1498
- deploymentCheck,
1499
- loadCredentials,
1500
- saveCredentials,
1501
- clearCredentials,
1502
- isTokenExpired,
1503
- getAuthToken,
1504
- fetchProRules,
1505
- runProRules,
1506
- runProRulesWithDispatch
1507
- };