/ opencodehub / src / lib / runner-auth.ts
swadhinbiswas feat: implement production-grade security and fix critical vulnerabilities · 1/1/2026
0c17327
60 lines · 1.7 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
/**
 * Runner Authentication Utilities
 * Token-based authentication for CI/CD runners
 */

import crypto from "crypto";

const RUNNER_SECRET = import.meta.env.RUNNER_SECRET || crypto.randomBytes(32).toString("hex");

/**
 * Generate a runner token for a specific run
 */
export function generateRunnerToken(runId: string, expiresInSeconds: number = 7200): string {
    const expires = Math.floor(Date.now() / 1000) + expiresInSeconds;
    const data = `${runId}:${expires}`;
    const signature = crypto
        .createHmac("sha256", RUNNER_SECRET)
        .update(data)
        .digest("hex");

    return Buffer.from(JSON.stringify({ runId, expires, sig: signature })).toString("base64");
}

/**
 * Verify a runner token
 */
export function verifyRunnerToken(token: string | null | undefined, expectedRunId: string): boolean {
    // If no secret configured, allow all (development mode)
    if (!import.meta.env.RUNNER_SECRET) {
        return true;
    }

    if (!token) return false;

    try {
        const decoded = JSON.parse(Buffer.from(token, "base64").toString("utf-8"));
        const { runId, expires, sig } = decoded;

        // Check run ID matches
        if (runId !== expectedRunId) return false;

        // Check expiration
        if (Date.now() / 1000 > expires) return false;

        // Verify signature
        const data = `${runId}:${expires}`;
        const expectedSig = crypto
            .createHmac("sha256", RUNNER_SECRET)
            .update(data)
            .digest("hex");

        return crypto.timingSafeEqual(
            Buffer.from(sig, "hex"),
            Buffer.from(expectedSig, "hex")
        );
    } catch {
        return false;
    }
}