コンテンツにスキップ

Webhook サーバー

WebhookServer は Ed25519 署名検証付きの HTTP Webhook サーバーです。mixi2 からのイベントを安全に受信できます。

// ESM
import { WebhookServer, EventType } from 'mixi2-js';
import type { EventHandler, Event } from 'mixi2-js';
// CJS
const { WebhookServer, EventType } = require('mixi2-js');
const handler: EventHandler = {
handle: async (event: Event) => {
switch (event.eventType) {
case EventType.POST_CREATED:
console.log('Post created:', event.postCreatedEvent?.post?.text);
break;
case EventType.CHAT_MESSAGE_RECEIVED:
console.log('Chat message:', event.chatMessageReceivedEvent?.message?.text);
break;
}
},
};
// 公開鍵は Base64 からデコード
const publicKey = Buffer.from(process.env.SIGNATURE_PUBLIC_KEY!, 'base64');
const server = new WebhookServer({
port: 8080,
publicKey,
handler,
});
await server.start();
console.log('Webhook server started on :8080');
new WebhookServer(options: WebhookServerOptions)
プロパティ必須デフォルト説明
publicKeyBuffer-Ed25519 公開鍵(Base64 をデコードしたもの)
handlerEventHandler-イベントハンドラ
portnumber-8080リッスンポート
syncHandlingboolean-falseイベントを同期処理するか
メソッド戻り値説明
start()Promise<void>サーバーを起動
shutdown()Promise<void>サーバーを停止
addressstringリッスンアドレス
httpServerhttp.Server内部の HTTP サーバーインスタンス
eventHandlerFuncFunctionイベントハンドラ関数(フレームワーク統合用)
パスメソッド説明
/eventsPOSTイベント受信(署名検証 → protobuf デコード → ハンドラ呼出)
/healthzGETヘルスチェック(常に 200 OK
項目
署名ヘッダx-mixi2-application-event-signature(Base64)
タイムスタンプヘッダx-mixi2-application-event-timestamp(Unix 秒)
署名対象リクエストボディ + タイムスタンプ
許容時刻ズレ±300 秒(5 分)
署名失敗レスポンスHTTP 401
成功レスポンスHTTP 204

Vercel、AWS Lambda などレスポンス後にプロセスが終了する環境では syncHandling: true を設定してください:

const server = new WebhookServer({
port: 8080,
publicKey,
handler,
syncHandling: true,
});
export default server.httpServer;

詳細は 公式ドキュメント を参照してください。