Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesPull RequestsActionsSecurityInsightsSettings
✨ AI
More
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.

api.tsBlame333 lines · 2 contributors
fc1817aClaude1/**
2 * REST API routes for repository management.
3 */
4
5import { Hono } from "hono";
8102dd4ccantynz-alt6import type { AuthEnv } from "../middleware/auth";
829a046Claude7import { eq, and, isNull, ilike, sql } from "drizzle-orm";
fc1817aClaude8import { db } from "../db";
7437605Claude9import { users, repositories, organizations, orgMembers } from "../db/schema";
fc1817aClaude10import { initBareRepo, repoExists } from "../git/repository";
06d5ffeClaude11import { hashPassword } from "../lib/auth";
7437605Claude12import { orgRoleAtLeast } from "../lib/orgs";
6cd2f0eClaude13import { renderMarkdown } from "../lib/markdown";
fc1817aClaude14
8102dd4ccantynz-alt15// Typed with AuthEnv so handlers can read the viewer that the global
16// `softAuth` middleware already resolved (needed for private-repo gating).
17const api = new Hono<AuthEnv>().basePath("/api");
fc1817aClaude18
19// Create repository
20api.post("/repos", async (c) => {
63807e5Claude21 let body: {
fc1817aClaude22 name: string;
23 owner: string;
7437605Claude24 orgSlug?: string;
fc1817aClaude25 description?: string;
26 isPrivate?: boolean;
63807e5Claude27 };
28 try {
29 body = await c.req.json();
30 } catch {
31 return c.json({ error: "Invalid JSON body" }, 400);
32 }
fc1817aClaude33
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 }
2cd3bb4ccantynz-alt42 // 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();
fc1817aClaude46
63807e5Claude47 try {
7437605Claude48 // Find creator (user who is performing the action)
63807e5Claude49 const [owner] = await db
50 .select()
51 .from(users)
52 .where(eq(users.username, body.owner));
fc1817aClaude53
63807e5Claude54 if (!owner) {
55 return c.json({ error: "Owner not found" }, 404);
56 }
fc1817aClaude57
7437605Claude58 // 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)) {
63807e5Claude113 return c.json({ error: "Repository already exists" }, 409);
114 }
fc1817aClaude115
7437605Claude116 // Init bare repo on disk, keyed by the namespace slug (user or org).
117 const diskPath = await initBareRepo(namespaceSlug, body.name);
63807e5Claude118
119 // Insert into DB
120 const [repo] = await db
121 .insert(repositories)
122 .values({
123 name: body.name,
124 ownerId: owner.id,
7437605Claude125 orgId,
63807e5Claude126 description: body.description || null,
127 isPrivate: body.isPrivate || false,
128 diskPath,
129 })
130 .returning();
3ef4c9dClaude131
63807e5Claude132 // Green-ecosystem bootstrap: settings, protection, labels, welcome issue
133 if (repo) {
cde9983Claude134 const { bootstrapRepository, ensureAiBuildSeedIssue } = await import("../lib/repo-bootstrap");
63807e5Claude135 await bootstrapRepository({
136 repositoryId: repo.id,
137 ownerUserId: owner.id,
138 });
cde9983Claude139 // Fire-and-forget — never block the response
140 ensureAiBuildSeedIssue(repo.id, owner.id).catch(err =>
141 console.warn('[ai-build-seed]', err?.message)
142 );
63807e5Claude143 }
fc1817aClaude144
63807e5Claude145 return c.json(repo, 201);
146 } catch (err) {
147 console.error("[api] POST /repos:", err);
148 return c.json({ error: "Service unavailable" }, 503);
fc1817aClaude149 }
150});
151
152// List user's repositories
153api.get("/users/:username/repos", async (c) => {
154 const { username } = c.req.param();
63807e5Claude155 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
fde8ff2ccantynz-alt162 // Sibling fix to GET /repos/:owner/:name: that handler was gated but this
163 // list was not, so it kept returning every private repo the user owns —
164 // name, description, ownerId and the internal diskPath — to anonymous
165 // callers. Filter per row through the same access helper the HTML surface
166 // uses, so collaborators and org members keep seeing what they should.
167 const rows = await db
63807e5Claude168 .select()
169 .from(repositories)
170 .where(eq(repositories.ownerId, owner.id));
171
fde8ff2ccantynz-alt172 const viewer = c.get("user");
173 const { resolveRepoAccess } = await import("../middleware/repo-access");
174 const visible = (
175 await Promise.all(
176 rows.map(async (r) => {
177 if (!r.isPrivate) return r;
178 const access = await resolveRepoAccess({
179 repoId: r.id,
180 userId: viewer?.id ?? null,
181 isPublic: false,
182 });
183 return access === "none" ? null : r;
184 })
185 )
186 ).filter((r): r is (typeof rows)[number] => r !== null);
187
188 // diskPath leaks the server's storage layout — never serialize it.
189 const safe = visible.map(({ diskPath: _diskPath, ...rest }) => rest);
190
191 return c.json(safe);
63807e5Claude192 } catch (err) {
193 console.error("[api] /users/:username/repos:", err);
194 return c.json({ error: "Service unavailable" }, 503);
195 }
fc1817aClaude196});
197
7437605Claude198// Get single repository (resolves both user- and org-owned namespaces)
fc1817aClaude199api.get("/repos/:owner/:name", async (c) => {
200 const { owner: ownerName, name } = c.req.param();
63807e5Claude201 try {
7437605Claude202 const { loadRepoByPath } = await import("../lib/namespace");
203 const repo = await loadRepoByPath(ownerName, name);
63807e5Claude204 if (!repo) return c.json({ error: "Not found" }, 404);
8102dd4ccantynz-alt205
206 // A private repo must not disclose its existence — let alone its
207 // description, ownerId and on-disk path — to a viewer without read
208 // access. Mirror the HTML surface, which already 404s here.
209 const viewer = c.get("user");
210 const { resolveRepoAccess } = await import("../middleware/repo-access");
211 const access = await resolveRepoAccess({
212 repoId: repo.id,
213 userId: viewer?.id ?? null,
214 isPublic: !repo.isPrivate,
215 });
216 if (access === "none") return c.json({ error: "Not found" }, 404);
217
218 // `diskPath` is server-internal (it leaks the storage layout); never
219 // serialize it to an API client regardless of access level.
220 const { diskPath: _diskPath, ...safeRepo } = repo as typeof repo & {
221 diskPath?: string;
222 };
223 return c.json(safeRepo);
63807e5Claude224 } catch (err) {
225 console.error("[api] /repos/:owner/:name:", err);
226 return c.json({ error: "Service unavailable" }, 503);
227 }
fc1817aClaude228});
229
230// Quick-setup: create user + repo in one call (dev convenience)
231api.post("/setup", async (c) => {
63807e5Claude232 let body: {
fc1817aClaude233 username: string;
234 email: string;
235 repoName: string;
236 description?: string;
63807e5Claude237 };
238 try {
239 body = await c.req.json();
240 } catch {
241 return c.json({ error: "Invalid JSON body" }, 400);
242 }
243 if (!body.username || !body.email || !body.repoName) {
244 return c.json(
245 { error: "username, email, and repoName are required" },
246 400
247 );
fc1817aClaude248 }
249
63807e5Claude250 try {
251 // Upsert user
252 let [user] = await db
253 .select()
254 .from(users)
255 .where(eq(users.username, body.username));
fc1817aClaude256
63807e5Claude257 if (!user) {
258 [user] = await db
259 .insert(users)
260 .values({
261 username: body.username,
262 email: body.email,
263 passwordHash: await hashPassword("changeme"),
264 })
265 .returning();
266 }
fc1817aClaude267
63807e5Claude268 // Create repo if not exists
269 if (!(await repoExists(body.username, body.repoName))) {
270 const diskPath = await initBareRepo(body.username, body.repoName);
271 const [repo] = await db
272 .insert(repositories)
273 .values({
274 name: body.repoName,
275 ownerId: user.id,
276 description: body.description || null,
277 diskPath,
278 })
279 .returning();
280 if (repo) {
281 const { bootstrapRepository } = await import("../lib/repo-bootstrap");
282 await bootstrapRepository({
283 repositoryId: repo.id,
284 ownerUserId: user.id,
285 });
286 }
3ef4c9dClaude287 }
fc1817aClaude288
63807e5Claude289 return c.json({
290 user: user.username,
291 repo: body.repoName,
292 status: "ready",
fc1817aClaude293 });
63807e5Claude294 } catch (err) {
295 console.error("[api] POST /setup:", err);
296 return c.json({ error: "Service unavailable" }, 503);
fc1817aClaude297 }
298});
299
6cd2f0eClaude300// Markdown preview — render markdown to HTML for the live preview tab.
301// Body: { text: string }. Returns { html: string }.
302// Rate-limited by the global limiter in middleware. No auth required.
303api.post("/markdown/preview", async (c) => {
304 let text = "";
305 try {
306 const body = await c.req.json();
307 text = String(body.text || "").slice(0, 64_000);
308 } catch {
309 return c.json({ html: "" }, 400);
310 }
311 const html = renderMarkdown(text);
312 return c.json({ html });
313});
314
829a046Claude315// User mention autocomplete — returns up to 8 matching usernames for `@` suggestions.
316// Public endpoint (no auth required) since usernames are public.
317api.get("/users/suggest", async (c) => {
318 const q = String(c.req.query("q") || "").trim().replace(/^@/, "").slice(0, 39);
319 if (!q) return c.json({ users: [] });
320 try {
321 const rows = await db
322 .select({ username: users.username, displayName: users.displayName })
323 .from(users)
324 .where(ilike(users.username, `${q}%`))
325 .orderBy(sql`lower(${users.username})`)
326 .limit(8);
327 return c.json({ users: rows });
328 } catch {
329 return c.json({ users: [] });
330 }
331});
332
fc1817aClaude333export default api;