sodabase 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,52 @@
1
- # Temporary Holding Version
1
+ # sodabase (v2 CLI)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The `npx sodabase` interactive onboarding wizard — the real, shippable package.
4
+ Design: `docs/specs/v2-cli-onboarding-spec.md` (planning repo). Proven first as the
5
+ zero-dep spike in that repo's `scripts/cli-wizard-spike/`; this is the Ink/TS port.
6
+
7
+ > **Status: scaffold.** Toolchain + API client + token store are in; the flow screens
8
+ > are being built on top. Lands behind the spec's §9 gates; **not published** (`private: true`).
9
+
10
+ ## Stack
11
+
12
+ Ink 7 + React 19 + TypeScript (Node ≥22). Deliberately dep-light: native `fetch`,
13
+ `child_process` for opening a browser, a `0600` config file for the token (no native
14
+ keychain), `useInput` for pickers (no extra component libs), and `tsc` for the build
15
+ (no bundler).
16
+
17
+ ## Develop
18
+
19
+ ```bash
20
+ cd cli
21
+ npm install
22
+ npm run typecheck # tsc --noEmit
23
+ npm run build # -> dist/
24
+ node dist/cli.js # run the built CLI
25
+ # or, no build step:
26
+ npm run dev # node --experimental-strip-types src/cli.tsx
27
+ ```
28
+
29
+ Point at a local backend with `SODABASE_API_URL=http://localhost:8080`.
30
+
31
+ ## Layout
32
+
33
+ ```
34
+ src/
35
+ cli.tsx entry — renders <App/>
36
+ app.tsx the Ink app (flow orchestrator + screens)
37
+ api/
38
+ client.ts HTTP client for the real endpoints (device grant, onboarding
39
+ job poll, connections, relevance, scan report)
40
+ types.ts wire types
41
+ config/
42
+ tokenStore.ts 0600 credential file
43
+ ```
44
+
45
+ ## What backs each step (all real endpoints)
46
+
47
+ - **Sign-in:** OAuth device grant (`/oauth/device_authorization` + `/oauth/token`) — PR #383.
48
+ - **Connect:** Supabase authorize + poll `GET /connections`.
49
+ - **Discover / monitors / scan:** trigger + poll the server-side onboarding job
50
+ (`POST`/`GET /onboarding/jobs/{id}`, per-step `steps[]`).
51
+ - **Scope:** onboard-then-adjust via `confirm`/`decline_proposals`.
52
+ - **MCP install:** consented in-flow `add-mcp -a <chosen>`.
@@ -0,0 +1,230 @@
1
+ // Real HTTP client for the Sodabase /api/v1 API. Native fetch only (Node 22) — no deps.
2
+ // The CLI is a GoTrue client: every /api/v1 call carries Authorization: Bearer <GoTrue JWT>.
3
+ // NOTE: this is NOT the mcp_oauth device-grant token (that targets the MCP server, a
4
+ // different audience, and /api/v1 rejects it). See signIn()'s TODO(gotrue-auth).
5
+ import { spawn } from "node:child_process";
6
+ import { existsSync, readFileSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { emailOtpStart, emailOtpVerify, loopbackSignIn, resolveGoTrueConfig } from "./gotrueAuth.js";
9
+ import { ApiError, } from "./types.js";
10
+ export const MCP_URL = "https://sodabase.io/mcp";
11
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
12
+ /** Open a URL in the user's default browser (best-effort; the URL is also shown as text). */
13
+ function openUrl(url) {
14
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
15
+ try {
16
+ spawn(cmd, [url], { stdio: "ignore", detached: true, shell: process.platform === "win32" }).unref();
17
+ }
18
+ catch {
19
+ /* best-effort */
20
+ }
21
+ }
22
+ export class SodabaseClient {
23
+ site;
24
+ api;
25
+ bearer;
26
+ constructor(opts = {}) {
27
+ this.site = (opts.baseUrl ?? process.env.SODABASE_API_URL ?? "https://sodabase.io").replace(/\/$/, "");
28
+ this.api = `${this.site}/api/v1`;
29
+ this.bearer = opts.bearer;
30
+ }
31
+ setBearer(token) {
32
+ this.bearer = token;
33
+ }
34
+ // ── Leg 1: GoTrue sign-in (loopback PKCE → aud="authenticated" session) ──────
35
+ async signIn(provider) {
36
+ // Matches the web app's @supabase/ssr PKCE flow, driven from a loopback redirect.
37
+ // Config + the one-time redirect-allowlist requirement live in gotrueAuth.ts.
38
+ const cfg = resolveGoTrueConfig();
39
+ const session = await loopbackSignIn(provider ? { ...cfg, provider } : cfg);
40
+ this.bearer = session.accessToken;
41
+ return session;
42
+ }
43
+ // ── Leg 1 (alt): browserless email one-time-code sign-in (no loopback, no PKCE) ──
44
+ async emailOtpStart(email) {
45
+ await emailOtpStart(resolveGoTrueConfig(), email);
46
+ }
47
+ async emailOtpVerify(email, code) {
48
+ const session = await emailOtpVerify(resolveGoTrueConfig(), email, code);
49
+ this.bearer = session.accessToken;
50
+ return session;
51
+ }
52
+ // ── Local: detect the Supabase project from the cwd ─────────────────────────
53
+ async detectProject() {
54
+ const cwd = process.cwd();
55
+ let projectRef = "unknown";
56
+ const configToml = join(cwd, "supabase", "config.toml");
57
+ if (existsSync(configToml)) {
58
+ const m = /project_id\s*=\s*"([^"]+)"/.exec(readFileSync(configToml, "utf8"));
59
+ if (m?.[1])
60
+ projectRef = m[1];
61
+ }
62
+ let framework = "unknown";
63
+ const pkg = join(cwd, "package.json");
64
+ if (existsSync(pkg)) {
65
+ try {
66
+ const deps = JSON.parse(readFileSync(pkg, "utf8"));
67
+ if (deps.dependencies?.["@supabase/supabase-js"])
68
+ framework = "@supabase/supabase-js";
69
+ if (deps.dependencies?.next)
70
+ framework = "Next.js + @supabase/supabase-js";
71
+ }
72
+ catch {
73
+ /* a malformed package.json in the cwd must not crash boot — detection is best-effort */
74
+ }
75
+ }
76
+ return { directory: cwd, framework, projectRef, database: "Supabase Postgres" };
77
+ }
78
+ // ── Leg 2: Supabase connect via the HOSTED handback (Supabase requires an HTTPS public-host
79
+ // redirect, so no loopback). start(redirect_uri = hosted handback) → browser authorizes →
80
+ // Supabase redirects to sodabase.io/.../cli-handback (stashes code+state) → the CLI polls
81
+ // cli-complete with its OWN Bearer; the backend exchanges + creates server-side. The raw
82
+ // Supabase code never reaches the CLI.
83
+ handbackUrl() {
84
+ // MUST equal the backend's allowlisted value (connect_service.cli_handback_redirect_uri,
85
+ // derived from SITE_URL) and be registered on the Supabase OAuth app.
86
+ return `${this.api}/connections/supabase/cli-handback`;
87
+ }
88
+ async startConnect(redirectUri) {
89
+ const r = await this.post("/connections/supabase/start", { redirect_uri: redirectUri });
90
+ return { authorizeUrl: r.authorize_url };
91
+ }
92
+ /** One poll of cli-complete. `pending` → keep polling; otherwise the connection is created (or, when the org
93
+ * was already connected, the existing one is returned with `already_connected`). */
94
+ async cliComplete(state) {
95
+ const r = await this.post("/connections/supabase/cli-complete", { state });
96
+ return {
97
+ status: r.status,
98
+ ...(r.connection_id ? { connectionId: r.connection_id } : {}),
99
+ ...(r.already_connected ? { alreadyConnected: true } : {}),
100
+ };
101
+ }
102
+ async connect() {
103
+ const { authorizeUrl } = await this.startConnect(this.handbackUrl());
104
+ const state = new URL(authorizeUrl).searchParams.get("state");
105
+ if (!state)
106
+ throw new ApiError("authorize URL is missing state", 500, "connect");
107
+ openUrl(authorizeUrl);
108
+ const deadline = Date.now() + 5 * 60_000; // give the user time to approve in the browser
109
+ // Serialize polls (await each before the next) per the cli-complete polling contract — overlapping
110
+ // in-flight polls can race the take-before-exchange window.
111
+ let seenPending = false;
112
+ for (;;) {
113
+ let r;
114
+ try {
115
+ r = await this.cliComplete(state);
116
+ }
117
+ catch (e) {
118
+ // Contract: a 400 AFTER a prior 'pending' means a poll likely consumed the state mid-exchange —
119
+ // the connect may have completed. Surface that instead of a hard failure, rather than crash.
120
+ if (seenPending && e instanceof ApiError && e.status === 400) {
121
+ throw new ApiError("Connection may have completed — re-run `sodabase` to resume, or check your dashboard.", 409, "maybe_completed");
122
+ }
123
+ throw e;
124
+ }
125
+ if (r.connectionId)
126
+ return { connectionId: r.connectionId, ...(r.alreadyConnected ? { alreadyConnected: true } : {}) };
127
+ seenPending = true; // status was "pending"
128
+ if (Date.now() > deadline) {
129
+ throw new ApiError("timed out waiting for Supabase authorization in the browser", 408, "timeout");
130
+ }
131
+ await sleep(2000);
132
+ }
133
+ }
134
+ async listProjects(connectionId) {
135
+ const rows = await this.get(`/connections/${encodeURIComponent(connectionId)}/projects`);
136
+ return rows.map((p) => ({
137
+ id: p.id,
138
+ ref: p.ref,
139
+ name: p.name,
140
+ status: p.status ?? "",
141
+ ...(p.region ? { region: p.region } : {}),
142
+ ...(p.already_connected_elsewhere ? { alreadyConnectedElsewhere: true } : {}),
143
+ ...(p.already_watched ? { watching: true } : {}),
144
+ }));
145
+ }
146
+ // ── Status: the workspace's watched projects + live open-issue counts ────────
147
+ async dashboardProjects() {
148
+ const rows = await this.get("/projects");
149
+ return rows.map((p) => ({
150
+ ref: p.ref,
151
+ name: p.name,
152
+ openIssues: p.open_issues ?? 0,
153
+ dataQualityIssues: p.data_quality_issues ?? 0,
154
+ watched: p.watched ?? 0,
155
+ status: p.status ?? "ready",
156
+ }));
157
+ }
158
+ // ── The server-side onboarding job ──────────────────────────────────────────
159
+ async enqueueOnboarding(connectionId, projectRef) {
160
+ return this.post("/onboarding/jobs", {
161
+ connection_id: connectionId,
162
+ project_ref: projectRef,
163
+ slack_alerting: true,
164
+ email_alerting: true,
165
+ });
166
+ }
167
+ async jobStatus(jobId) {
168
+ return this.get(`/onboarding/jobs/${encodeURIComponent(jobId)}`);
169
+ }
170
+ // ── Scope: relevance (onboard-then-adjust; operates on monitor ids) ──────────
171
+ async proposals() {
172
+ return this.get("/relevance/proposals");
173
+ }
174
+ async confirmProposals(monitorIds) {
175
+ await this.post("/relevance/proposals/confirm", { monitor_ids: monitorIds });
176
+ }
177
+ async declineProposals(monitorIds) {
178
+ await this.post("/relevance/proposals/decline", { monitor_ids: monitorIds });
179
+ }
180
+ // ── Local: consented in-flow MCP install via add-mcp ────────────────────────
181
+ async installMcp(agents) {
182
+ // `-y` on npx skips its first-run "install add-mcp?" prompt; `-y` on add-mcp skips ITS confirmation. We run
183
+ // non-interactively (stdio is not a TTY), so without BOTH, add-mcp blocks on a prompt it can never get and
184
+ // the install silently does nothing. (`-g -a <agent>` is add-mcp's global + per-agent targeting.)
185
+ const args = ["-y", "add-mcp", MCP_URL, "-g", ...agents.flatMap((a) => ["-a", a]), "-y"];
186
+ const command = `npx ${args.join(" ")}`;
187
+ await new Promise((resolve, reject) => {
188
+ let stderr = "";
189
+ // On Windows npx is `npx.cmd`, only resolvable via the shell (args are a fixed constant list — no injection).
190
+ const child = spawn("npx", args, { stdio: ["ignore", "ignore", "pipe"], shell: process.platform === "win32" });
191
+ child.stderr?.on("data", (d) => (stderr += String(d)));
192
+ child.on("error", reject);
193
+ child.on("exit", (code) => code === 0
194
+ ? resolve()
195
+ : reject(new Error(`add-mcp exited ${code}${stderr ? `: ${stderr.trim().split("\n").slice(-2).join("; ")}` : ""}`)));
196
+ });
197
+ const paths = {
198
+ "claude-code": "~/.claude.json",
199
+ cursor: "~/.cursor/mcp.json",
200
+ codex: "~/.codex/config.toml",
201
+ };
202
+ return { command, wrote: agents.map((a) => ({ agent: a, path: paths[a] ?? "~/.config/<agent>" })) };
203
+ }
204
+ // Note: no scanReport/illustrativeFindings — the data-trust surface is MCP-only, there is
205
+ // no /api/v1 route returning scan findings. The Findings screen shows status + a link.
206
+ // ── low-level helpers ───────────────────────────────────────────────────────
207
+ authHeaders() {
208
+ return this.bearer ? { authorization: `Bearer ${this.bearer}` } : {};
209
+ }
210
+ async get(path) {
211
+ return this.parse(await fetch(`${this.api}${path}`, { headers: this.authHeaders() }));
212
+ }
213
+ async post(path, json) {
214
+ const init = { method: "POST", headers: { ...this.authHeaders() } };
215
+ if (json !== undefined) {
216
+ init.headers["content-type"] = "application/json";
217
+ init.body = JSON.stringify(json);
218
+ }
219
+ return this.parse(await fetch(`${this.api}${path}`, init));
220
+ }
221
+ async parse(res) {
222
+ const text = await res.text();
223
+ const body = text ? JSON.parse(text) : {};
224
+ if (!res.ok) {
225
+ const b = body;
226
+ throw new ApiError(String(b.error_description ?? b.detail ?? res.statusText), res.status, b.error);
227
+ }
228
+ return body;
229
+ }
230
+ }
@@ -0,0 +1,130 @@
1
+ // Offline stand-in for the real Services (used by `sodabase --demo`). Scripted data +
2
+ // small delays. Lets the full flow run with no backend — a hands-off/interactive
3
+ // playthrough and the UI test harness. Matches the real /api/v1 shapes.
4
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
5
+ const JOB_STEPS = [
6
+ { name: "Map schema & relationships", detail: "reltuples-first; no table scans" },
7
+ { name: "Set up freshness monitors", detail: "4 core tables" },
8
+ { name: "Set up volume monitors", detail: "row_count baselines" },
9
+ { name: "Run day-1 quality scan", detail: "missing · invalid · duplicate (async)" },
10
+ { name: "Set up flow monitors", detail: "no partitioned tables — skipped", skip: true },
11
+ { name: "Establish baselines", detail: "alerts quiet for 24h warm-up" },
12
+ { name: "Build trust dashboard", detail: "" },
13
+ ];
14
+ export class FakeClient {
15
+ fast;
16
+ jobIdx = 0;
17
+ constructor(opts = {}) {
18
+ this.fast = opts.fast ?? false;
19
+ }
20
+ tick(ms) {
21
+ return sleep(Math.round(ms * (this.fast ? 0.12 : 1)));
22
+ }
23
+ async detectProject() {
24
+ await this.tick(700);
25
+ return {
26
+ directory: "project-supabase",
27
+ framework: "Next.js + @supabase/supabase-js",
28
+ projectRef: "supabase-demo",
29
+ database: "Postgres 17 · Supavisor pooler reachable",
30
+ };
31
+ }
32
+ async signIn(_provider) {
33
+ await this.tick(800);
34
+ return { accessToken: "demo.gotrue.jwt", expiresAt: Date.now() + 3600_000 };
35
+ }
36
+ async emailOtpStart(_email) {
37
+ // No real email in demo — just a short beat before the "enter the code" step.
38
+ await this.tick(600);
39
+ }
40
+ async emailOtpVerify(_email, _code) {
41
+ await this.tick(800);
42
+ return { accessToken: "demo.gotrue.jwt", expiresAt: Date.now() + 3600_000 };
43
+ }
44
+ setBearer() {
45
+ /* no-op in demo */
46
+ }
47
+ async connect() {
48
+ // No real browser in demo — just simulate the authorize + callback round-trip.
49
+ await this.tick(900);
50
+ return { connectionId: "conn_demo" };
51
+ }
52
+ async listProjects(_connectionId) {
53
+ await this.tick(500);
54
+ return [
55
+ { id: "prj_1", ref: "supabase-demo", name: "Supabase Demo", status: "ACTIVE_HEALTHY" },
56
+ { id: "prj_2", ref: "analytics", name: "Analytics", status: "ACTIVE_HEALTHY", watching: true },
57
+ { id: "prj_3", ref: "staging", name: "Staging", status: "INACTIVE" },
58
+ ];
59
+ }
60
+ async enqueueOnboarding() {
61
+ await this.tick(300);
62
+ this.jobIdx = 0;
63
+ return { id: "job_demo", status: "queued" };
64
+ }
65
+ async dashboardProjects() {
66
+ await this.tick(300);
67
+ return [
68
+ { ref: "supabase-demo", name: "Supabase Demo", openIssues: 2, dataQualityIssues: 13, watched: 7, status: "ready" },
69
+ { ref: "analytics", name: "Analytics", openIssues: 0, dataQualityIssues: 0, watched: 4, status: "ready" },
70
+ ];
71
+ }
72
+ async jobStatus(jobId) {
73
+ await this.tick(650);
74
+ const done = this.jobIdx;
75
+ this.jobIdx += 1;
76
+ const steps = JOB_STEPS.map((s, i) => ({
77
+ name: s.name,
78
+ detail: s.detail,
79
+ status: s.skip ? "skipped" : i < done ? "done" : i === done ? "running" : "pending",
80
+ }));
81
+ const finished = done >= JOB_STEPS.length;
82
+ return {
83
+ id: jobId,
84
+ status: finished ? "done" : "running",
85
+ step: finished ? null : (JOB_STEPS[done]?.name ?? null),
86
+ steps,
87
+ error: null,
88
+ };
89
+ }
90
+ async proposals() {
91
+ await this.tick(500);
92
+ return {
93
+ enabled: true,
94
+ total_datasets: 34,
95
+ proposals: [
96
+ { id: "m1", dataset: "public.orders", type: "freshness", reason: "high write rate", row_estimate: 1_420_000 },
97
+ { id: "m2", dataset: "public.orders", type: "row_count", reason: "core table", row_estimate: 1_420_000 },
98
+ { id: "m3", dataset: "public.payments", type: "freshness", reason: "high write rate", row_estimate: 1_390_000 },
99
+ { id: "m4", dataset: "public.events", type: "row_count", reason: "append-only", row_estimate: 22_700_000 },
100
+ ],
101
+ others: [{ id: "d9", dataset: "public.feature_flags", row_estimate: 36 }],
102
+ };
103
+ }
104
+ async confirmProposals() {
105
+ await this.tick(400);
106
+ }
107
+ async declineProposals() {
108
+ await this.tick(400);
109
+ }
110
+ async installMcp(agents) {
111
+ await this.tick(500);
112
+ const paths = {
113
+ "claude-code": "~/.claude.json",
114
+ cursor: "~/.cursor/mcp.json",
115
+ codex: "~/.codex/config.toml",
116
+ };
117
+ return {
118
+ command: `npx add-mcp https://sodabase.io/mcp -g ${agents.map((a) => "-a " + a).join(" ")}`,
119
+ wrote: agents.map((a) => ({ agent: a, path: paths[a] ?? "~/.config/<agent>" })),
120
+ };
121
+ }
122
+ async illustrativeFindings() {
123
+ await this.tick(500);
124
+ return [
125
+ { column: "public.orders.customer_email", family: "missing", detail: "3.2% missing on last-24h rows", severity: "bad" },
126
+ { column: "public.payments.idempotency_key", family: "duplicate", detail: "11 duplicate keys in the last hour", severity: "warn" },
127
+ { column: "public.events", family: "healthy", detail: "Flowing on schedule — within baseline", severity: "ok" },
128
+ ];
129
+ }
130
+ }
@@ -0,0 +1,160 @@
1
+ // GoTrue loopback sign-in (PKCE) — gets the CLI a Supabase session JWT (aud="authenticated"),
2
+ // the token /api/v1 requires. Mirrors the web app's @supabase/ssr PKCE flow, driven from a
3
+ // standalone binary via a 127.0.0.1 loopback redirect. Native http + crypto + fetch — no deps.
4
+ //
5
+ // Config (env, with a sane default URL):
6
+ // SODABASE_SUPABASE_URL / NEXT_PUBLIC_SUPABASE_URL (default: the control-plane project)
7
+ // SODABASE_SUPABASE_ANON_KEY / NEXT_PUBLIC_SUPABASE_ANON_KEY (publishable key — REQUIRED)
8
+ // SODABASE_AUTH_PROVIDER (default: github; e.g. google)
9
+ //
10
+ // ONE-TIME SETUP (owner): add http://127.0.0.1:8976/callback to the Supabase project's
11
+ // Auth → URL Configuration → Redirect URLs allowlist. Without it, GoTrue won't redirect back
12
+ // to the loopback and sign-in times out.
13
+ import { spawn } from "node:child_process";
14
+ import { createHash, randomBytes } from "node:crypto";
15
+ import { createServer } from "node:http";
16
+ import { ApiError } from "./types.js";
17
+ const DEFAULT_SUPABASE_URL = "https://jxbfyuzqizsenxekupte.supabase.co";
18
+ // The anon key is PUBLIC by design — RLS-protected, and the web app already ships it in client JS as
19
+ // NEXT_PUBLIC_SUPABASE_ANON_KEY. Baking the default (the "Soda Supabase" control-plane project's anon key) so
20
+ // `npx sodabase` works with zero env setup; SODABASE_SUPABASE_ANON_KEY / NEXT_PUBLIC_… still override for dev
21
+ // against another project. NOT a secret — do not treat as one.
22
+ const DEFAULT_SUPABASE_ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imp4YmZ5dXpxaXpzZW54ZWt1cHRlIiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODkzNzQzNDUsImV4cCI6MjEwNDk1MDM0NX0.ahdAbYaIRZXr8awIBG-W7soWLahtLISSrIzl243Xuas";
23
+ export const LOOPBACK_PORT = 8976;
24
+ export const LOOPBACK_REDIRECT = `http://127.0.0.1:${LOOPBACK_PORT}/callback`;
25
+ const b64url = (buf) => buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
26
+ function openUrl(url) {
27
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
28
+ try {
29
+ spawn(cmd, [url], { stdio: "ignore", detached: true, shell: process.platform === "win32" }).unref();
30
+ }
31
+ catch {
32
+ /* best-effort — the URL is surfaced via onUrl too */
33
+ }
34
+ }
35
+ export function resolveGoTrueConfig() {
36
+ // Deliberately NOT falling back to NEXT_PUBLIC_SUPABASE_URL/ANON_KEY: the CLI is run inside a customer's own
37
+ // Supabase/Next.js project dir (it reads supabase/config.toml + package.json there), where those vars point at
38
+ // the CUSTOMER's project — sign-in would target the wrong GoTrue and then 401 against sodabase.io. Only an
39
+ // explicit SODABASE_* override (dev) or the baked control-plane default is used.
40
+ const supabaseUrl = (process.env.SODABASE_SUPABASE_URL || DEFAULT_SUPABASE_URL).replace(/\/$/, "");
41
+ const anonKey = process.env.SODABASE_SUPABASE_ANON_KEY || DEFAULT_SUPABASE_ANON_KEY;
42
+ const provider = process.env.SODABASE_AUTH_PROVIDER || "github";
43
+ return { supabaseUrl, anonKey, provider };
44
+ }
45
+ /** The anon-key headers every GoTrue auth endpoint requires (publishable key, not the session). */
46
+ function anonHeaders(anonKey) {
47
+ return { apikey: anonKey, authorization: `Bearer ${anonKey}`, "content-type": "application/json" };
48
+ }
49
+ /** Guard: the publishable anon key is required to talk to GoTrue at all. */
50
+ function requireAnonKey(cfg) {
51
+ if (!cfg.anonKey) {
52
+ throw new ApiError("Missing Supabase anon key. Set SODABASE_SUPABASE_ANON_KEY (the project's publishable key).", 400, "config");
53
+ }
54
+ }
55
+ /** Map a GoTrue token-endpoint body to our Session (shared by every grant: pkce + email OTP). */
56
+ function sessionFromTokenBody(body) {
57
+ return {
58
+ accessToken: body.access_token,
59
+ ...(typeof body.refresh_token === "string" ? { refreshToken: body.refresh_token } : {}),
60
+ ...(typeof body.expires_in === "number" ? { expiresAt: Date.now() + body.expires_in * 1000 } : {}),
61
+ };
62
+ }
63
+ /** Run the loopback PKCE flow and return a GoTrue session. */
64
+ export async function loopbackSignIn(cfg = resolveGoTrueConfig(), opts = {}) {
65
+ requireAnonKey(cfg);
66
+ const verifier = b64url(randomBytes(48));
67
+ const challenge = b64url(createHash("sha256").update(verifier).digest());
68
+ // `state` is echoed back by GoTrue — we require it to match so a stray/forged hit on the fixed loopback port
69
+ // can't pre-empt the real redirect (defense in depth; PKCE already prevents an injected-code takeover).
70
+ const state = b64url(randomBytes(16));
71
+ const authorizeUrl = `${cfg.supabaseUrl}/auth/v1/authorize?provider=${encodeURIComponent(cfg.provider)}` +
72
+ `&redirect_to=${encodeURIComponent(LOOPBACK_REDIRECT)}` +
73
+ `&state=${state}` +
74
+ `&code_challenge=${challenge}&code_challenge_method=s256`;
75
+ const code = await new Promise((resolve, reject) => {
76
+ const server = createServer((req, res) => {
77
+ const u = new URL(req.url ?? "/", LOOPBACK_REDIRECT);
78
+ if (u.pathname !== "/callback") {
79
+ res.writeHead(404);
80
+ res.end();
81
+ return;
82
+ }
83
+ // Ignore any callback that isn't ours (missing/mismatched state) — don't let it resolve or reject; keep
84
+ // waiting for the real redirect (or the timeout).
85
+ if (u.searchParams.get("state") !== state) {
86
+ res.writeHead(404);
87
+ res.end();
88
+ return;
89
+ }
90
+ const c = u.searchParams.get("code");
91
+ const err = u.searchParams.get("error_description") || u.searchParams.get("error");
92
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
93
+ res.end(`<!doctype html><meta charset="utf-8"><body style="font-family:system-ui;padding:3rem;text-align:center">` +
94
+ `<h2>${c ? "Signed in ✓" : "Sign-in failed"}</h2>` +
95
+ `<p>${c ? "You can close this tab and return to your terminal." : err || "No code returned."}</p></body>`);
96
+ clearTimeout(timer); // always clear so the process doesn't linger on the 3-min timer after sign-in
97
+ server.close();
98
+ if (c)
99
+ resolve(c);
100
+ else
101
+ reject(new ApiError(err || "sign-in failed", 401, "oauth"));
102
+ });
103
+ const timer = setTimeout(() => {
104
+ server.close();
105
+ reject(new ApiError(`Timed out waiting for sign-in. Is ${LOOPBACK_REDIRECT} in the Supabase Auth redirect allowlist?`, 408, "timeout"));
106
+ }, opts.timeoutMs ?? 180_000);
107
+ server.on("error", (e) => {
108
+ clearTimeout(timer);
109
+ reject(new ApiError(`loopback server failed (port ${LOOPBACK_PORT} in use?): ${String(e)}`, 500, "loopback"));
110
+ });
111
+ server.listen(LOOPBACK_PORT, "127.0.0.1", () => (opts.onUrl ?? openUrl)(authorizeUrl));
112
+ });
113
+ // Exchange the PKCE code for a GoTrue session.
114
+ const res = await fetch(`${cfg.supabaseUrl}/auth/v1/token?grant_type=pkce`, {
115
+ method: "POST",
116
+ headers: anonHeaders(cfg.anonKey),
117
+ body: JSON.stringify({ auth_code: code, code_verifier: verifier }),
118
+ });
119
+ const body = (await res.json().catch(() => ({})));
120
+ if (!res.ok || typeof body.access_token !== "string") {
121
+ throw new ApiError(String(body.error_description ?? body.msg ?? "token exchange failed"), res.status, String(body.error ?? ""));
122
+ }
123
+ return sessionFromTokenBody(body);
124
+ }
125
+ // ── Email one-time-code sign-in (browserless; no loopback, no PKCE) ───────────────
126
+ // GoTrue's email OTP grant: POST /otp emails a code, POST /verify trades the typed code
127
+ // for a session. Two plain fetches, same anon-key headers — nothing to spin up locally.
128
+ //
129
+ // ONE-TIME SETUP (owner, Supabase dashboard): (a) email auth enabled; (b) the Auth email
130
+ // template must emit a numeric CODE via `{{ .Token }}` — Supabase's default template sends a
131
+ // magic LINK ({{ .ConfirmationURL }}), which a typed-code flow can't use; (c) ideally custom
132
+ // SMTP (Resend) so delivery + rate limits are production-grade rather than the shared sandbox.
133
+ /** Start the email OTP flow: GoTrue emails a one-time code (create_user so new emails work). */
134
+ export async function emailOtpStart(cfg, email) {
135
+ requireAnonKey(cfg);
136
+ const res = await fetch(`${cfg.supabaseUrl}/auth/v1/otp`, {
137
+ method: "POST",
138
+ headers: anonHeaders(cfg.anonKey),
139
+ body: JSON.stringify({ email, create_user: true }),
140
+ });
141
+ if (!res.ok) {
142
+ const body = (await res.json().catch(() => ({})));
143
+ throw new ApiError(String(body.error_description ?? body.msg ?? "could not send the sign-in code"), res.status, String(body.error ?? ""));
144
+ }
145
+ }
146
+ /** Verify the typed one-time code and return a GoTrue session. Throws ApiError on a bad/expired
147
+ * code or a 429 rate-limit, carrying GoTrue's own message + HTTP status for the UI to surface. */
148
+ export async function emailOtpVerify(cfg, email, token) {
149
+ requireAnonKey(cfg);
150
+ const res = await fetch(`${cfg.supabaseUrl}/auth/v1/verify`, {
151
+ method: "POST",
152
+ headers: anonHeaders(cfg.anonKey),
153
+ body: JSON.stringify({ email, token, type: "email" }),
154
+ });
155
+ const body = (await res.json().catch(() => ({})));
156
+ if (!res.ok || typeof body.access_token !== "string") {
157
+ throw new ApiError(String(body.error_description ?? body.msg ?? "code verification failed"), res.status, String(body.error ?? ""));
158
+ }
159
+ return sessionFromTokenBody(body);
160
+ }
@@ -0,0 +1,15 @@
1
+ // Wire types for the Sodabase /api/v1 API, as the v2 CLI consumes them.
2
+ // Verified against the real route definitions on main. The CLI is a GoTrue client:
3
+ // every /api/v1 call needs Authorization: Bearer <GoTrue JWT, aud="authenticated">.
4
+ /** The single "issues" number the CLI shows = monitor signals + data-quality findings. */
5
+ export const totalIssues = (p) => p.openIssues + p.dataQualityIssues;
6
+ export class ApiError extends Error {
7
+ status;
8
+ code;
9
+ constructor(message, status, code) {
10
+ super(message);
11
+ this.status = status;
12
+ this.code = code;
13
+ this.name = "ApiError";
14
+ }
15
+ }
package/dist/app.js ADDED
@@ -0,0 +1,47 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Box } from "ink";
3
+ import { useCallback, useState } from "react";
4
+ import { clearProgress, saveProgress } from "./config/flowState.js";
5
+ import { AgentView, BootDetect, BrandBar, Connect, Findings, McpInstall, Report, ScopeAdjust, SignIn, WizardProvider, } from "./ui.js";
6
+ // Ordered flow. Names are the resume keys (index-independent).
7
+ const PHASES = [
8
+ { name: "boot", Comp: BootDetect },
9
+ { name: "signin", Comp: SignIn },
10
+ { name: "connect", Comp: Connect },
11
+ { name: "agent", Comp: AgentView },
12
+ { name: "scope", Comp: ScopeAdjust },
13
+ { name: "findings", Comp: Findings },
14
+ { name: "mcp", Comp: McpInstall },
15
+ { name: "report", Comp: Report },
16
+ ];
17
+ export function App({ services, fast, interactive, signedIn, demo, startPhase, initialCtx }) {
18
+ const startIndex = Math.max(0, startPhase ? PHASES.findIndex((p) => p.name === startPhase) : 0);
19
+ const [phase, setPhase] = useState(startIndex === -1 ? 0 : startIndex);
20
+ const [ctx, setCtx] = useState(initialCtx ?? {});
21
+ const onDone = useCallback((patch, opts) => {
22
+ setCtx((c) => {
23
+ const next = { ...c, ...patch };
24
+ setPhase((p) => {
25
+ // `to` jumps to a named phase (skipping intermediate steps, e.g. an already-watched project skips
26
+ // setup+scope); default is the next step. Never jump backwards.
27
+ const target = opts?.to ? PHASES.findIndex((ph) => ph.name === opts.to) : p + 1;
28
+ const nextIndex = target > p ? target : p + 1;
29
+ const nextPhase = PHASES[nextIndex];
30
+ // Persist resume state; clear once the flow reaches the terminal report.
31
+ if (!nextPhase || nextPhase.name === "report")
32
+ clearProgress();
33
+ else
34
+ saveProgress({
35
+ phase: nextPhase.name,
36
+ ...(next.projectRef ? { projectRef: next.projectRef } : {}),
37
+ ...(next.connectionId ? { connectionId: next.connectionId } : {}),
38
+ ...(next.alreadyWatching ? { alreadyWatching: true } : {}),
39
+ });
40
+ return nextIndex;
41
+ });
42
+ return next;
43
+ });
44
+ }, []);
45
+ const current = PHASES[phase];
46
+ return (_jsx(WizardProvider, { value: { services, fast, interactive, signedIn, demo }, children: _jsxs(Box, { flexDirection: "column", children: [_jsx(BrandBar, {}), current ? _jsx(current.Comp, { ctx: ctx, onDone: onDone }) : null] }) }));
47
+ }