line: centralize webhook signature validation

This commit is contained in:
Shadow
2026-01-26 19:10:11 -06:00
committed by Shadow
parent 3b8792ee29
commit e0dc49f287
4 changed files with 48 additions and 22 deletions

View File

@@ -1,8 +1,8 @@
import type { Request, Response, NextFunction } from "express";
import crypto from "node:crypto";
import type { WebhookRequestBody } from "@line/bot-sdk";
import { logVerbose, danger } from "../globals.js";
import type { RuntimeEnv } from "../runtime.js";
import { validateLineSignature } from "./signature.js";
export interface LineWebhookOptions {
channelSecret: string;
@@ -10,20 +10,6 @@ export interface LineWebhookOptions {
runtime?: RuntimeEnv;
}
function validateSignature(body: string, signature: string, channelSecret: string): boolean {
const hash = crypto.createHmac("SHA256", channelSecret).update(body).digest("base64");
const hashBuffer = Buffer.from(hash);
const signatureBuffer = Buffer.from(signature);
// Use constant-time comparison to prevent timing attacks
// Ensure buffers are same length before comparison to prevent timing leak
if (hashBuffer.length !== signatureBuffer.length) {
return false;
}
return crypto.timingSafeEqual(hashBuffer, signatureBuffer);
}
function readRawBody(req: Request): string | null {
const rawBody =
(req as { rawBody?: string | Buffer }).rawBody ??
@@ -61,7 +47,7 @@ export function createLineWebhookMiddleware(options: LineWebhookOptions) {
return;
}
if (!validateSignature(rawBody, signature, channelSecret)) {
if (!validateLineSignature(rawBody, signature, channelSecret)) {
logVerbose("line: webhook signature validation failed");
res.status(401).json({ error: "Invalid signature" });
return;