supabase-scan 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +28 -0
  2. package/README.md +36 -2
  3. package/dist/cli.js +1483 -0
  4. package/package.json +41 -3
package/dist/cli.js ADDED
@@ -0,0 +1,1483 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { createRequire } from "module";
5
+
6
+ // ../core/dist/index.js
7
+ var SEVERITY_RANK = {
8
+ CRITICAL: 5,
9
+ HIGH: 4,
10
+ MEDIUM: 3,
11
+ LOW: 2,
12
+ INFO: 1,
13
+ OK: 0
14
+ };
15
+ function base64UrlToString(b64url) {
16
+ const padLen = b64url.length % 4;
17
+ const pad = padLen === 0 ? "" : "=".repeat(4 - padLen);
18
+ const b64 = b64url.replace(/-/g, "+").replace(/_/g, "/") + pad;
19
+ const binary = atob(b64);
20
+ const bytes = Uint8Array.from(binary, (ch) => ch.charCodeAt(0));
21
+ return new TextDecoder().decode(bytes);
22
+ }
23
+ function decodeJwtPayload(token) {
24
+ const parts = token.split(".");
25
+ if (parts.length !== 3) return null;
26
+ const payloadPart = parts[1];
27
+ if (!payloadPart) return null;
28
+ try {
29
+ const parsed = JSON.parse(base64UrlToString(payloadPart));
30
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
31
+ return parsed;
32
+ }
33
+ return null;
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
38
+ function classifyApiKey(token) {
39
+ const t = token.trim();
40
+ if (t.startsWith("sb_secret_")) return { keyType: "new", role: "service_role" };
41
+ if (t.startsWith("sb_publishable_")) return { keyType: "new", role: "anon" };
42
+ const payload = decodeJwtPayload(t);
43
+ if (payload) {
44
+ const role = typeof payload.role === "string" ? payload.role : "unknown";
45
+ return { keyType: "jwt", role };
46
+ }
47
+ return { keyType: "unknown", role: "unknown" };
48
+ }
49
+ function isPublicRole(role) {
50
+ return role === "anon" || role === "authenticated" || role === "unknown";
51
+ }
52
+ var SENSITIVE_COLUMN_PATTERNS = {
53
+ CRITICAL: [
54
+ "password",
55
+ "passwd",
56
+ "pass_hash",
57
+ "password_hash",
58
+ "hashed_password",
59
+ "secret",
60
+ "secret_key",
61
+ "api_key",
62
+ "apikey",
63
+ "api_secret",
64
+ "access_token",
65
+ "refresh_token",
66
+ "auth_token",
67
+ "private_key",
68
+ "priv_key",
69
+ "credit_card",
70
+ "card_number",
71
+ "card_num",
72
+ "cc_number",
73
+ "cvv",
74
+ "cvc",
75
+ "ccv",
76
+ "ssn",
77
+ "social_security",
78
+ "social_security_number",
79
+ "encryption_key",
80
+ "master_key"
81
+ ],
82
+ HIGH: [
83
+ // A bare "token" segment is often a type or count (token_type), so it is
84
+ // HIGH; the named token kinds above stay CRITICAL.
85
+ "token",
86
+ "email",
87
+ "email_address",
88
+ "user_email",
89
+ "phone",
90
+ "phone_number",
91
+ "mobile",
92
+ "mobile_number",
93
+ "telephone",
94
+ "address",
95
+ "street_address",
96
+ "home_address",
97
+ "mailing_address",
98
+ "date_of_birth",
99
+ "dob",
100
+ "birth_date",
101
+ "birthday",
102
+ "salary",
103
+ "income",
104
+ "compensation",
105
+ "wage",
106
+ "bank_account",
107
+ "account_number",
108
+ "iban",
109
+ "routing_number",
110
+ "drivers_license",
111
+ "driver_license",
112
+ "passport_number",
113
+ "tax_id",
114
+ "ein",
115
+ "tin"
116
+ ],
117
+ MEDIUM: [
118
+ "first_name",
119
+ "last_name",
120
+ "full_name",
121
+ "display_name",
122
+ "username",
123
+ "user_name",
124
+ "login",
125
+ "ip_address",
126
+ "ip_addr",
127
+ "client_ip",
128
+ "remote_addr",
129
+ "location",
130
+ "geo_location",
131
+ "latitude",
132
+ "longitude",
133
+ "lat",
134
+ "lng",
135
+ "age",
136
+ "gender",
137
+ "race",
138
+ "ethnicity",
139
+ "religion",
140
+ "medical",
141
+ "diagnosis",
142
+ "health"
143
+ ]
144
+ };
145
+ var NON_SENSITIVE_FIELDS = /* @__PURE__ */ new Set([
146
+ "id",
147
+ "uuid",
148
+ "uid",
149
+ "created_at",
150
+ "updated_at",
151
+ "deleted_at",
152
+ "modified_at",
153
+ "created_by",
154
+ "updated_by",
155
+ "description",
156
+ "title",
157
+ "content",
158
+ "body",
159
+ "text",
160
+ "note",
161
+ "notes",
162
+ "name",
163
+ "label",
164
+ "slug",
165
+ "handle",
166
+ "image",
167
+ "image_url",
168
+ "avatar",
169
+ "avatar_url",
170
+ "icon",
171
+ "thumbnail",
172
+ "photo",
173
+ "picture",
174
+ "logo",
175
+ "banner",
176
+ "cover",
177
+ "url",
178
+ "link",
179
+ "href",
180
+ "src",
181
+ "source",
182
+ "type",
183
+ "kind",
184
+ "category",
185
+ "status",
186
+ "state",
187
+ "role",
188
+ "count",
189
+ "total",
190
+ "amount",
191
+ "quantity",
192
+ "size",
193
+ "color",
194
+ "colour",
195
+ "theme",
196
+ "author",
197
+ "creator",
198
+ "owner",
199
+ "search_vector",
200
+ "vector",
201
+ "embedding",
202
+ "metadata",
203
+ "meta",
204
+ "config",
205
+ "options",
206
+ "settings",
207
+ "is_active",
208
+ "is_deleted",
209
+ "is_public",
210
+ "is_verified",
211
+ "enabled",
212
+ "disabled",
213
+ "visible",
214
+ "hidden",
215
+ "sort_order",
216
+ "position",
217
+ "rank",
218
+ "priority",
219
+ "weight",
220
+ "currency",
221
+ "language",
222
+ "locale",
223
+ "timezone",
224
+ "example_emails"
225
+ ]);
226
+ var SEVERITY_ORDER = ["CRITICAL", "HIGH", "MEDIUM"];
227
+ function isNonSensitiveField(columnName) {
228
+ return NON_SENSITIVE_FIELDS.has(columnName.toLowerCase());
229
+ }
230
+ function segmentsOf(columnName) {
231
+ return columnName.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").toLowerCase().split(/[_\-\s]+/).filter((s) => s !== "");
232
+ }
233
+ function containsRun(segments, parts) {
234
+ for (let i = 0; i + parts.length <= segments.length; i++) {
235
+ if (parts.every((p, j) => segments[i + j] === p)) return true;
236
+ }
237
+ return false;
238
+ }
239
+ function classifyColumn(columnName) {
240
+ if (isNonSensitiveField(columnName)) return null;
241
+ const segments = segmentsOf(columnName);
242
+ if (isNonSensitiveField(segments.join("_"))) return null;
243
+ let best = null;
244
+ for (const severity of SEVERITY_ORDER) {
245
+ for (const pattern of SENSITIVE_COLUMN_PATTERNS[severity] ?? []) {
246
+ const parts = pattern.split("_");
247
+ if (best && parts.length <= best.span) continue;
248
+ if (containsRun(segments, parts)) {
249
+ best = { severity, pattern, span: parts.length };
250
+ }
251
+ }
252
+ }
253
+ return best ? { severity: best.severity, pattern: best.pattern } : null;
254
+ }
255
+ function maskValue(value, severity) {
256
+ if (value === null || value === void 0) return "NULL";
257
+ const s = String(value);
258
+ if (s === "") return "(empty)";
259
+ if (severity === "CRITICAL") {
260
+ return s.slice(0, 1) + "*".repeat(Math.min(s.length - 1, 15));
261
+ }
262
+ if (severity === "HIGH") {
263
+ if (s.includes("@")) {
264
+ const parts = s.split("@");
265
+ const local = parts[0] ?? "";
266
+ const domain = parts[parts.length - 1] ?? "";
267
+ return local.slice(0, 2) + "***@" + domain;
268
+ }
269
+ return s.slice(0, 2) + "*".repeat(Math.min(s.length - 2, 10));
270
+ }
271
+ return s.slice(0, 3) + "***";
272
+ }
273
+ function normalizeUrl(url) {
274
+ let u = url.trim().replace(/\/+$/, "");
275
+ if (!/^https?:\/\//i.test(u)) u = "https://" + u;
276
+ return u;
277
+ }
278
+ function parseContentRangeCount(value) {
279
+ if (!value || !value.includes("/")) return null;
280
+ const total = value.slice(value.lastIndexOf("/") + 1).trim();
281
+ if (total === "*" || !/^\d+$/.test(total)) return null;
282
+ return Number.parseInt(total, 10);
283
+ }
284
+ function authHeaders(token) {
285
+ return {
286
+ apikey: token,
287
+ Authorization: `Bearer ${token}`,
288
+ Accept: "application/json"
289
+ };
290
+ }
291
+ var REDIRECT_REFUSED = "Redirect refused";
292
+ function describeError(err) {
293
+ const message = err instanceof Error ? err.message : String(err);
294
+ const cause = err instanceof Error && err.cause instanceof Error ? err.cause.message : "";
295
+ if (/redirect/i.test(message) || /redirect/i.test(cause)) {
296
+ return `${REDIRECT_REFUSED}: the URL redirects, and the key is never sent on.`;
297
+ }
298
+ return message;
299
+ }
300
+ async function request(ctx, path, options = {}) {
301
+ const url = `${ctx.baseUrl}${path}`;
302
+ const headers = { ...authHeaders(ctx.token), ...options.headers ?? {} };
303
+ const controller = new AbortController();
304
+ const timer = setTimeout(() => controller.abort(), ctx.timeoutMs);
305
+ try {
306
+ const resp = await ctx.fetch(url, {
307
+ method: options.method ?? "GET",
308
+ headers,
309
+ body: options.body,
310
+ signal: controller.signal,
311
+ // The key rides in the `apikey` header, which fetch keeps on a
312
+ // cross-origin redirect. Never follow one.
313
+ redirect: "error"
314
+ });
315
+ const text = await resp.text();
316
+ let data = text;
317
+ try {
318
+ data = JSON.parse(text);
319
+ } catch {
320
+ }
321
+ return { status: resp.status, data, headers: resp.headers };
322
+ } catch (err) {
323
+ return {
324
+ status: null,
325
+ data: null,
326
+ headers: null,
327
+ error: describeError(err)
328
+ };
329
+ } finally {
330
+ clearTimeout(timer);
331
+ }
332
+ }
333
+ var DAY_SECONDS = 86400;
334
+ function analyzeKey(token) {
335
+ const findings = [];
336
+ const { keyType, role } = classifyApiKey(token);
337
+ if (keyType === "new") {
338
+ if (role === "service_role") {
339
+ findings.push({
340
+ ruleId: "key.secret_exposed",
341
+ severity: "INFO",
342
+ category: "Key",
343
+ title: "sb_secret_ key: full access, bypasses RLS",
344
+ detail: "Secret key. Keep it server-side, never ship it client-side."
345
+ });
346
+ } else {
347
+ findings.push({
348
+ ruleId: "key.publishable",
349
+ severity: "INFO",
350
+ category: "Key",
351
+ title: "sb_publishable_ key: public by design",
352
+ detail: "Safe to expose. Security depends on RLS policies."
353
+ });
354
+ }
355
+ return findings;
356
+ }
357
+ if (keyType === "unknown") {
358
+ findings.push({
359
+ ruleId: "key.unrecognized",
360
+ severity: "MEDIUM",
361
+ category: "Key",
362
+ title: "Unrecognized API key format",
363
+ detail: "Not a valid JWT or sb_ key. The scan may be limited."
364
+ });
365
+ return findings;
366
+ }
367
+ const payload = decodeJwtPayload(token) ?? {};
368
+ if (role === "service_role") {
369
+ findings.push({
370
+ ruleId: "key.service_role_exposed",
371
+ severity: "INFO",
372
+ category: "Key",
373
+ title: "service_role key: bypasses Row Level Security",
374
+ detail: "Full database access. Keep it server-side, never ship it client-side."
375
+ });
376
+ } else if (role === "anon") {
377
+ findings.push({
378
+ ruleId: "key.anon",
379
+ severity: "INFO",
380
+ category: "Key",
381
+ title: "anon key: public by design",
382
+ detail: "Safe to expose. Security depends on RLS policies."
383
+ });
384
+ } else if (role === "authenticated") {
385
+ findings.push({
386
+ ruleId: "key.authenticated",
387
+ severity: "MEDIUM",
388
+ category: "Key",
389
+ title: "authenticated user token",
390
+ detail: "Scoped to one user. It should not be shared or embedded."
391
+ });
392
+ } else {
393
+ findings.push({
394
+ ruleId: "key.role_other",
395
+ severity: "INFO",
396
+ category: "Key",
397
+ title: `Key role: ${role}`
398
+ });
399
+ }
400
+ if (role === "anon") return findings;
401
+ const exp = typeof payload.exp === "number" ? payload.exp : void 0;
402
+ if (exp === void 0) {
403
+ findings.push({
404
+ ruleId: "key.no_expiry",
405
+ severity: "HIGH",
406
+ category: "Key",
407
+ title: "Token has no expiry",
408
+ detail: "A non-expiring token cannot be retired by expiry; rotate with care."
409
+ });
410
+ } else {
411
+ const nowSeconds = Date.now() / 1e3;
412
+ if (exp < nowSeconds) {
413
+ findings.push({
414
+ ruleId: "key.expired",
415
+ severity: "OK",
416
+ category: "Key",
417
+ title: "Token is expired",
418
+ evidence: { expiresAt: new Date(exp * 1e3).toISOString() }
419
+ });
420
+ } else {
421
+ const days = Math.floor((exp - nowSeconds) / DAY_SECONDS);
422
+ if (days > 3650) {
423
+ findings.push({
424
+ ruleId: "key.long_expiry",
425
+ severity: "HIGH",
426
+ category: "Key",
427
+ title: `Token expiry is ${days} days (10+ years)`,
428
+ detail: "Extremely long-lived tokens are hard to contain if leaked.",
429
+ evidence: { days }
430
+ });
431
+ }
432
+ }
433
+ }
434
+ return findings;
435
+ }
436
+ var COMMON_TABLES = [
437
+ "users",
438
+ "profiles",
439
+ "accounts",
440
+ "customers",
441
+ "orders",
442
+ "payments",
443
+ "transactions",
444
+ "invoices",
445
+ "products",
446
+ "items",
447
+ "categories",
448
+ "posts",
449
+ "comments",
450
+ "messages",
451
+ "notifications",
452
+ "sessions",
453
+ "logs",
454
+ "events",
455
+ "analytics",
456
+ "settings",
457
+ "configurations",
458
+ "permissions",
459
+ "roles",
460
+ "files",
461
+ "documents",
462
+ "uploads",
463
+ "media",
464
+ "subscriptions",
465
+ "plans",
466
+ "billing",
467
+ "contacts",
468
+ "leads",
469
+ "organizations",
470
+ "teams",
471
+ "user",
472
+ "profile",
473
+ "account",
474
+ "customer",
475
+ "order",
476
+ "payment",
477
+ "item",
478
+ "post",
479
+ "comment",
480
+ "message",
481
+ "notification",
482
+ "event",
483
+ "setting",
484
+ "file",
485
+ "document",
486
+ "device",
487
+ "devices",
488
+ "task",
489
+ "tasks",
490
+ "todo",
491
+ "todos",
492
+ "note",
493
+ "notes",
494
+ "project",
495
+ "projects",
496
+ "member",
497
+ "members",
498
+ "chat",
499
+ "chats"
500
+ ];
501
+ var MAX_PROBES = 150;
502
+ var CONCURRENCY = 6;
503
+ var TABLE_NAME = /^[A-Za-z_][A-Za-z0-9_$]{0,62}$/;
504
+ var HINT = /Perhaps you meant the table '(?:(\w+)\.)?([A-Za-z0-9_$]+)'/;
505
+ function tablesFromOpenApi(data) {
506
+ if (!data || typeof data !== "object") return [];
507
+ const obj = data;
508
+ const definitions = obj.definitions;
509
+ if (definitions && typeof definitions === "object") {
510
+ return Object.keys(definitions);
511
+ }
512
+ const paths = obj.paths;
513
+ if (paths && typeof paths === "object") {
514
+ return Object.keys(paths).map((p) => p.replace(/^\//, "")).filter((name) => name.length > 0 && !name.startsWith("rpc/"));
515
+ }
516
+ return [];
517
+ }
518
+ var COLUMN_NAME = /^[A-Za-z_][A-Za-z0-9_$-]{0,62}$/;
519
+ var MAX_COLUMNS_PER_TABLE = 300;
520
+ function columnsFromOpenApi(data) {
521
+ const out = {};
522
+ if (!data || typeof data !== "object") return out;
523
+ const definitions = data.definitions;
524
+ if (!definitions || typeof definitions !== "object") return out;
525
+ for (const [table, def] of Object.entries(definitions)) {
526
+ const props = def && typeof def === "object" ? def.properties : void 0;
527
+ if (props && typeof props === "object") {
528
+ out[table] = Object.keys(props).filter((name) => COLUMN_NAME.test(name)).slice(0, MAX_COLUMNS_PER_TABLE);
529
+ }
530
+ }
531
+ return out;
532
+ }
533
+ function field(data, name) {
534
+ if (data && typeof data === "object" && name in data) {
535
+ const value = data[name];
536
+ return typeof value === "string" ? value : void 0;
537
+ }
538
+ return void 0;
539
+ }
540
+ function hintedTable(data) {
541
+ const match = HINT.exec(field(data, "hint") ?? "");
542
+ if (!match) return void 0;
543
+ const [, schema, table] = match;
544
+ return schema === void 0 || schema === "public" ? table : void 0;
545
+ }
546
+ function cleanTableNames(names) {
547
+ const out = [];
548
+ const rejected = [];
549
+ for (const raw of names) {
550
+ const trimmed = raw.trim();
551
+ if (trimmed === "") continue;
552
+ const name = trimmed.replace(/^public\./i, "");
553
+ if (!TABLE_NAME.test(name)) {
554
+ if (!rejected.includes(trimmed)) rejected.push(trimmed);
555
+ } else if (!out.includes(name)) {
556
+ out.push(name);
557
+ }
558
+ }
559
+ return { names: out, rejected };
560
+ }
561
+ async function probe(ctx, own, builtIn) {
562
+ const queue = [...own, ...builtIn];
563
+ const seen = new Set(queue);
564
+ const outcome = /* @__PURE__ */ new Map();
565
+ const hinted = [];
566
+ const limit = own.length + MAX_PROBES;
567
+ let sent = 0;
568
+ let sample;
569
+ async function worker() {
570
+ while (sent < limit) {
571
+ const table = queue.shift();
572
+ if (table === void 0) return;
573
+ sent++;
574
+ const res = await request(
575
+ ctx,
576
+ `/rest/v1/${encodeURIComponent(table)}?select=*&limit=0`
577
+ );
578
+ const code = field(res.data, "code");
579
+ if (res.status === 200 || res.status === 206) {
580
+ outcome.set(table, "readable");
581
+ } else if ((res.status === 401 || res.status === 403) && code === "42501") {
582
+ outcome.set(table, "denied");
583
+ } else if (res.status === 404 && code === "PGRST205") {
584
+ outcome.set(table, "missing");
585
+ const next = hintedTable(res.data);
586
+ if (next && !seen.has(next)) {
587
+ seen.add(next);
588
+ hinted.push(next);
589
+ queue.unshift(next);
590
+ }
591
+ } else {
592
+ outcome.set(table, "unknown");
593
+ sample ??= { status: res.status, code, error: res.error };
594
+ }
595
+ }
596
+ }
597
+ await Promise.all(Array.from({ length: CONCURRENCY }, worker));
598
+ const pick = (o) => [...outcome].filter(([, v]) => v === o).map(([k]) => k);
599
+ return {
600
+ readable: pick("readable"),
601
+ denied: pick("denied"),
602
+ hinted,
603
+ missing: pick("missing").length,
604
+ unknown: pick("unknown"),
605
+ sample,
606
+ skipped: queue.length
607
+ };
608
+ }
609
+ function answeredCount(result) {
610
+ return result.readable.length + result.denied.length + result.missing;
611
+ }
612
+ function probeFindings(result, answered) {
613
+ const findings = [];
614
+ const { readable, denied, hinted, unknown, sample, skipped } = result;
615
+ if (answered === 0) {
616
+ findings.push({
617
+ ruleId: "tables.probe_failed",
618
+ severity: "MEDIUM",
619
+ category: "Tables",
620
+ title: "Could not check any table: no probe got a clear answer",
621
+ detail: "Check the key and URL. A bad or expired key, rate limiting or a network block gives this.",
622
+ evidence: { ...sample }
623
+ });
624
+ return findings;
625
+ }
626
+ if (unknown.length > 0) {
627
+ findings.push({
628
+ ruleId: "tables.probe_incomplete",
629
+ severity: "INFO",
630
+ category: "Tables",
631
+ title: `${unknown.length} table probe(s) got no clear answer`,
632
+ evidence: { tables: unknown, ...sample }
633
+ });
634
+ }
635
+ if (skipped > 0) {
636
+ findings.push({
637
+ ruleId: "tables.probe_limit",
638
+ severity: "INFO",
639
+ category: "Tables",
640
+ title: `${skipped} name(s) left unprobed: probe limit reached`
641
+ });
642
+ }
643
+ if (hinted.length > 0) {
644
+ findings.push({
645
+ ruleId: "tables.name_hint",
646
+ severity: "LOW",
647
+ category: "Tables",
648
+ title: `Error hints revealed ${hinted.length} table name(s)`,
649
+ detail: "PostgREST suggests the closest table name on a miss. Names alone are not a leak while grants and RLS hold.",
650
+ evidence: { tables: hinted }
651
+ });
652
+ }
653
+ if (denied.length > 0) {
654
+ findings.push({
655
+ ruleId: "tables.denied",
656
+ severity: "OK",
657
+ category: "Tables",
658
+ title: `${denied.length} table(s) found, no access with this key`,
659
+ evidence: { tables: denied }
660
+ });
661
+ }
662
+ if (readable.length > 0) {
663
+ findings.push({
664
+ ruleId: "tables.queryable",
665
+ severity: "INFO",
666
+ category: "Tables",
667
+ title: `${readable.length} table(s) queryable with this key`,
668
+ detail: "The key has a grant on them. The RLS check counts visible rows.",
669
+ evidence: { tables: readable }
670
+ });
671
+ }
672
+ if (readable.length === 0 && denied.length === 0) {
673
+ findings.push({
674
+ ruleId: "tables.none_found",
675
+ severity: "INFO",
676
+ category: "Tables",
677
+ title: "No table found by name",
678
+ detail: "Add your own table names to check them."
679
+ });
680
+ }
681
+ return findings;
682
+ }
683
+ async function enumerateTables(ctx, extraTables = []) {
684
+ const findings = [];
685
+ const { names: extra, rejected } = cleanTableNames(extraTables);
686
+ if (rejected.length > 0) {
687
+ findings.push({
688
+ ruleId: "tables.bad_names",
689
+ severity: "INFO",
690
+ category: "Tables",
691
+ title: `${rejected.length} table name(s) skipped: not a plain identifier`,
692
+ evidence: { tables: rejected }
693
+ });
694
+ }
695
+ const res = await request(ctx, "/rest/v1/");
696
+ if (res.status === null) {
697
+ findings.push({
698
+ ruleId: "tables.rest_unreachable",
699
+ severity: "INFO",
700
+ category: "Tables",
701
+ title: "REST API could not be reached from this environment",
702
+ detail: res.error
703
+ });
704
+ return { enumerated: [], toCheck: [], findings };
705
+ }
706
+ const fromSpec = res.status === 200 ? tablesFromOpenApi(res.data) : [];
707
+ if (fromSpec.length > 0) {
708
+ findings.push({
709
+ ruleId: "tables.enumerable",
710
+ severity: "LOW",
711
+ category: "Tables",
712
+ title: `${fromSpec.length} table(s) listed via the OpenAPI spec`,
713
+ detail: "Listed does not mean readable; the RLS check measures access.",
714
+ evidence: { tables: fromSpec }
715
+ });
716
+ const unlisted = extra.filter((t) => !fromSpec.includes(t));
717
+ const columns = columnsFromOpenApi(res.data);
718
+ if (unlisted.length === 0) {
719
+ return { enumerated: fromSpec, toCheck: fromSpec, findings, columns };
720
+ }
721
+ const result2 = await probe(ctx, unlisted, []);
722
+ findings.push(...probeFindings(result2, answeredCount(result2)));
723
+ return {
724
+ enumerated: [...fromSpec, ...result2.readable, ...result2.denied],
725
+ toCheck: [...fromSpec, ...result2.readable],
726
+ findings,
727
+ columns
728
+ };
729
+ }
730
+ const builtIn = cleanTableNames(COMMON_TABLES).names.filter(
731
+ (t) => !extra.includes(t)
732
+ );
733
+ const result = await probe(ctx, extra, builtIn);
734
+ const answered = answeredCount(result);
735
+ if ((res.status === 401 || res.status === 403) && answered > 0) {
736
+ findings.push({
737
+ ruleId: "tables.spec_hidden",
738
+ severity: "OK",
739
+ category: "Tables",
740
+ title: "Table list (OpenAPI) is hidden from this key",
741
+ detail: "Expected on hosted Supabase. Tables were probed by name instead."
742
+ });
743
+ }
744
+ findings.push(...probeFindings(result, answered));
745
+ return {
746
+ enumerated: [...result.readable, ...result.denied],
747
+ toCheck: result.readable,
748
+ findings
749
+ };
750
+ }
751
+ async function checkRls(ctx, tables, role) {
752
+ const findings = [];
753
+ if (role === "service_role") {
754
+ findings.push({
755
+ ruleId: "rls.service_role_bypass",
756
+ severity: "LOW",
757
+ category: "RLS",
758
+ title: "Full-access key: RLS not tested",
759
+ detail: "Rerun with the anon or publishable key to test public access."
760
+ });
761
+ }
762
+ const publicKey = isPublicRole(role);
763
+ for (const table of tables) {
764
+ const res = await request(ctx, `/rest/v1/${encodeURIComponent(table)}?select=*&limit=0`, {
765
+ headers: { Prefer: "count=exact" }
766
+ });
767
+ if (res.status === null) {
768
+ findings.push({
769
+ ruleId: "rls.check_failed",
770
+ severity: "INFO",
771
+ category: "RLS",
772
+ title: `${table}: could not be checked`,
773
+ detail: res.error
774
+ });
775
+ continue;
776
+ }
777
+ if (res.status !== 200 && res.status !== 206) {
778
+ findings.push({
779
+ ruleId: "rls.table_inaccessible",
780
+ severity: "OK",
781
+ category: "RLS",
782
+ title: `${table}: not readable with this key`,
783
+ evidence: { status: res.status }
784
+ });
785
+ continue;
786
+ }
787
+ const count = parseContentRangeCount(res.headers?.get("Content-Range") ?? null);
788
+ if (count === null) {
789
+ findings.push({
790
+ ruleId: "rls.count_unknown",
791
+ severity: "INFO",
792
+ category: "RLS",
793
+ title: `${table}: readable, row count unknown`,
794
+ evidence: { table }
795
+ });
796
+ } else if (count === 0) {
797
+ findings.push({
798
+ ruleId: "rls.table_empty_or_protected",
799
+ severity: "OK",
800
+ category: "RLS",
801
+ title: `${table}: 0 rows visible to this key`,
802
+ evidence: { rows: 0 }
803
+ });
804
+ } else if (publicKey) {
805
+ findings.push({
806
+ ruleId: "rls.public_read",
807
+ severity: "HIGH",
808
+ category: "RLS",
809
+ title: `${table}: ${count.toLocaleString()} row(s) readable by a public key`,
810
+ detail: "A public/limited key should not read protected data. Check RLS.",
811
+ evidence: { rows: count, table }
812
+ });
813
+ } else {
814
+ findings.push({
815
+ ruleId: "rls.rows_visible",
816
+ severity: "INFO",
817
+ category: "RLS",
818
+ title: `${table}: ${count.toLocaleString()} row(s) visible to this key`,
819
+ evidence: { rows: count }
820
+ });
821
+ }
822
+ }
823
+ return findings;
824
+ }
825
+ function checkColumns(columns, rlsFindings) {
826
+ const findings = [];
827
+ for (const f of rlsFindings) {
828
+ if (f.ruleId !== "rls.public_read" && f.ruleId !== "rls.count_unknown") continue;
829
+ const table = f.evidence?.table;
830
+ if (typeof table !== "string") continue;
831
+ const matches = [];
832
+ for (const column of columns[table] ?? []) {
833
+ const match = classifyColumn(column);
834
+ if (match) matches.push({ column, severity: match.severity });
835
+ }
836
+ if (matches.length === 0) continue;
837
+ matches.sort((a, b) => SEVERITY_RANK[b.severity] - SEVERITY_RANK[a.severity]);
838
+ findings.push({
839
+ ruleId: "columns.sensitive_readable",
840
+ severity: matches[0].severity,
841
+ category: "RLS",
842
+ title: `${table}: sensitive columns readable by a public key`,
843
+ detail: `Columns: ${matches.map((m) => `${m.column} (${m.severity})`).join(", ")}. Names come from the API spec; no row values were read.`,
844
+ evidence: { tables: [table], columns: matches.map((m) => m.column) }
845
+ });
846
+ }
847
+ return findings;
848
+ }
849
+ var MAX_BUCKETS_PROBED = 20;
850
+ var OBJECT_PROBE_LIMIT = 100;
851
+ function objectEntries(data) {
852
+ if (!Array.isArray(data)) return [];
853
+ return data.filter(
854
+ (e) => !!e && typeof e === "object"
855
+ );
856
+ }
857
+ async function checkStorage(ctx, role) {
858
+ const findings = [];
859
+ const publicKey = isPublicRole(role);
860
+ const res = await request(ctx, "/storage/v1/bucket");
861
+ if (res.status === null) {
862
+ findings.push({
863
+ ruleId: "storage.unreachable",
864
+ severity: "INFO",
865
+ category: "Storage",
866
+ title: "Storage API not reachable from this environment",
867
+ detail: res.error
868
+ });
869
+ return findings;
870
+ }
871
+ if (res.status === 401 || res.status === 403) {
872
+ findings.push({
873
+ ruleId: "storage.restricted",
874
+ severity: "OK",
875
+ category: "Storage",
876
+ title: "Bucket listing is properly restricted for this key"
877
+ });
878
+ return findings;
879
+ }
880
+ if (res.status !== 200 || !Array.isArray(res.data)) {
881
+ findings.push({
882
+ ruleId: "storage.unexpected",
883
+ severity: "INFO",
884
+ category: "Storage",
885
+ title: `Storage bucket listing returned HTTP ${res.status}`,
886
+ evidence: { status: res.status }
887
+ });
888
+ return findings;
889
+ }
890
+ const buckets = objectEntries(res.data);
891
+ if (buckets.length === 0) {
892
+ findings.push({
893
+ ruleId: "storage.no_buckets",
894
+ severity: "OK",
895
+ category: "Storage",
896
+ title: "No storage buckets visible to this key"
897
+ });
898
+ return findings;
899
+ }
900
+ if (publicKey) {
901
+ findings.push({
902
+ ruleId: "storage.bucket_list_public",
903
+ severity: "HIGH",
904
+ category: "Storage",
905
+ title: `${buckets.length} bucket(s) listable by a public key`,
906
+ detail: "A public/limited key should not enumerate all buckets. Review storage access policies.",
907
+ evidence: { buckets: buckets.length }
908
+ });
909
+ } else {
910
+ findings.push({
911
+ ruleId: "storage.bucket_list",
912
+ severity: "INFO",
913
+ category: "Storage",
914
+ title: `${buckets.length} bucket(s) listable with this key`,
915
+ evidence: { buckets: buckets.length }
916
+ });
917
+ }
918
+ let probed = 0;
919
+ for (const bucket of buckets) {
920
+ const isPublic = bucket.public === true;
921
+ const name = typeof bucket.name === "string" ? bucket.name : null;
922
+ if (isPublic) {
923
+ findings.push({
924
+ ruleId: "storage.public_bucket",
925
+ severity: "LOW",
926
+ category: "Storage",
927
+ title: `Public bucket: ${name ?? "(unnamed)"}`,
928
+ detail: "Objects in a public bucket are world-readable by URL. Confirm this is intended.",
929
+ evidence: { bucket: name ?? "(unnamed)" }
930
+ });
931
+ }
932
+ if (!publicKey || name === null || probed >= MAX_BUCKETS_PROBED) continue;
933
+ probed++;
934
+ const list = await request(
935
+ ctx,
936
+ `/storage/v1/object/list/${encodeURIComponent(name)}`,
937
+ {
938
+ method: "POST",
939
+ headers: { "Content-Type": "application/json" },
940
+ body: JSON.stringify({ prefix: "", limit: OBJECT_PROBE_LIMIT, offset: 0 })
941
+ }
942
+ );
943
+ if (list.status !== 200) continue;
944
+ const objects = objectEntries(list.data);
945
+ if (objects.length === 0) continue;
946
+ const atLeast = objects.length >= OBJECT_PROBE_LIMIT;
947
+ const shown = atLeast ? `${OBJECT_PROBE_LIMIT}+` : `${objects.length}`;
948
+ const evidence = {
949
+ bucket: name,
950
+ objects: objects.length,
951
+ ...atLeast ? { truncated: true } : {}
952
+ };
953
+ if (ctx.includeSamples) {
954
+ evidence.sample = objects.slice(0, 5).map((o) => maskValue(typeof o.name === "string" ? o.name : "?", "MEDIUM"));
955
+ }
956
+ findings.push({
957
+ ruleId: "storage.objects_readable",
958
+ severity: isPublic ? "MEDIUM" : "HIGH",
959
+ category: "Storage",
960
+ title: `${shown} object(s) listable in ${isPublic ? "public" : "non-public"} bucket ${name} by a public key`,
961
+ detail: isPublic ? "Expected for a public bucket; listed here for awareness." : "A public key can enumerate objects in a non-public bucket. Check storage policies.",
962
+ evidence
963
+ });
964
+ }
965
+ return findings;
966
+ }
967
+ function enabledProviders(data) {
968
+ const out = /* @__PURE__ */ new Set();
969
+ const external = data.external;
970
+ if (external && typeof external === "object") {
971
+ for (const [name, val] of Object.entries(external)) {
972
+ if (val === true) out.add(name);
973
+ else if (val && typeof val === "object" && val.enabled === true) {
974
+ out.add(name);
975
+ }
976
+ }
977
+ }
978
+ for (const [key, val] of Object.entries(data)) {
979
+ if (key.startsWith("external_") && val && typeof val === "object" && val.enabled === true) {
980
+ out.add(key.slice("external_".length));
981
+ }
982
+ }
983
+ return [...out].sort();
984
+ }
985
+ function userCount(data) {
986
+ if (Array.isArray(data)) return data.length;
987
+ if (data && typeof data === "object") {
988
+ const users = data.users;
989
+ if (Array.isArray(users)) return users.length;
990
+ }
991
+ return null;
992
+ }
993
+ function maskedEmails(data) {
994
+ const users = Array.isArray(data) ? data : data && typeof data === "object" && Array.isArray(data.users) ? data.users : [];
995
+ const out = [];
996
+ for (const u of users.slice(0, 5)) {
997
+ if (u && typeof u === "object") {
998
+ const email = u.email;
999
+ if (typeof email === "string" && email) out.push(maskValue(email, "HIGH"));
1000
+ }
1001
+ }
1002
+ return out;
1003
+ }
1004
+ var ADMIN_ENDPOINTS = [
1005
+ {
1006
+ path: "/auth/v1/admin/users",
1007
+ name: "user list",
1008
+ id: "users",
1009
+ extract: (data, includeSamples) => {
1010
+ const count = userCount(data);
1011
+ if (count === null) return null;
1012
+ const evidence = { users: count };
1013
+ if (includeSamples) {
1014
+ const sample = maskedEmails(data);
1015
+ if (sample.length > 0) evidence.sample = sample;
1016
+ }
1017
+ return evidence;
1018
+ }
1019
+ },
1020
+ {
1021
+ path: "/auth/v1/admin/audit",
1022
+ name: "audit log",
1023
+ id: "audit",
1024
+ extract: (data) => Array.isArray(data) ? { entries: data.length } : null
1025
+ }
1026
+ ];
1027
+ async function checkAuth(ctx, role) {
1028
+ const findings = [];
1029
+ const fullAccess = !isPublicRole(role);
1030
+ const settings = await request(ctx, "/auth/v1/settings");
1031
+ if (settings.status === 200 && settings.data && typeof settings.data === "object") {
1032
+ const data = settings.data;
1033
+ findings.push({
1034
+ ruleId: "auth.settings_public",
1035
+ severity: "INFO",
1036
+ category: "Auth",
1037
+ title: "Auth settings are publicly readable (expected)"
1038
+ });
1039
+ const providers = enabledProviders(data);
1040
+ if (providers.length > 0) {
1041
+ findings.push({
1042
+ ruleId: "auth.providers",
1043
+ severity: "INFO",
1044
+ category: "Auth",
1045
+ title: `Enabled auth providers: ${providers.join(", ")}`,
1046
+ evidence: { providers }
1047
+ });
1048
+ }
1049
+ const signupOpen = data.disable_signup !== true;
1050
+ if (signupOpen && (data.mailer_autoconfirm === true || data.autoconfirm === true)) {
1051
+ findings.push({
1052
+ ruleId: "auth.mailer_autoconfirm",
1053
+ severity: "MEDIUM",
1054
+ category: "Auth",
1055
+ title: "Email confirmation is disabled (mailer_autoconfirm)",
1056
+ detail: "New accounts are usable without verifying the e-mail address."
1057
+ });
1058
+ }
1059
+ if (signupOpen && data.phone_autoconfirm === true) {
1060
+ findings.push({
1061
+ ruleId: "auth.phone_autoconfirm",
1062
+ severity: "MEDIUM",
1063
+ category: "Auth",
1064
+ title: "Phone confirmation is disabled (phone_autoconfirm)",
1065
+ detail: "New accounts are usable without verifying the phone number."
1066
+ });
1067
+ }
1068
+ } else if (settings.status === null) {
1069
+ findings.push({
1070
+ ruleId: "auth.settings_unreachable",
1071
+ severity: "INFO",
1072
+ category: "Auth",
1073
+ title: "Auth settings not reachable from this environment",
1074
+ detail: settings.error
1075
+ });
1076
+ } else {
1077
+ findings.push({
1078
+ ruleId: "auth.settings_unexpected",
1079
+ severity: "INFO",
1080
+ category: "Auth",
1081
+ title: `Auth settings returned HTTP ${settings.status}`,
1082
+ evidence: { status: settings.status }
1083
+ });
1084
+ }
1085
+ for (const ep of ADMIN_ENDPOINTS) {
1086
+ const res = await request(ctx, ep.path);
1087
+ if (res.status === 401 || res.status === 403) {
1088
+ findings.push({
1089
+ ruleId: `auth.admin_${ep.id}_restricted`,
1090
+ severity: "OK",
1091
+ category: "Auth",
1092
+ title: `Admin ${ep.name} is properly restricted`
1093
+ });
1094
+ continue;
1095
+ }
1096
+ if (res.status === null) {
1097
+ findings.push({
1098
+ ruleId: `auth.admin_${ep.id}_unreachable`,
1099
+ severity: "INFO",
1100
+ category: "Auth",
1101
+ title: `Admin ${ep.name} not reachable from this environment`
1102
+ });
1103
+ continue;
1104
+ }
1105
+ if (res.status !== 200) {
1106
+ findings.push({
1107
+ ruleId: `auth.admin_${ep.id}_unexpected`,
1108
+ severity: "INFO",
1109
+ category: "Auth",
1110
+ title: `Admin ${ep.name} returned HTTP ${res.status}`,
1111
+ evidence: { status: res.status }
1112
+ });
1113
+ continue;
1114
+ }
1115
+ const evidence = ep.extract(res.data, ctx.includeSamples);
1116
+ if (evidence === null) {
1117
+ findings.push({
1118
+ ruleId: `auth.admin_${ep.id}_unexpected`,
1119
+ severity: "INFO",
1120
+ category: "Auth",
1121
+ title: `Admin ${ep.name} returned HTTP 200 with an unexpected body`
1122
+ });
1123
+ continue;
1124
+ }
1125
+ if (fullAccess) {
1126
+ findings.push({
1127
+ ruleId: `auth.admin_${ep.id}_full_key`,
1128
+ severity: "INFO",
1129
+ category: "Auth",
1130
+ title: `Admin ${ep.name} reachable (expected with a full-access key)`
1131
+ });
1132
+ } else {
1133
+ findings.push({
1134
+ ruleId: `auth.admin_${ep.id}_exposed`,
1135
+ severity: "CRITICAL",
1136
+ category: "Auth",
1137
+ title: `Admin ${ep.name} is reachable with a non-admin key`,
1138
+ detail: "This endpoint requires service_role. A public/limited key must never reach it.",
1139
+ evidence
1140
+ });
1141
+ }
1142
+ }
1143
+ return findings;
1144
+ }
1145
+ function isLocalHost(baseUrl) {
1146
+ try {
1147
+ const host = new URL(baseUrl).hostname;
1148
+ return host === "localhost" || host === "127.0.0.1" || host === "[::1]";
1149
+ } catch {
1150
+ return false;
1151
+ }
1152
+ }
1153
+ function unreachableDetail(baseUrl, error) {
1154
+ if (error?.startsWith(REDIRECT_REFUSED)) {
1155
+ return "The URL redirects, and the scan never follows a redirect so the key cannot be sent to another host. Use the final https:// project URL, such as https://<ref>.supabase.co.";
1156
+ }
1157
+ const base = "No request reached the host. The project may be paused or the URL may be wrong; the remaining checks were skipped.";
1158
+ if (baseUrl.startsWith("http://") && !isLocalHost(baseUrl)) {
1159
+ return `${base} An http:// URL usually redirects to https://, which the scan refuses: use https://.`;
1160
+ }
1161
+ return `${base} If the URL redirects (a custom domain), use the final https:// URL.`;
1162
+ }
1163
+ function highestSeverity(findings) {
1164
+ let worst = "OK";
1165
+ for (const f of findings) {
1166
+ if (SEVERITY_RANK[f.severity] > SEVERITY_RANK[worst]) worst = f.severity;
1167
+ }
1168
+ return worst;
1169
+ }
1170
+ async function scanProject(input) {
1171
+ const ctx = {
1172
+ baseUrl: normalizeUrl(input.url),
1173
+ token: input.token.trim(),
1174
+ fetch: input.fetch,
1175
+ timeoutMs: input.timeoutMs ?? 15e3,
1176
+ includeSamples: input.includeSamples ?? false
1177
+ };
1178
+ const keyInfo = classifyApiKey(ctx.token);
1179
+ const findings = [];
1180
+ findings.push(...analyzeKey(ctx.token));
1181
+ const enumResult = await enumerateTables(ctx, input.tables);
1182
+ const restUnreachable = enumResult.findings.find(
1183
+ (f) => f.ruleId === "tables.rest_unreachable"
1184
+ );
1185
+ if (restUnreachable) {
1186
+ findings.push(
1187
+ ...enumResult.findings.filter((f) => f.ruleId !== "tables.rest_unreachable")
1188
+ );
1189
+ findings.push({
1190
+ ruleId: "scan.target_unreachable",
1191
+ severity: "INFO",
1192
+ category: "Scan",
1193
+ title: "Target not reachable, so the scan could not run",
1194
+ detail: unreachableDetail(ctx.baseUrl, restUnreachable.detail),
1195
+ evidence: { baseUrl: ctx.baseUrl }
1196
+ });
1197
+ return {
1198
+ baseUrl: ctx.baseUrl,
1199
+ keyInfo,
1200
+ tables: [],
1201
+ findings,
1202
+ overall: highestSeverity(findings)
1203
+ };
1204
+ }
1205
+ findings.push(...enumResult.findings);
1206
+ const tables = enumResult.enumerated;
1207
+ if (enumResult.toCheck.length > 0) {
1208
+ const rls = await checkRls(ctx, enumResult.toCheck, keyInfo.role);
1209
+ findings.push(...rls);
1210
+ findings.push(...checkColumns(enumResult.columns ?? {}, rls));
1211
+ }
1212
+ findings.push(...await checkStorage(ctx, keyInfo.role));
1213
+ findings.push(...await checkAuth(ctx, keyInfo.role));
1214
+ return {
1215
+ baseUrl: ctx.baseUrl,
1216
+ keyInfo,
1217
+ tables,
1218
+ findings,
1219
+ overall: highestSeverity(findings)
1220
+ };
1221
+ }
1222
+ var SCAN_LIMITS = [
1223
+ "Writes: the scan only reads, so insert, update and delete are not tested.",
1224
+ "Signed-in users: access is checked only as this key's role.",
1225
+ "Database functions (RPC): who can call them is not checked.",
1226
+ "Edge Functions: whether each one requires a JWT is not checked.",
1227
+ "Storage: only visible buckets are listed; uploads and deletes are not tested."
1228
+ ];
1229
+ var TABLES_LISTED = "Tables: only the public schema is checked.";
1230
+ var TABLES_GUESSED = "Tables: only common names and names you add, in the public schema, are checked.";
1231
+ var COLUMNS_HIDDEN = "Column names: not checked, since the API spec is hidden.";
1232
+ function scanLimits(report) {
1233
+ const rules = new Set(report.findings.map((f) => f.ruleId));
1234
+ if (rules.has("scan.target_unreachable")) return [];
1235
+ return rules.has("tables.enumerable") ? [...SCAN_LIMITS, TABLES_LISTED] : [...SCAN_LIMITS, TABLES_GUESSED, COLUMNS_HIDDEN];
1236
+ }
1237
+
1238
+ // src/render.ts
1239
+ var ANSI = {
1240
+ reset: "\x1B[0m",
1241
+ bold: "\x1B[1m",
1242
+ dim: "\x1B[2m",
1243
+ red: "\x1B[91m",
1244
+ magenta: "\x1B[95m",
1245
+ yellow: "\x1B[93m",
1246
+ blue: "\x1B[94m",
1247
+ cyan: "\x1B[96m",
1248
+ green: "\x1B[92m"
1249
+ };
1250
+ var SEVERITY_COLOR = {
1251
+ CRITICAL: ANSI.red,
1252
+ HIGH: ANSI.magenta,
1253
+ MEDIUM: ANSI.yellow,
1254
+ LOW: ANSI.blue,
1255
+ INFO: ANSI.cyan,
1256
+ OK: ANSI.green
1257
+ };
1258
+ function paint(text, codes, enabled) {
1259
+ return enabled ? `${codes}${text}${ANSI.reset}` : text;
1260
+ }
1261
+ function sortFindings(findings) {
1262
+ return [...findings].sort(
1263
+ (a, b) => SEVERITY_RANK[b.severity] - SEVERITY_RANK[a.severity]
1264
+ );
1265
+ }
1266
+ function renderJson(report) {
1267
+ return JSON.stringify(report, null, 2);
1268
+ }
1269
+ function renderText(report, opts) {
1270
+ const { color } = opts;
1271
+ const lines = [];
1272
+ const b = (t) => paint(t, ANSI.bold, color);
1273
+ const dim = (t) => paint(t, ANSI.dim, color);
1274
+ lines.push("");
1275
+ lines.push(b("Supabase Security Scan"));
1276
+ lines.push(`${b("Target:")} ${report.baseUrl}`);
1277
+ lines.push(
1278
+ `${b("Key:")} ${report.keyInfo.keyType} / ${report.keyInfo.role}`
1279
+ );
1280
+ lines.push(`${b("Tables:")} ${report.tables.length}`);
1281
+ lines.push("");
1282
+ const counts = {
1283
+ CRITICAL: 0,
1284
+ HIGH: 0,
1285
+ MEDIUM: 0,
1286
+ LOW: 0,
1287
+ INFO: 0,
1288
+ OK: 0
1289
+ };
1290
+ for (const f of report.findings) counts[f.severity]++;
1291
+ const overallColor = SEVERITY_COLOR[report.overall];
1292
+ lines.push(
1293
+ `${b("Overall:")} ${paint(report.overall, overallColor + ANSI.bold, color)}`
1294
+ );
1295
+ lines.push(
1296
+ dim(
1297
+ `CRITICAL ${counts.CRITICAL} HIGH ${counts.HIGH} MEDIUM ${counts.MEDIUM} LOW ${counts.LOW} INFO ${counts.INFO} OK ${counts.OK}`
1298
+ )
1299
+ );
1300
+ lines.push("");
1301
+ for (const f of sortFindings(report.findings)) {
1302
+ const tag = paint(
1303
+ `[${f.severity}]`.padEnd(10),
1304
+ SEVERITY_COLOR[f.severity] + ANSI.bold,
1305
+ color
1306
+ );
1307
+ lines.push(`${tag} ${f.title}`);
1308
+ if (f.detail) lines.push(dim(` ${f.detail}`));
1309
+ const tables = f.evidence?.tables;
1310
+ if (Array.isArray(tables) && tables.length > 0) {
1311
+ lines.push(dim(` ${tables.join(", ")}`));
1312
+ }
1313
+ }
1314
+ lines.push("");
1315
+ const limits = scanLimits(report);
1316
+ if (limits.length > 0) {
1317
+ lines.push(b("Not covered by this scan:"));
1318
+ for (const limit of limits) lines.push(dim(` - ${limit}`));
1319
+ lines.push("");
1320
+ }
1321
+ return lines.join("\n");
1322
+ }
1323
+
1324
+ // src/args.ts
1325
+ function parseArgs(argv, colorDefault) {
1326
+ const args = {
1327
+ json: false,
1328
+ color: colorDefault,
1329
+ timeoutMs: 15e3,
1330
+ tables: [],
1331
+ help: false,
1332
+ version: false,
1333
+ strayKey: false
1334
+ };
1335
+ const positionals = [];
1336
+ for (let i = 0; i < argv.length; i++) {
1337
+ const arg = argv[i];
1338
+ const eq = arg.startsWith("--") ? arg.indexOf("=") : -1;
1339
+ const a = eq > 0 ? arg.slice(0, eq) : arg;
1340
+ const inline = eq > 0 ? arg.slice(eq + 1) : void 0;
1341
+ if (inline !== void 0 && a !== "--timeout" && a !== "--tables") {
1342
+ args.badOption ??= arg;
1343
+ } else if (a === "--json") args.json = true;
1344
+ else if (a === "--no-color") args.color = false;
1345
+ else if (a === "--help" || a === "-h") args.help = true;
1346
+ else if (a === "--version" || a === "-v") args.version = true;
1347
+ else if (a === "--timeout" || a === "--tables") {
1348
+ const value = inline ?? argv[++i];
1349
+ if (value === void 0 || value === "" || inline === void 0 && value.startsWith("-")) {
1350
+ args.badOption ??= a;
1351
+ if (inline === void 0 && value !== void 0) i--;
1352
+ continue;
1353
+ }
1354
+ if (a === "--timeout") {
1355
+ const v = Number(value);
1356
+ if (Number.isFinite(v) && v > 0) args.timeoutMs = v;
1357
+ else args.badOption ??= a;
1358
+ } else {
1359
+ args.tables.push(...value.split(",").map((t) => t.trim()).filter(Boolean));
1360
+ }
1361
+ } else if (a.startsWith("-")) args.badOption ??= a;
1362
+ else positionals.push(a);
1363
+ }
1364
+ args.url = positionals[0];
1365
+ if (positionals.length > 1) args.strayKey = true;
1366
+ return args;
1367
+ }
1368
+
1369
+ // src/stdin.ts
1370
+ var STDIN_WAIT_MS = 5e3;
1371
+ function readKeyFromStream(stream, waitMs = STDIN_WAIT_MS) {
1372
+ return new Promise((resolve) => {
1373
+ const chunks = [];
1374
+ const text = () => Buffer.concat(chunks).toString("utf8");
1375
+ const finish = () => {
1376
+ clearTimeout(timer);
1377
+ stream.off("data", onData);
1378
+ stream.off("end", finish);
1379
+ stream.off("error", finish);
1380
+ stream.pause();
1381
+ const value = text().split(/\r?\n/, 1)[0] ?? "";
1382
+ resolve(value === "" ? null : value);
1383
+ };
1384
+ const onData = (chunk) => {
1385
+ chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
1386
+ if (text().includes("\n")) finish();
1387
+ };
1388
+ const timer = setTimeout(finish, waitMs);
1389
+ stream.on("data", onData);
1390
+ stream.once("end", finish);
1391
+ stream.once("error", finish);
1392
+ });
1393
+ }
1394
+
1395
+ // src/cli.ts
1396
+ var KEY_ENV = "SUPABASE_SCAN_KEY";
1397
+ var { version } = createRequire(import.meta.url)("../package.json");
1398
+ var HELP = `supabase-scan: Supabase security scanner
1399
+
1400
+ Usage:
1401
+ SUPABASE_SCAN_KEY=<key> supabase-scan <url> [options]
1402
+ echo "<key>" | supabase-scan <url> [options]
1403
+
1404
+ Options:
1405
+ --json Output the report as JSON.
1406
+ --no-color Disable ANSI colors.
1407
+ --tables <a,b> Also check these tables (repeatable). Public keys cannot
1408
+ list tables on hosted Supabase, so the scan only finds
1409
+ common names and the ones error hints reveal.
1410
+ --timeout <ms> Per-request timeout (default 15000).
1411
+ -v, --version Show the version.
1412
+ -h, --help Show this help.
1413
+
1414
+ The API key is taken from the ${KEY_ENV} env var or from stdin, never from the
1415
+ command line. Scan only projects you own or are authorized to test.
1416
+
1417
+ Exit codes: 2 if any CRITICAL/HIGH finding, 1 if MEDIUM, 0 otherwise.`;
1418
+ async function resolveToken() {
1419
+ const fromEnv = process.env[KEY_ENV];
1420
+ if (fromEnv && fromEnv.trim()) return fromEnv.trim();
1421
+ if (!process.stdin.isTTY) {
1422
+ const piped = (await readKeyFromStream(process.stdin))?.trim();
1423
+ if (piped) return piped;
1424
+ }
1425
+ return null;
1426
+ }
1427
+ function exitCodeFor(report) {
1428
+ if (report.overall === "CRITICAL" || report.overall === "HIGH") return 2;
1429
+ if (report.overall === "MEDIUM") return 1;
1430
+ return 0;
1431
+ }
1432
+ async function main() {
1433
+ const args = parseArgs(
1434
+ process.argv.slice(2),
1435
+ Boolean(process.stdout.isTTY) && !process.env.NO_COLOR
1436
+ );
1437
+ if (args.version) {
1438
+ process.stdout.write(`${version}
1439
+ `);
1440
+ process.exit(0);
1441
+ }
1442
+ if (args.help || !args.url) {
1443
+ process.stdout.write(HELP + "\n");
1444
+ process.exit(args.url ? 0 : 1);
1445
+ }
1446
+ if (args.badOption) {
1447
+ process.stderr.write(`Unknown option or missing value: ${args.badOption}. See --help.
1448
+ `);
1449
+ process.exit(1);
1450
+ }
1451
+ if (args.strayKey) {
1452
+ process.stderr.write(
1453
+ `Refusing to read a key from the command line. Pass it via ${KEY_ENV} or stdin instead.
1454
+ `
1455
+ );
1456
+ process.exit(1);
1457
+ }
1458
+ const token = await resolveToken();
1459
+ if (!token) {
1460
+ process.stderr.write(
1461
+ `No API key. Set ${KEY_ENV} or pipe the key on stdin (read for up to ${STDIN_WAIT_MS / 1e3}s). See --help.
1462
+ `
1463
+ );
1464
+ process.exit(1);
1465
+ }
1466
+ const report = await scanProject({
1467
+ url: args.url,
1468
+ token,
1469
+ fetch: globalThis.fetch,
1470
+ timeoutMs: args.timeoutMs,
1471
+ includeSamples: true,
1472
+ tables: args.tables
1473
+ });
1474
+ process.stdout.write(
1475
+ (args.json ? renderJson(report) : renderText(report, { color: args.color })) + "\n"
1476
+ );
1477
+ process.exit(exitCodeFor(report));
1478
+ }
1479
+ main().catch((err) => {
1480
+ process.stderr.write(`Scan failed: ${err instanceof Error ? err.message : String(err)}
1481
+ `);
1482
+ process.exit(1);
1483
+ });