husteno-o feat: issue management, standup, full PR review, webhooks, news digest · 9/10/2026
967bdc7
346 lines · 12.3 KB
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
import { cache } from "@devpulse/cache";
import { config } from "@devpulse/config";
import { formatBytes } from "@devpulse/core";
import { db, users } from "@devpulse/database";
import { logger } from "@devpulse/logger";
import { metricsCollector } from "@devpulse/monitoring";
import { encryptSecret } from "@devpulse/security";
import { createHmac, timingSafeEqual } from "crypto";
import { eq, sql } from "drizzle-orm";
import Fastify, { type FastifyBaseLogger, type FastifyInstance } from "fastify";

const RATE_LIMIT_WINDOW = 60;
const RATE_LIMIT_MAX = 100;

async function rateLimitHook(
  req: { ip: string },
  reply: { status: (code: number) => { send: (body: unknown) => void } },
) {
  const key = `ratelimit:api:${req.ip}`;
  const result = await cache.checkRateLimit(key, RATE_LIMIT_MAX, RATE_LIMIT_WINDOW);
  if (!result.allowed) {
    reply.status(429).send({
      error: "Too Many Requests",
      retryAfter: result.resetSeconds,
    });
  }
}

export interface ServerOptions {
  discordClient?: {
    isReady?: () => boolean;
    ws?: { ping?: number };
    guilds?: { cache?: { size: number } };
    user?: { tag?: string } | null;
  };
}

/**
 * Builds and configures the Fastify HTTP server with health, readiness,
 * metrics, and GitHub OAuth endpoints. Includes rate limiting.
 */
export function buildServer(options?: ServerOptions): FastifyInstance {
  const server = Fastify({
    loggerInstance: logger as FastifyBaseLogger,
  });

  server.addHook("onRequest", rateLimitHook);

  server.get("/health", async () => {
    const memory = process.memoryUsage();
    const discordStatus = options?.discordClient
      ? {
          connected: options.discordClient.isReady ? options.discordClient.isReady() : false,
          pingMs: options.discordClient.ws?.ping ?? -1,
          guildsCount: options.discordClient.guilds?.cache?.size ?? 0,
          user: options.discordClient.user?.tag ?? null,
        }
      : undefined;

    return {
      status: "healthy",
      service: "DevPulse API",
      uptimeSeconds: Math.floor(process.uptime()),
      timestamp: new Date().toISOString(),
      ...(discordStatus ? { discord: discordStatus } : {}),
      memory: {
        rss: formatBytes(memory.rss),
        heapUsed: formatBytes(memory.heapUsed),
        heapTotal: formatBytes(memory.heapTotal),
      },
    };
  });

  server.get("/ready", async (_req, reply) => {
    try {
      // Test DB
      await db.run(sql`SELECT 1`);

      // Test Cache
      await cache.set("devpulse:readiness-probe", "ok", 10);
      const cacheVal = await cache.get<string>("devpulse:readiness-probe");
      if (cacheVal !== "ok") {
        return reply.status(503).send({ status: "degraded", reason: "Cache read failure" });
      }

      return {
        status: "ready",
        database: "connected",
        cache: "connected",
        ...(options?.discordClient
          ? { discord: options.discordClient.isReady?.() ? "connected" : "connecting" }
          : {}),
        timestamp: new Date().toISOString(),
      };
    } catch (err: unknown) {
      logger.error({ err }, "Readiness check failed");
      return reply.status(503).send({
        status: "unready",
        error: err instanceof Error ? err.message : String(err),
      });
    }
  });

  server.get("/metrics", async () => {
    const allServers = await db.query.servers.findMany();
    const allRepos = await db.query.repositories.findMany();
    const allMonitors = await db.query.monitors.findMany();

    return {
      serversCount: allServers.length,
      repositoriesTracked: allRepos.length,
      monitorsActive: allMonitors.filter((m) => m.isActive).length,
      monitorsTotal: allMonitors.length,
      ...(options?.discordClient?.guilds?.cache
        ? { discordGuilds: options.discordClient.guilds.cache.size }
        : {}),
      nodeVersion: process.version,
      platform: process.platform,
      detailed: metricsCollector.getSnapshot(),
    };
  });

  server.get("/metrics/prometheus", async (_req, reply) => {
    reply.header("Content-Type", "text/plain; version=0.0.4; charset=utf-8");
    return metricsCollector.getPrometheusMetrics();
  });

  // --------------------------------------------------------------------------
  // GitHub Webhook Endpoint
  // --------------------------------------------------------------------------
  server.post("/webhooks/github", async (req, reply) => {
    const signature = req.headers["x-hub-signature-256"] as string | undefined;
    const event = req.headers["x-github-event"] as string | undefined;
    const deliveryId = req.headers["x-github-delivery"] as string | undefined;

    if (!event) {
      return reply.status(400).send({ error: "Missing X-GitHub-Event header" });
    }

    // Verify webhook signature if secret is configured
    if (config.GITHUB_WEBHOOK_SECRET && signature) {
      const payload = JSON.stringify(req.body);
      const expectedSig = `sha256=${createHmac("sha256", config.GITHUB_WEBHOOK_SECRET).update(payload).digest("hex")}`;
      const sigBytes = Buffer.from(signature);
      const expectedBytes = Buffer.from(expectedSig);

      if (sigBytes.length !== expectedBytes.length || !timingSafeEqual(sigBytes, expectedBytes)) {
        logger.warn({ deliveryId, event }, "Webhook signature verification failed");
        return reply.status(401).send({ error: "Invalid signature" });
      }
    }

    const payload = req.body as Record<string, unknown>;
    const repo = (payload.repository as { full_name?: string })?.full_name || "unknown";

    logger.info({ event, repo, deliveryId }, "GitHub webhook received");

    // Store event for deduplication
    const eventId = `webhook:${deliveryId || Date.now()}:${event}`;
    const existing = await cache.get(eventId);
    if (existing) {
      return reply.status(200).send({ status: "duplicate" });
    }
    await cache.set(eventId, "1", 3600);

    // Process event type
    switch (event) {
      case "release": {
        const action = payload.action as string;
        const release = payload.release as { tag_name?: string; html_url?: string } | undefined;
        if (action === "published" && release) {
          logger.info({ repo, tag: release.tag_name }, "New release published");
        }
        break;
      }
      case "pull_request": {
        const action = payload.action as string;
        const pr = payload.pull_request as { number?: number; title?: string } | undefined;
        if (action === "opened" && pr) {
          logger.info({ repo, pr: pr.number, title: pr.title }, "New PR opened");
        }
        break;
      }
      case "issues": {
        const action = payload.action as string;
        const issue = payload.issue as { number?: number; title?: string } | undefined;
        if (action === "opened" && issue) {
          logger.info({ repo, issue: issue.number, title: issue.title }, "New issue opened");
        }
        break;
      }
      case "push": {
        const commits = payload.commits as Array<{ message?: string }> | undefined;
        const branch = (payload.ref as string)?.replace("refs/heads/", "");
        logger.info({ repo, branch, commitCount: commits?.length || 0 }, "Push received");
        break;
      }
      default:
        logger.debug({ event, repo }, "Unhandled webhook event type");
    }

    return reply.status(200).send({ status: "ok", event, repo });
  });

  // --------------------------------------------------------------------------
  // GitHub OAuth Endpoints
  // --------------------------------------------------------------------------
  server.get("/auth/github/login", async (req, reply) => {
    const { userId } = req.query as { userId?: string };
    if (!config.GITHUB_CLIENT_ID) {
      return reply
        .status(500)
        .type("text/html")
        .send("<h1>Error: GITHUB_CLIENT_ID is not configured in .env</h1>");
    }

    const redirectUri =
      config.GITHUB_REDIRECT_URI ||
      `${req.protocol}://${req.headers.host || req.hostname}/auth/github/callback`;
    const state = userId || "anonymous";
    const githubAuthUrl = `https://github.com/login/oauth/authorize?client_id=${encodeURIComponent(
      config.GITHUB_CLIENT_ID,
    )}&redirect_uri=${encodeURIComponent(redirectUri)}&scope=repo,read:user&state=${encodeURIComponent(state)}`;

    return reply.redirect(githubAuthUrl);
  });

  server.get("/auth/github/callback", async (req, reply) => {
    const { code, state } = req.query as { code?: string; state?: string };

    if (!code) {
      return reply
        .status(400)
        .type("text/html")
        .send("<h1>Error: Missing authorization code from GitHub</h1>");
    }

    if (!config.GITHUB_CLIENT_ID || !config.GITHUB_CLIENT_SECRET) {
      return reply
        .status(500)
        .type("text/html")
        .send("<h1>Error: GitHub OAuth credentials not configured on server</h1>");
    }

    try {
      const tokenRes = await fetch("https://github.com/login/oauth/access_token", {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          client_id: config.GITHUB_CLIENT_ID,
          client_secret: config.GITHUB_CLIENT_SECRET,
          code,
        }),
      });

      const tokenData = (await tokenRes.json()) as {
        access_token?: string;
        error?: string;
        error_description?: string;
      };

      if (!tokenData.access_token) {
        return reply
          .status(400)
          .type("text/html")
          .send(
            `<h1>Authentication Failed</h1><p>${tokenData.error_description || "Could not retrieve access token."}</p>`,
          );
      }

      const userRes = await fetch("https://api.github.com/user", {
        headers: {
          Authorization: `Bearer ${tokenData.access_token}`,
          "User-Agent": "DevPulse-Discord-Bot",
        },
      });

      const ghUser = (await userRes.json()) as { login: string; id: number };
      const encrypted = encryptSecret(tokenData.access_token);
      const discordUserId = state && state !== "anonymous" ? state : null;

      if (discordUserId) {
        const existing = await db.query.users.findFirst({
          where: eq(users.id, discordUserId),
        });

        if (existing) {
          await db
            .update(users)
            .set({
              githubUsername: ghUser.login,
              githubTokenEncrypted: encrypted,
              updatedAt: new Date(),
            })
            .where(eq(users.id, discordUserId));
        } else {
          await db.insert(users).values({
            id: discordUserId,
            username: ghUser.login,
            githubUsername: ghUser.login,
            githubTokenEncrypted: encrypted,
          });
        }
      }

      return reply.type("text/html").send(`
        <!DOCTYPE html>
        <html>
        <head>
          <title>DevPulse - Connected</title>
          <style>
            body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #0d1117; color: #f0f6fc; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; }
            .card { background: #161b22; border: 1px solid #30363d; border-radius: 12px; padding: 40px; text-align: center; max-width: 440px; box-shadow: 0 8px 24px rgba(0,0,0,0.5); }
            h1 { color: #3fb950; font-size: 1.5rem; margin-bottom: 12px; }
            p { color: #8b949e; line-height: 1.6; margin-bottom: 24px; font-size: 0.95rem; }
            .badge { display: inline-block; background: rgba(56,139,253,0.15); color: #58a6ff; border: 1px solid rgba(56,139,253,0.4); padding: 4px 12px; border-radius: 6px; font-family: monospace; font-size: 0.9rem; margin-bottom: 20px; }
            .footer { font-size: 0.8rem; color: #6e7681; }
          </style>
        </head>
        <body>
          <div class="card">
            <h1>GitHub Connected</h1>
            <div class="badge">@${ghUser.login}</div>
            <p>Your GitHub account has been securely linked and encrypted with AES-256-GCM. You can now close this tab and return to Discord!</p>
            <div class="footer">DevPulse Developer Operating System</div>
          </div>
        </body>
        </html>
      `);
    } catch (err: unknown) {
      logger.error({ err }, "GitHub OAuth exchange failed");
      return reply
        .status(500)
        .type("text/html")
        .send(
          `<h1>Internal Server Error</h1><p>${err instanceof Error ? err.message : String(err)}</p>`,
        );
    }
  });

  return server;
}