g1t/apps/api/src/index.ts

229 lines9,031 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

API and MCP server, Rust identity service, registration, site redesign1import { Hono } from "hono";
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer2import { cors } from "hono/cors";
API and MCP server, Rust identity service, registration, site redesign3
Rust repos service with shipping; pull requests kept in the model4import {
5 type ServiceBinding,
6 type Viewer,
7 httpStatus,
8 identityClient,
9 reposClient,
Work service in Rust, with RFC 3339 timestamps10 workClient,
Rust repos service with shipping; pull requests kept in the model11} from "@g1t/contracts";
API and MCP server, Rust identity service, registration, site redesign12
13import { handleMcp } from "./mcp";
OAuth 2.1 sign-in for MCP clients and other applications14import { MCP_CHALLENGE, oauth } from "./oauth";
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer15import { openApiDocument } from "./openapi";
API and MCP server, Rust identity service, registration, site redesign16import { type ApiEnv, operations, operationsByName } from "./operations";
17
18type Input = Record<string, unknown>;
Rust repos service with shipping; pull requests kept in the model19/** The Worker's raw bindings; Rust services are reached through clients. */
Work service in Rust, with RFC 3339 timestamps20type Bindings = Omit<ApiEnv, "IDENTITY" | "REPOS" | "WORK"> & {
Rust repos service with shipping; pull requests kept in the model21 IDENTITY: ServiceBinding;
22 REPOS: ServiceBinding;
Work service in Rust, with RFC 3339 timestamps23 WORK: ServiceBinding;
Rust repos service with shipping; pull requests kept in the model24};
25type App = { Bindings: Bindings; Variables: { viewer: Viewer; services: ApiEnv } };
API and MCP server, Rust identity service, registration, site redesign26
27/**
28 * REST routes. Each maps an HTTP request onto one operation; `input` builds
29 * the operation's input from the path, query string and JSON body.
30 */
31const ROUTES: {
Issues and pull requests replace intents and attempts32 method: "GET" | "POST" | "PATCH";
API and MCP server, Rust identity service, registration, site redesign33 path: string;
34 operation: string;
35 input?: (params: Record<string, string>, query: Input, body: Input) => Input;
36}[] = [
37 { method: "GET", path: "/v1/user", operation: "whoami" },
Workspaces own repositories38 { method: "POST", path: "/v1/workspaces", operation: "create_workspace", input: (_p, _q, b) => b },
API and MCP server, Rust identity service, registration, site redesign39 { method: "GET", path: "/v1/repos", operation: "list_repos", input: (_p, q) => ({ query: q.q }) },
40 { method: "POST", path: "/v1/repos", operation: "create_repo", input: (_p, _q, b) => b },
41 { method: "GET", path: "/v1/repos/:owner/:name", operation: "get_repo", input: repo },
42 { method: "GET", path: "/v1/repos/:owner/:name/events", operation: "list_events", input: (p, q) => ({ ...repo(p), before: q.before }) },
Issues and pull requests replace intents and attempts43 { method: "GET", path: "/v1/repos/:owner/:name/labels", operation: "list_labels", input: repo },
44 { method: "GET", path: "/v1/repos/:owner/:name/issues", operation: "list_issues", input: (p, q) => ({ ...repo(p), state: q.state, label: q.label }) },
45 { method: "POST", path: "/v1/repos/:owner/:name/issues", operation: "create_issue", input: (p, _q, b) => ({ ...b, ...repo(p) }) },
46 { method: "GET", path: "/v1/repos/:owner/:name/issues/:number", operation: "get_issue", input: numbered },
47 { method: "PATCH", path: "/v1/repos/:owner/:name/issues/:number", operation: "update_issue", input: numbered },
48 { method: "POST", path: "/v1/repos/:owner/:name/issues/:number/close", operation: "close_issue", input: numbered },
49 { method: "POST", path: "/v1/repos/:owner/:name/issues/:number/reopen", operation: "reopen_issue", input: numbered },
50 { method: "POST", path: "/v1/repos/:owner/:name/issues/:number/comments", operation: "add_comment", input: numbered },
51 { method: "GET", path: "/v1/repos/:owner/:name/pulls", operation: "list_pull_requests", input: (p, q) => ({ ...repo(p), state: q.state }) },
52 { method: "POST", path: "/v1/repos/:owner/:name/pulls", operation: "create_pull_request", input: (p, _q, b) => ({ ...b, ...repo(p) }) },
53 { method: "GET", path: "/v1/repos/:owner/:name/pulls/:number", operation: "get_pull_request", input: numbered },
54 { method: "GET", path: "/v1/repos/:owner/:name/pulls/:number/changes", operation: "get_pull_request_changes", input: numbered },
55 { method: "GET", path: "/v1/repos/:owner/:name/pulls/:number/session", operation: "read_session", input: (p, q) => ({ ...numbered(p), after: Number(q.after) || 0 }) },
56 { method: "POST", path: "/v1/repos/:owner/:name/pulls/:number/session", operation: "record_session", input: numbered },
57 { method: "POST", path: "/v1/repos/:owner/:name/pulls/:number/ready", operation: "mark_pull_request_ready", input: numbered },
58 { method: "POST", path: "/v1/repos/:owner/:name/pulls/:number/close", operation: "close_pull_request", input: numbered },
59 { method: "POST", path: "/v1/repos/:owner/:name/pulls/:number/merge", operation: "merge_pull_request", input: numbered },
API and MCP server, Rust identity service, registration, site redesign60];
61
62function repo(params: Record<string, string>): Input {
63 return { repo: `${params.owner}/${params.name}` };
64}
65
Issues and pull requests replace intents and attempts66/** An issue or pull request named in the path, with the body's fields. */
67function numbered(params: Record<string, string>, _query: Input = {}, body: Input = {}): Input {
68 return { ...body, ...repo(params), number: Number(params.number) };
69}
70
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer71/** The section of the API reference an operation is listed under. */
72function tagFor(operation: string): string {
Workspaces own repositories73 if (operation === "whoami" || operation.includes("workspace")) return "Accounts";
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer74 if (operation.includes("session")) return "Sessions";
Issues and pull requests replace intents and attempts75 if (operation.includes("pull_request")) return "Pull requests";
76 if (/issue|label|comment/.test(operation)) return "Issues";
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer77 return "Repositories";
78}
79
API and MCP server, Rust identity service, registration, site redesign80const app = new Hono<App>();
81
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer82// The API is called from browsers too: the reference's explorer, and apps
83// built on g1t. It carries no cookies, so any origin may call it.
Issues and pull requests replace intents and attempts84app.use(cors({
85 origin: "*",
86 allowHeaders: ["authorization", "content-type"],
87 allowMethods: ["GET", "POST", "PATCH", "OPTIONS"],
88 }));
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer89
API and MCP server, Rust identity service, registration, site redesign90// `Authorization: Bearer g1t_…`. A missing token is an anonymous viewer; a
91// wrong one is rejected so a typo does not silently look signed out.
92app.use(async (c, next) => {
93 const [scheme, token] = (c.req.header("authorization") ?? "").split(" ");
Rust repos service with shipping; pull requests kept in the model94 const services: ApiEnv = {
95 ...c.env,
96 IDENTITY: identityClient(c.env.IDENTITY),
97 REPOS: reposClient(c.env.REPOS),
Work service in Rust, with RFC 3339 timestamps98 WORK: workClient(c.env.WORK),
Rust repos service with shipping; pull requests kept in the model99 };
100 c.set("services", services);
API and MCP server, Rust identity service, registration, site redesign101 let viewer: Viewer = null;
102 if (scheme?.toLowerCase() === "bearer" && token) {
Rust repos service with shipping; pull requests kept in the model103 viewer = await services.IDENTITY.userForAccessToken(token);
API and MCP server, Rust identity service, registration, site redesign104 if (!viewer) {
105 return c.json(
106 { error: { code: "unauthenticated", message: "Invalid access token." } },
107 401,
OAuth 2.1 sign-in for MCP clients and other applications108 // Tells an MCP client where to sign in again.
109 { "www-authenticate": `${MCP_CHALLENGE}, error="invalid_token"` },
API and MCP server, Rust identity service, registration, site redesign110 );
111 }
112 }
113 c.set("viewer", viewer);
114 await next();
115});
116
OAuth 2.1 sign-in for MCP clients and other applications117// Signing in with OAuth. Served on both hosts: an MCP client looks for the
118// metadata next to the MCP server.
119app.route("/", oauth);
120
API and MCP server, Rust identity service, registration, site redesign121app.all("*", async (c, next) => {
OAuth 2.1 sign-in for MCP clients and other applications122 if (!new URL(c.req.url).hostname.startsWith("mcp.")) return next();
123 const viewer = c.get("viewer");
124 // The MCP server needs a signed-in user. Saying so this way is what
125 // makes a client open the browser to sign in.
126 if (!viewer) {
127 return c.json(
128 {
129 error: {
130 code: "unauthenticated",
131 message: "Sign in to use the g1t MCP server.",
132 },
133 },
134 401,
135 { "www-authenticate": MCP_CHALLENGE },
136 );
API and MCP server, Rust identity service, registration, site redesign137 }
OAuth 2.1 sign-in for MCP clients and other applications138 return handleMcp(c.req.raw, c.get("services"), viewer);
API and MCP server, Rust identity service, registration, site redesign139});
140
Device sign-in replaces registering and minting tokens over the API141// Signing in from a tool. Accounts are created, and passwords typed, only
142// in a browser; a tool gets its token by having a person approve a code.
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)143
144async function jsonBody(request: Request): Promise<Record<string, unknown>> {
145 try {
146 return await request.json();
147 } catch {
148 return {};
149 }
150}
151
Device sign-in replaces registering and minting tokens over the API152app.post("/v1/device/code", async (c) => {
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)153 const body = await jsonBody(c.req.raw);
Device sign-in replaces registering and minting tokens over the API154 const started = await c
155 .get("services")
156 .IDENTITY.deviceStart(String(body.client_name ?? ""));
157 return c.json({
158 device_code: started.deviceCode,
159 user_code: started.userCode,
160 verification_uri: "https://g1t.sh/device",
161 verification_uri_complete: `https://g1t.sh/device?code=${started.userCode}`,
162 expires_in: started.expiresIn,
163 interval: started.interval,
164 });
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)165});
166
Device sign-in replaces registering and minting tokens over the API167app.post("/v1/device/token", async (c) => {
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)168 const body = await jsonBody(c.req.raw);
Device sign-in replaces registering and minting tokens over the API169 const claim = await c
170 .get("services")
171 .IDENTITY.deviceClaim(String(body.device_code ?? ""));
172 if (claim.status !== "approved") return c.json({ status: claim.status });
173 return c.json({
174 status: "approved",
175 token: claim.token,
176 username: claim.user.username,
177 verified: claim.user.verified === true,
178 });
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)179});
180
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer181app.get("/openapi.json", (c) =>
182 c.json(
183 openApiDocument(
184 ROUTES.map(({ method, path, operation }) => ({
185 method,
186 path,
187 operation,
188 tag: tagFor(operation),
189 })),
190 ),
191 ),
192);
193
API and MCP server, Rust identity service, registration, site redesign194app.get("/", (c) =>
195 c.json({
196 name: "g1t API",
197 version: "v1",
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer198 documentation: "https://docs.g1t.sh/api",
199 openapi: "https://api.g1t.sh/openapi.json",
API and MCP server, Rust identity service, registration, site redesign200 operations: operations.map(({ name, description }) => ({ name, description })),
201 }),
202);
203
204for (const route of ROUTES) {
205 const operation = operationsByName.get(route.operation)!;
206 app.on(route.method, route.path, async (c) => {
207 let body: Input = {};
Issues and pull requests replace intents and attempts208 if (route.method !== "GET") {
API and MCP server, Rust identity service, registration, site redesign209 try {
210 body = await c.req.json();
211 } catch {
212 // An empty or non-JSON body is treated as no input.
213 }
214 }
215 const input = route.input?.(c.req.param(), c.req.query(), body) ?? {};
Rust repos service with shipping; pull requests kept in the model216 const outcome = await operation.run(c.get("services"), c.get("viewer"), input);
API and MCP server, Rust identity service, registration, site redesign217 if (outcome.ok) return c.json(outcome.value);
218 return c.json(
219 { error: outcome.error },
220 httpStatus(outcome.error) as 401 | 403 | 404 | 409 | 422,
221 );
222 });
223}
224
225app.notFound((c) =>
226 c.json({ error: { code: "not_found", message: "No such endpoint." } }, 404),
227);
228
229export default app;