Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesPull RequestsActionsSecurityInsightsSettings
✨ AI
More
claude/adoring-hopper-5x74bqclaude/affectionate-feynman-ykrf1hclaude/architecture-audit-design-wxprenclaude/build-status-update-3MXsfclaude/charming-meitner-mllb5rclaude/compare-gate-gluecron-s4mFQclaude/confident-faraday-tikcwbclaude/continue-work-XMTlIclaude/crontech-gluecron-deploy-7MIECclaude/crontech-platform-setup-SeKfwclaude/design-2026claude/ecstatic-ptolemy-jMdigclaude/enhance-github-integration-QNHdGclaude/fix-aa-loop-issue-PonMQclaude/fix-actions-and-processclaude/fix-desktop-errors-XqoW8claude/fix-red-workflowsclaude/fix-website-access-6FKJNclaude/gatetest-integration-hardeningclaude/github-audit-improvements-bDFr9claude/gluecron-launch-status-FoMRlclaude/hopeful-lamport-olfCTclaude/issue-to-pr-and-protectionsclaude/jolly-heisenberg-2sg1Qclaude/launch-preparation-QmTb6claude/new-session-xk1l7claude/plan-platform-architecture-kkN4yclaude/platform-analysis-roadmap-1nUGLclaude/platform-launch-assessment-8dWV8claude/polish-platform-release-AeDrUclaude/resume-previous-work-KzyLwclaude/review-crontech-handoff-qYEVqclaude/review-project-completeness-lHhS2claude/review-readme-docs-ulqPKclaude/serene-edison-rj87weclaude/setup-multi-repo-dev-BCwNQclaude/ship-fixes-and-tests-Jvz1cclaude/site-audit-competitive-pctlwgclaude/site-migration-vercel-XstpKclaude/standalone-product-repos-XHFTDcopilot/feat-smart-empty-states-keyboard-first-enhancementcopilot/feat-smart-morning-digest-review-context-restorecopilot/fix-and-process-workflowscopilot/update-ai-powered-code-reviewfeat/debt-mapfeat/push-policy-codeowners-hardeningfeat/smart-digest-contextfeat/stage-impactfeat/t1-secret-migrationfeat/u-polishfeat/w-self-hostfeat/w2-claude-configfix/agent-journey-orphan-sweepgatetest/auto-fix-1776586424172gatetest/auto-fix-1776586534814gatetest/auto-fix-1776590685143gatetest/auto-fix-1776590808199mainops/redeploy-retriggerstyle/dxt-cta-themeworktree-agent-a3377aad30d55da26worktree-agent-a7ef607b7ee1d6c74
claude-integration.ts9.9 KB · 324 lines
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
/**
 * 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 } from "../db/schema";
import { initBareRepo } 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 });
});

export default claudeIntegration;