rlsproof 0.0.0-stage → 1.0.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.
@@ -0,0 +1,247 @@
1
+ import fs from "node:fs";
2
+ import { createFinding, toPosixRelPath } from "../core/findings.js";
3
+
4
+ const JWT_RE = /\b(eyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{6,})\b/g;
5
+
6
+ const SECRET_PATTERNS = [
7
+ {
8
+ name: "Supabase sb_secret key",
9
+ regex: /\b(sb_secret_[A-Za-z0-9_-]{16,})\b/g,
10
+ },
11
+ {
12
+ name: "OpenAI project API key",
13
+ regex: /\b(sk-proj-[A-Za-z0-9_-]{20,})\b/g,
14
+ },
15
+ {
16
+ name: "OpenAI legacy API key",
17
+ regex: /\b(sk-[A-Za-z0-9]{16,}T3BlbkFJ[A-Za-z0-9]{16,})\b/g,
18
+ },
19
+ {
20
+ name: "Anthropic API key",
21
+ regex: /\b(sk-ant-api\d*-[A-Za-z0-9_-]{20,})\b/g,
22
+ },
23
+ {
24
+ name: "Google Gemini / AIza API key",
25
+ regex: /\b(AIza[0-9A-Za-z_-]{35})\b/g,
26
+ },
27
+ {
28
+ name: "Stripe live secret key",
29
+ regex: /\b(sk_live_[A-Za-z0-9]{16,})\b/g,
30
+ },
31
+ {
32
+ name: "Stripe live restricted key",
33
+ regex: /\b(rk_live_[A-Za-z0-9]{16,})\b/g,
34
+ },
35
+ {
36
+ name: "Stripe webhook secret",
37
+ regex: /\b(whsec_[A-Za-z0-9]{20,})\b/g,
38
+ },
39
+ ];
40
+
41
+ const POSTGRES_URI_RE = /(postgres(?:ql)?:\/\/[^:\s'"`]+:[^@\s'"`]+@[^\s'"`]+)/gi;
42
+
43
+ const CLIENT_PUBLIC_PRIVILEGED_ENV_RE =
44
+ /\b((?:VITE|NEXT_PUBLIC|REACT_APP|PUBLIC|NUXT_PUBLIC|EXPO_PUBLIC)_[A-Z0-9_]*(?:SERVICE_ROLE|SUPABASE_SECRET|OPENAI_API_KEY|ANTHROPIC_API_KEY|GEMINI_API_KEY|GOOGLE_AI_API_KEY|STRIPE_SECRET|STRIPE_WEBHOOK_SECRET|DATABASE_URL|PRIVATE_KEY)[A-Z0-9_]*)\b/g;
45
+
46
+ const ANON_CLIENT_USAGE_RE =
47
+ /\b(?:VITE_|NEXT_PUBLIC_|REACT_APP_|PUBLIC_|EXPO_PUBLIC_)?SUPABASE_ANON_KEY\b|\bsupabase\.createClient\b|\bcreateBrowserClient\b|\bcreateClientComponentClient\b/;
48
+
49
+ const PLACEHOLDER_RE =
50
+ /(?:your[_-]|placeholder|example|dummy|sample|changeme|replace[_-]?me|test[_-]key|mock[_-]key|xxxx|<[^>]+>|\*{4,}|\$\{[^}]+\})/i;
51
+
52
+ function decodeJwtPayloadSafe(token) {
53
+ try {
54
+ const [, payloadB64] = token.split(".");
55
+ const json = Buffer.from(payloadB64, "base64url").toString("utf8");
56
+ return JSON.parse(json);
57
+ } catch {
58
+ return null;
59
+ }
60
+ }
61
+
62
+ const SUPABASE_DEMO_SERVICE_SIG = "EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU";
63
+
64
+ function isLocalOrDemoContext(relPath) {
65
+ const lower = relPath.toLowerCase();
66
+ return (
67
+ lower.includes(".example") ||
68
+ lower.includes(".template") ||
69
+ lower.includes(".sample") ||
70
+ lower.includes("readme") ||
71
+ lower.includes("docs/") ||
72
+ lower.includes("__tests__") ||
73
+ lower.includes(".test.") ||
74
+ lower.includes(".spec.") ||
75
+ lower.endsWith("config.toml") ||
76
+ lower.endsWith("seed.sql") ||
77
+ (lower.includes("supabase/migrations/") && lower.endsWith(".sql"))
78
+ );
79
+ }
80
+
81
+ function isPlaceholderSecret(token) {
82
+ if (!token) return true;
83
+ if (PLACEHOLDER_RE.test(token)) return true;
84
+ // Detect repeated single characters such as sk-proj-aaaaaaaaaaaa...
85
+ const tail = token.replace(/^[^_-]+[_-]/, "");
86
+ if (tail.length >= 10 && new Set(tail).size <= 3) return true;
87
+ return false;
88
+ }
89
+
90
+ function isLocalPostgresUri(uri) {
91
+ const lower = uri.toLowerCase();
92
+ return (
93
+ PLACEHOLDER_RE.test(lower) ||
94
+ /@(?:localhost|127\.0\.0\.1|0\.0\.0\.0|db|postgres|supabase_db)(?::\d+)?\b/.test(lower) ||
95
+ /:\/\/postgres:postgres@/.test(lower)
96
+ );
97
+ }
98
+
99
+ function isFirebasePublicClientKeyContext(lineText, relFile) {
100
+ // Firebase web config intentionally ships `AIza...` apiKey when combined with Firebase config objects;
101
+ // flag `AIza...` unless explicitly inside a Firebase web config object (`authDomain` / `firebaseConfig`).
102
+ const lower = lineText.toLowerCase();
103
+ if (relFile.toLowerCase().includes("firebase")) return true;
104
+ return lower.includes("firebase") || lower.includes("authdomain");
105
+ }
106
+
107
+ /**
108
+ * Scans repository files for real privileged secrets and client-exposed privileged env vars
109
+ * while ignoring public Supabase `anon` keys (@all Lock #2) and demo placeholders.
110
+ */
111
+ export function scanSecrets(files, rootDir) {
112
+ const findings = [];
113
+ let anonClientUsageDetected = false;
114
+
115
+ for (const filePath of files) {
116
+ const relFile = toPosixRelPath(rootDir, filePath);
117
+ let content;
118
+ try {
119
+ content = fs.readFileSync(filePath, "utf8");
120
+ } catch {
121
+ continue;
122
+ }
123
+
124
+ if (ANON_CLIENT_USAGE_RE.test(content)) {
125
+ anonClientUsageDetected = true;
126
+ }
127
+
128
+ const lines = content.split(/\r?\n/);
129
+ const localOrExample = isLocalOrDemoContext(relFile);
130
+
131
+ for (let idx = 0; idx < lines.length; idx++) {
132
+ const lineText = lines[idx];
133
+ const lineNum = idx + 1;
134
+ let matchedOnLine = false;
135
+
136
+ // 1. Hardcoded JWTs (ONLY privileged roles like service_role; NEVER flag anon)
137
+ for (const m of lineText.matchAll(JWT_RE)) {
138
+ const token = m[1];
139
+ const payload = decodeJwtPayloadSafe(token);
140
+ if (!payload || !payload.role) continue;
141
+ if (payload.role === "anon") continue; // @all Lock #2: anon key is NOT a secret!
142
+ if (payload.role === "service_role" || payload.role === "supabase_admin") {
143
+ // Ignore the well-known Supabase CLI local development demo JWT only in local/migration/docs contexts
144
+ if (
145
+ payload.iss === "supabase-demo" &&
146
+ token.endsWith(SUPABASE_DEMO_SERVICE_SIG) &&
147
+ localOrExample
148
+ ) {
149
+ continue;
150
+ }
151
+ findings.push(
152
+ createFinding({
153
+ ruleId: "SECRET_HARDCODED_OR_CLIENT_EXPOSED",
154
+ severity: "CRITICAL",
155
+ file: relFile,
156
+ line: lineNum,
157
+ object: `${relFile}:${lineNum} (JWT role=${payload.role})`,
158
+ title: `Hardcoded privileged "${payload.role}" JWT detected`,
159
+ detail: `A JWT with privileged role "${payload.role}" is committed in ${relFile}. Unlike public anon keys, service_role JWTs bypass all RLS policies.`,
160
+ snippet: lineText,
161
+ rootDir,
162
+ })
163
+ );
164
+ matchedOnLine = true;
165
+ break;
166
+ }
167
+ }
168
+ if (matchedOnLine) continue;
169
+
170
+ // 2. Named secret key prefixes
171
+ for (const pat of SECRET_PATTERNS) {
172
+ for (const m of lineText.matchAll(pat.regex)) {
173
+ const token = m[1];
174
+ if (isPlaceholderSecret(token)) continue;
175
+ if (token.startsWith("AIza") && isFirebasePublicClientKeyContext(lineText, relFile)) {
176
+ continue;
177
+ }
178
+ findings.push(
179
+ createFinding({
180
+ ruleId: "SECRET_HARDCODED_OR_CLIENT_EXPOSED",
181
+ severity: "CRITICAL",
182
+ file: relFile,
183
+ line: lineNum,
184
+ object: `${relFile}:${lineNum} (${pat.name})`,
185
+ title: `Hardcoded ${pat.name} detected`,
186
+ detail: `${pat.name} is embedded directly in ${relFile}.`,
187
+ snippet: lineText,
188
+ rootDir,
189
+ })
190
+ );
191
+ matchedOnLine = true;
192
+ break;
193
+ }
194
+ if (matchedOnLine) break;
195
+ }
196
+ if (matchedOnLine) continue;
197
+
198
+ // 3. Embedded remote Postgres URI credentials
199
+ for (const m of lineText.matchAll(POSTGRES_URI_RE)) {
200
+ const uri = m[1];
201
+ if (isLocalPostgresUri(uri)) continue;
202
+ findings.push(
203
+ createFinding({
204
+ ruleId: "SECRET_HARDCODED_OR_CLIENT_EXPOSED",
205
+ severity: "CRITICAL",
206
+ file: relFile,
207
+ line: lineNum,
208
+ object: `${relFile}:${lineNum} (Postgres URI)`,
209
+ title: `Embedded PostgreSQL connection string with credentials detected`,
210
+ detail: `A non-local Postgres connection URI containing embedded username/password credentials was found in ${relFile}.`,
211
+ snippet: lineText,
212
+ rootDir,
213
+ })
214
+ );
215
+ matchedOnLine = true;
216
+ break;
217
+ }
218
+ if (matchedOnLine) continue;
219
+
220
+ // 4. Client-bundled privileged env var names (VITE_*, NEXT_PUBLIC_*, etc.)
221
+ // Explicitly ignores ANON_KEY and PUBLISHABLE_KEY.
222
+ for (const m of lineText.matchAll(CLIENT_PUBLIC_PRIVILEGED_ENV_RE)) {
223
+ const varName = m[1];
224
+ findings.push(
225
+ createFinding({
226
+ ruleId: "SECRET_HARDCODED_OR_CLIENT_EXPOSED",
227
+ severity: "CRITICAL",
228
+ file: relFile,
229
+ line: lineNum,
230
+ object: `${relFile} (${varName})`,
231
+ title: `Client-bundled public env prefix exposes privileged variable ${varName}`,
232
+ detail: `Variable "${varName}" uses a frontend public prefix, causing build bundlers to ship server-only credentials into public browser JS.`,
233
+ snippet: lineText,
234
+ rootDir,
235
+ })
236
+ );
237
+ matchedOnLine = true;
238
+ break;
239
+ }
240
+ }
241
+ }
242
+
243
+ return {
244
+ findings,
245
+ anonClientUsageDetected,
246
+ };
247
+ }