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:
1 parent
e7c5c8df69
commit
a842601665
9 files changed
+30
-298
No files matched your search
@@ -1,8 +1,6 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { migrate } from "@/lib/migrate";
|
||||
import { currentEnv } from "@/lib/setup";
|
||||
import { accountConnected, finishConnect, listProjects } from "@/lib/supabase-mcp";
|
||||
import { fillFrom } from "@/lib/supabase-fill";
|
||||
import { finishConnect } from "@/lib/supabase-mcp";
|
||||
|
||||
// Supabase sends the browser back here after "Approve". Finish the sign-in, then bring the tables up to date.
|
||||
// The result goes back as a code (DB_MESSAGES on the Setup page), never as text, so the link can't carry a message.
|
||||
@@ -17,17 +15,6 @@ export async function GET(request: Request) {
|
||||
console.error("[broke] supabase callback:", e instanceof Error ? e.message : e);
|
||||
return back(e instanceof Error && /didn't start/.test(e.message) ? "elsewhere" : "rejected");
|
||||
}
|
||||
// Signed in to the whole account with no project set yet: one project is used straight away, several are picked on the page.
|
||||
if (accountConnected() && !currentEnv().NEXT_PUBLIC_SUPABASE_URL?.includes(".supabase.co")) {
|
||||
try {
|
||||
const projects = await listProjects();
|
||||
if (projects.length !== 1) return back(projects.length ? "pick" : "no-project");
|
||||
return back((await fillFrom(projects[0].id)).tables ? "filled" : "filled-no-tables");
|
||||
} catch (e) {
|
||||
console.error("[broke] supabase fill:", e instanceof Error ? e.message : e);
|
||||
return back("pick");
|
||||
}
|
||||
}
|
||||
const r = await migrate();
|
||||
return back(r.error ? "update-failed" : r.applied.length ? "updated" : "current");
|
||||
}
|
||||
@@ -4,15 +4,14 @@ import { refFromUrl, startConnect } from "@/lib/supabase-mcp";
|
||||
|
||||
const LOOPBACK = /^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/;
|
||||
|
||||
// "Connect Supabase": returns the Supabase approval page, for this project or (before one is set) the whole account. Localhost only.
|
||||
// "Connect Supabase": returns the Supabase approval page for this project. Localhost only.
|
||||
export async function POST(request: Request) {
|
||||
const host = request.headers.get("host") ?? "";
|
||||
if (!LOOPBACK.test(host) || !(await setupAccess()).allowed) return NextResponse.json({ error: "Only on this computer." }, { status: 403 });
|
||||
// No project yet: sign in to the whole account, and broke picks (or makes) the project after.
|
||||
const ref = refFromUrl(currentEnv().NEXT_PUBLIC_SUPABASE_URL);
|
||||
if (!ref) return NextResponse.json({ error: "Add your Supabase Project URL first." }, { status: 400 });
|
||||
try {
|
||||
const { fresh } = (await request.json().catch(() => ({}))) as { fresh?: boolean };
|
||||
const url = await startConnect(fresh ? undefined : ref, `http://${host}/api/setup/supabase/callback`, !!fresh);
|
||||
const url = await startConnect(ref, `http://${host}/api/setup/supabase/callback`);
|
||||
return NextResponse.json(url ? { url } : { connected: true });
|
||||
} catch (e) {
|
||||
console.error("[broke] supabase connect:", e instanceof Error ? e.message : e);
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { sameOrigin, setupAccess } from "@/lib/setup";
|
||||
import { fillFrom } from "@/lib/supabase-fill";
|
||||
import { accountConnected, createProject, listOrgs, listProjects } from "@/lib/supabase-mcp";
|
||||
|
||||
const LOOPBACK = /^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/;
|
||||
const local = async (request: Request) => LOOPBACK.test(request.headers.get("host") ?? "") && (await setupAccess()).allowed && accountConnected();
|
||||
|
||||
// After "Connect Supabase" signed in to the whole account: list its projects, or use one (or a new one). Using one writes
|
||||
// its address and publishable key to .env.local and creates broke's tables through the same sign-in. Localhost only.
|
||||
export async function GET(request: Request) {
|
||||
if (!(await local(request))) return NextResponse.json({ error: "Only on this computer, after Connect Supabase." }, { status: 403 });
|
||||
try {
|
||||
// One after the other: two at once could both renew the sign-in, and the second renewal cancels the first.
|
||||
const projects = await listProjects();
|
||||
const orgs = await listOrgs();
|
||||
return NextResponse.json({ projects, orgs: orgs.map((o) => o.name) });
|
||||
} catch (e) {
|
||||
console.error("[broke] supabase projects:", e instanceof Error ? e.message : e);
|
||||
return NextResponse.json({ error: e instanceof Error && /expired/.test(e.message) ? e.message : "Couldn't list your Supabase projects. Press Connect Supabase again." }, { status: 502 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
if (!(await local(request)) || !sameOrigin(request)) return NextResponse.json({ error: "Only on this computer, after Connect Supabase." }, { status: 403 });
|
||||
const { ref, create } = (await request.json().catch(() => ({}))) as { ref?: string; create?: boolean };
|
||||
try {
|
||||
const id = create ? await createProject() : ref && /^[a-z0-9]{20}$/.test(ref) ? ref : null;
|
||||
if (!id) return NextResponse.json({ error: "Pick a project." }, { status: 400 });
|
||||
return NextResponse.json(await fillFrom(id));
|
||||
} catch (e) {
|
||||
console.error("[broke] supabase project:", e instanceof Error ? e.message : e);
|
||||
return NextResponse.json({ error: e instanceof Error && /cost money|organization|free projects|expired/.test(e.message) ? e.message : "Supabase didn't answer. Try again in a moment." }, { status: 502 });
|
||||
}
|
||||
}
|
||||
@@ -171,20 +171,20 @@ export function MigrateButton({ onDone }: { onDone: () => void }) {
|
||||
}
|
||||
|
||||
// One click: Supabase's own sign-in page, then back to /setup with the tables created.
|
||||
export function ConnectSupabaseButton({ onDone, onFail, fresh = false, label = "Connect Supabase", quiet = false }: { onDone: () => void; onFail?: () => void; fresh?: boolean; label?: string; quiet?: boolean }) {
|
||||
export function ConnectSupabaseButton({ onDone, onFail }: { onDone: () => void; onFail?: () => void }) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [msg, setMsg] = useState("");
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<button
|
||||
className={quiet ? "btn" : "btn-primary"}
|
||||
className="btn"
|
||||
disabled={busy}
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
setMsg("");
|
||||
// Supabase opens in its own tab, so broke stays put. Opened now, while the click still counts, or it's blocked.
|
||||
const tab = window.open("", "_blank");
|
||||
const res = await fetch("/api/setup/supabase/connect", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ fresh }) });
|
||||
const res = await fetch("/api/setup/supabase/connect", { method: "POST" });
|
||||
const body = await res.json().catch(() => ({}));
|
||||
if (body.url) {
|
||||
if (tab) tab.location.href = body.url;
|
||||
@@ -201,57 +201,10 @@ export function ConnectSupabaseButton({ onDone, onFail, fresh = false, label = "
|
||||
onDone();
|
||||
}}
|
||||
>
|
||||
{busy ? "Opening Supabase..." : label}
|
||||
{busy ? "Opening Supabase..." : "Connect Supabase"}
|
||||
</button>
|
||||
{msg && <span className="text-sm text-bad">{msg}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type Project = { id: string; name: string; region?: string; status?: string };
|
||||
|
||||
// After Connect Supabase: the account's projects, or a new free one called broke. Picking fills in its address and
|
||||
// public key and creates the tables (POST /api/setup/supabase/project).
|
||||
export function ProjectPicker({ onDone }: { onDone: () => void }) {
|
||||
const [projects, setProjects] = useState<Project[] | null>(null);
|
||||
const [orgs, setOrgs] = useState<string[]>([]);
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const [msg, setMsg] = useState("");
|
||||
useEffect(() => {
|
||||
fetch("/api/setup/supabase/project").then((r) => r.json()).then((b: { projects?: Project[]; orgs?: string[]; error?: string }) => { if (b.error) setMsg(b.error); else { setProjects(b.projects ?? []); setOrgs(b.orgs ?? []); } }).catch(() => setMsg("Couldn't reach broke. Is it still running?"));
|
||||
}, []);
|
||||
async function use(body: { ref?: string; create?: boolean }, label: string) {
|
||||
setBusy(label);
|
||||
setMsg("");
|
||||
const res = await fetch("/api/setup/supabase/project", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }).catch(() => null);
|
||||
const b = (await res?.json().catch(() => ({}))) as { error?: string } | undefined;
|
||||
setBusy(null);
|
||||
if (res?.ok) onDone();
|
||||
else setMsg(b?.error ?? "That didn't work. Try again.");
|
||||
}
|
||||
if (!projects && !msg) return <p className="text-sm text-muted">Finding your projects…</p>;
|
||||
const where = orgs.length ? `Supabase organization${orgs.length > 1 ? "s" : ""} ${orgs.map((o) => `“${o}”`).join(", ")}` : "your Supabase account";
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm text-muted">{projects?.length ? `Projects in ${where}:` : `Connected to ${where}, which has no projects yet.`}</p>
|
||||
{!!projects?.length && (
|
||||
<ul className="space-y-2">
|
||||
{projects.map((p) => (
|
||||
<li key={p.id} className="flex items-center justify-between gap-3 rounded-xl border border-line px-4 py-3">
|
||||
<span className="min-w-0"><span className="block font-medium truncate">{p.name}</span><span className="block text-xs text-muted">{p.id}{p.region ? ` · ${p.region}` : ""}</span></span>
|
||||
<button className="btn shrink-0" disabled={!!busy} onClick={() => use({ ref: p.id }, p.id)}>{busy === p.id ? "Setting up…" : "Use this one"}</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<button className={projects?.length ? "btn" : "btn-primary"} disabled={!!busy} onClick={() => use({ create: true }, "new")}>
|
||||
{busy === "new" ? "Making your project… about a minute" : "Make a new free project called broke"}
|
||||
</button>
|
||||
{msg && <p className="text-sm text-bad">{msg}</p>}
|
||||
<div className="pt-1 space-y-1">
|
||||
<ConnectSupabaseButton onDone={onDone} fresh quiet label="Use a different Supabase organization" />
|
||||
<p className="text-xs text-muted">Signs in to Supabase again. On Supabase's approval page, change the organization to the one that has the project you want before you approve.</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import Link from "next/link";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Logo } from "@/components/Logo";
|
||||
import type { AiRow, Part, Section, SetupStatus } from "@/lib/setup";
|
||||
import { CopyCommand, KeyForm, ConnectSupabaseButton, MigrateButton, ProjectPicker } from "./SetupActions";
|
||||
import { CopyCommand, KeyForm, ConnectSupabaseButton, MigrateButton } from "./SetupActions";
|
||||
|
||||
export function ExtLink({ href, children }: { href: string; children: React.ReactNode }) {
|
||||
return (
|
||||
@@ -214,16 +214,16 @@ export function Body({ s, data, signedIn, reload }: { s: Section; data: SetupSta
|
||||
<>
|
||||
{s.note && s.status !== "done" && s.status !== "error" && <p className="text-sm">{s.note}</p>}
|
||||
{s.note && s.status === "done" && s.kind === "more" && <p className="text-sm">{s.note}</p>}
|
||||
{s.action === "connect" && <ConnectSupabaseButton onDone={reload} onFail={() => setFallback(true)} />}
|
||||
{s.action === "pick" && <ProjectPicker onDone={() => window.location.reload()} />}
|
||||
{(s.action === "connect" || s.action === "pick") && (s.steps || s.fields) ? (
|
||||
<details className="text-sm" open={fallback} onToggle={(e) => setFallback(e.currentTarget.open)}>
|
||||
<summary className="cursor-pointer text-muted hover:text-ink">{s.fallback ?? "Button didn't work? Paste a connection string instead"}</summary>
|
||||
<div className="pt-3 space-y-4">
|
||||
{s.action === "connect" && (s.steps || s.fields) ? (
|
||||
// Step 2: paste the connection string and password (the reliable way), or sign in to Supabase instead.
|
||||
<>
|
||||
<Steps steps={s.steps} />
|
||||
{form}
|
||||
</div>
|
||||
<details className="text-sm" open={fallback} onToggle={(e) => setFallback(e.currentTarget.open)}>
|
||||
<summary className="cursor-pointer text-muted hover:text-ink">Or sign in to Supabase instead of pasting</summary>
|
||||
<div className="pt-3"><ConnectSupabaseButton onDone={reload} /></div>
|
||||
</details>
|
||||
</>
|
||||
) : s.status === "done" && s.kind !== "more" && s.fields ? (
|
||||
// Connected: the steps and empty boxes are noise now. They stay one click away for changing a key.
|
||||
<details className="text-sm">
|
||||
|
||||
@@ -6,8 +6,4 @@ export const DB_MESSAGES: Record<string, string> = {
|
||||
"update-failed": "Connected, but a database update failed. Press Update database below to see why.",
|
||||
updated: "Connected. Tables updated.",
|
||||
current: "Connected. Tables are up to date.",
|
||||
filled: "Connected. broke filled in your project's address and public key and created its tables. One key left to paste.",
|
||||
"filled-no-tables": "Connected and filled in. Creating the tables didn't finish: press Update database under step 2.",
|
||||
pick: "Connected. Pick the project broke should use.",
|
||||
"no-project": "Connected. This account has no projects yet: make one below.",
|
||||
};
|
||||
+4
-22
@@ -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."],
|
||||
|
||||
@@ -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
@@ -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(() => {});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user