periderm-cli 0.1.33 → 0.1.36

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,8 +1,6 @@
1
1
  # periderm-cli
2
2
 
3
- A pre-launch checklist for every JavaScript and TypeScript project.
4
-
5
- Scan **`.js`**, **`.jsx`**, **`.ts`**, and **`.tsx`** codebases (plus `.mjs` / `.cjs`) before you ship.
3
+ Pre-launch scanner for web and mobile codebases — context-aware checks for JS, TS, Flutter, React Native, and Swift.
6
4
 
7
5
  ## Install
8
6
 
@@ -10,6 +8,8 @@ Scan **`.js`**, **`.jsx`**, **`.ts`**, and **`.tsx`** codebases (plus `.mjs` / `
10
8
  npm install -g periderm-cli
11
9
  ```
12
10
 
11
+ Or use the install script from your Periderm dashboard docs (`curl -fsSL $PERIDERM_API_URL/install.sh | bash`).
12
+
13
13
  ## Quick start
14
14
 
15
15
  ```bash
@@ -20,4 +20,8 @@ periderm watch # rerun on file change
20
20
  periderm whoami # show current token + plan
21
21
  ```
22
22
 
23
- Full docs: [periderm-cli.vercel.app/docs](https://periderm-cli.vercel.app/docs)
23
+ ## Project context
24
+
25
+ Admin dashboard in the same repo as your marketing site? Add `.periderm/context.json` — see `context.example.json` in this package.
26
+
27
+ Full docs live on your Periderm dashboard at `/docs`.
package/dist/config.js CHANGED
@@ -3,19 +3,21 @@ import path from "node:path";
3
3
  import os from "node:os";
4
4
  const CONFIG_DIR = path.join(os.homedir(), ".periderm");
5
5
  const CONFIG_FILE = path.join(CONFIG_DIR, "config.json");
6
- const DEFAULT_API_URL = process.env.PERIDERM_API_URL || "https://periderm-cli.vercel.app";
6
+ export function resolveApiUrl(stored) {
7
+ return (process.env.PERIDERM_API_URL || stored || "").replace(/\/$/, "");
8
+ }
7
9
  export function readConfig() {
8
10
  try {
9
11
  if (fs.existsSync(CONFIG_FILE)) {
10
12
  const raw = JSON.parse(fs.readFileSync(CONFIG_FILE, "utf8"));
11
- return { apiUrl: process.env.PERIDERM_API_URL || raw.apiUrl || DEFAULT_API_URL, token: raw.token };
13
+ return { apiUrl: resolveApiUrl(raw.apiUrl), token: raw.token };
12
14
  }
13
15
  }
14
16
  catch (e) {
15
17
  console.error("[periderm] Failed to read config file — using defaults.", e);
16
- return { apiUrl: DEFAULT_API_URL };
18
+ return { apiUrl: resolveApiUrl() };
17
19
  }
18
- return { apiUrl: DEFAULT_API_URL };
20
+ return { apiUrl: resolveApiUrl() };
19
21
  }
20
22
  export function writeConfig(cfg) {
21
23
  fs.mkdirSync(CONFIG_DIR, { recursive: true });
package/dist/index.js CHANGED
@@ -31,7 +31,7 @@ const program = new Command();
31
31
  program
32
32
  .name("periderm")
33
33
  .description("A pre-launch checklist.")
34
- .version("0.1.32");
34
+ .version("0.1.36");
35
35
  // Easter egg: `periderm bless` — hidden, undocumented
36
36
  program
37
37
  .command("bless", { hidden: true })
@@ -154,7 +154,7 @@ program
154
154
  await fs.mkdir(outDir, { recursive: true });
155
155
  await fs.writeFile(path.join(outDir, "last-report.md"), result.markdown, "utf8");
156
156
  await fs.writeFile(path.join(outDir, "last-report.json"), JSON.stringify(result, null, 2), "utf8");
157
- await fs.writeFile(path.join(outDir, "ai-instructions.md"), getAiInstructions(), "utf8");
157
+ await fs.writeFile(path.join(outDir, "ai-instructions.md"), getAiInstructions(readConfig().apiUrl), "utf8");
158
158
  // Ignore all files in the .periderm folder to prevent leaking vulnerabilities
159
159
  await fs.writeFile(path.join(outDir, ".gitignore"), "*\n", "utf8");
160
160
  if (!opts.localOnly) {
@@ -284,7 +284,13 @@ program
284
284
  .command("login")
285
285
  .description("Open the dashboard to grab a CLI token, then paste it here.")
286
286
  .action(async () => {
287
- const { apiUrl } = readConfig();
287
+ const cfg = readConfig();
288
+ const apiUrl = cfg.apiUrl;
289
+ if (!apiUrl) {
290
+ console.error(chalk.red("No API URL configured. Set PERIDERM_API_URL or log in after configuring ~/.periderm/config.json"));
291
+ process.exitCode = 1;
292
+ return;
293
+ }
288
294
  const server = http.createServer(async (req, res) => {
289
295
  const url = new URL(req.url || "", `http://127.0.0.1:${req.socket.localPort}`);
290
296
  const token = url.searchParams.get("token");
@@ -1,4 +1,6 @@
1
- export const getAiInstructions = () => `
1
+ export const getAiInstructions = (apiUrl) => {
2
+ const base = apiUrl || "{{PERIDERM_API_URL}}";
3
+ return `
2
4
  # Periderm CLI - AI Agent Instructions
3
5
 
4
6
  You are assisting a developer with a project that uses **Periderm**, a pre-launch codebase scanner.
@@ -10,7 +12,7 @@ Your primary goal is to help the user achieve a "LAUNCH READY" verdict by runnin
10
12
  1. **Install and Run Periderm:**
11
13
  - If Periderm CLI is not installed, install it using the instructions below.
12
14
  - Run \`periderm scan\` in the root of the project.
13
- - If the scan fails due to authentication (the user is not logged in), **stop and tell the user to create an account at https://periderm-cli.vercel.app/ and log in by running \`periderm login\`**. DO NOT try to bypass this.
15
+ - If the scan fails due to authentication (the user is not logged in), **stop and tell the user to create an account at ${base}/ and log in by running \`periderm login\`**. DO NOT try to bypass this.
14
16
 
15
17
  2. **Fix Findings Iteratively:**
16
18
  - Review the \`.periderm/last-report.md\` file or the terminal output.
@@ -20,6 +22,8 @@ Your primary goal is to help the user achieve a "LAUNCH READY" verdict by runnin
20
22
  - Re-run \`periderm scan\` after making changes to verify the fix.
21
23
  - Repeat this process until the scan returns a "LAUNCH READY" verdict with zero findings.
22
24
 
25
+ **Important:** Do not invent issues (e.g. regenerate favicons) when the report says none exist. Trust the scan report — it uses project context and AI triage to avoid false positives on admin dashboards and nonstandard asset paths.
26
+
23
27
  ---
24
28
 
25
29
  ## Periderm Documentation
@@ -29,7 +33,7 @@ Here is the essential documentation for Periderm to help you understand its feat
29
33
  ### Installation
30
34
  The easiest way to install Periderm CLI is using our installation script:
31
35
  \`\`\`bash
32
- curl -fsSL https://periderm-cli.vercel.app/install.sh | bash
36
+ curl -fsSL ${base}/install.sh | bash
33
37
  \`\`\`
34
38
  **Alternative (NPM):**
35
39
  \`\`\`bash
@@ -53,6 +57,19 @@ You get a terminal verdict plus report files at:
53
57
  - \`.periderm/last-report.md\`
54
58
  - \`.periderm/last-report.json\`
55
59
 
60
+ Scans upload to your dashboard by default. Use \`periderm scan --local-only\` for offline-only reports.
61
+
62
+ ### Project context (admin dashboards & monorepos)
63
+ Periderm detects project structure — not just folder names — to skip legal, SEO, and accessibility checks on internal admin surfaces. Override with \`.periderm/context.json\`:
64
+
65
+ \`\`\`json
66
+ {
67
+ "profile": "monorepo",
68
+ "internal_globs": ["**/_authenticated/**", "**/admin/**"],
69
+ "skip_categories": ["Legal & Compliance"]
70
+ }
71
+ \`\`\`
72
+
56
73
  ### Severity shorthand
57
74
  When viewing scan reports, findings are broken down by severity:
58
75
  - **c** (Critical): Application-breaking bugs, severe security vulnerabilities, or runaway cloud costs.
@@ -73,6 +90,9 @@ When viewing scan reports, findings are broken down by severity:
73
90
  \`periderm review --deep\` runs an AI agent locally against your codebase **after** a scan. It is designed for nuanced edge cases that deterministic rules cannot enumerate upfront.
74
91
  Deep review **adds** findings; it does not replace the fast deterministic layer. Use both together before launch.
75
92
 
93
+ ### Supported stacks
94
+ JavaScript, TypeScript, JSX, TSX, React Native, Expo, Flutter (Dart), and Swift (iOS). Web projects use Babel AST parsing; mobile sources use pattern-based checks plus AI context triage.
95
+
76
96
  ### Uninstalling
77
97
  If you ever need to remove the CLI and its local configuration:
78
98
  \`\`\`bash
@@ -84,3 +104,4 @@ rm -rf ~/.periderm
84
104
  - **Privacy Policy:** Periderm CLI scans are designed to be privacy-first and run locally on your machine. **It does NOT access, collect, or store your source code, API keys, environment variables, or any sensitive project data.** Only high-level telemetry and metadata about the scan results are securely transmitted.
85
105
  - **Terms:** Scan results are guidance, not legal, security, or compliance advice. Periderm CLI is provided "as is".
86
106
  `;
107
+ };
@@ -15,6 +15,12 @@ export function renderMarkdown(r) {
15
15
  lines.push(`- **Deterministic checks run:** ${r.meta.totalChecksRun.toLocaleString()} (${r.meta.perFileCheckCount} per source file + repo/SEO/policy passes)`);
16
16
  lines.push(`- **Privacy policy cross-reference:** ${r.meta.policySignalsChecked} tracking/legal signals compared against your policy pages`);
17
17
  lines.push(`- **Files analyzed:** ${r.filesScanned}`);
18
+ if (r.meta.projectProfile) {
19
+ lines.push(`- **Project profile:** ${r.meta.projectProfile}${r.meta.stacks?.length ? ` (${r.meta.stacks.join(", ")})` : ""}`);
20
+ }
21
+ if (r.meta.aiContextUsed) {
22
+ lines.push(`- **AI context triage:** enabled${r.meta.contextFilteredCount ? ` · ${r.meta.contextFilteredCount} finding(s) filtered as not applicable` : ""}`);
23
+ }
18
24
  lines.push("");
19
25
  }
20
26
  lines.push(`| Metric | Score |`);
@@ -34,6 +40,13 @@ export function renderMarkdown(r) {
34
40
  lines.push("No findings. Ship it.");
35
41
  return lines.join("\n");
36
42
  }
43
+ const isMobile = r.meta?.projectProfile === "mobile-app" || r.meta?.stacks?.some(s => ["react-native", "expo", "flutter", "swift-ios"].includes(s));
44
+ if (isMobile) {
45
+ lines.push("## Mobile Launch Advice");
46
+ lines.push("");
47
+ lines.push("> **Note on Legal & SEO:** We've skipped web SEO and on-page Legal & Compliance checks because this is a mobile project. However, mobile apps typically link to external web pages for their Terms and Privacy Policies. Make sure your externally hosted legal pages are complete, up to date, and correctly state your data collection practices (especially for app store review).");
48
+ lines.push("");
49
+ }
37
50
  lines.push("## How to use this report");
38
51
  lines.push("");
39
52
  lines.push("Each finding below has a **Why it matters**, an **Exact fix**, and an **AI prompt** you can paste directly into your coding assistant. Fix the criticals first, then the highs, then re-run `periderm scan`.");
@@ -0,0 +1,137 @@
1
+ const CLASSIFY_PROMPT = `You classify codebases for a pre-launch scanner. Return ONLY valid JSON (no markdown).
2
+
3
+ Given a project summary, decide:
4
+ - profile: one of consumer-app | admin-only | internal-tool | mobile-app | monorepo | library
5
+ - surfaces: { consumer, admin, internal, mobile } booleans
6
+ - skip_categories: array of check categories to skip GLOBALLY (only when the whole project is admin/internal/mobile-only)
7
+ - skip_check_ids: array of specific check ids to always skip
8
+ - internal_globs: glob patterns for admin/internal files (e.g. "**/_authenticated/**", "**/admin/**")
9
+ - notes: one sentence explaining your reasoning
10
+
11
+ Rules:
12
+ - If both marketing/landing routes AND admin/dashboard routes exist → monorepo. Do NOT skip legal/SEO globally; only internal_globs for admin paths.
13
+ - Pure admin dashboards with no public marketing → admin-only, skip Legal & Compliance and SEO & Discoverability globally.
14
+ - Mobile-only (Flutter/RN/Swift, no web marketing) → mobile-app, skip SEO.
15
+ - Never skip Security, Runtime Stability, or Runaway Cloud Costs unless library with no runtime.`;
16
+ const TRIAGE_PROMPT = `You triage scan findings for false positives. Return ONLY valid JSON:
17
+ { "remove_ids": string[], "demote": [{ "id": string, "new_severity": "low"|"medium" }], "notes": string }
18
+
19
+ Remove findings that clearly do not apply given project context (e.g. favicon missing when nonstandard icon exists, legal pages not needed on admin-only internal tools, accessibility on internal admin panels).
20
+
21
+ Keep real security and cost issues. Be conservative — when unsure, keep the finding.`;
22
+ import { readConfig } from "../config.js";
23
+ async function groqJson(apiKey, system, user) {
24
+ const cfg = readConfig();
25
+ if (cfg.token && cfg.apiUrl) {
26
+ try {
27
+ const res = await fetch(`${cfg.apiUrl}/api/public/deep-review`, {
28
+ method: "POST",
29
+ headers: { "Content-Type": "application/json", "x-periderm-token": cfg.token },
30
+ body: JSON.stringify({ system, user }),
31
+ });
32
+ if (res.ok) {
33
+ const data = (await res.json());
34
+ if (data.valid && data.content) {
35
+ return JSON.parse(data.content);
36
+ }
37
+ }
38
+ }
39
+ catch {
40
+ // Fallback to direct Groq API if backend fails or network error
41
+ }
42
+ }
43
+ if (!apiKey)
44
+ return null;
45
+ try {
46
+ const res = await fetch("https://api.groq.com/openai/v1/chat/completions", {
47
+ method: "POST",
48
+ headers: {
49
+ Authorization: `Bearer ${apiKey}`,
50
+ "Content-Type": "application/json",
51
+ },
52
+ body: JSON.stringify({
53
+ model: "llama-3.3-70b-versatile",
54
+ temperature: 0.1,
55
+ response_format: { type: "json_object" },
56
+ messages: [
57
+ { role: "system", content: system },
58
+ { role: "user", content: user },
59
+ ],
60
+ }),
61
+ });
62
+ if (!res.ok)
63
+ return null;
64
+ const data = (await res.json());
65
+ const text = data.choices?.[0]?.message?.content;
66
+ if (!text)
67
+ return null;
68
+ return JSON.parse(text);
69
+ }
70
+ catch {
71
+ return null;
72
+ }
73
+ }
74
+ function globToRegExp(glob) {
75
+ const escaped = glob
76
+ .replace(/[.+^${}()|[\]\\]/g, "\\$&")
77
+ .replace(/\*\*/g, "<<<GLOBSTAR>>>")
78
+ .replace(/\*/g, "[^/\\\\]+")
79
+ .replace(/<<<GLOBSTAR>>>/g, ".*");
80
+ return new RegExp(`(?:^|[/\\\\])${escaped}$`, "i");
81
+ }
82
+ export async function enhanceContextWithGroq(ctx, summary, apiKey) {
83
+ const patch = await groqJson(apiKey, CLASSIFY_PROMPT, summary);
84
+ if (!patch)
85
+ return ctx;
86
+ if (patch.profile)
87
+ ctx.profile = patch.profile;
88
+ if (patch.skip_categories) {
89
+ for (const c of patch.skip_categories)
90
+ ctx.skipCategories.add(c);
91
+ }
92
+ if (patch.skip_check_ids) {
93
+ for (const id of patch.skip_check_ids)
94
+ ctx.skipCheckIds.add(id);
95
+ }
96
+ if (patch.internal_globs) {
97
+ ctx.internalPathRe.push(...patch.internal_globs.map(globToRegExp));
98
+ }
99
+ if (patch.surfaces) {
100
+ ctx.surfaces = { ...ctx.surfaces, ...patch.surfaces };
101
+ }
102
+ if (patch.notes)
103
+ ctx.reasoning.push(`Groq: ${patch.notes}`);
104
+ return ctx;
105
+ }
106
+ export async function triageFindingsWithGroq(findings, ctx, apiKey) {
107
+ if (findings.length === 0)
108
+ return findings;
109
+ const payload = {
110
+ profile: ctx.profile,
111
+ stacks: ctx.stacks,
112
+ surfaces: ctx.surfaces,
113
+ findings: findings.slice(0, 60).map((f) => ({
114
+ id: f.id,
115
+ category: f.category,
116
+ severity: f.severity,
117
+ file: f.file,
118
+ message: f.message,
119
+ })),
120
+ };
121
+ const triage = await groqJson(apiKey, TRIAGE_PROMPT, JSON.stringify(payload, null, 2));
122
+ if (!triage)
123
+ return findings;
124
+ const remove = new Set(triage.remove_ids ?? []);
125
+ const demote = new Map((triage.demote ?? []).map((d) => [d.id, d.new_severity]));
126
+ if (triage.notes)
127
+ ctx.reasoning.push(`Groq triage: ${triage.notes}`);
128
+ return findings
129
+ .filter((f) => !remove.has(f.id))
130
+ .map((f) => {
131
+ const sev = demote.get(f.id);
132
+ return sev ? { ...f, severity: sev } : f;
133
+ });
134
+ }
135
+ export function resolveGroqApiKey(explicit) {
136
+ return explicit ?? process.env.GROQ_API_KEY ?? process.env.groq_api_key;
137
+ }
@@ -6,20 +6,38 @@ import { runChecks, PER_FILE_CHECK_COUNT } from "./checks.js";
6
6
  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
+ import { runMobileChecks, MOBILE_CHECK_COUNT } from "./mobile-checks.js";
10
+ import { detectProjectContext, shouldSkipFinding, buildContextSummary, } from "./project-context.js";
11
+ import { enhanceContextWithGroq, triageFindingsWithGroq, resolveGroqApiKey, } from "./context-agent.js";
9
12
  import { computeScores, computeVerdict } from "../report/verdict.js";
10
13
  import { renderMarkdown } from "../report/markdown.js";
11
14
  import { mapWithProgress } from "./progress.js";
12
15
  export { formatScanPath } from "./progress.js";
16
+ function isJsLike(rel) {
17
+ return /\.(tsx?|jsx?|mjs|cjs)$/i.test(rel);
18
+ }
19
+ function isMobileSource(rel) {
20
+ return /\.(dart|swift)$/i.test(rel);
21
+ }
13
22
  export async function scan(root, options = {}) {
14
- const { onProgress, cloudIgnores = [], cloudAiRules = "" } = options;
15
- const findings = [];
23
+ const { onProgress, cloudIgnores = [], cloudAiRules = "", enableAiContext } = options;
24
+ const rawFindings = [];
16
25
  onProgress?.({ type: "discovering" });
17
26
  const files = await walk(root, cloudIgnores);
27
+ const relFiles = files.map((f) => path.relative(root, f).replace(/\\/g, "/"));
18
28
  onProgress?.({ type: "discovered", total: files.length });
29
+ onProgress?.({ type: "phase", label: "Analyzing project context…" });
30
+ let ctx = await detectProjectContext(root, files);
31
+ const groqKey = resolveGroqApiKey(options.groqApiKey);
32
+ const useAi = enableAiContext !== false;
33
+ if (useAi) {
34
+ ctx = await enhanceContextWithGroq(ctx, buildContextSummary(ctx, root, relFiles), groqKey);
35
+ }
19
36
  const estimatedChecks = files.length * PER_FILE_CHECK_COUNT +
20
37
  REPO_WIDE_CHECK_COUNT +
21
38
  POLICY_CHECK_COUNT +
22
- SEO_CHECK_COUNT;
39
+ SEO_CHECK_COUNT +
40
+ MOBILE_CHECK_COUNT;
23
41
  let checksRun = 0;
24
42
  const bumpChecks = (n) => {
25
43
  checksRun += n;
@@ -40,24 +58,36 @@ export async function scan(root, options = {}) {
40
58
  return;
41
59
  }
42
60
  const rel = path.relative(root, abs);
43
- const ast = parseSource(src, rel);
44
- findings.push(...runChecks(src, rel, ast));
61
+ if (isJsLike(rel)) {
62
+ const ast = parseSource(src, rel);
63
+ rawFindings.push(...runChecks(src, rel, ast));
64
+ }
65
+ if (isMobileSource(rel) || (isJsLike(rel) && /react-native|expo|@react-native/.test(src))) {
66
+ rawFindings.push(...runMobileChecks(src, rel));
67
+ }
45
68
  bumpChecks(PER_FILE_CHECK_COUNT);
46
69
  }, (_abs, completed, total) => {
47
70
  const rel = path.relative(root, _abs);
48
71
  onProgress?.({ type: "file", file: rel, index: completed, total });
49
72
  });
50
73
  onProgress?.({ type: "phase", label: "Running repo-wide checks…" });
51
- findings.push(...(await runRepoChecks(root, files)));
74
+ rawFindings.push(...(await runRepoChecks(root, files, ctx)));
52
75
  bumpChecks(REPO_WIDE_CHECK_COUNT);
53
76
  onProgress?.({ type: "phase", label: "Cross-referencing privacy policy vs codebase…" });
54
77
  const policyFindings = await runPolicyChecks(root, files);
55
- findings.push(...policyFindings);
78
+ rawFindings.push(...policyFindings);
56
79
  policySignalsChecked = policyFindings.length > 0 ? 12 : 8;
57
80
  bumpChecks(POLICY_CHECK_COUNT);
58
81
  onProgress?.({ type: "phase", label: "Checking SEO & social meta…" });
59
- findings.push(...(await runSeoChecks(root, files)));
82
+ rawFindings.push(...(await runSeoChecks(root, files)));
60
83
  bumpChecks(SEO_CHECK_COUNT);
84
+ onProgress?.({ type: "phase", label: "Applying project context filters…" });
85
+ let findings = rawFindings.filter((f) => !shouldSkipFinding(f, ctx));
86
+ const contextFilteredCount = rawFindings.length - findings.length;
87
+ if (useAi) {
88
+ onProgress?.({ type: "phase", label: "Triaging findings with AI…" });
89
+ findings = await triageFindingsWithGroq(findings, ctx, groqKey);
90
+ }
61
91
  onProgress?.({ type: "phase", label: "Computing launch verdict…" });
62
92
  const meta = {
63
93
  perFileCheckCount: PER_FILE_CHECK_COUNT,
@@ -65,6 +95,10 @@ export async function scan(root, options = {}) {
65
95
  seoCheckCount: SEO_CHECK_COUNT,
66
96
  policySignalsChecked,
67
97
  totalChecksRun: checksRun,
98
+ projectProfile: ctx.profile,
99
+ stacks: ctx.stacks,
100
+ aiContextUsed: useAi,
101
+ contextFilteredCount,
68
102
  };
69
103
  const counts = { critical: 0, high: 0, medium: 0, low: 0 };
70
104
  for (const f of findings)
@@ -0,0 +1,67 @@
1
+ function mk(f) {
2
+ return f;
3
+ }
4
+ export const MOBILE_CHECK_COUNT = 4;
5
+ export function runMobileChecks(source, file) {
6
+ const out = [];
7
+ const ext = file.split(".").pop()?.toLowerCase() ?? "";
8
+ if (ext === "dart") {
9
+ if (/http\.get\s*\(|http\.post\s*\(/.test(source) && !/https:\/\//.test(source)) {
10
+ out.push(mk({
11
+ id: "dart-insecure-http",
12
+ category: "Security",
13
+ severity: "high",
14
+ file,
15
+ line: 1,
16
+ message: "HTTP (non-TLS) request detected in Dart code.",
17
+ why: "App Store and Play Store reject cleartext traffic; users on public WiFi are exposed.",
18
+ fix: "Use https:// URLs and configure ATS / network security config appropriately.",
19
+ aiPrompt: `In ${file}, replace http:// API calls with https://.`,
20
+ }));
21
+ }
22
+ if (/print\s*\(/.test(source) && !/\/\/.*print/.test(source)) {
23
+ out.push(mk({
24
+ id: "dart-debug-print",
25
+ category: "Observability",
26
+ severity: "low",
27
+ file,
28
+ line: 1,
29
+ message: "print() left in Dart source — use debugPrint or a logger.",
30
+ why: "Release builds may leak sensitive data to device logs.",
31
+ fix: "Remove print statements or gate behind kDebugMode.",
32
+ aiPrompt: `Remove or guard print() calls in ${file}.`,
33
+ }));
34
+ }
35
+ }
36
+ if (ext === "swift") {
37
+ if (/NSAllowsArbitraryLoads\s*=\s*true/i.test(source)) {
38
+ out.push(mk({
39
+ id: "swift-ats-disabled",
40
+ category: "Security",
41
+ severity: "critical",
42
+ file,
43
+ line: 1,
44
+ message: "App Transport Security allows arbitrary loads.",
45
+ why: "Disabling ATS permits insecure HTTP and weak TLS — App Store scrutiny and MITM risk.",
46
+ fix: "Remove NSAllowsArbitraryLoads or scope exceptions narrowly.",
47
+ aiPrompt: `Fix ATS configuration in ${file} — avoid global arbitrary loads.`,
48
+ }));
49
+ }
50
+ }
51
+ if (/\.(tsx|jsx|ts|js)$/.test(file) && /react-native|expo/.test(source)) {
52
+ if (/AsyncStorage\.setItem\s*\([^)]*token/i.test(source) && !/encrypt|secure/i.test(source)) {
53
+ out.push(mk({
54
+ id: "rn-token-async-storage",
55
+ category: "Security",
56
+ severity: "high",
57
+ file,
58
+ line: 1,
59
+ message: "Auth token stored in AsyncStorage without encryption.",
60
+ why: "AsyncStorage is not encrypted — rooted/jailbroken devices can read tokens.",
61
+ fix: "Use expo-secure-store or react-native-keychain for tokens.",
62
+ aiPrompt: `In ${file}, move token storage from AsyncStorage to SecureStore/Keychain.`,
63
+ }));
64
+ }
65
+ }
66
+ return out;
67
+ }
@@ -0,0 +1,260 @@
1
+ /**
2
+ * Project context — what kind of app this is and which checks apply.
3
+ * Avoids hard-coded "admin" name matching; uses structure, manifests, and optional Groq.
4
+ */
5
+ import fs from "node:fs/promises";
6
+ import path from "node:path";
7
+ import fg from "fast-glob";
8
+ const INTERNAL_PATH_RE = [
9
+ /(?:^|[/\\])_authenticated[/\\]/,
10
+ /(?:^|[/\\])routes[/\\][^/\\]*admin/i,
11
+ /(?:^|[/\\])admin[/\\]/i,
12
+ /(?:^|[/\\])dashboard[/\\]/i,
13
+ /(?:^|[/\\])backoffice[/\\]/i,
14
+ /(?:^|[/\\])cms[/\\]/i,
15
+ /(?:^|[/\\])internal[/\\]/i,
16
+ /(?:^|[/\\])portal[/\\]/i,
17
+ /(?:^|[/\\])src[/\\]admin[/\\]/i,
18
+ /(?:^|[/\\])app[/\\]\(admin\)/i,
19
+ /(?:^|[/\\])middleware\.(?:ts|js)/,
20
+ ];
21
+ const CONSUMER_PATH_RE = [
22
+ /(?:^|[/\\])routes[/\\]index\.(tsx|jsx)$/,
23
+ /(?:^|[/\\])routes[/\\]__root\.(tsx|jsx)$/,
24
+ /(?:^|[/\\])pages[/\\]index\.(tsx|jsx)$/,
25
+ /(?:^|[/\\])app[/\\]page\.(tsx|jsx)$/,
26
+ /(?:^|[/\\])landing/i,
27
+ /(?:^|[/\\])marketing/i,
28
+ /(?:^|[/\\])routes[/\\]docs\.(tsx|jsx)$/,
29
+ /(?:^|[/\\])routes[/\\]privacy\.(tsx|jsx)$/,
30
+ /(?:^|[/\\])routes[/\\]terms\.(tsx|jsx)$/,
31
+ ];
32
+ const INTERNAL_ONLY_SKIP = new Set([
33
+ "Legal & Compliance",
34
+ "SEO & Discoverability",
35
+ "Accessibility",
36
+ "Polish & Embarrassment Risks",
37
+ ]);
38
+ const ADMIN_ONLY_SKIP = new Set([
39
+ "Legal & Compliance",
40
+ "SEO & Discoverability",
41
+ ]);
42
+ const MOBILE_SKIP = new Set([
43
+ "Legal & Compliance",
44
+ "SEO & Discoverability",
45
+ "Polish & Embarrassment Risks",
46
+ ]);
47
+ async function readMaybe(p) {
48
+ try {
49
+ return await fs.readFile(p, "utf8");
50
+ }
51
+ catch {
52
+ return null;
53
+ }
54
+ }
55
+ async function loadContextFile(root) {
56
+ for (const rel of [".periderm/context.json", "periderm.context.json"]) {
57
+ const raw = await readMaybe(path.join(root, rel));
58
+ if (!raw)
59
+ continue;
60
+ try {
61
+ return JSON.parse(raw);
62
+ }
63
+ catch {
64
+ /* ignore */
65
+ }
66
+ }
67
+ return null;
68
+ }
69
+ function globToRegExp(glob) {
70
+ const escaped = glob
71
+ .replace(/[.+^${}()|[\]\\]/g, "\\$&")
72
+ .replace(/\*\*/g, "<<<GLOBSTAR>>>")
73
+ .replace(/\*/g, "[^/\\\\]+")
74
+ .replace(/<<<GLOBSTAR>>>/g, ".*");
75
+ return new RegExp(`(?:^|[/\\\\])${escaped}$`, "i");
76
+ }
77
+ export function isInternalPath(rel, ctx) {
78
+ const norm = rel.replace(/\\/g, "/");
79
+ return ctx.internalPathRe.some((re) => re.test(norm));
80
+ }
81
+ export function shouldSkipFinding(finding, ctx) {
82
+ if (ctx.skipCheckIds.has(finding.id))
83
+ return true;
84
+ if (ctx.skipCategories.has(finding.category))
85
+ return true;
86
+ const rel = finding.file.replace(/\\/g, "/");
87
+ if (isInternalPath(rel, ctx) && ctx.internalOnlySkipCategories.has(finding.category)) {
88
+ return true;
89
+ }
90
+ // Monorepo: skip consumer-only SEO/legal on internal files even when profile is monorepo
91
+ if (ctx.profile === "monorepo" && isInternalPath(rel, ctx)) {
92
+ if (INTERNAL_ONLY_SKIP.has(finding.category))
93
+ return true;
94
+ }
95
+ return false;
96
+ }
97
+ export async function detectProjectContext(root, files) {
98
+ const relFiles = files.map((f) => path.relative(root, f).replace(/\\/g, "/"));
99
+ const reasoning = [];
100
+ const stacks = [];
101
+ const skipCategories = new Set();
102
+ const skipCheckIds = new Set();
103
+ let internalPathRe = [...INTERNAL_PATH_RE];
104
+ const consumerPathRe = [...CONSUMER_PATH_RE];
105
+ const userCfg = await loadContextFile(root);
106
+ if (userCfg)
107
+ reasoning.push("Loaded .periderm/context.json overrides.");
108
+ // Stack detection from manifests
109
+ const hasPubspec = await readMaybe(path.join(root, "pubspec.yaml"));
110
+ const hasAppJson = await readMaybe(path.join(root, "app.json"));
111
+ const hasExpo = await readMaybe(path.join(root, "app.config.js"))
112
+ ?? await readMaybe(path.join(root, "app.config.ts"));
113
+ const pkgRaw = await readMaybe(path.join(root, "package.json"));
114
+ const hasPackageSwift = relFiles.some((f) => /Package\.swift$/i.test(f))
115
+ || relFiles.some((f) => /\.xcodeproj\//i.test(f));
116
+ const hasDart = relFiles.some((f) => f.endsWith(".dart"));
117
+ const hasSwift = relFiles.some((f) => f.endsWith(".swift"));
118
+ const hasRn = pkgRaw && /react-native|expo/.test(pkgRaw);
119
+ if (hasPubspec || hasDart) {
120
+ stacks.push("flutter");
121
+ reasoning.push("Detected Flutter/Dart (pubspec.yaml or .dart files).");
122
+ }
123
+ if (hasAppJson || hasExpo || (hasRn && /expo/.test(pkgRaw ?? ""))) {
124
+ stacks.push("expo");
125
+ reasoning.push("Detected Expo.");
126
+ }
127
+ else if (hasRn || relFiles.some((f) => /\.(tsx|jsx)$/.test(f) && /react-native/.test(f))) {
128
+ stacks.push("react-native");
129
+ reasoning.push("Detected React Native.");
130
+ }
131
+ if (hasPackageSwift || hasSwift) {
132
+ stacks.push("swift-ios");
133
+ reasoning.push("Detected Swift/iOS.");
134
+ }
135
+ if (pkgRaw && /react|vite|next|tanstack|svelte|vue/.test(pkgRaw)) {
136
+ stacks.push("web-js");
137
+ reasoning.push("Detected web JavaScript/TypeScript stack.");
138
+ }
139
+ if (stacks.length === 0)
140
+ stacks.push("web-js");
141
+ // Surface detection from route structure (not project name)
142
+ let adminSignals = 0;
143
+ let consumerSignals = 0;
144
+ for (const rel of relFiles) {
145
+ if (INTERNAL_PATH_RE.some((re) => re.test(rel)))
146
+ adminSignals++;
147
+ if (CONSUMER_PATH_RE.some((re) => re.test(rel)))
148
+ consumerSignals++;
149
+ if (/(?:^|[/\\])routes[/\\]api[/\\]/.test(rel))
150
+ adminSignals += 0; // api is neutral
151
+ }
152
+ const hasAuthenticatedShell = relFiles.some((f) => /_authenticated|middleware\.(ts|js)/.test(f));
153
+ if (hasAuthenticatedShell) {
154
+ adminSignals += 2;
155
+ reasoning.push("Found authenticated app shell (_authenticated routes or auth middleware).");
156
+ }
157
+ const surfaces = {
158
+ consumer: consumerSignals > 0 || userCfg?.surfaces?.consumer !== false,
159
+ admin: adminSignals > 0 || userCfg?.surfaces?.admin === true,
160
+ internal: adminSignals > 0 && consumerSignals === 0,
161
+ mobile: stacks.some((s) => ["flutter", "expo", "react-native", "swift-ios"].includes(s)),
162
+ };
163
+ if (adminSignals > 0 && consumerSignals > 0) {
164
+ reasoning.push("Monorepo: both public and authenticated/admin routes detected.");
165
+ }
166
+ else if (adminSignals > 0 && consumerSignals === 0) {
167
+ surfaces.internal = true;
168
+ reasoning.push("Only authenticated/admin-style routes — treating as internal/admin app.");
169
+ }
170
+ let profile = userCfg?.profile ?? "consumer-app";
171
+ if (!userCfg?.profile) {
172
+ if (surfaces.mobile && !surfaces.consumer && !surfaces.admin)
173
+ profile = "mobile-app";
174
+ else if (surfaces.internal && !surfaces.consumer)
175
+ profile = "admin-only";
176
+ else if (surfaces.admin && surfaces.consumer)
177
+ profile = "monorepo";
178
+ else if (surfaces.internal)
179
+ profile = "internal-tool";
180
+ else
181
+ profile = "consumer-app";
182
+ }
183
+ if (profile === "admin-only" || profile === "internal-tool") {
184
+ for (const c of ADMIN_ONLY_SKIP)
185
+ skipCategories.add(c);
186
+ reasoning.push(`Profile ${profile}: skipping legal & SEO globally.`);
187
+ }
188
+ if (profile === "mobile-app" || (surfaces.mobile && !surfaces.consumer)) {
189
+ for (const c of MOBILE_SKIP)
190
+ skipCategories.add(c);
191
+ reasoning.push("Mobile-focused project: skipping web SEO checks.");
192
+ }
193
+ if (userCfg?.skip_categories) {
194
+ for (const c of userCfg.skip_categories)
195
+ skipCategories.add(c);
196
+ }
197
+ if (userCfg?.skip_check_ids) {
198
+ for (const id of userCfg.skip_check_ids)
199
+ skipCheckIds.add(id);
200
+ }
201
+ if (userCfg?.internal_globs) {
202
+ internalPathRe = [...internalPathRe, ...userCfg.internal_globs.map(globToRegExp)];
203
+ }
204
+ return {
205
+ stacks: stacks.length ? stacks : ["web-js"],
206
+ profile,
207
+ surfaces,
208
+ skipCategories,
209
+ skipCheckIds,
210
+ internalPathRe,
211
+ consumerPathRe,
212
+ internalOnlySkipCategories: INTERNAL_ONLY_SKIP,
213
+ reasoning,
214
+ };
215
+ }
216
+ /** Scan public/ and head refs for any favicon — not just hardcoded paths. */
217
+ export async function detectFaviconPresent(root, files) {
218
+ const publicDir = path.join(root, "public");
219
+ try {
220
+ const publicFiles = await fg(["**/*"], { cwd: publicDir, dot: false });
221
+ for (const f of publicFiles) {
222
+ if (/favicon|apple-touch|icon\.(ico|png|svg|webp)$/i.test(f))
223
+ return true;
224
+ if (/\.ico$/i.test(f) && /icon/i.test(f))
225
+ return true;
226
+ }
227
+ }
228
+ catch {
229
+ /* no public dir */
230
+ }
231
+ for (const abs of files) {
232
+ const content = await readMaybe(abs);
233
+ if (!content)
234
+ continue;
235
+ if (/rel\s*=\s*["'](?:icon|shortcut icon|apple-touch-icon)["']/i.test(content))
236
+ return true;
237
+ if (/rel:\s*["']icon["']/i.test(content))
238
+ return true;
239
+ if (/apple-touch-icon|manifest\.webmanifest|site\.webmanifest/i.test(content))
240
+ return true;
241
+ }
242
+ const manifest = await readMaybe(path.join(root, "public/manifest.webmanifest"))
243
+ ?? await readMaybe(path.join(root, "public/site.webmanifest"));
244
+ if (manifest && /"icons"\s*:/.test(manifest))
245
+ return true;
246
+ return false;
247
+ }
248
+ export function buildContextSummary(ctx, root, relFiles) {
249
+ const routeSample = relFiles
250
+ .filter((f) => /routes|pages|app|lib|screens|views/i.test(f))
251
+ .slice(0, 40);
252
+ return JSON.stringify({
253
+ project: path.basename(root),
254
+ profile: ctx.profile,
255
+ stacks: ctx.stacks,
256
+ surfaces: ctx.surfaces,
257
+ route_sample: routeSample,
258
+ reasoning: ctx.reasoning,
259
+ }, null, 2);
260
+ }
@@ -5,6 +5,7 @@
5
5
  import fs from "node:fs/promises";
6
6
  import path from "node:path";
7
7
  import fg from "fast-glob";
8
+ import { detectFaviconPresent } from "./project-context.js";
8
9
  async function exists(p) {
9
10
  try {
10
11
  await fs.access(p);
@@ -23,7 +24,7 @@ async function readMaybe(p) {
23
24
  }
24
25
  }
25
26
  export const REPO_WIDE_CHECK_COUNT = 15;
26
- export async function runRepoChecks(root, _files) {
27
+ export async function runRepoChecks(root, _files, ctx) {
27
28
  const out = [];
28
29
  const has = async (rel) => exists(path.join(root, rel));
29
30
  // README
@@ -65,51 +66,28 @@ export async function runRepoChecks(root, _files) {
65
66
  });
66
67
  }
67
68
  }
68
- // public dir favicon
69
+ // public dir favicon — any rel=icon, manifest icons, or public/*icon* file counts
69
70
  const pkgRaw = await readMaybe(path.join(root, "package.json"));
70
71
  const looksLikeWeb = pkgRaw ? /react|vite|next|tanstack|svelte|vue/.test(pkgRaw) : false;
71
- // Detect project type based on name/description to avoid false positives.
72
- // We do NOT rely on "private": true because many SaaS landing pages are in private repos.
73
- let isInternalAdmin = false;
74
- let isCustomerPortal = false;
75
- const evaluateName = (str) => {
76
- if (/(?:^|_|-|\b)(admin|internal|backoffice|cms)(?:_|-|\b|$)/i.test(str))
77
- isInternalAdmin = true;
78
- if (/(?:^|_|-|\b)(portal|dashboard)(?:_|-|\b|$)/i.test(str))
79
- isCustomerPortal = true;
80
- };
81
- if (pkgRaw) {
82
- try {
83
- const pkg = JSON.parse(pkgRaw);
84
- evaluateName(pkg.name || "");
85
- evaluateName(pkg.description || "");
86
- }
87
- catch { }
88
- }
89
- if (!isInternalAdmin && !isCustomerPortal) {
90
- evaluateName(path.basename(root));
91
- }
72
+ const skipLegalGlobally = ctx?.skipCategories.has("Legal & Compliance") ||
73
+ ctx?.profile === "admin-only" ||
74
+ ctx?.profile === "internal-tool";
75
+ const skipSeoGlobally = ctx?.skipCategories.has("SEO & Discoverability");
92
76
  if (looksLikeWeb) {
93
- const favicons = ["public/favicon.ico", "public/favicon.svg", "src/favicon.ico"];
94
- let hasFavicon = false;
95
- for (const p of favicons)
96
- if (await has(p)) {
97
- hasFavicon = true;
98
- break;
99
- }
77
+ const hasFavicon = await detectFaviconPresent(root, _files);
100
78
  if (!hasFavicon) {
101
79
  out.push({
102
80
  id: "missing-favicon",
103
81
  category: "Polish & Embarrassment Risks",
104
82
  severity: "medium",
105
- file: "public/favicon.ico", line: 1,
106
- message: "No favicon found.",
83
+ file: "public/", line: 1,
84
+ message: "No favicon detected (checked link rel=icon tags, manifests, and public/ icon files).",
107
85
  why: "Without a favicon the browser tab shows a generic blank icon. Looks unfinished.",
108
- fix: "Add a favicon (favicon.ico or .svg) to /public and reference it from your root layout head.",
109
- aiPrompt: "Add a favicon.svg to /public and a <link rel=\"icon\"> tag in the root layout's head().",
86
+ fix: "Add a favicon and reference it from your root layout head (any path/extension is fine).",
87
+ aiPrompt: "Add a favicon to /public and a <link rel=\"icon\"> tag in the root layout's head(). Use the project's existing brand asset if one exists.",
110
88
  });
111
89
  }
112
- if (!isInternalAdmin && !isCustomerPortal) {
90
+ if (!skipSeoGlobally) {
113
91
  if (!(await has("public/robots.txt"))) {
114
92
  out.push({
115
93
  id: "missing-robots",
@@ -123,7 +101,7 @@ export async function runRepoChecks(root, _files) {
123
101
  });
124
102
  }
125
103
  }
126
- if (!isInternalAdmin) {
104
+ if (!skipLegalGlobally) {
127
105
  const legalFilePaths = _files.filter(f => {
128
106
  const rel = path.relative(root, f);
129
107
  return /terms|privacy|cookie|policy|legal|compliance|eula|tos/i.test(rel);
@@ -15,7 +15,7 @@ export async function walk(root, extraIgnores = []) {
15
15
  // Cloud policy ignores: normalize to negated globs
16
16
  const cloudIgnoreGlobs = extraIgnores.map((ig) => ig.startsWith("!") ? ig : `!${ig}`);
17
17
  return fg([
18
- "**/*.{ts,tsx,js,jsx,mjs,cjs}",
18
+ "**/*.{ts,tsx,js,jsx,mjs,cjs,dart,swift}",
19
19
  ...baseIgnores,
20
20
  ...cloudIgnoreGlobs,
21
21
  ], { cwd: root, absolute: true, dot: false });
@@ -30,7 +30,9 @@ export async function checkUpdate() {
30
30
  if (!latestVersion || latestVersion === currentVersion)
31
31
  return null;
32
32
  const cfg = readConfig();
33
- const apiUrl = cfg?.apiUrl ?? "https://periderm-cli.vercel.app";
33
+ const apiUrl = cfg.apiUrl;
34
+ if (!apiUrl)
35
+ return null;
34
36
  const isUnix = process.platform !== "win32" && process.platform !== "android";
35
37
  const npmCmd = isUnix ? `sudo npm install -g ${name}` : `npm install -g ${name}`;
36
38
  const curlCmd = `curl -fsSL ${apiUrl}/install.sh | bash`;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "periderm-cli",
3
- "version": "0.1.33",
4
- "description": "A pre-launch checklist for your codebase. Scan JS, TS, JSX, and TSX projects before you ship.",
3
+ "version": "0.1.36",
4
+ "description": "Pre-launch scanner for web and mobile codebases. Context-aware checks for JS, TS, Flutter, React Native, and Swift.",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "periderm": "./dist/bin.js"
@@ -23,7 +23,12 @@
23
23
  "react",
24
24
  "launch-checklist",
25
25
  "static-analysis",
26
- "code-review"
26
+ "flutter",
27
+ "react-native",
28
+ "expo",
29
+ "swift",
30
+ "dart",
31
+ "mobile"
27
32
  ],
28
33
  "homepage": "https://periderm-cli.vercel.app",
29
34
  "repository": {