1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
|
import { Hono } from "hono";
import { eq, and } from "drizzle-orm";
import { createHash } from "crypto";
import { db } from "../db";
import { users, repositories, activityFeed, apiTokens } from "../db/schema";
import { initBareRepo } from "../git/repository";
import { config } from "../lib/config";
import type { AuthEnv } from "../middleware/auth";
const claudeIntegration = new Hono<AuthEnv>();
function sha256hex(value: string): string {
return createHash("sha256").update(value).digest("hex");
}
async function authenticateBearer(
authHeader: string | undefined
): Promise<
| { ok: true; user: typeof users.$inferSelect; tokenRow: typeof apiTokens.$inferSelect }
| { ok: false; error: string; status: 401 }
> {
if (!authHeader?.startsWith("Bearer ")) {
return { ok: false, error: "Missing or malformed Authorization header. Use: Bearer <token>", status: 401 };
}
const raw = authHeader.slice(7).trim();
if (!raw) {
return { ok: false, error: "Empty bearer token", status: 401 };
}
const tokenHash = sha256hex(raw);
try {
const [tokenRow] = await db
.select()
.from(apiTokens)
.where(eq(apiTokens.tokenHash, tokenHash))
.limit(1);
if (!tokenRow) {
return { ok: false, error: "Invalid API token", status: 401 };
}
if (tokenRow.expiresAt && new Date(tokenRow.expiresAt) < new Date()) {
return { ok: false, error: "API token has expired", status: 401 };
}
const [user] = await db
.select()
.from(users)
.where(eq(users.id, tokenRow.userId))
.limit(1);
if (!user) {
return { ok: false, error: "Token owner not found", status: 401 };
}
db.update(apiTokens)
.set({ lastUsedAt: new Date() })
.where(eq(apiTokens.id, tokenRow.id))
.catch(() => {});
return { ok: true, user, tokenRow };
} catch (err) {
return { ok: false, error: "Authentication failed", status: 401 };
}
}
claudeIntegration.post("/api/claude/connect", async (c) => {
const auth = await authenticateBearer(c.req.header("Authorization"));
if (!auth.ok) {
return c.json({ ok: false, error: auth.error }, auth.status);
}
const { user } = auth;
let body: { username?: string; repoName?: string; description?: string };
try {
body = await c.req.json();
} catch {
return c.json({ ok: false, error: "Invalid JSON body" }, 400);
}
const repoName = body.repoName?.trim();
const description = body.description?.trim() || null;
try {
const baseUrl = config.appBaseUrl;
if (!repoName) {
return c.json({
ok: true,
username: user.username,
mcpUrl: `${baseUrl}/mcp`,
message: "Token valid. Provide repoName to auto-create a repository.",
});
}
if (!/^[a-zA-Z0-9._-]+$/.test(repoName)) {
return c.json({ ok: false, error: "Invalid repository name. Use letters, digits, hyphens, dots, or underscores." }, 400);
}
const [existing] = await db
.select()
.from(repositories)
.where(and(eq(repositories.ownerId, user.id), eq(repositories.name, repoName)))
.limit(1);
if (existing) {
const gitRemote = `${baseUrl}/${user.username}/${repoName}.git`;
const mcpUrl = `${baseUrl}/mcp`;
return c.json({
ok: true,
created: false,
gitRemote,
mcpUrl,
repoId: existing.id,
message: "Repository already exists.",
});
}
const diskPath = await initBareRepo(user.username, repoName);
const [repo] = await db
.insert(repositories)
.values({
name: repoName,
ownerId: user.id,
description,
isPrivate: false,
diskPath,
})
.returning();
if (!repo) {
return c.json({ ok: false, error: "Failed to create repository record" }, 500);
}
await db.insert(activityFeed).values({
repositoryId: repo.id,
userId: user.id,
action: "repo_created",
targetType: "repository",
targetId: repo.id,
metadata: JSON.stringify({ source: "claude_connect", via: "api" }),
}).catch(() => {});
const gitRemote = `${baseUrl}/${user.username}/${repoName}.git`;
const mcpUrl = `${baseUrl}/mcp`;
return c.json({
ok: true,
created: true,
gitRemote,
mcpUrl,
repoId: repo.id,
message: `Repository '${repoName}' created. Push with: git push gluecron main`,
});
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
return c.json({ ok: false, error: `Server error: ${msg}` }, 500);
}
});
claudeIntegration.get("/api/claude/connect", async (c) => {
const auth = await authenticateBearer(c.req.header("Authorization"));
if (!auth.ok) {
return c.json({ ok: false, error: auth.error }, auth.status);
}
const { user } = auth;
const repoName = c.req.query("repo");
try {
const baseUrl = config.appBaseUrl;
if (!repoName) {
const repos = await db
.select({ id: repositories.id, name: repositories.name, description: repositories.description, createdAt: repositories.createdAt })
.from(repositories)
.where(eq(repositories.ownerId, user.id));
return c.json({
ok: true,
username: user.username,
mcpUrl: `${baseUrl}/mcp`,
repos: repos.map((r) => ({
...r,
gitRemote: `${baseUrl}/${user.username}/${r.name}.git`,
})),
});
}
const [repo] = await db
.select()
.from(repositories)
.where(and(eq(repositories.ownerId, user.id), eq(repositories.name, repoName)))
.limit(1);
if (!repo) {
return c.json({ ok: false, error: `Repository '${repoName}' not found` }, 404);
}
const gitRemote = `${baseUrl}/${user.username}/${repoName}.git`;
const mcpUrl = `${baseUrl}/mcp`;
return c.json({
ok: true,
username: user.username,
repoId: repo.id,
repoName: repo.name,
gitRemote,
mcpUrl,
});
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
return c.json({ ok: false, error: `Server error: ${msg}` }, 500);
}
});
claudeIntegration.post("/api/claude/session", async (c) => {
let body: {
sessionId?: string;
repoName?: string;
event?: "start" | "push" | "issue" | "pr";
payload?: unknown;
};
try {
body = await c.req.json();
} catch {
return c.json({ ok: false, error: "Invalid JSON body" }, 400);
}
const { sessionId, repoName, event, payload } = body;
if (!event || !["start", "push", "issue", "pr"].includes(event)) {
return c.json({ ok: false, error: "event must be one of: start, push, issue, pr" }, 400);
}
try {
let repositoryId: string | null = null;
let userId: string | null = null;
if (repoName) {
const ownerHint =
(payload && typeof payload === "object" && "owner" in payload
? (payload as Record<string, unknown>).owner
: undefined) as string | undefined;
if (ownerHint) {
const [ownerRow] = await db
.select({ id: users.id })
.from(users)
.where(eq(users.username, ownerHint))
.limit(1);
if (ownerRow) {
userId = ownerRow.id;
const [repo] = await db
.select({ id: repositories.id })
.from(repositories)
.where(and(eq(repositories.ownerId, ownerRow.id), eq(repositories.name, repoName)))
.limit(1);
if (repo) repositoryId = repo.id;
}
}
}
if (repositoryId) {
await db.insert(activityFeed).values({
repositoryId,
userId: userId ?? undefined,
action: "claude_session",
targetType: "session",
targetId: sessionId ?? null,
metadata: JSON.stringify({ sessionId, event, repoName, payload }),
});
}
} catch {
}
return c.json({ ok: true });
});
export default claudeIntegration;
|