Skip to content

Feature: Implement GitHub Webhook Handler for Task Detection #237

Closed

Description

@integry

Goal:
Implement a GitHub webhook listener as an alternative to the current polling mechanism for detecting new issues and PR comments. This should be configurable via environment variables.

The webhook listener should run within the 'daemon' service, as it has access to the task queue and configuration.

Implementation Steps:

  1. Update Dependencies:

    • Add 'express' to the root 'package.json'.
    • Run 'npm install'.
  2. Refactor 'src/daemon.js' Logic:

    • Create a new helper function 'processDetectedIssue' that takes an 'issue' object. This function will contain the logic currently in 'pollForIssues' for checking labels, finding target models, and enqueueing one or more 'processGitHubIssueJob' tasks.
    • Create a new helper function 'processCommentEvent' that takes a 'payload' (from 'issue_comment' or 'pull_request_review_comment') and the 'eventType'. This function will contain the logic for checking authors, trigger keywords, and enqueueing a 'processPullRequestCommentJob'.
    • Refactor 'pollForIssues' and 'pollForPullRequestComments' to use these new helper functions in their loops.
  3. Add Webhook Server to 'src/daemon.js':

    • Import 'express' and 'crypto'.
    • Add new constants for 'ENABLE_WEBHOOKS', 'WEBHOOK_PORT', and 'WEBHOOK_SECRET' from 'process.env'.
    • Create a 'verifySignature' middleware function that uses 'express.raw' and 'crypto.createHmac' to validate the 'X-Hub-Signature-256' header against the 'WEBHOOK_SECRET'.
    • Create a 'setupWebhookServer' function that initializes an Express app.
    • Add a 'POST /webhook' route to the app. This route MUST use the 'verifySignature' middleware first.
    • The '/webhook' handler should:
      • Read the 'x-github-event' header.
      • Parse the JSON payload (from 'req.body').
      • Use a 'switch' statement on the event type:
        • 'case 'issues'': If 'action' is 'labeled', call 'processDetectedIssue(payload.issue)'.
        • 'case 'issue_comment'': If 'action' is 'created', call 'processCommentEvent(payload, 'issue_comment')'.
        • 'case 'pull_request_review_comment'': If 'action' is 'created', call 'processCommentEvent(payload, 'pull_request_review_comment')'.
      • Start this server ('app.listen') inside 'setupWebhookServer'.
  4. Update 'startDaemon' in 'src/daemon.js':

    • At the beginning of the function, check 'if (ENABLE_WEBHOOKS)'.
    • If 'true':
      • Call 'await setupWebhookServer();'
      • Log that the webhook listener is active on 'WEBHOOK_PORT'.
      • DO NOT call 'safePoll()' or 'setInterval(safePoll, ...)'.
    • If 'false':
      • Keep the existing 'safePoll()' and 'setInterval' logic.
    • IMPORTANT: The config reloading interval and heartbeats should run in both modes.
  5. Update Config Files:

    • '.env.example': Add 'ENABLE_GITHUB_WEBHOOKS=false' and 'WEBHOOK_PORT=9090'.
    • 'docker-compose.yml': Expose the 'WEBHOOK_PORT' on the 'daemon' service.
    • 'docker-compose.prod.yml': Expose the 'WEBHOOK_PORT' on the 'daemon' service.

By centralizing the enqueueing logic, both the poller and the new webhook handler can use the same functions, reducing code duplication.

Activity

  1. integry commented on Nov 14, 2025

    @integry
    OwnerAuthor

    Here are the implementation details:

    1. package.json (root):
    Add 'express' to dependencies:

      "dependencies": {
        "@anthropic-ai/claude-code": "^2.0.1",
        "@octokit/auth-app": "^8.0.1",
    ...
        "bullmq": "^5.53.0",
        "dotenv": "^16.5.0",
    +   "express": "^4.19.2",
        "fs-extra": "^11.3.0",
    ...

    2. .env.example:
    Add new variables for webhook configuration.

    ...
    # Queue Configuration
    GITHUB_ISSUE_QUEUE_NAME=github-issue-processor
    WORKER_CONCURRENCY=2
    
    +# Webhook Configuration
    +ENABLE_GITHUB_WEBHOOKS=false
    +WEBHOOK_PORT=9090
    +GH_WEBHOOK_SECRET=your-webhook-secret
    +
    # Worker Configuration
    ...

    3. docker-compose.yml:
    Expose the webhook port on the 'daemon' service.

      daemon:
        build:
          context: .
          dockerfile: Dockerfile.node
        container_name: gitfix-daemon
        command: npm run daemon
    +   ports:
    +     - "${WEBHOOK_PORT:-9090}:${WEBHOOK_PORT:-9090}"
        volumes:
          - ./logs:/usr/src/app/logs
    ...

    4. docker-compose.prod.yml:
    Also expose the port in the production config.

      daemon:
        build:
          context: .
          dockerfile: Dockerfile
        restart: unless-stopped
    +   ports:
    +     - "${WEBHOOK_PORT:-9090}:${WEBHOOK_PORT:-9090}"
        environment:
          NODE_ENV: production
    ...

    5. src/daemon.js:
    This file will have the most significant changes.

    • Imports:

      import 'dotenv/config';
      import express from 'express';
      import crypto from 'crypto';
      import { getAuthenticatedOctokit } from './auth/githubAuth.js';
      // ... other imports
    • New Constants:

      // ...
      const ENABLE_WEBHOOKS = process.env.ENABLE_GITHUB_WEBHOOKS === 'true';
      const WEBHOOK_PORT = process.env.WEBHOOK_PORT || 9090;
      const WEBHOOK_SECRET = process.env.GH_WEBHOOK_SECRET;
      // ...
    • New Refactored Enqueueing Logic:
      (Create these functions to be called by both polling and webhooks)

      async function processDetectedIssue(issue, correlationId) {
        // This function contains the logic from 'pollForIssues' for a *single* issue
        // 1. Check labels against allExcludeLabels
        // 2. Find targetModels
        // 3. Loop targetModels and enqueue jobs (check for existing jobs)
        // 4. Log activity
      }
      
      async function processCommentEvent(payload, eventType, correlationId) {
        // This function contains the logic from 'pollForPullRequestComments' for a *single* event
        // 1. Determine if it's a PR comment
        // 2. Check author against whitelist/blacklist
        // 3. Check for trigger keywords
        // 4. Check if already processed (using Redis key)
        // 5. If all checks pass, enqueue a 'processPullRequestCommentJob'
      }
    • New Webhook Server Logic:

      function verifySignature(req, res, buf, encoding) {
        if (!WEBHOOK_SECRET) {
          logger.warn('Webhook secret not configured. Skipping signature verification.');
          return;
        }
        
        const signature = req.headers['x-hub-signature-256'];
        if (!signature) {
          throw new Error('No webhook signature provided.');
        }
      
        const hmac = crypto.createHmac('sha256', WEBHOOK_SECRET);
        hmac.update(buf, encoding);
        const computedSignature = `sha256=${hmac.digest('hex')}`;
      
        if (!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(computedSignature))) {
          throw new Error('Webhook signature mismatch.');
        }
      }
      
      async function setupWebhookServer() {
        const app = express();
        
        app.post('/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
          const correlationId = generateCorrelationId();
          const correlatedLogger = logger.withCorrelation(correlationId);
          
          try {
            verifySignature(req, res, req.body);
            const payload = JSON.parse(req.body.toString());
            const event = req.headers['x-github-event'];
            
            correlatedLogger.info({ event, action: payload.action, repo: payload.repository?.full_name }, 'Webhook event received');
      
            switch (event) {
              case 'issues':
                if (payload.action === 'labeled') {
                  await processDetectedIssue(payload.issue, correlationId);
                }
                break;
              case 'issue_comment':
                if (payload.action === 'created' && payload.issue.pull_request) {
                  await processCommentEvent(payload, 'issue_comment', correlationId);
                }
                break;
              case 'pull_request_review_comment':
                if (payload.action === 'created') {
                  await processCommentEvent(payload, 'pull_request_review_comment', correlationId);
                }
                break;
              default:
                correlatedLogger.debug({ event }, 'Ignoring webhook event');
            }
            
            res.status(200).send('Webhook processed.');
          } catch (error) {
            correlatedLogger.error({ error: error.message, stack: error.stack }, 'Failed to process webhook');
            res.status(error.message === 'Webhook signature mismatch.' ? 401 : 500).send(error.message);
          }
        });
      
        app.listen(WEBHOOK_PORT, () => {
          logger.info({ port: WEBHOOK_PORT }, `GitHub Webhook listener started on port ${WEBHOOK_PORT}`);
        });
      }
    • Updated 'startDaemon' Logic:

      async function startDaemon(options = {}) {
        // ... (load configs, run migrations, handle reset) ...
      
        if (ENABLE_WEBHOOKS) {
          logger.info('GitHub Webhooks are enabled. Starting webhook server.');
          if (!WEBHOOK_SECRET) {
            logger.warn('GH_WEBHOOK_SECRET is not set! Webhook signature verification will be skipped.');
          }
          await setupWebhookServer();
        } else {
          logger.info('GitHub Webhooks are disabled. Starting polling-based daemon.');
          // Initial poll
          const safePoll = withErrorHandling(pollForIssues, 'daemon polling');
          safePoll();
      
          // Set up recurring polling
          const intervalId = setInterval(safePoll, POLLING_INTERVAL_MS);
          
          // Handle shutdown for intervalId
          process.on('SIGINT', () => { ... clearInterval(intervalId); ... });
          process.on('SIGTERM', () => { ... clearInterval(intervalId); ... });
        }
      
        // ... (heartbeat logic, config reload interval, and shutdown handlers) ...
      }
  2. propr-dev commented on Nov 14, 2025

    @propr-dev
    Contributor

    🤖 AI processing has started for this issue using claude-sonnet-4-5-20250929 model.

    I'll analyze the problem and work on a solution. This may take a few minutes.

    Processing Details:

    • Model: claude-sonnet-4-5-20250929
    • Branch: ai-fix/237-feature-implement-github--20251114-1132-claude-sonnet-4-5-20250929-5le
    • Base Branch: main
    • Worktree: issue-237-20251114-1132-claude-sonnet-4-5-20250929-5le
  3. added a commit that references this issue on Nov 14, 2025
  4. added a commit that references this issue on Nov 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions