g1t/apps/api/src/index.ts

193 lines7,114 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";
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: "GET", path: "/v1/repos", operation: "list_repos", input: (_p, q) => ({ query: q.q }) },
38 { method: "POST", path: "/v1/repos", operation: "create_repo", input: (_p, _q, b) => b },
39 { method: "GET", path: "/v1/repos/:owner/:name", operation: "get_repo", input: repo },
40 { method: "GET", path: "/v1/repos/:owner/:name/intents", operation: "list_intents", input: (p, q) => ({ ...repo(p), status: q.status }) },
41 { method: "POST", path: "/v1/repos/:owner/:name/intents", operation: "open_intent", input: (p, _q, b) => ({ ...b, ...repo(p) }) },
42 { method: "GET", path: "/v1/repos/:owner/:name/intents/:number", operation: "get_intent", input: (p) => ({ ...repo(p), number: Number(p.number) }) },
43 { method: "GET", path: "/v1/repos/:owner/:name/events", operation: "list_events", input: (p, q) => ({ ...repo(p), before: q.before }) },
44 { method: "POST", path: "/v1/intents/:intent_id/attempts", operation: "start_attempt", input: (p, _q, b) => ({ ...b, intent_id: p.intent_id }) },
45 { method: "GET", path: "/v1/attempts/:attempt_id", operation: "get_attempt", input: (p) => p },
46 { method: "GET", path: "/v1/attempts/:attempt_id/session", operation: "read_session", input: (p, q) => ({ ...p, after: Number(q.after) || 0 }) },
47 { method: "POST", path: "/v1/attempts/:attempt_id/session", operation: "record_session", input: (p, _q, b) => ({ ...b, ...p }) },
48 { method: "POST", path: "/v1/attempts/:attempt_id/submit", operation: "submit_attempt", input: (p, _q, b) => ({ ...b, ...p }) },
49 { method: "POST", path: "/v1/attempts/:attempt_id/abandon", operation: "abandon_attempt", input: (p) => p },
50 { method: "POST", path: "/v1/attempts/:attempt_id/ship", operation: "ship_attempt", input: (p) => p },
51 { method: "GET", path: "/v1/attempts/:attempt_id/changes", operation: "get_attempt_changes", input: (p) => p },
52];
53
54function repo(params: Record<string, string>): Input {
55 return { repo: `${params.owner}/${params.name}` };
56}
57
58/** The section of the API reference an operation is listed under. */
59function tagFor(operation: string): string {
60 if (operation === "whoami") return "Accounts";
61 if (operation.includes("session")) return "Sessions";
62 if (operation.includes("attempt")) return "Attempts";
63 if (operation.includes("intent")) return "Intents";
64 return "Repositories";
65}
66
67const app = new Hono<App>();
68
69// The API is called from browsers too: the reference's explorer, and apps
70// built on g1t. It carries no cookies, so any origin may call it.
71app.use(cors({ origin: "*", allowHeaders: ["authorization", "content-type"] }));
72
73// `Authorization: Bearer g1t_…`. A missing token is an anonymous viewer; a
74// wrong one is rejected so a typo does not silently look signed out.
75app.use(async (c, next) => {
76 const [scheme, token] = (c.req.header("authorization") ?? "").split(" ");
77 const services: ApiEnv = {
78 ...c.env,
79 IDENTITY: identityClient(c.env.IDENTITY),
80 REPOS: reposClient(c.env.REPOS),
81 WORK: workClient(c.env.WORK),
82 };
83 c.set("services", services);
84 let viewer: Viewer = null;
85 if (scheme?.toLowerCase() === "bearer" && token) {
86 viewer = await services.IDENTITY.userForAccessToken(token);
87 if (!viewer) {
88 return c.json(
89 { error: { code: "unauthenticated", message: "Invalid access token." } },
90 401,
91 );
92 }
93 }
94 c.set("viewer", viewer);
95 await next();
96});
97
98app.all("*", async (c, next) => {
99 if (new URL(c.req.url).hostname.startsWith("mcp.")) {
100 return handleMcp(c.req.raw, c.get("services"), c.get("viewer"));
101 }
102 await next();
103});
104
105// Signing in from a tool. Accounts are created, and passwords typed, only
106// in a browser; a tool gets its token by having a person approve a code.
107
108async function jsonBody(request: Request): Promise<Record<string, unknown>> {
109 try {
110 return await request.json();
111 } catch {
112 return {};
113 }
114}
115
116app.post("/v1/device/code", async (c) => {
117 const body = await jsonBody(c.req.raw);
118 const started = await c
119 .get("services")
120 .IDENTITY.deviceStart(String(body.client_name ?? ""));
121 return c.json({
122 device_code: started.deviceCode,
123 user_code: started.userCode,
124 verification_uri: "https://g1t.sh/device",
125 verification_uri_complete: `https://g1t.sh/device?code=${started.userCode}`,
126 expires_in: started.expiresIn,
127 interval: started.interval,
128 });
129});
130
131app.post("/v1/device/token", async (c) => {
132 const body = await jsonBody(c.req.raw);
133 const claim = await c
134 .get("services")
135 .IDENTITY.deviceClaim(String(body.device_code ?? ""));
136 if (claim.status !== "approved") return c.json({ status: claim.status });
137 return c.json({
138 status: "approved",
139 token: claim.token,
140 username: claim.user.username,
141 verified: claim.user.verified === true,
142 });
143});
144
145app.get("/openapi.json", (c) =>
146 c.json(
147 openApiDocument(
148 ROUTES.map(({ method, path, operation }) => ({
149 method,
150 path,
151 operation,
152 tag: tagFor(operation),
153 })),
154 ),
155 ),
156);
157
158app.get("/", (c) =>
159 c.json({
160 name: "g1t API",
161 version: "v1",
162 documentation: "https://docs.g1t.sh/api",
163 openapi: "https://api.g1t.sh/openapi.json",
164 operations: operations.map(({ name, description }) => ({ name, description })),
165 }),
166);
167
168for (const route of ROUTES) {
169 const operation = operationsByName.get(route.operation)!;
170 app.on(route.method, route.path, async (c) => {
171 let body: Input = {};
172 if (route.method === "POST") {
173 try {
174 body = await c.req.json();
175 } catch {
176 // An empty or non-JSON body is treated as no input.
177 }
178 }
179 const input = route.input?.(c.req.param(), c.req.query(), body) ?? {};
180 const outcome = await operation.run(c.get("services"), c.get("viewer"), input);
181 if (outcome.ok) return c.json(outcome.value);
182 return c.json(
183 { error: outcome.error },
184 httpStatus(outcome.error) as 401 | 403 | 404 | 409 | 422,
185 );
186 });
187}
188
189app.notFound((c) =>
190 c.json({ error: { code: "not_found", message: "No such endpoint." } }, 404),
191);
192
193export default app;