Back to manual Supabase setup: paste three keys, then the connection string and password

The account-wide sign-in, project picker and project creation are gone. Signing in to Supabase stays as an option on step 2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
minimus7andClaude Opus 5.5 committed 2026-11-09 12:13:42 -06:00
1 parent e7c5c8df69
commit a842601665
9 files changed
+33 -301

No files matched your search

+4 -22
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 { accountConnected, mcpConnected } from "@/lib/supabase-mcp";
import { mcpConnected } from "@/lib/supabase-mcp";
import { cardReferralSection } from "@/lib/cards-data";
import { akahuTokens } from "@/lib/providers";
import { akahuGet } from "@/lib/providers/akahu";
@@ -25,8 +25,7 @@ export type Section = {
steps?: Part[][];
fields?: Field[];
command?: string;
action?: "migrate" | "connect" | "pick";
fallback?: string; // the label over the steps and boxes when a button comes first
action?: "migrate" | "connect";
providers?: AiRow[];
};
export type SetupStatus = { sections: Section[]; ready: boolean; canWrite: boolean; writeNote?: string };
@@ -104,7 +103,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 new project at ", { href: "https://supabase.com/dashboard/new", label: "supabase.com" }, ". Any name works. Write down the database password you choose."],
["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."],
["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."],
],
@@ -114,30 +113,13 @@ 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",
title: "Turn on your database",
what: "broke creates its own tables and keeps them up to date.",
status: "todo",
note: "Press the button, sign in to Supabase and approve broke. Nothing to copy.",
note: undefined,
action: "connect",
steps: [
["In Supabase, press ", { href: dash("?showConnect=true"), label: "Connect" }, " at the top of your project."],
-14
View File
@@ -1,14 +0,0 @@
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 };
}
+10 -146
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; all?: boolean; redirect?: string; client?: OAuthClientInformationMixed; tokens?: OAuthTokens; verifier?: string; state?: string };
type Saved = { ref?: string; redirect?: string; client?: OAuthClientInformationMixed; tokens?: OAuthTokens; verifier?: string; state?: string };
const load = (): Saved => {
try {
@@ -26,9 +26,7 @@ const save = (patch: Saved) => {
chmodSync(FILE, 0o600);
};
// 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);
const serverUrl = (ref: string) => `https://mcp.supabase.com/mcp?project_ref=${ref}`;
export const refFromUrl = (url?: string) => url?.match(/https:\/\/([a-z0-9]+)\.supabase\.co/)?.[1];
function provider(redirect: string, onRedirect?: (u: URL) => void): OAuthClientProvider {
@@ -62,15 +60,10 @@ 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. */
// 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, fresh = false): Promise<string | null> {
// fresh: forget this sign-in, so Supabase asks again (and the person can pick a different organization).
if (fresh) save({ client: undefined, tokens: undefined, ref: undefined, all: undefined });
export async function startConnect(ref: string, redirect: string): Promise<string | null> {
const s = load();
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 });
// 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 });
let url: URL | undefined;
const r = await auth(provider(redirect, (u) => (url = u)), { serverUrl: serverUrl(ref) });
return r === "AUTHORIZED" ? null : url!.toString();
@@ -79,8 +72,8 @@ export async function startConnect(ref: string | undefined, redirect: string, fr
/** 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.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 });
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 });
save({ state: undefined, verifier: undefined });
}
@@ -90,9 +83,10 @@ 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 = await connectClient(s);
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 exec: Exec = async (query) => {
const res = await client.callTool({ name: "execute_sql", arguments: s.all ? { project_id: s.ref, query } : { query } });
const res = await client.callTool({ name: "execute_sql", arguments: { 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>..."}.
@@ -107,133 +101,3 @@ 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" });
try {
await client.connect(new StreamableHTTPClientTransport(new URL(urlOf(s)), { authProvider: provider(s.redirect!) }));
} catch (e) {
// The sign-in expired and couldn't be renewed: forget it, so the page offers Connect Supabase again.
if (/unauthori[sz]ed|invalid_grant|401/i.test(e instanceof Error ? e.message : String(e))) {
save({ tokens: undefined });
throw new Error("Your Supabase sign-in expired. Press Connect Supabase again.");
}
throw e;
}
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 };
// Supabase's list tools wrap the list: {"projects": [...]}, {"organizations": [...]}. A bare list works too.
const listOf = <T,>(text: string, key: string): T[] => {
const raw = JSON.parse(text) as T[] | Record<string, T[]>;
return Array.isArray(raw) ? raw : raw[key] ?? [];
};
/** The projects this Supabase account can see. */
export async function listProjects(): Promise<Project[]> {
const s = load();
const client = await connectClient(s);
try {
return listOf<Project>(unwrap(await call(client, "list_projects", {})), "projects").map((p) => ({ id: p.id, name: p.name, region: p.region, status: p.status }));
} finally {
await client.close().catch(() => {});
}
}
/** The organizations this sign-in was approved for (Supabase's approval page picks them). */
export async function listOrgs(): Promise<{ id: string; name: string }[]> {
const client = await connectClient(load());
try {
return listOf<{ id: string; name: string }>(unwrap(await call(client, "list_organizations", {})), "organizations").map((o) => ({ id: o.id, name: o.name }));
} 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") {
try {
return await makeProject(region);
} catch (e) {
// Supabase allows each person 2 active free projects, counted across all their organizations.
if (/maximum limits?|project limit/i.test(e instanceof Error ? e.message : "")) throw new Error("Your Supabase account already has 2 free projects, Supabase's limit. Pause or delete one at supabase.com, then try again. Or connect again and pick the organization that has a project to use.");
throw e;
}
}
async function makeProject(region: string) {
const s = load();
const client = await connectClient(s);
try {
const orgs = listOf<{ id: string }>(unwrap(await call(client, "list_organizations", {})), "organizations");
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.");
// Free: Supabase's create_project says to call it without a cost confirmation unless it asks for one.
const one = (t: string) => { const r = JSON.parse(t) as Project & { project?: Project }; return r.project ?? r; };
let made: Project;
try {
made = one(await callFit(client, "create_project", pool));
} catch (e) {
if (!/confirm/i.test(e instanceof Error ? e.message : "")) throw e;
const confirm = await callFit(client, "confirm_cost", { ...pool, amount });
pool.confirm_cost_id = (() => { try { const c = JSON.parse(confirm) as { confirmation_id?: string; confirm_cost_id?: string; id?: string }; return c.confirmation_id ?? c.confirm_cost_id ?? c.id; } catch { return confirm.match(/[A-Za-z0-9_-]{16,}/)?.[0] ?? confirm.trim(); } })();
made = one(await callFit(client, "create_project", pool));
}
for (let i = 0; i < 60; i++) {
const p = one(await callFit(client, "get_project", { id: made.id, project_id: made.id }));
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(() => {});
}
}