import 'dart:convert'; import 'package:flutter_test/flutter_test.dart'; import 'package:tachyon_proxy/core/models/runtime_config.dart'; import 'package:tachyon_proxy/core/services/core_bridge.dart'; import 'package:tachyon_proxy/core/services/link_parser.dart'; import 'package:tachyon_proxy/core/services/settings_store.dart'; void main() { const profile = Profile( id: 'vless-1', name: 'Тестовый сервер', type: 'vless', server: 'example.com', port: 443, uuid: '00000000-0000-0000-0000-000000000000', sni: 'example.com', ); test('конфигурация собирается под требования ядра', () { final config = RuntimeConfig( profile: profile, routingMode: RoutingMode.rules, dns: const DnsSettings(), ruleSets: const [], ).toJson(); // Ядро требует явный резолвер имён, когда DNS-серверов больше одного, // и уникальные теги у каждого сервера в dns.servers. expect(config['route']['default_domain_resolver'], isNotNull); final dnsServers = (config['dns']['servers'] as List).cast(); final dnsTags = dnsServers.map((s) => s['tag'] as String).toList(); expect(dnsTags.toSet().length, dnsTags.length); // DNS-запросы приложений перехватываются ядром. final rules = config['route']['rules'] as List; expect( rules.any((rule) => rule['action'] == 'hijack-dns'), isTrue, reason: 'без hijack-dns запросы к резолверам уходят мимо DNS-системы', ); // Исходящие соединения ядра описаны явно. final outbounds = config['outbounds'] as List; expect(outbounds.any((outbound) => outbound['tag'] == 'proxy'), isTrue); expect(outbounds.any((outbound) => outbound['tag'] == 'direct'), isTrue); }); test('списки правил попадают в route.rule_set в формате trs', () { final config = RuntimeConfig( profile: profile, routingMode: RoutingMode.rules, dns: const DnsSettings(), ruleSets: const [ RuleSetEntry( id: 'russia_inside', title: 'Россия', path: '/data/lists/russia_inside.trs', action: 'direct', enabled: true, ), ], ).toJson(); final ruleSets = config['route']['rule_set'] as List; expect(ruleSets, hasLength(1)); expect(ruleSets.first['type'], 'local'); expect(ruleSets.first['format'], 'trs'); expect(ruleSets.first['tag'], 'russia_inside'); // Прямой список разрешается прямым резолвером, иначе домены из него // не совпадут с правилом маршрутизации. final dnsRules = (config['dns']['rules'] as List).cast(); expect( dnsRules.any((r) => (r['rule_set'] as List?)?.contains('russia_inside') == true && r['server'] == RuntimeConfig.directTag), isTrue, ); }); test('DoH-адрес превращается в типизированный сервер', () { final config = RuntimeConfig( profile: profile, routingMode: RoutingMode.global, dns: const DnsSettings(servers: ['https://dns.google/dns-query']), ruleSets: const [], ).toJson(); final servers = config['dns']['servers'] as List; final doh = servers.firstWhere( (server) => server['type'] == 'https', ); expect(doh['server'], 'dns.google'); expect(doh['path'], '/dns-query'); }); test('все 19 протоколов подписки роутера Tachyon корректно парсятся и собираются в конфиг ядра', () { const routerLinks = ''' tewfai://0f8f7be7-2593-4e05-8de0-50ef29b036c4:d42fb465f8264e36bd4bd667978e3467@192.168.1.205:8443?sni=192.168.1.205&insecure=1&pcs=4cd2d695b2fb7deeb9a3ca479b73a5337da7a11635ed942fb79de36f45529b1c&transport=quic%2Ctcp&inner_cipher=aes-256-gcm#TewFai%20%28Tachyon%20Router%29 naive+https://Naive:e21d95da5e3c10282ca40eb851fd6d3a@192.168.1.205:8444?sni=192.168.1.205&pcs=4cd2d695b2fb7deeb9a3ca479b73a5337da7a11635ed942fb79de36f45529b1c#Naive%20%28Tachyon%20Router%29 vless://53663e0d-9aa2-4423-9aa7-0c876f2a6484@192.168.1.205:8445?encryption=none&security=reality&sni=www.microsoft.com&fp=chrome&pbk=-j20a4wX0aA1tD4p8lI8n_b-dY6E2vR0c9k3mZ1xX2A&sid=fc328ca2c4598c1e&type=tcp&flow=xtls-rprx-vision#VLESS%20%28Tachyon%20Router%29 vless://de335982-e2a1-4385-8162-215d26da9a43@192.168.1.205:8446?encryption=none&security=tls&sni=192.168.1.205&allowInsecure=1&pcs=4cd2d695b2fb7deeb9a3ca479b73a5337da7a11635ed942fb79de36f45529b1c&fp=chrome&type=tcp#VLESS-TLS%20%28Tachyon%20Router%29 vmess://eyJ2IjoiMiIsInBzIjoiVk1lc3MgKFRhY2h5b24gUm91dGVyKSIsImFkZCI6IjE5Mi4xNjguMS4yMDUiLCJwb3J0IjoiODQ0NyIsImlkIjoiNTk3NzgwOTAtODRmNS00ZTBjLTg4MjQtNDk2NWU5MGQ0ZGIxIiwiYWlkIjoiMCIsInNjeSI6ImF1dG8iLCJuZXQiOiJ0Y3AiLCJ0eXBlIjoibm9uZSIsImhvc3QiOiIiLCJwYXRoIjoiIiwidGxzIjoidGxzIiwic25pIjoiMTkyLjE2OC4xLjIwNSIsImFsbG93SW5zZWN1cmUiOjEsInBjcyI6IjRjZDJkNjk1YjJmYjdkZWViOWEzY2E0NzliNzNhNTMzN2RhN2ExMTYzNWVkOTQyZmI3OWRlMzZmNDU1MjliMWMifQ== trojan://4427b698a5f826444bf0d7be6f083e26@192.168.1.205:8458?security=tls&sni=192.168.1.205&allowInsecure=1&pcs=4cd2d695b2fb7deeb9a3ca479b73a5337da7a11635ed942fb79de36f45529b1c&type=tcp#Trojan%20%28Tachyon%20Router%29 ss://MjAyMi1ibGFrZTMtYWVzLTEyOC1nY206WlRZeFl6WmhOamN5T1dWbVpXRTBObU5rTnpNNVlqWXc=@192.168.1.205:8388#Shadowsocks%20%28Tachyon%20Router%29 socks5://Socks5:a229cb7e823a0d16ce79a26d4cb0c82e@192.168.1.205:1080#Socks5%20%28Tachyon%20Router%29 http://HttpProxy:7c1e7608be1a3b2a9d37fc3a210f9d44@192.168.1.205:8080#HttpProxy%20%28Tachyon%20Router%29 socks5://MixedProxy:9f50be772e11ab42f592096444620a65@192.168.1.205:1081#MixedProxy%20%28Tachyon%20Router%29 hysteria2://38ee8451ec63222d04e6883164d14671@192.168.1.205:8448?sni=192.168.1.205&insecure=1&pinSHA256=4cd2d695b2fb7deeb9a3ca479b73a5337da7a11635ed942fb79de36f45529b1c#Hysteria2%20%28Tachyon%20Router%29 tuic://f29c469d-6097-4189-a2f2-6070580fd6c7:8750298283431e530e965d682221a98c@192.168.1.205:8449?sni=192.168.1.205&insecure=1&pcs=4cd2d695b2fb7deeb9a3ca479b73a5337da7a11635ed942fb79de36f45529b1c&congestion_control=bbr&alpn=h3#TUIC%20%28Tachyon%20Router%29 anytls://49a7490315219d2b2e9b399cf5351162@192.168.1.205:8450?sni=192.168.1.205&insecure=1&pcs=4cd2d695b2fb7deeb9a3ca479b73a5337da7a11635ed942fb79de36f45529b1c#AnyTLS%20%28Tachyon%20Router%29 shadowtls://3be3b88851fd95d579434873e162cf22@192.168.1.205:8451?sni=www.microsoft.com&version=3#ShadowTLS%20%28Tachyon%20Router%29 mierus://Mieru:7d989872364516095747be888c426707@192.168.1.205?port=2012-2022&protocol=TCP&profile=Mieru%20%28Tachyon%20Router%29 fptn://eyAidmVyc2lvbiI6IDEsICJzZXJ2aWNlX25hbWUiOiAiRlBUTiAoVGFjaHlvbiBSb3V0ZXIpIiwgInVzZXJuYW1lIjogIkZQVE4iLCAicGFzc3dvcmQiOiAiZGIzZjg1ZTEzYzg5OTM2ZDBlZWE5NzQ3NGU2YzEyZmMiLCAic2VydmVycyI6IFt7ICJuYW1lIjogIkZQVE4gKFRhY2h5b24gUm91dGVyKSIsICJob3N0IjogIjE5Mi4xNjguMS4yMDUiLCAicG9ydCI6IDg0NTMsICJtZDVfZmluZ2VycHJpbnQiOiAiZjc4ZjAzZThmMzA1ZDdmNDI3NGI4OTk1NDkzMGI1MTMiLCAiaXNfY2Vuc29yZWQiOiBmYWxzZSB9XSB9#FPTN%20%28Tachyon%20Router%29 trusttunnel://TrustTunnel:64fd8d89c2e973ec3a4a6e393218993b@192.168.1.205:8454?sni=192.168.1.205&insecure=1&pcs=4cd2d695b2fb7deeb9a3ca479b73a5337da7a11635ed942fb79de36f45529b1c#TrustTunnel%20%28Tachyon%20Router%29 masque://192.168.1.205:8455?sni=192.168.1.205&insecure=1&pcs=4cd2d695b2fb7deeb9a3ca479b73a5337da7a11635ed942fb79de36f45529b1c&profile=standard&uri=https%3A%2F%2F192.168.1.205%3A8455%2F.well-known%2Fmasque%2Fip%2F%2A%2F%2A%2F&ip=172.16.0.0%2F24&mtu=1400#MASQUE%20%28Tachyon%20Router%29 openconnect://0195b65f7017cf503857921ccca9278f@192.168.1.205:8456?sni=192.168.1.205&insecure=1&pcs=4cd2d695b2fb7deeb9a3ca479b73a5337da7a11635ed942fb79de36f45529b1c&flavor=anyconnect&cookie=0195b65f7017cf503857921ccca9278f&address=172.16.1.2%2F24&mtu=1400#OpenConnect%20%28Tachyon%20Router%29 https://t.me/proxy?server=192.168.1.205&port=8457&secret=daa0dc1ef3940ec586aa54e73b045fd1#MTProto%20%28Tachyon%20Router%29 amneziawg://W0ludGVyZmFjZV0KUHJpdmF0ZUtleSA9IGdHNEJ4T01yUDhuV1dIelZ6VGt2OXJ6T1lGUG93aG03SGhmN1Z5d0N5V2M9CkFkZHJlc3MgPSAxMC42Ni42Ni4yLzMyCkROUyA9IDEuMS4xLjEKSmMgPSA0CkptaW4gPSA0MApKbWF4ID0gNzAKU19xID0gMApTMiA9IDAKRDEgPSAxMjM0NTY3ODkKSDIgPSAyMzQ1Njc4OTEKSDMgPSAzNDU2Nzg5MTIKSDQgPSA0NTY3ODkxMjMKCltQZWVyXQpQdWJsaWNLZXkgPSBFdnpPMEtqMG1jU2Z1T1dXNWQ2TldkSDJ2OXI0T1lGUG93aG03SGhmN1Z5d0M9CkFsbG93ZWRJUHMgPSAwLjAuMC4wLzAsIDo6LzAKRW5kcG9pbnQgPSAxOTIuMTY4LjEuMjA1OjUxODIwCg==#AmneziaWG%20%28Tachyon%20Router%29 '''; final parser = LinkParser(); final b64Payload = base64.encode(utf8.encode(routerLinks.trim())); final profiles = parser.parseSubscription(b64Payload, subscriptionId: 'sub-router'); expect(profiles, hasLength(21)); for (final p in profiles) { final cfg = RuntimeConfig( profile: p, routingMode: RoutingMode.rules, dns: const DnsSettings(), ruleSets: const [], ).toJson(); if (p.type == 'wireguard') { expect(cfg['endpoints'], isA()); expect((cfg['endpoints'] as List).first['type'], 'wireguard'); } else { final outbounds = cfg['outbounds'] as List; expect(outbounds.first['type'], p.type); } } }); test('адаптивный desync и tewfai корректно сериализуются в конфиг ядра', () { final config = RuntimeConfig( profile: profile, routingMode: RoutingMode.desync, dns: const DnsSettings(fakeIp: true), ruleSets: const [], desync: const DesyncSettings( enabled: true, preset: 'multi_disorder', fooling: 'md5_badack', autoTune: true, customSni: 'padencap', ), filesDir: '/data/user/0/app.tachyon.proxy/files', ).toJson(); final exp = config['experimental'] as Map; final cacheFile = exp['cache_file'] as Map; expect(cacheFile['enabled'], isTrue); expect(cacheFile['path'], '/data/user/0/app.tachyon.proxy/files/cache.db'); expect(cacheFile['store_fakeip'], isTrue); final outbounds = (config['outbounds'] as List).cast>(); final desyncOut = outbounds.firstWhere((o) => o['tag'] == 'desync'); expect(desyncOut['type'], 'desync'); expect(desyncOut['preset'], 'multi_disorder'); expect(desyncOut['fooling'], 'md5_badack'); expect(desyncOut['auto_tune'], isTrue); expect(desyncOut['fake_sni'], 'padencap'); const tewfaiLink = 'tewfai://6259d517-551f-4902-ae1c-86073deb2a25:tfpass@tf.example.com:443?sni=tf.example.com&transport=quic,tcp&inner_cipher=aes-256-gcm&morph_profile=auto&pqc=1&handover=1&rotate_secs=300&rotate_mb=128&fec=1&desync=1&shaper=1&shaper_profile=adaptive&mtu=1400#Tewfai-1'; final parser = LinkParser(); final parsed = parser.parse(tewfaiLink); expect(parsed, isNotNull); final outbound = parsed!.toOutbound(); expect(outbound['type'], 'tewfai'); expect(outbound['morph_profile'], 'auto'); expect(outbound['desync'], isTrue); expect(outbound['pqc'], isTrue); expect(outbound['fec'], isTrue); expect((outbound['shaper'] as Map)['mode'], 'adaptive'); expect((outbound['handover'] as Map)['rotate_secs'], 300); expect((outbound['handover'] as Map)['rotate_mb'], 128); expect(outbound['mtu'], 1400); final reparsed = parser.parse(parsed.toShareUri()); expect(reparsed, isNotNull); final reOutbound = reparsed!.toOutbound(); expect(reOutbound['desync'], isTrue); expect((reOutbound['handover'] as Map)['rotate_secs'], 300); expect((reOutbound['handover'] as Map)['rotate_mb'], 128); expect(reOutbound['mtu'], 1400); }); test('устаревшие бесплатные узлы (WARP и SHARD) автоматически отфильтровываются из списков', () { const warpProfile = Profile( id: 'warp-1', name: 'WARP AWG 1', type: 'wireguard', server: '162.159.192.1', port: 2408, subscriptionId: 'free-warp', ); const shardProfile = Profile( id: 'shard-1', name: 'SHARD CF 1', type: 'vless', server: '104.16.0.1', port: 443, subscriptionId: 'free-shard', ); const userSub = SubscriptionEntry( id: 'sub-user', url: 'https://sub.example.com/api', name: 'Моя подписка', ); const warpSub = SubscriptionEntry( id: 'free-warp', url: 'https://api.cloudflareclient.com/warp', name: 'Cloudflare WARP (AmneziaWG)', ); final settingsWithLegacy = AppSettings( profiles: const [warpProfile, shardProfile, profile], subscriptions: const [warpSub, userSub], selectedProfileId: 'warp-1', ); expect(settingsWithLegacy.visibleProfiles.map((p) => p.id), ['vless-1']); expect(settingsWithLegacy.visibleSubscriptions.map((s) => s.id), ['sub-user']); expect(settingsWithLegacy.selectedProfile?.id, 'vless-1'); final restored = AppSettings.fromJson(settingsWithLegacy.toJson()); expect(restored.profiles.map((p) => p.id), ['vless-1']); expect(restored.subscriptions.map((s) => s.id), ['sub-user']); }); test('балансировщики tachyon-core 0.3.9 корректно сериализуются для всех режимов и телеметрии', () { const balancerModesWithBlock = [ 'stability', 'sticky', 'least_load', 'weighted', 'passive', 'priority', 'hedged', 'throughput', 'quota', 'round_robin', ]; for (final mode in balancerModesWithBlock) { final settings = BalancerSettings( mode: mode, pool: 5, poolTolerance: 90, stickyHash: const ['domain', 'dest_ip'], quotaMib: 256, interval: '2m', tolerance: 40, ); final out = settings.toUrltestOutbound( tag: 'proxy', outbounds: const ['auto-srv-0', 'auto-srv-1'], ); expect(out['type'], 'urltest'); expect(out['tag'], 'proxy'); expect(out['mode'], mode); expect(out['interval'], '2m'); expect(out['tolerance'], 40); expect(out['balancer'], isA>()); final bal = out['balancer'] as Map; expect(bal['pool'], 5); expect(bal['pool_tolerance'], 90); expect(bal['sticky_hash'], ['domain', 'dest_ip']); expect(bal['quota_mib'], 256); } for (final legacyMode in ['least_test', 'failover']) { final settings = BalancerSettings( mode: legacyMode, pool: 4, poolTolerance: 80, ); final out = settings.toUrltestOutbound( tag: 'proxy', outbounds: const ['auto-srv-0'], ); expect(out['mode'], legacyMode); expect(out.containsKey('balancer'), isFalse); } const wgCandidate = Profile( id: 'wg-1', name: 'WARP 1', type: 'wireguard', server: '162.159.192.1', port: 2408, subscriptionId: 'sub-1', ); const vlessCandidate = Profile( id: 'vless-2', name: 'VLESS 2', type: 'vless', server: 'example.org', port: 443, uuid: '00000000-0000-0000-0000-000000000000', subscriptionId: 'sub-1', ); const autoProfile = Profile( id: 'auto:sub-1', name: 'Автовыбор', type: 'urltest', server: 'auto', port: 443, subscriptionId: 'sub-1', ); const customBalancer = BalancerSettings( mode: 'stability', pool: 6, poolTolerance: 100, ); final cfg = RuntimeConfig( profile: autoProfile, routingMode: RoutingMode.rules, dns: const DnsSettings(), ruleSets: const [], extraProfiles: const [vlessCandidate, wgCandidate], balancer: customBalancer, ).toJson(); final outbounds = (cfg['outbounds'] as List).cast>(); final proxyOut = outbounds.firstWhere((o) => o['tag'] == 'proxy'); expect(proxyOut['type'], 'urltest'); expect(proxyOut['mode'], 'stability'); expect(proxyOut['outbounds'], ['auto-srv-0', 'auto-srv-1']); expect((proxyOut['balancer'] as Map)['pool'], 6); expect((proxyOut['balancer'] as Map)['pool_tolerance'], 100); expect(outbounds.any((o) => o['tag'] == 'auto-srv-0' && o['type'] == 'vless'), isTrue); final endpoints = (cfg['endpoints'] as List).cast>(); expect(endpoints.any((e) => e['tag'] == 'auto-srv-1' && e['type'] == 'wireguard'), isTrue); final appSettings = AppSettings(balancer: customBalancer); final restoredSettings = AppSettings.fromJson(appSettings.toJson()); expect(restoredSettings.balancer.mode, 'stability'); expect(restoredSettings.balancer.pool, 6); expect(restoredSettings.balancer.poolTolerance, 100); final stats = TrafficStats.fromJson({ 'running': true, 'up': 1024, 'down': 2048, 'connections': 3, 'balancer': { 'tag': 'proxy', 'now': 'auto-srv-0', 'mode': 'stability', 'telemetry': { 'auto-srv-0': { 'rtt_ms': 42, 'ewma_rtt_ms': 45, 'jitter_ms': 4, 'loss_penalty_ms': 0, 'quarantined': false, 'quarantine_rem_s': 0, 'active_conns': 2, 'throughput_kib_s': 1280, 'transferred_kib': 4096, }, }, }, }); expect(stats.balancer, isNotNull); expect(stats.balancer!.now, 'auto-srv-0'); expect(stats.balancer!.mode, 'stability'); final nodeTel = stats.balancer!.telemetry['auto-srv-0']; expect(nodeTel, isNotNull); expect(nodeTel!.rttMs, 42); expect(nodeTel.ewmaRttMs, 45); expect(nodeTel.jitterMs, 4); expect(nodeTel.activeConns, 2); expect(nodeTel.throughputKibS, 1280); expect(nodeTel.quarantined, isFalse); final sub77 = List.generate( 77, (i) => Profile( id: 'srv-$i', name: 'Server $i', type: 'vless', server: 's$i.example.org', port: 443, uuid: '00000000-0000-0000-0000-000000000000', subscriptionId: 'sub-1', ), ); final resolved77 = RuntimeConfig.resolveAutoCandidates(autoProfile, sub77); expect(resolved77.length, 77); }); test('Subscription customHwid, updatedAt and Wi-Fi / Cellular network server lists work', () { const wifiSub = SubscriptionEntry( id: 'sub-wifi', url: 'https://example.org/wifi', name: 'Домашняя подписка', updatedAt: 1730970000000, customHwid: 'aabbccddeeff00112233445566778899', networkScope: 'wifi', ); const cellSub = SubscriptionEntry( id: 'sub-lte', url: 'https://example.org/lte', name: 'Мобильная подписка', updatedAt: 1730973600000, networkScope: 'cellular', ); final restoredSub = SubscriptionEntry.fromJson(wifiSub.toJson()); expect(restoredSub.updatedAt, 1730970000000); expect(restoredSub.customHwid, 'aabbccddeeff00112233445566778899'); expect(restoredSub.networkScope, 'wifi'); const srvWifi = Profile( id: 'srv-wifi-1', name: 'Wi-Fi Node', type: 'vless', server: 'wifi.example.org', port: 443, uuid: '00000000-0000-0000-0000-000000000001', subscriptionId: 'sub-wifi', ); const srvCell = Profile( id: 'srv-lte-1', name: 'LTE Whitelist Node', type: 'vless', server: 'lte.example.org', port: 443, uuid: '00000000-0000-0000-0000-000000000002', subscriptionId: 'sub-lte', ); const srvManualCell = Profile( id: 'srv-manual-lte', name: 'Manual LTE Node', type: 'vless', server: 'm-lte.example.org', port: 443, uuid: '00000000-0000-0000-0000-000000000003', extra: {'network_scope': 'cellular'}, ); expect(srvManualCell.networkScope, 'cellular'); expect(srvManualCell.toOutbound().containsKey('network_scope'), isFalse); const globalAuto = Profile( id: 'auto:all', name: 'Автовыбор', type: 'urltest', server: 'auto', port: 443, ); final allProfiles = [srvWifi, srvCell, srvManualCell]; final allSubs = [wifiSub, cellSub]; final onWifi = RuntimeConfig.resolveAutoCandidates( globalAuto, allProfiles, activeNetworkType: 'wifi', subscriptions: allSubs, ); expect(onWifi.map((p) => p.id).toList(), ['srv-wifi-1']); final onCellular = RuntimeConfig.resolveAutoCandidates( globalAuto, allProfiles, activeNetworkType: 'cellular', subscriptions: allSubs, ); expect(onCellular.map((p) => p.id).toList(), ['srv-lte-1', 'srv-manual-lte']); final settings = AppSettings( wifiProfileId: 'auto:sub-wifi', cellularProfileId: 'auto:sub-lte', subscriptions: allSubs, profiles: allProfiles, ); final restoredSettings = AppSettings.fromJson(settings.toJson()); expect(restoredSettings.wifiProfileId, 'auto:sub-wifi'); expect(restoredSettings.cellularProfileId, 'auto:sub-lte'); }); }