periderm-cli 0.1.62 → 0.1.69

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.
@@ -7,11 +7,13 @@ import { runRepoChecks, REPO_WIDE_CHECK_COUNT } from "./repo-checks.js";
7
7
  import { runPolicyChecks, POLICY_CHECK_COUNT } from "./policy-checks.js";
8
8
  import { runSeoChecks, SEO_CHECK_COUNT } from "./seo-checks.js";
9
9
  import { runMobileChecks, MOBILE_CHECK_COUNT } from "./mobile-checks.js";
10
- import { detectProjectContext, shouldSkipFinding, buildContextSummary, } from "./project-context.js";
10
+ import { detectProjectContext, shouldSkipFinding, buildContextSummary } from "./project-context.js";
11
11
  import { enhanceContextWithGroq, triageFindingsWithGroq, resolveGroqApiKey, } from "./context-agent.js";
12
12
  import { computeScores, computeVerdict } from "../report/verdict.js";
13
13
  import { renderMarkdown } from "../report/markdown.js";
14
14
  import { mapWithProgress } from "./progress.js";
15
+ import { extractMetrics } from "./metrics.js";
16
+ import { initPredictor, predictDefect } from "./ml-predictor.js";
15
17
  export { formatScanPath } from "./progress.js";
16
18
  function isJsLike(rel) {
17
19
  return /\.(tsx?|jsx?|mjs|cjs)$/i.test(rel);
@@ -44,6 +46,9 @@ export async function scan(root, options = {}) {
44
46
  onProgress?.({ type: "checks", current: checksRun, total: estimatedChecks });
45
47
  };
46
48
  let policySignalsChecked = 0;
49
+ let policyPagesFound = 0;
50
+ onProgress?.({ type: "phase", label: "Initializing AI Defect Predictor…" });
51
+ await initPredictor();
47
52
  await mapWithProgress(files, 6, async (abs) => {
48
53
  let src;
49
54
  try {
@@ -65,6 +70,23 @@ export async function scan(root, options = {}) {
65
70
  if (isMobileSource(rel) || (isJsLike(rel) && /react-native|expo|@react-native/.test(src))) {
66
71
  rawFindings.push(...runMobileChecks(src, rel));
67
72
  }
73
+ if (isJsLike(rel) || isMobileSource(rel)) {
74
+ const metrics = extractMetrics(src);
75
+ const isDefective = await predictDefect(metrics);
76
+ if (isDefective) {
77
+ rawFindings.push({
78
+ id: "ai-defect-prediction",
79
+ category: "Code Quality",
80
+ severity: "high",
81
+ file: rel,
82
+ line: 1,
83
+ message: "AI Defect Prediction: High Risk",
84
+ why: `The ML model predicts a high probability of defects in this file based on its code metrics (LOC: ${metrics.loc}, Max CC: ${metrics.max_cc.toFixed(1)}).`,
85
+ fix: "Consider refactoring this file to reduce complexity, decouple logic, and add unit tests.",
86
+ aiPrompt: "Refactor this file to reduce cyclomatic complexity and decouple logic into smaller, testable units.",
87
+ });
88
+ }
89
+ }
68
90
  bumpChecks(PER_FILE_CHECK_COUNT);
69
91
  }, (_abs, completed, total) => {
70
92
  const rel = path.relative(root, _abs);
@@ -74,9 +96,10 @@ export async function scan(root, options = {}) {
74
96
  rawFindings.push(...(await runRepoChecks(root, files, ctx)));
75
97
  bumpChecks(REPO_WIDE_CHECK_COUNT);
76
98
  onProgress?.({ type: "phase", label: "Cross-referencing privacy policy vs codebase…" });
77
- const policyFindings = await runPolicyChecks(root, files);
78
- rawFindings.push(...policyFindings);
79
- policySignalsChecked = policyFindings.length > 0 ? 12 : 8;
99
+ const policy = await runPolicyChecks(root, files);
100
+ rawFindings.push(...policy.findings);
101
+ policySignalsChecked = policy.signalsChecked;
102
+ policyPagesFound = policy.legalPagesFound;
80
103
  bumpChecks(POLICY_CHECK_COUNT);
81
104
  onProgress?.({ type: "phase", label: "Checking SEO & social meta…" });
82
105
  rawFindings.push(...(await runSeoChecks(root, files)));
@@ -94,6 +117,7 @@ export async function scan(root, options = {}) {
94
117
  repoWideCheckCount: REPO_WIDE_CHECK_COUNT,
95
118
  seoCheckCount: SEO_CHECK_COUNT,
96
119
  policySignalsChecked,
120
+ policyPagesFound,
97
121
  totalChecksRun: checksRun,
98
122
  projectProfile: ctx.profile,
99
123
  stacks: ctx.stacks,
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Legal-page detection shared by repo-wide checks and the privacy-policy
3
+ * cross-reference.
4
+ *
5
+ * Only real legal *pages/documents* count as legal pages. A file whose path
6
+ * merely contains "tos"/"policy" as a substring must NOT be treated as one —
7
+ * e.g. `lib/convertToSubcurrency.ts` contains "ToS" (convert**ToS**ubcurrency),
8
+ * and matching it suppresses the "no legal pages" finding while making the
9
+ * report claim a Privacy Policy exists when none does.
10
+ */
11
+ const LEGAL_KEYWORD_RE = /\b(?:privacy|privacypolicy|terms|termsofservice|tos|eula|legal|legalnotice|compliance|cookies?|cookiepolicy|policies?)\b/i;
12
+ /** Document-like files that can hold legal copy. */
13
+ const PAGE_EXT_RE = /\.(?:tsx|jsx|md|mdx|html|htm|txt|svelte|vue|astro)$/i;
14
+ /** Framework route entry files (e.g. app/privacy/page.tsx). */
15
+ const ROUTE_STEM_RE = /^(?:page|index|\+page)$/i;
16
+ export function isLegalPage(rel) {
17
+ const parts = rel.split(/[\\/]/);
18
+ const basename = parts[parts.length - 1] ?? "";
19
+ // Standalone legal doc: privacy.md, terms.tsx, cookie-policy.html, policies.svelte…
20
+ if (LEGAL_KEYWORD_RE.test(basename))
21
+ return PAGE_EXT_RE.test(basename);
22
+ // Framework route: app/privacy/page.tsx, pages/terms/index.jsx, content/legal/index.md…
23
+ const stem = basename.replace(/\.[^.]+$/, "");
24
+ return ROUTE_STEM_RE.test(stem) && parts.slice(0, -1).some((seg) => LEGAL_KEYWORD_RE.test(seg));
25
+ }
26
+ export function findLegalPages(relFiles) {
27
+ return relFiles.filter(isLegalPage);
28
+ }
@@ -0,0 +1,23 @@
1
+ export function extractMetrics(code) {
2
+ const loc = code.split("\n").length;
3
+ // Weighted methods per class / function count
4
+ const wmcMatches = code.match(/\b(function|func|def)\b|=>/g);
5
+ const wmc = wmcMatches ? wmcMatches.length : 1;
6
+ // Number of public methods
7
+ const npmMatches = code.match(/\b(export|public)\b/g);
8
+ const npm = npmMatches ? npmMatches.length : 0;
9
+ // Cyclomatic complexity estimation
10
+ // Count branching operations and keywords
11
+ const ccMatches = code.match(/\b(if|for|while|switch|case|catch)\b|&&|\|\||\?/g);
12
+ const total_cc = (ccMatches ? ccMatches.length : 0) + wmc;
13
+ const avg_cc = total_cc / (wmc || 1);
14
+ // Without AST, max_cc is a heuristic based on avg_cc + some variance
15
+ const max_cc = avg_cc > 1 ? avg_cc * 1.5 : 1;
16
+ return {
17
+ loc,
18
+ wmc,
19
+ npm,
20
+ max_cc,
21
+ avg_cc
22
+ };
23
+ }
@@ -0,0 +1,43 @@
1
+ import * as ort from "onnxruntime-node";
2
+ import path from "node:path";
3
+ import fs from "node:fs";
4
+ import { fileURLToPath } from "node:url";
5
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
6
+ let session = null;
7
+ export async function initPredictor() {
8
+ if (session)
9
+ return;
10
+ 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
+ }
21
+ }
22
+ catch (e) {
23
+ console.error("[AI Defect Predictor] Failed to load ONNX model:", e);
24
+ }
25
+ }
26
+ export async function predictDefect(metrics) {
27
+ if (!session)
28
+ return false;
29
+ try {
30
+ const input = new Float32Array([metrics.loc, metrics.wmc, metrics.npm, metrics.max_cc, metrics.avg_cc]);
31
+ const tensor = new ort.Tensor("float32", input, [1, 5]);
32
+ const feeds = { float_input: tensor };
33
+ const results = await session.run(feeds);
34
+ const label = results.output_label;
35
+ if (label && label.data && label.data.length > 0) {
36
+ return Number(label.data[0]) > 0;
37
+ }
38
+ return false;
39
+ }
40
+ catch (e) {
41
+ return false;
42
+ }
43
+ }
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import fs from "node:fs/promises";
6
6
  import path from "node:path";
7
+ import { findLegalPages } from "./legal.js";
7
8
  async function readMaybe(p) {
8
9
  try {
9
10
  return await fs.readFile(p, "utf8");
@@ -14,53 +15,91 @@ async function readMaybe(p) {
14
15
  }
15
16
  /** Signals that user data is sent to trackers, ad networks, or data brokers. */
16
17
  const TRACKING_IN_CODE = [
17
- [/gtag\s*\(|googletagmanager|google-analytics|GA_MEASUREMENT_ID|G-[A-Z0-9]{6,}/i, "Google Analytics / gtag"],
18
+ [
19
+ /gtag\s*\(|googletagmanager|google-analytics|GA_MEASUREMENT_ID|G-[A-Z0-9]{6,}/i,
20
+ "Google Analytics / gtag",
21
+ ],
18
22
  [/fbq\s*\(|facebook\.net\/en_US\/fbevents|connect\.facebook\.net/i, "Meta / Facebook Pixel"],
19
23
  [/posthog\.(?:capture|init)|import\s+posthog/i, "PostHog analytics"],
20
24
  [/mixpanel\.(?:track|init)|from\s+['"]mixpanel/i, "Mixpanel"],
21
25
  [/analytics\.(?:track|page)|segment\.(?:track|page)|@segment\//i, "Segment analytics"],
22
26
  [/amplitude\.(?:track|init)|@amplitude\//i, "Amplitude"],
23
27
  [/hotjar|hj\s*\(|clarity\.ms|fullstory|logrocket/i, "Session recording / heatmap tool"],
24
- [/doubleclick|googlesyndication|googleadservices|ads\.twitter|tiktok.*track/i, "Ad / retargeting network"],
28
+ [
29
+ /doubleclick|googlesyndication|googleadservices|ads\.twitter|tiktok.*track/i,
30
+ "Ad / retargeting network",
31
+ ],
25
32
  [/linkedin\.com\/px|snap\.licdn|taboola|outbrain|criteo/i, "Ad / retargeting pixel"],
26
33
  [/plausible\(|umami\.track|heap\.(?:track|load)/i, "Analytics SDK"],
27
34
  ];
28
35
  /** Strong privacy promises that contradict the signals above. */
29
36
  const PRIVACY_PROMISES = [
30
- [/(?:do|does|will|shall)\s+not\s+(?:share|sell|disclose|transfer)/i, "promises not to share/sell/disclose data"],
37
+ [
38
+ /(?:do|does|will|shall)\s+not\s+(?:share|sell|disclose|transfer)/i,
39
+ "promises not to share/sell/disclose data",
40
+ ],
31
41
  [/never\s+(?:share|sell|disclose|transfer)/i, "promises never to share/sell data"],
32
42
  [/(?:remain|stays?|keeping?|keep)\s+(?:private|confidential)/i, "claims user data stays private"],
33
- [/not\s+(?:shared|sold|disclosed|transferred)\s+(?:with|to)\s+third/i, "denies third-party sharing"],
34
- [/(?:no|without)\s+third[- ]party\s+(?:sharing|access|tracking|data)/i, "denies third-party tracking/sharing"],
35
- [/(?:do|does)\s+not\s+(?:use|employ|utilize)\s+(?:tracking|analytics|advertising|ad\s)/i, "denies use of tracking/analytics/ads"],
36
- [/information\s+(?:will|shall)\s+(?:remain|stay)\s+private/i, "claims information will remain private"],
37
- [/(?:personal\s+information|user\s+data).{0,40}(?:is\s+not|are\s+not|will\s+not\s+be)\s+sold/i, "claims personal data is not sold"],
38
- [/(?:only|solely)\s+(?:for|to)\s+(?:provide|operate|improve)\s+(?:the\s+)?(?:service|app|site)/i, "claims data is used only to provide the service"],
39
- [/(?:do|does)\s+not\s+(?:use|set)\s+cookies?\s+(?:for|to)\s+(?:track|advertis|market)/i, "denies tracking/ad cookies"],
43
+ [
44
+ /not\s+(?:shared|sold|disclosed|transferred)\s+(?:with|to)\s+third/i,
45
+ "denies third-party sharing",
46
+ ],
47
+ [
48
+ /(?:no|without)\s+third[- ]party\s+(?:sharing|access|tracking|data)/i,
49
+ "denies third-party tracking/sharing",
50
+ ],
51
+ [
52
+ /(?:do|does)\s+not\s+(?:use|employ|utilize)\s+(?:tracking|analytics|advertising|ad\s)/i,
53
+ "denies use of tracking/analytics/ads",
54
+ ],
55
+ [
56
+ /information\s+(?:will|shall)\s+(?:remain|stay)\s+private/i,
57
+ "claims information will remain private",
58
+ ],
59
+ [
60
+ /(?:personal\s+information|user\s+data).{0,40}(?:is\s+not|are\s+not|will\s+not\s+be)\s+sold/i,
61
+ "claims personal data is not sold",
62
+ ],
63
+ [
64
+ /(?:only|solely)\s+(?:for|to)\s+(?:provide|operate|improve)\s+(?:the\s+)?(?:service|app|site)/i,
65
+ "claims data is used only to provide the service",
66
+ ],
67
+ [
68
+ /(?:do|does)\s+not\s+(?:use|set)\s+cookies?\s+(?:for|to)\s+(?:track|advertis|market)/i,
69
+ "denies tracking/ad cookies",
70
+ ],
40
71
  [/(?:no|without)\s+(?:advertising|marketing)\s+cookies?/i, "denies advertising cookies"],
41
72
  ];
42
73
  const COOKIE_TRACKING_IN_CODE = [
43
74
  [/document\.cookie\s*[+=]|cookies?\.set\s*\(/i, "sets cookies in JavaScript"],
44
- [/localStorage\.setItem\s*\(\s*['"][^'"]*(?:track|analytics|pixel|utm|session|user)/i, "persists tracking identifiers in localStorage"],
45
- [/sessionStorage\.setItem\s*\(\s*['"][^'"]*(?:track|analytics|pixel|utm|session|user)/i, "persists tracking identifiers in sessionStorage"],
75
+ [
76
+ /localStorage\.setItem\s*\(\s*['"][^'"]*(?:track|analytics|pixel|utm|session|user)/i,
77
+ "persists tracking identifiers in localStorage",
78
+ ],
79
+ [
80
+ /sessionStorage\.setItem\s*\(\s*['"][^'"]*(?:track|analytics|pixel|utm|session|user)/i,
81
+ "persists tracking identifiers in sessionStorage",
82
+ ],
46
83
  ];
47
84
  const TRACKING_DEPS = /posthog|mixpanel|segment|amplitude|google-analytics|@vercel\/analytics|plausible|heap-js|hotjar/i;
48
85
  export const POLICY_CHECK_COUNT = 2;
86
+ /** Total signal categories the cross-reference tests for. */
87
+ export const POLICY_SIGNAL_COUNT = TRACKING_IN_CODE.length + COOKIE_TRACKING_IN_CODE.length + 1; // +1 for TRACKING_DEPS
49
88
  export async function runPolicyChecks(root, files) {
50
89
  const out = [];
51
90
  const relFiles = files.map((f) => path.relative(root, f));
52
- const legalPaths = relFiles.filter((f) => /(?:^|\/)routes\/.*(?:privacy|terms|cookie|policy|legal|compliance|eula|tos)/i.test(f)
53
- || /(?:privacy|terms|cookie|policy|legal|compliance|eula|tos).*\.(?:tsx|jsx|md|html)$/i.test(path.basename(f)));
91
+ const legalPaths = findLegalPages(relFiles);
54
92
  if (legalPaths.length === 0)
55
- return out;
93
+ return { findings: out, legalPagesFound: 0, signalsChecked: 0 };
56
94
  let legalText = "";
57
95
  for (const rel of legalPaths) {
58
96
  const content = await readMaybe(path.join(root, rel));
59
97
  if (content)
60
98
  legalText += `\n${content}`;
61
99
  }
62
- if (!legalText.trim())
63
- return out;
100
+ if (!legalText.trim()) {
101
+ return { findings: out, legalPagesFound: legalPaths.length, signalsChecked: 0 };
102
+ }
64
103
  const legalLower = legalText.toLowerCase();
65
104
  // Collect what the codebase actually does
66
105
  const codeSignals = new Map(); // label -> first file
@@ -87,8 +126,9 @@ export async function runPolicyChecks(root, files) {
87
126
  }
88
127
  }
89
128
  }
90
- if (codeSignals.size === 0)
91
- return out;
129
+ if (codeSignals.size === 0) {
130
+ return { findings: out, legalPagesFound: legalPaths.length, signalsChecked: 0 };
131
+ }
92
132
  // Flag outright contradictions: policy promises privacy, code sends data to trackers
93
133
  const brokenPromises = [];
94
134
  for (const [re, claim] of PRIVACY_PROMISES) {
@@ -130,5 +170,5 @@ export async function runPolicyChecks(root, files) {
130
170
  `Found in code: ${[...codeSignals.keys()].join(", ")}. Align the policy with reality or remove the SDKs.`,
131
171
  });
132
172
  }
133
- return out;
173
+ return { findings: out, legalPagesFound: legalPaths.length, signalsChecked: codeSignals.size };
134
174
  }
@@ -37,10 +37,7 @@ const INTERNAL_ONLY_SKIP = new Set([
37
37
  "Accessibility",
38
38
  "Polish & Embarrassment Risks",
39
39
  ]);
40
- const ADMIN_ONLY_SKIP = new Set([
41
- "Legal & Compliance",
42
- "SEO & Discoverability",
43
- ]);
40
+ const ADMIN_ONLY_SKIP = new Set(["Legal & Compliance", "SEO & Discoverability"]);
44
41
  const MOBILE_SKIP = new Set([
45
42
  "Legal & Compliance",
46
43
  "SEO & Discoverability",
@@ -113,11 +110,11 @@ export async function detectProjectContext(root, files) {
113
110
  // Stack detection from manifests
114
111
  const hasPubspec = await readMaybe(path.join(root, "pubspec.yaml"));
115
112
  const hasAppJson = await readMaybe(path.join(root, "app.json"));
116
- const hasExpo = await readMaybe(path.join(root, "app.config.js"))
117
- ?? await readMaybe(path.join(root, "app.config.ts"));
113
+ const hasExpo = (await readMaybe(path.join(root, "app.config.js"))) ??
114
+ (await readMaybe(path.join(root, "app.config.ts")));
118
115
  const pkgRaw = await readMaybe(path.join(root, "package.json"));
119
- const hasPackageSwift = relFiles.some((f) => /Package\.swift$/i.test(f))
120
- || relFiles.some((f) => /\.xcodeproj\//i.test(f));
116
+ const hasPackageSwift = relFiles.some((f) => /Package\.swift$/i.test(f)) ||
117
+ relFiles.some((f) => /\.xcodeproj\//i.test(f));
121
118
  const hasDart = relFiles.some((f) => f.endsWith(".dart"));
122
119
  const hasSwift = relFiles.some((f) => f.endsWith(".swift"));
123
120
  let pkg = {};
@@ -150,9 +147,20 @@ export async function detectProjectContext(root, files) {
150
147
  reasoning.push("Detected Swift/iOS.");
151
148
  }
152
149
  const isWebJs = [
153
- "react", "vite", "next", "svelte", "vue", "angular", "astro", "nuxt", "remix", "gatsby", "@tanstack/react-router"
154
- ].some(d => deps[d]);
155
- if (isWebJs || (!hasRn && !hasExpoDep && !hasPubspec && !hasDart && !hasPackageSwift && !hasSwift)) {
150
+ "react",
151
+ "vite",
152
+ "next",
153
+ "svelte",
154
+ "vue",
155
+ "angular",
156
+ "astro",
157
+ "nuxt",
158
+ "remix",
159
+ "gatsby",
160
+ "@tanstack/react-router",
161
+ ].some((d) => deps[d]);
162
+ if (isWebJs ||
163
+ (!hasRn && !hasExpoDep && !hasPubspec && !hasDart && !hasPackageSwift && !hasSwift)) {
156
164
  stacks.push("web-js");
157
165
  reasoning.push("Detected web JavaScript/TypeScript stack.");
158
166
  }
@@ -260,8 +268,8 @@ export async function detectFaviconPresent(root, files) {
260
268
  if (/apple-touch-icon|manifest\.webmanifest|site\.webmanifest/i.test(content))
261
269
  return true;
262
270
  }
263
- const manifest = await readMaybe(path.join(root, "public/manifest.webmanifest"))
264
- ?? await readMaybe(path.join(root, "public/site.webmanifest"));
271
+ const manifest = (await readMaybe(path.join(root, "public/manifest.webmanifest"))) ??
272
+ (await readMaybe(path.join(root, "public/site.webmanifest")));
265
273
  if (manifest && /"icons"\s*:/.test(manifest))
266
274
  return true;
267
275
  return false;