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"; |
| dc32319 | 14 | import { openIssueCountsByRepo } from "../lib/issue-counts"; |
| fc1817a | 15 | |
| 8102dd4 | 16 | // Typed with AuthEnv so handlers can read the viewer that the global |
| 17 | // `softAuth` middleware already resolved (needed for private-repo gating). | |
| 18 | const api = new Hono<AuthEnv>().basePath("/api"); | |
| fc1817a | 19 | |
| 20 | // Create repository | |
| 21 | api.post("/repos", async (c) => { | |
| 754596c | 22 | // This handler had NO auth middleware and took the target namespace from |
| 23 | // `owner` in the request body, so anyone on the internet could create | |
| 24 | // repositories inside any user's namespace. csrfProtect does not help: | |
| 25 | // src/middleware/csrf.ts explicitly exempts paths under /api/. | |
| 26 | // | |
| 27 | // softAuth (applied globally in app.tsx) has already resolved a session | |
| 28 | // cookie, an OAuth bearer, or a `glc_` PAT into c.get("user"), so an inline | |
| 29 | // check is enough — and returns a JSON 401 rather than the HTML redirect | |
| 30 | // requireAuth would issue for a cookie-less caller. | |
| 31 | const viewer = c.get("user"); | |
| 32 | if (!viewer) { | |
| 33 | return c.json( | |
| 34 | { error: "Authentication required", hint: "Use Authorization: Bearer <token> header" }, | |
| 35 | 401 | |
| 36 | ); | |
| 37 | } | |
| 38 | ||
| 63807e5 | 39 | let body: { |
| fc1817a | 40 | name: string; |
| 41 | owner: string; | |
| 7437605 | 42 | orgSlug?: string; |
| fc1817a | 43 | description?: string; |
| 44 | isPrivate?: boolean; | |
| 63807e5 | 45 | }; |
| 46 | try { | |
| 47 | body = await c.req.json(); | |
| 48 | } catch { | |
| 49 | return c.json({ error: "Invalid JSON body" }, 400); | |
| 50 | } | |
| fc1817a | 51 | |
| 754596c | 52 | if (!body.name) { |
| 53 | return c.json({ error: "name is required" }, 400); | |
| 54 | } | |
| 55 | ||
| 56 | // The caller may only create in their own namespace. `owner` is now | |
| 57 | // optional; if supplied it must match, so an old client that sends its own | |
| 58 | // username keeps working while a forged one is refused. Org placement still | |
| 59 | // goes through orgSlug below, which checks the creator's admin rights. | |
| 60 | if (body.owner && body.owner !== viewer.username) { | |
| 61 | return c.json( | |
| 62 | { error: "Cannot create a repository in another user's namespace" }, | |
| 63 | 403 | |
| 64 | ); | |
| fc1817a | 65 | } |
| 754596c | 66 | body.owner = viewer.username; |
| fc1817a | 67 | |
| 68 | // Validate repo name | |
| 69 | if (!/^[a-zA-Z0-9._-]+$/.test(body.name)) { | |
| 70 | return c.json({ error: "Invalid repository name" }, 400); | |
| 71 | } | |
| 2cd3bb4 | 72 | // Normalize to lowercase — repo slugs are canonically lowercase so |
| 73 | // "MyRepo" and "myrepo" can't both exist and cause "Vapron" vs "vapron" | |
| 74 | // confusion. Applied before the duplicate checks + on-disk init below. | |
| 75 | body.name = body.name.toLowerCase(); | |
| fc1817a | 76 | |
| 63807e5 | 77 | try { |
| 7437605 | 78 | // Find creator (user who is performing the action) |
| 63807e5 | 79 | const [owner] = await db |
| 80 | .select() | |
| 81 | .from(users) | |
| 82 | .where(eq(users.username, body.owner)); | |
| fc1817a | 83 | |
| 63807e5 | 84 | if (!owner) { |
| 85 | return c.json({ error: "Owner not found" }, 404); | |
| 86 | } | |
| fc1817a | 87 | |
| 7437605 | 88 | // B2: if orgSlug supplied, place the repo in the org namespace. |
| 89 | // Requires the creator to be an admin+ of the org. | |
| 90 | let orgId: string | null = null; | |
| 91 | let namespaceSlug = body.owner; | |
| 92 | if (body.orgSlug) { | |
| 93 | const [org] = await db | |
| 94 | .select({ id: organizations.id, slug: organizations.slug }) | |
| 95 | .from(organizations) | |
| 96 | .where(eq(organizations.slug, body.orgSlug)) | |
| 97 | .limit(1); | |
| 98 | if (!org) return c.json({ error: "Organization not found" }, 404); | |
| 99 | ||
| 100 | const [mem] = await db | |
| 101 | .select({ role: orgMembers.role }) | |
| 102 | .from(orgMembers) | |
| 103 | .where( | |
| 104 | and(eq(orgMembers.orgId, org.id), eq(orgMembers.userId, owner.id)) | |
| 105 | ) | |
| 106 | .limit(1); | |
| 107 | if (!mem || !orgRoleAtLeast(mem.role, "admin")) { | |
| 108 | return c.json({ error: "Admin rights required on org" }, 403); | |
| 109 | } | |
| 110 | orgId = org.id; | |
| 111 | namespaceSlug = org.slug; | |
| 112 | } | |
| 113 | ||
| 114 | // Duplicate check: scoped to the right namespace. | |
| 115 | if (orgId) { | |
| 116 | const [existing] = await db | |
| 117 | .select({ id: repositories.id }) | |
| 118 | .from(repositories) | |
| 119 | .where( | |
| 120 | and(eq(repositories.orgId, orgId), eq(repositories.name, body.name)) | |
| 121 | ) | |
| 122 | .limit(1); | |
| 123 | if (existing) { | |
| 124 | return c.json({ error: "Repository already exists" }, 409); | |
| 125 | } | |
| 126 | } else { | |
| 127 | const [existing] = await db | |
| 128 | .select({ id: repositories.id }) | |
| 129 | .from(repositories) | |
| 130 | .where( | |
| 131 | and( | |
| 132 | eq(repositories.ownerId, owner.id), | |
| 133 | eq(repositories.name, body.name), | |
| 134 | isNull(repositories.orgId) | |
| 135 | ) | |
| 136 | ) | |
| 137 | .limit(1); | |
| 138 | if (existing) { | |
| 139 | return c.json({ error: "Repository already exists" }, 409); | |
| 140 | } | |
| 141 | } | |
| 142 | if (await repoExists(namespaceSlug, body.name)) { | |
| 63807e5 | 143 | return c.json({ error: "Repository already exists" }, 409); |
| 144 | } | |
| fc1817a | 145 | |
| 7437605 | 146 | // Init bare repo on disk, keyed by the namespace slug (user or org). |
| 147 | const diskPath = await initBareRepo(namespaceSlug, body.name); | |
| 63807e5 | 148 | |
| 149 | // Insert into DB | |
| 150 | const [repo] = await db | |
| 151 | .insert(repositories) | |
| 152 | .values({ | |
| 153 | name: body.name, | |
| 154 | ownerId: owner.id, | |
| 7437605 | 155 | orgId, |
| 63807e5 | 156 | description: body.description || null, |
| 157 | isPrivate: body.isPrivate || false, | |
| 158 | diskPath, | |
| 159 | }) | |
| 160 | .returning(); | |
| 3ef4c9d | 161 | |
| 63807e5 | 162 | // Green-ecosystem bootstrap: settings, protection, labels, welcome issue |
| 163 | if (repo) { | |
| cde9983 | 164 | const { bootstrapRepository, ensureAiBuildSeedIssue } = await import("../lib/repo-bootstrap"); |
| 63807e5 | 165 | await bootstrapRepository({ |
| 166 | repositoryId: repo.id, | |
| 167 | ownerUserId: owner.id, | |
| 168 | }); | |
| cde9983 | 169 | // Fire-and-forget — never block the response |
| 170 | ensureAiBuildSeedIssue(repo.id, owner.id).catch(err => | |
| 171 | console.warn('[ai-build-seed]', err?.message) | |
| 172 | ); | |
| 63807e5 | 173 | } |
| fc1817a | 174 | |
| 63807e5 | 175 | return c.json(repo, 201); |
| 176 | } catch (err) { | |
| 177 | console.error("[api] POST /repos:", err); | |
| 178 | return c.json({ error: "Service unavailable" }, 503); | |
| fc1817a | 179 | } |
| 180 | }); | |
| 181 | ||
| 182 | // List user's repositories | |
| 183 | api.get("/users/:username/repos", async (c) => { | |
| 184 | const { username } = c.req.param(); | |
| 63807e5 | 185 | try { |
| 186 | const [owner] = await db | |
| 187 | .select() | |
| 188 | .from(users) | |
| 189 | .where(eq(users.username, username)); | |
| 190 | if (!owner) return c.json({ error: "User not found" }, 404); | |
| 191 | ||
| fde8ff2 | 192 | // Sibling fix to GET /repos/:owner/:name: that handler was gated but this |
| 193 | // list was not, so it kept returning every private repo the user owns — | |
| 194 | // name, description, ownerId and the internal diskPath — to anonymous | |
| 195 | // callers. Filter per row through the same access helper the HTML surface | |
| 196 | // uses, so collaborators and org members keep seeing what they should. | |
| 197 | const rows = await db | |
| 63807e5 | 198 | .select() |
| 199 | .from(repositories) | |
| 200 | .where(eq(repositories.ownerId, owner.id)); | |
| 201 | ||
| fde8ff2 | 202 | const viewer = c.get("user"); |
| 203 | const { resolveRepoAccess } = await import("../middleware/repo-access"); | |
| 204 | const visible = ( | |
| 205 | await Promise.all( | |
| 206 | rows.map(async (r) => { | |
| 207 | if (!r.isPrivate) return r; | |
| 208 | const access = await resolveRepoAccess({ | |
| 209 | repoId: r.id, | |
| 210 | userId: viewer?.id ?? null, | |
| 211 | isPublic: false, | |
| 212 | }); | |
| 213 | return access === "none" ? null : r; | |
| 214 | }) | |
| 215 | ) | |
| 216 | ).filter((r): r is (typeof rows)[number] => r !== null); | |
| 217 | ||
| 218 | // diskPath leaks the server's storage layout — never serialize it. | |
| 219 | const safe = visible.map(({ diskPath: _diskPath, ...rest }) => rest); | |
| 220 | ||
| dc32319 | 221 | // `issueCount` is the stored repositories.issue_count column, which is |
| 222 | // incremented in eight places and decremented in none — closing an issue | |
| 223 | // never touches it — so it is an issues-ever-created total, not an open | |
| 224 | // count. The API docs list it beside starCount and forkCount, where a | |
| 225 | // consumer reads it the way GitHub's open_issues_count reads. Serve the | |
| 226 | // real number. Failure leaves the stored value rather than dropping the | |
| 227 | // field, so the response shape never changes. | |
| 228 | try { | |
| 229 | const counts = await openIssueCountsByRepo(safe.map((r) => r.id)); | |
| 230 | for (const row of safe) { | |
| 231 | row.issueCount = counts.get(String(row.id)) ?? 0; | |
| 232 | } | |
| 233 | } catch (err) { | |
| 234 | console.warn( | |
| 235 | "[api] open issue counts failed, serving stored issueCount:", | |
| 236 | err instanceof Error ? err.message : err | |
| 237 | ); | |
| 238 | } | |
| 239 | ||
| fde8ff2 | 240 | return c.json(safe); |
| 63807e5 | 241 | } catch (err) { |
| 242 | console.error("[api] /users/:username/repos:", err); | |
| 243 | return c.json({ error: "Service unavailable" }, 503); | |
| 244 | } | |
| fc1817a | 245 | }); |
| 246 | ||
| 7437605 | 247 | // Get single repository (resolves both user- and org-owned namespaces) |
| fc1817a | 248 | api.get("/repos/:owner/:name", async (c) => { |
| 249 | const { owner: ownerName, name } = c.req.param(); | |
| 63807e5 | 250 | try { |
| 7437605 | 251 | const { loadRepoByPath } = await import("../lib/namespace"); |
| 252 | const repo = await loadRepoByPath(ownerName, name); | |
| 63807e5 | 253 | if (!repo) return c.json({ error: "Not found" }, 404); |
| 8102dd4 | 254 | |
| 255 | // A private repo must not disclose its existence — let alone its | |
| 256 | // description, ownerId and on-disk path — to a viewer without read | |
| 257 | // access. Mirror the HTML surface, which already 404s here. | |
| 258 | const viewer = c.get("user"); | |
| 259 | const { resolveRepoAccess } = await import("../middleware/repo-access"); | |
| 260 | const access = await resolveRepoAccess({ | |
| 261 | repoId: repo.id, | |
| 262 | userId: viewer?.id ?? null, | |
| 263 | isPublic: !repo.isPrivate, | |
| 264 | }); | |
| 265 | if (access === "none") return c.json({ error: "Not found" }, 404); | |
| 266 | ||
| 267 | // `diskPath` is server-internal (it leaks the storage layout); never | |
| 268 | // serialize it to an API client regardless of access level. | |
| 269 | const { diskPath: _diskPath, ...safeRepo } = repo as typeof repo & { | |
| 270 | diskPath?: string; | |
| 271 | }; | |
| 272 | return c.json(safeRepo); | |
| 63807e5 | 273 | } catch (err) { |
| 274 | console.error("[api] /repos/:owner/:name:", err); | |
| 275 | return c.json({ error: "Service unavailable" }, 503); | |
| 276 | } | |
| fc1817a | 277 | }); |
| 278 | ||
| 279 | // Quick-setup: create user + repo in one call (dev convenience) | |
| 280 | api.post("/setup", async (c) => { | |
| 754596c | 281 | // First-run bootstrap ONLY. |
| 282 | // | |
| 283 | // This endpoint was completely unauthenticated and upserts a user, seeding | |
| 284 | // any username that does not yet exist with the fixed password "changeme". | |
| 285 | // On a populated instance that is anonymous account creation plus username | |
| 286 | // squatting — register the victim's preferred handle, or any name that looks | |
| 287 | // official, with a password the attacker already knows. | |
| 288 | // | |
| 289 | // Its legitimate purpose is seeding the very first account on a fresh | |
| 290 | // install, so gate it on the instance genuinely being empty. There are no | |
| 291 | // production callers; the only references are tests. | |
| 292 | let userCount: number; | |
| 293 | try { | |
| 294 | const [row] = await db.select({ n: sql<number>`count(*)::int` }).from(users); | |
| 295 | userCount = Number(row?.n ?? 0); | |
| 296 | } catch { | |
| 297 | // Fail CLOSED. If we cannot prove the instance is empty we must not seed | |
| 298 | // an account — an unreachable DB is not permission to bootstrap. | |
| 299 | return c.json({ error: "Service unavailable" }, 503); | |
| 300 | } | |
| 301 | if (userCount > 0) { | |
| 302 | // 404, not 403: on a live instance this endpoint simply does not exist. | |
| 303 | return c.json({ error: "Not found" }, 404); | |
| 304 | } | |
| 305 | ||
| 63807e5 | 306 | let body: { |
| fc1817a | 307 | username: string; |
| 308 | email: string; | |
| 309 | repoName: string; | |
| 310 | description?: string; | |
| 63807e5 | 311 | }; |
| 312 | try { | |
| 313 | body = await c.req.json(); | |
| 314 | } catch { | |
| 315 | return c.json({ error: "Invalid JSON body" }, 400); | |
| 316 | } | |
| 317 | if (!body.username || !body.email || !body.repoName) { | |
| 318 | return c.json( | |
| 319 | { error: "username, email, and repoName are required" }, | |
| 320 | 400 | |
| 321 | ); | |
| fc1817a | 322 | } |
| 323 | ||
| 63807e5 | 324 | try { |
| 325 | // Upsert user | |
| 326 | let [user] = await db | |
| 327 | .select() | |
| 328 | .from(users) | |
| 329 | .where(eq(users.username, body.username)); | |
| fc1817a | 330 | |
| 63807e5 | 331 | if (!user) { |
| 332 | [user] = await db | |
| 333 | .insert(users) | |
| 334 | .values({ | |
| 335 | username: body.username, | |
| 336 | email: body.email, | |
| 337 | passwordHash: await hashPassword("changeme"), | |
| 338 | }) | |
| 339 | .returning(); | |
| 340 | } | |
| fc1817a | 341 | |
| 63807e5 | 342 | // Create repo if not exists |
| 343 | if (!(await repoExists(body.username, body.repoName))) { | |
| 344 | const diskPath = await initBareRepo(body.username, body.repoName); | |
| 345 | const [repo] = await db | |
| 346 | .insert(repositories) | |
| 347 | .values({ | |
| 348 | name: body.repoName, | |
| 349 | ownerId: user.id, | |
| 350 | description: body.description || null, | |
| 351 | diskPath, | |
| 352 | }) | |
| 353 | .returning(); | |
| 354 | if (repo) { | |
| 355 | const { bootstrapRepository } = await import("../lib/repo-bootstrap"); | |
| 356 | await bootstrapRepository({ | |
| 357 | repositoryId: repo.id, | |
| 358 | ownerUserId: user.id, | |
| 359 | }); | |
| 360 | } | |
| 3ef4c9d | 361 | } |
| fc1817a | 362 | |
| 63807e5 | 363 | return c.json({ |
| 364 | user: user.username, | |
| 365 | repo: body.repoName, | |
| 366 | status: "ready", | |
| fc1817a | 367 | }); |
| 63807e5 | 368 | } catch (err) { |
| 369 | console.error("[api] POST /setup:", err); | |
| 370 | return c.json({ error: "Service unavailable" }, 503); | |
| fc1817a | 371 | } |
| 372 | }); | |
| 373 | ||
| 6cd2f0e | 374 | // Markdown preview — render markdown to HTML for the live preview tab. |
| 375 | // Body: { text: string }. Returns { html: string }. | |
| 376 | // Rate-limited by the global limiter in middleware. No auth required. | |
| 377 | api.post("/markdown/preview", async (c) => { | |
| 378 | let text = ""; | |
| 379 | try { | |
| 380 | const body = await c.req.json(); | |
| 381 | text = String(body.text || "").slice(0, 64_000); | |
| 382 | } catch { | |
| 383 | return c.json({ html: "" }, 400); | |
| 384 | } | |
| 385 | const html = renderMarkdown(text); | |
| 386 | return c.json({ html }); | |
| 387 | }); | |
| 388 | ||
| 829a046 | 389 | // User mention autocomplete — returns up to 8 matching usernames for `@` suggestions. |
| 390 | // Public endpoint (no auth required) since usernames are public. | |
| 391 | api.get("/users/suggest", async (c) => { | |
| 392 | const q = String(c.req.query("q") || "").trim().replace(/^@/, "").slice(0, 39); | |
| 393 | if (!q) return c.json({ users: [] }); | |
| 394 | try { | |
| 395 | const rows = await db | |
| 396 | .select({ username: users.username, displayName: users.displayName }) | |
| 397 | .from(users) | |
| 398 | .where(ilike(users.username, `${q}%`)) | |
| 399 | .orderBy(sql`lower(${users.username})`) | |
| 400 | .limit(8); | |
| 401 | return c.json({ users: rows }); | |
| 402 | } catch { | |
| 403 | return c.json({ users: [] }); | |
| 404 | } | |
| 405 | }); | |
| 406 | ||
| fc1817a | 407 | export default api; |