lilith-skill 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -83,9 +83,12 @@ Lilith has no account and no server. Your code goes only to the AI agent you alr
83
83
  | S9 | Unsafe HTML | `dangerouslySetInnerHTML` with user text |
84
84
  | S10 | File uploads | private files in a public bucket |
85
85
  | S11 | AI features | secrets in the system prompt, AI tools with too much power |
86
- | S12 | Debug doors | `/api/seed`, `admin@admin.com` / `admin123` |
87
- | S13 | Old packages | critical `npm audit` results |
86
+ | S12 | Debug doors | `/api/seed`, `admin@admin.com` / `admin123`, JWT secret `supersecretkey` |
87
+ | S13 | Old or fake packages | critical `npm audit` results, a package the AI made up or a look-alike |
88
88
  | S14 | CORS and headers | any site can call your API as the logged-in user |
89
+ | S15 | Account flows | password changed without the old one, reset link that never expires |
90
+ | S16 | Money and race conditions | "get bonus" tapped 20 times gives 20 bonuses, a resent webhook pays twice |
91
+ | S17 | The AI agent and production | real keys in `.mcp.json`, the agent holds the production database password |
89
92
  | C1–C8 | Code cleanup | logs, fake data, dead buttons, giant files |
90
93
  | U1–U20 | UI and copy | eyebrow labels, fake badges, gradients, "seamless", "elevate" |
91
94
  | VPS | Own server | firewall, SSH keys, closed database ports |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lilith-skill",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "Security check for vibecoded apps: an Agent Skill for Claude Code, Codex, Cursor, Copilot, Gemini CLI and more. Finds leaked keys, open Supabase/Firebase databases and missing login checks, in plain words.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -23,7 +23,7 @@ Cleanup runs only when asked.
23
23
  ## Steps
24
24
 
25
25
  1. **Scan.** `python3 <this-skill-folder>/scripts/lilith_scan.py <project-root>`: stack, size, leads (hints, not findings), **read plan**. No Python: check by reading. Tell the user the stack in one line. If the scan skipped a gitignored folder that gets deployed, scan that folder too.
26
- 2. **Security.** Load what the table below says, go through S1 to S14, read the plan's files. A problem counts only if you can finish "[who] can [do what] to [whose data or money]".
26
+ 2. **Security.** Load what the table below says, go through S1 to S17, read the plan's files. A problem counts only if you can finish "[who] can [do what] to [whose data or money]".
27
27
  3. **Live database** (Supabase or Firebase in the stack): follow the live check in the stack file. Skipped → the report says "Live database: NOT checked".
28
28
  4. **Cleanup** (full or cleanup mode only): code, then UI and copy. Cleanup never changes what the app does.
29
29
  5. **Report** with templates/report.md. Security mode ends with exactly one question: "Fix the critical ones, or continue to cleanup?" (nothing critical or high: "Nothing urgent. Continue to cleanup?")
@@ -38,6 +38,7 @@ Cleanup runs only when asked.
38
38
  | guides/stacks/firebase.md + checks/firebase_check.md | stack has Firebase |
39
39
  | guides/stacks/stripe.md | stack has Stripe or Payments |
40
40
  | guides/stacks/ai.md | stack has AI API |
41
+ | guides/stacks/telegram.md | stack has Telegram (bot or Mini App) |
41
42
  | guides/cleanup-code.md | cleanup of code |
42
43
  | guides/cleanup-ui.md | UI and copy cleanup (it routes to guides/ui/*) |
43
44
  | templates/report.md | writing the report |
@@ -4,3 +4,4 @@
4
4
  2. Add to `.gitignore`: `.env`, `.env.*`, and keep `!.env.example` with empty values.
5
5
  3. Stop tracking: `git rm --cached .env`.
6
6
  4. **Rotate the key** in the provider dashboard (only the owner can). Once a key was in git or a deploy, treat it as public; deleting it from the code is not enough, it stays in git history.
7
+ 5. **Keys in old commits:** rotating the key is the fix. Rewriting git history is optional and needs the owner's yes (`git filter-repo`). Telegram bot token: @BotFather → /revoke, then put the new token in env.
@@ -1,3 +1,5 @@
1
1
  # Fix S12: leftover debug and test doors
2
2
 
3
3
  Delete seed/debug routes, or protect them with a server-side admin check. Create the first admin with a one-off script run from your own machine, not a public route. Remove test accounts from production. Return a generic error to the browser and log details on the server.
4
+
5
+ **Weak signing secret:** generate one (`openssl rand -hex 32`), put it in env, no fallback; changing it logs everyone out once, which is fine. **API docs:** serve them only outside production (`if (process.env.NODE_ENV !== "production") app.use("/docs", swaggerUi.serve, swaggerUi.setup(spec))`; FastAPI: `FastAPI(docs_url=None, redoc_url=None, openapi_url=None)`) or put them behind login. **Default logins:** change every default password on panels and databases.
@@ -1,3 +1,5 @@
1
1
  # Fix S13: vulnerable packages
2
2
 
3
3
  Update the specific package (`npm install pkg@latest`), run the app, check it still works. Commit a lockfile. Don't run `npm audit fix --force` without asking: it can make breaking upgrades.
4
+
5
+ **Suspicious package:** don't install or run it. Find the real one (the docs of the library you meant, or the most-downloaded package for that job), replace it in `package.json`/`requirements.txt`, reinstall. If the fake one was already installed: rotate keys on that machine and check `~/.ssh/authorized_keys` for keys you don't know.
@@ -0,0 +1,7 @@
1
+ # Fix S15: account flows
2
+
3
+ - **Change password or email:** ask for the current password on the server and check it before saving. Supabase: Auth → Providers → Email → turn on "Secure password change" and "Secure email change" (only the owner can), then pass the `nonce` from `auth.reauthenticate()` to `updateUser`.
4
+ - **2FA:** issue the full session only after the code is verified on the server. Supabase MFA: check `aal2` on the server (`supabase.auth.mfa.getAuthenticatorAssuranceLevel()`) or in RLS: `(select auth.jwt()->>'aal') = 'aal2'`.
5
+ - **Reset tokens:** random (`crypto.randomBytes(32).toString("hex")`), stored hashed, expire in 15–60 minutes, deleted on first use and when the password changes. Build the link from a fixed `APP_URL`, never the request `Host` header. Same reply whether or not the email exists.
6
+ - **Invite-only apps:** turn signup off (Supabase: Auth → Providers → Email → "Allow new users to sign up" off; invite with `auth.admin.inviteUserByEmail` from the server), or check an allowlist in the signup route.
7
+ - Limit login, reset and code attempts (S8).
@@ -0,0 +1,16 @@
1
+ # Fix S16: money and race conditions
2
+
3
+ **Change the balance in one database statement**, with the check inside it:
4
+ ```sql
5
+ update profiles set credits = credits - 1
6
+ where id = $1 and credits >= 1
7
+ returning credits; -- no row back = not enough credits
8
+ ```
9
+ Prisma: `prisma.profile.updateMany({ where: { id, credits: { gte: 1 } }, data: { credits: { decrement: 1 } } })`, then check `count === 1`. Supabase from the browser: put the statement in a function the server calls; never let users update `credits` themselves (fixes/S3.md).
10
+
11
+ **Once-only rewards and payments: a unique constraint does the check.**
12
+ ```sql
13
+ create table reward_claims (user_id uuid, reward text, primary key (user_id, reward));
14
+ create table payments (provider_payment_id text primary key, user_id uuid, amount int);
15
+ ```
16
+ Insert the claim or payment id first; a duplicate fails (`on conflict do nothing`, then check whether a row was inserted). Give credits only when the insert succeeded, in the same transaction. A resent webhook then answers 200 and changes nothing.
@@ -0,0 +1,6 @@
1
+ # Fix S17: the AI agent and production
2
+
3
+ 1. **Keys in agent configs:** read them from the environment. Claude Code and Cursor expand `${VAR}` in `.mcp.json`: use `"env": { "API_KEY": "${API_KEY}" }` and set the variable in your shell profile or an untracked `.env`. Add personal configs (`.cursor/mcp.json`, `.claude/settings.local.json`) to `.gitignore`. A key that was committed: rotate it (fixes/S1.md).
4
+ 2. **Separate databases:** a dev database (a second Supabase project, a local Postgres) for the agent and for `DATABASE_URL` in `.env.local`. The production URL lives only in the hosting dashboard. If an MCP server must see production, give it a read-only database user.
5
+ 3. **Backups (only the owner can):** turn them on (Supabase: Database → Backups; a VPS: provider snapshots plus a `pg_dump` copied elsewhere), then restore one into a test database once to prove it works.
6
+ 4. Tell the agent (in CLAUDE.md, AGENTS.md or .cursorrules) to ask before any command that deletes data or resets the database.
@@ -9,3 +9,14 @@ export async function POST(req: Request) {
9
9
  }
10
10
  ```
11
11
  JWT: `jwt.verify(token, secret, { algorithms: ["HS256"] })`, never `jwt.decode` for auth. Server actions need the same check at the top.
12
+
13
+ **Supabase `security definer` functions:** check the caller inside (`if auth.uid() is null then raise exception 'not allowed'; end if;`), add `set search_path = ''`, and `revoke execute on function f from anon, public;` for anything not meant for visitors. Prefer `security invoker` when the function doesn't need extra rights.
14
+
15
+ **Fail closed:** the default answer is "no". `if (!user || !user.isAdmin) return 403`; an error inside the check returns 401/403, never `next()`.
16
+
17
+ **Bot admin commands:** compare the sender's id with an allowlist from env.
18
+ ```python
19
+ ADMIN_IDS = {int(x) for x in os.environ["ADMIN_IDS"].split(",")}
20
+ @router.message(Command("ban"), F.from_user.id.in_(ADMIN_IDS)) # aiogram 3
21
+ ```
22
+ grammY/Telegraf: `if (!ADMIN_IDS.has(ctx.from?.id)) return;`
@@ -5,3 +5,4 @@
5
5
  - Write only named fields: `data: { name }`, never `data: req.body`.
6
6
  - Check admin rights on the server for every admin endpoint, from your database, not from the request.
7
7
  - Block users from updating their own `role`/`plan` column (see fixes/S3.md).
8
+ - **Telegram Mini Apps:** the browser sends the raw `Telegram.WebApp.initData` string (e.g. `Authorization: tma <initData>`); the server verifies it and takes the user id only from the verified result. Node: `validate(initData, BOT_TOKEN, { expiresIn: 3600 })` from `@telegram-apps/init-data-node`. aiogram: `safe_parse_webapp_init_data(token=BOT_TOKEN, init_data=raw)`. Reject when `auth_date` is older than an hour.
@@ -9,3 +9,5 @@ const { success } = await ratelimit.limit(user.id);
9
9
  if (!success) return new Response("Too many requests", { status: 429 });
10
10
  ```
11
11
  Express: `express-rate-limit` on login/signup routes. Supabase Edge Functions: a per-user usage table checked before the call.
12
+
13
+ **SMS and OTP:** limit per phone number (e.g. 3 codes an hour) and per IP, add a captcha before "send code" on public forms, allow about 5 wrong codes, then expire the code. Block country codes you don't serve. **Spend caps (only the owner can):** a hard monthly limit and an alert in each provider dashboard: AI keys, Google Cloud billing budget, SMS gateway balance.
@@ -1,12 +1,12 @@
1
1
  # Security checks (core)
2
2
 
3
- The 14 holes AI-built apps have most often. Here: how to spot each one and why it matters. Stack details live in `stacks/` (loaded only for the detected stack). Fix code lives in `fixes/S<n>.md` (loaded only when the user agrees to fix that check).
3
+ The 17 holes AI-built apps have most often. Here: how to spot each one and why it matters. Stack details live in `stacks/` (loaded only for the detected stack). Fix code lives in `fixes/S<n>.md` (loaded only when the user agrees to fix that check).
4
4
 
5
5
  A finding counts only if you can finish **"[who] can [do what] to [whose data or money]"** from the code. If it depends on something you can't see (a dashboard setting, a deployed config), report "worth checking" with the exact thing to look at.
6
6
 
7
7
  ## S1. Secret keys in the code or in git 🔴
8
- **Spot it.** Scanner hits for live keys (`sk_live_`, `sk-proj-`, `sk-ant-`, `AKIA`, `ghp_`, private keys, database URLs with a password, Supabase `service_role` JWTs), hard-coded fallbacks (`process.env.JWT_SECRET || "..."`), `.env` files tracked by git (`git ls-files | grep -i '\.env'`, also `git log --all --oneline -- .env`).
9
- **Why.** Anyone who sees the repo can use the key: spend your money, read the whole database, sign their own login tokens.
8
+ **Spot it.** Scanner hits for live keys (`sk_live_`, `sk-proj-`, `sk-ant-`, `AKIA`, `ghp_`, private keys, database URLs with a password, Supabase `service_role` JWTs), hard-coded fallbacks (`process.env.JWT_SECRET || "..."`), `.env` files tracked by git (`git ls-files | grep -i '\.env'`, also `git log --all --oneline -- .env`). Old commits count: a key deleted from the code is still in git history (the scanner checks it; deeper: `gitleaks git`). Telegram bot tokens (`123456789:AA…`) are secrets too.
9
+ **Why.** Anyone who sees the repo can use the key: spend your money, read the whole database, sign their own login tokens. Deleting the key doesn't stop this: over 64% of leaked keys still work years later. Only replacing (rotating) the key in the provider dashboard does.
10
10
  **Not secrets:** Supabase anon key, Firebase web `apiKey`, Stripe `pk_` key, domain-restricted Maps keys. Their safety comes from S3 and dashboard restrictions.
11
11
 
12
12
  ## S2. Secret keys sent to the browser 🔴
@@ -14,11 +14,18 @@ A finding counts only if you can finish **"[who] can [do what] to [whose data or
14
14
  **Why.** Everything with these prefixes ships in the JavaScript every visitor downloads.
15
15
 
16
16
  ## S3. Database open to everyone 🔴
17
- **Spot it.** Database rules in migrations or rules files that let anyone read or write; tables with no access rules at all. Details per stack: `stacks/supabase.md`, `stacks/firebase.md`. The live database can differ from the repo: run the live check.
17
+ **Spot it.** Database rules in migrations or rules files that let anyone read or write; tables with no access rules at all. Details per stack: `stacks/supabase.md`, `stacks/firebase.md`. The live database can differ from the repo: run the live check. Also:
18
+ - Storage buckets holding private files set to public (S10).
19
+ - Postgres/Supabase views: they run with the owner's rights and skip RLS unless created `with (security_invoker = true)`.
20
+ - Databases on your own server (Postgres, MongoDB, Redis, Elasticsearch) reachable from the internet, often with no password. A Docker `ports: "27017:27017"` line opens the port past the firewall. See guides/server.md, phase 3.
18
21
  **Why.** The public client key is in every browser. With open rules it can read, change or delete every row.
19
22
 
20
23
  ## S4. API routes with no login check 🔴/🟠
21
- **Spot it.** Every server entry point (API routes, server actions, edge functions, Express routes) that reads or changes private data without a session check at the top, or with a check that doesn't verify anything (`jwt.decode` instead of `jwt.verify`). Server actions are public endpoints too. Login and signup routes are public by design (check them for S8 instead).
24
+ **Spot it.** Every server entry point (API routes, server actions, edge functions, Express routes) that reads or changes private data without a session check at the top, or with a check that doesn't verify anything (`jwt.decode` instead of `jwt.verify`). Server actions are public endpoints too. Login and signup routes are public by design (check them for S8 instead). Other doors with the same problem:
25
+ - Database functions callable through the API: Supabase `security definer` functions are reachable at `/rest/v1/rpc/<name>` and run with the owner's rights, skipping RLS. They need their own `auth.uid()` check, or `revoke execute ... from anon, authenticated`.
26
+ - `/admin` pages and admin API routes guarded only in the browser.
27
+ - Checks that fail open: `catch { return next() }`, `if (user && !user.isAdmin)` (no user at all passes), a missing env var that turns the check off.
28
+ - Bot admin commands that check `chat.id` or `username` instead of the sender (`message.from_user.id` in aiogram, `ctx.from.id` in grammY/Telegraf). In a group `chat.id` is the group, so every member passes; usernames can be changed and taken.
22
29
  **Why.** Hiding a button doesn't protect the endpoint. Anyone can call it with curl.
23
30
 
24
31
  ## S5. Users can open other users' data 🟠
@@ -26,7 +33,7 @@ A finding counts only if you can finish **"[who] can [do what] to [whose data or
26
33
  **Why.** User A changes `/invoices/41` to `/42` and sees user B's invoice.
27
34
 
28
35
  ## S6. Trusting what the browser says 🟠
29
- **Spot it.** The server takes `price`, `amount`, `role`, `isAdmin`, `plan`, `credits`, `userId` from the request; `data: req.body` written straight to the database; admin pages protected only in a React component; users allowed to update their own `role`/`plan` column.
36
+ **Spot it.** The server takes `price`, `amount`, `role`, `isAdmin`, `plan`, `credits`, `userId` from the request; `data: req.body` written straight to the database; admin pages protected only in a React component; users allowed to update their own `role`/`plan` column. Telegram Mini Apps: the server takes the user from `initDataUnsafe` (or from `initData` without checking its `hash`). The server must verify the raw `initData` string with the bot token and check `auth_date` is fresh; otherwise anyone opens the app in a browser and claims any Telegram id.
30
37
  **Why.** Anyone can edit the request in DevTools and pay $0.01 or set `role: "admin"`.
31
38
 
32
39
  ## S7. Payments not verified 🔴
@@ -34,8 +41,8 @@ A finding counts only if you can finish **"[who] can [do what] to [whose data or
34
41
  **Why.** Anyone can send a fake "payment succeeded" event or open the success URL and get the paid plan.
35
42
 
36
43
  ## S8. No limits on expensive or sensitive actions 🟡 (🟠 for AI)
37
- **Spot it.** No rate limit or per-user cap on AI endpoints, email/SMS sending, login, signup, password reset, OTP, uploads, public forms.
38
- **Why.** A bot runs up your AI bill overnight, guesses passwords, or sends spam from your domain.
44
+ **Spot it.** No rate limit or per-user cap on AI endpoints, email/SMS sending, login, signup, password reset, OTP, uploads, public forms. SMS and OTP sending need their own limit per phone number and per IP, plus a cap on wrong-code attempts. Hard spend caps can't be set in code: ask the owner to set them in the provider dashboard (OpenAI, Anthropic, Google Cloud/Gemini, the SMS gateway).
45
+ **Why.** A bot runs up your AI bill overnight (a stolen Gemini key cost one developer $82,314 in two days), guesses passwords, sends spam from your domain, or uses your "send code" button as an SMS bomber that empties the SMS balance.
39
46
 
40
47
  ## S9. Unsafe HTML and code execution 🟠
41
48
  **Spot it.** `dangerouslySetInnerHTML`, `v-html`, `{@html}`, `.innerHTML =`, `eval(`, `new Function(`, Markdown with raw HTML, `exec` with user input, SQL built from strings (`$queryRawUnsafe`, template literals). A finding needs user- or AI-controlled text reaching the sink; static HTML and JSON-LD from your own object are fine.
@@ -43,24 +50,53 @@ A finding counts only if you can finish **"[who] can [do what] to [whose data or
43
50
 
44
51
  ## S10. File uploads 🟡
45
52
  **Spot it.** No size or type limit; the user's file name used on disk; public buckets or public folders holding private files (IDs, invoices).
46
- **Why.** Private documents become downloadable by link; someone uploads a huge file or an HTML page served from your domain.
53
+ **Why.** Private documents become downloadable by link (the Tea app leaked ~13,000 selfies and ID photos from an open bucket); someone uploads a huge file or an HTML page served from your domain.
54
+ 💡 **Collect less.** Passport scans, ID photos, national ids (PINFL, SNILS, SSN): ask for them only if a law or a real process needs them. If you must, keep them in a private bucket and delete them when no longer needed. What you don't store can't leak.
47
55
 
48
56
  ## S11. AI features 🟡/🟠
49
57
  **Spot it.** Secrets, internal URLs or logins in system prompts; AI tools that can write data or send things, fed with user or web text; model output passed to `eval`, SQL, shell or raw HTML.
50
58
  **Why.** Prompt injection makes the AI act for the attacker, and system prompts can always be extracted.
51
59
 
52
60
  ## S12. Leftover debug and test doors 🟡 (🔴 if it grants access)
53
- **Spot it.** `/api/debug`, `/api/seed`, `/admin/setup` without a server check; routes that return `process.env`; hard-coded test accounts (`admin@admin.com`); stack traces or SQL errors sent to the browser. Test credentials inside test files are fine.
54
- **Why.** Attackers scan for these paths automatically.
61
+ **Spot it.** `/api/debug`, `/api/seed`, `/admin/setup` without a server check; routes that return `process.env`; hard-coded test accounts (`admin@admin.com`); stack traces or SQL errors sent to the browser. Also:
62
+ - Weak or default signing secrets for JWT and sessions (`secret`, `supersecretkey`, `changeme`, `your-secret`): 🔴, anyone can sign an admin token. Invicti found `supersecretkey` in 1,182 of 20,656 generated apps.
63
+ - API docs (Swagger UI, `/docs`, `/api-docs`) public in production: 💡 for a public API, 🟡 if they list admin or internal routes.
64
+ - Default logins on admin panels and databases (`admin`/`admin`, an unchanged Grafana, pgAdmin or Mongo Express password).
65
+ Test credentials inside test files are fine.
66
+ **Why.** Attackers scan for these paths and default secrets automatically.
55
67
 
56
68
  ## S13. Vulnerable packages 🟡
57
- **Spot it.** `npm audit --omit=dev` (or pnpm/yarn/pip-audit): report only critical/high in packages used at runtime. No lockfile. Package names that don't exist on npm (AI sometimes invents them).
69
+ **Spot it.** `npm audit --omit=dev` (or pnpm/yarn/pip-audit): report only critical/high in packages used at runtime. No lockfile. Packages the AI suggested that don't exist (it invents names), or look-alikes of popular ones: fake `node-telegram-bot-api` clones added the attacker's SSH key to `~/.ssh/authorized_keys`. For each unfamiliar runtime dependency check age, downloads and repo: `npm view <pkg> time.created repository.url` and weekly downloads on npmjs.com (PyPI: pypistats.org). Days old, a few downloads and a name one letter off a popular package: 🔴 lead, ask before running anything. Also flag `postinstall` scripts in unfamiliar packages.
58
70
  **Why.** Bots exploit known holes in old packages.
59
71
 
60
72
  ## S14. Headers, CORS and HTTPS 💡 (🟠 for credentialed CORS)
61
73
  **Spot it.** Any origin allowed (`*`, `origin: true`, the request origin reflected) **together with** credentials on an API that uses cookies. If auth uses a Bearer header and no cookies, there is no attack path: 💡 at most. Missing security headers are hardening only.
62
74
  **Why.** Credentialed CORS that trusts any site lets another website act as the logged-in user.
63
75
 
76
+ ## S15. Account flows 🟠 (🔴 if a stranger can take over accounts)
77
+ **Spot it.**
78
+ - Changing the password or email doesn't ask for the current password (or a fresh login). Supabase: `auth.updateUser({ password })` with "Secure password change" off.
79
+ - 2FA checked only in the browser: the API hands out the session before the code is verified, or the "verify code" step can be skipped by calling the next endpoint.
80
+ - Password reset tokens that never expire, work more than once, or can be guessed (`Math.random()`, a user id or timestamp in the link); reset links built from the request `Host` header.
81
+ - Signup open on an app meant for invited users only (a public signup route, or Supabase Auth "Allow new users to sign up" on).
82
+ **Why.** One stolen session or guessed reset link becomes a permanent takeover: the attacker changes the email and password, and the owner can't get back in.
83
+
84
+ ## S16. Money and race conditions 🟠
85
+ **Spot it.**
86
+ - Balance, credits, bonuses or stock read in code, changed, and written back (`credits: user.credits - 1`, `balance = balance + amount` in JavaScript). Two requests at the same moment both pass the "enough credits?" check.
87
+ - "Claim bonus", promo codes, referral rewards and free trials without a unique constraint on (user, reward). The check "already claimed?" runs before the insert, so 20 fast taps make 20 claims.
88
+ - Payment webhooks that add credits without saving the provider's payment id under a unique constraint. Providers resend webhooks on purpose (Stripe, YooKassa, Payme all retry), so one payment tops up twice.
89
+ **Why.** Real money, and it never shows up when you test by hand: only when someone sends 20 requests in a second.
90
+
91
+ ## S17. The AI agent and production 🔴/🟡
92
+ **Spot it.**
93
+ - Agent and MCP configs (`.mcp.json`, `.cursor/mcp.json`, `.vscode/mcp.json`, `.claude/settings*.json`) with real keys or a database URL written in, instead of `${ENV_VAR}`. Committed to git: 🔴 like any S1 key.
94
+ - The coding agent has the production database password, or an MCP server points at production with write access. Worth checking: ask the owner which database the agent's connection string points to.
95
+ - No separate dev database; no backups, or backups never restored once (🟡, owner checklist).
96
+ **Why.** One wrong agent command deletes the live data: Replit's agent wiped SaaStr's production database during a code freeze. Keys in MCP configs leak like any other: GitGuardian counted 24,008 secrets in public MCP config files.
97
+
64
98
  ## Only the owner can check (add to the report checklist when relevant)
65
- - Every leaked key rotated in the provider dashboard; AI provider spending limit set.
66
- - Production env vars set in the hosting dashboard, not the repo; backups on.
99
+ - Every leaked key rotated in the provider dashboard (Telegram bot token: @BotFather → /revoke).
100
+ - Hard spending limits set at every paid provider: AI (OpenAI, Anthropic, Google Cloud), SMS gateway, hosting.
101
+ - Production env vars set in the hosting dashboard, not the repo.
102
+ - Backups on, and restored once into a test database to prove they work. The coding agent connects only to a dev database.
@@ -50,8 +50,8 @@ Check: from a new terminal you can still log in. Make sure you know where your p
50
50
 
51
51
  ## Phase 3. Don't expose what doesn't need to be public (10 min)
52
52
 
53
- - Databases (Postgres 5432, MySQL 3306, Redis 6379, MongoDB 27017) must not be open to the internet. Check: `sudo ss -tulpn` and look for `0.0.0.0:5432` or similar. Bind them to `127.0.0.1` or keep them inside a Docker network.
54
- - **Docker warning:** `ports: - "5432:5432"` in docker-compose opens the port to the world **and skips ufw**. Use `"127.0.0.1:5432:5432"` or remove the `ports` line if only other containers need it.
53
+ - Databases (Postgres 5432, MySQL 3306, Redis 6379, MongoDB 27017, Elasticsearch 9200) must not be open to the internet. MongoDB, Redis and Elasticsearch often start with **no password at all**: open to the internet means anyone reads, wipes or ransoms the data. Check: `sudo ss -tulpn` and look for `0.0.0.0:27017` or similar. Bind them to `127.0.0.1` or keep them inside a Docker network, and turn on a password anyway (Redis `requirepass`, MongoDB `--auth`, Elasticsearch security on).
54
+ - **Docker warning:** `ports: - "5432:5432"` in docker-compose opens the port to the world **and skips ufw**. Use `"127.0.0.1:5432:5432"` or remove the `ports` line if only other containers need it. Check: `docker ps --format '{{.Names}} {{.Ports}}'` must show no `0.0.0.0:` for a database. From your own computer, `nc -zv SERVER_IP 6379` should fail.
55
55
  - Admin panels (Portainer, pgAdmin, Coolify dashboards): protect with a strong password and, ideally, reach them only through a VPN like Tailscale.
56
56
  - Keep `.env` files out of the web root and readable only by the app user: `chmod 600 .env`.
57
57
 
@@ -0,0 +1,46 @@
1
+ # Telegram details (load when the scanner detects a Telegram bot or Mini App)
2
+
3
+ ## S1 / S2: the bot token
4
+ - Format `123456789:AA…`. It lives only in server env. Whoever has it controls the bot: reads every chat it is in, messages all its users, points the webhook at their own server.
5
+ - File links `https://api.telegram.org/file/bot<token>/<path>` contain the token. Never send them to the browser or to users: download on the server, then serve the file yourself.
6
+ - `api.telegram.org/bot…` called from Mini App code means the token is in the bundle (🔴).
7
+ - Leaked: @BotFather → /revoke, set the new token in env, call `setWebhook` again.
8
+
9
+ ## S4: who really sent this update
10
+ - **Webhook without a secret** 🟠: anyone who finds the URL can POST fake updates: an "admin" sending /ban, a fake `successful_payment`. Fix: pass `secret_token` (1–256 chars, `A-Z a-z 0-9 _ -`) to `setWebhook` and reject requests whose `X-Telegram-Bot-Api-Secret-Token` header doesn't match. aiogram: `SimpleRequestHandler(dispatcher=dp, bot=bot, secret_token=SECRET)`. Telegraf: `bot.launch({ webhook: { domain, secretToken } })`. grammY: the `secretToken` option of `webhookCallback`. Long polling has no webhook to protect.
11
+ - **Admin commands** (more in core S4): check `message.from_user.id` (aiogram) / `ctx.from.id` (grammY, Telegraf) against an id list from env. Not `chat.id` (in a group that is the group), not `username` (it can be changed and taken), and a hidden command protects nothing (anyone can type /admin).
12
+ - **Inline buttons:** `callback_data` comes back from the user's app, and a modified client can send any value. Before acting on `approve:1234` or `delete:55`, check this user may do it (S5).
13
+ - **Login with Telegram on a website:** never take `id` from the query string as is. Legacy widget (`telegram-widget.js`, fields `id … auth_date hash`): the server checks `hash` = HMAC-SHA256 of the data-check-string, keyed with SHA256(bot token), and that `auth_date` is fresh. The newer OIDC login: verify the `id_token` against Telegram's JWKS and check `iss`, `aud`, `exp`.
14
+
15
+ ## S6: Mini Apps (the most common Telegram hole)
16
+ `initDataUnsafe` is for display only: anyone can open the app in a browser and claim any id. The browser sends the raw `Telegram.WebApp.initData` string (e.g. `Authorization: tma <initData>`); the server checks it:
17
+ ```ts
18
+ import { createHmac, timingSafeEqual } from "node:crypto";
19
+ export function verifyInitData(raw: string, botToken: string, maxAgeSec = 3600) {
20
+ const params = new URLSearchParams(raw);
21
+ const hash = params.get("hash") ?? "";
22
+ params.delete("hash");
23
+ const dataCheckString = [...params].sort(([a], [b]) => (a < b ? -1 : 1)).map(([k, v]) => `${k}=${v}`).join("\n");
24
+ const secret = createHmac("sha256", "WebAppData").update(botToken).digest();
25
+ const expected = createHmac("sha256", secret).update(dataCheckString).digest("hex");
26
+ if (hash.length !== expected.length || !timingSafeEqual(Buffer.from(hash), Buffer.from(expected))) return null;
27
+ if (Date.now() / 1000 - Number(params.get("auth_date")) > maxAgeSec) return null;
28
+ return JSON.parse(params.get("user") ?? "null"); // trust this id only now
29
+ }
30
+ ```
31
+ Python (aiogram): `safe_parse_webapp_init_data(token=BOT_TOKEN, init_data=raw)` raises `ValueError` when the hash is wrong; then check `auth_date` yourself.
32
+ - Telegram sets no maximum age for `auth_date`: pick one (an hour to a day) and reject older data, or verify once and issue your own session.
33
+ - `start_param` (deep links, referral codes) is user input, not proof (S6, S16).
34
+
35
+ ## S7: Telegram Stars and payments
36
+ - Deliver only after the bot receives the `successful_payment` update (Telegram's own rule). The Mini App `openInvoice` callback reporting `"paid"` is just the browser saying so: show "thanks", grant on the server.
37
+ - `pre_checkout_query`: answer within 10 seconds; check `invoice_payload` points to this user's real order and `total_amount` and currency (`XTR` for Stars) match the server price.
38
+ - Prices go into `createInvoiceLink` / `sendInvoice` from the server, never from the Mini App request (S6).
39
+ - Save `telegram_payment_charge_id` under a unique constraint (S16): it stops double delivery and `refundStarPayment` needs it.
40
+
41
+ ## S8 / S10
42
+ - Per-user limits on AI commands and anything that costs money; broadcasts to all users only from admins.
43
+ - Documents users send (passport photos are common in bots) go to private storage, deleted when no longer needed (💡 collect less).
44
+
45
+ ## Owner checklist
46
+ Token only in server env (rotated if it was ever shared); webhook set with `secret_token`; admin ids in env, not in code.
@@ -17,6 +17,7 @@ import os
17
17
  import re
18
18
  import subprocess
19
19
  import sys
20
+ import time
20
21
  from typing import Iterator, List, Set, Tuple
21
22
 
22
23
  SKIP_DIRS = {
@@ -51,9 +52,13 @@ CHECK_TITLES = {
51
52
  "S8": "Endpoints to check for rate limits",
52
53
  "S9": "Unsafe HTML / code execution",
53
54
  "S10": "Storage / upload to check",
55
+ "S11": "AI features",
54
56
  "S12": "Debug / test doors",
55
57
  "S13": "Packages",
56
58
  "S14": "CORS / headers",
59
+ "S15": "Account flows to check",
60
+ "S16": "Money / race conditions",
61
+ "S17": "AI agent configs and production",
57
62
  "C1": "Leftover logs and debugger",
58
63
  "C2": "Fake / placeholder data",
59
64
  "C3": "TODOs and empty handlers",
@@ -81,9 +86,12 @@ SECRET_PATTERNS = [
81
86
  ("Groq key", r"\bgsk_[A-Za-z0-9]{40,}", "critical"),
82
87
  ("Hugging Face token", r"\bhf_[A-Za-z0-9]{30,}", "high"),
83
88
  ("Replicate token", r"\br8_[A-Za-z0-9]{30,}", "critical"),
89
+ ("Telegram bot token", r"\b\d{8,10}:AA[A-Za-z0-9_\-]{33}(?![A-Za-z0-9_\-])", "critical"),
84
90
  ]
85
91
  SECRET_RX = [(name, re.compile(rx), sev) for name, rx, sev in SECRET_PATTERNS]
86
92
  JWT_RX = re.compile(r"\beyJ[A-Za-z0-9_\-]{10,}\.eyJ[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}")
93
+ FAKE_VALUE_RX = re.compile(r"^(?:123456|000000)\d*:|@(?:localhost|127\.0\.0\.1|0\.0\.0\.0|host\.docker\.internal)\b") # sample bot tokens, local databases
94
+ BUILD_ASSET_RX = re.compile(r"(?:^|/)assets/[^/]+-(?=[A-Za-z0-9_\-]{8}\.)(?=[^.]*\d)(?=[^.]*[A-Za-z])[A-Za-z0-9_\-]{8}\.(?:js|mjs|css)$") # bundler output: name-<8-char hash>.js
87
95
  PLACEHOLDER_RX = re.compile(r"(?i)(x{6,}|your[_\-]?(?:api[_\-]?)?key|example|placeholder|dummy|<[^>]+>|\*{4,}|\.\.\.|changeme|replace[_\-]?me)")
88
96
 
89
97
  PUBLIC_PREFIX_RX = re.compile(
@@ -153,8 +161,8 @@ DEBUG_ROUTE_RX = re.compile(r"(?i)(?:^|/)(?:debug|seed|test|testing|dev|_dev|adm
153
161
  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)['\"]")
154
162
 
155
163
  TEST_FILE_RX = re.compile(r"(?i)(?:^|/)(?:tests?|__tests__|spec|specs|e2e|cypress|playwright)/|\.(?:test|spec)\.[jt]sx?$")
156
- AUTH_ENDPOINT_RX = re.compile(r"(?i)sign-?up|sign-?in|log-?in|register|reset-?password|forgot-?password|otp|magic-?link")
157
- AUTH_ROUTE_STRING_RX = re.compile(r"(?i)\.(?:post|put)\s*\(\s*['\"`][^'\"`]*(?:sign-?up|sign-?in|log-?in|register|reset|forgot|otp|magic-?link)")
164
+ AUTH_ENDPOINT_RX = re.compile(r"(?i)sign-?up|sign-?in|log-?in|register|reset-?password|forgot-?password|otp|magic-?link|send-?code|verify-?code|send-?sms")
165
+ AUTH_ROUTE_STRING_RX = re.compile(r"(?i)\.(?:post|put)\s*\(\s*['\"`][^'\"`]*(?:sign-?up|sign-?in|log-?in|register|reset|forgot|otp|magic-?link|send-?code|verify-?code|send-?sms)")
158
166
  FALLBACK_SECRET_RX = re.compile(r"process\.env\.[A-Z0-9_]*(?:SECRET|PRIVATE|PASSWORD|TOKEN|API_KEY)[A-Z0-9_]*\s*(?:\|\||\?\?)\s*['\"`][^'\"`]{6,}['\"`]")
159
167
  JWT_DECODE_RX = re.compile(r"\bjwt\.decode\s*\(|\bjwtDecode\s*\(")
160
168
  JWT_VERIFY_RX = re.compile(r"\bjwt\.verify\s*\(|\bjwtVerify\s*\(|\bverifyJwt\s*\(")
@@ -178,7 +186,77 @@ AUTH_HINT_RX = re.compile(
178
186
  RATELIMIT_HINT_RX = re.compile(r"(?i)ratelimit|rate-limit|rate_limit|limiter|slowDown|throttle")
179
187
  WEBHOOK_VERIFY_RX = re.compile(r"constructEvent|constructEventAsync|svix|Webhook\(|verifySignature|createHmac|timingSafeEqual|verifyWebhook|validateEvent|x-signature|signature", re.I)
180
188
  AI_USE_RX = re.compile(r"openai|anthropic|generateText|streamText|chat\.completions|messages\.create|groq|gemini|replicate", re.I)
181
- EMAIL_USE_RX = re.compile(r"resend|sendgrid|nodemailer|postmark|mailgun|twilio", re.I)
189
+ EMAIL_USE_RX = re.compile(r"resend|sendgrid|nodemailer|postmark|mailgun|twilio|eskiz|playmobile|smsc\.|sms\.ru|smsaero|vonage|messagebird|send_?sms|signInWithOtp", re.I)
190
+
191
+ # S4: database functions and bot admin checks
192
+ SQL_FUNCTION_RX = re.compile(r"(?is)create\s+(?:or\s+replace\s+)?function\s+([\w.\"]+)\s*\(")
193
+ SQL_VIEW_RX = re.compile(r"(?is)create\s+(?:or\s+replace\s+)?view\s+(?:if\s+not\s+exists\s+)?([\w.\"]+)(.{0,200}?)\bas\b")
194
+ SQL_CALLER_CHECK_RX = re.compile(r"(?i)auth\.(?:uid|role|jwt)\s*\(|\bcurrent_user\b|\bsession_user\b")
195
+ BOT_ADMIN_RX = re.compile(
196
+ r"(?i)(?:chat\.id|chat_id|\.username)\s*(?:===?|!==?|\bnot\s+in\b|\bin\b)\s*[\w.\[\(]*admin|"
197
+ r"admin\w*\s*(?:===?|!==?)\s*[\w.]*(?:chat\.id|chat_id|\.username)\b|"
198
+ r"admin\w*\.(?:includes|has)\(\s*[\w.]*(?:chat\.id|chat_id|\.username)\s*\)"
199
+ )
200
+ # S6: Telegram Mini Apps
201
+ INIT_UNSAFE_RX = re.compile(r"\.initDataUnsafe\b")
202
+ SENDS_TO_SERVER_RX = re.compile(r"\bfetch\s*\(|\baxios\b|\.post\s*\(|\.from\(\s*['\"]|\.insert\s*\(")
203
+ # S12: weak signing secrets and API docs
204
+ WEAK_SECRET_VALUES = (r"(?:super-?secret(?:-?key)?|supersecretkey|secret-?key|secret|change-?me|"
205
+ r"your[-_]?(?:jwt[-_]?)?secret(?:[-_]?key)?|my-?secret|jwt-?secret|keyboard cat|123456|password)")
206
+ WEAK_SECRET_RX = re.compile(
207
+ r"(?i)\b(?:jwt|session|auth|cookie|token|signing|app)[_\-]?secret(?:[_\-]?key)?['\"]?\s*[:=]\s*['\"]?" + WEAK_SECRET_VALUES + r"['\"]?(?![\w\-])|"
208
+ r"\bjwt\.sign\s*\([^()]*?,\s*['\"]" + WEAK_SECRET_VALUES + r"['\"]|"
209
+ r"\bsecret\s*:\s*['\"]" + WEAK_SECRET_VALUES + r"['\"]"
210
+ )
211
+ SWAGGER_RX = re.compile(r"swaggerUi\.setup\s*\(|SwaggerModule\.setup\s*\(|@fastify/swagger-ui|\bflasgger\b|\bdrf_yasg\b|SpectacularSwaggerView")
212
+ # S15: account flows
213
+ ACCOUNT_FLOW_RX = re.compile(r"(?i)change-?password|update-?password|change-?email|reset-?password|forgot|\b2fa\b|\bmfa\b|totp|verify-?code|invite|sign-?up|register")
214
+ WEAK_TOKEN_RX = re.compile(
215
+ r"(?i)\b\w*(?:reset|otp|nonce|invite|verif|magic|pin_?code|sms_?code|auth_?code|login_?code)\w*\s*[:=]\s*[^;\n]{0,60}?"
216
+ r"(?:Math\.random\s*\(|\brandom\.(?:randint|random|choice)\s*\()"
217
+ )
218
+ CHANGE_CREDENTIAL_RX = re.compile(r"auth\.updateUser\(\s*\{\s*(?:password|email)\s*:")
219
+ # S16: money and race conditions
220
+ BALANCE_FIELDS = r"(?:balance|credits?|coins|points|bonus(?:es)?|tokens?_?left|quota|stock|wallet|gems|stars)"
221
+ MONEY_FIELDS = r"(?:balance|credits?|coins|bonus(?:es)?|wallet)" # `+=` on these is money; points/stars/stock are often counters
222
+ BALANCE_RMW_RX = re.compile(r"(?i)\b(" + BALANCE_FIELDS + r")\s*:\s*[\w.?\[\]'\"]+?\.\1\s*[-+]|\.(" + MONEY_FIELDS + r")\s*[-+]=")
223
+ DB_WRITE_RX = re.compile(r"\.(?:update|updateMany|save|commit|upsert|set)\s*\(|\bUPDATE\s")
224
+ MONEY_HINT_RX = re.compile(r"(?i)\b" + BALANCE_FIELDS + r"\b|reward|referral|promo|claim")
225
+ ADDS_MONEY_RX = re.compile(r"(?i)" + MONEY_FIELDS + r"\s*:\s*\{\s*increment\b|" + MONEY_FIELDS + r"\s*[:=]\s*[^,}\n]*\+|"
226
+ + MONEY_FIELDS + r"\s*\+=|add_?credits|add_?balance|top_?up")
227
+ IDEMPOTENCY_RX = re.compile(r"(?i)\bunique\b|upsert\s*\(|on\s+conflict|idempot|event\.id\b|payment_?id|transaction_?id|providerPaymentId")
228
+ # S17: agent and MCP configs
229
+ AGENT_CONFIGS = (".mcp.json", "mcp.json", ".cursor/mcp.json", ".vscode/mcp.json", ".windsurf/mcp.json",
230
+ ".gemini/settings.json", ".claude/settings.json", ".claude/settings.local.json")
231
+ CONFIG_LITERAL_RX = re.compile(
232
+ r"(?i)\"([A-Za-z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|DSN|DATABASE_URL|CONNECTION_STRING)[A-Za-z0-9_]*)\"\s*:\s*\"([^\"\s]{12,})\""
233
+ )
234
+ # Telegram bots and Mini Apps (stacks/telegram.md)
235
+ TG_NODE_DEPS = ("grammy", "telegraf", "node-telegram-bot-api", "@telegram-apps/sdk", "@telegram-apps/sdk-react",
236
+ "@telegram-apps/init-data-node", "@tma.js/sdk", "@twa-dev/sdk", "@vkruglikov/react-telegram-web-app")
237
+ TG_PY_DEPS_RX = re.compile(r"(?im)^[\s\"']*(?:aiogram|python-telegram-bot|pytelegrambotapi|telebot|telethon|pyrogram)\b")
238
+ TG_API_IN_CODE_RX = re.compile(r"api\.telegram\.org/(file/)?bot")
239
+ TG_WEBHOOK_HANDLERS = (
240
+ (re.compile(r"SimpleRequestHandler\s*\("), "secret_token"), # aiogram
241
+ (re.compile(r"webhookCallback\s*\("), "secretToken"), # grammY, Telegraf
242
+ (re.compile(r"\blaunch\s*\(\s*\{\s*webhook\b"), "secretToken"), # Telegraf
243
+ (re.compile(r"\bset_?[wW]ebhook\s*\("), "secret_token"), # raw Bot API calls
244
+ )
245
+ TG_SECRET_HEADER_RX = re.compile(r"(?i)x-telegram-bot-api-secret-token")
246
+ TG_INIT_DATA_RX = re.compile(r"\binitData\b|tgWebAppData|['\"`]tma ")
247
+ TG_INIT_PARSE_RX = re.compile(r"URLSearchParams\s*\(|\bparse_qsl?\s*\(|\.get\(\s*['\"]user['\"]\s*\)|\[['\"]user['\"]\]")
248
+ TG_DOWNLOAD_CALL_RX = re.compile(r"(?:fetch|get|request|download\w*|urlopen|open)\s*\(\s*f?[`'\"]?$")
249
+ TG_INIT_VERIFY_RX = re.compile(r"(?i)WebAppData|createHmac|\bhmac\b|safe_parse_webapp_init_data|check_webapp_signature|"
250
+ r"\bvalidate\s*\(|\bisValid\s*\(|verifyInitData|validateInitData")
251
+ TG_PAID_CLIENT_RX = re.compile(r"openInvoice\s*\([\s\S]{0,300}?['\"]paid['\"]")
252
+ TG_SUCCESS_PAYMENT_RX = re.compile(r"successful_payment|successfulPayment")
253
+ TG_PAYMENT_HINT_RX = re.compile(r"successful_payment|successfulPayment|pre_checkout|preCheckout|PreCheckout|sendInvoice|createInvoiceLink|send_invoice|create_invoice_link")
254
+
255
+ # S1: keys deleted from the code but left in git history
256
+ HISTORY_MAX_COMMITS = 1000
257
+ HISTORY_MAX_BYTES = 40_000_000
258
+ HISTORY_SHOWN = 10
259
+ HISTORY_MAX_SECONDS = 20
182
260
 
183
261
 
184
262
  # ------------------------------------------------------------------ helpers
@@ -228,6 +306,133 @@ def git_history_env(root):
228
306
  return []
229
307
 
230
308
 
309
+ def iter_history_lines(root: str) -> Iterator[str]:
310
+ """Changed lines of recent commits (`git log -p`), capped in commits and bytes. Empty without git."""
311
+ cmd = ["git", "-C", root, "log", "--all", "-p", "--no-color", "--no-ext-diff", "-U0",
312
+ f"--max-count={HISTORY_MAX_COMMITS}", "--pretty=format:commit %h", "--", "."]
313
+ cmd += [f":(exclude,glob)**/{name}" for name in SKIP_FILES]
314
+ try:
315
+ proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, errors="replace")
316
+ except Exception:
317
+ return
318
+ read_bytes, deadline = 0, time.monotonic() + HISTORY_MAX_SECONDS
319
+ try:
320
+ for line in proc.stdout:
321
+ read_bytes += len(line)
322
+ if read_bytes > HISTORY_MAX_BYTES or time.monotonic() > deadline:
323
+ break
324
+ yield line.rstrip("\n")
325
+ finally:
326
+ proc.kill()
327
+ proc.stdout.close()
328
+ proc.wait()
329
+
330
+
331
+ def git_history_secrets(root: str, current_values: Set[str]) -> List[Tuple[str, str, str, str]]:
332
+ """Keys in old commits that the current scan did not already report: (path, commit, label, value)."""
333
+ found, seen = [], set(current_values)
334
+ commit = path = ""
335
+ for line in iter_history_lines(root):
336
+ if line.startswith("commit "):
337
+ commit = line[7:].strip()
338
+ continue
339
+ if line.startswith("diff --git "):
340
+ path = line.rsplit(" b/", 1)[-1]
341
+ continue
342
+ if line[:1] not in ("+", "-") or line.startswith(("+++", "---")):
343
+ continue
344
+ if os.path.basename(path).lower().startswith(".env") or TEST_FILE_RX.search(path) or path in AGENT_CONFIGS:
345
+ continue # env files have their own history lead, examples hold no keys; agent configs are S17
346
+ for label, rx, _sev in SECRET_RX:
347
+ for m in rx.finditer(line):
348
+ val = m.group(0)
349
+ if val in seen or PLACEHOLDER_RX.search(val) or FAKE_VALUE_RX.search(val):
350
+ continue
351
+ seen.add(val)
352
+ found.append((path, commit, label, val))
353
+ if len(found) >= HISTORY_SHOWN:
354
+ break
355
+ return found
356
+
357
+
358
+ def scan_agent_configs(root: str, tracked, ignored_dirs: Set[str], ignored_files: Set[str], add) -> Set[str]:
359
+ """S17: keys and database URLs written into agent / MCP configs instead of env vars. Returns the values found."""
360
+ found = set()
361
+ for rel in AGENT_CONFIGS:
362
+ text = read(os.path.join(root, rel))
363
+ if not text:
364
+ continue
365
+ is_tracked = tracked is not None and rel in tracked
366
+ is_ignored = rel in ignored_files or any(rel.startswith(d + "/") for d in ignored_dirs)
367
+ severity = "critical" if is_tracked else ("info" if is_ignored else "high")
368
+ if tracked is None:
369
+ severity, where = "medium", " (no git here: keep it out of any repo you share)"
370
+ else:
371
+ where = " (committed to git)" if is_tracked else (" (gitignored, stays on this machine)" if is_ignored else " (not gitignored: the next commit leaks it)")
372
+ hits = {}
373
+ for label, rx, _sev in SECRET_RX:
374
+ for m in rx.finditer(text):
375
+ if not PLACEHOLDER_RX.search(m.group(0)):
376
+ hits.setdefault(m.group(0), (m.start(), label))
377
+ for m in CONFIG_LITERAL_RX.finditer(text):
378
+ val = m.group(2)
379
+ if "$" in val or "/" in val or "~" in val or PLACEHOLDER_RX.search(val) or any(val in v or v in val for v in hits):
380
+ continue # env references, paths and URLs are not secrets (URLs with passwords match SECRET_RX)
381
+ hits.setdefault(val, (m.start(2), f"value of {m.group(1)}"))
382
+ for val, (pos, label) in hits.items():
383
+ found.add(val)
384
+ note = f"{label} written into the agent config{where}: {mask(val)}. Use ${{ENV_VAR}} instead"
385
+ if label == "Database URL with password":
386
+ if FAKE_VALUE_RX.search(val):
387
+ add("S17", "info", rel, line_of(text, pos), f"local database URL in the agent config: {mask(val)} (fine for a dev database)")
388
+ continue
389
+ note += "; the agent can reach this database, make sure it is a dev one, not production"
390
+ add("S17", severity, rel, line_of(text, pos), note)
391
+ return found
392
+
393
+
394
+ def sql_function_body(text: str, start: int, limit: int) -> str:
395
+ """One CREATE FUNCTION statement: up to the closing dollar quote and `;`, or the next `;` without one."""
396
+ tag = re.compile(r"\$(\w*)\$").search(text, start, limit)
397
+ end = limit
398
+ if tag:
399
+ close = text.find(tag.group(0), tag.end(), limit)
400
+ if close != -1:
401
+ semi = text.find(";", close + len(tag.group(0)), limit)
402
+ end = semi + 1 if semi != -1 else limit
403
+ else:
404
+ semi = text.find(";", start, limit)
405
+ end = semi + 1 if semi != -1 else limit
406
+ return text[start:end]
407
+
408
+
409
+ def scan_sql_doors(rel: str, text: str, uses_rls: bool, add) -> None:
410
+ """S3 views that skip RLS, S4 security definer functions callable through the API."""
411
+ if uses_rls:
412
+ for m in SQL_VIEW_RX.finditer(text):
413
+ name = m.group(1)
414
+ if "security_invoker" in m.group(2).lower():
415
+ continue
416
+ short = name.split(".")[-1].strip('"')
417
+ if re.search(rf"(?is)alter\s+view\s+(?:[\w\"]+\.)?\"?{re.escape(short)}\"?\s+set\s*\(\s*security_invoker", text):
418
+ continue
419
+ add("S3", "medium", rel, line_of(text, m.start()),
420
+ f"view {name} runs with its owner's rights and skips RLS: add with (security_invoker = true) or keep it out of the API")
421
+ starts = list(SQL_FUNCTION_RX.finditer(text))
422
+ for i, m in enumerate(starts):
423
+ body = sql_function_body(text, m.start(), starts[i + 1].start() if i + 1 < len(starts) else len(text))
424
+ if not re.search(r"(?i)security\s+definer", body) or re.search(r"(?i)returns\s+trigger", body):
425
+ continue
426
+ if SQL_CALLER_CHECK_RX.search(body):
427
+ continue
428
+ name = m.group(1)
429
+ short = name.split(".")[-1].strip('"')
430
+ if re.search(rf"(?is)revoke\s+(?:all|execute)[^;]*function\s+(?:public\.)?\"?{re.escape(short)}\b[^;]*\bfrom\b[^;]*\b(?:public|authenticated)\b", text):
431
+ continue
432
+ add("S4", "medium", rel, line_of(text, m.start()),
433
+ f"security definer function {name} skips RLS and anyone can call it via /rpc: check auth.uid() inside or revoke execute")
434
+
435
+
231
436
  def is_env_file(name):
232
437
  n = name.lower()
233
438
  if not (n == ".env" or n.startswith(".env.") or n.endswith(".env")):
@@ -253,6 +458,8 @@ def iter_files(root: str, ignored_dirs: Set[str] = frozenset(), ignored_files: S
253
458
  ext = os.path.splitext(f)[1].lower()
254
459
  if ext not in TEXT_EXT and not is_env_file(f) and f not in ("Dockerfile", ".gitignore"):
255
460
  continue
461
+ if BUILD_ASSET_RX.search(rel_of(dirpath, f)):
462
+ continue
256
463
  try:
257
464
  if os.path.getsize(path) > MAX_BYTES:
258
465
  continue
@@ -296,6 +503,20 @@ def is_client_file(rel, text, project):
296
503
  return False
297
504
 
298
505
 
506
+ def workspace_manifests(root: str) -> List[str]:
507
+ """Dependency manifests at the root and one folder down (monorepos: apps/*, packages/*, backend/...)."""
508
+ names = ("package.json", "requirements.txt", "pyproject.toml", "Pipfile")
509
+ dirs = [root]
510
+ for top in sorted(os.listdir(root)) if os.path.isdir(root) else []:
511
+ sub = os.path.join(root, top)
512
+ if top in SKIP_DIRS or top.startswith(".") or not os.path.isdir(sub):
513
+ continue
514
+ dirs.append(sub)
515
+ if top in ("apps", "packages", "services"):
516
+ dirs += [os.path.join(sub, d) for d in sorted(os.listdir(sub)) if os.path.isdir(os.path.join(sub, d))]
517
+ return [os.path.join(d, n) for d in dirs for n in names if os.path.isfile(os.path.join(d, n))]
518
+
519
+
299
520
  def detect_project(root):
300
521
  info = {"stack": [], "spa": False}
301
522
  pkg = read(os.path.join(root, "package.json"))
@@ -333,6 +554,9 @@ def detect_project(root):
333
554
  info["stack"].append("Charts")
334
555
  if has("@lemonsqueezy/lemonsqueezy.js", "@paddle/paddle-js", "@paddle/paddle-node-sdk"): info["stack"].append("Payments")
335
556
  if has("next-auth", "@auth/core", "better-auth", "lucia"): info["stack"].append("Auth library")
557
+ manifests = "".join(read(path) or "" for path in workspace_manifests(root))
558
+ if has(*TG_NODE_DEPS) or TG_PY_DEPS_RX.search(manifests) or any(f'"{d}"' in manifests for d in TG_NODE_DEPS):
559
+ info["stack"].append("Telegram")
336
560
  if os.path.exists(os.path.join(root, "vercel.json")): info["stack"].append("Vercel")
337
561
  if os.path.exists(os.path.join(root, "netlify.toml")): info["stack"].append("Netlify")
338
562
  if os.path.exists(os.path.join(root, "Dockerfile")) or os.path.exists(os.path.join(root, "docker-compose.yml")): info["stack"].append("Docker")
@@ -378,6 +602,72 @@ def scan_server_code(rel, text, add):
378
602
  break
379
603
  for m in STACK_LEAK_RX.finditer(text):
380
604
  add("S12", "medium", rel, line_of(text, m.start()), "stack trace sent in the response: return a generic error, log details on the server")
605
+ m = BALANCE_RMW_RX.search(text)
606
+ if m and DB_WRITE_RX.search(text):
607
+ add("S16", "high", rel, line_of(text, m.start()),
608
+ "balance read in code, changed and written back: two requests at once both pass, change it in one database statement")
609
+ m = WEAK_TOKEN_RX.search(text)
610
+ if m:
611
+ add("S15", "medium", rel, line_of(text, m.start()),
612
+ "reset token / code made with a non-crypto random: use crypto.randomBytes / secrets, store it hashed, expire it")
613
+
614
+
615
+ def scan_telegram(rel: str, text: str, client: bool, add) -> None:
616
+ """Telegram leads: token in the browser, webhook without a secret, unverified initData, Stars delivery."""
617
+ m = TG_API_IN_CODE_RX.search(text)
618
+ if m and client:
619
+ add("S2", "critical", rel, line_of(text, m.start()), "Bot API called from browser code: the bot token ships to every visitor")
620
+ elif m and m.group(1) and not TG_DOWNLOAD_CALL_RX.search(text[max(0, m.start() - 40):m.start()].rstrip("htps:/")):
621
+ add("S2", "medium", rel, line_of(text, m.start()),
622
+ "Telegram file link holds the bot token: don't send it to users, download on the server and serve the file")
623
+ if client:
624
+ m = TG_PAID_CLIENT_RX.search(text)
625
+ if m:
626
+ add("S7", "medium", rel, line_of(text, m.start()),
627
+ "Mini App reacts to invoice status 'paid': grant the purchase only in the bot's successful_payment handler")
628
+ return
629
+ if not TG_SECRET_HEADER_RX.search(text):
630
+ for rx, option in TG_WEBHOOK_HANDLERS:
631
+ m = rx.search(text)
632
+ if m and option not in text[m.start():m.start() + 400]:
633
+ add("S4", "high", rel, line_of(text, m.start()),
634
+ f"Telegram webhook without a secret token: anyone can send fake updates. Set {option} and check X-Telegram-Bot-Api-Secret-Token")
635
+ break
636
+ m = TG_INIT_DATA_RX.search(text) if TG_INIT_PARSE_RX.search(text) else None
637
+ if m and not TG_INIT_VERIFY_RX.search(text):
638
+ add("S6", "high", rel, line_of(text, m.start()),
639
+ "Mini App initData read on the server without checking its hash: anyone can claim any Telegram id")
640
+ elif m and "WebAppData" in text and "auth_date" not in text:
641
+ add("S6", "info", rel, line_of(text, m.start()), "initData hash checked, but not its age: reject old auth_date")
642
+ m = TG_SUCCESS_PAYMENT_RX.search(text)
643
+ if m and "telegram_payment_charge_id" not in text and "telegramPaymentChargeId" not in text:
644
+ add("S16", "medium", rel, line_of(text, m.start()),
645
+ "payment handler doesn't save telegram_payment_charge_id: needed for refunds, and to stop double delivery (unique)")
646
+
647
+
648
+ def scan_app_doors(rel: str, text: str, client: bool, add) -> None:
649
+ """Leads in any app code: bot admin checks (S4), Mini App identity (S6), API docs (S12), credential changes (S15)."""
650
+ m = BOT_ADMIN_RX.search(text)
651
+ if m:
652
+ group = "group" in text[m.start():m.end() + 20].lower()
653
+ add("S4", "info" if group else "medium", rel, line_of(text, m.start()),
654
+ "admin check on an admin group's chat id: fine if only admins are in that group, else check from_user.id" if group else
655
+ "admin check on chat id or username: in a group every member passes, usernames change. Check the sender's from_user.id")
656
+ m = INIT_UNSAFE_RX.search(text)
657
+ if m and not client and is_server_route(rel, text):
658
+ add("S6", "high", rel, line_of(text, m.start()),
659
+ "server reads initDataUnsafe, which nobody signed: verify the raw initData hash with the bot token")
660
+ elif m and SENDS_TO_SERVER_RX.search(text):
661
+ add("S6", "medium", rel, line_of(text, m.start()),
662
+ "Mini App sends initDataUnsafe data to the server: send the raw initData and verify its hash there (fine for display only)")
663
+ m = SWAGGER_RX.search(text)
664
+ if m:
665
+ add("S12", "info", rel, line_of(text, m.start()),
666
+ "API docs served: hide them in production or put them behind login if they list internal routes")
667
+ m = CHANGE_CREDENTIAL_RX.search(text)
668
+ if m:
669
+ add("S15", "info", rel, line_of(text, m.start()),
670
+ "password/email change: check the current password is asked (Supabase: Secure password change on)")
381
671
 
382
672
 
383
673
  def plan_hints(rel, name, ext, text, is_code, client):
@@ -396,6 +686,16 @@ def plan_hints(rel, name, ext, text, is_code, client):
396
686
  checks.add("S8")
397
687
  if DEBUG_ROUTE_RX.search(low):
398
688
  checks.add("S12")
689
+ if ACCOUNT_FLOW_RX.search(low) or ACCOUNT_FLOW_RX.search(text[:2000]):
690
+ checks.add("S15")
691
+ if MONEY_HINT_RX.search(text):
692
+ checks.add("S16")
693
+ if TG_PAYMENT_HINT_RX.search(text):
694
+ checks.update(("S7", "S16"))
695
+ if TG_INIT_DATA_RX.search(text) and not client:
696
+ checks.add("S6")
697
+ if BOT_ADMIN_RX.search(text) or re.search(r"(?i)(?:Command|command)\(\s*['\"](?:admin|ban|broadcast|stats|users)", text):
698
+ checks.add("S4")
399
699
  if client and (AI_USE_RX.search(text) or "process.env" in text or "import.meta.env" in text):
400
700
  checks.add("S2")
401
701
  if client and re.search(r"(?i)useSearchParams|searchParams|[?&]success", text) and re.search(r"(?i)\.update\(|\bplan\b|premium|isPro", text):
@@ -470,6 +770,8 @@ def scan(root, max_examples):
470
770
  add("S1", "high", p, 0, "env file was committed in git history (deleted now, keys still in history: rotate them)")
471
771
  if project["has_package_json"] and not project["has_lockfile"]:
472
772
  add("S13", "info", "package.json", 0, "no lockfile: installs are not reproducible")
773
+ secret_values = scan_agent_configs(root, tracked, ignored_dirs, ignored_files, add)
774
+ uses_rls = "Supabase" in project["stack"]
473
775
 
474
776
  big_files = []
475
777
  totals = {"C1": 0, "C3": 0}
@@ -479,6 +781,8 @@ def scan(root, max_examples):
479
781
 
480
782
  for path in iter_files(root, ignored_dirs, ignored_files):
481
783
  rel = os.path.relpath(path, root)
784
+ if rel.replace(os.sep, "/") in AGENT_CONFIGS:
785
+ continue # scanned by scan_agent_configs (S17)
482
786
  name = os.path.basename(path)
483
787
  ext = os.path.splitext(name)[1].lower()
484
788
  text = read(path)
@@ -504,7 +808,7 @@ def scan(root, max_examples):
504
808
  for label, rx, sev in SECRET_RX:
505
809
  for m in rx.finditer(text):
506
810
  val = m.group(0)
507
- if PLACEHOLDER_RX.search(val):
811
+ if PLACEHOLDER_RX.search(val) or (label == "Telegram bot token" and FAKE_VALUE_RX.search(val)):
508
812
  continue
509
813
  s = sev
510
814
  if is_doc and s == "critical":
@@ -516,6 +820,9 @@ def scan(root, max_examples):
516
820
  note = f"{label}: {mask(val)}"
517
821
  if label == "Google API key":
518
822
  note += " (often a public Firebase/Maps key: check it is restricted in Google Cloud)"
823
+ elif label == "Telegram bot token":
824
+ note += " (anyone can run your bot and read its chats: @BotFather → /revoke)"
825
+ secret_values.add(val)
519
826
  add("S1", s, rel, line_of(text, m.start()), note)
520
827
  for m in JWT_RX.finditer(text):
521
828
  if jwt_role(m.group(0)) == "service_role":
@@ -527,6 +834,17 @@ def scan(root, max_examples):
527
834
  for m in FALLBACK_SECRET_RX.finditer(text):
528
835
  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")
529
836
 
837
+ # S12 weak or default signing secrets
838
+ low = rel.replace("\\", "/").lower()
839
+ if not is_example_env and not TEST_FILE_RX.search(low):
840
+ m = WEAK_SECRET_RX.search(text)
841
+ if m:
842
+ untracked_env = is_env and (tracked is None or rel.replace(os.sep, "/") not in tracked)
843
+ sev = "info" if is_doc or is_data else ("medium" if untracked_env else "critical")
844
+ note = ("weak or default signing secret: anyone can sign their own login token, generate one with `openssl rand -hex 32`"
845
+ if not untracked_env else "weak signing secret in a local env file: production must use a different, random value")
846
+ add("S12", sev, rel, line_of(text, m.start()), note)
847
+
530
848
  # S2 public-prefixed secret env names
531
849
  for m in PUBLIC_PREFIX_RX.finditer(text):
532
850
  var = m.group(0)
@@ -543,8 +861,8 @@ def scan(root, max_examples):
543
861
  break
544
862
 
545
863
  # S3 database rules
546
- low = rel.replace("\\", "/").lower()
547
864
  if ext == ".sql":
865
+ scan_sql_doors(rel, text, uses_rls or bool(re.search(r"(?i)row\s+level\s+security|auth\.uid", text)), add)
548
866
  for m in re.finditer(r"(?is)create\s+table\s+(?:if\s+not\s+exists\s+)?(?:public\.)?\"?(\w+)\"?", text):
549
867
  table = m.group(1)
550
868
  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):
@@ -579,10 +897,12 @@ def scan(root, max_examples):
579
897
  if "webhook" in low or "webhook" in text[:2000].lower():
580
898
  if not WEBHOOK_VERIFY_RX.search(text):
581
899
  add("S7", "critical", rel, 1, "webhook handler with no signature verification found")
900
+ if ADDS_MONEY_RX.search(text) and not IDEMPOTENCY_RX.search(text):
901
+ add("S16", "medium", rel, 1, "webhook adds credits/balance without saving the payment id: a resent webhook pays twice")
582
902
  elif writes and not auth_endpoint and not AUTH_HINT_RX.search(text):
583
903
  add("S4", "high", rel, 1, "server route/action changes data, no login check found in this file (check middleware)")
584
904
  if (AI_USE_RX.search(text) or EMAIL_USE_RX.search(text) or auth_endpoint) and not RATELIMIT_HINT_RX.search(text):
585
- add("S8", "medium", rel, 1, "AI / email / auth endpoint with no rate limit found in this file")
905
+ add("S8", "medium", rel, 1, "AI / email / SMS / auth endpoint with no rate limit found in this file")
586
906
  if DEBUG_ROUTE_RX.search(low) and (is_server_route(rel, text) or "/pages/" in low or "/app/" in low):
587
907
  add("S12", "medium", rel, 1, "debug/seed/test route: delete or protect before launch")
588
908
  for ln in sorted({line_of(text, m.start()) for m in TEST_CRED_RX.finditer(text)}):
@@ -590,6 +910,10 @@ def scan(root, max_examples):
590
910
  "test credentials in a test file (fine if never used in production)" if is_test else "hard-coded test credentials")
591
911
  if not is_test and not client:
592
912
  scan_server_code(rel, text, add)
913
+ if not is_test:
914
+ scan_app_doors(rel, text, client, add)
915
+ if "Telegram" in project["stack"]:
916
+ scan_telegram(rel, text, client, add)
593
917
 
594
918
  # S9 sinks
595
919
  for rx, label in DANGEROUS_SINKS:
@@ -642,6 +966,11 @@ def scan(root, max_examples):
642
966
  for n_lines, rel in sorted(big_files, reverse=True):
643
967
  add("C6", "cleanup", rel, 0, f"{n_lines} lines")
644
968
 
969
+ if tracked is not None:
970
+ for path, commit, label, val in git_history_secrets(root, secret_values):
971
+ add("S1", "high", path, 0,
972
+ f"{label} in git history (commit {commit}): deleting it from the code does not remove it from history, rotate it: {mask(val)}")
973
+
645
974
  for f in findings:
646
975
  f["file"] = f["file"].replace(os.sep, "/")
647
976
  project["size"] = {"files": n_files, "lines": n_lines_total, "class": size_class(n_files, n_lines_total)}
@@ -655,7 +984,8 @@ def scan(root, max_examples):
655
984
 
656
985
  ICONS = {"critical": "🔴", "high": "🟠", "medium": "🟡", "cleanup": "⚪", "info": "💡"}
657
986
  NOT_COVERED = ("Regex covers only simple forms of S5, S6, S7 (premium unlocked in the browser), S11 and "
658
- "per-column Supabase policies: read the plan. S13: run `npm audit --omit=dev`.")
987
+ "per-column Supabase policies: read the plan. S13: run `npm audit --omit=dev`. "
988
+ "S15-S17 mostly need reading: account flows, atomic balance updates, which database the agent reaches.")
659
989
  CLEANUP_UNITS = {"C1": "console.log/debugger", "C3": "TODO/FIXME or empty handlers"}
660
990
 
661
991
 
@@ -54,7 +54,8 @@ S7 payments (no payments in this app), server guide (hosted on Vercel)
54
54
 
55
55
  ## 📋 Only you can do this
56
56
  - [ ] Rotate the OpenAI key: platform.openai.com → API keys
57
- - [ ] Set a monthly spending limit with your AI provider
57
+ - [ ] Set a hard monthly spending limit with your AI provider (and the SMS gateway, if you send codes)
58
+ - [ ] Turn on backups and restore one into a test database once; the coding agent uses only a dev database
58
59
  - [ ] Supabase → Advisors → Security Advisor: fix every red item
59
60
  - [ ] If "Live database: NOT checked": run `checks/supabase_check.sql` in the SQL Editor (or paste your Firebase rules) and send me the result
60
61