periderm-cli 0.1.70 → 0.1.72

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/dist/index.js CHANGED
@@ -30,7 +30,8 @@ function requireAuth() {
30
30
  process.exit(1);
31
31
  }
32
32
  const program = new Command();
33
- program.name("periderm").description("A pre-launch checklist.").version("0.1.57");
33
+ const pkg = JSON.parse(await fs.readFile(new URL("../package.json", import.meta.url), "utf-8"));
34
+ program.name("periderm").description("A pre-launch checklist.").version(pkg.version);
34
35
  // Easter egg: `periderm bless` — hidden, undocumented
35
36
  program
36
37
  .command("bless", { hidden: true })
@@ -30,6 +30,12 @@ export function renderMarkdown(r) {
30
30
  if (r.meta.aiContextUsed) {
31
31
  lines.push(`- **AI context triage:** enabled${r.meta.contextFilteredCount ? ` · ${r.meta.contextFilteredCount} finding(s) filtered as not applicable` : ""}`);
32
32
  }
33
+ if (r.meta.mlPredictorLoaded) {
34
+ lines.push(`- **ML defect predictor:** PROMISE-trained ONNX model loaded (check id \`ai-defect-prediction\`)`);
35
+ }
36
+ else {
37
+ lines.push(`- **ML defect predictor:** not loaded (model file or ONNX runtime missing — findings will not include \`ai-defect-prediction\`)`);
38
+ }
33
39
  lines.push("");
34
40
  }
35
41
  lines.push(`| Metric | Score |`);
@@ -10,6 +10,31 @@ import { reportCliError } from "../error-report.js";
10
10
  // @babel/traverse ships CJS; pick the default export defensively.
11
11
  const traverse = traverseDefault.default ??
12
12
  traverseDefault;
13
+ function isToolingPath(file) {
14
+ return (/(^|\/)(scripts|vite\.config|vitest\.config|eslint\.config)/.test(file) ||
15
+ /\.(?:test|spec)\./.test(file) ||
16
+ /(^|\/)(test\d*|test-server)\.js$/.test(file));
17
+ }
18
+ function isInsideCreateServerFn(p) {
19
+ let cur = p;
20
+ while (cur) {
21
+ if (cur.node?.type === "CallExpression") {
22
+ let n = cur.node.callee;
23
+ while (n) {
24
+ if (n.type === "Identifier" && n.name === "createServerFn")
25
+ return true;
26
+ if (n.type === "MemberExpression")
27
+ n = n.object;
28
+ else if (n.type === "CallExpression")
29
+ n = n.callee;
30
+ else
31
+ break;
32
+ }
33
+ }
34
+ cur = cur.parentPath;
35
+ }
36
+ return false;
37
+ }
13
38
  const lineOf = (source, idx) => source.slice(0, idx).split("\n").length;
14
39
  function stripStrings(source) {
15
40
  return source.replace(/`[^`]*`|"[^"\n]*"|'[^'\n]*'/g, "''");
@@ -40,7 +65,7 @@ const silentCatch = (source, file, ast) => {
40
65
  CatchClause(p) {
41
66
  const body = p.node.body.body;
42
67
  const catchSrc = source.slice(p.node.start ?? 0, p.node.end ?? 0);
43
- if (/periderm-ignore/.test(catchSrc))
68
+ if (/periderm-ignore|keep original|ignore auth|unauthenticated|fallback/i.test(catchSrc))
44
69
  return;
45
70
  if (body.length === 0) {
46
71
  out.push(mkFinding({
@@ -66,6 +91,8 @@ const silentCatch = (source, file, ast) => {
66
91
  e.callee.object.name === "console");
67
92
  });
68
93
  if (onlyConsole) {
94
+ if (isToolingPath(file) || isInsideCreateServerFn(p))
95
+ return;
69
96
  out.push(mkFinding({
70
97
  id: "silent-catch-console",
71
98
  category: "Runtime Stability",
@@ -87,6 +114,8 @@ const silentCatch = (source, file, ast) => {
87
114
  // ───────────────────────────────────────────────────────────────────────
88
115
  const envLeak = (source, file) => {
89
116
  const out = [];
117
+ if (isToolingPath(file) || /(^|\/)scripts\//.test(file))
118
+ return out;
90
119
  const isServer = /\.server\.|\/api\/|\.functions\.|server-fn|createServerFn/.test(file + source);
91
120
  if (isServer)
92
121
  return out;
@@ -96,6 +125,9 @@ const envLeak = (source, file) => {
96
125
  const name = m[1];
97
126
  if (/^(NODE_ENV|VITE_)/.test(name))
98
127
  continue;
128
+ // Public-by-design names (Supabase anon / publishable keys, etc.)
129
+ if (/(PUBLISHABLE|ANON|PUBLIC)/.test(name))
130
+ continue;
99
131
  if (/(SECRET|KEY|TOKEN|PASSWORD|PRIVATE)/.test(name)) {
100
132
  out.push(mkFinding({
101
133
  id: "env-leak",
@@ -386,7 +418,7 @@ const consoleLog = (source, file) => {
386
418
  const out = [];
387
419
  if (!/\.(tsx|jsx|ts|js)$/.test(file))
388
420
  return out;
389
- if (/\.test\.|\.spec\.|\/scripts\//.test(file))
421
+ if (/\.test\.|\.spec\.|\/scripts\//.test(file) || isToolingPath(file))
390
422
  return out;
391
423
  const matches = source.match(/console\.log\s*\(/g);
392
424
  if (matches && matches.length >= 1) {
@@ -461,31 +493,60 @@ const placeholderContent = (source, file) => {
461
493
  // ───────────────────────────────────────────────────────────────────────
462
494
  // 15. fetch call without .catch / try/catch nearby
463
495
  // ───────────────────────────────────────────────────────────────────────
464
- const unhandledFetch = (source, file) => {
496
+ const unhandledFetch = (source, file, ast) => {
465
497
  const out = [];
466
498
  if (!/\.(tsx|jsx|ts|js)$/.test(file))
467
499
  return out;
500
+ if (isToolingPath(file) || /(^|\/)scripts\//.test(file))
501
+ return out;
502
+ const push = (line) => {
503
+ if (out.length)
504
+ return;
505
+ out.push(mkFinding({
506
+ id: "unhandled-fetch",
507
+ category: "Runtime Stability",
508
+ severity: "high",
509
+ file,
510
+ line,
511
+ message: "fetch call has no visible .catch or try/catch.",
512
+ why: "Network requests fail. Without a catch, the UI silently breaks and the user has no idea why.",
513
+ fix: "Wrap in try/catch (for await) or chain .catch — set an error state and surface a retry path.",
514
+ aiPrompt: `In ${file} near line ${line}, wrap the fetch call in try/catch (or chain .catch), set an error UI state on failure, and offer the user a retry button.`,
515
+ }));
516
+ };
517
+ if (ast) {
518
+ traverse(ast, {
519
+ CallExpression(p) {
520
+ const callee = p.node.callee;
521
+ if (callee.type !== "Identifier" || callee.name !== "fetch")
522
+ return;
523
+ let cur = p;
524
+ while (cur) {
525
+ if (cur.node?.type === "TryStatement")
526
+ return;
527
+ if (cur.node?.type === "CallExpression") {
528
+ const c = cur.node.callee;
529
+ if (c?.type === "MemberExpression" &&
530
+ c.property?.type === "Identifier" &&
531
+ c.property.name === "catch")
532
+ return;
533
+ }
534
+ cur = cur.parentPath;
535
+ }
536
+ push(p.node.loc?.start.line ?? 1);
537
+ },
538
+ });
539
+ return out;
540
+ }
468
541
  const re = /\bfetch\s*\(/g;
469
542
  let m;
470
543
  while ((m = re.exec(source))) {
471
- // Look 200 chars in either direction for .catch or try
472
- const window = source.slice(Math.max(0, m.index - 80), m.index + 400);
473
- const handled = /\.catch\s*\(|try\s*\{[\s\S]*?await\s+[\s\S]{0,40}fetch/.test(window) ||
474
- /try\s*\{/.test(source.slice(Math.max(0, m.index - 200), m.index));
475
- if (!handled) {
476
- out.push(mkFinding({
477
- id: "unhandled-fetch",
478
- category: "Runtime Stability",
479
- severity: "high",
480
- file,
481
- line: lineOf(source, m.index),
482
- message: "fetch call has no visible .catch or try/catch.",
483
- why: "Network requests fail. Without a catch, the UI silently breaks and the user has no idea why.",
484
- fix: "Wrap in try/catch (for await) or chain .catch — set an error state and surface a retry path.",
485
- aiPrompt: `In ${file} near line ${lineOf(source, m.index)}, wrap the fetch call in try/catch (or chain .catch), set an error UI state on failure, and offer the user a retry button.`,
486
- }));
487
- return out; // one per file is enough signal
488
- }
544
+ const before = source.slice(Math.max(0, m.index - 2500), m.index);
545
+ const after = source.slice(m.index, m.index + 400);
546
+ const handled = /\.catch\s*\(/.test(before + after) ||
547
+ /try\s*\{/.test(before);
548
+ if (!handled)
549
+ push(lineOf(source, m.index));
489
550
  }
490
551
  return out;
491
552
  };
@@ -602,7 +663,9 @@ const idorDataFetch = (source, file) => {
602
663
  let m;
603
664
  while ((m = re.exec(source))) {
604
665
  const window = source.slice(Math.max(0, m.index - 50), m.index + 200);
605
- if (!window.includes(".eq('user_id'") && !window.includes('.eq("user_id"')) {
666
+ if (!window.includes(".eq('user_id'") &&
667
+ !window.includes('.eq("user_id"') &&
668
+ !/\.eq\(\s*['"]id['"]\s*,\s*(currentUserId|userId|context\.userId|user\.id|data\.userId)/.test(window)) {
606
669
  out.push(mkFinding({
607
670
  id: "idor-data-fetch",
608
671
  category: "Security",
@@ -629,6 +692,9 @@ const deadEndPage = (source, file) => {
629
692
  return out; // Only check route pages
630
693
  if (/__root|_layout|\.server/.test(file))
631
694
  return out; // Ignore layouts
695
+ // Nested dashboard / admin / auth / device-login routes inherit chrome or are transient.
696
+ if (/\/dashboard\/|_authenticated[/\\]|cli-login|auth\.callback|\/auth\./.test(file))
697
+ return out;
632
698
  const isRoute = /createFileRoute|export default function/i.test(source);
633
699
  if (!isRoute)
634
700
  return out;
@@ -1057,8 +1123,12 @@ const missingErrorTyping = (source, file, ast) => {
1057
1123
  const hasGuard = new RegExp(`instanceof\\s+Error|typeof\\s+${errorName}\\s*===?\\s*['"]object['"]|${errorName}\\s+is\\s+|as\\s+Error`).test(catchBodySrc) ||
1058
1124
  new RegExp(`\\b${errorName}\\s+instanceof\\b`).test(catchBodySrc) ||
1059
1125
  /Error\s*\(/.test(catchBodySrc) ||
1060
- new RegExp(`isError\\s*\\(\\s*${errorName}\\s*\\)`).test(catchBodySrc);
1061
- if (!hasGuard) {
1126
+ new RegExp(`isError\\s*\\(\\s*${errorName}\\s*\\)`).test(catchBodySrc) ||
1127
+ new RegExp(`\\b${errorName}\\?\\.(message|code|name|stack)\\b`).test(catchBodySrc) ||
1128
+ new RegExp(`String\\s*\\(\\s*${errorName}\\s*\\)`).test(catchBodySrc);
1129
+ const param = p.node.param;
1130
+ const isExplicitAny = param.typeAnnotation?.typeAnnotation?.type === "TSAnyKeyword";
1131
+ if (!hasGuard && !isExplicitAny) {
1062
1132
  out.push(mkFinding({
1063
1133
  id: "missing-error-typing",
1064
1134
  category: "Data Integrity",
@@ -1083,7 +1153,7 @@ const unusedVariablesImports = (source, file, ast) => {
1083
1153
  const out = [];
1084
1154
  if (!ast || !/\.(tsx|jsx|ts|js|mjs|cjs)$/.test(file))
1085
1155
  return out;
1086
- if (/\.d\.ts$/.test(file))
1156
+ if (/\.d\.ts$/.test(file) || isToolingPath(file))
1087
1157
  return out;
1088
1158
  traverse(ast, {
1089
1159
  Program(p) {
@@ -1167,6 +1237,9 @@ const emptyLinkText = (source, file, ast) => {
1167
1237
  (a.name.name === "aria-label" || a.name.name === "aria-labelledby"));
1168
1238
  if (hasAriaLabel)
1169
1239
  return;
1240
+ const hasSpread = p.node.attributes.some((a) => a.type === "JSXSpreadAttribute");
1241
+ if (hasSpread)
1242
+ return;
1170
1243
  const parent = p.parentPath.node;
1171
1244
  if (parent.type !== "JSXElement")
1172
1245
  return;
@@ -13,7 +13,7 @@ import { computeScores, computeVerdict } from "../report/verdict.js";
13
13
  import { renderMarkdown } from "../report/markdown.js";
14
14
  import { mapWithProgress } from "./progress.js";
15
15
  import { extractMetrics } from "./metrics.js";
16
- import { initPredictor, predictDefect } from "./ml-predictor.js";
16
+ import { initPredictor, isPredictorReady, predictDefect } from "./ml-predictor.js";
17
17
  export { formatScanPath } from "./progress.js";
18
18
  function isJsLike(rel) {
19
19
  return /\.(tsx?|jsx?|mjs|cjs)$/i.test(rel);
@@ -123,6 +123,7 @@ export async function scan(root, options = {}) {
123
123
  stacks: ctx.stacks,
124
124
  aiContextUsed: useAi,
125
125
  contextFilteredCount,
126
+ mlPredictorLoaded: isPredictorReady(),
126
127
  };
127
128
  const counts = { critical: 0, high: 0, medium: 0, low: 0 };
128
129
  for (const f of findings)
@@ -1,23 +1,43 @@
1
- import * as ort from "onnxruntime-node";
2
1
  import path from "node:path";
3
2
  import fs from "node:fs";
4
3
  import { fileURLToPath } from "node:url";
5
4
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
6
5
  let session = null;
6
+ let ort = null;
7
+ export function isPredictorReady() {
8
+ return session != null;
9
+ }
10
+ function debugMl(...args) {
11
+ if (process.env.PERIDERM_DEBUG_ML === "1") {
12
+ console.error("[periderm-ml]", ...args);
13
+ }
14
+ }
15
+ function resolveModelPath() {
16
+ const candidates = [
17
+ path.join(__dirname, "../../assets/defect_model.onnx"),
18
+ path.join(process.cwd(), "packages/cli/assets/defect_model.onnx"),
19
+ path.join(process.cwd(), "assets/defect_model.onnx"),
20
+ ];
21
+ return candidates.find((p) => fs.existsSync(p)) ?? null;
22
+ }
7
23
  export async function initPredictor() {
8
24
  if (session)
9
25
  return;
10
26
  try {
11
- // Resolve model path relative to execution
12
- let modelPath = path.join(process.cwd(), "packages/cli/assets/defect_model.onnx");
13
- if (!fs.existsSync(modelPath)) {
14
- // In dist/scanner/ml-predictor.js, __dirname is packages/cli/dist/scanner
15
- // So we go up two levels to get to packages/cli, then into assets
16
- modelPath = path.join(__dirname, "../../assets/defect_model.onnx");
17
- }
18
- if (fs.existsSync(modelPath)) {
19
- session = await ort.InferenceSession.create(modelPath);
20
- }
27
+ ort = await import("onnxruntime-web");
28
+ debugMl("runtime: onnxruntime-web");
29
+ }
30
+ catch {
31
+ debugMl("no ONNX runtime available");
32
+ return;
33
+ }
34
+ try {
35
+ const modelPath = resolveModelPath();
36
+ debugMl("model path:", modelPath);
37
+ if (!modelPath)
38
+ return;
39
+ session = await ort.InferenceSession.create(modelPath);
40
+ debugMl("session loaded");
21
41
  }
22
42
  catch (e) {
23
43
  console.error("[AI Defect Predictor] Failed to load ONNX model:", e);
@@ -27,17 +47,21 @@ export async function predictDefect(metrics) {
27
47
  if (!session)
28
48
  return false;
29
49
  try {
30
- const input = new Float32Array([metrics.loc, metrics.wmc, metrics.npm, metrics.max_cc, metrics.avg_cc]);
50
+ const input = new Float32Array([
51
+ metrics.loc,
52
+ metrics.wmc,
53
+ metrics.npm,
54
+ metrics.max_cc,
55
+ metrics.avg_cc,
56
+ ]);
31
57
  const tensor = new ort.Tensor("float32", input, [1, 5]);
32
- const feeds = { float_input: tensor };
33
- const results = await session.run(feeds);
58
+ const results = await session.run({ float_input: tensor });
34
59
  const label = results.output_label;
35
- if (label && label.data && label.data.length > 0) {
60
+ if (label?.data?.length)
36
61
  return Number(label.data[0]) > 0;
37
- }
38
62
  return false;
39
63
  }
40
- catch (e) {
64
+ catch {
41
65
  return false;
42
66
  }
43
67
  }
@@ -23,11 +23,10 @@ async function readMaybe(p) {
23
23
  function isMarketingRoute(rel) {
24
24
  if (!/routes\//.test(rel))
25
25
  return false;
26
- if (/_authenticated|admin|dashboard|api\//.test(rel))
26
+ if (/_authenticated|admin|dashboard|api\/|auth\.|cli-login|callback/.test(rel))
27
27
  return false;
28
- return (/(?:^|\/)index\.(tsx|jsx)$/.test(rel) ||
29
- /routes\/(?:index|__root)\.(tsx|jsx)$/.test(rel) ||
30
- !/_authenticated|admin/.test(rel));
28
+ return (/(?:^|\/)(?:index|about|docs|privacy|terms|reddit)(?:-reddit)?\.(tsx|jsx)$/.test(rel) ||
29
+ /routes\/(?:index|__root|about|docs|privacy|terms|reddit)\.(tsx|jsx)$/.test(rel));
31
30
  }
32
31
  export const SEO_CHECK_COUNT = 5;
33
32
  export async function runSeoChecks(root, files) {
@@ -11,6 +11,12 @@ export async function walk(root, extraIgnores = []) {
11
11
  "!**/*.d.ts",
12
12
  "!**/routeTree.gen.*",
13
13
  "!**/packages/cli/**", // never scan the scanner itself
14
+ "!**/scripts/**",
15
+ "!**/test.js",
16
+ "!**/test2.js",
17
+ "!**/test-server.js",
18
+ "!**/fix-*.mjs",
19
+ "!**/*.{test,spec}.{ts,tsx,js,jsx,mjs,cjs}",
14
20
  ];
15
21
  // Cloud policy ignores: normalize to negated globs
16
22
  const cloudIgnoreGlobs = extraIgnores.map((ig) => (ig.startsWith("!") ? ig : `!${ig}`));
@@ -5,6 +5,26 @@ import { fileURLToPath } from "node:url";
5
5
  import { readConfig } from "./config.js";
6
6
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
7
7
  const pkgPath = path.join(__dirname, "..", "package.json");
8
+ /** Returns true when `latest` is strictly newer than `current` (numeric semver, prerelease ignored). */
9
+ function isNewerVersion(latest, current) {
10
+ const parse = (v) => v
11
+ .replace(/^v/i, "")
12
+ .split("-")[0]
13
+ .split(".")
14
+ .map((n) => Number.parseInt(n, 10) || 0);
15
+ const a = parse(latest);
16
+ const b = parse(current);
17
+ const len = Math.max(a.length, b.length);
18
+ for (let i = 0; i < len; i++) {
19
+ const av = a[i] ?? 0;
20
+ const bv = b[i] ?? 0;
21
+ if (av > bv)
22
+ return true;
23
+ if (av < bv)
24
+ return false;
25
+ }
26
+ return false;
27
+ }
8
28
  /**
9
29
  * Checks for a newer version of the CLI on NPM.
10
30
  * Returns the update banner string if an update is available, otherwise null.
@@ -31,14 +51,13 @@ export async function checkUpdate() {
31
51
  return null;
32
52
  const data = (await res.json());
33
53
  const latestVersion = data.version;
34
- if (!latestVersion || latestVersion === currentVersion)
54
+ if (!latestVersion || !isNewerVersion(latestVersion, currentVersion))
35
55
  return null;
36
56
  const cfg = readConfig();
37
57
  const apiUrl = cfg.apiUrl;
38
58
  if (!apiUrl)
39
59
  return null;
40
- const isUnix = process.platform !== "win32" && process.platform !== "android";
41
- const npmCmd = isUnix ? `sudo npm update -g ${name}` : `npm update -g ${name}`;
60
+ const npmCmd = `npm update -g ${name}`;
42
61
  const curlCmd = `curl -fsSL ${apiUrl}/install.sh | bash`;
43
62
  const title = `A new version of Periderm CLI is available: ${currentVersion} → ${latestVersion}`;
44
63
  const textNpm = `Update via npm: ${npmCmd}`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "periderm-cli",
3
- "version": "0.1.70",
3
+ "version": "0.1.72",
4
4
  "description": "Periderm CLI: A pre-launch checklist to catch user-losing bugs, legal liabilities, revenue leaks, runaway cloud bills and so many more before you ship.",
5
5
  "type": "module",
6
6
  "preferGlobal": true,
@@ -54,7 +54,7 @@
54
54
  "chalk": "^5.3.0",
55
55
  "commander": "^12.1.0",
56
56
  "fast-glob": "^3.3.2",
57
- "onnxruntime-node": "^1.29.0",
57
+ "onnxruntime-web": "^1.29.0",
58
58
  "open": "^10.1.0",
59
59
  "ora": "^9.4.1"
60
60
  },