{
  "openapi": "3.1.0",
  "info": {
    "title": "Mitekbro Chat Platform API (E2EE)",
    "version": "1.0.0",
    "summary": "Real-time Go workspace chat API with Zero-Knowledge End-to-End Encryption (ECDH P-256 + AES-256-GCM).",
    "description": "REST and WebSocket API for **Mitekbro Chat** (`https://chat.mitekbro.com`).\n\n### Authentication\nAuthenticate using any of:\n- **`Authorization: Bearer <jwt>`** HTTP header (recommended for API/CLI clients)\n- **`dpchat_token`** `HttpOnly` session cookie (automatically set by `/api/auth/login` and `/api/auth/register`)\n- **`?token=<jwt>`** query parameter (supported for browser/client WebSocket handshakes on `/api/ws`)\n\n### Zero-Knowledge End-to-End Encryption (E2EE) Protocol\n1. **Identity Keys**: Clients generate a **NIST P-256 ECDH** keypair (`kty: \"EC\"`, `crv: \"P-256\"`). The server validates curve membership and computes a canonical 40-digit SHA-256 Safety Number over the uncompressed point `0x04 || X || Y`.\n2. **Private Key Backup**: Clients encrypt their private JWK using **PBKDF2-HMAC-SHA256** (`310,000` iterations, 16-byte salt) + **AES-256-GCM** (12-byte IV) before uploading `encryptedPrivateKey`, `keySalt`, and `keyIv`.\n3. **Room Key Wrapping (ECIES / HPKE style)**: Each E2EE room (all 1:1 DMs and encrypted channels) uses a random 32-byte `AES-256-GCM` room key wrapped per member via ephemeral **ECDH P-256 + HKDF-SHA256** (`salt = roomId`, `info = \"dpchat-room-key-v1\"`) + **AES-256-GCM** (`AAD = \"<roomId>:<userId>:<keyVersion>\"`).\n4. **Messages & Attachments**: Encrypted client-side using **AES-256-GCM** (`AAD = \"<roomId>:<keyVersion>\"`). Plaintext `content` is strictly rejected (`400 Bad Request`) in E2EE rooms. Attachments in E2EE rooms are encrypted client-side with a one-time 256-bit `AES-GCM` key stored inside the encrypted message payload.\n\n### Real-Time WebSocket (`/api/ws`)\n- **Client \u2192 Server frames**:\n  - `{\"type\": \"typing\", \"roomId\": \"<uuid>\"}`\n  - `{\"type\": \"ping\"}`\n- **Server \u2192 Client events**:\n  - `presence.snapshot` (`{onlineUserIds: string[]}`)\n  - `presence.update` (`{userId: string, online: boolean}`)\n  - `user.updated` (`User`)\n  - `room.created` (`Room`)\n  - `room.member_joined` (`{roomId, userId, username}`)\n  - `room.key_shared` (`{roomId, fromId}`)\n  - `message.new` (`{message: Message, clientTempId?: string}`)\n  - `message.updated` (`Message`)\n  - `message.deleted` (`{id: number, roomId: string}`)\n  - `typing` (`{roomId, userId, username}`)\n  - `read.updated` (`{roomId, userId, lastReadMessageId}`)\n"
  },
  "servers": [
    {
      "url": "https://chat.mitekbro.com",
      "description": "Production server (vps-2)"
    },
    {
      "url": "http://127.0.0.1:8080",
      "description": "Local development"
    }
  ],
  "tags": [
    {
      "name": "System",
      "description": "Health probes and OpenAPI specifications"
    },
    {
      "name": "Auth",
      "description": "Registration, sign-in, session inspection, and sign-out"
    },
    {
      "name": "Users & E2EE Keys",
      "description": "User directory, profile updates, and E2EE public/backup key management"
    },
    {
      "name": "Rooms & Channels",
      "description": "Public/private channels, 1:1 E2EE Direct Messages, membership, room keys, and read receipts"
    },
    {
      "name": "Messages & Reactions",
      "description": "Real-time messages, E2EE ciphertexts, replies, edits, deletions, reactions, and search"
    },
    {
      "name": "Attachments",
      "description": "Encrypted and standard file/image uploads and authenticated downloads"
    },
    {
      "name": "Realtime WebSocket",
      "description": "Persistent bidirectional WebSocket stream"
    }
  ],
  "paths": {
    "/health": {
      "get": {
        "tags": [
          "System"
        ],
        "summary": "Service and PostgreSQL health check",
        "operationId": "getHealth",
        "responses": {
          "200": {
            "description": "Service and database are healthy",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "status"
                  ],
                  "properties": {
                    "status": {
                      "type": "string",
                      "example": "ok"
                    }
                  }
                }
              }
            }
          },
          "503": {
            "description": "Database unavailable",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        }
      }
    },
    "/api/auth/register": {
      "post": {
        "tags": [
          "Auth"
        ],
        "summary": "Register a new user account and E2EE identity keypair",
        "operationId": "registerUser",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "username",
                  "password"
                ],
                "properties": {
                  "username": {
                    "type": "string",
                    "pattern": "^[a-zA-Z0-9_.-]{3,32}$",
                    "example": "alice"
                  },
                  "displayName": {
                    "type": "string",
                    "maxLength": 64,
                    "example": "Alice Nguyen"
                  },
                  "password": {
                    "type": "string",
                    "minLength": 8,
                    "maxLength": 128,
                    "example": "CorrectHorse#2026"
                  },
                  "publicKeyJwk": {
                    "$ref": "#/components/schemas/PublicJWK"
                  },
                  "encryptedPrivateKey": {
                    "type": "string",
                    "description": "Base64 AES-256-GCM encrypted private JWK (derived via PBKDF2-SHA256, 310k iterations)"
                  },
                  "keySalt": {
                    "type": "string",
                    "description": "Base64 16-byte PBKDF2 salt"
                  },
                  "keyIv": {
                    "type": "string",
                    "description": "Base64 12-byte AES-GCM IV"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Account created and session issued",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AuthResponse"
                }
              }
            }
          },
          "400": {
            "description": "Validation error or invalid P-256 public key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          },
          "409": {
            "description": "Username already taken",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          },
          "429": {
            "description": "Rate limit exceeded",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        }
      }
    },
    "/api/auth/login": {
      "post": {
        "tags": [
          "Auth"
        ],
        "summary": "Sign in with username and password",
        "operationId": "loginUser",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "username",
                  "password"
                ],
                "properties": {
                  "username": {
                    "type": "string",
                    "example": "alice"
                  },
                  "password": {
                    "type": "string",
                    "example": "CorrectHorse#2026"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Authenticated session token and user key vault bundle",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AuthResponse"
                }
              }
            }
          },
          "401": {
            "description": "Invalid credentials",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          },
          "429": {
            "description": "Too many login attempts",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        }
      }
    },
    "/api/auth/logout": {
      "post": {
        "tags": [
          "Auth"
        ],
        "summary": "Clear the HttpOnly authentication cookie",
        "operationId": "logoutUser",
        "responses": {
          "200": {
            "description": "Logged out",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "status": {
                      "type": "string",
                      "example": "logged_out"
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/api/auth/me": {
      "get": {
        "tags": [
          "Auth"
        ],
        "summary": "Get current authenticated user and E2EE key backup bundle",
        "operationId": "getCurrentUser",
        "security": [
          {
            "bearerAuth": []
          },
          {
            "cookieAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Current authenticated user",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "user"
                  ],
                  "properties": {
                    "user": {
                      "$ref": "#/components/schemas/SelfUser"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        }
      }
    },
    "/api/users": {
      "get": {
        "tags": [
          "Users & E2EE Keys"
        ],
        "summary": "Search workspace users and retrieve E2EE public keys",
        "operationId": "listUsers",
        "security": [
          {
            "bearerAuth": []
          },
          {
            "cookieAuth": []
          }
        ],
        "parameters": [
          {
            "name": "q",
            "in": "query",
            "description": "Case-insensitive username or display name filter",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Matching users with online status and E2EE public keys",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "users"
                  ],
                  "properties": {
                    "users": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/User"
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        }
      }
    },
    "/api/users/me": {
      "put": {
        "tags": [
          "Users & E2EE Keys"
        ],
        "summary": "Update current user's display name and status text",
        "operationId": "updateProfile",
        "security": [
          {
            "bearerAuth": []
          },
          {
            "cookieAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "displayName"
                ],
                "properties": {
                  "displayName": {
                    "type": "string",
                    "maxLength": 64,
                    "example": "Alice Nguyen"
                  },
                  "statusText": {
                    "type": "string",
                    "maxLength": 120,
                    "example": "Building Go services"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Updated user profile",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "user": {
                      "$ref": "#/components/schemas/SelfUser"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        }
      }
    },
    "/api/users/me/keys": {
      "put": {
        "tags": [
          "Users & E2EE Keys"
        ],
        "summary": "Upload or rotate current user's E2EE ECDH P-256 identity keypair",
        "operationId": "updateIdentityKeys",
        "security": [
          {
            "bearerAuth": []
          },
          {
            "cookieAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "publicKeyJwk",
                  "encryptedPrivateKey",
                  "keySalt",
                  "keyIv"
                ],
                "properties": {
                  "publicKeyJwk": {
                    "$ref": "#/components/schemas/PublicJWK"
                  },
                  "encryptedPrivateKey": {
                    "type": "string"
                  },
                  "keySalt": {
                    "type": "string"
                  },
                  "keyIv": {
                    "type": "string"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Keys validated and stored",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "user": {
                      "$ref": "#/components/schemas/SelfUser"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        }
      }
    },
    "/api/rooms": {
      "get": {
        "tags": [
          "Rooms & Channels"
        ],
        "summary": "List all channels and 1:1 DMs joined by the current user",
        "operationId": "listJoinedRooms",
        "security": [
          {
            "bearerAuth": []
          },
          {
            "cookieAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Joined rooms with unread counts, DM peers, and wrapped E2EE keys",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "rooms"
                  ],
                  "properties": {
                    "rooms": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/Room"
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        }
      },
      "post": {
        "tags": [
          "Rooms & Channels"
        ],
        "summary": "Create a public, private, or E2EE channel",
        "operationId": "createChannel",
        "security": [
          {
            "bearerAuth": []
          },
          {
            "cookieAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "name"
                ],
                "properties": {
                  "name": {
                    "type": "string",
                    "pattern": "^[a-z0-9][a-z0-9_-]{1,39}$",
                    "example": "engineering"
                  },
                  "topic": {
                    "type": "string",
                    "maxLength": 200,
                    "example": "Backend architecture and deployments"
                  },
                  "isPrivate": {
                    "type": "boolean",
                    "default": false
                  },
                  "isEncrypted": {
                    "type": "boolean",
                    "default": false
                  },
                  "memberIds": {
                    "type": "array",
                    "items": {
                      "type": "string",
                      "format": "uuid"
                    }
                  },
                  "wrappedKeys": {
                    "type": "array",
                    "items": {
                      "$ref": "#/components/schemas/RoomMemberKeyInput"
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Channel created",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "room": {
                      "$ref": "#/components/schemas/Room"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "409": {
            "description": "Channel name already exists",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        }
      }
    },
    "/api/rooms/discover": {
      "get": {
        "tags": [
          "Rooms & Channels"
        ],
        "summary": "Browse all public workspace channels",
        "operationId": "discoverPublicChannels",
        "security": [
          {
            "bearerAuth": []
          },
          {
            "cookieAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Discoverable public channels",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "rooms": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/Room"
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        }
      }
    },
    "/api/rooms/dm": {
      "post": {
        "tags": [
          "Rooms & Channels"
        ],
        "summary": "Get or create an idempotent 1:1 E2EE Direct Message room",
        "operationId": "getOrCreateDM",
        "security": [
          {
            "bearerAuth": []
          },
          {
            "cookieAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "peerId"
                ],
                "properties": {
                  "peerId": {
                    "type": "string",
                    "format": "uuid"
                  },
                  "wrappedKeys": {
                    "type": "array",
                    "items": {
                      "$ref": "#/components/schemas/RoomMemberKeyInput"
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Direct message room returned",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "room": {
                      "$ref": "#/components/schemas/Room"
                    },
                    "created": {
                      "type": "boolean"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Peer user not found",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        }
      }
    },
    "/api/rooms/{id}/join": {
      "post": {
        "tags": [
          "Rooms & Channels"
        ],
        "summary": "Join a public channel",
        "operationId": "joinPublicChannel",
        "security": [
          {
            "bearerAuth": []
          },
          {
            "cookieAuth": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/RoomId"
          }
        ],
        "responses": {
          "200": {
            "description": "Joined channel",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "room": {
                      "$ref": "#/components/schemas/Room"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          }
        }
      }
    },
    "/api/rooms/{id}/members": {
      "get": {
        "tags": [
          "Rooms & Channels"
        ],
        "summary": "List room members, presence, read state, and E2EE key status",
        "operationId": "listRoomMembers",
        "security": [
          {
            "bearerAuth": []
          },
          {
            "cookieAuth": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/RoomId"
          }
        ],
        "responses": {
          "200": {
            "description": "Room members",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "members": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/RoomMember"
                      }
                    }
                  }
                }
              }
            }
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          }
        }
      },
      "post": {
        "tags": [
          "Rooms & Channels"
        ],
        "summary": "Invite a user to a channel (with optional wrapped E2EE room key)",
        "operationId": "addRoomMember",
        "security": [
          {
            "bearerAuth": []
          },
          {
            "cookieAuth": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/RoomId"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "userId"
                ],
                "properties": {
                  "userId": {
                    "type": "string",
                    "format": "uuid"
                  },
                  "wrappedKey": {
                    "$ref": "#/components/schemas/RoomMemberKeyInput"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Member added",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "status": {
                      "type": "string",
                      "example": "added"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          }
        }
      }
    },
    "/api/rooms/{id}/keys": {
      "get": {
        "tags": [
          "Rooms & Channels"
        ],
        "summary": "Fetch the caller's wrapped E2EE room keys across all key versions",
        "operationId": "getMyRoomKeys",
        "security": [
          {
            "bearerAuth": []
          },
          {
            "cookieAuth": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/RoomId"
          }
        ],
        "responses": {
          "200": {
            "description": "Wrapped room keys for the authenticated user",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "keys": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/RoomMemberKey"
                      }
                    }
                  }
                }
              }
            }
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          }
        }
      },
      "post": {
        "tags": [
          "Rooms & Channels"
        ],
        "summary": "Store ECDH-wrapped E2EE room keys for room members",
        "operationId": "saveWrappedRoomKeys",
        "security": [
          {
            "bearerAuth": []
          },
          {
            "cookieAuth": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/RoomId"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "wrappedKeys"
                ],
                "properties": {
                  "wrappedKeys": {
                    "type": "array",
                    "items": {
                      "$ref": "#/components/schemas/RoomMemberKeyInput"
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Wrapped keys saved and recipients notified via WebSocket",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "status": {
                      "type": "string",
                      "example": "saved"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          }
        }
      }
    },
    "/api/rooms/{id}/read": {
      "post": {
        "tags": [
          "Rooms & Channels"
        ],
        "summary": "Mark room messages read up to a given message ID",
        "operationId": "markRoomRead",
        "security": [
          {
            "bearerAuth": []
          },
          {
            "cookieAuth": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/RoomId"
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "messageId": {
                    "type": "integer",
                    "format": "int64"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Updated read watermark",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "lastReadMessageId": {
                      "type": "integer",
                      "format": "int64"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          }
        }
      }
    },
    "/api/rooms/{id}/messages": {
      "get": {
        "tags": [
          "Messages & Reactions"
        ],
        "summary": "List room messages in chronological order (cursor pagination)",
        "operationId": "listRoomMessages",
        "security": [
          {
            "bearerAuth": []
          },
          {
            "cookieAuth": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/RoomId"
          },
          {
            "name": "before",
            "in": "query",
            "description": "Return messages with ID strictly less than this cursor",
            "schema": {
              "type": "integer",
              "format": "int64"
            }
          },
          {
            "name": "limit",
            "in": "query",
            "description": "Number of messages to fetch (1-100, default 50)",
            "schema": {
              "type": "integer",
              "default": 50
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Chronological message page",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "messages": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/Message"
                      }
                    }
                  }
                }
              }
            }
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          }
        }
      },
      "post": {
        "tags": [
          "Messages & Reactions"
        ],
        "summary": "Send a message (plaintext in public channels, AES-256-GCM ciphertext in E2EE rooms)",
        "operationId": "createMessage",
        "security": [
          {
            "bearerAuth": []
          },
          {
            "cookieAuth": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/RoomId"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "content": {
                    "type": "string",
                    "description": "Plaintext content (must be empty when isEncrypted is true)"
                  },
                  "isEncrypted": {
                    "type": "boolean",
                    "default": false
                  },
                  "ciphertext": {
                    "type": "string",
                    "description": "Base64 AES-256-GCM ciphertext (required when isEncrypted is true)"
                  },
                  "iv": {
                    "type": "string",
                    "description": "Base64 12-byte AES-GCM nonce (required when isEncrypted is true)"
                  },
                  "keyVersion": {
                    "type": "integer",
                    "default": 1
                  },
                  "replyToId": {
                    "type": "integer",
                    "format": "int64",
                    "nullable": true
                  },
                  "attachmentId": {
                    "type": "string",
                    "format": "uuid",
                    "nullable": true
                  },
                  "clientTempId": {
                    "type": "string",
                    "description": "Optional client correlation token echoed in WebSocket `message.new`"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Message stored and broadcast via WebSocket",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "message": {
                      "$ref": "#/components/schemas/Message"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          }
        }
      }
    },
    "/api/messages/{id}": {
      "patch": {
        "tags": [
          "Messages & Reactions"
        ],
        "summary": "Edit own message",
        "operationId": "editMessage",
        "security": [
          {
            "bearerAuth": []
          },
          {
            "cookieAuth": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/MessageId"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "content": {
                    "type": "string"
                  },
                  "ciphertext": {
                    "type": "string"
                  },
                  "iv": {
                    "type": "string"
                  },
                  "keyVersion": {
                    "type": "integer",
                    "default": 1
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Edited message",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "message": {
                      "$ref": "#/components/schemas/Message"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          }
        }
      },
      "delete": {
        "tags": [
          "Messages & Reactions"
        ],
        "summary": "Delete own message and scrub stored content/ciphertext",
        "operationId": "deleteMessage",
        "security": [
          {
            "bearerAuth": []
          },
          {
            "cookieAuth": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/MessageId"
          }
        ],
        "responses": {
          "200": {
            "description": "Soft-deleted message",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "message": {
                      "$ref": "#/components/schemas/Message"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          }
        }
      }
    },
    "/api/messages/{id}/reactions": {
      "post": {
        "tags": [
          "Messages & Reactions"
        ],
        "summary": "Toggle an emoji reaction on a message",
        "operationId": "toggleReaction",
        "security": [
          {
            "bearerAuth": []
          },
          {
            "cookieAuth": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/MessageId"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "emoji"
                ],
                "properties": {
                  "emoji": {
                    "type": "string",
                    "example": "\ud83d\ude80"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Updated message with aggregated reactions",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "message": {
                      "$ref": "#/components/schemas/Message"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          }
        }
      }
    },
    "/api/messages/search": {
      "get": {
        "tags": [
          "Messages & Reactions"
        ],
        "summary": "Full-text search across non-encrypted rooms the user belongs to",
        "operationId": "searchMessages",
        "security": [
          {
            "bearerAuth": []
          },
          {
            "cookieAuth": []
          }
        ],
        "parameters": [
          {
            "name": "q",
            "in": "query",
            "required": true,
            "description": "Search query (PostgreSQL `websearch_to_tsquery`)",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "roomId",
            "in": "query",
            "required": false,
            "description": "Optional room UUID to scope search",
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Matching plaintext messages (E2EE messages are never indexed server-side)",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "messages": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/Message"
                      }
                    }
                  }
                }
              }
            }
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          }
        }
      }
    },
    "/api/uploads": {
      "post": {
        "tags": [
          "Attachments"
        ],
        "summary": "Upload a file or client-encrypted E2EE blob to a room",
        "operationId": "uploadAttachment",
        "security": [
          {
            "bearerAuth": []
          },
          {
            "cookieAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "multipart/form-data": {
              "schema": {
                "type": "object",
                "required": [
                  "roomId",
                  "file"
                ],
                "properties": {
                  "roomId": {
                    "type": "string",
                    "format": "uuid"
                  },
                  "isEncrypted": {
                    "type": "string",
                    "enum": [
                      "true",
                      "false"
                    ],
                    "description": "Must be `\"true\"` when uploading to an E2EE room"
                  },
                  "file": {
                    "type": "string",
                    "format": "binary"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Attachment stored",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "attachment": {
                      "$ref": "#/components/schemas/Attachment"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "413": {
            "description": "File exceeds maximum upload size (default 20 MB)",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        }
      }
    },
    "/api/uploads/{id}": {
      "get": {
        "tags": [
          "Attachments"
        ],
        "summary": "Download an attachment (requires membership in the upload's room)",
        "operationId": "downloadAttachment",
        "security": [
          {
            "bearerAuth": []
          },
          {
            "cookieAuth": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Raw file stream or encrypted ciphertext bytes",
            "content": {
              "application/octet-stream": {
                "schema": {
                  "type": "string",
                  "format": "binary"
                }
              }
            }
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          }
        }
      }
    },
    "/api/ws": {
      "get": {
        "tags": [
          "Realtime WebSocket"
        ],
        "summary": "Upgrade connection to real-time WebSocket stream",
        "operationId": "connectWebSocket",
        "security": [
          {
            "bearerAuth": []
          },
          {
            "cookieAuth": []
          }
        ],
        "parameters": [
          {
            "name": "token",
            "in": "query",
            "required": false,
            "description": "Optional JWT when connecting without cookies/headers",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "101": {
            "description": "Switching Protocols to WebSocket"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "JWT"
      },
      "cookieAuth": {
        "type": "apiKey",
        "in": "cookie",
        "name": "dpchat_token"
      }
    },
    "parameters": {
      "RoomId": {
        "name": "id",
        "in": "path",
        "required": true,
        "description": "Room UUID",
        "schema": {
          "type": "string",
          "format": "uuid"
        }
      },
      "MessageId": {
        "name": "id",
        "in": "path",
        "required": true,
        "description": "Monotonic 64-bit message ID",
        "schema": {
          "type": "integer",
          "format": "int64"
        }
      }
    },
    "responses": {
      "BadRequest": {
        "description": "Invalid request input",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorResponse"
            }
          }
        }
      },
      "Unauthorized": {
        "description": "Missing or invalid authentication token",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorResponse"
            }
          }
        }
      },
      "Forbidden": {
        "description": "Caller does not have permission for this resource",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorResponse"
            }
          }
        }
      },
      "NotFound": {
        "description": "Resource not found",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorResponse"
            }
          }
        }
      }
    },
    "schemas": {
      "ErrorResponse": {
        "type": "object",
        "required": [
          "error"
        ],
        "properties": {
          "error": {
            "type": "string",
            "example": "authentication required"
          }
        }
      },
      "PublicJWK": {
        "type": "object",
        "required": [
          "kty",
          "crv",
          "x",
          "y"
        ],
        "properties": {
          "kty": {
            "type": "string",
            "const": "EC"
          },
          "crv": {
            "type": "string",
            "const": "P-256"
          },
          "x": {
            "type": "string",
            "description": "Base64url-encoded 32-byte X coordinate"
          },
          "y": {
            "type": "string",
            "description": "Base64url-encoded 32-byte Y coordinate"
          }
        }
      },
      "User": {
        "type": "object",
        "required": [
          "id",
          "username",
          "displayName",
          "avatarColor",
          "statusText",
          "online",
          "createdAt",
          "lastSeenAt"
        ],
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "username": {
            "type": "string"
          },
          "displayName": {
            "type": "string"
          },
          "avatarColor": {
            "type": "string",
            "example": "#6366f1"
          },
          "statusText": {
            "type": "string"
          },
          "publicKeyJwk": {
            "$ref": "#/components/schemas/PublicJWK"
          },
          "keyFingerprint": {
            "type": "string",
            "example": "48291 03948 19283 77412 90124 55310 66219 00418"
          },
          "online": {
            "type": "boolean"
          },
          "createdAt": {
            "type": "string",
            "format": "date-time"
          },
          "lastSeenAt": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "SelfUser": {
        "allOf": [
          {
            "$ref": "#/components/schemas/User"
          },
          {
            "type": "object",
            "properties": {
              "encryptedPrivateKey": {
                "type": "string"
              },
              "keySalt": {
                "type": "string"
              },
              "keyIv": {
                "type": "string"
              }
            }
          }
        ]
      },
      "AuthResponse": {
        "type": "object",
        "required": [
          "token",
          "user"
        ],
        "properties": {
          "token": {
            "type": "string"
          },
          "user": {
            "$ref": "#/components/schemas/SelfUser"
          }
        }
      },
      "UserSummary": {
        "type": "object",
        "required": [
          "id",
          "username",
          "displayName",
          "avatarColor"
        ],
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "username": {
            "type": "string"
          },
          "displayName": {
            "type": "string"
          },
          "avatarColor": {
            "type": "string"
          },
          "keyFingerprint": {
            "type": "string"
          }
        }
      },
      "RoomMemberKeyInput": {
        "type": "object",
        "required": [
          "userId",
          "wrappedKey",
          "ephemeralPubJwk",
          "iv"
        ],
        "properties": {
          "userId": {
            "type": "string",
            "format": "uuid"
          },
          "keyVersion": {
            "type": "integer",
            "default": 1
          },
          "wrappedKey": {
            "type": "string",
            "description": "Base64 AES-256-GCM encrypted 32-byte room key"
          },
          "ephemeralPubJwk": {
            "$ref": "#/components/schemas/PublicJWK"
          },
          "iv": {
            "type": "string",
            "description": "Base64 12-byte AES-GCM IV"
          }
        }
      },
      "RoomMemberKey": {
        "allOf": [
          {
            "$ref": "#/components/schemas/RoomMemberKeyInput"
          },
          {
            "type": "object",
            "properties": {
              "roomId": {
                "type": "string",
                "format": "uuid"
              },
              "wrappedBy": {
                "type": "string"
              },
              "createdAt": {
                "type": "string",
                "format": "date-time"
              }
            }
          }
        ]
      },
      "Room": {
        "type": "object",
        "required": [
          "id",
          "kind",
          "name",
          "topic",
          "isPrivate",
          "isEncrypted",
          "memberCount",
          "unreadCount",
          "lastReadMessageId",
          "createdAt"
        ],
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "kind": {
            "type": "string",
            "enum": [
              "channel",
              "dm"
            ]
          },
          "name": {
            "type": "string"
          },
          "topic": {
            "type": "string"
          },
          "isPrivate": {
            "type": "boolean"
          },
          "isEncrypted": {
            "type": "boolean"
          },
          "role": {
            "type": "string",
            "enum": [
              "owner",
              "admin",
              "member",
              ""
            ]
          },
          "memberCount": {
            "type": "integer"
          },
          "unreadCount": {
            "type": "integer"
          },
          "lastReadMessageId": {
            "type": "integer",
            "format": "int64"
          },
          "peerUser": {
            "$ref": "#/components/schemas/User"
          },
          "myWrappedKey": {
            "$ref": "#/components/schemas/RoomMemberKey"
          },
          "createdBy": {
            "type": "string"
          },
          "createdAt": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "RoomMember": {
        "allOf": [
          {
            "$ref": "#/components/schemas/User"
          },
          {
            "type": "object",
            "required": [
              "role",
              "lastReadMessageId",
              "hasRoomKey",
              "joinedAt"
            ],
            "properties": {
              "role": {
                "type": "string"
              },
              "lastReadMessageId": {
                "type": "integer",
                "format": "int64"
              },
              "hasRoomKey": {
                "type": "boolean"
              },
              "joinedAt": {
                "type": "string",
                "format": "date-time"
              }
            }
          }
        ]
      },
      "Attachment": {
        "type": "object",
        "required": [
          "id",
          "roomId",
          "uploaderId",
          "fileName",
          "mimeType",
          "sizeBytes",
          "isEncrypted",
          "url",
          "createdAt"
        ],
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "roomId": {
            "type": "string",
            "format": "uuid"
          },
          "uploaderId": {
            "type": "string",
            "format": "uuid"
          },
          "fileName": {
            "type": "string"
          },
          "mimeType": {
            "type": "string"
          },
          "sizeBytes": {
            "type": "integer",
            "format": "int64"
          },
          "isEncrypted": {
            "type": "boolean"
          },
          "url": {
            "type": "string",
            "example": "/api/uploads/550e8400-e29b-41d4-a716-446655440000"
          },
          "createdAt": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "ReactionGroup": {
        "type": "object",
        "required": [
          "emoji",
          "count",
          "userIds"
        ],
        "properties": {
          "emoji": {
            "type": "string"
          },
          "count": {
            "type": "integer"
          },
          "userIds": {
            "type": "array",
            "items": {
              "type": "string",
              "format": "uuid"
            }
          }
        }
      },
      "ReplyPreview": {
        "type": "object",
        "required": [
          "id",
          "senderId",
          "senderUsername",
          "senderDisplayName",
          "isEncrypted",
          "hasAttachment",
          "deleted"
        ],
        "properties": {
          "id": {
            "type": "integer",
            "format": "int64"
          },
          "senderId": {
            "type": "string",
            "format": "uuid"
          },
          "senderUsername": {
            "type": "string"
          },
          "senderDisplayName": {
            "type": "string"
          },
          "content": {
            "type": "string"
          },
          "isEncrypted": {
            "type": "boolean"
          },
          "ciphertext": {
            "type": "string"
          },
          "iv": {
            "type": "string"
          },
          "keyVersion": {
            "type": "integer"
          },
          "hasAttachment": {
            "type": "boolean"
          },
          "deleted": {
            "type": "boolean"
          }
        }
      },
      "Message": {
        "type": "object",
        "required": [
          "id",
          "roomId",
          "sender",
          "content",
          "isEncrypted",
          "keyVersion",
          "reactions",
          "deleted",
          "createdAt"
        ],
        "properties": {
          "id": {
            "type": "integer",
            "format": "int64"
          },
          "roomId": {
            "type": "string",
            "format": "uuid"
          },
          "roomName": {
            "type": "string"
          },
          "sender": {
            "$ref": "#/components/schemas/UserSummary"
          },
          "content": {
            "type": "string"
          },
          "isEncrypted": {
            "type": "boolean"
          },
          "ciphertext": {
            "type": "string"
          },
          "iv": {
            "type": "string"
          },
          "keyVersion": {
            "type": "integer"
          },
          "replyToId": {
            "type": "integer",
            "format": "int64"
          },
          "replyPreview": {
            "$ref": "#/components/schemas/ReplyPreview"
          },
          "attachment": {
            "$ref": "#/components/schemas/Attachment"
          },
          "reactions": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ReactionGroup"
            }
          },
          "editedAt": {
            "type": "string",
            "format": "date-time"
          },
          "deleted": {
            "type": "boolean"
          },
          "createdAt": {
            "type": "string",
            "format": "date-time"
          }
        }
      }
    }
  }
}