forked from therealaleph/MasterHttpRelayVPN-RUST
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.rs
More file actions
1474 lines (1377 loc) · 57.5 KB
/
Copy pathconfig.rs
File metadata and controls
1474 lines (1377 loc) · 57.5 KB
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
use rustls::pki_types::ServerName;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
#[error("failed to read config file {0}: {1}")]
Read(String, #[source] std::io::Error),
#[error("failed to parse config json: {0}")]
Parse(#[from] serde_json::Error),
#[error("failed to parse config toml: {0}")]
ParseToml(#[from] toml::de::Error),
#[error("invalid config: {0}")]
Invalid(String),
}
/// Operating mode. `AppsScript` is the full client — MITMs TLS locally and
/// relays HTTP/HTTPS through a user-deployed Apps Script endpoint.
/// `Direct` runs without any Apps Script relay: only the SNI-rewrite tunnel
/// is active, targeting the Google edge by default plus any user-configured
/// `fronting_groups`. Originally introduced as a `script.google.com`
/// bootstrap (when this mode could only reach Google's edge it was named
/// `google_only`), now generalized to any user-configured CDN edge.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
AppsScript,
/// Was named `GoogleOnly` before v1.9 and the introduction of
/// `fronting_groups`. The string `"google_only"` is still accepted
/// in `mode_kind()` as a deprecated alias so existing configs do
/// not break.
Direct,
Full,
}
impl Mode {
pub fn as_str(self) -> &'static str {
match self {
Mode::AppsScript => "apps_script",
Mode::Direct => "direct",
Mode::Full => "full",
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum ScriptId {
One(String),
Many(Vec<String>),
}
impl ScriptId {
pub fn into_vec(self) -> Vec<String> {
match self {
ScriptId::One(s) => vec![s],
ScriptId::Many(v) => v,
}
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct Config {
pub mode: String,
#[serde(default = "default_google_ip")]
pub google_ip: String,
#[serde(default = "default_front_domain")]
pub front_domain: String,
#[serde(default)]
pub script_id: Option<ScriptId>,
#[serde(default)]
pub script_ids: Option<ScriptId>,
#[serde(default)]
pub auth_key: String,
#[serde(default = "default_listen_host")]
pub listen_host: String,
#[serde(default = "default_listen_port")]
pub listen_port: u16,
#[serde(default)]
pub socks5_port: Option<u16>,
#[serde(default = "default_log_level")]
pub log_level: String,
#[serde(default = "default_verify_ssl")]
pub verify_ssl: bool,
#[serde(default)]
pub hosts: HashMap<String, String>,
#[serde(default)]
pub enable_batching: bool,
/// Optional upstream SOCKS5 proxy for non-HTTP / raw-TCP traffic
/// (e.g. `"127.0.0.1:50529"` pointing at a local xray / v2ray instance).
/// When set, the SOCKS5 listener forwards raw-TCP flows through it
/// instead of connecting directly. HTTP/HTTPS traffic (which goes
/// through the Apps Script relay) and SNI-rewrite tunnels are
/// unaffected.
#[serde(default)]
pub upstream_socks5: Option<String>,
/// Fan-out factor for non-cached relay requests when multiple
/// `script_id`s are configured. `0` or `1` = off (round-robin, the
/// default). `2` or more = fire that many Apps Script instances in
/// parallel per request and return the first successful response —
/// kills long-tail latency caused by a single slow Apps Script
/// instance, at the cost of using that much more daily quota.
/// Value is clamped to the number of available (non-blacklisted)
/// script IDs.
#[serde(default)]
pub parallel_relay: u8,
/// Adaptive batch coalesce: after each op arrives, wait this many ms
/// for more ops before firing the batch. Resets on every arrival.
/// 0 = use compiled default (10ms).
#[serde(default)]
pub coalesce_step_ms: u16,
/// Hard cap on total coalesce wait (ms). 0 = use compiled default (1000ms).
#[serde(default)]
pub coalesce_max_ms: u16,
/// Optional explicit SNI rotation pool for outbound TLS to `google_ip`.
/// Empty / missing = auto-expand from `front_domain` (current default of
/// {www, mail, drive, docs, calendar}.google.com). Set to an explicit list
/// to pick exactly which SNI names get rotated through — useful when one
/// of the defaults is locally blocked (e.g. mail.google.com in Iran at
/// various times). Can be tested per-name via the UI or `mhrv-rs test-sni`.
#[serde(default)]
pub sni_hosts: Option<Vec<String>>,
#[serde(default = "default_fetch_ips_from_api")]
pub fetch_ips_from_api: bool,
#[serde(default = "default_max_ips_to_scan")]
pub max_ips_to_scan: usize,
#[serde(default = "default_scan_batch_size")]
pub scan_batch_size:usize,
#[serde(default = "default_google_ip_validation")]
pub google_ip_validation: bool,
/// When true, GET requests to `x.com/i/api/graphql/<hash>/<op>?variables=…`
/// have their query trimmed to just the `variables=` param before being
/// relayed. The `features` / `fieldToggles` params that X ships with
/// these requests change frequently and bust the response cache —
/// stripping them dramatically improves hit rate on Twitter/X browsing.
///
/// Credit: idea from seramo_ir, originally adapted to the Python
/// MasterHttpRelayVPN by the Persian community
/// (https://gist.github.com/seramo/0ae9e5d30ac23a73d5eb3bd2710fcd67).
///
/// Off by default — some X endpoints may reject calls that omit
/// features. Turn on and observe.
#[serde(default)]
pub normalize_x_graphql: bool,
/// Route YouTube traffic through the Apps Script relay instead of
/// the direct SNI-rewrite tunnel. Ported from upstream Python
/// `youtube_via_relay` (issue #102).
///
/// Why this exists: when YouTube is SNI-rewritten to `google_ip`
/// with `SNI=www.google.com`, Google's frontend can enforce
/// SafeSearch / Restricted Mode based on the SNI → some videos show
/// as "restricted." Routing through Apps Script bypasses that check
/// (it hits YouTube from Google's own backend, not via www.google.com
/// SNI) but introduces the UrlFetchApp User-Agent and quota costs.
///
/// Trade-off: enabling removes SafeSearch-on-SNI, adds `User-Agent:
/// Google-Apps-Script` header and counts YouTube traffic against
/// your Apps Script quota. Off by default.
#[serde(default)]
pub youtube_via_relay: bool,
/// User-configurable passthrough list. Any host whose name matches
/// one of these entries bypasses the Apps Script relay entirely and
/// is plain-TCP-passthroughed (optionally through `upstream_socks5`).
///
/// Accepts exact hostnames ("example.com") and leading-dot suffixes
/// (".internal.example" matches "a.b.internal.example"). Matches are
/// case-insensitive.
///
/// Dispatched BEFORE SNI-rewrite and Apps Script, so a passthrough
/// entry wins over the default Google-edge routing. Useful for
/// sites where you already have reachability without the relay
/// (saving Apps Script quota) or for hosts that break under MITM.
///
/// Issues #39, #127.
#[serde(default)]
pub passthrough_hosts: Vec<String>,
/// Block outbound QUIC (UDP/443) at the SOCKS5 listener.
///
/// QUIC is HTTP/3-over-UDP. In `apps_script` mode it's hopeless —
/// Apps Script is HTTP-only, so QUIC datagrams either get refused
/// outright (UDP ASSOCIATE rejected) or silently fall through to
/// `raw-tcp direct` and fail in interesting ways. In `full` mode
/// the tunnel-node CAN carry UDP, but QUIC's congestion control
/// stacked on top of TCP-encapsulated transport produces TCP
/// meltdown for any non-trivial bandwidth — browsers see <1 Mbps
/// where the same site over plain HTTPS would do >50.
///
/// With `block_quic = true`, the SOCKS5 UDP relay drops any
/// datagram destined for port 443 (silent UDP — caller's stack
/// retries a few times then falls back). Browsers then re-issue
/// the same request as TCP/HTTPS through the regular CONNECT
/// path, which goes through the relay normally.
///
/// Why this is opt-in rather than always-on: for users on Full
/// mode + udpgw (a recent path; v1.7.0+) the QUIC TCP-meltdown
/// is partially mitigated by udpgw's persistent-socket reuse,
/// and a tiny minority of sites only support HTTP/3 (rare). The
/// flag lets users who care about consistency over peak speed
/// opt out of QUIC at the source rather than discovering its
/// failure modes later. Issue #213.
/// Block STUN/TURN UDP ports (3478, 5349, 19302) at the SOCKS5 listener.
/// Forces WebRTC apps (Google Meet, Discord, WhatsApp) to fall back to
/// TCP TURN on port 443, skipping the 10-30s UDP ICE timeout. Default
/// true — TCP fallback works for all tested apps and connects instantly.
#[serde(default = "default_block_stun")]
pub block_stun: bool,
#[serde(default = "default_block_quic")]
pub block_quic: bool,
/// When true, suppress the random `_pad` field that v1.8.0+ adds
/// to outbound Apps Script requests for DPI evasion. Default off
/// (padding active). Some users on heavily-throttled ISPs find
/// the +25% bandwidth cost from padding compounds with the
/// throttle to push borderline-working batches into timeouts;
/// turning padding off recovers a bit of headroom at the cost of
/// length-distribution defense against DPI fingerprinting. Issue
/// #391 (EBRAHIM-AM).
///
/// Don't flip this on speculatively — for users where Apps Script
/// outbound is uncongested, padding is free DPI defense. Only
/// turn off if you've measured throughput improvement after the
/// flip on your specific ISP path.
#[serde(default)]
pub disable_padding: bool,
/// Disable HTTP/2 multiplexing on the Apps Script relay leg.
/// Default `false` (= h2 enabled): the TLS handshake to the Google
/// edge advertises ALPN `["h2", "http/1.1"]`; if the server picks
/// h2 we route all relay traffic over a single multiplexed
/// connection (~100 concurrent streams) instead of the legacy
/// per-request TLS pool of 8-80 sockets. Kills head-of-line
/// blocking on slow Apps Script responses (one stalled call no
/// longer pins a whole socket). Set to `true` to force the
/// pre-v1.9.x HTTP/1.1 path — useful as a kill switch if a specific
/// deployment, fronting domain, or middlebox refuses h2.
#[serde(default)]
pub force_http1: bool,
/// Opt-out for the DoH bypass. Default `false` (= bypass active):
/// CONNECTs to well-known DoH hostnames (Cloudflare, Google, Quad9,
/// AdGuard, NextDNS, OpenDNS, browser-pinned variants like
/// `chrome.cloudflare-dns.com` and `mozilla.cloudflare-dns.com`)
/// skip the Apps Script tunnel and exit via plain TCP (or
/// `upstream_socks5` if set). DoH already encrypts the queries
/// themselves, so the only privacy property the tunnel was adding
/// is hiding *the fact that you're doing DoH* from the local
/// network — a marginal gain not worth the ~2 s Apps Script
/// round-trip cost paid on every name lookup. In Full mode this
/// was the dominant DNS slowdown source.
///
/// Set `tunnel_doh: false` to enable the bypass and let DoH go
/// direct (saves the ~2 s Apps Script round-trip per name on
/// networks where the DoH endpoints are reachable). With the
/// bypass off, browsers that find their pinned DoH host
/// unreachable already fall back to OS DNS on their own, so
/// failure modes are graceful in either direction.
///
/// **Default flipped to `true` in v1.9.0** (issue #468). The
/// previous default (`false` = bypass active) silently broke for
/// Iranian users because Iran ISPs filter direct connections to
/// `dns.google`, `chrome.cloudflare-dns.com`, etc. — exactly the
/// "pinned DoH" hosts that the bypass was sending through. The
/// safe default keeps DoH inside the tunnel; users on networks
/// where direct DoH works can opt back into the bypass.
///
/// Port-gated to TCP/443 only. A private DoH on a non-standard port
/// (e.g. `doh.internal.example:8443`) won't take the bypass path —
/// list it in `passthrough_hosts` instead, which has no port gate.
#[serde(default = "default_tunnel_doh")]
pub tunnel_doh: bool,
/// Extra hostnames to treat as DoH endpoints in addition to the
/// built-in default list. Case-insensitive; entries match exactly
/// OR as a dot-anchored suffix unconditionally — `doh.acme.test`
/// covers both `doh.acme.test` and `tenant.doh.acme.test`. (Unlike
/// `passthrough_hosts`, no leading dot is required for suffix
/// matching: every legitimate subdomain of a DoH host is itself
/// a DoH endpoint, so the leading-dot convention would be a
/// footgun.) Use this to cover private/enterprise DoH resolvers
/// without waiting for a release.
///
/// Inert when `tunnel_doh = true` — the bypass itself is off, so
/// the extras have nothing to feed. The proxy logs a warning at
/// startup if both are set together.
#[serde(default)]
pub bypass_doh_hosts: Vec<String>,
/// When true, immediately reject (close) any CONNECT to a known DoH
/// endpoint. Takes priority over `tunnel_doh` — the connection is
/// never established in either direction. Browsers fall back to system
/// DNS, which tun2proxy handles via virtual DNS (instant, no tunnel
/// round-trip). This eliminates the ~1.5s per-domain DoH overhead
/// that #468's `tunnel_doh: true` default introduced.
///
/// Background: #468 changed `tunnel_doh` from false (bypass) to true
/// (tunnel) because Iranian ISPs block direct DoH endpoints. But
/// tunneling DoH costs an extra ~1.5s Apps Script round-trip per DNS
/// lookup, which made every page load noticeably slower. Blocking
/// DoH entirely avoids both problems: no ISP-visible DoH connection,
/// no tunnel round-trip — browsers use the system DNS path instead.
///
/// Default `true` (NOT `bool::default() = false`). Critical for
/// upgrading users — see #773: with the v1.9.13 default-derive bug,
/// existing configs got `block_doh = false` paired with `tunnel_doh
/// = true` (the new tunnel-DoH default from #468), routing every
/// browser DNS lookup through Apps Script and adding ~1.5s per page
/// load. The named-default function fixes the upgrade path so the
/// fast block-then-system-DNS behaviour is what users actually get.
#[serde(default = "default_block_doh")]
pub block_doh: bool,
/// Multi-edge domain-fronting groups. Each group is a triple of
/// (edge IP, front SNI, member domains): when a CONNECT to one of
/// the member domains arrives, the proxy MITMs at the local CA
/// then re-encrypts upstream against `ip` with `sni` as the TLS
/// SNI — same trick we already do for `google_ip` + `front_domain`,
/// but generalised so users can target Vercel's edge (sni=react.dev,
/// fronting vercel.com / vercel.app / nextjs.org / ...) or Fastly's
/// (sni=www.python.org, fronting reddit.com / githubassets.com / ...)
/// directly without burning Apps Script quota or relying on the
/// Google edge for non-Google traffic.
///
/// The cert returned by the upstream is validated against `sni` by
/// rustls as normal — no custom SAN-allowlist needed, the front SNI
/// must itself be a real domain hosted by the same edge as the
/// targets. Picking the right (ip, sni) pair is on the user; see
/// `docs/fronting-groups.md` for the recipe.
///
/// Group match wins over the built-in Google SNI-rewrite suffix list
/// but loses to `passthrough_hosts` (explicit user opt-out wins) and
/// to the DoH bypass. Empty / missing = feature off.
#[serde(default)]
pub fronting_groups: Vec<FrontingGroup>,
/// Auto-blacklist tuning — how many timeouts within the window
/// trip a per-deployment cooldown.
///
/// Default `3` matches the historical behavior. Single-deployment
/// users who hit transient network blips have reported (#391, #444)
/// that 3 strikes are too few — one cold-start stall plus two
/// network glitches lock out their only relay path. Bumping to
/// `5` or `6` is a reasonable workaround for that case.
///
/// Multi-deployment users with 10+ healthy alternatives can lower
/// this (e.g. `2`) to fail-fast off a flaky deployment without
/// burning latency on retries.
#[serde(default = "default_auto_blacklist_strikes")]
pub auto_blacklist_strikes: u32,
/// Window (seconds) for the auto-blacklist strike counter. Strikes
/// older than this are dropped. Default `30`. Larger windows make
/// the heuristic less twitchy at the cost of holding state longer
/// for deployments that have already recovered.
#[serde(default = "default_auto_blacklist_window_secs")]
pub auto_blacklist_window_secs: u64,
/// Cooldown (seconds) when the strike threshold trips. Default
/// `120`. Single-deployment users who can't afford a 2-min lockout
/// when their only relay misbehaves can drop to `30` or `60`. Multi-
/// deployment users with healthy alternatives can extend to `600`
/// to keep a known-bad deployment out of rotation longer.
#[serde(default = "default_auto_blacklist_cooldown_secs")]
pub auto_blacklist_cooldown_secs: u64,
/// Per-batch HTTP round-trip timeout (seconds). Default `30` —
/// matches Apps Script's typical response cliff and historical
/// `BATCH_TIMEOUT` constant. Slow Iran ISP networks may want `45`
/// or `60` to give Apps Script time to respond past throttle
/// windows. Networks with fail-fast preference may want `15` to
/// retry sooner when a deployment hangs. Floor `5`, ceiling `300`
/// (anything beyond exceeds Apps Script's hard 6-min cap with
/// no benefit).
///
/// This applies to connection establishment and response header
/// arrival only. Body streaming is governed by `stream_timeout_secs`.
#[serde(default = "default_request_timeout_secs")]
pub request_timeout_secs: u64,
/// Per-chunk body streaming idle timeout (seconds). Default `300`.
/// Applies to each individual body chunk read after headers arrive —
/// a chunk that goes silent for longer than this is considered a
/// stalled connection and the request is aborted. Distinct from
/// `request_timeout_secs` so large responses through Apps Script
/// (where each 256 KB range chunk can take 30-90s) are not killed
/// mid-transfer. Floor `10`, ceiling `3600`.
#[serde(default = "default_stream_timeout_secs")]
pub stream_timeout_secs: u64,
/// Optional second-hop exit node, for sites that block traffic
/// from Google datacenter IPs (Apps Script's outbound IP space).
/// Most visibly: Cloudflare-fronted services that flag the GCP IP
/// block as bots — ChatGPT (chatgpt.com), Claude (claude.ai),
/// Grok (grok.com / x.com), and a long tail of CF-protected SaaS.
///
/// Architecture: chain becomes
/// `client → SNI rewrite → Apps Script (Google IP) → exit node
/// (Deno Deploy / fly.io / etc., non-Google IP) → destination`
///
/// The destination sees the exit node's outbound IP, not Google's.
/// CF anti-bot's "this is a Google datacenter" heuristic doesn't
/// fire. mhrv-rs's DPI cover (Iran ISP only sees the SNI-rewritten
/// TLS to a Google IP) is unchanged — the second hop happens
/// inside Apps Script, invisible from the user's network.
///
/// Setup walkthrough at `assets/exit_node/README.md`. Default off.
#[serde(default)]
pub exit_node: ExitNodeConfig,
}
/// Configuration for the optional second-hop exit node.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct ExitNodeConfig {
/// Master switch. Default false. Even with `relay_url` and `psk`
/// set, nothing routes through the exit node unless this is true.
#[serde(default)]
pub enabled: bool,
/// HTTPS URL of the exit-node endpoint. Typically a Deno Deploy /
/// fly.io serverless deployment (or your own VPS) running the
/// `assets/exit_node/exit_node.ts` script (or an equivalent). The
/// exit node is what makes the outbound `fetch()` call to the
/// destination, so its IP is what the destination sees.
#[serde(default)]
pub relay_url: String,
/// Pre-shared key — must match the `PSK` constant in the exit-node
/// script. Without a matching PSK the exit node refuses the request
/// (401). The PSK is what keeps the exit node from being usable as
/// an open proxy by anyone who learns its URL. Treat like a
/// password: do not commit, rotate if leaked. Generate with
/// `openssl rand -hex 32`.
#[serde(default)]
pub psk: String,
/// `"selective"` (default): only hosts in `hosts` go through the
/// exit node; everything else takes the regular Apps Script path.
/// Recommended — the exit-node hop adds ~200-500 ms per request,
/// so reserve it for sites that need a non-Google IP.
///
/// `"full"`: every request goes through the exit node. Useful only
/// when the entire workload is CF-anti-bot affected, or when the
/// exit node happens to be faster than Apps Script alone for the
/// user's network path (rare but possible on very slow ISPs).
#[serde(default = "default_exit_node_mode")]
pub mode: String,
/// In `"selective"` mode, the list of destination hostnames that
/// route through the exit node. Matches exactly OR as a
/// dot-anchored suffix, mirroring `passthrough_hosts` semantics:
/// `"chatgpt.com"` covers `chatgpt.com` and `api.chatgpt.com` and
/// `auth.chatgpt.com` etc. Leading dots are stripped at load.
///
/// The recurring CF-anti-bot list from community reports:
/// `chatgpt.com`, `claude.ai`, `x.com`, `grok.com`. Extend for
/// any other CF-blocked sites you need.
#[serde(default)]
pub hosts: Vec<String>,
}
fn default_exit_node_mode() -> String {
"selective".into()
}
/// One multi-edge fronting group. Edge CDNs like Vercel and Fastly
/// host hundreds of tenants behind a single set of edge IPs and use
/// the inner HTTP `Host` header (after TLS handshake) to dispatch to
/// the right backend. Pick one neutral domain hosted on the same edge
/// as `sni`; the cert it serves will be valid for that name (rustls
/// validates against `sni`, not against the inner `Host`), and the
/// edge will route based on the `Host` header.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct FrontingGroup {
/// Human-readable name used in log lines. Free-form; uniqueness not
/// enforced but recommended.
pub name: String,
/// Edge IP to dial. A single IP for now — most edges have many but
/// one is enough to validate the technique. IP rotation per-group
/// can come later.
pub ip: String,
/// SNI to send on the outbound TLS handshake. Must be a real domain
/// served by the same edge as `domains`, otherwise the edge will
/// either refuse the handshake or serve a default page that 404s
/// the inner Host. Examples: `react.dev` for Vercel, `www.python.org`
/// for Fastly.
pub sni: String,
/// Member domain list. Matching is case-insensitive: an entry
/// matches the host exactly OR as an unconditional dot-anchored
/// suffix (`vercel.com` matches `app.vercel.com` too). Same shape
/// as the DoH host list.
///
/// Canonical form for matching is lowercase and trailing-dot
/// trimmed; entries are normalized to that form once at proxy
/// startup. The on-disk representation is preserved as written
/// (we don't mutate the user's config), so `Vercel.com.` and
/// `vercel.com` both work — the matcher is the source of truth
/// for equality.
pub domains: Vec<String>,
}
fn default_fetch_ips_from_api() -> bool { false }
fn default_max_ips_to_scan() -> usize { 100 }
fn default_scan_batch_size() -> usize {500}
fn default_google_ip_validation() -> bool {true}
/// Default for `tunnel_doh`: `true` (DoH stays inside the tunnel).
/// Flipped from `false` in v1.9.0 per #468 — Iran ISPs filter direct
/// connections to pinned DoH hosts (`dns.google`, `chrome.cloudflare-dns.com`,
/// …) and the prior bypass-on default silently broke DNS for the
/// dominant userbase. Users on networks where direct DoH works can
/// opt back in with `tunnel_doh: false`.
fn default_tunnel_doh() -> bool { true }
/// Default for `block_quic`: `true`. QUIC over the TCP-based tunnel
/// causes TCP-over-TCP meltdown (<1 Mbps). Browsers fall back to
/// HTTPS/TCP within seconds of the silent UDP drop. Issue #793.
fn default_block_stun() -> bool { false }
fn default_block_quic() -> bool { true }
/// Default for `block_doh`: `true` (browser DoH is rejected so the
/// browser falls back to system DNS, which `tun2proxy` resolves
/// instantly via virtual DNS — saves the ~1.5s tunnel round-trip per
/// name lookup that #468's `tunnel_doh: true` default would otherwise
/// pay). #773 — without this named-default function, `#[serde(default)]`
/// on `bool` resolves to `false`, and existing configs upgrading to
/// v1.9.13 silently lost the block-and-fall-back behaviour, paying
/// the full DoH-via-Apps-Script penalty on every page load. Power
/// users who specifically want browser DoH (with the latency cost)
/// can opt back in by setting `block_doh: false`.
fn default_block_doh() -> bool { true }
/// Defaults for the auto-blacklist tuning knobs (#391, #444). These
/// preserve historical behavior — `3 strikes / 30s window / 120s cooldown`.
fn default_auto_blacklist_strikes() -> u32 { 3 }
fn default_auto_blacklist_window_secs() -> u64 { 30 }
fn default_auto_blacklist_cooldown_secs() -> u64 { 120 }
/// Default for `request_timeout_secs`: 30s, matching the historical
/// hard-coded `BATCH_TIMEOUT` and Apps Script's typical response cliff.
fn default_request_timeout_secs() -> u64 { 30 }
/// Default for `stream_timeout_secs`: 300s per-chunk idle timeout for
/// body streaming, separate from the header/connect timeout.
fn default_stream_timeout_secs() -> u64 { 300 }
fn default_google_ip() -> String {
"216.239.38.120".into()
}
fn default_front_domain() -> String {
"www.google.com".into()
}
fn default_listen_host() -> String {
"0.0.0.0".into()
}
fn default_listen_port() -> u16 {
8085
}
fn default_log_level() -> String {
"warn".into()
}
fn default_verify_ssl() -> bool {
true
}
impl Config {
pub fn load(path: &Path) -> Result<(Self, Option<String>), ConfigError> {
let ext = path
.extension()
.and_then(|e| e.to_str())
.unwrap_or("")
.to_ascii_lowercase();
match ext.as_str() {
"toml" => Self::load_toml(path).map(|c| (c, None)),
"json" => Self::load_json_and_migrate(path),
_ => {
// No extension or unrecognised: try TOML first, then JSON.
// JSON success also triggers migration. On double failure,
// surface the TOML error (the format new configs expect).
let toml_err = match Self::load_toml(path) {
Ok(cfg) => return Ok((cfg, None)),
Err(e) => e,
};
match Self::load_json_and_migrate(path) {
Ok((cfg, msg)) => Ok((cfg, msg)),
Err(_) => Err(toml_err),
}
}
}
}
pub fn load_toml(path: &Path) -> Result<Self, ConfigError> {
let data = std::fs::read_to_string(path)
.map_err(|e| ConfigError::Read(path.display().to_string(), e))?;
let toml_cfg: TomlConfig = toml::from_str(&data)
.map_err(ConfigError::ParseToml)?;
let cfg = Config::from(toml_cfg);
cfg.validate()?;
Ok(cfg)
}
fn load_json_and_migrate(path: &Path) -> Result<(Self, Option<String>), ConfigError> {
let data = std::fs::read_to_string(path)
.map_err(|e| ConfigError::Read(path.display().to_string(), e))?;
let cfg: Config = serde_json::from_str(&data)?;
cfg.validate()?;
// Write a .toml equivalent alongside the .json file. Failure is
// non-fatal: the in-memory Config is still valid and returned.
let toml_path = path.with_extension("toml");
let msg = match toml::to_string_pretty(&TomlConfig::from(&cfg)) {
Ok(toml_str) => match std::fs::write(&toml_path, &toml_str) {
Ok(()) => Some(format!(
"Found legacy config.json. Translated to {} automatically. \
config.json has been left in place but will no longer be read. \
You can delete it.",
toml_path.display()
)),
Err(e) => Some(format!(
"Found legacy config.json but could not write {}: {}. \
Continuing from the JSON config.",
toml_path.display(), e
)),
},
Err(e) => Some(format!(
"Found legacy config.json but could not serialize to TOML: {}. \
Continuing from the JSON config.",
e
)),
};
Ok((cfg, msg))
}
fn validate(&self) -> Result<(), ConfigError> {
let mode = self.mode_kind()?;
if mode == Mode::AppsScript || mode == Mode::Full {
if self.auth_key.trim().is_empty() || self.auth_key == "CHANGE_ME_TO_A_STRONG_SECRET" {
return Err(ConfigError::Invalid(
"auth_key must be set to a strong secret".into(),
));
}
let ids = self.script_ids_resolved();
if ids.is_empty() {
return Err(ConfigError::Invalid(
"script_id (or script_ids) is required".into(),
));
}
for id in &ids {
if id.is_empty() || id == "YOUR_APPS_SCRIPT_DEPLOYMENT_ID" {
return Err(ConfigError::Invalid(
"script_id is not set — deploy Code.gs and paste its Deployment ID".into(),
));
}
}
}
if self.scan_batch_size == 0 {
return Err(ConfigError::Invalid(
"scan_batch_size must be greater than 0".into(),
));
}
if self.socks5_port == Some(self.listen_port) {
return Err(ConfigError::Invalid(format!(
"listen_port and socks5_port must differ on the same host \
(both set to {} on {}). Change one of them in config.toml.",
self.listen_port, self.listen_host
)));
}
for (i, g) in self.fronting_groups.iter().enumerate() {
if g.name.trim().is_empty() {
return Err(ConfigError::Invalid(format!(
"fronting_groups[{}]: name is empty", i
)));
}
if g.ip.trim().is_empty() {
return Err(ConfigError::Invalid(format!(
"fronting_groups[{}] ('{}'): ip is empty", i, g.name
)));
}
if g.sni.trim().is_empty() {
return Err(ConfigError::Invalid(format!(
"fronting_groups[{}] ('{}'): sni is empty", i, g.name
)));
}
// Parse the SNI here so an invalid hostname fails the same
// load path the UI / `mhrv-rs` CLI both use, rather than
// surfacing later only when ProxyServer::new tries to build
// the TLS server name. Same fail-fast contract as the rest
// of validate(). The parse is cheap; runtime path repeats
// it once at proxy startup, idempotently.
if let Err(e) = ServerName::try_from(g.sni.clone()) {
return Err(ConfigError::Invalid(format!(
"fronting_groups[{}] ('{}'): invalid sni '{}': {}",
i, g.name, g.sni, e
)));
}
if g.domains.is_empty() {
return Err(ConfigError::Invalid(format!(
"fronting_groups[{}] ('{}'): domains list is empty", i, g.name
)));
}
for d in &g.domains {
if d.trim().is_empty() {
return Err(ConfigError::Invalid(format!(
"fronting_groups[{}] ('{}'): empty domain entry", i, g.name
)));
}
}
}
Ok(())
}
pub fn mode_kind(&self) -> Result<Mode, ConfigError> {
match self.mode.as_str() {
"apps_script" => Ok(Mode::AppsScript),
"direct" => Ok(Mode::Direct),
// Deprecated alias. `google_only` was the name of `direct`
// before fronting_groups generalized the mode beyond
// Google's edge. Accepted forever so old configs keep
// working — the UI rewrites it on next save.
"google_only" => Ok(Mode::Direct),
"full" => Ok(Mode::Full),
other => Err(ConfigError::Invalid(format!(
"unknown mode '{}' (expected 'apps_script', 'direct', or 'full')",
other
))),
}
}
pub fn script_ids_resolved(&self) -> Vec<String> {
if let Some(s) = &self.script_ids {
return s.clone().into_vec();
}
if let Some(s) = &self.script_id {
return s.clone().into_vec();
}
Vec::new()
}
}
// TOML intermediate structs
//
// The flat `Config` struct and all its callers are unchanged. These structs
// only exist inside Config::load_toml and the JSON->TOML migration writer.
// Both paths produce a flat Config in the end via From<TomlConfig>.
/// [relay] section of config.toml.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TomlRelay {
pub mode: String,
#[serde(default)]
pub script_id: Option<ScriptId>,
#[serde(default)]
pub script_ids: Option<ScriptId>,
#[serde(default)]
pub auth_key: String,
#[serde(default)]
pub parallel_relay: u8,
#[serde(default)]
pub enable_batching: bool,
#[serde(default)]
pub coalesce_step_ms: u16,
#[serde(default)]
pub coalesce_max_ms: u16,
#[serde(default)]
pub youtube_via_relay: bool,
#[serde(default)]
pub normalize_x_graphql: bool,
#[serde(default)]
pub disable_padding: bool,
#[serde(default)]
pub force_http1: bool,
#[serde(default = "default_auto_blacklist_strikes")]
pub auto_blacklist_strikes: u32,
#[serde(default = "default_auto_blacklist_window_secs")]
pub auto_blacklist_window_secs: u64,
#[serde(default = "default_auto_blacklist_cooldown_secs")]
pub auto_blacklist_cooldown_secs: u64,
#[serde(default = "default_request_timeout_secs")]
pub request_timeout_secs: u64,
#[serde(default = "default_stream_timeout_secs")]
pub stream_timeout_secs: u64,
}
/// [network] section of config.toml.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TomlNetwork {
#[serde(default = "default_google_ip")]
pub google_ip: String,
#[serde(default = "default_front_domain")]
pub front_domain: String,
#[serde(default = "default_listen_host")]
pub listen_host: String,
#[serde(default = "default_listen_port")]
pub listen_port: u16,
#[serde(default)]
pub socks5_port: Option<u16>,
#[serde(default = "default_verify_ssl")]
pub verify_ssl: bool,
#[serde(default)]
pub upstream_socks5: Option<String>,
#[serde(default = "default_block_quic")]
pub block_quic: bool,
#[serde(default = "default_block_stun")]
pub block_stun: bool,
#[serde(default)]
pub sni_hosts: Option<Vec<String>>,
#[serde(default)]
pub passthrough_hosts: Vec<String>,
#[serde(default = "default_tunnel_doh")]
pub tunnel_doh: bool,
#[serde(default = "default_block_doh")]
pub block_doh: bool,
#[serde(default)]
pub bypass_doh_hosts: Vec<String>,
#[serde(default)]
pub hosts: HashMap<String, String>,
}
impl Default for TomlNetwork {
fn default() -> Self {
Self {
google_ip: default_google_ip(),
front_domain: default_front_domain(),
listen_host: default_listen_host(),
listen_port: default_listen_port(),
socks5_port: None,
verify_ssl: default_verify_ssl(),
upstream_socks5: None,
block_quic: default_block_quic(),
block_stun: default_block_stun(),
sni_hosts: None,
passthrough_hosts: Vec::new(),
tunnel_doh: default_tunnel_doh(),
block_doh: default_block_doh(),
bypass_doh_hosts: Vec::new(),
hosts: HashMap::new(),
}
}
}
/// [scan] section of config.toml.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TomlScan {
#[serde(default = "default_fetch_ips_from_api")]
pub fetch_ips_from_api: bool,
#[serde(default = "default_max_ips_to_scan")]
pub max_ips_to_scan: usize,
#[serde(default = "default_scan_batch_size")]
pub scan_batch_size: usize,
#[serde(default = "default_google_ip_validation")]
pub google_ip_validation: bool,
}
impl Default for TomlScan {
fn default() -> Self {
Self {
fetch_ips_from_api: default_fetch_ips_from_api(),
max_ips_to_scan: default_max_ips_to_scan(),
scan_batch_size: default_scan_batch_size(),
google_ip_validation: default_google_ip_validation(),
}
}
}
/// [logging] section of config.toml.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TomlLogging {
#[serde(default = "default_log_level")]
pub log_level: String,
}
impl Default for TomlLogging {
fn default() -> Self {
Self { log_level: default_log_level() }
}
}
/// Root config.toml document. Deserialized first, then flattened into
/// `Config` via `From<TomlConfig>` so the rest of the codebase is untouched.
#[derive(Debug, Deserialize, Serialize)]
pub struct TomlConfig {
pub relay: TomlRelay,
#[serde(default)]
pub network: TomlNetwork,
#[serde(default)]
pub scan: TomlScan,
#[serde(default)]
pub logging: TomlLogging,
#[serde(default)]
pub exit_node: ExitNodeConfig,
#[serde(default)]
pub fronting_groups: Vec<FrontingGroup>,
}
impl From<TomlConfig> for Config {
fn from(t: TomlConfig) -> Self {
Config {
mode: t.relay.mode,
google_ip: t.network.google_ip,
front_domain: t.network.front_domain,
script_id: t.relay.script_id,
script_ids: t.relay.script_ids,
auth_key: t.relay.auth_key,
listen_host: t.network.listen_host,
listen_port: t.network.listen_port,
socks5_port: t.network.socks5_port,
log_level: t.logging.log_level,
verify_ssl: t.network.verify_ssl,
hosts: t.network.hosts,
enable_batching: t.relay.enable_batching,
upstream_socks5: t.network.upstream_socks5,
parallel_relay: t.relay.parallel_relay,
coalesce_step_ms: t.relay.coalesce_step_ms,
coalesce_max_ms: t.relay.coalesce_max_ms,
sni_hosts: t.network.sni_hosts,
fetch_ips_from_api: t.scan.fetch_ips_from_api,
max_ips_to_scan: t.scan.max_ips_to_scan,
scan_batch_size: t.scan.scan_batch_size,
google_ip_validation: t.scan.google_ip_validation,
normalize_x_graphql: t.relay.normalize_x_graphql,
youtube_via_relay: t.relay.youtube_via_relay,
passthrough_hosts: t.network.passthrough_hosts,
block_stun: t.network.block_stun,
block_quic: t.network.block_quic,
disable_padding: t.relay.disable_padding,
force_http1: t.relay.force_http1,
tunnel_doh: t.network.tunnel_doh,
bypass_doh_hosts: t.network.bypass_doh_hosts,
block_doh: t.network.block_doh,
fronting_groups: t.fronting_groups,
auto_blacklist_strikes: t.relay.auto_blacklist_strikes,
auto_blacklist_window_secs: t.relay.auto_blacklist_window_secs,
auto_blacklist_cooldown_secs: t.relay.auto_blacklist_cooldown_secs,
request_timeout_secs: t.relay.request_timeout_secs,
stream_timeout_secs: t.relay.stream_timeout_secs,
exit_node: t.exit_node,
}
}
}
/// Used by the JSON->TOML migration write path: takes a reference so the
/// flat Config can still be returned as Ok(config) after the TOML is written.
impl From<&Config> for TomlConfig {
fn from(c: &Config) -> Self {
TomlConfig {
relay: TomlRelay {
mode: c.mode.clone(),
script_id: c.script_id.clone(),
script_ids: c.script_ids.clone(),
auth_key: c.auth_key.clone(),
parallel_relay: c.parallel_relay,
enable_batching: c.enable_batching,
coalesce_step_ms: c.coalesce_step_ms,
coalesce_max_ms: c.coalesce_max_ms,
youtube_via_relay: c.youtube_via_relay,
normalize_x_graphql: c.normalize_x_graphql,
disable_padding: c.disable_padding,
force_http1: c.force_http1,
auto_blacklist_strikes: c.auto_blacklist_strikes,
auto_blacklist_window_secs: c.auto_blacklist_window_secs,
auto_blacklist_cooldown_secs: c.auto_blacklist_cooldown_secs,
request_timeout_secs: c.request_timeout_secs,
stream_timeout_secs: c.stream_timeout_secs,
},
network: TomlNetwork {
google_ip: c.google_ip.clone(),
front_domain: c.front_domain.clone(),
listen_host: c.listen_host.clone(),
listen_port: c.listen_port,
socks5_port: c.socks5_port,
verify_ssl: c.verify_ssl,
upstream_socks5: c.upstream_socks5.clone(),
block_quic: c.block_quic,
block_stun: c.block_stun,
sni_hosts: c.sni_hosts.clone(),
passthrough_hosts: c.passthrough_hosts.clone(),
tunnel_doh: c.tunnel_doh,
block_doh: c.block_doh,
bypass_doh_hosts: c.bypass_doh_hosts.clone(),
hosts: c.hosts.clone(),
},
scan: TomlScan {
fetch_ips_from_api: c.fetch_ips_from_api,
max_ips_to_scan: c.max_ips_to_scan,
scan_batch_size: c.scan_batch_size,
google_ip_validation: c.google_ip_validation,
},
logging: TomlLogging {
log_level: c.log_level.clone(),
},
exit_node: c.exit_node.clone(),
fronting_groups: c.fronting_groups.clone(),
}
}