> ## Documentation Index
> Fetch the complete documentation index at: https://docs.leapfinancial.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Middleware pipeline

> The ordered processing pipeline that authenticates, enriches, and transforms every inbound message before it reaches an agent.

Every inbound message passes through an ordered middleware chain before reaching any agent. Each middleware stage can inspect, enrich, or reject the message. The pipeline runs synchronously — each stage completes before the next begins. The bank controls which middleware runs, in what order, and with what configuration.

## Pipeline stages

<Steps>
  <Step title="CommandsAuthMiddleware">
    Intercepts slash commands (e.g., `/info`, `/new`, `/payers`). When the `ACTIVE_COMMANDS` environment variable is set to `false`, this middleware blocks all command messages and sends a notification to the sender.

    When commands are enabled, the message passes through to the registered command handlers on the LogicRouter. This allows operators and testers to invoke diagnostic commands during controlled rollouts.

    | Configuration          | Value                                                           |
    | ---------------------- | --------------------------------------------------------------- |
    | Environment variable   | `ACTIVE_COMMANDS`                                               |
    | Default                | `true` (commands enabled)                                       |
    | Behavior when disabled | Blocks all `/` prefixed messages, sends "Commands are disabled" |
  </Step>

  <Step title="PhoneFakerMiddleware">
    Development-only middleware that allows testers to simulate different sender identities by overriding the phone number associated with a session. Uses a Redis hash to map session IDs to substitute phone numbers.

    Testers can use `/phone +1234567890` to set a specific identity, or `/new` to generate a random phone number — enabling testing of onboarding flows, blocked states, and CIP-pending scenarios without real sender accounts.

    <Warning>
      PhoneFakerMiddleware must be disabled in production. It is a development tool for testing different sender identities. In production, the sender's actual phone number from the channel connector is used.
    </Warning>
  </Step>

  <Step title="PayhubAuthMiddleware">
    Authenticates the sender by phone number against the identity service. This middleware:

    1. Validates that a phone number is present on the inbound message
    2. Normalizes the phone number to a standard format
    3. Queries the identity service for the sender's profile
    4. Injects the sender's identity (name, compliance status, payment methods, country) into the message metadata

    The LogicRouter uses this injected metadata to route the message to the appropriate agent.

    On service failure (HTTP 404), the middleware sets the `unavailable_service` flag in metadata but does not block the message. The LogicRouter detects this flag and routes to the service unavailable agent for graceful degradation.

    <Note>
      This middleware never blocks message delivery. Authentication failures result in routing to the appropriate fallback agent — not in dropped messages.
    </Note>
  </Step>

  <Step title="ContactDecodingMiddleware">
    Normalizes contact information from the message payload. Standardizes phone numbers and contact data formats before they reach the agent layer.
  </Step>

  <Step title="ChatwootMiddleware">
    Syncs conversations to Chatwoot for human agent visibility and handoff. When enabled, every message and response is mirrored to a Chatwoot inbox, allowing human agents to:

    * Monitor active conversations in real time
    * Take over a conversation when escalation is triggered
    * Review conversation history for quality assurance

    | Configuration  | Environment variable         |
    | -------------- | ---------------------------- |
    | Enable/disable | `CHATWOOT_ENABLE_MIDDLEWARE` |
    | Chatwoot URL   | `CHATWOOT_URL`               |
    | Access key     | `CHATWOOT_ACCESS_KEY`        |
    | Account ID     | `CHATWOOT_ACCOUNT_ID`        |
    | Inbox name     | `CHATWOOT_INBOX_NAME`        |

    This middleware is optional and can be disabled entirely without affecting agent behavior.
  </Step>
</Steps>

## Middleware registration order

Middleware stages execute in registration order. The order in `main.py` defines the pipeline:

```python theme={null}
gateway.register_middleware(commands_auth_middleware)
gateway.register_middleware(phone_faker_middleware)
gateway.register_middleware(payhub_auth_middleware)
gateway.register_middleware(contact_decoding_middleware)
gateway.register_middleware(chatwoot_middleware)
```

Any middleware can halt the pipeline by returning `False`. For example, `CommandsAuthMiddleware` returns `False` when commands are disabled, preventing the command message from reaching subsequent middleware or the agent.

## Security considerations

* **Phone normalization**: `PayhubAuthMiddleware` normalizes phone numbers before querying the identity service, preventing identity spoofing through formatting variations.
* **Identity injection**: Sender identity is injected into message metadata by the middleware — not provided by the sender. The agent receives pre-authenticated context.
* **Graceful failure**: Authentication middleware does not drop messages on failure. Service outages result in routing to the service unavailable agent, maintaining a response to the sender.
* **Development isolation**: `PhoneFakerMiddleware` uses a dedicated Redis hash and is controlled by deployment configuration. It produces no effect in production when disabled.

## Configuration and control

| Control              | Description                                                                              |
| -------------------- | ---------------------------------------------------------------------------------------- |
| Middleware ordering  | The bank defines which middleware runs and in what sequence                              |
| Command availability | `ACTIVE_COMMANDS` toggles slash command access                                           |
| Chatwoot integration | Independently enabled or disabled via environment variables                              |
| Phone faker          | Disabled in production; enabled only in development environments                         |
| Custom middleware    | The bank can add new middleware stages to the pipeline without modifying existing stages |
