rowprobe 0.0.0-stage → 0.2.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 (3) hide show
  1. package/README.md +58 -2
  2. package/dist/rowprobe.mjs +1382 -0
  3. package/package.json +33 -4
@@ -0,0 +1,1382 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { appendFileSync } from "node:fs";
5
+
6
+ // ../web/src/lib/scan/rest.ts
7
+ var Rest = class {
8
+ constructor(url, key, fetchFn = (...a) => fetch(...a)) {
9
+ this.key = key;
10
+ this.fetchFn = fetchFn;
11
+ this.base = url.replace(/\/+$/, "") + "/rest/v1/";
12
+ }
13
+ headers(who, extra = {}) {
14
+ const h = { apikey: this.key, ...extra };
15
+ const bearer = who.token ?? (this.key.startsWith("eyJ") ? this.key : void 0);
16
+ if (bearer) h.Authorization = `Bearer ${bearer}`;
17
+ return h;
18
+ }
19
+ qs(filter) {
20
+ return Object.entries(filter).map(([k, v]) => `${encodeURIComponent(k)}=eq.${encodeURIComponent(String(v))}`).join("&");
21
+ }
22
+ async send(method, path, who, extra, body) {
23
+ let r;
24
+ try {
25
+ r = await this.fetchFn(this.base + path, {
26
+ method,
27
+ headers: this.headers(who, body !== void 0 ? { "Content-Type": "application/json", ...extra } : extra),
28
+ body: body !== void 0 ? JSON.stringify(body) : void 0
29
+ });
30
+ } catch (e) {
31
+ return { status: 0, rows: [], message: e instanceof Error ? e.message : String(e) };
32
+ }
33
+ const text = await r.text();
34
+ let json = void 0;
35
+ try {
36
+ json = text ? JSON.parse(text) : void 0;
37
+ } catch {
38
+ }
39
+ const cr = r.headers.get("content-range");
40
+ const count = cr && /\/(\d+)$/.test(cr) ? Number(cr.split("/")[1]) : void 0;
41
+ if (!r.ok) {
42
+ const j = json ?? {};
43
+ return { status: r.status, rows: [], code: j.code, message: j.message ?? text.slice(0, 200), hint: j.hint ?? void 0, count };
44
+ }
45
+ return { status: r.status, rows: Array.isArray(json) ? json : [], count };
46
+ }
47
+ select(table, who, filter = {}, limit = 500) {
48
+ const q = this.qs(filter);
49
+ return this.send("GET", `${encodeURIComponent(table)}?select=*${q ? "&" + q : ""}&limit=${limit}`, who, {});
50
+ }
51
+ insert(table, who, row, returnRows) {
52
+ return this.send("POST", encodeURIComponent(table), who, { Prefer: returnRows ? "return=representation" : "return=minimal" }, row);
53
+ }
54
+ update(table, who, filter, patch, returnRows) {
55
+ return this.send(
56
+ "PATCH",
57
+ `${encodeURIComponent(table)}?${this.qs(filter)}`,
58
+ who,
59
+ { Prefer: (returnRows ? "return=representation" : "return=minimal") + ",count=exact" },
60
+ patch
61
+ );
62
+ }
63
+ remove(table, who, filter) {
64
+ return this.send("DELETE", `${encodeURIComponent(table)}?${this.qs(filter)}`, who, { Prefer: "return=representation,count=exact" });
65
+ }
66
+ async openapi(who) {
67
+ try {
68
+ const r = await this.fetchFn(this.base, { headers: this.headers(who, { Accept: "application/openapi+json" }) });
69
+ if (!r.ok) return { ok: false, status: r.status };
70
+ return { ok: true, status: r.status, spec: await r.json() };
71
+ } catch {
72
+ return { ok: false, status: 0 };
73
+ }
74
+ }
75
+ };
76
+ function isDenied(r) {
77
+ return r.status === 401 || r.status === 403 || r.code === "42501" || r.code === "PGRST301";
78
+ }
79
+
80
+ // ../web/src/lib/scan/discover.ts
81
+ function parseSpec(spec) {
82
+ const s = spec;
83
+ const out = [];
84
+ for (const [name, def] of Object.entries(s.definitions ?? {})) {
85
+ const path = s.paths?.["/" + name];
86
+ if (!path) continue;
87
+ const columns = Object.entries(def.properties ?? {}).map(([col, p]) => ({
88
+ name: col,
89
+ format: p.format ?? p.type ?? "",
90
+ pk: (p.description ?? "").includes("<pk/>"),
91
+ hasDefault: p.default !== void 0
92
+ }));
93
+ out.push({
94
+ name,
95
+ columns,
96
+ pk: columns.filter((c2) => c2.pk).map((c2) => c2.name),
97
+ writable: ["post", "patch", "delete"].some((m) => m in path)
98
+ });
99
+ }
100
+ return out.sort((a, b) => a.name.localeCompare(b.name));
101
+ }
102
+ async function discoverTables(rest, users) {
103
+ for (const who of [{ label: "visitor" }, ...users]) {
104
+ const r = await rest.openapi(who);
105
+ if (r.ok && r.spec) {
106
+ const t = parseSpec(r.spec);
107
+ if (t.length) return t;
108
+ }
109
+ }
110
+ return null;
111
+ }
112
+ var COMMON_TABLES = [
113
+ "users",
114
+ "profiles",
115
+ "accounts",
116
+ "organizations",
117
+ "organisations",
118
+ "orgs",
119
+ "organization_members",
120
+ "teams",
121
+ "team_members",
122
+ "members",
123
+ "memberships",
124
+ "workspaces",
125
+ "workspace_members",
126
+ "companies",
127
+ "company_members",
128
+ "tenants",
129
+ "customers",
130
+ "clients",
131
+ "contacts",
132
+ "leads",
133
+ "deals",
134
+ "projects",
135
+ "project_members",
136
+ "tasks",
137
+ "todos",
138
+ "notes",
139
+ "documents",
140
+ "files",
141
+ "attachments",
142
+ "uploads",
143
+ "images",
144
+ "posts",
145
+ "comments",
146
+ "likes",
147
+ "messages",
148
+ "conversations",
149
+ "chats",
150
+ "chat_messages",
151
+ "threads",
152
+ "notifications",
153
+ "invoices",
154
+ "invoice_items",
155
+ "payments",
156
+ "subscriptions",
157
+ "plans",
158
+ "prices",
159
+ "products",
160
+ "orders",
161
+ "order_items",
162
+ "carts",
163
+ "cart_items",
164
+ "transactions",
165
+ "bookings",
166
+ "appointments",
167
+ "events",
168
+ "tickets",
169
+ "reviews",
170
+ "settings",
171
+ "user_settings",
172
+ "preferences",
173
+ "api_keys",
174
+ "api_tokens",
175
+ "tokens",
176
+ "invitations",
177
+ "invites",
178
+ "roles",
179
+ "user_roles",
180
+ "permissions",
181
+ "audit_log",
182
+ "audit_logs",
183
+ "logs",
184
+ "activity",
185
+ "activities",
186
+ "feedback",
187
+ "categories",
188
+ "tags",
189
+ "items",
190
+ "inventory",
191
+ "courses",
192
+ "lessons",
193
+ "enrollments",
194
+ "students",
195
+ "patients",
196
+ "records",
197
+ "reports",
198
+ "forms",
199
+ "submissions",
200
+ "responses",
201
+ "surveys",
202
+ "jobs",
203
+ "applications",
204
+ "candidates",
205
+ "employees",
206
+ "departments",
207
+ "locations",
208
+ "addresses",
209
+ "vendors",
210
+ "campaigns",
211
+ "emails",
212
+ "webhooks",
213
+ "integrations",
214
+ "credits",
215
+ "usage",
216
+ "agents",
217
+ "prompts",
218
+ "generations",
219
+ "embeddings",
220
+ "credentials",
221
+ "secrets",
222
+ "favorites",
223
+ "bookmarks"
224
+ ];
225
+ async function probeTables(rest, who, extra = [], maxProbes = 220) {
226
+ const queue = [.../* @__PURE__ */ new Set([...extra, ...COMMON_TABLES])];
227
+ const seen = new Set(queue);
228
+ const found = /* @__PURE__ */ new Set();
229
+ let probes = 0;
230
+ const worker = async () => {
231
+ while (queue.length && probes < maxProbes) {
232
+ const name = queue.shift();
233
+ probes++;
234
+ const r = await rest.select(name, who, {}, 1);
235
+ if (r.status === 200 || r.code === "42501") found.add(name);
236
+ const hint = /public\.([A-Za-z0-9_$]+)'/.exec(r.hint ?? "");
237
+ if (r.code === "PGRST205" && hint && !seen.has(hint[1])) {
238
+ seen.add(hint[1]);
239
+ queue.unshift(hint[1]);
240
+ }
241
+ }
242
+ };
243
+ await Promise.all(Array.from({ length: 6 }, worker));
244
+ return [...found].sort();
245
+ }
246
+ function manualTables(names) {
247
+ return names.map((n) => n.trim()).filter(Boolean).map((name) => ({ name, columns: [], pk: [], writable: true }));
248
+ }
249
+
250
+ // ../web/src/lib/scan/deep.ts
251
+ async function call(fetchFn, url, init) {
252
+ try {
253
+ const r = await fetchFn(url, init);
254
+ const text = await r.text();
255
+ let json;
256
+ try {
257
+ json = text ? JSON.parse(text) : void 0;
258
+ } catch {
259
+ }
260
+ return { status: r.status, ok: r.ok, text, json };
261
+ } catch (e) {
262
+ return { status: 0, ok: false, text: e instanceof Error ? e.message : String(e) };
263
+ }
264
+ }
265
+ var enc = (p) => p.split("/").map(encodeURIComponent).join("/");
266
+ var StorageApi = class {
267
+ constructor(url, rest, fetchFn = (...a) => fetch(...a)) {
268
+ this.rest = rest;
269
+ this.fetchFn = fetchFn;
270
+ this.base = url.replace(/\/+$/, "") + "/storage/v1";
271
+ }
272
+ /** Buckets this user may see (often none: listing buckets needs its own policy). */
273
+ async listBuckets(who) {
274
+ const r = await call(this.fetchFn, `${this.base}/bucket`, { headers: this.rest.headers(who) });
275
+ return r.ok && Array.isArray(r.json) ? r.json.map((b) => ({ name: b.id, public: b.public })) : [];
276
+ }
277
+ /**
278
+ * Whether a bucket exists, by trying to upload as a signed-out visitor: storage answers
279
+ * "Bucket not found" for a missing bucket and a security refusal for an existing one
280
+ * (the public file address is not reliable for this). "open" means the upload worked.
281
+ */
282
+ async probe(bucket, visitor, path) {
283
+ const r = await this.upload(bucket, path, visitor, "RowProbe bucket check");
284
+ if (r.ok) return "open";
285
+ return /bucket not found/i.test(r.text) || r.status === 0 ? "missing" : "exists";
286
+ }
287
+ async list(bucket, prefix, who) {
288
+ const r = await call(this.fetchFn, `${this.base}/object/list/${encodeURIComponent(bucket)}`, {
289
+ method: "POST",
290
+ headers: this.rest.headers(who, { "Content-Type": "application/json" }),
291
+ body: JSON.stringify({ prefix, limit: 100, offset: 0, sortBy: { column: "name", order: "asc" } })
292
+ });
293
+ return r.ok && Array.isArray(r.json) ? r.json : [];
294
+ }
295
+ async upload(bucket, path, who, body, overwrite = false) {
296
+ return call(this.fetchFn, `${this.base}/object/${encodeURIComponent(bucket)}/${enc(path)}`, {
297
+ method: overwrite ? "PUT" : "POST",
298
+ headers: this.rest.headers(who, { "Content-Type": "image/png", "cache-control": "no-cache" }),
299
+ body
300
+ });
301
+ }
302
+ async download(bucket, path, who) {
303
+ return call(this.fetchFn, `${this.base}/object/authenticated/${encodeURIComponent(bucket)}/${enc(path)}`, { headers: this.rest.headers(who), cache: "no-store" });
304
+ }
305
+ async publicDownload(bucket, path) {
306
+ return call(this.fetchFn, `${this.base}/object/public/${encodeURIComponent(bucket)}/${enc(path)}`, { cache: "no-store" });
307
+ }
308
+ /** Deletes; returns how many files were really removed (storage answers [] when not allowed). */
309
+ async remove(bucket, paths, who) {
310
+ const r = await call(this.fetchFn, `${this.base}/object/${encodeURIComponent(bucket)}`, {
311
+ method: "DELETE",
312
+ headers: this.rest.headers(who, { "Content-Type": "application/json" }),
313
+ body: JSON.stringify({ prefixes: paths })
314
+ });
315
+ return r.ok && Array.isArray(r.json) ? r.json.length : 0;
316
+ }
317
+ };
318
+ var COMMON_BUCKETS = [
319
+ "avatars",
320
+ "avatar",
321
+ "profile-pictures",
322
+ "profile_pictures",
323
+ "profiles",
324
+ "images",
325
+ "photos",
326
+ "uploads",
327
+ "files",
328
+ "documents",
329
+ "docs",
330
+ "attachments",
331
+ "invoices",
332
+ "invoice-files",
333
+ "receipts",
334
+ "media",
335
+ "public",
336
+ "private",
337
+ "assets",
338
+ "user-files",
339
+ "user_files",
340
+ "user-uploads",
341
+ "videos",
342
+ "audio",
343
+ "recordings",
344
+ "exports",
345
+ "reports",
346
+ "contracts",
347
+ "resumes",
348
+ "logos"
349
+ ];
350
+ var PUBLIC_LOOKING = /avatar|public|image|photo|asset|logo|media|static|banner|cover|thumb|icon/i;
351
+ var finding = (area, table, kind, severity, extra = {}) => ({ area, table, kind, severity, pk: [], columns: [], ...extra });
352
+ async function scanStorage(c2) {
353
+ const { storage } = c2;
354
+ await c2.step("storage", "Looking for storage buckets");
355
+ const known = /* @__PURE__ */ new Map();
356
+ for (const who of [c2.visitor, c2.alice, c2.bob]) for (const b of await storage.listBuckets(who)) known.set(b.name, b.public);
357
+ const probePath = `rowprobe-probe/${c2.marker}.png`;
358
+ const probed = /* @__PURE__ */ new Map();
359
+ const candidates = [.../* @__PURE__ */ new Set([...c2.hints, ...c2.writeTests ? COMMON_BUCKETS : []])].filter((n) => !known.has(n) && /^[\w.-]{1,63}$/.test(n));
360
+ const res = c2.writeTests ? await pool(candidates, 6, (n) => storage.probe(n, c2.visitor, probePath)) : candidates.map(() => "exists");
361
+ candidates.forEach((n, i) => {
362
+ probed.set(n, res[i]);
363
+ if (res[i] !== "missing") known.set(n, void 0);
364
+ });
365
+ const buckets = [...known.keys()].slice(0, 12);
366
+ if (!buckets.length) c2.outcome("storage", c2.writeTests ? "No storage buckets found" : "No storage buckets listed (turn on write tests to look for more)", "info");
367
+ const findings = [];
368
+ const checks = [];
369
+ for (const bucket of buckets) {
370
+ const subject = `storage: ${bucket}`;
371
+ const f = [];
372
+ const notes = [];
373
+ const add = (kind, severity, extra = {}) => f.push(finding("storage", bucket, kind, severity, extra));
374
+ const has = (kind) => f.some((x) => x.kind === kind);
375
+ if (c2.writeTests) {
376
+ await c2.step(subject, "Can signed-out visitors upload files?");
377
+ const p = probed.get(bucket) ?? await storage.probe(bucket, c2.visitor, probePath);
378
+ if (p === "open") {
379
+ add("storage_public_upload", "high");
380
+ c2.outcome(subject, "Visitors can upload files", "leak");
381
+ if (!await storage.remove(bucket, [probePath], c2.visitor))
382
+ c2.leftovers.push({ table: subject, description: `Test file uploaded as a signed-out visitor: ${probePath}`, sql: `-- Supabase dashboard \u2192 Storage \u2192 ${bucket} \u2192 delete "${probePath}"` });
383
+ } else c2.outcome(subject, "Visitors can't upload", "blocked");
384
+ }
385
+ await c2.step(subject, "Can signed-out visitors list the files?");
386
+ const visList = await storage.list(bucket, "", c2.visitor);
387
+ if (visList.length) {
388
+ add("storage_public_list", PUBLIC_LOOKING.test(bucket) ? "medium" : "high", { count: visList.length });
389
+ c2.outcome(subject, `Visitors can list ${visList.length} item${visList.length > 1 ? "s" : ""}`, "leak");
390
+ } else c2.outcome(subject, "Visitors can't list files", "blocked");
391
+ await c2.step(subject, "Can Alice see Bob's existing files?");
392
+ const aliceRoot = await storage.list(bucket, "", c2.alice);
393
+ if (aliceRoot.some((x) => x.name === c2.bobId)) {
394
+ const inside = (await storage.list(bucket, `${c2.bobId}/`, c2.alice)).filter((x) => x.id);
395
+ if (inside.length) {
396
+ add("storage_list_other", "high", { count: inside.length, detail: `${c2.bobId}/` });
397
+ c2.outcome(subject, `Alice can list ${inside.length} of Bob's files`, "leak");
398
+ const file = `${c2.bobId}/${inside[0].name}`;
399
+ const isPublic = known.get(bucket) === true || (await storage.publicDownload(bucket, file)).ok;
400
+ const d = isPublic ? void 0 : await storage.download(bucket, file, c2.alice);
401
+ if (d?.ok) {
402
+ add("storage_read_other", "critical", { detail: "an existing file in Bob's folder" });
403
+ c2.outcome(subject, "Alice can download Bob's files", "leak");
404
+ }
405
+ } else c2.outcome(subject, "Bob's folder looks empty to Alice", "blocked");
406
+ } else c2.outcome(subject, "Alice sees no folder of Bob's", "blocked");
407
+ if (c2.writeTests) {
408
+ const name = `${c2.marker}.png`;
409
+ const bobBody = `RowProbe test file (Bob) ${c2.marker}`;
410
+ await c2.step(subject, "Bob uploads a test file");
411
+ let path;
412
+ for (const p of [`${c2.bobId}/${name}`, name, `public/${c2.bobId}/${name}`, `users/${c2.bobId}/${name}`, `private/${c2.bobId}/${name}`]) {
413
+ const up = await storage.upload(bucket, p, c2.bob, bobBody);
414
+ if (up.ok) {
415
+ path = p;
416
+ break;
417
+ }
418
+ }
419
+ if (!path) {
420
+ notes.push("Bob couldn't upload a test file here (uploads may be limited to certain folders or file types), so cross-user file tests were skipped.");
421
+ c2.outcome(subject, "Couldn't upload a test file", "info");
422
+ } else {
423
+ const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/") + 1) : "";
424
+ let removed = false;
425
+ await c2.step(subject, "Can a signed-out visitor download it?");
426
+ const pub = await storage.publicDownload(bucket, path);
427
+ const isPublic = pub.ok && pub.text.includes(c2.marker);
428
+ const vis = isPublic ? void 0 : await storage.download(bucket, path, c2.visitor);
429
+ if (!has("storage_read_other") && !isPublic) {
430
+ await c2.step(subject, "Alice tries to download Bob's file");
431
+ const d = await storage.download(bucket, path, c2.alice);
432
+ if (d.ok && d.text.includes(c2.marker)) {
433
+ add("storage_read_other", "critical");
434
+ c2.outcome(subject, "Alice can download Bob's files", "leak");
435
+ } else c2.outcome(subject, "Download blocked", "blocked");
436
+ }
437
+ if (!has("storage_list_other") && dir) {
438
+ const seen = await storage.list(bucket, dir, c2.alice);
439
+ if (seen.some((x) => x.name === name)) {
440
+ add("storage_list_other", "high", { detail: dir });
441
+ c2.outcome(subject, "Alice can list Bob's files", "leak");
442
+ }
443
+ }
444
+ if (isPublic) {
445
+ const sev = PUBLIC_LOOKING.test(bucket) ? "low" : "high";
446
+ add("storage_public_bucket", sev);
447
+ c2.outcome(subject, "Public bucket: anyone with a file's link can download it", sev === "low" ? "info" : "leak");
448
+ } else if (vis?.ok && vis.text.includes(c2.marker)) {
449
+ add("storage_visitor_read", "critical");
450
+ c2.outcome(subject, "Visitors can download private files", "leak");
451
+ } else c2.outcome(subject, "Visitors can't download it", "blocked");
452
+ await c2.step(subject, "Alice tries to replace Bob's file");
453
+ const ow = await storage.upload(bucket, path, c2.alice, `RowProbe test file (Alice) ${c2.marker}`, true);
454
+ if (ow.ok) {
455
+ const now = await storage.download(bucket, path, c2.bob);
456
+ if (now.ok && now.text.includes("(Alice)")) {
457
+ add("storage_write_other", "critical", { detail: "replace" });
458
+ c2.outcome(subject, "Alice can replace Bob's files", "leak");
459
+ } else c2.outcome(subject, "Replace blocked", "blocked");
460
+ } else c2.outcome(subject, "Replace blocked", "blocked");
461
+ if (dir) {
462
+ await c2.step(subject, "Alice tries to upload into Bob's folder");
463
+ const planted = `${dir}${c2.marker}-alice.png`;
464
+ const pl = await storage.upload(bucket, planted, c2.alice, `RowProbe test file (Alice) ${c2.marker}`);
465
+ if (pl.ok) {
466
+ if (!has("storage_write_other")) add("storage_write_other", "high", { detail: "upload" });
467
+ c2.outcome(subject, "Alice can upload files into Bob's folder", "leak");
468
+ if (!await storage.remove(bucket, [planted], c2.alice) && !await storage.remove(bucket, [planted], c2.bob))
469
+ c2.leftovers.push({ table: subject, description: `Test file uploaded by Alice into Bob's folder: ${planted}`, sql: `-- Supabase dashboard \u2192 Storage \u2192 ${bucket} \u2192 delete "${planted}"` });
470
+ } else c2.outcome(subject, "Uploading into Bob's folder blocked", "blocked");
471
+ }
472
+ await c2.step(subject, "Alice tries to delete Bob's file");
473
+ if (await storage.remove(bucket, [path], c2.alice)) {
474
+ removed = true;
475
+ add("storage_delete_other", "critical");
476
+ c2.outcome(subject, "Alice can delete Bob's files", "leak");
477
+ } else c2.outcome(subject, "Delete blocked", "blocked");
478
+ if (!removed && !await storage.remove(bucket, [path], c2.bob))
479
+ c2.leftovers.push({ table: subject, description: `Test file uploaded by Bob: ${path}`, sql: `-- Supabase dashboard \u2192 Storage \u2192 ${bucket} \u2192 delete "${path}"` });
480
+ }
481
+ } else notes.push("Turn on write tests to check whether Alice can open, replace or delete Bob's files.");
482
+ findings.push(...f);
483
+ checks.push({ area: "storage", name: bucket, status: statusOf(f), notes });
484
+ }
485
+ return { findings, checks };
486
+ }
487
+ function parseFunctions(spec) {
488
+ const paths = spec?.paths ?? {};
489
+ return Object.entries(paths).filter(([p]) => p.startsWith("/rpc/")).map(([p, def]) => {
490
+ const query = (def.get?.parameters ?? []).filter((x) => x.in === "query").map((x) => ({ name: x.name, format: x.format ?? x.type ?? "" }));
491
+ const body = Object.entries((def.post?.parameters ?? []).find((x) => x.in === "body")?.schema?.properties ?? {}).map(([name, x]) => ({ name, format: x.format ?? x.type ?? "" }));
492
+ return { name: p.slice(5), params: query.length ? query : body };
493
+ });
494
+ }
495
+ var USERISH = /(^|_)(user|uid|owner|profile|member|author|customer|client|creator|recipient|sender|account_user)(_?id)?$/i;
496
+ var TENANTISH = /(company|org|organization|organisation|team|workspace|tenant|account|project)_?id$/i;
497
+ async function scanFunctions(c2) {
498
+ await c2.step("functions", "Looking for database functions");
499
+ const specs = /* @__PURE__ */ new Map();
500
+ for (const [who, role] of [[c2.visitor, "visitor"], [c2.alice, "user"]]) {
501
+ const o = await c2.rest.openapi(who);
502
+ if (!o.ok) continue;
503
+ for (const f of parseFunctions(o.spec)) {
504
+ const s = specs.get(f.name) ?? { name: f.name, params: f.params, visitor: false, user: false };
505
+ s[role] = true;
506
+ specs.set(f.name, s);
507
+ }
508
+ }
509
+ for (const h of c2.hints) {
510
+ if (!specs.has(h.name)) specs.set(h.name, { name: h.name, params: (h.params ?? []).map((p) => ({ name: p, format: "" })), visitor: true, user: true });
511
+ }
512
+ const fns = [...specs.values()].filter((f) => /^[A-Za-z_]\w{0,62}$/.test(f.name)).slice(0, 40);
513
+ if (!fns.length) c2.outcome("functions", "No database functions found", "info");
514
+ const findings = [];
515
+ const checks = [];
516
+ for (const fn of fns) {
517
+ const subject = `${fn.name}()`;
518
+ const f = [];
519
+ const notes = [];
520
+ const add = (kind, severity, extra = {}) => f.push(finding("function", fn.name, kind, severity, { columns: fn.params.map((p) => p.name), ...extra }));
521
+ const bobParams = fn.params.filter((p) => USERISH.test(p.name) || TENANTISH.test(p.name)).map((p) => p.name);
522
+ await c2.step(subject, "Can signed-out visitors run it?");
523
+ const v = await runFn(c2, fn, c2.visitor);
524
+ if (v.kind === "data" && proves(v.text, c2)) {
525
+ add("rpc_public_data", "critical", { detail: bobParams.join(", ") });
526
+ c2.outcome(subject, "Visitors can read Bob's data through it", "leak");
527
+ } else if (v.kind === "data") {
528
+ add("rpc_public_data", "medium");
529
+ c2.outcome(subject, "Visitors can run it and get data back", "info");
530
+ } else if (v.kind === "writes") {
531
+ add("rpc_public_write", "high", { detail: bobParams.join(", ") });
532
+ c2.outcome(subject, "Visitors can run it, and it changes data (stopped before it did)", "leak");
533
+ } else if (v.kind === "unknown") {
534
+ notes.push("We couldn't work out this function's inputs, so it wasn't called.");
535
+ c2.outcome(subject, "Couldn't call it", "info");
536
+ } else c2.outcome(subject, v.kind === "denied" ? "Visitors can't run it" : v.kind === "empty" ? "Visitors get nothing back" : "It refused the visitor", "blocked");
537
+ if (bobParams.length && v.kind !== "unknown" && !f.some((x) => x.severity === "critical")) {
538
+ await c2.step(subject, "Alice calls it with Bob's ids");
539
+ const a = await runFn(c2, fn, c2.alice);
540
+ if (a.kind === "data" && proves(a.text, c2)) {
541
+ add("rpc_read_other", "critical", { detail: bobParams.join(", ") });
542
+ c2.outcome(subject, "Alice can read Bob's data through it", "leak");
543
+ } else if (a.kind === "writes" && !f.some((x) => x.kind === "rpc_public_write")) {
544
+ add("rpc_user_write", "medium", { detail: bobParams.join(", ") });
545
+ c2.outcome(subject, "Alice can run it on Bob's ids, and it changes data (stopped before it did)", "info");
546
+ } else c2.outcome(subject, "Bob's data stays out of reach", "blocked");
547
+ }
548
+ findings.push(...f);
549
+ checks.push({ area: "function", name: fn.name, status: statusOf(f), notes });
550
+ }
551
+ return { findings, checks };
552
+ }
553
+ function argValue(c2, p, attempt) {
554
+ const fmt2 = p.format.toLowerCase();
555
+ if (TENANTISH.test(p.name)) {
556
+ const exact = c2.bobTenants.get(p.name.replace(/^p_/, "")) ?? [...c2.bobTenants.values()][0];
557
+ return String(exact ?? c2.bobId);
558
+ }
559
+ if (USERISH.test(p.name) || fmt2 === "uuid" || /(^|_)id$/i.test(p.name) && attempt === 0) return c2.bobId;
560
+ if (/int|numeric|number|double|real|bigint|smallint/.test(fmt2) || /(limit|count|amount|qty|quantity|page|size|offset|num|days)$/i.test(p.name)) return "1";
561
+ if (/bool/.test(fmt2)) return "true";
562
+ if (/date|time/.test(fmt2)) return "2026-01-01";
563
+ if (/email/i.test(p.name)) return "rowprobe-test@example.com";
564
+ return attempt === 0 ? "rowprobe" : "1";
565
+ }
566
+ async function runFn(c2, fn, who) {
567
+ for (let attempt = 0; attempt < 2; attempt++) {
568
+ const qs = fn.params.map((p) => `${encodeURIComponent(p.name)}=${encodeURIComponent(argValue(c2, p, attempt))}`).join("&");
569
+ const r = await call(c2.fetchFn, `${c2.url.replace(/\/+$/, "")}/rest/v1/rpc/${encodeURIComponent(fn.name)}${qs ? "?" + qs : ""}`, { headers: c2.rest.headers(who) });
570
+ const code = r.json?.code;
571
+ if (r.ok) {
572
+ const empty = r.json === null || r.json === void 0 || Array.isArray(r.json) && !r.json.length || r.json === "" || r.json === 0 || r.json === false;
573
+ return { kind: empty ? "empty" : "data", text: r.text };
574
+ }
575
+ if (code === "25006") return { kind: "writes", text: "" };
576
+ if (r.status === 401 || r.status === 403 || code === "42501") return { kind: "denied", text: "" };
577
+ if (code === "PGRST202" || code === "PGRST203" || code === "0A000") return { kind: "unknown", text: "" };
578
+ if (code === "22P02" || code === "22007" || code === "42883") continue;
579
+ return { kind: "rejected", text: "" };
580
+ }
581
+ return { kind: "unknown", text: "" };
582
+ }
583
+ function proves(text, c2) {
584
+ for (const m of c2.bobMarks) if (m.length >= 6 && text.includes(m)) return true;
585
+ return false;
586
+ }
587
+ async function authSettings(url, rest, fetchFn) {
588
+ const r = await call(fetchFn, `${url.replace(/\/+$/, "")}/auth/v1/settings`, { headers: { apikey: rest.headers({ label: "visitor" }).apikey } });
589
+ if (!r.ok) return null;
590
+ const s = r.json;
591
+ return { anonymous: !!s.external?.anonymous_users, openSignup: !s.disable_signup && s.external?.email !== false, autoconfirm: !!s.mailer_autoconfirm };
592
+ }
593
+ async function anonymousSignIn(url, rest, fetchFn) {
594
+ const r = await call(fetchFn, `${url.replace(/\/+$/, "")}/auth/v1/signup`, {
595
+ method: "POST",
596
+ headers: { apikey: rest.headers({ label: "visitor" }).apikey, "Content-Type": "application/json" },
597
+ body: JSON.stringify({ data: {} })
598
+ });
599
+ const j = r.json;
600
+ if (r.ok && j?.access_token && j.user) return { id: j.user.id, token: j.access_token };
601
+ return { error: j?.msg ?? j?.message ?? j?.error_description ?? `HTTP ${r.status}` };
602
+ }
603
+ function statusOf(f) {
604
+ if (f.some((x) => x.severity === "critical" || x.severity === "high")) return "leak";
605
+ if (f.length) return "check";
606
+ return "safe";
607
+ }
608
+ async function pool(items, n, fn) {
609
+ const out = new Array(items.length);
610
+ let i = 0;
611
+ await Promise.all(Array.from({ length: Math.min(n, items.length) }, async () => {
612
+ while (i < items.length) {
613
+ const k = i++;
614
+ out[k] = await fn(items[k]);
615
+ }
616
+ }));
617
+ return out;
618
+ }
619
+
620
+ // ../web/src/lib/scan/engine.ts
621
+ function subjectOf(f) {
622
+ switch (f.area) {
623
+ case "storage":
624
+ return `Storage: ${f.table}`;
625
+ case "function":
626
+ return `${f.table}()`;
627
+ case "auth":
628
+ return "Sign-in settings";
629
+ case "website":
630
+ return "Website code";
631
+ default:
632
+ return f.column ? `${f.table}.${f.column}` : f.table;
633
+ }
634
+ }
635
+ var SEVERITY_ORDER = ["critical", "high", "medium", "low"];
636
+ var SENSITIVE = /email|phone|address|token|secret|password|key|ssn|birth|salary|user|owner|actor|author|created_by|customer|client|member|note|body|message|amount|card|iban/i;
637
+ var TIMESTAMP_COL = /^(created_at|updated_at|inserted_at|modified_at)$/i;
638
+ var TENANT_COL = /^(company|org|organization|organisation|team|workspace|tenant|account)_id$/i;
639
+ function sqlLiteral(v) {
640
+ if (v === null || v === void 0) return "null";
641
+ if (typeof v === "number" || typeof v === "boolean") return String(v);
642
+ return `'${String(v).replace(/'/g, "''")}'`;
643
+ }
644
+ function whereSql(f) {
645
+ return Object.entries(f).map(([k, v]) => `"${k}" = ${sqlLiteral(v)}`).join(" and ");
646
+ }
647
+ function rowKey(row, pk) {
648
+ return pk.length ? pk.map((c2) => String(row[c2])).join("\0") : JSON.stringify(row);
649
+ }
650
+ function pkFilter(row, pk) {
651
+ const f = {};
652
+ for (const c2 of pk) f[c2] = row[c2];
653
+ return f;
654
+ }
655
+ function columnsOf(t, rows) {
656
+ if (t.columns.length) return t.columns;
657
+ const names = /* @__PURE__ */ new Set();
658
+ rows.forEach((r) => Object.keys(r).forEach((k) => names.add(k)));
659
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
660
+ const ISO_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/;
661
+ return [...names].map((name) => {
662
+ const v = rows.map((r) => r[name]).find((x) => x !== null && x !== void 0);
663
+ const format = typeof v === "string" ? UUID.test(v) ? "uuid" : ISO_TIME.test(v) ? "timestamp" : "text" : typeof v === "number" ? "number" : "";
664
+ return { name, format, pk: name === "id", hasDefault: false };
665
+ });
666
+ }
667
+ function findOwnerCols(a, b, alice, bob) {
668
+ const cols = /* @__PURE__ */ new Set();
669
+ for (const r of b) for (const [k, v] of Object.entries(r)) if (v === bob) cols.add(k);
670
+ for (const r of a) for (const [k, v] of Object.entries(r)) if (v === alice) cols.add(k);
671
+ return [...cols];
672
+ }
673
+ function isTextCol(c2) {
674
+ return /^(text|character varying|varchar|citext)$/i.test(c2.format);
675
+ }
676
+ function copyPayload(row, cols, pk, keepPk) {
677
+ const out = {};
678
+ for (const [k, v] of Object.entries(row)) {
679
+ if (!keepPk && pk.includes(k)) continue;
680
+ if (TIMESTAMP_COL.test(k)) continue;
681
+ const col = cols.find((c2) => c2.name === k);
682
+ if (col && col.pk && !keepPk) continue;
683
+ out[k] = v;
684
+ }
685
+ return out;
686
+ }
687
+ function learnTenants(reads, A, B) {
688
+ const m = /* @__PURE__ */ new Map();
689
+ for (const r of reads) {
690
+ if (!r.ownerCols.length) continue;
691
+ for (const tc of r.cols.filter((c2) => TENANT_COL.test(c2))) {
692
+ if (!m.has(tc)) m.set(tc, { alice: /* @__PURE__ */ new Set(), bob: /* @__PURE__ */ new Set() });
693
+ const e = m.get(tc);
694
+ for (const row of r.a) if (r.ownerCols.some((c2) => row[c2] === A) && row[tc] != null) e.alice.add(row[tc]);
695
+ for (const row of r.b) if (r.ownerCols.some((c2) => row[c2] === B) && row[tc] != null) e.bob.add(row[tc]);
696
+ }
697
+ }
698
+ for (const e of m.values()) for (const v of [...e.alice]) if (e.bob.has(v)) {
699
+ e.alice.delete(v);
700
+ e.bob.delete(v);
701
+ }
702
+ return m;
703
+ }
704
+ async function runScan(input, ev = {}) {
705
+ const rest = new Rest(input.url, input.key, input.fetchFn);
706
+ const visitor = { label: "visitor" };
707
+ const alice = { label: "alice", token: input.alice.token };
708
+ const bob = { label: "bob", token: input.bob.token };
709
+ const A = input.alice.id;
710
+ const B = input.bob.id;
711
+ const shared = new Set(input.sharedTables ?? []);
712
+ const leftovers = [];
713
+ const results = [];
714
+ const log = (m) => ev.onLog?.(m);
715
+ const pace = Math.max(0, input.stepDelayMs ?? 0);
716
+ const step = async (table, text) => {
717
+ ev.onStep?.({ table, text });
718
+ log(`${table}: ${text}`);
719
+ if (pace) await new Promise((r) => setTimeout(r, pace));
720
+ };
721
+ let attempts = 0;
722
+ let blocked = 0;
723
+ const outcome = (table, text, kind) => {
724
+ if (kind !== "info") attempts++;
725
+ if (kind === "blocked") blocked++;
726
+ ev.onStep?.({ table, text, outcome: kind });
727
+ };
728
+ const deep = input.deep !== false;
729
+ const checks = [...input.extraChecks ?? []];
730
+ const extraFindings = [...input.extraFindings ?? []];
731
+ const bobMarks = /* @__PURE__ */ new Set();
732
+ const totalWork = input.tables.length * 2 + (input.deep !== false ? 2 : 0);
733
+ let workDone = 0;
734
+ const progress = () => ev.onProgress?.(++workDone, totalWork);
735
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
736
+ const marker = "rowprobe-test-" + Math.random().toString(36).slice(2, 8);
737
+ const reads = [];
738
+ for (const t of input.tables) {
739
+ ev.onTable?.(t.name, "testing");
740
+ await step(t.name, "Reading as a signed-out visitor");
741
+ const v = await rest.select(t.name, visitor);
742
+ await step(t.name, "Reading as Alice");
743
+ const a = await rest.select(t.name, alice);
744
+ await step(t.name, "Reading as Bob");
745
+ const b = await rest.select(t.name, bob);
746
+ const cols = columnsOf(t, [...v.rows, ...a.rows, ...b.rows]);
747
+ const pk = t.pk.length ? t.pk : cols.some((c2) => c2.name === "id") ? ["id"] : [];
748
+ reads.push({ t, v, a, b, cols, pk, ownerCols: findOwnerCols(a.rows, b.rows, A, B) });
749
+ ev.onTable?.(t.name, "read");
750
+ progress();
751
+ }
752
+ await step("schema", "Working out which rows belong to which user and account");
753
+ const tenants = learnTenants(reads.map((r) => ({ a: r.a.rows, b: r.b.rows, ownerCols: r.ownerCols, cols: r.cols.map((c2) => c2.name) })), A, B);
754
+ let anon;
755
+ if (deep) {
756
+ await step("sign-in", "Checking your project's sign-in settings");
757
+ const settings = await authSettings(input.url, rest, input.fetchFn ?? ((...a) => fetch(...a)));
758
+ const notes = [];
759
+ const af = [];
760
+ if (settings?.anonymous) {
761
+ if (input.writeTests) {
762
+ await step("sign-in", "Signing in as an anonymous user (anyone can do this)");
763
+ const s = await anonymousSignIn(input.url, rest, input.fetchFn ?? ((...a) => fetch(...a)));
764
+ if ("token" in s) {
765
+ anon = { label: "visitor", token: s.token };
766
+ outcome("sign-in", "Anonymous sign-in works: we'll check what it can read", "info");
767
+ leftovers.push({ table: "sign-in", description: "Anonymous test user created to check what anyone can read", sql: `delete from auth.users where id = ${sqlLiteral(s.id)};` });
768
+ } else notes.push(`Anonymous sign-ins are on, but signing in failed (${s.error}).`);
769
+ } else notes.push("Anonymous sign-ins are on. Turn on write tests to check what an anonymous user can read.");
770
+ }
771
+ if (settings?.openSignup && settings.autoconfirm) {
772
+ af.push({ area: "auth", table: "auth", kind: "auth_open_signup", severity: "low", pk: [], columns: [] });
773
+ outcome("sign-in", "Anyone can sign up instantly, without confirming an email", "info");
774
+ }
775
+ if (settings) checks.push({ area: "auth", name: "Sign-in settings", status: af.length ? "check" : "safe", notes });
776
+ extraFindings.push(...af);
777
+ }
778
+ for (const { t, v, a, b, cols, pk, ownerCols } of reads) {
779
+ ev.onTable?.(t.name, "testing");
780
+ const findings2 = [];
781
+ const notes = [];
782
+ const colNames = cols.map((c2) => c2.name);
783
+ const add = (kind, severity, extra = {}) => findings2.push({ table: t.name, kind, severity, pk, columns: colNames, ...t.writable ? {} : { view: true }, ...extra });
784
+ if ([v, a, b].every((r) => isDenied(r))) {
785
+ outcome(t.name, "No one can read this table", "blocked");
786
+ results.push(done(t.name, findings2, ["No one can read this table through the API."]));
787
+ progress();
788
+ continue;
789
+ }
790
+ const otherError = [v, a, b].find((r) => r.status !== 200 && !isDenied(r));
791
+ if (otherError && a.status !== 200 && b.status !== 200) {
792
+ notes.push(`Could not read this table: ${otherError.message ?? "HTTP " + otherError.status}`);
793
+ outcome(t.name, "Couldn't read this table", "info");
794
+ results.push(done(t.name, findings2, notes, true));
795
+ progress();
796
+ continue;
797
+ }
798
+ const ownerCol = ownerCols.find((c2) => !pk.includes(c2)) ?? ownerCols[0];
799
+ const tenantCol = colNames.find((c2) => {
800
+ const e = tenants.get(c2);
801
+ return e && e.alice.size && e.bob.size;
802
+ });
803
+ const te = tenantCol ? tenants.get(tenantCol) : void 0;
804
+ const ownedBy = (r, uid) => {
805
+ if (ownerCols.some((c2) => r[c2] === uid)) return true;
806
+ if (te && tenantCol && !pk.includes(tenantCol)) {
807
+ const mine = uid === A ? te.alice : te.bob;
808
+ return mine.has(r[tenantCol]);
809
+ }
810
+ return false;
811
+ };
812
+ const proves2 = ownerCols.length > 0 || !!(te && tenantCol && !pk.includes(tenantCol));
813
+ if (proves2) {
814
+ for (const r of b.rows) {
815
+ if (!ownedBy(r, B) || ownedBy(r, A)) continue;
816
+ for (const k of pk) if (typeof r[k] === "string" || typeof r[k] === "number") bobMarks.add(String(r[k]));
817
+ for (const v2 of Object.values(r)) if (typeof v2 === "string" && /^[^@\s]+@[^@\s]+\.[a-z]{2,}$/i.test(v2)) bobMarks.add(v2);
818
+ }
819
+ }
820
+ await step(t.name, "Can signed-out visitors see rows?");
821
+ if (v.rows.length && !shared.has(t.name)) {
822
+ const sensitive = proves2 || cols.some((c2) => SENSITIVE.test(c2.name));
823
+ add("public_read", sensitive ? "high" : "low", { count: v.rows.length, ownerCol, tenantCol });
824
+ outcome(t.name, `Visitors can read ${v.rows.length} row${v.rows.length > 1 ? "s" : ""}`, sensitive ? "leak" : "info");
825
+ } else outcome(t.name, "Visitors see nothing", "blocked");
826
+ await step(t.name, "Can Alice see Bob's rows, or Bob see Alice's?");
827
+ const aliceSeesBob = proves2 ? a.rows.filter((r) => ownedBy(r, B) && !ownedBy(r, A)) : [];
828
+ const bobSeesAlice = proves2 ? b.rows.filter((r) => ownedBy(r, A) && !ownedBy(r, B)) : [];
829
+ const crossRead = Math.max(aliceSeesBob.length, bobSeesAlice.length);
830
+ if (crossRead > 0 && !shared.has(t.name)) {
831
+ add("read_other", "critical", { count: crossRead, ownerCol, tenantCol });
832
+ outcome(t.name, `Alice can read ${crossRead} of Bob's rows`, "leak");
833
+ } else if (proves2) outcome(t.name, "Each user only sees their own rows", "blocked");
834
+ if (anon && proves2 && !shared.has(t.name)) {
835
+ await step(t.name, "Can an anonymous user see Alice's or Bob's rows?");
836
+ const an = await rest.select(t.name, anon);
837
+ const visible = new Set(v.rows.map((r) => rowKey(r, pk)));
838
+ const seen = an.rows.filter((r) => (ownedBy(r, A) || ownedBy(r, B)) && !visible.has(rowKey(r, pk)));
839
+ if (seen.length) {
840
+ add("anon_signin_read", "critical", { count: seen.length, ownerCol, tenantCol });
841
+ outcome(t.name, `An anonymous user can read ${seen.length} of Alice's and Bob's rows`, "leak");
842
+ } else outcome(t.name, "Anonymous users see nothing of theirs", "blocked");
843
+ }
844
+ if (!crossRead && !v.rows.length && !shared.has(t.name)) {
845
+ const bKeys = new Set(b.rows.map((r) => rowKey(r, pk)));
846
+ const both = a.rows.filter((r) => bKeys.has(rowKey(r, pk)));
847
+ if (both.length && !proves2) add("shared_rows", "medium", { count: both.length });
848
+ }
849
+ if (!a.rows.length && !b.rows.length && !v.rows.length) {
850
+ notes.push("Neither test user has rows here. Add some data as both users, then rescan.");
851
+ }
852
+ const canWrite = input.writeTests && t.writable && pk.length > 0;
853
+ if (input.writeTests && t.writable && !pk.length && (a.rows.length || b.rows.length))
854
+ notes.push("Edit and delete were not tested: no primary key found.");
855
+ const claimCol = ownerCol ?? (te ? tenantCol : void 0);
856
+ const bobValue = ownerCol ? B : te ? [...te.bob][0] : void 0;
857
+ const aliceValue = ownerCol ? A : te ? [...te.alice][0] : void 0;
858
+ if (canWrite && proves2 && claimCol) {
859
+ const target = aliceSeesBob[0];
860
+ if (target) {
861
+ const c2 = cols.find((c3) => !pk.includes(c3.name) && !ownerCols.includes(c3.name) && c3.name !== tenantCol && target[c3.name] !== void 0 && typeof target[c3.name] !== "object");
862
+ if (c2) {
863
+ await step(t.name, "Alice tries to edit one of Bob's rows");
864
+ const r = await rest.update(t.name, alice, pkFilter(target, pk), { [c2.name]: target[c2.name] }, true);
865
+ if (r.status < 300 && r.rows.length) {
866
+ add("update_other", "critical", { ownerCol, tenantCol });
867
+ outcome(t.name, "Alice can edit Bob's rows", "leak");
868
+ } else outcome(t.name, "Edit blocked", "blocked");
869
+ }
870
+ }
871
+ const bobOwn = b.rows.find((r) => ownedBy(r, B) && !ownedBy(r, A));
872
+ if (target && bobOwn) {
873
+ await step(t.name, "Bob creates a test row");
874
+ const created = await insertCopy(rest, t.name, bob, bobOwn, cols, pk, pk.includes(claimCol), marker, true);
875
+ if (created.row) {
876
+ const f = pkFilter(created.row, pk);
877
+ await step(t.name, "Alice tries to delete Bob's test row");
878
+ const del = await rest.remove(t.name, alice, f);
879
+ if (del.status < 300 && (del.rows.length || del.count === 1)) {
880
+ add("delete_other", "critical", { ownerCol, tenantCol });
881
+ outcome(t.name, "Alice can delete Bob's rows", "leak");
882
+ } else {
883
+ outcome(t.name, "Delete blocked", "blocked");
884
+ await step(t.name, "Cleaning up Bob's test row");
885
+ const clean = await rest.remove(t.name, bob, f);
886
+ if (!(clean.status < 300 && (clean.rows.length || clean.count === 1)))
887
+ leftovers.push({ table: t.name, description: "Test row created by Bob for the delete test", sql: `delete from public."${t.name}" where ${whereSql(f)};` });
888
+ }
889
+ } else if (created.reason) notes.push(`Delete was not tested: ${created.reason}`);
890
+ }
891
+ const template = b.rows.find((r) => ownedBy(r, B) && !ownedBy(r, A)) ?? a.rows.find((r) => ownedBy(r, A));
892
+ if (template && bobValue !== void 0) {
893
+ await step(t.name, "Alice tries to create a row in Bob's name");
894
+ const payload = { ...template, [claimCol]: bobValue };
895
+ if (ownerCol && tenantCol && te && te.bob.size) payload[tenantCol] = [...te.bob][0];
896
+ const before = new Set(b.rows.map((r) => rowKey(r, pk)));
897
+ const ins = await insertCopy(rest, t.name, alice, payload, cols, pk, pk.includes(claimCol), marker, false);
898
+ if (ins.ok) {
899
+ add("insert_as_other", "high", { ownerCol, tenantCol });
900
+ outcome(t.name, "Alice can create rows as Bob", "leak");
901
+ await step(t.name, "Removing the test row");
902
+ await cleanupInserted(rest, t.name, pk, claimCol, bobValue, before, [bob, alice], leftovers, ins.markedCol ? marker : void 0, ins.markedCol);
903
+ } else if (ins.reason) {
904
+ notes.push(`Creating rows as another user was not tested: ${ins.reason}`);
905
+ outcome(t.name, "Couldn't test creating rows", "info");
906
+ } else outcome(t.name, "Creating rows as Bob blocked", "blocked");
907
+ }
908
+ const aliceOwn = a.rows.find((r) => ownedBy(r, A) && !ownedBy(r, B));
909
+ if (aliceOwn && !pk.includes(claimCol) && bobValue !== void 0 && aliceValue !== void 0) {
910
+ await step(t.name, "Alice tries to hand her row to Bob");
911
+ const f = pkFilter(aliceOwn, pk);
912
+ const original = aliceOwn[claimCol];
913
+ const r = await rest.update(t.name, alice, f, { [claimCol]: bobValue }, false);
914
+ let moved = false;
915
+ if (r.status < 300) {
916
+ const check = await rest.select(t.name, bob, f);
917
+ moved = check.rows.some((x) => x[claimCol] === bobValue) || r.count === 1;
918
+ if (moved) {
919
+ add("owner_transfer", "high", { ownerCol, tenantCol });
920
+ outcome(t.name, "Alice can move her rows into Bob's account", "leak");
921
+ await step(t.name, "Moving the row back");
922
+ const back = await rest.update(t.name, bob, f, { [claimCol]: original }, false);
923
+ const verify = await rest.select(t.name, alice, f);
924
+ if (!(back.status < 300 && verify.rows.some((x) => x[claimCol] === original)))
925
+ leftovers.push({ table: t.name, description: "Alice's row was moved to Bob during the test and could not be moved back", sql: `update public."${t.name}" set "${claimCol}" = ${sqlLiteral(original)} where ${whereSql(f)};` });
926
+ }
927
+ }
928
+ if (!moved) outcome(t.name, "Handing rows to Bob blocked", "blocked");
929
+ }
930
+ }
931
+ if (canWrite && proves2 && deep) {
932
+ const aliceRow = a.rows.find((r) => ownedBy(r, A) && !ownedBy(r, B));
933
+ if (aliceRow) {
934
+ const seenValues = (col) => [...new Set([...a.rows, ...b.rows, ...v.rows].map((r) => r[col]).filter((x) => typeof x === "string"))];
935
+ for (const col of colNames) {
936
+ if (pk.includes(col) || ownerCols.includes(col) || col === claimCol) continue;
937
+ const kind = privilegeOf(col);
938
+ const current = aliceRow[col];
939
+ let tries = [];
940
+ let severity = "high";
941
+ if (col === tenantCol && te && te.bob.size) {
942
+ tries = [[...te.bob][0]];
943
+ severity = "critical";
944
+ } else if (kind) {
945
+ tries = escalations(kind.kind, current, seenValues(col));
946
+ severity = kind.severity;
947
+ }
948
+ if (!tries.length) continue;
949
+ const f = pkFilter(aliceRow, pk);
950
+ await step(t.name, col === tenantCol ? `Alice tries to move herself into Bob's ${col.replace(/_id$/, "")}` : `Alice tries to change her own ${col}`);
951
+ let won;
952
+ for (const value of tries.slice(0, 3)) {
953
+ const r = await rest.update(t.name, alice, f, { [col]: value }, true);
954
+ if (r.status < 300 && r.rows.some((x) => String(x[col]) === String(value))) {
955
+ won = value;
956
+ break;
957
+ }
958
+ if (isDenied(r) || r.status < 300 && !r.rows.length) break;
959
+ }
960
+ if (won === void 0) {
961
+ outcome(t.name, `Changing ${col} blocked`, "blocked");
962
+ continue;
963
+ }
964
+ add("self_escalation", severity, { ownerCol, tenantCol, column: col, detail: `${fmt(current)} \u2192 ${fmt(won)}` });
965
+ outcome(t.name, col === tenantCol ? `Alice can move herself into Bob's ${col.replace(/_id$/, "")}` : `Alice can change her own ${col} (${fmt(current)} \u2192 ${fmt(won)})`, "leak");
966
+ await step(t.name, `Putting ${col} back`);
967
+ let restored = false;
968
+ for (const who of [alice, bob]) {
969
+ const back = await rest.update(t.name, who, f, { [col]: current }, true);
970
+ if (back.status < 300 && back.rows.some((x) => String(x[col]) === String(current))) {
971
+ restored = true;
972
+ break;
973
+ }
974
+ }
975
+ if (!restored)
976
+ leftovers.push({ table: t.name, description: `Alice's ${col} was changed during the test and could not be put back`, sql: `update public."${t.name}" set "${col}" = ${sqlLiteral(current)} where ${whereSql(f)};` });
977
+ }
978
+ const roleCol = colNames.find((c2) => !pk.includes(c2) && privilegeOf(c2)?.kind === "role");
979
+ if (roleCol && ownerCol && !pk.includes(ownerCol) && !findings2.some((x) => x.kind === "self_escalation" && x.column === roleCol)) {
980
+ const value = escalations("role", aliceRow[roleCol], seenValues(roleCol))[0];
981
+ if (value !== void 0) {
982
+ await step(t.name, `Alice tries to add a ${fmt(value)} ${roleCol} for herself`);
983
+ const before = new Set(a.rows.map((r) => rowKey(r, pk)));
984
+ const ins = await insertCopy(rest, t.name, alice, { ...aliceRow, [roleCol]: value }, cols, pk, false, marker, false);
985
+ if (ins.ok) {
986
+ add("self_grant", "critical", { ownerCol, tenantCol, column: roleCol, detail: fmt(value) });
987
+ outcome(t.name, `Alice can give herself the ${fmt(value)} ${roleCol}`, "leak");
988
+ await cleanupInserted(rest, t.name, pk, ownerCol, A, before, [alice, bob], leftovers, ins.markedCol ? marker : void 0, ins.markedCol);
989
+ } else outcome(t.name, `Adding a ${fmt(value)} ${roleCol} blocked`, "blocked");
990
+ }
991
+ }
992
+ }
993
+ }
994
+ if (canWrite && !proves2 && findings2.some((f) => f.kind === "shared_rows" || f.kind === "public_read")) {
995
+ notes.push("Nothing in this table says which user or account a row belongs to, so edits across users were not tested.");
996
+ }
997
+ results.push(done(t.name, findings2, notes));
998
+ progress();
999
+ }
1000
+ if (deep) {
1001
+ const fetchFn = input.fetchFn ?? ((...a) => fetch(...a));
1002
+ const st = await scanStorage({
1003
+ storage: new StorageApi(input.url, rest, fetchFn),
1004
+ visitor,
1005
+ alice,
1006
+ bob,
1007
+ aliceId: A,
1008
+ bobId: B,
1009
+ writeTests: input.writeTests,
1010
+ hints: input.bucketHints ?? [],
1011
+ marker,
1012
+ step,
1013
+ outcome,
1014
+ leftovers
1015
+ });
1016
+ progress();
1017
+ const bobTenants = /* @__PURE__ */ new Map();
1018
+ for (const [col, e] of tenants) if (e.bob.size) bobTenants.set(col, [...e.bob][0]);
1019
+ const fn = await scanFunctions({
1020
+ rest,
1021
+ fetchFn,
1022
+ url: input.url,
1023
+ visitor,
1024
+ alice,
1025
+ aliceId: A,
1026
+ bobId: B,
1027
+ bobTenants,
1028
+ bobMarks,
1029
+ hints: input.functionHints ?? [],
1030
+ step,
1031
+ outcome
1032
+ });
1033
+ progress();
1034
+ extraFindings.push(...st.findings, ...fn.findings);
1035
+ checks.push(...st.checks, ...fn.checks);
1036
+ }
1037
+ const findings = [...results.flatMap((r) => r.findings), ...extraFindings].sort((x, y) => SEVERITY_ORDER.indexOf(x.severity) - SEVERITY_ORDER.indexOf(y.severity));
1038
+ log(leftovers.length ? `Done. ${leftovers.length} test change(s) could not be undone.` : "Done. All test changes were undone.");
1039
+ return { tables: results, checks, attempts, blocked, findings, leftovers, startedAt, finishedAt: (/* @__PURE__ */ new Date()).toISOString() };
1040
+ function done(table, f, notes, failed = false) {
1041
+ f.sort((x, y) => SEVERITY_ORDER.indexOf(x.severity) - SEVERITY_ORDER.indexOf(y.severity));
1042
+ let status = "safe";
1043
+ if (failed) status = "untested";
1044
+ else if (f.some((x) => x.kind !== "public_read" && x.kind !== "shared_rows")) status = "leak";
1045
+ else if (f.some((x) => x.kind === "public_read" && x.severity !== "low")) status = "public";
1046
+ else if (f.length) status = "check";
1047
+ else if (notes.some((n) => n.startsWith("Neither test user"))) status = "untested";
1048
+ const r = { table, status, findings: f, notes };
1049
+ ev.onTable?.(table, r);
1050
+ return r;
1051
+ }
1052
+ }
1053
+ function privilegeOf(col) {
1054
+ if (/^(role|roles|user_role|app_role|account_role|access_level|permission_level|user_type|account_type|membership_role)$/i.test(col)) return { kind: "role", severity: "critical" };
1055
+ if (/^(is_)?(admin|super_?admin|superuser|staff|moderator|internal)$/i.test(col)) return { kind: "flag", severity: "critical" };
1056
+ if (/^(is_)?(banned|suspended|blocked|disabled|locked)$/i.test(col)) return { kind: "restriction", severity: "high" };
1057
+ if (/^(plan|tier|subscription|subscription_(tier|plan|status)|plan_(id|name)|is_(pro|premium|paid|subscribed|vip)|pro|premium|paid|vip)$/i.test(col)) return { kind: "plan", severity: "high" };
1058
+ if (/^(pro|premium|plan|trial|subscription|paid)_(until|expires_at|ends_at|end|expiry)$/i.test(col)) return { kind: "date", severity: "high" };
1059
+ if (/(^|_)(credits?|balance|coins|points|tokens_left|token_balance|quota|wallet|usage_limit)$/i.test(col)) return { kind: "number", severity: "high" };
1060
+ if (/^(is_)?(verified|approved|email_verified|kyc_verified|kyc_status|onboarded)$/i.test(col)) return { kind: "status", severity: "medium" };
1061
+ return void 0;
1062
+ }
1063
+ var HIGH_ROLES = ["owner", "admin", "superadmin", "super_admin", "staff", "moderator", "manager", "editor"];
1064
+ var HIGH_PLANS = ["enterprise", "business", "premium", "pro", "team", "paid", "active", "unlimited"];
1065
+ function escalations(kind, current, seen) {
1066
+ if (typeof current === "boolean") {
1067
+ if (kind === "restriction") return current ? [false] : [];
1068
+ return current ? [] : [true];
1069
+ }
1070
+ if (typeof current === "number") return kind === "number" ? [current + 1e3] : [];
1071
+ if (kind === "date") return ["2099-12-31T00:00:00Z"];
1072
+ if (typeof current !== "string" && current !== null) return [];
1073
+ const ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1074
+ if (typeof current === "string" && ID.test(current)) return kind === "role" || kind === "plan" ? seen.filter((x) => x !== current && ID.test(x)).slice(0, 2) : [];
1075
+ const pool2 = kind === "role" ? HIGH_ROLES : kind === "plan" ? HIGH_PLANS : kind === "status" ? ["verified", "approved"] : [];
1076
+ if (!pool2.length) return [];
1077
+ const cur = typeof current === "string" ? current.toLowerCase() : "";
1078
+ const ranked = [...seen.filter((x) => pool2.includes(x.toLowerCase())), ...pool2];
1079
+ return [...new Set(ranked)].filter((x) => x.toLowerCase() !== cur && pool2.indexOf(x.toLowerCase()) < (pool2.indexOf(cur) === -1 ? pool2.length : pool2.indexOf(cur)));
1080
+ }
1081
+ function fmt(v) {
1082
+ if (v === null || v === void 0) return "empty";
1083
+ return typeof v === "string" ? v : JSON.stringify(v);
1084
+ }
1085
+ async function insertCopy(rest, table, who, row, cols, pk, keepPk, marker, returnRows) {
1086
+ const base = copyPayload(row, cols, pk, keepPk);
1087
+ const markCol = cols.find((c2) => isTextCol(c2) && !pk.includes(c2.name) && typeof base[c2.name] === "string");
1088
+ const attempts = [];
1089
+ if (markCol) attempts.push({ body: { ...base, [markCol.name]: marker }, markedCol: markCol.name });
1090
+ attempts.push({ body: base });
1091
+ let last;
1092
+ for (const at of attempts) {
1093
+ const r = await rest.insert(table, who, at.body, returnRows);
1094
+ if (r.status < 300) return { ok: true, row: r.rows[0], markedCol: at.markedCol };
1095
+ last = r;
1096
+ if (isDenied(r)) return { ok: false };
1097
+ }
1098
+ return { ok: false, reason: friendlyError(last) };
1099
+ }
1100
+ async function cleanupInserted(rest, table, pk, claimCol, claimVal, before, cleaners, leftovers, marker, markedCol) {
1101
+ for (const who of cleaners) {
1102
+ const now = await rest.select(table, who, { [claimCol]: claimVal });
1103
+ const fresh = now.rows.filter((r) => !before.has(rowKey(r, pk)) && (!marker || !markedCol || r[markedCol] === marker));
1104
+ if (!fresh.length) continue;
1105
+ let all = true;
1106
+ for (const r of fresh) {
1107
+ const d = await rest.remove(table, who, pkFilter(r, pk));
1108
+ if (!(d.status < 300 && (d.rows.length || d.count === 1))) all = false;
1109
+ }
1110
+ if (all) return;
1111
+ }
1112
+ leftovers.push({
1113
+ table,
1114
+ description: "Test row created as part of the 'create as another user' test",
1115
+ sql: marker && markedCol ? `delete from public."${table}" where "${markedCol}" = ${sqlLiteral(marker)};` : `-- find the newest row in public."${table}" where "${claimCol}" = ${sqlLiteral(claimVal)} and delete it`
1116
+ });
1117
+ }
1118
+ function friendlyError(r) {
1119
+ if (!r) return "unknown error";
1120
+ switch (r.code) {
1121
+ case "23505":
1122
+ return "a unique value clashed with an existing row";
1123
+ case "23502":
1124
+ return "a required column has no value";
1125
+ case "23503":
1126
+ return "a linked row does not exist";
1127
+ case "23514":
1128
+ return "a check rule on the table rejected the test row";
1129
+ case "428C9":
1130
+ return "a column can't be set by hand";
1131
+ default:
1132
+ return r.message ?? `HTTP ${r.status}`;
1133
+ }
1134
+ }
1135
+ function isLeak(f) {
1136
+ if (f.kind === "shared_rows") return false;
1137
+ return f.severity === "critical" || f.severity === "high" || f.kind !== "public_read" && f.severity !== "low" && f.kind !== "rpc_public_data" && f.kind !== "rpc_user_write" && f.kind !== "storage_public_list";
1138
+ }
1139
+ function summarize(r) {
1140
+ const leaks = r.findings.filter(isLeak);
1141
+ const checksCount = r.findings.length - leaks.length;
1142
+ const others = r.checks ?? [];
1143
+ const count = (s) => r.tables.filter((t) => t.status === s).length + others.filter((c2) => c2.status === s).length;
1144
+ return {
1145
+ leaks: leaks.length,
1146
+ checks: checksCount,
1147
+ leaking: count("leak"),
1148
+ public: count("public"),
1149
+ safe: count("safe"),
1150
+ check: count("check"),
1151
+ untested: count("untested"),
1152
+ total: r.tables.length + others.length,
1153
+ tables: r.tables.length,
1154
+ buckets: others.filter((c2) => c2.area === "storage").length,
1155
+ functions: others.filter((c2) => c2.area === "function").length,
1156
+ attempts: r.attempts,
1157
+ blocked: r.blocked
1158
+ };
1159
+ }
1160
+
1161
+ // src/cli.ts
1162
+ var VERSION = "0.2.0";
1163
+ var HELP = `rowprobe ${VERSION}: find Supabase data leaks between users
1164
+
1165
+ Usage: npx rowprobe scan [options]
1166
+
1167
+ Every option can also be set with the environment variable shown.
1168
+ --url <url> Supabase project URL SUPABASE_URL
1169
+ --key <key> anon / publishable key SUPABASE_ANON_KEY
1170
+ --alice-email <email> test user A ROWPROBE_ALICE_EMAIL
1171
+ --alice-password <pw> ROWPROBE_ALICE_PASSWORD
1172
+ --bob-email <email> test user B (a different account/org) ROWPROBE_BOB_EMAIL
1173
+ --bob-password <pw> ROWPROBE_BOB_PASSWORD
1174
+ --token <rp_...> RowProbe CI token (Pro) ROWPROBE_TOKEN
1175
+ --tables <a,b,c> tables to test (default: discover) ROWPROBE_TABLES
1176
+ --shared <a,b> tables meant to be shared/public ROWPROBE_SHARED
1177
+ --site <url> your app's website: checks its public ROWPROBE_SITE
1178
+ code for leaked secret keys and finds
1179
+ the tables, buckets and functions it uses
1180
+ --fail-on <leak|critical|never> when to fail (default leak) ROWPROBE_FAIL_ON
1181
+ --no-write only test reads (no test rows or files)
1182
+ --no-deep skip storage, function and sign-in checks
1183
+ --no-fixes don't fetch SQL fixes
1184
+ --json print the result as JSON
1185
+ --api <url> RowProbe API (default https://rowprobe.com)
1186
+
1187
+ What it tries: other users' rows (read, edit, delete, create), users changing their own
1188
+ role/plan/credits, other users' storage files, database functions (called read-only),
1189
+ anonymous sign-in, and (with --site) secret keys in your website's code.
1190
+
1191
+ Exit codes: 0 = no leaks, 1 = leaks found, 2 = setup or auth problem.
1192
+ Use test accounts and, ideally, a staging project. Test only projects you're allowed to test.`;
1193
+ function parseArgs(argv) {
1194
+ const flags = {};
1195
+ const rest = [];
1196
+ for (let i = 0; i < argv.length; i++) {
1197
+ const a = argv[i];
1198
+ if (!a.startsWith("--")) {
1199
+ rest.push(a);
1200
+ continue;
1201
+ }
1202
+ const [k, v] = a.slice(2).split("=", 2);
1203
+ if (v !== void 0) flags[k] = v;
1204
+ else if (k.startsWith("no-") || ["json", "help", "version"].includes(k)) flags[k] = true;
1205
+ else flags[k] = argv[++i] ?? "";
1206
+ }
1207
+ return { flags, rest };
1208
+ }
1209
+ var isTTY = process.stdout.isTTY && !process.env.NO_COLOR;
1210
+ var c = (code) => (s) => isTTY ? `\x1B[${code}m${s}\x1B[0m` : s;
1211
+ var red = c(31);
1212
+ var green = c(32);
1213
+ var yellow = c(33);
1214
+ var dim = c(2);
1215
+ var bold = c(1);
1216
+ function fail(msg) {
1217
+ console.error(red(`\u2717 ${msg}`));
1218
+ process.exit(2);
1219
+ }
1220
+ async function signIn(url, key, email, password, who) {
1221
+ const r = await fetch(`${url}/auth/v1/token?grant_type=password`, {
1222
+ method: "POST",
1223
+ headers: { apikey: key, "Content-Type": "application/json" },
1224
+ body: JSON.stringify({ email, password })
1225
+ }).catch((e) => fail(`Couldn't reach ${url}: ${e instanceof Error ? e.message : e}`));
1226
+ const j = await r.json().catch(() => ({}));
1227
+ if (!r.ok || !j.access_token || !j.user?.id) fail(`Couldn't sign in ${who} (${email}): ${j.error_description ?? j.msg ?? j.message ?? `HTTP ${r.status}`}`);
1228
+ return { id: j.user.id, token: j.access_token };
1229
+ }
1230
+ function failing(f, failOn) {
1231
+ if (failOn === "never") return false;
1232
+ if (!isLeak(f)) return false;
1233
+ return failOn === "leak" || f.severity === "critical";
1234
+ }
1235
+ function markdown(r, fixes, project, failed) {
1236
+ const s = summarize(r);
1237
+ const lines = [
1238
+ `## ${failed ? "\u274C" : "\u2705"} RowProbe: ${s.leaks} leak${s.leaks === 1 ? "" : "s"} in ${project}`,
1239
+ "",
1240
+ `${s.leaking} leaking \xB7 ${s.public} public \xB7 ${s.check} to check \xB7 ${s.safe} safe${s.untested ? ` \xB7 ${s.untested} not tested` : ""}`,
1241
+ "",
1242
+ `${s.attempts ?? 0} attacks tried, ${s.blocked ?? 0} blocked \xB7 ${s.tables} tables${s.buckets ? `, ${s.buckets} storage buckets` : ""}${s.functions ? `, ${s.functions} functions` : ""}`,
1243
+ ""
1244
+ ];
1245
+ if (r.findings.length) {
1246
+ lines.push("| Where | Severity | Problem |", "|---|---|---|");
1247
+ r.findings.forEach((f, i) => lines.push(`| \`${subjectOf(f)}\` | ${f.severity} | ${fixes?.[i]?.title ?? f.kind.replace(/_/g, " ")} |`));
1248
+ lines.push("");
1249
+ if (fixes) r.findings.forEach((f, i) => {
1250
+ const fx = fixes[i];
1251
+ if (fx) lines.push(`<details><summary><code>${subjectOf(f)}</code>: ${fx.title}</summary>`, "", fx.explanation, "", "```sql", fx.sql, "```", "</details>", "");
1252
+ });
1253
+ }
1254
+ if (r.leftovers.length) lines.push("### \u26A0 Test changes that couldn't be undone", "", "```sql", ...r.leftovers.map((l) => l.sql), "```");
1255
+ return lines.join("\n");
1256
+ }
1257
+ async function main() {
1258
+ const { flags, rest } = parseArgs(process.argv.slice(2));
1259
+ if (flags.version) {
1260
+ console.log(VERSION);
1261
+ return;
1262
+ }
1263
+ if (flags.help || rest[0] !== "scan") {
1264
+ console.log(HELP);
1265
+ process.exit(flags.help ? 0 : rest.length ? 2 : 0);
1266
+ }
1267
+ const opt = (flag, env) => (typeof flags[flag] === "string" ? flags[flag] : process.env[env] ?? "").trim();
1268
+ const url = opt("url", "SUPABASE_URL").replace(/\/+$/, "");
1269
+ const key = opt("key", "SUPABASE_ANON_KEY");
1270
+ const token = opt("token", "ROWPROBE_TOKEN");
1271
+ const api = (opt("api", "ROWPROBE_API") || "https://rowprobe.com").replace(/\/+$/, "");
1272
+ const failOn = opt("fail-on", "ROWPROBE_FAIL_ON") || "leak";
1273
+ const list = (s2) => s2.split(/[\s,]+/).map((x) => x.trim()).filter(Boolean);
1274
+ const users = {
1275
+ alice: { email: opt("alice-email", "ROWPROBE_ALICE_EMAIL"), password: opt("alice-password", "ROWPROBE_ALICE_PASSWORD") },
1276
+ bob: { email: opt("bob-email", "ROWPROBE_BOB_EMAIL"), password: opt("bob-password", "ROWPROBE_BOB_PASSWORD") }
1277
+ };
1278
+ const missing = [
1279
+ [url, "--url / SUPABASE_URL"],
1280
+ [key, "--key / SUPABASE_ANON_KEY"],
1281
+ [token, "--token / ROWPROBE_TOKEN"],
1282
+ [users.alice.email, "--alice-email"],
1283
+ [users.alice.password, "--alice-password"],
1284
+ [users.bob.email, "--bob-email"],
1285
+ [users.bob.password, "--bob-password"]
1286
+ ].filter(([v]) => !v).map(([, n]) => n);
1287
+ if (missing.length) fail(`Missing: ${missing.join(", ")}. Run "npx rowprobe --help".`);
1288
+ if (!["leak", "critical", "never"].includes(failOn)) fail(`--fail-on must be leak, critical or never`);
1289
+ if (key.startsWith("sb_secret_") || /"role"\s*:\s*"service_role"/.test(Buffer.from(key.split(".")[1] ?? "", "base64").toString())) {
1290
+ fail("That's a secret/service_role key. It bypasses all security rules, so the scan would prove nothing. Use the anon or publishable key.");
1291
+ }
1292
+ const check = await fetch(`${api}/api/ci/check`, { method: "POST", headers: { Authorization: `Bearer ${token}` } }).catch(() => null);
1293
+ const cj = await check?.json().catch(() => ({}));
1294
+ if (!check || !check.ok || !cj?.ok) fail(cj?.error ?? `Couldn't reach ${api} to check your CI token.`);
1295
+ const project = new URL(url).host;
1296
+ if (!flags.json) console.log(bold(`RowProbe ${VERSION}`) + dim(` scanning ${project}`));
1297
+ const alice = await signIn(url, key, users.alice.email, users.alice.password, "Alice");
1298
+ const bob = await signIn(url, key, users.bob.email, users.bob.password, "Bob");
1299
+ if (alice.id === bob.id) fail("Alice and Bob are the same account. Use two different test users.");
1300
+ let site = null;
1301
+ const siteUrl = opt("site", "ROWPROBE_SITE");
1302
+ if (siteUrl) {
1303
+ if (!flags.json) console.log(dim(` checking ${siteUrl} for leaked keys\u2026`));
1304
+ const r = await fetch(`${api}/api/site-scan`, {
1305
+ method: "POST",
1306
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
1307
+ body: JSON.stringify({ url: siteUrl, projectUrl: url })
1308
+ }).catch(() => null);
1309
+ const j = await r?.json().catch(() => ({}));
1310
+ site = r?.ok && j.check ? j : { findings: [], check: { area: "website", name: siteUrl, status: "untested", notes: [j?.error ?? "The website couldn't be checked."] }, hints: { tables: [], buckets: [], functions: [] } };
1311
+ if (!flags.json && !r?.ok) console.log(yellow(` ! website not checked: ${site.check.notes[0]}`));
1312
+ }
1313
+ const restClient = new Rest(url, key);
1314
+ const given = list(opt("tables", "ROWPROBE_TABLES"));
1315
+ const tables = given.length ? manualTables(given) : await discoverTables(restClient, [{ label: "alice", token: alice.token }]) ?? manualTables(await probeTables(restClient, { label: "alice", token: alice.token }, site?.hints.tables ?? []));
1316
+ if (!tables.length) fail("No tables found. Pass them with --tables a,b,c.");
1317
+ const result = await runScan(
1318
+ {
1319
+ url,
1320
+ key,
1321
+ tables,
1322
+ alice,
1323
+ bob,
1324
+ writeTests: !flags["no-write"],
1325
+ sharedTables: list(opt("shared", "ROWPROBE_SHARED")),
1326
+ deep: !flags["no-deep"],
1327
+ bucketHints: site?.hints.buckets,
1328
+ functionHints: site?.hints.functions,
1329
+ extraFindings: site?.findings,
1330
+ extraChecks: site ? [site.check] : void 0
1331
+ },
1332
+ { onTable: (t, st) => {
1333
+ if (!flags.json && typeof st === "object") console.log(` ${st.status === "safe" ? green("\u2713") : st.status === "untested" ? dim("\xB7") : st.status === "check" ? yellow("!") : red("\u2717")} ${t.padEnd(28)} ${dim(st.status)}`);
1334
+ } }
1335
+ );
1336
+ if (!flags.json) {
1337
+ for (const ck of result.checks ?? []) {
1338
+ const label = ck.area === "storage" ? `storage: ${ck.name}` : ck.area === "function" ? `${ck.name}()` : ck.area === "website" ? `website: ${ck.name}` : ck.name;
1339
+ console.log(` ${ck.status === "safe" ? green("\u2713") : ck.status === "untested" ? dim("\xB7") : ck.status === "check" ? yellow("!") : red("\u2717")} ${label.padEnd(28)} ${dim(ck.status)}`);
1340
+ }
1341
+ }
1342
+ let fixes = null;
1343
+ if (!flags["no-fixes"] && result.findings.length) {
1344
+ const r = await fetch(`${api}/api/fixes`, {
1345
+ method: "POST",
1346
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
1347
+ body: JSON.stringify({ findings: result.findings.map(({ area, table, kind, severity, count, ownerCol, tenantCol, view, pk, columns, column, detail }) => ({ area, table, kind, severity, count, ownerCol, tenantCol, view, pk, columns, column, detail })) })
1348
+ }).catch(() => null);
1349
+ if (r?.ok) fixes = (await r.json()).fixes;
1350
+ }
1351
+ const failedFindings = result.findings.filter((f) => failing(f, failOn));
1352
+ const failed = failedFindings.length > 0;
1353
+ const s = summarize(result);
1354
+ if (process.env.GITHUB_STEP_SUMMARY) {
1355
+ try {
1356
+ appendFileSync(process.env.GITHUB_STEP_SUMMARY, markdown(result, fixes, project, failed) + "\n");
1357
+ } catch {
1358
+ }
1359
+ }
1360
+ if (flags.json) {
1361
+ console.log(JSON.stringify({ version: VERSION, project, summary: s, failed, findings: result.findings.map((f, i) => ({ ...f, fix: fixes?.[i] ?? null })), leftovers: result.leftovers }, null, 2));
1362
+ } else {
1363
+ console.log("");
1364
+ console.log(dim(`${s.attempts ?? 0} attacks tried, ${s.blocked ?? 0} blocked by your rules.`));
1365
+ if (!result.findings.length) console.log(green(bold(`\u2713 No leaks found in ${s.total} places tested.`)));
1366
+ for (const [i, f] of result.findings.entries()) {
1367
+ const tag = f.severity === "critical" || f.severity === "high" ? red(f.severity.toUpperCase()) : yellow("CHECK");
1368
+ console.log(`${tag} ${bold(subjectOf(f))} ${fixes?.[i]?.title ?? f.kind.replace(/_/g, " ")}`);
1369
+ if (fixes?.[i]) console.log(dim(fixes[i].explanation));
1370
+ }
1371
+ if (result.leftovers.length) {
1372
+ console.log(yellow(`
1373
+ \u26A0 ${result.leftovers.length} test change(s) couldn't be undone. Run:`));
1374
+ result.leftovers.forEach((l) => console.log(" " + l.sql));
1375
+ }
1376
+ console.log("");
1377
+ console.log(failed ? red(bold(`\u2717 ${failedFindings.length} leak(s) found. Failing (--fail-on ${failOn}).`)) : green(bold("\u2713 RowProbe check passed.")));
1378
+ if (fixes && result.findings.length) console.log(dim("Full SQL fixes are in the GitHub job summary, or run with --json."));
1379
+ }
1380
+ process.exit(failed ? 1 : 0);
1381
+ }
1382
+ main().catch((e) => fail(e instanceof Error ? e.message : String(e)));