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