# HAR import and export

Phantom reads and writes HTTP history as [HAR 1.2](http://www.softwareishard.com/blog/har-12-spec/).
Exports follow the export redaction policy, exactly like body downloads
([HTTP history](history.md#body-download)). Imports are checked
entry by entry and stored as flows with `source: import`.

Code: `backend/app/core/har/` (pure parse and build),
`backend/app/services/har/` (export, import), `backend/app/api/v1/har.py`,
`backend/app/mcp/tools/flow_har.py`.

## Export

`GET /api/v1/vaults/{vault_id}/flows/export.har`

| Parameter | Meaning |
| --- | --- |
| `host`, `method`, `status_class`, `tag` (repeatable), `in_scope`, `search`, `bookmarked`, `view_id` | The filters of `GET /flows` ([Research annotations](../annotations.md)); all must hold. |
| `ids` (repeatable, up to 1,000) | Export a selection. Ids of other vaults are ignored. |
| `decoded` (default `true`) | Bodies without content codings, as HAR viewers expect. `false` writes the stored bytes, base64 when they are still coded. |
| `reveal` | The user's choice under the export policy (see below). |

The response is streamed (`application/json`), oldest flow first, read
from the database 50 flows at a time; the whole history is never held in
memory. Headers: `Content-Disposition: attachment;
filename="phantom-<vault>-<YYYY-MM-DD>.har"`, `X-Content-Type-Options:
nosniff`, `Cache-Control: no-store`, `X-Phantom-Redacted: true|false`,
`X-Phantom-Entries: <count>`.

At most **50,000** flows per export. A larger selection is refused with
422 `invalid_value` (`details: {limit, matching}`) before anything is
streamed; narrow it with filters, a saved view or ids. Flows captured
while an export streams are not included.

### Redaction

| Export policy | Export |
| --- | --- |
| `redact` (default) | Credentials masked in the URL, headers (cookie names kept), bodies (the shared body redactor, JSON field by field) and flow errors. `queryString` and `cookies` are derived from the masked values. Coded bodies are written decoded, because coded bytes cannot be masked. `reveal=true` is refused with 403. |
| `reveal` | Stored values. `reveal=false` masks this one export. |
| `ask` | 409 `conflict` until the request says `reveal=true` or `reveal=false`. |

`log._phantom.redacted` repeats the decision inside the file.

### Mapping

| HAR | From |
| --- | --- |
| `log.creator` | `{name: "Phantom", version}` |
| `log._phantom` | `{vault_id, exported_at, redacted, decoded}` |
| `startedDateTime` | recorded time minus `time` (Phantom records a flow when it ends) |
| `time`, `timings.wait` | `duration_ms`; `send` and `receive` are 0 |
| `request.method`, `url`, `httpVersion`, `headers` | stored values, headers in order with duplicates |
| `request.queryString`, `cookies` | derived from the URL and `Cookie` headers |
| `request.postData` | `{mimeType, params, text}`, plus `encoding: "base64"` for binary or non-UTF-8 bodies; `params` for urlencoded forms |
| `request.bodySize` | size on the wire; `headersSize` is -1 |
| `response.status`, `statusText` | status code and its standard reason phrase; status 0 without a response |
| `response.cookies` | derived from `Set-Cookie` headers |
| `response.content` | `{size, mimeType, text, encoding?}`; `size` is the length of the written bytes |
| `response.redirectURL` | `Location` header |
| `response.bodySize` | size on the wire |
| `cache` | `{}` |
| `comment`, `content.comment` | set when a body is incomplete (truncated by the capture limit, decoding limit, or MCP clipping) |
| `_phantom` | `{flow_id, source, in_scope, bookmarked, tags (names), truncated {request, response}, decoded {request, response}, intercepted, edited, error, import_batch}`; MCP exports add `clipped` |


## Review before export

Every HAR export, from the history menu or a row menu, first opens a
review of what it would carry. Phantom reads the selected requests (at
most 5,000) and finds credentials in their URLs, headers and stored
bodies with the shared detector. The review counts them by kind and by
part and lists the requests that hold them. A masked export masks them.
An export as recorded names how many leave the machine and needs an
explicit tick. Compressed bodies are read as stored
(`GET /flows/export.har/review` with the export's filters or `ids`;
nothing is exported).

## Import

`POST /api/v1/vaults/{vault_id}/flows/import`, multipart form with the
file in field `file`. Options are query parameters:

| Parameter | Meaning |
| --- | --- |
| `dry_run` (default `false`) | Check and count only; nothing is stored. |
| `in_scope_only` (default `false`) | Import only entries the vault scope allows. |
| `preview` (0-200, default 20) | Entry summaries to return. |

Multipart was chosen over a JSON body with base64 so a 50 MiB file is not
inflated by a third and parsed twice. The interface sends
`FormData` with `file`.

Response (`HarImportResult`), the same for a dry run and an import:

```json
{
  "dry_run": false,
  "entries": 5, "valid": 3, "skipped": 2,
  "skip_reasons": {"request.url is missing": 1, "response body is not valid base64": 1},
  "skipped_entries": [{"index": 2, "reason": "request.url is missing"}],
  "in_scope": 2, "out_of_scope": 1, "imported": 3,
  "hosts": [{"host": "a.test", "count": 2, "in_scope": true}],
  "bytes": 2048, "body_bytes": 17, "truncated_bodies": 0,
  "redacted_source": false,
  "creator": {"name": "Firefox", "version": "120"},
  "batch": "3f2a...",
  "preview": [{"index": 0, "method": "GET", "url": "https://a.test/", "host": "a.test",
               "status_code": 200, "in_scope": true, "started_at": "...", "duration_ms": 42,
               "request_bytes": 0, "response_bytes": 5, "mime_type": "text/plain", "truncated": false}]
}
```

`imported` is the number of flows stored, or that a dry run would store.
`redacted_source` is true for a redacted Phantom export: its masked
values are placeholders, not credentials, and replaying them sends the
placeholders. `batch` is null on a dry run or when nothing was stored.

### Validation

The whole file is refused with 422 `invalid_value` when it is larger than
**50 MiB**, is not JSON (`details.reason: invalid_json`), has no
`log.entries` array (`not_har`), or has more than **50,000** entries.
Otherwise each entry is checked on its own and skipped with a reason when
it fails. Reasons never repeat the rejected value.

Required per entry: `startedDateTime` (ISO 8601), `request.method` (an
HTTP token), `request.url` (absolute http/https with a host and a valid
port), `request.headers` and `response.headers` (arrays of `{name, value}`
strings, at most 500, names up to 256 and values up to 64 KiB characters,
no CR, LF or NUL), and `response.status` (0-999; 0 means no response).
`postData` and `content` are optional; `text` is read as UTF-8, or as
base64 when `encoding` is `base64` (other encodings are refused).

Nothing in a file is executed, fetched or sent. Entries are only copied.

### Stored values

- `source: import`, `import_batch` (the import's id, on flow summaries).
- `created_at` is the entry's end (`startedDateTime + time`), so the
  original times are kept; flows are inserted in that order.
- `in_scope` uses the vault's scope at import time.
- Headers keep their order and duplicates.
- Bodies are kept up to `PROXY_BODY_LIMIT` like captured traffic, with the
  original size and the truncation flag; a body a Phantom export marked
  truncated stays marked. `request_size` / `response_size` come from
  `bodySize` when it is positive.
- `intercepted`, `edited` and the error of a Phantom export are restored;
  an entry without a response keeps `_phantom.error`, a browser's
  `_error`, or "No response was recorded in the HAR file".
- The import is one transaction and is announced by one
  `proxy.imported {count, batch, actor}` event, not one `proxy.flow` per
  entry. The MCP `phantom://vault/{id}/flows/recent` resource updates.

## WebSocket sessions

A session's entry carries `_resourceType: "websocket"` and its messages in
`_webSocketMessages` (Chrome's extension), redacted like bodies; import
reads them back from Phantom and browser files, within the capture limits.
The mapping is in [WebSocket sessions](websocket.md#har).

## MCP

- `flow_export_har` returns the newest `limit` matching flows (1-100,
  default 20) as a HAR document, oldest first, with the `flow_list`
  filters and `ids`. Each body keeps at most `max_body_bytes` (default
  16 KiB, up to 256 KiB); `_phantom.clipped` and `comment` mark cut
  bodies, `log._phantom.more` says more flows matched. It is redacted by
  the **MCP** policy (and honours `reveal_secrets` only when the user
  allows it), never by the export policy.
- `flow_import_har` takes the file as `content` text with `dry_run`,
  `in_scope_only` and `preview` (up to 50). The import event records
  `actor: agent`. Preview URLs are masked by the MCP policy.

## Interface

In Proxy > History (`components/proxy/har/`):

- **HAR menu** in the toolbar. Export covers the selected rows when several
  are selected (by `ids`), otherwise every request matching the current
  filters (the same query as the table), or the whole history. It offers
  "Secrets masked" always and "As captured" only when the export policy
  is not `redact`; every link states the choice with `reveal`. The export
  is probed first (status and headers, body cancelled), so a refusal (too
  many flows, a choice needed, unmasked not allowed) shows the backend's
  message as a toast instead of a broken download; then the streamed file
  downloads through a link.
- **Row menu**: "Export as HAR" for the row, or for the selection it
  belongs to; "with secrets" when the policy allows it.
- **Import HAR** (toolbar menu, or the empty history) opens the docked
  panel: drop or choose a file, a dry run shows entries, valid, in scope,
  size, skip reasons, hosts with their scope, truncated bodies, the first
  entries, and a warning for a masked Phantom export. "Only in-scope
  requests" narrows it; Import stores the flows and the history reloads on
  `proxy.imported`. Imported rows read `import` in the Source column, with
  the batch id in its tooltip.

## What is not preserved

- Detailed timings: only the total time survives (`send`, `receive`,
  `blocked`, `dns`, `connect`, `ssl` are not recorded by Phantom).
- Reason phrases: Phantom stores only the status code, so `statusText` is
  the standard phrase on export and is ignored on import.
- `headersSize`: always -1.
- HTTP/2 and HTTP/3 pseudo-headers (`:authority`, `:path`, ...) are dropped
  on import; the URL and method carry the same information.
- `cookies` and `queryString` arrays are derived from headers and the URL
  on export and ignored on import (headers and URL are the source).
- URL user information (`user:pass@`) and fragments are dropped on import.
- `pages`, `pageref`, `cache`, `serverIPAddress`, `connection` and
  browser-specific `_` fields other than `_error` are ignored on import.
- Tags and bookmarks in `_phantom` are exported as names but not restored
  on import (tag names may not exist in the target vault).
- Imported response bodies are what the file holds: HAR text is normally
  decoded, while headers may still say `Content-Encoding: gzip`. Display
  falls back to the stored bytes, and the raw download serves them as
  stored. Export with `decoded=false` (revealed) to move the exact wire
  bytes between vaults.
- A lone UTF-16 surrogate in a body text is stored as its surrogate bytes.
