Files
nick-doc/03 - API Reference/Chat API.md
Siavash Sameni dceaf82934 audit: 2026-05-30 full-codebase audit — report, issues, docs, runbooks
Full-codebase-audit 2026-05-30 outputs:
- Audit report: 09 - Audits/Full Codebase Audit - 2026-05-30.md
- 81 issue files ISSUE-055..135 (decisions + 1 skipped no-brainer).
- Scanner docs from scratch (was zero): architecture, data model, API ref, payment
  flow, operations runbook + repo README.
- Doc-sync updates across API reference, data models, flows, design system.
- Secret Rotation Runbook (08 - Operations) for the exposed credentials.
- Reusable workflow guide (07 - Development) + .claude/workflows/full-codebase-audit.js.

Issues remain status:open intentionally — the code fixes are uncommitted-then-committed
working-tree changes per repo and aren't "resolved" until merged/deployed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-05-30 18:48:04 +04:00

160 lines
6.5 KiB
Markdown

---
title: Chat API
tags: [api, chat, reference]
---
# Chat API
> **Last updated:** 2026-05-30 — admin and resolver roles can now read and send messages in any chat (commit `766a9a2`)
All chat endpoints live under `/api/chat/*`. The router is [`backend/src/services/chat/chatRoutes.ts`](../../backend/src/services/chat/chatRoutes.ts), controller is `chatController`, service is `ChatService`. Every endpoint requires `Bearer JWT` — the router applies `authenticateToken` globally.
> [!note] Admin and resolver chat access
> Users with role `admin` or `resolver` can **read messages and send messages in any chat** without being a listed participant (`ChatService` checks `canBypassMembership = senderRole === 'admin' || senderRole === 'resolver'`). This applies to `GET /api/chat/:id/messages`, `GET /api/chat/:id/info`, and `POST /api/chat/:id/messages`. Dispute-chat monitoring for resolvers was the primary driver (commit `766a9a2`).
Model: [[Chat]]. Real-time delivery happens over Socket.IO rooms named `chat-<chatId>`. Clients must call `join-chat-room` after connecting. See [[Socket Events]] for `new-message`, `messages-read`, `message-edited`, `message-deleted`, `participants-added`, `participant-removed`, and `user-typing` payloads.
## Rate limits and constraints
| Rule | Value |
| --- | --- |
| Messages per user per minute | **20** |
| Edit window | **15 minutes** after send |
| Maximum message length | **5 000 characters** |
## Conversations
### POST /api/chat
**Description:** Create a generic chat between two or more participants.
**Auth required:** Bearer JWT
**Request body:**
```ts
{
participantIds: string[]; // 2+ user ids (caller is added automatically)
type?: "direct" | "group"; // default "direct"
title?: string; // group only
metadata?: Record<string, unknown>;
}
```
**Response 201:** `{ success: true, data: { chat: { _id, participants, type, ... } } }`
**Errors:** `400` need 2+ participants, `404` participant not found.
### POST /api/chat/purchase-request
**Description:** Create (or fetch the existing) chat tied to a specific [[PurchaseRequest]] between buyer and seller. Idempotent.
**Auth required:** Bearer JWT
**Request body:** `{ purchaseRequestId: string; sellerId: string }`
**Response 200/201:** `{ success: true, data: { chat } }`
### POST /api/chat/support
**Description:** Open a support chat. Adds the caller and the support/admin pool. Used by the in-app help widget.
**Auth required:** Bearer JWT
**Request body:** `{ subject?: string; initialMessage?: string }`
**Response 201:** `{ success: true, data: { chat } }`
### GET /api/chat
**Description:** List the caller's chats, ordered by latest message. Includes unread counts.
**Auth required:** Bearer JWT
**Query params:** `page`, `limit`, `type` (`direct` | `group` | `support`)
**Response 200:** `{ success, data: { chats: [...], pagination } }`
### GET /api/chat/stats
**Description:** Aggregate counts (total chats, total messages, total unread).
**Auth required:** Bearer JWT
### GET /api/chat/:id/info
**Description:** Full chat metadata: participants (populated), title, type, created-at, last message, unread per user.
**Auth required:** Bearer JWT (participant)
**Errors:** `403` not a participant, `404` not found.
### PUT /api/chat/:id/archive
**Description:** Toggle archived state for the caller (per-user flag). Calling this endpoint on an already-archived chat **unarchives** it (toggle semantics).
**Auth required:** Bearer JWT (participant)
### POST /api/chat/:id/participants
**Description:** Add a participant to a group chat.
**Auth required:** Bearer JWT (creator/admin)
**Request body:** `{ userId: string }`
**Side effects:** Emits `participants-added` on `chat-<id>`.
### DELETE /api/chat/:id/participants/:participantId
**Description:** Remove a participant from a group chat.
**Auth required:** Bearer JWT (creator/admin)
**Side effects:** Emits `participant-removed` on `chat-<id>`.
## Messages
### GET /api/chat/:id/messages
**Description:** Paginated message history (newest first by default).
**Auth required:** Bearer JWT (participant)
**Query params:** `page`, `limit`, `before` (cursor by createdAt)
### POST /api/chat/:id/messages
**Description:** Send a text message.
**Auth required:** Bearer JWT (participant)
**Request body:**
```ts
{
content: string;
type?: "text" | "system"; // default "text"
replyToMessageId?: string;
metadata?: Record<string, unknown>;
}
```
**Response 201:** `{ success, data: { message } }`
**Side effects:** Emits `new-message` on `chat-<chatId>`; increments unread for other participants.
### POST /api/chat/:id/messages/file
**Description:** Send a message with a binary attachment. Multipart form (`file` field). Maxes follow the [[File API]] limits.
**Auth required:** Bearer JWT (participant)
**Form fields:**
- `file` - the file blob
- `content?` - optional caption
- `replyToMessageId?` - optional
**Response 201:** `{ success, data: { message: { attachments: [{ url, filename, mimeType, size }] } } }`
> ⚠️ **KNOWN BUG** — The frontend `sendFileMessage` function incorrectly posts to `POST /api/chat/:id/messages` (the plain-text endpoint) instead of `POST /api/chat/:id/messages/file`. File uploads are currently broken as a result; the attachment is silently dropped or the request is rejected.
### PATCH /api/chat/:id/messages/read
**Description:** Mark messages as read for the caller. Passing an empty `messageIds` array (or omitting it) marks **all** messages in the chat as read.
**Auth required:** Bearer JWT (participant)
**Response 200:** `{ success, data: { modifiedCount } }`
**Side effects:** Emits `messages-read` on `chat-<id>`.
### PUT /api/chat/:id/messages/:messageId
**Description:** Edit an existing message (author only, within the 15-minute edit window).
**Auth required:** Bearer JWT (message author)
**Request body:** `{ content: string }`
**Side effects:** Emits `message-edited` on `chat-<id>`.
### DELETE /api/chat/:id/messages/:messageId
**Description:** Soft-delete a message (author or admin). The record stays but `deletedAt` is set and `content` is cleared.
**Auth required:** Bearer JWT (author or admin)
**Side effects:** Emits `message-deleted` on `chat-<id>`.
## Typing indicator
Typing indicators are not REST endpoints — clients emit `typing-start` and `typing-stop` over Socket.IO. The server broadcasts `user-typing` to the chat room. Full details in [[Socket Events]].
## Related
- [[Chat]]
- [[Chat Flow]]
- [[File API]] (for attachment uploads)
- [[Notification API]] (for out-of-band notifications when a chat message is received and the user is offline)