Open1
Spearly CMSのWebhookのエンドポイントをCloud Functionsで作る
Spearly CMSのWebhook URLのエンドポイントをCloud Functionsで作る時のメモ
- 毎回どこに書いたか忘れるので、コピーできるように貼っておく
index.ts
import * as functions from "firebase-functions";
import {Octokit} from "@octokit/core";
import * as crypto from "crypto";
const GITHUB_TOKEN = process.env.GITHUB_TOKEN ?? "";
const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET ?? "";
type SIGNATURE = `sha256=${string}`
const octokit = new Octokit({auth: GITHUB_TOKEN});
const generateRequestSignature = (body: string): SIGNATURE => {
const hash = crypto.createHmac("sha256", WEBHOOK_SECRET)
.update(JSON.stringify(body))
.digest("hex");
return `sha256=${hash}`;
};
const owner = "ユーザー名";
const repo = "リポジトリ名";
const eventType = "イベント名";
export const deploy = functions.https.onRequest(async (request, response) => {
if (request.method !== "POST") {
response.status(405).send("Invalid method");
return;
}
const signature = request.headers["x-spy-signature-256"] as SIGNATURE;
const computedSignature = generateRequestSignature(request.body);
if (signature !== computedSignature) {
response.status(403).send("Invalid signature");
return;
}
try {
await octokit.request("POST /repos/{owner}/{repo}/dispatches", {
owner: owner,
repo: repo,
event_type: eventType,
});
} catch (error: any) {
functions.logger.error(error, {structuredData: true});
console.error(error);
}
});