proxelar 0.8.0

MITM proxy for HTTP/HTTPS traffic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
use axum::{
    extract::{
        ws::{Message, WebSocket, WebSocketUpgrade},
        Path, Query, State,
    },
    response::{Html, IntoResponse},
    routing::{get, post, put},
    Json, Router,
};
use bytes::Bytes;
use http::{
    header::{AUTHORIZATION, CACHE_CONTROL, CONTENT_TYPE, COOKIE, HOST, ORIGIN, SET_COOKIE},
    HeaderMap, Uri,
};
use proxyapi::{FlowFilter, InterceptConfig, InterceptDecision, ProxyEvent, SessionRecorder};
use proxyapi_models::{CapturedFlow, HeaderBlock, HeaderField, ProxiedRequest, TrafficSession};
use rand::RngExt;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::{broadcast, mpsc, RwLock};
use tokio_util::sync::CancellationToken;

use crate::wireguard_setup::WireGuardSetup;

const INDEX_HTML: &str = include_str!("assets/index.html");
const STYLE_CSS: &str = include_str!("assets/style.css");
const APP_JS: &str = include_str!("assets/app.js");
const BROWSER_COOKIE: &str = "proxelar_session";

struct WebState {
    broadcast_tx: broadcast::Sender<String>,
    api_token: String,
    browser_token: String,
    intercept: Arc<InterceptConfig>,
    replay_tx: mpsc::Sender<ProxiedRequest>,
    recorder: Arc<RwLock<SessionRecorder>>,
    wireguard_setup: Option<Arc<WireGuardSetup>>,
}

fn generate_token() -> String {
    let bytes: [u8; 32] = rand::rng().random();
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

/// A message sent from the browser to the proxy.
#[derive(Deserialize)]
#[serde(tag = "type")]
enum ClientMessage {
    /// Enable or disable intercept mode.
    SetIntercept { enabled: bool },
    /// Drop a pending request (returns 504 to the client).
    Drop { id: u64 },
    /// Forward a pending request (with any edits the user made).
    Modified {
        id: u64,
        method: String,
        uri: String,
        headers: ClientHeaders,
        body: ClientBody,
    },
    /// Replay a previously captured request.
    Replay {
        method: String,
        uri: String,
        headers: ClientHeaders,
        body: ClientBody,
    },
}

#[derive(Deserialize)]
#[serde(untagged)]
enum ClientBody {
    Text(String),
    Bytes { bytes: Vec<u8> },
    Structured { format: String, text: String },
}

impl Default for ClientBody {
    fn default() -> Self {
        Self::Text(String::new())
    }
}

impl ClientBody {
    fn try_into_bytes(self) -> Result<Bytes, String> {
        match self {
            Self::Text(body) => Ok(Bytes::from(body)),
            Self::Bytes { bytes } => Ok(Bytes::from(bytes)),
            Self::Structured { format, text } => {
                proxyapi::content::encode_edit(&format, &text).map_err(|error| error.to_string())
            }
        }
    }
}

#[derive(Deserialize)]
#[serde(untagged)]
enum ClientHeaders {
    Map(HashMap<String, HeaderValues>),
    List(Vec<HeaderField>),
}

#[derive(Deserialize)]
#[serde(untagged)]
enum HeaderValues {
    One(String),
    Many(Vec<String>),
}

impl ClientHeaders {
    fn try_into_header_block(self) -> Result<HeaderBlock, String> {
        match self {
            Self::List(headers) => Ok(HeaderBlock::from_fields(headers)),
            Self::Map(headers) => {
                let mut output = HeaderBlock::new();
                for (name, values) in headers {
                    match values {
                        HeaderValues::One(value) => output
                            .add(&name, value)
                            .map_err(|error| format!("invalid header: {error}"))?,
                        HeaderValues::Many(values) => {
                            for value in values {
                                output
                                    .add(&name, value)
                                    .map_err(|error| format!("invalid header: {error}"))?;
                            }
                        }
                    }
                }
                Ok(output)
            }
        }
    }
}

/// Status broadcast to all connected browser clients when intercept state changes.
#[derive(Serialize)]
struct InterceptStatus {
    enabled: bool,
    pending_count: usize,
}

pub(crate) struct ServerConfig {
    pub(crate) addr: std::net::IpAddr,
    pub(crate) port: u16,
    pub(crate) token: Option<String>,
    pub(crate) open_browser: bool,
    pub(crate) wireguard_setup: Option<Arc<WireGuardSetup>>,
    pub(crate) browser_proxy: Option<(std::net::SocketAddr, std::path::PathBuf)>,
}

pub async fn run(
    mut event_rx: mpsc::Receiver<ProxyEvent>,
    intercept: Arc<InterceptConfig>,
    replay_tx: mpsc::Sender<ProxiedRequest>,
    recorder: Arc<RwLock<SessionRecorder>>,
    config: ServerConfig,
    cancel: CancellationToken,
) {
    let api_token = config
        .token
        .filter(|token| !token.is_empty())
        .unwrap_or_else(generate_token);
    let browser_token = generate_token();
    let (broadcast_tx, _) = broadcast::channel::<String>(256);
    let state = Arc::new(WebState {
        broadcast_tx: broadcast_tx.clone(),
        api_token: api_token.clone(),
        browser_token: browser_token.clone(),
        intercept,
        replay_tx,
        recorder,
        wireguard_setup: config.wireguard_setup,
    });

    // Background task: forward proxy events to broadcast channel
    tokio::spawn(async move {
        while let Some(event) = event_rx.recv().await {
            match serialize_browser_event(&event) {
                Ok(json) => {
                    if let Err(e) = broadcast_tx.send(json) {
                        tracing::debug!("No active WebSocket subscribers: {e}");
                    }
                }
                Err(e) => {
                    tracing::warn!("Failed to serialize proxy event: {e}");
                }
            }
        }
    });

    let app = Router::new()
        .route("/", get(index_handler))
        .route("/style.css", get(css_handler))
        .route("/app.js", get(js_handler))
        .route("/api/v1/auth", post(api_authenticate_browser))
        .route("/api/v1/wireguard.svg", get(api_wireguard_svg))
        .route("/ws", get(ws_handler))
        .route("/api/v1/status", get(api_status))
        .route("/api/v1/session", get(api_session))
        .route("/api/v1/flows", get(api_flows).delete(api_clear_flows))
        .route("/api/v1/filter", get(api_filter_matches))
        .route("/api/v1/flows/{id}", get(api_flow))
        .route("/api/v1/flows/{id}/content/{side}", get(api_content))
        .route("/api/v1/flows/{id}/replay", post(api_replay))
        .route("/api/v1/intercept", put(api_set_intercept))
        .route("/api/v1/intercept/{id}", post(api_resolve_intercept))
        .with_state(state);

    let addr = format!("{}:{}", config.addr, config.port);

    let listener = match tokio::net::TcpListener::bind(&addr).await {
        Ok(l) => l,
        Err(e) => {
            tracing::error!("Failed to bind web GUI on {addr}: {e}");
            return;
        }
    };

    // Open browser *after* successful bind
    let url = format!("http://{addr}");
    let browser_url = format!("{url}/#token={browser_token}");
    tracing::info!("Web/API server available at {url}");
    tracing::info!("Browser GUI login URL: {browser_url}");
    tracing::info!("REST API bearer token: {api_token}");
    if let Some((proxy, profile)) = config.browser_proxy {
        if let Err(error) = crate::browser::launch(&browser_url, proxy, &profile) {
            tracing::warn!("Failed to launch proxy-configured browser: {error}");
        }
    } else if config.open_browser {
        if let Err(e) = open::that(&browser_url) {
            tracing::warn!("Failed to open browser: {e}");
        }
    }

    if let Err(e) = axum::serve(listener, app)
        .with_graceful_shutdown(cancel.cancelled_owned())
        .await
    {
        tracing::error!("Web GUI server error: {e}");
    }
}

async fn api_wireguard_svg(
    headers: HeaderMap,
    State(state): State<Arc<WebState>>,
) -> axum::response::Response {
    if !api_authorized(&headers, &state) {
        return forbidden();
    }
    let Some(setup) = &state.wireguard_setup else {
        return axum::http::StatusCode::NOT_FOUND.into_response();
    };
    let mut response = setup.svg().to_owned().into_response();
    response.headers_mut().insert(
        CONTENT_TYPE,
        "image/svg+xml; charset=utf-8"
            .parse()
            .expect("static content type is valid"),
    );
    response.headers_mut().insert(
        CACHE_CONTROL,
        "no-store".parse().expect("static cache control is valid"),
    );
    response
}

fn serialize_browser_event(event: &ProxyEvent) -> Result<String, serde_json::Error> {
    let mut value = serde_json::to_value(event)?;
    if let ProxyEvent::RequestIntercepted { request, .. } = event {
        let editor = proxyapi::content::editable_content(request.headers(), request.body())
            .ok()
            .flatten();
        let intercepted = value
            .get_mut("RequestIntercepted")
            .and_then(serde_json::Value::as_object_mut);
        if let (Some(editor), Some(intercepted)) = (editor, intercepted) {
            intercepted.insert(
                "editor".to_owned(),
                serde_json::json!({
                    "format": editor.format.as_str(),
                    "text": editor.text,
                }),
            );
        }
    }
    serde_json::to_string(&value)
}

fn bearer_token(headers: &HeaderMap) -> Option<&str> {
    headers
        .get(AUTHORIZATION)
        .and_then(|value| value.to_str().ok())
        .and_then(|value| value.split_once(' '))
        .filter(|(scheme, token)| scheme.eq_ignore_ascii_case("bearer") && !token.is_empty())
        .map(|(_, token)| token)
}

fn browser_cookie_matches(headers: &HeaderMap, expected: &str) -> bool {
    headers
        .get_all(COOKIE)
        .iter()
        .filter_map(|value| value.to_str().ok())
        .flat_map(|value| value.split(';'))
        .filter_map(|cookie| cookie.trim().split_once('='))
        .any(|(name, value)| name == BROWSER_COOKIE && value == expected)
}

fn api_authorized(headers: &HeaderMap, state: &WebState) -> bool {
    bearer_token(headers).is_some_and(|token| token == state.api_token)
        || browser_cookie_matches(headers, &state.browser_token)
}

fn forbidden() -> axum::response::Response {
    (axum::http::StatusCode::FORBIDDEN, "Forbidden").into_response()
}

async fn api_authenticate_browser(
    headers: HeaderMap,
    State(state): State<Arc<WebState>>,
) -> axum::response::Response {
    if !bearer_token(&headers).is_some_and(|token| token == state.browser_token) {
        return forbidden();
    }

    let cookie = format!(
        "{BROWSER_COOKIE}={}; HttpOnly; SameSite=Strict; Path=/",
        state.browser_token
    );
    let mut response = axum::http::StatusCode::NO_CONTENT.into_response();
    response.headers_mut().insert(
        SET_COOKIE,
        cookie
            .parse()
            .expect("generated browser tokens are valid cookie values"),
    );
    response
}

#[derive(Serialize)]
struct ApiStatus {
    version: &'static str,
    intercept_enabled: bool,
    pending_count: usize,
    flow_count: usize,
    websocket_count: usize,
    tcp_stream_count: usize,
    dns_exchange_count: usize,
    udp_exchange_count: usize,
}

async fn api_status(
    headers: HeaderMap,
    State(state): State<Arc<WebState>>,
) -> axum::response::Response {
    if !api_authorized(&headers, &state) {
        return forbidden();
    }
    let session = state.recorder.read().await;
    Json(ApiStatus {
        version: env!("CARGO_PKG_VERSION"),
        intercept_enabled: state.intercept.is_enabled(),
        pending_count: state.intercept.pending_count(),
        flow_count: session.session().flows.len(),
        websocket_count: session.session().websockets.len(),
        tcp_stream_count: session.session().tcp_streams.len(),
        dns_exchange_count: session.session().dns_exchanges.len(),
        udp_exchange_count: session.session().udp_exchanges.len(),
    })
    .into_response()
}

async fn api_session(
    headers: HeaderMap,
    State(state): State<Arc<WebState>>,
) -> axum::response::Response {
    if !api_authorized(&headers, &state) {
        return forbidden();
    }
    Json::<TrafficSession>(state.recorder.read().await.snapshot()).into_response()
}

async fn api_flows(
    headers: HeaderMap,
    Query(params): Query<HashMap<String, String>>,
    State(state): State<Arc<WebState>>,
) -> axum::response::Response {
    if !api_authorized(&headers, &state) {
        return forbidden();
    }
    let filter = match params.get("filter") {
        Some(expression) => match FlowFilter::parse(expression) {
            Ok(filter) => Some(filter),
            Err(error) => {
                return (axum::http::StatusCode::BAD_REQUEST, error.to_string()).into_response()
            }
        },
        None => None,
    };
    let flows = state
        .recorder
        .read()
        .await
        .session()
        .flows
        .iter()
        .filter(|flow| {
            filter
                .as_ref()
                .is_none_or(|filter| filter.matches(&flow.request, Some(&flow.response), false))
        })
        .cloned()
        .collect::<Vec<_>>();
    Json::<Vec<CapturedFlow>>(flows).into_response()
}

#[derive(Serialize)]
struct ApiFilterMatches {
    flow_ids: Vec<u64>,
    websocket_ids: Vec<u64>,
    tcp_stream_ids: Vec<u64>,
    dns_exchange_ids: Vec<u64>,
    udp_exchange_ids: Vec<u64>,
}

async fn api_filter_matches(
    headers: HeaderMap,
    Query(params): Query<HashMap<String, String>>,
    State(state): State<Arc<WebState>>,
) -> axum::response::Response {
    if !api_authorized(&headers, &state) {
        return forbidden();
    }
    let expression = params.get("filter").map_or("", String::as_str);
    let filter = match FlowFilter::parse(expression) {
        Ok(filter) => filter,
        Err(error) => {
            return (axum::http::StatusCode::BAD_REQUEST, error.to_string()).into_response()
        }
    };
    let recorder = state.recorder.read().await;
    let session = recorder.session();
    Json(ApiFilterMatches {
        flow_ids: session
            .flows
            .iter()
            .filter(|flow| filter.matches(&flow.request, Some(&flow.response), false))
            .map(|flow| flow.id)
            .collect(),
        websocket_ids: session
            .websockets
            .iter()
            .filter(|flow| {
                filter.matches_websocket(&flow.request, &flow.response, &flow.frames, flow.closed)
            })
            .map(|flow| flow.id)
            .collect(),
        tcp_stream_ids: session
            .tcp_streams
            .iter()
            .filter(|stream| filter.matches_tcp(stream))
            .map(|stream| stream.id)
            .collect(),
        dns_exchange_ids: session
            .dns_exchanges
            .iter()
            .filter(|exchange| filter.matches_dns(exchange))
            .map(|exchange| exchange.id)
            .collect(),
        udp_exchange_ids: session
            .udp_exchanges
            .iter()
            .filter(|exchange| filter.matches_udp(exchange))
            .map(|exchange| exchange.id)
            .collect(),
    })
    .into_response()
}

async fn api_flow(
    Path(id): Path<u64>,
    headers: HeaderMap,
    State(state): State<Arc<WebState>>,
) -> axum::response::Response {
    if !api_authorized(&headers, &state) {
        return forbidden();
    }
    let session = state.recorder.read().await;
    match session.session().flows.iter().find(|flow| flow.id == id) {
        Some(flow) => Json(flow.clone()).into_response(),
        None => (axum::http::StatusCode::NOT_FOUND, "Flow not found").into_response(),
    }
}

#[derive(Serialize)]
struct ApiContentView {
    kind: &'static str,
    text: String,
    decoded_len: usize,
    content_encoding: Option<String>,
    image_media_type: Option<String>,
    image_base64: Option<String>,
    truncated: bool,
    total_seen: usize,
}

async fn api_content(
    Path((id, side)): Path<(u64, String)>,
    headers: HeaderMap,
    State(state): State<Arc<WebState>>,
) -> axum::response::Response {
    if !api_authorized(&headers, &state) {
        return forbidden();
    }
    let session = state.recorder.read().await;
    let Some(flow) = session.session().flows.iter().find(|flow| flow.id == id) else {
        return (axum::http::StatusCode::NOT_FOUND, "Flow not found").into_response();
    };
    let (headers, body, metadata) = match side.as_str() {
        "request" => (
            flow.request.headers(),
            flow.request.body(),
            flow.request.body_metadata(),
        ),
        "response" => (
            flow.response.headers(),
            flow.response.body(),
            flow.response.body_metadata(),
        ),
        _ => {
            return (
                axum::http::StatusCode::BAD_REQUEST,
                "side must be request or response",
            )
                .into_response()
        }
    };
    match proxyapi::content::content_view(headers, body) {
        Ok(view) => {
            let image_media_type = view
                .inline_image
                .as_ref()
                .map(|image| image.media_type.clone());
            let image_base64 = view.inline_image.map(|image| image.base64);
            Json(ApiContentView {
                kind: view.kind.label(),
                text: view.text,
                decoded_len: view.decoded_len,
                content_encoding: view.content_encoding,
                image_media_type,
                image_base64,
                truncated: metadata.truncated,
                total_seen: metadata.total_seen,
            })
            .into_response()
        }
        Err(error) => (
            axum::http::StatusCode::UNPROCESSABLE_ENTITY,
            error.to_string(),
        )
            .into_response(),
    }
}

async fn api_clear_flows(
    headers: HeaderMap,
    State(state): State<Arc<WebState>>,
) -> axum::response::Response {
    if !api_authorized(&headers, &state) {
        return forbidden();
    }
    state.recorder.write().await.clear();
    axum::http::StatusCode::NO_CONTENT.into_response()
}

async fn api_replay(
    Path(id): Path<u64>,
    headers: HeaderMap,
    State(state): State<Arc<WebState>>,
) -> axum::response::Response {
    if !api_authorized(&headers, &state) {
        return forbidden();
    }
    let request = state
        .recorder
        .read()
        .await
        .session()
        .flows
        .iter()
        .find(|flow| flow.id == id)
        .map(|flow| flow.request.clone());
    let Some(request) = request else {
        return (axum::http::StatusCode::NOT_FOUND, "Flow not found").into_response();
    };
    match state.replay_tx.try_send(request) {
        Ok(()) => axum::http::StatusCode::ACCEPTED.into_response(),
        Err(_) => (
            axum::http::StatusCode::SERVICE_UNAVAILABLE,
            "Replay queue full",
        )
            .into_response(),
    }
}

#[derive(Deserialize)]
struct SetInterceptBody {
    enabled: bool,
}

async fn api_set_intercept(
    headers: HeaderMap,
    State(state): State<Arc<WebState>>,
    Json(body): Json<SetInterceptBody>,
) -> axum::response::Response {
    if !api_authorized(&headers, &state) {
        return forbidden();
    }
    state.intercept.set_enabled(body.enabled);
    axum::http::StatusCode::NO_CONTENT.into_response()
}

#[derive(Deserialize)]
#[serde(tag = "action", rename_all = "snake_case")]
enum ApiInterceptDecision {
    Forward,
    Drop {
        #[serde(default = "default_drop_status")]
        status: u16,
        #[serde(default)]
        body: String,
    },
    Modify {
        method: String,
        uri: String,
        headers: ClientHeaders,
        #[serde(default)]
        body: ClientBody,
    },
}

const fn default_drop_status() -> u16 {
    504
}

async fn api_resolve_intercept(
    Path(id): Path<u64>,
    headers: HeaderMap,
    State(state): State<Arc<WebState>>,
    Json(body): Json<ApiInterceptDecision>,
) -> axum::response::Response {
    if !api_authorized(&headers, &state) {
        return forbidden();
    }
    let decision = match body {
        ApiInterceptDecision::Forward => InterceptDecision::Forward,
        ApiInterceptDecision::Drop { status, body } => {
            if http::StatusCode::from_u16(status).is_err() {
                return (
                    axum::http::StatusCode::UNPROCESSABLE_ENTITY,
                    "Invalid HTTP status",
                )
                    .into_response();
            }
            InterceptDecision::Block {
                status,
                body: Bytes::from(body),
            }
        }
        ApiInterceptDecision::Modify {
            method,
            uri,
            headers,
            body,
        } => {
            if method.parse::<http::Method>().is_err() || uri.parse::<Uri>().is_err() {
                return (
                    axum::http::StatusCode::UNPROCESSABLE_ENTITY,
                    "Invalid method or URI",
                )
                    .into_response();
            }
            let Ok(headers) = headers.try_into_header_block() else {
                return (
                    axum::http::StatusCode::UNPROCESSABLE_ENTITY,
                    "Invalid headers",
                )
                    .into_response();
            };
            let body = match body.try_into_bytes() {
                Ok(body) => body,
                Err(error) => {
                    return (axum::http::StatusCode::UNPROCESSABLE_ENTITY, error).into_response()
                }
            };
            InterceptDecision::Modified {
                method,
                uri,
                headers,
                body,
            }
        }
    };
    if state.intercept.resolve(id, decision) {
        axum::http::StatusCode::NO_CONTENT.into_response()
    } else {
        (axum::http::StatusCode::NOT_FOUND, "Pending flow not found").into_response()
    }
}

async fn index_handler() -> Html<&'static str> {
    Html(INDEX_HTML)
}

async fn css_handler() -> impl IntoResponse {
    ([(axum::http::header::CONTENT_TYPE, "text/css")], STYLE_CSS)
}

async fn js_handler() -> impl IntoResponse {
    (
        [(axum::http::header::CONTENT_TYPE, "application/javascript")],
        APP_JS,
    )
}

fn origin_matches_host(headers: &HeaderMap) -> bool {
    let Some(host) = headers.get(HOST).and_then(|value| value.to_str().ok()) else {
        return false;
    };
    let Some(origin) = headers.get(ORIGIN).and_then(|value| value.to_str().ok()) else {
        return false;
    };
    let Ok(origin) = origin.parse::<Uri>() else {
        return false;
    };

    origin.scheme_str() == Some("http")
        && origin
            .authority()
            .is_some_and(|authority| authority.as_str().eq_ignore_ascii_case(host))
        && origin
            .path_and_query()
            .is_none_or(|path_and_query| path_and_query.as_str() == "/")
}

async fn ws_handler(
    ws: WebSocketUpgrade,
    headers: HeaderMap,
    State(state): State<Arc<WebState>>,
) -> axum::response::Response {
    // The GUI and its WebSocket are same-origin. Comparing against Host allows
    // LAN addresses and hostnames without permitting cross-site WebSocket use.
    if !origin_matches_host(&headers) {
        return (axum::http::StatusCode::FORBIDDEN, "Forbidden").into_response();
    }

    if !browser_cookie_matches(&headers, &state.browser_token) {
        return (axum::http::StatusCode::FORBIDDEN, "Forbidden").into_response();
    }

    ws.on_upgrade(move |socket| handle_socket(socket, state))
}

async fn handle_socket(mut socket: WebSocket, state: Arc<WebState>) {
    let mut rx = state.broadcast_tx.subscribe();

    loop {
        tokio::select! {
            // Proxy events → browser
            result = rx.recv() => {
                match result {
                    Ok(msg) => {
                        if socket.send(Message::Text(msg.into())).await.is_err() {
                            break;
                        }
                    }
                    Err(broadcast::error::RecvError::Closed) => break,
                    Err(broadcast::error::RecvError::Lagged(n)) => {
                        tracing::warn!("WebSocket broadcast lagged by {n} messages");
                    }
                }
            }
            // Browser → proxy commands
            result = socket.recv() => {
                match result {
                    Some(Ok(Message::Text(text))) => {
                        handle_client_message(&text, &state).await;
                    }
                    Some(Ok(Message::Close(_))) | None => break,
                    Some(Err(e)) => {
                        tracing::debug!("WebSocket receive error: {e}");
                        break;
                    }
                    _ => {} // Ping/Pong/Binary ignored
                }
            }
        }
    }
}

async fn handle_client_message(text: &str, state: &WebState) {
    let msg: ClientMessage = match serde_json::from_str(text) {
        Ok(m) => m,
        Err(e) => {
            tracing::warn!("Invalid client message: {e}");
            return;
        }
    };

    match msg {
        ClientMessage::SetIntercept { enabled } => {
            state.intercept.set_enabled(enabled);
            // Broadcast updated intercept status to all connected clients
            let status = InterceptStatus {
                enabled,
                pending_count: state.intercept.pending_count(),
            };
            if let Ok(json) = serde_json::to_string(&serde_json::json!({"InterceptStatus": status}))
            {
                let _ = state.broadcast_tx.send(json);
            }
        }
        ClientMessage::Drop { id } => {
            state.intercept.resolve(
                id,
                InterceptDecision::Block {
                    status: 504,
                    body: Bytes::from_static(b"Blocked by Proxelar intercept"),
                },
            );
        }
        ClientMessage::Modified {
            id,
            method,
            uri,
            headers,
            body,
        } => {
            let Ok(method) = method.parse::<http::Method>() else {
                tracing::warn!("Invalid method in browser intercept edit");
                return;
            };
            let Ok(uri) = uri.parse::<Uri>() else {
                tracing::warn!("Invalid URI in browser intercept edit");
                return;
            };
            let Ok(header_block) = headers.try_into_header_block() else {
                tracing::warn!("Invalid header in browser intercept edit");
                return;
            };
            let body = match body.try_into_bytes() {
                Ok(body) => body,
                Err(error) => {
                    let message = serde_json::json!({
                        "EditorError": { "id": id, "message": error }
                    });
                    if let Ok(message) = serde_json::to_string(&message) {
                        let _ = state.broadcast_tx.send(message);
                    }
                    return;
                }
            };
            state.intercept.resolve(
                id,
                InterceptDecision::Modified {
                    method: method.to_string(),
                    uri: uri.to_string(),
                    headers: header_block,
                    body,
                },
            );
        }
        ClientMessage::Replay {
            method,
            uri,
            headers,
            body,
        } => {
            let Ok(header_block) = headers.try_into_header_block() else {
                tracing::warn!("Invalid header in browser replay");
                return;
            };
            let Ok(method) = method.parse() else {
                tracing::warn!("Invalid method in browser replay");
                return;
            };
            let Ok(uri) = uri.parse() else {
                tracing::warn!("Invalid URI in browser replay");
                return;
            };
            let now = jiff::Timestamp::now().as_millisecond();
            let Ok(body) = body.try_into_bytes() else {
                tracing::warn!("Invalid structured body in browser replay");
                return;
            };
            let req =
                ProxiedRequest::new(method, uri, http::Version::HTTP_11, header_block, body, now);
            if state.replay_tx.try_send(req).is_err() {
                tracing::warn!("Replay channel full");
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::body::to_bytes;
    use axum::response::IntoResponse;
    use http::{HeaderValue, Method, Version};
    use proxyapi_models::{ProxiedResponse, WsDirection, WsFrame, WsOpcode};

    fn test_state() -> (
        WebState,
        broadcast::Receiver<String>,
        mpsc::Receiver<ProxiedRequest>,
    ) {
        let (broadcast_tx, broadcast_rx) = broadcast::channel(16);
        let (replay_tx, replay_rx) = mpsc::channel(4);
        (
            WebState {
                broadcast_tx,
                api_token: "api-token".to_owned(),
                browser_token: "browser-token".to_owned(),
                intercept: InterceptConfig::new(),
                replay_tx,
                recorder: Arc::new(RwLock::new(SessionRecorder::default())),
                wireguard_setup: None,
            },
            broadcast_rx,
            replay_rx,
        )
    }

    async fn response_text(response: axum::response::Response) -> String {
        let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
        String::from_utf8(bytes.to_vec()).unwrap()
    }

    fn websocket_headers(host: Option<&str>, origin: Option<&str>) -> HeaderMap {
        let mut headers = HeaderMap::new();
        if let Some(host) = host {
            headers.insert(HOST, HeaderValue::from_str(host).unwrap());
        }
        if let Some(origin) = origin {
            headers.insert(ORIGIN, HeaderValue::from_str(origin).unwrap());
        }
        headers
    }

    #[test]
    fn generate_token_returns_64_hex_chars() {
        let token = generate_token();

        assert_eq!(token.len(), 64);
        assert!(token.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[tokio::test]
    async fn static_asset_handlers_return_expected_content() {
        let index = index_handler().await.into_response();
        assert_eq!(index.status(), http::StatusCode::OK);
        assert!(response_text(index).await.contains("<html"));

        let css = css_handler().await.into_response();
        assert_eq!(css.headers()[http::header::CONTENT_TYPE], "text/css");
        assert!(response_text(css).await.contains(":root"));

        let js = js_handler().await.into_response();
        assert_eq!(
            js.headers()[http::header::CONTENT_TYPE],
            "application/javascript"
        );
        let js_text = response_text(js).await;
        assert!(!js_text.contains("api-token"));
        assert!(!js_text.contains("browser-token"));
    }

    #[test]
    fn websocket_origin_accepts_matching_local_and_lan_hosts() {
        for (host, origin) in [
            ("127.0.0.1:8081", "http://127.0.0.1:8081"),
            ("localhost:8081", "http://localhost:8081"),
            ("192.168.1.20:8081", "http://192.168.1.20:8081"),
            ("PROXELAR.local:8081", "http://proxelar.local:8081"),
            ("[::1]:8081", "http://[::1]:8081"),
        ] {
            let headers = websocket_headers(Some(host), Some(origin));

            assert!(origin_matches_host(&headers));
        }
    }

    #[test]
    fn websocket_origin_rejects_missing_malformed_and_cross_site_values() {
        for (host, origin) in [
            (None, Some("http://192.168.1.20:8081")),
            (Some("192.168.1.20:8081"), None),
            (Some("192.168.1.20:8081"), Some("null")),
            (Some("192.168.1.20:8081"), Some("not-an-origin")),
            (Some("192.168.1.20:8081"), Some("https://192.168.1.20:8081")),
            (
                Some("192.168.1.20:8081"),
                Some("http://192.168.1.20:8081/path"),
            ),
            (
                Some("192.168.1.20:8081"),
                Some("http://attacker.example:8081"),
            ),
        ] {
            let headers = websocket_headers(host, origin);

            assert!(!origin_matches_host(&headers));
        }
    }

    #[test]
    fn browser_cookie_must_match() {
        let mut headers = HeaderMap::new();
        headers.insert(
            COOKIE,
            "other=value; proxelar_session=browser-token"
                .parse()
                .unwrap(),
        );
        assert!(browser_cookie_matches(&headers, "browser-token"));
        assert!(!browser_cookie_matches(&headers, "wrong-token"));
        assert!(!browser_cookie_matches(&HeaderMap::new(), "browser-token"));
    }

    #[test]
    fn api_accepts_api_bearer_or_browser_cookie() {
        let (state, _broadcast_rx, _replay_rx) = test_state();
        let mut headers = HeaderMap::new();
        headers.insert(AUTHORIZATION, "bearer api-token".parse().unwrap());
        assert!(api_authorized(&headers, &state));

        headers.insert(AUTHORIZATION, "Basic api-token".parse().unwrap());
        assert!(!api_authorized(&headers, &state));

        headers.remove(AUTHORIZATION);
        headers.insert(COOKIE, "proxelar_session=browser-token".parse().unwrap());
        assert!(api_authorized(&headers, &state));
    }

    #[tokio::test]
    async fn browser_authentication_sets_http_only_cookie() {
        let (state, _broadcast_rx, _replay_rx) = test_state();
        let mut headers = HeaderMap::new();
        headers.insert(AUTHORIZATION, "Bearer browser-token".parse().unwrap());

        let response = api_authenticate_browser(headers, State(Arc::new(state))).await;

        assert_eq!(response.status(), http::StatusCode::NO_CONTENT);
        assert_eq!(
            response.headers()[SET_COOKIE],
            "proxelar_session=browser-token; HttpOnly; SameSite=Strict; Path=/"
        );
    }

    #[tokio::test]
    async fn browser_authentication_rejects_api_and_invalid_tokens() {
        for token in ["api-token", "wrong-token"] {
            let (state, _broadcast_rx, _replay_rx) = test_state();
            let mut headers = HeaderMap::new();
            headers.insert(AUTHORIZATION, format!("Bearer {token}").parse().unwrap());

            let response = api_authenticate_browser(headers, State(Arc::new(state))).await;

            assert_eq!(response.status(), http::StatusCode::FORBIDDEN);
            assert!(!response.headers().contains_key(SET_COOKIE));
        }
    }

    #[tokio::test]
    async fn wireguard_qr_requires_authentication_and_disables_caching() {
        let (mut state, _broadcast_rx, _replay_rx) = test_state();
        state.wireguard_setup = Some(Arc::new(
            WireGuardSetup::from_bytes(
                "proxelar-wg".to_owned(),
                std::path::PathBuf::from("/tmp/proxelar-wg.conf"),
                b"[Interface]\nPrivateKey = test\n\n[Peer]\nPublicKey = peer\n",
            )
            .unwrap(),
        ));
        let state = Arc::new(state);

        let forbidden_response =
            api_wireguard_svg(HeaderMap::new(), State(Arc::clone(&state))).await;
        assert_eq!(forbidden_response.status(), http::StatusCode::FORBIDDEN);

        let mut headers = HeaderMap::new();
        headers.insert(COOKIE, "proxelar_session=browser-token".parse().unwrap());
        let response = api_wireguard_svg(headers, State(state)).await;

        assert_eq!(response.status(), http::StatusCode::OK);
        assert_eq!(
            response.headers()[CONTENT_TYPE],
            "image/svg+xml; charset=utf-8"
        );
        assert_eq!(response.headers()[CACHE_CONTROL], "no-store");
        assert!(response_text(response).await.starts_with("<svg"));
    }

    #[tokio::test]
    async fn set_intercept_message_updates_state_and_broadcasts_status() {
        let (state, mut broadcast_rx, _replay_rx) = test_state();

        handle_client_message(r#"{"type":"SetIntercept","enabled":true}"#, &state).await;

        assert!(state.intercept.is_enabled());
        let json = broadcast_rx.recv().await.unwrap();
        assert!(json.contains("InterceptStatus"));
        assert!(json.contains("\"enabled\":true"));
    }

    #[tokio::test]
    async fn drop_message_resolves_pending_request_as_blocked() {
        let (state, _broadcast_rx, _replay_rx) = test_state();
        let mut rx = state.intercept.register(12);

        handle_client_message(r#"{"type":"Drop","id":12}"#, &state).await;

        match rx.try_recv().unwrap() {
            InterceptDecision::Block { status, body } => {
                assert_eq!(status, 504);
                assert_eq!(body.as_ref(), b"Blocked by Proxelar intercept");
            }
            _ => panic!("expected block decision"),
        }
    }

    #[tokio::test]
    async fn modified_message_builds_header_map_and_resolves_pending_request() {
        let (state, _broadcast_rx, _replay_rx) = test_state();
        let mut rx = state.intercept.register(33);

        handle_client_message(
            r#"{
                "type":"Modified",
                "id":33,
                "method":"PATCH",
                "uri":"http://api.test/items",
                "headers":[
                    {"name":"x-good","value":"yes"},
                    {"name":"x-repeat","value":"one"},
                    {"name":"x-repeat","value":"two"},
                    {"name":"x-binary","value_base64":"gP8="}
                ],
                "body":{"bytes":[255,0,1]}
            }"#,
            &state,
        )
        .await;

        match rx.try_recv().unwrap() {
            InterceptDecision::Modified {
                method,
                uri,
                headers,
                body,
            } => {
                assert_eq!(method, "PATCH");
                assert_eq!(uri, "http://api.test/items");
                assert_eq!(headers.get("x-good"), Some(b"yes".as_slice()));
                assert_eq!(headers.get_all("x-repeat").count(), 2);
                assert_eq!(headers.get("x-binary"), Some([0x80, 0xff].as_slice()));
                assert_eq!(body.as_ref(), b"\xff\x00\x01");
            }
            _ => panic!("expected modified decision"),
        }
    }

    #[test]
    fn intercepted_protobuf_event_includes_structured_editor() {
        let mut headers = HeaderBlock::new();
        headers
            .add("content-type", "application/x-protobuf")
            .unwrap();
        let request = ProxiedRequest::new(
            Method::POST,
            "http://api.test/message".parse().unwrap(),
            Version::HTTP_11,
            headers,
            Bytes::from_static(&[0x08, 0x96, 0x01]),
            0,
        );
        let event = ProxyEvent::RequestIntercepted {
            id: 9,
            request: Box::new(request),
        };
        let value: serde_json::Value =
            serde_json::from_str(&serialize_browser_event(&event).unwrap()).unwrap();
        assert_eq!(value["RequestIntercepted"]["editor"]["format"], "protobuf");
        assert!(value["RequestIntercepted"]["editor"]["text"]
            .as_str()
            .unwrap()
            .contains("\"field\": 1"));
    }

    #[tokio::test]
    async fn structured_protobuf_message_is_validated_and_encoded() {
        let (state, _broadcast_rx, _replay_rx) = test_state();
        let mut decision_rx = state.intercept.register(34);
        handle_client_message(
            r#"{
                "type":"Modified",
                "id":34,
                "method":"POST",
                "uri":"http://api.test/message",
                "headers":{"content-type":"application/x-protobuf"},
                "body":{
                    "format":"protobuf",
                    "text":"[{\"field\":1,\"wire\":\"varint\",\"value\":\"151\"}]"
                }
            }"#,
            &state,
        )
        .await;
        let InterceptDecision::Modified { body, .. } = decision_rx.try_recv().unwrap() else {
            panic!("expected modified decision");
        };
        assert_eq!(body.as_ref(), &[0x08, 0x97, 0x01]);
    }

    #[tokio::test]
    async fn replay_message_sends_proxied_request() {
        let (state, _broadcast_rx, mut replay_rx) = test_state();

        handle_client_message(
            r#"{
                "type":"Replay",
                "method":"POST",
                "uri":"http://api.test/replay",
                "headers":{"content-type":"text/plain"},
                "body":"again"
            }"#,
            &state,
        )
        .await;

        let req = replay_rx.recv().await.unwrap();
        assert_eq!(req.method(), Method::POST);
        assert_eq!(req.uri().path(), "/replay");
        assert_eq!(req.version(), Version::HTTP_11);
        assert_eq!(
            req.headers().get("content-type"),
            Some(b"text/plain".as_slice())
        );
        assert_eq!(req.body().as_ref(), b"again");
    }

    #[tokio::test]
    async fn malformed_json_and_invalid_replay_are_ignored() {
        let (state, _broadcast_rx, mut replay_rx) = test_state();

        handle_client_message("not json", &state).await;
        handle_client_message(
            r#"{"type":"Replay","method":"bad method","uri":"%%%","headers":{},"body":""}"#,
            &state,
        )
        .await;

        assert!(replay_rx.try_recv().is_err());
    }

    #[test]
    fn proxy_events_serialize_for_browser_broadcasts() {
        let event = ProxyEvent::WebSocketFrame {
            conn_id: 42,
            frame: Box::new(WsFrame::new(
                WsDirection::ServerToClient,
                WsOpcode::Text,
                100,
                Bytes::from_static(b"hello"),
                false,
            )),
        };
        let json = serde_json::to_value(&event).unwrap();
        let frame_event = json.get("WebSocketFrame").unwrap();

        assert_eq!(frame_event["conn_id"], 42);
        assert_eq!(frame_event["frame"]["direction"], "ServerToClient");
        assert_eq!(frame_event["frame"]["opcode"], "Text");
        assert_eq!(frame_event["frame"]["time"], 100);
        assert_eq!(
            frame_event["frame"]["payload"],
            serde_json::json!([104, 101, 108, 108, 111])
        );
        assert_eq!(frame_event["frame"]["truncated"], false);

        let complete = ProxyEvent::RequestComplete {
            id: 1,
            request: Box::new(ProxiedRequest::new(
                Method::GET,
                "http://api.test/".parse().unwrap(),
                Version::HTTP_11,
                HeaderBlock::new(),
                Bytes::new(),
                1,
            )),
            response: Box::new(ProxiedResponse::new(
                http::StatusCode::OK,
                Version::HTTP_11,
                HeaderBlock::new(),
                Bytes::new(),
                2,
            )),
            cancelled: false,
            body_file: None,
        };
        let json = serde_json::to_value(&complete).unwrap();
        let complete_event = json.get("RequestComplete").unwrap();

        assert_eq!(complete_event["id"], 1);
        assert_eq!(complete_event["request"]["method"], "GET");
        assert_eq!(complete_event["request"]["uri"], "http://api.test/");
        assert_eq!(complete_event["request"]["time"], 1);
        assert_eq!(complete_event["response"]["status"], 200);
        assert_eq!(complete_event["response"]["time"], 2);

        let udp = ProxyEvent::UdpExchange {
            exchange: Box::new(proxyapi_models::CapturedUdpExchange {
                id: 7,
                target: "127.0.0.1:9000".to_owned(),
                client: "127.0.0.1:50000".to_owned(),
                time: 3,
                request: Bytes::from_static(b"ping"),
                response: Bytes::new(),
                response_received: true,
                request_truncated: false,
                response_truncated: false,
            }),
        };
        let json = serde_json::to_value(&udp).unwrap();
        assert_eq!(
            json["UdpExchange"]["exchange"]["request"],
            serde_json::json!([112, 105, 110, 103])
        );
        assert_eq!(json["UdpExchange"]["exchange"]["response_received"], true);
    }
}