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.tsBlame309 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
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 }
fc1817aClaude172});
173
7437605Claude174// Get single repository (resolves both user- and org-owned namespaces)
fc1817aClaude175api.get("/repos/:owner/:name", async (c) => {
176 const { owner: ownerName, name } = c.req.param();
63807e5Claude177 try {
7437605Claude178 const { loadRepoByPath } = await import("../lib/namespace");
179 const repo = await loadRepoByPath(ownerName, name);
63807e5Claude180 if (!repo) return c.json({ error: "Not found" }, 404);
8102dd4ccantynz-alt181
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);
63807e5Claude200 } catch (err) {
201 console.error("[api] /repos/:owner/:name:", err);
202 return c.json({ error: "Service unavailable" }, 503);
203 }
fc1817aClaude204});
205
206// Quick-setup: create user + repo in one call (dev convenience)
207api.post("/setup", async (c) => {
63807e5Claude208 let body: {
fc1817aClaude209 username: string;
210 email: string;
211 repoName: string;
212 description?: string;
63807e5Claude213 };
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 );
fc1817aClaude224 }
225
63807e5Claude226 try {
227 // Upsert user
228 let [user] = await db
229 .select()
230 .from(users)
231 .where(eq(users.username, body.username));
fc1817aClaude232
63807e5Claude233 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 }
fc1817aClaude243
63807e5Claude244 // 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 }
3ef4c9dClaude263 }
fc1817aClaude264
63807e5Claude265 return c.json({
266 user: user.username,
267 repo: body.repoName,
268 status: "ready",
fc1817aClaude269 });
63807e5Claude270 } catch (err) {
271 console.error("[api] POST /setup:", err);
272 return c.json({ error: "Service unavailable" }, 503);
fc1817aClaude273 }
274});
275
6cd2f0eClaude276// 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.
279api.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
829a046Claude291// User mention autocomplete — returns up to 8 matching usernames for `@` suggestions.
292// Public endpoint (no auth required) since usernames are public.
293api.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
fc1817aClaude309export default api;