Docs menu

You're reading the docs for dotwire 0.3. The latest release is 0.5. Upgrading? See Upgrading to 0.4.

Moderation webhooks

dotwire doesn't moderate content. It gives your host two hooks, and your host decides what to do with each message.

Two hooks, two speeds

HookWhen it runsEffect on the sendUse it for
PresendBefore the message is acceptedBlocking. It can reject the message or rewrite its content.Cheap, local, deterministic checks: blocklists, regular expressions, length caps, per-user rate limits
PostsendAfter the message is accepted, with its seqNone. The message is already sent.Handing off to asynchronous review, including anything that calls a network service

Postsend runs only for accepted messages, because only those have a (roomId, seq) pair that a later redaction can target.

Where the hooks run

You write the hooks once, as presend and postSend on @dotwire/host or Presend and PostSend on Dotwire.Host. The SDK runs them on every path a message can take through your host:

  • sends from your backend with sendAsUser / SendAsUserAsync,
  • sends that browsers make through your own route, handled by handleClientSend / HandleClientSendAsync,
  • dotwire's own webhook call-outs, handled by the presend and postsend webhook handlers.

The hooks never run for system messages you send with sendSystemMessage / SendSystemMessageAsync.

Browsers that send directly to dotwire bypass your host. To cover those sends, either set the client's sendUrl to your own route, or turn on dotwire's webhook call-outs.

Write the hooks

Node.js (@dotwire/host)

host.presend = async (ctx) =>
  Blocklist.hits(ctx.content) ? PresendResult.reject('blocked term') : PresendResult.accept();

const queue = new ModerationQueue();
host.postSend = queue.postSendHook;

PresendResult is exported from @dotwire/host. To rewrite content, return PresendResult.accept('<rewritten text>'). The helpers build plain objects, so returning { allow: false, rejectionReason: '...' } or { allow: true, content: '...' } directly works too.

.NET (Dotwire.Host)

client.Presend = (ctx, ct) => Task.FromResult(
    Blocklist.Hits(ctx.Content) ? PresendResult.Reject("blocked term") : PresendResult.Accept());

var queue = new ModerationQueue();          // bounded; back-pressures sends when full
client.PostSend = queue.PostSendHook;

Blocklist stands for your own check.

When presend rejects a message:

  • sendAsUser throws PresendRejectedError (Node), and SendAsUserAsync throws PresendRejectedException (.NET).
  • The client-send handlers and the webhook path return 422 with { "error": "presend_rejected", "reason": "..." }.

If postsend throws during SendAsUserAsync or sendAsUser, you get PostSendException or PostSendError, which carries the ack. The send already happened, so don't retry it.

ModerationQueue holds 10,000 messages by default. When it's full, postSendHook / PostSendHook waits for room, which slows sends. If the queue stays full for 30 seconds, the hook throws: the message was sent, but it isn't queued for review. Change the wait with enqueueTimeoutMs / enqueueTimeout.

Route browser sends through your host

Set sendUrl on @dotwire/client to a host route. The client then posts { roomId, content } to that route with credentials: 'include' and no bearer header. If the send has an idempotency key, the body also carries idempotencyKey, and the handlers forward it to dotwire. Hand the request to the SDK with the authenticated user's id:

Node.js (@dotwire/host)

const res = await host.handleClientSend(request, 'dave');

handleClientSend takes a Fetch API Request and returns a Response that mirrors dotwire's answer: 202 with { seq, time } on success. For frameworks without Fetch API requests, handleClientSendBody(body, userId) takes the parsed body and returns { status, body }.

.NET (Dotwire.Host)

app.MapPost("/my-app/rooms/{roomId}/send", async (HttpRequest req, string userId) =>
{
    var result = await client.HandleClientSendAsync(req.Body, userId);
    return Results.Text(result.Json, "application/json", statusCode: result.StatusCode);
});

Use dotwire's webhook call-outs

Instead of routing sends through your host, you can have dotwire call your host. Each call-out is on only when its URL is set.

Dotwire__Webhooks__Presend__Url=https://my-host.example.com/webhooks/dotwire/presend
Dotwire__Webhooks__PostSend__Url=https://my-host.example.com/webhooks/dotwire/postsend
Dotwire__Webhooks__Secret=<webhook-hmac-secret>

Set the same secret as webhookSecret (Node) or WebhookSecret (.NET) in your host SDK. The webhook handlers throw without it. To accept unsigned calls anyway, for example in local development, set allowUnsignedWebhooks: true / AllowUnsignedWebhooks = true.

Webhook URLs must be https, or a loopback host such as localhost. dotwire refuses to start with a plain http URL anywhere else unless you set Dotwire__Webhooks__AllowInsecureUrls=true.

Handle the call-outs

Node.js (@dotwire/host)

const presendResponse = await host.handlePresendWebhook(request);
const postSendResponse = await host.handlePostSendWebhook(request);

Each takes a Fetch API Request and returns a Response. A bad or stale signature gets 401, and a body over maxWebhookBodyBytes (1 MiB by default) gets 413. With no presend hook configured, the presend handler allows the message.

For frameworks without Fetch API requests, handlePresendWebhookBody(body, signature, rawBody, { timestamp, signatureV2 }) and handlePostSendWebhookBody(...) take the raw body and the X-Dotwire-Signature, X-Dotwire-Timestamp and X-Dotwire-Signature-V2 header values.

.NET (Dotwire.Host)

static WebhookHeaders Headers(HttpRequest req) => new(
    req.Headers["X-Dotwire-Signature"], req.Headers["X-Dotwire-Timestamp"], req.Headers["X-Dotwire-Signature-V2"]);

app.MapPost("/webhooks/presend", async (HttpRequest req) =>
{
    var result = await client.HandlePresendWebhookAsync(req.Body, Headers(req));
    return Results.Text(result.Json, "application/json", statusCode: result.StatusCode);
});

app.MapPost("/webhooks/postsend", async (HttpRequest req) =>
{
    var result = await client.HandlePostSendWebhookAsync(req.Body, Headers(req));
    return Results.Text(result.Json, "application/json", statusCode: result.StatusCode);
});

Pass all three headers. The older overload that takes only X-Dotwire-Signature still compiles, but it can only verify the legacy signature, which is off by default, so every call gets 401. A bad or stale signature gets 401, and a body over MaxWebhookBodyBytes (1 MiB by default) gets 413.

The postsend handlers swallow an exception from your postSend hook, because the message they describe was already sent.

Presend call-out

dotwire sends a POST with the header X-Dotwire-Event: presend and this body:

{
  "roomId": "a0000000-0000-0000-0000-000000000001",
  "senderId": "alice",
  "content": "<message text>",
  "time": "2026-11-06T12:00:00+00:00",
  "source": "member"
}

source is member for member sends, or admin for injected messages when IncludeAdminSends is on.

Your endpoint answers 200 with one of:

  • { "allow": true } to accept the message as is,
  • { "allow": true, "content": "<rewritten text>" } to accept it with new content,
  • { "allow": false, "reason": "<text>" } to reject it. The sender gets 422 presend_rejected with your reason.

Any other status, a body dotwire can't parse, or no answer within TimeoutMs (500 ms by default) counts as unavailable. Then FailPolicy decides:

  • Closed, the default, fails the send with 503 presend_unavailable.
  • Open accepts the original content.

Rewritten content is checked against the same size limit as the original.

Postsend call-out

After a message is accepted, dotwire queues a POST with the header X-Dotwire-Event: postsend. The body is the presend body plus the message's seq. The queue holds QueueCapacity items (1,000 by default) and MaxQueueBytes bytes (64 MiB by default); when either is exceeded, dotwire drops the newest item and logs a warning. dotwire makes up to MaxAttempts delivery attempts per item (3 by default), each with a TimeoutMs of 2,000 ms by default. Postsend never blocks or fails a send.

Signatures

When Dotwire:Webhooks:Secret is set, both call-outs carry three headers:

  • X-Dotwire-Timestamp: Unix time in seconds when dotwire sent the call.
  • X-Dotwire-Signature-V2: sha256=<hex>: HMAC-SHA256 of "<timestamp>.<raw body>".
  • X-Dotwire-Signature: sha256=<hex>: HMAC-SHA256 of the raw body alone. This is the legacy signature, kept for older handlers.

The host SDK handlers verify the V2 signature and reject a timestamp more than five minutes from now (webhookToleranceSeconds / WebhookTimestampTolerance), so a captured call can't be replayed later. They accept the legacy signature only when you set allowLegacyWebhookSignatures: true / AllowLegacyWebhookSignatures = true.

If you write your own handler, verify the V2 signature against the raw body before you parse it, compare in constant time, and check the timestamp.

Admin sends

Injected system messages skip both call-outs unless you set IncludeAdminSends to true on that hook. They're host-authored and audited already.

Batched asynchronous review

Both host SDKs pair ModerationQueue with BatchModerationWorker. The worker drains the queue in batches bounded by size or time, asks a classifier for verdicts, and runs an action for each flagged message. The built-in action, redactWith, redacts through the admin API and retries on 429, honoring Retry-After.

dotwire ships no classifier, so you implement ModerationClassifier (Node) or IModerationClassifier (.NET). It receives a batch of messages and returns one verdict per message. Only flagged verdicts trigger the action, and a message with no verdict counts as not flagged. A classifier can call an LLM, a moderation API, or anything else too slow to run inside a send. If it fails for every attempt, 3 by default (maxClassifierAttempts / MaxClassifierAttempts), the worker drops that batch and carries on.

Node.js (@dotwire/host)

const classifier: ModerationClassifier = {
  classify: (batch, signal) =>
    Promise.all(
      batch.map(async (m) => ({
        roomId: m.roomId,
        seq: m.seq,
        flagged: await Reviewer.flags(m.content, signal)
      }))
    )
};

const worker = new BatchModerationWorker(queue, classifier, BatchModerationWorker.redactWith(host));
await worker.run(abortController.signal);

.NET (Dotwire.Host)

sealed class ReviewClassifier : IModerationClassifier
{
    public async Task<IReadOnlyList<ModerationVerdict>> ClassifyAsync(IReadOnlyList<PendingModeration> batch, CancellationToken ct)
    {
        var verdicts = new List<ModerationVerdict>(batch.Count);
        foreach (var m in batch)
            verdicts.Add(new ModerationVerdict(m.RoomId, m.Seq, await Reviewer.FlagsAsync(m.Content, ct)));
        return verdicts;
    }
}

var worker = new BatchModerationWorker(
    queue,
    new ReviewClassifier(),
    onFlagged: BatchModerationWorker.RedactWith(client),
    new BatchModerationOptions { MaxBatchSize = 100, MaxBatchDelay = TimeSpan.FromSeconds(30) },
    onError: ex => logger.LogError(ex, "moderation"));

// e.g. inside a BackgroundService:
await worker.RunAsync(stoppingToken);

Reviewer stands for your own check. A flagged message stays visible until its batch has been reviewed, so use batched review as a second line of defense behind presend, never as the first. If your classifier sends message content to an outside service, see Accepted limitations.

Related