DEV Community

ottoneumann8425
ottoneumann8425

Posted on

How to Build Secure Realtime Publish Receipts for Customer Support Conversations

Short answer: treat a publish acknowledgement as a signed, replay-safe receipt, and keep token authority, subscription state, and business delivery as separate records. That decision gives a support agent a useful answer to “did my message arrive?” without turning an untrusted browser acknowledgement into proof that a customer saw it.

In a customer support chat, presence accuracy is a business property, not a green dot. A browser can reconnect while an agent is away, a mobile network can duplicate a publish, and a tab can close after the server has accepted bytes but before the receipt reaches the user. The backend therefore needs a stable event identifier, an explicit acknowledgement state, and an audit trail that survives reconnects.

What should secure realtime publish acknowledgements prove?

The receipt should prove only the narrow fact the server can establish: an authenticated principal was authorized to publish event evt_8f2, and the service durably accepted that event for the conversation. It should not claim delivery to every subscriber, rendering in a browser, or human reading. Those are later observations with different evidence.

I use three monotonic states: accepted, delivered, and read. Each transition carries the event ID, actor ID, conversation ID, server time, and a hash of the canonical payload. An idempotency key binds retries to one event. If the same key arrives with a different payload hash, reject it and log the security decision; silently replacing a financial or support record is unacceptable.

The authorization check also has two dimensions. The access token must be valid and unexpired, and its scope must include the specific conversation action. Subscription membership is not authorization to publish. This distinction matters after a role change, when an agent may remain connected to a channel but lose permission to send.

How do authentication, token scope, and acknowledgements fit together?

Issue short-lived, conversation-scoped credentials from a server-side authority. The browser never receives the long-lived application secret. The generic realtime API surface exposes token issuance and revocation at /v1/realtime/token/issue and /v1/realtime/token/revoke; keep those calls behind your own authorization service so a support role, tenant, and conversation are checked before a token is minted.

Here is the critical path in Go. The transport can be WebSocket, WebRTC data channels, or another realtime protocol; the receipt contract stays the same.

package receipts

import (
    "crypto/sha256"
    "encoding/hex"
    "errors"
    "time"
)

type Publish struct {
    EventID       string
    IdempotencyKey string
    Conversation  string
    Actor         string
    Payload       []byte
}

type Receipt struct {
    EventID string
    State   string
    Hash    string
    At      time.Time
}

func Accept(p Publish, authorized func(string, string) bool, seen func(string) (string, bool), store func(Publish, string) error) (Receipt, error) {
    if p.EventID == "" || p.IdempotencyKey == "" || p.Conversation == "" {
        return Receipt{}, errors.New("missing publish identity")
    }
    if !authorized(p.Actor, p.Conversation) {
        return Receipt{}, errors.New("publish scope denied")
    }
    h := sha256.Sum256(p.Payload)
    hash := hex.EncodeToString(h[:])
    if old, ok := seen(p.IdempotencyKey); ok {
        if old != hash {
            return Receipt{}, errors.New("idempotency key payload conflict")
        }
        return Receipt{EventID: p.EventID, State: "accepted", Hash: hash, At: time.Now().UTC()}, nil
    }
    if err := store(p, hash); err != nil {
        return Receipt{}, err
    }
    return Receipt{EventID: p.EventID, State: "accepted", Hash: hash, At: time.Now().UTC()}, nil
}
Enter fullscreen mode Exit fullscreen mode

The durable write and the acknowledgement must have a clear boundary. Write the event and its audit record in one transaction, then emit the receipt. If the process dies before emission, the client retries with the same idempotency key and receives the original receipt. If emission happens twice, the client deduplicates by event ID. “Exactly once” is a useful storage invariant; on a network, it is a reconciliation protocol.

Short receipt. Long audit.

Which design trade-offs matter for a support chat?

Choice Strength Cost or boundary
Signed server receipt Client can verify origin and event hash Key rotation and clock handling become operational work
Plain transport acknowledgement Small implementation and low latency It cannot establish durable acceptance or caller scope
Per-conversation token Limits blast radius after disclosure More token issuance and refresh events to observe
Broad tenant token Fewer auth calls A compromised tab can probe unrelated conversations
Append-only audit log Strong reconciliation and compliance evidence Retention, erasure, and access controls need deliberate policy

The catch is that a signed receipt does not solve presence. It is unsuitable when the product promise is “the agent is watching right now”; use a separately measured presence signal with heartbeat expiry and make its uncertainty visible to operators. Stick with a plain acknowledgement when messages are disposable telemetry and no durable customer record exists. For regulated support, keep the append-only audit trail, but define a retention and deletion policy that matches the applicable privacy rules.

How should reconnect, expiry, and duplicate delivery be tested?

Build a deterministic test matrix around the event ID. Delay the receipt, drop the subscriber connection, expire the token between authorization and retry, and deliver the same event twice. The expected result is stable: one stored event, one audit identity, and a receipt that reports the same hash. A revoked token must not authorize a new publish, while a previously accepted event remains queryable for reconciliation.

I also record separate metrics for authentication failures, subscription changes, publish decisions, receipt emission, and client read markers. Combining them into one “message success” counter hides the exact failure boundary that an incident responder needs. I am not sure every team needs cryptographic signatures; the deciding evidence is your threat model, key-management maturity, and whether clients must verify receipts outside the transport session.

Presence accuracy improves when the client treats the receipt as data, not UI decoration. On reconnect, it sends the last acknowledged event ID; the server returns the missing range or a “resync required” marker, and the client reconciles by ID before showing an agent as available. In practice, that means retaining enough event metadata to answer several awkward questions at once: did authorization pass before the token expired, was the publish persisted before the socket disappeared, did a retry reuse the original idempotency key, and did the read marker arrive from the same principal that received the message? The audit record should let an operator follow those transitions without joining logs from four unrelated services, while redacting message content when retention policy requires it. This is slower than trusting a volatile browser flag, but it makes the behavior explainable during audits and customer disputes.

Don't confuse a green presence badge with evidence.

References

Top comments (0)