Compare commits

...

2 Commits

69 changed files with 2482 additions and 419 deletions
+151
View File
@@ -324,5 +324,156 @@
"PublicBaseCommit": "ac650ed51dc3efad38b128f4c2e3dbb0ca9a4144",
"SourceOnly": true,
"Version": "0.3.0"
},
"Windows031MonitorDelta": {
"CandidateSha256": "fe6d7ae81022a774e13f8c347592ffdaaad76ecdcccd352057e0203ea453b7f2",
"ExampleEndpointChanges": [
{
"Count": 4,
"Path": "windows/KnownTailnetEndpoints.cs"
},
{
"Count": 3,
"Path": "windows/LearningSelfTest.cs"
},
{
"Count": 1,
"Path": "windows/LearningTransportSelfTest.cs"
},
{
"Count": 1,
"Path": "windows/NetworkHandoverSelfTest.cs"
},
{
"Count": 1,
"Path": "windows/PlatformBootstrapTransport.cs"
},
{
"Count": 5,
"Path": "windows/PlatformBootstrapTransportSelfTest.cs"
},
{
"Count": 4,
"Path": "windows/PrivateAuxiliaryRouting.cs"
},
{
"Count": 25,
"Path": "windows/PrivateAuxiliaryRoutingSelfTest.cs"
},
{
"Count": 1,
"Path": "windows/PublicTailnetSelectionSelfTest.cs"
},
{
"Count": 65,
"Path": "windows/TailnetTransportSelfTest.cs"
},
{
"Count": 1,
"Path": "windows/ConnectionSelfTest.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 1,
"Path": "windows/GitReleasePolicySelfTest.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 1,
"Path": "windows/InstallationIntegration.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 2,
"Path": "windows/LearningSelfTest.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 1,
"Path": "windows/MainForm.Dashboard.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 2,
"Path": "windows/MainForm.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 1,
"Path": "windows/PlatformBootstrapTransport.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 6,
"Path": "windows/PlatformBootstrapTransportSelfTest.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 1,
"Path": "windows/PrivateAuxiliaryRouting.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 7,
"Path": "windows/PrivateAuxiliaryRoutingSelfTest.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 2,
"Path": "windows/TailnetTransportProbe.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 1,
"Path": "windows/TailnetTransportSelfTest.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 2,
"Path": "windows/TunConfigBuilder.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 1,
"Path": "windows/VpnApiClient.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 1,
"Path": "windows/XrayManager.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 1,
"Path": "windows/installer/VPNPlus.nsi",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 1,
"Path": "windows/build/ProductionInstallationBaseline.ps1",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 1,
"Path": "windows/release/RELEASE-NOTES-0.2.21.md",
"RuleSet": "windows-monitor-20261027"
}
],
"FrozenSha256": "c8fd3ef49cf6aaf499e12e55291795f900f8fe861736fbb30f368a53ce5a2927",
"Omitted": [
"windows/assets/login-cloud-scene-v1.jpg"
],
"OptionalUnlicensedSceneRemainsOmitted": true,
"OriginalAcceptanceTransferred": false,
"OriginalSourceManifestSha256": "a8f099ce039f0712c50683af1e586ad0f95318d4acf0f07bf8e59420843d3d5c",
"OtherComponentsModified": false,
"PrivateHistoryIncluded": false,
"ProductionAccepted": false,
"PublicBaseCommit": "366b3c5c9ac5047691e7f272e718f5f6f9ae7757",
"PublicDownloadDomainsRetained": [
"pro.ucvl.cn"
],
"SourceOnly": true,
"Version": "0.3.1"
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
# 纵横家开源源码
此仓库是无私有 Git 历史的清洁源码快照:Windows 0.3.0、Django 后台及 iPhone/iPad 1.0.2。公司自有代码按 MIT 开源;第三方组件遵守原许可,公司商标及 Logo 不在 MIT 授权范围。Android 保留原 GPL-3.0 公开仓库,不重复拷贝或改换许可。
此仓库是无私有 Git 历史的清洁源码快照:Windows 0.3.1、Django 后台及 iPhone/iPad 1.0.2。公司自有代码按 MIT 开源;第三方组件遵守原许可,公司商标及 Logo 不在 MIT 授权范围。Android 保留原 GPL-3.0 公开仓库,不重复拷贝或改换许可。
| 目录 | 内容与状态 |
| --- | --- |
+52 -35
View File
@@ -4,7 +4,7 @@
"ExportDiffersFromOriginalCandidates": true,
"FilesBeforeProvenanceAndAudit": {
"LICENSE": "b7e94910b8dc377b0a05ccde3c6e5941838dfc15c9dd790078d11728205b524e",
"README.md": "7f750cb284d9f09e811ef82236c8e9aa64209832c6afb55fd057b4e73e8972d7",
"README.md": "c2c081754048ff7561f65eb5a471c08e7293acaddbbe48839ab302a3ec37b6d7",
"SECURITY.md": "34e56cd9b8f6aa5fee45921c6eb831a542e05e76e41850fc31c44e09de088b3c",
"THIRD_PARTY_NOTICES.md": "8c862f2f6b71440616a887e6deb7444a1262cf7d9f144208cc04041c3f9a3371",
"android/README.md": "bb4387da9a055e97f33bb29a883c543e0938fa858df3fd744abc80553a5ec65c",
@@ -179,9 +179,10 @@
"ios/ThirdParty/Xray-core-MPL-2.0.txt": "2684de17300e0a434686f1ec7f8af6045207a4b457a3fe04b2b9ce655e7c5d50",
"ios/ThirdParty/libXray-MIT.txt": "fc13535fb01ab48c3c594d4c47c1067ebe7650ee86a35a23395b2d9ee58513e2",
"ios/project.yml": "2a88092fc27f503c05a5a1c163f345d568117d50cd04268115dae044431cffab",
"windows/ApiModels.cs": "6ba3dda38066f632a538301ca0bb0f4eba9c24826dc9fcfbeb9fcf0441b865b9",
"windows/ApiModels.cs": "4eb3174c564462ae53a4f73487745c02286146ee412512c834d9ed937846ead5",
"windows/AppPaths.cs": "2bac68512acfb68b4f3dad0d30c9ee17eb6f576eeb73c6a453501d4ea184488e",
"windows/Brand.cs": "621a1c5b75880cbf4f88b482dc58bdd3c98e0f4d156bf816d23d63d48e199bca",
"windows/ChartFreshnessSelfTest.cs": "4af3f37b14296fc34097f5708f8f0f78fb1683c1b091459091c425a11c500a62",
"windows/ClientShutdownScope.cs": "f5944b57ccb4616dbd32ee2952b56dd0c9feccb7c556d8954092c88354a78d41",
"windows/ClientUpdater.cs": "b218513dc57b8513eb749aeab093e39911428a07f05363ae349555d22e53e4b8",
"windows/ConnectionAcceptanceTrace.cs": "c9efd15e19672a5ac3b4b807c96a3de3db3ff2fd373e13494a548df51fecdd9a",
@@ -190,16 +191,16 @@
"windows/ConnectionRecoveryPolicy.cs": "860bd4cedf393f157fc1dd68e407776e1fe0fa1cc6cef7e99cd5581b64c6f5f6",
"windows/ConnectionSelection.cs": "def94b338b9e1fd940c19b8991e4268a4e59bec741ea624f5a6e4fb7a7d3bbcc",
"windows/ConnectionSelectionSelfTest.cs": "12bd82071989c5e539031f6e7921660edb4eb10a4136ac332cc84eca2e2d96de",
"windows/ConnectionSelfTest.cs": "6511feda4c81da766e745a499c682d2d0b3be0386c4ba424e7ddc04029ebca12",
"windows/ConnectionSelfTest.cs": "6ad3f227cec3e26514d833ec1cb996818597a0cb27901053362faa45e3c1c9b3",
"windows/DailyTrafficChart.cs": "4af8d8a91559e6a3fc1dd56db11f3534606aeb486ff918b2b301db0b82e4c716",
"windows/DashboardControls.cs": "1be17efd73acec775aade94461e59c7255a988bd46d056ad8613fdc3e4bd126d",
"windows/DashboardInteractionSelfTest.cs": "4105a6b9651664677c2bdd8aab3058ccdecd51aaad393610fdc79ed6aa30f0e8",
"windows/DashboardLayout.cs": "6c1c45ec5e6d65007949a38f27c5f87e3189439314e292d1fe67407a50c66994",
"windows/DashboardTailnetLayoutSelfTest.cs": "38de35c0a47b766407ca702409910da3a85f09c781822faedf0e704a9b781312",
"windows/DashboardInteractionSelfTest.cs": "ad4845d14b5b5db4d91a180f95536dd1093458fab86ec8767b74983891a456b4",
"windows/DashboardLayout.cs": "a07985d84c69ed68783068d847059452db889ee244a98d7ab4e02ace4a5528ba",
"windows/DashboardTailnetLayoutSelfTest.cs": "64ed480d434f673137c5edc5b2b1a5d51f8aa31f8440efb734c052a472bf81d6",
"windows/DashboardWheelRouter.cs": "d903097a5febbff296febb65855dc10b4e056ea5bb54d2df71b5d1f0297dcc1f",
"windows/GitReleasePolicySelfTest.cs": "c43d0e63e9c00a7c6b376ed204bc6c400572085075397685c92862e8318fe369",
"windows/GitReleasePolicySelfTest.cs": "9e49ba957ab15a5c23d889004b171856c3d523f98cecf10088df4fcd8b577c61",
"windows/GitReleaseUpdater.cs": "dcd00a0feca6801aad4e346c7565d8bcd80b3fd24a4accbe5cd4643d04264b9b",
"windows/InstallationIntegration.cs": "af4e5d0cd78d66546079f452e110be627494550594e847d13b77178494fb3bda",
"windows/InstallationIntegration.cs": "fac35b48db7e3c8787a963fa9abdc4e0188e1383ff1d74ffabc685c23ba0d5ce",
"windows/InstallationIntegrationSelfTest.cs": "a381a2e6b650e4b841551d3bf06ade4edcc267acca15cd812185f58f03bac5f6",
"windows/InstallationPackageSelfTest.cs": "4a1d401768e65f8d933b86500407ae8e1baa9e8575da01f97030059078fc2848",
"windows/InstallationRemoval.cs": "bdba7f9921f1645d9a0bc50e31cb55ef37da2d15330f763005936a60085733c7",
@@ -213,19 +214,19 @@
"windows/LearningMatrixSelfTest.cs": "edb37d73f3db2e2722d49f92cf141e1b13275c76bdfadf36ab65eacf1d83d8ec",
"windows/LearningPolicy.cs": "858646bbbe65cf18a193c425fbd9cbfe114accf34abe5c981df866ec27a45fcf",
"windows/LearningProbeBudget.cs": "3001e1deda8a4337d1754a09bbc7569619f2730258d44d019d2fbcca472e51e5",
"windows/LearningSelfTest.cs": "786587e8a145bbcd86acfc77f8f204958a6576aa008a19637e521ebb93926b10",
"windows/LearningSelfTest.cs": "74cc9cc1c653935885bd7e4478647738e3e30bdd1caa15c0af33a7fbd95519a0",
"windows/LearningStore.cs": "cc1c6cf1b0c5b948e16be24a46dc2429a020cafa176a36ad9c450d887410169e",
"windows/LearningSyncCoordinator.cs": "dd5b3c75d2c712ac11d1b6c4e4e698cc17947df743394abf9287efdb48174742",
"windows/LearningSyncCoordinatorSelfTest.cs": "471ec344130fe74d892c1115637bd98c517084fc309e982d4d11d3f0ee19403c",
"windows/LearningTransportSelfTest.cs": "05dcfd3fcfc6f25e20612c020583eb6c36934c1b251e50e70fcd29501ad0efe7",
"windows/MainForm.Chrome.cs": "30dc6520a44a5120c78c472c9fb053e2e4dea8e254b5531d04a5342964969c7a",
"windows/MainForm.Dashboard.cs": "306eb7939a1f571f17bf0747c3373851e38f2628247f85c49ea496bf35097b11",
"windows/MainForm.Handover.cs": "a7c6e81186be1d7a154c6997b7d44621543c163ba703901d7974632dd462d25f",
"windows/MainForm.NextGeneration.cs": "dfd9a07a8da1b194f7aa0585f2c9e22ddb6d92ecf867341dd1a284ae25f273f7",
"windows/MainForm.Dashboard.cs": "1e081c6039eac155e87c057919d7381eecdc2388615b9d56f211de0e379386f4",
"windows/MainForm.Handover.cs": "4a914f4de335331f1f9d2397407328f17ae372e9119329e534af218555dc92e6",
"windows/MainForm.NextGeneration.cs": "b560218aed601359310e9ee57f9628d28432be046342748931253c22dbc2d8b5",
"windows/MainForm.Selection.cs": "d872004a98fc634e40c5edebf85eac7f3dfbb62fad8cafaae66a5c8470cfdaf3",
"windows/MainForm.TailnetTraffic.cs": "432ea16a7f5fe66006530b5b90af6eab59362a2b02685ec2130dadfd43c1652b",
"windows/MainForm.TransportSelection.cs": "6a9b7ef4001564bc88e1903e4e035b7d206104a004bc63bf7bbd720b14a1c11b",
"windows/MainForm.cs": "007d2606a450280f57af368d4a4965858c4849b28d9beec150456238e64fc35c",
"windows/MainForm.TransportSelection.cs": "92e1dd715f39cc40f217e65125d89747bb8c9bedf9a11f70bcd577926e75b995",
"windows/MainForm.cs": "0c202d8c136fc8ae5ed812582bff5d9177c14d009b27e47bd24f5ea518f8c9dd",
"windows/NOTICE.md": "8c862f2f6b71440616a887e6deb7444a1262cf7d9f144208cc04041c3f9a3371",
"windows/NetworkHandover.cs": "b43548be0051cf92dfd332e537951e4b5083f2a123be8021994513bbc3748d46",
"windows/NetworkHandoverSelfTest.cs": "681d0154dc0aa5f49d7ce1f3088b465eea3ed82571b464951df8d4c89cecdf73",
@@ -239,25 +240,27 @@
"windows/NodeHealthProbe.cs": "c49e5cf6b3a62242ae0e486aa3fd267d50485269ec0bd769cf140e743850fec7",
"windows/NodeMatrixSelfTest.cs": "eed8e56036d300fdffd82b83cca87ea6b2806e8598b2c4fc916aded15197f20d",
"windows/NodePresentation.cs": "c70a8be06cce937f309fd10531d97b02b675a72509fff2419e412fbdf84977c0",
"windows/NodeTransportConnector.cs": "ca73c48cbe5a451ce9ecfc182e1e04d2e2682a0594b017da6c476a93fd225ef4",
"windows/NodeTrafficMonitor.cs": "365c821eb9fc08f33e9387369c9f985f31992470214a5a13758f51dc3c84f0b8",
"windows/NodeTrafficSelfTest.cs": "33d7c8e16d23d19396f60e36d3204196e9499546022c09b3a8aaca9b957e01f2",
"windows/NodeTransportConnector.cs": "91d53471f35470fc9a4578e2819863e56a790cda62a7dbfe891a71149d2386e1",
"windows/PhysicalUplink.cs": "b0a0eca6b9f724972d0e445c2dc352326ea4d7357317b98639972d60dadc2e63",
"windows/PlatformBootstrapTransport.cs": "a1f54cd698c778eca74aca5406977c0e39673f9b33eaec3a9d3567a1d02e642a",
"windows/PlatformBootstrapTransportSelfTest.cs": "150dc9973bc5ffc981eb7b89723620cb32be0ebeea8c41e4088d65a6663b8710",
"windows/PrivateAuxiliaryRouting.cs": "60bf679c0d620a38203323852cd585b44e1b77613dac7708ea93306ffeb9d255",
"windows/PrivateAuxiliaryRoutingSelfTest.cs": "1a955b2d8e7e9ffe8ff0c6a7bc717877ccd0f7681ff8a65219bb2fe93c230382",
"windows/PlatformBootstrapTransport.cs": "0eef4a4272449c0e2adfac2e4652bd9cff9c1b2bc11011ca2049dde2f97e4e2b",
"windows/PlatformBootstrapTransportSelfTest.cs": "59177ceb52391fb27f04599e138f49a1c461ad283bb930bffc4bcefa663ab23f",
"windows/PrivateAuxiliaryRouting.cs": "75fe16563edd7747c7bfd1dec3d8285378ae4a990cdc660e6972d3f84532a0b1",
"windows/PrivateAuxiliaryRoutingSelfTest.cs": "8b2e867f562017e680def8f74c7fba972404442816abae7bf54fcab5d47339df",
"windows/PrivateAuxiliaryRuntime.cs": "dcfb406508e3d7e9a9163163cfe5e2724a6955a18ae4604e2d9f890da61308cf",
"windows/PrivateTransportProbe.cs": "e29e9bd0180a37bdcecf7104fde5069be799aca92b747881d0485a62d382d9b3",
"windows/Program.cs": "76870d42cd185f246a4d7b9b654f94da7fd3c403379f39ea5beddda96afcc720",
"windows/Program.cs": "632a984e5c971b016a5f15b2ff1804b99cfd279661bd637a45f40dcd42e68ecd",
"windows/ProxyDnsPolicy.cs": "997e2e922ad43956932c1bd0a6da3457bc308ee723f4f77ff8e52aa23fa954c0",
"windows/ProxyProbe.cs": "5d27b5a6c6b192a0c0f3ec4637c5a876a71130497af57f7cb4a04ab4735ca1ec",
"windows/PublicTailnetSelection.cs": "cdd6e9195e678bd29dcef96aa9d16ffac9bf42bfe1a10ef293aefd31a2c4a68a",
"windows/PublicTailnetSelectionSelfTest.cs": "aed90554aa88aa7701eaccc925307a48d4a79e244c40d0c456b88f1207b540c0",
"windows/README.md": "46c64d55b7ca6704510f060bf3d533b7f2750c48c5e2c37dae9d53d386badf3d",
"windows/README.md": "7296f084849469b2420a091cbee1ed381986d95956dd79d94338b4b924167671",
"windows/ReplacementContinuitySelfTest.cs": "107878ab2b367f1812377c0b209f6d620da390091c3882e4be53a48e517d86a1",
"windows/RouteLeaseSelfTest.cs": "6189c66b9f66c58bed26de4441c58a9ec02b67257bfa04ed66d702acfcd054d9",
"windows/RoutingRuleBatches.cs": "9997bfa766fffe7bed7352f307c1f6f118a9be9aa86653eaefae3b2bdaa26c1e",
"windows/RoutingUpdateSelfTest.cs": "48c99fc7a01037aa0368c53ccdb7eec0fea1edfac3bb2532c0de89631343206d",
"windows/ScenicTheme.cs": "d0c22d7c38071c37f56a5d0e2e7eadb3d30a3435d0bdd9e921259375c2f0f117",
"windows/ScenicTheme.cs": "da0ec888a65216b57f881cf5bbc2ed551a07363afae9f2b6a54f22c6502169c7",
"windows/SessionOperationFence.cs": "86e8dff164dc7f6f45ba3a41126b8e2e36af9de098479a08a9007604ff112277",
"windows/StartupSelfTest.cs": "cb035bf5d22624ed5034b719f0c52a4c1527ace4c371e966f15f7c25c8126013",
"windows/SystemPowerShell.cs": "1f9247d2e4f8c9bad1d71105886d2ab33d8958006dcff7fadc63f27502eda6fe",
@@ -265,23 +268,23 @@
"windows/THIRD_PARTY_NOTICES.md": "c7141fe279b2c364c868888db37bd995feba1552025e2259dc4662a01e5122bb",
"windows/TailnetReadinessPolicy.cs": "0c195d79e89850934b94b5660ab82a1908728ad0d242d7df3e30bdcfb05db1cb",
"windows/TailnetReadinessSelfTest.cs": "97777dba53a970140c549b7ac25183e3b2732c95cd62d8e6c95ca078d2c6c29b",
"windows/TailnetTransport.cs": "1061f3214871d43d017841f1ed32f0ed867ff3d5a35b6642d165b0567be27e48",
"windows/TailnetTransportProbe.cs": "d0811b7d9cddcbf622d88e502c7eb05c6afbddbbc0caf3077fa9ec769e52cf50",
"windows/TailnetTransportSelfTest.cs": "bb5dde2771db35c430dfc6cff907c90f0594301a81a471e7dea1b7ea71444805",
"windows/TailnetTransport.cs": "c93769b845090f244eeedef2b49afa4bea500af809a995ffdcaf8c314ffb84eb",
"windows/TailnetTransportProbe.cs": "c71a0d946cbefb2713e0b564ea95ae99cbd70f0ec19c8cfc416a12e16589f99a",
"windows/TailnetTransportSelfTest.cs": "8ace8cc2f443c1ce576bbb9471cb46f107ac28f999090baa30431412d8a263f3",
"windows/TokenStore.cs": "e07cf7d1a4cf7a1bba871c19e50b9d6355cb8c1546657346b0256c8215fed8bb",
"windows/TrafficChart.cs": "d4deee2bcde169aee349fe183bbb3bd4cf2f89eb6639e5d37f32bb5df9102653",
"windows/TunConfigBuilder.cs": "f651c0525ee0e083d4e723f9409c0992b8cc274105bb8ad1e4c7d1c75f3b4354",
"windows/TrafficChart.cs": "9b2b42761d9f636cd3be3d6015ce4eff73bf7c0645105c7679f1987b1f5571a0",
"windows/TunConfigBuilder.cs": "35a17b9da204e338dde5ed6cd4f2e979d94ad73c4c01cc0001fc582e94b67194",
"windows/TunConnectivitySelfTest.cs": "a7d7aff1d03e45dff921807cbfb8f83b5013c9df5c7e06b6662d84a8686b2f86",
"windows/TunRouting.cs": "c6b3e1070a0ba0a3c42dbd12becba55404e540d06aba03cb1cc1053fa426a4c1",
"windows/UpdateProgressForm.cs": "25286b76a235635704dbe8831367141939d063153d0828ee375f1c71d461f041",
"windows/UpdateSelfTest.cs": "453165bb611efb8db0d8a8c9ea13f3553e0047aa22b838c43096e3d83fe18771",
"windows/UpdateStreamSelfTest.cs": "ad059016c0197f33582b1969ab3280c5b9589a28d659613b3e97ce4a357d38c1",
"windows/UsageHistorySeries.cs": "9e7515ceede1899e06116352de79edd6252c921048bcae9958bf9358d93b3069",
"windows/VPNPlus.csproj": "bb2aaba90223713a4669a0b121f97af47b6c67391d0f1ccd9fca1b2669beed25",
"windows/VpnApiClient.cs": "6e227467981bbc68aac7fb93fe32cfb96f06b0d06f04405209512f1a11c971af",
"windows/VPNPlus.csproj": "cc59524a6a01f8a606bece97ae45ca6cf25f9fb5ec83b36372d68a0f02f76cab",
"windows/VpnApiClient.cs": "187829698d9f26b896dbfef596bc71b12a9ed4e014261abde0497e6763e40ae3",
"windows/WindowChrome.cs": "0eceea0879e792b8ae83a74eaf5658d4a7be6a798fbdb026ff8d19fa9aa6af2c",
"windows/WindowChromeSelfTest.cs": "4bc45ed8c7357f360e1d17fe189698102b249cf6d7226c887faf5be4104f55af",
"windows/XrayManager.cs": "c07fac3e677c71efef6e3f6fd6140e75d7a5ee79ea263a730713db7f96cee580",
"windows/WindowChromeSelfTest.cs": "c17dd805a0102d12b71a3e32c77ceeb45e303e08612de5d3c5259c78327532be",
"windows/XrayManager.cs": "024178506c01a7fe6074c4a05973125338999862e3b52181a0a0ce7399209375",
"windows/XrayRoutingUpdater.cs": "91fd2b5db25477dbe4de7118faef79f9c51f9a8a3dd86e8b26c676092de3bca5",
"windows/app.manifest": "4c9a2e8e2056c3bb0ae45a5f7b2e223298ee683a82b70ba4910e17f5728cf5b6",
"windows/assets/company-logo-original.png": "04cf7f754a5353b96cddbed4a57a557154342c190a1785487e3bfb36cab04163",
@@ -299,7 +302,7 @@
"windows/build/GuardianGateFixture.cs": "b1762ff88076919307eea1b6b0050b7ff561d73759a4cf1283a866659313f9fc",
"windows/build/GuardianGateFixture.csproj": "a4ddf6cdc6730270df8c94c6508467906e04dd057fc39e54c690c77cc01420f4",
"windows/build/OwnedProcessGroup.cs": "00fc73e00dbc25bdf5ff6557f0d81786ba1ef235822ea290bead9b8a5ac66618",
"windows/build/ProductionInstallationBaseline.ps1": "02675e525dd5060a5b0ea20320665533cbb55f9b011b4fd67c99cd88804b983e",
"windows/build/ProductionInstallationBaseline.ps1": "1079dcc459af2b217d7cbddb81d286888d1210f1069cada6272d3b79a531062a",
"windows/build/ProductionNetworkBaseline.ps1": "aa3600f92ba19d3041b0c50696d1035efe68013dec7ae3f7973e75b5fc17f9b1",
"windows/build/Test-InstallerGuardianGate.ps1": "5289a4643cc41279eae8d32a7cfdabfdd528506b03cc9fadaf33880dea996694",
"windows/build/Test-ProductionInstallationBaseline.ps1": "7d5afbffd8e4ed595917fdc8054469cdf071cfe4c932955bb84840d867eec0f0",
@@ -311,14 +314,15 @@
"windows/installer/RegistryAcceptance.nsi": "1982ccea32d06f536e4b9e8fbce56cdf06fc23221d3726f812e7f9b13fe7c456",
"windows/installer/RegistryCleanup.nsh": "eb1b7345e195dd04f91d778e9120b04af04b2e28be6712290011609b7481b58f",
"windows/installer/RemovalPayload.nsh": "2cfcac32faf79e988bd5c4f92fc37f3f9bbe1fb39875d8645d689edb9c209b7e",
"windows/installer/VPNPlus.nsi": "6e53ec57071e4c8b48f2c168396fc13a3caa9ce11a78c9426c1fd4c830f2798d",
"windows/installer/VPNPlus.nsi": "a40f55a919901b260a9734827e08aa47b7ed8a0983ff2528e49c38b18bfec966",
"windows/licenses/NSIS-COPYING.txt": "388357c1215ff403c5ebde3a5ecd273e68f8b79a579996775245d1ee65442aba",
"windows/licenses/Wintun-License.txt": "183adac21e7d96c508c8fd34d394b7b6708bc81564ad1bad61ab66143a008cd2",
"windows/licenses/Xray-MPL-2.0.txt": "1f256ecad192880510e84ad60474eab7589218784b9a50bc7ceee34c2b91f1d5",
"windows/release/RELEASE-NOTES-0.2.21.md": "839f36685e39c04bf692ffd2896bab4538577c0b3bbddd0a3cc335fe13b65d4c",
"windows/release/RELEASE-NOTES-0.2.21.md": "abab21868b3699072aaaef12452ceebaa10c51405eedbf7b560e20c1182af5f7",
"windows/release/RELEASE-NOTES-0.2.22.md": "bf6c8b448481f59a05e8653fbaa1356d986d2d481c3cbaf02fe6402dcf55d499",
"windows/release/RELEASE-NOTES-0.2.23.md": "2f8aea1ec4d4f1bcc9860d8945dc6266be6ea924ff9958c589a6e4eb0550dc76",
"windows/release/RELEASE-NOTES-0.3.0.md": "cc1e398354ffb562c0647dbe91ffd3f43e614f3923298005c76999c457b77bf2"
"windows/release/RELEASE-NOTES-0.3.0.md": "cc1e398354ffb562c0647dbe91ffd3f43e614f3923298005c76999c457b77bf2",
"windows/release/RELEASE-NOTES-0.3.1.md": "e28a99d049842adc34f593e39bbc33484dd4dfc9e31568cbcb1aef1f3bcd4132"
},
"IosSourceCommit": "b07d085413b1b6370245866fd82271b76590b6d6",
"Kind": "clean-history-free-open-source-export",
@@ -540,5 +544,18 @@
"SourceOnly": true,
"Version": "0.3.0"
},
"Windows031MonitorDelta": {
"CandidateSha256": "fe6d7ae81022a774e13f8c347592ffdaaad76ecdcccd352057e0203ea453b7f2",
"FrozenSha256": "c8fd3ef49cf6aaf499e12e55291795f900f8fe861736fbb30f368a53ce5a2927",
"OptionalUnlicensedSceneRemainsOmitted": true,
"OriginalAcceptanceTransferred": false,
"OriginalSourceManifestSha256": "a8f099ce039f0712c50683af1e586ad0f95318d4acf0f07bf8e59420843d3d5c",
"OtherComponentsModified": false,
"PrivateHistoryIncluded": false,
"ProductionAccepted": false,
"PublicBaseCommit": "366b3c5c9ac5047691e7f272e718f5f6f9ae7757",
"SourceOnly": true,
"Version": "0.3.1"
},
"WindowsSourceCommit": "0d463e6af91a3802c564b06dabb6bf86ebff5a38"
}
+16 -2
View File
@@ -1,5 +1,19 @@
# 优创⁺纵横家 iPhone / iPad 验收记录
## 2026-10-27:1.0.3 / 10003 源码候选(非 IPA)
结论:`SOURCE_CANDIDATE`。本次新增的是源码与归档流程;没有生成、签名、安装或发布 iPhone/iPad 二进制,也没有对用户手机执行操作。
- 源码连接策略只接受后台为当前节点明确授权的内部 IP 入口,先执行限时 ICMP Ping;匹配回复后才尝试内部代理,并验证实际出口。内部 Ping 不通或内部传输失败先回退同一节点的原公网配置;本次连接一旦走公网,含后续节点重试在内都不自动切回内部入口。
- 内部入口依赖系统原有可达路由;不登录、启动、停止或管理 Tailscale,不修改其配置,不承诺 iOS 同时运行两个 Packet Tunnel。Ping 通过不能代替本应用 VPN 建立后的真实代理业务验收。
- 2026-10-27 对公司 Git 的认证只读查询:iOS 仓库启用 Actions,runner API `total_count=0`;仅有的 5 次运行均为 `source-audit.yml` 且全部 cancelled,未发现 `apple-build.yml` 执行。未读取秘密值、触发 workflow 或更改远端。
- `Scripts/verify-and-archive.sh` 改为从 `project.yml` 读取唯一有效版本,归档为 `build/UCVL-Zonghengjia-1.0.3.xcarchive`;支持 `SIMULATOR_DESTINATION` 覆盖默认 iPhone 16 Pro。缺少 Team、版本无效、导出文件缺失或 plist 格式错误时,在下载/构建前停止;fetch 的官方 SHA256 校验流程保留。
- Windows 上已运行 9 项 Python subprocess 测试,复制真实归档脚本到临时目录并替换外部命令,验证精确的归档/导出参数、模拟器覆盖、预检及逐阶段失败停止。测试先在旧脚本上失败,再在修改后通过;它不执行 Xcode/XCTest、真实 `plutil`、下载、签名或真实 VPN 流量。
仍缺可用 Mac/Xcode runner、获授权 Apple Team 与 Network Extension Provisioning Profile、对应分发方式的签名/ExportOptions,以及真实 iPhone/iPad 的 VPN 授权、内部入口/同节点公网回退、出口、睡眠唤醒、切网和断开恢复验收。源码静态审计以本次 `Scripts/source-audit.py` 的实际报告为准;离线脚本测试不能替代这些条件,当前没有可安装 IPA 或 TestFlight/MDM 发布结果。
以下保留历史版本记录,其检查结果不自动转移到本次候选。
## 2026-09-09:1.0.2 源码候选(非 IPA)
工程 `MARKETING_VERSION` 为 1.0.2,README 已与之同步,源码审计新增文档版本一致性检查并通过。现有错误分类源码区分平台/本机授权/节点失败及 401/403 授权失效;XCTest 已编写,仍未运行。这次只修正文档和静态校验,没有新的 iOS 二进制构建、签名、安装包、真机连接或公开发布。未取得 Mac/Xcode/开发者团队条件,不能把 Windows 测试当成苹果验收。
@@ -17,14 +31,14 @@
- 登录令牌保存在 Keychain,源代码没有公司账号、密码、令牌、证书或私钥。
- 后台以 `node=auto&new_connection=1` 分配节点,客户端隐藏节点选择,只显示实际工作节点。
- 最多三次失败切换;每次失败把已失败节点加入 `exclude`,断开并等待系统 VPN 恢复后再试。
- 001/002 节点由 NPM TCP Stream 端口分流;节点子域无 A 记录时,主应用通过阿里/腾讯 DoH 获取统一入口 `vpn.toplc.cn` 的真实公网 IPv4,拒绝 Clash Fake-IP (`198.18.0.0/15`)、私网、Tailscale 和其它保留地址。
- 001/002 节点由 NPM TCP Stream 端口分流;节点子域无 A 记录时,主应用通过阿里/腾讯 DoH 获取统一入口 `vpn.example.invalid` 的真实公网 IPv4,拒绝 Clash Fake-IP (`198.18.0.0/15`)、私网、Tailscale 和其它保留地址。
- Packet Tunnel 在接管默认路由前排除该公网 IPv4,并将运行时 VLESS 地址改为同一 IP;Reality SNI 保持不变。
- 支持后台 `config_contract=2` 统一 NPM 网关字段,同时兼容未返回该字段的旧后台。
- VPN 连接状态变为 connected 后,再访问 OpenAI / ChatGPT HTTPS 入口;两个入口均失败才判定当前节点不可用。
- 出口探测返回后再次确认系统 VPN 仍处于 connected,避免隧道已退出时出现假成功。
- libXray v26.7.28 本地官方归档 SHA256:`07F7ED7697277930E1C517755855950F594F41435B0DFC5917A66EEA6278AEB9`。
- 注册入口、套餐与流量、AI 智能代理/全局代理/本地直连、退出账号与网络恢复流程均已在源码中接通。
- Windows 侧对 NPM 公网入口 `192.0.2.1` 复核:`vpn.toplc.cn` HTTPS 健康接口正常,TCP `11081`、`11082`、`11083` 均可建立连接。该检查只证明 NPM 入口与端口在线,不替代 VLESS Reality 握手或 iPhone 真机出口验收。
- Windows 侧对 NPM 公网入口 `203.0.113.17` 复核:`vpn.example.invalid` HTTPS 健康接口正常,TCP `11081`、`11082`、`11083` 均可建立连接。该检查只证明 NPM 入口与端口在线,不替代 VLESS Reality 握手或 iPhone 真机出口验收。
## 必须在 Mac 和真机完成后才能发布 IPA
+83 -31
View File
@@ -65,9 +65,11 @@ final class AppState: ObservableObject {
busy = true
defer { busy = false }
if vpn.isConnected {
await vpn.disconnectAndWait()
currentNode = nil
message = "正在断开,系统将自动恢复原网络"
do {
try await vpn.disconnectAndWait()
currentNode = nil
message = "已断开,系统已撤销本应用的 VPN 连接"
} catch { errorMessage = friendly(error) }
return
}
guard let profile,
@@ -77,7 +79,8 @@ final class AppState: ObservableObject {
return
}
if route.id == "direct" {
await vpn.disconnectAndWait()
do { try await vpn.disconnectAndWait() }
catch { errorMessage = friendly(error); return }
currentNode = nil
message = "当前为本地直连,不经过 VPN 节点"
return
@@ -91,44 +94,29 @@ final class AppState: ObservableObject {
var excludedNodes: [String] = []
var lastError: Error = UCVLError.connection("没有可用节点。")
let maximumAttempts = max(1, min(profile.nodes.count, 3))
// One explicit connect owns this state across all assigned nodes.
// No timers or system restore path may promote a public connection.
var transport = ProxyTransportSession()
for attempt in 1...maximumAttempts {
var attemptedNode: VPNNode?
do {
let response = try await api.config(token: token, route: route.id, excluding: excludedNodes)
attemptedNode = response.node
let configJSON = try response.configJSONString()
guard let remoteHost = TunnelConfigurationBuilder.remoteAddress(from: configJSON) else {
throw UCVLError.invalidConfiguration("后台线路配置缺少节点域名。")
}
let gatewayHost = response.gateway?.host.trimmingCharacters(in: .whitespacesAndNewlines)
let pinnedGatewayIPv4 = response.gateway?.ipv4?.trimmingCharacters(in: .whitespacesAndNewlines)
let remoteAddress: String
if let pinnedGatewayIPv4, NetworkAddress.isPublicIPv4(pinnedGatewayIPv4) {
remoteAddress = pinnedGatewayIPv4
} else {
let hostToResolve = (gatewayHost?.isEmpty == false ? gatewayHost : nil) ?? remoteHost
remoteAddress = try await api.resolvePublicIPv4(host: hostToResolve)
}
currentNode = response.node
message = "正在连接 \(response.node.displayName)(第 \(attempt) 次验证)…"
try await vpn.connect(
configJSON: configJSON,
resolvedRemoteAddress: remoteAddress,
node: response.node,
route: route
)
try await api.verifyProxyEgress()
guard vpn.status == .connected else {
throw UCVLError.connection("出口验证返回时 VPN 已断开,正在切换备用节点。")
}
message = "已连接 \(response.node.displayName),出口验证通过"
try await connectAssigned(response, route: route, transport: &transport)
return
} catch {
lastError = error
let decision = ConnectionAttemptPolicy.decide(error: error, hasAssignedNode: attemptedNode != nil)
currentNode = nil
await vpn.disconnectAndWait()
do { try await vpn.disconnectAndWait() }
catch {
errorMessage = friendly(error)
message = "系统尚未完成断开,已停止切换线路"
return
}
if decision == .revokeAuthorization {
logoutLocal()
errorMessage = friendly(error)
@@ -149,11 +137,74 @@ final class AppState: ObservableObject {
message = "所有可用节点均未通过验证,已恢复本地网络"
}
private func connectAssigned(
_ response: ClientConfigResponse, route: RouteMode, transport: inout ProxyTransportSession
) async throws {
let configJSON = try response.configJSONString()
if !transport.domainOnly,
let endpoint = ProxyTransportPolicy.authorizedInternalEndpoint(response: response) {
let reachable = await InternalIPProbe.isReachable(endpoint.address)
try Task.checkCancellation()
if reachable {
message = "正在通过内部 IP 连接 \(response.node.displayName)…"
do {
try await vpn.connect(
configJSON: configJSON, resolvedRemoteAddress: endpoint.address,
node: response.node, route: route, internalEndpoint: endpoint,
configContract: response.configContract, connectionScope: response.connectionScope
)
try await verifyActiveEgress()
message = "已连接 \(response.node.displayName) · 内部 IP,出口验证通过"
return
} catch {
guard ConnectionAttemptPolicy.decide(error: error, hasAssignedNode: true) == .retryNode else {
throw error
}
try await vpn.disconnectAndWait()
}
}
}
transport.commitPublicFallback()
try Task.checkCancellation()
// Resolve only when public transport is actually needed. DNS failure
// must not prevent an otherwise usable authorized internal endpoint.
guard let remoteHost = TunnelConfigurationBuilder.remoteAddress(from: configJSON) else {
throw UCVLError.invalidConfiguration("后台线路配置缺少节点域名。")
}
let gatewayHost = response.gateway?.host.trimmingCharacters(in: .whitespacesAndNewlines)
let pinnedAddress = response.gateway?.ipv4?.trimmingCharacters(in: .whitespacesAndNewlines)
let publicAddress: String
if let pinnedAddress, NetworkAddress.isPublicIPv4(pinnedAddress) {
publicAddress = pinnedAddress
} else {
publicAddress = try await api.resolvePublicIPv4(
host: (gatewayHost?.isEmpty == false ? gatewayHost : nil) ?? remoteHost
)
}
message = "正在通过域名入口连接 \(response.node.displayName)…"
try await vpn.connect(
configJSON: configJSON, resolvedRemoteAddress: publicAddress, node: response.node, route: route
)
try await verifyActiveEgress()
message = "已连接 \(response.node.displayName) · 域名入口,本次连接保持不切换"
}
private func verifyActiveEgress() async throws {
try Task.checkCancellation()
try await api.verifyProxyEgress()
try Task.checkCancellation()
guard vpn.status == .connected else {
throw UCVLError.connection("出口验证返回时 VPN 已断开,正在尝试备用入口。")
}
}
func logout() async {
guard !busy else { return }
busy = true
defer { busy = false }
await vpn.disconnectAndWait()
do { try await vpn.disconnectAndWait() }
catch { errorMessage = friendly(error); return }
if let token = SecureStore.token() {
await api.logout(token: token)
}
@@ -182,7 +233,8 @@ final class AppState: ObservableObject {
apply(try await api.profile(token: token))
message = "账号和线路已同步"
} catch UCVLError.api(let status, let message) where status == 401 || status == 403 {
await vpn.disconnectAndWait()
do { try await vpn.disconnectAndWait() }
catch { errorMessage = friendly(error) }
SecureStore.clearToken()
profile = nil
errorMessage = message
+261 -94
View File
@@ -5,7 +5,8 @@ struct ContentView: View {
var body: some View {
ZStack {
UCVLColors.background.ignoresSafeArea()
LandscapeArtwork()
.ignoresSafeArea()
if let profile = state.profile {
DashboardView(profile: profile)
} else {
@@ -13,6 +14,8 @@ struct ContentView: View {
}
}
.tint(UCVLColors.royal)
.foregroundColor(UCVLColors.navy)
.preferredColorScheme(.light)
.alert("提示", isPresented: Binding(
get: { !state.errorMessage.isEmpty },
set: { if !$0 { state.errorMessage = "" } }
@@ -24,23 +27,81 @@ struct ContentView: View {
}
}
// Both placements draw the same original asset with a native aspect-fill crop.
// Artwork remains separate from the real controls and never changes VPN state.
private struct LandscapeArtwork: View {
var body: some View {
GeometryReader { geometry in
Image("MountainLandscape")
.resizable()
.scaledToFill()
.frame(width: geometry.size.width, height: geometry.size.height)
.clipped()
}
.background(UCVLColors.surface)
.allowsHitTesting(false)
.accessibilityHidden(true)
}
}
private struct ScenicPage<Content: View>: View {
let maxWidth: CGFloat
let content: Content
init(maxWidth: CGFloat, @ViewBuilder content: () -> Content) {
self.maxWidth = maxWidth
self.content = content()
}
var body: some View {
ScrollView {
content
.frame(maxWidth: maxWidth)
.padding(.horizontal, 18)
.padding(.vertical, 24)
.frame(maxWidth: .infinity)
}
}
}
private struct BrandHeader: View {
var compact = false
var body: some View {
VStack(spacing: compact ? 8 : 16) {
VStack(spacing: compact ? 8 : 12) {
Image("UCVLLogo")
.resizable()
.scaledToFit()
.frame(width: compact ? 84 : 132, height: compact ? 84 : 132)
.accessibilityLabel("优创未来 Logo")
Text("优创⁺纵横家")
.frame(width: compact ? 60 : 88, height: compact ? 60 : 88)
.accessibilityHidden(true)
Text("纵横家")
.font(compact ? .title2.bold() : .largeTitle.bold())
.foregroundStyle(.white)
Text("优创未来安全网络")
.font(.subheadline)
.foregroundStyle(UCVLColors.sky)
.foregroundStyle(UCVLColors.navy)
.fixedSize(horizontal: false, vertical: true)
Text(AppVersion.label)
.font(.caption)
.foregroundStyle(UCVLColors.muted)
.fixedSize(horizontal: false, vertical: true)
}
.multilineTextAlignment(.center)
.frame(maxWidth: .infinity)
.padding(.horizontal, 16)
.padding(.vertical, compact ? 16 : 24)
.background {
LandscapeArtwork()
.overlay(Color.white.opacity(0.18))
.mask(LinearGradient(colors: [.black, .black, .clear], startPoint: .top, endPoint: .bottom))
}
}
}
private enum AppVersion {
static var label: String {
let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
let build = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String
guard let version, !version.isEmpty else { return "版本信息不可用" }
guard let build, !build.isEmpty else { return "版本 \(version)" }
return "版本 \(version) (\(build))"
}
}
@@ -48,36 +109,39 @@ private struct LoginView: View {
@EnvironmentObject private var state: AppState
@State private var identifier = SecureStore.lastLogin
@State private var password = ""
@FocusState private var focusedField: Field?
private enum Field: Hashable { case identifier, password }
var body: some View {
ScrollView {
VStack(spacing: 28) {
ScenicPage(maxWidth: 540) {
VStack(spacing: 20) {
BrandHeader()
.padding(.top, 34)
VStack(alignment: .leading, spacing: 18) {
Text("公司统一账号登录")
.font(.title2.bold())
.foregroundStyle(UCVLColors.navy)
TextField("用户名或邮箱", text: $identifier)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.disableAutocorrection(true)
.keyboardType(.emailAddress)
.textContentType(.username)
.submitLabel(.next)
.focused($focusedField, equals: .identifier)
.ucvlField()
.onSubmit { focusedField = .password }
SecureField("密码", text: $password)
.textContentType(.password)
.submitLabel(.go)
.focused($focusedField, equals: .password)
.ucvlField()
.onSubmit { Task { await state.login(identifier: identifier, password: password) } }
Button {
Task {
await state.login(identifier: identifier, password: password)
if state.profile != nil { password = "" }
}
} label: {
.onSubmit { signIn() }
Button(action: signIn) {
HStack {
if state.busy { ProgressView().tint(.white) }
Text(state.busy ? "正在登录…" : "安全登录").fontWeight(.semibold)
}
.foregroundColor(.white)
.frame(maxWidth: .infinity)
.padding(.vertical, 14)
}
@@ -85,65 +149,113 @@ private struct LoginView: View {
.disabled(state.busy)
Text("账号停用后,设备授权与线路将自动失效。")
.font(.footnote)
.foregroundStyle(.secondary)
HStack {
Text("还没有账号?")
.font(.footnote)
.foregroundStyle(.secondary)
Link("注册新用户", destination: URL(string: "https://vpn.toplc.cn/register/")!)
.font(.footnote.weight(.semibold))
}
.foregroundStyle(UCVLColors.muted)
.fixedSize(horizontal: false, vertical: true)
RegistrationPrompt()
}
.padding(24)
.background(.white, in: RoundedRectangle(cornerRadius: 24, style: .continuous))
.shadow(color: .black.opacity(0.14), radius: 24, y: 12)
.frame(maxWidth: 540)
Text("vpn.toplc.cn · © 2026 UCVL")
.font(.footnote)
.foregroundStyle(UCVLColors.sky)
.padding(.bottom, 30)
.padding(20)
.scenicCard(cornerRadius: 24)
}
.padding(.horizontal, 20)
}
.toolbar {
ToolbarItemGroup(placement: .keyboard) {
Spacer()
Button("完成") { focusedField = nil }
}
}
}
private func signIn() {
focusedField = nil
Task {
await state.login(identifier: identifier, password: password)
if state.profile != nil { password = "" }
}
}
}
private struct RegistrationPrompt: View {
private var message: AttributedString {
var prompt = AttributedString("还没有账号?")
prompt.foregroundColor = UCVLColors.muted
var link = AttributedString("注册新用户")
link.link = URL(string: "https://vpn.example.invalid/register/")
link.foregroundColor = UCVLColors.royal
link.font = .footnote.weight(.semibold)
prompt.append(link)
return prompt
}
var body: some View {
// A single inline run shares a baseline and wraps naturally at large sizes.
Text(message)
.font(.footnote)
.lineSpacing(4)
.fixedSize(horizontal: false, vertical: true)
}
}
private struct DashboardHeader: View {
@Environment(\.horizontalSizeClass) private var sizeClass
@Environment(\.dynamicTypeSize) private var dynamicTypeSize
let profile: ClientProfile
private var account: some View {
VStack(alignment: .leading, spacing: 6) {
Text("你好,\(profile.displayName.isEmpty ? profile.username : profile.displayName)")
.font(.headline)
Text(profile.email)
.font(.subheadline)
.foregroundStyle(UCVLColors.muted)
Text(profile.identityType == "employee" ? "内部员工" : "外部联系人")
.font(.caption)
.foregroundStyle(UCVLColors.muted)
}
.fixedSize(horizontal: false, vertical: true)
.frame(maxWidth: .infinity, alignment: .leading)
}
var body: some View {
Group {
if sizeClass == .regular && !dynamicTypeSize.isAccessibilitySize {
HStack(spacing: 24) {
BrandHeader(compact: true)
account
}
} else {
VStack(spacing: 16) {
BrandHeader(compact: true)
account
}
}
}
.padding(18)
.scenicCard()
}
}
private struct DashboardView: View {
@EnvironmentObject private var state: AppState
@Environment(\.horizontalSizeClass) private var sizeClass
@Environment(\.dynamicTypeSize) private var dynamicTypeSize
let profile: ClientProfile
var body: some View {
ScrollView {
ScenicPage(maxWidth: 760) {
VStack(spacing: 18) {
HStack(spacing: 16) {
BrandHeader(compact: true)
Spacer()
VStack(alignment: .trailing, spacing: 4) {
Text("你好,\(profile.displayName.isEmpty ? profile.username : profile.displayName)")
.font(.headline)
.foregroundStyle(.white)
Text("\(profile.email) · \(profile.identityType == "employee" ? "内部员工" : "外部联系人")")
.font(.caption)
.foregroundStyle(UCVLColors.sky)
}
}
.padding(.vertical, 8)
DashboardHeader(profile: profile)
StatusCard()
UCVLCard(title: "工作节点与代理模式", systemImage: "point.3.connected.trianglepath.dotted") {
VStack(spacing: 14) {
HStack {
Text("当前工作节点")
Spacer()
AdaptiveDetailRow(title: "当前工作节点") {
Text(state.currentNode?.displayName ?? "由 vpn-ai 自动选择")
.foregroundStyle(state.currentNode == nil ? .secondary : UCVLColors.royal)
.multilineTextAlignment(.trailing)
.foregroundStyle(state.currentNode == nil ? UCVLColors.muted : UCVLColors.royal)
.fixedSize(horizontal: false, vertical: true)
}
Divider()
HStack {
Text("代理模式")
Spacer()
AdaptiveDetailRow(title: "代理模式") {
Picker("代理模式", selection: $state.selectedRouteID) {
ForEach(profile.routeModes) { route in Text(route.name).tag(route.id) }
}
@@ -158,6 +270,7 @@ private struct DashboardView: View {
Image(systemName: state.vpn.isConnected ? "stop.fill" : "bolt.shield.fill")
Text(state.vpn.isConnected ? "断开连接" : "连接")
}
.foregroundColor(.white)
.frame(maxWidth: .infinity)
.padding(.vertical, 12)
}
@@ -169,25 +282,66 @@ private struct DashboardView: View {
UsageCard(subscription: profile.subscription)
HStack(spacing: 12) {
Button { Task { await state.refresh() } } label: {
Label("刷新", systemImage: "arrow.clockwise")
.frame(maxWidth: .infinity)
Group {
if sizeClass == .regular && !dynamicTypeSize.isAccessibilitySize {
HStack(spacing: 12) { accountActions }
} else {
VStack(spacing: 12) { accountActions }
}
.buttonStyle(.bordered)
.disabled(state.busy)
Button(role: .destructive) { Task { await state.logout() } } label: {
Label("退出账号", systemImage: "rectangle.portrait.and.arrow.right")
.frame(maxWidth: .infinity)
}
.buttonStyle(.bordered)
.disabled(state.busy)
}
.padding(16)
.scenicCard()
}
}
}
@ViewBuilder private var accountActions: some View {
Button { Task { await state.refresh() } } label: {
Label("刷新", systemImage: "arrow.clockwise")
.frame(maxWidth: .infinity)
.padding(.vertical, 6)
}
.buttonStyle(.bordered)
.disabled(state.busy)
Button(role: .destructive) { Task { await state.logout() } } label: {
Label("退出账号", systemImage: "rectangle.portrait.and.arrow.right")
.frame(maxWidth: .infinity)
.padding(.vertical, 6)
}
.buttonStyle(.bordered)
.disabled(state.busy)
}
}
private struct AdaptiveDetailRow<Content: View>: View {
@Environment(\.dynamicTypeSize) private var dynamicTypeSize
let title: String
let content: Content
init(title: String, @ViewBuilder content: () -> Content) {
self.title = title
self.content = content()
}
var body: some View {
Group {
if dynamicTypeSize.isAccessibilitySize {
VStack(alignment: .leading, spacing: 8) {
Text(title)
content
.frame(maxWidth: .infinity, alignment: .leading)
}
} else {
HStack(alignment: .firstTextBaseline, spacing: 12) {
Text(title)
.fixedSize(horizontal: true, vertical: false)
content
.multilineTextAlignment(.trailing)
.frame(maxWidth: .infinity, alignment: .trailing)
}
}
.frame(maxWidth: 760)
.padding(.horizontal, 18)
.padding(.vertical, 18)
}
.frame(maxWidth: .infinity, alignment: .leading)
}
}
@@ -196,17 +350,19 @@ private struct StatusCard: View {
var body: some View {
UCVLCard(title: "连接状态", systemImage: "network.badge.shield.half.filled") {
HStack(spacing: 14) {
HStack(alignment: .top, spacing: 14) {
Circle()
.fill(state.statusIsActive ? Color.green : Color.gray)
.fill(state.statusIsActive ? UCVLColors.success : UCVLColors.muted)
.frame(width: 13, height: 13)
.padding(.top, 6)
VStack(alignment: .leading, spacing: 4) {
Text(state.statusTitle).font(.title3.bold())
Text(state.message.isEmpty ? "点击连接,vpn-ai 将自动选择并验证工作节点" : state.message)
.font(.subheadline)
.foregroundStyle(.secondary)
.foregroundStyle(UCVLColors.muted)
}
Spacer()
.fixedSize(horizontal: false, vertical: true)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
}
@@ -223,17 +379,21 @@ private struct UsageCard: View {
var body: some View {
UCVLCard(title: "本期流量", systemImage: "chart.bar.fill") {
VStack(alignment: .leading, spacing: 12) {
HStack {
AdaptiveDetailRow(title: "已用流量") {
Text(format(subscription.usedBytes))
Spacer()
.fixedSize(horizontal: false, vertical: true)
}
AdaptiveDetailRow(title: "套餐流量") {
Text(subscription.trafficLimitBytes > 0 ? format(subscription.trafficLimitBytes) : "不限流量")
.foregroundStyle(UCVLColors.royal)
.fixedSize(horizontal: false, vertical: true)
}
ProgressView(value: fraction)
.tint(UCVLColors.royal)
Text("套餐:\(subscription.plan) · 设备上限 \(subscription.deviceLimit) 台\(expiryText)")
.font(.footnote)
.foregroundStyle(.secondary)
.foregroundStyle(UCVLColors.muted)
.fixedSize(horizontal: false, vertical: true)
}
}
}
@@ -264,31 +424,38 @@ private struct UCVLCard<Content: View>: View {
Label(title, systemImage: systemImage)
.font(.headline)
.foregroundStyle(UCVLColors.navy)
.fixedSize(horizontal: false, vertical: true)
content
}
.padding(20)
.background(.white, in: RoundedRectangle(cornerRadius: 22, style: .continuous))
.shadow(color: .black.opacity(0.08), radius: 14, y: 7)
.frame(maxWidth: .infinity, alignment: .leading)
.scenicCard()
}
}
private enum UCVLColors {
static let navy = Color(red: 0.02, green: 0.10, blue: 0.26)
static let royal = Color(red: 0.02, green: 0.39, blue: 0.86)
static let sky = Color(red: 0.17, green: 0.73, blue: 0.98)
static let background = LinearGradient(
colors: [navy, Color(red: 0.03, green: 0.25, blue: 0.48)],
startPoint: .topLeading,
endPoint: .bottomTrailing
)
static let navy = Color(red: 10 / 255, green: 34 / 255, blue: 91 / 255)
static let royal = Color(red: 0, green: 80 / 255, blue: 221 / 255)
static let muted = Color(red: 52 / 255, green: 79 / 255, blue: 116 / 255)
static let surface = Color(red: 237 / 255, green: 248 / 255, blue: 1)
static let success = Color(red: 0, green: 113 / 255, blue: 110 / 255)
}
private extension View {
func scenicCard(cornerRadius: CGFloat = 22) -> some View {
self
.background(Color.white.opacity(0.50), in: RoundedRectangle(cornerRadius: cornerRadius, style: .continuous))
.overlay(RoundedRectangle(cornerRadius: cornerRadius, style: .continuous).stroke(Color.white.opacity(0.55)))
.shadow(color: UCVLColors.navy.opacity(0.08), radius: 14, y: 7)
}
func ucvlField() -> some View {
self
.foregroundColor(UCVLColors.navy)
.padding(.horizontal, 14)
.frame(height: 52)
.background(Color.gray.opacity(0.08), in: RoundedRectangle(cornerRadius: 13))
.overlay(RoundedRectangle(cornerRadius: 13).stroke(Color.gray.opacity(0.2)))
.padding(.vertical, 14)
.frame(minHeight: 52)
.background(Color.white.opacity(0.72), in: RoundedRectangle(cornerRadius: 13))
.overlay(RoundedRectangle(cornerRadius: 13).stroke(UCVLColors.navy.opacity(0.16)))
}
}
+94
View File
@@ -0,0 +1,94 @@
import Darwin
import Foundation
enum InternalIPProbe {
static func isReachable(_ address: String) async -> Bool {
guard NetworkAddress.isAuthorizedInternalIPv4(address), !Task.isCancelled else { return false }
let attempt = PingAttempt()
return await withTaskCancellationHandler(operation: {
await withCheckedContinuation { continuation in
DispatchQueue.global(qos: .utility).async {
continuation.resume(returning: attempt.run(address))
}
}
}, onCancel: { attempt.cancel() })
}
}
private final class PingAttempt: @unchecked Sendable {
private let lock = NSLock()
private var cancelled = false
func cancel() {
lock.lock()
cancelled = true
lock.unlock()
}
private var isCancelled: Bool {
lock.lock()
defer { lock.unlock() }
return cancelled
}
func run(_ address: String) -> Bool {
let deadline = DispatchTime.now().uptimeNanoseconds + 1_000_000_000
guard !isCancelled else { return false }
// Darwin datagram ICMP is unprivileged. Never run a shell, query a VPN
// service or replace ICMP with a TCP/HTTP test.
let descriptor = Darwin.socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP)
guard descriptor >= 0 else { return false }
defer { Darwin.close(descriptor) }
let flags = fcntl(descriptor, F_GETFL, 0)
guard flags >= 0, fcntl(descriptor, F_SETFL, flags | O_NONBLOCK) == 0 else { return false }
var destination = sockaddr_in()
destination.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
destination.sin_family = sa_family_t(AF_INET)
guard address.withCString({ inet_pton(AF_INET, $0, &destination.sin_addr) }) == 1 else { return false }
let connected = withUnsafePointer(to: &destination) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
Darwin.connect(descriptor, $0, socklen_t(MemoryLayout<sockaddr_in>.size))
}
}
guard connected == 0, !isCancelled else { return false }
let payload = Array(UUID().uuidString.utf8)
let packet = ICMPEchoPacket.request(identifier: UInt16.random(in: 1...UInt16.max), payload: payload)
let sent = packet.withUnsafeBytes { Darwin.write(descriptor, $0.baseAddress, $0.count) }
guard sent == packet.count else { return false }
var descriptorState = pollfd(fd: descriptor, events: Int16(POLLIN), revents: 0)
while !isCancelled {
let now = DispatchTime.now().uptimeNanoseconds
guard now < deadline else { return false }
let waitMS = Int32(min(50, max(1, (deadline - now) / 1_000_000)))
let ready = Darwin.poll(&descriptorState, 1, waitMS)
if ready < 0 {
if errno == EINTR { continue }
return false
}
guard ready > 0 else { continue }
guard descriptorState.revents & Int16(POLLIN) != 0 else { return false }
var buffer = [UInt8](repeating: 0, count: 4096)
var sender = sockaddr_in()
var senderSize = socklen_t(MemoryLayout<sockaddr_in>.size)
let received = withUnsafeMutablePointer(to: &sender) { senderPointer in
senderPointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { socketPointer in
buffer.withUnsafeMutableBytes {
Darwin.recvfrom(descriptor, $0.baseAddress, $0.count, 0, socketPointer, &senderSize)
}
}
}
guard received > 0 else {
if errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR { continue }
return false
}
if sender.sin_family == sa_family_t(AF_INET),
sender.sin_addr.s_addr == destination.sin_addr.s_addr,
ICMPEchoPacket.isReply(Array(buffer.prefix(received)), payload: payload) {
return !isCancelled && DispatchTime.now().uptimeNanoseconds < deadline
}
}
return false
}
}
+5 -5
View File
@@ -4,7 +4,7 @@ import UIKit
actor PlatformAPI {
static let shared = PlatformAPI()
private let baseURL = URL(string: "https://vpn.toplc.cn/")!
private let baseURL = URL(string: "https://vpn.example.invalid/")!
private let session: URLSession
private let decoder = JSONDecoder()
private let encoder = JSONEncoder()
@@ -16,7 +16,7 @@ actor PlatformAPI {
configuration.waitsForConnectivity = true
configuration.httpAdditionalHeaders = [
"Accept": "application/json",
"User-Agent": "UCVL-Zonghengjia/1.0.2 iOS",
"User-Agent": "UCVL-Zonghengjia/1.0.3 iOS",
]
session = URLSession(configuration: configuration)
}
@@ -27,7 +27,7 @@ actor PlatformAPI {
"password": password,
"device_id": SecureStore.deviceID(),
"device_name": await MainActor.run { UIDevice.current.name },
"app_version": Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0.2",
"app_version": Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0.3",
"platform": "ios",
]
return try await send(
@@ -98,7 +98,7 @@ actor PlatformAPI {
if NetworkAddress.isPublicIPv4(host) { return host }
// 001/002 是后台节点名称。NPM TCP Stream 依靠 11081/11082 等端口
// 分流,不要求每个节点子域名都单独发布 A 记录;解析不到时使用统一入口。
let candidateHosts = host == "vpn.toplc.cn" ? [host] : [host, "vpn.toplc.cn"]
let candidateHosts = host == "vpn.example.invalid" ? [host] : [host, "vpn.example.invalid"]
let resolvers = [
"https://dns.alidns.com/resolve",
"https://doh.pub/resolve",
@@ -131,7 +131,7 @@ actor PlatformAPI {
}
}
}
throw UCVLError.connection("无法取得 NPM 入口 vpn.toplc.cn 的真实公网 IPv4;已拒绝 Fake-IP/内网地址。")
throw UCVLError.connection("无法取得 NPM 入口 vpn.example.invalid 的真实公网 IPv4;已拒绝 Fake-IP/内网地址。")
}
func logout(token: String) async {
+39 -10
View File
@@ -15,7 +15,10 @@ final class VPNController: ObservableObject {
queue: .main
) { [weak self] note in
guard let connection = note.object as? NEVPNConnection else { return }
Task { @MainActor in self?.status = connection.status }
Task { @MainActor in
guard let self, connection === self.manager?.connection else { return }
self.status = connection.status
}
}
}
@@ -38,26 +41,51 @@ final class VPNController: ObservableObject {
}
}
func connect(configJSON: String, resolvedRemoteAddress: String, node: VPNNode, route: RouteMode) async throws {
func connect(
configJSON: String,
resolvedRemoteAddress: String,
node: VPNNode,
route: RouteMode,
internalEndpoint: ProxyTransportEndpoint? = nil,
configContract: Int? = nil,
connectionScope: String? = nil
) async throws {
guard route.id != "direct" else {
disconnect()
try await disconnectAndWait()
return
}
if let internalEndpoint {
guard internalEndpoint.address == resolvedRemoteAddress,
ProxyTransportPolicy.authorizedInternalEndpoint(
endpoint: internalEndpoint, nodeSlug: node.slug, configContract: configContract,
connectionScope: connectionScope, routeMode: route.id, configJSON: configJSON
) != nil else {
throw UCVLError.invalidConfiguration("内部入口与后台授权节点不一致。")
}
} else if !NetworkAddress.isPublicIPv4(resolvedRemoteAddress) {
throw UCVLError.invalidConfiguration("公网入口地址不可用。")
}
let selected = try await loadManager()
let tunnelProtocol = NETunnelProviderProtocol()
tunnelProtocol.providerBundleIdentifier = "cn.toplc.zonghengjia.PacketTunnel"
tunnelProtocol.serverAddress = node.name
tunnelProtocol.disconnectOnSleep = false
tunnelProtocol.includeAllNetworks = false
tunnelProtocol.providerConfiguration = [
var configuration: [String: Any] = [
"configJSON": configJSON,
"resolvedRemoteAddress": resolvedRemoteAddress,
"nodeSlug": node.slug,
"nodeName": node.name,
"routeMode": route.id,
]
if let internalEndpoint {
configuration["internalEndpointJSON"] = try JSONEncoder().encode(internalEndpoint)
configuration["configContract"] = configContract
configuration["connectionScope"] = connectionScope ?? ""
}
tunnelProtocol.providerConfiguration = configuration
selected.localizedDescription = "优创⁺纵横家"
selected.localizedDescription = "纵横家"
selected.protocolConfiguration = tunnelProtocol
selected.isEnabled = true
try await save(selected)
@@ -68,7 +96,7 @@ final class VPNController: ObservableObject {
try selected.connection.startVPNTunnel()
} catch {
activeNodeSlug = nil
throw UCVLError.vpnPermission("系统 VPN 启动失败,请在“设置”中允许优创⁺纵横家添加 VPN 配置。")
throw UCVLError.vpnPermission("系统 VPN 启动失败,请在“设置”中允许纵横家添加 VPN 配置。")
}
do {
try await waitUntilConnected(selected.connection)
@@ -84,15 +112,16 @@ final class VPNController: ObservableObject {
activeNodeSlug = nil
}
func disconnectAndWait(timeout: TimeInterval = 8) async {
func disconnectAndWait(timeout: TimeInterval = 8) async throws {
disconnect()
let deadline = Date().addingTimeInterval(timeout)
while Date() < deadline {
let deadline = ProcessInfo.processInfo.systemUptime + timeout
while ProcessInfo.processInfo.systemUptime < deadline {
let current = manager?.connection.status ?? .disconnected
status = current
if current == .disconnected || current == .invalid { return }
try? await Task.sleep(nanoseconds: 200_000_000)
try await Task.sleep(nanoseconds: 200_000_000)
}
throw UCVLError.invalidConfiguration("系统 VPN 尚未完成断开,已停止切换线路,请稍后重试。")
}
var isConnected: Bool {
+3 -19
View File
@@ -1,21 +1,5 @@
MIT License
# 优创⁺纵横家 iOS 客户端许可说明
Copyright (c) 2026 UCVL (Youchuang Future)
除 `THIRD_PARTY_NOTICES.md` 与 `ThirdParty/` 中另行标明的第三方组件外,本仓库中的优创⁺纵横家 iOS 客户端代码、界面与品牌资源归优创未来所有,仅限公司授权的开发、构建、测试和内部使用。未经书面许可,不得向第三方发布、销售或再许可。
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
第三方组件继续适用其原始许可证;本说明不改变 MIT、MPL-2.0 或数据资源各自的许可义务。
-10
View File
@@ -1,10 +0,0 @@
# 第三方许可及 MIT 范围
顶层及 Windows、后台、iOS 中 MIT 仅适用于 UCVL 有权授权的自有程序代码/文档与原创山水插画。第三方代码、库、数据、工具、商标、公司名称与 Logo 另行适用原权利及许可证,不因聚合仓库的 MIT 而被重新许可;此发布不授予公司商标权或服务访问权。
- Windows:windows/THIRD_PARTY_NOTICES.md 原文保留;windows/licenses/ 包含固定发行 payload 中的 Xray MPL-2.0、Wintun 预编译二进制再分发许可、NSIS 许可。这里不分发这些第三方可执行文件。
- iOS:ios/THIRD_PARTY_NOTICES.md、ios/ThirdParty/libXray-MIT.txt、ios/ThirdParty/Xray-core-MPL-2.0.txt 原文保留。Vendor XCFramework 与未明确来源许可的 Geo 数据未打包。
- Android:保留其既有 GPL-3.0 项目及 LGPL/MIT/lwIP/Wintun 等依赖许可,见 android/README.md 链接;不改为 MIT。
- 后台:requirements.txt 记录依赖。安装的第三方依赖继续遵循各上游版本许可证,不属于公司 MIT 再许可范围。
来源许可不明的用户提供登录图片未纳入此导出。原候选安装包、签名、生产数据库、配置及凭据不在公开源码范围。
+21 -3
View File
@@ -27,10 +27,28 @@ final class PacketTunnelProvider: NEPacketTunnelProvider {
guard let self else { return }
do {
let resolvedRemoteAddress: String
if let providedRemoteAddress, NetworkAddress.isPublicIPv4(providedRemoteAddress) {
let runtimeJSON: String
if let endpointData = providerConfiguration["internalEndpointJSON"] as? Data {
let endpoint = try JSONDecoder().decode(ProxyTransportEndpoint.self, from: endpointData)
guard endpoint.address == providedRemoteAddress,
ProxyTransportPolicy.authorizedInternalEndpoint(
endpoint: endpoint,
nodeSlug: providerConfiguration["nodeSlug"] as? String ?? "",
configContract: providerConfiguration["configContract"] as? Int,
connectionScope: providerConfiguration["connectionScope"] as? String,
routeMode: providerConfiguration["routeMode"] as? String ?? "",
configJSON: rawJSON
) != nil else {
throw UCVLError.invalidConfiguration("内部代理入口与授权配置不一致。")
}
resolvedRemoteAddress = endpoint.address
runtimeJSON = try ProxyTransportPolicy.internalConfigJSON(rawJSON: rawJSON, endpoint: endpoint)
} else if let providedRemoteAddress, NetworkAddress.isPublicIPv4(providedRemoteAddress) {
resolvedRemoteAddress = providedRemoteAddress
runtimeJSON = rawJSON
} else {
resolvedRemoteAddress = try Self.resolveIPv4Address(remoteHost)
runtimeJSON = rawJSON
}
let settings = self.makeNetworkSettings(remoteAddress: resolvedRemoteAddress)
self.setTunnelNetworkSettings(settings) { [weak self] error in
@@ -50,7 +68,7 @@ final class PacketTunnelProvider: NEPacketTunnelProvider {
throw UCVLError.invalidConfiguration("路由规则资源缺失。")
}
let config = try TunnelConfigurationBuilder.makeConfiguration(
rawJSON: rawJSON,
rawJSON: runtimeJSON,
tunnelFileDescriptor: tunnelFD,
assetDirectory: geoIP.deletingLastPathComponent().path,
resolvedRemoteAddress: resolvedRemoteAddress
@@ -142,7 +160,7 @@ final class PacketTunnelProvider: NEPacketTunnelProvider {
var hints = addrinfo()
hints.ai_flags = AI_ADDRCONFIG
hints.ai_family = AF_INET
hints.ai_socktype = Int32(SOCK_STREAM.rawValue)
hints.ai_socktype = SOCK_STREAM
hints.ai_protocol = IPPROTO_TCP
var results: UnsafeMutablePointer<addrinfo>?
let status = host.withCString { getaddrinfo($0, nil, &hints, &results) }
+54 -8
View File
@@ -1,15 +1,61 @@
# 纵横家 iPhone / iPad 1.0.2 源码候选版(开源)
# 纵横家 iPhone / iPad 1.0.3 源码候选版
Swift 主应用与 Apple Packet Tunnel 扩展源码,版本 `1.0.2`,最低 iOS 15。仅为源码快照和静态结构检查;没有可安装 IPA,未执行 Xcode 编译、XCTest、Apple 签名或 iPhone/iPad 真机 VPN 验收。macOS 客户端不在本目录范围。
公司内部 Apple 系统 VPN 客户端源码,版本 `1.0.3`,构建号 `10003`,主应用 Bundle ID 为 `cn.toplc.zonghengjia`,Packet Tunnel 扩展 Bundle ID 为 `cn.toplc.zonghengjia.PacketTunnel`。
## 构建前提
当前没有可安装的 IPA;以下功能指已编写的实现,不代表通过 Xcode 编译或 iPhone 真机验收。1.0.3 增加后台授权内部 IP 的 ICMP Ping 探测、同节点公网回退和本次连接的公网路径保持。平台/本机错误继续停止尝试,401/403 清理失效登录状态。对应 XCTest 已编写,但本机构建环境不能执行。
需要 Mac、Xcode、XcodeGen,以及获授权的 Apple Developer Team、Network Extension 权限和 Provisioning Profile。本快照通过 Git API 创建,脚本执行位不保留;在 Mac 的本目录先运行 `chmod +x Scripts/*.sh`,再运行 `./Scripts/generate-project.sh` 生成工程。`./Scripts/verify-and-archive.sh` 提供测试/归档入口,不代表这里已执行通过。公开示例端点需替换成自己的配置。
登录与主页统一“纵横家”品牌,使用与 Windows 相同的原创山水背景及50%白色卡片;注册提示与链接保持同行自然换行,适配手机键盘和大字体。后台配置节点未提供 `status` 时按“未知”解析,避免有效配置在连接前解码失败;不把未知状态冒充在线。Xcode 的 Swift 语言模式为 `5.0`,它与编译器版本号不同。
Scripts/fetch-libxray.sh 从原固定官方版本 v26.7.28 下载 Apple cgo XCFramework,并核验其源码中固定的 SHA-256;Vendor/ 二进制不在本仓库。下载脚本仅恢复 libXray,不能恢复 Geo 数据,也不提供 Apple 签名材料。
## 源码功能
## 未打包的 Geo 数据
- 使用 `vpn.example.invalid` 平台账号登录与设备授权。
- 展示套餐、流量、当前实际工作节点和代理模式;不向用户提供节点选择。
- 支持 AI 智能代理、全局代理与本地直连。
- 请求后台 `vpn-ai` 自动分配节点;连接失败时排除故障节点并重新分配,最多尝试三次。
- Apple 系统 VPN 建立后使用 OpenAI / ChatGPT HTTPS 入口验证实际出口,未通过就自动恢复本地网络并切换节点。
- 使用 Apple `NEPacketTunnelProvider` 实现 iPhone/iPad 整机代理。
- 断开时由 iOS 自动撤销虚拟路由并恢复原网络。
- 登录令牌通过 iOS Keychain 保存。
- 内嵌官方 libXray `v26.7.28` Apple XCFramework,支持 VLESS Reality。
- 仅当后台 `config_contract=2` 为当前同一节点下发有效的 `tailscale_endpoint`、公开连接范围及兼容 VLESS Reality 配置时,先对授权内部 IP 做限时 ICMP Ping;收到匹配回复后才尝试该内部入口。任意私网地址、其它节点入口或用户自行输入的地址不会因此获得授权。
- 内部 Ping 不通或内部传输失败时,先使用同一节点的原公网配置;一旦选用公网,本次用户发起的连接及其节点重试都保持公网路径,不自动切回内部入口。公网节点连接失败后才继续原有节点切换策略。
- 内部 IP 路径使用系统现有的可达路由;客户端不登录、启动、停止或管理 Tailscale。没有承诺 iOS 上两个 Packet Tunnel 能同时运行,Ping 成功也不代表启动本应用 VPN 后仍然可达;后者仍须完成代理出口验证,失败则按上述规则回退。
- 001/002 等节点的公网配置通过同一 NPM TCP Stream 入口、由端口分流,不要求各节点子域名单独发布 A 记录。需要公网路径时先解析节点域名,解析不到就通过阿里/腾讯 DoH 解析统一入口 `vpn.example.invalid` 的真实公网 IPv4;公网路径仍拒绝 Clash Fake-IP (`198.18.0.0/15`)、私网及 Tailscale 地址。
- 在接管默认路由前把 NPM 入口公网 IP 排除出隧道,并把运行时 VLESS 地址固定为同一 IP;节点端口及 Reality `serverName` 保持不变,避免节点连接被送回 TUN 形成回环。
- 兼容后台 `config_contract=2`:优先使用后台下发的统一 NPM 网关,旧后台未返回该字段时仍按原有域名解析流程连接。
- OpenAI/ChatGPT 出口探测完成后再次核对系统 VPN 状态,避免把“探测成功但隧道已退出”误报为已连接。
Resources/Geo/geoip.dat 与 geosite.dat 未纳入公开导出:旧源码未完整记录数据项目/版本及许可。project.yml 仍保留 Resources/Geo 的资源接入位置,但构建前须自行从可信官方数据源取得对应数据、核验下载校验值与许可,并放入该目录。此仓库不猜测或声称存在已验证的 Geo 下载 URL/hash,不能把 libXray 归档校验值当作 Geo 校验值。
## 在 Mac 上生成工程
公司自有代码适用 LICENSE.md/MIT;ThirdParty/ 和 THIRD_PARTY_NOTICES.md 保留原始第三方许可证与说明。公司商标/Logo 不在 MIT 授权范围。公司公开 API 域名只为源码兼容保留,不授予服务访问权限。
1. 安装 Xcode 及 XcodeGen:`brew install xcodegen`。
2. 若源码包不保留执行位,先运行 `chmod +x Scripts/*.sh`。运行 `./Scripts/fetch-libxray.sh` 下载官方 Apple XCFramework并核对固定 SHA256,再运行 `./Scripts/generate-project.sh`。
3. 在 Xcode 的 Signing & Capabilities 中为主应用和 `PacketTunnel` 目标选择同一个 Apple Developer Team。
4. 为两个 App ID 启用 Network Extensions / Packet Tunnel Provider 权限。
5. 使用真机运行;iOS 模拟器不能完整验证 Packet Tunnel 数据通路。
具备上述条件后,可用 `DEVELOPMENT_TEAM=你的TeamID ./Scripts/verify-and-archive.sh` 执行测试并归档。脚本从 `project.yml` 的唯一数字三段 `MARKETING_VERSION` 生成归档路径;当前为 `build/UCVL-Zonghengjia-1.0.3.xcarchive`。默认模拟器为 `platform=iOS Simulator,name=iPhone 16 Pro`;可通过 `SIMULATOR_DESTINATION='platform=iOS Simulator,id=已安装模拟器的UDID'` 显式指定本机可用设备。
如需同时导出 IPA,再传入 Xcode 生成且适用于所选分发方式的发布选项文件:`EXPORT_OPTIONS_PLIST=/path/ExportOptions.plist DEVELOPMENT_TEAM=你的TeamID ./Scripts/verify-and-archive.sh`。脚本在下载或构建前检查 Team 非空、版本唯一有效、导出文件可读及 `plutil -lint` 通过;任何依赖、测试、归档或导出失败都会停止后续步骤。plist 格式检查不代表签名配置和发布选项已被 Xcode 接受。
仓库配置了 push/PR 源码审计 workflow 和手动 `apple-build.yml`。2026-10-27 通过认证的 iOS 仓库 runner API 返回 `total_count=0`;历史 5 次运行均是已取消的源码审计,没有 Apple 构建运行记录。当前没有可用 Mac runner 的证据,不能把 workflow 文件存在称为 CI 验收通过。Apple workflow 也未配置签名材料导入、IPA 附件上传或 TestFlight/MDM 发布。
## 目前验收范围
- Windows 可运行 `py -3 Scripts/source-audit.py` 检查项目结构、plist、Packet Tunnel entitlement、依赖 SHA256 及源码约束;它不会编译或运行 Swift。
- `py -3 -m unittest discover -s Scripts/tests -p 'test_*.py' -v` 使用已有 Git Bash,在临时目录运行真实归档脚本,以替身命令验证参数、预检与失败停止。它不下载依赖,不执行 Xcode,不生成 IPA,也不证明真实 Apple 工具行为。
- 当前没有已验证可用的 Mac/Xcode 构建机、Apple Developer Team 与包含 Network Extension 权限的 Provisioning Profile,也未完成 iPhone 真机授权和测试;Swift 编译、XCTest、签名、IPA 导出及真机全隧道验收均未完成。
- 源码候选版不是可安装 IPA,不能把 ZIP 改名为 IPA,也不能以“绿色版”方式绕过 iOS 签名。
## 直接安装与发布限制
IPA 必须在 macOS 的 Xcode 中使用苹果开发者证书和包含 Network Extension / Packet Tunnel Provider 权限的 Provisioning Profile 签名。没有证书时可以审查全部源码,但不能生成可安装到普通 iPhone 的正式 IPA。
不通过 App Store 的可行交付方式只有经过苹果签名的 Ad Hoc、组织内 MDM/Custom App,或符合苹果条件的 Enterprise 内部分发;都不是免签名绿色版。获得构建机、Team ID 和授权后,运行 `DEVELOPMENT_TEAM=你的TeamID ./Scripts/verify-and-archive.sh`,再用对应的 ExportOptions 导出 IPA。导出的 IPA 仍须按所选分发方式登记设备或由组织设备管理安装。
## 源码包说明
Git 源码不提交约 300 MB 的 `Vendor/LibXray.xcframework`,避免把第三方构建产物塞进业务仓库。`Scripts/fetch-libxray.sh` 会从 XTLS 官方 v26.7.28 发布页下载 `libxray-apple-cgo.zip`,严格核对下面的 SHA256 后放入正确目录。仓库不包含账号、密码、访问令牌、Apple 证书、Provisioning Profile 或私钥。
## 开源基础
VPN 核心使用 XTLS/libXray `v26.7.28`(MIT)及其对应的 Xray-core。官方二进制 SHA-256 为 `07F7ED7697277930E1C517755855950F594F41435B0DFC5917A66EEA6278AEB9`。
@@ -0,0 +1,12 @@
{
"images" : [
{
"filename" : "landscape-header-v1.png",
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 MiB

+1 -1
View File
@@ -1 +1 @@
Geo 数据未打包。请按 ../../README.md 的资源说明取得并核验自己的合法数据;libXray 下载脚本不恢复 Geo 数据。
Public source export omits Resources/Geo/geoip.dat and Resources/Geo/geosite.dat because their redistribution license was not established. Before building, obtain legally licensed compatible data, verify its origin/license and SHA256, and restore those exact paths. Vendor/LibXray.xcframework must be restored using Scripts/fetch-libxray.sh and its pinned hash; ThirdParty/ contains the retained license texts. Logo/trademark rights are not granted by MIT. Source-audit evidence covers the private complete frozen snapshot only. This export has not been compiled with Xcode, run through XCTest, signed, exported as IPA, or accepted on an Apple device.
+32
View File
@@ -0,0 +1,32 @@
# 蓝青山水头图 v1
## iOS 资源引用
- iOS 资源:`Resources/Assets.xcassets/MountainLandscape.imageset/landscape-header-v1.png`。
- 来源:同仓库 Windows 工程 `../toplc-vpn-windows/assets/landscape-header-v1.png`,下文完整保留其相邻来源说明。
- 2026-10-27 按字节复制原始 PNG,未进行栅格裁切、缩放、重绘或重新导出;SHA256 保持 `E87B91F59038C1E9CCFE616FBC84A0F6CD8D00D6D98E71388C62562017D9DFD8`。
- SwiftUI 仅在屏幕背景与品牌头部使用原生等比填充裁切;所有文字、Logo、输入框、卡片与操作均由原生界面独立绘制。
## 原始来源说明
- 生成日期:2026-09-21。
- 生成方式:内置 `image_gen`,原创装饰背景;没有把用户界面截图作为图像编辑目标。
- 项目文件:`assets/landscape-header-v1.png`。
- 实际尺寸:2172 × 724,PNG,3:1。未进行裁切、缩放或再绘制。
- SHA256:`E87B91F59038C1E9CCFE616FBC84A0F6CD8D00D6D98E71388C62562017D9DFD8`。
- 原始生成文件保留在:`C:/Users/Administrator/.codex/generated_images/01a0c255-9c6f-7c60-8b73-e3d797d0c29c/exec-ee03a49a-7931-433f-8a9c-db4b1e4ee543.png`。
- 人工视觉检查:蓝青山水、雾、水面、小暖金日轮;上部及左右留白,无文字、商标、控件、统计数据或界面边框。官方 Logo、标题、窗口按钮、卡片、文字和图表必须由现有程序独立绘制。
- 用途:窗口标题区域与品牌头图区连续的装饰背景,不是完整软件界面,不替代任何交互控件。
## 完整生成提示词
```text
Use case: stylized-concept
Asset type: standalone decorative panoramic header background for an existing Windows desktop app; NOT an interface mockup.
Primary request: Create an original blue-cyan Chinese shanshui ink-and-watercolor mountain landscape, intended as a subtle continuous background behind a title bar and separate real software controls.
Scene/backdrop: very pale icy blue sky, layered blue-cyan mountain ridges and rocky central peaks, drifting white mist and soft calm water; one small pale warm-gold sun at about 70 percent across, below the top safe strip.
Style/medium: refined contemporary Chinese ink wash and watercolor, airy luminous atmosphere, lightly textured painting, restrained elegant detail.
Composition/framing: very wide panoramic 3:1 aspect ratio, preferably 3072 by 1024 pixels. Keep the entire top 15 percent mostly clear pale sky so independent window buttons can later be drawn there. Keep the left 30 percent mostly open pale mist and sky for an existing official logo and product name added in code. Place the most distinct mountain peaks around the horizontal middle 40–65 percent, with peaks in the middle-to-lower half. Keep the rightmost 25 percent light and sparse for independent typography. Mountain bases and water dissolve softly into pale blue mist toward the bottom edge. Seamless tonal continuity across the entire canvas, no separate title bar or section bands.
Color palette: icy blue-white, powder blue, restrained cyan-teal, muted indigo-blue details and a small pale gold sun; never black-heavy or saturated dark background.
Constraints: output ONLY the landscape illustration. Absolutely NO text, lettering, calligraphy, Chinese characters, signature, watermark, stamps, red seals, logos, compass marks, icons, buttons, graphs, cards, borders, interface panels, people, buildings, labels, or numerals. This is a reusable background asset, not a screenshot and not a full UI.
```
+25 -7
View File
@@ -20,10 +20,19 @@ EXPECTED = [
"Shared/Models.swift",
"Shared/TunnelConfigurationBuilder.swift",
"Shared/NetworkAddress.swift",
"Resources/Geo/geoip.dat",
"Resources/Geo/geosite.dat",
"Tests/TunnelConfigurationBuilderTests.swift",
"Tests/ClientConfigResponseTests.swift",
"Shared/ConnectionAttemptPolicy.swift",
"Tests/ConnectionAttemptPolicyTests.swift",
"Shared/ProxyTransportPolicy.swift",
"Shared/ICMPEchoPacket.swift",
"App/InternalIPProbe.swift",
"Tests/ProxyTransportPolicyTests.swift",
"Tests/ICMPEchoPacketTests.swift",
"Resources/Assets.xcassets/MountainLandscape.imageset/Contents.json",
"Resources/Assets.xcassets/MountainLandscape.imageset/landscape-header-v1.png",
]
@@ -54,6 +63,15 @@ def main() -> int:
and f"版本 `{source_version}`" in readme, "README 与工程版本不一致")
require("cn.toplc.zonghengjia.PacketTunnel" in project, "Packet Tunnel Bundle ID 缺失")
require('iOS: "15.0"' in project, "iOS 最低版本与验收基线不一致")
require("Shared/ProxyTransportPolicy.swift" in project,
"Packet Tunnel 未包含授权入口校验类型")
artwork = ROOT / "Resources/Assets.xcassets/MountainLandscape.imageset/landscape-header-v1.png"
require(hashlib.sha256(artwork.read_bytes()).hexdigest()
== "e87b91f59038c1e9ccfe616fbc84a0f6cd8d00d6d98e71388c62562017d9dfd8",
"原创山水图摘要不匹配")
asset = json.loads(artwork.with_name("Contents.json").read_text(encoding="utf-8"))
require(any(image.get("filename") == artwork.name for image in asset.get("images", [])),
"山水资源索引缺失")
app_state = (ROOT / "App/AppState.swift").read_text(encoding="utf-8")
api = (ROOT / "App/PlatformAPI.swift").read_text(encoding="utf-8")
@@ -90,16 +108,9 @@ def main() -> int:
require(digest == "07f7ed7697277930e1c517755855950f594f41435b0dfc5917a66eea6278aeb9", "libXray 本地归档 SHA256 不匹配")
vendor_result = digest
geo_files = [ROOT / "Resources/Geo/geoip.dat", ROOT / "Resources/Geo/geosite.dat"]
geo_present = [path.is_file() for path in geo_files]
require(all(geo_present) or not any(geo_present), "Geo data must be supplied as a complete pair")
geo_status = "present-not-verified-by-source-audit" if all(geo_present) else "not-packaged"
report = {
"result": "PASS",
"source_version": source_version,
"geo_data_status": geo_status,
"geo_data_required_before_build_and_tunnel": True,
"documentation_version_matches": True,
"scope": "Source audit only; no Xcode compile, signing, IPA export, or iPhone tunnel acceptance",
"automatic_node_selection": True,
@@ -107,6 +118,13 @@ def main() -> int:
"domain_loop_prevention": True,
"gateway_contract": 2,
"legacy_backend_compatible": True,
"authorized_internal_ip_source_implemented": True,
"sticky_public_fallback_source_implemented": True,
"original_landscape_sha256": hashlib.sha256(artwork.read_bytes()).hexdigest(),
"swift_compilation_executed": False,
"xctest_executed": False,
"ipa_generated": False,
"device_installation_verified": False,
"network_extension_entitlement": True,
"libxray_archive_sha256": vendor_result,
}
+180
View File
@@ -0,0 +1,180 @@
"""Offline subprocess checks for archive orchestration, never Xcode acceptance."""
from __future__ import annotations
import os
from pathlib import Path
import plistlib
import shutil
import subprocess
import tempfile
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / "verify-and-archive.sh"
def find_bash() -> str | None:
if os.name == "nt":
candidate = Path("C:/Program Files/Git/bin/bash.exe")
return str(candidate) if candidate.is_file() else None
return shutil.which("bash")
BASH = find_bash()
@unittest.skipUnless(BASH, "Requires bash; Windows checks use existing Git Bash")
class ArchiveScriptTests(unittest.TestCase):
def setUp(self) -> None:
self.temporary = tempfile.TemporaryDirectory(prefix="ucvl-ios-archive-")
self.addCleanup(self.temporary.cleanup)
self.root = Path(self.temporary.name)
(self.root / "Scripts").mkdir()
(self.root / "bin").mkdir()
self.trace = self.root / "trace"
self.trace.mkdir()
shutil.copyfile(SCRIPT, self.root / "Scripts/verify-and-archive.sh")
self.project(' MARKETING_VERSION: "1.0.3"\n')
self.environment = os.environ.copy()
self.environment.update({
"PATH": str(self.root / "bin") + os.pathsep + self.environment.get("PATH", ""),
"DEVELOPMENT_TEAM": "TESTTEAM01",
"ARCHIVE_TEST_TRACE": self.trace.as_posix(),
})
for name in ("EXPORT_OPTIONS_PLIST", "SIMULATOR_DESTINATION", "ARCHIVE_TEST_FAIL_STAGE"):
self.environment.pop(name, None)
for stage, name in (("fetch", "fetch-libxray.sh"), ("generate", "generate-project.sh")):
self.executable(self.root / "Scripts" / name,
'#!/bin/sh\nset -eu\n'
f'printf "%s\\n" {stage} >> "$ARCHIVE_TEST_TRACE/events"\n'
f'[ "${{ARCHIVE_TEST_FAIL_STAGE:-}}" != {stage} ] || exit 37\n')
self.executable(self.root / "bin/xcodebuild", r'''#!/bin/sh
set -eu
action=
for argument do
case "$argument" in test|archive|-exportArchive) action=$argument;; esac
done
[ "$action" != -exportArchive ] || action=export
printf '%s\n' "$action" >> "$ARCHIVE_TEST_TRACE/events"
printf '%s\0' "$@" > "$ARCHIVE_TEST_TRACE/$action.args"
[ "${ARCHIVE_TEST_FAIL_STAGE:-}" != "$action" ] || exit 37
''')
self.executable(self.root / "bin/plutil", r'''#!/bin/sh
set -eu
printf '%s\n' validate_export >> "$ARCHIVE_TEST_TRACE/events"
printf '%s\0' "$@" > "$ARCHIVE_TEST_TRACE/plutil.args"
[ "${ARCHIVE_TEST_FAIL_STAGE:-}" != validate_export ] || exit 37
''')
@staticmethod
def executable(path: Path, text: str) -> None:
path.write_text(text, encoding="utf-8", newline="\n")
path.chmod(0o755)
def project(self, text: str) -> None:
(self.root / "project.yml").write_text("settings:\n base:\n" + text,
encoding="utf-8", newline="\n")
def run_script(self) -> subprocess.CompletedProcess[str]:
return subprocess.run([BASH, "--noprofile", "--norc", "./Scripts/verify-and-archive.sh"],
cwd=self.root, env=self.environment, capture_output=True,
text=True, encoding="utf-8", timeout=15, check=False)
def events(self) -> list[str]:
path = self.trace / "events"
return path.read_text(encoding="utf-8").splitlines() if path.exists() else []
def arguments(self, stage: str) -> list[str]:
raw = (self.trace / (stage + ".args")).read_bytes()
self.assertTrue(raw.endswith(b"\0"))
return [value.decode("utf-8") for value in raw[:-1].split(b"\0")]
def export_options(self) -> str:
path = self.root / "export options.plist"
path.write_bytes(plistlib.dumps({"method": "debugging", "teamID": "TESTTEAM01"}))
return path.as_posix()
def test_archive_uses_project_version_and_default_simulator(self) -> None:
result = self.run_script()
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(self.events(), ["fetch", "generate", "test", "archive"])
self.assertEqual(self.arguments("test"), [
"-project", "UCVLZonghengjia.xcodeproj", "-scheme", "UCVLZonghengjia",
"-destination", "platform=iOS Simulator,name=iPhone 16 Pro",
"DEVELOPMENT_TEAM=TESTTEAM01", "test"])
self.assertEqual(self.arguments("archive"), [
"-project", "UCVLZonghengjia.xcodeproj", "-scheme", "UCVLZonghengjia",
"-configuration", "Release", "-destination", "generic/platform=iOS",
"-archivePath", "build/UCVL-Zonghengjia-1.0.3.xcarchive",
"DEVELOPMENT_TEAM=TESTTEAM01", "archive"])
def test_changed_project_version_changes_archive_path(self) -> None:
self.project(' MARKETING_VERSION: "2.7.19"\n')
result = self.run_script()
self.assertEqual(result.returncode, 0, result.stderr)
arguments = self.arguments("archive")
self.assertEqual(arguments[arguments.index("-archivePath") + 1],
"build/UCVL-Zonghengjia-2.7.19.xcarchive")
def test_explicit_simulator_destination_is_one_argument(self) -> None:
self.environment["SIMULATOR_DESTINATION"] = "platform=iOS Simulator,id=test-simulator-id"
result = self.run_script()
self.assertEqual(result.returncode, 0, result.stderr)
arguments = self.arguments("test")
self.assertEqual(arguments[arguments.index("-destination") + 1],
"platform=iOS Simulator,id=test-simulator-id")
def test_export_validates_first_and_uses_same_versioned_archive(self) -> None:
options = self.export_options()
self.environment["EXPORT_OPTIONS_PLIST"] = options
result = self.run_script()
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(self.events(), ["validate_export", "fetch", "generate", "test", "archive", "export"])
self.assertEqual(self.arguments("plutil"), ["-lint", "--", options])
self.assertEqual(self.arguments("export"), [
"-exportArchive", "-archivePath", "build/UCVL-Zonghengjia-1.0.3.xcarchive",
"-exportPath", "build/export", "-exportOptionsPlist", options])
def test_missing_team_stops_before_external_commands(self) -> None:
self.environment.pop("DEVELOPMENT_TEAM")
result = self.run_script()
self.assertNotEqual(result.returncode, 0)
self.assertEqual(self.events(), [])
def test_missing_export_file_stops_before_fetch_or_build(self) -> None:
self.environment["EXPORT_OPTIONS_PLIST"] = (self.root / "missing.plist").as_posix()
result = self.run_script()
self.assertNotEqual(result.returncode, 0)
self.assertEqual(self.events(), [])
def test_export_lint_failure_stops_before_fetch_or_build(self) -> None:
self.environment["EXPORT_OPTIONS_PLIST"] = self.export_options()
self.environment["ARCHIVE_TEST_FAIL_STAGE"] = "validate_export"
result = self.run_script()
self.assertNotEqual(result.returncode, 0)
self.assertEqual(self.events(), ["validate_export"])
def test_invalid_or_ambiguous_project_version_stops_before_fetch(self) -> None:
for text in (' SWIFT_VERSION: "5.10"\n',
' MARKETING_VERSION: "../../escape"\n',
' MARKETING_VERSION: "1.0.3"\n MARKETING_VERSION: "1.0.4"\n'):
with self.subTest(project=text):
self.project(text)
result = self.run_script()
self.assertNotEqual(result.returncode, 0)
self.assertEqual(self.events(), [])
def test_each_failed_stage_prevents_all_later_stages(self) -> None:
stages = ["fetch", "generate", "test", "archive", "export"]
self.environment["EXPORT_OPTIONS_PLIST"] = self.export_options()
for index, stage in enumerate(stages):
with self.subTest(stage=stage):
(self.trace / "events").unlink(missing_ok=True)
self.environment["ARCHIVE_TEST_FAIL_STAGE"] = stage
result = self.run_script()
self.assertEqual(result.returncode, 37, result.stderr)
self.assertEqual(self.events(), ["validate_export"] + stages[:index + 1])
if __name__ == "__main__":
unittest.main()
+83
View File
@@ -0,0 +1,83 @@
"""Exercise the source-audit boundary; these are not Swift runtime tests."""
from contextlib import redirect_stdout
import importlib.util
import io
import json
from pathlib import Path
import plistlib
import shutil
import tempfile
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / "source-audit.py"
spec = importlib.util.spec_from_file_location("ios_source_audit", SCRIPT)
audit = importlib.util.module_from_spec(spec)
spec.loader.exec_module(audit)
SOURCE = SCRIPT.parent.parent
class SourceAuditTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory()
self.addCleanup(self.temporary.cleanup)
self.root = Path(self.temporary.name) / "ios"
shutil.copytree(SOURCE, self.root,
ignore=shutil.ignore_patterns(".git", "Vendor", "BuildArtifacts", "__pycache__"))
self.original = audit.ROOT
audit.ROOT = self.root
self.addCleanup(setattr, audit, "ROOT", self.original)
def run_audit(self):
output = io.StringIO()
with redirect_stdout(output):
result = audit.main()
self.assertEqual(result, 0)
return json.loads(output.getvalue())
def test_valid_source_reports_only_source_acceptance(self):
report = self.run_audit()
self.assertEqual(report["source_version"], "1.0.3")
self.assertFalse(report["swift_compilation_executed"])
self.assertFalse(report["xctest_executed"])
self.assertFalse(report["ipa_generated"])
self.assertFalse(report["device_installation_verified"])
def test_missing_shared_policy_stops_audit(self):
(self.root / "Shared/ProxyTransportPolicy.swift").unlink()
with self.assertRaisesRegex(RuntimeError, "ProxyTransportPolicy"):
self.run_audit()
def test_unbundled_artwork_stops_audit(self):
path = self.root / "Resources/Assets.xcassets/MountainLandscape.imageset/Contents.json"
path.write_text('{"images":[]}', encoding="utf-8")
with self.assertRaisesRegex(RuntimeError, "山水资源"):
self.run_audit()
def test_modified_artwork_stops_audit(self):
path = self.root / "Resources/Assets.xcassets/MountainLandscape.imageset/landscape-header-v1.png"
path.write_bytes(b"replaced artwork")
with self.assertRaisesRegex(RuntimeError, "山水图"):
self.run_audit()
def test_missing_extension_entitlement_stops_audit(self):
path = self.root / "PacketTunnel/PacketTunnel.entitlements"
path.write_bytes(plistlib.dumps({}))
with self.assertRaisesRegex(RuntimeError, "权限缺失"):
self.run_audit()
def test_version_mismatch_stops_audit(self):
path = self.root / "README.md"
path.write_text(path.read_text(encoding="utf-8").replace("1.0.3", "1.0.2"), encoding="utf-8")
with self.assertRaisesRegex(RuntimeError, "版本不一致"):
self.run_audit()
def test_modified_vendor_archive_stops_audit(self):
path = self.root / "Vendor/libxray-apple-cgo-v26.7.28.zip"
path.parent.mkdir()
path.write_bytes(b"untrusted binary")
with self.assertRaisesRegex(RuntimeError, "libXray"):
self.run_audit()
if __name__ == "__main__":
unittest.main()
+34 -7
View File
@@ -5,12 +5,43 @@ test -n "${DEVELOPMENT_TEAM:-}" || {
echo "请设置 DEVELOPMENT_TEAM(Apple Developer Team ID)。" >&2
exit 1
}
source_version=$(awk '
$1 == "MARKETING_VERSION:" {
value = $2
sub(/^"/, "", value)
sub(/"$/, "", value)
if (value !~ /^[0-9]+\.[0-9]+\.[0-9]+$/ || seen++) exit 1
version = value
}
END {
if (seen != 1 || version == "") exit 1
print version
}
' project.yml) || {
echo "project.yml 必须包含唯一的数字三段 MARKETING_VERSION。" >&2
exit 1
}
archive_path="build/UCVL-Zonghengjia-${source_version}.xcarchive"
simulator_destination=${SIMULATOR_DESTINATION:-'platform=iOS Simulator,name=iPhone 16 Pro'}
if [ -n "${EXPORT_OPTIONS_PLIST:-}" ]; then
test -f "$EXPORT_OPTIONS_PLIST" && test -r "$EXPORT_OPTIONS_PLIST" || {
echo "EXPORT_OPTIONS_PLIST 必须指定可读的发布选项文件。" >&2
exit 1
}
plutil -lint -- "$EXPORT_OPTIONS_PLIST" >/dev/null || {
echo "EXPORT_OPTIONS_PLIST 不是有效的 plist 文件。" >&2
exit 1
}
fi
./Scripts/fetch-libxray.sh
./Scripts/generate-project.sh
xcodebuild \
-project UCVLZonghengjia.xcodeproj \
-scheme UCVLZonghengjia \
-destination 'platform=iOS Simulator,name=iPhone 16 Pro' \
-destination "$simulator_destination" \
DEVELOPMENT_TEAM="$DEVELOPMENT_TEAM" \
test
xcodebuild \
@@ -18,18 +49,14 @@ xcodebuild \
-scheme UCVLZonghengjia \
-configuration Release \
-destination 'generic/platform=iOS' \
-archivePath build/UCVL-Zonghengjia-1.0.0.xcarchive \
-archivePath "$archive_path" \
DEVELOPMENT_TEAM="$DEVELOPMENT_TEAM" \
archive
if [ -n "${EXPORT_OPTIONS_PLIST:-}" ]; then
test -f "$EXPORT_OPTIONS_PLIST" || {
echo "EXPORT_OPTIONS_PLIST 指定的文件不存在。" >&2
exit 1
}
xcodebuild \
-exportArchive \
-archivePath build/UCVL-Zonghengjia-1.0.0.xcarchive \
-archivePath "$archive_path" \
-exportPath build/export \
-exportOptionsPlist "$EXPORT_OPTIONS_PLIST"
fi
+38
View File
@@ -0,0 +1,38 @@
import Foundation
// A nonce in the payload binds a reply to this request. The kernel may rewrite
// the identifier on an unprivileged datagram ICMP socket.
enum ICMPEchoPacket {
static func checksum(_ bytes: [UInt8]) -> UInt16 {
var sum: UInt32 = 0
var index = 0
while index + 1 < bytes.count {
sum += (UInt32(bytes[index]) << 8) | UInt32(bytes[index + 1])
index += 2
}
if index < bytes.count { sum += UInt32(bytes[index]) << 8 }
while sum >> 16 != 0 { sum = (sum & 0xffff) + (sum >> 16) }
return ~UInt16(sum)
}
static func request(identifier: UInt16, payload: [UInt8]) -> [UInt8] {
var bytes: [UInt8] = [8, 0, 0, 0, UInt8(identifier >> 8), UInt8(identifier & 0xff), 0, 1]
bytes += payload
let value = checksum(bytes)
bytes[2] = UInt8(value >> 8)
bytes[3] = UInt8(value & 0xff)
return bytes
}
static func isReply(_ received: [UInt8], payload: [UInt8]) -> Bool {
var offset = 0
if let first = received.first, first >> 4 == 4 {
offset = Int(first & 0x0f) * 4
guard offset >= 20 else { return false }
}
guard received.count == offset + 8 + payload.count else { return false }
let reply = Array(received.dropFirst(offset))
return reply[0] == 0 && reply[1] == 0 && reply[6] == 0 && reply[7] == 1
&& Array(reply.dropFirst(8)) == payload && checksum(reply) == 0
}
}
+37
View File
@@ -104,6 +104,18 @@ struct VPNNode: Decodable, Identifiable, Hashable, Sendable {
let region: String
let status: String
enum CodingKeys: String, CodingKey { case slug, name, region, status }
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
slug = try container.decode(String.self, forKey: .slug)
name = try container.decode(String.self, forKey: .name)
region = try container.decode(String.self, forKey: .region)
// Config responses omit the profile-only node status. Absence is not
// evidence of offline/online state and must not break a valid config.
status = try container.decodeIfPresent(String.self, forKey: .status) ?? "unknown"
}
var id: String { slug }
var displayName: String { region.isEmpty ? name : "\(name) · \(region)" }
}
@@ -121,6 +133,8 @@ struct ClientConfigResponse: Decodable, Sendable {
let configContract: Int?
let gateway: Gateway?
let tailscaleEndpoint: ProxyTransportEndpoint?
let connectionScope: String?
let node: VPNNode
let routeMode: String
let config: [String: JSONValue]
@@ -128,11 +142,34 @@ struct ClientConfigResponse: Decodable, Sendable {
enum CodingKeys: String, CodingKey {
case configContract = "config_contract"
case gateway
case tailscaleEndpoint = "tailscale_endpoint"
case connectionScope = "connection_scope"
case node
case routeMode = "route_mode"
case config
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
configContract = try container.decodeIfPresent(Int.self, forKey: .configContract)
gateway = try container.decodeIfPresent(Gateway.self, forKey: .gateway)
node = try container.decode(VPNNode.self, forKey: .node)
routeMode = try container.decode(String.self, forKey: .routeMode)
config = try container.decode([String: JSONValue].self, forKey: .config)
// Optional transport hints never make a valid public configuration fail.
// A malformed scope also disables the hint: it is not a legacy absence.
let scopeIsNull = (try? container.decodeNil(forKey: .connectionScope)) ?? true
let scopePresent = container.contains(.connectionScope) && !scopeIsNull
let decodedScope = try? container.decode(String.self, forKey: .connectionScope)
connectionScope = decodedScope
if scopePresent && decodedScope == nil {
tailscaleEndpoint = nil
} else {
tailscaleEndpoint = try? container.decode(ProxyTransportEndpoint.self, forKey: .tailscaleEndpoint)
}
}
func configJSONString() throws -> String {
let encoder = JSONEncoder()
encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]
+14
View File
@@ -1,6 +1,20 @@
import Foundation
enum NetworkAddress {
static func isAuthorizedInternalIPv4(_ value: String) -> Bool {
let parts = value.split(separator: ".", omittingEmptySubsequences: false)
guard parts.count == 4 else { return false }
let octets = parts.compactMap { UInt8($0) }
guard octets.count == 4,
octets.map({ String($0) }).joined(separator: ".") == value,
octets[0] == 100,
(64...127).contains(octets[1])
else { return false }
return value != "100.64.0.0"
&& value != "100.127.255.255"
&& value != "100.100.100.100"
}
static func isPublicIPv4(_ value: String) -> Bool {
let parts = value.split(separator: ".", omittingEmptySubsequences: false)
guard parts.count == 4,
+124
View File
@@ -0,0 +1,124 @@
import Foundation
struct ProxyTransportEndpoint: Codable, Equatable, Sendable {
let contract: Int
let nodeSlug: String
let address: String
let port: Int
enum CodingKeys: String, CodingKey {
case contract
case nodeSlug = "node_slug"
case address
case port
}
}
// One value belongs to one explicit user connection, including its node retries.
// Once public ingress is chosen, automatic recovery has no promotion operation.
struct ProxyTransportSession {
private(set) var domainOnly = false
mutating func commitPublicFallback() {
domainOnly = true
}
}
enum ProxyTransportPolicy {
static func authorizedInternalEndpoint(response: ClientConfigResponse) -> ProxyTransportEndpoint? {
guard let rawJSON = try? response.configJSONString() else { return nil }
return authorizedInternalEndpoint(
endpoint: response.tailscaleEndpoint,
nodeSlug: response.node.slug,
configContract: response.configContract,
connectionScope: response.connectionScope,
routeMode: response.routeMode,
configJSON: rawJSON
)
}
// The Packet Tunnel repeats the same gates over its saved original config.
static func authorizedInternalEndpoint(
endpoint: ProxyTransportEndpoint?,
nodeSlug: String,
configContract: Int?,
connectionScope: String?,
routeMode: String,
configJSON: String
) -> ProxyTransportEndpoint? {
guard let endpoint,
configContract == 2,
connectionScope == nil || connectionScope == "" || connectionScope == "public",
routeMode == "smart" || routeMode == "global",
!nodeSlug.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
endpoint.nodeSlug == nodeSlug,
isValidEndpoint(endpoint),
let root = configurationRoot(configJSON),
proxyIndex(in: root) != nil
else { return nil }
return endpoint
}
// The caller keeps rawJSON for same-node public fallback. Nothing else in
// the authorization, Reality identity or routing is reconstructed here.
static func internalConfigJSON(rawJSON: String, endpoint: ProxyTransportEndpoint) throws -> String {
guard isValidEndpoint(endpoint),
var root = configurationRoot(rawJSON),
let index = proxyIndex(in: root),
var outbounds = root["outbounds"] as? [[String: Any]],
var settings = outbounds[index]["settings"] as? [String: Any],
var servers = settings["vnext"] as? [[String: Any]]
else {
throw UCVLError.invalidConfiguration("授权内部入口与节点代理配置不匹配。")
}
servers[0]["address"] = endpoint.address
servers[0]["port"] = endpoint.port
settings["vnext"] = servers
outbounds[index]["settings"] = settings
root["outbounds"] = outbounds
let output = try JSONSerialization.data(withJSONObject: root, options: [.sortedKeys])
return String(decoding: output, as: UTF8.self)
}
private static func isValidEndpoint(_ endpoint: ProxyTransportEndpoint) -> Bool {
endpoint.contract == 1
&& !endpoint.nodeSlug.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
&& NetworkAddress.isAuthorizedInternalIPv4(endpoint.address)
&& (1...65535).contains(endpoint.port)
}
private static func configurationRoot(_ rawJSON: String) -> [String: Any]? {
guard let data = rawJSON.data(using: .utf8),
let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
root["ucvl_private_auxiliary"] == nil,
root["ucvl_tailnet_transport"] == nil
else { return nil }
return root
}
private static func proxyIndex(in root: [String: Any]) -> Int? {
guard let outbounds = root["outbounds"] as? [[String: Any]] else { return nil }
let matches = outbounds.indices.filter { outbounds[$0]["tag"] as? String == "proxy" }
guard matches.count == 1, let index = matches.first else { return nil }
let proxy = outbounds[index]
guard proxy["protocol"] as? String == "vless",
let settings = proxy["settings"] as? [String: Any],
let servers = settings["vnext"] as? [[String: Any]], servers.count == 1,
let users = servers[0]["users"] as? [[String: Any]], !users.isEmpty,
users.allSatisfy({ nonemptyString($0["id"]) }),
let stream = proxy["streamSettings"] as? [String: Any],
stream["security"] as? String == "reality",
let network = stream["network"] as? String,
network == "tcp" || network == "raw",
let reality = stream["realitySettings"] as? [String: Any],
nonemptyString(reality["serverName"]),
nonemptyString(reality["password"]) || nonemptyString(reality["publicKey"])
else { return nil }
return index
}
private static func nonemptyString(_ value: Any?) -> Bool {
guard let value = value as? String else { return false }
return !value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
}
+47 -3
View File
@@ -2,13 +2,20 @@ import XCTest
@testable import UCVLZonghengjia
final class ClientConfigResponseTests: XCTestCase {
func testActualBackendConfigNodeDoesNotRequireProfileOnlyStatus() throws {
let data = Data(#"{"config_contract":2,"node":{"slug":"n1","name":"VPN001","region":"东京"},"route_mode":"smart","config":{}}"#.utf8)
let response = try JSONDecoder().decode(ClientConfigResponse.self, from: data)
XCTAssertEqual(response.node.slug, "n1")
XCTAssertEqual(response.node.status, "unknown")
}
func testDecodesVersionedGatewayContract() throws {
let data = Data(#"{"config_contract":2,"gateway":{"host":"vpn.toplc.cn","ipv4":"192.0.2.1"},"node":{"slug":"n1","name":"VPN001","region":"东京","status":"online"},"route_mode":"smart","config":{}}"#.utf8)
let data = Data(#"{"config_contract":2,"gateway":{"host":"vpn.example.invalid","ipv4":"203.0.113.17"},"node":{"slug":"n1","name":"VPN001","region":"东京","status":"online"},"route_mode":"smart","config":{}}"#.utf8)
let response = try JSONDecoder().decode(ClientConfigResponse.self, from: data)
XCTAssertEqual(response.configContract, 2)
XCTAssertEqual(response.gateway?.host, "vpn.toplc.cn")
XCTAssertEqual(response.gateway?.ipv4, "192.0.2.1")
XCTAssertEqual(response.gateway?.host, "vpn.example.invalid")
XCTAssertEqual(response.gateway?.ipv4, "203.0.113.17")
}
func testOldBackendPayloadRemainsCompatible() throws {
@@ -17,5 +24,42 @@ final class ClientConfigResponseTests: XCTestCase {
XCTAssertNil(response.configContract)
XCTAssertNil(response.gateway)
XCTAssertNil(response.tailscaleEndpoint)
XCTAssertNil(response.connectionScope)
}
func testDecodesOptionalInternalEndpointWithoutChangingPublicConfiguration() throws {
let data = Data(#"{"config_contract":2,"connection_scope":"public","tailscale_endpoint":{"contract":1,"node_slug":"n1","address":"100.70.1.2","port":12001},"node":{"slug":"n1","name":"VPN001","region":"东京","status":"online"},"route_mode":"smart","config":{"public":"preserved"}}"#.utf8)
let response = try JSONDecoder().decode(ClientConfigResponse.self, from: data)
XCTAssertEqual(response.connectionScope, "public")
XCTAssertEqual(response.tailscaleEndpoint?.nodeSlug, "n1")
XCTAssertEqual(response.tailscaleEndpoint?.address, "100.70.1.2")
XCTAssertEqual(response.tailscaleEndpoint?.port, 12001)
XCTAssertEqual(response.config["public"], .string("preserved"))
}
func testMalformedOptionalEndpointDoesNotBreakPublicPayload() throws {
for optionalValue in ["null", "true", "[]", "{}", #"{"contract":1,"node_slug":"n1","address":"100.70.1.2","port":"12001"}"#] {
let data = Data("""
{"tailscale_endpoint":\(optionalValue),"node":{"slug":"n1","name":"VPN001","region":"东京","status":"online"},"route_mode":"smart","config":{"public":"preserved"}}
""".utf8)
let response = try JSONDecoder().decode(ClientConfigResponse.self, from: data)
XCTAssertNil(response.tailscaleEndpoint)
XCTAssertEqual(response.config["public"], .string("preserved"))
}
}
func testMalformedOptionalScopeDisablesInternalEndpointAndPreservesPublicPayload() throws {
for scope in ["true", "1", "[]", "{}"] {
let data = Data("""
{"config_contract":2,"connection_scope":\(scope),"tailscale_endpoint":{"contract":1,"node_slug":"n1","address":"100.70.1.2","port":12001},"node":{"slug":"n1","name":"VPN001","region":"东京","status":"online"},"route_mode":"smart","config":{"public":"preserved"}}
""".utf8)
let response = try JSONDecoder().decode(ClientConfigResponse.self, from: data)
XCTAssertNil(response.tailscaleEndpoint)
XCTAssertEqual(response.config["public"], .string("preserved"))
}
}
}
+39
View File
@@ -0,0 +1,39 @@
import XCTest
@testable import UCVLZonghengjia
final class ICMPEchoPacketTests: XCTestCase {
func testEchoRequestHasValidChecksumAndPayload() {
let payload: [UInt8] = [1, 2, 3, 4, 5]
let request = ICMPEchoPacket.request(identifier: 0x1234, payload: payload)
XCTAssertEqual(Array(request.prefix(2)), [8, 0])
XCTAssertEqual(Array(request[4..<8]), [0x12, 0x34, 0, 1])
XCTAssertEqual(Array(request.dropFirst(8)), payload)
XCTAssertEqual(ICMPEchoPacket.checksum(request), 0)
}
func testAcceptsOnlyMatchingEchoReply() {
let payload: [UInt8] = [11, 12, 13]
var reply = ICMPEchoPacket.request(identifier: 7, payload: payload)
reply[0] = 0
reply[2] = 0
reply[3] = 0
let checksum = ICMPEchoPacket.checksum(reply)
reply[2] = UInt8(checksum >> 8)
reply[3] = UInt8(checksum & 0xff)
XCTAssertTrue(ICMPEchoPacket.isReply(reply, payload: payload))
XCTAssertFalse(ICMPEchoPacket.isReply(reply, payload: [99]))
XCTAssertFalse(ICMPEchoPacket.isReply(Array(reply.dropLast()), payload: payload))
reply[1] = 1
XCTAssertFalse(ICMPEchoPacket.isReply(reply, payload: payload))
}
func testRejectsRequestAndCorruptReply() {
let payload: [UInt8] = [11, 12]
let request = ICMPEchoPacket.request(identifier: 7, payload: payload)
XCTAssertFalse(ICMPEchoPacket.isReply(request, payload: payload))
var corrupt = request
corrupt[0] = 0
XCTAssertFalse(ICMPEchoPacket.isReply(corrupt, payload: payload))
XCTAssertFalse(ICMPEchoPacket.isReply([], payload: []))
}
}
+4 -4
View File
@@ -3,15 +3,15 @@ import XCTest
final class NetworkAddressTests: XCTestCase {
func testAcceptsPublicIPv4() {
XCTAssertTrue(NetworkAddress.isPublicIPv4("192.0.2.1"))
XCTAssertTrue(NetworkAddress.isPublicIPv4("203.0.113.17"))
XCTAssertTrue(NetworkAddress.isPublicIPv4("8.216.53.107"))
}
func testRejectsPrivateTailscaleAndFakeIPv4() {
XCTAssertFalse(NetworkAddress.isPublicIPv4("127.0.0.1"))
XCTAssertFalse(NetworkAddress.isPublicIPv4("192.168.50.1"))
XCTAssertFalse(NetworkAddress.isPublicIPv4("100.64.0.2"))
XCTAssertFalse(NetworkAddress.isPublicIPv4("192.168.8.1"))
XCTAssertFalse(NetworkAddress.isPublicIPv4("100.99.142.38"))
XCTAssertFalse(NetworkAddress.isPublicIPv4("198.18.0.119"))
XCTAssertFalse(NetworkAddress.isPublicIPv4("001.vpn.toplc.cn"))
XCTAssertFalse(NetworkAddress.isPublicIPv4("001.vpn.example.invalid"))
}
}
+196
View File
@@ -0,0 +1,196 @@
import XCTest
@testable import UCVLZonghengjia
final class ProxyTransportPolicyTests: XCTestCase {
private let fixture = #"""
{
"config_contract":2,"connection_scope":"public",
"tailscale_endpoint":{"contract":1,"node_slug":"fixture-node","address":"100.70.1.2","port":12001},
"node":{"slug":"fixture-node","name":"Fixture","region":"","status":"online"},
"route_mode":"smart",
"config":{
"log":{"loglevel":"warning"},
"outbounds":[
{"tag":"proxy","protocol":"vless","settings":{"vnext":[{"address":"node.example.test","port":443,"users":[{"id":"11111111-2222-3333-4444-555555555555","flow":"xtls-rprx-vision","encryption":"none"}]}]},"streamSettings":{"network":"tcp","security":"reality","realitySettings":{"serverName":"server.example.test","publicKey":"fixture-public-key","shortId":"abcd"}}},
{"tag":"direct","protocol":"freedom"}
],
"routing":{"rules":[{"type":"field","domain":["example.test"],"outboundTag":"proxy"}]}
}
}
"""#
private func response(_ change: (inout [String: Any]) -> Void = { _ in }) throws -> ClientConfigResponse {
var root = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(fixture.utf8)) as? [String: Any])
change(&root)
return try JSONDecoder().decode(ClientConfigResponse.self, from: JSONSerialization.data(withJSONObject: root))
}
private func changingEndpoint(_ change: (inout [String: Any]) -> Void) throws -> ClientConfigResponse {
try response { root in
var endpoint = root["tailscale_endpoint"] as! [String: Any]
change(&endpoint)
root["tailscale_endpoint"] = endpoint
}
}
private func changingProxy(_ change: (inout [String: Any]) -> Void) throws -> ClientConfigResponse {
try response { root in
var config = root["config"] as! [String: Any]
var outbounds = config["outbounds"] as! [[String: Any]]
change(&outbounds[0])
config["outbounds"] = outbounds
root["config"] = config
}
}
func testAcceptsOnlyCanonicalAuthorizedInternalIPv4() {
for address in ["100.64.0.1", "100.70.1.2", "100.127.255.254"] {
XCTAssertTrue(NetworkAddress.isAuthorizedInternalIPv4(address), address)
XCTAssertFalse(NetworkAddress.isPublicIPv4(address), address)
}
for address in ["100.63.255.255", "100.128.0.0", "100.64.0.0", "100.127.255.255", "100.100.100.100", "100.070.1.2", "+100.70.1.2", " 100.70.1.2", "100.70.1.2 ", "100.70.1", "100.70.1.256", "192.168.1.2", "198.18.1.2", "8.8.8.8", "node.example.test"] {
XCTAssertFalse(NetworkAddress.isAuthorizedInternalIPv4(address), address)
}
}
func testAuthorizedEndpointAcceptsCompatiblePublicScopesAndRouteModes() throws {
for scope in [nil, "", "public"] as [String?] {
for route in ["smart", "global"] {
let value = try response { root in
root["connection_scope"] = scope
root["route_mode"] = route
}
XCTAssertEqual(ProxyTransportPolicy.authorizedInternalEndpoint(response: value)?.address, "100.70.1.2")
}
}
}
func testMissingInvalidOrUnauthorizedMetadataNeverCreatesAnInternalCandidate() throws {
let changes: [(inout [String: Any]) -> Void] = [
{ $0.removeValue(forKey: "tailscale_endpoint") },
{ $0["tailscale_endpoint"] = NSNull() },
{ $0["config_contract"] = 3 },
{ $0.removeValue(forKey: "config_contract") },
{ $0["connection_scope"] = "private_auxiliary" },
{ $0["connection_scope"] = true },
{ $0["route_mode"] = "direct" },
{ $0["route_mode"] = "unsupported" }
]
for change in changes {
XCTAssertNil(ProxyTransportPolicy.authorizedInternalEndpoint(response: try response(change)))
}
for port in [0, -1, 65536] {
XCTAssertNil(ProxyTransportPolicy.authorizedInternalEndpoint(response: try changingEndpoint { $0["port"] = port }))
}
for address in ["8.8.8.8", "192.168.1.2", "198.18.1.2", "100.100.100.100", "100.070.1.2"] {
XCTAssertNil(ProxyTransportPolicy.authorizedInternalEndpoint(response: try changingEndpoint { $0["address"] = address }))
}
XCTAssertNil(ProxyTransportPolicy.authorizedInternalEndpoint(response: try changingEndpoint { $0["node_slug"] = "other-node" }))
XCTAssertNil(ProxyTransportPolicy.authorizedInternalEndpoint(response: try changingEndpoint { $0["contract"] = 2 }))
XCTAssertNotNil(ProxyTransportPolicy.authorizedInternalEndpoint(response: try changingEndpoint { $0["port"] = 1 }))
XCTAssertNotNil(ProxyTransportPolicy.authorizedInternalEndpoint(response: try changingEndpoint { $0["port"] = 65535 }))
}
func testUnsupportedOrAmbiguousProxyIdentityIsRejected() throws {
let changes: [(inout [String: Any]) -> Void] = [
{ $0["protocol"] = "socks" },
{ $0["streamSettings"] = ["network":"tcp", "security":"tls"] },
{ $0["settings"] = ["vnext":[]] },
{ $0["settings"] = ["vnext":[["address":"node.example.test", "port":443, "users":[]]]] },
{ $0["settings"] = ["vnext":[["address":"node.example.test", "port":443, "users":[["id":" "]]]]] },
{ $0["streamSettings"] = ["network":"ws", "security":"reality", "realitySettings":["serverName":"server.example.test", "publicKey":"fixture-public-key"]] },
{ $0["streamSettings"] = ["network":"tcp", "security":"reality", "realitySettings":["serverName":" ", "publicKey":"fixture-public-key"]] },
{ $0["streamSettings"] = ["network":"tcp", "security":"reality", "realitySettings":["serverName":"server.example.test", "publicKey":" "]] }
]
for change in changes {
XCTAssertNil(ProxyTransportPolicy.authorizedInternalEndpoint(response: try changingProxy(change)))
}
let duplicate = try response { root in
var config = root["config"] as! [String: Any]
var outbounds = config["outbounds"] as! [[String: Any]]
outbounds.append(outbounds[0])
config["outbounds"] = outbounds
root["config"] = config
}
XCTAssertNil(ProxyTransportPolicy.authorizedInternalEndpoint(response: duplicate))
let multipleServers = try changingProxy { proxy in
var settings = proxy["settings"] as! [String: Any]
var servers = settings["vnext"] as! [[String: Any]]
servers.append(servers[0])
settings["vnext"] = servers
proxy["settings"] = settings
}
XCTAssertNil(ProxyTransportPolicy.authorizedInternalEndpoint(response: multipleServers))
}
func testRawNetworkAndRealityPasswordRemainCompatible() throws {
let value = try changingProxy { proxy in
var reality = ["serverName":"server.example.test"]
reality["password"] = "fixture-public-key"
proxy["streamSettings"] = ["network":"raw", "security":"reality", "realitySettings":reality]
}
XCTAssertNotNil(ProxyTransportPolicy.authorizedInternalEndpoint(response: value))
}
func testPrivateOrPreviouslyPreparedConfigurationsDoNotCreateAnInternalCandidate() throws {
for marker in ["ucvl_private_auxiliary", "ucvl_tailnet_transport"] {
let value = try response { root in
var config = root["config"] as! [String: Any]
config[marker] = ["address":"100.70.1.2"]
root["config"] = config
}
XCTAssertNil(ProxyTransportPolicy.authorizedInternalEndpoint(response: value))
}
}
func testRuntimeReplacementChangesOnlyAddressAndPort() throws {
let value = try response()
let endpoint = try XCTUnwrap(ProxyTransportPolicy.authorizedInternalEndpoint(response: value))
let original = try value.configJSONString()
let runtime = try ProxyTransportPolicy.internalConfigJSON(rawJSON: original, endpoint: endpoint)
var output = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(runtime.utf8)) as? [String: Any])
var outbounds = try XCTUnwrap(output["outbounds"] as? [[String: Any]])
var settings = try XCTUnwrap(outbounds[0]["settings"] as? [String: Any])
var servers = try XCTUnwrap(settings["vnext"] as? [[String: Any]])
XCTAssertEqual(servers[0]["address"] as? String, "100.70.1.2")
XCTAssertEqual(servers[0]["port"] as? Int, 12001)
servers[0]["address"] = "node.example.test"
servers[0]["port"] = 443
settings["vnext"] = servers
outbounds[0]["settings"] = settings
output["outbounds"] = outbounds
let expected = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(original.utf8)) as? [String: Any])
XCTAssertTrue(NSDictionary(dictionary: output).isEqual(to: expected))
XCTAssertEqual(try value.configJSONString(), original)
}
func testRuntimeReplacementRejectsInvalidEndpointOrProxy() throws {
let value = try response()
let endpoint = try XCTUnwrap(value.tailscaleEndpoint)
XCTAssertThrowsError(try ProxyTransportPolicy.internalConfigJSON(rawJSON: "{}", endpoint: endpoint))
XCTAssertThrowsError(try ProxyTransportPolicy.internalConfigJSON(rawJSON: "invalid", endpoint: endpoint))
let publicAddress = ProxyTransportEndpoint(contract: 1, nodeSlug: "fixture-node", address: "8.8.8.8", port: 12001)
XCTAssertThrowsError(try ProxyTransportPolicy.internalConfigJSON(rawJSON: try value.configJSONString(), endpoint: publicAddress))
}
func testProviderValidationRepeatsNodeContractAndConfigurationGates() throws {
let value = try response()
let endpoint = try XCTUnwrap(value.tailscaleEndpoint)
let config = try value.configJSONString()
XCTAssertEqual(ProxyTransportPolicy.authorizedInternalEndpoint(endpoint: endpoint, nodeSlug: "fixture-node", configContract: 2, connectionScope: "public", routeMode: "smart", configJSON: config), endpoint)
XCTAssertNil(ProxyTransportPolicy.authorizedInternalEndpoint(endpoint: endpoint, nodeSlug: "other-node", configContract: 2, connectionScope: "public", routeMode: "smart", configJSON: config))
XCTAssertNil(ProxyTransportPolicy.authorizedInternalEndpoint(endpoint: endpoint, nodeSlug: "fixture-node", configContract: 3, connectionScope: "public", routeMode: "smart", configJSON: config))
XCTAssertNil(ProxyTransportPolicy.authorizedInternalEndpoint(endpoint: endpoint, nodeSlug: "fixture-node", configContract: 2, connectionScope: "private_auxiliary", routeMode: "smart", configJSON: config))
XCTAssertNil(ProxyTransportPolicy.authorizedInternalEndpoint(endpoint: endpoint, nodeSlug: "fixture-node", configContract: 2, connectionScope: "public", routeMode: "smart", configJSON: "{}"))
}
func testPublicFallbackRemainsLockedForTheEntireSession() {
var session = ProxyTransportSession()
XCTAssertFalse(session.domainOnly)
session.commitPublicFallback()
XCTAssertTrue(session.domainOnly)
session.commitPublicFallback()
XCTAssertTrue(session.domainOnly)
XCTAssertFalse(ProxyTransportSession().domainOnly)
}
}
@@ -8,7 +8,7 @@ final class TunnelConfigurationBuilderTests: XCTestCase {
"log":{"loglevel":"warning"},
"inbounds":[{"tag":"socks-in","protocol":"socks","port":10808}],
"outbounds":[
{"tag":"proxy","protocol":"vless","settings":{"vnext":[{"address":"001.vpn.toplc.cn","port":11081,"users":[{"id":"11111111-2222-3333-4444-555555555555"}]}]},"streamSettings":{"security":"reality","realitySettings":{"serverName":"www.microsoft.com"}}},
{"tag":"proxy","protocol":"vless","settings":{"vnext":[{"address":"001.vpn.example.invalid","port":11081,"users":[{"id":"11111111-2222-3333-4444-555555555555"}]}]},"streamSettings":{"security":"reality","realitySettings":{"serverName":"www.microsoft.com"}}},
{"tag":"direct","protocol":"freedom"}
],
"routing":{"rules":[]}
@@ -19,7 +19,7 @@ final class TunnelConfigurationBuilderTests: XCTestCase {
rawJSON: raw,
tunnelFileDescriptor: 42,
assetDirectory: "/app/assets",
resolvedRemoteAddress: "192.0.2.1"
resolvedRemoteAddress: "203.0.113.17"
)
let data = try XCTUnwrap(output.data(using: .utf8))
let root = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any])
@@ -35,10 +35,10 @@ final class TunnelConfigurationBuilderTests: XCTestCase {
XCTAssertEqual(outbounds.first?["protocol"] as? String, "vless")
let settings = try XCTUnwrap(outbounds.first?["settings"] as? [String: Any])
let vnext = try XCTUnwrap(settings["vnext"] as? [[String: Any]])
XCTAssertEqual(vnext.first?["address"] as? String, "192.0.2.1")
XCTAssertEqual(vnext.first?["address"] as? String, "203.0.113.17")
let stream = try XCTUnwrap(outbounds.first?["streamSettings"] as? [String: Any])
let reality = try XCTUnwrap(stream["realitySettings"] as? [String: Any])
XCTAssertEqual(reality["serverName"] as? String, "www.microsoft.com")
XCTAssertEqual(TunnelConfigurationBuilder.remoteAddress(from: raw), "001.vpn.toplc.cn")
XCTAssertEqual(TunnelConfigurationBuilder.remoteAddress(from: raw), "001.vpn.example.invalid")
}
}
@@ -0,0 +1,46 @@
# iOS 1.0.3 同步更新计划
> **For agentic workers:** Use executing-plans, test-driven-development and verification-before-completion. User already opted out of repeated design and publication approval questions.
**Goal:** 更新现有 iPhone/iPad 源码,沿用已发布 Windows 0.3.1 的授权内部 IP 优先、公网回落保持与山水半透明视觉;如缺 Apple 构建/签名条件,明确交付源码候选,绝不冒称 IPA 或安装完成。
**Architecture:** 保留 SwiftUI + NetworkExtension + 官方固定 libXray。后台可选契约提供同节点内部入口;严格验证后最多1秒原生 ICMP,出口仍需现有 HTTPS 验证。显式连接拥有一次公网回落状态,完整断开前不启动备用;不管理 Tailscale,不承诺同机两个 Packet Tunnel 并存。
**Tech Stack:** Swift5语言模式 / iOS15 / XcodeGen / XCTest / Python源审计。
## Global constraints
- 不改 Windows 已发布内容、后台生产、路由器、现用网络、Sony 夜猫或电视。
- 仅使用认证后台返回且同节点匹配的100.64.0.0/10入口;不硬编码节点;不把Ping当身份验证。
- 只重写代理地址与端口;Reality/UUID/路由等原始授权保持。公网解析延迟到公网分支。
- 统一品牌“纵横家”,复用有来源的原创山水图;不把许可不明人物图公开。
- 真机、签名与Xcode缺失时保持 IPA/正式稳定发行/生产验收=false,静态审计不冒充Swift行为测试。
## Tasks
- [ ] 建立可选端点容错解析、严格100/10和同身份替换、sticky策略的XCTest;增加可执行静态审计负向夹具并保留RED。
- [ ] 实现受限入口策略、原生ICMP、同节点公网回退;Provider重复验证并仅排除所选/32;清理超时停止;过滤无关VPN通知。
- [ ] 同步山水背景、50%卡片、注册行对齐、品牌与响应式iPhone/iPad布局;不伪造速度数据。
- [ ] 版本1.0.3/build10003,改归档脚本版本路径与可配置Simulator;更新真实验收范围。
- [ ] 跑源审计及其负向夹具、全部可执行本地检查;XCTest/Xcode只能在实际可用构建机上执行。独立审查重要问题。
- [ ] 冻结精确源码与审计/未验收声明,推送新的专属分支和公开清洁源码分支,逐blob与附件下载核对;源码候选只标prerelease。
## Review focus
- 缺失/null/格式错误的可选入口不得破坏旧公网配置。
- 节点、契约、scope、端口、单一VLESS Reality身份不匹配不得触发Ping或改写。
- Ping/内部出口失败后的同节点公网回退,随后其它节点不得再次提升内部。
- 清理超时、取消、本机权限、401/403不能继续切换或误报连接成功。
- iPhone窄屏/键盘/大字体保持可操作;同机Tailscale被系统替换后不循环重试内网。
## Capability evidence
2026-10-27 authenticated read-only company Git audit: iOS repo11 private; Actions runner inventory empty, all5 historical runs cancelled. Windows host has no Swift/Xcode. No configured signing/export/TestFlight/MDM publication path. This is an external installable-release blocker, not a request to reconfirm publication authority.
## Execution ledger before source freeze
- User confirmed no Mac/build/signing environment. Continue source update and scoped source synchronization; no installable or stable iOS release can be claimed.
- Added native bounded ICMP and nonce/source/checksum reply matching; optional endpoint authorization and same-node sticky fallback. Actual Swift/XCTest execution is unavailable. XCTest sources were written first but their RED/GREEN runtime cycle remains unexecuted; no static grep is counted as their replacement.
- Source audit and all16 executable Python tests passed (9 real shell subprocess archive tests,7 source-audit boundary tests). Old archive script produced expected failures before its change; source version mismatch was also observed and corrected. No Xcode, simulator, IPA, real plutil, download or device activity is represented by these tests.
- Independent review corrected two important baseline issues: config node.status absent in real backend payload now decodes to unknown, with exact-shape XCTest; Swift language setting changed from invalid5.10 to5.0. UI review corrected inherited foreground on primary buttons. Swift compilation remains unverified.
- Source-only candidate identity1.0.3/build10003. Public export must omit unlicensed Geo binaries as in previous publication, preserve third-party licenses/trademark exceptions and provide restore notes. Do not call public resource omission a complete binary build.
+7 -5
View File
@@ -7,9 +7,9 @@ options:
groupSortPosition: top
settings:
base:
SWIFT_VERSION: "5.10"
MARKETING_VERSION: "1.0.2"
CURRENT_PROJECT_VERSION: "10002"
SWIFT_VERSION: "5.0"
MARKETING_VERSION: "1.0.3"
CURRENT_PROJECT_VERSION: "10003"
CODE_SIGN_STYLE: Automatic
DEVELOPMENT_TEAM: ""
CLANG_ENABLE_MODULES: YES
@@ -31,7 +31,8 @@ targets:
info:
path: App/Info.plist
properties:
CFBundleDisplayName: 优创⁺纵横家
CFBundleDisplayName: 纵横家
NSLocalNetworkUsageDescription: 用于检测后台授权的内部代理地址是否可达,以优先使用内部网络。
CFBundleShortVersionString: $(MARKETING_VERSION)
CFBundleVersion: $(CURRENT_PROJECT_VERSION)
UILaunchScreen:
@@ -65,6 +66,7 @@ targets:
- path: Shared/TunnelConfigurationBuilder.swift
- path: Shared/Models.swift
- path: Shared/NetworkAddress.swift
- path: Shared/ProxyTransportPolicy.swift
resources:
- path: Resources/Geo
entitlements:
@@ -72,7 +74,7 @@ targets:
info:
path: PacketTunnel/Info.plist
properties:
CFBundleDisplayName: 优创⁺纵横家网络扩展
CFBundleDisplayName: 纵横家网络扩展
CFBundleShortVersionString: $(MARKETING_VERSION)
CFBundleVersion: $(CURRENT_PROJECT_VERSION)
NSExtension:
+1
View File
@@ -27,6 +27,7 @@ internal sealed class ProfileEnvelope
internal sealed class Profile
{
[JsonPropertyName("can_view_node_traffic")] public bool CanViewNodeTraffic { get; init; }
[JsonPropertyName("usage_history_ranges")] public Dictionary<string, UsageHistorySeries>? UsageHistoryRanges { get; init; }
[JsonPropertyName("usage_history")] public List<DailyUsage> UsageHistory { get; init; } = [];
[JsonPropertyName("username")] public string Username { get; init; } = "";
+138
View File
@@ -0,0 +1,138 @@
using System.Text.Json;
namespace UCVL.VPNPlus;
internal static class ChartFreshnessSelfTest
{
internal static int Run()
{
var checks = new Dictionary<string, bool>();
string? error = null;
try
{
var at = new DateTimeOffset(2026, 10, 22, 12, 0, 0, TimeSpan.FromHours(8));
var now = at;
var timeline = new TrafficChartTimeline(() => now);
var minute = TimeSpan.FromMinutes(1);
checks["empty_history_has_no_fabricated_zero_sample"] = timeline.PointCount == 0
&& timeline.Visible(minute).Length == 0 && !timeline.HasFreshSample && timeline.LastSampleAt is null;
checks["injected_clock_controls_initial_axis"] = timeline.End == at;
checks["measured_zero_is_valid_not_missing"] = timeline.Add(0, 0) && timeline.HasFreshSample
&& timeline.PointCount == 1 && timeline.Visible(minute)[0].Up == 0;
now = at.AddSeconds(5);
checks["valid_sample_preserves_fractional_rates"] = timeline.Add(123.5, 987.25)
&& timeline.Visible(minute)[^1] is { Up: 123.5, Down: 987.25 };
var beforeGap = timeline.Visible(minute);
var previousSegment = beforeGap[^1].Segment;
now = at.AddSeconds(10);
timeline.MarkUnavailable();
checks["missing_reader_advances_axis_without_zero_point"] = timeline.End == now
&& timeline.PointCount == 2 && !timeline.HasFreshSample && timeline.LastSampleAt == at.AddSeconds(5);
now = at.AddSeconds(15);
timeline.MarkUnavailable();
timeline.AdvanceClock();
checks["repeated_missing_ticks_do_not_add_or_change_values"] = timeline.PointCount == 2
&& timeline.Visible(minute).SequenceEqual(beforeGap);
now = at.AddSeconds(20);
checks["recovery_adds_only_real_sample"] = timeline.Add(12, 34) && timeline.PointCount == 3 && timeline.HasFreshSample;
var recovered = timeline.Visible(minute);
checks["recovery_starts_new_curve_segment"] = recovered[^1].Segment != previousSegment;
checks["recovery_does_not_rewrite_prior_samples_or_accumulate_gap"] = recovered.Take(2).SequenceEqual(beforeGap)
&& recovered[^1].Up == 12 && recovered[^1].Down == 34;
now = at.AddSeconds(25);
checks["subsequent_good_samples_share_recovered_segment"] = timeline.Add(56, 78)
&& timeline.Visible(minute)[^1].Segment == recovered[^1].Segment;
var latest = timeline.LastSampleAt;
var latestCount = timeline.PointCount;
checks["duplicate_timestamp_cannot_double_count_display_sample"] = !timeline.Add(900, 800, now)
&& timeline.PointCount == latestCount && timeline.LastSampleAt == latest;
checks["late_sample_cannot_move_axis_or_replace_current_sample"] = !timeline.Add(900, 800, at.AddSeconds(1))
&& timeline.PointCount == latestCount && timeline.End == now && timeline.HasFreshSample;
timeline.AdvanceClock(at.AddMinutes(-1));
checks["backwards_clock_does_not_rewind_axis"] = timeline.End == now;
var unannounced = new TrafficChartTimeline(() => now);
unannounced.Add(1, 2, at);
unannounced.Add(3, 4, at.AddSeconds(5));
var segment = unannounced.Visible(minute)[^1].Segment;
now = at.AddSeconds(20);
unannounced.AdvanceClock();
checks["fifteen_second_age_boundary_is_still_fresh"] = unannounced.HasFreshSample;
now = at.AddSeconds(21);
unannounced.AdvanceClock();
checks["silent_reader_stalls_become_unavailable_after_deadline"] = !unannounced.HasFreshSample
&& unannounced.PointCount == 2 && unannounced.End == now;
now = at.AddSeconds(25);
unannounced.Add(5, 6);
checks["silent_gap_recovery_does_not_bridge_line"] = unannounced.HasFreshSample
&& unannounced.Visible(minute)[^1].Segment != segment;
var noTick = new TrafficChartTimeline(() => now);
noTick.Add(7, 8, at);
noTick.Add(9, 10, at.AddSeconds(20));
checks["large_timestamp_gap_breaks_line_even_without_missing_tick"] = noTick.Visible(minute)
.Select(point => point.Segment).Distinct().Count() == 2;
foreach (var (label, up, down) in new[]
{
("negative_up", -1d, 1d), ("negative_down", 1d, -1d),
("nan_up", double.NaN, 1d), ("nan_down", 1d, double.NaN),
("positive_infinity", double.PositiveInfinity, 1d), ("negative_infinity", 1d, double.NegativeInfinity)
})
{
var invalid = new TrafficChartTimeline(() => now);
invalid.Add(11, 22, at);
now = at.AddSeconds(5);
checks[label + "_is_missing_not_fake_zero"] = !invalid.Add(up, down) && invalid.PointCount == 1
&& !invalid.HasFreshSample && invalid.Visible(minute)[0] is { Up: 11, Down: 22 };
now = at.AddSeconds(10);
invalid.Add(33, 44);
checks[label + "_recovery_breaks_curve"] = invalid.Visible(minute)[0].Segment
!= invalid.Visible(minute)[1].Segment;
}
var history = new TrafficChartTimeline(() => now);
for (var i = 0; i <= 720; i++) history.Add(i, i * 2, at.AddSeconds(i * 5));
checks["actual_five_second_samples_keep_one_hour_inclusive"] = history.PointCount == 721;
checks["period_selection_only_filters_actual_samples"] = history.Visible(minute).Length == 13
&& history.Visible(TimeSpan.FromMinutes(5)).Length == 61
&& history.Visible(TimeSpan.FromMinutes(15)).Length == 181
&& history.Visible(TimeSpan.FromMinutes(60)).Length == 721 && history.PointCount == 721;
now = at.AddHours(1).AddSeconds(5);
history.AdvanceClock();
checks["retention_prunes_while_sampling_is_stopped"] = history.PointCount == 720
&& history.Visible(TimeSpan.FromMinutes(60))[0].Time == at.AddSeconds(5);
now = at.AddHours(1).AddMinutes(2);
history.MarkUnavailable();
checks["selected_window_expires_without_new_samples"] = history.Visible(minute).Length == 0 && !history.HasFreshSample;
now = at.AddHours(2).AddSeconds(1);
history.AdvanceClock();
checks["whole_history_expires_without_synthetic_points"] = history.PointCount == 0
&& history.Visible(TimeSpan.FromHours(1)).Length == 0 && history.LastSampleAt == at.AddHours(1);
checks["axis_continues_after_history_is_empty"] = history.End == now;
history.Add(99, 88);
checks["post_expiry_recovery_is_one_actual_point"] = history.PointCount == 1 && history.HasFreshSample
&& history.Visible(minute)[0] is { Up: 99, Down: 88 };
history.Reset();
checks["reset_discards_old_sample_segment_and_freshness"] = history.PointCount == 0 && !history.HasFreshSample
&& history.LastSampleAt is null && history.End == now;
history.Add(0, 0);
checks["zero_after_reset_is_real_sample_in_initial_segment"] = history.PointCount == 1
&& history.Visible(minute)[0].Segment == 0 && history.HasFreshSample;
var bounded = new TrafficChartTimeline(() => at);
for (var i = 0; i < 4000; i++) bounded.Add(i, i, at.AddMilliseconds(i));
checks["high_frequency_history_remains_bounded"] = bounded.PointCount == 3600;
}
catch (Exception exception) { error = exception.ToString(); }
var passed = error is null && checks.Count >= 35 && checks.Values.All(value => value);
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "chart-freshness-self-test.json"),
JsonSerializer.Serialize(new
{
passed, checks, error,
scope = "pure presentation-history clock and missing-sample policy; not a real-window, network-throughput or cumulative-accounting acceptance",
network_modified = false, installed_client_modified = false, credentials_loaded = false,
untested = new[] { "physical multi-monitor DPI transitions", "live resize frame latency", "production tray/occlusion pixel stability" }
}, new JsonSerializerOptions { WriteIndented = true }));
return passed ? 0 : 29;
}
}
+1 -1
View File
@@ -96,7 +96,7 @@ internal static class ConnectionSelfTest
result.Probes.Add(await ProbeAsync(client, "OpenAI API", "https://api.openai.com/v1/models", timeout.Token));
result.Probes.Add(await ProbeAsync(client, "Codex endpoint (unauthenticated)", "https://chatgpt.com/backend-api/codex/models", timeout.Token));
result.Probes.Add(await ProbeAsync(client, "ChatGPT", "https://chatgpt.com/", timeout.Token));
result.Probes.Add(await ProbeAsync(client, "管理平台", "https://vpn.toplc.cn/health/", timeout.Token));
result.Probes.Add(await ProbeAsync(client, "管理平台", "https://vpn.example.invalid/health/", timeout.Token));
// A browser following an explicit HTTP proxy is not evidence that
// native clients use the global TUN. Exercise both paths separately.
+21
View File
@@ -98,6 +98,27 @@ internal sealed partial class MainForm
checks["whole_content_composition_disabled"] = !_content.ComposeChildren;
checks["metric_dirty_refresh_clears_previous_digits"] = CheckMetricRefreshPaint();
foreach (var check in CheckTailnetTrafficUi()) checks.Add(check.Key, check.Value);
var monitorSize = ClientSize;
var monitorAccounting = (_sessionUp, _sessionDown, _trafficChart.PointCount);
SetNodeTrafficPermission(true);
SetTailnetTrafficVisibility(true);
LayoutDashboard();
Application.DoEvents();
using (var monitorFont = Brand.Font(7.1f))
{
var monitorTextHeight = TextRenderer.MeasureText("VPN002 上传", monitorFont).Height;
var rows = NodeTrafficPanel.TextLayout(_nodeTrafficPanel.ClientSize, DeviceDpi, monitorTextHeight);
checks["monitor_two_native_dpi_text_rows_fit"] = rows.Rows.All(row => row.Height >= monitorTextHeight)
&& !rows.Rows[0].IntersectsWith(rows.Rows[1]);
}
checks["monitor_stays_below_speed_without_resizing_window"] = ClientSize == monitorSize
&& _nodeTrafficPanel.Top > _dailyCard.Bottom && _nodeTrafficPanel.Bottom < _footer.Top
&& !_dashboardScrollBar.Visible && _dashboardBody.Top == 0;
checks["monitor_does_not_overflow_other_controls"] = DashboardControlsFit();
checks["monitor_does_not_change_personal_proxy_accounting"] = monitorAccounting == (_sessionUp, _sessionDown, _trafficChart.PointCount);
SetNodeTrafficPermission(false);
SetTailnetTrafficVisibility(false);
checks["monitor_revoked_hides_and_stops_timer"] = !_nodeTrafficPanel.Visible && !_nodeTrafficTimer.Enabled;
ShowLogin();
checks["hidden_dashboard_does_not_consume_login_wheel"] = !Wheel(_loginText, -120);
RequestExit();
+12 -8
View File
@@ -3,19 +3,19 @@ namespace UCVL.VPNPlus;
internal readonly record struct DashboardGeometry(
Rectangle WelcomeLabel, Rectangle AccountLabel, Rectangle IdentityBadge,
Rectangle LogoutButton, Rectangle StatusCard, Rectangle NodeCard, Rectangle ModeCard,
Rectangle[] Metrics, Rectangle TrafficCard, Rectangle TailnetTrafficCard, Rectangle DailyCard, Rectangle Footer,
Rectangle[] Metrics, Rectangle TrafficCard, Rectangle TailnetTrafficCard, Rectangle DailyCard, Rectangle ServerTrafficCard, Rectangle Footer,
int ContentHeight, bool Compact, float VerticalScale);
// Logical pixels converted once, independent of WinForms autoscaling.
internal static class DashboardLayout
{
internal static DashboardGeometry Calculate(Size viewport, int dpi, bool showTailnet = false)
internal static DashboardGeometry Calculate(Size viewport, int dpi, bool showTailnet = false, bool showServerTraffic = false)
{
var scale = Math.Max(1f, dpi / 96f);
int S(int n) => (int)Math.Round(n * scale);
// Tailnet is a subdivision of the existing speed area, not another
// dashboard row. Fit the complete canvas even on a small/high-DPI screen.
var verticalScale = Math.Min(1f, Math.Max(1, viewport.Height) / (614f * scale));
var verticalScale = Math.Min(1f, Math.Max(1, viewport.Height) / ((showServerTraffic ? 718f : 614f) * scale));
int Y(int n) => Math.Max(1, (int)Math.Floor(n * scale * verticalScale));
var margin = S(20);
var gap = Y(10);
@@ -43,23 +43,26 @@ internal static class DashboardLayout
speed ? Math.Min(Y(82), parent.Height - Y(44)) : Y(82));
// Relative to their matching chart card: totals together; speeds together.
Rectangle[] metrics = [Metric(daily, 0, false), Metric(traffic, 0, true), Metric(traffic, 1, true), Metric(daily, 1, false)];
var footer = new Rectangle(margin, daily.Bottom + gap, width, Y(76));
var serverTraffic = showServerTraffic ? new Rectangle(margin, daily.Bottom + gap, width, Y(94)) : Rectangle.Empty;
var footer = new Rectangle(margin, (showServerTraffic ? serverTraffic.Bottom : daily.Bottom) + gap, width, Y(76));
return new(welcome, account, identity, logout, status, node, mode, metrics, traffic,
tailnet, daily, footer, Math.Min(viewport.Height, footer.Bottom + Y(12)), compact, verticalScale);
tailnet, daily, serverTraffic, footer, Math.Min(viewport.Height, footer.Bottom + Y(12)), compact, verticalScale);
}
internal static bool SelfTest()
{
foreach (var dpi in new[] { 96, 120, 144, 168, 192, 240, 288 })
foreach (var dpi in new[] { 96, 120, 144, 168, 192, 240, 288, 336, 384 })
foreach (var width in new[] { 600, 620, 739, 760, 780, 900, 1100, 1600 })
foreach (var height in new[] { 350, 418, 560, 720 })
foreach (var showTailnet in new[] { false, true })
foreach (var showServers in new[] { false, true })
{
var viewport = new Size(width * dpi / 96, height * dpi / 96);
var p = Calculate(viewport, dpi, showTailnet);
var p = Calculate(viewport, dpi, showTailnet, showServers);
Rectangle[] cards = showTailnet
? [p.StatusCard, p.NodeCard, p.ModeCard, p.TrafficCard, p.TailnetTrafficCard, p.DailyCard, p.Footer]
: [p.StatusCard, p.NodeCard, p.ModeCard, p.TrafficCard, p.DailyCard, p.Footer];
if (showServers) cards = [..cards, p.ServerTrafficCard];
if (cards.Any(c => c.Left < 0 || c.Right > viewport.Width || c.Bottom > p.ContentHeight || c.Width <= 0)) return false;
for (var i = 0; i < cards.Length; i++)
for (var j = i + 1; j < cards.Length; j++)
@@ -70,10 +73,11 @@ internal static class DashboardLayout
if (p.Metrics[i].Right > (i == 0 || i == 3 ? p.DailyCard.Width : p.TrafficCard.Width)) return false;
if (!showTailnet && p.TailnetTrafficCard != Rectangle.Empty) return false;
if (p.ContentHeight > viewport.Height || p.Footer.Bottom > viewport.Height) return false;
var baseline = Calculate(viewport, dpi, false);
var baseline = Calculate(viewport, dpi, false, showServers);
if (p.DailyCard != baseline.DailyCard || p.Footer != baseline.Footer || p.ContentHeight != baseline.ContentHeight) return false;
if (showTailnet && (p.TailnetTrafficCard.Top <= p.TrafficCard.Bottom
|| p.DailyCard.Top != p.TrafficCard.Top || p.DailyCard.Bottom != p.TailnetTrafficCard.Bottom)) return false;
if (showServers && (p.ServerTrafficCard.Top <= p.DailyCard.Bottom || p.ServerTrafficCard.Bottom >= p.Footer.Top)) return false;
}
return true;
}
@@ -49,8 +49,15 @@ internal sealed partial class MainForm
&& _dailyCard.Controls.OfType<TrafficChart>().Single() == _trafficChart
&& _dailyChart.Parent is null && !_dailyChart.Visible;
UpdateConnectedTransportPresentation(true);
DisplayTraffic(1024, 2048, "互斥入口样本");
DisplayTailnetTraffic(1024, 2048, "互斥入口样本");
checks["tailnet_sample_is_not_duplicated_as_public_speed"] = _uploadMetric.ValueText == "—"
&& _downloadMetric.ValueText == "—" && _uploadMetric.Hint == "未使用公网入口"
&& _tailnetUploadMetric.ValueText == "1" && _tailnetDownloadMetric.ValueText == "2";
checks["actual_tailnet_transport_shows_section"] = _currentNodeUsesTailnet && _tailnetTrafficVisible;
UpdateConnectedTransportPresentation(false);
DisplayTraffic(3072, 4096, "公网样本");
checks["public_sample_uses_only_public_speed_section"] = _uploadMetric.ValueText == "3" && _downloadMetric.ValueText == "4";
checks["public_transport_hides_section"] = !_currentNodeUsesTailnet && !_tailnetTrafficVisible;
using var curve = new TrafficChart();
var end = DateTimeOffset.Now;
+1 -1
View File
@@ -22,7 +22,7 @@ internal static class GitReleasePolicySelfTest
var release = JsonNode.Parse(JsonSerializer.Serialize(new {
tag_name="windows-v0.2.16", draft=false, prerelease=false, body="fixture",
assets=new[] {
new { name=Name, size=300000, browser_download_url="http://172.16.0.21:3000/untrusted.exe" },
new { name=Name, size=300000, browser_download_url="http://192.0.2.21:3000/untrusted.exe" },
new { name=Name+".sha256", size=120, browser_download_url="https://untrusted.invalid/sha" },
},
}))!;
+1 -1
View File
@@ -105,7 +105,7 @@ internal static class InstallationIntegration
!string.Equals(InstallationTransaction.Root((string)Decode(registered)), target, StringComparison.OrdinalIgnoreCase)))
throw new IOException("安装目录与当前登记不一致,未覆盖其它安装。");
object[] next = [Path.Combine(target, "VPNPlus.exe"), target, "优创⁺纵横家", Path.Combine(target, "VPNPlus.exe"),
version, "优创未来(UCVL)", "https://vpn.toplc.cn/", "\"" + Path.Combine(target, "Uninstall.exe") + "\"", 1, 1];
version, "优创未来(UCVL)", "https://vpn.example.invalid/", "\"" + Path.Combine(target, "Uninstall.exe") + "\"", 1, 1];
var values = Names.Select((name, i) => new Registration(i,
Encode(next[i], i < 8 ? RegistryValueKind.String : RegistryValueKind.DWord),
Read(hive, Key(target, isolated, KeyIndex(i)), name))).ToList();
+2 -2
View File
@@ -18,7 +18,7 @@ internal static class LearningSelfTest
checks["http_auth_status_is_not_failure"] = Parse("HTTP 401 / 403 / 429 direct learn.example.com:443") is null;
checks["proxy_failures_not_direct"] = Parse(line.Replace("proxy/freedom", "proxy/vless/outbound")) is null;
checks["private_failures_not_collected"] = Parse(line.Replace("learn.example.com", "192.168.50.111")) is null;
checks["company_not_collected"] = Parse(line.Replace("learn.example.com", "vpn.toplc.cn")) is null;
checks["company_not_collected"] = Parse(line.Replace("learn.example.com", "vpn.example.invalid")) is null;
checks["source_not_misidentified"] = Parse("tcp:127.0.0.1:777 " + line)?.Target == "learn.example.com";
checks["oversized_line_rejected"] = Parse(new string('x', 8193) + line) is null;
const string attempt = "[Info] [1753901314] app/dispatcher: taking detour [direct] for [tcp:tls-gap.example.com:443]";
@@ -71,7 +71,7 @@ internal static class LearningSelfTest
checks["private_precedes_learned"] = JsonNode.Parse(verified)!["routing"]!["rules"]![0]!["ip"]![0]!.GetValue<string>() == "geoip:private";
checks["expiry_restores_direct"] = !LearningPolicy.Merge(verified, new() { Contract=1, Revision=new string('b',64) }).Contains("learn.example.com");
checks["network_change_restores_direct"] = !LearningPolicy.DirectFirst(verified).Contains("learn.example.com");
checks["unsafe_manifest_rejected"] = Throws(() => LearningPolicy.Merge(direct, Rules("vpn.toplc.cn")));
checks["unsafe_manifest_rejected"] = Throws(() => LearningPolicy.Merge(direct, Rules("vpn.example.invalid")));
checks["invalid_manifest_contract_rejected"] = Throws(() => LearningPolicy.Merge(direct, new() { Contract=99, Revision=new string('a',64) }));
var runtime = JsonNode.Parse(TunConfigBuilder.Build(direct, "Ethernet", true, includeTun:false, routingApiPort:18090, learningProbePort:18091))!;
checks["info_in_memory_access_disabled"] = runtime["log"]!["loglevel"]!.GetValue<string>() == "info" && runtime["log"]!["access"]!.GetValue<string>() == "none";
+13 -7
View File
@@ -94,7 +94,8 @@ internal sealed partial class MainForm
_routeReadOnly.Visible = false;
_modeCard.Controls.AddRange([_modeIcon, _routeHeading, _routeCombo, _routeReadOnly]);
ConfigureLabel(_trafficHeading, "代理实时速度", Brand.Font(9.5f, FontStyle.Bold), Brand.Text);
ConfigureLabel(_trafficHeading, "公网入口速度", Brand.Font(9.5f, FontStyle.Bold), Brand.Text);
_trafficCard.AccessibleDescription = "仅当前纵横家使用域名或公网入口的代理速度;Tailscale 入口速度另列,非整机流量。";
ConfigureLabel(_dailyHeading, "速度与累计", Brand.Font(9.5f, FontStyle.Bold), Brand.Text);
ConfigureLabel(_sampleLabel, "仅代理流量 · 近 5 分钟", Brand.Font(7.5f), Brand.Muted);
_sampleLabel.TextAlign = ContentAlignment.MiddleRight;
@@ -139,7 +140,7 @@ internal sealed partial class MainForm
_footerPoem.TextAlign = ContentAlignment.MiddleRight;
_footerCompanyLogo.Image = LoadCompanyLogo();
_footerCompanyLogo.SizeMode = PictureBoxSizeMode.Zoom;
ConfigureLabel(_footerCompanySite, "vpn.toplc.cn", Brand.Font(8), Brand.Muted);
ConfigureLabel(_footerCompanySite, "vpn.example.invalid", Brand.Font(8), Brand.Muted);
_footerCompanyLogo.BackColor = Color.Transparent;
_footer.Controls.AddRange([_planLabel, _expiryLabel, _footerHint, _footerPoem, _footerCompanyLogo, _footerCompanySite]);
foreach (var card in new CardPanel[] { _statusCard, _nodeCard, _modeCard, _trafficCard, _dailyCard })
@@ -151,6 +152,7 @@ internal sealed partial class MainForm
_trafficCard.Controls.AddRange([_uploadMetric, _downloadMetric]);
_dailyCard.Controls.AddRange([_usageMetric, _sessionMetric]);
BuildTailnetTrafficCard();
BuildNodeTrafficMonitor();
_dashboardBody.Controls.Add(_footer);
foreach (var label in new[] { _welcomeLabel, _accountLabel, _statusTitle, _statusDetail, _currentNodeLabel, _planLabel, _expiryLabel })
{
@@ -166,8 +168,11 @@ internal sealed partial class MainForm
private void DisplayTraffic(double? upload, double? download, string sampling)
{
_uploadMetric.SetBytes(upload, speed: true, hint: "");
_downloadMetric.SetBytes(download, speed: true, hint: "");
var publicUpload = _currentNodeUsesTailnet ? null : upload;
var publicDownload = _currentNodeUsesTailnet ? null : download;
var hint = _currentNodeUsesTailnet ? "未使用公网入口" : "";
_uploadMetric.SetBytes(publicUpload, speed: true, hint: hint);
_downloadMetric.SetBytes(publicDownload, speed: true, hint: hint);
_sampleLabel.Text = sampling;
_uploadLegend.Text = upload.HasValue ? $"● 上传 {FormatBytes((long)upload.Value)}/s" : "● 上传 —";
_downloadLegend.Text = download.HasValue ? $"● 下载 {FormatBytes((long)download.Value)}/s" : "● 下载 —";
@@ -180,12 +185,12 @@ internal sealed partial class MainForm
{
if (_layingOutDashboard || _dashboardView.ClientSize.Width <= 0) return;
_layingOutDashboard = true;
Control[] layoutContainers = [_dashboardView, _dashboardBody, _statusCard, _nodeCard, _modeCard, _trafficCard, _tailnetTrafficCard, _dailyCard, _footer];
Control[] layoutContainers = [_dashboardView, _dashboardBody, _statusCard, _nodeCard, _modeCard, _trafficCard, _tailnetTrafficCard, _dailyCard, _nodeTrafficPanel, _footer];
foreach (var container in layoutContainers) container.SuspendLayout();
try
{
var viewport = _dashboardView.ClientSize;
var layout = DashboardLayout.Calculate(viewport, DeviceDpi, _tailnetTrafficVisible);
var layout = DashboardLayout.Calculate(viewport, DeviceDpi, _tailnetTrafficVisible, _canViewNodeTraffic);
var titleSize = 17f * Math.Max(.7f, layout.VerticalScale);
if (Math.Abs(_statusTitle.Font.Size - titleSize) > .1f)
{
@@ -205,6 +210,7 @@ internal sealed partial class MainForm
var metrics = new[] { _usageMetric, _uploadMetric, _downloadMetric, _sessionMetric };
for (var i = 0; i < 4; i++) Place(metrics[i], layout.Metrics[i]);
Place(_trafficCard, layout.TrafficCard); Place(_dailyCard, layout.DailyCard); Place(_footer, layout.Footer);
Place(_nodeTrafficPanel, layout.ServerTrafficCard);
LayoutTailnetTrafficCard(layout.TailnetTrafficCard, layout.VerticalScale);
_statusDot.Bounds = R(24, 15, 42, 46);
@@ -226,7 +232,7 @@ internal sealed partial class MainForm
_routeCombo.Bounds = new(ScaleLogical(54), Y(33), _modeCard.Width - ScaleLogical(70), Y(28));
_routeReadOnly.Bounds = new(_routeCombo.Left, _routeCombo.Top, _routeCombo.Width, Y(28));
_trafficIcon.Bounds = R(15, 10, 20, 20); _dailyIcon.Bounds = R(15, 10, 20, 20);
_trafficHeading.Bounds = R(42, 8, 92, 26);
_trafficHeading.Bounds = R(42, 8, 150, 26);
_dailyHeading.Bounds = new(ScaleLogical(42), Y(8), Math.Max(1, _dailyCard.Width - ScaleLogical(166)), Y(26));
_historyRangeCombo.Bounds = new(_dailyCard.Width - ScaleLogical(120), Y(8), ScaleLogical(106), Y(26));
_trafficChart.Bounds = new(ScaleLogical(10), Y(127), _dailyCard.Width - ScaleLogical(20), Y(105));
+1
View File
@@ -66,6 +66,7 @@ internal sealed partial class MainForm
{
if (_currentNodeUsesTailnet && !_xray.UsesTailnet)
{
_tailnetPreference.CommitDomainFallback();
if (_currentNodeSlug is not null) _tailnetPreference.Failed(_currentNodeSlug, Environment.TickCount64);
_transportRetryNodeSlug = null;
}
+2
View File
@@ -12,6 +12,8 @@ internal sealed partial class MainForm
_connectionAttemptCancellation?.Cancel();
_accessToken = token;
_sessionRevision++;
_nodeTrafficPanel.Unavailable("等待当前账号采样", clear: true);
_nextNodeTrafficAttempt = DateTimeOffset.MinValue;
_learningSync.Reset();
_learningSyncCore = null;
_tailnetReadiness.Reset();
+2 -1
View File
@@ -12,7 +12,8 @@ internal sealed partial class MainForm
if (selection.Manual || routeMode == "direct")
return legacy.Select(a => new PlannedTransport(a)).ToArray();
_statusDetail.Text = "先并行检测授权内网入口,按响应时间选择;全部不可用后再使用公网。";
_statusDetail.Text = _tailnetPreference.DomainOnly ? "本次连接保持域名入口,不再自动切回内网。"
: "先 Ping 授权代理内网 IP,按响应时间选择;不通则使用域名。";
var publicTailnet = await PublicTailnetSelection.RankAsync(
_manualNodeCombo.Items.Cast<NodeInfo>().Where(n => n is not PrivateAuxiliaryNode), routeMode,
slug => _failedNodes.ContainsKey(slug) || !_tailnetPreference.MayTry(slug, Environment.TickCount64),
+28 -12
View File
@@ -507,7 +507,7 @@ internal sealed partial class MainForm : Form
_connectionHealth.Invalidate();
_nextReconnect = DateTimeOffset.MinValue;
_wantConnected = true;
if (!reconnect) { _transportRetryNodeSlug = null; _failedNodes.Clear(); _sessionUp = _sessionDown = 0; _trafficChart.Reset(); ResetTailnetTraffic(); _sessionMetric.SetBytes(0, hint: "本次连接累计"); }
if (!reconnect) { _tailnetPreference.ResetForUserConnect(); _transportRetryNodeSlug = null; _failedNodes.Clear(); _sessionUp = _sessionDown = 0; _trafficChart.Reset(); ResetTailnetTraffic(); _sessionMetric.SetBytes(0, hint: "本次连接累计"); }
foreach (var slug in _failedNodes.Where(p => p.Value <= DateTimeOffset.UtcNow).Select(p => p.Key).ToList()) _failedNodes.Remove(slug);
SetConnectionState(false, "正在连接", selection.Manual ? "正在连接手动指定节点…" : "vpn-ai 正在分配工作节点…");
var replacementStarted = false;
@@ -521,7 +521,7 @@ internal sealed partial class MainForm : Form
throw new InvalidOperationException("私有节点授权已过期,请刷新账号信息后重试。");
if (route.Id == "direct" && selection.Manual && privateGrants.Any(n => n.Slug == selection.NodeSlug))
throw new InvalidOperationException("济南办私有辅助节点用于代理连接,请选择智能或全局代理。");
var rankedPrivate = route.Id == "direct" ? Array.Empty<PrivateAuxiliaryNode>() : await PrivateAuxiliaryRouting.RankForSelectionAsync(selection, privateGrants,
var rankedPrivate = route.Id == "direct" || _tailnetPreference.DomainOnly ? Array.Empty<PrivateAuxiliaryNode>() : await PrivateAuxiliaryRouting.RankForSelectionAsync(selection, privateGrants,
_failedNodes.Keys.ToHashSet(StringComparer.Ordinal), _xray.IsRunning,
PrivateAuxiliaryRouting.MeasureEndpointAsync, connectionToken);
var attempts = await PlanTransportsAsync(selection, rankedPrivate, route.Id, connectionToken);
@@ -705,7 +705,16 @@ internal sealed partial class MainForm : Form
private async Task RefreshTrafficAsync()
{
if (_trafficReading || _busy || !_xray.IsRunning || _exiting) return;
_trafficChart.AdvanceClock();
if (_exiting) return;
if (_trafficReading) return;
if (_busy || !_xray.IsRunning)
{
_trafficChart.MarkUnavailable();
_historyStatus.Text = "采样暂停 · 历史时间轴继续推进";
DisplayTraffic(null, null, "采样暂停");
return;
}
_trafficReading = true;
try
{
@@ -713,6 +722,8 @@ internal sealed partial class MainForm : Form
var counters = await _xray.ReadTrafficAsync(_lifetime.Token);
if (counters is null || core != _xray.CoreId)
{
_trafficChart.MarkUnavailable();
_historyStatus.Text = "采样暂不可用 · 不补零";
DisplayTraffic(null, null, "采样暂不可用");
return;
}
@@ -726,6 +737,7 @@ internal sealed partial class MainForm : Form
DisplayTraffic(up / seconds, down / seconds, $"{now.LocalDateTime:HH:mm:ss} · 近 5 分钟");
_sessionMetric.SetBytes(_sessionUp + _sessionDown, hint: "本次连接累计");
_trafficChart.Add(up/seconds, down/seconds);
_historyStatus.Text = "仅本次运行采样 · B/s";
// This is a view of the SAME proxy sample, not a second counter.
// A single connected proxy uses either its Tailnet or public ingress.
// Do not read the whole Tailscale adapter or add this subset to usage.
@@ -733,7 +745,13 @@ internal sealed partial class MainForm : Form
DisplayTailnetTraffic(up / seconds, down / seconds, $"{now.LocalDateTime:HH:mm:ss} · 近 5 分钟");
}
catch (OperationCanceledException) { }
catch (Exception exception) { AppPaths.WriteError(exception); }
catch (Exception exception)
{
_trafficChart.MarkUnavailable();
_historyStatus.Text = "采样暂不可用 · 不补零";
DisplayTraffic(null, null, "采样暂不可用");
AppPaths.WriteError(exception);
}
finally { _trafficReading = false; }
}
@@ -776,7 +794,6 @@ internal sealed partial class MainForm : Form
AppPaths.WriteLog("普通智能路径已恢复,沿用原内核与工作节点。");
}
ConnectionAcceptanceTrace.Record("health_ok", _currentNodeSlug, true, _xray.CoreId);
await CheckTailnetReadinessAsync();
return;
}
if (decision == ConnectionHealthPolicy.Decision.Repair) {
@@ -786,7 +803,6 @@ internal sealed partial class MainForm : Form
_statusDot.ForeColor = _statusTitle.ForeColor;
_notifyIcon.Text = "纵横家 · 分流修复中";
AppPaths.WriteLog($"健康诊断:普通路径失败、代理路径正常;保留内核 {_xray.CoreId},未判为节点故障。");
await CheckTailnetReadinessAsync();
return;
}
ConnectionAcceptanceTrace.Record("health_failed", _currentNodeSlug, _xray.IsRunning, _xray.CoreId, _connectionHealth.Failures);
@@ -798,6 +814,7 @@ internal sealed partial class MainForm : Form
// Transport failure is not node failure. Retry the same authorized
// node through its original ingress before asking for another node.
_tailnetPreference.Failed(_currentNodeSlug, Environment.TickCount64);
_tailnetPreference.CommitDomainFallback();
_transportRetryNodeSlug = _currentNodeSlug;
}
else _failedNodes[_currentNodeSlug] = DateTimeOffset.UtcNow.AddMinutes(5);
@@ -995,6 +1012,7 @@ internal sealed partial class MainForm : Form
if (_exiting || IsDisposed || Disposing) return;
_knownTailnetAllowed = false;
_refreshTimer.Stop();
SetNodeTrafficPermission(false);
_content.SuspendLayout();
_loginView.SuspendLayout();
try
@@ -1035,6 +1053,7 @@ internal sealed partial class MainForm : Form
{
if (_exiting || IsDisposed || Disposing) return;
_knownTailnetAllowed = true;
SetNodeTrafficPermission(profile.CanViewNodeTraffic);
var selectedRoute = preserveSelections ? (_routeCombo.SelectedItem as RouteModeInfo)?.Id : null;
_welcomeLabel.Text = $"你好,{profile.DisplayName}";
_accountLabel.Text = profile.Email;
@@ -1179,6 +1198,7 @@ internal sealed partial class MainForm : Form
_busy = true;
StopHandoverMonitoring();
_refreshTimer.Stop(); _updateTimer.Stop(); _trafficTimer.Stop(); _healthTimer.Stop();
_nodeTrafficTimer.Stop();
_lifetime.Cancel();
if (_uiOnly || _preview) return _exitCleanupTask = Task.FromResult<Exception?>(null);
// The same tracked cleanup serves menu/installer exit and session end.
@@ -1253,13 +1273,9 @@ internal sealed partial class MainForm : Form
var showItem = new ToolStripMenuItem("显示纵横家");
var menu = new ContextMenuStrip();
menu.Items.Add(showItem);
menu.Items.Add(_tailnetReconnectItem);
menu.Items.Add(new ToolStripSeparator());
menu.Items.Add(exitItem);
showItem.Click += (_, _) => ShowFromTray();
_tailnetReconnectItem.Click += async (_, _) => await ReconnectThroughPreferredTailnetAsync();
menu.Opening += (_, _) => _tailnetReconnectItem.Enabled = _tailnetReadiness.IsReady
&& !_busy && !_exiting && _wantConnected && _xray.IsRunning && !_xray.UsesTailnet;
exitItem.Click += (_, _) => RequestExit();
var notify = new NotifyIcon
{
@@ -1337,14 +1353,14 @@ internal sealed partial class MainForm : Form
{
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
{
FileName = "https://vpn.toplc.cn/register/",
FileName = "https://vpn.example.invalid/register/",
UseShellExecute = true,
});
}
catch (Exception exception)
{
AppPaths.WriteError(exception);
MessageBox.Show("无法打开注册页面,请在浏览器访问 https://vpn.toplc.cn/register/", "注册新用户", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessageBox.Show("无法打开注册页面,请在浏览器访问 https://vpn.example.invalid/register/", "注册新用户", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
+158
View File
@@ -0,0 +1,158 @@
using System.Text.Json.Serialization;
namespace UCVL.VPNPlus;
internal sealed class NodeTrafficSnapshot
{
[JsonPropertyName("contract")] public int Contract { get; init; }
[JsonPropertyName("scope")] public string Scope { get; init; } = "";
[JsonPropertyName("source")] public string Source { get; init; } = "";
[JsonPropertyName("direction")] public string Direction { get; init; } = "";
[JsonPropertyName("counter_since")] public string CounterSince { get; init; } = "";
[JsonPropertyName("generated_at")] public DateTimeOffset GeneratedAt { get; init; }
[JsonPropertyName("nodes")] public List<NodeTrafficReading> Nodes { get; init; } = [];
}
internal sealed class NodeTrafficReading
{
[JsonPropertyName("slug")] public string Slug { get; init; } = "";
[JsonPropertyName("name")] public string Name { get; init; } = "";
[JsonPropertyName("region")] public string Region { get; init; } = "";
[JsonPropertyName("current_upload_bytes_per_second")] public long? UploadRate { get; init; }
[JsonPropertyName("current_download_bytes_per_second")] public long? DownloadRate { get; init; }
[JsonPropertyName("total_upload_bytes")] public long? TotalUpload { get; init; }
[JsonPropertyName("total_download_bytes")] public long? TotalDownload { get; init; }
[JsonPropertyName("sampled_at")] public DateTimeOffset? SampledAt { get; init; }
[JsonPropertyName("interval_seconds")] public double? IntervalSeconds { get; init; }
[JsonPropertyName("stale")] public bool Stale { get; init; }
[JsonPropertyName("counter_epoch")] public string? CounterEpoch { get; init; }
}
// Read-only display contract: no personal accounting or route/core mutations.
internal static class NodeTrafficPresentation
{
internal static readonly string[] Slugs = ["aliyun-tokyo-002", "aliyun-siliconvalley-003"];
internal static bool Valid(NodeTrafficSnapshot value, DateTimeOffset now) => value.Contract == 1
&& value.Scope == "server_host_interface" && value.Source == "linux_host_interface"
&& value.Direction == "interface_perspective" && value.CounterSince == "boot_or_interface_reset"
&& value.GeneratedAt <= now.AddSeconds(5) && value.GeneratedAt >= now.AddSeconds(-15)
&& value.Nodes is { Count: <= 2 } && value.Nodes.All(n => n is not null)
&& value.Nodes.Select(n => n.Slug).Distinct(StringComparer.Ordinal).Count() == value.Nodes.Count
&& value.Nodes.All(n => Slugs.Contains(n.Slug, StringComparer.Ordinal)
&& n.UploadRate is not < 0 && n.DownloadRate is not < 0
&& n.TotalUpload is not < 0 && n.TotalDownload is not < 0
&& (n.IntervalSeconds is null || double.IsFinite(n.IntervalSeconds.Value) && n.IntervalSeconds > 0 && n.IntervalSeconds <= 30));
internal static bool Fresh(NodeTrafficReading row, DateTimeOffset now) => !row.Stale
&& row.SampledAt is { } sampled && sampled <= now.AddSeconds(5) && sampled >= now.AddSeconds(-15)
&& row.IntervalSeconds is > 0 and <= 30 && !string.IsNullOrWhiteSpace(row.CounterEpoch);
internal static string Bytes(long? bytes, bool speed = false)
{
if (bytes is null or < 0) return "—";
var value = (double)bytes.Value;
string[] units = ["B", "KB", "MB", "GB", "TB"];
var unit = 0;
while (value >= 1024 && unit < units.Length - 1) { value /= 1024; unit++; }
return $"{value:0.##} {units[unit]}" + (speed ? "/s" : "");
}
}
// One buffered surface, not a table of native child HWNDs. A snapshot swaps
// atomically on the UI thread and never changes row count or window height.
internal sealed class NodeTrafficPanel : CardPanel
{
private NodeTrafficSnapshot? _snapshot;
private string _status = "等待服务器采样";
internal void SetSnapshot(NodeTrafficSnapshot value) { _snapshot = value; _status = "每 5 秒更新"; Invalidate(); }
internal void Unavailable(string status, bool clear = false) { if (clear) _snapshot = null; _status = status; Invalidate(); }
internal NodeTrafficPanel() => AccessibleName = "VPN 服务器上行下行实时速度与累计流量";
internal static (Rectangle Title, Rectangle[] Rows) TextLayout(Size size, int dpi, int fontHeight)
{
var pad = Math.Max(2, 4 * dpi / 96);
var contentHeight = Math.Max(0, size.Height - pad * 2);
var title = contentHeight >= fontHeight * 3;
var height = contentHeight / (title ? 3 : 2);
Rectangle Line(int row) => new(pad, pad + row * height, Math.Max(0, size.Width - pad * 2), height);
return (title ? Line(0) : Rectangle.Empty, [Line(title ? 1 : 0), Line(title ? 2 : 1)]);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
var now = DateTimeOffset.UtcNow;
using var font = Brand.Font(7.1f);
var layout = TextLayout(ClientSize, DeviceDpi, TextRenderer.MeasureText(e.Graphics, "VPN002 上传", font).Height);
var flags = ChartAxis.PaintFlags | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis;
if (!layout.Title.IsEmpty) TextRenderer.DrawText(e.Graphics, "服务器整机流量 · 主 WAN 网卡 · 累计自网卡启动 / 重置", font,
layout.Title, Brand.Muted, flags);
for (var i = 0; i < 2; i++)
{
var slug = NodeTrafficPresentation.Slugs[i];
var row = _snapshot?.Nodes.SingleOrDefault(n => n.Slug == slug);
var fresh = row is not null && _snapshot is not null && NodeTrafficPresentation.Valid(_snapshot, now)
&& NodeTrafficPresentation.Fresh(row, now) && _status == "每 5 秒更新";
var name = i == 0 ? "VPN002 东京" : "VPN003 美国";
var up = fresh ? row!.UploadRate : null;
var down = fresh ? row!.DownloadRate : null;
var status = fresh ? row!.SampledAt!.Value.LocalDateTime.ToString("HH:mm:ss")
: row?.SampledAt is { } oldTime ? $"过期 {oldTime.LocalDateTime:HH:mm:ss}" : "等待上报";
var text = $"{name} ↑ {NodeTrafficPresentation.Bytes(up, true)} ↓ {NodeTrafficPresentation.Bytes(down, true)}"
+ $" 累计 ↑ {NodeTrafficPresentation.Bytes(row?.TotalUpload)} ↓ {NodeTrafficPresentation.Bytes(row?.TotalDownload)} {status}";
TextRenderer.DrawText(e.Graphics, text, font,
layout.Rows[i], Brand.Text, flags);
}
AccessibleDescription = _status + ";速率为采样区间平均。服务器整机网卡数据,不是本账号代理流量,不计入套餐用量;过期累计保留采样时间。";
}
}
internal sealed partial class MainForm
{
private readonly NodeTrafficPanel _nodeTrafficPanel = new();
private readonly System.Windows.Forms.Timer _nodeTrafficTimer = new() { Interval = 5_000 };
private bool _canViewNodeTraffic, _nodeTrafficReading;
private DateTimeOffset _nextNodeTrafficAttempt;
private void BuildNodeTrafficMonitor()
{
_nodeTrafficPanel.Visible = false;
_dashboardBody.Controls.Add(_nodeTrafficPanel);
_nodeTrafficTimer.Tick += async (_, _) => await RefreshNodeTrafficAsync();
_nodeTrafficPanel.Disposed += (_, _) => _nodeTrafficTimer.Dispose();
}
private void SetNodeTrafficPermission(bool allowed)
{
if (_canViewNodeTraffic != allowed) _nodeTrafficPanel.Unavailable("等待服务器采样", clear: true);
_canViewNodeTraffic = allowed;
_nodeTrafficPanel.Visible = allowed;
if (allowed && !_preview && !_uiOnly && !_exiting) _nodeTrafficTimer.Start();
else _nodeTrafficTimer.Stop();
LayoutDashboard();
}
private async Task RefreshNodeTrafficAsync()
{
_nodeTrafficPanel.Invalidate();
if (!_canViewNodeTraffic || _nodeTrafficReading || _preview || _uiOnly || _exiting
|| string.IsNullOrWhiteSpace(_accessToken) || DateTimeOffset.UtcNow < _nextNodeTrafficAttempt) return;
var token = _accessToken;
var revision = _sessionRevision;
bool Current() => !_exiting && !IsDisposed && _canViewNodeTraffic && _sessionRevision == revision && _accessToken == token;
_nodeTrafficReading = true;
try
{
var result = await _api.GetNodeTrafficAsync(token, _lifetime.Token);
if (!Current()) return;
if (!NodeTrafficPresentation.Valid(result, DateTimeOffset.UtcNow)) throw new IOException("监控契约或时间戳无效。");
_nodeTrafficPanel.SetSnapshot(result);
}
catch (ApiException error) when (error.StatusCode is 401 or 403)
{
if (Current()) { _nodeTrafficPanel.Unavailable("监控权限不可用", clear: true); SetNodeTrafficPermission(false); }
// An optional monitor must not log out or disconnect the VPN.
}
catch (ApiException error) when (error.StatusCode is 404 or 405)
{
if (Current()) { _nextNodeTrafficAttempt = DateTimeOffset.UtcNow.AddMinutes(2); _nodeTrafficPanel.Unavailable("后台尚未提供服务器监控"); }
}
catch (OperationCanceledException) { if (Current()) _nodeTrafficPanel.Unavailable("采样请求超时"); }
catch (Exception) { if (Current()) _nodeTrafficPanel.Unavailable("服务器采样暂不可用"); }
finally { _nodeTrafficReading = false; }
}
}
+83
View File
@@ -0,0 +1,83 @@
using System.Text.Json;
namespace UCVL.VPNPlus;
internal static class NodeTrafficSelfTest
{
internal static int Run()
{
var checks = new Dictionary<string, bool>();
string? error = null;
try
{
var now = new DateTimeOffset(2026, 10, 22, 8, 0, 0, TimeSpan.Zero);
NodeTrafficReading Row(string slug = "aliyun-tokyo-002", bool stale = false, DateTimeOffset? sampled = null,
long? up = 10, long? down = 20, long? totalUp = 30, long? totalDown = 40, double? interval = 5, string? epoch = "fixture") => new()
{ Slug = slug, Stale = stale, SampledAt = sampled ?? now, UploadRate = up, DownloadRate = down,
TotalUpload = totalUp, TotalDownload = totalDown, IntervalSeconds = interval, CounterEpoch = epoch };
NodeTrafficSnapshot Snapshot(List<NodeTrafficReading>? rows = null, string scope = "server_host_interface",
string source = "linux_host_interface", DateTimeOffset? generated = null, string direction = "interface_perspective") => new()
{ Contract = 1, Scope = scope, Source = source, Direction = direction, CounterSince = "boot_or_interface_reset",
GeneratedAt = generated ?? now, Nodes = rows ?? [Row(), Row(NodeTrafficPresentation.Slugs[1])] };
bool Valid(NodeTrafficSnapshot value) => NodeTrafficPresentation.Valid(value, now);
checks["exact_two_authorized_server_contract"] = Valid(Snapshot());
checks["empty_authorized_set_is_not_fake_servers"] = Valid(Snapshot([]));
checks["other_nodes_rejected"] = !Valid(Snapshot([Row("phone")]));
checks["duplicate_node_rejected"] = !Valid(Snapshot([Row(), Row()]));
checks["too_many_rows_rejected"] = !Valid(Snapshot([Row(), Row(), Row()]));
checks["proxy_accounting_cannot_be_mislabelled_host"] = !Valid(Snapshot(scope: "server_proxy_aggregate"));
checks["unknown_source_rejected"] = !Valid(Snapshot(source: "unknown"));
checks["wrong_direction_rejected"] = !Valid(Snapshot(direction: "client_perspective"));
checks["stale_envelope_rejected"] = !Valid(Snapshot(generated: now.AddSeconds(-16)));
checks["future_envelope_rejected"] = !Valid(Snapshot(generated: now.AddSeconds(6)));
checks["negative_upload_rejected"] = !Valid(Snapshot([Row(up: -1)]));
checks["negative_download_rejected"] = !Valid(Snapshot([Row(down: -1)]));
checks["negative_total_rejected"] = !Valid(Snapshot([Row(totalUp: -1)]));
checks["nonfinite_interval_rejected"] = !Valid(Snapshot([Row(interval: double.NaN)]));
checks["unbounded_interval_rejected"] = !Valid(Snapshot([Row(interval: 31)]));
checks["fresh_sample_is_current"] = NodeTrafficPresentation.Fresh(Row(), now);
checks["backend_stale_is_not_live"] = !NodeTrafficPresentation.Fresh(Row(stale: true), now);
checks["client_checks_sample_age_independently"] = !NodeTrafficPresentation.Fresh(Row(sampled: now.AddSeconds(-16)), now);
checks["future_sample_is_not_live"] = !NodeTrafficPresentation.Fresh(Row(sampled: now.AddSeconds(6)), now);
checks["first_counter_has_no_invented_rate"] = !NodeTrafficPresentation.Fresh(Row(up: null, down: null, interval: null), now);
checks["reset_epoch_required"] = !NodeTrafficPresentation.Fresh(Row(epoch: null), now);
checks["missing_is_dash_not_zero"] = NodeTrafficPresentation.Bytes(null, true) == "—";
checks["measured_zero_retained"] = NodeTrafficPresentation.Bytes(0, true) == "0 B/s";
checks["rate_uses_bytes_not_bits"] = NodeTrafficPresentation.Bytes(204800, true) == "200 KB/s";
checks["cumulative_has_no_speed_suffix"] = NodeTrafficPresentation.Bytes(204800) == "200 KB";
checks["all_geometry_monitor_tailnet_cases_fit"] = DashboardLayout.SelfTest();
using (var font = Brand.Font(7.1f))
{
var measuredHeight = TextRenderer.MeasureText("VPN002 上传", font).Height;
foreach (var dpi in new[] { 96, 120, 144, 192, 336, 384 })
{
var view = new Size(620 * dpi / 96, 350 * dpi / 96);
var panel = DashboardLayout.Calculate(view, dpi, true, true).ServerTrafficCard;
var text = NodeTrafficPanel.TextLayout(panel.Size, dpi, (int)Math.Ceiling(measuredHeight * dpi / 96d));
checks["minimum_two_text_rows_fit_" + dpi] = text.Rows.Length == 2
&& text.Rows.All(row => row.Height >= measuredHeight * dpi / 96d && row.Bottom <= panel.Height)
&& !text.Rows[0].IntersectsWith(text.Rows[1]);
}
}
foreach (var tailnet in new[] { false, true })
{
var view = new Size(960, 612);
var layout = DashboardLayout.Calculate(view, 96, tailnet, true);
checks["server_rows_below_real_speed_" + tailnet] = layout.ServerTrafficCard.Top > layout.DailyCard.Bottom
&& layout.ServerTrafficCard.Top > layout.TrafficCard.Bottom
&& (!tailnet || layout.ServerTrafficCard.Top > layout.TailnetTrafficCard.Bottom);
checks["no_extra_window_height_or_scroll_" + tailnet] = layout.Footer.Bottom <= view.Height
&& layout.ContentHeight <= view.Height && layout.ServerTrafficCard.Bottom < layout.Footer.Top;
}
var oldProfile = JsonSerializer.Deserialize<Profile>("{\"email\":\"fixture@example.invalid\"}")!;
checks["older_backend_omission_does_not_enable_monitor"] = !oldProfile.CanViewNodeTraffic;
}
catch (Exception exception) { error = exception.GetType().Name; }
var passed = error is null && checks.Count >= 30 && checks.Values.All(value => value);
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "node-traffic-self-test.json"),
JsonSerializer.Serialize(new { passed, checks, error, scope = "offline contract and fixed-height geometry only",
network_modified = false, credentials_loaded = false, production_sample_observed = false },
new JsonSerializerOptions { WriteIndented = true }));
return passed ? 0 : 84;
}
}
+19 -33
View File
@@ -29,41 +29,25 @@ internal static class NodeTransportConnector
throw new InvalidOperationException("缺少可验证的同节点原入口,未尝试切换。");
var selected = current;
var fallback = original;
if (!tailnet && preferredTailnetConfig is not null)
{
// Only a confirmed physical-network recovery calls this method.
// Re-check the cached alternate of this SAME authorized config; a
// previous-network cooldown must not make public ingress sticky.
if (!TailnetTransport.SameAuthorizedFallback(preferredTailnetConfig, current))
throw new InvalidOperationException("Tailscale 恢复入口与当前授权线路不匹配。");
if (requireRoute is null || endpointProbe is null)
throw new InvalidOperationException("Tailscale 恢复入口缺少独立路由或端口验证。");
var recheckReason = "route_unavailable";
try
{
var address = TailnetTransport.Address(preferredTailnetConfig)!;
requireRoute(address);
token.ThrowIfCancellationRequested();
recheckReason = "endpoint_unreachable";
if (!await endpointProbe(address, TailnetTransport.Port(preferredTailnetConfig), token))
diagnostic?.Invoke(new("rebind_skipped", "endpoint_unreachable", ""));
else
{
token.ThrowIfCancellationRequested();
selected = preferredTailnetConfig;
fallback = current;
tailnet = true;
diagnostic?.Invoke(new("rebind_attempt", "tailnet_recovered", ""));
}
}
catch (Exception e) when (e is not OperationCanceledException && e is not LocalNetworkException)
{ diagnostic?.Invoke(new("rebind_skipped", recheckReason, "")); }
}
// Once domain fallback has been selected, physical-network recovery
// retains it. Do not probe/promote a cached internal alternative.
// Only an explicit new user connection may select the internal IP again.
token.ThrowIfCancellationRequested();
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
if (tailnet) deadline.CancelAfter(TimeSpan.FromSeconds(45));
try
{
if (tailnet && endpointProbe is not null)
{
var available = await endpointProbe(TailnetTransport.Address(selected)!, TailnetTransport.Port(selected), deadline.Token);
token.ThrowIfCancellationRequested();
if (!available)
{
selected = fallback!;
tailnet = false;
diagnostic?.Invoke(new("rebind_fallback", "ping_unreachable", ""));
}
}
await start(selected, deadline.Token);
if (tailnet && !await proxyHealth(deadline.Token)) throw new IOException("Tailscale 切网后出口未通过。");
deadline.Token.ThrowIfCancellationRequested();
@@ -117,9 +101,9 @@ internal static class NodeTransportConnector
{
try
{
status("正在检测 Tailscale 入口(最多 3 秒)");
status("正在 Ping 代理内网 IP(最多 1 秒)");
if (!await endpointProbe(TailnetTransport.Address(tailnet)!, TailnetTransport.Port(tailnet), token))
throw new IOException("Tailscale 端口不可达。");
throw new IOException("代理内网 IP Ping 不通。");
token.ThrowIfCancellationRequested();
}
catch (Exception e) when (e is not OperationCanceledException)
@@ -128,7 +112,7 @@ internal static class NodeTransportConnector
tailnet = null;
reason = "endpoint_unreachable";
Report("tailnet_skipped", reason);
status(tailnetOnly ? "Tailscale 端口不可达,继续检测其他授权内网节点" : "Tailscale 端口不可达,使用同一节点公网入口");
status(tailnetOnly ? "内网 IP Ping 不通,继续其他授权内网节点" : "内网 IP Ping 不通,回退域名并保持");
}
}
if (tailnet is not null)
@@ -163,6 +147,8 @@ internal static class NodeTransportConnector
// Automatic selection can test ALL authorized Tailnet nodes first. A
// failed alternate must not launch public ingress before that pass ends.
if (tailnetOnly) throw new TailnetUnavailableException(reason);
if (response.ConnectionScope != PrivateAuxiliaryRouting.Scope && response.RouteMode is "smart" or "global")
preference.CommitDomainFallback();
Report("selected", "public_ingress");
await start(response.GetRuntimeConfigJson(), token);
token.ThrowIfCancellationRequested();
+1 -1
View File
@@ -8,7 +8,7 @@ namespace UCVL.VPNPlus;
// there is no HTTP retry, URL rewrite, system DNS change or TLS bypass.
internal static class PlatformBootstrapTransport
{
internal const string Host = "vpn.toplc.cn";
internal const string Host = "vpn.example.invalid";
private static readonly IPAddress BootstrapAddress = IPAddress.Parse("192.0.2.1");
internal static SocketsHttpHandler CreateHandler() => new()
@@ -12,11 +12,11 @@ internal static class PlatformBootstrapTransportSelfTest
using var handler = PlatformBootstrapTransport.CreateHandler();
checks.Add(!handler.UseProxy && !handler.AllowAutoRedirect && !handler.UseCookies);
checks.Add(handler.SslOptions.RemoteCertificateValidationCallback is null);
PlatformBootstrapTransport.ValidateRequest(new Uri("https://vpn.toplc.cn/api/v1/client/login/"));
foreach (var uri in new[] { "http://vpn.toplc.cn/", "https://vpn.toplc.cn:444/", "https://192.0.2.1/",
"https://other.invalid/", "https://vpn.toplc.cn.evil.invalid/", "https://user@vpn.toplc.cn/" })
PlatformBootstrapTransport.ValidateRequest(new Uri("https://vpn.example.invalid/api/v1/client/login/"));
foreach (var uri in new[] { "http://vpn.example.invalid/", "https://vpn.example.invalid:444/", "https://192.0.2.1/",
"https://other.invalid/", "https://vpn.example.invalid.evil.invalid/", "https://user@vpn.example.invalid/" })
checks.Add(Rejects(() => PlatformBootstrapTransport.ValidateRequest(new Uri(uri))));
checks.Add(Rejects(() => PlatformBootstrapTransport.ValidateRequest(new Uri("https://vpn.toplc.cn/"), "other.invalid")));
checks.Add(Rejects(() => PlatformBootstrapTransport.ValidateRequest(new Uri("https://vpn.example.invalid/"), "other.invalid")));
foreach (var ip in new[] { "198.18.0.0", "198.19.255.255", "::ffff:198.18.0.41" })
checks.Add(PlatformBootstrapTransport.IsFakeAddress(IPAddress.Parse(ip)));
foreach (var ip in new[] { "198.17.255.255", "198.20.0.0", "192.0.2.1", "::1" })
+1 -1
View File
@@ -17,7 +17,7 @@ internal static class PrivateAuxiliaryRouting
internal const string PhoneAddress = "192.168.50.170";
internal const string PhoneTailnetAddress = "100.64.0.4";
internal const string PublicPhoneAddress = "192.0.2.1";
internal const string PublicPhoneHost = "vpn.toplc.cn";
internal const string PublicPhoneHost = "vpn.example.invalid";
internal static bool IsRegisteredEndpoint(string? address) =>
address is JinanAddress or PhoneAddress or PhoneTailnetAddress or PublicPhoneAddress or PublicPhoneHost;
internal static bool ValidEndpoint(PrivateAuxiliaryNode node) =>
+7 -7
View File
@@ -77,7 +77,7 @@ internal static class PrivateAuxiliaryRoutingSelfTest
[slow, fast], empty, Tie, default)).SequenceEqual([slow, fast]);
var domain = new PrivateAuxiliaryNode { Slug = "same-site", Name = "济南(博翠明湖)", Status = "candidate",
Contract = 1, ExpiresAt = now.AddMinutes(3), TlsLeafSha256 = new string('a', 64),
ProbeIpv4 = "192.0.2.1", ConnectAddress = "vpn.toplc.cn", ProbePort = 11080 };
ProbeIpv4 = "192.0.2.1", ConnectAddress = "vpn.example.invalid", ProbePort = 11080 };
Task<long?> PublicFast(PrivateAuxiliaryNode n, CancellationToken t) => Task.FromResult<long?>(n == domain ? 1 : 90);
checks["internal_priority_even_when_domain_ping_is_faster"] = (await PrivateAuxiliaryRouting.RankByLatencyAsync(
[domain, slow], empty, PublicFast, default)).SequenceEqual([slow, domain]);
@@ -85,7 +85,7 @@ internal static class PrivateAuxiliaryRoutingSelfTest
Contract = 1, ExpiresAt = now.AddMinutes(3), TlsLeafSha256 = new string('a', 64),
ProbeIpv4 = "100.64.0.4", ConnectionEndpoints = [
new() { Address = "100.64.0.4", ProbeIpv4 = "100.64.0.4", Port = 18081 },
new() { Address = "vpn.toplc.cn", ProbeIpv4 = "192.0.2.1", Port = 11080 }] };
new() { Address = "vpn.example.invalid", ProbeIpv4 = "192.0.2.1", Port = 11080 }] };
Task<long?> Both(PrivateAuxiliaryNode n, CancellationToken t) => Task.FromResult<long?>(n.ProbePort == 11080 ? 1 : 90);
var fixedSite = ConnectionSelection.Create(true, "same-site", ["same-site"]);
var sameSiteRanking = await PrivateAuxiliaryRouting.RankForSelectionAsync(fixedSite, [oneSite], empty, false, Both, default);
@@ -94,16 +94,16 @@ internal static class PrivateAuxiliaryRoutingSelfTest
checks["manual_can_fallback_transport_not_node"] = ConnectionAttemptPlanner.CreateRanked(fixedSite, sameSiteRanking, 3)
.All(a => a.IsPrivate && a.Slug == "same-site");
var renewal = PrivateAuxiliaryRouting.ForRenewal(oneSite, domain);
checks["renewal_keeps_working_domain_not_preferred_tailnet"] = renewal.EndpointHost == "vpn.toplc.cn"
checks["renewal_keeps_working_domain_not_preferred_tailnet"] = renewal.EndpointHost == "vpn.example.invalid"
&& renewal.ProbePort == 11080 && renewal.ExpiresAt == oneSite.ExpiresAt;
checks["renewal_keeps_working_internal_endpoint"] = PrivateAuxiliaryRouting.ForRenewal(oneSite, sameSiteRanking[0]).ProbeIpv4 == "100.64.0.4";
checks["renewal_revoked_transport_rejected"] = Reject(() => PrivateAuxiliaryRouting.ForRenewal(oneSite, Node()));
checks["renewal_legacy_endpoint_preserved"] = PrivateAuxiliaryRouting.ForRenewal(grants[0], grants[0]) == grants[0];
Task<long?> OnlyDomain(PrivateAuxiliaryNode n, CancellationToken t) => Task.FromResult<long?>(n.ProbePort == 11080 ? 30 : null);
checks["failed_internal_selects_same_site_domain"] = (await PrivateAuxiliaryRouting.RankForSelectionAsync(
fixedSite, [oneSite], empty, false, OnlyDomain, default)).Single().EndpointHost == "vpn.toplc.cn";
fixedSite, [oneSite], empty, false, OnlyDomain, default)).Single().EndpointHost == "vpn.example.invalid";
var domainConfig = Config(mutate: r => {
r["outbounds"]![0]!["settings"]!["servers"]![0]!["address"] = "vpn.toplc.cn";
r["outbounds"]![0]!["settings"]!["servers"]![0]!["address"] = "vpn.example.invalid";
r["outbounds"]![0]!["settings"]!["servers"]![0]!["port"] = 11080;
});
// The fixture config helper is defined below; domain validation is checked there.
@@ -155,9 +155,9 @@ internal static class PrivateAuxiliaryRoutingSelfTest
checks["compatible_private_config_accepted"] = !Reject(() => PrivateAuxiliaryRouting.ValidateConfig(grants[0], Config(), "smart"));
var sameSlugDomain = new PrivateAuxiliaryNode { Slug = "jinan-private", Status = "candidate", Contract = 1,
ExpiresAt = now.AddMinutes(3), TlsLeafSha256 = new string('a', 64), ProbeIpv4 = "192.0.2.1",
ConnectAddress = "vpn.toplc.cn", ProbePort = 11080 };
ConnectAddress = "vpn.example.invalid", ProbePort = 11080 };
checks["authorized_domain_mapping_config_accepted"] = !Reject(() => PrivateAuxiliaryRouting.ValidateConfig(sameSlugDomain, domainConfig, "smart"));
checks["domain_runtime_keeps_real_hostname"] = PrivateAuxiliaryRuntime.Address(domainConfig.GetRuntimeConfigJson()) == "vpn.toplc.cn";
checks["domain_runtime_keeps_real_hostname"] = PrivateAuxiliaryRuntime.Address(domainConfig.GetRuntimeConfigJson()) == "vpn.example.invalid";
foreach (var address in new[] { "192.168.50.170", "100.64.0.4" }) {
var phoneGrant = Node(address: address);
var phoneConfig = Config(mutate: r => r["outbounds"]![0]!["settings"]!["servers"]![0]!["address"] = address);
+4
View File
@@ -25,6 +25,10 @@ internal static class Program
return LearningSyncCoordinatorSelfTest.RunAsync().GetAwaiter().GetResult();
if (args.Length == 1 && args[0] == "--tailnet-readiness-self-test")
return TailnetReadinessSelfTest.Run();
if (args.Length == 1 && args[0] == "--chart-freshness-self-test")
return ChartFreshnessSelfTest.Run();
if (args.Length == 1 && args[0] == "--node-traffic-self-test")
return NodeTrafficSelfTest.Run();
if (args.Length == 1 && args[0] == "--nextgen-lifecycle-self-test")
{
ApplicationConfiguration.Initialize();
+5 -3
View File
@@ -1,6 +1,6 @@
# 纵横家 Windows 0.3.0 开源源码
# 纵横家 Windows 0.3.1 开源源码
基于已冻结的 0.3.0 r1 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。
基于已冻结的 0.3.1 r1 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。
## 构建
@@ -17,4 +17,6 @@ dotnet publish VPNPlus.csproj -c Release -r win-x64 --self-contained true
公司自有代码适用 LICENSE;公司 Logo/商标保留来源识别用途、不授予品牌权利;第三方许可文本在 licenses/ 中,原 THIRD_PARTY_NOTICES.md 保持原文。
本次 0.3.0 同步连接排序与内网恢复提示、可取消连接、会话代际及学习同步退避、固定高度单页与实时速度显示。内网恢复不静默中断长连接;需要明确重连。此清洁源码以原创山水替代许可不明的可选人物插图,真实内部端点替换为示例。原安装包测试结论不自动转移为此导出的网络或安装验收。
本次 0.3.1 同步连接排序与内网恢复提示、可取消连接、会话代际及学习同步退避、固定高度单页与实时速度显示。内网恢复不静默中断长连接;需要明确重连。此清洁源码以原创山水替代许可不明的可选人物插图,真实内部端点替换为示例。原安装包测试结论不自动转移为此导出的网络或安装验收。
0.3.1:固定画布实时速率、主WAN采样显示、节点延迟和粘性连接维护。整机WAN监控与个人套餐分开;未部署的后台、账户限速、真实网络和实窗结论不转移到此清洁源码。
+17 -8
View File
@@ -188,14 +188,23 @@ internal sealed class ScenicPanel : Panel
if (_loginBackdrop is null || _loginBackdrop.Size != ClientSize
|| _loginBackdropDpi != DeviceDpi || _loginBackdropFooter != FooterArtwork)
{
using var next = new Bitmap(Width, Height);
using (var graphics = Graphics.FromImage(next))
ScenicTheme.Backdrop(graphics, ClientSize, DeviceDpi, footer: FooterArtwork, login: true);
var previous = _loginBackdrop;
_loginBackdrop = new Bitmap(next);
_loginBackdropDpi = DeviceDpi;
_loginBackdropFooter = FooterArtwork;
previous?.Dispose();
Bitmap? next = null;
try
{
next = new Bitmap(Width, Height);
using (var graphics = Graphics.FromImage(next))
ScenicTheme.Backdrop(graphics, ClientSize, DeviceDpi, footer: FooterArtwork, login: true);
// Transfer the completed bitmap rather than copying the whole
// canvas on the UI thread. A failed render leaves the previous
// cache owned and intact; only the incomplete replacement dies.
var previous = _loginBackdrop;
_loginBackdrop = next;
next = null;
_loginBackdropDpi = DeviceDpi;
_loginBackdropFooter = FooterArtwork;
previous?.Dispose();
}
finally { next?.Dispose(); }
}
e.Graphics.DrawImageUnscaled(_loginBackdrop, Point.Empty);
}
+22 -25
View File
@@ -99,29 +99,23 @@ internal static class TailnetTransport
internal static int Port(string json) => JsonNode.Parse(json)![Marker]!["port"]!.GetValue<int>();
// Before starting/replacing a core, test only this socket through the existing
// user-owned route. ICMP success isn't enough; TCP success still isn't auth.
// Selection checks only ICMP through the existing OS network. It never
// queries or changes Tailscale; authenticated proxy health is checked after
// starting the chosen authorized transport, separately from reachability.
internal static async Task<bool> ProbeEndpointAsync(string address, int port, CancellationToken token)
{
token.ThrowIfCancellationRequested();
if (!IsTailnetAddress(address) || port is < 1 or > 65535) return false;
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
deadline.CancelAfter(TimeSpan.FromSeconds(3));
deadline.CancelAfter(TimeSpan.FromSeconds(1));
try
{
var name = RequireExistingRoute(address);
var nic = NetworkInterface.GetAllNetworkInterfaces().Single(n => n.Name == name);
var index = nic.GetIPProperties().GetIPv4Properties()!.Index;
using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Windows IP_UNICAST_IF=31 is not named by .NET 8's enum.
// https://learn.microsoft.com/en-us/windows/win32/winsock/ipproto-ip-socket-options
const SocketOptionName ipUnicastInterface = (SocketOptionName)31;
socket.SetSocketOption(SocketOptionLevel.IP, ipUnicastInterface, IPAddress.HostToNetworkOrder(index));
await socket.ConnectAsync(new IPEndPoint(IPAddress.Parse(address), port), deadline.Token);
return true;
using var ping = new Ping();
var reply = await ping.SendPingAsync(IPAddress.Parse(address), 1000).WaitAsync(deadline.Token).ConfigureAwait(false);
return reply.Status == IPStatus.Success;
}
catch (OperationCanceledException) when (!token.IsCancellationRequested) { return false; }
catch (Exception e) when (e is SocketException or NetworkInformationException or InvalidOperationException) { return false; }
catch (Exception e) when (e is PingException or SocketException or NetworkInformationException or InvalidOperationException) { return false; }
}
internal static bool SameAuthorizedFallback(string current, string? fallback)
@@ -142,20 +136,21 @@ internal static class TailnetTransport
}
// Read only. No CLI/process/service dependency: user owns the underlying network.
// Require an existing more-specific route; never manufacture a /32 through the
// phone/default gateway. Bind the proxy socket to that interface so a lost
// tailnet route cannot silently recurse into our own TUN.
// Ask Windows which existing interface owns this IP path, including a valid
// default route. No adapter-name, service or route-prefix prerequisite.
// This UDP Connect sends no payload. Refuse our own TUN to avoid recursion;
// no /32 or user route is manufactured or removed.
internal static string RequireExistingRoute(string address)
{
if (!IsTailnetAddress(address)) throw new InvalidOperationException("Tailscale 地址无效。");
var interfaces = NetworkInterface.GetAllNetworkInterfaces()
using var route = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
route.Connect(new IPEndPoint(IPAddress.Parse(address), 443));
var local = (route.LocalEndPoint as IPEndPoint)?.Address;
var owner = NetworkInterface.GetAllNetworkInterfaces()
.Where(n => n.OperationalStatus == OperationalStatus.Up && n.NetworkInterfaceType != NetworkInterfaceType.Loopback
&& !n.Name.StartsWith(TunRouting.AdapterName, StringComparison.OrdinalIgnoreCase))
.Select(n => new { n.Name, Index = n.GetIPProperties().GetIPv4Properties()?.Index })
.Where(n => n.Index.HasValue).ToDictionary(n => n.Index!.Value, n => n.Name);
var index = SelectRoute(address, new WindowsRouteTable().Snapshot(), interfaces.Keys.ToHashSet());
return index is { } found ? interfaces[found]
: throw new InvalidOperationException("Tailscale 节点路径暂不可用,保留原入口作为回退。");
.FirstOrDefault(n => n.GetIPProperties().UnicastAddresses.Any(a => a.Address.Equals(local)));
return owner?.Name ?? throw new InvalidOperationException("代理内网 IP 路径暂不可用,保留域名入口作为回退。");
}
internal static int? SelectRoute(string address, IEnumerable<Ipv4Route> routes, IReadOnlySet<int> usable)
@@ -191,9 +186,11 @@ internal static class TailnetTransport
internal sealed class TailnetPreference
{
private readonly Dictionary<string, long> _cooldowns = new(StringComparer.Ordinal);
internal bool DomainOnly { get; private set; }
// Only an explicit user connect action resets failures. Automatic recovery
// continues respecting the existing monotonic cooldown.
internal void ResetForUserConnect() => _cooldowns.Clear();
internal bool MayTry(string slug, long now) => !_cooldowns.TryGetValue(slug, out var expiry) || now >= expiry;
internal void ResetForUserConnect() { _cooldowns.Clear(); DomainOnly = false; }
internal void CommitDomainFallback() => DomainOnly = true;
internal bool MayTry(string slug, long now) => !DomainOnly && (!_cooldowns.TryGetValue(slug, out var expiry) || now >= expiry);
internal void Failed(string slug, long now) => _cooldowns[slug] = now + 5 * 60_000;
}
+1 -1
View File
@@ -74,7 +74,7 @@ internal static class TailnetTransportProbe
country = lines.FirstOrDefault(l => l[0] == "loc")?[1];
}
checks["expected_node_exit"] = node == "aliyun-tokyo-002"
? exitIp == "8.216.53.107" && country == "JP" : exitIp == "47.254.94.29" && country == "US";
? exitIp == "198.51.100.22" && country == "JP" : exitIp == "203.0.113.23" && country == "US";
checks["actual_transport_label"] = NodePresentation.WithTransport(node == "aliyun-tokyo-002" ? "VPN002" : "VPN003", true)
== (node == "aliyun-tokyo-002" ? "VPN002 + Tailscale" : "VPN003 + Tailscale");
}
+42 -13
View File
@@ -92,8 +92,11 @@ internal static class TailnetTransportSelfTest
starts.Clear(); routeReads=0;
selected = await NodeTransportConnector.ConnectAsync(response, preference, Start, Stop, Healthy, Route,_=>{},()=>tick+299999,CancellationToken.None);
checks["cooldown_skips_route_and_probe"] = !selected && starts.SequenceEqual(new[]{"vpn002.example.invalid"}) && routeReads==0 && probes==0;
checks["cooldown_monotonic_expiry"] = preference.MayTry("tokyo",tick+300000) && !preference.MayTry("tokyo",tick+299999);
checks["other_node_cooldown_independent"] = preference.MayTry("silicon",tick);
checks["domain_fallback_stays_sticky_after_five_minutes"] = !preference.MayTry("tokyo",tick+300000)
&& !preference.MayTry("tokyo",tick+86_400_000);
checks["domain_fallback_blocks_other_internal_nodes_this_session"] = !preference.MayTry("silicon",tick);
preference.ResetForUserConnect();
checks["explicit_user_connect_resets_domain_choice"] = preference.MayTry("tokyo",tick+1) && preference.MayTry("silicon",tick+1);
starts.Clear(); statuses.Clear();
selected = await NodeTransportConnector.ConnectAsync(response,new(),Start,Stop,Healthy,_=>throw new IOException("SYNTHETIC_SECRET route unavailable"),statuses.Add,()=>tick,CancellationToken.None);
checks["route_read_failure_keeps_original"] = !selected && starts.SequenceEqual(new[]{"vpn002.example.invalid"});
@@ -204,7 +207,7 @@ internal static class TailnetTransportSelfTest
["contract"] = 1, ["node_slug"] = "aliyun-tokyo-002", ["address"] = "100.65.1.9", ["port"] = 2345
}), true)!;
checks["explicit_server_metadata_takes_priority"] = Host(future) == "100.65.1.9" && TailnetTransport.Port(future) == 2345;
var gatewayKnown = Known(r => r["gateway"] = new JsonObject { ["host"] = "vpn.toplc.cn", ["ipv4"] = "192.0.2.1" });
var gatewayKnown = Known(r => r["gateway"] = new JsonObject { ["host"] = "vpn.example.invalid", ["ipv4"] = "192.0.2.1" });
checks["compatibility_checks_node_before_gateway_rewrite"] = Host(TailnetTransport.TryPrepare(gatewayKnown, true)!) == "100.64.0.2";
checks["compatibility_fallback_keeps_api_public_gateway"] = TailnetTransport.SameAuthorizedFallback(
TailnetTransport.TryPrepare(gatewayKnown, true)!, gatewayKnown.GetRuntimeConfigJson()) && Host(gatewayKnown.GetRuntimeConfigJson()) == "192.0.2.1";
@@ -221,7 +224,7 @@ internal static class TailnetTransportSelfTest
selected = await NodeTransportConnector.ConnectAsync(known,deniedPreference,Start,Stop,Healthy,Route,statuses.Add,()=>tick,CancellationToken.None,
allowKnownEndpoints:true, endpointProbe:(_,_,_)=>Task.FromResult(false));
checks["closed_port_skips_tailnet_start_and_stop"] = !selected && starts.SequenceEqual(new[]{"vpn002.example.invalid"}) && stops == beforeStops && probes == 0;
checks["closed_port_status_is_distinct_from_route_failure"] = statuses.Last() == "Tailscale 端口不可达,使用同一节点公网入口";
checks["ping_unreachable_status_is_distinct_from_route_failure"] = statuses.Last() == "内网 IP Ping 不通,回退域名并保持";
checks["closed_port_sets_node_cooldown"] = !deniedPreference.MayTry(known.Node.Slug,tick+1);
starts.Clear();
selected = await NodeTransportConnector.ConnectAsync(known,deniedPreference,Start,Stop,Healthy,Route,_=>{},()=>tick+1,CancellationToken.None,
@@ -283,9 +286,9 @@ internal static class TailnetTransportSelfTest
starts.Clear(); beforeStops=stops; probes=0; preflights=0; routeReads=0; diagnostics.Clear();
rebound = await NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None,
preferredTailnetConfig:prepared,requireRoute:Route,endpointProbe:(_,_,_)=>{preflights++;return Task.FromResult(true);},diagnostic:diagnostics.Add);
checks["handover_public_rechecks_authorized_tailnet"] = rebound==prepared && starts.SequenceEqual(new[]{"100.64.0.2"})
&& stops==beforeStops && preflights==1 && routeReads==1 && probes==1;
checks["handover_promotion_requires_verified_exit"] = diagnostics.Any(d=>d.Event=="rebind_selected" && d.Reason=="tailnet_verified");
checks["handover_public_never_rechecks_or_promotes_internal"] = rebound==original && starts.SequenceEqual(new[]{"vpn002.example.invalid"})
&& stops==beforeStops && preflights==0 && routeReads==0 && probes==0;
checks["handover_reports_public_choice"] = diagnostics.Any(d=>d.Event=="rebind_selected" && d.Reason=="public_ingress");
starts.Clear(); beforeStops=stops; probes=0;
rebound = await NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None,
preferredTailnetConfig:prepared,requireRoute:Route,endpointProbe:(_,_,_)=>Task.FromResult(false));
@@ -294,13 +297,21 @@ internal static class TailnetTransportSelfTest
starts.Clear(); beforeStops=stops;
rebound = await NodeTransportConnector.RebindAsync(original,null,Start,Stop,_=>Task.FromResult(false),CancellationToken.None,
preferredTailnetConfig:prepared,requireRoute:Route,endpointProbe:(_,_,_)=>Task.FromResult(true));
checks["handover_promotion_failure_same_node_cleanup_fallback"] = rebound==original
&& starts.SequenceEqual(new[]{"100.64.0.2","vpn002.example.invalid"}) && stops==beforeStops+1;
checks["handover_public_does_not_restart_internal_even_when_probe_would_succeed"] = rebound==original
&& starts.SequenceEqual(new[]{"vpn002.example.invalid"}) && stops==beforeStops;
starts.Clear();
try {
rebound = await NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None,
preferredTailnetConfig:prepared.Replace("fixture-key","different-key"),requireRoute:Route,endpointProbe:(_,_,_)=>Task.FromResult(true));
checks["handover_ignores_unused_preferred_credentials"] = rebound==original && starts.SequenceEqual(new[]{"vpn002.example.invalid"});
} catch { checks["handover_ignores_unused_preferred_credentials"] = false; }
starts.Clear();
try {
rebound = await NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None,
preferredTailnetConfig:prepared,requireRoute:Route);
checks["handover_public_needs_no_internal_probe"] = rebound==original && starts.SequenceEqual(new[]{"vpn002.example.invalid"});
} catch { checks["handover_public_needs_no_internal_probe"] = false; }
starts.Clear();
checks["handover_forged_preferred_credentials_rejected_before_start"] = await ThrowsAsync(()=>NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None,
preferredTailnetConfig:prepared.Replace("fixture-key","different-key"),requireRoute:Route,endpointProbe:(_,_,_)=>Task.FromResult(true))) && starts.Count==0;
checks["handover_promotion_without_probe_rejected"] = await ThrowsAsync(()=>NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None,
preferredTailnetConfig:prepared,requireRoute:Route)) && starts.Count==0;
checks["handover_preferred_cancellation_does_not_start_any_path"] = await ThrowsAsync(()=>NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,cancel.Token,
preferredTailnetConfig:prepared,requireRoute:Route,endpointProbe:(_,_,_)=>Task.FromResult(true))) && starts.Count==0;
@@ -358,6 +369,24 @@ internal static class TailnetTransportSelfTest
selected=await NodeTransportConnector.ConnectAsync(response,rankedPreference,Start,Stop,Healthy,Route,_=>{},()=>tick+1,CancellationToken.None);
checks["integration_public_pass_only_after_all_internal_fail"] = !selected
&& starts.SequenceEqual(new[]{"100.64.0.2","100.64.0.3","vpn002.example.invalid"});
starts.Clear();
rebound = await NodeTransportConnector.RebindAsync(prepared,original,Start,Stop,Healthy,CancellationToken.None,
endpointProbe:(_,_,_)=>Task.FromResult(false));
checks["handover_ping_failure_uses_domain_without_internal_start"] = rebound==original
&& starts.SequenceEqual(new[]{"vpn002.example.invalid"});
var privateResponse = Sample(r => {
r["connection_scope"] = "private_auxiliary"; r["config_contract"] = 3;
r["config_expires_at"] = DateTimeOffset.UtcNow.AddMinutes(2).ToString("O");
r["config"]!["outbounds"]![0] = new JsonObject {
["tag"]="proxy",["protocol"]="socks",["settings"]=new JsonObject {
["servers"]=new JsonArray(new JsonObject {["address"]="192.168.50.111",["port"]=18081}) }
};
});
var privatePreference = new TailnetPreference();
await NodeTransportConnector.ConnectAsync(privateResponse,privatePreference,(_,_)=>Task.CompletedTask,
Stop,Healthy,Route,_=>{},()=>tick,CancellationToken.None);
checks["private_ip_success_is_not_domain_fallback"] = !privatePreference.DomainOnly
&& privatePreference.MayTry("tokyo",tick+1);
var report = new { passed=checks.Values.All(x=>x), checks, simulated_transport=true,
production_network_actions=Array.Empty<string>(), note="Pure config/route models and fake start/stop/probe delegates; not a live Tailscale or release acceptance." };
File.WriteAllText(Path.Combine(AppContext.BaseDirectory,"tailnet-transport-self-test.json"),JsonSerializer.Serialize(report,new JsonSerializerOptions{WriteIndented=true}));
+96 -22
View File
@@ -5,24 +5,24 @@ namespace UCVL.VPNPlus;
// Reads only existing proxy-outbound counters; never the physical adapter.
internal sealed class TrafficChart : Control
{
private readonly Queue<(DateTimeOffset Time, double Up, double Down)> _points = new();
private readonly TrafficChartTimeline _timeline;
private TimeSpan _period = TimeSpan.FromMinutes(5);
internal int PeriodMinutes => (int)_period.TotalMinutes;
internal int PointCount => _points.Count;
internal int PointCount => _timeline.PointCount;
internal int VisiblePointCount => VisiblePoints().Length;
internal bool HasFreshSample => _timeline.HasFreshSample;
internal DateTimeOffset? LastSampleAt => _timeline.LastSampleAt;
internal DateTimeOffset TimelineEnd => _timeline.End;
internal void SetPeriodMinutes(int minutes)
{
if (minutes is not (1 or 5 or 15 or 60)) throw new ArgumentOutOfRangeException(nameof(minutes));
_period = TimeSpan.FromMinutes(minutes);
Invalidate();
}
private (DateTimeOffset Time, double Up, double Down)[] VisiblePoints()
{
var end = _points.Count == 0 ? DateTimeOffset.Now : _points.Last().Time;
return _points.Where(point => end - point.Time <= _period).ToArray();
}
internal TrafficChart()
private TrafficChartTimeline.Sample[] VisiblePoints() => _timeline.Visible(_period);
internal TrafficChart(Func<DateTimeOffset>? clock = null)
{
_timeline = new TrafficChartTimeline(clock);
DoubleBuffered = true;
SetStyle(ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.Opaque, false);
@@ -31,35 +31,109 @@ internal sealed class TrafficChart : Control
}
internal void Add(double up, double down, DateTimeOffset? time = null)
{
var at = time ?? DateTimeOffset.Now;
double Clean(double n) => double.IsFinite(n) ? Math.Max(0, n) : 0;
_points.Enqueue((at, Clean(up), Clean(down)));
// Bounded current-session samples only: never turn daily accounting
// totals into a fictitious speed curve. Changing range preserves samples.
while (_points.Count > 3600 || (_points.Count > 0 && at - _points.Peek().Time > TimeSpan.FromMinutes(60))) _points.Dequeue();
_timeline.Add(up, down, time);
Invalidate();
}
internal void Reset() { _points.Clear(); Invalidate(); }
// Called by the existing sampling timer even when the reader is busy or
// returns no counters. Neither method invents a zero-speed sample or bytes.
internal void AdvanceClock(DateTimeOffset? now = null) { _timeline.AdvanceClock(now); Invalidate(); }
internal void MarkUnavailable(DateTimeOffset? now = null) { _timeline.MarkUnavailable(now); Invalidate(); }
internal void Reset() { _timeline.Reset(); Invalidate(); }
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
_timeline.AdvanceClock();
var points = VisiblePoints();
var peak = points.Length == 0 ? 1024 : Math.Max(1024, points.Max(p => Math.Max(p.Up, p.Down)));
var chart = ChartAxis.Draw(e.Graphics, ClientRectangle, Font, DeviceDpi, peak, speed: true);
if (chart.Plot.Width < 1 || chart.Plot.Height < 1) return;
var end = points.Length == 0 ? DateTimeOffset.Now : points[^1].Time;
var end = _timeline.End;
ChartAxis.TimeLabels(e.Graphics, chart.Plot, Font, [end.Subtract(_period).ToString("HH:mm"), end.Subtract(_period / 2).ToString("HH:mm"), end.ToString("HH:mm")]);
if (points.Length == 0)
{
TextRenderer.DrawText(e.Graphics, "等待代理流量采样", Font, Rectangle.Round(chart.Plot), Brand.Muted,
TextRenderer.DrawText(e.Graphics, LastSampleAt.HasValue ? "采样暂不可用" : "等待代理流量采样", Font, Rectangle.Round(chart.Plot), Brand.Muted,
ChartAxis.PaintFlags | TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
return;
}
PointF[] Line(bool up) => points.Select(p => new PointF(
chart.Plot.Left + (float)Math.Clamp(1 - (end - p.Time).TotalSeconds / _period.TotalSeconds, 0, 1) * chart.Plot.Width,
chart.Plot.Bottom - (float)((up ? p.Up : p.Down) / chart.Maximum) * chart.Plot.Height)).ToArray();
ChartAxis.Curve(e.Graphics, Line(true), Brand.RoyalBlue, DeviceDpi, dots: points.Length == 1);
ChartAxis.Curve(e.Graphics, Line(false), Brand.Cyan, DeviceDpi, dots: points.Length == 1);
foreach (var segment in points.GroupBy(point => point.Segment))
{
var samples = segment.ToArray();
PointF[] Line(bool up) => samples.Select(p => new PointF(
chart.Plot.Left + (float)Math.Clamp(1 - (end - p.Time).TotalSeconds / _period.TotalSeconds, 0, 1) * chart.Plot.Width,
chart.Plot.Bottom - (float)((up ? p.Up : p.Down) / chart.Maximum) * chart.Plot.Height)).ToArray();
ChartAxis.Curve(e.Graphics, Line(true), Brand.RoyalBlue, DeviceDpi, dots: samples.Length == 1);
ChartAxis.Curve(e.Graphics, Line(false), Brand.Cyan, DeviceDpi, dots: samples.Length == 1);
}
if (!HasFreshSample)
TextRenderer.DrawText(e.Graphics, "采样暂不可用", Font, Rectangle.Round(chart.Plot), Brand.Muted,
ChartAxis.PaintFlags | TextFormatFlags.Right | TextFormatFlags.Top | TextFormatFlags.SingleLine);
}
}
// Pure presentation history: no proxy/adapter reads, cumulative byte totals or
// timers. An injected clock makes missing-sample behavior deterministic in tests.
internal sealed class TrafficChartTimeline
{
internal readonly record struct Sample(DateTimeOffset Time, double Up, double Down, long Segment);
internal static readonly TimeSpan MaximumSampleAge = TimeSpan.FromSeconds(15);
private static readonly TimeSpan Retention = TimeSpan.FromMinutes(60);
private readonly Queue<Sample> _points = new();
private readonly Func<DateTimeOffset> _clock;
private DateTimeOffset? _end, _lastSampleAt;
private bool _gapPending, _unavailable = true;
private long _segment;
internal TrafficChartTimeline(Func<DateTimeOffset>? clock = null) => _clock = clock ?? (() => DateTimeOffset.Now);
internal int PointCount => _points.Count;
internal DateTimeOffset End => _end ?? _clock();
internal DateTimeOffset? LastSampleAt => _lastSampleAt;
internal bool HasFreshSample => !_unavailable && _lastSampleAt is { } last && End - last <= MaximumSampleAge;
private void MoveEnd(DateTimeOffset at)
{
if (!_end.HasValue || at > _end.Value) _end = at;
while (_points.Count > 3600 || (_points.Count > 0 && End - _points.Peek().Time > Retention)) _points.Dequeue();
}
internal void AdvanceClock(DateTimeOffset? now = null)
{
MoveEnd(now ?? _clock());
if (_lastSampleAt is { } last && End - last > MaximumSampleAge)
_gapPending = _unavailable = true;
}
internal void MarkUnavailable(DateTimeOffset? now = null)
{
AdvanceClock(now);
_gapPending = _unavailable = true;
}
internal bool Add(double up, double down, DateTimeOffset? time = null)
{
var at = time ?? _clock();
if (!double.IsFinite(up) || !double.IsFinite(down) || up < 0 || down < 0)
{
MarkUnavailable(at);
return false;
}
// Late/duplicate callbacks must not move the axis backwards, inject a
// second point or turn a newer good sample into an unavailable one.
if (_lastSampleAt is { } previous && at <= previous) return false;
if (_lastSampleAt is { } last && (_gapPending || at - last > MaximumSampleAge)) _segment++;
_points.Enqueue(new Sample(at, up, down, _segment));
_lastSampleAt = at;
_gapPending = _unavailable = false;
MoveEnd(at);
return true;
}
internal Sample[] Visible(TimeSpan period) => _points.Where(point => End - point.Time <= period).ToArray();
internal void Reset()
{
_points.Clear();
_end = _lastSampleAt = null;
_gapPending = false;
_unavailable = true;
_segment = 0;
}
}
+2 -2
View File
@@ -249,7 +249,7 @@ internal static class TunConfigBuilder
}
""";
var hosts = GetProxyServerHosts(sample);
var gatewayConfig = JsonNode.Parse(OverrideProxyServerAddress(sample, "vpn.toplc.cn"))?.AsObject();
var gatewayConfig = JsonNode.Parse(OverrideProxyServerAddress(sample, "vpn.example.invalid"))?.AsObject();
var gatewayOutbound = gatewayConfig?["outbounds"]?.AsArray()[0]?.AsObject();
var gatewayServer = gatewayOutbound?["settings"]?["vnext"]?.AsArray()[0]?.AsObject();
var gatewayReality = gatewayOutbound?["streamSettings"]?["realitySettings"]?.AsObject();
@@ -259,7 +259,7 @@ internal static class TunConfigBuilder
var runtimeDnsServers = config?["dns"]?["servers"]?.AsArray();
return hosts.Count == 1
&& hosts[0] == "203.0.113.10"
&& gatewayServer?["address"]?.GetValue<string>() == "vpn.toplc.cn"
&& gatewayServer?["address"]?.GetValue<string>() == "vpn.example.invalid"
&& gatewayServer?["port"]?.GetValue<int>() == 443
&& gatewayReality?["publicKey"]?.GetValue<string>() == "legacy-key"
&& tun?["protocol"]?.GetValue<string>() == "tun"
+5 -5
View File
@@ -10,10 +10,10 @@
<ApplicationIcon>assets\zonghengjia-app-v1.ico</ApplicationIcon>
<ApplicationManifest>app.manifest</ApplicationManifest>
<ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode>
<Version>0.3.0</Version>
<AssemblyVersion>0.3.0.0</AssemblyVersion>
<FileVersion>0.3.0.0</FileVersion>
<InformationalVersion>0.3.0</InformationalVersion>
<Version>0.3.1</Version>
<AssemblyVersion>0.3.1.0</AssemblyVersion>
<FileVersion>0.3.1.0</FileVersion>
<InformationalVersion>0.3.1</InformationalVersion>
<Product>纵横家</Product>
<Company>优创未来(UCVL)</Company>
<Description>纵横家 Windows 智能网络客户端</Description>
@@ -27,7 +27,7 @@
</PropertyGroup>
<ItemGroup>
<!-- Recovery helpers and retained test snapshots are not app source. -->
<Compile Remove="build\**\*.cs;artifacts\**\*.cs;dist\**\*.cs" />
<Compile Remove="build\**\*.cs;artifacts\**\*.cs;dist\**\*.cs;obj\**\*.cs;bin\**\*.cs" />
<EmbeddedResource Include="assets\landscape-header-v1.png" LogicalName="UCVL.VPNPlus.assets.landscape-header-v1.png" />
<Content Include="assets\zonghengjia-app-logo-v1.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+26 -3
View File
@@ -7,7 +7,7 @@ namespace UCVL.VPNPlus;
internal sealed class VpnApiClient : IDisposable
{
internal const string BaseAddress = "https://vpn.toplc.cn/";
internal const string BaseAddress = "https://vpn.example.invalid/";
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNameCaseInsensitive = true,
@@ -65,6 +65,14 @@ internal sealed class VpnApiClient : IDisposable
return await GitReleaseUpdater.GetLatestAsync(cancellationToken);
}
internal async Task<NodeTrafficSnapshot> GetNodeTrafficAsync(string token, CancellationToken cancellationToken)
{
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
deadline.CancelAfter(TimeSpan.FromSeconds(3));
using var request = AuthorizedRequest(HttpMethod.Get, "api/v1/client/node-traffic/", token);
return await SendAsync<NodeTrafficSnapshot>(request, deadline.Token, maximumBodyBytes: 32 * 1024);
}
internal async Task<ConfigResponse> GetConfigAsync(string token, string nodeSlug, string routeMode, CancellationToken cancellationToken, IEnumerable<string>? excluded = null)
{
var url = $"api/v1/client/config/?node={Uri.EscapeDataString(nodeSlug)}&route={Uri.EscapeDataString(routeMode)}";
@@ -126,7 +134,7 @@ internal sealed class VpnApiClient : IDisposable
return request;
}
private async Task<T> SendAsync<T>(HttpRequestMessage request, CancellationToken cancellationToken)
private async Task<T> SendAsync<T>(HttpRequestMessage request, CancellationToken cancellationToken, int? maximumBodyBytes = null)
{
var uri = request.RequestUri ?? throw new InvalidOperationException("管理接口地址为空。");
PlatformBootstrapTransport.ValidateRequest(uri.IsAbsoluteUri ? uri : new Uri(new Uri(BaseAddress), uri), request.Headers.Host);
@@ -136,7 +144,22 @@ internal sealed class VpnApiClient : IDisposable
deadline.CancelAfter(TimeSpan.FromSeconds(20));
cancellationToken = deadline.Token;
using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
var payload = await response.Content.ReadAsStringAsync(cancellationToken);
string payload;
if (maximumBodyBytes is { } maximum)
{
if (response.Content.Headers.ContentLength > maximum) throw new IOException("监控响应过大。");
using var body = new MemoryStream();
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
var buffer = new byte[4096];
int read;
while ((read = await stream.ReadAsync(buffer, cancellationToken)) != 0)
{
if (body.Length + read > maximum) throw new IOException("监控响应过大。");
body.Write(buffer, 0, read);
}
payload = new UTF8Encoding(false, true).GetString(body.ToArray());
}
else payload = await response.Content.ReadAsStringAsync(cancellationToken);
if (!response.IsSuccessStatusCode)
{
string message;
+36 -2
View File
@@ -93,9 +93,13 @@ internal static class WindowChromeSelfTest
// Synthetic close-to-tray contract. The real MainForm branch is
// exercised separately by existing StartupSelfTest --uiOnly mode.
form.FormClosing += (_, e) => { closeEvents++; e.Cancel = true; form.Hide(); };
FitFixtureHeaderToDpi(form, header);
form.Show();
var initiallyReady = WaitForState(form, FormWindowState.Normal, "initial_show");
chrome.LayoutButtons();
var blankHeaderPoint = BlankFixtureHeaderPoint(form, header);
geometry["fixture_dpi_and_caption"] = $"dpi={form.DeviceDpi}; header={header.ClientRectangle}; button={chrome.MinimizeButton.Bounds}; blank={blankHeaderPoint}";
checks["fixture_header_contains_entire_dpi_scaled_caption"] = header.ClientRectangle.Contains(chrome.MinimizeButton.Bounds);
checks["client_canvas_replaces_entire_caption"] = initiallyReady && form.RectangleToScreen(form.ClientRectangle) == form.Bounds;
checks["native_sizable_style_preserved"] = (ChromeNative.GetWindowLongPtr(form.Handle, ChromeNative.GwlStyle).ToInt64() & ChromeNative.NativeFrameStyles) == ChromeNative.NativeFrameStyles;
checks["native_caption_style_absent"] = NativeCaptionAbsent(form);
@@ -105,7 +109,7 @@ internal static class WindowChromeSelfTest
ChromeNative.SetWindowLongPtr(form.Handle, ChromeNative.GwlStyle, (IntPtr)(initialStyle | ChromeNative.WsCaption));
checks["native_caption_cannot_return_on_style_refresh"] = NativeCaptionAbsent(form);
checks["system_menu_available_for_alt_space"] = ChromeNative.GetSystemMenu(form.Handle, false) != IntPtr.Zero;
checks["caption_blank_native_drag"] = Hit(form, header.PointToScreen(new Point(240, 20))) == ChromeNative.HtCaption;
checks["caption_blank_native_drag"] = Hit(form, header.PointToScreen(blankHeaderPoint)) == ChromeNative.HtCaption;
checks["caption_label_native_drag"] = Hit(form, title.PointToScreen(new Point(8, 8))) == ChromeNative.HtCaption;
checks["label_forwards_hit_to_form"] = Hit(title, title.PointToScreen(new Point(8, 8))) == ChromeNative.HtTransparent;
checks["combo_keeps_client_input"] = Hit(form, combo.PointToScreen(new Point(10, 10))) == ChromeNative.HtClient && Hit(combo, combo.PointToScreen(new Point(10, 10))) != ChromeNative.HtTransparent;
@@ -183,7 +187,7 @@ internal static class WindowChromeSelfTest
ChromeNative.SendMessage(form.Handle, ChromeNative.WmSysCommand, (IntPtr)ChromeNative.ScMaximize, IntPtr.Zero);
checks["system_maximize_blocked"] = WaitForState(form, FormWindowState.Normal, "blocked_maximize", restoreBounds);
ChromeNative.SendMessage(form.Handle, 0xa3 /* WM_NCLBUTTONDBLCLK */, (IntPtr)ChromeNative.HtCaption,
Pack(header.PointToScreen(new Point(240, 20))));
Pack(header.PointToScreen(blankHeaderPoint)));
checks["caption_double_click_does_not_maximize"] = WaitForState(form, FormWindowState.Normal, "blocked_double_click", restoreBounds);
chrome.MinimizeButton.PerformClick();
var minimized = WaitForState(form, FormWindowState.Minimized, "minimize_button");
@@ -248,10 +252,12 @@ internal static class WindowChromeSelfTest
var closeEvents = 0;
form.FormClosing += (_, e) => { closeEvents++; e.Cancel = true; };
using var chrome = new WindowChrome(form, header, () => exitRequests++);
FitFixtureHeaderToDpi(form, header);
form.Show();
var bounds = form.Bounds;
checks["mode_fixture_initially_ready"] = waitForState(form, FormWindowState.Normal, "mode_initial", bounds);
var button = chrome.MinimizeButton;
checks["login_fixture_header_contains_entire_dpi_scaled_caption"] = header.ClientRectangle.Contains(button.Bounds);
var buttonBounds = button.Bounds;
string ToolTipText() => ((ToolTip)typeof(WindowChrome).GetField("_toolTip",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.GetValue(chrome)!).GetToolTip(button) ?? "";
@@ -343,6 +349,34 @@ internal static class WindowChromeSelfTest
checks["dashboard_explicit_menu_exit_preserved"] = exitRequests == 5 && closeEvents == 0;
}
private static void FitFixtureHeaderToDpi(Form form, Panel header)
{
// Get the actual owned HWND's monitor DPI before sizing its synthetic
// header. At 350%, the real caption is 105px high plus a 21px inset;
// the old fixed 80/100px fixture clipped its background, not the app.
_ = form.Handle;
var minimum = (int)Math.Ceiling((WindowChrome.CaptionHeight + 12) * form.DeviceDpi / 96.0);
header.Height = Math.Max(header.Height, minimum);
form.PerformLayout();
}
private static Point BlankFixtureHeaderPoint(Form form, Panel header)
{
var border = Math.Max(1, (int)Math.Round(6 * form.DeviceDpi / 96.0));
// Choose an actually empty client point outside the resize band. A
// fixed y=20 becomes HTTOP when the current monitor DPI reaches 336.
for (var y = border + 2; y < header.ClientSize.Height - border; y++)
for (var x = border + 2; x < header.ClientSize.Width - border; x++)
{
var point = new Point(x, y);
if (header.GetChildAtPoint(point, GetChildAtPointSkip.Invisible) is not null) continue;
var inForm = form.PointToClient(header.PointToScreen(point));
if (ChromeGeometry.ResizeHitTest(form.ClientSize, inForm, border, true) == ChromeNative.HtClient)
return point;
}
throw new InvalidOperationException("Owned fixture has no blank header point outside its resize band.");
}
private static int Distance(Color a, Color b) => Math.Abs(a.R - b.R) + Math.Abs(a.G - b.G) + Math.Abs(a.B - b.B);
internal sealed record MinimizeInputProbe(bool Mouse, bool PointTargetsButton, bool CapturedAfterDown,
int Clicks, bool CapturedDuringClick, bool ManagedMinimized, bool NativeMinimized, bool Visible,
+4 -4
View File
@@ -26,9 +26,9 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
private readonly string _xrayDirectory = Path.Combine(AppContext.BaseDirectory, "xray");
private string? _baseConfigJson;
private string? _tailnetFallbackConfigJson;
// Retain only the authenticated in-memory alternative. A physical-network
// recovery already has to restart the core, so it can recheck the overlay
// instead of permanently retaining an earlier public fallback.
// Retain the authenticated alternative for compatibility/identity checks.
// A public fallback is sticky: automatic physical-network recovery must
// never promote it to this cached internal alternative.
private string? _preferredTailnetConfigJson;
private string? _tailnetInterfaceName;
internal bool UsesTailnet => _baseConfigJson is not null && TailnetTransport.Address(_baseConfigJson) is not null;
@@ -387,7 +387,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
{
try
{
var addresses = await Dns.GetHostAddressesAsync("vpn.toplc.cn", cancellationToken);
var addresses = await Dns.GetHostAddressesAsync("vpn.example.invalid", cancellationToken);
if (addresses.Any(address => address.AddressFamily == AddressFamily.InterNetwork))
{
AppPaths.WriteLog($"Windows DNS 已就绪({started.ElapsedMilliseconds} ms)。");
@@ -212,7 +212,7 @@ function Get-PIBRegistration($Profile) {
function Get-PIBCandidateRegistration($Profile,[string]$Version) {
$p=Assert-PIBProfile $Profile
$data=@((Join-Path $p.Target 'VPNPlus.exe'),$p.Target,'优创⁺纵横家',(Join-Path $p.Target 'VPNPlus.exe'),$Version,
'优创未来(UCVL)','https://vpn.toplc.cn/',('"'+(Join-Path $p.Target 'Uninstall.exe')+'"'),1,1)
'优创未来(UCVL)','https://vpn.example.invalid/',('"'+(Join-Path $p.Target 'Uninstall.exe')+'"'),1,1)
return [ordered]@{Keys=@($true,$true);Values=@(for($i=0;$i -lt 10;$i++){[ordered]@{Kind=$(if($i -lt 8){'String'}else{'DWord'});Data=$data[$i]}})}
}
function Get-PIBComponents($Manifest) {
+1 -1
View File
@@ -29,7 +29,7 @@ RequestExecutionLevel admin
!ifndef APP_SOURCE_DIR
!define APP_SOURCE_DIR "${__FILEDIR__}\..\dist\app"
!endif
!define PRODUCT_WEB "https://vpn.toplc.cn/"
!define PRODUCT_WEB "https://vpn.example.invalid/"
!define PRODUCT_DIR_REGKEY "Software\Microsoft\Windows\CurrentVersion\App Paths\VPNPlus.exe"
!define PRODUCT_UNINST_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\UCVL.VPNPlus"
+1 -1
View File
@@ -20,7 +20,7 @@
保留三个节点身份及已有认证、流量和代理逻辑。新连接优先检测可用内部入口,按响应排序;内部入口不可用时回退同节点域名公网。实际通过 Tailscale 代理验证才显示“VPN002 + Tailscale”或“VPN003 + Tailscale”,公网连接不加后缀,不以 Ping 通冒充代理可用,也不因排序变化迁移健康连接。
公开源码示例入口(非生产配置)为 VPN002(东京)100.64.0.2:10803、VPN003(硅谷)100.64.0.3:11083;济南(博翠明湖)内部入口为 GL 100.64.0.4:18081,域名入口为 vpn.toplc.cn:11080,GL 仅转发手机 192.168.50.170:18081,实际出口仍由手机夜猫处理。这里仅记录公开导出的示例,不表示可实际连接。保留旧后台省略字段的窄范围兼容,不增加账号或绕过权限,显式禁用字段继续生效。
公开源码示例入口(非生产配置)为 VPN002(东京)100.64.0.2:10803、VPN003(硅谷)100.64.0.3:11083;济南(博翠明湖)内部入口为 GL 100.64.0.4:18081,域名入口为 vpn.example.invalid:11080,GL 仅转发手机 192.168.50.170:18081,实际出口仍由手机夜猫处理。这里仅记录公开导出的示例,不表示可实际连接。保留旧后台省略字段的窄范围兼容,不增加账号或绕过权限,显式禁用字段继续生效。
## 验收范围
+13
View File
@@ -0,0 +1,13 @@
# 纵横家 Windows 0.3.1
正式、非强制更新。沿用现有账号和代理授权,不启停、登录或配置 Tailscale。
- 连接时先 Ping 已授权代理的内网 IP,能通则优先按响应时间使用内网入口;不通则回退同一节点的公网/域名入口。
- 回退后,本次连接的后台恢复、网络切换和自动重试保持公网入口,不因内网恢复再自动切回;手动断开后重新连接才重新选择。
- Ping 仅用于入口可达性选择;代理凭据、服务器身份、授权撤销和代理出口验证继续生效。禁用 ICMP 的内网入口会被跳过。
- 公网与 Tailscale 当前速率分开,监控固定高度;两台服务器整机 WAN 监控与个人代理流量分开。无有效服务器样本时显示不可用,不显示伪实时数值。
- 图表刷新、缺样本断线段及背景缓存优化;保留现有透明山水界面、托盘及退出行为。
安装包未进行 Authenticode 签名,更新需要 Windows 管理员授权。
本次验证包含同包离线回归、合成界面和隔离文件升级/恢复;不等同于当前用户生产覆盖安装、实际 TUN/UDP 共存或长期业务连接验收。
共享账户限速执行层仍未启用;本版本不宣称已实现两服务器共享限速或全体用户实测提速。