---
name: masheev-webhooks
description: >-
  Use when setting up, verifying, or handling Masheev webhook events in your backend. Covers creating webhook subscriptions, HMAC-SHA256 signature verification with timingSafeEqual, raw body preservation before JSON parsing, idempotent event handling, retry logic, and all 11 event types (conversation.created, message.received, contact.updated, etc.). Use this skill whenever someone asks to "handle Masheev events", "set up webhooks", "verify webhook signatures", or wants real-time notifications from Masheev. Also use when debugging webhook delivery failures or missed events.
license: Apache-2.0
metadata:
  author: masheev
  version: "0.1.0"
title: masheev-webhooks
canonical_url: https://skilld.dev/gh/masheev/skills/masheev-webhooks
last_updated: 2026-11-12T05:30:47.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> Supporting files, fetch one when the Skill refers to it: [references/events.md](https://skilld.dev/api/skills-raw/masheev/skills/masheev-webhooks/references/events.md), [references/frameworks.md](https://skilld.dev/api/skills-raw/masheev/skills/masheev-webhooks/references/frameworks.md).
>
> If the user asked to install this Skill, run `npx skilld install masheev/skills/masheev-webhooks`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/masheev-webhooks`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/masheev/skills/masheev-webhooks) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/masheev-webhooks`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/masheev-webhooks --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/masheev-webhooks --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# Masheev Webhooks

Receive real-time HTTP callbacks when events happen in Masheev. Every webhook is signed with HMAC-SHA256 so you can verify it came from Masheev.

## Quick Start

### 1. Create a Webhook (Dashboard or API)

Via the Masheev dashboard: **Settings > Developers > Webhooks > Create webhook**

Or via API:

```typescript
import { apiClient } from "@masheev/client/server";

await apiClient.webhooks.create.mutate({
  orgId: "org_...",
  name: "My App Events",
  url: "https://myapp.com/api/webhooks/masheev",
  events: ["conversation.created", "message.received", "contact.updated"],
});
```

### 2. Handle and Verify the Webhook

```typescript
// Next.js App Router — app/api/webhooks/masheev/route.ts
import crypto from "node:crypto";

const WEBHOOK_SECRET = process.env.MASHEEV_WEBHOOK_SECRET!;

export async function POST(request: Request) {
  // Step 1: Get raw body BEFORE parsing JSON
  const rawBody = await request.text();
  const signature = request.headers.get("x-webhook-signature");

  if (!signature) {
    return new Response("Missing signature", { status: 401 });
  }

  // Step 2: Verify HMAC-SHA256 signature
  const expected = crypto
    .createHmac("sha256", WEBHOOK_SECRET)
    .update(rawBody)
    .digest("hex");

  const isValid = crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expected),
  );

  if (!isValid) {
    return new Response("Invalid signature", { status: 401 });
  }

  // Step 3: Parse and handle the event
  const event = JSON.parse(rawBody);

  switch (event.type) {
    case "message.received":
      await handleNewMessage(event.payload);
      break;
    case "conversation.created":
      await handleNewConversation(event.payload);
      break;
    case "contact.updated":
      await handleContactUpdate(event.payload);
      break;
  }

  // Step 4: Return 200 quickly (Masheev retries on non-2xx)
  return new Response("OK", { status: 200 });
}
```

## Signature Verification

Every webhook includes an `x-webhook-signature` header containing the HMAC-SHA256 hex digest of the raw request body.

**Correct** (timing-safe comparison):
```typescript
const expected = crypto.createHmac("sha256", secret).update(rawBody).digest("hex");
const isValid = crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected));
```

**Wrong** (vulnerable to timing attacks):
```typescript
// NEVER do this
if (signature === expected) { ... }
```

**Wrong** (body already parsed — signature won't match):
```typescript
// NEVER do this — JSON.stringify reorders keys, changes whitespace
const body = await request.json();
const rawBody = JSON.stringify(body); // This is NOT the original raw body
```

### Framework-Specific Raw Body Access

| Framework | Raw Body Access |
|-----------|----------------|
| Next.js App Router | `await request.text()` |
| Next.js Pages Router | Set `config.api.bodyParser = false`, read `req` as stream |
| Express | `app.use("/webhooks", express.raw({ type: "application/json" }))` |
| Hono | `await c.req.text()` |
| Fastify | `fastify.addContentTypeParser("application/json", { parseAs: "string" }, ...)` |

See [references/frameworks.md](https://skilld.dev/api/skills-raw/masheev/skills/masheev-webhooks/references/frameworks.md) for complete examples in each framework.

## Event Types

| Event | Trigger | Key Payload Fields |
|-------|---------|--------------------|
| `conversation.created` | New conversation started | `conversationId`, `contactId`, `inboxId`, `channel` |
| `conversation.updated` | Status, priority, or assignment changed | `conversationId`, `status`, `priority`, `assigneeId` |
| `conversation.closed` | Conversation resolved | `conversationId`, `resolvedAt`, `outcome` |
| `conversation.assigned` | Assigned to agent or AI | `conversationId`, `assigneeType`, `assigneeId` |
| `message.received` | Message from contact | `messageId`, `conversationId`, `role: "contact"`, `content` |
| `message.sent` | Message sent by agent or AI | `messageId`, `conversationId`, `role`, `content`, `status` |
| `message.failed` | Message delivery failed | `messageId`, `conversationId`, `status: "failed"`, `error` |
| `contact.created` | New contact identified | `contactId`, `name`, `email`, `phone` |
| `contact.updated` | Contact info changed | `contactId`, changed fields |
| `escalation.created` | Conversation escalated to human | `escalationId`, `conversationId`, `reason` |
| `escalation.resolved` | Escalation handled | `escalationId`, `conversationId`, `status: "resolved"` |

See [references/events.md](https://skilld.dev/api/skills-raw/masheev/skills/masheev-webhooks/references/events.md) for complete payload schemas.

## Webhook Payload Format

Every webhook delivery has this shape:

```typescript
{
  id: string;          // Unique event ID (for idempotency)
  type: string;        // e.g., "conversation.created"
  timestamp: number;   // Unix ms
  payload: { ... };    // Event-specific data
}
```

## Idempotent Handling

Masheev may deliver the same event more than once (retries on timeout/error). Use the `id` field to deduplicate:

```typescript
// Simple in-memory dedup (use Redis/DB for production)
const processed = new Set<string>();

async function handleWebhook(event: WebhookEvent) {
  if (processed.has(event.id)) return; // Already handled
  processed.add(event.id);

  // Process the event...
}
```

## Retry Behavior

- Masheev retries on non-2xx responses and timeouts
- Retry schedule: 1 min, 5 min, 30 min, 2 hours, 24 hours
- Webhooks are paused after 7 consecutive days of failures
- Respond with 200 within 30 seconds to avoid timeout retries

## Testing Webhooks

```bash
# Test delivery from the Masheev dashboard
# Settings > Developers > Webhooks > [your webhook] > Send Test

# Or via API
await apiClient.webhooks.test.mutate({
  id: "wh_...",
  orgId: "org_...",
});
```

For local development, use a tunnel:

```bash
# ngrok
ngrok http 3000

# Then update your webhook URL to the ngrok URL
```

## Managing Webhooks

```typescript
// List all webhooks
const webhooks = await apiClient.webhooks.list.query({ orgId: "org_..." });

// Update events
await apiClient.webhooks.update.mutate({
  id: "wh_...",
  orgId: "org_...",
  events: ["message.received", "message.sent"],
});

// Rotate the signing secret
await apiClient.webhooks.regenerateSecret.mutate({
  id: "wh_...",
  orgId: "org_...",
});

// Delete
await apiClient.webhooks.delete.mutate({ id: "wh_...", orgId: "org_..." });
```
