| 1 | import { Hono } from "hono"; |
| 2 | import { cors } from "hono/cors"; |
| 3 | |
| 4 | import { |
| 5 | type ServiceBinding, |
| 6 | type Viewer, |
| 7 | httpStatus, |
| 8 | identityClient, |
| 9 | reposClient, |
| 10 | } from "@g1t/contracts"; |
| 11 | |
| 12 | import { handleMcp } from "./mcp"; |
| 13 | import { openApiDocument } from "./openapi"; |
| 14 | import { type ApiEnv, operations, operationsByName } from "./operations"; |
| 15 | |
| 16 | type Input = Record<string, unknown>; |
| 17 | /** The Worker's raw bindings; Rust services are reached through clients. */ |
| 18 | type Bindings = Omit<ApiEnv, "IDENTITY" | "REPOS"> & { |
| 19 | IDENTITY: ServiceBinding; |
| 20 | REPOS: ServiceBinding; |
| 21 | }; |
| 22 | type 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 | */ |
| 28 | const 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 | |
| 52 | function 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. */ |
| 57 | function 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 | |
| 65 | const 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. |
| 69 | app.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. |
| 73 | app.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 | |
| 95 | app.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 | // Onboarding. These two are REST only: they take a password, which has no |
| 103 | // place in an agent's tool call. |
| 104 | |
| 105 | async function jsonBody(request: Request): Promise<Record<string, unknown>> { |
| 106 | try { |
| 107 | return await request.json(); |
| 108 | } catch { |
| 109 | return {}; |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | app.post("/v1/register", async (c) => { |
| 114 | const body = await jsonBody(c.req.raw); |
| 115 | const result = await c.get("services").IDENTITY.register( |
| 116 | String(body.username ?? ""), |
| 117 | String(body.email ?? ""), |
| 118 | String(body.password ?? ""), |
| 119 | ); |
| 120 | if (!result.ok) { |
| 121 | return c.json({ error: result.error }, httpStatus(result.error) as 409 | 422); |
| 122 | } |
| 123 | return c.json( |
| 124 | { |
| 125 | user: result.value.user, |
| 126 | next: "A confirmation link was sent to that email address. The account cannot create or push anything until the link is opened.", |
| 127 | }, |
| 128 | 201, |
| 129 | ); |
| 130 | }); |
| 131 | |
| 132 | app.post("/v1/tokens", async (c) => { |
| 133 | const body = await jsonBody(c.req.raw); |
| 134 | const identity = c.get("services").IDENTITY; |
| 135 | const password = String(body.password ?? ""); |
| 136 | // An existing token must not be usable to mint more tokens. |
| 137 | const user = password.startsWith("g1t_") |
| 138 | ? null |
| 139 | : await identity.userForGitCredentials(String(body.username ?? ""), password); |
| 140 | if (!user) { |
| 141 | return c.json( |
| 142 | { error: { code: "unauthenticated", message: "Incorrect username or password." } }, |
| 143 | 401, |
| 144 | ); |
| 145 | } |
| 146 | const created = await identity.createAccessToken(user, String(body.name ?? "")); |
| 147 | return c.json({ token: created.token, verified: user.verified === true }, 201); |
| 148 | }); |
| 149 | |
| 150 | app.get("/openapi.json", (c) => |
| 151 | c.json( |
| 152 | openApiDocument( |
| 153 | ROUTES.map(({ method, path, operation }) => ({ |
| 154 | method, |
| 155 | path, |
| 156 | operation, |
| 157 | tag: tagFor(operation), |
| 158 | })), |
| 159 | ), |
| 160 | ), |
| 161 | ); |
| 162 | |
| 163 | app.get("/", (c) => |
| 164 | c.json({ |
| 165 | name: "g1t API", |
| 166 | version: "v1", |
| 167 | documentation: "https://docs.g1t.sh/api", |
| 168 | openapi: "https://api.g1t.sh/openapi.json", |
| 169 | operations: operations.map(({ name, description }) => ({ name, description })), |
| 170 | }), |
| 171 | ); |
| 172 | |
| 173 | for (const route of ROUTES) { |
| 174 | const operation = operationsByName.get(route.operation)!; |
| 175 | app.on(route.method, route.path, async (c) => { |
| 176 | let body: Input = {}; |
| 177 | if (route.method === "POST") { |
| 178 | try { |
| 179 | body = await c.req.json(); |
| 180 | } catch { |
| 181 | // An empty or non-JSON body is treated as no input. |
| 182 | } |
| 183 | } |
| 184 | const input = route.input?.(c.req.param(), c.req.query(), body) ?? {}; |
| 185 | const outcome = await operation.run(c.get("services"), c.get("viewer"), input); |
| 186 | if (outcome.ok) return c.json(outcome.value); |
| 187 | return c.json( |
| 188 | { error: outcome.error }, |
| 189 | httpStatus(outcome.error) as 401 | 403 | 404 | 409 | 422, |
| 190 | ); |
| 191 | }); |
| 192 | } |
| 193 | |
| 194 | app.notFound((c) => |
| 195 | c.json({ error: { code: "not_found", message: "No such endpoint." } }, 404), |
| 196 | ); |
| 197 | |
| 198 | export default app; |