vibe-preflight 0.0.0-stage → 0.1.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/.claude-plugin/marketplace.json +11 -0
- package/.claude-plugin/plugin.json +9 -0
- package/LICENSE +21 -0
- package/README.md +88 -2
- package/bin/preflight.js +4 -0
- package/commands/preflight.md +13 -0
- package/examples/vibe-app/.env +2 -0
- package/examples/vibe-app/README.md +3 -0
- package/examples/vibe-app/app/api/stripe/webhook/route.ts +7 -0
- package/examples/vibe-app/index.html +7 -0
- package/examples/vibe-app/package.json +6 -0
- package/examples/vibe-app/server.js +5 -0
- package/examples/vibe-app/src/lib/stripe.ts +3 -0
- package/examples/vibe-app/src/lib/supabase.ts +4 -0
- package/examples/vibe-app/supabase/migrations/001_init.sql +11 -0
- package/package.json +22 -4
- package/src/cli.js +93 -0
- package/src/demo.js +43 -0
- package/src/project.js +112 -0
- package/src/report/colors.js +12 -0
- package/src/report/html.js +133 -0
- package/src/report/terminal.js +59 -0
- package/src/rules/_client-paths.js +19 -0
- package/src/rules/_gitignore.js +24 -0
- package/src/rules/_template.js +33 -0
- package/src/rules/cors-wildcard.js +30 -0
- package/src/rules/env-file-committed.js +18 -0
- package/src/rules/index.js +12 -0
- package/src/rules/missing-meta-tags.js +43 -0
- package/src/rules/no-error-monitoring.js +17 -0
- package/src/rules/no-privacy-policy.js +20 -0
- package/src/rules/secret-in-client.js +44 -0
- package/src/rules/stripe-webhook-unverified.js +26 -0
- package/src/rules/supabase-rls-disabled.js +36 -0
- package/src/run.js +30 -0
- package/src/score.js +30 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "preflight",
|
|
3
|
+
"description": "Check whether your vibe-coded app is ready to launch: leaked keys, open databases, unverified payments and missing launch basics, with a fix for every finding.",
|
|
4
|
+
"version": "0.1.0",
|
|
5
|
+
"author": { "name": "erdellll" },
|
|
6
|
+
"homepage": "https://github.com/erdellll/preflight",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"keywords": ["launch", "security", "checklist", "vibe-coding"]
|
|
9
|
+
}
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 erdellll
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,89 @@
|
|
|
1
|
-
|
|
1
|
+
<div align="center">
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
# ✈️ Preflight
|
|
4
|
+
|
|
5
|
+
**Is your vibe-coded app ready to launch? Find out in one command.**
|
|
6
|
+
|
|
7
|
+
Preflight scans your project for leaked keys, open databases, unverified payments and missing launch basics, then gives you a report card with a fix for every finding.
|
|
8
|
+
|
|
9
|
+
[](LICENSE)
|
|
10
|
+
[](package.json)
|
|
11
|
+
[](CONTRIBUTING.md)
|
|
12
|
+
|
|
13
|
+

|
|
14
|
+
|
|
15
|
+
</div>
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npx vibe-preflight
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
No install, no account, no network calls. Your code never leaves your machine.
|
|
22
|
+
|
|
23
|
+
## Why
|
|
24
|
+
|
|
25
|
+
AI tools make it easy to build an app in a weekend, and just as easy to ship it with your Stripe secret key in the browser bundle or a Supabase table anyone can read. Preflight checks for the mistakes that hurt most after launch, before you launch.
|
|
26
|
+
|
|
27
|
+
## Try it on a broken app first
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
npx vibe-preflight --demo
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Scans a deliberately broken demo app (every secret is fake) so you can see what a failing report looks like.
|
|
34
|
+
|
|
35
|
+
## What it checks
|
|
36
|
+
|
|
37
|
+
8 checks today, across security, reliability and launch basics. See [all checks](docs/rules.md).
|
|
38
|
+
|
|
39
|
+
| | |
|
|
40
|
+
|---|---|
|
|
41
|
+
| 🔑 Live secrets in client code | 🗄️ Supabase tables without row-level security |
|
|
42
|
+
| 📄 `.env` files that can be committed | 💳 Stripe webhooks without signature checks |
|
|
43
|
+
| 🌍 CORS open to every website | 🚨 No error monitoring |
|
|
44
|
+
| 🔒 No privacy policy | 🔗 Missing title, description or share image |
|
|
45
|
+
|
|
46
|
+
## Options
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
npx vibe-preflight [path] # scan a folder (default: current folder)
|
|
50
|
+
npx vibe-preflight --html # also write a shareable preflight-report.html
|
|
51
|
+
npx vibe-preflight --json # machine-readable output
|
|
52
|
+
npx vibe-preflight --ignore a,b # skip checks by id
|
|
53
|
+
npx vibe-preflight --fail-on warning # exit code policy: critical (default) | warning | never
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Silence a finding that points at a line with `// preflight-ignore <check-id>` on that line or the line above. For findings about a whole file or project (for example a missing privacy page), skip the check with `--ignore <check-id>`.
|
|
57
|
+
|
|
58
|
+
## Use it in CI
|
|
59
|
+
|
|
60
|
+
```yaml
|
|
61
|
+
- run: npx vibe-preflight --fail-on critical
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
The command exits with code 1 when a finding reaches the `--fail-on` level, so a leaked key blocks the merge.
|
|
65
|
+
|
|
66
|
+
## Use it inside Claude Code
|
|
67
|
+
|
|
68
|
+
Preflight ships as a Claude Code plugin with a `/preflight` command that runs the scan, explains the results and offers to fix critical issues one at a time, asking before every change.
|
|
69
|
+
|
|
70
|
+
In Claude Code, run:
|
|
71
|
+
|
|
72
|
+
```text
|
|
73
|
+
/plugin marketplace add erdellll/preflight
|
|
74
|
+
/plugin install preflight@preflight
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Then type `/preflight` in any project.
|
|
78
|
+
|
|
79
|
+
## Add a check in 10 minutes
|
|
80
|
+
|
|
81
|
+
Every check is one small file plus two example folders, one it must flag and one it must leave alone. No build step, no dependencies. Read [CONTRIBUTING.md](CONTRIBUTING.md), or pick an issue labelled [`good first issue`](https://github.com/erdellll/preflight/issues?q=is%3Aopen+label%3A%22good+first+issue%22).
|
|
82
|
+
|
|
83
|
+
## Not a security audit
|
|
84
|
+
|
|
85
|
+
Preflight catches common, high-impact mistakes with fast pattern checks. A clean report means none of its checks fired, not that your app is secure. Use it as a seatbelt, not a substitute for a review.
|
|
86
|
+
|
|
87
|
+
## License
|
|
88
|
+
|
|
89
|
+
[MIT](LICENSE). Free for any use.
|
package/bin/preflight.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: Check whether this app is ready to launch and help fix what's blocking it
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
Run Preflight on the current project and help the user fix what it finds.
|
|
6
|
+
|
|
7
|
+
1. Run `node "${CLAUDE_PLUGIN_ROOT}/bin/preflight.js" --json --fail-on never` in the project root and parse the JSON report. If that path is unavailable, fall back to `npx -y vibe-preflight --json --fail-on never`.
|
|
8
|
+
2. Summarise it in a few lines: the score out of 100, the grade, and the number of critical issues, warnings and info items.
|
|
9
|
+
3. List the findings grouped by category, critical first, each with its `file:line` and the fix Preflight suggests.
|
|
10
|
+
4. Offer to fix the critical findings one at a time. Before each change, say which file you'll edit and what you'll do, and wait for the user's OK. Never print a secret value; if a key was exposed, remind the user to rotate it with the provider, since removing it from the code is not enough.
|
|
11
|
+
5. After the fixes, run the same command without `--json` and show the new score.
|
|
12
|
+
|
|
13
|
+
If the user asks for a shareable report, run the same command with `--html` and tell them where `preflight-report.html` was written.
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "vibe-app",
|
|
3
|
+
"private": true,
|
|
4
|
+
"description": "A deliberately broken demo app for Preflight. Every secret here is fake.",
|
|
5
|
+
"dependencies": { "next": "^16.0.0", "react": "^19.0.0", "@supabase/supabase-js": "^2.50.0", "stripe": "^19.0.0", "cors": "^2.8.5" }
|
|
6
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { createClient } from '@supabase/supabase-js';
|
|
2
|
+
// Demo only: fake service_role key that should never ship to the browser.
|
|
3
|
+
export const supabase = createClient('https://demo.supabase.co', '__SERVICE_ROLE_JWT__');
|
|
4
|
+
export const signUp = (email: string, password: string) => supabase.auth.signUp({ email, password });
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
create table public.profiles (
|
|
2
|
+
id uuid primary key references auth.users,
|
|
3
|
+
email text,
|
|
4
|
+
plan text default 'free'
|
|
5
|
+
);
|
|
6
|
+
|
|
7
|
+
create table public.payments (
|
|
8
|
+
id bigint generated always as identity primary key,
|
|
9
|
+
user_id uuid references public.profiles,
|
|
10
|
+
amount integer
|
|
11
|
+
);
|
package/package.json
CHANGED
|
@@ -1,6 +1,24 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vibe-preflight",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Is your vibe-coded app ready to launch? One command checks for leaked keys, open databases and missing launch basics, then gives you a report card.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"vibe-preflight": "bin/preflight.js",
|
|
8
|
+
"preflight": "bin/preflight.js"
|
|
9
|
+
},
|
|
10
|
+
"files": ["bin", "src", "examples", ".claude-plugin", "commands"],
|
|
11
|
+
"scripts": {
|
|
12
|
+
"test": "node --test"
|
|
13
|
+
},
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=20"
|
|
16
|
+
},
|
|
17
|
+
"keywords": ["vibe-coding", "launch", "checklist", "security", "supabase", "stripe", "cli", "claude-code"],
|
|
18
|
+
"author": "erdellll",
|
|
19
|
+
"license": "MIT",
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "git+https://github.com/erdellll/preflight.git"
|
|
23
|
+
}
|
|
24
|
+
}
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { parseArgs } from 'node:util';
|
|
2
|
+
import { existsSync, statSync, writeFileSync, readFileSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { run } from './run.js';
|
|
5
|
+
import { renderTerminal } from './report/terminal.js';
|
|
6
|
+
import { renderHtml } from './report/html.js';
|
|
7
|
+
import { buildDemo } from './demo.js';
|
|
8
|
+
|
|
9
|
+
const LEVELS = { critical: ['critical'], warning: ['critical', 'warning'], never: [] };
|
|
10
|
+
|
|
11
|
+
const HELP = `vibe-preflight: is your vibe-coded app ready to launch?
|
|
12
|
+
|
|
13
|
+
Usage
|
|
14
|
+
npx vibe-preflight [path] [options]
|
|
15
|
+
|
|
16
|
+
Options
|
|
17
|
+
--html [file] also write a shareable report card (default: preflight-report.html)
|
|
18
|
+
--json print the report as JSON instead of the card
|
|
19
|
+
--demo scan a deliberately broken demo app (fake secrets) to see Preflight in action
|
|
20
|
+
--ignore <ids> comma-separated check ids to skip
|
|
21
|
+
--fail-on <level> critical (default) | warning | never; sets the exit code for CI
|
|
22
|
+
-v, --version print the version
|
|
23
|
+
-h, --help show this help
|
|
24
|
+
|
|
25
|
+
Silence one finding with a comment on the line or the line above:
|
|
26
|
+
// preflight-ignore <check-id>
|
|
27
|
+
`;
|
|
28
|
+
|
|
29
|
+
function version() {
|
|
30
|
+
return JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Runs the CLI. Returns the exit code instead of exiting, so it can be tested.
|
|
35
|
+
* @param {string[]} argv
|
|
36
|
+
* @param {{ cwd: string, stdout: { write(s: string): void }, stderr: { write(s: string): void } }} io
|
|
37
|
+
*/
|
|
38
|
+
export async function main(argv, io) {
|
|
39
|
+
let args;
|
|
40
|
+
try {
|
|
41
|
+
// --html takes an optional file, which parseArgs can't express: normalise it first.
|
|
42
|
+
const norm = [];
|
|
43
|
+
for (let i = 0; i < argv.length; i++) {
|
|
44
|
+
if (argv[i] === '--html') {
|
|
45
|
+
const next = argv[i + 1];
|
|
46
|
+
norm.push('--html', next && !next.startsWith('-') && next.endsWith('.html') ? argv[++i] : 'preflight-report.html');
|
|
47
|
+
} else norm.push(argv[i]);
|
|
48
|
+
}
|
|
49
|
+
args = parseArgs({
|
|
50
|
+
args: norm,
|
|
51
|
+
allowPositionals: true,
|
|
52
|
+
options: {
|
|
53
|
+
html: { type: 'string' },
|
|
54
|
+
json: { type: 'boolean' },
|
|
55
|
+
demo: { type: 'boolean' },
|
|
56
|
+
ignore: { type: 'string' },
|
|
57
|
+
'fail-on': { type: 'string', default: 'critical' },
|
|
58
|
+
version: { type: 'boolean', short: 'v' },
|
|
59
|
+
help: { type: 'boolean', short: 'h' },
|
|
60
|
+
},
|
|
61
|
+
});
|
|
62
|
+
} catch (err) {
|
|
63
|
+
io.stderr.write(`${err.message}\n\nRun with --help for usage.\n`);
|
|
64
|
+
return 2;
|
|
65
|
+
}
|
|
66
|
+
const { values, positionals } = args;
|
|
67
|
+
if (values.help) { io.stdout.write(HELP); return 0; }
|
|
68
|
+
if (values.version) { io.stdout.write(`${version()}\n`); return 0; }
|
|
69
|
+
if (!LEVELS[values['fail-on']]) {
|
|
70
|
+
io.stderr.write(`--fail-on must be critical, warning or never (got "${values['fail-on']}").\n`);
|
|
71
|
+
return 2;
|
|
72
|
+
}
|
|
73
|
+
const root = values.demo ? buildDemo() : path.resolve(io.cwd, positionals[0] ?? '.');
|
|
74
|
+
if (!existsSync(root) || !statSync(root).isDirectory()) {
|
|
75
|
+
io.stderr.write(`Folder not found: ${root}\n`);
|
|
76
|
+
return 2;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const report = await run(root, { ignore: values.ignore ? values.ignore.split(',').map((s) => s.trim()).filter(Boolean) : [] });
|
|
80
|
+
|
|
81
|
+
if (values.demo && !values.json) io.stdout.write('Scanning the Preflight demo app (deliberately broken, every secret is fake)...\n\n');
|
|
82
|
+
if (values.json) io.stdout.write(JSON.stringify(report, null, 2) + '\n');
|
|
83
|
+
else io.stdout.write(renderTerminal(report));
|
|
84
|
+
|
|
85
|
+
if (values.html) {
|
|
86
|
+
const file = path.resolve(io.cwd, values.html);
|
|
87
|
+
writeFileSync(file, renderHtml(report));
|
|
88
|
+
if (!values.json) io.stdout.write(`Report card written to ${path.relative(io.cwd, file) || file}\n`);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const failing = LEVELS[values['fail-on']];
|
|
92
|
+
return report.results.some((r) => failing.includes(r.severity)) ? 1 : 0;
|
|
93
|
+
}
|
package/src/demo.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { cpSync, mkdtempSync, readdirSync, readFileSync, writeFileSync, statSync } from 'node:fs';
|
|
2
|
+
import { tmpdir } from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Fake secrets are assembled at runtime instead of being committed, so the repo
|
|
8
|
+
* never contains strings that look like real keys to secret scanners.
|
|
9
|
+
*/
|
|
10
|
+
export const PLACEHOLDERS = {
|
|
11
|
+
__STRIPE_LIVE__: ['sk', 'live', '51HdemoFAKEkey'].join('_') + '0'.repeat(20),
|
|
12
|
+
__ANTHROPIC_KEY__: ['sk', 'ant', 'api03'].join('-') + '-FAKEdemoKEY' + '0'.repeat(20),
|
|
13
|
+
__OPENAI_KEY__: ['sk', 'proj'].join('-') + '-FAKEdemoKEY' + '0'.repeat(20),
|
|
14
|
+
__AWS_KEY__: 'AKIA' + 'FAKEDEMO00000000',
|
|
15
|
+
__ANON_JWT__: 'eyJ' + 'hbGciOiJIUzI1NiJ9.eyJyb2xlIjoiYW5vbiJ9.FAKEsignature',
|
|
16
|
+
__SERVICE_ROLE_JWT__: 'eyJ' + 'hbGciOiJIUzI1NiJ9.eyJyb2xlIjoic2VydmljZV9yb2xlIn0.FAKEsignature',
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/** Replaces every placeholder in every file under `dir`, in place. */
|
|
20
|
+
export function fillPlaceholders(dir) {
|
|
21
|
+
for (const name of readdirSync(dir)) {
|
|
22
|
+
const full = path.join(dir, name);
|
|
23
|
+
if (statSync(full).isDirectory()) fillPlaceholders(full);
|
|
24
|
+
else {
|
|
25
|
+
let text = readFileSync(full, 'utf8');
|
|
26
|
+
for (const [k, v] of Object.entries(PLACEHOLDERS)) text = text.split(k).join(v);
|
|
27
|
+
writeFileSync(full, text);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Copies a template folder to a fresh temp dir with placeholders filled. */
|
|
33
|
+
export function materialize(src, label = 'demo') {
|
|
34
|
+
const dest = mkdtempSync(path.join(tmpdir(), `preflight-${label}-`));
|
|
35
|
+
cpSync(src, dest, { recursive: true });
|
|
36
|
+
fillPlaceholders(dest);
|
|
37
|
+
return dest;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Builds the deliberately broken demo app and returns its folder. */
|
|
41
|
+
export function buildDemo() {
|
|
42
|
+
return materialize(fileURLToPath(new URL('../examples/vibe-app/', import.meta.url)), 'demo');
|
|
43
|
+
}
|
package/src/project.js
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { readdir, stat } from 'node:fs/promises';
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { existsSync } from 'node:fs';
|
|
5
|
+
import { isGitignored } from './rules/_gitignore.js';
|
|
6
|
+
|
|
7
|
+
/** Directories that are never scanned: dependencies, VCS data and build output. */
|
|
8
|
+
export const SKIP_DIRS = new Set([
|
|
9
|
+
'node_modules', '.git', 'dist', 'build', '.next', 'out', 'coverage', '.vercel',
|
|
10
|
+
'.svelte-kit', '.nuxt', '.turbo', '.cache', '.expo', 'Pods', 'DerivedData', '.output', '.parcel-cache',
|
|
11
|
+
'.venv', 'venv', '__pycache__', 'vendor', 'target', '.gradle', '.dart_tool', '.terraform', 'bower_components', '.yarn',
|
|
12
|
+
]);
|
|
13
|
+
|
|
14
|
+
/** Files larger than this are skipped (bundles, dumps, generated code). */
|
|
15
|
+
export const MAX_FILE_BYTES = 1024 * 1024;
|
|
16
|
+
|
|
17
|
+
const BINARY_EXT = new Set([
|
|
18
|
+
'.png', '.jpg', '.jpeg', '.gif', '.webp', '.avif', '.ico', '.icns', '.bmp', '.tiff', '.psd',
|
|
19
|
+
'.woff', '.woff2', '.ttf', '.otf', '.eot',
|
|
20
|
+
'.zip', '.gz', '.tgz', '.bz2', '.xz', '.7z', '.rar', '.jar',
|
|
21
|
+
'.mp3', '.mp4', '.mov', '.wav', '.ogg', '.webm', '.m4a', '.avi',
|
|
22
|
+
'.pdf', '.exe', '.dll', '.so', '.dylib', '.bin', '.wasm', '.sqlite', '.db', '.lockb',
|
|
23
|
+
]);
|
|
24
|
+
|
|
25
|
+
async function walk(root, dir, out) {
|
|
26
|
+
let entries;
|
|
27
|
+
try {
|
|
28
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
29
|
+
} catch {
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
for (const entry of entries) {
|
|
33
|
+
const full = path.join(dir, entry.name);
|
|
34
|
+
if (entry.isDirectory()) {
|
|
35
|
+
if (!SKIP_DIRS.has(entry.name)) await walk(root, full, out);
|
|
36
|
+
} else if (entry.isFile()) {
|
|
37
|
+
if (BINARY_EXT.has(path.extname(entry.name).toLowerCase())) continue;
|
|
38
|
+
try {
|
|
39
|
+
if ((await stat(full)).size > MAX_FILE_BYTES) continue;
|
|
40
|
+
} catch {
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
out.push(path.relative(root, full).split(path.sep).join('/'));
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Builds the view of a project that every rule receives.
|
|
50
|
+
* @param {string} root
|
|
51
|
+
*/
|
|
52
|
+
export async function loadProject(root) {
|
|
53
|
+
const files = [];
|
|
54
|
+
await walk(root, root, files);
|
|
55
|
+
files.sort();
|
|
56
|
+
const cache = new Map();
|
|
57
|
+
const read = (file) => {
|
|
58
|
+
if (!cache.has(file)) {
|
|
59
|
+
let text = '';
|
|
60
|
+
try {
|
|
61
|
+
text = readFileSync(path.join(root, file), 'utf8');
|
|
62
|
+
} catch {
|
|
63
|
+
text = '';
|
|
64
|
+
}
|
|
65
|
+
cache.set(file, text);
|
|
66
|
+
}
|
|
67
|
+
return cache.get(file);
|
|
68
|
+
};
|
|
69
|
+
const gitignore = files.includes('.gitignore')
|
|
70
|
+
? read('.gitignore').split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !l.startsWith('#'))
|
|
71
|
+
: [];
|
|
72
|
+
// .gitignore files that apply: parents up to the repo root (outermost first), then nested ones.
|
|
73
|
+
const sources = [];
|
|
74
|
+
const parents = [];
|
|
75
|
+
for (let dir = path.dirname(path.resolve(root)); ; dir = path.dirname(dir)) {
|
|
76
|
+
if (existsSync(path.join(dir, '.gitignore'))) parents.unshift(dir);
|
|
77
|
+
if (existsSync(path.join(dir, '.git')) || path.dirname(dir) === dir) break;
|
|
78
|
+
}
|
|
79
|
+
if (existsSync(path.join(root, '.git'))) parents.length = 0;
|
|
80
|
+
const parse = (text) => text.split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !l.startsWith('#'));
|
|
81
|
+
for (const dir of parents) {
|
|
82
|
+
let text = '';
|
|
83
|
+
try { text = readFileSync(path.join(dir, '.gitignore'), 'utf8'); } catch { text = ''; }
|
|
84
|
+
sources.push({ base: path.relative(dir, path.resolve(root)).split(path.sep).join('/'), patterns: parse(text) });
|
|
85
|
+
}
|
|
86
|
+
for (const f of files.filter((f) => f === '.gitignore' || f.endsWith('/.gitignore'))) {
|
|
87
|
+
const dir = f.includes('/') ? f.slice(0, f.lastIndexOf('/')) : '';
|
|
88
|
+
sources.push({ prefix: dir, patterns: parse(read(f)) });
|
|
89
|
+
}
|
|
90
|
+
const isIgnored = (file) => {
|
|
91
|
+
let ignored = false;
|
|
92
|
+
for (const src of sources) {
|
|
93
|
+
let rel;
|
|
94
|
+
if ('base' in src) rel = src.base ? `${src.base}/${file}` : file;
|
|
95
|
+
else if (!src.prefix) rel = file;
|
|
96
|
+
else if (file.startsWith(src.prefix + '/')) rel = file.slice(src.prefix.length + 1);
|
|
97
|
+
else continue;
|
|
98
|
+
const verdict = isGitignored(rel, src.patterns, null);
|
|
99
|
+
if (verdict !== null) ignored = verdict;
|
|
100
|
+
}
|
|
101
|
+
return ignored;
|
|
102
|
+
};
|
|
103
|
+
return {
|
|
104
|
+
root,
|
|
105
|
+
isIgnored,
|
|
106
|
+
files,
|
|
107
|
+
read,
|
|
108
|
+
lines: (file) => read(file).split(/\r?\n/),
|
|
109
|
+
has: (pattern) => files.some((f) => pattern.test(f)),
|
|
110
|
+
gitignore,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
const CODES = { bold: 1, dim: 2, red: 31, green: 32, yellow: 33, blue: 34, magenta: 35, cyan: 36, gray: 90 };
|
|
2
|
+
|
|
3
|
+
/** Returns a palette of colour functions; all are identity when `enabled` is false. */
|
|
4
|
+
export function palette(enabled) {
|
|
5
|
+
const p = {};
|
|
6
|
+
for (const [name, code] of Object.entries(CODES)) p[name] = (s) => (enabled ? `\x1b[${code}m${s}\x1b[0m` : String(s));
|
|
7
|
+
return p;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export const gradeColor = (grade) => ({ A: 'green', B: 'green', C: 'yellow', D: 'red', F: 'red' }[grade]);
|
|
11
|
+
export const severityColor = (sev) => ({ critical: 'red', warning: 'yellow', info: 'gray' }[sev]);
|
|
12
|
+
export const stripAnsi = (s) => s.replace(/\x1b\[[0-9;]*m/g, '');
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { CATEGORIES } from '../score.js';
|
|
2
|
+
|
|
3
|
+
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (ch) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[ch]));
|
|
4
|
+
|
|
5
|
+
/** Escapes text, then turns `code` spans into inline code. */
|
|
6
|
+
const rich = (s) => esc(s).replace(/`([^`]+)`/g, '<code class="inline">$1</code>');
|
|
7
|
+
|
|
8
|
+
const GRADE_COLOR = { A: '#34d399', B: '#a3e635', C: '#fbbf24', D: '#fb923c', F: '#f87171' };
|
|
9
|
+
const SEVERITY_COLOR = { critical: '#f87171', warning: '#fbbf24', info: '#94a3b8' };
|
|
10
|
+
const SEVERITY_ORDER = { critical: 0, warning: 1, info: 2 };
|
|
11
|
+
const CATEGORY_LABEL = { security: 'Security', reliability: 'Reliability', launch: 'Launch basics' };
|
|
12
|
+
const VERDICT = {
|
|
13
|
+
A: 'Cleared for takeoff.',
|
|
14
|
+
B: 'Nearly there. A few things to tidy.',
|
|
15
|
+
C: 'Fix the red items before you launch.',
|
|
16
|
+
D: 'Not ready to launch yet.',
|
|
17
|
+
F: 'Grounded. Fix the critical issues first.',
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
function gauge(score, color) {
|
|
21
|
+
const r = 70;
|
|
22
|
+
const circumference = 2 * Math.PI * r;
|
|
23
|
+
const offset = circumference * (1 - score / 100);
|
|
24
|
+
return `<svg class="gauge" viewBox="0 0 180 180" role="img" aria-label="Score ${score} out of 100">
|
|
25
|
+
<circle cx="90" cy="90" r="${r}" fill="none" stroke="#1f2430" stroke-width="14"/>
|
|
26
|
+
<circle cx="90" cy="90" r="${r}" fill="none" stroke="${color}" stroke-width="14" stroke-linecap="round"
|
|
27
|
+
stroke-dasharray="${circumference.toFixed(2)}" stroke-dashoffset="${offset.toFixed(2)}" transform="rotate(-90 90 90)"/>
|
|
28
|
+
<text x="90" y="92" text-anchor="middle" class="gauge-score" fill="${color}" style="fill:${color}">${score}</text>
|
|
29
|
+
<text x="90" y="118" text-anchor="middle" class="gauge-out">/ 100</text>
|
|
30
|
+
</svg>`;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function categoryBars(report) {
|
|
34
|
+
const max = Math.max(1, ...CATEGORIES.map((c) => report.byCategory[c] ?? 0));
|
|
35
|
+
return CATEGORIES.map((c) => {
|
|
36
|
+
const n = report.byCategory[c] ?? 0;
|
|
37
|
+
const width = n === 0 ? 100 : Math.max(8, Math.round((n / max) * 100));
|
|
38
|
+
const color = n === 0 ? '#34d399' : report.results.some((r) => r.category === c && r.severity === 'critical') ? '#f87171' : '#fbbf24';
|
|
39
|
+
return `<div class="bar"><span class="bar-label">${CATEGORY_LABEL[c]}</span><span class="bar-track"><span class="bar-fill" style="width:${width}%;background:${color}"></span></span><span class="bar-count">${n === 0 ? '✓' : n}</span></div>`;
|
|
40
|
+
}).join('\n');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function findingCards(report) {
|
|
44
|
+
if (!report.results.length) return '<div class="clean">No issues found. Ready for takeoff.</div>';
|
|
45
|
+
return CATEGORIES.map((c) => {
|
|
46
|
+
const items = report.results.filter((r) => r.category === c).sort((a, b) => SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity]);
|
|
47
|
+
if (!items.length) return '';
|
|
48
|
+
return `<h2>${CATEGORY_LABEL[c]}</h2>\n` + items.map((r) => `<article class="finding" style="--sev:${SEVERITY_COLOR[r.severity]}">
|
|
49
|
+
<div class="finding-head"><span class="pill">${esc(r.severity)}</span><h3>${esc(r.title)}</h3></div>
|
|
50
|
+
${r.file ? `<code>${esc(r.line ? `${r.file}:${r.line}` : r.file)}</code>` : ''}
|
|
51
|
+
<p>${rich(r.message)}</p>
|
|
52
|
+
<p class="fix"><span>Fix</span>${rich(r.fix)}</p>
|
|
53
|
+
</article>`).join('\n');
|
|
54
|
+
}).join('\n');
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Renders a self-contained, shareable HTML report card.
|
|
59
|
+
* @param {object} report from run()
|
|
60
|
+
*/
|
|
61
|
+
export function renderHtml(report) {
|
|
62
|
+
const color = GRADE_COLOR[report.grade];
|
|
63
|
+
const { critical, warning, info } = report.counts;
|
|
64
|
+
return `<!doctype html>
|
|
65
|
+
<html lang="en">
|
|
66
|
+
<head>
|
|
67
|
+
<meta charset="utf-8">
|
|
68
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
69
|
+
<title>Preflight report: ${report.score}/100 (${report.grade})</title>
|
|
70
|
+
<style>
|
|
71
|
+
:root { color-scheme: dark; }
|
|
72
|
+
* { box-sizing: border-box; }
|
|
73
|
+
body { margin: 0; background: radial-gradient(1200px 600px at 50% -200px, #1a2033, #0b0d12 60%); color: #e5e7eb;
|
|
74
|
+
font: 15px/1.55 ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
|
|
75
|
+
main { max-width: 880px; margin: 0 auto; padding: 48px 20px 64px; }
|
|
76
|
+
.brand { display: flex; justify-content: space-between; align-items: center; color: #94a3b8; font-size: 13px; letter-spacing: .14em; text-transform: uppercase; }
|
|
77
|
+
.brand b { color: #e5e7eb; letter-spacing: .2em; }
|
|
78
|
+
.card { margin-top: 18px; background: linear-gradient(180deg, #131722, #0f121a); border: 1px solid #222838; border-radius: 22px; padding: 32px; box-shadow: 0 30px 80px -30px rgba(0,0,0,.7); }
|
|
79
|
+
.hero { display: grid; grid-template-columns: 180px 1fr; gap: 32px; align-items: center; }
|
|
80
|
+
.gauge { width: 180px; height: 180px; }
|
|
81
|
+
.gauge-score { fill: #f8fafc; font-size: 48px; font-weight: 800; }
|
|
82
|
+
.gauge-out { fill: #64748b; font-size: 14px; }
|
|
83
|
+
.grade { display: inline-block; font-weight: 800; font-size: 22px; color: ${color}; }
|
|
84
|
+
.verdict { font-size: 26px; font-weight: 700; margin: 4px 0 10px; color: #f8fafc; }
|
|
85
|
+
.counts { display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 18px; }
|
|
86
|
+
.count { border: 1px solid #262c3b; border-radius: 999px; padding: 4px 12px; font-size: 13px; color: #cbd5e1; }
|
|
87
|
+
.count i { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 6px; }
|
|
88
|
+
.bar { display: grid; grid-template-columns: 110px 1fr 28px; gap: 12px; align-items: center; margin: 7px 0; font-size: 13px; color: #94a3b8; }
|
|
89
|
+
.bar-track { height: 8px; background: #1f2430; border-radius: 999px; overflow: hidden; }
|
|
90
|
+
.bar-fill { display: block; height: 100%; border-radius: 999px; }
|
|
91
|
+
.bar-count { text-align: right; color: #cbd5e1; font-weight: 600; }
|
|
92
|
+
h2 { margin: 36px 0 12px; font-size: 13px; letter-spacing: .14em; text-transform: uppercase; color: #94a3b8; }
|
|
93
|
+
.finding { background: #121621; border: 1px solid #222838; border-left: 3px solid var(--sev); border-radius: 14px; padding: 16px 18px; margin: 10px 0; }
|
|
94
|
+
.finding-head { display: flex; gap: 10px; align-items: center; }
|
|
95
|
+
.finding h3 { margin: 0; font-size: 16px; color: #f1f5f9; }
|
|
96
|
+
.pill { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: .08em; color: var(--sev); border: 1px solid var(--sev); border-radius: 999px; padding: 1px 8px; }
|
|
97
|
+
code { display: inline-block; margin-top: 8px; font: 12.5px ui-monospace, SFMono-Regular, Menlo, monospace; color: #7dd3fc; background: #0b0e15; border: 1px solid #1e2433; border-radius: 8px; padding: 2px 8px; }
|
|
98
|
+
.finding p { margin: 8px 0 0; color: #cbd5e1; }
|
|
99
|
+
.fix { color: #d1fae5 !important; }
|
|
100
|
+
code.inline { display: inline; margin: 0; padding: 1px 6px; font-size: 12.5px; color: #e2e8f0; }
|
|
101
|
+
.fix span { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: .08em; color: #34d399; margin-right: 8px; }
|
|
102
|
+
.clean { margin-top: 28px; padding: 22px; text-align: center; border: 1px dashed #2f3b2f; border-radius: 14px; color: #a7f3d0; font-weight: 600; }
|
|
103
|
+
footer { margin-top: 28px; text-align: center; color: #64748b; font-size: 12.5px; }
|
|
104
|
+
footer a { color: #94a3b8; }
|
|
105
|
+
@media (max-width: 640px) { .hero { grid-template-columns: 1fr; justify-items: center; text-align: center; } .counts { justify-content: center; } .card { padding: 22px; } }
|
|
106
|
+
</style>
|
|
107
|
+
</head>
|
|
108
|
+
<body>
|
|
109
|
+
<main>
|
|
110
|
+
<div class="brand"><b>Preflight</b><span>Launch readiness report</span></div>
|
|
111
|
+
<section class="card">
|
|
112
|
+
<div class="hero">
|
|
113
|
+
${gauge(report.score, color)}
|
|
114
|
+
<div>
|
|
115
|
+
<span class="grade">Grade ${report.grade}</span>
|
|
116
|
+
<div class="verdict">${VERDICT[report.grade]}</div>
|
|
117
|
+
<div class="counts">
|
|
118
|
+
<span class="count"><i style="background:${SEVERITY_COLOR.critical}"></i>${critical} critical</span>
|
|
119
|
+
<span class="count"><i style="background:${SEVERITY_COLOR.warning}"></i>${warning} warning${warning === 1 ? '' : 's'}</span>
|
|
120
|
+
<span class="count"><i style="background:${SEVERITY_COLOR.info}"></i>${info} info</span>
|
|
121
|
+
<span class="count">${report.rulesRun} checks · ${report.filesScanned ?? 0} files</span>
|
|
122
|
+
</div>
|
|
123
|
+
${categoryBars(report)}
|
|
124
|
+
</div>
|
|
125
|
+
</div>
|
|
126
|
+
${findingCards(report)}
|
|
127
|
+
</section>
|
|
128
|
+
<footer>Generated by vibe-preflight · MIT · <a href="https://github.com/erdellll/preflight">github.com/erdellll/preflight</a></footer>
|
|
129
|
+
</main>
|
|
130
|
+
</body>
|
|
131
|
+
</html>
|
|
132
|
+
`;
|
|
133
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { palette, gradeColor, severityColor, stripAnsi } from './colors.js';
|
|
2
|
+
import { CATEGORIES } from '../score.js';
|
|
3
|
+
|
|
4
|
+
const SEVERITY_ORDER = { critical: 0, warning: 1, info: 2 };
|
|
5
|
+
const ICON = { critical: '✖', warning: '▲', info: '●' };
|
|
6
|
+
const BAR_CELLS = 24;
|
|
7
|
+
|
|
8
|
+
const plural = (n, word) => `${n} ${word}${n === 1 || word === 'info' ? '' : 's'}`;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Renders the report card for a terminal.
|
|
12
|
+
* @param {object} report from run()
|
|
13
|
+
* @param {{ color?: boolean, width?: number }} [opts]
|
|
14
|
+
*/
|
|
15
|
+
export function renderTerminal(report, opts = {}) {
|
|
16
|
+
const color = opts.color ?? (Boolean(process.stdout.isTTY) && !process.env.NO_COLOR);
|
|
17
|
+
const c = palette(color);
|
|
18
|
+
const inner = Math.max(40, (opts.width ?? 50) - 2);
|
|
19
|
+
const row = (text = '') => `│${text}${' '.repeat(Math.max(0, inner - [...stripAnsi(text)].length))}│`;
|
|
20
|
+
const gc = c[gradeColor(report.grade)];
|
|
21
|
+
const filled = Math.round((report.score / 100) * BAR_CELLS);
|
|
22
|
+
const { critical, warning, info } = report.counts;
|
|
23
|
+
|
|
24
|
+
const head = ` ${c.bold('PREFLIGHT')}`;
|
|
25
|
+
const tag = c.dim('vibe-preflight');
|
|
26
|
+
const lines = [
|
|
27
|
+
`╭${'─'.repeat(inner)}╮`,
|
|
28
|
+
row(head + ' '.repeat(Math.max(1, inner - [...stripAnsi(head)].length - [...stripAnsi(tag)].length - 2)) + tag + ' '),
|
|
29
|
+
row(),
|
|
30
|
+
row(` ${gc(c.bold(`${report.score} / 100`))} ${gc(c.bold(`Grade ${report.grade}`))}`),
|
|
31
|
+
row(` ${gc('█'.repeat(filled))}${c.dim('░'.repeat(BAR_CELLS - filled))}`),
|
|
32
|
+
row(` ${c.red(`${critical} critical`)} · ${c.yellow(plural(warning, 'warning'))} · ${c.gray(`${info} info`)} · ${c.dim(`${report.rulesRun} checks`)}`),
|
|
33
|
+
`╰${'─'.repeat(inner)}╯`,
|
|
34
|
+
'',
|
|
35
|
+
];
|
|
36
|
+
|
|
37
|
+
if (!report.results.length) {
|
|
38
|
+
lines.push(` ${c.green('✔')} No issues found. Ready for takeoff.`, '');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
for (const category of CATEGORIES) {
|
|
42
|
+
const items = report.results
|
|
43
|
+
.filter((r) => r.category === category)
|
|
44
|
+
.sort((a, b) => SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity]);
|
|
45
|
+
if (!items.length) continue;
|
|
46
|
+
lines.push(c.bold(category.toUpperCase()));
|
|
47
|
+
for (const r of items) {
|
|
48
|
+
const sc = c[severityColor(r.severity)];
|
|
49
|
+
lines.push(` ${sc(`${ICON[r.severity]} ${r.severity.toUpperCase().padEnd(8)}`)} ${c.bold(r.title)}`);
|
|
50
|
+
if (r.file) lines.push(` ${c.cyan(r.line ? `${r.file}:${r.line}` : r.file)}`);
|
|
51
|
+
lines.push(` ${r.message}`);
|
|
52
|
+
lines.push(` ${c.green('→')} ${r.fix}`);
|
|
53
|
+
lines.push('');
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
lines.push(c.dim('Run with --html for a shareable report card.'));
|
|
58
|
+
return lines.join('\n') + '\n';
|
|
59
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
const CLIENT_EXT = /\.(?:js|jsx|mjs|ts|tsx|vue|svelte|html|astro)$/;
|
|
2
|
+
const SERVER_PATH = new RegExp([
|
|
3
|
+
'(?:^|/)(?:api|server|servers|scripts|functions|edge-functions|backend|migrations|cron|workers)/',
|
|
4
|
+
'\\.server\\.', '(?:^|/)\\+server\\.', '(?:^|/)\\+page\\.server\\.', '(?:^|/)route\\.(?:js|ts|mjs)$',
|
|
5
|
+
'(?:^|/)middleware\\.', '(?:^|/)(?:next|nuxt|vite|astro|svelte|tailwind|postcss|webpack|babel|metro|jest|vitest|eslint)\\.config\\.',
|
|
6
|
+
'(?:^|/)server\\.(?:js|ts|mjs|cjs)$', '(?:^|/)(?:actions|instrumentation)\\.(?:js|ts)$',
|
|
7
|
+
].join('|'));
|
|
8
|
+
const CLIENT_DIR = /(?:^|\/)(?:src|app|pages|components|public|lib|static|assets|web|frontend|client|screens|hooks|services|utils|views|features|store|context|navigation)\//;
|
|
9
|
+
const ROOT_CLIENT = /^(?:App|main|index)\.(?:jsx|tsx|ts|js|vue|svelte)$|\.html$/;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* True for code that ends up in the browser or the app bundle. Pass the file's
|
|
13
|
+
* text to also honour a 'use server' directive.
|
|
14
|
+
*/
|
|
15
|
+
export function isClientFile(path, text = '') {
|
|
16
|
+
if (!CLIENT_EXT.test(path) || SERVER_PATH.test(path)) return false;
|
|
17
|
+
if (/^\s*['"]use server['"]/.test(text)) return false;
|
|
18
|
+
return path.includes('/') ? CLIENT_DIR.test(path) : ROOT_CLIENT.test(path);
|
|
19
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
function toRegex(pattern) {
|
|
2
|
+
let p = pattern;
|
|
3
|
+
const anchored = p.startsWith('/') || (p.slice(0, -1).includes('/') && !p.startsWith('**/'));
|
|
4
|
+
p = p.replace(/^\//, '').replace(/\/$/, '').replace(/^\*\*\//, '');
|
|
5
|
+
const body = p
|
|
6
|
+
.split('**').map((part) => part.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^/]*').replace(/\?/g, '[^/]'))
|
|
7
|
+
.join('.*');
|
|
8
|
+
return new RegExp(anchored ? `^${body}(/.*)?$` : `(^|/)${body}(/.*)?$`);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Applies .gitignore lines to `file` (a POSIX path relative to that .gitignore's
|
|
13
|
+
* folder). Supports *, **, ?, leading / and ! negation; the last match wins.
|
|
14
|
+
* Returns true/false, or `fallback` when no line matches.
|
|
15
|
+
*/
|
|
16
|
+
export function isGitignored(file, patterns, fallback = false) {
|
|
17
|
+
let ignored = fallback;
|
|
18
|
+
for (const raw of patterns) {
|
|
19
|
+
const negate = raw.startsWith('!');
|
|
20
|
+
const pattern = negate ? raw.slice(1) : raw;
|
|
21
|
+
if (pattern && toRegex(pattern).test(file)) ignored = !negate;
|
|
22
|
+
}
|
|
23
|
+
return ignored;
|
|
24
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Template for a new Preflight check. Copy this file to
|
|
3
|
+
* src/rules/<your-rule-id>.js, then add tests/fixtures/<your-rule-id>/bad
|
|
4
|
+
* (must be flagged) and tests/fixtures/<your-rule-id>/good (must stay quiet).
|
|
5
|
+
*
|
|
6
|
+
* project.files every scanned file, as POSIX paths relative to the root
|
|
7
|
+
* project.read(f) file contents ('' if unreadable)
|
|
8
|
+
* project.lines(f) file contents split into lines
|
|
9
|
+
* project.has(re) true if any file path matches the regex
|
|
10
|
+
* project.gitignore the root .gitignore lines
|
|
11
|
+
*/
|
|
12
|
+
export default {
|
|
13
|
+
id: 'example-rule',
|
|
14
|
+
title: 'Short, human title of the problem',
|
|
15
|
+
category: 'security', // security | reliability | launch
|
|
16
|
+
severity: 'warning', // critical | warning | info
|
|
17
|
+
check(project) {
|
|
18
|
+
const findings = [];
|
|
19
|
+
for (const file of project.files) {
|
|
20
|
+
project.lines(file).forEach((line, i) => {
|
|
21
|
+
if (line.includes('SOMETHING_RISKY')) {
|
|
22
|
+
findings.push({
|
|
23
|
+
file,
|
|
24
|
+
line: i + 1,
|
|
25
|
+
message: 'What is wrong, in one sentence.',
|
|
26
|
+
fix: 'What to do about it, in one sentence.',
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
return findings;
|
|
32
|
+
},
|
|
33
|
+
};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
const CODE = /\.(?:js|jsx|mjs|cjs|ts|tsx|py|rb|go|php|json|toml|ya?ml)$/;
|
|
2
|
+
const PATTERNS = [
|
|
3
|
+
/\bcors\(\s*\)/,
|
|
4
|
+
/Access-Control-Allow-Origin['"]?\s*[:,=]\s*['"]\*['"]/i,
|
|
5
|
+
/\borigin\s*:\s*['"]\*['"]/,
|
|
6
|
+
/allow_origins\s*=\s*\[\s*['"]\*['"]\s*\]/,
|
|
7
|
+
];
|
|
8
|
+
|
|
9
|
+
export default {
|
|
10
|
+
id: 'cors-wildcard',
|
|
11
|
+
title: 'CORS allows every website',
|
|
12
|
+
category: 'security',
|
|
13
|
+
severity: 'warning',
|
|
14
|
+
check(project) {
|
|
15
|
+
const findings = [];
|
|
16
|
+
for (const file of project.files.filter((f) => CODE.test(f) && f !== 'package.json')) {
|
|
17
|
+
project.lines(file).forEach((line, i) => {
|
|
18
|
+
if (PATTERNS.some((re) => re.test(line))) {
|
|
19
|
+
findings.push({
|
|
20
|
+
file,
|
|
21
|
+
line: i + 1,
|
|
22
|
+
message: 'CORS is open to every origin, so any website can call this API from a visitor\'s browser.',
|
|
23
|
+
fix: "List the origins you trust, for example `cors({ origin: ['https://yourapp.com'] })`.",
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
return findings;
|
|
29
|
+
},
|
|
30
|
+
};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
const ENV_FILE = /(?:^|\/)\.env(?:\.[\w.-]+)?$/;
|
|
2
|
+
const SAFE = /\.(?:example|sample|template|defaults|dist)$/;
|
|
3
|
+
|
|
4
|
+
export default {
|
|
5
|
+
id: 'env-file-committed',
|
|
6
|
+
title: '.env file is not git-ignored',
|
|
7
|
+
category: 'security',
|
|
8
|
+
severity: 'critical',
|
|
9
|
+
check(project) {
|
|
10
|
+
return project.files
|
|
11
|
+
.filter((f) => ENV_FILE.test(f) && !SAFE.test(f) && !project.isIgnored(f))
|
|
12
|
+
.map((file) => ({
|
|
13
|
+
file,
|
|
14
|
+
message: `${file} holds secrets but .gitignore does not cover it, so it can be committed and pushed.`,
|
|
15
|
+
fix: 'Add `.env*` (and `!.env.example`) to .gitignore, run `git rm --cached ' + file + '`, and rotate any keys that were pushed.',
|
|
16
|
+
}));
|
|
17
|
+
},
|
|
18
|
+
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { readdir } from 'node:fs/promises';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Loads every rule in this folder. Files named index.js or starting with
|
|
5
|
+
* "_" (helpers and the template) are not rules.
|
|
6
|
+
*/
|
|
7
|
+
export async function loadRules() {
|
|
8
|
+
const dir = new URL('.', import.meta.url);
|
|
9
|
+
const names = (await readdir(dir)).filter((n) => n.endsWith('.js') && n !== 'index.js' && !n.startsWith('_'));
|
|
10
|
+
const rules = await Promise.all(names.map(async (n) => (await import(new URL(n, dir))).default));
|
|
11
|
+
return rules.filter((r) => r && typeof r.check === 'function').sort((a, b) => a.id.localeCompare(b.id));
|
|
12
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
const HTML_ENTRY = /(?:^|\/)index\.html$/;
|
|
2
|
+
const LAYOUT = /^(?:src\/)?app\/layout\.(?:tsx|jsx|js|ts)$/;
|
|
3
|
+
|
|
4
|
+
function missingInHtml(text) {
|
|
5
|
+
const missing = [];
|
|
6
|
+
if (!/<title>[^<]+<\/title>/i.test(text)) missing.push('<title>');
|
|
7
|
+
if (!/<meta[^>]+name=["']description["']/i.test(text)) missing.push('meta description');
|
|
8
|
+
if (!/<meta[^>]+property=["']og:image["']/i.test(text)) missing.push('og:image');
|
|
9
|
+
return missing;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function missingInLayout(text) {
|
|
13
|
+
if (!/export\s+(?:const\s+metadata|(?:async\s+)?function\s+generateMetadata)/.test(text)) return ['metadata export'];
|
|
14
|
+
const missing = [];
|
|
15
|
+
if (!/\btitle\s*:/.test(text)) missing.push('title');
|
|
16
|
+
if (!/\bdescription\s*:/.test(text)) missing.push('description');
|
|
17
|
+
if (!/\bopenGraph\s*:/.test(text)) missing.push('openGraph image');
|
|
18
|
+
return missing;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export default {
|
|
22
|
+
id: 'missing-meta-tags',
|
|
23
|
+
title: 'Missing title, description or share image',
|
|
24
|
+
category: 'launch',
|
|
25
|
+
severity: 'warning',
|
|
26
|
+
check(project) {
|
|
27
|
+
const findings = [];
|
|
28
|
+
for (const file of project.files) {
|
|
29
|
+
const isHtml = HTML_ENTRY.test(file) && !file.includes('/dist/');
|
|
30
|
+
const isLayout = LAYOUT.test(file);
|
|
31
|
+
if (!isHtml && !isLayout) continue;
|
|
32
|
+
const missing = isHtml ? missingInHtml(project.read(file)) : missingInLayout(project.read(file));
|
|
33
|
+
if (missing.length) {
|
|
34
|
+
findings.push({
|
|
35
|
+
file,
|
|
36
|
+
message: `Missing ${missing.join(', ')}: search results and link previews will look empty or broken.`,
|
|
37
|
+
fix: 'Add a page title, a one-sentence meta description and an og:image (1200x630) so shared links get a proper preview.',
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return findings;
|
|
42
|
+
},
|
|
43
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
const MONITORING = /"(?:@sentry\/[\w-]+|sentry-[\w-]+|posthog-js|posthog-node|posthog-react-native|@bugsnag\/[\w-]+|rollbar|logrocket|@datadog\/browser-rum|@highlight-run\/[\w-]+|@honeybadger-io\/[\w-]+|@appsignal\/[\w-]+|newrelic|@newrelic\/[\w-]+)"\s*:/;
|
|
2
|
+
|
|
3
|
+
export default {
|
|
4
|
+
id: 'no-error-monitoring',
|
|
5
|
+
title: 'No error monitoring',
|
|
6
|
+
category: 'reliability',
|
|
7
|
+
severity: 'info',
|
|
8
|
+
check(project) {
|
|
9
|
+
if (!project.files.includes('package.json')) return [];
|
|
10
|
+
if (MONITORING.test(project.read('package.json'))) return [];
|
|
11
|
+
return [{
|
|
12
|
+
file: 'package.json',
|
|
13
|
+
message: 'No error-monitoring tool is installed, so you will not hear about crashes your users hit.',
|
|
14
|
+
fix: 'Add a free tier of Sentry (`npx @sentry/wizard`) or PostHog so errors reach you before users complain.',
|
|
15
|
+
}];
|
|
16
|
+
},
|
|
17
|
+
};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
const CODE = /\.(?:js|jsx|mjs|ts|tsx|vue|svelte|html|astro|dart|swift|kt|py)$/;
|
|
2
|
+
const COLLECTS_DATA = /supabase\.auth\.|\bsignUp\(|createUserWithEmailAndPassword|signInWithPassword|<input[^>]+type=["']email|next-auth|@clerk\/|@auth0\/|firebase\/auth|useSignUp\(/;
|
|
3
|
+
const PRIVACY = /privacy/i;
|
|
4
|
+
|
|
5
|
+
export default {
|
|
6
|
+
id: 'no-privacy-policy',
|
|
7
|
+
title: 'No privacy policy',
|
|
8
|
+
category: 'launch',
|
|
9
|
+
severity: 'warning',
|
|
10
|
+
check(project) {
|
|
11
|
+
if (project.has(PRIVACY)) return [];
|
|
12
|
+
const collector = project.files.find((f) => CODE.test(f) && COLLECTS_DATA.test(project.read(f)));
|
|
13
|
+
if (!collector) return [];
|
|
14
|
+
return [{
|
|
15
|
+
file: collector,
|
|
16
|
+
message: 'The app signs users up or collects emails but has no privacy policy page. App stores, payment providers and privacy laws require one.',
|
|
17
|
+
fix: 'Add a /privacy page that says what you collect, why, who processes it (for example Supabase, Stripe) and how users delete their data.',
|
|
18
|
+
}];
|
|
19
|
+
},
|
|
20
|
+
};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { isClientFile } from './_client-paths.js';
|
|
2
|
+
|
|
3
|
+
const SECRETS = [
|
|
4
|
+
{ name: 'Stripe secret key', re: /\b[sr]k_live_[0-9A-Za-z]{10,}/ },
|
|
5
|
+
{ name: 'Anthropic API key', re: /\bsk-ant-[0-9A-Za-z_-]{20,}/ },
|
|
6
|
+
{ name: 'OpenAI API key', re: /\bsk-proj-[0-9A-Za-z_-]{20,}/ },
|
|
7
|
+
{ name: 'AWS access key', re: /\bAKIA[0-9A-Z]{16}\b/ },
|
|
8
|
+
];
|
|
9
|
+
|
|
10
|
+
const JWT = /\beyJ[\w-]+\.([\w-]+)\.[\w-]+/g;
|
|
11
|
+
|
|
12
|
+
/** True if a JWT on this line carries the Supabase service_role claim. */
|
|
13
|
+
function hasServiceRoleJwt(line) {
|
|
14
|
+
for (const m of line.matchAll(JWT)) {
|
|
15
|
+
try {
|
|
16
|
+
if (/"role"\s*:\s*"service_role"/.test(Buffer.from(m[1], 'base64url').toString('utf8'))) return true;
|
|
17
|
+
} catch { /* not a JWT */ }
|
|
18
|
+
}
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export default {
|
|
23
|
+
id: 'secret-in-client',
|
|
24
|
+
title: 'Live secret in client-side code',
|
|
25
|
+
category: 'security',
|
|
26
|
+
severity: 'critical',
|
|
27
|
+
check(project) {
|
|
28
|
+
const findings = [];
|
|
29
|
+
for (const file of project.files.filter((f) => isClientFile(f, project.read(f)))) {
|
|
30
|
+
project.lines(file).forEach((line, i) => {
|
|
31
|
+
const hit = SECRETS.find((s) => s.re.test(line)) ?? (hasServiceRoleJwt(line) ? { name: 'Supabase service_role key' } : null);
|
|
32
|
+
if (hit) {
|
|
33
|
+
findings.push({
|
|
34
|
+
file,
|
|
35
|
+
line: i + 1,
|
|
36
|
+
message: `A ${hit.name} is in code that ships to the browser or app, where anyone can read it.`,
|
|
37
|
+
fix: 'Move the key to a server-side environment variable used only by an API route, then rotate it: treat it as leaked.',
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
return findings;
|
|
43
|
+
},
|
|
44
|
+
};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
const CODE = /\.(?:js|jsx|mjs|cjs|ts|tsx|py|rb|go|php)$/;
|
|
2
|
+
const STRIPE_EVENT = /checkout\.session\.completed|invoice\.(?:paid|payment_succeeded)|customer\.subscription\.|payment_intent\.succeeded/;
|
|
3
|
+
const HANDLER = /export\s+(?:async\s+)?(?:function\s+POST|const\s+POST)|\b(?:app|router|server)\.post\(|@app\.(?:post|route)\(|stripe-signature|def\s+\w*webhook/i;
|
|
4
|
+
const VERIFIED = /construct_?event/i;
|
|
5
|
+
|
|
6
|
+
export default {
|
|
7
|
+
id: 'stripe-webhook-unverified',
|
|
8
|
+
title: 'Stripe webhook without signature check',
|
|
9
|
+
category: 'security',
|
|
10
|
+
severity: 'critical',
|
|
11
|
+
check(project) {
|
|
12
|
+
const code = project.files.filter((f) => CODE.test(f));
|
|
13
|
+
// A project that verifies anywhere (often in a shared helper) is treated as verified.
|
|
14
|
+
if (code.some((f) => VERIFIED.test(project.read(f)))) return [];
|
|
15
|
+
return code
|
|
16
|
+
.filter((f) => {
|
|
17
|
+
const text = project.read(f);
|
|
18
|
+
return HANDLER.test(text) && STRIPE_EVENT.test(text);
|
|
19
|
+
})
|
|
20
|
+
.map((file) => ({
|
|
21
|
+
file,
|
|
22
|
+
message: 'This Stripe webhook handler never verifies the signature, so anyone can POST a fake "payment succeeded" event.',
|
|
23
|
+
fix: 'Read the raw body and call `stripe.webhooks.constructEvent(body, signature, STRIPE_WEBHOOK_SECRET)` before trusting the event.',
|
|
24
|
+
}));
|
|
25
|
+
},
|
|
26
|
+
};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
const CREATE = /create\s+table\s+(?:if\s+not\s+exists\s+)?((?:"?\w+"?\.)?"?\w+"?)/i;
|
|
2
|
+
const ENABLE = /alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?((?:"?\w+"?\.)?"?\w+"?)\s+enable\s+row\s+level\s+security/gi;
|
|
3
|
+
const bare = (name) => name.replace(/"/g, '').split('.').pop().toLowerCase();
|
|
4
|
+
|
|
5
|
+
export default {
|
|
6
|
+
id: 'supabase-rls-disabled',
|
|
7
|
+
title: 'Supabase table without row-level security',
|
|
8
|
+
category: 'security',
|
|
9
|
+
severity: 'critical',
|
|
10
|
+
check(project) {
|
|
11
|
+
// Row-level security only protects data exposed through Supabase's public API.
|
|
12
|
+
const usesSupabase = project.has(/(?:^|\/)supabase\//) || /"@supabase\//.test(project.read('package.json'));
|
|
13
|
+
if (!usesSupabase) return [];
|
|
14
|
+
const sqlFiles = project.files.filter((f) => f.endsWith('.sql'));
|
|
15
|
+
if (!sqlFiles.length) return [];
|
|
16
|
+
const enabled = new Set();
|
|
17
|
+
for (const f of sqlFiles) for (const m of project.read(f).matchAll(ENABLE)) enabled.add(bare(m[1]));
|
|
18
|
+
const findings = [];
|
|
19
|
+
for (const file of sqlFiles) {
|
|
20
|
+
project.lines(file).forEach((line, i) => {
|
|
21
|
+
if (/^\s*--/.test(line)) return;
|
|
22
|
+
const m = line.match(CREATE);
|
|
23
|
+
if (m && !enabled.has(bare(m[1]))) {
|
|
24
|
+
const table = bare(m[1]);
|
|
25
|
+
findings.push({
|
|
26
|
+
file,
|
|
27
|
+
line: i + 1,
|
|
28
|
+
message: `Table "${table}" is created without row-level security, so anyone with your public anon key can read and change every row.`,
|
|
29
|
+
fix: `Add \`alter table ${table} enable row level security;\` and write policies for who may select, insert, update and delete.`,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
return findings;
|
|
35
|
+
},
|
|
36
|
+
};
|
package/src/run.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { loadProject } from './project.js';
|
|
2
|
+
import { loadRules } from './rules/index.js';
|
|
3
|
+
import { score } from './score.js';
|
|
4
|
+
|
|
5
|
+
function ignoredInline(project, finding, ruleId) {
|
|
6
|
+
if (!finding.file || !finding.line) return false;
|
|
7
|
+
const lines = project.lines(finding.file);
|
|
8
|
+
const token = `preflight-ignore ${ruleId}`;
|
|
9
|
+
return [lines[finding.line - 1], lines[finding.line - 2]].some((l) => l?.includes(token));
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Scans a project and returns the full report.
|
|
14
|
+
* @param {string} root
|
|
15
|
+
* @param {{ ignore?: string[], rules?: object[] }} [opts]
|
|
16
|
+
*/
|
|
17
|
+
export async function run(root, opts = {}) {
|
|
18
|
+
const project = await loadProject(root);
|
|
19
|
+
const rules = opts.rules ?? (await loadRules());
|
|
20
|
+
const ignore = new Set(opts.ignore ?? []);
|
|
21
|
+
const results = [];
|
|
22
|
+
for (const rule of rules) {
|
|
23
|
+
if (ignore.has(rule.id)) continue;
|
|
24
|
+
for (const finding of rule.check(project)) {
|
|
25
|
+
if (ignoredInline(project, finding, rule.id)) continue;
|
|
26
|
+
results.push({ ruleId: rule.id, title: rule.title, category: rule.category, severity: rule.severity, ...finding });
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return { root, results, ...score(results), rulesRun: rules.length, filesScanned: project.files.length };
|
|
30
|
+
}
|
package/src/score.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/** Points lost per finding, by severity. */
|
|
2
|
+
export const WEIGHTS = { critical: 15, warning: 5, info: 1 };
|
|
3
|
+
|
|
4
|
+
export const CATEGORIES = ['security', 'reliability', 'launch'];
|
|
5
|
+
|
|
6
|
+
/** @param {number} n score from 0 to 100 */
|
|
7
|
+
export function gradeFor(n) {
|
|
8
|
+
if (n >= 90) return 'A';
|
|
9
|
+
if (n >= 80) return 'B';
|
|
10
|
+
if (n >= 70) return 'C';
|
|
11
|
+
if (n >= 50) return 'D';
|
|
12
|
+
return 'F';
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Turns findings into a score, grade and counts.
|
|
17
|
+
* @param {Array<{severity: 'critical'|'warning'|'info', category: string}>} results
|
|
18
|
+
*/
|
|
19
|
+
export function score(results) {
|
|
20
|
+
const counts = { critical: 0, warning: 0, info: 0 };
|
|
21
|
+
const byCategory = Object.fromEntries(CATEGORIES.map((c) => [c, 0]));
|
|
22
|
+
let lost = 0;
|
|
23
|
+
for (const r of results) {
|
|
24
|
+
counts[r.severity] += 1;
|
|
25
|
+
byCategory[r.category] = (byCategory[r.category] ?? 0) + 1;
|
|
26
|
+
lost += WEIGHTS[r.severity] ?? 0;
|
|
27
|
+
}
|
|
28
|
+
const value = Math.max(0, Math.min(100, 100 - lost));
|
|
29
|
+
return { score: value, grade: gradeFor(value), counts, byCategory };
|
|
30
|
+
}
|