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.
Files changed (61) hide show
  1. package/CHANGELOG.md +77 -6
  2. package/LICENSE +1 -0
  3. package/README.md +95 -20
  4. package/dist/src/access.d.ts +52 -0
  5. package/dist/src/access.js +482 -0
  6. package/dist/src/baseline.d.ts +6 -3
  7. package/dist/src/baseline.js +15 -8
  8. package/dist/src/changed.d.ts +12 -0
  9. package/dist/src/changed.js +34 -0
  10. package/dist/src/checks/access.d.ts +7 -0
  11. package/dist/src/checks/access.js +868 -0
  12. package/dist/src/checks/costs.d.ts +7 -0
  13. package/dist/src/checks/costs.js +14 -6
  14. package/dist/src/checks/database.js +79 -3
  15. package/dist/src/checks/first-impressions.js +22 -2
  16. package/dist/src/checks/legal.js +3 -1
  17. package/dist/src/checks/monitoring.js +8 -5
  18. package/dist/src/checks/payments.js +10 -2
  19. package/dist/src/checks/secrets.d.ts +8 -0
  20. package/dist/src/checks/secrets.js +82 -9
  21. package/dist/src/checks/supabase-storage.d.ts +31 -0
  22. package/dist/src/checks/supabase-storage.js +216 -0
  23. package/dist/src/cli.js +111 -9
  24. package/dist/src/demo.js +1 -0
  25. package/dist/src/detect.d.ts +1 -1
  26. package/dist/src/detect.js +1 -1
  27. package/dist/src/fixes.js +8 -5
  28. package/dist/src/git.d.ts +25 -0
  29. package/dist/src/git.js +121 -0
  30. package/dist/src/github.d.ts +11 -1
  31. package/dist/src/github.js +56 -14
  32. package/dist/src/history.js +17 -3
  33. package/dist/src/hook.d.ts +13 -0
  34. package/dist/src/hook.js +96 -0
  35. package/dist/src/hooks-setup.d.ts +24 -0
  36. package/dist/src/hooks-setup.js +187 -0
  37. package/dist/src/ignore.d.ts +36 -0
  38. package/dist/src/ignore.js +164 -0
  39. package/dist/src/index.js +28 -3
  40. package/dist/src/live.d.ts +9 -0
  41. package/dist/src/live.js +73 -22
  42. package/dist/src/mcp.js +7 -2
  43. package/dist/src/net-guard.d.ts +34 -0
  44. package/dist/src/net-guard.js +144 -0
  45. package/dist/src/project.d.ts +34 -5
  46. package/dist/src/project.js +145 -111
  47. package/dist/src/report.d.ts +2 -0
  48. package/dist/src/report.js +11 -0
  49. package/dist/src/routes.d.ts +10 -0
  50. package/dist/src/routes.js +21 -4
  51. package/dist/src/safe-fs.d.ts +19 -0
  52. package/dist/src/safe-fs.js +77 -0
  53. package/dist/src/sanitize.d.ts +17 -0
  54. package/dist/src/sanitize.js +90 -0
  55. package/dist/src/sarif.js +1 -1
  56. package/dist/src/summary.d.ts +4 -0
  57. package/dist/src/summary.js +9 -4
  58. package/dist/src/types.d.ts +24 -0
  59. package/dist/src/util.d.ts +1 -1
  60. package/dist/src/util.js +1 -1
  61. package/package.json +9 -5
@@ -0,0 +1,482 @@
1
+ import { evidenceOf, handlersOf, matchBracket, reach } from './routes.js';
2
+ const isPython = (f) => f.path.endsWith('.py');
3
+ const isScript = (f) => /\.[cm]?[jt]sx?$/.test(f.path);
4
+ // ---------- JavaScript / TypeScript ----------
5
+ /** A whole file of Server Actions: "use server" is its first statement. */
6
+ export const FILE_USE_SERVER = /^\s*(?:["']use strict["'];?\s*)?["']use server["']/;
7
+ function skipString(code, i) {
8
+ const q = code[i];
9
+ let j = i + 1;
10
+ while (j < code.length) {
11
+ if (code[j] === '\\')
12
+ j += 2;
13
+ else if (code[j] === q)
14
+ return j + 1;
15
+ else
16
+ j++;
17
+ }
18
+ return code.length;
19
+ }
20
+ /** Where an expression-bodied arrow function ends. */
21
+ function expressionEnd(code, from) {
22
+ let depth = 0;
23
+ for (let i = from; i < code.length; i++) {
24
+ const ch = code[i];
25
+ if (ch === '"' || ch === "'" || ch === '`') {
26
+ i = skipString(code, i) - 1;
27
+ }
28
+ else if (ch === '(' || ch === '[' || ch === '{')
29
+ depth++;
30
+ else if (ch === ')' || ch === ']' || ch === '}') {
31
+ if (depth === 0)
32
+ return i;
33
+ depth--;
34
+ }
35
+ else if (depth === 0 && (ch === ';' || ch === ','))
36
+ return i;
37
+ else if (depth === 0 &&
38
+ ch === '\n' &&
39
+ /^\s*(?:export|const|let|var|function|async|import|class)\b/.test(code.slice(i + 1, i + 40)))
40
+ return i;
41
+ }
42
+ return code.length;
43
+ }
44
+ /**
45
+ * The body of a function whose parameter list opens at `paren`: skips a return type annotation
46
+ * (`: Promise<{ ok: boolean }>`) and an arrow. Returns [start, end) of the body, or null.
47
+ */
48
+ export function bodyAfterParams(code, paren) {
49
+ const close = matchBracket(code, paren);
50
+ if (close === -1)
51
+ return null;
52
+ let angle = 0;
53
+ let prev = ')';
54
+ for (let i = close + 1; i < code.length; i++) {
55
+ const ch = code[i];
56
+ if (/\s/.test(ch))
57
+ continue;
58
+ if (ch === '"' || ch === "'" || ch === '`') {
59
+ i = skipString(code, i) - 1;
60
+ prev = 'x';
61
+ continue;
62
+ }
63
+ if (ch === '=' && code[i + 1] === '>') {
64
+ if (angle > 0) {
65
+ // a function type inside generics: Promise<() => void>
66
+ i++;
67
+ prev = '>';
68
+ continue;
69
+ }
70
+ let j = i + 2;
71
+ while (j < code.length && /\s/.test(code[j]))
72
+ j++;
73
+ if (code[j] === '{') {
74
+ const end = matchBracket(code, j);
75
+ return end === -1 ? null : { start: j, end: end + 1 };
76
+ }
77
+ return { start: j, end: expressionEnd(code, j) };
78
+ }
79
+ if (ch === '<')
80
+ angle++;
81
+ else if (ch === '>')
82
+ angle = Math.max(0, angle - 1);
83
+ else if (ch === '(') {
84
+ const end = matchBracket(code, i);
85
+ if (end === -1)
86
+ return null;
87
+ i = end;
88
+ prev = ')';
89
+ continue;
90
+ }
91
+ else if (ch === '{') {
92
+ const end = matchBracket(code, i);
93
+ if (end === -1)
94
+ return null;
95
+ // An object type in the annotation (": { ok: boolean }") rather than the body.
96
+ if (angle > 0 || /[:|&,<(]/.test(prev)) {
97
+ i = end;
98
+ prev = '}';
99
+ continue;
100
+ }
101
+ return { start: i, end: end + 1 };
102
+ }
103
+ else if (ch === ';')
104
+ return null;
105
+ prev = ch;
106
+ }
107
+ return null;
108
+ }
109
+ function unitFrom(ctx, file, code, start, paren, fields) {
110
+ const close = matchBracket(code, paren);
111
+ const body = bodyAfterParams(code, paren);
112
+ if (close === -1 || !body)
113
+ return null;
114
+ const text = code.slice(start, body.end);
115
+ const reached = reach(ctx, file, text);
116
+ return {
117
+ ...fields,
118
+ file,
119
+ params: code.slice(paren + 1, close),
120
+ text,
121
+ start,
122
+ line: ctx.lineOf(file, start),
123
+ reachedCode: reached.files.map((f) => ctx.codeOf(f)).join('\n'),
124
+ shared: '',
125
+ };
126
+ }
127
+ // "function(?:\s+(\w+))?\s*(?:<...>\s*)?\(" rather than "function\s*(\w*)\s*(?:<...>)?\s*\(": with an empty name, the
128
+ // two \s* could share a long run of spaces in every possible way (quadratic).
129
+ const EXPORTED_ASYNC_FN = /export\s+(?:default\s+)?async\s+function(?:\s+(\w+))?\s*(?:<[^>()]*>\s*)?\(/g;
130
+ const EXPORTED_ASYNC_ARROW = /export\s+const\s+(\w+)\s*(?::[^=;]+)?=\s*async\s*(?:function(?:\s+\w+)?\s*)?\(/g;
131
+ const INLINE_ACTION = /(?:async\s+function\s+(\w+)\s*\(|(?:const|let)\s+(\w+)\s*=\s*async\s*\()/g;
132
+ function serverActions(ctx, file, code) {
133
+ const out = [];
134
+ const fields = (name) => ({
135
+ kind: 'action',
136
+ name,
137
+ method: 'POST',
138
+ urlPath: null,
139
+ paramsFromCaller: true,
140
+ authOutside: false,
141
+ adminOnly: false,
142
+ });
143
+ if (FILE_USE_SERVER.test(code)) {
144
+ // Every exported async function in a "use server" file is an action anyone can POST to.
145
+ for (const re of [EXPORTED_ASYNC_FN, EXPORTED_ASYNC_ARROW]) {
146
+ re.lastIndex = 0;
147
+ for (let m = re.exec(code); m; m = re.exec(code)) {
148
+ const unit = unitFrom(ctx, file, code, m.index, m.index + m[0].length - 1, fields(m[1] || 'default'));
149
+ if (unit)
150
+ out.push(unit);
151
+ }
152
+ }
153
+ return out;
154
+ }
155
+ if (!/["']use server["']/.test(code))
156
+ return out;
157
+ // Inline actions: a function whose body starts with "use server" (inside a Server Component).
158
+ INLINE_ACTION.lastIndex = 0;
159
+ for (let m = INLINE_ACTION.exec(code); m; m = INLINE_ACTION.exec(code)) {
160
+ const paren = m.index + m[0].length - 1;
161
+ const body = bodyAfterParams(code, paren);
162
+ if (!body || !/^\{\s*["']use server["']/.test(code.slice(body.start, body.start + 40)))
163
+ continue;
164
+ const unit = unitFrom(ctx, file, code, m.index, paren, fields(m[1] ?? m[2] ?? ''));
165
+ if (unit)
166
+ out.push(unit);
167
+ }
168
+ return out;
169
+ }
170
+ /** Next.js files that render pages: their default export is a component, not a request handler. */
171
+ const PAGE_FILE = /(^|\/)(?:page|layout|template|loading|error|not-found|default)\.[cm]?[jt]sx?$/;
172
+ function routeHandlers(ctx, file) {
173
+ return handlersOf(ctx, file).map((h) => {
174
+ const paren = h.text.indexOf('(');
175
+ const close = paren === -1 ? -1 : matchBracket(h.text, paren);
176
+ return {
177
+ kind: 'route',
178
+ file,
179
+ name: h.method,
180
+ method: h.method === 'DEFAULT' ? 'ANY' : h.method,
181
+ urlPath: h.urlPath,
182
+ params: close === -1 ? '' : h.text.slice(paren + 1, close),
183
+ text: h.text,
184
+ start: ctx.codeOf(file).indexOf(h.text),
185
+ line: h.line,
186
+ paramsFromCaller: false,
187
+ authOutside: evidenceOf(ctx, h).wrapped,
188
+ adminOnly: /\b\w*[aA]dmin\w*\s*\(/.test(h.head),
189
+ reachedCode: h.reached.map((f) => ctx.codeOf(f)).join('\n'),
190
+ shared: '',
191
+ };
192
+ });
193
+ }
194
+ const EXPRESS_ROUTE = /\b(?:app|router|routes|\w+Router)\.(get|post|put|patch|delete|all)\s*\(\s*(["'`])([^"'`]*)\2/g;
195
+ /** Route middleware that signs the caller in (passed before the handler, or with app.use). */
196
+ const EXPRESS_AUTH_MW = /\b(?:\w*[aA]uth\w*|protect\w*|requireUser|requireLogin|ensureLoggedIn|isLoggedIn|loggedIn|verifyToken|verifyJwt|checkJwt|jwtCheck|requireSession|passport\.authenticate|clerkMiddleware|requireAdmin|isAdmin)\b/;
197
+ /** `app.use([path,] middleware)`: the optional mount path and the first middleware passed. */
198
+ const EXPRESS_USE = /\.use\(\s*(?:(["'`])([^"'`]*)\1\s*,\s*)?([\w$.]+)/g;
199
+ const AUTH_MIDDLEWARE_NAME = /(?:[aA]uth|protect|requireUser|requireLogin|ensureLoggedIn|verifyToken|verifyJwt|checkJwt|jwt|clerkMiddleware)/;
200
+ /** A router mounted with app.use("/api/auth", authRoutes) serves the sign-in pages; it doesn't guard other routes. */
201
+ const ROUTER_NAME = /(?:Routes?|Router|routes?|router|Controller|controller)$/;
202
+ /** app.use(...) sign-in middleware in this file: its mount path ("" = every route) and where it is registered. */
203
+ function authMounts(code) {
204
+ const out = [];
205
+ for (const m of code.matchAll(EXPRESS_USE)) {
206
+ const fn = m[3].split('.').pop();
207
+ if (AUTH_MIDDLEWARE_NAME.test(fn) && !ROUTER_NAME.test(fn))
208
+ out.push({ path: m[2] ?? '', at: m.index });
209
+ }
210
+ return out;
211
+ }
212
+ function expressRoutes(ctx, file, code) {
213
+ const out = [];
214
+ const mounts = authMounts(code);
215
+ // Express runs middleware in the order it is registered: app.use(requireAuth) only guards the routes added
216
+ // after it. A route registered earlier in the file is not protected by it.
217
+ const mountedAuth = (path, routeAt) => mounts.some((p) => p.at < routeAt && (p.path === '' || p.path === '/' || path.startsWith(p.path)));
218
+ EXPRESS_ROUTE.lastIndex = 0;
219
+ for (let m = EXPRESS_ROUTE.exec(code); m; m = EXPRESS_ROUTE.exec(code)) {
220
+ const open = code.indexOf('(', m.index);
221
+ const close = matchBracket(code, open);
222
+ if (close === -1)
223
+ continue;
224
+ const call = code.slice(open, close + 1);
225
+ // The handler is the last function in the call; everything between the path and it is middleware.
226
+ const fnStarts = [
227
+ ...call.matchAll(/(?:async\s*)?(?:function(?:\s+\w+)?\s*)?\(\s*(?:req|request|c|ctx)\b[^)]*\)\s*(?:=>|\{)/g),
228
+ ];
229
+ const last = fnStarts.at(-1);
230
+ if (!last)
231
+ continue;
232
+ const middleware = call.slice(m[0].length - (open - m.index), last.index);
233
+ const reached = reach(ctx, file, call);
234
+ out.push({
235
+ kind: 'express',
236
+ file,
237
+ name: `${m[1].toUpperCase()} ${m[3]}`,
238
+ method: m[1] === 'all' ? 'ANY' : m[1].toUpperCase(),
239
+ urlPath: m[3] || null,
240
+ params: '',
241
+ text: call,
242
+ start: open,
243
+ line: ctx.lineOf(file, m.index),
244
+ paramsFromCaller: false,
245
+ authOutside: mountedAuth(m[3], m.index) || EXPRESS_AUTH_MW.test(middleware),
246
+ adminOnly: /\b\w*[aA]dmin\w*\b/.test(middleware),
247
+ reachedCode: reached.files.map((f) => ctx.codeOf(f)).join('\n'),
248
+ shared: '',
249
+ });
250
+ }
251
+ return out;
252
+ }
253
+ // "\b\w+Procedure": without the \b, a long run of letters was tried from every position (quadratic).
254
+ const TRPC_FILE = /@trpc\/server|createTRPCRouter|\bt\.router\s*\(|\bProcedure\b|\b\w+Procedure\s*[.=]/;
255
+ const TRPC_CALL = /\.(query|mutation)\s*\(/g;
256
+ function trpcProcedures(ctx, file, code) {
257
+ if (!TRPC_FILE.test(code))
258
+ return [];
259
+ const out = [];
260
+ let insideUntil = -1;
261
+ TRPC_CALL.lastIndex = 0;
262
+ for (let m = TRPC_CALL.exec(code); m; m = TRPC_CALL.exec(code)) {
263
+ // A `.query(` inside a procedure body (pool.query, db.query) is SQL, not another procedure.
264
+ if (m.index < insideUntil)
265
+ continue;
266
+ const back = code.slice(Math.max(0, m.index - 800), m.index);
267
+ // "name: protectedProcedure.input(...)" with no statement break before ".query(" / ".mutation(".
268
+ const procs = [...back.matchAll(/(?:\b(\w+)\s*[:=]\s*)?\b(\w*[pP]rocedure)\b/g)];
269
+ const proc = procs.at(-1);
270
+ if (!proc || /;/.test(back.slice(proc.index)))
271
+ continue;
272
+ const open = m.index + m[0].length - 1;
273
+ const close = matchBracket(code, open);
274
+ if (close === -1)
275
+ continue;
276
+ const text = code.slice(open, close + 1);
277
+ insideUntil = close;
278
+ const procName = proc[2];
279
+ const reached = reach(ctx, file, text);
280
+ out.push({
281
+ kind: 'trpc',
282
+ file,
283
+ name: proc[1] ?? procName,
284
+ method: m[1] === 'mutation' ? 'POST' : 'GET',
285
+ urlPath: null,
286
+ params: 'input',
287
+ text,
288
+ start: open,
289
+ line: ctx.lineOf(file, m.index),
290
+ paramsFromCaller: true,
291
+ authOutside: !/^(?:public|un|anon|guest|open)/i.test(procName) &&
292
+ /protected|authed|auth|private|user|admin|member|org|team|signedIn/i.test(procName),
293
+ adminOnly: /admin|superuser|staff/i.test(procName),
294
+ reachedCode: reached.files.map((f) => ctx.codeOf(f)).join('\n'),
295
+ shared: '',
296
+ });
297
+ }
298
+ return out;
299
+ }
300
+ // ---------- Python ----------
301
+ const PY_ROUTE_DECORATOR = /^@\s*[\w.]+\.(get|post|put|patch|delete|route|api_route)\s*\(/;
302
+ /** Decorators and parameters that sign the caller in. */
303
+ export const PY_AUTH_DECORATOR = /^@\s*[\w.]*(?:login_required|jwt_required|auth\w*_required|requires?_auth\w*|token_required|permission_required|staff_member_required|user_passes_test|admin_required|roles_required|roles_accepted|superuser_required|authenticated)\b|^@\s*permission_classes\s*\(\s*\[[^\]]*IsAuthenticated|^@\s*[\w.]*(?:auth|login)\w*\s*$/;
304
+ /** Admin-only views: dependencies=[Depends(get_current_active_superuser)], @staff_member_required, IsAdminUser. */
305
+ const PY_ADMIN = /(?:Depends|Security)\(\s*[\w.]*(?:superuser|admin|staff)\w*|@\s*[\w.]*(?:staff_member_required|superuser_required|admin_required)\b|\bIsAdminUser\b/i;
306
+ const PY_AUTH_PARAM = /(?:Depends|Security)\(\s*[\w.]*(?:user|auth|current|session|token|login|verify|jwt|principal|account|member|admin|claims)\w*/i;
307
+ function pythonDefs(code) {
308
+ const out = [];
309
+ let pending = [];
310
+ let pendingStart = -1;
311
+ let lastEnd = 0;
312
+ const re = /^([ \t]*)(?:(@[\w.]+)|(?:async[ \t]+)?def[ \t]+(\w+)[ \t]*\()/gm;
313
+ for (let m = re.exec(code); m; m = re.exec(code)) {
314
+ if (code.slice(lastEnd, m.index).trim())
315
+ pending = [];
316
+ if (m[2]) {
317
+ if (!pending.length)
318
+ pendingStart = m.index + m[1].length;
319
+ // A decorator; its arguments may span several lines.
320
+ const after = m.index + m[0].length;
321
+ const paren = /^\s*\(/.exec(code.slice(after, after + 20));
322
+ let end = code.indexOf('\n', after);
323
+ if (paren) {
324
+ const close = matchBracket(code, after + paren[0].length - 1);
325
+ if (close !== -1)
326
+ end = close + 1;
327
+ }
328
+ if (end === -1)
329
+ end = code.length;
330
+ pending.push(code.slice(m.index + m[1].length, end));
331
+ lastEnd = end;
332
+ re.lastIndex = end;
333
+ continue;
334
+ }
335
+ out.push({
336
+ name: m[3],
337
+ indent: m[1].replace(/\t/g, ' ').length,
338
+ start: m.index + m[1].length,
339
+ textStart: pending.length ? pendingStart : m.index + m[1].length,
340
+ paren: m.index + m[0].length - 1,
341
+ decorators: pending,
342
+ });
343
+ pending = [];
344
+ lastEnd = m.index + m[0].length;
345
+ }
346
+ return out;
347
+ }
348
+ /** End of a Python function body: the first non-blank line indented no deeper than the def. */
349
+ function pythonBodyEnd(code, def) {
350
+ const close = matchBracket(code, def.paren);
351
+ let pos = close === -1 ? def.paren : close;
352
+ pos = code.indexOf('\n', pos);
353
+ if (pos === -1)
354
+ return code.length;
355
+ pos++;
356
+ while (pos < code.length) {
357
+ let next = code.indexOf('\n', pos);
358
+ if (next === -1)
359
+ next = code.length;
360
+ const line = code.slice(pos, next);
361
+ if (line.trim()) {
362
+ const indent = /^[ \t]*/.exec(line)[0].replace(/\t/g, ' ').length;
363
+ if (indent <= def.indent)
364
+ return pos;
365
+ }
366
+ pos = next + 1;
367
+ }
368
+ return code.length;
369
+ }
370
+ /** FastAPI, Flask and Django views. */
371
+ /**
372
+ * A function in views.py that no URL points at: its name starts with "_", or it is handed an object the URL
373
+ * can't carry (a parameter typed as a model, like "channel: Channel"). Its caller does the checking.
374
+ */
375
+ function isHelperFunction(name, params) {
376
+ if (name.startsWith('_'))
377
+ return true;
378
+ return params
379
+ .split(',')
380
+ .slice(1)
381
+ .some((p) => /:\s*[A-Z]\w*/.test(p) && !/:\s*(?:UUID|Optional|Any|Union|Literal)\b/.test(p));
382
+ }
383
+ function pythonViews(ctx, file, code, projectAuth) {
384
+ const out = [];
385
+ const isViewsFile = /(^|\/)views(?:\.py$|\/)/.test(file.path);
386
+ // Sign-in applied to a whole router, app or blueprint.
387
+ const fileAuth = projectAuth ||
388
+ /(?:APIRouter|FastAPI)\s*\([^)]*dependencies\s*=\s*\[[^\]]*(?:Depends|Security)\(/s.test(code) ||
389
+ /@\w+\.before_(?:app_)?request\b/.test(code);
390
+ for (const def of pythonDefs(code)) {
391
+ const decorators = def.decorators;
392
+ const route = decorators.map((d) => PY_ROUTE_DECORATOR.exec(d)).find(Boolean);
393
+ const apiView = decorators.find((d) => /^@\s*api_view\b/.test(d));
394
+ const close = matchBracket(code, def.paren);
395
+ if (close === -1)
396
+ continue;
397
+ const params = code.slice(def.paren + 1, close);
398
+ const djangoView = isViewsFile && /^\s*request\b/.test(params) && !isHelperFunction(def.name, params);
399
+ if (!route && !apiView && !djangoView)
400
+ continue;
401
+ let method = 'ANY';
402
+ if (route) {
403
+ const verb = route[1].toLowerCase();
404
+ if (verb === 'route' || verb === 'api_route') {
405
+ const listed = /methods\s*=\s*[[(]([^\])]*)[\])]/.exec(decorators.join('\n'))?.[1];
406
+ const verbs = listed ? [...listed.matchAll(/["'](\w+)["']/g)].map((x) => x[1].toUpperCase()) : ['GET'];
407
+ method = verbs.length === 1 ? verbs[0] : verbs.some((v) => v !== 'GET') ? 'ANY' : 'GET';
408
+ }
409
+ else
410
+ method = verb.toUpperCase();
411
+ }
412
+ else if (apiView) {
413
+ const verbs = [...apiView.matchAll(/["'](\w+)["']/g)].map((x) => x[1].toUpperCase());
414
+ method = verbs.length === 1 ? verbs[0] : verbs.some((v) => v !== 'GET') ? 'ANY' : 'GET';
415
+ }
416
+ const end = pythonBodyEnd(code, def);
417
+ const pathArg = route
418
+ ? /\(\s*(?:path\s*=\s*)?["']([^"']*)["']/.exec(decorators.find((d) => PY_ROUTE_DECORATOR.test(d)))
419
+ : null;
420
+ out.push({
421
+ kind: 'python',
422
+ file,
423
+ name: def.name,
424
+ method,
425
+ urlPath: pathArg?.[1] ?? null,
426
+ params,
427
+ // The text starts at the first decorator, so start + index is always a real position in the file.
428
+ text: code.slice(def.textStart, end),
429
+ start: def.textStart,
430
+ line: ctx.lineOf(file, def.start),
431
+ paramsFromCaller: true,
432
+ authOutside: fileAuth || decorators.some((d) => PY_AUTH_DECORATOR.test(d)) || PY_AUTH_PARAM.test(params),
433
+ adminOnly: PY_ADMIN.test(`${decorators.join('\n')}\n${params}`),
434
+ reachedCode: '',
435
+ shared: '',
436
+ });
437
+ }
438
+ return out;
439
+ }
440
+ // ---------- all units ----------
441
+ /** Blank out the units' own text, leaving the helpers and module-level code around them. */
442
+ function sharedText(code, units) {
443
+ const chars = code.split('');
444
+ for (const u of units) {
445
+ if (u.start < 0)
446
+ continue;
447
+ for (let i = u.start; i < u.start + u.text.length && i < chars.length; i++)
448
+ if (chars[i] !== '\n')
449
+ chars[i] = ' ';
450
+ }
451
+ return chars.join('');
452
+ }
453
+ /**
454
+ * Every request entry point in server code.
455
+ * `isServer` says which files run on the server; `projectPythonAuth` is true when sign-in is enforced
456
+ * for every Python view project-wide (Django's LoginRequiredMiddleware, a FastAPI router included with dependencies).
457
+ */
458
+ export function findUnits(ctx, isServer, isRoute, projectPythonAuth) {
459
+ const all = [];
460
+ for (const file of ctx.files) {
461
+ if (!isServer(file))
462
+ continue;
463
+ const code = ctx.codeOf(file);
464
+ let units = [];
465
+ if (isPython(file)) {
466
+ units = pythonViews(ctx, file, code, projectPythonAuth);
467
+ }
468
+ else if (isScript(file)) {
469
+ units = serverActions(ctx, file, code);
470
+ if (!FILE_USE_SERVER.test(code) && !PAGE_FILE.test(file.path) && isRoute(file)) {
471
+ units.push(...routeHandlers(ctx, file), ...expressRoutes(ctx, file, code), ...trpcProcedures(ctx, file, code));
472
+ }
473
+ }
474
+ if (!units.length)
475
+ continue;
476
+ const shared = sharedText(code, units);
477
+ for (const u of units)
478
+ u.shared = shared;
479
+ all.push(...units);
480
+ }
481
+ return all;
482
+ }
@@ -1,4 +1,4 @@
1
- import type { ProjectContext } from './project.js';
1
+ import { type ProjectContext } from './project.js';
2
2
  import type { Finding, Report } from './types.js';
3
3
  export declare const BASELINE_FILE = ".launchdoctor-baseline.json";
4
4
  /**
@@ -6,8 +6,11 @@ export declare const BASELINE_FILE = ".launchdoctor-baseline.json";
6
6
  * It doesn't include the line number, so it survives lines moving up or down.
7
7
  */
8
8
  export declare function fingerprint(ctx: ProjectContext, f: Finding): string;
9
- /** Fingerprints in the project's baseline file, or null if there is none (or it can't be read). */
10
- export declare function loadBaseline(root: string): Set<string> | null;
9
+ /**
10
+ * Fingerprints in the project's baseline file, or null if there is none (or it can't be read).
11
+ * With `configFrom`, the file is read from that git ref instead of the working folder.
12
+ */
13
+ export declare function loadBaseline(root: string, configFrom?: string): Set<string> | null;
11
14
  /** Save every current finding as the new baseline. Returns how many were saved. */
12
15
  export declare function writeBaseline(root: string, report: Report): number;
13
16
  /** Mark findings that are in the baseline. Returns how many matched. */
@@ -1,6 +1,7 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { readFileSync, writeFileSync } from 'node:fs';
3
2
  import { join } from 'node:path';
3
+ import { CONFIG_FILE_MAX_BYTES, readAtRef } from './project.js';
4
+ import { readRegularFile, writeRegularFile } from './safe-fs.js';
4
5
  export const BASELINE_FILE = '.launchdoctor-baseline.json';
5
6
  /**
6
7
  * A stable fingerprint: finding id + file + a hash of the trimmed text of the matched line.
@@ -19,15 +20,21 @@ export function fingerprint(ctx, f) {
19
20
  const hash = createHash('sha256').update(text).digest('hex').slice(0, 16);
20
21
  return `${f.id}|${file}|${hash}`;
21
22
  }
22
- /** Fingerprints in the project's baseline file, or null if there is none (or it can't be read). */
23
- export function loadBaseline(root) {
23
+ /**
24
+ * Fingerprints in the project's baseline file, or null if there is none (or it can't be read).
25
+ * With `configFrom`, the file is read from that git ref instead of the working folder.
26
+ */
27
+ export function loadBaseline(root, configFrom) {
24
28
  let raw;
25
- try {
26
- raw = readFileSync(join(root, BASELINE_FILE), 'utf8');
29
+ if (configFrom) {
30
+ raw = readAtRef(root, configFrom, BASELINE_FILE);
27
31
  }
28
- catch {
29
- return null;
32
+ else {
33
+ // Only a regular file in the project: a symlink or a FIFO counts as no baseline.
34
+ raw = readRegularFile(join(root, BASELINE_FILE), CONFIG_FILE_MAX_BYTES);
30
35
  }
36
+ if (raw === null)
37
+ return null;
31
38
  try {
32
39
  const data = JSON.parse(raw);
33
40
  return new Set((data.findings ?? []).map((e) => e.fingerprint).filter((f) => typeof f === 'string'));
@@ -49,7 +56,7 @@ export function writeBaseline(root, report) {
49
56
  ...(f.location ? { file: f.location.file } : {}),
50
57
  })),
51
58
  };
52
- writeFileSync(join(root, BASELINE_FILE), `${JSON.stringify(data, null, 2)}\n`);
59
+ writeRegularFile(join(root, BASELINE_FILE), `${JSON.stringify(data, null, 2)}\n`);
53
60
  return findings.length;
54
61
  }
55
62
  /** Mark findings that are in the baseline. Returns how many matched. */
@@ -0,0 +1,12 @@
1
+ export type ChangeMode = 'changed' | 'staged';
2
+ /**
3
+ * Files in `root` that changed, as paths relative to `root` written with "/", or null when `root`
4
+ * is not inside a git repository.
5
+ *
6
+ * - changed: edited or added since the last commit (staged or not), plus new files git doesn't ignore.
7
+ * - staged: what is in the index, i.e. what the next commit will contain.
8
+ *
9
+ * Deleted files are left out, since there is nothing left to check. Content is read from the working
10
+ * copy, so a file that is only partly staged is checked as it is on disk.
11
+ */
12
+ export declare function changedFiles(root: string, mode: ChangeMode): string[] | null;
@@ -0,0 +1,34 @@
1
+ import { git, SAFE_DIFF } from './git.js';
2
+ import { findGitRoot } from './project.js';
3
+ /** git prints NUL-separated paths with -z, so names with spaces or odd characters stay intact. */
4
+ const split = (out) => (out ?? '').split('\0').filter(Boolean);
5
+ /**
6
+ * Files in `root` that changed, as paths relative to `root` written with "/", or null when `root`
7
+ * is not inside a git repository.
8
+ *
9
+ * - changed: edited or added since the last commit (staged or not), plus new files git doesn't ignore.
10
+ * - staged: what is in the index, i.e. what the next commit will contain.
11
+ *
12
+ * Deleted files are left out, since there is nothing left to check. Content is read from the working
13
+ * copy, so a file that is only partly staged is checked as it is on disk.
14
+ */
15
+ export function changedFiles(root, mode) {
16
+ if (!findGitRoot(root))
17
+ return null;
18
+ const diff = ['diff', ...SAFE_DIFF, '-z', '--name-only', '--relative', '--diff-filter=ACMR', '--no-renames'];
19
+ const out = new Set();
20
+ if (mode === 'staged') {
21
+ for (const f of split(git(root, [...diff, '--cached'])))
22
+ out.add(f);
23
+ }
24
+ else {
25
+ const hasHead = git(root, ['rev-parse', '--verify', '--quiet', 'HEAD']) !== null;
26
+ // A repository with no commits yet has no HEAD: everything git knows about is new.
27
+ const tracked = hasHead ? split(git(root, [...diff, 'HEAD'])) : split(git(root, ['ls-files', '-z', '--cached']));
28
+ for (const f of tracked)
29
+ out.add(f);
30
+ for (const f of split(git(root, ['ls-files', '-z', '--others', '--exclude-standard'])))
31
+ out.add(f);
32
+ }
33
+ return [...out].map((f) => f.replace(/\\/g, '/')).sort();
34
+ }
@@ -0,0 +1,7 @@
1
+ import { type Unit } from '../access.js';
2
+ import type { Check } from '../types.js';
3
+ type Origin = 'request' | 'session' | 'unknown';
4
+ /** Does this value come from the request, from the signed-in session, or can't we tell? */
5
+ export declare function originOf(expr: string, u: Unit, depth?: number): Origin;
6
+ export declare const accessCheck: Check;
7
+ export {};