mcpField
R
replicate-webhooks

replicate-webhooks

github.com/hookdeck開発95198 回インストール今日更新
リポジトリ

replicate-webhooks について

ReplicateのWebhookハンドラーを構築する開発者向けのスキルです。予測のライフサイクルイベント、署名検証、ペイロードを扱い、各種フレームワークの実装例を案内します。

主な機能

  1. 01予測ステータスイベントの処理
  2. 02Webhook署名の検証
  3. 03イベントペイロード構造の確認
  4. 04Express、Next.js、FastAPIの実装リファレンス
  5. 05ローカルトンネルでのテスト

活用シーン

  1. 01予測完了または失敗の通知処理
  2. 02予測ステータスに応じた画面更新や出力処理

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/hookdeck/webhook-skills --skill replicate-webhooks

インストール後、Claude Code で/replicate-webhooksを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

TODO.md
examples/express/
.env.example
jest.config.js
package.json
README.md
examples/express/src/
index.js
examples/express/test/
webhook.test.js
examples/fastapi/
.env.example
main.py
README.md
requirements.txt
test_webhook.py
examples/nextjs/
.env.example
package.json
README.md
vitest.config.ts
examples/nextjs/app/webhooks/replicate/
route.ts
examples/nextjs/test/
webhook.test.ts
references/
overview.md
setup.md
verification.md

詳細

Replicate Webhook

このスキルを使用する場面

  • Replicate の webhook ハンドラーを設定する
  • 署名検証の失敗をデバッグする
  • Replicate のイベントタイプとペイロードを理解する
  • 予測のライフサイクルイベント(開始、出力、ログ、完了)を処理する

必須コード(必ず使用)

Express Webhook ハンドラー
const express = require('express');
const crypto = require('crypto');

const app = express();

// CRITICAL: Use express.raw() for webhook endpoint - Replicate needs raw body
app.post('/webhooks/replicate',
  express.raw({ type: 'application/json' }),
  async (req, res) => {
    // Get webhook headers
    const webhookId = req.headers['webhook-id'];
    const webhookTimestamp = req.headers['webhook-timestamp'];
    const webhookSignature = req.headers['webhook-signature'];

    // Verify we have required headers
    if (!webhookId || !webhookTimestamp || !webhookSignature) {
      return res.status(400).json({ error: 'Missing required webhook headers' });
    }

    // Manual signature verification (recommended approach)
    const secret = process.env.REPLICATE_WEBHOOK_SECRET; // whsec_xxxxx from Replicate
    const signedContent = `${webhookId}.${webhookTimestamp}.${req.body}`;

    try {
      // Extract base64 secret after 'whsec_' prefix
      const secretBytes = Buffer.from(secret.split('_')[1], 'base64');
      const expectedSignature = crypto
        .createHmac('sha256', secretBytes)
        .update(signedContent)
        .digest('base64');

      // Replicate can send multiple signatures, check each one
      const signatures = webhookSignature.split(' ').map(sig => {
        const parts = sig.split(',');
        return parts.length > 1 ? parts[1] : sig;
      });

      const isValid = signatures.some(sig => {
        try {
          return crypto.timingSafeEqual(
            Buffer.from(sig),
            Buffer.from(expectedSignature)
          );
        } catch {
          return false; // Different lengths = invalid
        }
      });

      if (!isValid) {
        return res.status(400).json({ error: 'Invalid signature' });
      }

      // Check timestamp to prevent replay attacks (5-minute window)
      const timestamp = parseInt(webhookTimestamp, 10);
      const currentTime = Math.floor(Date.now() / 1000);
      if (currentTime - timestamp > 300) {
        return res.status(400).json({ error: 'Timestamp too old' });
      }
    } catch (err) {
      console.error('Signature verification error:', err);
      return res.status(400).json({ error: 'Invalid signature' });
    }

    // Parse the verified webhook body
    const prediction = JSON.parse(req.body.toString());

    // Handle the prediction based on its status
    console.log('Prediction webhook received:', {
      id: prediction.id,
      status: prediction.status,
      version: prediction.version
    });

    switch (prediction.status) {
      case 'starting':
        console.log('Prediction starting:', prediction.id);
        break;
      case 'processing':
        console.log('Prediction processing:', prediction.id);
        if (prediction.logs) {
          console.log('Logs:', prediction.logs);
        }
        break;
      case 'succeeded':
        console.log('Prediction completed successfully:', prediction.id);
        console.log('Output:', prediction.output);
        break;
      case 'failed':
        console.log('Prediction failed:', prediction.id);
        console.log('Error:', prediction.error);
        break;
      case 'canceled':
        console.log('Prediction canceled:', prediction.id);
        break;
      default:
        console.log('Unknown status:', prediction.status);
    }

    res.status(200).json({ received: true });
  }
);

よくある予測ステータス

ステータス説明よくある使用例
starting予測を初期化していますUI に読み込み状態を表示する
processingモデルが実行中です進行状況を表示し、利用可能な場合はログを表示する
succeeded予測が正常に完了しました最終出力を処理し、UI を更新する
failed予測でエラーが発生しましたユーザーにエラーメッセージを表示する
canceled予測がキャンセルされましたリソースをクリーンアップし、ユーザーに通知する

環境変数

# Your webhook signing secret from Replicate
REPLICATE_WEBHOOK_SECRET=whsec_your_secret_here

ローカル開発

ローカルで webhook をテストするには、Hookdeck CLI をインストールします。

次に、トンネルを起動します。

npx hookdeck-cli listen 3000 replicate --path /webhooks/replicate

アカウントは不要です。リクエストを確認できるローカルトンネルと Web UI を提供します。

参考資料

実装用リソース

フレームワークの例
ドキュメント

推奨:webhook-handler-patterns

次のパターンを活用して、webhook の実装を強化しましょう。

関連スキル

コメント