launch-doctor 0.4.2 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,85 @@
1
+ import { type ChangeMode } from './changed.js';
2
+ import { type RuleExplanation } from './explanations.js';
3
+ import { type GradeEntry } from './grades.js';
4
+ import type { Finding, Report } from './types.js';
5
+ /** A problem the caller should explain to the user (not a crash). */
6
+ export declare class CoreError extends Error {
7
+ readonly kind: 'not-found' | 'not-git' | 'usage';
8
+ constructor(kind: 'not-found' | 'not-git' | 'usage', message: string);
9
+ }
10
+ export interface ScanRequest {
11
+ /** Project folder (resolved against the current folder). */
12
+ root: string;
13
+ offline?: boolean;
14
+ domain?: string;
15
+ only?: string[];
16
+ skip?: string[];
17
+ /** Read this many commits of git history for removed keys (true = the default depth). */
18
+ history?: number | boolean;
19
+ /** Use .launchdoctor-baseline.json (default true). */
20
+ baseline?: boolean;
21
+ configFrom?: string;
22
+ /** Report only on these files (relative paths with "/"). */
23
+ onlyFiles?: string[];
24
+ onProgress?: (step: string) => void;
25
+ }
26
+ /** The folder, resolved, or a CoreError when it isn't a folder. */
27
+ export declare function projectRoot(path: string, cwd?: string): string;
28
+ /** Scan a project folder. A folder with no project files gives a report with filesScanned 0; callers explain it. */
29
+ export declare function scan(req: ScanRequest): Promise<Report>;
30
+ /** Run `fn` on a fresh copy of the built-in demo project, and always remove the copy afterwards. */
31
+ export declare function withDemo<T>(fn: (root: string) => Promise<T>, onCreate?: (root: string) => void): Promise<T>;
32
+ /** Files changed since the last commit (`changed`) or staged (`staged`), the --changed / --staged logic. */
33
+ export declare function changedPaths(root: string, mode: ChangeMode): string[];
34
+ export interface RescanRequest extends Omit<ScanRequest, 'onlyFiles'> {
35
+ /** Report on these files. */
36
+ paths?: string[];
37
+ /** Report on the files of these findings (refs from an earlier scan of the same project). */
38
+ refs?: string[];
39
+ /** The earlier report the refs come from. Without it, refs are looked up in a fresh full scan. */
40
+ previous?: Report;
41
+ }
42
+ /**
43
+ * Check again after a fix: only the given files, the files of the given findings, or (with neither) the files changed
44
+ * since the last commit, exactly like --changed. The whole project is still read, so checks across files keep working.
45
+ */
46
+ export declare function rescan(req: RescanRequest): Promise<{
47
+ report: Report;
48
+ files: string[];
49
+ fixed: string[];
50
+ }>;
51
+ /** A path inside the project, as a relative path with "/". Paths outside the project are refused. */
52
+ export declare function normalizeRelative(root: string, path: string): string;
53
+ /**
54
+ * A finding by its stable ref ("3f9a1c2b"), or by its fix-prompt number ("2" or 2: the numbers in the report and in
55
+ * LAUNCH_FIXES.md).
56
+ */
57
+ export declare function findFinding(report: Report, key: string | number): Finding | null;
58
+ /** The fix-prompt number of a finding (1-based), as in LAUNCH_FIXES.md. */
59
+ export declare function promptNumber(report: Report, f: Finding): number;
60
+ /** The recorded grade history, oldest first. */
61
+ export declare function gradeHistory(root: string): GradeEntry[];
62
+ /** Everything about one finding, for `explain` (CLI and MCP) and the report file. */
63
+ export interface FindingDetails {
64
+ ref: string;
65
+ /** Fix-prompt number, as in the report and LAUNCH_FIXES.md. */
66
+ number: number;
67
+ rule: string;
68
+ severity: Finding['severity'];
69
+ title: string;
70
+ file?: string;
71
+ line?: number;
72
+ /** This finding's own explanation (with masked values only). */
73
+ why: string;
74
+ /** What the rule means in general, from src/explanations.ts. */
75
+ explanation: RuleExplanation | null;
76
+ rotate?: string;
77
+ usage?: string;
78
+ baseline: boolean;
79
+ }
80
+ export declare function findingDetails(report: Report, f: Finding): FindingDetails;
81
+ /**
82
+ * What a scan did and did not look at, in plain sentences: limits that were hit, skipped and unused categories,
83
+ * folders left out. Shown with MCP scan results, so the model doesn't read a clean result as "everything is fine".
84
+ */
85
+ export declare function coverageNotes(report: Report): string[];
@@ -0,0 +1,166 @@
1
+ /**
2
+ * The shared core behind the CLI and the MCP server: scan, rescan, look up a finding, its fix prompt and the grade
3
+ * history. Both wrappers only parse arguments and format output; everything they do with a project goes through here,
4
+ * so the two can't drift apart.
5
+ */
6
+ import { existsSync, rmSync, statSync } from 'node:fs';
7
+ import { isAbsolute, relative, resolve } from 'node:path';
8
+ import { changedFiles } from './changed.js';
9
+ import { createDemoProject } from './demo.js';
10
+ import { explainRule } from './explanations.js';
11
+ import { orderedFindings } from './fixes.js';
12
+ import { loadGrades } from './grades.js';
13
+ import { DEFAULT_HISTORY_DEPTH } from './history.js';
14
+ import { runDoctor } from './index.js';
15
+ /** A problem the caller should explain to the user (not a crash). */
16
+ export class CoreError extends Error {
17
+ kind;
18
+ constructor(kind, message) {
19
+ super(message);
20
+ this.kind = kind;
21
+ }
22
+ }
23
+ /** The folder, resolved, or a CoreError when it isn't a folder. */
24
+ export function projectRoot(path, cwd = process.cwd()) {
25
+ const root = resolve(cwd, path);
26
+ if (!existsSync(root) || !statSync(root).isDirectory())
27
+ throw new CoreError('not-found', `Folder not found: ${root}`);
28
+ return root;
29
+ }
30
+ /** Scan a project folder. A folder with no project files gives a report with filesScanned 0; callers explain it. */
31
+ export async function scan(req) {
32
+ const root = projectRoot(req.root);
33
+ const depth = req.history === true ? DEFAULT_HISTORY_DEPTH : typeof req.history === 'number' ? req.history : 0;
34
+ const options = {
35
+ offline: req.offline,
36
+ domain: req.domain,
37
+ only: req.only,
38
+ skip: req.skip,
39
+ baseline: req.baseline,
40
+ configFrom: req.configFrom,
41
+ onlyFiles: req.onlyFiles,
42
+ onProgress: req.onProgress,
43
+ ...(depth ? { history: { depth } } : {}),
44
+ };
45
+ return runDoctor(root, options);
46
+ }
47
+ /** Run `fn` on a fresh copy of the built-in demo project, and always remove the copy afterwards. */
48
+ export async function withDemo(fn, onCreate) {
49
+ const root = createDemoProject();
50
+ onCreate?.(root);
51
+ try {
52
+ return await fn(root);
53
+ }
54
+ finally {
55
+ rmSync(root, { recursive: true, force: true });
56
+ }
57
+ }
58
+ /** Files changed since the last commit (`changed`) or staged (`staged`), the --changed / --staged logic. */
59
+ export function changedPaths(root, mode) {
60
+ const files = changedFiles(root, mode);
61
+ if (!files)
62
+ throw new CoreError('not-git', `--${mode} needs a folder inside a git repository`);
63
+ return files;
64
+ }
65
+ /**
66
+ * Check again after a fix: only the given files, the files of the given findings, or (with neither) the files changed
67
+ * since the last commit, exactly like --changed. The whole project is still read, so checks across files keep working.
68
+ */
69
+ export async function rescan(req) {
70
+ const root = projectRoot(req.root);
71
+ let files;
72
+ let wanted = [];
73
+ if (req.refs?.length) {
74
+ const before = req.previous ?? (await scan({ ...req, root }));
75
+ const found = req.refs.map((r) => findFinding(before, r));
76
+ const unknown = req.refs.filter((_, i) => !found[i]);
77
+ if (unknown.length)
78
+ throw new CoreError('usage', `Unknown finding id: ${unknown.join(', ')}. Run a scan first.`);
79
+ wanted = req.refs;
80
+ files = [...new Set(found.map((f) => f.location?.file).filter((f) => Boolean(f)))];
81
+ if (!files.length) {
82
+ throw new CoreError('usage', 'Those findings are about the whole project, not one file: run a full scan instead.');
83
+ }
84
+ }
85
+ else if (req.paths?.length) {
86
+ files = req.paths.map((p) => normalizeRelative(root, p));
87
+ }
88
+ else {
89
+ files = changedPaths(root, 'changed');
90
+ }
91
+ const report = await scan({ ...req, root, onlyFiles: files });
92
+ const still = new Set(report.categories.flatMap((c) => c.findings.map((f) => f.ref)));
93
+ return { report, files, fixed: wanted.filter((r) => !still.has(r)) };
94
+ }
95
+ /** A path inside the project, as a relative path with "/". Paths outside the project are refused. */
96
+ export function normalizeRelative(root, path) {
97
+ const rel = relative(root, resolve(root, path));
98
+ if (!rel || rel.startsWith('..') || isAbsolute(rel))
99
+ throw new CoreError('usage', `${path} is outside the project folder`);
100
+ return rel.replace(/\\/g, '/');
101
+ }
102
+ /**
103
+ * A finding by its stable ref ("3f9a1c2b"), or by its fix-prompt number ("2" or 2: the numbers in the report and in
104
+ * LAUNCH_FIXES.md).
105
+ */
106
+ export function findFinding(report, key) {
107
+ const ordered = orderedFindings(report);
108
+ const asNumber = typeof key === 'number' ? key : /^\d{1,4}$/.test(key.trim()) ? Number(key) : null;
109
+ if (asNumber !== null)
110
+ return ordered[asNumber - 1] ?? null;
111
+ const ref = String(key).trim().toLowerCase();
112
+ return ordered.find((f) => f.ref === ref) ?? null;
113
+ }
114
+ /** The fix-prompt number of a finding (1-based), as in LAUNCH_FIXES.md. */
115
+ export function promptNumber(report, f) {
116
+ return orderedFindings(report).indexOf(f) + 1;
117
+ }
118
+ /** The recorded grade history, oldest first. */
119
+ export function gradeHistory(root) {
120
+ return loadGrades(projectRoot(root));
121
+ }
122
+ export function findingDetails(report, f) {
123
+ return {
124
+ ref: f.ref ?? '',
125
+ number: promptNumber(report, f),
126
+ rule: f.id,
127
+ severity: f.severity,
128
+ title: f.display?.title ?? f.title,
129
+ ...(f.location?.file ? { file: f.location.file } : {}),
130
+ ...(f.location?.line ? { line: f.location.line } : {}),
131
+ why: f.why,
132
+ explanation: explainRule(f.id),
133
+ ...(f.display?.rotate ? { rotate: f.display.rotate } : {}),
134
+ ...(f.display?.usage ? { usage: f.display.usage } : {}),
135
+ baseline: Boolean(f.baseline),
136
+ };
137
+ }
138
+ /**
139
+ * What a scan did and did not look at, in plain sentences: limits that were hit, skipped and unused categories,
140
+ * folders left out. Shown with MCP scan results, so the model doesn't read a clean result as "everything is fine".
141
+ */
142
+ export function coverageNotes(report) {
143
+ const notes = [];
144
+ const unit = report.mode === 'live' ? 'request' : 'file';
145
+ notes.push(`${report.filesScanned} ${unit}${report.filesScanned === 1 ? '' : 's'} checked.`);
146
+ if (report.partial)
147
+ notes.push(`Only ${report.partial.files.length} changed file(s) were reported on, not the whole project.`);
148
+ if (report.truncated)
149
+ notes.push('Very large project: only the first 20,000 files were checked.');
150
+ if (report.byteLimitReached)
151
+ notes.push('Only the first 128 MB of source files were read.');
152
+ const skipped = report.categories.filter((c) => c.skipped).map((c) => c.name);
153
+ if (skipped.length)
154
+ notes.push(`Skipped on request: ${skipped.join(', ')}.`);
155
+ const unused = report.categories
156
+ .filter((c) => !c.skipped && !c.applicable)
157
+ .map((c) => `${c.name} (${c.note ?? 'not used'})`);
158
+ if (unused.length)
159
+ notes.push(`Not applicable: ${unused.join('; ')}.`);
160
+ if (report.nestedRepos?.length)
161
+ notes.push(`Left out ${report.nestedRepos.length} nested git repositor${report.nestedRepos.length === 1 ? 'y' : 'ies'}.`);
162
+ if (report.mode !== 'live') {
163
+ notes.push('Not checked from the code: dashboard settings (Supabase, Stripe, hosting), production environment variables, backups and real sign-ins.');
164
+ }
165
+ return notes;
166
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * What each rule means, written once and used by `explain`, the MCP server and the report file.
3
+ *
4
+ * Plain data keyed by rule id (the finding `id`), with no code in the entries, so it can move into the 0.5.0 rule
5
+ * definitions as it is. test/explanations.test.ts fails if a rule has no entry.
6
+ *
7
+ * - title: the rule in a few words.
8
+ * - whyItMatters: what an attacker, a stranger or a surprise bill does with it, in plain words.
9
+ * - howToConfirm: how to check by hand that the finding is real.
10
+ * - howToFix: the fix in short (the finding's fix prompt has the details for this project).
11
+ * - falsePositiveHint: when the finding is wrong, and what to do then.
12
+ */
13
+ export interface RuleExplanation {
14
+ title: string;
15
+ whyItMatters: string;
16
+ howToConfirm: string;
17
+ howToFix: string;
18
+ falsePositiveHint: string;
19
+ }
20
+ export declare const RULE_EXPLANATIONS: Record<string, RuleExplanation>;
21
+ /** Checklist-only ids: things to check by hand, never reported as findings, so they have no rule explanation. */
22
+ export declare const CHECKLIST_IDS: Set<string>;
23
+ /** The explanation of a rule, or null for an unknown id. */
24
+ export declare function explainRule(ruleId: string): RuleExplanation | null;