rattlecheck 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.
Files changed (39) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +173 -2
  4. package/bin/rattlecheck.js +12 -0
  5. package/docs/rules/RC001.md +40 -0
  6. package/docs/rules/RC002.md +35 -0
  7. package/docs/rules/RC003.md +25 -0
  8. package/docs/rules/RC004.md +23 -0
  9. package/docs/rules/RC005.md +32 -0
  10. package/docs/rules/RC101.md +31 -0
  11. package/integrations/AGENTS.md +11 -0
  12. package/integrations/claude-code/rattlecheck/SKILL.md +42 -0
  13. package/integrations/cursor/rattlecheck.mdc +13 -0
  14. package/package.json +45 -4
  15. package/src/cli.js +158 -0
  16. package/src/config.js +62 -0
  17. package/src/live/catalog.js +43 -0
  18. package/src/live/env.js +102 -0
  19. package/src/live/ownership.js +72 -0
  20. package/src/live/probe.js +80 -0
  21. package/src/live/rc101-anon-readable.js +38 -0
  22. package/src/mcp/server.js +163 -0
  23. package/src/model.js +723 -0
  24. package/src/report/badge-svg.js +26 -0
  25. package/src/report/card-svg.js +50 -0
  26. package/src/report/grade.js +26 -0
  27. package/src/report/sarif.js +44 -0
  28. package/src/report/terminal.js +105 -0
  29. package/src/rules/index.js +14 -0
  30. package/src/rules/supabase/rc001-table-without-rls.js +54 -0
  31. package/src/rules/supabase/rc002-definer-callable-by-anon.js +37 -0
  32. package/src/rules/supabase/rc003-definer-search-path.js +33 -0
  33. package/src/rules/supabase/rc004-invoker-trigger-locked-table.js +49 -0
  34. package/src/rules/supabase/rc005-permissive-true-policy.js +81 -0
  35. package/src/scan.js +167 -0
  36. package/src/sql/ident.js +25 -0
  37. package/src/sql/signature.js +143 -0
  38. package/src/sql/statements.js +267 -0
  39. package/src/version.js +6 -0
@@ -0,0 +1,163 @@
1
+ // A minimal MCP server over stdio: newline-delimited JSON-RPC 2.0.
2
+ //
3
+ // Written by hand instead of pulling in the official SDK, which brings 17
4
+ // dependencies (Express, Hono, and more) for a server that only needs four
5
+ // methods. A security tool should be easy to audit end to end.
6
+ //
7
+ // stdout carries protocol messages only. Anything human goes to stderr.
8
+ import path from 'node:path';
9
+ import readline from 'node:readline';
10
+ import { scan, ScanError } from '../scan.js';
11
+ import { ConfigError } from '../config.js';
12
+ import { ALL_RULES, getRule } from '../rules/index.js';
13
+ import { VERSION } from '../version.js';
14
+
15
+ const SUPPORTED_PROTOCOLS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
16
+
17
+ const INSTRUCTIONS = `rattlecheck finds security holes in Supabase projects: tables anyone can read, functions anyone can call with full database powers, and policies that let anyone change every row.
18
+
19
+ How to use it:
20
+ 1. Call scan on the project folder before you deploy, and after any migration that creates or changes tables, policies, functions, or grants.
21
+ 2. For each finding, put its fix SQL into a NEW migration file. Never edit migrations that already ran. Never run SQL against a production database yourself.
22
+ 3. Call scan again until the grade is A.
23
+ 4. If a finding is intentional (a public menu, say), ask the user before adding an allow entry with a reason to rattlecheck.config.json. Never allow a finding just to make it go away.
24
+ 5. Tell the user what was found in plain words, using each finding's "plain" text.`;
25
+
26
+ const TOOLS = [
27
+ {
28
+ name: 'scan',
29
+ title: 'Scan a Supabase project',
30
+ description:
31
+ 'Replays the project\'s supabase/migrations and reports every open door: tables without row-level security, SECURITY DEFINER functions anyone can call, unpinned search paths, triggers that break user writes, and always-true policies. Returns a grade (A to F), each finding in plain English, and the SQL to fix it. Read-only. With live=true it also asks the running project, read-only and only after proving the user owns it, how many rows each table hands to the public key.',
32
+ inputSchema: {
33
+ type: 'object',
34
+ properties: {
35
+ path: { type: 'string', description: 'Project folder that contains supabase/migrations. Defaults to the current folder.' },
36
+ live: { type: 'boolean', description: 'Also check the running project (read-only). Requires the project URL and keys in the local .env and proof of ownership.', default: false },
37
+ },
38
+ additionalProperties: false,
39
+ },
40
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true },
41
+ },
42
+ {
43
+ name: 'explain_rule',
44
+ title: 'Explain a rattlecheck rule',
45
+ description: 'Explains one rule (for example RC002): what it catches, why it matters, and which security standards it maps to.',
46
+ inputSchema: { type: 'object', properties: { id: { type: 'string', description: 'Rule id, like RC001' } }, required: ['id'], additionalProperties: false },
47
+ annotations: { readOnlyHint: true },
48
+ },
49
+ {
50
+ name: 'list_rules',
51
+ title: 'List rattlecheck rules',
52
+ description: 'Lists every rule rattlecheck checks, with severity.',
53
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
54
+ annotations: { readOnlyHint: true },
55
+ },
56
+ ];
57
+
58
+ function summarize(report) {
59
+ const lines = [`Grade ${report.grade.letter} (${report.grade.label}). ${report.doors.checked} doors checked, ${report.doors.open} open.`];
60
+ for (const f of report.findings) {
61
+ lines.push('', `[${f.severity.toUpperCase()}] ${f.rule} ${f.name}${f.detail ? ` (${f.detail})` : ''}`, f.plain, `What to do: ${f.todo}`, `Location: ${f.file ?? 'live project'}${f.line ? `:${f.line}` : ''}`, 'Fix SQL (put in a NEW migration):', f.fix);
62
+ }
63
+ if (!report.coverage.ok) lines.push('', 'WARNING: migration files were found but nothing could be parsed. Do not trust this result.');
64
+ if (report.live.ran && !report.live.coverage.complete) {
65
+ lines.push('', `WARNING: the live check only covered the ${report.live.coverage.fromMigrations} tables found in migrations (${report.live.coverage.reason}). Tables created outside migrations were not checked. Tell the user; do not report this as a full all-clear.`);
66
+ }
67
+ for (const w of report.configWarnings) lines.push('', `Config: ${w}`);
68
+ return lines.join('\n');
69
+ }
70
+
71
+ export async function callTool(name, args = {}, { cwd = process.cwd(), env = process.env, fetchImpl = globalThis.fetch } = {}) {
72
+ if (name === 'list_rules') {
73
+ const rules = ALL_RULES.map((r) => ({ id: r.id, severity: r.severity, title: r.title, live: Boolean(r.live) }));
74
+ return { content: [{ type: 'text', text: rules.map((r) => `${r.id} ${r.severity} ${r.title}`).join('\n') }], structuredContent: { rules } };
75
+ }
76
+ if (name === 'explain_rule') {
77
+ const r = getRule(args.id);
78
+ if (!r) return { content: [{ type: 'text', text: `No rule called ${args.id}.` }], isError: true };
79
+ const data = { id: r.id, severity: r.severity, title: r.title, summary: r.summary, standards: r.standards };
80
+ return { content: [{ type: 'text', text: `${r.id} ${r.title}\n\n${r.summary}\n\nStandards: ${JSON.stringify(r.standards)}` }], structuredContent: data };
81
+ }
82
+ if (name === 'scan') {
83
+ if (args.path !== undefined && typeof args.path !== 'string') return { content: [{ type: 'text', text: '"path" must be a string.' }], isError: true };
84
+ if (args.live !== undefined && typeof args.live !== 'boolean') return { content: [{ type: 'text', text: '"live" must be true or false.' }], isError: true };
85
+ try {
86
+ const report = await scan({ root: path.resolve(cwd, args.path ?? '.'), live: args.live === true, env, fetchImpl });
87
+ return { content: [{ type: 'text', text: summarize(report) }], structuredContent: report };
88
+ } catch (e) {
89
+ const known = e instanceof ScanError || e instanceof ConfigError;
90
+ return { content: [{ type: 'text', text: known ? e.message : `rattlecheck hit an unexpected error: ${e.message}` }], isError: true };
91
+ }
92
+ }
93
+ return null;
94
+ }
95
+
96
+ export async function handleMessage(msg, ctx = {}) {
97
+ if (!msg || typeof msg !== 'object' || Array.isArray(msg)) {
98
+ return { jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid request' } };
99
+ }
100
+ const { id, method, params } = msg;
101
+ const reply = (result) => ({ jsonrpc: '2.0', id, result });
102
+ const fail = (code, message) => ({ jsonrpc: '2.0', id, error: { code, message } });
103
+
104
+ // A response from the client (to a request we never send) or a notification: no reply.
105
+ if (typeof method !== 'string') {
106
+ if (id !== undefined && ('result' in msg || 'error' in msg)) return null;
107
+ return { jsonrpc: '2.0', id: id ?? null, error: { code: -32600, message: 'Invalid request' } };
108
+ }
109
+ if (id === undefined) return null; // notifications/initialized, notifications/cancelled, ...
110
+
111
+ if (method === 'initialize') {
112
+ const asked = params?.protocolVersion;
113
+ return reply({
114
+ protocolVersion: SUPPORTED_PROTOCOLS.includes(asked) ? asked : SUPPORTED_PROTOCOLS[0],
115
+ capabilities: { tools: { listChanged: false } },
116
+ serverInfo: { name: 'rattlecheck', title: 'rattlecheck', version: VERSION },
117
+ instructions: INSTRUCTIONS,
118
+ });
119
+ }
120
+ if (method === 'ping') return reply({});
121
+ if (method === 'tools/list') return reply({ tools: TOOLS });
122
+ if (method === 'tools/call') {
123
+ const result = await callTool(params?.name, params?.arguments ?? {}, ctx);
124
+ if (!result) return fail(-32602, `Unknown tool: ${params?.name}`);
125
+ return reply(result);
126
+ }
127
+ return fail(-32601, `Method not found: ${method}`);
128
+ }
129
+
130
+ export function runMcpServer({ input = process.stdin, output = process.stdout } = {}) {
131
+ const rl = readline.createInterface({ input, crlfDelay: Infinity });
132
+ rl.on('line', async (line) => {
133
+ if (!line.trim()) return;
134
+ let msg;
135
+ try {
136
+ msg = JSON.parse(line);
137
+ } catch {
138
+ output.write(`${JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } })}\n`);
139
+ return;
140
+ }
141
+ const one = async (m) => {
142
+ try {
143
+ return await handleMessage(m);
144
+ } catch (e) {
145
+ const id = m && typeof m === 'object' && m.id !== undefined ? m.id : null;
146
+ return { jsonrpc: '2.0', id, error: { code: -32603, message: e.message } };
147
+ }
148
+ };
149
+ if (Array.isArray(msg)) {
150
+ // JSON-RPC batch (required by protocol 2025-03-26).
151
+ if (msg.length === 0) {
152
+ output.write(`${JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid request' } })}\n`);
153
+ return;
154
+ }
155
+ const replies = (await Promise.all(msg.map(one))).filter(Boolean);
156
+ if (replies.length) output.write(`${JSON.stringify(replies)}\n`);
157
+ return;
158
+ }
159
+ const res = await one(msg);
160
+ if (res) output.write(`${JSON.stringify(res)}\n`);
161
+ });
162
+ return new Promise((resolve) => rl.on('close', resolve));
163
+ }