sodabase 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,180 @@
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
+ // Branded sign-in result page served on the loopback -- the browser half of `npx sodabase`. Matches the
26
+ // connect-handback housestyle (IBM Plex, the dot-matrix mark, green = Sodabase, light + dark). Sign-in is
27
+ // only authentication -- nothing is connected yet -- so the mark holds still here; the moving "watching"
28
+ // scan is reserved for the connect handback, where the data connection is actually live.
29
+ const CALLBACK_MARK = '<circle cx="8.27" cy="1.2" r=".48"/><circle cx="9.47" cy="1.2" r=".48"/><circle cx="10.67" cy="1.2" r=".48"/><circle cx="7.07" cy="2.4" r=".48"/><circle cx="8.27" cy="2.4" r=".48"/><circle cx="9.47" cy="2.4" r=".48"/><circle cx="10.67" cy="2.4" r=".48"/><circle cx="11.87" cy="2.4" r=".48"/><circle cx="5.87" cy="3.6" r=".48"/><circle cx="7.07" cy="3.6" r=".48"/><circle cx="8.27" cy="3.6" r=".48"/><circle cx="9.47" cy="3.6" r=".48"/><circle cx="10.67" cy="3.6" r=".48"/><circle cx="11.87" cy="3.6" r=".48"/><circle cx="13.07" cy="3.6" r=".48"/><circle cx="5.87" cy="4.8" r=".48"/><circle cx="7.07" cy="4.8" r=".48"/><circle cx="8.27" cy="4.8" r=".48"/><circle cx="9.47" cy="4.8" r=".48"/><circle cx="10.67" cy="4.8" r=".48"/><circle cx="11.87" cy="4.8" r=".48"/><circle cx="13.07" cy="4.8" r=".48"/><circle cx="5.87" cy="6.0" r=".48"/><circle cx="7.07" cy="6.0" r=".48"/><circle cx="8.27" cy="6.0" r=".48"/><circle cx="9.47" cy="6.0" r=".48"/><circle cx="10.67" cy="6.0" r=".48"/><circle cx="11.87" cy="6.0" r=".48"/><circle cx="13.07" cy="6.0" r=".48"/><circle cx="7.07" cy="7.2" r=".48"/><circle cx="8.27" cy="7.2" r=".48"/><circle cx="9.47" cy="7.2" r=".48"/><circle cx="10.67" cy="7.2" r=".48"/><circle cx="11.87" cy="7.2" r=".48"/><circle cx="8.27" cy="8.4" r=".48"/><circle cx="9.47" cy="8.4" r=".48"/><circle cx="10.67" cy="8.4" r=".48"/><circle cx="8.27" cy="1.2" r=".48"/><circle cx="9.47" cy="1.2" r=".48"/><circle cx="10.67" cy="1.2" r=".48"/><circle cx="7.07" cy="2.4" r=".48"/><circle cx="8.27" cy="2.4" r=".48"/><circle cx="9.47" cy="2.4" r=".48"/><circle cx="10.67" cy="2.4" r=".48"/><circle cx="11.87" cy="2.4" r=".48"/><circle cx="5.87" cy="3.6" r=".48"/><circle cx="7.07" cy="3.6" r=".48"/><circle cx="8.27" cy="3.6" r=".48"/><circle cx="9.47" cy="3.6" r=".48"/><circle cx="10.67" cy="3.6" r=".48"/><circle cx="11.87" cy="3.6" r=".48"/><circle cx="13.07" cy="3.6" r=".48"/><circle cx="5.87" cy="4.8" r=".48"/><circle cx="7.07" cy="4.8" r=".48"/><circle cx="8.27" cy="4.8" r=".48"/><circle cx="9.47" cy="4.8" r=".48"/><circle cx="10.67" cy="4.8" r=".48"/><circle cx="11.87" cy="4.8" r=".48"/><circle cx="13.07" cy="4.8" r=".48"/><circle cx="5.87" cy="6.0" r=".48"/><circle cx="7.07" cy="6.0" r=".48"/><circle cx="8.27" cy="6.0" r=".48"/><circle cx="9.47" cy="6.0" r=".48"/><circle cx="10.67" cy="6.0" r=".48"/><circle cx="11.87" cy="6.0" r=".48"/><circle cx="13.07" cy="6.0" r=".48"/><circle cx="7.07" cy="7.2" r=".48"/><circle cx="8.27" cy="7.2" r=".48"/><circle cx="9.47" cy="7.2" r=".48"/><circle cx="14.8" cy="12.4" r=".48"/><circle cx="16.0" cy="12.4" r=".48"/><circle cx="17.2" cy="12.4" r=".48"/><circle cx="13.6" cy="13.6" r=".48"/><circle cx="14.8" cy="13.6" r=".48"/><circle cx="16.0" cy="13.6" r=".48"/><circle cx="17.2" cy="13.6" r=".48"/><circle cx="18.4" cy="13.6" r=".48"/><circle cx="12.4" cy="14.8" r=".48"/><circle cx="13.6" cy="14.8" r=".48"/><circle cx="14.8" cy="14.8" r=".48"/><circle cx="16.0" cy="14.8" r=".48"/><circle cx="17.2" cy="14.8" r=".48"/><circle cx="18.4" cy="14.8" r=".48"/><circle cx="19.6" cy="14.8" r=".48"/><circle cx="12.4" cy="16.0" r=".48"/><circle cx="13.6" cy="16.0" r=".48"/><circle cx="14.8" cy="16.0" r=".48"/><circle cx="16.0" cy="16.0" r=".48"/><circle cx="17.2" cy="16.0" r=".48"/><circle cx="18.4" cy="16.0" r=".48"/><circle cx="19.6" cy="16.0" r=".48"/><circle cx="12.4" cy="17.2" r=".48"/><circle cx="13.6" cy="17.2" r=".48"/><circle cx="14.8" cy="17.2" r=".48"/><circle cx="16.0" cy="17.2" r=".48"/><circle cx="17.2" cy="17.2" r=".48"/><circle cx="18.4" cy="17.2" r=".48"/><circle cx="19.6" cy="17.2" r=".48"/><circle cx="13.6" cy="18.4" r=".48"/><circle cx="14.8" cy="18.4" r=".48"/><circle cx="16.0" cy="18.4" r=".48"/><circle cx="17.2" cy="18.4" r=".48"/><circle cx="18.4" cy="18.4" r=".48"/><circle cx="14.8" cy="19.6" r=".48"/><circle cx="16.0" cy="19.6" r=".48"/><circle cx="17.2" cy="19.6" r=".48"/><circle cx="14.8" cy="12.4" r=".48"/><circle cx="16.0" cy="12.4" r=".48"/><circle cx="17.2" cy="12.4" r=".48"/><circle cx="13.6" cy="13.6" r=".48"/><circle cx="14.8" cy="13.6" r=".48"/><circle cx="16.0" cy="13.6" r=".48"/><circle cx="17.2" cy="13.6" r=".48"/><circle cx="18.4" cy="13.6" r=".48"/><circle cx="12.4" cy="14.8" r=".48"/><circle cx="13.6" cy="14.8" r=".48"/><circle cx="14.8" cy="14.8" r=".48"/><circle cx="16.0" cy="14.8" r=".48"/><circle cx="17.2" cy="14.8" r=".48"/><circle cx="18.4" cy="14.8" r=".48"/><circle cx="19.6" cy="14.8" r=".48"/><circle cx="12.4" cy="16.0" r=".48"/><circle cx="13.6" cy="16.0" r=".48"/><circle cx="14.8" cy="16.0" r=".48"/><circle cx="16.0" cy="16.0" r=".48"/><circle cx="17.2" cy="16.0" r=".48"/><circle cx="18.4" cy="16.0" r=".48"/><circle cx="19.6" cy="16.0" r=".48"/><circle cx="12.4" cy="17.2" r=".48"/><circle cx="13.6" cy="17.2" r=".48"/><circle cx="14.8" cy="17.2" r=".48"/><circle cx="16.0" cy="17.2" r=".48"/><circle cx="17.2" cy="17.2" r=".48"/><circle cx="18.4" cy="17.2" r=".48"/><circle cx="19.6" cy="17.2" r=".48"/><circle cx="13.6" cy="18.4" r=".48"/><circle cx="14.8" cy="18.4" r=".48"/><circle cx="16.0" cy="18.4" r=".48"/><circle cx="21.33" cy="23.6" r=".48"/><circle cx="22.53" cy="23.6" r=".48"/><circle cx="23.73" cy="23.6" r=".48"/><circle cx="20.13" cy="24.8" r=".48"/><circle cx="21.33" cy="24.8" r=".48"/><circle cx="22.53" cy="24.8" r=".48"/><circle cx="23.73" cy="24.8" r=".48"/><circle cx="24.93" cy="24.8" r=".48"/><circle cx="18.93" cy="26.0" r=".48"/><circle cx="20.13" cy="26.0" r=".48"/><circle cx="21.33" cy="26.0" r=".48"/><circle cx="22.53" cy="26.0" r=".48"/><circle cx="23.73" cy="26.0" r=".48"/><circle cx="24.93" cy="26.0" r=".48"/><circle cx="26.13" cy="26.0" r=".48"/><circle cx="18.93" cy="27.2" r=".48"/><circle cx="20.13" cy="27.2" r=".48"/><circle cx="21.33" cy="27.2" r=".48"/><circle cx="22.53" cy="27.2" r=".48"/><circle cx="23.73" cy="27.2" r=".48"/><circle cx="24.93" cy="27.2" r=".48"/><circle cx="26.13" cy="27.2" r=".48"/><circle cx="18.93" cy="28.4" r=".48"/><circle cx="20.13" cy="28.4" r=".48"/><circle cx="21.33" cy="28.4" r=".48"/><circle cx="22.53" cy="28.4" r=".48"/><circle cx="23.73" cy="28.4" r=".48"/><circle cx="24.93" cy="28.4" r=".48"/><circle cx="26.13" cy="28.4" r=".48"/><circle cx="20.13" cy="29.6" r=".48"/><circle cx="21.33" cy="29.6" r=".48"/><circle cx="22.53" cy="29.6" r=".48"/><circle cx="23.73" cy="29.6" r=".48"/><circle cx="24.93" cy="29.6" r=".48"/><circle cx="21.33" cy="30.8" r=".48"/><circle cx="22.53" cy="30.8" r=".48"/><circle cx="23.73" cy="30.8" r=".48"/><circle cx="21.33" cy="23.6" r=".48"/><circle cx="22.53" cy="23.6" r=".48"/><circle cx="23.73" cy="23.6" r=".48"/><circle cx="20.13" cy="24.8" r=".48"/><circle cx="21.33" cy="24.8" r=".48"/><circle cx="22.53" cy="24.8" r=".48"/><circle cx="23.73" cy="24.8" r=".48"/><circle cx="24.93" cy="24.8" r=".48"/><circle cx="18.93" cy="26.0" r=".48"/><circle cx="20.13" cy="26.0" r=".48"/><circle cx="21.33" cy="26.0" r=".48"/><circle cx="22.53" cy="26.0" r=".48"/><circle cx="23.73" cy="26.0" r=".48"/><circle cx="24.93" cy="26.0" r=".48"/><circle cx="26.13" cy="26.0" r=".48"/><circle cx="18.93" cy="27.2" r=".48"/><circle cx="20.13" cy="27.2" r=".48"/><circle cx="21.33" cy="27.2" r=".48"/><circle cx="22.53" cy="27.2" r=".48"/><circle cx="23.73" cy="27.2" r=".48"/><circle cx="24.93" cy="27.2" r=".48"/><circle cx="26.13" cy="27.2" r=".48"/><circle cx="18.93" cy="28.4" r=".48"/><circle cx="20.13" cy="28.4" r=".48"/><circle cx="21.33" cy="28.4" r=".48"/><circle cx="22.53" cy="28.4" r=".48"/><circle cx="23.73" cy="28.4" r=".48"/><circle cx="24.93" cy="28.4" r=".48"/><circle cx="26.13" cy="28.4" r=".48"/><circle cx="20.13" cy="29.6" r=".48"/><circle cx="21.33" cy="29.6" r=".48"/><circle cx="22.53" cy="29.6" r=".48"/>';
30
+ const CALLBACK_CSS = ':root{--bg:#f7f7f7;--ink:#0b0b0b;--muted:#6b6b6b;--green:#3CDC97;--accent:#ffc800;color-scheme:light dark}@media(prefers-color-scheme:dark){:root{--bg:#0b0b0b;--ink:#f5f5f5;--muted:#a3a3a3}}*{box-sizing:border-box}html,body{margin:0}body{min-height:100vh;min-height:100svh;display:grid;place-items:center;padding:24px 16px;font-family:"IBM Plex Sans",system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;color:var(--ink);background:var(--bg);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}::selection{background:var(--accent);color:#0b0b0b}.stage{display:flex;flex-direction:column;align-items:center;text-align:center;gap:16px;max-width:30rem;animation:rise .45s cubic-bezier(.23,1,.32,1) both}.mark{width:84px;height:84px;display:block}.mark circle{fill:var(--green)}.mark.muted circle{fill:var(--muted);opacity:.72}h1{margin:2px 0 0;font-size:24px;line-height:30px;font-weight:600;letter-spacing:-.02em}.lede{margin:4px auto 0;max-width:34ch;font-size:15px;line-height:22px;color:var(--muted)}@media(prefers-reduced-motion:no-preference){.mark.scan circle{transform-box:fill-box;transform-origin:center;animation:ob-scan 2.1s cubic-bezier(.23,1,.32,1) infinite;animation-delay:calc(var(--t,0) * -2.1s)}}@media(prefers-reduced-motion:reduce){.mark.scan circle{animation:ob-breathe 2.4s ease-in-out infinite}.stage{animation:none}}@keyframes rise{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none}}@keyframes ob-scan{0%{opacity:.18;transform:scale(1)}16%{opacity:1;transform:scale(1.28)}42%{opacity:.18;transform:scale(1)}100%{opacity:.18;transform:scale(1)}}@keyframes ob-breathe{0%,100%{opacity:.55}50%{opacity:.95}}';
31
+ const HTML_ESCAPES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
32
+ function escapeHtml(s) {
33
+ return s.replace(/[&<>"']/g, (c) => HTML_ESCAPES[c] ?? c);
34
+ }
35
+ /** The page served back after the OAuth redirect: signed-in (green mark) or a surfaced error (muted mark). */
36
+ function callbackPage(ok, message) {
37
+ return ("<!doctype html><html lang=en><head><meta charset=utf-8>" +
38
+ '<meta name=viewport content="width=device-width,initial-scale=1">' +
39
+ `<title>Sodabase</title><style>${CALLBACK_CSS}</style></head>` +
40
+ `<body><main class=stage><svg class="mark${ok ? "" : " muted"}" viewBox="0 0 32 32" aria-hidden="true">${CALLBACK_MARK}</svg>` +
41
+ `<h1>${ok ? "You\u2019re signed in" : "Sign-in didn\u2019t finish"}</h1>` +
42
+ `<p class=lede>${message}</p></main></body></html>`);
43
+ }
44
+ const b64url = (buf) => buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
45
+ function openUrl(url) {
46
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
47
+ try {
48
+ spawn(cmd, [url], { stdio: "ignore", detached: true, shell: process.platform === "win32" }).unref();
49
+ }
50
+ catch {
51
+ /* best-effort — the URL is surfaced via onUrl too */
52
+ }
53
+ }
54
+ export function resolveGoTrueConfig() {
55
+ // Deliberately NOT falling back to NEXT_PUBLIC_SUPABASE_URL/ANON_KEY: the CLI is run inside a customer's own
56
+ // Supabase/Next.js project dir (it reads supabase/config.toml + package.json there), where those vars point at
57
+ // the CUSTOMER's project — sign-in would target the wrong GoTrue and then 401 against sodabase.io. Only an
58
+ // explicit SODABASE_* override (dev) or the baked control-plane default is used.
59
+ const supabaseUrl = (process.env.SODABASE_SUPABASE_URL || DEFAULT_SUPABASE_URL).replace(/\/$/, "");
60
+ const anonKey = process.env.SODABASE_SUPABASE_ANON_KEY || DEFAULT_SUPABASE_ANON_KEY;
61
+ const provider = process.env.SODABASE_AUTH_PROVIDER || "github";
62
+ return { supabaseUrl, anonKey, provider };
63
+ }
64
+ /** The anon-key headers every GoTrue auth endpoint requires (publishable key, not the session). */
65
+ function anonHeaders(anonKey) {
66
+ return { apikey: anonKey, authorization: `Bearer ${anonKey}`, "content-type": "application/json" };
67
+ }
68
+ /** Guard: the publishable anon key is required to talk to GoTrue at all. */
69
+ function requireAnonKey(cfg) {
70
+ if (!cfg.anonKey) {
71
+ throw new ApiError("Missing Supabase anon key. Set SODABASE_SUPABASE_ANON_KEY (the project's publishable key).", 400, "config");
72
+ }
73
+ }
74
+ /** Map a GoTrue token-endpoint body to our Session (shared by every grant: pkce + email OTP). */
75
+ function sessionFromTokenBody(body) {
76
+ return {
77
+ accessToken: body.access_token,
78
+ ...(typeof body.refresh_token === "string" ? { refreshToken: body.refresh_token } : {}),
79
+ ...(typeof body.expires_in === "number" ? { expiresAt: Date.now() + body.expires_in * 1000 } : {}),
80
+ };
81
+ }
82
+ /** Run the loopback PKCE flow and return a GoTrue session. */
83
+ export async function loopbackSignIn(cfg = resolveGoTrueConfig(), opts = {}) {
84
+ requireAnonKey(cfg);
85
+ const verifier = b64url(randomBytes(48));
86
+ const challenge = b64url(createHash("sha256").update(verifier).digest());
87
+ // `state` is echoed back by GoTrue — we require it to match so a stray/forged hit on the fixed loopback port
88
+ // can't pre-empt the real redirect (defense in depth; PKCE already prevents an injected-code takeover).
89
+ const state = b64url(randomBytes(16));
90
+ const authorizeUrl = `${cfg.supabaseUrl}/auth/v1/authorize?provider=${encodeURIComponent(cfg.provider)}` +
91
+ `&redirect_to=${encodeURIComponent(LOOPBACK_REDIRECT)}` +
92
+ `&state=${state}` +
93
+ `&code_challenge=${challenge}&code_challenge_method=s256`;
94
+ const code = await new Promise((resolve, reject) => {
95
+ const server = createServer((req, res) => {
96
+ const u = new URL(req.url ?? "/", LOOPBACK_REDIRECT);
97
+ if (u.pathname !== "/callback") {
98
+ res.writeHead(404);
99
+ res.end();
100
+ return;
101
+ }
102
+ // Ignore any callback that isn't ours (missing/mismatched state) — don't let it resolve or reject; keep
103
+ // waiting for the real redirect (or the timeout).
104
+ if (u.searchParams.get("state") !== state) {
105
+ res.writeHead(404);
106
+ res.end();
107
+ return;
108
+ }
109
+ const c = u.searchParams.get("code");
110
+ const err = u.searchParams.get("error_description") || u.searchParams.get("error");
111
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
112
+ const ok = Boolean(c);
113
+ res.end(callbackPage(ok, ok
114
+ ? "Head back to your terminal to pick up where you left off."
115
+ : escapeHtml(err || "Sign-in was cancelled, or no code came back. Head back to your terminal and try again.")));
116
+ clearTimeout(timer); // always clear so the process doesn't linger on the 3-min timer after sign-in
117
+ server.close();
118
+ if (c)
119
+ resolve(c);
120
+ else
121
+ reject(new ApiError(err || "sign-in failed", 401, "oauth"));
122
+ });
123
+ const timer = setTimeout(() => {
124
+ server.close();
125
+ reject(new ApiError(`Timed out waiting for sign-in. Is ${LOOPBACK_REDIRECT} in the Supabase Auth redirect allowlist?`, 408, "timeout"));
126
+ }, opts.timeoutMs ?? 180_000);
127
+ server.on("error", (e) => {
128
+ clearTimeout(timer);
129
+ reject(new ApiError(`loopback server failed (port ${LOOPBACK_PORT} in use?): ${String(e)}`, 500, "loopback"));
130
+ });
131
+ server.listen(LOOPBACK_PORT, "127.0.0.1", () => (opts.onUrl ?? openUrl)(authorizeUrl));
132
+ });
133
+ // Exchange the PKCE code for a GoTrue session.
134
+ const res = await fetch(`${cfg.supabaseUrl}/auth/v1/token?grant_type=pkce`, {
135
+ method: "POST",
136
+ headers: anonHeaders(cfg.anonKey),
137
+ body: JSON.stringify({ auth_code: code, code_verifier: verifier }),
138
+ });
139
+ const body = (await res.json().catch(() => ({})));
140
+ if (!res.ok || typeof body.access_token !== "string") {
141
+ throw new ApiError(String(body.error_description ?? body.msg ?? "token exchange failed"), res.status, String(body.error ?? ""));
142
+ }
143
+ return sessionFromTokenBody(body);
144
+ }
145
+ // ── Email one-time-code sign-in (browserless; no loopback, no PKCE) ───────────────
146
+ // GoTrue's email OTP grant: POST /otp emails a code, POST /verify trades the typed code
147
+ // for a session. Two plain fetches, same anon-key headers — nothing to spin up locally.
148
+ //
149
+ // ONE-TIME SETUP (owner, Supabase dashboard): (a) email auth enabled; (b) the Auth email
150
+ // template must emit a numeric CODE via `{{ .Token }}` — Supabase's default template sends a
151
+ // magic LINK ({{ .ConfirmationURL }}), which a typed-code flow can't use; (c) ideally custom
152
+ // SMTP (Resend) so delivery + rate limits are production-grade rather than the shared sandbox.
153
+ /** Start the email OTP flow: GoTrue emails a one-time code (create_user so new emails work). */
154
+ export async function emailOtpStart(cfg, email) {
155
+ requireAnonKey(cfg);
156
+ const res = await fetch(`${cfg.supabaseUrl}/auth/v1/otp`, {
157
+ method: "POST",
158
+ headers: anonHeaders(cfg.anonKey),
159
+ body: JSON.stringify({ email, create_user: true }),
160
+ });
161
+ if (!res.ok) {
162
+ const body = (await res.json().catch(() => ({})));
163
+ throw new ApiError(String(body.error_description ?? body.msg ?? "could not send the sign-in code"), res.status, String(body.error ?? ""));
164
+ }
165
+ }
166
+ /** Verify the typed one-time code and return a GoTrue session. Throws ApiError on a bad/expired
167
+ * code or a 429 rate-limit, carrying GoTrue's own message + HTTP status for the UI to surface. */
168
+ export async function emailOtpVerify(cfg, email, token) {
169
+ requireAnonKey(cfg);
170
+ const res = await fetch(`${cfg.supabaseUrl}/auth/v1/verify`, {
171
+ method: "POST",
172
+ headers: anonHeaders(cfg.anonKey),
173
+ body: JSON.stringify({ email, token, type: "email" }),
174
+ });
175
+ const body = (await res.json().catch(() => ({})));
176
+ if (!res.ok || typeof body.access_token !== "string") {
177
+ throw new ApiError(String(body.error_description ?? body.msg ?? "code verification failed"), res.status, String(body.error ?? ""));
178
+ }
179
+ return sessionFromTokenBody(body);
180
+ }
@@ -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,98 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Box, useApp, useInput } from "ink";
3
+ import { useCallback, useRef, useState } from "react";
4
+ import { AgentView, BrandBar, Connect, Home, ManageProjects, ManageTables, McpInstall, ScopeAdjust, SignIn, WizardProvider, } from "./ui.js";
5
+ // The screens, by name. Unlike the old linear wizard, navigation is a hub: sign-in lands on `home`
6
+ // (the trust report + action menu), and each action returns there when it finishes.
7
+ const SCREENS = {
8
+ signin: SignIn, // combined detect + sign-in
9
+ home: Home, // trust report + hub menu
10
+ manageprojects: ManageProjects, // pick a watched project, or onboard a new one
11
+ managetables: ManageTables, // watch/unwatch a project's tables
12
+ connect: Connect, // pick a project to watch (onboarding a new one)
13
+ agent: AgentView, // server-side provisioning job (new projects only)
14
+ scope: ScopeAdjust, // choose which tables/monitors run
15
+ mcp: McpInstall, // install the MCP for a coding agent
16
+ };
17
+ /** Where a screen goes when it finishes with no explicit target. `null` = terminal (exit).
18
+ * The hub menu on `home` navigates with an explicit `to`, so `home` has no default next. */
19
+ function nextScreen(name, ctx, interactive) {
20
+ switch (name) {
21
+ case "signin":
22
+ // Interactive: land on the hub. Non-interactive (CI/pipe): no menu to drive, so run the
23
+ // linear setup straight through, then the terminal home report auto-exits.
24
+ return interactive ? "home" : "connect";
25
+ case "connect":
26
+ // Both paths end at the table-scope editor: a brand-new project is provisioned first, an
27
+ // already-watched one goes straight to adjusting which tables are watched.
28
+ return ctx.alreadyWatching ? "scope" : "agent";
29
+ case "agent":
30
+ return "scope";
31
+ case "scope":
32
+ case "mcp":
33
+ return "home";
34
+ default:
35
+ return null;
36
+ }
37
+ }
38
+ /** Where escape goes from a screen: one level back, or `null` to quit (top level). */
39
+ function backTarget(name) {
40
+ switch (name) {
41
+ case "manageprojects":
42
+ case "mcp":
43
+ return "home";
44
+ case "managetables":
45
+ return "manageprojects";
46
+ case "connect":
47
+ case "agent":
48
+ case "scope":
49
+ // These make up the "onboard a new project" sub-flow launched from the project picker.
50
+ return "manageprojects";
51
+ default:
52
+ return null; // signin / home → quit
53
+ }
54
+ }
55
+ export function App({ services, fast, interactive, signedIn, demo }) {
56
+ const [screen, setScreen] = useState("signin");
57
+ const [ctx, setCtx] = useState({});
58
+ // onDone reads the current screen + ctx to compute the default next screen; refs keep those reads
59
+ // fresh without rebuilding the callback on every transition.
60
+ const screenRef = useRef(screen);
61
+ screenRef.current = screen;
62
+ const ctxRef = useRef(ctx);
63
+ ctxRef.current = ctx;
64
+ // Global escape handling. Runs alongside each screen's own useInput (Ink delivers every key to
65
+ // every active handler). The sign-in screen owns escape itself (it steps back through email/code
66
+ // entry instead of quitting), so we defer to it there. In any other sub-screen escape steps BACK
67
+ // one level toward the hub; at the hub it quits. exit() already restores the terminal synchronously
68
+ // in Ink; the follow-up process.exit guarantees promptness — it doesn't wait on in-flight awaits
69
+ // (OAuth handback polling, the agent log tail) that could otherwise keep the event loop alive.
70
+ // 130 = conventional "terminated by the user" code, so a scripted caller can tell an abort from a
71
+ // completed run. Guarded on `interactive` (useInput needs a raw-mode TTY).
72
+ const { exit } = useApp();
73
+ useInput((_input, key) => {
74
+ if (!key.escape)
75
+ return;
76
+ if (screenRef.current === "signin")
77
+ return; // SignIn owns escape (step back through text entry / quit)
78
+ const back = backTarget(screenRef.current);
79
+ if (back === null) {
80
+ exit();
81
+ process.exit(130);
82
+ }
83
+ else {
84
+ setScreen(back); // step back toward the hub; screens re-derive their state from the server
85
+ }
86
+ }, { isActive: interactive });
87
+ const onDone = useCallback((patch, opts) => {
88
+ // Compute from refs, then fire the two state updates as siblings. (Calling setScreen from
89
+ // inside the setCtx updater makes that updater impure, which React may re-run — here it
90
+ // wedged the event loop so sub-screen timers never fired.)
91
+ const next = { ...ctxRef.current, ...patch };
92
+ const target = opts?.to ?? nextScreen(screenRef.current, next, interactive);
93
+ setCtx(next);
94
+ setScreen(target ?? "home");
95
+ }, [interactive]);
96
+ const Current = SCREENS[screen];
97
+ return (_jsx(WizardProvider, { value: { services, fast, interactive, signedIn, demo }, children: _jsxs(Box, { flexDirection: "column", children: [_jsx(BrandBar, {}), Current ? _jsx(Current, { ctx: ctx, onDone: onDone }) : null] }) }));
98
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,83 @@
1
+ #!/usr/bin/env node
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { render } from "ink";
4
+ import { rmSync } from "node:fs";
5
+ import { createRequire } from "node:module";
6
+ import { homedir } from "node:os";
7
+ import { join } from "node:path";
8
+ import { SodabaseClient } from "./api/client.js";
9
+ import { FakeClient } from "./api/fakeClient.js";
10
+ import { App } from "./app.js";
11
+ import { clearCreds, loadCreds } from "./config/tokenStore.js";
12
+ const argv = process.argv.slice(2);
13
+ const args = new Set(argv);
14
+ if (args.has("--help") || args.has("-h")) {
15
+ process.stdout.write([
16
+ "sodabase — data-quality onboarding wizard",
17
+ "",
18
+ "Usage: npx sodabase [options]",
19
+ "",
20
+ "Options:",
21
+ " --demo run the whole flow offline against a fake backend",
22
+ " --fast shorter delays (implied by --demo)",
23
+ " --login sign in again (clears the saved session first)",
24
+ " --logout clear the saved session and exit",
25
+ " --help, -h show this help",
26
+ " --version print the version",
27
+ "",
28
+ "Env:",
29
+ " SODABASE_API_URL API origin (default https://sodabase.io)",
30
+ "",
31
+ "Read-only, always. The only write is one scoped, audited read-only role.",
32
+ "",
33
+ ].join("\n"));
34
+ process.exit(0);
35
+ }
36
+ if (args.has("--version")) {
37
+ // Read the real version from package.json (one level up from dist/cli.js, and included in the tarball) so it
38
+ // never goes stale — the old hardcoded string shipped as 0.0.0-dev against a 0.1.0 package.
39
+ const { version } = createRequire(import.meta.url)("../package.json");
40
+ process.stdout.write(`sodabase ${version}\n`);
41
+ process.exit(0);
42
+ }
43
+ // Sign out: drop the saved session and stop.
44
+ if (args.has("--logout")) {
45
+ clearCreds();
46
+ // Best-effort: remove the legacy resume file an older build may have left behind. It's not a secret
47
+ // (tokens live in credentials.json, cleared above), but a clean sign-out shouldn't leave a file
48
+ // naming your last project on disk. Nothing writes it anymore, so this only ever cleans up.
49
+ try {
50
+ const base = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
51
+ rmSync(join(base, "sodabase", "progress.json"));
52
+ }
53
+ catch {
54
+ /* already gone */
55
+ }
56
+ process.stdout.write("Signed out of Sodabase.\n");
57
+ process.exit(0);
58
+ }
59
+ // Force a fresh sign-in: clear the saved session first, then run normally so it re-prompts.
60
+ if (args.has("--login")) {
61
+ clearCreds();
62
+ }
63
+ const demo = args.has("--demo");
64
+ const fast = args.has("--fast") || demo;
65
+ // Interactive pickers need a raw-mode-capable TTY. Keyed off the TTY only — so
66
+ // `--demo` in a real terminal is a fully interactive offline playthrough, while a
67
+ // piped/CI run (no TTY) auto-advances. Opt out explicitly with --no-input.
68
+ const interactive = !!process.stdin.isTTY && !args.has("--no-input");
69
+ let signedIn = false;
70
+ const services = demo
71
+ ? new FakeClient({ fast })
72
+ : (() => {
73
+ const c = new SodabaseClient();
74
+ const creds = loadCreds();
75
+ // Require a real GoTrue JWT (starts "eyJ") — guards against a stale/fake token
76
+ // (e.g. a leftover --demo session) skipping sign-in and then 401-ing on /api/v1.
77
+ if (creds?.accessToken && creds.accessToken.startsWith("eyJ")) {
78
+ c.setBearer(creds.accessToken);
79
+ signedIn = !creds.expiresAt || creds.expiresAt > Date.now() + 60_000;
80
+ }
81
+ return c;
82
+ })();
83
+ render(_jsx(App, { services: services, fast: fast, interactive: interactive, signedIn: signedIn, demo: demo }));
@@ -0,0 +1,33 @@
1
+ // Per-user credential storage. A 0600 file under the user's config dir — deliberately
2
+ // dep-free (no native keychain module). Documented tradeoff: less hardened than an OS
3
+ // keychain, but no node-gyp/platform build and no new dependency. Can move to a keychain
4
+ // later if warranted.
5
+ import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6
+ import { homedir } from "node:os";
7
+ import { dirname, join } from "node:path";
8
+ function credsPath() {
9
+ const base = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
10
+ return join(base, "sodabase", "credentials.json");
11
+ }
12
+ export function loadCreds() {
13
+ try {
14
+ return JSON.parse(readFileSync(credsPath(), "utf8"));
15
+ }
16
+ catch {
17
+ return null; // missing / unreadable / malformed → treat as signed-out
18
+ }
19
+ }
20
+ export function saveCreds(creds) {
21
+ const path = credsPath();
22
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
23
+ writeFileSync(path, JSON.stringify(creds, null, 2), { mode: 0o600 });
24
+ chmodSync(path, 0o600); // enforce even if the file pre-existed with looser perms
25
+ }
26
+ export function clearCreds() {
27
+ try {
28
+ rmSync(credsPath());
29
+ }
30
+ catch {
31
+ /* already gone */
32
+ }
33
+ }