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

# Client and session rules

> Monitor clients and their logins, not only their transactions: rules that run when a client is created or updated, or when a client session is created, with a Client or Session Monitoring alert or an inline ALLOW / FLAG decision.

Transaction rules run when money moves. **Client rules** and **session rules** run when something happens to the client itself, so you can check onboarding, profile changes and logins before any transaction:

| Rule | Runs when | Checks | Raises |
| - | - | - | - |
| [**Client rule**](#client-rules) | A client is created or updated | The client as it is at that moment | A Client Monitoring alert |
| [**Session rule**](#session-rules) | A client session is created | The new session together with its client | A Session Monitoring alert |

Use client rules for onboarding screening and for changes to a client's country or risk data. Use session rules for login and access checks: a new device, a VPN or Tor connection, a burst of IP addresses, or a device shared by many clients.

> [!NOTE]
>
> Client rules and session rules are rolled out per platform behind feature flags. If you don't see the **Client** or **Session** option when you create a rule, ask your Corsa contact to enable it. With either enabled, the **Transaction Monitoring** module is called **Monitoring Rules**.

***

## How they work

1. You create a rule and choose **Client** or **Session** as what it applies to. You can't change this later.
2. When a client is created or updated, Corsa evaluates the active client rules whose trigger matches the change. When a [session](https://docs.corsa.finance/api/ingesting-sessions.md) is created, Corsa evaluates the active session rules. Evaluation runs right after the write is stored, or [inline](#get-an-inline-decision) when you ask for a decision.
3. The rule's conditions are checked against the client's current data and, for a session rule, the new session.
4. When the rule matches, Corsa creates an alert linked to the client (and, for a session rule, to the session). These alerts are not linked to a transaction.

Transaction rules keep working exactly as before: they still run on every transaction and can check the sending or receiving client.

***

## What client and session rules can check

A client or session rule always checks one client (and one session), so you don't choose a sender or receiver.

| Data | Examples | Client rules | Session rules |
| - | - | - | - |
| **Client profile** | Risk tier, country, account status, KYC and screening status, onboarding dates | ✓ | ✓ |
| **Tags and custom fields** | `customFields.segment`, client tags | ✓ | ✓ |
| **Lists** | Client on a block, allow or watch list; client country on a country list | ✓ | ✓ |
| **Transaction history** | Sum, count or average of the client's transactions over a time window | ✓ | ✓ |
| **Session data** | Login IP, IP country, city, VPN, proxy, Tor, datacenter, device fingerprint, device type, browser, operating system | From the client's latest session | From the session being evaluated |
| **Device and IP** | Device or IP on a list, device custom fields | From the client's latest session | From the session being evaluated |
| **[Session Activity](#session-activity)** | Device is new, more than 5 IP addresses in 24 hours, device shared by more than 3 clients | — | ✓ |

Client properties are the same as in [transaction rules](https://docs.corsa.finance/transaction-monitoring/conditions-reference.md#entities), and custom fields follow the [custom field rules](https://docs.corsa.finance/transaction-monitoring/conditions-reference.md#custom-fields). In transaction history aggregations on a client rule, choose **All of the client's transactions**, **Outgoing** or **Incoming**.

Some conditions need a transaction in progress, so neither kind offers them:

* transaction properties (amount, type, currency) outside an aggregation;
* wallet, bank account, payment account and merchant conditions;
* **include current transaction** on aggregations;
* conditions that match the current transaction's counterparty or wallet.

***

## Client rules

### When a client rule runs

Each client rule has a trigger:

| Run on | When it runs |
| - | - |
| **Client created** (default) | Once, when the client is created. |
| **Client created or updated** | When the client is created and on every update. |
| **Client updated** | On every update, not on creation. |

### Only when specific fields change

A rule that runs on updates can be narrowed to **only when these fields change**. List the client fields as dotted paths, as they appear in the [client API](https://docs.corsa.finance/api/data-ingestion.md) (for example, `address.country` or `address.city`). The rule runs on an update only when one of those fields changed:

* A field matches a change to itself or to anything below it: `address` matches a change to `address.city`.
* A change to a whole parent object matches the fields inside it.
* Other fields don't count: a rule on `address.city` doesn't run when only `address.country` changes.

> [!TIP]
>
> Updates that arrive close together are evaluated on the client's latest data. If a newer update has already been stored when an older one is processed, the older update is skipped and the newer one evaluates the client. A **Client created** rule still runs for every new client.

### Alerts from client rules

* **One alert per match** (default): a rule alerts when a client starts matching. While the client keeps matching on later updates, no new alert is created. If the client stops matching and later matches again, the rule alerts again.
* **Alert on every match:** turn this on to create an alert every time the rule runs and matches.

***

## Session rules

A session rule runs once, when the session is created, and checks that session together with its client. Updating a session (for example, setting `endedAt`) doesn't run session rules again, and a rule alerts at most once for a session, even if the session event is delivered twice.

### Session Activity

**Session Activity** compares the session being evaluated with earlier sessions: the client's own, or every client's sessions on the same IP or device. In the Rule Builder it appears under **Client** → **Session Activity**, and each condition reads as one row:

**Client** · **Session Activity** · *attribute* · *measure* · *time window* · *comparison*

**Attributes**

| Attribute | API value | Compared across clients |
| - | - | - |
| **IP Address** | `loginIp` | Yes |
| **Device** | `deviceFingerprint` | Yes |
| **IP Country** | `ipCountryCode` | No |
| **Network (ASN)** | `asn` | No |
| **City** | `geoCity` | No |
| **Browser** | `browser` | No |
| **Operating System** | `os` | No |

**Measures**

| Measure | What it counts | Example |
| - | - | - |
| **is new** | Whether any earlier session of the client had this value | Device is new for the client |
| **sessions with this value** | The client's sessions with the same value, this one included | More than 3 sessions from this city in the last hour |
| **count distinct** | Different values across the client's sessions | More than 5 IP addresses in the last 24 hours |
| **clients sharing it** | Clients with a session on this IP or device | Device used by more than 3 clients in the last 30 days |
| **sessions from this IP or device, any client** | Sessions on this IP or device, whoever the client | More than 20 sessions from this IP in the last hour |
| **Sessions** (no attribute) | All the client's sessions | More than 10 sessions in the last hour |

**clients sharing it** and **sessions from this IP or device, any client** are only available for **IP Address** and **Device**.

**Time windows**

* **Ever** (all of the client's history), or **in the last** N minutes, hours, days or weeks.
* The window ends at the start of the session being evaluated and includes it. The session that crosses a threshold is the one that raises the alert.
* Measures that look across clients need an **in the last** window.
* If the session has no value for the attribute (for example, no device fingerprint or no ASN), the condition doesn't match. A missing value never counts as zero.

**In the API**, a Session Activity condition uses `property: "sessions"` on the `client` entity:

| Field | Value |
| - | - |
| `aggregationOperator` | `count` (sessions) or `countDistinct` (different values of `aggregationProperty`) |
| `aggregationProperty` | `countDistinct` only: an attribute's API value, or `clientId` for clients sharing an IP or device |
| `aggregationSessionMatch` | Optional. `{ "property": "<attribute>" }` counts only sessions with the same value as this session. Add `"anyClient": true` to count every client's sessions (`loginIp` and `deviceFingerprint` only). |
| `aggregationTimeType` | `all_time` (not with `anyClient`) or `in_the_last` |
| `aggregationTimeValue`, `aggregationTimePeriod` | With `in_the_last`: a number, and `minutes`, `hours`, `days` or `weeks` |

"Device is new" is a same-value count equal to 1: the only session with this device is the current one. See [Create a session rule](#create-a-session-rule) for a full example.

***

## Alerts

The only action on a client or session rule is **Create alert**. These rules can't halt transactions.

* **Category:** always `CLIENT_MONITORING` for client rules and `SESSION_MONITORING` for session rules. Priority, assignee, sub-category and due date come from the rule's alert settings, as for transaction rules.
* Client Monitoring and Session Monitoring alerts appear in the [Alerts](https://docs.corsa.finance/case-management/alerts.md) queue with the client's details (and the session, for session rules). You can filter, assign, escalate and resolve them like any other alert.

***

## Build a rule in the dashboard

1. Go to **Monitoring Rules** → **Rules** and click **Create Rule**.
2. Choose **Client** or **Session**. You can't change this after the rule is created.
3. **Define conditions.** The condition menu offers client, device and IP data, plus **Session Activity** on session rules. Aggregations on client rules let you choose the direction of the client's transactions.
4. **Configure the response:**
   * Client rules: **Run on** (**Client created**, **Client created or updated**, or **Client updated**), **Only when these fields change** when the rule runs on updates, and **Alert on every match** (off by default).
   * Session rules always run when a session is created, so there's no **Run on** choice.
   * Alert priority and routing, as for [transaction rules](https://docs.corsa.finance/transaction-monitoring/building-rules.md#step-2-configure-response).
5. **Test** the rule. Session rules replay recent sessions. Client rules can **Backtest clients** or **Test one client**. Tests create no alerts. See [Testing client and session rules](https://docs.corsa.finance/transaction-monitoring/testing-rules.md#testing-client-and-session-rules).
6. **Review and activate.**

The **Rules** list has an **Applies to** column and filter, so you can tell transaction, client and session rules apart.

The **Rule Builder Assistant** can propose conditions from a plain-language description, including Session Activity on session rules, and when the rule runs and **Alert on every match** on client rules. See [Build with the Rule Builder Assistant](https://docs.corsa.finance/transaction-monitoring/building-rules.md#build-with-the-rule-builder-assistant).

***

## Get an inline decision

By default, client and session rules run right after the write is stored. To get the result in the response instead, set `evaluateSynchronously: true` when you:

* create or update a client ([Ingesting clients](https://docs.corsa.finance/api/ingesting-clients.md#evaluate-client-rules-inline)). A create evaluates the rules that run on **Client created**; an update evaluates the rules that run on updates. Bulk updates never evaluate inline.
* create a session ([Ingesting sessions](https://docs.corsa.finance/api/ingesting-sessions.md#evaluate-session-rules-inline)), for example to step up authentication on a risky login.

The response then includes `evaluationResult`:

| `decision` | Meaning |
| - | - |
| `ALLOW` | No active rule matched. |
| `FLAG` | At least one rule matched. `matchedRules` lists them (`ruleId`, `ruleVersion`, `ruleName`, `tags`). |
| `EVALUATION_FAILED` | The evaluation couldn't finish in time or hit an error. `failureReason` is `TIMEOUT` or `ERROR`. |

The client or session is stored in every case, and matching rules create alerts as for asynchronous evaluation.

To check a stored client or session again without creating anything, use [Evaluate a client or session](https://docs.corsa.finance/transaction-monitoring/rules-api.md#evaluate-a-client-or-session).

***

## Manage client and session rules with the API

Client and session rules use the same [Rules API](https://docs.corsa.finance/transaction-monitoring/rules-api.md) as transaction rules, with these extra fields:

| Field | Applies to | Description |
| - | - | - |
| `baseEntity` | Create only | `client` or `session`. Omit it, or send `transaction`, for a transaction rule. It can't be changed later. |
| `triggers` | Client rules | `events`: `["created"]` (default), `["updated"]`, or both. `updatedFields`: optional dotted client field paths; needs `updated` in `events`. |
| `alertOnEveryMatch` | Client rules | `false` (default) alerts when a client starts matching; `true` alerts on every match. |

`triggers` and `alertOnEveryMatch` are refused on session rules. A request is also refused with `400` if the rule kind isn't enabled for your platform, if a condition needs a transaction, if an action other than `CREATE_ALERT` is used, or if a Session Activity condition isn't valid (for example, `anyClient` on IP country, or `all_time` with `anyClient`).

Rules are created as drafts. [Activate a rule](https://docs.corsa.finance/transaction-monitoring/rules-api.md#activate-a-rule) to start evaluating clients or sessions.

### Create a client rule

```json REST API theme={null}
POST /v1/rules
Content-Type: application/json

{
  "name": "Client moved to a high-risk country",
  "description": "Alert when a client's address country changes to a high-risk jurisdiction",
  "baseEntity": "client",
  "triggers": {
    "events": ["created", "updated"],
    "updatedFields": ["address.country"]
  },
  "alertOnEveryMatch": false,
  "conditions": {
    "all": [
      {
        "entity": "client",
        "property": "country",
        "operator": "in",
        "value": ["IRN", "PRK"]
      }
    ]
  },
  "actions": [
    {
      "type": "CREATE_ALERT",
      "config": {
        "category": "CLIENT_MONITORING",
        "priority": "HIGH",
        "status": "NEW"
      }
    }
  ]
}
```

```typescript Javascript theme={null}
const rule = await corsa.rules.createRule({
  name: "Client moved to a high-risk country",
  description:
    "Alert when a client's address country changes to a high-risk jurisdiction",
  baseEntity: "client",
  triggers: {
    events: ["created", "updated"],
    updatedFields: ["address.country"],
  },
  alertOnEveryMatch: false,
  conditions: {
    all: [
      {
        entity: "client",
        property: "country",
        operator: "in",
        value: ["IRN", "PRK"],
      },
    ],
  },
  actions: [
    {
      type: "CREATE_ALERT",
      config: { category: "CLIENT_MONITORING", priority: "HIGH", status: "NEW" },
    },
  ],
});
```

```python Python theme={null}
from corsa_sdk.api.rules.create_rule import _get_kwargs
from corsa_sdk.models.create_rule_dto import CreateRuleDto

resp = http.request(**_get_kwargs(
    body=CreateRuleDto.from_dict({
        "name": "Client moved to a high-risk country",
        "description": "Alert when a client's address country changes to a high-risk jurisdiction",
        "baseEntity": "client",
        "triggers": {"events": ["created", "updated"], "updatedFields": ["address.country"]},
        "alertOnEveryMatch": False,
        "conditions": {"all": [
            {"entity": "client", "property": "country", "operator": "in", "value": ["IRN", "PRK"]},
        ]},
        "actions": [{"type": "CREATE_ALERT", "config": {"category": "CLIENT_MONITORING", "priority": "HIGH", "status": "NEW"}}],
    }),
))
rule = resp.json()
```

### Create a session rule

```json REST API theme={null}
POST /v1/rules
Content-Type: application/json

{
  "name": "New device and more than 5 IP addresses in 24 hours",
  "description": "Alert when a client logs in from a new device after using many IP addresses",
  "baseEntity": "session",
  "conditions": {
    "all": [
      {
        "entity": "client",
        "property": "sessions",
        "aggregationOperator": "count",
        "aggregationSessionMatch": { "property": "deviceFingerprint" },
        "aggregationTimeType": "all_time",
        "operator": "equal",
        "value": 1
      },
      {
        "entity": "client",
        "property": "sessions",
        "aggregationOperator": "countDistinct",
        "aggregationProperty": "loginIp",
        "aggregationTimeType": "in_the_last",
        "aggregationTimeValue": 24,
        "aggregationTimePeriod": "hours",
        "operator": "greaterThan",
        "value": 5
      }
    ]
  },
  "actions": [
    {
      "type": "CREATE_ALERT",
      "config": { "category": "SESSION_MONITORING", "priority": "HIGH", "status": "NEW" }
    }
  ]
}
```

```typescript Javascript theme={null}
const rule = await corsa.rules.createRule({
  name: "New device and more than 5 IP addresses in 24 hours",
  description: "Alert when a client logs in from a new device after using many IP addresses",
  baseEntity: "session",
  conditions: {
    all: [
      {
        entity: "client",
        property: "sessions",
        aggregationOperator: "count",
        aggregationSessionMatch: { property: "deviceFingerprint" },
        aggregationTimeType: "all_time",
        operator: "equal",
        value: 1,
      },
      {
        entity: "client",
        property: "sessions",
        aggregationOperator: "countDistinct",
        aggregationProperty: "loginIp",
        aggregationTimeType: "in_the_last",
        aggregationTimeValue: 24,
        aggregationTimePeriod: "hours",
        operator: "greaterThan",
        value: 5,
      },
    ],
  },
  actions: [
    {
      type: "CREATE_ALERT",
      config: { category: "SESSION_MONITORING", priority: "HIGH", status: "NEW" },
    },
  ],
});
```

```python Python theme={null}
from corsa_sdk.api.rules.create_rule import _get_kwargs
from corsa_sdk.models.create_rule_dto import CreateRuleDto

resp = http.request(**_get_kwargs(
    body=CreateRuleDto.from_dict({
        "name": "New device and more than 5 IP addresses in 24 hours",
        "description": "Alert when a client logs in from a new device after using many IP addresses",
        "baseEntity": "session",
        "conditions": {"all": [
            {"entity": "client", "property": "sessions", "aggregationOperator": "count",
             "aggregationSessionMatch": {"property": "deviceFingerprint"},
             "aggregationTimeType": "all_time", "operator": "equal", "value": 1},
            {"entity": "client", "property": "sessions", "aggregationOperator": "countDistinct",
             "aggregationProperty": "loginIp", "aggregationTimeType": "in_the_last",
             "aggregationTimeValue": 24, "aggregationTimePeriod": "hours",
             "operator": "greaterThan", "value": 5},
        ]},
        "actions": [{"type": "CREATE_ALERT", "config": {"category": "SESSION_MONITORING", "priority": "HIGH", "status": "NEW"}}],
    }),
))
rule = resp.json()
```

### Change when a client rule runs

Send `triggers` or `alertOnEveryMatch` on [update](https://docs.corsa.finance/transaction-monitoring/rules-api.md#update-a-rule). Fields you omit keep their stored values.

```json REST API theme={null}
PUT /v1/rules/rule-uuid
Content-Type: application/json

{
  "triggers": { "events": ["updated"], "updatedFields": ["address.country", "address.city"] },
  "alertOnEveryMatch": true,
  "reason": "Also watch city changes"
}
```

```typescript Javascript theme={null}
const rule = await corsa.rules.updateRule("rule-uuid", {
  triggers: { events: ["updated"], updatedFields: ["address.country", "address.city"] },
  alertOnEveryMatch: true,
  reason: "Also watch city changes",
});
```

```python Python theme={null}
from corsa_sdk.api.rules.update_rule import _get_kwargs
from corsa_sdk.models.update_rule_dto import UpdateRuleDto

resp = http.request(**_get_kwargs(
    id="rule-uuid",
    body=UpdateRuleDto.from_dict({
        "triggers": {"events": ["updated"], "updatedFields": ["address.country", "address.city"]},
        "alertOnEveryMatch": True,
        "reason": "Also watch city changes",
    }),
))
rule = resp.json()
```

### List client or session rules

Filter on `baseEntity`: `$eq:client` or `$eq:session`.

```bash REST API theme={null}
GET /v1/rules?filter.baseEntity=$eq:session
```

```typescript Javascript theme={null}
// listRules(page, limit, filterId, filterName, filterStatus, filterIsExternalRule, filterVendorName, filterBaseEntity, ...)
const rules = await corsa.rules.listRules(
  1, 20, undefined, undefined, undefined, undefined, undefined, ["$eq:session"]
);
```

```python Python theme={null}
from corsa_sdk.api.rules.list_rules import _get_kwargs

kwargs = _get_kwargs(limit=20, page=1)
kwargs["params"]["filter.baseEntity"] = ["$eq:session"]
resp = http.request(**kwargs)
rules = resp.json()
```

Rule responses include `baseEntity`, `triggers` and `alertOnEveryMatch`. A transaction or session rule returns `triggers: null`.

***

## What's next?

> [card] [Ingesting sessions](https://docs.corsa.finance/api/ingesting-sessions.md)
>
> Send sessions with IP and device data, and ask for an inline decision.

> [card] [Testing rules](https://docs.corsa.finance/transaction-monitoring/testing-rules.md#testing-client-and-session-rules)
>
> Backtest a client or session rule before you activate it.

> [card] [Conditions reference](https://docs.corsa.finance/transaction-monitoring/conditions-reference.md)
>
> Operators, entities, aggregations and time windows.

> [card] [Workflows](https://docs.corsa.finance/workflows.md#event-triggers)
>
> Start a workflow when a client session is created.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.