g1t/apps/api/src/index.ts

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