@clearrecord/check 1.1.1 → 1.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 +8 -7
- package/bin/check.js +296 -14
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -21,13 +21,14 @@ npx @clearrecord/check --strict
|
|
|
21
21
|
## ⚙️ How it Works
|
|
22
22
|
The scanner is **Air-Gapped**. It is read-only and performs zero outbound network calls. Your source code never leaves your environment.
|
|
23
23
|
|
|
24
|
-
## 📊
|
|
25
|
-
The scanner verifies your codebase
|
|
26
|
-
1. **PostgreSQL/Supabase Security** (RLS Enforcement)
|
|
27
|
-
2. **Next.js
|
|
28
|
-
3. **
|
|
29
|
-
4. **Secrets & Auth Hygiene** (
|
|
30
|
-
5. **DB Performance** (
|
|
24
|
+
## 📊 Verified Rule Coverage
|
|
25
|
+
The scanner verifies your codebase locally with zero network egress across 6 deterministic modules:
|
|
26
|
+
1. **PostgreSQL/Supabase Security (`CR-ARCH-02`, `CR-ARCH-03`)** (RLS Enforcement & CVE-2025-48757 Zero-Policy Trap)
|
|
27
|
+
2. **Next.js Route & Middleware Auth (`CR-ARCH-01`)** (Server Route Auth Guards + `middleware.ts` Resolution)
|
|
28
|
+
3. **Billing & Webhook Hygiene (`CR-BIL-01..03`)** (Stripe, Lemon Squeezy & Paddle Signature Verification)
|
|
29
|
+
4. **Secrets & Auth Hygiene (`CR-SEC-01..07`)** (Supabase, Stripe, OpenAI, Anthropic, AWS, GitHub & Slack Credentials)
|
|
30
|
+
5. **DB & Schema Performance (`CR-PERF-01`)** (SQL Foreign Key & Prisma `@relation` Index Coverage)
|
|
31
|
+
6. **Dependency Triage** (Framework & EOL Runtime Checks)
|
|
31
32
|
|
|
32
33
|
## 📜 License
|
|
33
34
|
MIT
|
package/bin/check.js
CHANGED
|
@@ -5817,9 +5817,10 @@ var Crawler = class {
|
|
|
5817
5817
|
"secret-scanner": [],
|
|
5818
5818
|
"billing-auditor": [],
|
|
5819
5819
|
"index-detector": [],
|
|
5820
|
-
"dependency-triage": []
|
|
5820
|
+
"dependency-triage": [],
|
|
5821
|
+
"route-auth-analyzer": []
|
|
5821
5822
|
};
|
|
5822
|
-
const allFiles = await (0, import_fast_glob.default)(["**/*.{ts,tsx,js,jsx,sql,json}"], {
|
|
5823
|
+
const allFiles = await (0, import_fast_glob.default)(["**/*.{ts,tsx,js,jsx,mjs,sql,prisma,json}"], {
|
|
5823
5824
|
cwd: this.rootDir,
|
|
5824
5825
|
ignore: this.ignorePatterns,
|
|
5825
5826
|
absolute: true
|
|
@@ -5827,14 +5828,19 @@ var Crawler = class {
|
|
|
5827
5828
|
for (const filePath of allFiles) {
|
|
5828
5829
|
const ext = import_path.default.extname(filePath);
|
|
5829
5830
|
const fileName = import_path.default.basename(filePath);
|
|
5831
|
+
const normalized = filePath.replace(/\\/g, "/").toLowerCase();
|
|
5830
5832
|
if (ext === ".sql") {
|
|
5831
5833
|
manifest["rls-analyzer"].push(filePath);
|
|
5832
5834
|
manifest["index-detector"].push(filePath);
|
|
5833
5835
|
}
|
|
5834
|
-
if (
|
|
5836
|
+
if (ext === ".prisma") {
|
|
5837
|
+
manifest["index-detector"].push(filePath);
|
|
5838
|
+
}
|
|
5839
|
+
if ([".ts", ".tsx", ".js", ".jsx", ".mjs"].includes(ext)) {
|
|
5835
5840
|
manifest["secret-scanner"].push(filePath);
|
|
5841
|
+
manifest["route-auth-analyzer"].push(filePath);
|
|
5836
5842
|
}
|
|
5837
|
-
if (
|
|
5843
|
+
if (normalized.includes("webhook")) {
|
|
5838
5844
|
manifest["billing-auditor"].push(filePath);
|
|
5839
5845
|
}
|
|
5840
5846
|
if (fileName === "package.json") {
|
|
@@ -5919,9 +5925,11 @@ var RlsAnalyzer = class {
|
|
|
5919
5925
|
const lines = content.split(/\r?\n/);
|
|
5920
5926
|
const tables = [];
|
|
5921
5927
|
const enabledRls = /* @__PURE__ */ new Set();
|
|
5928
|
+
const tablesWithPolicies = /* @__PURE__ */ new Set();
|
|
5922
5929
|
const publicPolicies = /* @__PURE__ */ new Map();
|
|
5923
5930
|
const createTableRegex = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:public\.)?(\w+)/i;
|
|
5924
5931
|
const enableRlsRegex = /ALTER\s+TABLE\s+(?:public\.)?(\w+)\s+ENABLE\s+ROW\s+LEVEL\s+SECURITY/i;
|
|
5932
|
+
const anyPolicyRegex = /CREATE\s+POLICY\s+["']?[^"'\n]+["']?\s+ON\s+(?:public\.)?(\w+)/i;
|
|
5925
5933
|
const publicPolicyRegex = /CREATE\s+POLICY\s+".*?"\s+ON\s+(?:public\.)?(\w+)\s+FOR\s+SELECT\s+TO\s+public/i;
|
|
5926
5934
|
lines.forEach((line, idx) => {
|
|
5927
5935
|
const lineNumber = idx + 1;
|
|
@@ -5929,6 +5937,8 @@ var RlsAnalyzer = class {
|
|
|
5929
5937
|
if (tableMatch) tables.push({ name: tableMatch[1], line: lineNumber });
|
|
5930
5938
|
const rlsMatch = line.match(enableRlsRegex);
|
|
5931
5939
|
if (rlsMatch) enabledRls.add(rlsMatch[1]);
|
|
5940
|
+
const anyPolicyMatch = line.match(anyPolicyRegex);
|
|
5941
|
+
if (anyPolicyMatch) tablesWithPolicies.add(anyPolicyMatch[1]);
|
|
5932
5942
|
const policyMatch = line.match(publicPolicyRegex);
|
|
5933
5943
|
if (policyMatch && !publicPolicies.has(policyMatch[1])) {
|
|
5934
5944
|
publicPolicies.set(policyMatch[1], lineNumber);
|
|
@@ -5963,6 +5973,33 @@ CREATE POLICY "Users can read own" ON public.${table} FOR SELECT TO authenticate
|
|
|
5963
5973
|
},
|
|
5964
5974
|
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
5965
5975
|
});
|
|
5976
|
+
} else if (!tablesWithPolicies.has(table)) {
|
|
5977
|
+
findings.push({
|
|
5978
|
+
id: "CR-ARCH-03",
|
|
5979
|
+
moduleId: "rls-analyzer",
|
|
5980
|
+
title: "RLS Enabled Without Policy (CVE-2025-48757 Zero-Policy Trap)",
|
|
5981
|
+
severity: "HIGH",
|
|
5982
|
+
cvssScore: 8.2,
|
|
5983
|
+
location: {
|
|
5984
|
+
filePath,
|
|
5985
|
+
startLine: createLine,
|
|
5986
|
+
endLine: createLine,
|
|
5987
|
+
startCol: 1,
|
|
5988
|
+
endCol: 100,
|
|
5989
|
+
snippet: `ALTER TABLE public.${table} ENABLE ROW LEVEL SECURITY (0 policies)`
|
|
5990
|
+
},
|
|
5991
|
+
analysis: {
|
|
5992
|
+
description: `The '${table}' table enables RLS without defining explicit CREATE POLICY rules.`,
|
|
5993
|
+
aiContrast: "Many scanners stop once ENABLE ROW LEVEL SECURITY appears, missing incomplete/untested policy coverage.",
|
|
5994
|
+
empiricalProof: `SELECT tablename, policyname FROM pg_policies WHERE tablename = '${table}';`
|
|
5995
|
+
},
|
|
5996
|
+
remediation: {
|
|
5997
|
+
summary: "Define explicit authenticated tenant policies on the RLS-enabled table.",
|
|
5998
|
+
fixScript: `CREATE POLICY "Authenticated Read" ON public.${table} FOR SELECT TO authenticated USING (auth.uid() = user_id);`,
|
|
5999
|
+
prTitle: `Security: Add explicit RLS policies to ${table}`
|
|
6000
|
+
},
|
|
6001
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
6002
|
+
});
|
|
5966
6003
|
} else if (publicPolicies.has(table)) {
|
|
5967
6004
|
const policyLine = publicPolicies.get(table) || createLine;
|
|
5968
6005
|
findings.push({
|
|
@@ -6001,13 +6038,23 @@ CREATE POLICY "Authenticated Read" ON public.${table} FOR SELECT TO authenticate
|
|
|
6001
6038
|
// src/analyzers/secret-scanner.ts
|
|
6002
6039
|
var SecretScanner = class {
|
|
6003
6040
|
secretPatterns = [
|
|
6041
|
+
{
|
|
6042
|
+
id: "CR-SEC-01",
|
|
6043
|
+
title: "Google / Firebase Server API Key Leak",
|
|
6044
|
+
regex: /AIza[0-9A-Za-z_-]{35}/g,
|
|
6045
|
+
severity: "HIGH",
|
|
6046
|
+
cvssScore: 7.5,
|
|
6047
|
+
aiContrast: "AI helpers rarely check whether an AIza key is unrestricted in frontend JS.",
|
|
6048
|
+
empiricalProof: 'curl "https://identitytoolkit.googleapis.com/v1/accounts:lookup?key=AIza..."',
|
|
6049
|
+
remediation: "Restrict HTTP referrers / APIs in GCP Console or move key to a server-only env var."
|
|
6050
|
+
},
|
|
6004
6051
|
{
|
|
6005
6052
|
id: "CR-SEC-02",
|
|
6006
6053
|
title: "Supabase Service Role Leak",
|
|
6007
|
-
regex: /sb_admin_[a-zA-Z0-9]
|
|
6054
|
+
regex: /(?:sb_admin_[a-zA-Z0-9]+|sb_secret_[a-zA-Z0-9_-]{16,}|SUPABASE_SERVICE_ROLE_KEY\s*[:=]\s*['"][^'"]{12,}['"])/g,
|
|
6008
6055
|
severity: "CRITICAL",
|
|
6009
6056
|
cvssScore: 9.8,
|
|
6010
|
-
aiContrast: "General LLMs often ignore strings starting with sb_admin_ as they look like internal IDs. They fail to recognize this as the bypass-all-RLS master key.",
|
|
6057
|
+
aiContrast: "General LLMs often ignore strings starting with sb_admin_ / sb_secret_ as they look like internal IDs. They fail to recognize this as the bypass-all-RLS master key.",
|
|
6011
6058
|
empiricalProof: "curl -X GET 'https://[PROJECT].supabase.co/rest/v1/any_table?select=*' -H 'apikey: [SERVICE_ROLE_KEY]'",
|
|
6012
6059
|
remediation: "Move this key to a server-side .env file and never expose it to the client bundle."
|
|
6013
6060
|
},
|
|
@@ -6020,11 +6067,52 @@ var SecretScanner = class {
|
|
|
6020
6067
|
aiContrast: 'AI agents may see "sk_live" and assume it is a configuration constant. They fail to flag it as an immediate financial risk.',
|
|
6021
6068
|
empiricalProof: "curl https://api.stripe.com/v1/charges -u sk_live_...:",
|
|
6022
6069
|
remediation: "Immediately rotate this key in the Stripe Dashboard and move it to a secure secret manager."
|
|
6070
|
+
},
|
|
6071
|
+
{
|
|
6072
|
+
id: "CR-SEC-04",
|
|
6073
|
+
title: "AWS IAM Access Key ID Leak",
|
|
6074
|
+
regex: /AKIA(?!IOSFODNN7EXAMPLE)[0-9A-Z]{16}/g,
|
|
6075
|
+
severity: "CRITICAL",
|
|
6076
|
+
cvssScore: 9,
|
|
6077
|
+
aiContrast: "Long-lived AKIA credentials grant programmatic AWS S3/IAM access if leaked in git.",
|
|
6078
|
+
empiricalProof: "aws sts get-caller-identity with extracted AKIA access key",
|
|
6079
|
+
remediation: "Revoke the IAM access key immediately in AWS IAM and adopt short-lived OIDC roles."
|
|
6080
|
+
},
|
|
6081
|
+
{
|
|
6082
|
+
id: "CR-SEC-05",
|
|
6083
|
+
title: "RSA / PEM Private Key Leak",
|
|
6084
|
+
regex: /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/g,
|
|
6085
|
+
severity: "CRITICAL",
|
|
6086
|
+
cvssScore: 9.5,
|
|
6087
|
+
aiContrast: "Private cryptographic keys inside source files allow token forgery or MITM compromise.",
|
|
6088
|
+
empiricalProof: "PEM private key header committed directly in repository",
|
|
6089
|
+
remediation: "Remove PEM block from repository, rotate the signing key, and inject via KMS / secret manager."
|
|
6090
|
+
},
|
|
6091
|
+
{
|
|
6092
|
+
id: "CR-SEC-06",
|
|
6093
|
+
title: "Client-Exposed Secret Env Prefix (NEXT_PUBLIC_ / VITE_)",
|
|
6094
|
+
regex: /(?:NEXT_PUBLIC_|VITE_)[A-Z0-9_]*(?:SERVICE_ROLE|SECRET_KEY|WEBHOOK_SECRET|PRIVATE_KEY|ADMIN_KEY)/g,
|
|
6095
|
+
severity: "CRITICAL",
|
|
6096
|
+
cvssScore: 9.3,
|
|
6097
|
+
aiContrast: "Frameworks inline NEXT_PUBLIC_* and VITE_* variables verbatim into browser bundles.",
|
|
6098
|
+
empiricalProof: "Any visitor can inspect compiled browser JS chunks to read the credential.",
|
|
6099
|
+
remediation: "Remove the NEXT_PUBLIC_ / VITE_ prefix so the key stays strictly on the server."
|
|
6100
|
+
},
|
|
6101
|
+
{
|
|
6102
|
+
id: "CR-SEC-07",
|
|
6103
|
+
title: "Browser-Exposed AI SDK (dangerouslyAllowBrowser)",
|
|
6104
|
+
regex: /dangerouslyAllowBrowser\s*:\s*true/g,
|
|
6105
|
+
severity: "CRITICAL",
|
|
6106
|
+
cvssScore: 9,
|
|
6107
|
+
aiContrast: "Shipping dangerouslyAllowBrowser: true exposes your OpenAI/Anthropic billing key to every visitor.",
|
|
6108
|
+
empiricalProof: "Browser network tab exposes Authorization: Bearer sk-... on client LLM calls.",
|
|
6109
|
+
remediation: "Move AI SDK calls into a Next.js App Router API Route (/api/ai) and remove dangerouslyAllowBrowser."
|
|
6023
6110
|
}
|
|
6024
6111
|
];
|
|
6025
6112
|
async analyze(filePath, content) {
|
|
6026
6113
|
const findings = [];
|
|
6027
|
-
|
|
6114
|
+
const normalized = filePath.replace(/\\/g, "/");
|
|
6115
|
+
if (/(?:^|\/)(?:__tests__|tests?|mocks?|fixtures?)\//i.test(normalized) || /\.(?:test|spec)\.[jt]sx?$/i.test(normalized)) {
|
|
6028
6116
|
return [];
|
|
6029
6117
|
}
|
|
6030
6118
|
for (const pattern of this.secretPatterns) {
|
|
@@ -6073,6 +6161,71 @@ var SecretScanner = class {
|
|
|
6073
6161
|
var BillingAuditor = class {
|
|
6074
6162
|
async analyze(filePath, content) {
|
|
6075
6163
|
const findings = [];
|
|
6164
|
+
const lowerPath = filePath.replace(/\\/g, "/").toLowerCase();
|
|
6165
|
+
if (lowerPath.includes("lemon")) {
|
|
6166
|
+
const hasLemonVerify = content.toLowerCase().includes("x-signature") || content.includes("createHmac") || content.includes("timingSafeEqual");
|
|
6167
|
+
if (!hasLemonVerify) {
|
|
6168
|
+
findings.push({
|
|
6169
|
+
id: "CR-BIL-02",
|
|
6170
|
+
moduleId: "billing-auditor",
|
|
6171
|
+
title: "Unverified Lemon Squeezy Webhook Handler",
|
|
6172
|
+
severity: "CRITICAL",
|
|
6173
|
+
cvssScore: 8.8,
|
|
6174
|
+
location: {
|
|
6175
|
+
filePath,
|
|
6176
|
+
startLine: 1,
|
|
6177
|
+
endLine: 1,
|
|
6178
|
+
startCol: 1,
|
|
6179
|
+
endCol: 100,
|
|
6180
|
+
snippet: "Lemon Squeezy webhook missing X-Signature HMAC-SHA256 verification"
|
|
6181
|
+
},
|
|
6182
|
+
analysis: {
|
|
6183
|
+
description: "Lemon Squeezy webhook handler processes subscription events without verifying the X-Signature HMAC-SHA256 digest.",
|
|
6184
|
+
aiContrast: "AI helpers often check req.json() payloads while omitting crypto.timingSafeEqual signature validation.",
|
|
6185
|
+
empiricalProof: `curl -X POST https://[PROJECT].com/api/webhooks/lemonsqueezy -d '{"meta":{"event_name":"subscription_created"}}'`
|
|
6186
|
+
},
|
|
6187
|
+
remediation: {
|
|
6188
|
+
summary: "Verify X-Signature with HMAC-SHA256 and timingSafeEqual against LEMONSQUEEZY_WEBHOOK_SECRET.",
|
|
6189
|
+
fixScript: 'crypto.timingSafeEqual(digest, Buffer.from(signature, "utf8"))',
|
|
6190
|
+
prTitle: "Security: Verify Lemon Squeezy webhook HMAC signature"
|
|
6191
|
+
},
|
|
6192
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
6193
|
+
});
|
|
6194
|
+
}
|
|
6195
|
+
return findings;
|
|
6196
|
+
}
|
|
6197
|
+
if (lowerPath.includes("paddle")) {
|
|
6198
|
+
const hasPaddleVerify = content.toLowerCase().includes("paddle-signature") || content.includes("webhooks.unmarshal") || content.includes("createHmac");
|
|
6199
|
+
if (!hasPaddleVerify) {
|
|
6200
|
+
findings.push({
|
|
6201
|
+
id: "CR-BIL-03",
|
|
6202
|
+
moduleId: "billing-auditor",
|
|
6203
|
+
title: "Unverified Paddle Webhook Handler",
|
|
6204
|
+
severity: "CRITICAL",
|
|
6205
|
+
cvssScore: 8.8,
|
|
6206
|
+
location: {
|
|
6207
|
+
filePath,
|
|
6208
|
+
startLine: 1,
|
|
6209
|
+
endLine: 1,
|
|
6210
|
+
startCol: 1,
|
|
6211
|
+
endCol: 100,
|
|
6212
|
+
snippet: "Paddle webhook missing Paddle-Signature unmarshal verification"
|
|
6213
|
+
},
|
|
6214
|
+
analysis: {
|
|
6215
|
+
description: "Paddle webhook endpoint processes billing events without verifying Paddle-Signature via paddle.webhooks.unmarshal.",
|
|
6216
|
+
aiContrast: "Generic code reviewers rarely inspect Paddle unmarshal verification.",
|
|
6217
|
+
empiricalProof: `curl -X POST https://[PROJECT].com/api/webhooks/paddle -d '{"event_type":"subscription.activated"}'`
|
|
6218
|
+
},
|
|
6219
|
+
remediation: {
|
|
6220
|
+
summary: "Validate Paddle-Signature header with paddle.webhooks.unmarshal().",
|
|
6221
|
+
fixScript: "const event = await paddle.webhooks.unmarshal(rawBody, process.env.PADDLE_WEBHOOK_SECRET!, sig);",
|
|
6222
|
+
prTitle: "Security: Verify Paddle webhook signature"
|
|
6223
|
+
},
|
|
6224
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
6225
|
+
});
|
|
6226
|
+
}
|
|
6227
|
+
return findings;
|
|
6228
|
+
}
|
|
6076
6229
|
const hasConstructEvent = content.includes("stripe.webhooks.constructEvent");
|
|
6077
6230
|
const processesPayment = /update.*subscriptions|create.*customer|grant.*access|db\..*update|prisma\..*update|supabase\..*update/i.test(content);
|
|
6078
6231
|
if (processesPayment && !hasConstructEvent) {
|
|
@@ -6123,8 +6276,7 @@ var BillingAuditor = class {
|
|
|
6123
6276
|
analysis: {
|
|
6124
6277
|
description: "The Stripe webhook secret is either empty or uses a placeholder value.",
|
|
6125
6278
|
aiContrast: 'AI agents see a call to constructEvent and mark it "secure". They fail to check if the actual secret being passed is an empty string.',
|
|
6126
|
-
empiricalProof: "The webhook secret is empty; any signature will be rejected, or a trivial bypass may exist depending on the SDK version."
|
|
6127
|
-
remediation: "Ensure STRIPE_WEBHOOK_SECRET is loaded from an environment variable."
|
|
6279
|
+
empiricalProof: "The webhook secret is empty; any signature will be rejected, or a trivial bypass may exist depending on the SDK version."
|
|
6128
6280
|
},
|
|
6129
6281
|
remediation: {
|
|
6130
6282
|
summary: "Inject the webhook secret from environment variables.",
|
|
@@ -6143,6 +6295,49 @@ var BillingAuditor = class {
|
|
|
6143
6295
|
var IndexDetector = class {
|
|
6144
6296
|
async analyze(filePath, content) {
|
|
6145
6297
|
const findings = [];
|
|
6298
|
+
if (filePath.endsWith(".prisma")) {
|
|
6299
|
+
const modelBlocks = content.split(/^model\s+(\w+)\s*\{/m);
|
|
6300
|
+
for (let i = 1; i < modelBlocks.length; i += 2) {
|
|
6301
|
+
const modelName = modelBlocks[i];
|
|
6302
|
+
const body = (modelBlocks[i + 1] || "").split(/\n\}/)[0] || "";
|
|
6303
|
+
const relationMatches = Array.from(body.matchAll(/@relation\([^)]*fields:\s*\[([^\]]+)\]/g));
|
|
6304
|
+
for (const match of relationMatches) {
|
|
6305
|
+
const fkFields = match[1].split(",").map((s) => s.trim()).filter(Boolean);
|
|
6306
|
+
const firstField = fkFields[0];
|
|
6307
|
+
if (!firstField) continue;
|
|
6308
|
+
const hasIndex = new RegExp(`@@(?:index|unique)\\([^)]*\\b${firstField}\\b`).test(body);
|
|
6309
|
+
if (!hasIndex) {
|
|
6310
|
+
findings.push({
|
|
6311
|
+
id: "CR-PERF-01",
|
|
6312
|
+
moduleId: "index-detector",
|
|
6313
|
+
title: "Missing Prisma Relation Index",
|
|
6314
|
+
severity: "MEDIUM",
|
|
6315
|
+
cvssScore: 4.5,
|
|
6316
|
+
location: {
|
|
6317
|
+
filePath,
|
|
6318
|
+
startLine: 1,
|
|
6319
|
+
endLine: 1,
|
|
6320
|
+
startCol: 1,
|
|
6321
|
+
endCol: 100,
|
|
6322
|
+
snippet: `model ${modelName} FK ${firstField}`
|
|
6323
|
+
},
|
|
6324
|
+
analysis: {
|
|
6325
|
+
description: `Prisma model ${modelName} defines a foreign-key relation on '${firstField}' without an @@index([${firstField}]) directive.`,
|
|
6326
|
+
aiContrast: "Deterministic Prisma schema inspection catches missing relation indexes that trigger full-table scans on joins.",
|
|
6327
|
+
empiricalProof: `model ${modelName} { ... @@index([${firstField}]) }`
|
|
6328
|
+
},
|
|
6329
|
+
remediation: {
|
|
6330
|
+
summary: `Add @@index([${firstField}]) to Prisma model ${modelName}.`,
|
|
6331
|
+
fixScript: ` @@index([${firstField}])`,
|
|
6332
|
+
prTitle: `Perf: Add Prisma index on ${modelName}.${firstField}`
|
|
6333
|
+
},
|
|
6334
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
6335
|
+
});
|
|
6336
|
+
}
|
|
6337
|
+
}
|
|
6338
|
+
}
|
|
6339
|
+
return findings;
|
|
6340
|
+
}
|
|
6146
6341
|
const indices = /* @__PURE__ */ new Set();
|
|
6147
6342
|
const indexRegex = /CREATE\s+INDEX\s+[\w_]+\s+ON\s+(?:public\.)?(\w+)\((\w+)\)/gi;
|
|
6148
6343
|
let indexMatch;
|
|
@@ -6208,9 +6403,12 @@ var DependencyTriage = class {
|
|
|
6208
6403
|
} catch (e) {
|
|
6209
6404
|
return [];
|
|
6210
6405
|
}
|
|
6211
|
-
const dependencies = {
|
|
6406
|
+
const dependencies = {
|
|
6407
|
+
...pkg?.dependencies ?? {},
|
|
6408
|
+
...pkg?.devDependencies ?? {}
|
|
6409
|
+
};
|
|
6212
6410
|
for (const [lib, version] of Object.entries(dependencies)) {
|
|
6213
|
-
if (this.safeVersions[lib]) {
|
|
6411
|
+
if (this.safeVersions[lib] && typeof version === "string") {
|
|
6214
6412
|
const currentMajor = parseInt(version.replace(/[^0-9.]/, "").split(".")[0]);
|
|
6215
6413
|
const safeMajor = parseInt(this.safeVersions[lib].split(".")[0]);
|
|
6216
6414
|
if (currentMajor < safeMajor) {
|
|
@@ -6245,6 +6443,72 @@ var DependencyTriage = class {
|
|
|
6245
6443
|
}
|
|
6246
6444
|
};
|
|
6247
6445
|
|
|
6446
|
+
// src/analyzers/route-auth-analyzer.ts
|
|
6447
|
+
var RouteAuthAnalyzer = class {
|
|
6448
|
+
async analyze(filePath, content, options) {
|
|
6449
|
+
const findings = [];
|
|
6450
|
+
const normalizedPath = filePath.replace(/\\/g, "/");
|
|
6451
|
+
const lowerPath = normalizedPath.toLowerCase();
|
|
6452
|
+
if (/(?:^|\/)(?:__tests__|tests?|mocks?|fixtures?)\//i.test(normalizedPath) || /\.(?:test|spec)\.[jt]sx?$/i.test(normalizedPath)) {
|
|
6453
|
+
return [];
|
|
6454
|
+
}
|
|
6455
|
+
const baseName = normalizedPath.split("/").pop() || "";
|
|
6456
|
+
const isAppRouterEndpoint = baseName === "route.ts" || baseName === "route.js";
|
|
6457
|
+
const isPagesRouterEndpoint = /\/pages\/api\/.+\.(?:ts|js|mjs)$/i.test(normalizedPath) && (content.includes("export default") || content.includes("module.exports"));
|
|
6458
|
+
if (!isAppRouterEndpoint && !isPagesRouterEndpoint) {
|
|
6459
|
+
return [];
|
|
6460
|
+
}
|
|
6461
|
+
const codeOnly = content.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/.*$/gm, "");
|
|
6462
|
+
const isPublicAuthOrWebhookPath = /\/(?:\(auth\)\/)?(?:auth\/)?(?:callback|confirm|login|signin|signup|register|logout|signout|reset-password|forgot-password|verify|magic-link)\b/i.test(
|
|
6463
|
+
normalizedPath
|
|
6464
|
+
) || normalizedPath.includes("[...nextauth]") || normalizedPath.includes("/api/auth/") || lowerPath.includes("webhook") || /\/api\/(?:health|status|ping|public|og)\b/i.test(normalizedPath) || codeOnly.includes("NextAuth(") || codeOnly.includes("ImageResponse") || codeOnly.includes("exchangeCodeForSession");
|
|
6465
|
+
if (isPublicAuthOrWebhookPath) {
|
|
6466
|
+
return [];
|
|
6467
|
+
}
|
|
6468
|
+
if (options?.middlewareProtectsApi) {
|
|
6469
|
+
return [];
|
|
6470
|
+
}
|
|
6471
|
+
const hasMutatingAppMethod = /\bexport\s+(?:async\s+)?function\s+(?:POST|PUT|DELETE|PATCH)\b/.test(codeOnly) || /\bexport\s+const\s+(?:POST|PUT|DELETE|PATCH)\b/.test(codeOnly);
|
|
6472
|
+
if (isAppRouterEndpoint && !hasMutatingAppMethod) {
|
|
6473
|
+
return [];
|
|
6474
|
+
}
|
|
6475
|
+
const hasAuth = codeOnly.includes("auth()") || codeOnly.includes("auth.getUser") || codeOnly.includes("auth.getSession") || codeOnly.includes("getServerSession") || codeOnly.includes("getSession") || codeOnly.includes("requireUser") || codeOnly.includes("currentUser") || codeOnly.includes("protectedProcedure") || codeOnly.includes("constructEvent") || codeOnly.includes("createHmac") || codeOnly.includes("unmarshal") || /headers(?:\(\))?\.get\s*\(\s*['"](?:authorization|x-api-key|stripe-signature|x-signature|paddle-signature)['"]\s*\)/i.test(
|
|
6476
|
+
codeOnly
|
|
6477
|
+
) || /\b(?:verify|authenticate|validate|require|checkAuth|withAuth|ensureAuth|requireSession)[A-Za-z0-9_]*\s*\(/.test(
|
|
6478
|
+
codeOnly
|
|
6479
|
+
);
|
|
6480
|
+
if (!hasAuth) {
|
|
6481
|
+
findings.push({
|
|
6482
|
+
id: "CR-ARCH-01",
|
|
6483
|
+
moduleId: "route-auth-analyzer",
|
|
6484
|
+
title: "Unprotected API Route detected",
|
|
6485
|
+
severity: "CRITICAL",
|
|
6486
|
+
cvssScore: 9.2,
|
|
6487
|
+
location: {
|
|
6488
|
+
filePath,
|
|
6489
|
+
startLine: 1,
|
|
6490
|
+
endLine: 1,
|
|
6491
|
+
startCol: 1,
|
|
6492
|
+
endCol: 100,
|
|
6493
|
+
snippet: "Mutating route handler lacks session verification or API signature check."
|
|
6494
|
+
},
|
|
6495
|
+
analysis: {
|
|
6496
|
+
description: "Route handler executes server mutations without verifying caller session cookies or cryptographic request headers.",
|
|
6497
|
+
aiContrast: "LLM-generated API routes frequently omit session authentication at the top of POST/PUT/DELETE handlers.",
|
|
6498
|
+
empiricalProof: `curl -X POST https://[PROJECT].com/api/... -H "Content-Type: application/json"`
|
|
6499
|
+
},
|
|
6500
|
+
remediation: {
|
|
6501
|
+
summary: "Verify authenticated user session before executing handler mutations.",
|
|
6502
|
+
fixScript: 'const { data: { user } } = await supabase.auth.getUser(); if (!user) return Response.json({ error: "Unauthorized" }, { status: 401 });',
|
|
6503
|
+
prTitle: "Security: Add caller auth guard to mutating API route"
|
|
6504
|
+
},
|
|
6505
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
6506
|
+
});
|
|
6507
|
+
}
|
|
6508
|
+
return findings;
|
|
6509
|
+
}
|
|
6510
|
+
};
|
|
6511
|
+
|
|
6248
6512
|
// src/auditor/risk-matrix.ts
|
|
6249
6513
|
var RISK_MATRIX = {
|
|
6250
6514
|
"CR-ARCH-02": {
|
|
@@ -6658,7 +6922,8 @@ var ClearRecordEngine = class {
|
|
|
6658
6922
|
"secret-scanner": new SecretScanner(),
|
|
6659
6923
|
"billing-auditor": new BillingAuditor(),
|
|
6660
6924
|
"index-detector": new IndexDetector(),
|
|
6661
|
-
"dependency-triage": new DependencyTriage()
|
|
6925
|
+
"dependency-triage": new DependencyTriage(),
|
|
6926
|
+
"route-auth-analyzer": new RouteAuthAnalyzer()
|
|
6662
6927
|
};
|
|
6663
6928
|
}
|
|
6664
6929
|
rootDir;
|
|
@@ -6670,13 +6935,30 @@ var ClearRecordEngine = class {
|
|
|
6670
6935
|
async run() {
|
|
6671
6936
|
const manifest = await this.crawler.crawl();
|
|
6672
6937
|
const allFindings = [];
|
|
6938
|
+
let middlewareProtectsApi = false;
|
|
6939
|
+
for (const filePath of manifest.files["secret-scanner"] || []) {
|
|
6940
|
+
const normalized = filePath.replace(/\\/g, "/");
|
|
6941
|
+
if (/(?:^|\/)(?:src\/)?middleware\.(?:ts|js|mjs)$/i.test(normalized)) {
|
|
6942
|
+
try {
|
|
6943
|
+
const mw = await fs.readFile(filePath, "utf8");
|
|
6944
|
+
const codeOnly = mw.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/.*$/gm, "");
|
|
6945
|
+
const enforcesAuth = /\b(?:withAuth|authMiddleware|clerkMiddleware|updateSession|getServerSession|getToken)\b/.test(codeOnly) || codeOnly.includes("auth.getUser") || codeOnly.includes("auth.getSession");
|
|
6946
|
+
const excludesAllApi = /\(\?\![^)]*\bapi\b/i.test(codeOnly) && !/['"]\/api\/:path\*['"]/i.test(codeOnly);
|
|
6947
|
+
if (enforcesAuth && !excludesAllApi) {
|
|
6948
|
+
middlewareProtectsApi = true;
|
|
6949
|
+
break;
|
|
6950
|
+
}
|
|
6951
|
+
} catch {
|
|
6952
|
+
}
|
|
6953
|
+
}
|
|
6954
|
+
}
|
|
6673
6955
|
for (const [moduleId, files] of Object.entries(manifest.files)) {
|
|
6674
6956
|
const analyzer = this.analyzers[moduleId];
|
|
6675
6957
|
if (!analyzer) continue;
|
|
6676
6958
|
for (const filePath of files) {
|
|
6677
6959
|
try {
|
|
6678
6960
|
const content = await fs.readFile(filePath, "utf8");
|
|
6679
|
-
const findings = await analyzer.analyze(filePath, content);
|
|
6961
|
+
const findings = moduleId === "route-auth-analyzer" ? await analyzer.analyze(filePath, content, { middlewareProtectsApi }) : await analyzer.analyze(filePath, content);
|
|
6680
6962
|
allFindings.push(...findings);
|
|
6681
6963
|
} catch (err) {
|
|
6682
6964
|
console.error(`Error analyzing ${filePath}:`, err);
|
|
@@ -6845,7 +7127,7 @@ var CertificateGenerator = class {
|
|
|
6845
7127
|
};
|
|
6846
7128
|
|
|
6847
7129
|
// src/local-cli.ts
|
|
6848
|
-
var CLI_VERSION = "1.
|
|
7130
|
+
var CLI_VERSION = "1.2.0";
|
|
6849
7131
|
function parseCliArgs(args) {
|
|
6850
7132
|
const options = {
|
|
6851
7133
|
targetDir: process.cwd(),
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@clearrecord/check",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "1.2.0",
|
|
4
|
+
"description": "Local Air-Gapped Code Security, Route Auth, SQL RLS, Billing & Index Scanner",
|
|
5
5
|
"main": "bin/check.js",
|
|
6
6
|
"bin": {
|
|
7
7
|
"clearrecord": "bin/check.js",
|