launch-doctor 0.3.0 → 0.4.0
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/CHANGELOG.md +77 -6
- package/LICENSE +1 -0
- package/README.md +95 -20
- package/dist/src/access.d.ts +52 -0
- package/dist/src/access.js +482 -0
- package/dist/src/baseline.d.ts +6 -3
- package/dist/src/baseline.js +15 -8
- package/dist/src/changed.d.ts +12 -0
- package/dist/src/changed.js +34 -0
- package/dist/src/checks/access.d.ts +7 -0
- package/dist/src/checks/access.js +868 -0
- package/dist/src/checks/costs.d.ts +7 -0
- package/dist/src/checks/costs.js +14 -6
- package/dist/src/checks/database.js +79 -3
- package/dist/src/checks/first-impressions.js +22 -2
- package/dist/src/checks/legal.js +3 -1
- package/dist/src/checks/monitoring.js +8 -5
- package/dist/src/checks/payments.js +10 -2
- package/dist/src/checks/secrets.d.ts +8 -0
- package/dist/src/checks/secrets.js +82 -9
- package/dist/src/checks/supabase-storage.d.ts +31 -0
- package/dist/src/checks/supabase-storage.js +216 -0
- package/dist/src/cli.js +111 -9
- package/dist/src/demo.js +1 -0
- package/dist/src/detect.d.ts +1 -1
- package/dist/src/detect.js +1 -1
- package/dist/src/fixes.js +8 -5
- package/dist/src/git.d.ts +25 -0
- package/dist/src/git.js +121 -0
- package/dist/src/github.d.ts +11 -1
- package/dist/src/github.js +56 -14
- package/dist/src/history.js +17 -3
- package/dist/src/hook.d.ts +13 -0
- package/dist/src/hook.js +96 -0
- package/dist/src/hooks-setup.d.ts +24 -0
- package/dist/src/hooks-setup.js +187 -0
- package/dist/src/ignore.d.ts +36 -0
- package/dist/src/ignore.js +164 -0
- package/dist/src/index.js +28 -3
- package/dist/src/live.d.ts +9 -0
- package/dist/src/live.js +73 -22
- package/dist/src/mcp.js +7 -2
- package/dist/src/net-guard.d.ts +34 -0
- package/dist/src/net-guard.js +144 -0
- package/dist/src/project.d.ts +34 -5
- package/dist/src/project.js +145 -111
- package/dist/src/report.d.ts +2 -0
- package/dist/src/report.js +11 -0
- package/dist/src/routes.d.ts +10 -0
- package/dist/src/routes.js +21 -4
- package/dist/src/safe-fs.d.ts +19 -0
- package/dist/src/safe-fs.js +77 -0
- package/dist/src/sanitize.d.ts +17 -0
- package/dist/src/sanitize.js +90 -0
- package/dist/src/sarif.js +1 -1
- package/dist/src/summary.d.ts +4 -0
- package/dist/src/summary.js +9 -4
- package/dist/src/types.d.ts +24 -0
- package/dist/src/util.d.ts +1 -1
- package/dist/src/util.js +1 -1
- package/package.json +9 -5
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { lineAt } from '../util.js';
|
|
2
|
+
import { appCode, at } from './common.js';
|
|
3
|
+
/**
|
|
4
|
+
* Bucket names that suggest files people expect to stay private. A public bucket serves every
|
|
5
|
+
* file to anyone who has (or guesses) its URL, so these get a warning instead of a checklist item.
|
|
6
|
+
*/
|
|
7
|
+
export const PRIVATE_BUCKET_NAME = /private|invoice|receipt|document|contract|statement|passport|licen[cs]e|id[-_]?cards?|kyc|identit|verification|medical|health|resume|payslip|payroll|tax|bank|backup|export|attachment/i;
|
|
8
|
+
/** Remove SQL comments but keep line numbers the same. */
|
|
9
|
+
function stripSqlComments(sql) {
|
|
10
|
+
return sql.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' ')).replace(/--[^\n]*/g, '');
|
|
11
|
+
}
|
|
12
|
+
/** Split on commas that are not inside quotes, parentheses or brackets. */
|
|
13
|
+
function splitTopLevel(text) {
|
|
14
|
+
const parts = [];
|
|
15
|
+
let depth = 0;
|
|
16
|
+
let quote = false;
|
|
17
|
+
let start = 0;
|
|
18
|
+
for (let i = 0; i < text.length; i++) {
|
|
19
|
+
const c = text[i];
|
|
20
|
+
if (quote) {
|
|
21
|
+
if (c === "'") {
|
|
22
|
+
// '' is an escaped quote inside a string
|
|
23
|
+
if (text[i + 1] === "'")
|
|
24
|
+
i++;
|
|
25
|
+
else
|
|
26
|
+
quote = false;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
else if (c === "'")
|
|
30
|
+
quote = true;
|
|
31
|
+
else if (c === '(' || c === '[')
|
|
32
|
+
depth++;
|
|
33
|
+
else if (c === ')' || c === ']')
|
|
34
|
+
depth--;
|
|
35
|
+
else if (c === ',' && depth === 0) {
|
|
36
|
+
parts.push(text.slice(start, i).trim());
|
|
37
|
+
start = i + 1;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
parts.push(text.slice(start).trim());
|
|
41
|
+
return parts;
|
|
42
|
+
}
|
|
43
|
+
/** The top-level "( ... )" groups in a VALUES list. */
|
|
44
|
+
function tuples(text) {
|
|
45
|
+
const out = [];
|
|
46
|
+
let depth = 0;
|
|
47
|
+
let quote = false;
|
|
48
|
+
let start = -1;
|
|
49
|
+
for (let i = 0; i < text.length; i++) {
|
|
50
|
+
const c = text[i];
|
|
51
|
+
if (quote) {
|
|
52
|
+
if (c === "'") {
|
|
53
|
+
// '' is an escaped quote inside a string
|
|
54
|
+
if (text[i + 1] === "'")
|
|
55
|
+
i++;
|
|
56
|
+
else
|
|
57
|
+
quote = false;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
else if (c === "'")
|
|
61
|
+
quote = true;
|
|
62
|
+
else if (c === '(') {
|
|
63
|
+
if (depth === 0)
|
|
64
|
+
start = i + 1;
|
|
65
|
+
depth++;
|
|
66
|
+
}
|
|
67
|
+
else if (c === ')') {
|
|
68
|
+
depth--;
|
|
69
|
+
if (depth === 0 && start >= 0)
|
|
70
|
+
out.push(text.slice(start, i));
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
const unquote = (v) => v
|
|
76
|
+
.replace(/::\w+$/, '')
|
|
77
|
+
.replace(/^'(.*)'$/s, '$1')
|
|
78
|
+
.trim();
|
|
79
|
+
/** The text inside "using ( ... )" or "with check ( ... )", with balanced parentheses. */
|
|
80
|
+
function clause(body, keyword) {
|
|
81
|
+
const m = keyword.exec(body);
|
|
82
|
+
if (!m)
|
|
83
|
+
return null;
|
|
84
|
+
let i = m.index + m[0].length;
|
|
85
|
+
while (/\s/.test(body[i] ?? ''))
|
|
86
|
+
i++;
|
|
87
|
+
if (body[i] !== '(')
|
|
88
|
+
return null;
|
|
89
|
+
let depth = 0;
|
|
90
|
+
for (let j = i; j < body.length; j++) {
|
|
91
|
+
if (body[j] === '(')
|
|
92
|
+
depth++;
|
|
93
|
+
else if (body[j] === ')' && --depth === 0)
|
|
94
|
+
return body.slice(i + 1, j).trim();
|
|
95
|
+
}
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Is this policy condition open to anyone? "true", or only a bucket check like
|
|
100
|
+
* "bucket_id = 'avatars'", says nothing about who the caller is.
|
|
101
|
+
*/
|
|
102
|
+
function openCondition(cond) {
|
|
103
|
+
let c = cond.trim();
|
|
104
|
+
while (/^\(([\s\S]*)\)$/.test(c))
|
|
105
|
+
c = c.slice(1, -1).trim();
|
|
106
|
+
if (/^true$/i.test(c))
|
|
107
|
+
return { open: true, buckets: [] };
|
|
108
|
+
const buckets = [];
|
|
109
|
+
const parts = c.split(/\s+and\s+/i);
|
|
110
|
+
for (const raw of parts) {
|
|
111
|
+
let p = raw.trim();
|
|
112
|
+
while (/^\(([\s\S]*)\)$/.test(p))
|
|
113
|
+
p = p.slice(1, -1).trim();
|
|
114
|
+
const m = /^bucket_id\s*=\s*'([^']+)'(?:::text)?$/i.exec(p);
|
|
115
|
+
if (!m)
|
|
116
|
+
return { open: false, buckets: [] };
|
|
117
|
+
buckets.push(m[1]);
|
|
118
|
+
}
|
|
119
|
+
return { open: true, buckets };
|
|
120
|
+
}
|
|
121
|
+
function analyzeSql(file, buckets, policies) {
|
|
122
|
+
const sql = stripSqlComments(file.content);
|
|
123
|
+
let m;
|
|
124
|
+
// insert into storage.buckets (id, name, public) values ('avatars', 'avatars', true), (...);
|
|
125
|
+
const insertRe = /insert\s+into\s+"?storage"?\s*\.\s*"?buckets"?\s*\(([^)]*)\)\s*values\s*([\s\S]*?);/gi;
|
|
126
|
+
while ((m = insertRe.exec(sql))) {
|
|
127
|
+
const cols = m[1].split(',').map((c) => c.replace(/"/g, '').trim().toLowerCase());
|
|
128
|
+
const pub = cols.indexOf('public');
|
|
129
|
+
if (pub < 0)
|
|
130
|
+
continue;
|
|
131
|
+
const nameCol = cols.indexOf('name') >= 0 ? cols.indexOf('name') : cols.indexOf('id');
|
|
132
|
+
const values = m[2].replace(/\bon\s+conflict[\s\S]*$/i, '');
|
|
133
|
+
for (const tuple of tuples(values)) {
|
|
134
|
+
const vals = splitTopLevel(tuple);
|
|
135
|
+
if (!/^true$/i.test(unquote(vals[pub] ?? '')))
|
|
136
|
+
continue;
|
|
137
|
+
buckets.push({
|
|
138
|
+
name: nameCol >= 0 ? unquote(vals[nameCol] ?? '') : 'bucket',
|
|
139
|
+
loc: { file: file.path, line: lineAt(sql, m.index) },
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
// update storage.buckets set public = true where id = 'avatars';
|
|
144
|
+
const updateRe = /update\s+"?storage"?\s*\.\s*"?buckets"?\s+set\s+[^;]*?\bpublic\s*=\s*true\b[^;]*?where\s+(?:id|name)\s*=\s*'([^']+)'/gi;
|
|
145
|
+
while ((m = updateRe.exec(sql))) {
|
|
146
|
+
buckets.push({ name: m[1], loc: { file: file.path, line: lineAt(sql, m.index) } });
|
|
147
|
+
}
|
|
148
|
+
// create policy "..." on storage.objects for insert to anon with check (bucket_id = 'avatars');
|
|
149
|
+
const policyRe = /create\s+policy\s+("([^"]+)"|(\w+))\s+on\s+"?storage"?\s*\.\s*"?objects"?([\s\S]*?);/gi;
|
|
150
|
+
while ((m = policyRe.exec(sql))) {
|
|
151
|
+
const body = m[4] ?? '';
|
|
152
|
+
const rolesMatch = /\bto\s+((?:"?\w+"?\s*,\s*)*"?\w+"?)/i.exec(body);
|
|
153
|
+
const roles = rolesMatch ? rolesMatch[1].split(',').map((r) => r.replace(/"/g, '').trim().toLowerCase()) : [];
|
|
154
|
+
// No "to ..." clause means the policy applies to everyone, signed out too.
|
|
155
|
+
const toEveryone = !roles.length || roles.some((r) => r === 'anon' || r === 'public');
|
|
156
|
+
const signedIn = !toEveryone && roles.includes('authenticated');
|
|
157
|
+
if (!toEveryone && !signedIn)
|
|
158
|
+
continue;
|
|
159
|
+
const command = /\bfor\s+(all|select|insert|update|delete)\b/i.exec(body)?.[1]?.toLowerCase() ?? 'all';
|
|
160
|
+
if (command === 'select')
|
|
161
|
+
continue; // reading files is what a public bucket is for; covered by the bucket item
|
|
162
|
+
// Signed-in users uploading files is normal; replacing or deleting everyone's files is not.
|
|
163
|
+
if (signedIn && command === 'insert')
|
|
164
|
+
continue;
|
|
165
|
+
const conds = [clause(body, /\busing\b/i), clause(body, /\bwith\s+check\b/i)].filter((c) => c !== null);
|
|
166
|
+
if (!conds.length)
|
|
167
|
+
continue;
|
|
168
|
+
const checks = conds.map(openCondition);
|
|
169
|
+
if (!checks.every((c) => c.open))
|
|
170
|
+
continue;
|
|
171
|
+
policies.push({
|
|
172
|
+
name: m[2] ?? m[3] ?? 'policy',
|
|
173
|
+
buckets: [...new Set(checks.flatMap((c) => c.buckets))],
|
|
174
|
+
insertOnly: command === 'insert',
|
|
175
|
+
signedIn,
|
|
176
|
+
loc: { file: file.path, line: lineAt(sql, m.index) },
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
/** [storage.buckets.avatars] ... public = true in supabase/config.toml */
|
|
181
|
+
function analyzeConfig(file, buckets) {
|
|
182
|
+
// [ \t]* rather than \s*: with the m flag, \s* runs across every following newline from each line start.
|
|
183
|
+
const re = /^[ \t]*\[storage\.buckets\.([\w-]+)\][ \t]*$([\s\S]*?)(?=^[ \t]*\[|(?![\s\S]))/gm;
|
|
184
|
+
let m;
|
|
185
|
+
while ((m = re.exec(file.content))) {
|
|
186
|
+
const pub = /^[ \t]*public[ \t]*=[ \t]*true\b/m.exec(m[2]);
|
|
187
|
+
if (!pub)
|
|
188
|
+
continue;
|
|
189
|
+
buckets.push({ name: m[1], loc: { file: file.path, line: lineAt(file.content, m.index + m[0].indexOf('[')) } });
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
/** supabase.storage.createBucket('avatars', { public: true }) and updateBucket(...) in app code. */
|
|
193
|
+
const CODE_BUCKET = /\.(?:createBucket|updateBucket)\s*\(\s*(["'`])([^"'`]+)\1\s*,\s*\{[^}]*\bpublic\s*:\s*true\b/g;
|
|
194
|
+
/** Does the app use Supabase Storage at all? */
|
|
195
|
+
const USES_STORAGE = /\.storage\s*\.\s*(?:from|createBucket|updateBucket|listBuckets|getBucket)\s*\(/;
|
|
196
|
+
export function analyzeStorage(ctx) {
|
|
197
|
+
const buckets = [];
|
|
198
|
+
const policies = [];
|
|
199
|
+
for (const f of ctx.files) {
|
|
200
|
+
const lower = f.path.toLowerCase();
|
|
201
|
+
if (lower.endsWith('.sql'))
|
|
202
|
+
analyzeSql(f, buckets, policies);
|
|
203
|
+
else if (/(^|\/)supabase\/config\.toml$/.test(lower))
|
|
204
|
+
analyzeConfig(f, buckets);
|
|
205
|
+
}
|
|
206
|
+
for (const m of ctx.findCode(CODE_BUCKET, appCode, 20))
|
|
207
|
+
buckets.push({ name: m.match[2], loc: at(m) });
|
|
208
|
+
// One entry per bucket name (the first place it is made public).
|
|
209
|
+
const seen = new Set();
|
|
210
|
+
const unique = buckets.filter((b) => !seen.has(b.name) && seen.add(b.name));
|
|
211
|
+
const usesStorage = unique.length > 0 ||
|
|
212
|
+
policies.length > 0 ||
|
|
213
|
+
ctx.findCode(USES_STORAGE, appCode, 1).length > 0 ||
|
|
214
|
+
ctx.files.some((f) => f.path.toLowerCase().endsWith('.sql') && /storage\s*\.\s*(?:buckets|objects)/i.test(f.content));
|
|
215
|
+
return { buckets: unique, policies, usesStorage };
|
|
216
|
+
}
|
package/dist/src/cli.js
CHANGED
|
@@ -1,17 +1,22 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { appendFileSync, existsSync, rmSync, statSync
|
|
2
|
+
import { appendFileSync, existsSync, rmSync, statSync } from 'node:fs';
|
|
3
3
|
import { isAbsolute, join, relative, resolve } from 'node:path';
|
|
4
4
|
import { applyBaseline, BASELINE_FILE, loadBaseline, writeBaseline } from './baseline.js';
|
|
5
|
+
import { changedFiles } from './changed.js';
|
|
5
6
|
import { createDemoProject, removeOnSignal } from './demo.js';
|
|
6
7
|
import { renderFixes } from './fixes.js';
|
|
7
8
|
import { explainGitHubError, postPrFeedback, prContextFromEnv } from './github.js';
|
|
8
9
|
import { failingFindings } from './grade.js';
|
|
9
10
|
import { DEFAULT_HISTORY_DEPTH } from './history.js';
|
|
11
|
+
import { runHook } from './hook.js';
|
|
12
|
+
import { setupHooks } from './hooks-setup.js';
|
|
10
13
|
import { CATEGORY_IDS, runDoctor } from './index.js';
|
|
11
14
|
import { runInit } from './init.js';
|
|
12
15
|
import { runLiveScan } from './live.js';
|
|
13
16
|
import { runMcpServer } from './mcp.js';
|
|
17
|
+
import { assertConfigRef } from './project.js';
|
|
14
18
|
import { bold, dim, renderReport } from './report.js';
|
|
19
|
+
import { writeRegularFile } from './safe-fs.js';
|
|
15
20
|
import { renderSarif } from './sarif.js';
|
|
16
21
|
import { renderStepSummary } from './summary.js';
|
|
17
22
|
import { version } from './version.js';
|
|
@@ -21,6 +26,7 @@ const HELP = `
|
|
|
21
26
|
${bold('Usage')}
|
|
22
27
|
npx launch-doctor [folder] [options]
|
|
23
28
|
npx launch-doctor init [folder] Create .launchdoctorignore and a GitHub Actions workflow
|
|
29
|
+
npx launch-doctor init --hooks Set up hooks that check every AI edit and every commit
|
|
24
30
|
npx launch-doctor scan <url> Check your deployed site (exposed files, source maps, open Supabase tables, headers)
|
|
25
31
|
npx launch-doctor mcp Start an MCP server so Claude Code, Cursor and other AI tools can run checks
|
|
26
32
|
|
|
@@ -40,6 +46,12 @@ const HELP = `
|
|
|
40
46
|
--history-depth <n> How many commits --history reads (default 500)
|
|
41
47
|
--update-baseline Save today's findings to .launchdoctor-baseline.json as accepted
|
|
42
48
|
--no-baseline Ignore .launchdoctor-baseline.json and show every finding
|
|
49
|
+
--config-from <ref> Read .launchdoctorignore and the baseline from this git ref (a branch,
|
|
50
|
+
tag or commit) instead of the folder, and ignore inline ignore comments on
|
|
51
|
+
lines changed since then. The GitHub Action uses it so a pull request
|
|
52
|
+
can't silence its own findings
|
|
53
|
+
--changed Only report on files changed since the last commit (fast, for hooks)
|
|
54
|
+
--staged Only report on files staged for the next commit (for a pre-commit hook)
|
|
43
55
|
--demo Scan a built-in sample app full of mistakes
|
|
44
56
|
-h, --help Show this help
|
|
45
57
|
-v, --version Show the version
|
|
@@ -64,6 +76,11 @@ const HELP = `
|
|
|
64
76
|
npx launch-doctor ./my-app --domain myapp.com
|
|
65
77
|
npx launch-doctor --ci --fail-on warning
|
|
66
78
|
`;
|
|
79
|
+
function setChangeMode(current, next) {
|
|
80
|
+
if (current && current !== next)
|
|
81
|
+
fail('Use either --changed or --staged, not both');
|
|
82
|
+
return next;
|
|
83
|
+
}
|
|
67
84
|
function parseArgs(argv) {
|
|
68
85
|
const args = {
|
|
69
86
|
writeFile: true,
|
|
@@ -108,6 +125,14 @@ function parseArgs(argv) {
|
|
|
108
125
|
args.updateBaseline = true;
|
|
109
126
|
else if (a === '--no-baseline')
|
|
110
127
|
args.baseline = false;
|
|
128
|
+
else if (a === '--changed')
|
|
129
|
+
args.changeMode = setChangeMode(args.changeMode, 'changed');
|
|
130
|
+
else if (a === '--staged')
|
|
131
|
+
args.changeMode = setChangeMode(args.changeMode, 'staged');
|
|
132
|
+
else if (a === '--config-from')
|
|
133
|
+
args.configFrom = value();
|
|
134
|
+
else if (a.startsWith('--config-from='))
|
|
135
|
+
args.configFrom = a.slice(14);
|
|
111
136
|
else if (a === '--history')
|
|
112
137
|
args.history = true;
|
|
113
138
|
else if (a === '--history-depth')
|
|
@@ -189,20 +214,56 @@ function fail(message) {
|
|
|
189
214
|
process.exit(2);
|
|
190
215
|
}
|
|
191
216
|
function init(argv) {
|
|
192
|
-
const
|
|
217
|
+
const hooks = argv.includes('--hooks');
|
|
218
|
+
const rest = argv.filter((a) => a !== '--hooks');
|
|
219
|
+
const extra = rest.filter((a) => a.startsWith('-'));
|
|
193
220
|
if (extra.length)
|
|
194
|
-
fail(`init
|
|
195
|
-
if (
|
|
221
|
+
fail(`init only takes --hooks (got ${extra.join(' ')})`);
|
|
222
|
+
if (rest.length > 1)
|
|
196
223
|
fail('init takes at most one folder');
|
|
197
|
-
const root = resolve(
|
|
224
|
+
const root = resolve(rest[0] ?? '.');
|
|
198
225
|
if (!existsSync(root) || !statSync(root).isDirectory())
|
|
199
226
|
fail(`Folder not found: ${root}`);
|
|
227
|
+
if (hooks) {
|
|
228
|
+
const result = setupHooks(root);
|
|
229
|
+
for (const f of result.created)
|
|
230
|
+
process.stdout.write(` created ${f}
|
|
231
|
+
`);
|
|
232
|
+
for (const f of result.updated)
|
|
233
|
+
process.stdout.write(` updated ${f} ${dim('(a launch-doctor hook was added; your other settings are untouched)')}
|
|
234
|
+
`);
|
|
235
|
+
for (const [f, why] of result.skipped)
|
|
236
|
+
process.stdout.write(` skipped ${f} ${dim(`(${why})`)}
|
|
237
|
+
`);
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
200
240
|
const { created, skipped } = runInit(root);
|
|
201
241
|
for (const f of created)
|
|
202
242
|
process.stdout.write(` created ${f}\n`);
|
|
203
243
|
for (const f of skipped)
|
|
204
244
|
process.stdout.write(` skipped ${f} ${dim('(already exists)')}\n`);
|
|
205
245
|
}
|
|
246
|
+
/** The JSON an AI tool sends to a hook on stdin. A terminal has nothing to send. */
|
|
247
|
+
async function readStdin() {
|
|
248
|
+
if (process.stdin.isTTY)
|
|
249
|
+
return '';
|
|
250
|
+
const chunks = [];
|
|
251
|
+
for await (const chunk of process.stdin)
|
|
252
|
+
chunks.push(chunk);
|
|
253
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
254
|
+
}
|
|
255
|
+
async function hook(argv) {
|
|
256
|
+
const kind = argv[0];
|
|
257
|
+
if (kind !== 'claude' && kind !== 'cursor') {
|
|
258
|
+
fail('hook needs the tool it runs for: "launch-doctor hook claude" or "launch-doctor hook cursor". Set both up with "launch-doctor init --hooks".');
|
|
259
|
+
}
|
|
260
|
+
const result = await runHook(kind, await readStdin());
|
|
261
|
+
if (result.stdout)
|
|
262
|
+
process.stdout.write(result.stdout);
|
|
263
|
+
if (result.stderr)
|
|
264
|
+
process.stderr.write(result.stderr);
|
|
265
|
+
process.exitCode = result.exitCode;
|
|
266
|
+
}
|
|
206
267
|
const MCP_HELP = `
|
|
207
268
|
${bold('launch-doctor mcp')} - an MCP server for Claude Code, Cursor and other AI coding tools
|
|
208
269
|
|
|
@@ -305,7 +366,7 @@ async function scan(argv) {
|
|
|
305
366
|
if (writeFile && hasSomething) {
|
|
306
367
|
const target = out ? resolve(process.cwd(), out) : resolve(process.cwd(), 'LAUNCH_FIXES_LIVE.md');
|
|
307
368
|
try {
|
|
308
|
-
|
|
369
|
+
writeRegularFile(target, renderFixes(report));
|
|
309
370
|
const rel = relative(process.cwd(), target);
|
|
310
371
|
fixFile = rel && !rel.startsWith('..') ? rel : target;
|
|
311
372
|
}
|
|
@@ -380,6 +441,8 @@ async function main() {
|
|
|
380
441
|
return scan(process.argv.slice(3));
|
|
381
442
|
if (process.argv[2] === 'mcp')
|
|
382
443
|
return mcp(process.argv.slice(3));
|
|
444
|
+
if (process.argv[2] === 'hook')
|
|
445
|
+
return hook(process.argv.slice(3));
|
|
383
446
|
const args = parseArgs(process.argv.slice(2));
|
|
384
447
|
if (args.help) {
|
|
385
448
|
process.stdout.write(HELP);
|
|
@@ -407,15 +470,48 @@ async function main() {
|
|
|
407
470
|
const root = resolve(args.path ?? '.');
|
|
408
471
|
if (!existsSync(root) || !statSync(root).isDirectory())
|
|
409
472
|
fail(`Folder not found: ${root}`);
|
|
473
|
+
if (args.configFrom) {
|
|
474
|
+
if (args.updateBaseline)
|
|
475
|
+
fail('--config-from reads the baseline from git, so it cannot be used with --update-baseline');
|
|
476
|
+
try {
|
|
477
|
+
assertConfigRef(root, args.configFrom);
|
|
478
|
+
}
|
|
479
|
+
catch (err) {
|
|
480
|
+
fail(err.message);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
let onlyFiles;
|
|
484
|
+
if (args.changeMode) {
|
|
485
|
+
const flag = `--${args.changeMode}`;
|
|
486
|
+
if (args.demo)
|
|
487
|
+
fail(`${flag} needs a real project folder, not --demo`);
|
|
488
|
+
for (const [on, name] of [
|
|
489
|
+
[args.updateBaseline, '--update-baseline'],
|
|
490
|
+
[args.prComment, '--pr-comment'],
|
|
491
|
+
[args.history, '--history'],
|
|
492
|
+
]) {
|
|
493
|
+
if (on)
|
|
494
|
+
fail(`${flag} reports on some files only, so it can't be used with ${name}`);
|
|
495
|
+
}
|
|
496
|
+
const files = changedFiles(root, args.changeMode);
|
|
497
|
+
if (!files)
|
|
498
|
+
fail(`${flag} needs a folder inside a git repository`);
|
|
499
|
+
onlyFiles = files;
|
|
500
|
+
// A partial report must not overwrite LAUNCH_FIXES.md, which describes the whole project.
|
|
501
|
+
if (!args.out)
|
|
502
|
+
args.writeFile = false;
|
|
503
|
+
}
|
|
410
504
|
let report;
|
|
411
505
|
try {
|
|
412
506
|
report = await runDoctor(root, {
|
|
507
|
+
onlyFiles,
|
|
413
508
|
offline: args.offline,
|
|
414
509
|
domain: args.domain,
|
|
415
510
|
only: args.only,
|
|
416
511
|
skip: args.skip,
|
|
417
512
|
// When updating, start from scratch so every current finding is saved.
|
|
418
513
|
baseline: args.baseline && !args.updateBaseline,
|
|
514
|
+
configFrom: args.configFrom,
|
|
419
515
|
history: args.history ? { depth: args.historyDepth } : undefined,
|
|
420
516
|
});
|
|
421
517
|
}
|
|
@@ -432,7 +528,13 @@ async function main() {
|
|
|
432
528
|
if (args.updateBaseline) {
|
|
433
529
|
if (args.demo)
|
|
434
530
|
fail('--update-baseline needs a real project folder, not --demo');
|
|
435
|
-
|
|
531
|
+
let saved = 0;
|
|
532
|
+
try {
|
|
533
|
+
saved = writeBaseline(root, report);
|
|
534
|
+
}
|
|
535
|
+
catch (err) {
|
|
536
|
+
fail(`Couldn't write ${BASELINE_FILE}: ${err.message}`);
|
|
537
|
+
}
|
|
436
538
|
applyBaseline(report, loadBaseline(root) ?? new Set());
|
|
437
539
|
const msg = `Saved ${saved} finding${saved === 1 ? '' : 's'} to ${BASELINE_FILE}. Future runs (and --ci) only report new problems.`;
|
|
438
540
|
(args.json ? process.stderr : process.stdout).write(`\n ${dim(msg)}\n`);
|
|
@@ -447,7 +549,7 @@ async function main() {
|
|
|
447
549
|
// Rewrite an existing file even when everything passes, so old problems don't linger in it.
|
|
448
550
|
if (args.writeFile && (hasSomething || existsSync(target))) {
|
|
449
551
|
try {
|
|
450
|
-
|
|
552
|
+
writeRegularFile(target, renderFixes(report));
|
|
451
553
|
const rel = relative(process.cwd(), target);
|
|
452
554
|
fixFile = rel && !rel.startsWith('..') ? rel : target;
|
|
453
555
|
}
|
|
@@ -459,7 +561,7 @@ async function main() {
|
|
|
459
561
|
const sarifPath = isAbsolute(args.sarif) ? args.sarif : resolve(process.cwd(), args.sarif);
|
|
460
562
|
const fallbackUri = ['package.json', 'pyproject.toml', 'requirements.txt', 'README.md'].find((f) => existsSync(join(root, f)));
|
|
461
563
|
try {
|
|
462
|
-
|
|
564
|
+
writeRegularFile(sarifPath, renderSarif(report, { fallbackUri }));
|
|
463
565
|
}
|
|
464
566
|
catch (err) {
|
|
465
567
|
fail(`Couldn't write ${sarifPath}: ${err.message}`);
|
package/dist/src/demo.js
CHANGED
|
@@ -96,6 +96,7 @@ export function createDemoProject() {
|
|
|
96
96
|
'src/lib/supabase.ts': "import { createClient } from '@supabase/supabase-js';\nexport const supabase = createClient(import.meta.env.VITE_SUPABASE_URL, import.meta.env.VITE_SUPABASE_ANON_KEY);\n",
|
|
97
97
|
'src/lib/ai.ts': "import OpenAI from 'openai';\n\nconst openai = new OpenAI({ apiKey: import.meta.env.VITE_OPENAI_API_KEY, dangerouslyAllowBrowser: true });\n\nexport async function summarize(text: string) {\n return openai.chat.completions.create({ model: 'gpt-5-mini', messages: [{ role: 'user', content: text }] });\n}\n",
|
|
98
98
|
'src/pages/Signup.tsx': "import { supabase } from '../lib/supabase';\n\nexport function Signup() {\n return <button onClick={() => supabase.auth.signUp({ email: '', password: '' })}>Create account</button>;\n}\n",
|
|
99
|
+
'src/pages/Admin.tsx': "export function Admin({ user }: { user: { email: string } }) {\n if (user.email !== 'founder@example.com') return <p>Not allowed</p>;\n return <AllUsersTable />;\n}\n",
|
|
99
100
|
'src/api.ts': "export const getNotes = () => fetch('http://localhost:3001/notes').then((r) => r.json());\n",
|
|
100
101
|
'supabase/functions/stripe-webhook/index.ts': "Deno.serve(async (req) => {\n const event = await req.json();\n if (event.type === 'checkout.session.completed') {\n // mark the user as paid\n }\n return new Response('ok');\n});\n",
|
|
101
102
|
'supabase/functions/welcome-email/index.ts': "import { Resend } from 'npm:resend';\nconst resend = new Resend(Deno.env.get('RESEND_API_KEY'));\nDeno.serve(async () => {\n await resend.emails.send({ from: 'onboarding@resend.dev', to: 'user@example.com', subject: 'Welcome!', html: '<p>Hi</p>' });\n return new Response('sent');\n});\n",
|
package/dist/src/detect.d.ts
CHANGED
|
@@ -6,5 +6,5 @@ export declare function detectPayments(ctx: ProjectContext): boolean;
|
|
|
6
6
|
/** Analytics that set cookies (cookieless tools like Plausible are left out on purpose). */
|
|
7
7
|
export declare function detectCookieAnalytics(ctx: ProjectContext): boolean;
|
|
8
8
|
export declare function detectEmailProviders(ctx: ProjectContext): string[];
|
|
9
|
-
/** Common ways code checks who the user is. */
|
|
9
|
+
/** Common ways code checks who the user is. Test it on withoutImports(code) (routes.ts): an import checks nothing. */
|
|
10
10
|
export declare const AUTH_CHECK_RE: RegExp;
|
package/dist/src/detect.js
CHANGED
|
@@ -128,5 +128,5 @@ export function detectEmailProviders(ctx) {
|
|
|
128
128
|
}
|
|
129
129
|
return out;
|
|
130
130
|
}
|
|
131
|
-
/** Common ways code checks who the user is. */
|
|
131
|
+
/** Common ways code checks who the user is. Test it on withoutImports(code) (routes.ts): an import checks nothing. */
|
|
132
132
|
export const AUTH_CHECK_RE = /getServerSession|\bauth\s*\(\s*\)|currentUser\s*\(|getAuth\s*\(|\.getUser\s*\(|getSession\s*\(|verifyIdToken|verifyToken|jwtVerify|jwt\.verify|clerkClient|withAuth|requireAuth|requireUser|isAuthenticated|ensureAuth|session\?\.user|session\.user|req\.user|request\.user|ctx\.user|locals\.user|validateRequest|getKindeServerSession|getToken\s*\(/;
|
package/dist/src/fixes.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { shortWhere } from './checks/common.js';
|
|
2
|
+
import { md, mdCode } from './sanitize.js';
|
|
2
3
|
import { ISSUES_URL, plural } from './util.js';
|
|
3
4
|
function fence(text) {
|
|
4
5
|
// Use a fence longer than any backtick run inside the prompt.
|
|
@@ -6,13 +7,15 @@ function fence(text) {
|
|
|
6
7
|
const ticks = '`'.repeat(longest + 1);
|
|
7
8
|
return `${ticks}text\n${text}\n${ticks}`;
|
|
8
9
|
}
|
|
10
|
+
// Titles, explanations and paths can hold text from scanned files, so they go through md() / mdCode() (no links,
|
|
11
|
+
// HTML or @mentions); the prompts are in code fences, where nothing renders.
|
|
9
12
|
function section(f, n) {
|
|
10
|
-
const parts = [`### ${n}. ${f.title}`, ''];
|
|
13
|
+
const parts = [`### ${n}. ${md(f.title)}`, ''];
|
|
11
14
|
if (f.location)
|
|
12
|
-
parts.push(`**Where:**
|
|
15
|
+
parts.push(`**Where:** ${mdCode(shortWhere(f.location))}`, '');
|
|
13
16
|
if (f.baseline)
|
|
14
17
|
parts.push('_Existing issue, recorded in .launchdoctor-baseline.json._', '');
|
|
15
|
-
parts.push(`**Why it matters:** ${f.why}`, '', '**Prompt to paste:**', '', fence(f.fixPrompt), '');
|
|
18
|
+
parts.push(`**Why it matters:** ${md(f.why, { oneLine: false })}`, '', '**Prompt to paste:**', '', fence(f.fixPrompt), '');
|
|
16
19
|
parts.push(`<sub>Not relevant to your app? Add \`${f.id}\` to a \`.launchdoctorignore\` file.</sub>`, '');
|
|
17
20
|
return parts.join('\n');
|
|
18
21
|
}
|
|
@@ -25,7 +28,7 @@ export function renderFixes(report) {
|
|
|
25
28
|
const manual = report.categories.flatMap((c) => c.manual);
|
|
26
29
|
const date = report.generatedAt.slice(0, 10);
|
|
27
30
|
const out = [
|
|
28
|
-
`# Launch Doctor fixes for ${report.projectName}`,
|
|
31
|
+
`# Launch Doctor fixes for ${md(report.projectName)}`,
|
|
29
32
|
'',
|
|
30
33
|
`**Grade: ${report.grade}** · ${report.verdict} · ${plural(critical.length, 'critical issue')} · ${plural(warnings.length, 'warning')} · checked ${date}`,
|
|
31
34
|
'',
|
|
@@ -59,7 +62,7 @@ export function renderFixes(report) {
|
|
|
59
62
|
out.push('## Check yourself', '');
|
|
60
63
|
out.push("Things Launch Doctor can't see from your code:", '');
|
|
61
64
|
for (const m of manual)
|
|
62
|
-
out.push(`- [ ] **${m.title}** - ${m.how}`);
|
|
65
|
+
out.push(`- [ ] **${md(m.title)}** - ${md(m.how)}`);
|
|
63
66
|
out.push('');
|
|
64
67
|
}
|
|
65
68
|
out.push('---', '', `_Generated by [Launch Doctor](https://www.npmjs.com/package/launch-doctor) v${report.version}. Safe to delete or add to .gitignore._`, '', `_A finding that is wrong, or a problem it missed? Please [report it](${ISSUES_URL}). Launch Doctor reads code with pattern rules, so it can make mistakes both ways._`, '');
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** Flags for every command that prints a diff or compares files (log -p, diff). */
|
|
2
|
+
export declare const SAFE_DIFF: string[];
|
|
3
|
+
/** No git command we run should take this long; a hang (a FIFO for a config file, for example) is cut off. */
|
|
4
|
+
export declare const GIT_TIMEOUT_MS = 60000;
|
|
5
|
+
/**
|
|
6
|
+
* The full argument list for a git command run in `cwd`, or null when it isn't safe to run git there.
|
|
7
|
+
* Every git call goes through here (a test checks this).
|
|
8
|
+
*/
|
|
9
|
+
export declare function gitArgs(cwd: string, args: string[], { ownHooks }?: {
|
|
10
|
+
ownHooks?: boolean | undefined;
|
|
11
|
+
}): string[] | null;
|
|
12
|
+
/** Run git in `cwd`. Returns stdout, or null when git fails, isn't installed, times out or isn't safe to run. */
|
|
13
|
+
export declare function git(cwd: string, args: string[]): string | null;
|
|
14
|
+
/**
|
|
15
|
+
* The repository's own hooks folder (core.hooksPath, or .git/hooks), for `init --hooks`, which you run on your own
|
|
16
|
+
* project to install a hook there. The only git command that sees the repository's hooks setting; it runs nothing.
|
|
17
|
+
*/
|
|
18
|
+
export declare function gitHooksDir(cwd: string): string | null;
|
|
19
|
+
/** Like git(), but also reports the exit code, for commands where exit code 1 is an answer, not a failure. */
|
|
20
|
+
export declare function gitStatus(cwd: string, args: string[], opts?: {
|
|
21
|
+
ownHooks?: boolean;
|
|
22
|
+
}): {
|
|
23
|
+
stdout: string | null;
|
|
24
|
+
status: number | null;
|
|
25
|
+
};
|
package/dist/src/git.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { devNull } from 'node:os';
|
|
3
|
+
/**
|
|
4
|
+
* Running git safely inside a folder we don't trust.
|
|
5
|
+
*
|
|
6
|
+
* A project downloaded with its .git folder (a zip, a tarball, a copied folder; a plain `git clone` never copies
|
|
7
|
+
* .git/config) can set git options that run programs: core.fsmonitor, filter drivers (clean, smudge, process),
|
|
8
|
+
* diff drivers (textconv, command), diff.external, the pager, signature checks and hooks. Every git command
|
|
9
|
+
* Launch Doctor runs gets these settings, so none of them can run:
|
|
10
|
+
*
|
|
11
|
+
* - core.fsmonitor=false, no pager, no signature checks, hooks looked up in the null device (except for the one
|
|
12
|
+
* read-only lookup of the hooks folder that `init --hooks` makes, see gitHooksDir);
|
|
13
|
+
* - every filter driver the configuration names gets an empty clean, smudge and process command (git runs
|
|
14
|
+
* nothing for an empty one), wherever the attributes that select it come from (.gitattributes,
|
|
15
|
+
* .git/info/attributes or core.attributesFile);
|
|
16
|
+
* - log and diff calls also pass --no-textconv and --no-ext-diff (see SAFE_DIFF).
|
|
17
|
+
*
|
|
18
|
+
* When a driver name can't be overridden on the command line, git is treated as unavailable.
|
|
19
|
+
*/
|
|
20
|
+
/** Settings every git command gets. */
|
|
21
|
+
const FIXED = ['--no-pager', '-c', 'core.fsmonitor=false', '-c', 'log.showSignature=false'];
|
|
22
|
+
/** Hooks are looked up in the null device, so none can run (git status-like commands run post-index-change). */
|
|
23
|
+
const NO_HOOKS = ['-c', `core.hooksPath=${devNull}`];
|
|
24
|
+
/** Flags for every command that prints a diff or compares files (log -p, diff). */
|
|
25
|
+
export const SAFE_DIFF = ['--no-textconv', '--no-ext-diff'];
|
|
26
|
+
/** No git command we run should take this long; a hang (a FIFO for a config file, for example) is cut off. */
|
|
27
|
+
export const GIT_TIMEOUT_MS = 60_000;
|
|
28
|
+
const overrideCache = new Map();
|
|
29
|
+
/**
|
|
30
|
+
* `-c` settings that empty every filter driver the configuration seen from `cwd` defines, or null when one
|
|
31
|
+
* can't be overridden safely. Reading the configuration runs nothing.
|
|
32
|
+
*/
|
|
33
|
+
function driverOverrides(cwd) {
|
|
34
|
+
const cached = overrideCache.get(cwd);
|
|
35
|
+
if (cached !== undefined)
|
|
36
|
+
return cached;
|
|
37
|
+
let names;
|
|
38
|
+
try {
|
|
39
|
+
const out = execFileSync('git', [...FIXED, 'config', '-z', '--name-only', '--get-regexp', '^filter\\.'], {
|
|
40
|
+
cwd,
|
|
41
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
42
|
+
timeout: GIT_TIMEOUT_MS,
|
|
43
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
44
|
+
}).toString();
|
|
45
|
+
names = out.split('\0').filter(Boolean);
|
|
46
|
+
}
|
|
47
|
+
catch (err) {
|
|
48
|
+
// Exit code 1 means no filter is configured. Any other failure (no git, a broken config, a timeout) means we
|
|
49
|
+
// can't know which drivers exist, so git isn't run at all.
|
|
50
|
+
if (err.status !== 1) {
|
|
51
|
+
overrideCache.set(cwd, null);
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
names = [];
|
|
55
|
+
}
|
|
56
|
+
const drivers = new Set();
|
|
57
|
+
let unsafe = false;
|
|
58
|
+
for (const name of names) {
|
|
59
|
+
const m = /^filter\.(.+)\.[^.]+$/s.exec(name);
|
|
60
|
+
if (!m)
|
|
61
|
+
continue;
|
|
62
|
+
const driver = m[1];
|
|
63
|
+
// "-c" splits the setting at its first "="; such a name can't be overridden, so refuse to run git at all.
|
|
64
|
+
if (/[=\n\0]/.test(driver))
|
|
65
|
+
unsafe = true;
|
|
66
|
+
drivers.add(driver);
|
|
67
|
+
}
|
|
68
|
+
const result = unsafe
|
|
69
|
+
? null
|
|
70
|
+
: [...drivers].flatMap((d) => [
|
|
71
|
+
'-c',
|
|
72
|
+
`filter.${d}.clean=`,
|
|
73
|
+
'-c',
|
|
74
|
+
`filter.${d}.smudge=`,
|
|
75
|
+
'-c',
|
|
76
|
+
`filter.${d}.process=`,
|
|
77
|
+
'-c',
|
|
78
|
+
`filter.${d}.required=false`,
|
|
79
|
+
]);
|
|
80
|
+
overrideCache.set(cwd, result);
|
|
81
|
+
return result;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* The full argument list for a git command run in `cwd`, or null when it isn't safe to run git there.
|
|
85
|
+
* Every git call goes through here (a test checks this).
|
|
86
|
+
*/
|
|
87
|
+
export function gitArgs(cwd, args, { ownHooks = false } = {}) {
|
|
88
|
+
const overrides = driverOverrides(cwd);
|
|
89
|
+
if (overrides === null)
|
|
90
|
+
return null;
|
|
91
|
+
return [...FIXED, ...(ownHooks ? [] : NO_HOOKS), ...overrides, ...args];
|
|
92
|
+
}
|
|
93
|
+
/** Run git in `cwd`. Returns stdout, or null when git fails, isn't installed, times out or isn't safe to run. */
|
|
94
|
+
export function git(cwd, args) {
|
|
95
|
+
return gitStatus(cwd, args).stdout;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* The repository's own hooks folder (core.hooksPath, or .git/hooks), for `init --hooks`, which you run on your own
|
|
99
|
+
* project to install a hook there. The only git command that sees the repository's hooks setting; it runs nothing.
|
|
100
|
+
*/
|
|
101
|
+
export function gitHooksDir(cwd) {
|
|
102
|
+
return gitStatus(cwd, ['rev-parse', '--git-path', 'hooks'], { ownHooks: true }).stdout?.trim() || null;
|
|
103
|
+
}
|
|
104
|
+
/** Like git(), but also reports the exit code, for commands where exit code 1 is an answer, not a failure. */
|
|
105
|
+
export function gitStatus(cwd, args, opts = {}) {
|
|
106
|
+
const full = gitArgs(cwd, args, opts);
|
|
107
|
+
if (!full)
|
|
108
|
+
return { stdout: null, status: null };
|
|
109
|
+
try {
|
|
110
|
+
const stdout = execFileSync('git', full, {
|
|
111
|
+
cwd,
|
|
112
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
113
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
114
|
+
timeout: GIT_TIMEOUT_MS,
|
|
115
|
+
}).toString();
|
|
116
|
+
return { stdout, status: 0 };
|
|
117
|
+
}
|
|
118
|
+
catch (err) {
|
|
119
|
+
return { stdout: null, status: err.status ?? null };
|
|
120
|
+
}
|
|
121
|
+
}
|