Skill站外收录 @skilllib/skill-2117939930272416916
ideogram-webhooks-events
实现 Ideogram 平台事件的可信接收与安全处理,包含请求签名验证、时间戳防重放、事件类型分发及基于 ID 的幂等性保障,适用于需与外部 AI 服务建立可靠异步通信的后端系统。
效率工具 AI 技能
Skills.MD
# Ideogram Webhooks & Events
## Overview
Securely handle Ideogram webhooks with signature validation and replay protection.
## Prerequisites
- Ideogram webhook secret configured
- HTTPS endpoint accessible from internet
- Understanding of cryptographic signatures
- Redis or database for idempotency (optional)
## Webhook Endpoint Setup
### Express.js
```typescript
import express from 'express';
import crypto from 'crypto';
const app = express();
// IMPORTANT: Raw body needed for signature verification
app.post('/webhooks/ideogram',
express.raw({ type: 'application/json' }),
async (req, res) => {
const signature = req.headers['x-ideogram-signature'] as string;
const timestamp = req.headers['x-ideogram-timestamp'] as string;
if (!verifyIdeogramSignature(req.body, signature, timestamp)) {
return res.status(401).json({ error: 'Invalid signature' });
}
const event = JSON.parse(req.body.toString());
await handleIdeogramEvent(event);
res.status(200).json({ received: true });
}
);
```
## Signature Verification
```typescript
function verifyIdeogramSignature(
payload: Buffer,
signature: string,
timestamp: string
): boolean {
const secret = process.env.IDEOGRAM_WEBHOOK_SECRET!;
// Reject old timestamps (replay attack protection)
const timestampAge = Date.now() - parseInt(timestamp) * 1000;
if (timestampAge > 300000) { // 5 minutes
console.error('Webhook timestamp too old');
return false;
}
// Compute expected signature
const signedPayload = `${timestamp}.${payload.toString()}`;
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(signedPayload)
.digest('hex');
// Timing-safe comparison
return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(expectedSignature)
);
}
```
## Event Handler Pattern
```typescript
type IdeogramEventType = 'resource.created' | 'resource.updated' | 'resource.deleted';
interface IdeogramEvent {
id: string;
type: IdeogramEventType;
data: Record<string, any>;
created: string;
}
const eventHandlers: Record<IdeogramEventType, (data: any) => Promise<void>> = {
'resource.created': async (data) => { /* handle */ },
'resource.updated': async (data) => { /* handle */ },
'resource.deleted': async (data) => { /* handle */ }
};
async function handleIdeogramEvent(event: IdeogramEvent): Promise<void> {
const handler = eventHandlers[event.type];
if (!handler) {
console.log(`Unhandled event type: ${event.type}`);
return;
}
try {
await handler(event.data);
console.log(`Processed ${event.type}: ${event.id}`);
} catch (error) {
console.error(`Failed to process ${event.type}: ${event.id}`, error);
throw error; // Rethrow to trigger retry
}
}
```
## Idempotency Handling
```typescript
import { Redis } from 'ioredis';
const redis = new Redis(process.env.REDIS_URL);
async function isEventProcessed(eventId: string): Promise<boolean> {
const key = `ideogram:event:${eventId}`;
const exists = await redis.exists(key);
return exists === 1;
}
async function markEventProcessed(eventId: string): Promise<void> {
const key = `ideogram:event:${eventId}`;
await redis.set(key, '1', 'EX', 86400 * 7); // 7 days TTL
}
```
## Webhook Testing
```bash
# Use Ideogram CLI to send test events
ideogram webhooks trigger resource.created --url http://localhost:3000/webhooks/ideogram
# Or use webhook.site for debugging
curl -X POST https://webhook.site/your-uuid \
-H "Content-Type: application/json" \
-d '{"type": "resource.created", "data": {}}'
```
## Instructions
### Step 1: Register Webhook Endpoint
Configure your webhook URL in the Ideogram dashboard.
### Step 2: Implement Signature Verification
Use the signature verification code to validate incoming webhooks.
### Step 3: Handle Events
Implement handlers for each event type your application needs.
### Step 4: Add Idempotency
Prevent duplicate processing with event ID tracking.
## Output
- Secure webhook endpoint
- Signature validation enabled
- Event handlers implemented
- Replay attack protection active
## Error Handling
| Issue | Cause | Solution |
|-------|-------|----------|
| Invalid signature | Wrong secret | Verify webhook secret |
| Timestamp rejected | Clock drift | Check server time sync |
| Duplicate events | Missing idempotency | Implement event ID tracking |
| Handler timeout | Slow processing | Use async queue |
## Examples
### Testing Webhooks Locally
```bash
# Use ngrok to expose local server
ngrok http 3000
# Send test webhook
curl -X POST https://your-ngrok-url/webhooks/ideogram \
-H "Content-Type: application/json" \
-d '{"type": "test", "data": {}}'
```
## Resources
- [Ideogram Webhooks Guide](https://docs.ideogram.com/webhooks)
- [Webhook Security Best Practices](https://docs.ideogram.com/webhooks/security)
## Next Steps
For performance optimization, see `ideogram-performance-tuning`.
评论 0
还没有评论,来抢沙发。
相关内容
同类或同场景的收录内容
building-with-kafka-strimzi
在 Kubernetes 上构建基于 Apache Kafka 的事件驱动系统,支持高可靠的消息传递、事务性处理与精确一次语义,结合 Strimzi 运营商实现集群自动化管理,利用 Schema Registry 保障事件模式演进,适用于微服务间解耦通信与实时数据流处理场景。
站外数据与分析
609 0.0
personal-tool-builder
专注于从个人真实痛点出发快速构建实用工具,涵盖命令行程序、本地优先应用和自动化脚本的开发与演进,强调先满足自身需求再逐步扩展,通过持续自用打磨功能,避免过度设计,确保工具简洁有效且长期可维护。
站外商业与营销
196 0.0
threejs-lighting
实现三维场景中的光照与阴影控制,支持多种光源类型及环境光照明,提供从基础布光到高级阴影优化的完整方案,适用于需要真实感渲染或性能平衡的可视化项目。
站外效率工具
442 0.0
aggregation-helper
提供数据聚合场景的自动化辅助能力,涵盖 SQL 查询编写、统计分析建模、可视化方案设计及商业智能配置,支持从需求理解到生产级代码生成的全流程指导。
站外效率工具数据与分析
217 0.0
举报「ideogram-webhooks-events」
举报信息仅审核团队可见,同一资产 24 小时内仅可举报一次