periderm-cli 0.1.77 → 0.1.79

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
@@ -1,26 +1,74 @@
1
1
  # periderm-cli
2
2
 
3
- Pre-launch scanner for web and mobile codebases — context-aware checks for JS, TS, Flutter, React Native, and Swift.
4
-
5
- ## Install
6
-
7
- **Important:** This is a CLI tool and must be installed globally.
3
+ **The pre-launch scanner for apps built with AI.** One command checks your codebase for the problems that lose users, drain your wallet or get you sued — then tells you exactly how to fix each one.
8
4
 
9
5
  ```bash
10
6
  npm install -g periderm-cli
7
+ periderm login
8
+ periderm scan
11
9
  ```
12
10
 
13
- Or use the install script from your Periderm dashboard docs (`curl -fsSL https://periderm-cli.vercel.app//install.sh | bash`).
11
+ You get a verdict (**LAUNCH READY**, **HOLD** or **DO NOT LAUNCH**), a 0–100 launch confidence score, and a report where every finding has the file and line, why it matters, the exact fix, and a prompt you can paste into Cursor, Claude Code or ChatGPT.
12
+
13
+ Your code is scanned on your machine — it is not uploaded.
14
+
15
+ ## Why
16
+
17
+ AI coding tools write code that runs. They also routinely ship:
18
+
19
+ - API keys and secrets in client code
20
+ - routes and Supabase functions anyone can call without logging in
21
+ - `catch {}` blocks that swallow errors so failures are invisible
22
+ - polling loops and recursion that run up your cloud bill
23
+ - a privacy policy that says one thing while the code does another
24
+
25
+ Linters, type checkers and dependency scanners don't look for these. Periderm does.
26
+
27
+ ## What it checks (150+ checks)
28
+
29
+ | Area | Examples |
30
+ | --- | --- |
31
+ | Security | hardcoded secrets, missing authorization, Supabase `SECURITY DEFINER` functions open to `anon`, XSS via `dangerouslySetInnerHTML`, client-trusted user IDs |
32
+ | Reliability | silent catch blocks, unhandled fetches, effects without cleanup, missing loading and error states |
33
+ | Cost | `setInterval` polling against your database or API, unbounded recursion |
34
+ | Legal | policy vs code contradictions, GDPR/CCPA wording, COPPA age gate at signup, Google Fonts from Google's CDN (GDPR), session replay without consent (CIPA), marketing email without unsubscribe (CAN-SPAM), subscriptions without auto-renewal terms, uploads without a DMCA policy |
35
+ | SEO & polish | titles, descriptions, Open Graph, favicon, robots.txt, placeholder text, dead links |
36
+ | Code quality | an ML defect predictor (trained on the PROMISE dataset) flags your most complex files |
14
37
 
15
- ## Quick start
38
+ Works with JavaScript, TypeScript, React, Next.js, TanStack, Supabase, Firebase, React Native / Expo, Flutter and Swift.
39
+
40
+ ## Make your AI coding agent check its own work
16
41
 
17
42
  ```bash
18
- periderm login # authenticate once
19
- periderm scan # scan + upload to your dashboard
20
- periderm watch # rerun on file change
21
- periderm whoami # show current token + plan
43
+ periderm agents
22
44
  ```
23
45
 
24
- ## Project context
46
+ Adds a short rule to `AGENTS.md` (and with `--all`: `CLAUDE.md`, Cursor, Copilot and Windsurf rule files) so your agent runs `periderm scan` after every change and keeps fixing findings until the verdict is LAUNCH READY.
47
+
48
+ ## Commands
49
+
50
+ | Command | What it does |
51
+ | --- | --- |
52
+ | `periderm scan` | Scan the current project and save the report to your dashboard (`--local` to keep it on your machine) |
53
+ | `periderm review --deep` | AI agent review for edge cases static checks miss (Scale / Unlimited) |
54
+ | `periderm agents` | Install the "always scan before you're done" rule for AI coding agents |
55
+ | `periderm watch` | Re-scan when files change |
56
+ | `periderm login` / `logout` / `whoami` | Manage the linked account |
57
+
58
+ Reports are written to `.periderm/last-report.md` and `.periderm/last-report.json`.
59
+
60
+ ## Free Lighthouse score checker
61
+
62
+ Check any live site's performance, accessibility, best practices and SEO scores — with Core Web Vitals and an AI fix plan — at [periderm-cli.vercel.app/lighthouse](https://periderm-cli.vercel.app/lighthouse). No account needed.
63
+
64
+ ## Pricing
65
+
66
+ - **Starter** — free: unlimited local scans, 15 cloud scans a month
67
+ - **Scale** — $9 one-time: 100 scan credits that never expire, AI reviewer, deep review
68
+ - **Unlimited** — $19/month or $190/year
69
+
70
+ ## Links
25
71
 
26
- Full docs live on your Periderm dashboard at `/docs`.
72
+ - Website & dashboard: https://periderm-cli.vercel.app
73
+ - Docs: https://periderm-cli.vercel.app/docs
74
+ - For AI assistants: https://periderm-cli.vercel.app/llms.txt
package/dist/index.js CHANGED
@@ -60,6 +60,7 @@ program
60
60
  .command("scan")
61
61
  .description("Scan the current directory and write a markdown report.")
62
62
  .option("--cwd <dir>", "Directory to scan", process.cwd())
63
+ .option("--local", "Scan without uploading results to the dashboard")
63
64
  .action(async (opts) => {
64
65
  const root = path.resolve(opts.cwd);
65
66
  const cfg = readConfig();
@@ -166,7 +167,10 @@ program
166
167
  if (!(await hasAgentRules(root))) {
167
168
  console.info(chalk.dim(" tip: run `periderm agents` so AI coding agents (Cursor, Claude Code, Copilot, Codex…) always scan & fix before saying they're done."));
168
169
  }
169
- if (!cfg.token) {
170
+ if (opts.local) {
171
+ console.info(chalk.dim(" local-only scan: results were not uploaded to your dashboard."));
172
+ }
173
+ else if (!cfg.token) {
170
174
  console.info(chalk.yellow("no token configured — run `periderm login` first to sync to dashboard."));
171
175
  }
172
176
  else {
@@ -210,7 +214,7 @@ program
210
214
  });
211
215
  program
212
216
  .command("review")
213
- .description("Run AI deep review on the last scan (Scale/Unlimited). Requires GROQ_API_KEY.")
217
+ .description("Run the AI deep review on the last scan (Scale/Unlimited plans).")
214
218
  .option("--deep", "Run the AI agent deep review")
215
219
  .option("--cwd <dir>", "Project directory", process.cwd())
216
220
  .action(async (opts) => {
@@ -298,7 +302,11 @@ program
298
302
  await run();
299
303
  try {
300
304
  const watcher = fs.watch(root, { recursive: true });
301
- for await (const _ of watcher) {
305
+ for await (const ev of watcher) {
306
+ // Dependency installs, git operations and build output would otherwise re-scan constantly.
307
+ if (ev.filename &&
308
+ /(^|[\\/])(node_modules|\.git|\.periderm|dist|build|\.next|\.output|\.vercel|coverage)([\\/]|$)/.test(ev.filename))
309
+ continue;
302
310
  if (scheduled)
303
311
  clearTimeout(scheduled);
304
312
  scheduled = setTimeout(run, 400);
@@ -311,7 +319,7 @@ program
311
319
  });
312
320
  program
313
321
  .command("login")
314
- .description("Open the dashboard to grab a CLI token, then paste it here.")
322
+ .description("Link the CLI to your Periderm account in the browser.")
315
323
  .action(async () => {
316
324
  const cfg = readConfig();
317
325
  const apiUrl = cfg.apiUrl;
@@ -455,7 +463,7 @@ program
455
463
  });
456
464
  program
457
465
  .command("whoami")
458
- .description("Verify the current token.")
466
+ .description("Show the linked account, plan and remaining scans.")
459
467
  .action(async () => {
460
468
  const cfg = readConfig();
461
469
  if (!cfg.token) {
@@ -31,10 +31,10 @@ export function renderMarkdown(r) {
31
31
  lines.push(`- **AI context triage:** enabled${r.meta.contextFilteredCount ? ` · ${r.meta.contextFilteredCount} finding(s) filtered as not applicable` : ""}`);
32
32
  }
33
33
  if (r.meta.mlPredictorLoaded) {
34
- lines.push(`- **ML defect predictor:** PROMISE-trained ONNX model loaded (check id \`ai-defect-prediction\`)`);
34
+ lines.push(`- **ML defect predictor:** PROMISE-trained Random Forest loaded (check id \`ai-defect-prediction\`)`);
35
35
  }
36
36
  else {
37
- lines.push(`- **ML defect predictor:** not loaded (model file or ONNX runtime missing — findings will not include \`ai-defect-prediction\`)`);
37
+ lines.push(`- **ML defect predictor:** not loaded (model file missing — findings will not include \`ai-defect-prediction\`)`);
38
38
  }
39
39
  lines.push("");
40
40
  }
@@ -135,8 +135,9 @@ export function renderMarkdown(r) {
135
135
  lines.push(`You are reviewing a Periderm CLI scan: Launch Confidence ${r.scores.confidence}/100, Reality ${r.scores.reality}/100, Perceived ${r.scores.perceived}/100 — verdict ${verdictLabel}.`);
136
136
  lines.push(`There are ${r.counts.critical} critical, ${r.counts.high} high, ${r.counts.medium} medium, ${r.counts.low} low findings.`);
137
137
  lines.push(`Fix them in priority order. For each finding, open the listed file, apply the Exact fix, and keep the change minimal.`);
138
- const aiInstructionsPath = process.cwd() + "/.periderm/ai-instructions.md";
139
- lines.push(`IMPORTANT: Before you begin, read the instructions in \`${aiInstructionsPath}\` for the full iterative process on how to run the scanner, verify fixes, and handle any authentication requirements.`);
138
+ // Relative to the project root, so it is valid on the user's machine (web scans run on a server).
139
+ const aiInstructionsPath = ".periderm/ai-instructions.md";
140
+ lines.push(`IMPORTANT: Before you begin, read the instructions in \`${aiInstructionsPath}\` (in the project root; run \`periderm scan\` once if it is missing) for the full iterative process on how to run the scanner, verify fixes, and handle any authentication requirements.`);
140
141
  lines.push("```");
141
142
  lines.push("");
142
143
  // Hidden watermark — only visible in raw .md source
@@ -113,7 +113,7 @@ Evidence rules (false positives destroy trust — a wrong finding is worse than
113
113
 
114
114
  Known NON-issues — never report these:
115
115
  - requestAnimationFrame / setTimeout loops that re-schedule themselves (e.g. Lenis, GSAP, Framer Motion "raf" loops). They are async and do not grow the stack; a cancelAnimationFrame/clearTimeout in cleanup is the complete fix.
116
- - Static asset CDNs (Google Fonts / fonts.googleapis.com / fonts.gstatic.com, jsDelivr, unpkg, cdnjs, Font Awesome) are NOT analytics, tracking or "data sharing", and do not need to be listed as third-party trackers in a privacy policy.
116
+ - Static asset CDNs (jsDelivr, unpkg, cdnjs, Font Awesome) are NOT analytics, tracking or "data sharing". Google Fonts' GDPR IP-transfer risk is already covered by the static check \`google-fonts-cdn\`; do not report it again or call it "tracking".
117
117
  - Tailwind/CSS class names (bg-*, text-*, heading-*) are not tracking IDs.
118
118
  - Self-hosted fonts via @fontsource are not third-party at all.${orgRulesSection}`;
119
119
  const context = {
@@ -67,6 +67,9 @@ const silentCatch = (source, file, ast) => {
67
67
  const catchSrc = source.slice(p.node.start ?? 0, p.node.end ?? 0);
68
68
  if (/periderm-ignore|keep original|ignore auth|unauthenticated|fallback/i.test(catchSrc))
69
69
  return;
70
+ // Like ESLint's no-empty: an empty catch with an explanatory comment is a deliberate choice.
71
+ if (body.length === 0 && (p.node.body.innerComments?.length ?? 0) > 0)
72
+ return;
70
73
  if (body.length === 0) {
71
74
  out.push(mkFinding({
72
75
  id: "silent-catch",
@@ -317,7 +320,17 @@ const dangerousHtml = (source, file) => {
317
320
  const expr = m[1].trim();
318
321
  const isLiteral = /^["'`]/.test(expr);
319
322
  const hasSanitize = /DOMPurify\.sanitize/.test(source);
320
- if (!isLiteral && !hasSanitize) {
323
+ // Structured data: <script type="application/ld+json"> filled with JSON.stringify(...) is the
324
+ // standard, safe way to embed JSON-LD (especially with "<" escaped).
325
+ // Only look at this element's own opening tag and this value — never neighbouring code.
326
+ const ownTag = source.slice(source.lastIndexOf("<", m.index), m.index);
327
+ // The value may be built inline or in a constant: `const LD = JSON.stringify(...)`.
328
+ const builtWithStringify = /JSON\.stringify\s*\(/.test(expr) ||
329
+ (/^[A-Za-z_$][\w$]*$/.test(expr) &&
330
+ new RegExp(`\\b(?:const|let|var)\\s+${expr}\\s*=\\s*JSON\\.stringify\\s*\\(`).test(source));
331
+ const isJsonLd = /application\/ld\+json/.test(ownTag) && builtWithStringify;
332
+ const escapesTags = /JSON\.stringify\s*\([^)]*\)\s*\.replace\(\s*\/<\/g/.test(expr);
333
+ if (!isLiteral && !hasSanitize && !isJsonLd && !escapesTags) {
321
334
  out.push(mkFinding({
322
335
  id: "dangerous-html",
323
336
  category: "Security",
@@ -537,10 +550,34 @@ const unhandledFetch = (source, file, ast) => {
537
550
  const callee = p.node.callee;
538
551
  if (callee.type !== "Identifier" || callee.name !== "fetch")
539
552
  return;
553
+ // A helper that just returns the fetch promise leaves handling to its (awaiting) callers.
554
+ let up = p.parentPath;
555
+ while (up && up.node.type === "AwaitExpression")
556
+ up = up.parentPath;
557
+ if (up &&
558
+ (up.node.type === "ReturnStatement" || up.node.type === "ArrowFunctionExpression")) {
559
+ return;
560
+ }
540
561
  let cur = p;
541
562
  while (cur) {
542
563
  if (cur.node?.type === "TryStatement")
543
564
  return;
565
+ // Server handlers: a thrown network error becomes an error response, not a silent UI break.
566
+ if (cur.node?.type === "CallExpression") {
567
+ const c = cur.node.callee;
568
+ if (c?.type === "MemberExpression" &&
569
+ c.property?.type === "Identifier" &&
570
+ /^(handler|server|middleware|loader|action)$/.test(c.property.name))
571
+ return;
572
+ }
573
+ if ((cur.node?.type === "ObjectProperty" || cur.node?.type === "ObjectMethod") &&
574
+ cur.node.key?.type === "Identifier" &&
575
+ /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS|loader|action)$/.test(cur.node.key.name))
576
+ return;
577
+ if (cur.node?.type === "FunctionDeclaration" &&
578
+ /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS|loader|action)$/.test(cur.node.id?.name ?? "") &&
579
+ cur.parentPath?.node?.type?.startsWith("Export"))
580
+ return;
544
581
  if (cur.node?.type === "CallExpression") {
545
582
  const c = cur.node.callee;
546
583
  if (c?.type === "MemberExpression" &&
@@ -560,8 +597,7 @@ const unhandledFetch = (source, file, ast) => {
560
597
  while ((m = re.exec(source))) {
561
598
  const before = source.slice(Math.max(0, m.index - 2500), m.index);
562
599
  const after = source.slice(m.index, m.index + 400);
563
- const handled = /\.catch\s*\(/.test(before + after) ||
564
- /try\s*\{/.test(before);
600
+ const handled = /\.catch\s*\(/.test(before + after) || /try\s*\{/.test(before);
565
601
  if (!handled)
566
602
  push(lineOf(source, m.index));
567
603
  }
@@ -699,6 +735,50 @@ const idorDataFetch = (source, file) => {
699
735
  return out;
700
736
  };
701
737
  // ───────────────────────────────────────────────────────────────────────
738
+ // 20b. Server code that trusts a user id sent by the browser
739
+ // ───────────────────────────────────────────────────────────────────────
740
+ // `.eq("user_id", data.userId)` looks like an ownership check, but when `data` is the request
741
+ // payload the caller simply sends someone else's id and gets (or deletes) their rows.
742
+ const CLIENT_USER_ID_RE = /\.eq\(\s*["'](?:user_id|owner_id|userId)["']\s*,\s*(?:data|body|input|args|payload|params|req\.body|request\.body)\.(?:userId|user_id|uid|ownerId)\s*\)|\buser_id\s*:\s*(?:data|body|input|args|payload)\.(?:userId|user_id|uid)\b/g;
743
+ const AUTH_EVIDENCE_RE = /\.middleware\(\s*\[[^\]]*(?:auth|Auth|session|Session)|requireAuth|requireSupabaseAuth|withAuth|getServerSession|auth\(\)|\.auth\.getUser\(|verifyToken|cli_tokens|context\.userId\s*!==|!==\s*context\.userId/;
744
+ const clientTrustedUserId = (source, file) => {
745
+ const out = [];
746
+ if (!/\.(ts|tsx|js|jsx|mjs)$/.test(file))
747
+ return out;
748
+ if (!CLIENT_USER_ID_RE.test(source))
749
+ return out;
750
+ CLIENT_USER_ID_RE.lastIndex = 0;
751
+ // Judge each server function on its own: auth on one function doesn't protect its neighbour.
752
+ const starts = [...source.matchAll(/createServerFn\s*\(/g)].map((m) => m.index ?? 0);
753
+ const blocks = starts.length > 0
754
+ ? starts.map((st, i) => [st, starts[i + 1] ?? source.length])
755
+ : /server\s*:\s*\{\s*handlers|export\s+(?:async\s+)?function\s+(?:GET|POST|PUT|PATCH|DELETE)\b/.test(source) || /(^|\/)api\//.test(file)
756
+ ? [[0, source.length]]
757
+ : [];
758
+ for (const [from, to] of blocks) {
759
+ const block = source.slice(from, to);
760
+ if (AUTH_EVIDENCE_RE.test(block))
761
+ continue;
762
+ const m = new RegExp(CLIENT_USER_ID_RE.source).exec(block);
763
+ if (!m)
764
+ continue;
765
+ const line = lineOf(source, from + m.index);
766
+ out.push(mkFinding({
767
+ id: "client-trusted-user-id",
768
+ category: "Security",
769
+ severity: "critical",
770
+ file,
771
+ line,
772
+ message: "Server code uses a user ID sent by the browser to decide whose data to read or change.",
773
+ why: "Anyone can send another user's ID in the request and read, overwrite or delete that user's data. Filtering by user_id only protects you if the id comes from the verified session, not the request.",
774
+ fix: "Require authentication on this function (e.g. an auth middleware) and take the user id from the verified session (context.userId / auth.uid()), never from the request body.",
775
+ aiPrompt: `In ${file} near line ${line}, a server function filters or writes rows using a user id taken from the request payload. Add the project's auth middleware to this function, remove userId from its input, and use the authenticated user's id from the session instead. Check every other server function in the file for the same pattern.`,
776
+ }));
777
+ break; // one finding per file is enough to fix the pattern
778
+ }
779
+ return out;
780
+ };
781
+ // ───────────────────────────────────────────────────────────────────────
702
782
  // 21. Dead End Page (No Navigation/Layout)
703
783
  // ───────────────────────────────────────────────────────────────────────
704
784
  const deadEndPage = (source, file) => {
@@ -1333,6 +1413,7 @@ const CHECKS = [
1333
1413
  unauthAdmin,
1334
1414
  missingRateLimit,
1335
1415
  idorDataFetch,
1416
+ clientTrustedUserId,
1336
1417
  deadEndPage,
1337
1418
  dbPollingAbuse,
1338
1419
  iconButtonNoLabel,
@@ -1347,32 +1428,26 @@ const CHECKS = [
1347
1428
  ];
1348
1429
  export const PER_FILE_CHECK_COUNT = CHECKS.length;
1349
1430
  export function runChecks(source, file, ast) {
1431
+ // Guard against callers (or fuzzers) passing something that isn't a source string / Babel File.
1432
+ if (typeof source !== "string" || typeof file !== "string")
1433
+ return [];
1434
+ const safeAst = ast && ast.type === "File" ? ast : null;
1350
1435
  const out = [];
1351
1436
  for (const c of CHECKS) {
1352
1437
  try {
1353
- out.push(...c(source, file, ast));
1438
+ out.push(...c(source, file, safeAst));
1354
1439
  }
1355
1440
  catch (e) {
1441
+ // A bug in one of *our* rules must not cost the user points or show up as their finding.
1442
+ // Report it for us to fix and keep scanning with the other rules.
1356
1443
  const err = e instanceof Error ? e : new Error(String(e));
1357
- // Report the crash silently in the background
1358
1444
  reportCliError({
1359
1445
  source: "cli-scan",
1360
- message: `Scanner rule crashed on ${file}`,
1446
+ message: `Scanner rule ${c.name || "anonymous"} crashed`,
1361
1447
  stack: err.stack,
1362
1448
  where: c.name || "anonymous check",
1363
1449
  extra: { file, rawError: String(e) },
1364
1450
  }).catch(() => { });
1365
- out.push(mkFinding({
1366
- id: "internal-error",
1367
- category: "Runtime Stability",
1368
- severity: "high",
1369
- file,
1370
- line: 1,
1371
- message: `Scanner crashed: ${e}`,
1372
- why: "Internal exception in scanner rule.",
1373
- fix: "Report this issue.",
1374
- aiPrompt: "Fix the crash in the scanner rule.",
1375
- }));
1376
1451
  }
1377
1452
  }
1378
1453
  return out;