Blame · Line-by-line history
api.ts
Each line is annotated with the commit that last touched it. Click any SHA to jump to that commit and see the surrounding change.
| fc1817a | 1 | /** |
| 2 | * REST API routes for repository management. | |
| 3 | */ | |
| 4 | ||
| 5 | import { Hono } from "hono"; | |
| 8102dd4 | 6 | import type { AuthEnv } from "../middleware/auth"; |
| 829a046 | 7 | import { eq, and, isNull, ilike, sql } from "drizzle-orm"; |
| fc1817a | 8 | import { db } from "../db"; |
| 7437605 | 9 | import { users, repositories, organizations, orgMembers } from "../db/schema"; |
| fc1817a | 10 | import { initBareRepo, repoExists } from "../git/repository"; |
| 06d5ffe | 11 | import { hashPassword } from "../lib/auth"; |
| 7437605 | 12 | import { orgRoleAtLeast } from "../lib/orgs"; |
| 6cd2f0e | 13 | import { renderMarkdown } from "../lib/markdown"; |
| fc1817a | 14 | |
| 8102dd4 | 15 | // Typed with AuthEnv so handlers can read the viewer that the global |
| 16 | // `softAuth` middleware already resolved (needed for private-repo gating). | |
| 17 | const api = new Hono<AuthEnv>().basePath("/api"); | |
| fc1817a | 18 | |
| 19 | // Create repository | |
| 20 | api.post("/repos", async (c) => { | |
| 63807e5 | 21 | let body: { |
| fc1817a | 22 | name: string; |
| 23 | owner: string; | |
| 7437605 | 24 | orgSlug?: string; |
| fc1817a | 25 | description?: string; |
| 26 | isPrivate?: boolean; | |
| 63807e5 | 27 | }; |
| 28 | try { | |
| 29 | body = await c.req.json(); | |
| 30 | } catch { | |
| 31 | return c.json({ error: "Invalid JSON body" }, 400); | |
| 32 | } | |
| fc1817a | 33 | |
| 34 | if (!body.name || !body.owner) { | |
| 35 | return c.json({ error: "name and owner are required" }, 400); | |
| 36 | } | |
| 37 | ||
| 38 | // Validate repo name | |
| 39 | if (!/^[a-zA-Z0-9._-]+$/.test(body.name)) { | |
| 40 | return c.json({ error: "Invalid repository name" }, 400); | |
| 41 | } | |
| 2cd3bb4 | 42 | // Normalize to lowercase — repo slugs are canonically lowercase so |
| 43 | // "MyRepo" and "myrepo" can't both exist and cause "Vapron" vs "vapron" | |
| 44 | // confusion. Applied before the duplicate checks + on-disk init below. | |
| 45 | body.name = body.name.toLowerCase(); | |
| fc1817a | 46 | |
| 63807e5 | 47 | try { |
| 7437605 | 48 | // Find creator (user who is performing the action) |
| 63807e5 | 49 | const [owner] = await db |
| 50 | .select() | |
| 51 | .from(users) | |
| 52 | .where(eq(users.username, body.owner)); | |
| fc1817a | 53 | |
| 63807e5 | 54 | if (!owner) { |
| 55 | return c.json({ error: "Owner not found" }, 404); | |
| 56 | } | |
| fc1817a | 57 | |
| 7437605 | 58 | // B2: if orgSlug supplied, place the repo in the org namespace. |
| 59 | // Requires the creator to be an admin+ of the org. | |
| 60 | let orgId: string | null = null; | |
| 61 | let namespaceSlug = body.owner; | |
| 62 | if (body.orgSlug) { | |
| 63 | const [org] = await db | |
| 64 | .select({ id: organizations.id, slug: organizations.slug }) | |
| 65 | .from(organizations) | |
| 66 | .where(eq(organizations.slug, body.orgSlug)) | |
| 67 | .limit(1); | |
| 68 | if (!org) return c.json({ error: "Organization not found" }, 404); | |
| 69 | ||
| 70 | const [mem] = await db | |
| 71 | .select({ role: orgMembers.role }) | |
| 72 | .from(orgMembers) | |
| 73 | .where( | |
| 74 | and(eq(orgMembers.orgId, org.id), eq(orgMembers.userId, owner.id)) | |
| 75 | ) | |
| 76 | .limit(1); | |
| 77 | if (!mem || !orgRoleAtLeast(mem.role, "admin")) { | |
| 78 | return c.json({ error: "Admin rights required on org" }, 403); | |
| 79 | } | |
| 80 | orgId = org.id; | |
| 81 | namespaceSlug = org.slug; | |
| 82 | } | |
| 83 | ||
| 84 | // Duplicate check: scoped to the right namespace. | |
| 85 | if (orgId) { | |
| 86 | const [existing] = await db | |
| 87 | .select({ id: repositories.id }) | |
| 88 | .from(repositories) | |
| 89 | .where( | |
| 90 | and(eq(repositories.orgId, orgId), eq(repositories.name, body.name)) | |
| 91 | ) | |
| 92 | .limit(1); | |
| 93 | if (existing) { | |
| 94 | return c.json({ error: "Repository already exists" }, 409); | |
| 95 | } | |
| 96 | } else { | |
| 97 | const [existing] = await db | |
| 98 | .select({ id: repositories.id }) | |
| 99 | .from(repositories) | |
| 100 | .where( | |
| 101 | and( | |
| 102 | eq(repositories.ownerId, owner.id), | |
| 103 | eq(repositories.name, body.name), | |
| 104 | isNull(repositories.orgId) | |
| 105 | ) | |
| 106 | ) | |
| 107 | .limit(1); | |
| 108 | if (existing) { | |
| 109 | return c.json({ error: "Repository already exists" }, 409); | |
| 110 | } | |
| 111 | } | |
| 112 | if (await repoExists(namespaceSlug, body.name)) { | |
| 63807e5 | 113 | return c.json({ error: "Repository already exists" }, 409); |
| 114 | } | |
| fc1817a | 115 | |
| 7437605 | 116 | // Init bare repo on disk, keyed by the namespace slug (user or org). |
| 117 | const diskPath = await initBareRepo(namespaceSlug, body.name); | |
| 63807e5 | 118 | |
| 119 | // Insert into DB | |
| 120 | const [repo] = await db | |
| 121 | .insert(repositories) | |
| 122 | .values({ | |
| 123 | name: body.name, | |
| 124 | ownerId: owner.id, | |
| 7437605 | 125 | orgId, |
| 63807e5 | 126 | description: body.description || null, |
| 127 | isPrivate: body.isPrivate || false, | |
| 128 | diskPath, | |
| 129 | }) | |
| 130 | .returning(); | |
| 3ef4c9d | 131 | |
| 63807e5 | 132 | // Green-ecosystem bootstrap: settings, protection, labels, welcome issue |
| 133 | if (repo) { | |
| cde9983 | 134 | const { bootstrapRepository, ensureAiBuildSeedIssue } = await import("../lib/repo-bootstrap"); |
| 63807e5 | 135 | await bootstrapRepository({ |
| 136 | repositoryId: repo.id, | |
| 137 | ownerUserId: owner.id, | |
| 138 | }); | |
| cde9983 | 139 | // Fire-and-forget — never block the response |
| 140 | ensureAiBuildSeedIssue(repo.id, owner.id).catch(err => | |
| 141 | console.warn('[ai-build-seed]', err?.message) | |
| 142 | ); | |
| 63807e5 | 143 | } |
| fc1817a | 144 | |
| 63807e5 | 145 | return c.json(repo, 201); |
| 146 | } catch (err) { | |
| 147 | console.error("[api] POST /repos:", err); | |
| 148 | return c.json({ error: "Service unavailable" }, 503); | |
| fc1817a | 149 | } |
| 150 | }); | |
| 151 | ||
| 152 | // List user's repositories | |
| 153 | api.get("/users/:username/repos", async (c) => { | |
| 154 | const { username } = c.req.param(); | |
| 63807e5 | 155 | try { |
| 156 | const [owner] = await db | |
| 157 | .select() | |
| 158 | .from(users) | |
| 159 | .where(eq(users.username, username)); | |
| 160 | if (!owner) return c.json({ error: "User not found" }, 404); | |
| 161 | ||
| 162 | const repos = await db | |
| 163 | .select() | |
| 164 | .from(repositories) | |
| 165 | .where(eq(repositories.ownerId, owner.id)); | |
| 166 | ||
| 167 | return c.json(repos); | |
| 168 | } catch (err) { | |
| 169 | console.error("[api] /users/:username/repos:", err); | |
| 170 | return c.json({ error: "Service unavailable" }, 503); | |
| 171 | } | |
| fc1817a | 172 | }); |
| 173 | ||
| 7437605 | 174 | // Get single repository (resolves both user- and org-owned namespaces) |
| fc1817a | 175 | api.get("/repos/:owner/:name", async (c) => { |
| 176 | const { owner: ownerName, name } = c.req.param(); | |
| 63807e5 | 177 | try { |
| 7437605 | 178 | const { loadRepoByPath } = await import("../lib/namespace"); |
| 179 | const repo = await loadRepoByPath(ownerName, name); | |
| 63807e5 | 180 | if (!repo) return c.json({ error: "Not found" }, 404); |
| 8102dd4 | 181 | |
| 182 | // A private repo must not disclose its existence — let alone its | |
| 183 | // description, ownerId and on-disk path — to a viewer without read | |
| 184 | // access. Mirror the HTML surface, which already 404s here. | |
| 185 | const viewer = c.get("user"); | |
| 186 | const { resolveRepoAccess } = await import("../middleware/repo-access"); | |
| 187 | const access = await resolveRepoAccess({ | |
| 188 | repoId: repo.id, | |
| 189 | userId: viewer?.id ?? null, | |
| 190 | isPublic: !repo.isPrivate, | |
| 191 | }); | |
| 192 | if (access === "none") return c.json({ error: "Not found" }, 404); | |
| 193 | ||
| 194 | // `diskPath` is server-internal (it leaks the storage layout); never | |
| 195 | // serialize it to an API client regardless of access level. | |
| 196 | const { diskPath: _diskPath, ...safeRepo } = repo as typeof repo & { | |
| 197 | diskPath?: string; | |
| 198 | }; | |
| 199 | return c.json(safeRepo); | |
| 63807e5 | 200 | } catch (err) { |
| 201 | console.error("[api] /repos/:owner/:name:", err); | |
| 202 | return c.json({ error: "Service unavailable" }, 503); | |
| 203 | } | |
| fc1817a | 204 | }); |
| 205 | ||
| 206 | // Quick-setup: create user + repo in one call (dev convenience) | |
| 207 | api.post("/setup", async (c) => { | |
| 63807e5 | 208 | let body: { |
| fc1817a | 209 | username: string; |
| 210 | email: string; | |
| 211 | repoName: string; | |
| 212 | description?: string; | |
| 63807e5 | 213 | }; |
| 214 | try { | |
| 215 | body = await c.req.json(); | |
| 216 | } catch { | |
| 217 | return c.json({ error: "Invalid JSON body" }, 400); | |
| 218 | } | |
| 219 | if (!body.username || !body.email || !body.repoName) { | |
| 220 | return c.json( | |
| 221 | { error: "username, email, and repoName are required" }, | |
| 222 | 400 | |
| 223 | ); | |
| fc1817a | 224 | } |
| 225 | ||
| 63807e5 | 226 | try { |
| 227 | // Upsert user | |
| 228 | let [user] = await db | |
| 229 | .select() | |
| 230 | .from(users) | |
| 231 | .where(eq(users.username, body.username)); | |
| fc1817a | 232 | |
| 63807e5 | 233 | if (!user) { |
| 234 | [user] = await db | |
| 235 | .insert(users) | |
| 236 | .values({ | |
| 237 | username: body.username, | |
| 238 | email: body.email, | |
| 239 | passwordHash: await hashPassword("changeme"), | |
| 240 | }) | |
| 241 | .returning(); | |
| 242 | } | |
| fc1817a | 243 | |
| 63807e5 | 244 | // Create repo if not exists |
| 245 | if (!(await repoExists(body.username, body.repoName))) { | |
| 246 | const diskPath = await initBareRepo(body.username, body.repoName); | |
| 247 | const [repo] = await db | |
| 248 | .insert(repositories) | |
| 249 | .values({ | |
| 250 | name: body.repoName, | |
| 251 | ownerId: user.id, | |
| 252 | description: body.description || null, | |
| 253 | diskPath, | |
| 254 | }) | |
| 255 | .returning(); | |
| 256 | if (repo) { | |
| 257 | const { bootstrapRepository } = await import("../lib/repo-bootstrap"); | |
| 258 | await bootstrapRepository({ | |
| 259 | repositoryId: repo.id, | |
| 260 | ownerUserId: user.id, | |
| 261 | }); | |
| 262 | } | |
| 3ef4c9d | 263 | } |
| fc1817a | 264 | |
| 63807e5 | 265 | return c.json({ |
| 266 | user: user.username, | |
| 267 | repo: body.repoName, | |
| 268 | status: "ready", | |
| fc1817a | 269 | }); |
| 63807e5 | 270 | } catch (err) { |
| 271 | console.error("[api] POST /setup:", err); | |
| 272 | return c.json({ error: "Service unavailable" }, 503); | |
| fc1817a | 273 | } |
| 274 | }); | |
| 275 | ||
| 6cd2f0e | 276 | // Markdown preview — render markdown to HTML for the live preview tab. |
| 277 | // Body: { text: string }. Returns { html: string }. | |
| 278 | // Rate-limited by the global limiter in middleware. No auth required. | |
| 279 | api.post("/markdown/preview", async (c) => { | |
| 280 | let text = ""; | |
| 281 | try { | |
| 282 | const body = await c.req.json(); | |
| 283 | text = String(body.text || "").slice(0, 64_000); | |
| 284 | } catch { | |
| 285 | return c.json({ html: "" }, 400); | |
| 286 | } | |
| 287 | const html = renderMarkdown(text); | |
| 288 | return c.json({ html }); | |
| 289 | }); | |
| 290 | ||
| 829a046 | 291 | // User mention autocomplete — returns up to 8 matching usernames for `@` suggestions. |
| 292 | // Public endpoint (no auth required) since usernames are public. | |
| 293 | api.get("/users/suggest", async (c) => { | |
| 294 | const q = String(c.req.query("q") || "").trim().replace(/^@/, "").slice(0, 39); | |
| 295 | if (!q) return c.json({ users: [] }); | |
| 296 | try { | |
| 297 | const rows = await db | |
| 298 | .select({ username: users.username, displayName: users.displayName }) | |
| 299 | .from(users) | |
| 300 | .where(ilike(users.username, `${q}%`)) | |
| 301 | .orderBy(sql`lower(${users.username})`) | |
| 302 | .limit(8); | |
| 303 | return c.json({ users: rows }); | |
| 304 | } catch { | |
| 305 | return c.json({ users: [] }); | |
| 306 | } | |
| 307 | }); | |
| 308 | ||
| fc1817a | 309 | export default api; |