g1t/apps/api/src/index.ts

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