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,337 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { createFinding, toPosixRelPath } from "../core/findings.js";
4
+
5
+ const WEBHOOK_SIGNATURE_RE =
6
+ /\b(?:constructEvent|constructEventAsync|stripe-signature|svix-signature|x-hub-signature|x-signature|webhookSecret|webhook[_-]?signing[_-]?secret|signingSecret|stripeWebhookHandler|billingWebhooksWrapper|verifyWebhook|crypto\.subtle\.verify|timingSafeEqual|createHmac)\b/i;
7
+
8
+ const MANUAL_AUTH_RE =
9
+ /\b(?:auth\.getUser|auth\.getSession|getServerSession|createServerClient|getServerProfile|getCurrentUser|getAuthUser|requireUser|requireSession|authenticateRequest|authenticateUser|currentUser|getAuth|requireAuth|withAuth|verifyToken|verifyJwt|jwtVerify|x-api-key|x-cron-secret|CRON_SECRET|WEBHOOK_SECRET|INTERNAL_SECRET|API_SECRET)\b|headers\.get\(\s*['"]authorization['"]\s*\)|req\.headers\[?['"]authorization['"]\]?|\.headers\.authorization\b/i;
10
+
11
+ const SERVICE_ROLE_USAGE_RE =
12
+ /\bSUPABASE_SERVICE_ROLE_KEY\b|\bservice_role\b|\bsb_secret_/i;
13
+
14
+ const PAID_AI_CALL_RE =
15
+ /\b(?:chat\.completions\.create|responses\.create|messages\.create|streamText|generateText|generateObject|streamObject|images\.generate|audio\.speech\.create|generateContent|startChat|sendMessage|embeddings\.create|embedMany|embedContent)\b|api\.openai\.com\/v1\/(?:chat\/completions|responses|images|audio|embeddings)|api\.anthropic\.com\/v1\/messages|generativelanguage\.googleapis\.com|openrouter\.ai\/api\/v1\/chat\/completions|api\.groq\.com\/openai\/v1\/chat\/completions|api\.mistral\.ai\/v1\/chat\/completions|api\.together\.xyz\/v1\/chat\/completions|api\.replicate\.com\/v1\/predictions|api\.elevenlabs\.io\/v1\/text-to-speech/i;
16
+
17
+ const LLM_PROVIDER_RE = PAID_AI_CALL_RE;
18
+
19
+ const EMBEDDING_ONLY_RE =
20
+ /\b(?:embeddings\.create|embedMany|embedContent|\/v1\/embeddings)\b/i;
21
+
22
+ const GENERATION_CALL_RE =
23
+ /\b(?:chat\.completions\.create|responses\.create|messages\.create|streamText|generateText|generateObject|streamObject|images\.generate|audio\.speech\.create|generateContent|startChat|sendMessage)\b|\/v1\/(?:chat\/completions|responses|messages|images|audio)/i;
24
+
25
+ const SERVER_BILLED_KEY_RE =
26
+ /\b(?:OPENAI_API_KEY|ANTHROPIC_API_KEY|GEMINI_API_KEY|GOOGLE_AI_API_KEY|GOOGLE_GENERATIVE_AI_API_KEY|OPENROUTER_API_KEY|GROQ_API_KEY|REPLICATE_API_TOKEN|ELEVENLABS_API_KEY)\b|\bnew\s+(?:OpenAI|Anthropic)\s*\(\s*\)/;
27
+
28
+ const BYOK_HEADER_RE =
29
+ /(?:headers\.get|req\.headers|request\.headers)\s*(?:\(|\[|\.)\s*['"]?(?:x-openai-key|x-api-key|openai-key|anthropic-key|x-anthropic-key|userApiKey)/i;
30
+
31
+ const MODEL_FROM_REQUEST_RE =
32
+ /(?:const|let)\s*\{[^}]*\bmodel\b[^}]*\}\s*=\s*(?:await\s+)?(?:req|request)\.(?:json|body)|(?:req|request)\.body\.model\b|\bbody\.model\b|\b(?:chatSettings|settings)\.model\b/i;
33
+
34
+ const MODEL_ALLOWLIST_RE =
35
+ /\b(?:ALLOWED_MODELS|MODEL_ALLOWLIST|VALID_MODELS|SUPPORTED_MODELS|z\.enum\s*\(|MODEL_MAP)\b|\.includes\(\s*model\b|\.has\(\s*model\b/;
36
+
37
+ const MAX_TOKENS_CLAMP_RE =
38
+ /\b(?:max_tokens|max_completion_tokens|maxTokens|maxOutputTokens)\s*:/;
39
+
40
+ const RAW_UNCLAMPED_MAX_TOKENS_RE =
41
+ /\b(?:max_tokens|max_completion_tokens|maxTokens)\s*:\s*(?:body|req\.body|payload|input)\.(?:max_tokens|maxTokens)\b(?!.*Math\.min)/;
42
+
43
+ const BUDGET_OR_RATELIMIT_RE =
44
+ /\b(?:ratelimit|Ratelimit|rateLimit|rate_limit|upstash|@upstash\/ratelimit|quota|budget|credits|creditBalance|reserve_ai_budget|ai_spend_ledger|checkLimit|checkQuota|incrementUsage|usageLimit|planLimit|throttle|limiter)\b/i;
45
+
46
+ const HTTP_HANDLER_SIGNATURE_RE =
47
+ /\b(?:Deno\.serve|serve\s*\()\b|\bexport\s+(?:async\s+)?function\s+(?:POST|GET|PUT|PATCH|DELETE)\b|\bexport\s+default\s+(?:async\s+)?function\s+handler\b/;
48
+
49
+ function stripJsCommentsPreservingLines(source) {
50
+ let out = "";
51
+ let i = 0;
52
+ const n = source.length;
53
+
54
+ while (i < n) {
55
+ const ch = source[i];
56
+ const next = source[i + 1] || "";
57
+
58
+ if (ch === "'") {
59
+ out += ch;
60
+ i += 1;
61
+ while (i < n) {
62
+ const c = source[i];
63
+ out += c;
64
+ if (c === "\\" && i + 1 < n) {
65
+ out += source[i + 1];
66
+ i += 2;
67
+ continue;
68
+ }
69
+ i += 1;
70
+ if (c === "'") break;
71
+ }
72
+ continue;
73
+ }
74
+
75
+ if (ch === '"') {
76
+ out += ch;
77
+ i += 1;
78
+ while (i < n) {
79
+ const c = source[i];
80
+ out += c;
81
+ if (c === "\\" && i + 1 < n) {
82
+ out += source[i + 1];
83
+ i += 2;
84
+ continue;
85
+ }
86
+ i += 1;
87
+ if (c === '"') break;
88
+ }
89
+ continue;
90
+ }
91
+
92
+ if (ch === "`") {
93
+ out += ch;
94
+ i += 1;
95
+ while (i < n) {
96
+ const c = source[i];
97
+ out += c;
98
+ if (c === "\\" && i + 1 < n) {
99
+ out += source[i + 1];
100
+ i += 2;
101
+ continue;
102
+ }
103
+ i += 1;
104
+ if (c === "`") break;
105
+ }
106
+ continue;
107
+ }
108
+
109
+ if (ch === "/" && next === "/") {
110
+ out += " ";
111
+ i += 2;
112
+ while (i < n && source[i] !== "\n") {
113
+ out += source[i] === "\r" ? "\r" : " ";
114
+ i += 1;
115
+ }
116
+ continue;
117
+ }
118
+
119
+ if (ch === "/" && next === "*") {
120
+ out += " ";
121
+ i += 2;
122
+ while (i < n) {
123
+ if (source[i] === "*" && source[i + 1] === "/") {
124
+ out += " ";
125
+ i += 2;
126
+ break;
127
+ }
128
+ out += source[i] === "\n" ? "\n" : source[i] === "\r" ? "\r" : " ";
129
+ i += 1;
130
+ }
131
+ continue;
132
+ }
133
+
134
+ out += ch;
135
+ i += 1;
136
+ }
137
+
138
+ return out;
139
+ }
140
+
141
+ function isApiRouteFile(relFile, codeContent, rootIsStandaloneDir) {
142
+ const lower = relFile.toLowerCase();
143
+ if (lower.includes(".test.") || lower.includes(".spec.") || lower.includes("__tests__")) {
144
+ return false;
145
+ }
146
+ if (!/\.(?:ts|tsx|js|jsx|mjs|mts|cjs)$/i.test(lower)) return false;
147
+
148
+ if (
149
+ lower.startsWith("supabase/functions/") ||
150
+ lower.includes("/supabase/functions/") ||
151
+ /^(?:src\/)?(?:app|pages)\/api\//.test(lower) ||
152
+ /\/(?:app|pages)\/api\//.test(lower)
153
+ ) {
154
+ return HTTP_HANDLER_SIGNATURE_RE.test(codeContent) || lower.endsWith("index.ts") || lower.endsWith("index.js") || /route\.(?:ts|js)$/.test(lower);
155
+ }
156
+
157
+ // In standalone fixture directories without standard Next/Supabase folders,
158
+ // treat files declaring an HTTP handler entrypoint as API endpoints.
159
+ if (rootIsStandaloneDir && HTTP_HANDLER_SIGNATURE_RE.test(codeContent)) {
160
+ return true;
161
+ }
162
+
163
+ return false;
164
+ }
165
+
166
+ function findLineNumber(content, regex) {
167
+ const match = regex.exec(content);
168
+ if (!match) return 1;
169
+ return content.slice(0, match.index).split(/\r?\n/).length;
170
+ }
171
+
172
+ function resolveEdgeFunctionFile(rootDir, fnName) {
173
+ const candidates = [
174
+ path.join(rootDir, "supabase", "functions", fnName, "index.ts"),
175
+ path.join(rootDir, "supabase", "functions", fnName, "index.js"),
176
+ path.join(rootDir, "supabase", "functions", fnName, "index.mts"),
177
+ ];
178
+ return candidates.find((p) => fs.existsSync(p) && fs.statSync(p).isFile()) || null;
179
+ }
180
+
181
+ /**
182
+ * Evaluates Rule 10 (Edge verify_jwt = false), Rule 11 (AI endpoint no auth),
183
+ * and Rule 12 (OWASP API4 unbounded AI cost controls).
184
+ */
185
+ export function scanAiAndEdgeSurface(files, rootDir, configToml) {
186
+ const findings = [];
187
+ const reportedEdgeNoAuth = new Set();
188
+
189
+ // Check whether target root has standard app/supabase structure vs standalone fixture folder
190
+ const hasStandardStructure = files.some((f) => {
191
+ const rel = toPosixRelPath(rootDir, f).toLowerCase();
192
+ return (
193
+ rel.includes("supabase/functions/") ||
194
+ rel.includes("app/api/") ||
195
+ rel.includes("pages/api/")
196
+ );
197
+ });
198
+
199
+ // Rule 10: EDGE_FUNCTION_VERIFY_JWT_DISABLED from supabase/config.toml
200
+ if (configToml?.found && configToml.functions.size > 0) {
201
+ for (const fnMeta of configToml.functions.values()) {
202
+ if (fnMeta.verifyJwt !== false) continue;
203
+
204
+ const handlerPath = resolveEdgeFunctionFile(rootDir, fnMeta.name);
205
+ let handlerText = "";
206
+ let handlerRel = configToml.file;
207
+ if (handlerPath) {
208
+ handlerText = stripJsCommentsPreservingLines(fs.readFileSync(handlerPath, "utf8"));
209
+ handlerRel = toPosixRelPath(rootDir, handlerPath);
210
+ }
211
+
212
+ const hasWebhookSig = WEBHOOK_SIGNATURE_RE.test(handlerText);
213
+ const hasManualAuth = MANUAL_AUTH_RE.test(handlerText);
214
+ if (hasWebhookSig || hasManualAuth) continue;
215
+
216
+ const usesServiceRoleOrLlm =
217
+ SERVICE_ROLE_USAGE_RE.test(handlerText) || LLM_PROVIDER_RE.test(handlerText);
218
+
219
+ findings.push(
220
+ createFinding({
221
+ ruleId: "EDGE_FUNCTION_VERIFY_JWT_DISABLED",
222
+ severity: usesServiceRoleOrLlm ? "CRITICAL" : "HIGH",
223
+ file: handlerRel,
224
+ line: handlerPath ? 1 : fnMeta.line,
225
+ object: `supabase/functions/${fnMeta.name} (verify_jwt = false)`,
226
+ title: `Edge Function "${fnMeta.name}" disables verify_jwt without alternative auth`,
227
+ detail: `\`[functions.${fnMeta.name}].verify_jwt = false\` in supabase/config.toml disables Supabase JWT verification, and no webhook signature or manual auth verification was found in the handler.`,
228
+ snippet: `verify_jwt = false # ${fnMeta.name}`,
229
+ rootDir,
230
+ })
231
+ );
232
+ reportedEdgeNoAuth.add(fnMeta.name);
233
+ }
234
+ }
235
+
236
+ // Rules 11 & 12: AI / LLM endpoints (Edge Functions + Next.js / web API routes)
237
+ for (const filePath of files) {
238
+ const relFile = toPosixRelPath(rootDir, filePath);
239
+ let content;
240
+ try {
241
+ content = fs.readFileSync(filePath, "utf8");
242
+ } catch {
243
+ continue;
244
+ }
245
+
246
+ const code = stripJsCommentsPreservingLines(content);
247
+ if (!isApiRouteFile(relFile, code, !hasStandardStructure)) {
248
+ continue;
249
+ }
250
+ if (!LLM_PROVIDER_RE.test(code)) continue;
251
+
252
+ // Skip strictly BYOK endpoints that require caller-supplied API key without any server env fallback
253
+ const usesByokOnly = BYOK_HEADER_RE.test(code) && !SERVER_BILLED_KEY_RE.test(code);
254
+ if (usesByokOnly) continue;
255
+
256
+ const llmLine = findLineNumber(code, LLM_PROVIDER_RE);
257
+ const isEdgeFn = /(?:^|\/)supabase\/functions\/([^/]+)\//i.exec(relFile);
258
+ const edgeFnName = isEdgeFn ? isEdgeFn[1] : null;
259
+ const isEmbeddingOnly = EMBEDDING_ONLY_RE.test(code) && !GENERATION_CALL_RE.test(code);
260
+
261
+ // Check caller authentication
262
+ let hasAuth = MANUAL_AUTH_RE.test(code);
263
+ if (edgeFnName) {
264
+ const tomlFn = configToml?.functions?.get(edgeFnName);
265
+ // Supabase Edge Functions verify JWT by default unless verify_jwt = false in config.toml
266
+ const verifyJwtEnabled = tomlFn ? tomlFn.verifyJwt !== false : true;
267
+ if (verifyJwtEnabled) hasAuth = true;
268
+ }
269
+
270
+ // Rule 11: AI_ENDPOINT_NO_AUTH
271
+ if (!hasAuth) {
272
+ findings.push(
273
+ createFinding({
274
+ ruleId: "AI_ENDPOINT_NO_AUTH",
275
+ severity: "CRITICAL",
276
+ file: relFile,
277
+ line: llmLine,
278
+ object: `${relFile} (AI endpoint without auth)`,
279
+ title: `Paid AI endpoint "${relFile}" lacks caller authentication`,
280
+ detail: `Endpoint invokes a server-billed LLM provider without verifying user session, JWT, or API key, enabling unauthenticated wallet-drain abuse (OWASP API4).`,
281
+ snippet: content.split(/\r?\n/)[llmLine - 1] || "",
282
+ rootDir,
283
+ })
284
+ );
285
+ }
286
+
287
+ // Rule 12: AI_ENDPOINT_UNBOUNDED_COST (applies even when caller has a valid free JWT)
288
+ const missingGaps = [];
289
+ const modelFromRequest = MODEL_FROM_REQUEST_RE.test(code);
290
+ const hasModelAllowlist = MODEL_ALLOWLIST_RE.test(code);
291
+ const untrustedModel = modelFromRequest && !hasModelAllowlist;
292
+ if (untrustedModel) {
293
+ missingGaps.push("req.body.model allowlist");
294
+ }
295
+
296
+ const hasMaxTokensCap =
297
+ MAX_TOKENS_CLAMP_RE.test(code) && !RAW_UNCLAMPED_MAX_TOKENS_RE.test(code);
298
+ if (!isEmbeddingOnly && !hasMaxTokensCap) {
299
+ missingGaps.push("server-enforced max_tokens cap");
300
+ }
301
+
302
+ const hasBudgetOrRateLimit = BUDGET_OR_RATELIMIT_RE.test(code);
303
+ if (!hasBudgetOrRateLimit) {
304
+ missingGaps.push("rate limit / per-user budget guard");
305
+ }
306
+
307
+ // Embedding sync routes protected by explicit server/admin auth don't need max_tokens;
308
+ // avoid noisy alerts unless missing budget guard AND user-facing generation or untrusted model.
309
+ if (isEmbeddingOnly && hasAuth && !untrustedModel) {
310
+ continue;
311
+ }
312
+
313
+ if (
314
+ untrustedModel ||
315
+ (!hasBudgetOrRateLimit && !hasMaxTokensCap) ||
316
+ (!hasBudgetOrRateLimit && !isEmbeddingOnly)
317
+ ) {
318
+ const severity =
319
+ untrustedModel || (!hasBudgetOrRateLimit && !hasMaxTokensCap) ? "HIGH" : "MEDIUM";
320
+ findings.push(
321
+ createFinding({
322
+ ruleId: "AI_ENDPOINT_UNBOUNDED_COST",
323
+ severity,
324
+ file: relFile,
325
+ line: llmLine,
326
+ object: `${relFile} (OWASP API4 cost controls)`,
327
+ title: `AI endpoint "${relFile}" lacks ${missingGaps.join(", ")}`,
328
+ detail: `Authenticated callers (or free-tier bot accounts) can trigger unbounded LLM spend due to missing: ${missingGaps.join(", ")}.`,
329
+ snippet: content.split(/\r?\n/)[llmLine - 1] || "",
330
+ rootDir,
331
+ })
332
+ );
333
+ }
334
+ }
335
+
336
+ return findings;
337
+ }
@@ -0,0 +1,137 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { toPosixRelPath } from "../core/findings.js";
4
+
5
+ function stripTomlComment(line) {
6
+ let inSingle = false;
7
+ let inDouble = false;
8
+ for (let i = 0; i < line.length; i++) {
9
+ const ch = line[i];
10
+ if (ch === "'" && !inDouble) {
11
+ inSingle = !inSingle;
12
+ } else if (ch === '"' && !inSingle && line[i - 1] !== "\\") {
13
+ inDouble = !inDouble;
14
+ } else if (ch === "#" && !inSingle && !inDouble) {
15
+ return line.slice(0, i);
16
+ }
17
+ }
18
+ return line;
19
+ }
20
+
21
+ function parseTomlValue(raw) {
22
+ const trimmed = raw.trim();
23
+ if (trimmed === "true") return true;
24
+ if (trimmed === "false") return false;
25
+ if (/^-?\d+$/.test(trimmed)) return Number(trimmed);
26
+ if (
27
+ (trimmed.startsWith('"') && trimmed.endsWith('"')) ||
28
+ (trimmed.startsWith("'") && trimmed.endsWith("'"))
29
+ ) {
30
+ return trimmed.slice(1, -1);
31
+ }
32
+ if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
33
+ const inner = trimmed.slice(1, -1).trim();
34
+ if (!inner) return [];
35
+ return inner
36
+ .split(",")
37
+ .map((item) => parseTomlValue(item))
38
+ .filter((v) => v !== "");
39
+ }
40
+ return trimmed;
41
+ }
42
+
43
+ /**
44
+ * Parses `supabase/config.toml` (when present) to extract API schemas/enabled state
45
+ * and per-function `verify_jwt` flags with accurate 1-based line numbers.
46
+ */
47
+ export function parseSupabaseConfigToml(rootDir) {
48
+ const candidates = [
49
+ path.join(rootDir, "supabase", "config.toml"),
50
+ path.join(rootDir, "config.toml"),
51
+ ];
52
+ const configPath = candidates.find((p) => fs.existsSync(p) && fs.statSync(p).isFile());
53
+ if (!configPath) {
54
+ return {
55
+ found: false,
56
+ file: null,
57
+ api: { enabled: true, schemas: ["public"] },
58
+ functions: new Map(),
59
+ };
60
+ }
61
+
62
+ const relFile = toPosixRelPath(rootDir, configPath);
63
+ const rawText = fs.readFileSync(configPath, "utf8");
64
+ const lines = rawText.split(/\r?\n/);
65
+
66
+ const result = {
67
+ found: true,
68
+ file: relFile,
69
+ rawText,
70
+ api: { enabled: true, schemas: ["public"], line: 1 },
71
+ functions: new Map(),
72
+ };
73
+
74
+ let currentSection = "";
75
+ let pendingKey = null;
76
+ let pendingVal = "";
77
+ let pendingLine = 1;
78
+
79
+ function applyKeyValue(section, key, val, lineNum) {
80
+ if (section === "api") {
81
+ if (key === "enabled" && typeof val === "boolean") {
82
+ result.api.enabled = val;
83
+ result.api.line = lineNum;
84
+ } else if (key === "schemas" && Array.isArray(val) && val.length > 0) {
85
+ result.api.schemas = val.map((s) => String(s).toLowerCase());
86
+ }
87
+ } else if (section.startsWith("functions.")) {
88
+ const fnName = section.slice("functions.".length).replace(/^["']|["']$/g, "");
89
+ if (!fnName) return;
90
+ if (!result.functions.has(fnName)) {
91
+ result.functions.set(fnName, { name: fnName, verifyJwt: true, line: lineNum });
92
+ }
93
+ const entry = result.functions.get(fnName);
94
+ if (key === "verify_jwt" && typeof val === "boolean") {
95
+ entry.verifyJwt = val;
96
+ entry.line = lineNum;
97
+ }
98
+ }
99
+ }
100
+
101
+ for (let idx = 0; idx < lines.length; idx++) {
102
+ const clean = stripTomlComment(lines[idx]).trim();
103
+ if (!clean) continue;
104
+
105
+ if (pendingKey) {
106
+ pendingVal += ` ${clean}`;
107
+ if (clean.includes("]")) {
108
+ applyKeyValue(currentSection, pendingKey, parseTomlValue(pendingVal), pendingLine);
109
+ pendingKey = null;
110
+ pendingVal = "";
111
+ }
112
+ continue;
113
+ }
114
+
115
+ const secMatch = clean.match(/^\[([^\]]+)\]$/);
116
+ if (secMatch) {
117
+ currentSection = secMatch[1].trim();
118
+ continue;
119
+ }
120
+
121
+ const eqIdx = clean.indexOf("=");
122
+ if (eqIdx === -1) continue;
123
+ const key = clean.slice(0, eqIdx).trim();
124
+ const rawVal = clean.slice(eqIdx + 1).trim();
125
+
126
+ if (rawVal.startsWith("[") && !rawVal.endsWith("]")) {
127
+ pendingKey = key;
128
+ pendingVal = rawVal;
129
+ pendingLine = idx + 1;
130
+ continue;
131
+ }
132
+
133
+ applyKeyValue(currentSection, key, parseTomlValue(rawVal), idx + 1);
134
+ }
135
+
136
+ return result;
137
+ }
@@ -0,0 +1,105 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { toPosixRelPath } from "../core/findings.js";
4
+
5
+ const SKIP_DIRS = new Set([
6
+ ".git",
7
+ "node_modules",
8
+ ".next",
9
+ ".nuxt",
10
+ "dist",
11
+ "build",
12
+ ".turbo",
13
+ ".cache",
14
+ "coverage",
15
+ ".vercel",
16
+ ".netlify",
17
+ "out",
18
+ ".svelte-kit",
19
+ ]);
20
+
21
+ const SKIP_FILES = new Set([
22
+ "package-lock.json",
23
+ "pnpm-lock.yaml",
24
+ "yarn.lock",
25
+ "bun.lockb",
26
+ "npm-shrinkwrap.json",
27
+ ]);
28
+
29
+ const ALLOWED_EXTENSIONS = new Set([
30
+ ".js",
31
+ ".mjs",
32
+ ".cjs",
33
+ ".jsx",
34
+ ".ts",
35
+ ".mts",
36
+ ".cts",
37
+ ".tsx",
38
+ ".vue",
39
+ ".svelte",
40
+ ".html",
41
+ ".toml",
42
+ ".json",
43
+ ".yaml",
44
+ ".yml",
45
+ ".sql",
46
+ ".env",
47
+ ]);
48
+
49
+ const MAX_FILE_BYTES = 1024 * 1024; // 1 MB
50
+
51
+ function isScannableFile(fileName) {
52
+ const lower = fileName.toLowerCase();
53
+ if (SKIP_FILES.has(lower)) return false;
54
+ if (lower === ".env" || lower.startsWith(".env.")) return true;
55
+ const ext = path.extname(lower);
56
+ return ALLOWED_EXTENSIONS.has(ext);
57
+ }
58
+
59
+ /**
60
+ * Safely collects scannable text files under a directory or single file path,
61
+ * skipping build artifacts, lockfiles, oversized files, and .rlsproofignore paths.
62
+ */
63
+ export function walkRepoFiles(targetPath, ignoreConfig = null) {
64
+ const abs = path.resolve(targetPath);
65
+ const stat = fs.statSync(abs);
66
+
67
+ if (stat.isFile()) {
68
+ const rootDir = path.dirname(abs);
69
+ if (stat.size <= MAX_FILE_BYTES && isScannableFile(path.basename(abs))) {
70
+ return { rootDir, files: [abs] };
71
+ }
72
+ return { rootDir, files: [] };
73
+ }
74
+
75
+ const files = [];
76
+
77
+ function walk(dir) {
78
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
79
+ for (const entry of entries) {
80
+ if (SKIP_DIRS.has(entry.name)) continue;
81
+ const full = path.join(dir, entry.name);
82
+ const relPosix = toPosixRelPath(abs, full);
83
+
84
+ if (ignoreConfig?.isPathIgnored(relPosix)) continue;
85
+
86
+ if (entry.isDirectory()) {
87
+ walk(full);
88
+ } else if (entry.isFile()) {
89
+ if (!isScannableFile(entry.name)) continue;
90
+ try {
91
+ const st = fs.statSync(full);
92
+ if (st.size <= MAX_FILE_BYTES) {
93
+ files.push(full);
94
+ }
95
+ } catch {
96
+ // Skip unreadable files cleanly
97
+ }
98
+ }
99
+ }
100
+ }
101
+
102
+ walk(abs);
103
+ files.sort((a, b) => a.replace(/\\/g, "/").localeCompare(b.replace(/\\/g, "/")));
104
+ return { rootDir: abs, files };
105
+ }