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:
1 parent
73208b79df
commit
0e1a05801c
9 files changed
+237
-20
No files matched your search
@@ -1,6 +1,8 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { migrate } from "@/lib/migrate";
|
||||
import { finishConnect } from "@/lib/supabase-mcp";
|
||||
import { currentEnv } from "@/lib/setup";
|
||||
import { accountConnected, finishConnect, listProjects } from "@/lib/supabase-mcp";
|
||||
import { fillFrom } from "@/lib/supabase-fill";
|
||||
|
||||
// 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.
|
||||
@@ -15,6 +17,17 @@ 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,12 +4,12 @@ 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. Localhost only.
|
||||
// "Connect Supabase": returns the Supabase approval page, for this project or (before one is set) the whole account. 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 url = await startConnect(ref, `http://${host}/api/setup/supabase/callback`);
|
||||
return NextResponse.json(url ? { url } : { connected: true });
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { sameOrigin, setupAccess } from "@/lib/setup";
|
||||
import { fillFrom } from "@/lib/supabase-fill";
|
||||
import { accountConnected, createProject, 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 {
|
||||
return NextResponse.json({ projects: await listProjects() });
|
||||
} catch (e) {
|
||||
console.error("[broke] supabase projects:", e instanceof Error ? e.message : e);
|
||||
return NextResponse.json({ error: "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/.test(e.message) ? e.message : "Supabase didn't answer. Try again in a moment." }, { status: 502 });
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { Check, Copy, Eye, EyeOff } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import type { Field } from "@/lib/setup";
|
||||
|
||||
export function CopyCommand({ command }: { command: string }) {
|
||||
@@ -199,3 +199,44 @@ export function ConnectSupabaseButton({ onDone, onFail }: { onDone: () => void;
|
||||
</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 [busy, setBusy] = useState<string | null>(null);
|
||||
const [msg, setMsg] = useState("");
|
||||
useEffect(() => {
|
||||
fetch("/api/setup/supabase/project").then((r) => r.json()).then((b: { projects?: Project[]; error?: string }) => (b.error ? setMsg(b.error) : setProjects(b.projects ?? []))).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>;
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{!!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>
|
||||
);
|
||||
}
|
||||
@@ -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 } from "./SetupActions";
|
||||
import { CopyCommand, KeyForm, ConnectSupabaseButton, MigrateButton, ProjectPicker } from "./SetupActions";
|
||||
|
||||
export function ExtLink({ href, children }: { href: string; children: React.ReactNode }) {
|
||||
return (
|
||||
@@ -201,9 +201,10 @@ 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 === "connect" && (s.steps || s.fields) ? (
|
||||
{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">Button didn't work? Paste a connection string instead</summary>
|
||||
<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">
|
||||
<Steps steps={s.steps} />
|
||||
{form}
|
||||
|
||||
@@ -6,4 +6,8 @@ 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.",
|
||||
};
|
||||
+21
-3
@@ -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",
|
||||
|
||||
@@ -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
@@ -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(() => {});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user