Webhooks

Receive moderation decisions as signed HTTPS requests. Create a webhook connector, verify the raw payload, then acknowledge it before doing slower work. For Slack, email and portal notifications, see Notifications and connectors.

Receive a queued moderation result

Use client.assets.create() (wait=false over HTTP) to queue moderation and let your app continue while it runs. Set externalId to your record's ID, save the returned asset ID, and subscribe to:

  • asset.allowed, asset.limited, asset.age-restricted, asset.blocked and asset.purged for the moderation status. Match asset.externalId to your record, or assetId to the asset ID you saved. externalId also works for an event that arrives before the upload response. Each fires for decisions by automated moderation, by a reviewer and through an API key; the event's actor.type (automated, user or api-key) tells them apart.
  • asset.classified if you also want the classification result, with its flagged categories and moderation status, as soon as it is complete.
  • asset.failed for a processing failure. Keep the content unpublished and handle the failure.

If you need the decision in the original request, use client.assets.classify() (wait=true) instead. Text and images support either flow; audio and video always run asynchronously. See Waiting for the decision.

Status changes after publishing

A status can change after you publish: a reviewer can allow, limit, age-restrict, block or purge an asset. Each change emits the event for the new status with actor.type set to user, or api-key when your integration decided it through the API. Update your stored status from it and re-render. The CDN applies the new status within seconds, so a blocked asset stops loading even from pages that still link it.

Event order

CalmLens writes a decision's events once the decision is stored, so retrieving the asset when one arrives shows what it reports. An automated decision's events arrive in this order:

  1. asset.classified.
  2. The event for the status, with actor.type set to automated.
  3. asset.region-restricted for each new or changed regional outcome.
  4. asset.hash-matched for a hash list match.

A decision by a reviewer or an API key supersedes the automated one. Once a newer decision is stored, the automated decision's classified and status events are no longer written, so an asset's latest status event always carries its current status. Regional outcomes still arrive, with the asset as it is then.

A reviewer's decision made while the asset is still being processed stands: classification finishes and stores its report and scores, but doesn't change the status. Its asset.classified carries the reviewer's status as moderation-status and the policy's decision, which was not applied, as automated-status, and no automated status event follows.

Retries and parallel deliveries can still bring events out of order. Every event about an asset carries an assetSequence that increases with each later event about that asset: store the last assetSequence you applied for each asset, and ignore an event with a lower one. Each SDK's webhook helpers include this comparison; see the webhook section of your SDK's reference.

Assets CalmLens extracts from an upload, such as a document's text and images, have their own events, with a parent-asset fact holding the ID of the upload they came from. The upload itself receives its asset.classified and status events once its parts decide it.

Create a connector

Create a webhook in Portal › Webhooks & connectors with your endpoint URL, a signing secret of at least 10 characters, and the event types your application handles. Leaving the selection empty subscribes the connector to every event type; see Event types and permissions.

Store the same secret in your receiving app, for example as CALMLENS_WEBHOOK_SECRET. The portal shows the secret only when it is created; afterwards it shows a hint of its last characters.

Use the final HTTPS endpoint URL. Private IP addresses, localhost names and URL credentials are rejected. Redirect responses count as failed attempts; CalmLens never forwards a signed payload to a redirected destination. To check a handler before it has a public URL, see Forward events to your machine.

Testing, retries, redelivery, filters and automatic disabling work the same for every connector, except that in-app notifications are never disabled automatically; see Notifications and connectors.

Webhook payload

A webhook connector sends a POST request whose JSON body is the event, in the same shape GET /projects/:projectId/events lists it:

{
  "id": "evt_7Lm3Xq8Rk2Vt9Wb4Np5C",
  "projectId": "proj_8fK2mQx7Lp4NvB3tRz9Y",
  "type": "asset.blocked",
  "severity": "high",
  "title": "beach.jpg blocked",
  "description": "The asset was blocked and is no longer delivered. Its content is kept.",
  "actor": {
    "type": "automated",
    "id": null
  },
  "assetId": "asset_5Gm2Rk8XqT3wLp9VbN4c",
  "assetSequence": 2,
  "asset": {
    "id": "asset_5Gm2Rk8XqT3wLp9VbN4c",
    "externalId": "post-123",
    "uploadPresetId": "preset_4Lk8Qw2Xm9Rt5Vb3Nc7P",
    "content": {
      "status": "stored"
    },
    "upload": {
      "status": "completed"
    },
    "classification": {
      "status": "completed",
      "testInput": false,
      "moderation": {
        "status": "blocked"
      }
    }
  },
  "facts": [
    {
      "key": "asset-name",
      "value": "beach.jpg",
      "url": "https://calmlens.com/go/asset/asset_5Gm2Rk8XqT3wLp9VbN4c"
    },
    {
      "key": "asset-type",
      "value": "image"
    },
    {
      "key": "flagged-categories",
      "value": ["violence"]
    }
  ],
  "createdAt": 1760000000000
}
FieldMeaning
idEvent ID. The same event sent to several connectors has the same id.
projectIdProject the event belongs to.
typeEvent type, such as asset.blocked. New types can be added at any time, so ignore types you don't handle.
severitylow or high.
title, descriptionHuman-readable summary; description may be null.
actorWho caused the event, as { type, id }: a user (a person in the portal, or an assistant acting for one), an api-key, automated moderation or CalmLens itself (system). id is the user's or API key's ID, otherwise null.
assetIdAsset the event is about, or null.
assetSequenceThe event's place among the asset's events: higher for each later event about the same asset, or null for events that aren't about an asset. Ignore an event whose assetSequence is lower than the last one you applied for its asset.
assetSnapshot of the asset's processing, moderation and content status when the event was created, or null.
factsDetails for the event's type, as an array of { key, value, url? } (see Event facts for the registered keys and value types). A fact's url is a stable link that opens its item in the CalmLens portal for anyone signed in with access to it. Facts that hold personal or account data are not included (see Personal and account data).
createdAtWhen the event happened, in milliseconds since the Unix epoch.

The asset snapshot means most receivers don't need to call the API:

FieldMeaning
idAsset ID.
externalIdYour external identifier, or null.
uploadPresetIdThe upload preset used to create the asset, or null for uploads without a preset.
upload.statusuploading or completed.
classification.statusqueued, processing, completed or failed.
classification.testInputtrue when the results came from one of the project's test inputs, as on the asset.
classification.moderation.statuspending, allowed, limited, age-restricted, blocked or purged.
content.statustemporary, stored or removed.

These are the same fields as on the asset; retrieve the asset for the report, notes and file details.

Parse events tolerantly. Ignore fields your handler does not use, read facts by key and treat each one as optional, and expect new event types and fact keys. New fact values may be structured JSON, so validate only the facts you use. Acknowledge event types you don't handle with a 2xx response so they aren't retried.

Personal and account data

Some facts show a person's name or email address, or the organisation's ID. They appear in the portal but are left out of webhook, Slack and email deliveries and the events feed, and the title and description are worded without them. For example, a project.member-joined delivery carries the member's user ID but not their name, and an api-key.created delivery carries the key's name and the creator's user ID but not the creator's name. The Event facts table marks each portal-only fact.

To show a person's name, look up the member or key ID from the event in your own records.

Headers

HeaderValue
content-typeapplication/json
x-calmlens-deliveryDelivery ID, the same on every attempt of a delivery.
x-calmlens-timestampWhen this attempt was signed, in seconds since the Unix epoch. Times in the payload, such as createdAt, are in milliseconds.
x-calmlens-signaturev1= followed by the lowercase hex HMAC-SHA256 of <timestamp>.<raw body>, keyed with the connector's signing secret.

Verify signatures

Verify every request before trusting it. Pass the exact raw request body, not JSON you have parsed and re-serialized, along with the signature and timestamp headers. The SDK helpers check the signature in constant time and reject timestamps more than 5 minutes from your server's clock, which limits the replay window.

import { CalmLensError, parseWebhookEvent } from "calmlens/server";

export async function POST(request: Request): Promise<Response> {
  try {
    const event = await parseWebhookEvent({
      payload: await request.text(), headers: request.headers,
      secret: (process.env.CALMLENS_WEBHOOK_SECRET ?? ""),
    });
    // Queue work keyed by event.id before acknowledging delivery.
    return new Response(null, { status: 204 });
  } catch (error) {
    if (CalmLensError.isCalmLensError(error)) return new Response(null, { status: 401 });
    throw error;
  }
}

Respond to deliveries

Respond with a 2xx status within 10 seconds and move slow work to your own queue.

Network errors, timeouts, 408, 425, 429 and 5xx responses are retried on the connector retry schedule. A Retry-After header on a 429 or 503 response can lengthen the next wait, up to 12 hours. Other responses, including 3xx and other 4xx codes, fail the delivery immediately.

Delivery is at least once, so a receiver can occasionally see the same event twice. Make handlers idempotent by storing the event id: every attempt of a delivery has the same delivery ID and event id, and a redelivery has a new delivery ID but the same event id.

Reliable application updates

Create and commit the draft/upload record with its unique externalId before sending content or issuing an upload token. A webhook can arrive before the upload response. If a record is temporarily unavailable, durably queue the verified event for reconciliation before acknowledging it; do not drop it with a successful response.

In one database transaction, deduplicate by event id, update the matching asset/version, and record the event's assetSequence. Ignore an event with a lower assetSequence than the last one you applied for that asset (see Event order). If an event conflicts with your stored state, retrieve the current asset rather than guessing. Handle failure events with the same ordering checks. An upload response must not overwrite a newer event already stored.

The helpers in the Moderate comments examples, such as updateModerationStatus, markModerationFailed and saveComment, represent your database operations, not SDK methods. They must implement these checks. Version selection is separate from event ordering: a result for an old comment edit or avatar upload must not promote it over the user’s current candidate.

For regional controls, also subscribe to asset.region-restricted and follow Self-hosted content. The asset snapshot’s base status is not the viewer-specific delivery action.

Test your webhook handler

Every webhook connector keeps a log of its deliveries in Portal › Webhooks & connectors, with the exact request each one sent and every attempt's response, so you can see what your handler received and how it answered.

Send a test event

A connector test sends a webhook a signed sample event of the type you choose. The event's facts are example values for that type, with the registered { "key": "test", "value": true } fact added; check for it if your handler should acknowledge test events without acting on them. The test is attempted once and recorded in the connector's deliveries as a test.

Delivery details

Each webhook delivery's details show:

  • the raw body that was sent, exactly as signed, which you can copy into a test for your handler;
  • every request header of each attempt, including x-calmlens-delivery, x-calmlens-timestamp and x-calmlens-signature. Each attempt is signed again, so its timestamp and signature differ from the others;
  • each attempt's time, HTTP status, response time, the first 1,000 characters of the response body and any error, for up to 7 attempts.

Bodies up to 64 KiB are kept in full; a longer body is kept truncated, and its signature can't be checked in the portal. Credential headers (authorization, cookie, proxy-authorization, x-api-key) are shown as [redacted]. Deliveries are kept for 30 days; see Retention.

You can redeliver an event as a new delivery, for example after fixing your handler.

Check a signature

When your handler rejects a delivery's signature, check the signature against your signing secret in the delivery's details in Portal › Webhooks & connectors. The portal verifies the stored body, timestamp and signature of each attempt the way the SDK helpers do, and shows whether it verifies with that secret. The check runs in your browser: the secret is never sent to CalmLens. If it verifies there but not in your handler, your handler is most likely verifying a parsed or re-encoded body instead of the raw bytes, or using a different secret.

Forward events to your machine

Before your handler has a public URL, run it against your project's real events with calmlens listen, which forwards each event to a local URL with the same body, headers and signature as a delivery; see Local development. Where your machine can't receive requests, read the events feed instead.

Last updated

Signing in

Signing out

Cookies on CalmLens

We use essential cookies for sign-in and security. With your permission, functional cookies remember your preferences and Google Analytics measures website use and signups. Optional ad measurement cookies link Google ad clicks to signups. Personalised advertising stays off. Manage cookies