Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
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
events.ts12.4 KB · 387 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
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
/**
 * Inbound deploy-event receiver for Crontech (Signal Bus P1 — E3/E4).
 *
 * Wire contract reference: chat-defined spec for Crontech → Gluecron deploy
 * events. Gluecron's OWN copy per HTTP-only coupling rule — do NOT import any
 * types from Crontech. If the contract is renegotiated, update this comment
 * and the validation below in lock-step.
 *
 *   POST  /api/events/deploy
 *   Authorization: Bearer ${CRONTECH_EVENT_TOKEN}
 *   Content-Type: application/json
 *
 *   {
 *     "event":         "deploy.succeeded" | "deploy.failed",
 *     "eventId":       "<uuid-v4>",           // idempotency key
 *     "repository":    "owner/name",
 *     "sha":           "<40-hex>",
 *     "environment":   "production",
 *     "deploymentId":  "<crontech-id>",
 *     "durationMs":    <int>,                 // optional
 *     "errorCategory": "build|runtime|timeout|config",  // required on failed
 *     "errorSummary":  "<string ≤500>",                 // required on failed
 *     "logsUrl":       "<string>",            // optional
 *     "timestamp":     "<ISO-8601>"
 *   }
 *
 *   → 200 { ok: true, duplicate: false }
 *   → 200 { ok: true, duplicate: true }
 *   → 401 invalid bearer
 *   → 400 malformed payload
 *
 * Idempotency: an incoming `eventId` is first looked up in `processed_events`.
 * On hit we return { duplicate: true } immediately — no side-effects. On miss
 * we INSERT the idempotency record BEFORE performing the side-effect update so
 * that a retry after a crash between steps sees the record and short-circuits.
 *
 * Side-effect: look up the matching `deployments` row by
 * (repository_id, commit_sha, environment) — `deployments` has no
 * `crontech_deployment_id` column so we key off the tuple that
 * `triggerCrontechDeploy` writes on the way out.
 *
 *   E3 deploy.succeeded → status='success',  completedAt=now
 *   E4 deploy.failed    → status='failed',   blockedReason=errorSummary,
 *                         completedAt=now, notify(owner, 'deploy_failed')
 */

import { Hono } from "hono";
import { and, desc, eq } from "drizzle-orm";
import { timingSafeEqual } from "crypto";
import { db } from "../db";
import { deployments, repositories, users } from "../db/schema";
import { processedEvents } from "../db/schema-events";
import { notify } from "../lib/notify";

const events = new Hono();

// ---------------------------------------------------------------------------
// Bearer auth — timing-safe comparison against CRONTECH_EVENT_TOKEN.
// ---------------------------------------------------------------------------

function constantTimeEq(a: string, b: string): boolean {
  const A = Buffer.from(a);
  const B = Buffer.from(b);
  if (A.length !== B.length) return false;
  try {
    return timingSafeEqual(A, B);
  } catch {
    return false;
  }
}

function verifyBearer(c: any): { ok: boolean; error?: string } {
  const expected = process.env.CRONTECH_EVENT_TOKEN || "";
  if (!expected) {
    // Refuse by default — an unset secret must NOT allow anonymous writes.
    return {
      ok: false,
      error:
        "Event endpoint not configured: set CRONTECH_EVENT_TOKEN in the environment",
    };
  }
  const auth = c.req.header("authorization") || "";
  if (!auth.startsWith("Bearer ")) {
    return { ok: false, error: "Missing Bearer token" };
  }
  const token = auth.slice(7).trim();
  if (!constantTimeEq(token, expected)) {
    return { ok: false, error: "Invalid bearer token" };
  }
  return { ok: true };
}

// ---------------------------------------------------------------------------
// Payload validation — no zod in this repo, use manual checks mirroring the
// existing hooks.ts style. Keep error messages specific enough to diagnose a
// mis-built emitter without leaking internals.
// ---------------------------------------------------------------------------

type DeployEvent = "deploy.succeeded" | "deploy.failed";
type ErrorCategory = "build" | "runtime" | "timeout" | "config";

interface DeployEventPayload {
  event: DeployEvent;
  eventId: string;
  repository: string;
  sha: string;
  environment: string;
  deploymentId: string;
  durationMs?: number;
  errorCategory?: ErrorCategory;
  errorSummary?: string;
  logsUrl?: string;
  timestamp: string;
}

const UUID_V4_RE =
  /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
const SHA_RE = /^[0-9a-f]{40}$/i;
const VALID_EVENTS: ReadonlySet<string> = new Set([
  "deploy.succeeded",
  "deploy.failed",
]);
const VALID_CATEGORIES: ReadonlySet<string> = new Set([
  "build",
  "runtime",
  "timeout",
  "config",
]);

function validatePayload(raw: unknown): {
  ok: true;
  payload: DeployEventPayload;
} | { ok: false; error: string } {
  if (!raw || typeof raw !== "object") {
    return { ok: false, error: "Body must be a JSON object" };
  }
  const p = raw as Record<string, unknown>;

  if (typeof p.event !== "string" || !VALID_EVENTS.has(p.event)) {
    return {
      ok: false,
      error: "event must be 'deploy.succeeded' or 'deploy.failed'",
    };
  }
  if (typeof p.eventId !== "string" || !UUID_V4_RE.test(p.eventId)) {
    return { ok: false, error: "eventId must be a uuid-v4 string" };
  }
  if (typeof p.repository !== "string" || !p.repository.includes("/")) {
    return { ok: false, error: "repository must be '<owner>/<name>'" };
  }
  if (typeof p.sha !== "string" || !SHA_RE.test(p.sha)) {
    return { ok: false, error: "sha must be a 40-hex commit id" };
  }
  if (typeof p.environment !== "string" || p.environment.length === 0) {
    return { ok: false, error: "environment must be a non-empty string" };
  }
  if (typeof p.deploymentId !== "string" || p.deploymentId.length === 0) {
    return { ok: false, error: "deploymentId must be a non-empty string" };
  }
  if (typeof p.timestamp !== "string" || Number.isNaN(Date.parse(p.timestamp))) {
    return { ok: false, error: "timestamp must be an ISO-8601 string" };
  }
  if (p.durationMs !== undefined) {
    if (
      typeof p.durationMs !== "number" ||
      !Number.isFinite(p.durationMs) ||
      p.durationMs < 0
    ) {
      return { ok: false, error: "durationMs must be a non-negative number" };
    }
  }
  if (p.logsUrl !== undefined && typeof p.logsUrl !== "string") {
    return { ok: false, error: "logsUrl must be a string when present" };
  }

  if (p.event === "deploy.failed") {
    if (
      typeof p.errorCategory !== "string" ||
      !VALID_CATEGORIES.has(p.errorCategory)
    ) {
      return {
        ok: false,
        error:
          "errorCategory is required for deploy.failed and must be one of build|runtime|timeout|config",
      };
    }
    if (
      typeof p.errorSummary !== "string" ||
      p.errorSummary.length === 0 ||
      p.errorSummary.length > 500
    ) {
      return {
        ok: false,
        error:
          "errorSummary is required for deploy.failed and must be 1-500 chars",
      };
    }
  }

  return { ok: true, payload: p as unknown as DeployEventPayload };
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

async function resolveRepo(
  full: string
): Promise<{ id: string; ownerId: string } | null> {
  if (!full.includes("/")) return null;
  const [owner, name] = full.split("/", 2);
  try {
    const [row] = await db
      .select({
        id: repositories.id,
        ownerId: repositories.ownerId,
      })
      .from(repositories)
      .innerJoin(users, eq(repositories.ownerId, users.id))
      .where(and(eq(users.username, owner), eq(repositories.name, name)))
      .limit(1);
    return row || null;
  } catch {
    return null;
  }
}

async function findTargetDeployment(
  repositoryId: string,
  commitSha: string,
  environment: string
): Promise<{ id: string } | null> {
  try {
    const [row] = await db
      .select({ id: deployments.id })
      .from(deployments)
      .where(
        and(
          eq(deployments.repositoryId, repositoryId),
          eq(deployments.commitSha, commitSha),
          eq(deployments.environment, environment)
        )
      )
      .orderBy(desc(deployments.createdAt))
      .limit(1);
    return row || null;
  } catch {
    return null;
  }
}

// ---------------------------------------------------------------------------
// POST /api/events/deploy
// ---------------------------------------------------------------------------

events.post("/deploy", async (c) => {
  const auth = verifyBearer(c);
  if (!auth.ok) {
    return c.json({ ok: false, error: auth.error || "Unauthorized" }, 401);
  }

  let raw: unknown;
  try {
    raw = await c.req.json();
  } catch {
    return c.json({ ok: false, error: "Invalid JSON body" }, 400);
  }

  const validated = validatePayload(raw);
  if (!validated.ok) {
    return c.json({ ok: false, error: validated.error }, 400);
  }
  const payload = validated.payload;

  // --- Idempotency check ---------------------------------------------------
  // If we've already processed this eventId, return duplicate:true without
  // firing any side-effects.
  try {
    const [existing] = await db
      .select({ id: processedEvents.id })
      .from(processedEvents)
      .where(eq(processedEvents.eventId, payload.eventId))
      .limit(1);
    if (existing) {
      return c.json({ ok: true, duplicate: true });
    }
  } catch (err) {
    console.error("[events/deploy] idempotency lookup failed:", err);
    // Fall through — better to process than to wedge on a transient DB blip.
  }

  // --- Record the idempotency token BEFORE side-effects --------------------
  // Race: two simultaneous deliveries of the same eventId. The UNIQUE
  // constraint on event_id makes the losing insert throw; we catch that and
  // return duplicate:true to keep behaviour stable.
  try {
    await db.insert(processedEvents).values({
      eventId: payload.eventId,
      eventType: payload.event,
      source: "crontech",
      payload: payload as unknown as Record<string, unknown>,
    });
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    if (msg.includes("unique") || msg.includes("duplicate")) {
      return c.json({ ok: true, duplicate: true });
    }
    console.error("[events/deploy] processed_events insert failed:", err);
    return c.json({ ok: false, error: "Failed to persist event" }, 500);
  }

  // --- Side-effect: update the matching deployments row --------------------
  const repo = await resolveRepo(payload.repository);
  if (!repo) {
    // The idempotency row is already committed; we accept the event so we
    // don't invite infinite retries for a repo that genuinely doesn't exist
    // on this side of the wire. Log for operator follow-up.
    console.warn(
      `[events/deploy] unknown repository ${payload.repository} — event ${payload.eventId} accepted but no deployment update applied`
    );
    return c.json({ ok: true, duplicate: false });
  }

  const target = await findTargetDeployment(
    repo.id,
    payload.sha,
    payload.environment
  );

  if (target) {
    try {
      if (payload.event === "deploy.succeeded") {
        await db
          .update(deployments)
          .set({
            status: "success",
            completedAt: new Date(),
          })
          .where(eq(deployments.id, target.id));
      } else {
        await db
          .update(deployments)
          .set({
            status: "failed",
            blockedReason: payload.errorSummary,
            completedAt: new Date(),
          })
          .where(eq(deployments.id, target.id));
      }
    } catch (err) {
      console.error("[events/deploy] deployments update failed:", err);
    }
  } else {
    console.warn(
      `[events/deploy] no deployments row found for ${payload.repository}@${payload.sha} env=${payload.environment}`
    );
  }

  // --- On failure: notify the repo owner ----------------------------------
  if (payload.event === "deploy.failed") {
    try {
      await notify(repo.ownerId, {
        kind: "deploy_failed",
        title: `Deploy failed on ${payload.repository}`,
        body:
          payload.errorSummary ||
          `Crontech reported deploy failure (${payload.errorCategory || "unknown"})`,
        url: payload.logsUrl,
        repositoryId: repo.id,
      });
    } catch (err) {
      console.error("[events/deploy] notify failed:", err);
    }
  }

  return c.json({ ok: true, duplicate: false });
});

// Test-only access for unit tests that want to exercise helpers directly.
export const __test = {
  constantTimeEq,
  validatePayload,
  resolveRepo,
  findTargetDeployment,
};

export default events;