> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch32-security-model/32.2-dm-pairing-system.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 32.2 DM Pairing System

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~260k tokens, Output \~7k tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

DM Pairing is OpenClaw's core security mechanism for controlling who can privately chat with the Bot. It implements a process similar to Bluetooth device pairing: when a stranger sends a message for the first time, they receive a pairing code, and only after the Bot owner approves it in the terminal is that user added to the whitelist. This section provides a complete analysis of this system from storage layer to CLI.

***

## 32.2.1 Pairing Flow: Code Generation → User Approval → Whitelist Persistence

### Core Data Structures

The pairing system involves two JSON files stored in the `~/.openclaw/oauth/` directory:

| File                       | Content                  | Format                                       |
| -------------------------- | ------------------------ | -------------------------------------------- |
| `{channel}-pairing.json`   | Pending pairing requests | `{ version: 1, requests: PairingRequest[] }` |
| `{channel}-allowFrom.json` | Approved whitelist       | `{ version: 1, allowFrom: string[] }`        |

The structure of `PairingRequest` is as follows:

```typescript
// src/pairing/pairing-store.ts

type PairingRequest = {
  id: string;          // User identifier (e.g., phone number, Telegram ID)
  code: string;        // 8-character human-friendly pairing code
  createdAt: string;   // ISO 8601 creation time
  lastSeenAt: string;  // Time of most recent attempt
  meta?: Record<string, string>;  // Additional metadata (e.g., username)
};
```

### Pairing Code Design

The pairing code is an 8-character combination of uppercase letters and digits, deliberately excluding easily confused characters:

```typescript
// src/pairing/pairing-store.ts

const PAIRING_CODE_LENGTH = 8;
const PAIRING_CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
// Note: excludes 0 (confused with O), 1 (confused with I), I, O

function randomCode(): string {
  let out = "";
  for (let i = 0; i < PAIRING_CODE_LENGTH; i++) {
    const idx = crypto.randomInt(0, PAIRING_CODE_ALPHABET.length);
    out += PAIRING_CODE_ALPHABET[idx];
  }
  return out;
}
```

> **Sidebar**: Excluding easily confused characters is common in human-readable encoding. Famous examples include Base32 encoding (RFC 4648) which excludes 0, 1, 8, and Crockford's Base32 variant. Here `crypto.randomInt` is used instead of `Math.random` because the latter is a pseudo-random number generator (PRNG) that should not be used in security contexts—`crypto.randomInt` uses the operating system's cryptographically secure random source (such as Linux's `/dev/urandom`).

### Complete Pairing Flow

```
┌──────────┐   DM Message   ┌──────────┐   Create/Update Request   ┌─────────────────────┐
│ Unknown  │───────────────→│ Channel  │──────────────────────────→│ pairing-store.json  │
│ User     │                │ Plugin   │                           └─────────────────────┘
└──────────┘                └──────────┘                                 │
                                 │                                       │
                                 │  Return Pairing Message               │ Generate 8-char Code
                                 ↓                                       │
                            ┌──────────┐                                 │
                            │ User     │←────────────────────────────────┘
                            │ Receives │
                            │ Code     │
                            └──────────┘

                        ┌──────────┐   approve <code>   ┌─────────────────────┐
                        │ Bot Owner│──────────────────→│ approveChannelPairing│
                        │ (CLI)    │                   │ Code                │
                        └──────────┘                   └─────────────────────┘
                                                            │
                                                       ┌────┴────┐
                                                       │ 1. Find matching code  │
                                                       │ 2. Remove from         │
                                                       │    requests            │
                                                       │ 3. Add to              │
                                                       │    allowFrom           │
                                                       └────────────────────┘
```

### Pairing Request Management

`upsertChannelPairingRequest` creates or updates a pairing request while managing expiration and capacity limits:

```typescript
// src/pairing/pairing-store.ts (simplified)

const PAIRING_PENDING_TTL_MS = 60 * 60 * 1000;  // 1 hour expiration
const PAIRING_PENDING_MAX = 3;                    // Max 3 concurrent requests

export async function upsertChannelPairingRequest(params) {
  return await withFileLock(filePath, fallback, async () => {
    // 1. Read existing requests
    const { value } = await readJsonFile(filePath, fallback);
    let reqs = value.requests;

    // 2. Clean up expired requests
    const { requests: pruned } = pruneExpiredRequests(reqs, Date.now());
    reqs = pruned;

    // 3. Check if already exists (same user sending message again)
    const existingIdx = reqs.findIndex((r) => r.id === id);
    if (existingIdx >= 0) {
      // Update lastSeenAt, keep original pairing code
      reqs[existingIdx] = { ...existing, lastSeenAt: now };
      return { code: existing.code, created: false };
    }

    // 4. Capacity check (max 3)
    if (reqs.length >= PAIRING_PENDING_MAX) {
      return { code: "", created: false };  // Reject new request
    }

    // 5. Generate unique pairing code and create new request
    const code = generateUniqueCode(existingCodes);
    reqs.push({ id, code, createdAt: now, lastSeenAt: now, meta });
    await writeJsonFile(filePath, { version: 1, requests: reqs });
    return { code, created: true };
  });
}
```

Key security design points:

* **1-hour expiration**: Prevents pairing codes from being exposed for extended periods
* **Max 3 concurrent requests**: Prevents attackers from generating massive pairing requests through bulk message sending (denial of service attack)
* **Unique code guarantee**: `generateUniqueCode` attempts up to 500 times to generate non-duplicate codes
* **File locking**: `withFileLock` (based on `proper-lockfile` library) ensures safe concurrent access

### Approval and Whitelist

`approveChannelPairingCode` completes the final step of pairing—verifying the code, removing from request list, and adding to whitelist:

```typescript
// src/pairing/pairing-store.ts (simplified)

export async function approveChannelPairingCode(params) {
  const code = params.code.trim().toUpperCase();

  return await withFileLock(filePath, fallback, async () => {
    const reqs = /* Read and clean expired requests */;
    const idx = reqs.findIndex((r) => r.code.toUpperCase() === code);
    if (idx < 0) return null;  // No matching code found

    const entry = reqs[idx];
    reqs.splice(idx, 1);  // Remove from request list
    await writeJsonFile(filePath, { version: 1, requests: reqs });

    // Add to whitelist
    await addChannelAllowFromStoreEntry({
      channel: params.channel,
      entry: entry.id,
    });

    return { id: entry.id, entry };
  });
}
```

### Atomic Write Protection

All file writes use atomic write mode (same as the configuration system):

```typescript
async function writeJsonFile(filePath: string, value: unknown): Promise<void> {
  const dir = path.dirname(filePath);
  await fs.promises.mkdir(dir, { recursive: true, mode: 0o700 });   // Directory perms 700
  const tmp = path.join(dir, `${path.basename(filePath)}.${crypto.randomUUID()}.tmp`);
  await fs.promises.writeFile(tmp, JSON.stringify(value, null, 2) + "\n");
  await fs.promises.chmod(tmp, 0o600);                                // File perms 600
  await fs.promises.rename(tmp, filePath);                            // Atomic rename
}
```

***

## 32.2.2 Pairing CLI (`src/cli/pairing-cli.ts`)

### Command Structure

The pairing CLI is registered under the `openclaw pairing` subcommand, providing two operations:

```bash
openclaw pairing list [channel]        # List pending pairing requests
openclaw pairing approve <channel> <code>  # Approve pairing code
```

### list Command

Lists pending requests for a specified channel, supporting both table and JSON output formats:

```typescript
// src/cli/pairing-cli.ts (simplified)

pairing.command("list")
  .argument("[channel]", "Channel (whatsapp, telegram, ...)")
  .option("--json", "Print JSON")
  .action(async (channelArg, opts) => {
    const channel = parseChannel(channelRaw, channels);
    const requests = await listChannelPairingRequests(channel);

    if (opts.json) {
      log(JSON.stringify({ channel, requests }, null, 2));
      return;
    }
    if (requests.length === 0) {
      log("No pending pairing requests.");
      return;
    }
    // Table output: Code | ID | Meta | Requested
    log(renderTable({
      columns: [
        { key: "Code", header: "Code" },
        { key: "ID", header: resolvePairingIdLabel(channel) },
        { key: "Meta", header: "Meta" },
        { key: "Requested", header: "Requested" },
      ],
      rows: requests.map(/* ... */),
    }));
  });
```

`resolvePairingIdLabel` returns a friendly ID label based on channel type—WhatsApp displays "Phone", Telegram displays "User ID", etc.

### approve Command

Approves and optionally notifies the requester:

```typescript
pairing.command("approve")
  .argument("<codeOrChannel>")
  .argument("[code]")
  .option("--notify", "Notify the requester")
  .action(async (codeOrChannel, code, opts) => {
    const channel = parseChannel(channelRaw, channels);
    const approved = await approveChannelPairingCode({ channel, code });
    if (!approved) {
      throw new Error("No pending pairing request found for code");
    }
    log(`Approved ${channel} sender ${approved.id}.`);

    if (opts.notify) {
      await notifyPairingApproved({ channelId: channel, id: approved.id, cfg });
    }
  });
```

The `--notify` option sends a notification message to the newly approved user through the channel plugin's `pairing.notifyApproval` interface.

### Channel Adapter

Each channel plugin can customize pairing behavior through the `ChannelPairingAdapter` interface:

```typescript
// src/channels/plugins/types.ts (conceptual)

type ChannelPairingAdapter = {
  idLabel: string;                                          // Human-readable label for ID
  normalizeAllowEntry?: (entry: string) => string;         // Normalize whitelist entry
  notifyApproval?: (params: { cfg; id; runtime }) => void; // Notify after approval
};
```

For example, WhatsApp's adapter might normalize phone numbers to international format (such as removing `+` prefix and spaces) to ensure consistent whitelist matching.

***

## 32.2.3 DM Policy: `pairing` / `open`

### Policy Enumeration

Each channel's DM reception policy is controlled by the `dmPolicy` configuration:

| Policy       | Behavior                                                                           |
| ------------ | ---------------------------------------------------------------------------------- |
| `"pairing"`  | Default policy. Unknown users receive a pairing code requiring Bot owner approval  |
| `"open"`     | Anyone can send DMs and receive responses (must be paired with `allowFrom: ["*"]`) |
| `"disabled"` | Completely disable DM functionality                                                |

### Security Checks for open Policy

The security audit system (Section 32.4) issues critical warnings for `open` policy:

```typescript
// src/security/audit.ts (simplified)

if (dmPolicy === "open") {
  findings.push({
    checkId: `channels.${provider}.dm.open`,
    severity: "critical",                    // Highest severity level
    title: `${label} DMs are open`,
    detail: `dmPolicy="open" allows anyone to DM the bot.`,
    remediation: "Use pairing/allowlist...",
  });
}
```

Additionally, if `dmPolicy` is set to `open` but `allowFrom` does not include the wildcard `"*"`, the audit system reports a configuration inconsistency:

```
channels.whatsapp.dm.open_invalid: "open" requires allowFrom to include "*".
```

### Session Isolation and Multi-User DMs

When multiple users can DM (via `open` policy or multiple entries in whitelist), the `session.dmScope` configuration determines the session isolation level:

| dmScope                      | Behavior                                                                        |
| ---------------------------- | ------------------------------------------------------------------------------- |
| `"main"`                     | All DM senders share the main session (**risk of context leakage**)             |
| `"per-channel-peer"`         | Each channel+sender pair has an independent session                             |
| `"per-account-channel-peer"` | Each account+channel+sender has an independent session (multi-account channels) |

The security audit issues a warning when detecting `dmScope="main"` with multiple DM senders:

```typescript
if (dmScope === "main" && isMultiUserDm) {
  findings.push({
    severity: "warn",
    title: `${label} DMs share the main session`,
    detail: "Multiple DM senders share the main session, which can leak context across users.",
    remediation: 'Set session.dmScope="per-channel-peer" to isolate DM sessions per sender.',
  });
}
```

***

## Summary of This Section

1. **Pairing Code**: 8-character alphanumeric combination, excluding easily confused characters (0, O, 1, I), generated using cryptographically secure randomness.
2. **Three-Step Flow**: Unknown user sends DM → Receives pairing code → Bot owner CLI approval → Added to whitelist.
3. **Security Limits**: Requests expire in 1 hour, max 3 concurrent pending requests, file locking prevents concurrency issues.
4. **Atomic Writes**: tmp file + rename pattern, file permissions 0o600, directory permissions 0o700.
5. **Channel Adapter**: Each channel can customize ID labels, whitelist normalization rules, and approval notification methods.
6. **Three-Level DM Policy**: `pairing` (secure by default), `open` (explicit opt-in with audit warnings), `disabled` (completely disabled).
7. **Session Isolation**: `dmScope` configuration prevents information leakage from multiple DM users sharing context.
