Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/utils/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export async function verifyGitHubSignature(rawBody: string, signatureHeader: st
export function timingSafeEqualHex(left: string, right: string): boolean {
const leftBytes = hexToBytes(left);
const rightBytes = hexToBytes(right);
if (!leftBytes || !rightBytes) return false;
if (leftBytes.length !== rightBytes.length) return false;
let result = 0;
for (let index = 0; index < leftBytes.length; index += 1) {
Expand All @@ -32,8 +33,8 @@ export function timingSafeEqualHex(left: string, right: string): boolean {
return result === 0;
}

function hexToBytes(hex: string): Uint8Array {
if (!/^[0-9a-f]+$/i.test(hex) || hex.length % 2 !== 0) return new Uint8Array();
function hexToBytes(hex: string): Uint8Array | null {
if (hex.length === 0 || hex.length % 2 !== 0 || !/^[0-9a-f]+$/i.test(hex)) return null;
const bytes = new Uint8Array(hex.length / 2);
for (let index = 0; index < bytes.length; index += 1) {
bytes[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16);
Expand Down
12 changes: 11 additions & 1 deletion test/unit/crypto.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { createOpaqueToken, hashToken, timingSafeEqual } from "../../src/auth/security";
import { verifyGitHubSignature } from "../../src/utils/crypto";
import { verifyGitHubSignature, timingSafeEqualHex } from "../../src/utils/crypto";

describe("webhook signature verification", () => {
it("accepts valid GitHub HMAC signatures and rejects tampering", async () => {
Expand All @@ -17,6 +17,16 @@ describe("webhook signature verification", () => {
await expect(verifyGitHubSignature(body, null, secret)).resolves.toBe(false);
await expect(verifyGitHubSignature(body, "bad-prefix", secret)).resolves.toBe(false);
await expect(verifyGitHubSignature(body, `sha256=${signature}`, "")).resolves.toBe(false);
await expect(verifyGitHubSignature(body, "sha256=not-valid-hex", secret)).resolves.toBe(false);
});

it("rejects invalid hex operands in timingSafeEqualHex", () => {
expect(timingSafeEqualHex("zz", "yy")).toBe(false);
expect(timingSafeEqualHex("not-hex-a", "not-hex-b")).toBe(false);
expect(timingSafeEqualHex("abc", "abcd")).toBe(false);
expect(timingSafeEqualHex("", "00")).toBe(false);
expect(timingSafeEqualHex("00", "01")).toBe(false);
expect(timingSafeEqualHex("00", "00")).toBe(true);
});

it("uses timing-safe token comparisons and one-way token hashes", async () => {
Expand Down
Loading