g1t/apps/api/src/index.ts

229 lines9,031 bytesCodeBlame
1import { Hono } from "hono";
2import { cors } from "hono/cors";
3
4import {
5 type ServiceBinding,
6 type Viewer,
7 httpStatus,
8 identityClient,
9 reposClient,
10 workClient,
11} from "@g1t/contracts";
12
13import { handleMcp } from "./mcp";
14import { MCP_CHALLENGE, oauth } from "./oauth";
15import { openApiDocument } from "./openapi";
16import { type ApiEnv, operations, operationsByName } from "./operations";
17
18type Input = Record<string, unknown>;
19/** The Worker's raw bindings; Rust services are reached through clients. */
20type Bindings = Omit<ApiEnv, "IDENTITY" | "REPOS" | "WORK"> & {
21 IDENTITY: ServiceBinding;
22 REPOS: ServiceBinding;
23 WORK: ServiceBinding;
24};
25type App = { Bindings: Bindings; Variables: { viewer: Viewer; services: ApiEnv } };
26
27/**
28 * REST routes. Each maps an HTTP request onto one operation; `input` builds
29 * the operation's input from the path, query string and JSON body.
30 */
31const ROUTES: {
32 method: "GET" | "POST" | "PATCH";
33 path: string;
34 operation: string;
35 input?: (params: Record<string, string>, query: Input, body: Input) => Input;
36}[] = [
37 { method: "GET", path: "/v1/user", operation: "whoami" },
38 { method: "POST", path: "/v1/workspaces", operation: "create_workspace", input: (_p, _q, b) => b },
39 { method: "GET", path: "/v1/repos", operation: "list_repos", input: (_p, q) => ({ query: q.q }) },
40 { method: "POST", path: "/v1/repos", operation: "create_repo", input: (_p, _q, b) => b },
41 { method: "GET", path: "/v1/repos/:owner/:name", operation: "get_repo", input: repo },
42 { method: "GET", path: "/v1/repos/:owner/:name/events", operation: "list_events", input: (p, q) => ({ ...repo(p), before: q.before }) },
43 { method: "GET", path: "/v1/repos/:owner/:name/labels", operation: "list_labels", input: repo },
44 { method: "GET", path: "/v1/repos/:owner/:name/issues", operation: "list_issues", input: (p, q) => ({ ...repo(p), state: q.state, label: q.label }) },
45 { method: "POST", path: "/v1/repos/:owner/:name/issues", operation: "create_issue", input: (p, _q, b) => ({ ...b, ...repo(p) }) },
46 { method: "GET", path: "/v1/repos/:owner/:name/issues/:number", operation: "get_issue", input: numbered },
47 { method: "PATCH", path: "/v1/repos/:owner/:name/issues/:number", operation: "update_issue", input: numbered },
48 { method: "POST", path: "/v1/repos/:owner/:name/issues/:number/close", operation: "close_issue", input: numbered },
49 { method: "POST", path: "/v1/repos/:owner/:name/issues/:number/reopen", operation: "reopen_issue", input: numbered },
50 { method: "POST", path: "/v1/repos/:owner/:name/issues/:number/comments", operation: "add_comment", input: numbered },
51 { method: "GET", path: "/v1/repos/:owner/:name/pulls", operation: "list_pull_requests", input: (p, q) => ({ ...repo(p), state: q.state }) },
52 { method: "POST", path: "/v1/repos/:owner/:name/pulls", operation: "create_pull_request", input: (p, _q, b) => ({ ...b, ...repo(p) }) },
53 { method: "GET", path: "/v1/repos/:owner/:name/pulls/:number", operation: "get_pull_request", input: numbered },
54 { method: "GET", path: "/v1/repos/:owner/:name/pulls/:number/changes", operation: "get_pull_request_changes", input: numbered },
55 { method: "GET", path: "/v1/repos/:owner/:name/pulls/:number/session", operation: "read_session", input: (p, q) => ({ ...numbered(p), after: Number(q.after) || 0 }) },
56 { method: "POST", path: "/v1/repos/:owner/:name/pulls/:number/session", operation: "record_session", input: numbered },
57 { method: "POST", path: "/v1/repos/:owner/:name/pulls/:number/ready", operation: "mark_pull_request_ready", input: numbered },
58 { method: "POST", path: "/v1/repos/:owner/:name/pulls/:number/close", operation: "close_pull_request", input: numbered },
59 { method: "POST", path: "/v1/repos/:owner/:name/pulls/:number/merge", operation: "merge_pull_request", input: numbered },
60];
61
62function repo(params: Record<string, string>): Input {
63 return { repo: `${params.owner}/${params.name}` };
64}
65
66/** An issue or pull request named in the path, with the body's fields. */
67function numbered(params: Record<string, string>, _query: Input = {}, body: Input = {}): Input {
68 return { ...body, ...repo(params), number: Number(params.number) };
69}
70
71/** The section of the API reference an operation is listed under. */
72function tagFor(operation: string): string {
73 if (operation === "whoami" || operation.includes("workspace")) return "Accounts";
74 if (operation.includes("session")) return "Sessions";
75 if (operation.includes("pull_request")) return "Pull requests";
76 if (/issue|label|comment/.test(operation)) return "Issues";
77 return "Repositories";
78}
79
80const app = new Hono<App>();
81
82// The API is called from browsers too: the reference's explorer, and apps
83// built on g1t. It carries no cookies, so any origin may call it.
84app.use(cors({
85 origin: "*",
86 allowHeaders: ["authorization", "content-type"],
87 allowMethods: ["GET", "POST", "PATCH", "OPTIONS"],
88 }));
89
90// `Authorization: Bearer g1t_…`. A missing token is an anonymous viewer; a
91// wrong one is rejected so a typo does not silently look signed out.
92app.use(async (c, next) => {
93 const [scheme, token] = (c.req.header("authorization") ?? "").split(" ");
94 const services: ApiEnv = {
95 ...c.env,
96 IDENTITY: identityClient(c.env.IDENTITY),
97 REPOS: reposClient(c.env.REPOS),
98 WORK: workClient(c.env.WORK),
99 };
100 c.set("services", services);
101 let viewer: Viewer = null;
102 if (scheme?.toLowerCase() === "bearer" && token) {
103 viewer = await services.IDENTITY.userForAccessToken(token);
104 if (!viewer) {
105 return c.json(
106 { error: { code: "unauthenticated", message: "Invalid access token." } },
107 401,
108 // Tells an MCP client where to sign in again.
109 { "www-authenticate": `${MCP_CHALLENGE}, error="invalid_token"` },
110 );
111 }
112 }
113 c.set("viewer", viewer);
114 await next();
115});
116
117// Signing in with OAuth. Served on both hosts: an MCP client looks for the
118// metadata next to the MCP server.
119app.route("/", oauth);
120
121app.all("*", async (c, next) => {
122 if (!new URL(c.req.url).hostname.startsWith("mcp.")) return next();
123 const viewer = c.get("viewer");
124 // The MCP server needs a signed-in user. Saying so this way is what
125 // makes a client open the browser to sign in.
126 if (!viewer) {
127 return c.json(
128 {
129 error: {
130 code: "unauthenticated",
131 message: "Sign in to use the g1t MCP server.",
132 },
133 },
134 401,
135 { "www-authenticate": MCP_CHALLENGE },
136 );
137 }
138 return handleMcp(c.req.raw, c.get("services"), viewer);
139});
140
141// Signing in from a tool. Accounts are created, and passwords typed, only
142// in a browser; a tool gets its token by having a person approve a code.
143
144async function jsonBody(request: Request): Promise<Record<string, unknown>> {
145 try {
146 return await request.json();
147 } catch {
148 return {};
149 }
150}
151
152app.post("/v1/device/code", async (c) => {
153 const body = await jsonBody(c.req.raw);
154 const started = await c
155 .get("services")
156 .IDENTITY.deviceStart(String(body.client_name ?? ""));
157 return c.json({
158 device_code: started.deviceCode,
159 user_code: started.userCode,
160 verification_uri: "https://g1t.sh/device",
161 verification_uri_complete: `https://g1t.sh/device?code=${started.userCode}`,
162 expires_in: started.expiresIn,
163 interval: started.interval,
164 });
165});
166
167app.post("/v1/device/token", async (c) => {
168 const body = await jsonBody(c.req.raw);
169 const claim = await c
170 .get("services")
171 .IDENTITY.deviceClaim(String(body.device_code ?? ""));
172 if (claim.status !== "approved") return c.json({ status: claim.status });
173 return c.json({
174 status: "approved",
175 token: claim.token,
176 username: claim.user.username,
177 verified: claim.user.verified === true,
178 });
179});
180
181app.get("/openapi.json", (c) =>
182 c.json(
183 openApiDocument(
184 ROUTES.map(({ method, path, operation }) => ({
185 method,
186 path,
187 operation,
188 tag: tagFor(operation),
189 })),
190 ),
191 ),
192);
193
194app.get("/", (c) =>
195 c.json({
196 name: "g1t API",
197 version: "v1",
198 documentation: "https://docs.g1t.sh/api",
199 openapi: "https://api.g1t.sh/openapi.json",
200 operations: operations.map(({ name, description }) => ({ name, description })),
201 }),
202);
203
204for (const route of ROUTES) {
205 const operation = operationsByName.get(route.operation)!;
206 app.on(route.method, route.path, async (c) => {
207 let body: Input = {};
208 if (route.method !== "GET") {
209 try {
210 body = await c.req.json();
211 } catch {
212 // An empty or non-JSON body is treated as no input.
213 }
214 }
215 const input = route.input?.(c.req.param(), c.req.query(), body) ?? {};
216 const outcome = await operation.run(c.get("services"), c.get("viewer"), input);
217 if (outcome.ok) return c.json(outcome.value);
218 return c.json(
219 { error: outcome.error },
220 httpStatus(outcome.error) as 401 | 403 | 404 | 409 | 422,
221 );
222 });
223}
224
225app.notFound((c) =>
226 c.json({ error: { code: "not_found", message: "No such endpoint." } }, 404),
227);
228
229export default app;