Files
outline/server/middlewares/validateWebhook.ts
Tom Moor 00fb4d1af7 chore: Update node style imports (#11277)
- crypto → node:crypto
  - fs → node:fs
  - fs/promises → node:fs/promises
  - path → node:path
  - http → node:http
  - https → node:https
  - stream → node:stream
  - buffer → node:buffer
  - url → node:url
  - os → node:os
  - net → node:net
  - dns → node:dns
  - events → node:events
  - readline → node:readline
  - querystring → node:querystring
  - util → node:util
2026-01-26 20:51:50 -05:00

37 lines
951 B
TypeScript

import crypto from "node:crypto";
import type { Next } from "koa";
import type { APIContext } from "@server/types";
import { safeEqual } from "@server/utils/crypto";
export default function validateWebhook({
secretKey,
getSignatureFromHeader,
}: {
secretKey: string;
getSignatureFromHeader: (ctx: APIContext) => string | undefined;
}) {
return async function validateWebhookMiddleware(ctx: APIContext, next: Next) {
const { body } = ctx.request;
const signatureFromHeader = getSignatureFromHeader(ctx);
if (!signatureFromHeader) {
ctx.status = 401;
ctx.body = "Missing signature header";
return;
}
const computedSignature = crypto
.createHmac("sha256", secretKey)
.update(JSON.stringify(body))
.digest("hex");
if (!safeEqual(computedSignature, signatureFromHeader)) {
ctx.status = 401;
ctx.body = "Invalid signature";
return;
}
return next();
};
}