mcpField
R
replicate-webhooks

replicate-webhooks

github.com/hookdeck开发95198 次安装今天更新
代码仓库

关于 replicate-webhooks

面向构建 Replicate Webhook 处理程序的开发者,介绍预测生命周期事件、签名验证和载荷处理,并列出多种框架的实现参考。

主要功能

  1. 01处理预测状态事件
  2. 02验证 Webhook 签名
  3. 03了解事件载荷结构
  4. 04查看 Express、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 Webhooks

何时使用此技能

  • 设置 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 实现:

相关技能

评论

支持 Markdown