Connect Supabase first: pick or make a project, and only the secret key is pasted

Signs in to the whole Supabase account, lists its projects (one is used straight away), or makes a free one called broke,
then fills in the address and public key and creates the tables. The paste-all-three route stays as the fallback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
minimus7andClaude Opus 5.5 committed 2026-11-09 11:04:06 -06:00
1 parent 73208b79df
commit 0e1a05801c
9 files changed
+237 -20

No files matched your search

+21 -3
View File
@@ -5,7 +5,7 @@ import * as llmConfig from "@/lib/llm/config";
import { probeLocal, providers } from "@/lib/llm/providers";
import { describe, ENV_KEYS, isPlaceholder, readEnv } from "@/lib/envfile";
import { migrate } from "@/lib/migrate";
import { mcpConnected } from "@/lib/supabase-mcp";
import { accountConnected, mcpConnected } from "@/lib/supabase-mcp";
import { cardReferralSection } from "@/lib/cards-data";
import { akahuTokens } from "@/lib/providers";
import { akahuGet } from "@/lib/providers/akahu";
@@ -25,7 +25,8 @@ export type Section = {
steps?: Part[][];
fields?: Field[];
command?: string;
action?: "migrate" | "connect";
action?: "migrate" | "connect" | "pick";
fallback?: string; // the label over the steps and boxes when a button comes first
providers?: AiRow[];
};
export type SetupStatus = { sections: Section[]; ready: boolean; canWrite: boolean; writeNote?: string };
@@ -103,7 +104,7 @@ export async function setupStatus(signedIn: boolean): Promise<SetupStatus> {
status: sb?.ok ? "done" : sb ? "error" : "todo",
note: sb?.ok ? (ref ? `Project ${ref}` : sb.message) : sb?.message,
steps: [
["Make a free account and a new project at ", { href: "https://supabase.com/dashboard/new", label: "supabase.com" }, ". Any name works. Write down the database password you choose: you need it in the next step if the button there doesn't work."],
["Make a new project at ", { href: "https://supabase.com/dashboard/new", label: "supabase.com" }, ". Any name works. Write down the database password you choose."],
["When the project is ready, open ", { href: dash("/settings/api-keys"), label: "Project Settings → API Keys" }, "."],
["Copy three things from that page into the boxes below, then press Save."],
],
@@ -113,6 +114,23 @@ export async function setupStatus(signedIn: boolean): Promise<SetupStatus> {
SUPABASE_SERVICE_ROLE_KEY: { placeholder: "sb_secret_…", help: "Under Secret keys: press the eye to show it, then copy. Starts with sb_secret_." },
}),
};
// The easy way first: Connect Supabase signs in to the account, picks (or makes) the project and fills in its address and
// public key. Then only the secret key is pasted: the sign-in can't read it, by Supabase's design.
if (!sb?.ok) {
const filled = isSet(env.NEXT_PUBLIC_SUPABASE_URL) && isSet(env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY);
if (filled && !isSet(env.SUPABASE_SERVICE_ROLE_KEY)) {
supabase.note = "Your project's address and public key are in. One key left.";
supabase.steps = [
["Open ", { href: dash("/settings/api-keys"), label: "Project Settings → API Keys" }, " in Supabase."],
["Under Secret keys, press the eye to show the key, copy it, paste it below and press Save."],
];
supabase.fields = fields(env, ["SUPABASE_SERVICE_ROLE_KEY"], { SUPABASE_SERVICE_ROLE_KEY: { placeholder: "sb_secret_…", help: "Starts with sb_secret_. It stays on this computer." } });
} else if (!filled) {
supabase.action = accountConnected() ? "pick" : "connect";
supabase.note = accountConnected() ? "Pick the project broke should use, or make a new one." : "Make a free account at supabase.com if you don't have one, then press Connect Supabase. broke finds your project, or makes one, and fills in its address and public key.";
supabase.fallback = "Button didn't work? Paste all three yourself";
}
}
let database: Section = {
id: "database", kind: "required",
+14
View File
@@ -0,0 +1,14 @@
import "server-only";
import { writeEnvLocal } from "@/lib/envfile";
import { migrate } from "@/lib/migrate";
import { projectKeys } from "@/lib/supabase-mcp";
/** Writes a project's address and publishable key (read through the Supabase sign-in), then creates broke's tables. */
export async function fillFrom(ref: string) {
const { url, key } = await projectKeys(ref);
const values = { NEXT_PUBLIC_SUPABASE_URL: url, NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY: key };
writeEnvLocal(values);
Object.assign(process.env, values); // usable now; Next's own env reload follows
const r = await migrate();
return { ok: true, tables: !r.error };
}
+104 -10
View File
@@ -11,7 +11,7 @@ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/
import type { OAuthClientInformationMixed, OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js";
const FILE = join(homedir(), ".broke", "supabase-mcp.json");
type Saved = { ref?: string; redirect?: string; client?: OAuthClientInformationMixed; tokens?: OAuthTokens; verifier?: string; state?: string };
type Saved = { ref?: string; all?: boolean; redirect?: string; client?: OAuthClientInformationMixed; tokens?: OAuthTokens; verifier?: string; state?: string };
const load = (): Saved => {
try {
@@ -26,7 +26,9 @@ const save = (patch: Saved) => {
chmodSync(FILE, 0o600);
};
const serverUrl = (ref: string) => `https://mcp.supabase.com/mcp?project_ref=${ref}`;
// One project (the older flow), or the whole account (all: the setup page's first step, which picks the project after).
const serverUrl = (ref?: string) => (ref ? `https://mcp.supabase.com/mcp?project_ref=${ref}` : "https://mcp.supabase.com/mcp");
const urlOf = (s: Saved) => serverUrl(s.all ? undefined : s.ref);
export const refFromUrl = (url?: string) => url?.match(/https:\/\/([a-z0-9]+)\.supabase\.co/)?.[1];
function provider(redirect: string, onRedirect?: (u: URL) => void): OAuthClientProvider {
@@ -60,10 +62,13 @@ export const mcpConnected = (ref?: string) => {
};
/** Starts the sign-in. Returns the Supabase approval page to send the browser to, or null if already signed in. */
export async function startConnect(ref: string, redirect: string): Promise<string | null> {
// ref undefined: sign in to the whole account, so broke can list projects and fill in the URL and public key itself.
export async function startConnect(ref: string | undefined, redirect: string): Promise<string | null> {
const s = load();
// A new project or a new callback address needs a fresh client registration and fresh tokens.
if (s.ref !== ref || s.redirect !== redirect) save({ ref, redirect, client: undefined, tokens: undefined });
const all = !ref;
// A new project, a change between one project and the whole account, or a new callback address needs fresh tokens.
if (all ? !s.all : s.all || s.ref !== ref) save({ ref, all, redirect, client: undefined, tokens: undefined });
else if (s.redirect !== redirect) save({ redirect, client: undefined, tokens: undefined });
let url: URL | undefined;
const r = await auth(provider(redirect, (u) => (url = u)), { serverUrl: serverUrl(ref) });
return r === "AUTHORIZED" ? null : url!.toString();
@@ -72,8 +77,8 @@ export async function startConnect(ref: string, redirect: string): Promise<strin
/** Finishes the sign-in from the callback. Throws on a wrong state (not our request) or a refused code. */
export async function finishConnect(code: string, state: string | null) {
const s = load();
if (!s.ref || !s.redirect || !state || state !== s.state) throw new Error("This sign-in didn't start on this computer. Press Connect Supabase again.");
await auth(provider(s.redirect), { serverUrl: serverUrl(s.ref), authorizationCode: code });
if ((!s.ref && !s.all) || !s.redirect || !state || state !== s.state) throw new Error("This sign-in didn't start on this computer. Press Connect Supabase again.");
await auth(provider(s.redirect), { serverUrl: urlOf(s), authorizationCode: code });
save({ state: undefined, verifier: undefined });
}
@@ -83,10 +88,9 @@ export type Exec = (sql: string) => Promise<Record<string, unknown>[]>;
export async function mcpSession(): Promise<{ exec: Exec; close: () => Promise<void> }> {
const s = load();
if (!s.ref || !s.redirect) throw new Error("Supabase isn't connected.");
const client = new Client({ name: "broke", version: "1.0.0" });
await client.connect(new StreamableHTTPClientTransport(new URL(serverUrl(s.ref)), { authProvider: provider(s.redirect) }));
const client = await connectClient(s);
const exec: Exec = async (query) => {
const res = await client.callTool({ name: "execute_sql", arguments: { query } });
const res = await client.callTool({ name: "execute_sql", arguments: s.all ? { project_id: s.ref, query } : { query } });
const text = (res.content as { type: string; text?: string }[]).map((c) => c.text ?? "").join("");
if (res.isError) throw new Error(text.slice(0, 500));
// Rows come back wrapped: {"result":"...<untrusted-data-ID>\n[rows]\n</untrusted-data-ID>..."}.
@@ -101,3 +105,93 @@ export async function mcpSession(): Promise<{ exec: Exec; close: () => Promise<v
};
return { exec, close: () => client.close() };
}
async function connectClient(s: Saved) {
const client = new Client({ name: "broke", version: "1.0.0" });
await client.connect(new StreamableHTTPClientTransport(new URL(urlOf(s)), { authProvider: provider(s.redirect!) }));
return client;
}
// A tool's reply as text (whatever wrapping the server puts around it).
async function call(client: Client, name: string, args: Record<string, unknown>) {
const res = await client.callTool({ name, arguments: args });
const text = (res.content as { type: string; text?: string }[]).map((c) => c.text ?? "").join("");
if (res.isError) throw new Error(text.slice(0, 300));
return text;
}
const unwrap = (text: string) => {
let body = text;
try { body = (JSON.parse(text) as { result?: string }).result ?? text; } catch { /* plain text */ }
return body.match(/<untrusted-data-[\w-]+>\s*([\s\S]*?)\s*<\/untrusted-data-[\w-]+>/)?.[1] ?? body;
};
/** Signed in to the whole account on this computer (the setup page's first step). */
export const accountConnected = () => {
const s = load();
return !!s.all && !!s.tokens;
};
export type Project = { id: string; name: string; region?: string; status?: string };
/** The projects this Supabase account can see. */
export async function listProjects(): Promise<Project[]> {
const s = load();
const client = await connectClient(s);
try {
const raw = JSON.parse(unwrap(await call(client, "list_projects", {}))) as Project[] | { projects?: Project[] };
return (Array.isArray(raw) ? raw : raw.projects ?? []).map((p) => ({ id: p.id, name: p.name, region: p.region, status: p.status }));
} finally {
await client.close().catch(() => {});
}
}
/** Picks a project: its address and publishable key, read through the sign-in. Saves the choice for the migrations. */
export async function projectKeys(ref: string) {
const s = load();
const client = await connectClient(s);
try {
const url = unwrap(await call(client, "get_project_url", { project_id: ref })).match(/https:\/\/[a-z0-9]+\.supabase\.co/)?.[0];
const keys = unwrap(await call(client, "get_publishable_keys", { project_id: ref }));
const key = keys.match(/sb_publishable_[\w-]+/)?.[0] ?? keys.match(/eyJ[\w-]+\.[\w-]+\.[\w-]+/)?.[0];
if (!url || !key) throw new Error("Supabase didn't return this project's address and key.");
save({ ref });
return { url, key };
} finally {
await client.close().catch(() => {});
}
}
// Calls a tool with only the inputs its own schema asks for, picked from what broke knows. The account tools' inputs
// aren't documented, so this reads them from the server rather than guessing names.
async function callFit(client: Client, name: string, pool: Record<string, unknown>) {
const { tools } = await client.listTools();
const props = Object.keys((tools.find((t) => t.name === name)?.inputSchema as { properties?: Record<string, unknown> } | undefined)?.properties ?? {});
return unwrap(await call(client, name, Object.fromEntries(props.filter((k) => k in pool).map((k) => [k, pool[k]]))));
}
/** Makes a free project called "broke" in the first organization, and waits until it's ready (a minute or two). */
export async function createProject(region = "us-east-1") {
const s = load();
const client = await connectClient(s);
try {
const orgs = JSON.parse(unwrap(await call(client, "list_organizations", {}))) as { id: string }[];
if (!orgs.length) throw new Error("This Supabase account has no organization yet. Open supabase.com once to make one.");
const pool: Record<string, unknown> = { type: "project", organization_id: orgs[0].id, name: "broke", region, recurrence: "monthly" };
// Supabase asks to confirm the cost first. A free organization's project costs $0; anything else is the user's call.
const cost = await callFit(client, "get_cost", pool);
const amount = Number(cost.match(/"amount"\s*:\s*([\d.]+)/)?.[1] ?? cost.match(/\$\s*([\d.]+)/)?.[1] ?? 0);
if (amount > 0) throw new Error("A new project would cost money on this account. Make one yourself at supabase.com instead.");
pool.amount = amount;
const confirm = await callFit(client, "confirm_cost", pool);
pool.confirm_cost_id = (() => { try { return (JSON.parse(confirm) as { confirm_cost_id?: string; id?: string }).confirm_cost_id ?? JSON.parse(confirm).id; } catch { return confirm.match(/[A-Za-z0-9_-]{16,}/)?.[0] ?? confirm.trim(); } })();
const made = JSON.parse(await callFit(client, "create_project", pool)) as Project;
for (let i = 0; i < 60; i++) {
const p = JSON.parse(await callFit(client, "get_project", { id: made.id, project_id: made.id })) as Project;
if (p.status === "ACTIVE_HEALTHY") return made.id;
await new Promise((r) => setTimeout(r, 5000));
}
return made.id; // still starting: the next step says so if it isn't ready
} finally {
await client.close().catch(() => {});
}
}