# WebSocket sessions

Phantom records WebSocket sessions that pass through the proxy: the
upgrade handshake as a flow of kind `websocket`, a session summary, and
every message in both directions with its metadata. Sessions can be
read and exported over REST, read by agents over MCP, and travel in HAR
files (`_webSocketMessages`).

Code: `backend/app/core/websocket/` (pure parsing, limits, inflation),
`backend/app/core/proxy/handler/ws_capture.py` and
`backend/app/core/proxy/transport/websocket.py` (relay paths),
`backend/app/runtime/ws_writer.py` and `ws_handle.py` (batched writes,
events), `backend/app/services/websocket/`, `backend/app/api/v1/websocket.py`,
`backend/app/mcp/tools/websocket.py`.

## Model

| Table | What it holds |
| --- | --- |
| `proxy_flows.kind` | `http` for every exchange, `websocket` for the handshake of a session (status 101). |
| `ws_sessions` | One summary per session: messages recorded per direction, payload bytes on the wire per direction, `stored_bytes`, `dropped_frames`, negotiated `extensions` and `protocol`, `opened_at`, `closed_at`, first close frame (`close_code`, `close_reason`, `closed_by`), and `error` when frame parsing stopped. |
| `ws_frames` | One row per message: `seq` (from 1, across both directions), `direction` (`client` = browser to server, `server`), numeric `opcode` (1 text, 2 binary, 8 close, 9 ping, 10 pong), `payload`, `size`, `wire_size`, `truncated`, `masked`, `compressed`, `inflated`, `fragments`, `close_code`, `close_reason`, `observed_at`. Unique on (`flow_id`, `seq`). |

A text or binary message split over several frames is one row
(`fragments` counts them); control frames between its fragments are rows
of their own. Payloads are stored unmasked. A message sent with
permessage-deflate is stored inflated (`compressed` and `inflated` true);
one that could not be inflated is kept as sent (`inflated` false).
`size` is the payload length (inflated length when inflated),
`wire_size` the bytes on the wire.

Both tables cascade from the flow (ON DELETE CASCADE), so deleting a
flow, pruning, clearing a vault's history or deleting the vault removes
the frames. Annotations belong to the flow and are deleted with it as
before.

Migration `c6d2a8f4e1b9` (after `b9e3f1a7c5d2`) is additive: it adds
`proxy_flows.kind` (`http` for existing rows) and the two tables.

## Capture

| Path | How frames are read |
| --- | --- |
| `wss://` inside a CONNECT tunnel | After `101 Switching Protocols` the decrypted bytes are piped untouched; a copy of each chunk goes to an incremental RFC 6455 parser per direction (`FrameParser`). The relay never waits for the parser. permessage-deflate is inflated per direction with the negotiated context rules. |
| `ws://` and absolute `wss://` on the plain path | aiohttp opens the upstream connection first (a refused or failed handshake answers the client with 502 and is recorded as a failed HTTP flow), then answers the client and relays message by message. Automatic ping answers and close handling are off, so pings, pongs and close codes travel end to end. Messages are recorded as they crossed the upstream connection. Both close frames are stored: a client close with its code and reason, then the server's reply with its code (aiohttp does not expose the reason of a reply); when the server starts the close handshake, its close is relayed to the client and the close the proxy sends back upstream is recorded as the client's. A session the proxy ends itself (the proxy stops or restarts, a peer goes away without a close, a close is not answered within 10 s) ends the peers still open with `1001` and the reason `Phantom proxy stopped` or `Peer went away`; those frames are recorded in the direction they travel (towards the server first), so the summary has a code, reason and side instead of none. aiohttp's 4 MiB message limit applies on this path. |

The handshake is recorded through the normal capture pipeline, so the
capture filter applies to it: a skipped handshake records no frames, and
the session is only counted as skipped. Without a capture vault nothing is
recorded.

### Limits

| Limit | Setting (`PUT /api/v1/proxy/capture`) | Default | Bounds |
| --- | --- | --- | --- |
| Bytes kept per message | `max_body_bytes` (shared with bodies) | `PROXY_BODY_LIMIT` (512 KiB) | 1 KiB to 64 MiB |
| Messages recorded per session | `ws_max_frames` | 10,000 | 1 to 1,000,000 |
| Payload bytes stored per session | `ws_max_bytes` | 32 MiB | 0 to 4 GiB |
| Memory held by payloads waiting to be written | `memory_budget_bytes` (shared with bodies) | 128 MiB | 1 MiB to 4 GiB |

A payload past the per-message limit keeps its first bytes and is flagged
`truncated` with its full `size`. Once a session has stored `ws_max_bytes`,
later messages are still recorded with their metadata but an empty
payload (`truncated`). Past `ws_max_frames`, messages are only counted in
`dropped_frames` and in the capture counter `ws_dropped_frames`. A
payload the memory budget cannot hold is cut like a body and counted in
`budget_truncations`. Fixed bounds: a compressed message inflates to at
most 16 MiB (beyond that inflation stops for its direction and later
compressed messages are kept as sent); at most 50,000 messages wait to be
written across all sessions.

### Writes and events

Messages are written in batches by one background writer: every 250 ms,
or sooner once 500 are pending, one transaction inserts the pending
frames of every session and refreshes their summaries. A session whose
flow was deleted meanwhile stops recording.

| Event | Data | When |
| --- | --- | --- |
| `proxy.flow` | Flow summary with `kind: websocket` | Handshake stored |
| `proxy.ws.frames` | `{flow_id, count, last_seq, total}` (`count` = frames stored since the previous event) | At most every 500 ms per session |
| `proxy.ws.closed` | `{flow_id, close_code, close_reason, closed_by, client_frames, server_frames, dropped_frames, error}` | Once, after the session ended and everything was written |

## REST

| Route | Returns |
| --- | --- |
| `GET /vaults/{id}/flows?kind=websocket` | Sessions only; every summary carries `kind` and, for a session, `websocket` (the `ws_sessions` summary). `kind=http` leaves sessions out. Flow detail carries the same summary. |
| `GET /vaults/{id}/flows/{flow_id}/frames` | `{flow_id, frames, next_after_seq}`. Parameters: `after_seq` (cursor), `limit` (1 to 1,000, default 200), `direction` and `opcode` (repeatable), `search` (case-insensitive substring of the stored payload; ASCII case folding on SQLite). Each payload shows its first 4 KiB. |
| `GET /vaults/{id}/flows/{flow_id}/frames/{seq}` | One frame with its whole stored payload. |
| `GET /vaults/{id}/flows/{flow_id}/frames/export.jsonl` | One JSON object per frame (`application/x-ndjson`, attachment), with the list filters. |

Payloads are `{encoding, content, kind, bytes, clipped}`: UTF-8 text when
the bytes are valid UTF-8 (`kind: text`), otherwise base64
(`kind: binary`). A frame or session that is not in the vault, or a flow
that is not a session, is 404.

Like flow detail, list and frame reads return stored values (the
interface masks them for display). The export follows the export
redaction policy exactly like body downloads and HAR: masked by default
(JSON payloads field by field, text and binary by format, close reasons),
`ask` needs `reveal=true|false` (409 without), `redact` refuses
`reveal=true` (403); `X-Phantom-Redacted` says which was served.

## MCP

| Tool | Notes |
| --- | --- |
| `ws_frames_list` | `vault_id`, `flow_id`, `after_seq`, `limit` (up to 200), `direction`, `opcodes`, `search`, `max_payload_chars` (default 2,000). |
| `ws_frame_get` | `vault_id`, `flow_id`, `seq`, `max_payload_chars` (default 64 Ki, up to 1 Mi). |
| `flow_list` | Takes `kind`; sessions carry their `websocket` summary. |

Results pass through the MCP redaction policy; redaction runs on the whole
stored payload before it is clipped, so a secret crossing the cut stays
masked. `reveal_secrets` is honoured only when the user allowed it.

## HAR

Export writes, for each session, `_resourceType: "websocket"` and
`_webSocketMessages` (Chrome's extension): `{type, time, opcode, data,
_phantom}` with `type` `send` (client) or `receive` (server), `time` in
epoch seconds, `data` as text for text messages and base64 for every
other opcode (a text message that is not UTF-8 is base64 with
`_phantom.encoding: "base64"`). `_phantom` per message holds `seq`,
sizes, flags and close code/reason; the entry's `_phantom.websocket`
holds the session summary and `messages_written`. A REST export writes up
to 50,000 messages per session; an MCP export up to 100, each clipped to
`max_body_bytes` (`_phantom.clipped`). Redaction follows the export (REST)
or MCP policy.

Import reads `_webSocketMessages` from Phantom and browser files (`ws://`
and `wss://` URLs are stored as `http`/`https`); a 101 websocket upgrade
without messages is imported as a session with no frames. Items that are
not messages are skipped. Payloads keep the capture body limit and each
session at most `ws_max_frames` messages and `ws_max_bytes` payload
bytes, like captured ones.

## Retention

Stored bytes are body bytes plus frame payload bytes
(`ws_sessions.stored_bytes`): `GET /flows/stats` reports `frame_bytes`
and `websocket_sessions`, includes frame bytes in `body_bytes`, and the
retention `max_body_bytes` limit and prune results count them. Pruning a
session deletes its frames.

## Interface

Code: `frontend/src/components/proxy/websocket/`, `composables/useWsFrames.ts`,
`utils/websocket.ts`.

- **History:** a session shows a `WS` chip instead of the method (its
  tooltip gives the state and the messages and bytes per direction), its
  message count as the type and its stored bytes as the size. The Type
  filter (All, HTTP, WebSocket) sends `kind=` to the backend.
- **Messages tab:** next to Request and Response, opened by default for a
  session. The header shows open (with a live duration) or closed (close
  code, reason, who closed), messages and bytes per direction, stored
  bytes, dropped messages, extensions, subprotocol and any capture error.
  The list is virtualized and paged 200 at a time: ↑ client to server and
  ↓ server to client in distinct colours, opcode chip, one-line preview
  (masked), size, time since the session opened, and markers for
  truncated, compressed and fragmented messages. Filters (direction,
  message types, payload search) run on the backend. While a session is
  open, `proxy.ws.frames` fetches the messages after the last one loaded,
  and `proxy.ws.closed` updates the header and the history row.
- **Payload:** the selected message opens in the shared message viewer
  below a draggable divider: text, JSON pretty-printed, binary messages in
  the hex view (also when their bytes happen to be valid UTF-8), secrets
  masked until revealed, and selections addable to payload collections. A
  message the list showed clipped is fetched whole when opened.
- **Export:** "Export" downloads the messages with the current filters as
  JSON lines under the export redaction policy, like the HAR menu: "Secrets
  masked" always, "As captured" only when the policy allows; the export is
  probed first so a 409 or 403 shows as a toast.
- **Settings:** Proxy → Settings → WebSocket sessions edits `ws_max_frames`
  and `ws_max_bytes` (defaults are sent as null so they keep following
  the backend) and shows `ws_dropped_frames`; the storage card adds frame
  bytes and the session count.

## Not yet

- No intercept or edit of WebSocket messages, and no replay of a session.
- Saved views and HAR export filters do not take `kind`.
- MCP resources do not list sessions; `proxy.ws.*` events are not
  forwarded to MCP listen streams.
