github-webhook-filter/lib/handler.ts

61 lines
1.9 KiB
TypeScript
Raw Normal View History

import { http } from "../deps.ts";
2022-09-02 23:14:28 +00:00
import { verify } from "./crypto.ts";
import filterWebhook from "./filter.ts";
import { UrlConfig } from "./types.d.ts";
2022-09-02 23:14:28 +00:00
import * as util from "./util.ts";
import { sendWebhook } from "./webhook.ts";
2022-09-02 20:24:33 +00:00
export default async function handle(req: Request): Promise<Response> {
if (req.method !== "POST") {
throw http.createHttpError(405);
}
// split url into parts
const url = new URL(req.url);
const [, id, token] = url.pathname.split("/");
const signature = url.searchParams.get("sig");
if (!id || !token || !signature) {
throw http.createHttpError(400);
}
// verify signature
if (!(await verify(`${id}/${token}`, signature))) {
throw http.createHttpError(403);
}
// extract data
const urlConfig = getUrlConfig(url.searchParams);
const data = await req.text();
const json = JSON.parse(data);
// do the thing
const filterReason = filterWebhook(req.headers, json, urlConfig);
2022-09-02 20:24:33 +00:00
if (filterReason !== null) {
return new Response(`Ignored by webhook filter (reason: ${filterReason})`, { status: 203 });
}
return await sendWebhook(id, token, req.headers, data);
}
2022-09-02 23:36:32 +00:00
function getUrlConfig(params: URLSearchParams): UrlConfig {
const config: UrlConfig = {};
for (const [key, value] of params) {
switch (key) {
case "sig":
continue;
case "allowBranches":
config.allowBranches = value.split(",");
break;
case "hideTags":
config.hideTags = util.parseBool(value);
break;
2022-09-03 15:10:58 +00:00
case "commentBurstLimit":
config.commentBurstLimit = parseInt(value);
break;
2022-09-02 23:36:32 +00:00
default:
throw http.createHttpError(418, `Unknown config option: ${key}`);
}
}
return config;
}