CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
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 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 | /**
* Claude Code Integration Receiver
*
* Lets any Claude Code session or repository report into Gluecron with zero
* config. Bearer token authenticated against api_tokens (SHA-256 hash).
*
* Routes
* POST /api/claude/connect — validate token, auto-create repo, return git remote + MCP URL
* GET /api/claude/connect — same auth, return existing connection info
* POST /api/claude/session — fire-and-forget session telemetry (no auth required)
*/
import { Hono } from "hono";
import { eq, and } from "drizzle-orm";
import { createHash } from "crypto";
import { db } from "../db";
import { users, repositories, activityFeed, apiTokens, pullRequests } from "../db/schema";
import { initBareRepo, getDefaultBranch } from "../git/repository";
import { config } from "../lib/config";
import type { AuthEnv } from "../middleware/auth";
const claudeIntegration = new Hono<AuthEnv>();
// ─── Auth helper ────────────────────────────────────────────────────────────
function sha256hex(value: string): string {
return createHash("sha256").update(value).digest("hex");
}
/**
* Extract + validate Bearer token. Returns { user, token } on success,
* or { error } if the token is missing / invalid.
*/
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 };
}
// Touch last-used timestamp (best effort — no await)
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 };
}
}
// ─── POST /api/claude/connect ───────────────────────────────────────────────
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);
}
// repoName is optional — if omitted, return basic connection info without a repo
const repoName = body.repoName?.trim();
const description = body.description?.trim() || null;
try {
const baseUrl = config.appBaseUrl;
if (!repoName) {
// No repo requested — just confirm the token is valid
return c.json({
ok: true,
username: user.username,
mcpUrl: `${baseUrl}/mcp`,
message: "Token valid. Provide repoName to auto-create a repository.",
});
}
// Validate repo name
if (!/^[a-zA-Z0-9._-]+$/.test(repoName)) {
return c.json({ ok: false, error: "Invalid repository name. Use letters, digits, hyphens, dots, or underscores." }, 400);
}
// Check if repo already exists
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.",
});
}
// Auto-create bare repo on disk
const diskPath = await initBareRepo(user.username, repoName);
// Insert into repositories table
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);
}
// Log to activity feed
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);
}
});
// ─── GET /api/claude/connect ────────────────────────────────────────────────
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) {
// List all repos for this user
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);
}
});
// ─── POST /api/claude/session ────────────────────────────────────────────────
// Fire-and-forget telemetry. No auth required — sessions post to this.
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);
}
// Best-effort: look up the repo if repoName is provided (need owner resolution via query param or body)
try {
let repositoryId: string | null = null;
let userId: string | null = null;
if (repoName) {
// Try to find via owner in payload or query string
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 }),
});
}
// If no repo found, silently swallow (fire-and-forget)
} catch {
// Intentionally swallowed — telemetry must not block callers
}
return c.json({ ok: true });
});
// ─── POST /api/claude/push ────────────────────────────────────────────────────
// Zero-config push-to-PR: after Claude pushes a branch, auto-create a draft PR.
// If a PR already exists for this branch, returns its info without creating.
claudeIntegration.post("/api/claude/push", 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: {
repoName?: string;
branch?: string;
title?: string;
description?: string;
baseBranch?: string;
};
try {
body = await c.req.json();
} catch {
return c.json({ ok: false, error: "Invalid JSON body" }, 400);
}
const repoName = body.repoName?.trim();
const branch = body.branch?.trim();
if (!repoName || !branch) {
return c.json({ ok: false, error: "repoName and branch are required" }, 400);
}
try {
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);
}
// Determine base branch
let baseBranch: string = body.baseBranch?.trim() || "";
if (!baseBranch) {
try {
baseBranch = (await getDefaultBranch(user.username, repoName)) ?? "main";
} catch {
baseBranch = "main";
}
}
// If pushing to the base branch itself, no PR needed
if (branch === baseBranch) {
const baseUrl = config.appBaseUrl;
return c.json({
ok: true,
prCreated: false,
message: `Push to default branch '${baseBranch}' — no PR needed.`,
pushWatchUrl: `${baseUrl}/${user.username}/${repoName}/push/HEAD`,
});
}
// Check for existing open PR for this head branch
const [existingPr] = await db
.select({ id: pullRequests.id, number: pullRequests.number })
.from(pullRequests)
.where(
and(
eq(pullRequests.repositoryId, repo.id),
eq(pullRequests.headBranch, branch),
eq(pullRequests.state, "open")
)
)
.limit(1);
const baseUrl = config.appBaseUrl;
if (existingPr) {
return c.json({
ok: true,
prCreated: false,
prNumber: existingPr.number,
prUrl: `${baseUrl}/${user.username}/${repoName}/pulls/${existingPr.number}`,
message: `PR #${existingPr.number} already exists for branch '${branch}'.`,
});
}
// Auto-create a draft PR
const title = body.title?.trim() || `Claude: ${branch.replace(/[-_]/g, " ")}`;
const prBody = body.description?.trim() ||
`Auto-created draft PR from Claude Code session.\n\n` +
`Branch: \`${branch}\` → \`${baseBranch}\`\n\n` +
`Review and merge when ready, or push more commits to update.`;
const [newPr] = await db
.insert(pullRequests)
.values({
repositoryId: repo.id,
authorId: user.id,
title,
body: prBody,
state: "open",
baseBranch,
headBranch: branch,
isDraft: true,
})
.returning({ id: pullRequests.id, number: pullRequests.number });
if (!newPr) {
return c.json({ ok: false, error: "Failed to create PR record" }, 500);
}
// Log to activity feed (best effort)
await db.insert(activityFeed).values({
repositoryId: repo.id,
userId: user.id,
action: "pull_request.opened",
targetType: "pr",
targetId: String(newPr.number),
metadata: JSON.stringify({ source: "claude_push", branch, baseBranch, draft: true }),
}).catch(() => {});
return c.json({
ok: true,
prCreated: true,
prNumber: newPr.number,
prUrl: `${baseUrl}/${user.username}/${repoName}/pulls/${newPr.number}`,
pushWatchUrl: `${baseUrl}/${user.username}/${repoName}/push/${branch}`,
message: `Draft PR #${newPr.number} created: "${title}"`,
});
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
return c.json({ ok: false, error: `Server error: ${msg}` }, 500);
}
});
export default claudeIntegration;
|