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
webhook-delivery.ts12.6 KB · 432 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
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
/**
 * Reliable webhook delivery (migration 0056).
 *
 * Replaces the inline single-shot fetch in src/routes/webhooks.tsx with a
 * durable pending-row queue. `enqueueWebhookDelivery()` precomputes the HMAC
 * signature, inserts one row per (hook, event) into `webhook_deliveries`
 * with `status='pending'` and `next_attempt_at=now()`, then kicks the
 * worker. The worker picks claims rows whose `next_attempt_at <= now()` and
 * attempts each POST.
 *
 * Retry schedule (after attempt #1 fires immediately):
 *   attempt 2 → +30s
 *   attempt 3 → +2m
 *   attempt 4 → +10m
 *   attempt 5 → +1h
 *   attempt 6 → +6h
 *   after attempt 6 → status='dead' (no further retries; row kept for ops)
 *
 * 2xx response → status='succeeded' + succeeded_at + last_status_code.
 * Anything else (including network errors and timeouts) → counted as a
 * failed attempt and rescheduled.
 *
 * Public surface:
 *   - enqueueWebhookDelivery({...})  — fire-and-forget queue insert
 *   - attemptDelivery(deliveryId)    — single attempt (exported for tests)
 *   - drainPendingDeliveries()       — drain a batch (exported for tests)
 *   - startWebhookDeliveryWorker()   — background poll loop
 *   - MAX_ATTEMPTS, BACKOFF_MS       — exported for tests
 */

import { and, asc, eq, lte, sql } from "drizzle-orm";
import { db } from "../db";
import { webhookDeliveries, webhooks } from "../db/schema";
import { assertPublicUrl } from "./ssrf-guard";

// ---------------------------------------------------------------------------
// Tunables
// ---------------------------------------------------------------------------

/** How many attempts in total before a row goes to status='dead'. */
export const MAX_ATTEMPTS = 6;

/**
 * Backoff schedule, indexed by the *next* attempt number we're scheduling.
 * After attemptCount=N fails, we schedule attempt N+1 at now() + BACKOFF_MS[N].
 * Index 0 is unused (attempt 1 is queued at now() by enqueue, not by retry).
 */
export const BACKOFF_MS: number[] = [
  0, // [0] unused
  30_000, // after attempt 1 fails → +30s for attempt 2
  120_000, // after attempt 2 fails → +2m for attempt 3
  600_000, // after attempt 3 fails → +10m for attempt 4
  3_600_000, // after attempt 4 fails → +1h for attempt 5
  21_600_000, // after attempt 5 fails → +6h for attempt 6
];

/** How often the worker scans for due pending rows. */
const DEFAULT_POLL_INTERVAL_MS = 5_000;

/** Cap on rows pulled in a single tick. */
const BATCH_SIZE = 10;

/** Per-delivery HTTP timeout. */
const DELIVERY_TIMEOUT_MS = 10_000;

/** Cap on stored last_error string. */
const ERROR_CAP = 2_000;

// ---------------------------------------------------------------------------
// Signing
// ---------------------------------------------------------------------------

/**
 * Compute the `sha256=<hex>` HMAC signature for a payload. Returns the empty
 * string when the hook has no secret — caller should still POST but skip the
 * `X-Gluecron-Signature` header.
 */
export async function computeSignature(
  secret: string | null,
  payloadJson: string
): Promise<string> {
  if (!secret) return "";
  const encoder = new TextEncoder();
  const key = await crypto.subtle.importKey(
    "raw",
    encoder.encode(secret),
    { name: "HMAC", hash: "SHA-256" },
    false,
    ["sign"]
  );
  const signature = await crypto.subtle.sign(
    "HMAC",
    key,
    encoder.encode(payloadJson)
  );
  return (
    "sha256=" +
    Array.from(new Uint8Array(signature))
      .map((b) => b.toString(16).padStart(2, "0"))
      .join("")
  );
}

// ---------------------------------------------------------------------------
// Enqueue
// ---------------------------------------------------------------------------

/**
 * Insert one pending delivery row. Caller passes hook + event + payload; we
 * snapshot the signature now so future schedule-time secret rotation can't
 * silently invalidate in-flight retries. Returns the new row id, or null on
 * insert failure (logged; never throws).
 */
export async function enqueueWebhookDelivery(input: {
  webhookId: string;
  secret: string | null;
  event: string;
  payload: Record<string, unknown>;
}): Promise<string | null> {
  try {
    const payloadJson = JSON.stringify(input.payload);
    const signature = await computeSignature(input.secret, payloadJson);

    const [row] = await db
      .insert(webhookDeliveries)
      .values({
        webhookId: input.webhookId,
        event: input.event,
        payload: payloadJson,
        signature,
        attemptCount: 0,
        nextAttemptAt: new Date(),
        status: "pending",
      })
      .returning({ id: webhookDeliveries.id });

    return row?.id ?? null;
  } catch (err) {
    console.error("[webhook-delivery] enqueue failed:", err);
    return null;
  }
}

// ---------------------------------------------------------------------------
// One attempt
// ---------------------------------------------------------------------------

/**
 * Run a single delivery attempt against the given row. Looks up the hook URL
 * fresh (so a deleted hook short-circuits), POSTs, then updates the row to
 * succeeded / pending (with new next_attempt_at) / dead based on the result.
 *
 * Returns 'succeeded' | 'retry' | 'dead' | 'gone' (hook was deleted).
 */
export async function attemptDelivery(
  deliveryId: string
): Promise<"succeeded" | "retry" | "dead" | "gone"> {
  // Pull the delivery row + the hook URL in one shot.
  const rows = await db
    .select({
      delivery: webhookDeliveries,
      url: webhooks.url,
      isActive: webhooks.isActive,
    })
    .from(webhookDeliveries)
    .leftJoin(webhooks, eq(webhooks.id, webhookDeliveries.webhookId))
    .where(eq(webhookDeliveries.id, deliveryId))
    .limit(1);

  const row = rows[0];
  if (!row) return "gone";
  if (!row.url || row.isActive === false) {
    // Hook deleted or disabled between enqueue and attempt — mark dead so
    // we don't keep polling it.
    await db
      .update(webhookDeliveries)
      .set({
        status: "dead",
        lastError: "hook deleted or disabled",
        lastAttemptedAt: new Date(),
      })
      .where(eq(webhookDeliveries.id, deliveryId));
    return "gone";
  }

  const d = row.delivery;
  const attemptNumber = d.attemptCount + 1;

  // SSRF guard (BUILD_BIBLE §7): refuse to POST to private/internal
  // addresses. Permanent condition — retrying won't change the URL — so
  // the row goes straight to 'dead' with a clear reason. Never throws.
  const guard = assertPublicUrl(row.url);
  if (!guard.ok) {
    const blockedAt = new Date();
    await db
      .update(webhookDeliveries)
      .set({
        status: "dead",
        attemptCount: attemptNumber,
        lastAttemptedAt: blockedAt,
        lastStatusCode: null,
        lastError: `blocked: ${guard.reason} (SSRF protection)`,
        nextAttemptAt: null,
      })
      .where(eq(webhookDeliveries.id, deliveryId));

    try {
      await db
        .update(webhooks)
        .set({ lastDeliveredAt: blockedAt, lastStatus: 0 })
        .where(eq(webhooks.id, d.webhookId));
    } catch {
      /* swallow */
    }

    return "dead";
  }

  // Perform the POST.
  let statusCode: number | null = null;
  let errorMessage: string | null = null;
  let success = false;

  try {
    const headers: Record<string, string> = {
      "Content-Type": "application/json",
      "X-Gluecron-Event": d.event,
      "X-Gluecron-Delivery": d.id,
    };
    if (d.signature) headers["X-Gluecron-Signature"] = d.signature;

    const res = await fetch(row.url, {
      method: "POST",
      headers,
      body: d.payload,
      signal: AbortSignal.timeout(DELIVERY_TIMEOUT_MS),
    });
    statusCode = res.status;
    success = res.status >= 200 && res.status < 300;
    if (!success) {
      errorMessage = `HTTP ${res.status}`;
    }
  } catch (err) {
    errorMessage =
      err instanceof Error ? err.message : String(err ?? "unknown error");
    if (errorMessage.length > ERROR_CAP) {
      errorMessage = errorMessage.slice(0, ERROR_CAP);
    }
  }

  const now = new Date();

  if (success) {
    await db
      .update(webhookDeliveries)
      .set({
        status: "succeeded",
        attemptCount: attemptNumber,
        lastAttemptedAt: now,
        lastStatusCode: statusCode,
        lastError: null,
        succeededAt: now,
        nextAttemptAt: null,
      })
      .where(eq(webhookDeliveries.id, deliveryId));

    // Best-effort sync of the parent hook row for the legacy "last status"
    // surface in /settings/webhooks. Never throws out.
    try {
      await db
        .update(webhooks)
        .set({ lastDeliveredAt: now, lastStatus: statusCode ?? 0 })
        .where(eq(webhooks.id, d.webhookId));
    } catch {
      /* swallow */
    }

    return "succeeded";
  }

  // Failure path.
  if (attemptNumber >= MAX_ATTEMPTS) {
    await db
      .update(webhookDeliveries)
      .set({
        status: "dead",
        attemptCount: attemptNumber,
        lastAttemptedAt: now,
        lastStatusCode: statusCode,
        lastError: errorMessage,
        nextAttemptAt: null,
      })
      .where(eq(webhookDeliveries.id, deliveryId));

    try {
      await db
        .update(webhooks)
        .set({ lastDeliveredAt: now, lastStatus: statusCode ?? 0 })
        .where(eq(webhooks.id, d.webhookId));
    } catch {
      /* swallow */
    }

    return "dead";
  }

  // Schedule the next attempt.
  const backoff = BACKOFF_MS[attemptNumber] ?? BACKOFF_MS[BACKOFF_MS.length - 1];
  const nextAt = new Date(now.getTime() + backoff);

  await db
    .update(webhookDeliveries)
    .set({
      status: "pending",
      attemptCount: attemptNumber,
      lastAttemptedAt: now,
      lastStatusCode: statusCode,
      lastError: errorMessage,
      nextAttemptAt: nextAt,
    })
    .where(eq(webhookDeliveries.id, deliveryId));

  try {
    await db
      .update(webhooks)
      .set({ lastDeliveredAt: now, lastStatus: statusCode ?? 0 })
      .where(eq(webhooks.id, d.webhookId));
  } catch {
    /* swallow */
  }

  return "retry";
}

// ---------------------------------------------------------------------------
// Drain — claim up to BATCH_SIZE due rows and attempt them.
// ---------------------------------------------------------------------------

/** Claim and attempt up to BATCH_SIZE due rows. Returns count attempted. */
export async function drainPendingDeliveries(): Promise<number> {
  const now = new Date();
  let due: { id: string }[] = [];
  try {
    due = await db
      .select({ id: webhookDeliveries.id })
      .from(webhookDeliveries)
      .where(
        and(
          eq(webhookDeliveries.status, "pending"),
          lte(webhookDeliveries.nextAttemptAt, now)
        )
      )
      .orderBy(asc(webhookDeliveries.nextAttemptAt))
      .limit(BATCH_SIZE);
  } catch (err) {
    console.error("[webhook-delivery] poll failed:", err);
    return 0;
  }

  if (due.length === 0) return 0;

  // Run attempts in parallel — they're IO-bound and target different URLs.
  await Promise.all(
    due.map((row) =>
      attemptDelivery(row.id).catch((err) => {
        console.error(
          `[webhook-delivery] attempt for ${row.id} threw:`,
          err
        );
      })
    )
  );

  return due.length;
}

// ---------------------------------------------------------------------------
// Worker
// ---------------------------------------------------------------------------

let workerStarted = false;

/**
 * Background poll loop. Idempotent — calling twice is a no-op. Returns a
 * stop function (used in tests; production never stops).
 */
export function startWebhookDeliveryWorker(opts?: {
  intervalMs?: number;
}): () => void {
  if (workerStarted) return () => {};
  workerStarted = true;

  const intervalMs = opts?.intervalMs ?? DEFAULT_POLL_INTERVAL_MS;
  let stopped = false;
  let active = false;

  const tick = async () => {
    if (stopped || active) return;
    active = true;
    try {
      // Keep draining while there's work — many due rows can pile up
      // after an outage of the downstream service.
      let n = await drainPendingDeliveries();
      while (n >= BATCH_SIZE && !stopped) {
        n = await drainPendingDeliveries();
      }
    } catch (err) {
      console.error("[webhook-delivery] worker tick:", err);
    } finally {
      active = false;
    }
  };

  const handle = setInterval(() => {
    void tick();
  }, intervalMs);

  // Best-effort: don't keep the process alive in tests/CLIs.
  if (typeof (handle as { unref?: () => void }).unref === "function") {
    (handle as { unref?: () => void }).unref?.();
  }

  return () => {
    stopped = true;
    workerStarted = false;
    clearInterval(handle);
  };
}

// Silence unused-import warnings for `sql` (kept in case future schedule
// migrations want raw expressions — drizzle's lte/eq cover all current uses).
void sql;