g1t/apps/api/src/index.ts

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