Skip to content

armgit / ARTEX

Public Imported from GitHub
0

ARTEX - AI autonomous penetration testing system (English translation; upstream: Autumn-27/ARTEX, AGPL-3.0)

feat(traffic): HAR 1.2 import and export (P3.4)

BaaRai74b9843761d0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 46638aa..3154e93 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,7 @@ All notable changes to this project are documented in this file. The format is b
- **`ask_operator` target warning**: a request whose question names a host or URL outside the goal targets is tagged as containing target-derived text (#197).
- **Opt-in update banner**: `ARTEX_UPDATE_CHECK` makes the backend check the latest GitHub release at most once per 24 hours and the UI show a banner; off by default (#202).
- **Release provenance**: release archives carry GitHub build provenance attestations and a CycloneDX SBOM (`gh attestation verify <zip> --repo BaaRai/ARTEX`); release notes are the matching `CHANGELOG.md` section (#219, #201).
+- **HAR 1.2 traffic import and export**: `POST /api/traffic/import/har` imports raw HAR 1.2 JSON captures (up to 32 MiB / 2,000 entries / 32 MiB decoded bodies) with deterministic `har-<sha256>` IDs for idempotent re-imports, base64 decoding, blob spilling above 256 KiB, and full-text indexing, without applying capture rewrite rules (`exchange_rewrites` stays empty); per-entry errors are reported alongside `imported`/`skipped`/`failed` counts. `GET /api/traffic/export/har` exports filtered traffic (reusing the `GET /api/traffic` filters) as a HAR 1.2 document in stable `(ts, id)` order, encoding UTF-8 bodies as text and binary bodies as base64, capped at 1,000 entries / 32 MiB with explicit truncation reporting via `X-ARTEX-HAR-*` headers and `_truncated`/`_truncatedReason`/`_totalMatched` fields. The Traffic page adds **Import HAR** and **Export HAR** controls. See `docs/traffic-har.md`.
- **Capture-proxy rewrite rules, storage and API**: `GET`, `POST`, `PUT` and `DELETE /api/traffic/rewrite-rules` and `POST /api/traffic/rewrite-rules/{id}/toggle` manage rules that match a request or a response (method, host, URL, headers, body, status) and describe a rewrite (method, path and query, headers, body, status). Rules are validated on save, limited to 100 of which 50 enabled, created disabled, and stored in the new table `traffic_rewrite_rules` (migration `0005_traffic_rewrite_rules.sql`) with `matchers` and `actions` encrypted at rest. The value of an action marked `sensitive` is never returned, and an update sent without it keeps the stored one. The server compiles the enabled rules at startup and after every change and hands the snapshot to the proxy. The proxy applies them from the next entry. See `docs/traffic-rewrite-rules.md`.
- **Capture-proxy rewrite rules applied**: the capture proxy applies enabled rules to each HTTP request before it is sent to the target and to each response before it reaches the client. Each action that ran is recorded in the new table `exchange_rewrites` in the same transaction as the exchange, `traffic_get` shows a `REWRITTEN` line, and `traffic_search` never finds a value a rule wrote. SSE status and headers are rewritten at the start of the stream. **WebSocket handshakes are not rewritten**: the capture library runs its hook after the upgrade, so the status and headers cannot be changed, and frames pass unchanged. **Responses of 5 MiB or more** are forwarded unchanged and not recorded in full, because the library does not call the response hook for them. Snapshots of original requests are capped at 1024 entries and 64 MiB. Replays (`POST /api/traffic/replay`) bypass capture rewrite rules by default via an internal `X-ARTEX-Replay-Nonce` header stripped unconditionally by the proxy, and apply the rules when opted in with `apply_rules: true` (the **Apply capture rewrite rules** checkbox in the Replay panel). `GET /api/traffic` exposes the proxy's `rewrite` counters (`large_responses`, `capacity_refusals`, `tombstone_drops`, `conversions`, `sweeps`), flags each exchange row with `rewritten`, and filters with `rewritten=all|rewritten|original` (also accepting `true`/`false`), surfaced with a filter control and row badge on the Traffic page. Traffic archives export version 2 with per-exchange `rewritten` and sorted distinct applied `rewrite_rule_ids` while remaining deterministic and backward-compatible with version 1 archives. The rule-management web UI comes later.
- **Bulk finding status** (#298): select findings in the findings table and apply one disposition to all of them, up to 500 per call, in one transaction; each row still goes through the single-decision notification semantics and the change is mirrored onto its exploration node (#289).
diff --git a/docs/traffic-har.md b/docs/traffic-har.md
new file mode 100644
index 0000000..648d061
--- /dev/null
+++ b/docs/traffic-har.md
@@ -0,0 +1,118 @@
+# Traffic HAR 1.2 Import and Export
+
+ARTEX supports importing and exporting captured HTTP traffic using the **HAR 1.2** JSON format so operators can bring captures from browser DevTools or external proxies into the Traffic store and export filtered subsets out of ARTEX.
+
+Both routes require the standard administrator JWT (`Authorization: Bearer <token>`) like the rest of `/api/traffic`, and return `503` when the traffic store is unavailable.
+
+---
+
+## Import: `POST /api/traffic/import/har`
+
+### Request format
+
+Send a raw HAR 1.2 JSON document directly as the HTTP request body (`Content-Type: application/json`), capped at the standard API JSON body limit (**32 MiB**; oversized bodies return `413 Request Entity Too Large`).
+
+```bash
+curl -X POST \
+ -H "Authorization: Bearer $TOKEN" \
+ -H "Content-Type: application/json" \
+ --data-binary @capture.har \
+ http://127.0.0.1:8787/api/traffic/import/har
+```
+
+The Traffic page also provides an **Import HAR** file picker that reads a `.har` / `.json` file, posts it to this endpoint, displays loading/error state and a count summary, and refreshes the table.
+
+### Validation & error handling
+
+The request is rejected with `400 Bad Request` naming the reason when:
+
+- the body is empty or malformed JSON (including trailing content after the root object),
+- the `log` object is missing,
+- `log.version` is not `"1.2"`,
+- `log.entries` is missing or `null`,
+- `log.entries` exceeds the per-import entry cap (`2000` entries).
+
+Individual malformed entries (invalid `startedDateTime`, non-HTTP(S) URL, invalid HTTP method, header names or values containing CR/LF/NUL, out-of-range status, invalid base64 or unsupported body encoding) do **not** fail the whole import: they are counted in `failed` and reported in `errors` (up to 50 error details) while valid entries continue importing. HTTP/2 pseudo-headers starting with `:` (such as `:authority` or `:method` from browser DevTools) are skipped cleanly.
+
+### Response
+
+```json
+{
+ "imported": 12,
+ "skipped": 3,
+ "failed": 1,
+ "truncated": false,
+ "errors": [
+ { "index": 4, "url": "notaurl", "reason": "invalid request url \"notaurl\"" }
+ ]
+}
+```
+
+### Deterministic IDs & idempotence
+
+Each imported entry is assigned a deterministic ID:
+
+```text
+har-<hex(sha256(ts_unix_seconds + NUL + METHOD + NUL + canonical_url + NUL + status + NUL + sha256(req_body) + NUL + sha256(resp_body)))>
+```
+
+- `ts_unix_seconds` is `startedDateTime` parsed as RFC 3339 and truncated to UTC Unix seconds (matching `exchanges.ts`).
+- Existing rows are never overwritten (`INSERT OR IGNORE`): re-importing the same HAR (or an exported HAR from ARTEX) skips existing IDs and increments `skipped`. Duplicate entries inside the same HAR file are likewise deduplicated into `skipped`.
+
+### Storage, bodies, and base64
+
+- `host` is derived from `URL.Hostname()` and `url_template` from `db.TemplatePath(URL.EscapedPath())`; `path` stays empty.
+- `response.content.text` and `request.postData.text` are stored as raw UTF-8 bytes when `encoding` is empty, and decoded via standard base64 when `encoding` is `"base64"`.
+- `req_len` and `resp_len` record the actual decoded byte lengths.
+- `content_type` comes from `response.content.mimeType` (falling back to the response `Content-Type` header).
+- Bodies larger than the 256 KiB inline threshold spill to the content-addressed blob store (`_blobs/sha256/...`) with `blob_refs` rows, and searchable text bodies are added to the `ex_fts` full-text index — identical to proxy capture and `ImportArchive`.
+
+### Capture rewrite rules are NOT applied
+
+HAR import writes directly to the traffic store without passing through the MITM capture proxy. **Capture rewrite rules are never applied to imported exchanges**, no `exchange_rewrites` rows are created, and imported rows always have `rewritten: false`.
+
+### Import limits
+
+| Limit | Default | Behavior when exceeded |
+|---|---|---|
+| Raw HTTP request body | 32 MiB | `413 Request Entity Too Large` |
+| Entries per HAR | 2,000 | `400 Bad Request` |
+| Total decoded request + response body bytes | 32 MiB | Stops importing remaining entries, sets `"truncated": true`, counts remaining entries in `skipped`, and appends an explanatory item in `errors`. |
+
+---
+
+## Export: `GET /api/traffic/export/har`
+
+### Request & filters
+
+Returns an `application/json` HAR 1.2 document (`Content-Disposition: attachment; filename="artex-traffic.har"`) ordered deterministically by `(ts ASC, id ASC)`.
+
+It reuses the same filter parser and SQL predicate builder as `GET /api/traffic`, supporting:
+
+- `host`, `method`, `path`, `status`, `q`, `body`, `rewritten` (`all` | `rewritten` | `original` | `true` | `false`), `resp_min`, `resp_max`.
+
+### Mapping & fidelity
+
+- `log.version` is `"1.2"` and `log.creator` is `{"name": "ARTEX", "version": "<build-version>"}`.
+- `startedDateTime` is formatted from `exchanges.ts` as UTC RFC 3339.
+- Request and response headers are parsed from the stored raw heads (`req_head` / `resp_head`). ARTEX does **not** invent `time`, `serverIPAddress`, or headers that are not present in the store.
+- Bodies are read in full from inline columns or spilled blobs: valid NUL-free UTF-8 bodies are emitted as plain `text`, and binary / non-UTF-8 bodies are emitted with `encoding: "base64"`.
+
+### Export limits & truncation reporting
+
+| Limit | Default | `truncatedReason` |
+|---|---|---|
+| Exported entries | 1,000 | `max_entries` |
+| Total raw request + response body bytes | 32 MiB | `max_bytes` |
+
+Truncation is never silent. Every export reports it in both HTTP response headers and HAR 1.2 custom (`_`-prefixed) `log` fields:
+
+- Headers:
+ - `X-ARTEX-HAR-Truncated: true|false`
+ - `X-ARTEX-HAR-Truncated-Reason: max_entries|max_bytes` (when truncated)
+ - `X-ARTEX-HAR-Exported: <count>`
+ - `X-ARTEX-HAR-Matched: <total matching rows>`
+- JSON (`log` object, omitted when not truncated):
+ - `_truncated: true`
+ - `_truncatedReason: "max_entries" | "max_bytes"`
+ - `_totalMatched: <total matching rows>`
diff --git a/server/server.go b/server/server.go
index cdc23a0..09efe3a 100644
--- a/server/server.go
+++ b/server/server.go
@@ -898,6 +898,8 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("GET /api/traffic/blob", s.getTrafficBlob)
mux.HandleFunc("POST /api/traffic/ingest", s.ingestTraffic)
mux.HandleFunc("POST /api/traffic/replay", s.replayTraffic)
+ mux.HandleFunc("POST /api/traffic/import/har", s.importTrafficHAR)
+ mux.HandleFunc("GET /api/traffic/export/har", s.exportTrafficHAR)
mux.HandleFunc("GET /api/commands", s.pgListCommands)
mux.HandleFunc("GET /api/commands/stats", s.pgToolStats) // aggregate call counts per tool
mux.HandleFunc("GET /api/llm/records", s.pgListLLMRecords)
@@ -3541,19 +3543,7 @@ func (s *Server) getTraffic(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
page := atoiDefault(q.Get("page"), 0)
size := atoiDefault(q.Get("size"), 100)
- ex, matched, _ := tr.Page(traffic.PageQuery{
- Host: q.Get("host"),
- Method: q.Get("method"),
- Query: q.Get("q"),
- Body: q.Get("body"),
- Path: q.Get("path"),
- Status: q.Get("status"),
- Rewritten: q.Get("rewritten"),
- RespMin: int64(atoiDefault(q.Get("resp_min"), -1)),
- RespMax: int64(atoiDefault(q.Get("resp_max"), -1)),
- Sort: q.Get("sort"),
- Order: q.Get("order"),
- }, page, size)
+ ex, matched, _ := tr.Page(parseTrafficPageQuery(q), page, size)
count, _ := tr.Count() // global total, for the stat card
writeJSON(w, 200, map[string]any{
"enabled": s.m.TrafficEnabled(), // reflect the capture toggle
diff --git a/server/traffic_har.go b/server/traffic_har.go
new file mode 100644
index 0000000..c69eb8c
--- /dev/null
+++ b/server/traffic_har.go
@@ -0,0 +1,96 @@
+package server
+
+import (
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/url"
+ "strconv"
+
+ "github.com/Autumn-27/artex/traffic"
+)
+
+func parseTrafficPageQuery(q url.Values) traffic.PageQuery {
+ return traffic.PageQuery{
+ Host: q.Get("host"),
+ Method: q.Get("method"),
+ Query: q.Get("q"),
+ Body: q.Get("body"),
+ Path: q.Get("path"),
+ Status: q.Get("status"),
+ Rewritten: q.Get("rewritten"),
+ RespMin: int64(atoiDefault(q.Get("resp_min"), -1)),
+ RespMax: int64(atoiDefault(q.Get("resp_max"), -1)),
+ Sort: q.Get("sort"),
+ Order: q.Get("order"),
+ }
+}
+
+// importTrafficHAR accepts a raw HAR 1.2 JSON document (capped at decodeMaxBytes,
+// 32 MiB) and imports valid entries into the traffic store with deterministic
+// IDs. Imported traffic never passes through capture rewrite rules.
+func (s *Server) importTrafficHAR(w http.ResponseWriter, r *http.Request) {
+ tr := s.m.Traffic()
+ if tr == nil {
+ writeErr(w, http.StatusServiceUnavailable, "traffic store is not available")
+ return
+ }
+ body := r.Body
+ if _, already := body.(*limitedBody); !already {
+ body = http.MaxBytesReader(w, body, decodeMaxBytes)
+ }
+ raw, err := io.ReadAll(body)
+ if err != nil {
+ var tooLarge *http.MaxBytesError
+ if errors.As(err, &tooLarge) {
+ writeErr(w, http.StatusRequestEntityTooLarge, "HAR payload exceeds 32 MiB limit")
+ return
+ }
+ writeErr(w, http.StatusBadRequest, "failed to read HAR body: "+err.Error())
+ return
+ }
+ res, err := tr.ImportHAR(raw, traffic.HARImportOptions{})
+ if err != nil {
+ if errors.Is(err, traffic.ErrInvalidHAR) {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ writeErr(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ writeJSON(w, http.StatusOK, res)
+}
+
+// exportTrafficHAR exports recorded traffic matching the query filters as an
+// application/json HAR 1.2 document in stable chronological order. Entry and
+// total-byte caps are enforced and reported via both X-ARTEX-HAR-* headers and
+// HAR 1.2 custom fields (_truncated, _truncatedReason, _totalMatched).
+func (s *Server) exportTrafficHAR(w http.ResponseWriter, r *http.Request) {
+ tr := s.m.Traffic()
+ if tr == nil {
+ writeErr(w, http.StatusServiceUnavailable, "traffic store is not available")
+ return
+ }
+ pq := parseTrafficPageQuery(r.URL.Query())
+ doc, meta, err := tr.ExportHAR(pq, traffic.HARExportOptions{CreatorVersion: BuildVersion})
+ if err != nil {
+ writeErr(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ payload, err := json.Marshal(doc)
+ if err != nil {
+ writeErr(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ w.Header().Set("Content-Type", "application/json; charset=utf-8")
+ w.Header().Set("Content-Disposition", `attachment; filename="artex-traffic.har"`)
+ w.Header().Set("X-ARTEX-HAR-Truncated", strconv.FormatBool(meta.Truncated))
+ w.Header().Set("X-ARTEX-HAR-Exported", strconv.Itoa(meta.Exported))
+ w.Header().Set("X-ARTEX-HAR-Matched", strconv.Itoa(meta.TotalMatched))
+ if meta.Truncated {
+ w.Header().Set("X-ARTEX-HAR-Truncated-Reason", meta.TruncatedReason)
+ }
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write(payload)
+}
diff --git a/server/traffic_har_test.go b/server/traffic_har_test.go
new file mode 100644
index 0000000..1036d51
--- /dev/null
+++ b/server/traffic_har_test.go
@@ -0,0 +1,199 @@
+package server
+
+import (
+ "bytes"
+ "encoding/base64"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/Autumn-27/artex/traffic"
+)
+
+func TestTrafficHAREndpointsRoundTripFilterAndErrors(t *testing.T) {
+ s, request := ingestServer(t)
+
+ binPayload := []byte{0x00, 0x01, 0x89, 0x50, 0xfe, 0xff}
+ harIn := traffic.HAR{
+ Log: &traffic.HARLog{
+ Version: "1.2",
+ Creator: traffic.HARCreator{Name: "TestSuite", Version: "1.0"},
+ Entries: []traffic.HAREntry{
+ {
+ StartedDateTime: "2026-06-01T08:00:00Z",
+ Request: traffic.HARRequest{
+ Method: "POST",
+ URL: "https://har-a.example/api/login",
+ Headers: []traffic.HARHeader{{Name: "Content-Type", Value: "application/json"}},
+ PostData: &traffic.HARPostData{
+ MimeType: "application/json",
+ Text: `{"user":"alice"}`,
+ },
+ },
+ Response: traffic.HARResponse{
+ Status: 200,
+ Headers: []traffic.HARHeader{{Name: "Content-Type", Value: "application/json"}},
+ Content: traffic.HARContent{
+ MimeType: "application/json",
+ Text: `{"ok":true}`,
+ },
+ },
+ },
+ {
+ StartedDateTime: "2026-06-01T08:00:10Z",
+ Request: traffic.HARRequest{
+ Method: "GET",
+ URL: "https://har-b.example/blob.bin",
+ Headers: []traffic.HARHeader{},
+ },
+ Response: traffic.HARResponse{
+ Status: 200,
+ Headers: []traffic.HARHeader{{Name: "Content-Type", Value: "application/octet-stream"}},
+ Content: traffic.HARContent{
+ MimeType: "application/octet-stream",
+ Text: base64.StdEncoding.EncodeToString(binPayload),
+ Encoding: "base64",
+ },
+ },
+ },
+ },
+ },
+ }
+ rawIn, err := json.Marshal(harIn)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // Import via HTTP endpoint.
+ w := request(http.MethodPost, "/api/traffic/import/har", string(rawIn))
+ if w.Code != http.StatusOK {
+ t.Fatalf("POST /api/traffic/import/har status=%d body=%s", w.Code, w.Body.String())
+ }
+ var importRes traffic.HARImportResult
+ if err := json.Unmarshal(w.Body.Bytes(), &importRes); err != nil {
+ t.Fatal(err)
+ }
+ if importRes.Imported != 2 || importRes.Skipped != 0 || importRes.Failed != 0 {
+ t.Fatalf("importRes = %+v, want 2/0/0", importRes)
+ }
+
+ // Re-import is idempotent.
+ w2 := request(http.MethodPost, "/api/traffic/import/har", string(rawIn))
+ if w2.Code != http.StatusOK {
+ t.Fatalf("re-import status=%d body=%s", w2.Code, w2.Body.String())
+ }
+ var importRes2 traffic.HARImportResult
+ if err := json.Unmarshal(w2.Body.Bytes(), &importRes2); err != nil {
+ t.Fatal(err)
+ }
+ if importRes2.Imported != 0 || importRes2.Skipped != 2 || importRes2.Failed != 0 {
+ t.Fatalf("re-import res = %+v, want 0/2/0", importRes2)
+ }
+
+ // Imported rows are listed on GET /api/traffic with rewritten=false and zero exchange_rewrites rows.
+ wList := request(http.MethodGet, "/api/traffic?host=har-", "")
+ if wList.Code != http.StatusOK {
+ t.Fatalf("GET /api/traffic status=%d body=%s", wList.Code, wList.Body.String())
+ }
+ var listResp struct {
+ Total int `json:"total"`
+ Exchanges []TrafficExchangeDTO `json:"exchanges"`
+ }
+ if err := json.Unmarshal(wList.Body.Bytes(), &listResp); err != nil {
+ t.Fatal(err)
+ }
+ if listResp.Total != 2 || len(listResp.Exchanges) != 2 {
+ t.Fatalf("listResp = %+v, want 2 exchanges", listResp)
+ }
+ for _, row := range listResp.Exchanges {
+ if row.Rewritten {
+ t.Fatalf("imported row %s marked rewritten", row.ID)
+ }
+ }
+ var rwCount int
+ if err := s.m.Traffic().DB().QueryRow(`SELECT COUNT(*) FROM exchange_rewrites`).Scan(&rwCount); err != nil || rwCount != 0 {
+ t.Fatalf("exchange_rewrites count after HTTP HAR import = %d err=%v, want 0", rwCount, err)
+ }
+
+ // Filtered export by host returns only har-b.example with binary payload preserved as base64.
+ wExp := request(http.MethodGet, "/api/traffic/export/har?host=har-b.example", "")
+ if wExp.Code != http.StatusOK {
+ t.Fatalf("GET /api/traffic/export/har status=%d body=%s", wExp.Code, wExp.Body.String())
+ }
+ if ct := wExp.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/json") {
+ t.Fatalf("export Content-Type = %q, want application/json", ct)
+ }
+ if wExp.Header().Get("X-ARTEX-HAR-Truncated") != "false" || wExp.Header().Get("X-ARTEX-HAR-Exported") != "1" || wExp.Header().Get("X-ARTEX-HAR-Matched") != "1" {
+ t.Fatalf("unexpected export headers: %+v", wExp.Header())
+ }
+ var exported traffic.HAR
+ if err := json.Unmarshal(wExp.Body.Bytes(), &exported); err != nil {
+ t.Fatal(err)
+ }
+ if exported.Log == nil || exported.Log.Version != "1.2" || len(exported.Log.Entries) != 1 {
+ t.Fatalf("filtered export = %+v", exported.Log)
+ }
+ entry := exported.Log.Entries[0]
+ if entry.Request.URL != "https://har-b.example/blob.bin" || entry.Response.Content.Encoding != "base64" {
+ t.Fatalf("exported binary entry = %+v", entry)
+ }
+ decoded, err := base64.StdEncoding.DecodeString(entry.Response.Content.Text)
+ if err != nil || !bytes.Equal(decoded, binPayload) {
+ t.Fatalf("exported binary bytes mismatch: got=%x err=%v", decoded, err)
+ }
+
+ // Re-importing the exported HAR via HTTP is idempotent.
+ wReimp := request(http.MethodPost, "/api/traffic/import/har", wExp.Body.String())
+ if wReimp.Code != http.StatusOK || !strings.Contains(wReimp.Body.String(), `"imported":0`) || !strings.Contains(wReimp.Body.String(), `"skipped":1`) {
+ t.Fatalf("re-import exported HAR status=%d body=%s", wReimp.Code, wReimp.Body.String())
+ }
+
+ // Error cases -> 400 naming the reason.
+ for _, tc := range []struct {
+ name string
+ body string
+ want string
+ }{
+ {"malformed", `{"log":`, "malformed JSON"},
+ {"missing entries", `{"log":{"version":"1.2"}}`, "missing log.entries"},
+ {"unsupported version", `{"log":{"version":"2.0","entries":[]}}`, "unsupported HAR version"},
+ } {
+ wErr := request(http.MethodPost, "/api/traffic/import/har", tc.body)
+ if wErr.Code != http.StatusBadRequest || !strings.Contains(wErr.Body.String(), tc.want) {
+ t.Fatalf("%s: status=%d body=%s, want 400 containing %q", tc.name, wErr.Code, wErr.Body.String(), tc.want)
+ }
+ }
+
+ // Traffic store unavailable -> 503 on both import and export.
+ sOff := &Server{m: &Manager{}}
+ wOffImp := httptest.NewRecorder()
+ sOff.importTrafficHAR(wOffImp, httptest.NewRequest(http.MethodPost, "/api/traffic/import/har", strings.NewReader(`{}`)))
+ if wOffImp.Code != http.StatusServiceUnavailable {
+ t.Fatalf("import with traffic off status=%d, want 503", wOffImp.Code)
+ }
+ wOffExp := httptest.NewRecorder()
+ sOff.exportTrafficHAR(wOffExp, httptest.NewRequest(http.MethodGet, "/api/traffic/export/har", nil))
+ if wOffExp.Code != http.StatusServiceUnavailable {
+ t.Fatalf("export with traffic off status=%d, want 503", wOffExp.Code)
+ }
+}
+
+func TestTrafficHAREndpointsRequireAuth(t *testing.T) {
+ s, _ := ingestServer(t)
+
+ rImp := httptest.NewRequest(http.MethodPost, "/api/traffic/import/har", strings.NewReader(`{"log":{"version":"1.2","entries":[]}}`))
+ wImp := httptest.NewRecorder()
+ s.Handler().ServeHTTP(wImp, rImp)
+ if wImp.Code != http.StatusUnauthorized {
+ t.Fatalf("unauthenticated HAR import status=%d, want 401", wImp.Code)
+ }
+
+ rExp := httptest.NewRequest(http.MethodGet, "/api/traffic/export/har", nil)
+ wExp := httptest.NewRecorder()
+ s.Handler().ServeHTTP(wExp, rExp)
+ if wExp.Code != http.StatusUnauthorized {
+ t.Fatalf("unauthenticated HAR export status=%d, want 401", wExp.Code)
+ }
+}
diff --git a/traffic/har.go b/traffic/har.go
new file mode 100644
index 0000000..70cd799
--- /dev/null
+++ b/traffic/har.go
@@ -0,0 +1,735 @@
+package traffic
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "database/sql"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+ "unicode/utf8"
+
+ "github.com/Autumn-27/artex/db"
+)
+
+const (
+ // HARVersion is the HAR specification version produced and accepted.
+ HARVersion = "1.2"
+
+ // DefaultHARMaxImportEntries caps how many entries a single HAR import accepts.
+ DefaultHARMaxImportEntries = 2000
+ // DefaultHARMaxImportBytes caps total decoded request+response body bytes
+ // imported in a single HAR document.
+ DefaultHARMaxImportBytes int64 = 32 << 20
+
+ // DefaultHARMaxExportEntries caps how many exchanges a single HAR export emits.
+ DefaultHARMaxExportEntries = 1000
+ // DefaultHARMaxExportBytes caps total raw request+response body bytes emitted
+ // in a single HAR export.
+ DefaultHARMaxExportBytes int64 = 32 << 20
+
+ maxHARImportErrors = 50
+)
+
+// ErrInvalidHAR marks a malformed or unsupported HAR document (mapped to HTTP 400).
+var ErrInvalidHAR = errors.New("invalid HAR")
+
+// HAR is a minimal HAR 1.2 envelope. Only fields backed by the traffic store
+// are populated on export; timings, serverIPAddress, and synthetic headers are
+// never invented.
+type HAR struct {
+ Log *HARLog `json:"log"`
+}
+
+type HARLog struct {
+ Version string `json:"version"`
+ Creator HARCreator `json:"creator"`
+ Entries []HAREntry `json:"entries"`
+ Truncated bool `json:"_truncated,omitempty"`
+ TruncatedReason string `json:"_truncatedReason,omitempty"`
+ TotalMatched int `json:"_totalMatched,omitempty"`
+}
+
+type HARCreator struct {
+ Name string `json:"name"`
+ Version string `json:"version"`
+}
+
+type HAREntry struct {
+ StartedDateTime string `json:"startedDateTime"`
+ Request HARRequest `json:"request"`
+ Response HARResponse `json:"response"`
+}
+
+type HARRequest struct {
+ Method string `json:"method"`
+ URL string `json:"url"`
+ HTTPVersion string `json:"httpVersion,omitempty"`
+ Headers []HARHeader `json:"headers"`
+ PostData *HARPostData `json:"postData,omitempty"`
+ BodySize int `json:"bodySize"`
+}
+
+type HARPostData struct {
+ MimeType string `json:"mimeType,omitempty"`
+ Text string `json:"text,omitempty"`
+ Encoding string `json:"encoding,omitempty"`
+}
+
+type HARResponse struct {
+ Status int `json:"status"`
+ StatusText string `json:"statusText,omitempty"`
+ HTTPVersion string `json:"httpVersion,omitempty"`
+ Headers []HARHeader `json:"headers"`
+ Content HARContent `json:"content"`
+ BodySize int `json:"bodySize"`
+}
+
+type HARContent struct {
+ Size int `json:"size"`
+ MimeType string `json:"mimeType,omitempty"`
+ Text string `json:"text,omitempty"`
+ Encoding string `json:"encoding,omitempty"`
+}
+
+type HARHeader struct {
+ Name string `json:"name"`
+ Value string `json:"value"`
+}
+
+// HARImportOptions configures safety caps for ImportHAR. Zero values use the
+// package defaults.
+type HARImportOptions struct {
+ MaxEntries int
+ MaxTotalBytes int64
+}
+
+// HARImportError describes one entry that could not be imported.
+type HARImportError struct {
+ Index int `json:"index"`
+ URL string `json:"url,omitempty"`
+ Reason string `json:"reason"`
+}
+
+// HARImportResult summarizes one ImportHAR run.
+type HARImportResult struct {
+ Imported int `json:"imported"`
+ Skipped int `json:"skipped"`
+ Failed int `json:"failed"`
+ Truncated bool `json:"truncated,omitempty"`
+ Errors []HARImportError `json:"errors,omitempty"`
+}
+
+// HARExportOptions configures ExportHAR. Zero caps use package defaults.
+type HARExportOptions struct {
+ CreatorVersion string
+ MaxEntries int
+ MaxTotalBytes int64
+}
+
+// HARExportMeta reports export counts and whether a cap stopped the export.
+type HARExportMeta struct {
+ Exported int
+ TotalMatched int
+ TotalBytes int64
+ Truncated bool
+ TruncatedReason string // "" | "max_entries" | "max_bytes"
+}
+
+// ImportHAR parses a HAR 1.2 JSON document and inserts valid entries into the
+// traffic store. Entries receive a deterministic ID so re-importing the same
+// HAR is idempotent and skips existing rows. Imported traffic is never passed
+// through capture rewrite rules and never gains exchange_rewrites rows.
+func (t *Traffic) ImportHAR(raw []byte, opts HARImportOptions) (HARImportResult, error) {
+ if t == nil {
+ return HARImportResult{}, errors.New("traffic store is not available")
+ }
+ if opts.MaxEntries <= 0 {
+ opts.MaxEntries = DefaultHARMaxImportEntries
+ }
+ if opts.MaxTotalBytes <= 0 {
+ opts.MaxTotalBytes = DefaultHARMaxImportBytes
+ }
+
+ doc, err := decodeHARDocument(raw)
+ if err != nil {
+ return HARImportResult{}, err
+ }
+ if len(doc.Log.Entries) > opts.MaxEntries {
+ return HARImportResult{}, fmt.Errorf("%w: HAR contains %d entries, exceeding limit of %d", ErrInvalidHAR, len(doc.Log.Entries), opts.MaxEntries)
+ }
+
+ var res HARImportResult
+ addErr := func(idx int, rawURL, reason string) {
+ if len(res.Errors) < maxHARImportErrors {
+ res.Errors = append(res.Errors, HARImportError{Index: idx, URL: rawURL, Reason: reason})
+ }
+ }
+
+ var totalBytes int64
+ for i, entry := range doc.Log.Entries {
+ parsed, err := parseHAREntry(entry)
+ if err != nil {
+ res.Failed++
+ addErr(i, entry.Request.URL, err.Error())
+ continue
+ }
+ entryBytes := int64(len(parsed.reqBody) + len(parsed.respBody))
+ if totalBytes+entryBytes > opts.MaxTotalBytes {
+ remaining := len(doc.Log.Entries) - i
+ res.Truncated = true
+ res.Skipped += remaining
+ addErr(i, entry.Request.URL, fmt.Sprintf("decoded body byte cap (%d bytes) reached; %d remaining entries skipped", opts.MaxTotalBytes, remaining))
+ break
+ }
+
+ inserted, err := t.insertHARExchange(parsed)
+ if err != nil {
+ res.Failed++
+ addErr(i, entry.Request.URL, err.Error())
+ continue
+ }
+ if !inserted {
+ res.Skipped++
+ continue
+ }
+ totalBytes += entryBytes
+ res.Imported++
+ }
+ return res, nil
+}
+
+func decodeHARDocument(raw []byte) (HAR, error) {
+ if len(bytes.TrimSpace(raw)) == 0 {
+ return HAR{}, fmt.Errorf("%w: empty HAR document", ErrInvalidHAR)
+ }
+ dec := json.NewDecoder(bytes.NewReader(raw))
+ var doc HAR
+ if err := dec.Decode(&doc); err != nil {
+ return HAR{}, fmt.Errorf("%w: malformed JSON: %v", ErrInvalidHAR, err)
+ }
+ // Reject trailing non-whitespace tokens after the root object.
+ if err := dec.Decode(&struct{}{}); err != io.EOF {
+ return HAR{}, fmt.Errorf("%w: malformed JSON: trailing content after HAR object", ErrInvalidHAR)
+ }
+ if doc.Log == nil {
+ return HAR{}, fmt.Errorf("%w: missing log object", ErrInvalidHAR)
+ }
+ if strings.TrimSpace(doc.Log.Version) != HARVersion {
+ return HAR{}, fmt.Errorf("%w: unsupported HAR version %q (expected %s)", ErrInvalidHAR, doc.Log.Version, HARVersion)
+ }
+ if doc.Log.Entries == nil {
+ return HAR{}, fmt.Errorf("%w: missing log.entries", ErrInvalidHAR)
+ }
+ return doc, nil
+}
+
+type parsedHARExchange struct {
+ id string
+ ts int64
+ host string
+ method string
+ urlTemplate string
+ rawURL string
+ status int
+ reqCT string
+ respCT string
+ reqHead string
+ reqBody []byte
+ respHead string
+ respBody []byte
+}
+
+func parseHAREntry(entry HAREntry) (parsedHARExchange, error) {
+ tsStr := strings.TrimSpace(entry.StartedDateTime)
+ if tsStr == "" {
+ return parsedHARExchange{}, errors.New("missing startedDateTime")
+ }
+ parsedTS, err := time.Parse(time.RFC3339Nano, tsStr)
+ if err != nil {
+ return parsedHARExchange{}, fmt.Errorf("invalid startedDateTime %q", entry.StartedDateTime)
+ }
+ ts := parsedTS.UTC().Unix()
+
+ rawURL := strings.TrimSpace(entry.Request.URL)
+ u, err := url.Parse(rawURL)
+ if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") {
+ return parsedHARExchange{}, fmt.Errorf("invalid request url %q", entry.Request.URL)
+ }
+ method := strings.ToUpper(strings.TrimSpace(entry.Request.Method))
+ if method == "" || !validHeaderName(method) {
+ return parsedHARExchange{}, fmt.Errorf("invalid request method %q", entry.Request.Method)
+ }
+ if entry.Response.Status < 0 || entry.Response.Status > 999 {
+ return parsedHARExchange{}, fmt.Errorf("invalid response status %d", entry.Response.Status)
+ }
+
+ reqHeaderText, reqCT, err := formatHARHeaders(entry.Request.Headers)
+ if err != nil {
+ return parsedHARExchange{}, fmt.Errorf("invalid request headers: %w", err)
+ }
+ respHeaderText, respHeaderCT, err := formatHARHeaders(entry.Response.Headers)
+ if err != nil {
+ return parsedHARExchange{}, fmt.Errorf("invalid response headers: %w", err)
+ }
+
+ var reqBody []byte
+ if entry.Request.PostData != nil {
+ reqBody, err = decodeHARBody(entry.Request.PostData.Text, entry.Request.PostData.Encoding)
+ if err != nil {
+ return parsedHARExchange{}, fmt.Errorf("invalid request postData: %w", err)
+ }
+ if reqCT == "" {
+ reqCT = strings.TrimSpace(entry.Request.PostData.MimeType)
+ }
+ }
+ respBody, err := decodeHARBody(entry.Response.Content.Text, entry.Response.Content.Encoding)
+ if err != nil {
+ return parsedHARExchange{}, fmt.Errorf("invalid response content: %w", err)
+ }
+
+ respCT := strings.TrimSpace(entry.Response.Content.MimeType)
+ if respCT == "" {
+ respCT = respHeaderCT
+ }
+
+ reqProto := sanitizeHARProto(entry.Request.HTTPVersion)
+ respProto := sanitizeHARProto(entry.Response.HTTPVersion)
+ reqHead := fmt.Sprintf("%s %s %s\n%s", method, u.RequestURI(), reqProto, reqHeaderText)
+
+ statusText := strings.TrimSpace(entry.Response.StatusText)
+ if strings.ContainsAny(statusText, "\r\n\x00") {
+ return parsedHARExchange{}, errors.New("response statusText contains control characters")
+ }
+ respHead := fmt.Sprintf("%s %d\n%s", respProto, entry.Response.Status, respHeaderText)
+ if statusText != "" {
+ respHead = fmt.Sprintf("%s %d %s\n%s", respProto, entry.Response.Status, statusText, respHeaderText)
+ }
+
+ canonicalURL := u.String()
+ id := harExchangeID(ts, method, canonicalURL, entry.Response.Status, reqBody, respBody)
+ return parsedHARExchange{
+ id: id,
+ ts: ts,
+ host: u.Hostname(),
+ method: method,
+ urlTemplate: db.TemplatePath(u.EscapedPath()),
+ rawURL: canonicalURL,
+ status: entry.Response.Status,
+ reqCT: reqCT,
+ respCT: respCT,
+ reqHead: reqHead,
+ reqBody: reqBody,
+ respHead: respHead,
+ respBody: respBody,
+ }, nil
+}
+
+// harExchangeID derives a deterministic ID from the exchange's timestamp (Unix
+// seconds), method, canonical URL, status code, and SHA-256 digests of both
+// bodies. Using Unix seconds matches exchanges.ts so export -> re-import
+// produces the exact same ID.
+func harExchangeID(ts int64, method, rawURL string, status int, reqBody, respBody []byte) string {
+ reqSum := sha256.Sum256(reqBody)
+ respSum := sha256.Sum256(respBody)
+ h := sha256.New()
+ fmt.Fprintf(h, "%d\x00%s\x00%s\x00%d\x00%x\x00%x", ts, method, rawURL, status, reqSum, respSum)
+ return "har-" + hex.EncodeToString(h.Sum(nil))
+}
+
+func formatHARHeaders(headers []HARHeader) (formatted string, contentType string, err error) {
+ var b strings.Builder
+ for _, h := range headers {
+ name := strings.TrimSpace(h.Name)
+ if name == "" {
+ return "", "", errors.New("empty header name")
+ }
+ // Skip HTTP/2 pseudo-headers (:method, :authority, :scheme, :path, :status)
+ // emitted by browser DevTools HAR exports; their semantics live in the
+ // request/status line.
+ if strings.HasPrefix(name, ":") {
+ continue
+ }
+ if !validHeaderName(name) {
+ return "", "", fmt.Errorf("invalid header name %q", h.Name)
+ }
+ if strings.ContainsAny(h.Value, "\r\n\x00") {
+ return "", "", fmt.Errorf("header %s contains a line break or NUL byte", name)
+ }
+ if contentType == "" && strings.EqualFold(name, "Content-Type") {
+ contentType = strings.TrimSpace(h.Value)
+ }
+ b.WriteString(name)
+ b.WriteString(": ")
+ b.WriteString(h.Value)
+ b.WriteByte('\n')
+ }
+ return b.String(), contentType, nil
+}
+
+func decodeHARBody(text, encoding string) ([]byte, error) {
+ enc := strings.ToLower(strings.TrimSpace(encoding))
+ switch enc {
+ case "":
+ if text == "" {
+ return nil, nil
+ }
+ return []byte(text), nil
+ case "base64":
+ if text == "" {
+ return nil, nil
+ }
+ decoded, err := base64.StdEncoding.DecodeString(text)
+ if err != nil {
+ return nil, fmt.Errorf("invalid base64 body: %w", err)
+ }
+ return decoded, nil
+ default:
+ return nil, fmt.Errorf("unsupported body encoding %q", encoding)
+ }
+}
+
+func sanitizeHARProto(v string) string {
+ v = strings.TrimSpace(v)
+ if v == "" || strings.ContainsAny(v, " \t\r\n\x00") || !strings.HasPrefix(strings.ToUpper(v), "HTTP/") {
+ return "HTTP/1.1"
+ }
+ return v
+}
+
+// insertHARExchange inserts one HAR exchange idempotently (INSERT OR IGNORE)
+// through the same spill/blob_refs/FTS path as the recorder and ImportArchive.
+// It never writes to exchange_rewrites.
+func (t *Traffic) insertHARExchange(ex parsedHARExchange) (bool, error) {
+ t.wmu.Lock()
+ defer t.wmu.Unlock()
+
+ var exists int
+ if err := t.db.QueryRow(`SELECT 1 FROM exchanges WHERE id=?`, ex.id).Scan(&exists); err == nil {
+ return false, nil
+ } else if !errors.Is(err, sql.ErrNoRows) {
+ return false, err
+ }
+
+ reqB := t.spill(ex.reqBody, ex.reqCT)
+ respB := t.spill(ex.respBody, ex.respCT)
+
+ tx, err := t.db.Begin()
+ if err != nil {
+ return false, fmt.Errorf("beginning transaction: %w", err)
+ }
+ defer tx.Rollback() //nolint:errcheck
+
+ res, err := tx.Exec(`INSERT OR IGNORE INTO exchanges(id,ts,host,method,url_template,url,status,content_type,req_len,resp_len,path)
+VALUES(?,?,?,?,?,?,?,?,?,?,'')`,
+ ex.id, ex.ts, ex.host, ex.method, ex.urlTemplate, ex.rawURL, ex.status, ex.respCT, len(ex.reqBody), len(ex.respBody))
+ if err != nil {
+ return false, fmt.Errorf("writing index: %w", err)
+ }
+ n, _ := res.RowsAffected()
+ if n == 0 {
+ return false, nil
+ }
+ var rowid int64
+ if err := tx.QueryRow(`SELECT rowid FROM exchanges WHERE id=?`, ex.id).Scan(&rowid); err != nil {
+ return false, fmt.Errorf("fetching rowid: %w", err)
+ }
+ if _, err := tx.Exec(`INSERT INTO exchange_bodies(id,req_head,req_body,req_blob,resp_head,resp_body,resp_blob)
+VALUES(?,?,?,?,?,?,?)`,
+ ex.id, ex.reqHead, reqB.inline, nullIfEmpty(reqB.hash), ex.respHead, respB.inline, nullIfEmpty(respB.hash)); err != nil {
+ return false, fmt.Errorf("writing body: %w", err)
+ }
+ for _, h := range []string{reqB.hash, respB.hash} {
+ if h == "" {
+ continue
+ }
+ if _, err := tx.Exec(`INSERT OR IGNORE INTO blob_refs(hash,exchange_id) VALUES(?,?)`, h, ex.id); err != nil {
+ return false, fmt.Errorf("registering blob reference: %w", err)
+ }
+ }
+ if t.fts {
+ idx := strings.Join([]string{ex.rawURL, ex.reqHead, reqB.index, ex.respHead, respB.index}, "\n")
+ if _, err := tx.Exec(`INSERT INTO ex_fts(rowid,content) VALUES(?,?)`, rowid, idx); err != nil {
+ return false, fmt.Errorf("writing full-text index: %w", err)
+ }
+ }
+ if err := tx.Commit(); err != nil {
+ return false, fmt.Errorf("committing: %w", err)
+ }
+ return true, nil
+}
+
+// ExportHAR exports exchanges matching f as a HAR 1.2 document in stable
+// chronological order (ts ASC, id ASC), capped by opts.MaxEntries and
+// opts.MaxTotalBytes. Truncation is reported in both HARExportMeta and the
+// HAR 1.2 custom fields _truncated / _truncatedReason / _totalMatched.
+func (t *Traffic) ExportHAR(f PageQuery, opts HARExportOptions) (HAR, HARExportMeta, error) {
+ if t == nil {
+ return HAR{}, HARExportMeta{}, errors.New("traffic store is not available")
+ }
+ if opts.MaxEntries <= 0 {
+ opts.MaxEntries = DefaultHARMaxExportEntries
+ }
+ if opts.MaxTotalBytes <= 0 {
+ opts.MaxTotalBytes = DefaultHARMaxExportBytes
+ }
+ creatorVer := strings.TrimSpace(opts.CreatorVersion)
+ if creatorVer == "" {
+ creatorVer = "dev"
+ }
+
+ where, args := t.pageWhere(f)
+ var totalMatched int
+ if err := t.db.QueryRow(`SELECT COUNT(*) FROM exchanges`+where, args...).Scan(&totalMatched); err != nil {
+ return HAR{}, HARExportMeta{}, err
+ }
+
+ type exRow struct {
+ id string
+ ts int64
+ host string
+ method string
+ rawURL string
+ status int
+ contentType string
+ legacyPath string
+ }
+
+ // Fetch at most MaxEntries+1 rows so we know whether the entry cap fired.
+ sel := `SELECT id,ts,host,method,url,status,content_type,path FROM exchanges` +
+ where + ` ORDER BY ts ASC, id ASC LIMIT ?`
+ qargs := append(append([]any{}, args...), opts.MaxEntries+1)
+ rows, err := t.db.Query(sel, qargs...)
+ if err != nil {
+ return HAR{}, HARExportMeta{}, err
+ }
+ var matched []exRow
+ for rows.Next() {
+ var r exRow
+ if err := rows.Scan(&r.id, &r.ts, &r.host, &r.method, &r.rawURL, &r.status, &r.contentType, &r.legacyPath); err != nil {
+ rows.Close()
+ return HAR{}, HARExportMeta{}, err
+ }
+ matched = append(matched, r)
+ }
+ if err := rows.Err(); err != nil {
+ rows.Close()
+ return HAR{}, HARExportMeta{}, err
+ }
+ rows.Close()
+
+ meta := HARExportMeta{TotalMatched: totalMatched}
+ hitEntryCap := len(matched) > opts.MaxEntries
+ if hitEntryCap {
+ matched = matched[:opts.MaxEntries]
+ }
+
+ entries := make([]HAREntry, 0, len(matched))
+ for _, r := range matched {
+ reqHead, reqBytes, respHead, respBytes, err := t.loadFullExchange(r.id, r.legacyPath)
+ if err != nil {
+ return HAR{}, HARExportMeta{}, err
+ }
+ entryBytes := int64(len(reqBytes) + len(respBytes))
+ if meta.TotalBytes+entryBytes > opts.MaxTotalBytes {
+ meta.Truncated = true
+ meta.TruncatedReason = "max_bytes"
+ break
+ }
+ meta.TotalBytes += entryBytes
+
+ reqProto, reqHeaders := parseStoredRequestHead(reqHead)
+ respProto, respStatusText, respHeaders := parseStoredResponseHead(respHead)
+
+ harReq := HARRequest{
+ Method: r.method,
+ URL: r.rawURL,
+ HTTPVersion: reqProto,
+ Headers: reqHeaders,
+ BodySize: len(reqBytes),
+ }
+ if len(reqBytes) > 0 {
+ text, enc := encodeHARBody(reqBytes)
+ harReq.PostData = &HARPostData{
+ MimeType: findHeaderValue(reqHeaders, "Content-Type"),
+ Text: text,
+ Encoding: enc,
+ }
+ }
+
+ harContent := HARContent{
+ Size: len(respBytes),
+ MimeType: r.contentType,
+ }
+ if len(respBytes) > 0 {
+ harContent.Text, harContent.Encoding = encodeHARBody(respBytes)
+ }
+
+ harResp := HARResponse{
+ Status: r.status,
+ StatusText: respStatusText,
+ HTTPVersion: respProto,
+ Headers: respHeaders,
+ Content: harContent,
+ BodySize: len(respBytes),
+ }
+
+ entries = append(entries, HAREntry{
+ StartedDateTime: time.Unix(r.ts, 0).UTC().Format(time.RFC3339),
+ Request: harReq,
+ Response: harResp,
+ })
+ }
+
+ if !meta.Truncated && hitEntryCap {
+ meta.Truncated = true
+ meta.TruncatedReason = "max_entries"
+ }
+ meta.Exported = len(entries)
+
+ doc := HAR{
+ Log: &HARLog{
+ Version: HARVersion,
+ Creator: HARCreator{Name: "ARTEX", Version: creatorVer},
+ Entries: entries,
+ Truncated: meta.Truncated,
+ TruncatedReason: meta.TruncatedReason,
+ },
+ }
+ if meta.Truncated {
+ doc.Log.TotalMatched = meta.TotalMatched
+ }
+ return doc, meta, nil
+}
+
+func (t *Traffic) loadFullExchange(id, legacyPath string) (reqHead string, reqBody []byte, respHead string, respBody []byte, err error) {
+ var reqBlob, respBlob sql.NullString
+ err = t.db.QueryRow(`SELECT req_head,req_body,req_blob,resp_head,resp_body,resp_blob
+FROM exchange_bodies WHERE id=?`, id).Scan(&reqHead, &reqBody, &reqBlob, &respHead, &respBody, &respBlob)
+ if errors.Is(err, sql.ErrNoRows) && strings.TrimSpace(legacyPath) != "" {
+ rb, readErr := os.ReadFile(filepath.Join(t.dir, legacyPath, "request.http"))
+ if readErr != nil && !os.IsNotExist(readErr) {
+ return "", nil, "", nil, readErr
+ }
+ pb, readErr := os.ReadFile(filepath.Join(t.dir, legacyPath, "response.http"))
+ if readErr != nil && !os.IsNotExist(readErr) {
+ return "", nil, "", nil, readErr
+ }
+ reqHead, reqBody = splitLegacyHTTP(rb)
+ respHead, respBody = splitLegacyHTTP(pb)
+ return reqHead, reqBody, respHead, respBody, nil
+ }
+ if err != nil {
+ return "", nil, "", nil, err
+ }
+ if reqBlob.Valid && reqBlob.String != "" {
+ p, err := t.blobPath(reqBlob.String)
+ if err != nil {
+ return "", nil, "", nil, err
+ }
+ reqBody, err = os.ReadFile(p)
+ if err != nil {
+ return "", nil, "", nil, err
+ }
+ }
+ if respBlob.Valid && respBlob.String != "" {
+ p, err := t.blobPath(respBlob.String)
+ if err != nil {
+ return "", nil, "", nil, err
+ }
+ respBody, err = os.ReadFile(p)
+ if err != nil {
+ return "", nil, "", nil, err
+ }
+ }
+ return reqHead, reqBody, respHead, respBody, nil
+}
+
+func splitLegacyHTTP(raw []byte) (string, []byte) {
+ if idx := bytes.Index(raw, []byte("\r\n\r\n")); idx >= 0 {
+ return string(raw[:idx]), raw[idx+4:]
+ }
+ if idx := bytes.Index(raw, []byte("\n\n")); idx >= 0 {
+ return string(raw[:idx]), raw[idx+2:]
+ }
+ return string(raw), nil
+}
+
+// encodeHARBody returns plain text for valid NUL-free UTF-8 bodies, and base64
+// otherwise so binary payloads survive export and re-import bit-for-bit.
+func encodeHARBody(body []byte) (text, encoding string) {
+ if utf8.Valid(body) && bytes.IndexByte(body, 0) < 0 {
+ return string(body), ""
+ }
+ return base64.StdEncoding.EncodeToString(body), "base64"
+}
+
+func parseStoredRequestHead(raw string) (httpVersion string, headers []HARHeader) {
+ headers = []HARHeader{}
+ lines := strings.Split(strings.ReplaceAll(raw, "\r\n", "\n"), "\n")
+ if len(lines) == 0 {
+ return "", headers
+ }
+ first := strings.TrimSpace(lines[0])
+ if parts := strings.SplitN(first, " ", 3); len(parts) == 3 && strings.HasPrefix(strings.ToUpper(parts[2]), "HTTP/") {
+ httpVersion = strings.TrimSpace(parts[2])
+ }
+ headers = appendParsedHeaders(headers, lines[1:])
+ return httpVersion, headers
+}
+
+func parseStoredResponseHead(raw string) (httpVersion, statusText string, headers []HARHeader) {
+ headers = []HARHeader{}
+ lines := strings.Split(strings.ReplaceAll(raw, "\r\n", "\n"), "\n")
+ if len(lines) == 0 {
+ return "", "", headers
+ }
+ first := strings.TrimSpace(lines[0])
+ if parts := strings.SplitN(first, " ", 3); len(parts) >= 2 && strings.HasPrefix(strings.ToUpper(parts[0]), "HTTP") {
+ if strings.HasPrefix(strings.ToUpper(parts[0]), "HTTP/") {
+ httpVersion = strings.TrimSpace(parts[0])
+ }
+ if len(parts) == 3 {
+ statusText = strings.TrimSpace(parts[2])
+ }
+ }
+ headers = appendParsedHeaders(headers, lines[1:])
+ return httpVersion, statusText, headers
+}
+
+func appendParsedHeaders(dst []HARHeader, lines []string) []HARHeader {
+ for _, line := range lines {
+ line = strings.TrimRight(line, "\r")
+ if strings.TrimSpace(line) == "" {
+ continue
+ }
+ colon := strings.IndexByte(line, ':')
+ if colon <= 0 {
+ continue
+ }
+ name := strings.TrimSpace(line[:colon])
+ if name == "" || !validHeaderName(name) {
+ continue
+ }
+ val := strings.TrimSpace(line[colon+1:])
+ dst = append(dst, HARHeader{Name: name, Value: val})
+ }
+ return dst
+}
+
+func findHeaderValue(headers []HARHeader, name string) string {
+ for _, h := range headers {
+ if strings.EqualFold(h.Name, name) {
+ return h.Value
+ }
+ }
+ return ""
+}
diff --git a/traffic/har_test.go b/traffic/har_test.go
new file mode 100644
index 0000000..375ce77
--- /dev/null
+++ b/traffic/har_test.go
@@ -0,0 +1,446 @@
+package traffic
+
+import (
+ "bytes"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "strings"
+ "testing"
+
+ "github.com/Autumn-27/artex/traffic/rewrite"
+)
+
+func TestHARRoundTripPlainBase64BinaryEmptyAndLargeBlob(t *testing.T) {
+ src, err := Open(t.TempDir(), "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer src.Close()
+
+ // Install an enabled capture rewrite rule to prove HAR import NEVER runs rules
+ // or writes exchange_rewrites rows.
+ set := rewrite.Compile([]rewrite.Rule{{
+ ID: 42, Name: "should-not-apply-to-har", Enabled: true, Phase: rewrite.PhaseRequest,
+ Actions: []rewrite.Action{{Type: rewrite.ActionSetHeader, Name: "X-Injected", Value: "1"}},
+ }}, rewrite.Options{})
+ if len(set.LoadErrors()) != 0 {
+ t.Fatalf("compile rewrite rules: %v", set.LoadErrors())
+ }
+ src.SetRewriteRules(set)
+
+ binaryResp := []byte{0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0xff, 0xfe, 0x01}
+ binaryReq := []byte{0x00, 0x01, 0x02, 0x80, 0xff}
+ largeTextBody := "LARGE-HAR-NEEDLE-" + strings.Repeat("abcdefghij", (maxInlineBody/10)+50) // > 256 KiB -> blob!
+
+ inputHAR := HAR{
+ Log: &HARLog{
+ Version: "1.2",
+ Creator: HARCreator{Name: "TestBrowser", Version: "1.0"},
+ Entries: []HAREntry{
+ {
+ StartedDateTime: "2026-05-01T10:00:00.789Z",
+ Request: HARRequest{
+ Method: "POST",
+ URL: "https://app.example.com/api/v1/items/42?mode=full",
+ HTTPVersion: "HTTP/1.1",
+ Headers: []HARHeader{
+ {Name: ":method", Value: "POST"},
+ {Name: ":authority", Value: "app.example.com"},
+ {Name: "Host", Value: "app.example.com"},
+ {Name: "Content-Type", Value: "application/json"},
+ {Name: "X-Trace", Value: "one"},
+ {Name: "X-Trace", Value: "two"},
+ },
+ PostData: &HARPostData{
+ MimeType: "application/json",
+ Text: `{"action":"create","needle":"plain-req-token"}`,
+ },
+ },
+ Response: HARResponse{
+ Status: 201,
+ StatusText: "Created",
+ HTTPVersion: "HTTP/1.1",
+ Headers: []HARHeader{
+ {Name: "Content-Type", Value: "application/json; charset=utf-8"},
+ {Name: "X-Resp", Value: "ok"},
+ },
+ Content: HARContent{
+ MimeType: "application/json; charset=utf-8",
+ Text: `{"id":42,"msg":"plain-resp-marker"}`,
+ },
+ },
+ },
+ {
+ StartedDateTime: "2026-05-01T10:00:05Z",
+ Request: HARRequest{
+ Method: "POST",
+ URL: "https://cdn.example.com/upload",
+ HTTPVersion: "HTTP/2.0",
+ Headers: []HARHeader{{Name: "Content-Type", Value: "application/octet-stream"}},
+ PostData: &HARPostData{
+ MimeType: "application/octet-stream",
+ Text: base64.StdEncoding.EncodeToString(binaryReq),
+ Encoding: "base64",
+ },
+ },
+ Response: HARResponse{
+ Status: 200,
+ HTTPVersion: "HTTP/2.0",
+ Headers: []HARHeader{{Name: "Content-Type", Value: "image/png"}},
+ Content: HARContent{
+ MimeType: "image/png",
+ Text: base64.StdEncoding.EncodeToString(binaryResp),
+ Encoding: "base64",
+ },
+ },
+ },
+ {
+ StartedDateTime: "2026-05-01T10:00:10Z",
+ Request: HARRequest{
+ Method: "GET",
+ URL: "https://app.example.com/empty",
+ Headers: []HARHeader{{Name: "Accept", Value: "*/*"}},
+ },
+ Response: HARResponse{
+ Status: 204,
+ Headers: []HARHeader{},
+ Content: HARContent{},
+ },
+ },
+ {
+ StartedDateTime: "2026-05-01T10:00:15Z",
+ Request: HARRequest{
+ Method: "GET",
+ URL: "https://blob.example.com/big.txt",
+ Headers: []HARHeader{},
+ },
+ Response: HARResponse{
+ Status: 200,
+ Headers: []HARHeader{{Name: "Content-Type", Value: "text/plain"}},
+ Content: HARContent{
+ MimeType: "text/plain",
+ Text: largeTextBody,
+ },
+ },
+ },
+ },
+ },
+ }
+
+ rawIn, err := json.Marshal(inputHAR)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ res, err := src.ImportHAR(rawIn, HARImportOptions{})
+ if err != nil {
+ t.Fatalf("ImportHAR: %v", err)
+ }
+ if res.Imported != 4 || res.Skipped != 0 || res.Failed != 0 || res.Truncated {
+ t.Fatalf("ImportHAR result = %+v, want 4/0/0/false", res)
+ }
+
+ // Re-importing the exact same HAR must be idempotent (all skipped).
+ res2, err := src.ImportHAR(rawIn, HARImportOptions{})
+ if err != nil {
+ t.Fatalf("re-import HAR: %v", err)
+ }
+ if res2.Imported != 0 || res2.Skipped != 4 || res2.Failed != 0 {
+ t.Fatalf("re-import result = %+v, want 0/4/0", res2)
+ }
+
+ // Verify none of the imported exchanges are flagged rewritten or have exchange_rewrites rows.
+ var rwRows int
+ if err := src.DB().QueryRow(`SELECT COUNT(*) FROM exchange_rewrites`).Scan(&rwRows); err != nil || rwRows != 0 {
+ t.Fatalf("exchange_rewrites count = %d err=%v, want 0", rwRows, err)
+ }
+ allRows, total, err := src.Page(PageQuery{RespMin: -1, RespMax: -1}, 0, 20)
+ if err != nil || total != 4 || len(allRows) != 4 {
+ t.Fatalf("Page after import = (%d, %d, %v), want (4, 4, nil)", len(allRows), total, err)
+ }
+ for _, r := range allRows {
+ if !strings.HasPrefix(r.ID, "har-") {
+ t.Fatalf("expected har- prefix on id %q", r.ID)
+ }
+ if r.Rewritten {
+ t.Fatalf("imported exchange %s unexpectedly flagged rewritten", r.ID)
+ }
+ if rw, ids, err := src.RewriteInfo(r.ID); err != nil || rw || len(ids) != 0 {
+ t.Fatalf("RewriteInfo(%s) = (%v, %v, %v), want (false, nil, nil)", r.ID, rw, ids, err)
+ }
+ }
+
+ // Verify searchable via FTS (both inline body and spilled large text body).
+ if rows, tot, err := src.Page(PageQuery{Body: "plain-resp-marker", RespMin: -1, RespMax: -1}, 0, 10); err != nil || tot != 1 || len(rows) != 1 {
+ t.Fatalf("FTS search inline body = (%d, %d, %v), want 1", len(rows), tot, err)
+ }
+ if rows, tot, err := src.Page(PageQuery{Body: "LARGE-HAR-NEEDLE", RespMin: -1, RespMax: -1}, 0, 10); err != nil || tot != 1 || len(rows) != 1 {
+ t.Fatalf("FTS search blob body = (%d, %d, %v), want 1", len(rows), tot, err)
+ }
+
+ // Verify large body actually spilled to a blob and registered in blob_refs.
+ var blobHash string
+ var blobRefCount int
+ if err := src.DB().QueryRow(`SELECT resp_blob FROM exchange_bodies b JOIN exchanges e ON e.id=b.id WHERE e.host='blob.example.com'`).Scan(&blobHash); err != nil || blobHash == "" {
+ t.Fatalf("large body did not spill to blob: hash=%q err=%v", blobHash, err)
+ }
+ if err := src.DB().QueryRow(`SELECT COUNT(*) FROM blob_refs WHERE hash=?`, blobHash).Scan(&blobRefCount); err != nil || blobRefCount != 1 {
+ t.Fatalf("blob_refs count for %s = %d err=%v, want 1", blobHash, blobRefCount, err)
+ }
+
+ // Export HAR from src.
+ exported, meta, err := src.ExportHAR(PageQuery{RespMin: -1, RespMax: -1}, HARExportOptions{CreatorVersion: "2.3.0"})
+ if err != nil {
+ t.Fatalf("ExportHAR: %v", err)
+ }
+ if meta.Exported != 4 || meta.TotalMatched != 4 || meta.Truncated || meta.TruncatedReason != "" {
+ t.Fatalf("ExportHAR meta = %+v", meta)
+ }
+ if exported.Log.Version != "1.2" || exported.Log.Creator.Name != "ARTEX" || exported.Log.Creator.Version != "2.3.0" {
+ t.Fatalf("ExportHAR header = %+v", exported.Log)
+ }
+ if len(exported.Log.Entries) != 4 {
+ t.Fatalf("ExportHAR entries = %d, want 4", len(exported.Log.Entries))
+ }
+
+ // Verify no invented fields (time, serverIPAddress) in marshaled HAR JSON.
+ rawExported, err := json.Marshal(exported)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(string(rawExported), `"serverIPAddress"`) || strings.Contains(string(rawExported), `"time":`) {
+ t.Fatalf("exported HAR invented prohibited fields: %s", string(rawExported))
+ }
+
+ // Verify stable chronological ordering & exact body encodings.
+ e0 := exported.Log.Entries[0]
+ if e0.Request.URL != "https://app.example.com/api/v1/items/42?mode=full" || e0.Response.Content.Encoding != "" || e0.Response.Content.Text != `{"id":42,"msg":"plain-resp-marker"}` {
+ t.Fatalf("entry 0 mismatch: %+v", e0)
+ }
+ e1 := exported.Log.Entries[1]
+ if e1.Response.Content.Encoding != "base64" || e1.Request.PostData == nil || e1.Request.PostData.Encoding != "base64" {
+ t.Fatalf("entry 1 binary encodings wrong: req=%+v resp=%+v", e1.Request.PostData, e1.Response.Content)
+ }
+ gotBinResp, err := base64.StdEncoding.DecodeString(e1.Response.Content.Text)
+ if err != nil || !bytes.Equal(gotBinResp, binaryResp) {
+ t.Fatalf("entry 1 binary resp mismatch: got=%x err=%v", gotBinResp, err)
+ }
+ gotBinReq, err := base64.StdEncoding.DecodeString(e1.Request.PostData.Text)
+ if err != nil || !bytes.Equal(gotBinReq, binaryReq) {
+ t.Fatalf("entry 1 binary req mismatch: got=%x err=%v", gotBinReq, err)
+ }
+ e2 := exported.Log.Entries[2]
+ if e2.Request.PostData != nil || e2.Response.Content.Size != 0 || e2.Response.Content.Text != "" {
+ t.Fatalf("entry 2 empty body mismatch: %+v", e2)
+ }
+ e3 := exported.Log.Entries[3]
+ if e3.Response.Content.Size != len(largeTextBody) || e3.Response.Content.Text != largeTextBody || e3.Response.Content.Encoding != "" {
+ t.Fatalf("entry 3 large blob body truncated or altered: size=%d len=%d", e3.Response.Content.Size, len(e3.Response.Content.Text))
+ }
+
+ // Re-importing the exported HAR into src must be 100% idempotent (same deterministic IDs!).
+ reimpSame, err := src.ImportHAR(rawExported, HARImportOptions{})
+ if err != nil {
+ t.Fatalf("re-import exported HAR into src: %v", err)
+ }
+ if reimpSame.Imported != 0 || reimpSame.Skipped != 4 || reimpSame.Failed != 0 {
+ t.Fatalf("re-import exported HAR into src = %+v, want 0/4/0", reimpSame)
+ }
+
+ // Re-importing the exported HAR into a fresh store must yield identical IDs, metadata, and bodies.
+ dst, err := Open(t.TempDir(), "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer dst.Close()
+
+ reimpFresh, err := dst.ImportHAR(rawExported, HARImportOptions{})
+ if err != nil {
+ t.Fatalf("import exported HAR into dst: %v", err)
+ }
+ if reimpFresh.Imported != 4 || reimpFresh.Skipped != 0 || reimpFresh.Failed != 0 {
+ t.Fatalf("dst import = %+v, want 4/0/0", reimpFresh)
+ }
+
+ exportedDst, _, err := dst.ExportHAR(PageQuery{RespMin: -1, RespMax: -1}, HARExportOptions{CreatorVersion: "2.3.0"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ rawDst, err := json.Marshal(exportedDst)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(rawExported, rawDst) {
+ t.Fatalf("dst round-trip HAR differs from src export")
+ }
+}
+
+func TestHARImportValidationDuplicatesAndPartialErrors(t *testing.T) {
+ tr, err := Open(t.TempDir(), "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer tr.Close()
+
+ badDocs := []struct {
+ name string
+ raw string
+ want string
+ }{
+ {"empty", "", "empty HAR"},
+ {"malformed json", `{"log":`, "malformed JSON"},
+ {"trailing garbage", `{"log":{"version":"1.2","entries":[]}} extra`, "trailing content"},
+ {"missing log", `{}`, "missing log"},
+ {"missing entries", `{"log":{"version":"1.2"}}`, "missing log.entries"},
+ {"null entries", `{"log":{"version":"1.2","entries":null}}`, "missing log.entries"},
+ {"unsupported version 1.1", `{"log":{"version":"1.1","entries":[]}}`, "unsupported HAR version"},
+ {"unsupported version 2.0", `{"log":{"version":"2.0","entries":[]}}`, "unsupported HAR version"},
+ {"empty version", `{"log":{"version":"","entries":[]}}`, "unsupported HAR version"},
+ }
+ for _, tc := range badDocs {
+ t.Run(tc.name, func(t *testing.T) {
+ _, err := tr.ImportHAR([]byte(tc.raw), HARImportOptions{})
+ if !errors.Is(err, ErrInvalidHAR) || !strings.Contains(err.Error(), tc.want) {
+ t.Fatalf("ImportHAR(%s) err = %v, want ErrInvalidHAR containing %q", tc.name, err, tc.want)
+ }
+ })
+ }
+
+ // Duplicate entries inside one HAR + bad entries mixed with valid ones.
+ mixed := `{
+ "log": {
+ "version": "1.2",
+ "entries": [
+ {
+ "startedDateTime": "2026-05-01T12:00:00Z",
+ "request": {"method": "GET", "url": "https://dup.example/a", "headers": []},
+ "response": {"status": 200, "headers": [], "content": {"text": "ok"}}
+ },
+ {
+ "startedDateTime": "2026-05-01T12:00:00Z",
+ "request": {"method": "GET", "url": "https://dup.example/a", "headers": []},
+ "response": {"status": 200, "headers": [], "content": {"text": "ok"}}
+ },
+ {
+ "startedDateTime": "not-a-timestamp",
+ "request": {"method": "GET", "url": "https://bad.example/ts", "headers": []},
+ "response": {"status": 200, "headers": [], "content": {}}
+ },
+ {
+ "startedDateTime": "2026-05-01T12:00:01Z",
+ "request": {"method": "GET", "url": "https://bad.example/hdr", "headers": [{"name": "X-Bad", "value": "a\r\nb"}]},
+ "response": {"status": 200, "headers": [], "content": {}}
+ },
+ {
+ "startedDateTime": "2026-05-01T12:00:02Z",
+ "request": {"method": "GET", "url": "https://bad.example/b64", "headers": []},
+ "response": {"status": 200, "headers": [], "content": {"text": "!!!not-base64!!!", "encoding": "base64"}}
+ },
+ {
+ "startedDateTime": "2026-05-01T12:00:03Z",
+ "request": {"method": "GET", "url": "https://good.example/b", "headers": []},
+ "response": {"status": 200, "headers": [], "content": {"text": "second"}}
+ }
+ ]
+ }
+ }`
+ res, err := tr.ImportHAR([]byte(mixed), HARImportOptions{})
+ if err != nil {
+ t.Fatalf("mixed ImportHAR: %v", err)
+ }
+ if res.Imported != 2 || res.Skipped != 1 || res.Failed != 3 || len(res.Errors) != 3 {
+ t.Fatalf("mixed ImportHAR result = %+v, want imported=2 skipped=1 failed=3 errors=3", res)
+ }
+
+ // Entry cap returns ErrInvalidHAR.
+ if _, err := tr.ImportHAR([]byte(mixed), HARImportOptions{MaxEntries: 2}); !errors.Is(err, ErrInvalidHAR) {
+ t.Fatalf("MaxEntries exceeded err = %v, want ErrInvalidHAR", err)
+ }
+
+ // Byte cap truncates cleanly and reports remaining skipped.
+ byteCapHAR := `{
+ "log": {
+ "version": "1.2",
+ "entries": [
+ {
+ "startedDateTime": "2026-05-01T12:01:00Z",
+ "request": {"method": "GET", "url": "https://cap.example/1", "headers": []},
+ "response": {"status": 200, "headers": [], "content": {"text": "1234567890"}}
+ },
+ {
+ "startedDateTime": "2026-05-01T12:01:01Z",
+ "request": {"method": "GET", "url": "https://cap.example/2", "headers": []},
+ "response": {"status": 200, "headers": [], "content": {"text": "1234567890"}}
+ }
+ ]
+ }
+ }`
+ capRes, err := tr.ImportHAR([]byte(byteCapHAR), HARImportOptions{MaxTotalBytes: 15})
+ if err != nil {
+ t.Fatalf("byte-capped ImportHAR: %v", err)
+ }
+ if capRes.Imported != 1 || capRes.Skipped != 1 || !capRes.Truncated || len(capRes.Errors) != 1 {
+ t.Fatalf("byte-capped ImportHAR = %+v, want imported=1 skipped=1 truncated=true", capRes)
+ }
+}
+
+func TestHARExportFiltersAndTruncationCaps(t *testing.T) {
+ tr, err := Open(t.TempDir(), "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer tr.Close()
+
+ insert := func(id string, ts int64, host string, status int, body string) {
+ t.Helper()
+ if _, err := tr.DB().Exec(`INSERT INTO exchanges(id,ts,host,method,url_template,url,status,content_type,req_len,resp_len,path)
+VALUES(?,?,?,?,?,?,?,?,?,?,?)`, id, ts, host, "GET", "/"+id, "https://"+host+"/"+id, status, "text/plain", 0, len(body), ""); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := tr.DB().Exec(`INSERT INTO exchange_bodies(id,req_head,req_body,resp_head,resp_body)
+VALUES(?,?,?,?,?)`, id, "GET /"+id+" HTTP/1.1\nHost: "+host, []byte{}, "HTTP/1.1 200 OK", []byte(body)); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ insert("e-2", 20, "alpha.example", 200, "bbbbbbbbbb")
+ insert("e-1", 10, "alpha.example", 404, "aaaaaaaaaa")
+ insert("e-3", 30, "beta.example", 200, "cccccccccc")
+
+ // Filter by host + status, verify chronological order.
+ doc, meta, err := tr.ExportHAR(PageQuery{Host: "alpha.example", RespMin: -1, RespMax: -1}, HARExportOptions{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if meta.Exported != 2 || meta.TotalMatched != 2 || meta.Truncated {
+ t.Fatalf("filtered export meta = %+v", meta)
+ }
+ if doc.Log.Entries[0].Request.URL != "https://alpha.example/e-1" || doc.Log.Entries[1].Request.URL != "https://alpha.example/e-2" {
+ t.Fatalf("export not in stable (ts,id) order: %+v", doc.Log.Entries)
+ }
+
+ // Truncation by MaxEntries.
+ docEntryCap, metaEntryCap, err := tr.ExportHAR(PageQuery{RespMin: -1, RespMax: -1}, HARExportOptions{MaxEntries: 2})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !metaEntryCap.Truncated || metaEntryCap.TruncatedReason != "max_entries" || metaEntryCap.Exported != 2 || metaEntryCap.TotalMatched != 3 {
+ t.Fatalf("entry-capped meta = %+v", metaEntryCap)
+ }
+ if !docEntryCap.Log.Truncated || docEntryCap.Log.TruncatedReason != "max_entries" || docEntryCap.Log.TotalMatched != 3 {
+ t.Fatalf("entry-capped log fields = %+v", docEntryCap.Log)
+ }
+
+ // Truncation by MaxTotalBytes.
+ docByteCap, metaByteCap, err := tr.ExportHAR(PageQuery{RespMin: -1, RespMax: -1}, HARExportOptions{MaxTotalBytes: 15})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !metaByteCap.Truncated || metaByteCap.TruncatedReason != "max_bytes" || metaByteCap.Exported != 1 || metaByteCap.TotalMatched != 3 {
+ t.Fatalf("byte-capped meta = %+v", metaByteCap)
+ }
+ if !docByteCap.Log.Truncated || docByteCap.Log.TruncatedReason != "max_bytes" || docByteCap.Log.TotalMatched != 3 {
+ t.Fatalf("byte-capped log fields = %+v", docByteCap.Log)
+ }
+}
diff --git a/traffic/traffic.go b/traffic/traffic.go
index f708d18..8444b83 100644
--- a/traffic/traffic.go
+++ b/traffic/traffic.go
@@ -1104,22 +1104,10 @@ func statusFilter(s string) (cond string, args []any, ok bool) {
return "", nil, false
}
-// Page returns one page of exchange metadata for the traffic list, filtered by
-// the criteria in f (all optional, combined with AND) and ordered by the
-// requested column. Query is the broad search box (metadata columns OR, when the
-// term is long enough for the trigram index, captured request/response text);
-// Body narrows to exchanges whose captured text matches, via that same index.
-// Also returns the total number of rows matching the filter (for the UI's
-// pagination). Bodies are never included in the rows.
-func (t *Traffic) Page(f PageQuery, page, size int) (rows []ExchangeMeta, total int, err error) {
- if size <= 0 || size > 500 {
- size = 100
- }
- if page < 0 {
- page = 0
- }
- where := ""
- var args []any
+// pageWhere builds the SQL WHERE clause and bound arguments for PageQuery.
+// Page and ExportHAR share this so list queries and HAR exports honor the exact
+// same filter semantics.
+func (t *Traffic) pageWhere(f PageQuery) (where string, args []any) {
add := func(cond string, vs ...any) {
if where == "" {
where = " WHERE "
@@ -1170,6 +1158,24 @@ func (t *Traffic) Page(f PageQuery, page, size int) (rows []ExchangeMeta, total
add(cond, arg)
}
}
+ return where, args
+}
+
+// Page returns one page of exchange metadata for the traffic list, filtered by
+// the criteria in f (all optional, combined with AND) and ordered by the
+// requested column. Query is the broad search box (metadata columns OR, when the
+// term is long enough for the trigram index, captured request/response text);
+// Body narrows to exchanges whose captured text matches, via that same index.
+// Also returns the total number of rows matching the filter (for the UI's
+// pagination). Bodies are never included in the rows.
+func (t *Traffic) Page(f PageQuery, page, size int) (rows []ExchangeMeta, total int, err error) {
+ if size <= 0 || size > 500 {
+ size = 100
+ }
+ if page < 0 {
+ page = 0
+ }
+ where, args := t.pageWhere(f)
if err = t.db.QueryRow(`SELECT COUNT(*) FROM exchanges`+where, args...).Scan(&total); err != nil {
return nil, 0, err
}
diff --git a/web/src/app/(main)/function/traffic/page.tsx b/web/src/app/(main)/function/traffic/page.tsx
index 74cb0ca..4cbb009 100644
--- a/web/src/app/(main)/function/traffic/page.tsx
+++ b/web/src/app/(main)/function/traffic/page.tsx
@@ -7,6 +7,7 @@ import {
ArrowUpNarrowWideIcon,
ChevronLeftIcon,
ChevronRightIcon,
+ DownloadIcon,
EraserIcon,
FilterXIcon,
ListChecksIcon,
@@ -14,11 +15,14 @@ import {
RadioTowerIcon,
SearchIcon,
Trash2Icon,
+ UploadIcon,
+ XIcon,
} from "lucide-react";
import { toast } from "sonner";
import { HttpCodeBlock } from "@/components/http-code-block";
import { LinkTrafficDialog } from "@/components/link-traffic-dialog";
+import { Alert, AlertDescription } from "@/components/ui/alert";
import {
AlertDialog,
AlertDialogAction,
@@ -44,7 +48,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip
import { api } from "@/lib/api";
import { setVisibleInterval } from "@/lib/polling";
import { useStoredSortPreference } from "@/lib/sort-preference";
-import type { TrafficDetail, TrafficExchange, TrafficHost, TrafficResp } from "@/lib/types";
+import type { TrafficDetail, TrafficExchange, TrafficHARImportResult, TrafficHost, TrafficResp } from "@/lib/types";
import { cn } from "@/lib/utils";
import { intlLocale, t } from "@/i18n";
@@ -159,6 +163,13 @@ export default function TrafficPage() {
const [deleting, setDeleting] = React.useState(false);
const [reloadTick, setReloadTick] = React.useState(0); // manual refetch trigger
+ // HAR 1.2 import/export state
+ const harInputRef = React.useRef<HTMLInputElement | null>(null);
+ const [harImporting, setHarImporting] = React.useState(false);
+ const [harExporting, setHarExporting] = React.useState(false);
+ const [harSummary, setHarSummary] = React.useState<TrafficHARImportResult | null>(null);
+ const [harError, setHarError] = React.useState<string | null>(null);
+
// Debounce both filters so we don't refetch on every keystroke.
React.useEffect(() => {
const t = setTimeout(() => setHostQ(host.trim()), 300);
@@ -367,6 +378,76 @@ export default function TrafficPage() {
: { field, direction: "desc" },
);
+ const handleHarFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
+ const file = event.target.files?.[0];
+ event.target.value = "";
+ if (!file) return;
+ setHarError(null);
+ setHarSummary(null);
+ if (file.size > 32 * 1024 * 1024) {
+ const msg = t("HAR file exceeds the 32 MiB limit");
+ setHarError(msg);
+ toast.error(msg);
+ return;
+ }
+ setHarImporting(true);
+ try {
+ const raw = await file.text();
+ const res = await api.trafficImportHAR(raw);
+ setHarSummary(res);
+ const summary = t("HAR import complete: {imported} imported, {skipped} skipped, {failed} failed", {
+ imported: res.imported,
+ skipped: res.skipped,
+ failed: res.failed,
+ });
+ if (res.failed > 0 || res.truncated) {
+ toast.warning(summary);
+ } else {
+ toast.success(summary);
+ }
+ setPage(0);
+ setReloadTick((n) => n + 1);
+ } catch (e) {
+ const msg = t("HAR import failed: {error}", { error: (e as Error).message });
+ setHarError(msg);
+ toast.error(msg);
+ } finally {
+ setHarImporting(false);
+ }
+ };
+
+ const handleHarExport = async () => {
+ setHarExporting(true);
+ try {
+ const meta = await api.trafficExportHAR({
+ host: hostQ,
+ method,
+ q: queryQ,
+ body: bodyQ,
+ path: pathQ,
+ status: statusFilter,
+ rewritten: rewrittenFilter,
+ respMin: respMinQ,
+ respMax: respMaxQ,
+ });
+ if (meta.truncated) {
+ toast.warning(
+ t("Exported {exported} of {matched} matching exchanges (truncated: {reason})", {
+ exported: meta.exported,
+ matched: meta.matched,
+ reason: meta.truncatedReason ?? "limit",
+ }),
+ );
+ } else {
+ toast.success(t("Exported {count} exchanges to HAR", { count: meta.exported }));
+ }
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ setHarExporting(false);
+ }
+ };
+
const exchanges = React.useMemo(() => traffic?.exchanges ?? [], [traffic]);
const total = traffic?.total ?? exchanges.length;
const pageCount = Math.max(1, Math.ceil(total / size));
@@ -396,9 +477,76 @@ export default function TrafficPage() {
<span className="text-xs text-muted-foreground tabular-nums">
{t("{count} records", { count: traffic?.count ?? 0 })}
</span>
+ <input
+ ref={harInputRef}
+ type="file"
+ accept=".har,application/json"
+ className="hidden"
+ onChange={(e) => void handleHarFileChange(e)}
+ />
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-8"
+ disabled={harImporting}
+ onClick={() => harInputRef.current?.click()}
+ >
+ {harImporting ? <Loader2Icon className="size-3.5 animate-spin" /> : <UploadIcon className="size-3.5" />}
+ {harImporting ? t("Importing HAR…") : t("Import HAR")}
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-8"
+ disabled={harExporting || !traffic?.count}
+ onClick={() => void handleHarExport()}
+ >
+ {harExporting ? <Loader2Icon className="size-3.5 animate-spin" /> : <DownloadIcon className="size-3.5" />}
+ {harExporting ? t("Exporting HAR…") : t("Export HAR")}
+ </Button>
</div>
</div>
+ {harError ? (
+ <Alert variant="destructive" className="flex items-center justify-between gap-2 py-2">
+ <AlertDescription className="text-xs">{harError}</AlertDescription>
+ <Button variant="ghost" size="icon-xs" aria-label={t("Dismiss")} onClick={() => setHarError(null)}>
+ <XIcon className="size-3.5" />
+ </Button>
+ </Alert>
+ ) : null}
+
+ {harSummary ? (
+ <Alert className="flex items-start justify-between gap-2 py-2">
+ <AlertDescription className="space-y-1 text-xs">
+ <p>
+ {t("HAR import complete: {imported} imported, {skipped} skipped, {failed} failed", {
+ imported: harSummary.imported,
+ skipped: harSummary.skipped,
+ failed: harSummary.failed,
+ })}
+ </p>
+ {harSummary.truncated ? (
+ <p className="text-amber-600 dark:text-amber-400">
+ {t("HAR import stopped early at the 32 MiB decoded body cap.")}
+ </p>
+ ) : null}
+ {harSummary.errors && harSummary.errors.length > 0 ? (
+ <ul className="list-disc pl-4 text-muted-foreground">
+ {harSummary.errors.slice(0, 5).map((item) => (
+ <li key={`${item.index}-${item.reason}`} className="font-mono">
+ #{item.index}: {item.reason}
+ </li>
+ ))}
+ </ul>
+ ) : null}
+ </AlertDescription>
+ <Button variant="ghost" size="icon-xs" aria-label={t("Dismiss")} onClick={() => setHarSummary(null)}>
+ <XIcon className="size-3.5" />
+ </Button>
+ </Alert>
+ ) : null}
+
{/* Toolbar */}
<div className="flex flex-wrap items-center gap-2">
<Popover open={pickerOpen} onOpenChange={setPickerOpen}>
diff --git a/web/src/i18n/locales/tr.json b/web/src/i18n/locales/tr.json
index c3c3ae0..e5deaed 100644
--- a/web/src/i18n/locales/tr.json
+++ b/web/src/i18n/locales/tr.json
@@ -767,6 +767,7 @@
"Discovery time": "Keşif zamanı",
"Discovery time currently ascending, click to toggle sort direction": "Keşif zamanı şu anda artan sırada, sıralama yönünü değiştirmek için tıklayın",
"Discovery time currently descending, click to toggle sort direction": "Keşif zamanı şu anda azalan sırada, sıralama yönünü değiştirmek için tıklayın",
+ "Dismiss": "Kapat",
"Dismiss update notice": "Güncelleme bildirimini kapat",
"dismissed": "yok sayıldı",
"Dismissed": "Yok sayıldı",
@@ -925,9 +926,13 @@
"Export failed: {error}": "Dışa aktarma başarısız: {error}",
"Export findings": "Bulguları dışa aktar",
"Export format": "Dışa aktarma biçimi",
+ "Export HAR": "HAR dışa aktar",
"Export scope": "Dışa aktarma kapsamı",
"Export the {count} selected items": "Seçili {count} öğeyi dışa aktar",
"Export the current filter results ({count} items)": "Mevcut süzgeç sonuçlarını dışa aktar ({count} öğe)",
+ "Exported {count} exchanges to HAR": "{count} değişim HAR olarak dışa aktarıldı",
+ "Exported {exported} of {matched} matching exchanges (truncated: {reason})": "Eşleşen {matched} değişimin {exported} tanesi dışa aktarıldı (kısaltıldı: {reason})",
+ "Exporting HAR…": "HAR dışa aktarılıyor…",
"Exporting…": "Dışa aktarılıyor…",
"External MCP tool servers · visibility granted per agent": "Harici MCP araç sunucuları · görünürlük ajan bazında verilir",
"Fact": "Olgu",
@@ -1070,6 +1075,13 @@
"greater than": "büyüktür",
"greater than or equal": "büyük veya eşittir",
"Handle automatically after the timeout instead of waiting": "Beklemek yerine zaman aşımından sonra otomatik olarak işle",
+ "HAR export failed: {error}": "HAR dışa aktarma başarısız: {error}",
+ "HAR export is not available in mock mode": "HAR dışa aktarma sahte modda kullanılamaz",
+ "HAR file exceeds the 32 MiB limit": "HAR dosyası 32 MiB sınırını aşıyor",
+ "HAR import complete: {imported} imported, {skipped} skipped, {failed} failed": "HAR içe aktarma tamamlandı: {imported} içe aktarıldı, {skipped} atlandı, {failed} başarısız",
+ "HAR import failed: {error}": "HAR içe aktarma başarısız: {error}",
+ "HAR import is not available in mock mode": "HAR içe aktarma sahte modda kullanılamaz",
+ "HAR import stopped early at the 32 MiB decoded body cap.": "HAR içe aktarma 32 MiB çözülmüş gövde sınırında erken durdu.",
"Hard delete": "Kalıcı silme",
"Header": "Başlık",
"Header name": "Başlık adı",
@@ -1112,6 +1124,8 @@
"Idle": "Boşta",
"Ignored": "Yok sayıldı",
"Implicit TLS": "Örtük TLS",
+ "Import HAR": "HAR içe aktar",
+ "Importing HAR…": "HAR içe aktarılıyor…",
"In": "Girdi",
"In {input} (incl. cache {cache}) · Out {output}": "Girdi {input} (önbellek {cache} dahil) · Çıktı {output}",
"In flight": "Devam eden",
diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts
index 53f1472..339d541 100644
--- a/web/src/lib/api.ts
+++ b/web/src/lib/api.ts
@@ -102,6 +102,8 @@ import type {
TrafficDetail,
TrafficEvidenceRef,
TrafficEvidenceRole,
+ TrafficHARExportMeta,
+ TrafficHARImportResult,
TrafficHost,
TrafficReplayRequest,
TrafficReplayResult,
@@ -886,6 +888,77 @@ export const api = {
apply_rules: Boolean(req.apply_rules),
});
},
+ // Imports a raw HAR 1.2 JSON document into the traffic store.
+ trafficImportHAR: async (rawJSON: string): Promise<TrafficHARImportResult> => {
+ if (MOCK) throw new Error(t("HAR import is not available in mock mode"));
+ return http<TrafficHARImportResult>(`/traffic/import/har`, {
+ method: "POST",
+ body: rawJSON,
+ });
+ },
+ // Exports filtered traffic as a HAR 1.2 file download and returns truncation metadata.
+ trafficExportHAR: async (
+ opts: {
+ host?: string;
+ method?: string;
+ q?: string;
+ body?: string;
+ path?: string;
+ status?: string;
+ rewritten?: string;
+ respMin?: string;
+ respMax?: string;
+ } = {},
+ ): Promise<TrafficHARExportMeta> => {
+ if (MOCK) throw new Error(t("HAR export is not available in mock mode"));
+ const qs = new URLSearchParams();
+ if (opts.host) qs.set("host", opts.host);
+ if (opts.method && opts.method !== "all") qs.set("method", opts.method);
+ if (opts.q) qs.set("q", opts.q);
+ if (opts.body) qs.set("body", opts.body);
+ if (opts.path) qs.set("path", opts.path);
+ if (opts.status && opts.status !== "all") qs.set("status", opts.status);
+ if (opts.rewritten && opts.rewritten !== "all") qs.set("rewritten", opts.rewritten);
+ if (opts.respMin) qs.set("resp_min", opts.respMin);
+ if (opts.respMax) qs.set("resp_max", opts.respMax);
+ const suffix = qs.toString();
+ const token = getToken();
+ const r = await fetch(`/api/traffic/export/har${suffix ? `?${suffix}` : ""}`, {
+ headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}) },
+ });
+ if (r.status === 401) {
+ if (typeof window !== "undefined") {
+ localStorage.removeItem("artex_token");
+ document.cookie = "artex_token=; path=/; max-age=0";
+ window.location.href = "/login";
+ }
+ throw new Error(t("Unauthorized"));
+ }
+ if (!r.ok) {
+ let msg = String(r.status);
+ try {
+ const payload = (await r.json()) as { error?: unknown };
+ if (typeof payload.error === "string" && payload.error.trim()) msg = payload.error.trim();
+ } catch {
+ // Keep status fallback.
+ }
+ throw new ApiError(t("HAR export failed: {error}", { error: msg }), r.status);
+ }
+ const blob = await r.blob();
+ const exported = Number(r.headers.get("X-ARTEX-HAR-Exported") ?? "0") || 0;
+ const matched = Number(r.headers.get("X-ARTEX-HAR-Matched") ?? "0") || 0;
+ const truncated = r.headers.get("X-ARTEX-HAR-Truncated") === "true";
+ const truncatedReason = r.headers.get("X-ARTEX-HAR-Truncated-Reason") ?? undefined;
+ const objectUrl = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = objectUrl;
+ a.download = "artex-traffic.har";
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ URL.revokeObjectURL(objectUrl);
+ return { exported, matched, truncated, truncatedReason };
+ },
trafficHosts: () => get<{ hosts: TrafficHost[] }>(`/traffic/hosts`),
trafficDeleteHost: (host: string) => del<{ deleted: number }>(`/traffic?host=${encodeURIComponent(host)}`),
trafficDeleteHosts: (hosts: string[]) => del<{ deleted: number }>(`/traffic/hosts`, { hosts }),
diff --git a/web/src/lib/types.ts b/web/src/lib/types.ts
index 9f26e1d..10e6e03 100644
--- a/web/src/lib/types.ts
+++ b/web/src/lib/types.ts
@@ -914,6 +914,27 @@ export interface TrafficRewriteStats {
sweeps: number;
}
+export interface TrafficHARImportError {
+ index: number;
+ url?: string;
+ reason: string;
+}
+
+export interface TrafficHARImportResult {
+ imported: number;
+ skipped: number;
+ failed: number;
+ truncated?: boolean;
+ errors?: TrafficHARImportError[];
+}
+
+export interface TrafficHARExportMeta {
+ exported: number;
+ matched: number;
+ truncated: boolean;
+ truncatedReason?: string;
+}
+
export interface TrafficResp {
enabled: boolean;
proxy?: string;