# Verify Oyster webhooks

Oyster doesn't compute a signature. It sends the `sharedSecret` you chose back in the `Authorization` header of every delivery, as `Bearer <sharedSecret>`, and you compare the whole value in constant time. A match shows the sender knows your secret, but nothing covers the body, and a captured request can be replayed.

Agent skill: `npx skills add hookdeck/webhook-skills --skill oyster-webhooks` ([details](https://hookdeck.com/webhooks/oyster/skill))

> Independent reference generated from hookdeck/webhook-registry (commit ff7f882, 20 Nov 2026). [Oyster's official docs](https://docs.oysterhr.com/docs/getting-started-with-webhooks).

[Overview](https://hookdeck.com/webhooks/oyster) · [Webhook events (97)](https://hookdeck.com/webhooks/oyster/events) · [MCP events](https://hookdeck.com/webhooks/oyster/mcp-events) · [Verify signatures](https://hookdeck.com/webhooks/oyster/verify) · [Production guide](https://hookdeck.com/webhooks/oyster/guide-duplicates-ordering-retries-timeouts) · [Agent skill](https://hookdeck.com/webhooks/oyster/skill)

## The facts

| Fact | Value | Source |
|---|---|---|
| Signature header | `None (unsigned)` | [Oyster docs](https://docs.oysterhr.com/docs/getting-started-with-webhooks) |
| What to build | `Compare the whole Authorization header with "Bearer " plus your shared secret, in constant time` | [Oyster docs](https://docs.oysterhr.com/docs/getting-started-with-webhooks) |
| Key | `shared secret` | [Oyster docs](https://docs.oysterhr.com/docs/getting-started-with-webhooks) |

## Oyster webhook secret

Chosen by the integrator and sent to Oyster as `sharedSecret` when the endpoint is created (or updated). Keep it in an environment variable, not in source code.

- You choose the value and send it as `sharedSecret` in `POST /v1/webhooks`. Oyster doesn't generate one.
- It belongs to that webhook endpoint, and each endpoint is set up with its own `sharedSecret`.
- Oyster sends it on every delivery as `Authorization: Bearer <sharedSecret>`, so a secret of `12345` arrives as `Bearer 12345`.
- The API returns it in the endpoint object, including from `GET /v1/webhooks`, so an access token that can read your endpoints can read the secret.
- Rotate it with `PATCH /v1/webhooks/{id}` and a new `sharedSecret`. You get the endpoint ID when you create the endpoint.
- Sandbox endpoints are created through `api-sandbox.oysterhr.com`, separately from production.

Source: [Oyster docs](https://docs.oysterhr.com/docs/getting-started-with-webhooks)

## Code

### Express

From [webhook-skills: skills/oyster-webhooks/examples/express/src/index.js](https://github.com/hookdeck/webhook-skills/blob/556a89753e3e66e85d2a3ce50558e95b96c08571/skills/oyster-webhooks/examples/express/src/index.js)

```javascript
// Generated with: oyster-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config({ quiet: true });
const crypto = require('crypto');
const express = require('express');

const app = express();

/**
 * Constant-time string comparison. Hashing both sides first gives equal-length
 * buffers, so timingSafeEqual never throws and the secret's length isn't leaked.
 */
function safeEqual(a, b) {
  const ha = crypto.createHash('sha256').update(String(a)).digest();
  const hb = crypto.createHash('sha256').update(String(b)).digest();
  return crypto.timingSafeEqual(ha, hb);
}

/**
 * Oyster does not sign payloads. The only authentication is the sharedSecret you
 * registered, sent as `Authorization: Bearer <sharedSecret>`. Compare the WHOLE header
 * value, "Bearer " prefix included; don't strip or parse it. A static credential
 * authenticates the sender, not the body, and gives no replay protection, so use
 * HTTPS, dedupe on the event id and rotate the secret if it leaks.
 */
function verifyOysterRequest(headers, config = process.env) {
  const expected = config.OYSTER_AUTHORIZATION;
  if (!expected) return false; // never accept when unconfigured
  const received = headers['authorization'];
  if (!received) return false;
  return safeEqual(received, expected);
}

function handleEvent(event) {
  const { eventName, data = {} } = event;

  switch (eventName) {
    case 'hiring.employment_engaged':
      console.log(`Employment engaged: engagement ${data.engagementId}`);
      // Your code: mark the hire as engaged in your system
      break;

    case 'expenses.expense_approved':
      console.log(`Expense ${data.expenseId} approved (${data.previousReviewState} -> ${data.reviewState})`);
      // Your code: reimburse or book the expense
      break;

    case 'contract.change_applied':
      console.log(`Contract change ${data.engagementChangeId} applied (${data.changeType}, ${data.state})`);
      // Your code: sync the updated contract terms
      break;

    case 'benefits.enrollment_enrolled':
      console.log(`Benefits enrollment ${data.enrollmentId} enrolled for engagement ${data.engagementId}`);
      // Your code: record the enrollment
      break;

    default:
      console.log(`Unhandled Oyster event: ${eventName}`);
  }
}

// Read the body raw so the request is authenticated before anything is parsed,
// whatever Content-Type Oyster uses.
app.post('/webhooks/oyster', express.raw({ type: '*/*' }), (req, res) => {
  if (!verifyOysterRequest(req.headers)) {
    return res.status(401).json({ error: 'Invalid or missing Authorization header' });
  }

  let event;
  try {
    const raw = Buffer.isBuffer(req.body) ? req.body.toString('utf8') : '';
    event = JSON.parse(raw);
  } catch {
    return res.status(400).json({ error: 'Invalid JSON body' });
  }

  if (!event || typeof event !== 'object' || Array.isArray(event) || typeof event.eventName !== 'string') {
    return res.status(400).json({ error: 'Expected a JSON object with an eventName' });
  }

  // Oyster may deliver the same webhook more than once: dedupe on event.id (wh_...)
  // in your own store before doing real work.
  try {
    handleEvent(event);
  } catch (err) {
    console.error('Error handling Oyster webhook:', err);
    return res.status(500).json({ error: 'Handler error' });
  }

  // Oyster needs a 200 within 5 seconds.
  res.status(200).json({ received: true });
});

app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

module.exports = app;
module.exports.verifyOysterRequest = verifyOysterRequest;

if (require.main === module) {
  const PORT = process.env.PORT || 3000;
  app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
    console.log(`Webhook endpoint: POST http://localhost:${PORT}/webhooks/oyster`);
  });
}
```

### Next.js

From [webhook-skills: skills/oyster-webhooks/examples/nextjs/app/webhooks/oyster/route.ts](https://github.com/hookdeck/webhook-skills/blob/556a89753e3e66e85d2a3ce50558e95b96c08571/skills/oyster-webhooks/examples/nextjs/app/webhooks/oyster/route.ts)

```typescript
// Generated with: oyster-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import { verifyOysterRequest } from '../../../lib/verify-oyster';

interface OysterEvent {
  eventName: string;
  eventTimestamp?: string;
  id?: string;
  companyId?: string;
  data?: Record<string, unknown>;
}

function handleEvent(event: OysterEvent): void {
  const data = event.data ?? {};

  switch (event.eventName) {
    case 'hiring.employment_engaged':
      console.log(`Employment engaged: engagement ${data.engagementId}`);
      // Your code: mark the hire as engaged in your system
      break;

    case 'expenses.expense_approved':
      console.log(`Expense ${data.expenseId} approved (${data.previousReviewState} -> ${data.reviewState})`);
      // Your code: reimburse or book the expense
      break;

    case 'contract.change_applied':
      console.log(`Contract change ${data.engagementChangeId} applied (${data.changeType}, ${data.state})`);
      // Your code: sync the updated contract terms
      break;

    case 'benefits.enrollment_enrolled':
      console.log(`Benefits enrollment ${data.enrollmentId} enrolled for engagement ${data.engagementId}`);
      // Your code: record the enrollment
      break;

    default:
      console.log(`Unhandled Oyster event: ${event.eventName}`);
  }
}

export async function POST(request: NextRequest) {
  // Authenticate before reading or parsing the body.
  if (!verifyOysterRequest(request.headers)) {
    return NextResponse.json({ error: 'Invalid or missing Authorization header' }, { status: 401 });
  }

  let payload: unknown;
  try {
    // Read the raw text so any content type works.
    payload = JSON.parse(await request.text());
  } catch {
    return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
  }

  const event = payload as Partial<OysterEvent> | null;
  if (!event || typeof event !== 'object' || Array.isArray(event) || typeof event.eventName !== 'string') {
    return NextResponse.json({ error: 'Expected a JSON object with an eventName' }, { status: 400 });
  }

  // Oyster may deliver the same webhook more than once: dedupe on event.id (wh_...)
  // in your own store before doing real work.
  try {
    handleEvent(event as OysterEvent);
  } catch (err) {
    console.error('Error handling Oyster webhook:', err);
    return NextResponse.json({ error: 'Handler error' }, { status: 500 });
  }

  // Oyster needs a 200 within 5 seconds.
  return NextResponse.json({ received: true });
}
```

### FastAPI

From [webhook-skills: skills/oyster-webhooks/examples/fastapi/main.py](https://github.com/hookdeck/webhook-skills/blob/556a89753e3e66e85d2a3ce50558e95b96c08571/skills/oyster-webhooks/examples/fastapi/main.py)

```python
# Generated with: oyster-webhooks skill
# https://github.com/hookdeck/webhook-skills
import hmac
import json
import os

from dotenv import load_dotenv
from fastapi import Depends, FastAPI, HTTPException, Request

load_dotenv()

app = FastAPI()


def safe_equal(a: str, b: str) -> bool:
    """Constant-time comparison on bytes (compare_digest raises on non-ASCII str)."""
    return hmac.compare_digest(a.encode("utf-8"), b.encode("utf-8"))


def verify_oyster_request(headers, config=os.environ) -> bool:
    """Oyster does not sign payloads. The only authentication is the sharedSecret you
    registered, sent as `Authorization: Bearer <sharedSecret>`. Compare the WHOLE header
    value, "Bearer " prefix included; don't strip or parse it. A static credential
    authenticates the sender, not the body, and gives no replay protection, so use
    HTTPS, dedupe on the event id and rotate the secret if it leaks.
    """
    expected = config.get("OYSTER_AUTHORIZATION")
    if not expected:
        return False  # never accept when unconfigured
    received = headers.get("authorization")
    if not received:
        return False
    return safe_equal(received, expected)


async def require_oyster_auth(request: Request) -> None:
    """FastAPI dependency: reject the request before the body is parsed."""
    if not verify_oyster_request(request.headers):
        raise HTTPException(status_code=401, detail="Invalid or missing Authorization header")


def handle_event(event: dict) -> None:
    event_name = event["eventName"]
    data = event.get("data") or {}

    if event_name == "hiring.employment_engaged":
        print(f"Employment engaged: engagement {data.get('engagementId')}")
        # Your code: mark the hire as engaged in your system

    elif event_name == "expenses.expense_approved":
        print(
            f"Expense {data.get('expenseId')} approved "
            f"({data.get('previousReviewState')} -> {data.get('reviewState')})"
        )
        # Your code: reimburse or book the expense

    elif event_name == "contract.change_applied":
        print(
            f"Contract change {data.get('engagementChangeId')} applied "
            f"({data.get('changeType')}, {data.get('state')})"
        )
        # Your code: sync the updated contract terms

    elif event_name == "benefits.enrollment_enrolled":
        print(
            f"Benefits enrollment {data.get('enrollmentId')} enrolled "
            f"for engagement {data.get('engagementId')}"
        )
        # Your code: record the enrollment

    else:
        print(f"Unhandled Oyster event: {event_name}")


@app.post("/webhooks/oyster", dependencies=[Depends(require_oyster_auth)])
async def oyster_webhook(request: Request):
    # Read the raw body so any content type works.
    raw_body = await request.body()

    try:
        event = json.loads(raw_body)
    except (json.JSONDecodeError, UnicodeDecodeError):
        raise HTTPException(status_code=400, detail="Invalid JSON body")

    if not isinstance(event, dict) or not isinstance(event.get("eventName"), str):
        raise HTTPException(status_code=400, detail="Expected a JSON object with an eventName")

    # Oyster may deliver the same webhook more than once: dedupe on event["id"] (wh_...)
    # in your own store before doing real work.
    try:
        handle_event(event)
    except Exception as err:  # noqa: BLE001
        print(f"Error handling Oyster webhook: {err}")
        raise HTTPException(status_code=500, detail="Handler error")

    # Oyster needs a 200 within 5 seconds.
    return {"received": True}


@app.get("/health")
async def health():
    return {"status": "ok"}


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)
```

Or install the Oyster webhooks skill: `npx skills add hookdeck/webhook-skills --skill oyster-webhooks`

## Common failures

- **Comparing with the bare secret.** For a secret of `12345` the header is `Bearer 12345`, so comparing it with `12345` rejects every delivery. The code on this page keeps the full value in `OYSTER_AUTHORIZATION`.
- **Changing the secret on one side.** `PATCH /v1/webhooks/{id}` changes what Oyster sends. Oyster doesn't say which value a pending retry carries, so accept both values briefly when you rotate.
- **Mixing up sandbox and production.** Endpoints created through `api-sandbox.oysterhr.com` are separate from production ones, so a sandbox delivery carries the secret you registered there.

From [Hookdeck's Oyster guide](https://hookdeck.com/webhooks/oyster/guide-duplicates-ordering-retries-timeouts).

---

Not affiliated with Oyster. Facts are compiled from public sources and linked inline. [View as JSON](https://hookdeck.com/webhooks/oyster.json) · [Report a correction](https://hookdeck.com/contact)
