lilith-skill 0.0.0-stage โ†’ 0.1.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.
Files changed (40) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +132 -2
  3. package/THIRD_PARTY_NOTICES.md +79 -0
  4. package/bin/lilith.mjs +147 -0
  5. package/package.json +43 -4
  6. package/skills/lilith/SKILL.md +61 -0
  7. package/skills/lilith/agents/openai.yaml +4 -0
  8. package/skills/lilith/checks/firebase_check.md +45 -0
  9. package/skills/lilith/checks/supabase_check.sql +211 -0
  10. package/skills/lilith/guides/cleanup-code.md +56 -0
  11. package/skills/lilith/guides/cleanup-ui.md +54 -0
  12. package/skills/lilith/guides/fixes/S1.md +6 -0
  13. package/skills/lilith/guides/fixes/S10.md +3 -0
  14. package/skills/lilith/guides/fixes/S11.md +3 -0
  15. package/skills/lilith/guides/fixes/S12.md +3 -0
  16. package/skills/lilith/guides/fixes/S13.md +3 -0
  17. package/skills/lilith/guides/fixes/S14.md +9 -0
  18. package/skills/lilith/guides/fixes/S2.md +15 -0
  19. package/skills/lilith/guides/fixes/S3.md +25 -0
  20. package/skills/lilith/guides/fixes/S4.md +11 -0
  21. package/skills/lilith/guides/fixes/S5.md +3 -0
  22. package/skills/lilith/guides/fixes/S6.md +7 -0
  23. package/skills/lilith/guides/fixes/S7.md +16 -0
  24. package/skills/lilith/guides/fixes/S8.md +11 -0
  25. package/skills/lilith/guides/fixes/S9.md +3 -0
  26. package/skills/lilith/guides/fixing.md +9 -0
  27. package/skills/lilith/guides/security-core.md +66 -0
  28. package/skills/lilith/guides/server.md +73 -0
  29. package/skills/lilith/guides/stacks/ai.md +14 -0
  30. package/skills/lilith/guides/stacks/firebase.md +13 -0
  31. package/skills/lilith/guides/stacks/stripe.md +13 -0
  32. package/skills/lilith/guides/stacks/supabase.md +31 -0
  33. package/skills/lilith/guides/ui/charts.md +10 -0
  34. package/skills/lilith/guides/ui/examples.md +30 -0
  35. package/skills/lilith/guides/ui/surface.md +11 -0
  36. package/skills/lilith/scripts/count_tells.py +384 -0
  37. package/skills/lilith/scripts/lilith_scan.py +750 -0
  38. package/skills/lilith/templates/report.md +64 -0
  39. package/src/agents.mjs +54 -0
  40. package/src/install.mjs +71 -0
@@ -0,0 +1,750 @@
1
+ #!/usr/bin/env python3
2
+ """Lilith quick scan: find leads for security and cleanup checks.
3
+
4
+ Usage:
5
+ python3 lilith_scan.py [project-root] [--brief | --full] [--json] [--plan-limit N]
6
+
7
+ Prints the project size, one line per security lead, cleanup as grouped
8
+ counts, and a READ PLAN: the files to read to confirm or rule out each check,
9
+ most suspicious first. Every hit is a LEAD for the agent to confirm by
10
+ reading the code, not a confirmed finding. --full lists every lead.
11
+ Secrets are always masked. Python 3.8+, standard library only.
12
+ """
13
+ import argparse
14
+ import base64
15
+ import json
16
+ import os
17
+ import re
18
+ import subprocess
19
+ import sys
20
+
21
+ SKIP_DIRS = {
22
+ "node_modules", ".git", "dist", "build", ".next", ".nuxt", ".svelte-kit", ".astro",
23
+ ".output", ".vercel", ".netlify", "coverage", ".venv", "venv", "__pycache__", ".turbo",
24
+ ".expo", "ios", "android", ".cache", "out", "vendor", ".idea", ".vscode",
25
+ ".claude", ".cursor", ".agents", ".codex", ".windsurf", # agent configs and installed skills
26
+ }
27
+ SELF_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # this skill's folder
28
+ SKIP_FILES = {"package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb", "poetry.lock", "Cargo.lock"}
29
+ CODE_EXT = {".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".vue", ".svelte", ".astro", ".py", ".rb", ".go", ".php", ".html"}
30
+ TEXT_EXT = CODE_EXT | {".json", ".yml", ".yaml", ".toml", ".sql", ".rules", ".md", ".env", ".txt", ".sh", ".tf", ".ini", ".cfg"}
31
+ MAX_BYTES = 1_000_000
32
+ BIG_FILE_LINES = 400
33
+ LONG_FILE_LINES = 300 # read plan gives line ranges for files longer than this
34
+ PLAN_LIMIT = 25
35
+ SIZE_CLASSES = [("small", 60, 8_000), ("medium", 400, 60_000)] # (name, max files, max lines); else large
36
+ RULE_FILES = ("firestore.rules", "storage.rules", "database.rules.json")
37
+ LEAD_WEIGHT = {"critical": 8, "high": 4, "medium": 2, "info": 0.5, "cleanup": 0}
38
+
39
+ SEVERITY_ORDER = {"critical": 0, "high": 1, "medium": 2, "cleanup": 3, "info": 4}
40
+
41
+ CHECK_TITLES = {
42
+ "S1": "Secret keys in code or git",
43
+ "S2": "Secret keys sent to the browser",
44
+ "S3": "Database rules may be open",
45
+ "S4": "API routes to check for login",
46
+ "S5": "Records loaded without an owner check",
47
+ "S6": "Server trusts what the browser sends",
48
+ "S7": "Webhook without signature check",
49
+ "S8": "Endpoints to check for rate limits",
50
+ "S9": "Unsafe HTML / code execution",
51
+ "S10": "Storage / upload to check",
52
+ "S12": "Debug / test doors",
53
+ "S13": "Packages",
54
+ "S14": "CORS / headers",
55
+ "C1": "Leftover logs and debugger",
56
+ "C2": "Fake / placeholder data",
57
+ "C3": "TODOs and empty handlers",
58
+ "C6": "Giant files",
59
+ "C8": "Template leftovers",
60
+ }
61
+
62
+ # ---------------------------------------------------------------- secrets (S1)
63
+
64
+ SECRET_PATTERNS = [
65
+ ("Stripe live secret key", r"\b(?:sk|rk)_live_[0-9A-Za-z]{16,}", "critical"),
66
+ ("Stripe test secret key", r"\b(?:sk|rk)_test_[0-9A-Za-z]{16,}", "medium"),
67
+ ("Stripe webhook secret", r"\bwhsec_[0-9A-Za-z]{20,}", "critical"),
68
+ ("OpenAI key", r"\bsk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_\-]{32,}", "critical"),
69
+ ("Anthropic key", r"\bsk-ant-[A-Za-z0-9_\-]{32,}", "critical"),
70
+ ("AWS access key", r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b", "critical"),
71
+ ("GitHub token", r"\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36,}|\bgithub_pat_[A-Za-z0-9_]{50,}", "critical"),
72
+ ("Slack token", r"\bxox[abprs]-[A-Za-z0-9-]{10,}", "critical"),
73
+ ("Google API key", r"\bAIza[0-9A-Za-z_\-]{35}", "info"),
74
+ ("Private key", r"-----BEGIN (?:RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY-----\s*[A-Za-z0-9+/=\\n]{40,}", "critical"),
75
+ ("Database URL with password", r"\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|rediss)://[^\s:/@'\"`]+:[^\s@'\"`]{3,}@[^\s'\"`]+", "critical"),
76
+ ("SendGrid key", r"\bSG\.[A-Za-z0-9_\-]{20,}\.[A-Za-z0-9_\-]{20,}", "critical"),
77
+ ("Resend key", r"\bre_[A-Za-z0-9]{8,}_[A-Za-z0-9]{16,}", "critical"),
78
+ ("Twilio key", r"\bSK[0-9a-fA-F]{32}\b", "high"),
79
+ ("Groq key", r"\bgsk_[A-Za-z0-9]{40,}", "critical"),
80
+ ("Hugging Face token", r"\bhf_[A-Za-z0-9]{30,}", "high"),
81
+ ("Replicate token", r"\br8_[A-Za-z0-9]{30,}", "critical"),
82
+ ]
83
+ SECRET_RX = [(name, re.compile(rx), sev) for name, rx, sev in SECRET_PATTERNS]
84
+ JWT_RX = re.compile(r"\beyJ[A-Za-z0-9_\-]{10,}\.eyJ[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}")
85
+ PLACEHOLDER_RX = re.compile(r"(?i)(x{6,}|your[_\-]?(?:api[_\-]?)?key|example|placeholder|dummy|<[^>]+>|\*{4,}|\.\.\.|changeme|replace[_\-]?me)")
86
+
87
+ PUBLIC_PREFIX_RX = re.compile(
88
+ r"\b(NEXT_PUBLIC_|VITE_|REACT_APP_|EXPO_PUBLIC_|PUBLIC_|NUXT_PUBLIC_|GATSBY_)"
89
+ r"([A-Z0-9_]*(?:SECRET|SERVICE_ROLE|SERVICE_KEY|PRIVATE|OPENAI|ANTHROPIC|GROQ|GEMINI_API|STRIPE_SECRET|STRIPE_SK|"
90
+ r"RESEND|SENDGRID|TWILIO_AUTH|DATABASE_URL|DB_PASS|ADMIN_KEY|WEBHOOK_SECRET|REPLICATE)[A-Z0-9_]*)\b"
91
+ )
92
+
93
+
94
+ def mask(value):
95
+ value = value.strip()
96
+ if len(value) <= 12:
97
+ return value[:3] + "โ€ขโ€ขโ€ขโ€ข"
98
+ return value[:8] + "โ€ขโ€ขโ€ขโ€ข" + value[-4:]
99
+
100
+
101
+ def jwt_role(token):
102
+ try:
103
+ payload = token.split(".")[1]
104
+ payload += "=" * (-len(payload) % 4)
105
+ data = json.loads(base64.urlsafe_b64decode(payload))
106
+ return data.get("role")
107
+ except Exception:
108
+ return None
109
+
110
+
111
+ # ------------------------------------------------------------- code patterns
112
+
113
+ CLIENT_SECRET_USE = [
114
+ (re.compile(r"new\s+OpenAI\s*\("), "OpenAI client"),
115
+ (re.compile(r"new\s+Anthropic\s*\("), "Anthropic client"),
116
+ (re.compile(r"api\.openai\.com|api\.anthropic\.com|api\.groq\.com"), "direct AI API call"),
117
+ (re.compile(r"dangerouslyAllowBrowser\s*:\s*true"), "dangerouslyAllowBrowser"),
118
+ (re.compile(r"(?i)service[_\-]?role"), "Supabase service_role"),
119
+ (re.compile(r"new\s+Stripe\s*\("), "Stripe secret client"),
120
+ ]
121
+
122
+ DANGEROUS_SINKS = [
123
+ (re.compile(r"dangerouslySetInnerHTML"), "dangerouslySetInnerHTML"),
124
+ (re.compile(r"\bv-html\b"), "v-html"),
125
+ (re.compile(r"\{@html\b"), "{@html}"),
126
+ (re.compile(r"\.innerHTML\s*=(?!=)"), ".innerHTML ="),
127
+ (re.compile(r"document\.write\s*\("), "document.write"),
128
+ (re.compile(r"(?<![\w.])eval\s*\("), "eval("),
129
+ (re.compile(r"new\s+Function\s*\("), "new Function("),
130
+ (re.compile(r"child_process|\bexecSync\s*\(|\bexec\s*\(\s*[`'\"].*\$\{"), "shell exec"),
131
+ (re.compile(r"\$queryRawUnsafe|\$executeRawUnsafe|\.raw\s*\(\s*`[^`]*\$\{|sql\.unsafe\s*\("), "raw SQL with interpolation"),
132
+ ]
133
+
134
+ CORS_RX = [
135
+ (re.compile(r"Access-Control-Allow-Origin['\"]?\s*[:,]\s*['\"]\*"), "Allow-Origin: *"),
136
+ (re.compile(r"key\s*:\s*['\"]Access-Control-Allow-Origin['\"]\s*,\s*value\s*:\s*['\"]\*"), "Allow-Origin: *"),
137
+ (re.compile(r"Access-Control-Allow-Origin['\"]\s*,\s*(?:origin\b|(?:req|request)\.headers)"), "Allow-Origin reflects the request origin"),
138
+ (re.compile(r"origin\s*:\s*(?:true|['\"]\*['\"])"), "cors origin any"),
139
+ ]
140
+ CREDENTIALS_RX = re.compile(r"credentials\s*:\s*true|Allow-Credentials['\"]?\s*[:,]\s*['\"]?true")
141
+
142
+ LOG_RX = re.compile(r"(?<![\w.])console\.(?:log|debug|trace|table)\s*\(|^\s*debugger\s*;?\s*$", re.M)
143
+ TODO_RX = re.compile(r"\b(?:TODO|FIXME|HACK|XXX)\b")
144
+ EMPTY_HANDLER_RX = re.compile(r"on[A-Z]\w*=\{\s*\(\s*\)\s*=>\s*\{\s*\}\s*\}|href=['\"]#['\"]")
145
+ FAKE_DATA_RX = re.compile(
146
+ r"(?i)\b(?:lorem ipsum|mock(?:Data|Users|Products|Orders)?\b|fake(?:Data|Users)\b|dummy(?:Data)?\b|sample(?:Data|Users|Products)\b|"
147
+ r"John Doe|Jane (?:Doe|Smith)|Acme(?: Inc| Corp)?)\b|placehold\.co|via\.placeholder\.com|picsum\.photos|test@example\.com"
148
+ )
149
+ TEMPLATE_RX = re.compile(r"(?i)Welcome to your Lovable project|Get started by editing|Vite \+ React|Create Next App|bolt\.new|This project was bootstrapped")
150
+ DEBUG_ROUTE_RX = re.compile(r"(?i)(?:^|/)(?:debug|seed|test|testing|dev|_dev|admin-?test)(?:/|$|\.)")
151
+ TEST_CRED_RX = re.compile(r"(?i)['\"](?:admin@admin\.com|admin@example\.com|test@test\.com)['\"]|password\s*[:=]\s*['\"](?:password|password123|admin|123456|admin123|test123)['\"]")
152
+
153
+ TEST_FILE_RX = re.compile(r"(?i)(?:^|/)(?:tests?|__tests__|spec|specs|e2e|cypress|playwright)/|\.(?:test|spec)\.[jt]sx?$")
154
+ AUTH_ENDPOINT_RX = re.compile(r"(?i)sign-?up|sign-?in|log-?in|register|reset-?password|forgot-?password|otp|magic-?link")
155
+ AUTH_ROUTE_STRING_RX = re.compile(r"(?i)\.(?:post|put)\s*\(\s*['\"`][^'\"`]*(?:sign-?up|sign-?in|log-?in|register|reset|forgot|otp|magic-?link)")
156
+ FALLBACK_SECRET_RX = re.compile(r"process\.env\.[A-Z0-9_]*(?:SECRET|PRIVATE|PASSWORD|TOKEN|API_KEY)[A-Z0-9_]*\s*(?:\|\||\?\?)\s*['\"`][^'\"`]{6,}['\"`]")
157
+ JWT_DECODE_RX = re.compile(r"\bjwt\.decode\s*\(|\bjwtDecode\s*\(")
158
+ JWT_VERIFY_RX = re.compile(r"\bjwt\.verify\s*\(|\bjwtVerify\s*\(|\bverifyJwt\s*\(")
159
+ STACK_LEAK_RX = re.compile(r"\bstack\s*:\s*(?:err|error|e)\.stack\b")
160
+ MASS_ASSIGN_RX = re.compile(r"\bdata\s*:\s*req\.body\b|\.(?:update|insert|upsert)\s*\(\s*(?:req\.body|body|await\s+req\.json\(\))\s*\)")
161
+ CLIENT_PRICE_RX = re.compile(r"\bunit_amount\s*:\s*(?:body\.|req\.body\.)?[a-z_]\w*\s*[,}\n]")
162
+ ID_FROM_REQUEST_RX = re.compile(
163
+ r"where\s*:\s*\{\s*id\s*:\s*(?:req\.params|req\.query|req\.body|params)\.\w+\s*\}|"
164
+ r"\.eq\(\s*['\"]id['\"]\s*,\s*(?:params|req\.params|searchParams)\b"
165
+ )
166
+ OWNER_FILTER_RX = re.compile(r"(?i)\b(?:user_?id|owner_?id|author_?id|created_by)\b\s*[:,]|\.eq\(\s*['\"](?:user_id|owner_id|author_id|created_by)")
167
+ ADMIN_CLIENT_RX = re.compile(r"(?i)supabaseAdmin|service_?role|adminClient")
168
+ UPLOAD_RISK_RX = re.compile(r"multer\s*\(\s*\)|multer\s*\(\s*\{\s*(?:storage|dest)\s*(?::\s*[^,}]+)?\s*\}\s*\)|cb\s*\(\s*null\s*,\s*file\.originalname\s*\)")
169
+
170
+ AUTH_HINT_RX = re.compile(
171
+ r"getUser\(|getServerSession|auth\(\)|currentUser\(|getAuth\(|verifyIdToken|requireAuth|requireUser|withAuth|"
172
+ r"clerkClient|getToken\(|session\?\.user|jwt\.verify|verifyJwt|getKindeServerSession|validateRequest|lucia|"
173
+ r"Authorization|authenticate|isAuthenticated|protectedProcedure|auth\.api\.getSession|"
174
+ r"\b(?:get|require|ensure|check|verify)(?:Current|Logged[Ii]n)?(?:User|Admin|Session|Auth)\w*\s*\("
175
+ )
176
+ RATELIMIT_HINT_RX = re.compile(r"(?i)ratelimit|rate-limit|rate_limit|limiter|slowDown|throttle")
177
+ WEBHOOK_VERIFY_RX = re.compile(r"constructEvent|constructEventAsync|svix|Webhook\(|verifySignature|createHmac|timingSafeEqual|verifyWebhook|validateEvent|x-signature|signature", re.I)
178
+ AI_USE_RX = re.compile(r"openai|anthropic|generateText|streamText|chat\.completions|messages\.create|groq|gemini|replicate", re.I)
179
+ EMAIL_USE_RX = re.compile(r"resend|sendgrid|nodemailer|postmark|mailgun|twilio", re.I)
180
+
181
+
182
+ # ------------------------------------------------------------------ helpers
183
+
184
+ def git_tracked(root):
185
+ try:
186
+ out = subprocess.run(["git", "-C", root, "ls-files"], capture_output=True, text=True, timeout=20)
187
+ if out.returncode == 0:
188
+ return set(out.stdout.splitlines())
189
+ except Exception:
190
+ pass
191
+ return None
192
+
193
+
194
+ def git_history_env(root):
195
+ try:
196
+ out = subprocess.run(
197
+ ["git", "-C", root, "log", "--all", "--diff-filter=A", "--name-only", "--pretty=format:"],
198
+ capture_output=True, text=True, timeout=30,
199
+ )
200
+ if out.returncode == 0:
201
+ return sorted({p for p in out.stdout.splitlines() if is_env_file(os.path.basename(p))})
202
+ except Exception:
203
+ pass
204
+ return []
205
+
206
+
207
+ def is_env_file(name):
208
+ n = name.lower()
209
+ if not (n == ".env" or n.startswith(".env.") or n.endswith(".env")):
210
+ return False
211
+ return not any(x in n for x in ("example", "sample", "template", "defaults"))
212
+
213
+
214
+ def iter_files(root):
215
+ for dirpath, dirnames, filenames in os.walk(root):
216
+ dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS and not d.startswith(".git")
217
+ and os.path.abspath(os.path.join(dirpath, d)) != SELF_DIR]
218
+ for f in filenames:
219
+ if f in SKIP_FILES:
220
+ continue
221
+ path = os.path.join(dirpath, f)
222
+ ext = os.path.splitext(f)[1].lower()
223
+ if ext not in TEXT_EXT and not is_env_file(f) and f not in ("Dockerfile", ".gitignore"):
224
+ continue
225
+ try:
226
+ if os.path.getsize(path) > MAX_BYTES:
227
+ continue
228
+ except OSError:
229
+ continue
230
+ yield path
231
+
232
+
233
+ def read(path):
234
+ try:
235
+ with open(path, encoding="utf-8", errors="replace") as fh:
236
+ return fh.read()
237
+ except OSError:
238
+ return None
239
+
240
+
241
+ def line_of(text, pos):
242
+ return text.count("\n", 0, pos) + 1
243
+
244
+
245
+ def is_minified(text):
246
+ lines = text.splitlines() or [""]
247
+ return len(text) > 5000 and len(lines) < 10
248
+
249
+
250
+ def is_client_file(rel, text, project):
251
+ if '"use client"' in text[:300] or "'use client'" in text[:300]:
252
+ return True
253
+ if '"use server"' in text[:300] or "'use server'" in text[:300]:
254
+ return False
255
+ low = rel.replace("\\", "/").lower()
256
+ server_markers = ("/api/", "pages/api", "app/api", "/server/", "supabase/functions", "netlify/functions",
257
+ "/functions/", "route.ts", "route.js", "+server.", "+page.server", ".server.", "middleware.",
258
+ "server.ts", "server.js", "/trpc/", "/actions/", "convex/")
259
+ if any(m in low for m in server_markers):
260
+ return False
261
+ if project["spa"] and low.startswith(("src/", "app/", "components/")) and low.endswith((".tsx", ".jsx", ".ts", ".js", ".vue", ".svelte")):
262
+ return True
263
+ if low.endswith((".tsx", ".jsx")) and ("components/" in low or "/pages/" in low and "pages/api" not in low):
264
+ return True
265
+ return False
266
+
267
+
268
+ def detect_project(root):
269
+ info = {"stack": [], "spa": False}
270
+ pkg = read(os.path.join(root, "package.json"))
271
+ deps = {}
272
+ if pkg:
273
+ try:
274
+ data = json.loads(pkg)
275
+ deps = {**data.get("dependencies", {}), **data.get("devDependencies", {})}
276
+ except Exception:
277
+ pass
278
+ names = set(deps)
279
+ def has(*xs):
280
+ return any(x in names for x in xs)
281
+ if has("next"): info["stack"].append("Next.js")
282
+ if has("vite") and not has("next", "@sveltejs/kit", "astro", "@remix-run/react"):
283
+ info["stack"].append("Vite"); info["spa"] = True
284
+ if has("react-scripts"): info["stack"].append("Create React App"); info["spa"] = True
285
+ if has("@sveltejs/kit"): info["stack"].append("SvelteKit")
286
+ if has("nuxt"): info["stack"].append("Nuxt")
287
+ if has("astro"): info["stack"].append("Astro")
288
+ if has("expo", "react-native"): info["stack"].append("Expo/React Native"); info["spa"] = True
289
+ if has("express", "fastify", "hono", "koa"): info["stack"].append("Node server")
290
+ if has("@supabase/supabase-js", "@supabase/ssr") or os.path.isdir(os.path.join(root, "supabase")): info["stack"].append("Supabase")
291
+ if has("firebase", "firebase-admin") or os.path.exists(os.path.join(root, "firebase.json")): info["stack"].append("Firebase")
292
+ if has("convex"): info["stack"].append("Convex")
293
+ if has("@prisma/client", "prisma"): info["stack"].append("Prisma")
294
+ if has("drizzle-orm"): info["stack"].append("Drizzle")
295
+ if has("stripe", "@stripe/stripe-js"): info["stack"].append("Stripe")
296
+ if has("openai", "@anthropic-ai/sdk", "ai", "@ai-sdk/openai", "groq-sdk", "@google/generative-ai"): info["stack"].append("AI API")
297
+ if has("@clerk/nextjs", "@clerk/clerk-react"): info["stack"].append("Clerk")
298
+ if has("recharts", "chart.js", "react-chartjs-2", "@nivo/core", "victory", "d3", "apexcharts", "react-apexcharts",
299
+ "echarts", "echarts-for-react", "@tremor/react", "highcharts", "@visx/visx", "lightweight-charts", "plotly.js"):
300
+ info["stack"].append("Charts")
301
+ if has("@lemonsqueezy/lemonsqueezy.js", "@paddle/paddle-js", "@paddle/paddle-node-sdk"): info["stack"].append("Payments")
302
+ if has("next-auth", "@auth/core", "better-auth", "lucia"): info["stack"].append("Auth library")
303
+ if os.path.exists(os.path.join(root, "vercel.json")): info["stack"].append("Vercel")
304
+ if os.path.exists(os.path.join(root, "netlify.toml")): info["stack"].append("Netlify")
305
+ if os.path.exists(os.path.join(root, "Dockerfile")) or os.path.exists(os.path.join(root, "docker-compose.yml")): info["stack"].append("Docker")
306
+ for py in ("requirements.txt", "pyproject.toml"):
307
+ if os.path.exists(os.path.join(root, py)): info["stack"].append("Python")
308
+ info["has_lockfile"] = any(os.path.exists(os.path.join(root, f)) for f in ("package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb", "bun.lock"))
309
+ info["has_package_json"] = bool(pkg)
310
+ return info
311
+
312
+
313
+ def is_server_route(rel, text):
314
+ low = rel.replace("\\", "/").lower()
315
+ if re.search(r"(^|/)(app|src/app)/.*api/.*route\.(t|j)sx?$", low): return True
316
+ if re.search(r"(^|/)pages/api/", low): return True
317
+ if "supabase/functions/" in low and low.endswith(("index.ts", "index.js")): return True
318
+ if "netlify/functions/" in low or re.search(r"(^|/)api/[^/]+\.(t|j)s$", low): return True
319
+ if re.search(r"\+server\.(t|j)s$", low): return True
320
+ if ('"use server"' in text[:300] or "'use server'" in text[:300]): return True
321
+ if re.search(r"\b(?:app|router)\.(?:get|post|put|patch|delete)\s*\(", text): return True
322
+ return False
323
+
324
+
325
+ def scan_server_code(rel, text, add):
326
+ """Leads that only make sense in server code: tokens, ownership, trusted input, uploads, errors."""
327
+ if JWT_DECODE_RX.search(text) and not JWT_VERIFY_RX.search(text):
328
+ m = JWT_DECODE_RX.search(text)
329
+ add("S4", "critical", rel, line_of(text, m.start()), "token is decoded but never verified: anyone can make their own token")
330
+ for m in ID_FROM_REQUEST_RX.finditer(text):
331
+ if OWNER_FILTER_RX.search(text[m.start():m.start() + 300]):
332
+ continue
333
+ if m.group(0).startswith(".eq") and not ADMIN_CLIENT_RX.search(text):
334
+ continue # user's own Supabase client: RLS decides, see S3
335
+ add("S5", "high", rel, line_of(text, m.start()), "record loaded by an id from the request with no owner filter: check users can't open each other's data")
336
+ for m in MASS_ASSIGN_RX.finditer(text):
337
+ add("S6", "high", rel, line_of(text, m.start()), "whole request body written to the database: users can set fields like role or plan")
338
+ if re.search(r"req\.json\(\)|req\.body", text):
339
+ for m in CLIENT_PRICE_RX.finditer(text):
340
+ add("S6", "high", rel, line_of(text, m.start()), "payment amount may come from the request: look prices up on the server")
341
+ for m in UPLOAD_RISK_RX.finditer(text):
342
+ add("S10", "medium", rel, line_of(text, m.start()), "upload with no size/type limit or with the user's file name")
343
+ break
344
+ for m in STACK_LEAK_RX.finditer(text):
345
+ add("S12", "medium", rel, line_of(text, m.start()), "stack trace sent in the response: return a generic error, log details on the server")
346
+
347
+
348
+ def plan_hints(rel, name, ext, text, is_code, client):
349
+ """Checks a file is worth reading for, even when no regex fired."""
350
+ low = rel.replace("\\", "/").lower()
351
+ checks = set()
352
+ if ext in (".sql", ".rules") or name in RULE_FILES:
353
+ checks.add("S3")
354
+ if not is_code or TEST_FILE_RX.search(low):
355
+ return checks
356
+ if is_server_route(rel, text):
357
+ checks.update(("S4", "S5", "S6"))
358
+ if "webhook" in low or "webhook" in text[:2000].lower():
359
+ checks.add("S7")
360
+ if AI_USE_RX.search(text) or EMAIL_USE_RX.search(text) or AUTH_ENDPOINT_RX.search(low):
361
+ checks.add("S8")
362
+ if DEBUG_ROUTE_RX.search(low):
363
+ checks.add("S12")
364
+ if client and (AI_USE_RX.search(text) or "process.env" in text or "import.meta.env" in text):
365
+ checks.add("S2")
366
+ if client and re.search(r"(?i)useSearchParams|searchParams|[?&]success", text) and re.search(r"(?i)\.update\(|\bplan\b|premium|isPro", text):
367
+ checks.add("S7")
368
+ if any(rx.search(text) for rx, _label in DANGEROUS_SINKS):
369
+ checks.add("S9")
370
+ if re.search(r"(?i)multer|formidable|busboy|storage\.from\(|createBucket|\.upload\(", text):
371
+ checks.add("S10")
372
+ if re.search(r"(?i)system_?prompt|role\s*:\s*['\"]system['\"]|\btools\s*:\s*\[", text):
373
+ checks.add("S11")
374
+ if re.search(r"Access-Control-Allow|\bcors\s*\(", text) or name.startswith(("middleware.", "next.config")):
375
+ checks.add("S14")
376
+ return checks
377
+
378
+
379
+ def size_class(files, lines):
380
+ for name, max_files, max_lines in SIZE_CLASSES:
381
+ if files <= max_files and lines <= max_lines:
382
+ return name
383
+ return "large"
384
+
385
+
386
+ def read_plan(findings, hints, file_lines, limit=PLAN_LIMIT):
387
+ """Files to read, most suspicious first: (entries, number left out)."""
388
+ score, checks, lines = {}, {}, {}
389
+ for f in findings:
390
+ if not f["check"].startswith("S"):
391
+ continue
392
+ rel = f["file"]
393
+ score[rel] = score.get(rel, 0) + LEAD_WEIGHT[f["severity"]]
394
+ checks.setdefault(rel, set()).add(f["check"])
395
+ if f["line"]:
396
+ lines.setdefault(rel, []).append(f["line"])
397
+ for rel, cs in hints.items():
398
+ score[rel] = score.get(rel, 0) + len(cs)
399
+ checks.setdefault(rel, set()).update(cs)
400
+ order = sorted(score, key=lambda r: (-score[r], r))
401
+ entries = []
402
+ for rel in order[:limit]:
403
+ n = file_lines.get(rel, 0)
404
+ span = None
405
+ if n > LONG_FILE_LINES and rel in lines:
406
+ span = [max(1, min(lines[rel]) - 10), min(n, max(lines[rel]) + 30)]
407
+ entries.append({"file": rel, "checks": sorted(checks[rel], key=lambda c: int(c[1:])), "lines": span, "file_lines": n})
408
+ return entries, max(0, len(order) - limit)
409
+
410
+
411
+ # --------------------------------------------------------------------- scan
412
+
413
+ def scan(root, max_examples):
414
+ root = os.path.abspath(root)
415
+ project = detect_project(root)
416
+ tracked = git_tracked(root)
417
+ findings = []
418
+
419
+ def add(check, severity, rel, line, note):
420
+ findings.append({"check": check, "severity": severity, "file": rel, "line": line, "note": note})
421
+
422
+ # env files and gitignore
423
+ gitignore = read(os.path.join(root, ".gitignore")) or ""
424
+ has_env_files = any(is_env_file(f) for f in os.listdir(root))
425
+ if (project["has_package_json"] or has_env_files) and not re.search(r"^\s*\.env", gitignore, re.M) and not re.search(r"^\s*\*\.env|^\s*\.env\*", gitignore, re.M):
426
+ add("S1", "medium", ".gitignore", 0, ".env is not in .gitignore")
427
+ if tracked is not None:
428
+ for p in sorted(tracked):
429
+ if is_env_file(os.path.basename(p)):
430
+ add("S1", "critical", p, 0, "env file is committed to git (keys inside are exposed to anyone with the repo)")
431
+ tracked_set = set(tracked)
432
+ for p in git_history_env(root):
433
+ if p not in tracked_set:
434
+ add("S1", "high", p, 0, "env file was committed in git history (deleted now, keys still in history: rotate them)")
435
+ if project["has_package_json"] and not project["has_lockfile"]:
436
+ add("S13", "info", "package.json", 0, "no lockfile: installs are not reproducible")
437
+
438
+ big_files = []
439
+ totals = {"C1": 0, "C3": 0}
440
+ hints, file_lines = {}, {}
441
+ n_files = n_lines_total = 0
442
+
443
+ for path in iter_files(root):
444
+ rel = os.path.relpath(path, root)
445
+ name = os.path.basename(path)
446
+ ext = os.path.splitext(name)[1].lower()
447
+ text = read(path)
448
+ if text is None or is_minified(text):
449
+ continue
450
+ is_env = is_env_file(name)
451
+ is_example_env = name.lower().startswith(".env") and not is_env
452
+ is_code = ext in CODE_EXT
453
+ is_doc = ext in (".md", ".txt")
454
+ client = is_code and is_client_file(rel, text, project)
455
+ file_lines[rel.replace(os.sep, "/")] = text.count("\n") + 1
456
+ if is_code or ext in (".sql", ".rules") or name in RULE_FILES:
457
+ n_files += 1
458
+ n_lines_total += file_lines[rel.replace(os.sep, "/")]
459
+ file_hints = plan_hints(rel, name, ext, text, is_code, client)
460
+ if file_hints:
461
+ hints[rel.replace(os.sep, "/")] = file_hints
462
+
463
+ # S1 secrets
464
+ if not is_example_env:
465
+ for label, rx, sev in SECRET_RX:
466
+ for m in rx.finditer(text):
467
+ val = m.group(0)
468
+ if PLACEHOLDER_RX.search(val):
469
+ continue
470
+ s = sev
471
+ if is_doc and s == "critical":
472
+ s = "high"
473
+ if is_env and tracked is not None and rel.replace(os.sep, "/") not in tracked:
474
+ continue # local untracked .env is the right place for secrets
475
+ if is_env and tracked is None:
476
+ s = "info" # no git: a local .env is fine as long as it is never shared
477
+ note = f"{label}: {mask(val)}"
478
+ if label == "Google API key":
479
+ note += " (often a public Firebase/Maps key: check it is restricted in Google Cloud)"
480
+ add("S1", s, rel, line_of(text, m.start()), note)
481
+ for m in JWT_RX.finditer(text):
482
+ if jwt_role(m.group(0)) == "service_role":
483
+ if is_env and tracked is not None and rel.replace(os.sep, "/") not in tracked:
484
+ continue
485
+ add("S1", "info" if is_env and tracked is None else "critical", rel, line_of(text, m.start()), f"Supabase service_role key hard-coded: {mask(m.group(0))}")
486
+
487
+ if is_code:
488
+ for m in FALLBACK_SECRET_RX.finditer(text):
489
+ add("S1", "high", rel, line_of(text, m.start()), "secret has a hard-coded fallback value: if the env var is missing, this public value is used")
490
+
491
+ # S2 public-prefixed secret env names
492
+ for m in PUBLIC_PREFIX_RX.finditer(text):
493
+ var = m.group(0)
494
+ if "PUBLISHABLE" in var or "ANON" in var:
495
+ continue
496
+ add("S2", "info" if is_doc else "critical", rel, line_of(text, m.start()), f"{var} is bundled into browser code (public prefix on a secret)")
497
+
498
+ # S2 secret clients in browser code
499
+ if client:
500
+ for rx, label in CLIENT_SECRET_USE:
501
+ for m in rx.finditer(text):
502
+ add("S2", "critical" if label != "Stripe secret client" or "sk_" in text else "high",
503
+ rel, line_of(text, m.start()), f"{label} in browser code")
504
+ break
505
+
506
+ # S3 database rules
507
+ low = rel.replace("\\", "/").lower()
508
+ if ext == ".sql":
509
+ for m in re.finditer(r"(?is)create\s+table\s+(?:if\s+not\s+exists\s+)?(?:public\.)?\"?(\w+)\"?", text):
510
+ table = m.group(1)
511
+ if not re.search(rf"(?is)alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?(?:public\.)?\"?{re.escape(table)}\"?\s+enable\s+row\s+level\s+security", text):
512
+ add("S3", "high", rel, line_of(text, m.start()), f"table '{table}' created without 'enable row level security' in this file (check other migrations)")
513
+ for m in re.finditer(r"(?is)create\s+policy\s+(.{0,120}?)\s+on\s+([\w.\"]+)(.{0,300}?);", text):
514
+ body = m.group(3).lower()
515
+ if re.search(r"for\s+insert", body) and re.search(r"with\s+check\s*\(\s*true\s*\)", body):
516
+ add("S3", "info", rel, line_of(text, m.start()), f"policy on {m.group(2)} lets anyone add rows (true): OK for a contact form, add a rate limit")
517
+ elif re.search(r"for\s+(update|delete|all)", body) and re.search(r"(using|with\s+check)\s*\(\s*true\s*\)", body):
518
+ add("S3", "critical", rel, line_of(text, m.start()), f"policy on {m.group(2)} allows writes for everyone (true)")
519
+ elif re.search(r"for\s+select", body) and re.search(r"to\s+authenticated", body) and re.search(r"using\s*\(\s*true\s*\)", body):
520
+ add("S3", "medium", rel, line_of(text, m.start()), f"policy on {m.group(2)} lets every logged-in user read every row: check this data is not private")
521
+ elif re.search(r"for\s+select", body) and re.search(r"using\s*\(\s*true\s*\)", body):
522
+ add("S3", "info", rel, line_of(text, m.start()), f"policy on {m.group(2)} lets everyone read: fine only for public data")
523
+ for m in re.finditer(r"(?i)disable\s+row\s+level\s+security", text):
524
+ add("S3", "critical", rel, line_of(text, m.start()), "row level security is disabled")
525
+ if name in ("firestore.rules", "storage.rules", "database.rules.json") or ext == ".rules":
526
+ for m in re.finditer(r"allow\s+[\w, ]+:\s*if\s+true|\"\.(?:read|write)\"\s*:\s*true|request\.time\s*<\s*timestamp", text):
527
+ add("S3", "critical", rel, line_of(text, m.start()), "Firebase rule open to everyone (or test mode)")
528
+
529
+ if not is_code:
530
+ if is_doc or ext in (".json",):
531
+ if TEMPLATE_RX.search(text) and name.lower().startswith("readme"):
532
+ add("C8", "info", rel, 1, "README still has template text")
533
+ continue
534
+
535
+ # Routes: auth, rate limit, webhooks
536
+ is_test = bool(TEST_FILE_RX.search(low))
537
+ if is_server_route(rel, text) and not is_test:
538
+ auth_endpoint = bool(AUTH_ENDPOINT_RX.search(low) or AUTH_ROUTE_STRING_RX.search(text))
539
+ writes = re.search(r"\.(?:insert|update|upsert|delete|create|createMany|updateMany|deleteMany)\s*\(|\bPOST\b|\bPUT\b|\bDELETE\b|\bPATCH\b", text)
540
+ if "webhook" in low or "webhook" in text[:2000].lower():
541
+ if not WEBHOOK_VERIFY_RX.search(text):
542
+ add("S7", "critical", rel, 1, "webhook handler with no signature verification found")
543
+ elif writes and not auth_endpoint and not AUTH_HINT_RX.search(text):
544
+ add("S4", "high", rel, 1, "server route/action changes data, no login check found in this file (check middleware)")
545
+ if (AI_USE_RX.search(text) or EMAIL_USE_RX.search(text) or auth_endpoint) and not RATELIMIT_HINT_RX.search(text):
546
+ add("S8", "medium", rel, 1, "AI / email / auth endpoint with no rate limit found in this file")
547
+ if DEBUG_ROUTE_RX.search(low) and (is_server_route(rel, text) or "/pages/" in low or "/app/" in low):
548
+ add("S12", "medium", rel, 1, "debug/seed/test route: delete or protect before launch")
549
+ for ln in sorted({line_of(text, m.start()) for m in TEST_CRED_RX.finditer(text)}):
550
+ add("S12", "info" if is_test else "medium", rel, ln,
551
+ "test credentials in a test file (fine if never used in production)" if is_test else "hard-coded test credentials")
552
+ if not is_test and not client:
553
+ scan_server_code(rel, text, add)
554
+
555
+ # S9 sinks
556
+ for rx, label in DANGEROUS_SINKS:
557
+ for m in rx.finditer(text):
558
+ if label == "dangerouslySetInnerHTML" and re.match(r"\s*=\s*\{\{\s*__html\s*:\s*JSON\.stringify\(", text[m.end():m.end() + 80]):
559
+ add("S9", "info", rel, line_of(text, m.start()), "dangerouslySetInnerHTML with JSON.stringify (JSON-LD): fine for your own data")
560
+ continue
561
+ if label == ".innerHTML =":
562
+ rhs = text[m.end():text.find("\n", m.end()) if "\n" in text[m.end():] else len(text)].strip()
563
+ if rhs[:1] in ("'", '"') or (rhs[:1] == "`" and "${" not in rhs) or rhs.startswith(("''", '""')):
564
+ continue
565
+ add("S9", "medium", rel, line_of(text, m.start()), f"{label}: check if user/AI text can reach it")
566
+
567
+ # S10 storage
568
+ for m in re.finditer(r"createBucket\([^)]*public\s*:\s*true|getPublicUrl\(", text):
569
+ add("S10", "info", rel, line_of(text, m.start()), "public storage URL: fine for public files only")
570
+
571
+ # S14 CORS
572
+ cors_hit = None
573
+ for rx, label in CORS_RX:
574
+ m = rx.search(text)
575
+ if m:
576
+ cors_hit = (m, label)
577
+ break
578
+ if cors_hit:
579
+ sev = "high" if CREDENTIALS_RX.search(text) else "info"
580
+ if "reflects" in cors_hit[1] and re.search(r"(?i)allow(?:ed)?_?(?:list|origins)|whitelist|\.has\(\s*origin\s*\)|\.includes\(\s*origin\s*\)", text):
581
+ sev = "info" # origin is checked against an allowlist first
582
+ add("S14", sev, rel, line_of(text, cors_hit[0].start()), cors_hit[1] + (" with credentials" if sev == "high" else ""))
583
+
584
+ # Cleanup
585
+ logs = list(LOG_RX.finditer(text))
586
+ if logs:
587
+ totals["C1"] += len(logs)
588
+ add("C1", "cleanup", rel, line_of(text, logs[0].start()), f"{len(logs)} console.log/debugger")
589
+ todos = list(TODO_RX.finditer(text)) + list(EMPTY_HANDLER_RX.finditer(text))
590
+ if todos:
591
+ totals["C3"] += len(todos)
592
+ add("C3", "cleanup", rel, line_of(text, todos[0].start()), f"{len(todos)} TODO/FIXME or empty handler")
593
+ fakes = list(FAKE_DATA_RX.finditer(text))
594
+ if fakes:
595
+ add("C2", "cleanup", rel, line_of(text, fakes[0].start()), f"{len(fakes)} fake/placeholder data: e.g. '{fakes[0].group(0)[:30]}'")
596
+ if TEMPLATE_RX.search(text):
597
+ m = TEMPLATE_RX.search(text)
598
+ add("C8", "info", rel, line_of(text, m.start()), "template text left in the app")
599
+ n_lines = text.count("\n") + 1
600
+ if n_lines > BIG_FILE_LINES:
601
+ big_files.append((n_lines, rel))
602
+
603
+ for n_lines, rel in sorted(big_files, reverse=True):
604
+ add("C6", "cleanup", rel, 0, f"{n_lines} lines")
605
+
606
+ for f in findings:
607
+ f["file"] = f["file"].replace(os.sep, "/")
608
+ project["size"] = {"files": n_files, "lines": n_lines_total, "class": size_class(n_files, n_lines_total)}
609
+ project["hints"] = hints
610
+ project["file_lines"] = file_lines
611
+ return project, findings, totals
612
+
613
+
614
+ ICONS = {"critical": "๐Ÿ”ด", "high": "๐ŸŸ ", "medium": "๐ŸŸก", "cleanup": "โšช", "info": "๐Ÿ’ก"}
615
+ NOT_COVERED = ("Regex covers only simple forms of S5, S6, S7 (premium unlocked in the browser), S11 and "
616
+ "per-column Supabase policies: read the plan. S13: run `npm audit --omit=dev`.")
617
+ CLEANUP_UNITS = {"C1": "console.log/debugger", "C3": "TODO/FIXME or empty handlers"}
618
+
619
+
620
+ def header_lines(project, findings):
621
+ size = project["size"]
622
+ counts = {k: 0 for k in SEVERITY_ORDER}
623
+ for f in findings:
624
+ counts[f["severity"]] += 1
625
+ head = (f"Lilith quick scan ยท {', '.join(project['stack']) or 'unknown stack'} ยท "
626
+ f"{size['files']} files, {size['lines']:,} lines ({size['class']})")
627
+ leads = "Leads (hints, confirm by reading): " + " ".join(f"{ICONS[k]}{v}" for k, v in counts.items() if v)
628
+ return [head, leads]
629
+
630
+
631
+ def plan_lines(entries, left_out):
632
+ if not entries:
633
+ return []
634
+ out = [f"Read plan ({len(entries)} files, most suspicious first" + (f"; {left_out} more left out" if left_out else "") + "):"]
635
+ for e in entries:
636
+ span = f":{e['lines'][0]}-{e['lines'][1]}" if e["lines"] else ""
637
+ out.append(f" {e['file']}{span} {' '.join(e['checks'])}")
638
+ return out
639
+
640
+
641
+ def cleanup_lines(findings):
642
+ out = []
643
+ by_check = {}
644
+ for f in findings:
645
+ if f["check"].startswith("C"):
646
+ by_check.setdefault(f["check"], []).append(f)
647
+ for check in sorted(by_check, key=lambda c: int(c[1:])):
648
+ items = by_check[check]
649
+ if check in CLEANUP_UNITS:
650
+ n = sum(int(re.match(r"\d+", i["note"]).group(0)) for i in items)
651
+ out.append(f"โšช {check} {n} {CLEANUP_UNITS[check]} in {len(items)} files")
652
+ elif check == "C6":
653
+ names = ", ".join(f"{i['file']} ({i['note'].split()[0]})" for i in items[:3])
654
+ out.append(f"โšช C6 {len(items)} files over {BIG_FILE_LINES} lines: {names}" + (" ..." if len(items) > 3 else ""))
655
+ else:
656
+ names = ", ".join(i["file"] for i in items[:3]) + (" ..." if len(items) > 3 else "")
657
+ out.append(f"{ICONS[items[0]['severity']]} {check} {CHECK_TITLES.get(check, '')}: {len(items)} files ({names})")
658
+ return out
659
+
660
+
661
+ def summarize_brief(project, findings, plan, left_out, per_check=4):
662
+ out = header_lines(project, findings)
663
+ security = sorted((f for f in findings if f["check"].startswith("S")),
664
+ key=lambda f: (SEVERITY_ORDER[f["severity"]], int(f["check"][1:]), f["file"]))
665
+ shown = {}
666
+ hidden = {}
667
+ for f in security:
668
+ if shown.get(f["check"], 0) >= per_check:
669
+ hidden[f["check"]] = hidden.get(f["check"], 0) + 1
670
+ continue
671
+ shown[f["check"]] = shown.get(f["check"], 0) + 1
672
+ loc = f["file"] + (f":{f['line']}" if f["line"] else "")
673
+ out.append(f"{ICONS[f['severity']]} {f['check']} {loc} {f['note']}")
674
+ if hidden:
675
+ out.append(" more: " + ", ".join(f"{n} {c}" for c, n in sorted(hidden.items())) + " (--full lists all)")
676
+ out += cleanup_lines(findings)
677
+ if not findings:
678
+ out.append("No leads. Still read the plan: most real holes need reading, not regex.")
679
+ out += plan_lines(plan, left_out)
680
+ out.append(NOT_COVERED)
681
+ return "\n".join(out)
682
+
683
+
684
+ def summarize(project, findings, max_examples):
685
+ out = []
686
+ out.append("Lilith quick scan")
687
+ out.append("Stack: " + (", ".join(project["stack"]) or "unknown"))
688
+ size = project["size"]
689
+ out.append(f"Size: {size['files']} files, {size['lines']:,} lines ({size['class']})")
690
+ out.append("Every item below is a LEAD. Confirm by reading the code before reporting it.\n")
691
+ by_check = {}
692
+ for f in findings:
693
+ by_check.setdefault(f["check"], []).append(f)
694
+ def check_key(item):
695
+ check, items = item
696
+ worst = min(SEVERITY_ORDER[i["severity"]] for i in items)
697
+ return (worst, check[0] != "S", int(re.sub(r"\D", "", check) or 0))
698
+ icons = {"critical": "๐Ÿ”ด", "high": "๐ŸŸ ", "medium": "๐ŸŸก", "cleanup": "โšช", "info": "๐Ÿ’ก"}
699
+ counts = {k: 0 for k in SEVERITY_ORDER}
700
+ for f in findings:
701
+ counts[f["severity"]] += 1
702
+ out.append("Leads: " + " ".join(f"{icons[k]} {k} {v}" for k, v in counts.items() if v))
703
+ out.append("")
704
+ for check, items in sorted(by_check.items(), key=check_key):
705
+ items.sort(key=lambda i: SEVERITY_ORDER[i["severity"]])
706
+ worst = items[0]["severity"]
707
+ out.append(f"{icons[worst]} {check} {CHECK_TITLES.get(check, '')} ({len(items)})")
708
+ for i in items[:max_examples]:
709
+ loc = i["file"] + (f":{i['line']}" if i["line"] else "")
710
+ out.append(f" {icons[i['severity']]} {loc} {i['note']}")
711
+ if len(items) > max_examples:
712
+ out.append(f" ... and {len(items) - max_examples} more")
713
+ if not findings:
714
+ out.append("No leads found. Still read the code for S3-S7: most real holes need reading, not regex.")
715
+ return "\n".join(out)
716
+
717
+
718
+ def main():
719
+ ap = argparse.ArgumentParser(description="Lilith quick scan")
720
+ ap.add_argument("root", nargs="?", default=".")
721
+ ap.add_argument("--json", action="store_true", help="print JSON instead of text")
722
+ mode = ap.add_mutually_exclusive_group()
723
+ mode.add_argument("--brief", action="store_true", help="compact output (default)")
724
+ mode.add_argument("--full", action="store_true", help="every lead, grouped by check")
725
+ ap.add_argument("--max-examples", type=int, default=6, help="leads per check with --full")
726
+ ap.add_argument("--plan-limit", type=int, default=PLAN_LIMIT, help=f"files in the read plan (default {PLAN_LIMIT})")
727
+ args = ap.parse_args()
728
+ if not os.path.isdir(args.root):
729
+ print(f"Not a folder: {args.root}", file=sys.stderr)
730
+ sys.exit(2)
731
+ project, findings, totals = scan(args.root, args.max_examples)
732
+ plan, left_out = read_plan(findings, project["hints"], project["file_lines"], args.plan_limit)
733
+ if args.json:
734
+ print(json.dumps({"stack": project["stack"], "size": project["size"], "findings": findings, "totals": totals,
735
+ "read_plan": plan, "read_plan_left_out": left_out}, indent=2, ensure_ascii=False))
736
+ return
737
+ try:
738
+ sys.stdout.reconfigure(encoding="utf-8")
739
+ except Exception:
740
+ pass
741
+ if args.full:
742
+ text = summarize(project, findings, args.max_examples)
743
+ text += "\n\n" + "\n".join(plan_lines(plan, left_out) + [NOT_COVERED])
744
+ else:
745
+ text = summarize_brief(project, findings, plan, left_out)
746
+ print(text)
747
+
748
+
749
+ if __name__ == "__main__":
750
+ main()