g1t/apps/api/src/index.ts

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