Branchwell

Bucksley / app · bucksley.ai / connect / src / index.ts

1// Sign in with Coinbase for the Bucksley Mac app, as a Cloudflare Worker. Coinbase needs a client
2// secret to swap a sign-in code for tokens, and an app can't keep a secret, so this Worker adds it
3// and passes the request through. It has no storage, keeps nothing and logs no tokens.
4
5interface Env {
6 COINBASE_CLIENT_ID?: string;
7 COINBASE_CLIENT_SECRET?: string;
8 COINBASE_REDIRECT_URI?: string;
9}
10
11const SCOPE = "wallet:accounts:read,offline_access";
12const APP_CALLBACK = "bucksley://coinbase/callback";
13const TOKEN_URL = "https://login.coinbase.com/oauth2/token";
14const noStore = { "Cache-Control": "no-store" };
15
16const json = (body: unknown, status = 200) => Response.json(body, { status, headers: noStore });
17const redirectURI = (env: Env) => env.COINBASE_REDIRECT_URI ?? "https://connect.bucksley.ai/oauth/callback";
18const text = (value: unknown, max = 4096) =>
19 typeof value === "string" && value.length > 0 && value.length <= max ? value : undefined;
20
21// The public half of the sign-in: what the app needs to open Coinbase's page.
22function config(env: Env): Response {
23 if (!env.COINBASE_CLIENT_ID) return json({ error: "not_configured" }, 503);
24 return json({ client_id: env.COINBASE_CLIENT_ID, redirect_uri: redirectURI(env), scope: SCOPE });
25}
26
27// Coinbase only redirects to https, so it lands here and goes straight on to the app's sign-in
28// sheet with the same code, state or error.
29function callback(url: URL): Response {
30 const out = new URL(APP_CALLBACK);
31 for (const name of ["code", "state", "error", "error_description"]) {
32 const value = url.searchParams.get(name);
33 if (value) out.searchParams.set(name, value.slice(0, 2048));
34 }
35 if (!out.searchParams.has("code") && !out.searchParams.has("error")) out.searchParams.set("error", "missing_code");
36 return new Response(null, { status: 302, headers: { Location: out.toString(), ...noStore, "Referrer-Policy": "no-referrer" } });
37}
38
39// Swaps a sign-in code (with its PKCE verifier) or a refresh token for new tokens. Only these two
40// grants, only to Coinbase's token endpoint, and only the tokens go back to the app.
41async function token(request: Request, env: Env): Promise<Response> {
42 const id = env.COINBASE_CLIENT_ID, secret = env.COINBASE_CLIENT_SECRET;
43 if (!id || !secret) return json({ error: "not_configured" }, 503);
44
45 let body: Record<string, unknown>;
46 try {
47 const raw = await request.text();
48 if (raw.length > 16_384) throw new Error("too large");
49 body = JSON.parse(raw);
50 } catch {
51 return json({ error: "invalid_request" }, 400);
52 }
53
54 const form = new URLSearchParams({ client_id: id, client_secret: secret });
55 if (body.grant_type === "authorization_code") {
56 const code = text(body.code), verifier = text(body.code_verifier, 128);
57 if (!code || !verifier) return json({ error: "invalid_request" }, 400);
58 form.set("grant_type", "authorization_code");
59 form.set("code", code);
60 form.set("code_verifier", verifier);
61 form.set("redirect_uri", redirectURI(env));
62 } else if (body.grant_type === "refresh_token") {
63 const refresh = text(body.refresh_token);
64 if (!refresh) return json({ error: "invalid_request" }, 400);
65 form.set("grant_type", "refresh_token");
66 form.set("refresh_token", refresh);
67 } else {
68 return json({ error: "unsupported_grant_type" }, 400);
69 }
70
71 const upstream = await fetch(TOKEN_URL, {
72 method: "POST",
73 headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
74 body: form,
75 });
76 const answer = (await upstream.json().catch(() => ({}))) as Record<string, unknown>;
77 if (!upstream.ok || typeof answer.access_token !== "string" || typeof answer.refresh_token !== "string") {
78 const error = typeof answer.error === "string" ? answer.error : "coinbase_error";
79 return json({ error }, upstream.status === 200 ? 502 : upstream.status);
80 }
81 return json({ access_token: answer.access_token, refresh_token: answer.refresh_token, expires_in: answer.expires_in, scope: answer.scope });
82}
83
84const home = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
85<title>Bucksley Connect</title>
86<body style="font:16px/1.5 -apple-system,system-ui,sans-serif;max-width:36rem;margin:4rem auto;padding:0 1rem;color:#222">
87<h1 style="font-size:1.4rem">Bucksley Connect</h1>
88<p>This is the sign-in helper for <a href="https://bucksley.ai">Bucksley</a>. When you sign in with Coinbase, it hands Coinbase's one-time code back to the app on your Mac. It has no database and keeps nothing.</p>
89</body>`;
90
91export default {
92 async fetch(request: Request, env: Env): Promise<Response> {
93 const url = new URL(request.url);
94 const route = `${request.method} ${url.pathname}`;
95 if (route === "GET /coinbase/config") return config(env);
96 if (route === "GET /oauth/callback") return callback(url);
97 if (route === "POST /coinbase/token") return token(request, env);
98 if (route === "GET /") return new Response(home, { headers: { "Content-Type": "text/html; charset=utf-8" } });
99 return json({ error: "not_found" }, 404);
100 },
101};