Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c4f43cca5c | |||
| ac40dd3a6c | |||
| 23a87387b8 |
@@ -1055,5 +1055,169 @@
|
||||
],
|
||||
"SourceOnly": true,
|
||||
"Version": "0.3.5"
|
||||
},
|
||||
"Windows036RuntimeRepairDelta": {
|
||||
"CandidateSha256": "001e2c92793d8508eed0eb5bfa82cdb51a243ac8aa7d2925e265f90c6454966e",
|
||||
"ExampleEndpointChanges": [
|
||||
{
|
||||
"Count": 2,
|
||||
"Path": "windows/ClientRuntimeSelfTest.cs"
|
||||
},
|
||||
{
|
||||
"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/TransportPlanSelfTest.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": 1,
|
||||
"Path": "windows/KnownTailnetEndpoints.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": 3,
|
||||
"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/KnownTailnetEndpoints.cs",
|
||||
"RuleSet": "windows-runtime-repair-20261106"
|
||||
},
|
||||
{
|
||||
"Count": 3,
|
||||
"Path": "windows/TailnetTransportSelfTest.cs",
|
||||
"RuleSet": "windows-runtime-repair-20261106"
|
||||
}
|
||||
],
|
||||
"FrozenSha256": "521d3065e0d8a9e6417dd721d64b16c12032edec7fb2a6cf60e0a05314c961f2",
|
||||
"Omitted": [
|
||||
"windows/assets/login-cloud-scene-v1.jpg"
|
||||
],
|
||||
"OptionalUnlicensedSceneRemainsOmitted": true,
|
||||
"OriginalAcceptanceTransferred": false,
|
||||
"OriginalSourceManifestSha256": "11d72a8778a76f90597aafec569bdd6d3a3f8e549ef8d09c9e70411ce916d58e",
|
||||
"OtherComponentsModified": false,
|
||||
"PrivateHistoryIncluded": false,
|
||||
"ProductionAccepted": false,
|
||||
"PublicBaseCommit": "23a87387b87aa82ffdafaf5cf87b4495d51207df",
|
||||
"PublicDownloadDomainsRetained": [
|
||||
"pro.ucvl.cn"
|
||||
],
|
||||
"SourceOnly": true,
|
||||
"Version": "0.3.6"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# 纵横家开源源码
|
||||
|
||||
此仓库是无私有 Git 历史的清洁源码快照:Windows 0.3.5、Django 后台及 iPhone/iPad 1.0.2。公司自有代码按 MIT 开源;第三方组件遵守原许可,公司商标及 Logo 不在 MIT 授权范围。Android 保留原 GPL-3.0 公开仓库,不重复拷贝或改换许可。
|
||||
此仓库是无私有 Git 历史的清洁源码快照:Windows 0.3.6、Django 后台及 iPhone/iPad 1.0.2。公司自有代码按 MIT 开源;第三方组件遵守原许可,公司商标及 Logo 不在 MIT 授权范围。Android 保留原 GPL-3.0 公开仓库,不重复拷贝或改换许可。
|
||||
|
||||
| 目录 | 内容与状态 |
|
||||
| --- | --- |
|
||||
|
||||
+51
-14
@@ -4,7 +4,7 @@
|
||||
"ExportDiffersFromOriginalCandidates": true,
|
||||
"FilesBeforeProvenanceAndAudit": {
|
||||
"LICENSE": "b7e94910b8dc377b0a05ccde3c6e5941838dfc15c9dd790078d11728205b524e",
|
||||
"README.md": "0a94bef78ae64402abf281075d68dcba5aafca466d284bb5dd88c492f9924834",
|
||||
"README.md": "1e974eb4f09d4bf219b8840ae7826a0d34423ddcfe1ed87932327ad35f29071b",
|
||||
"SECURITY.md": "34e56cd9b8f6aa5fee45921c6eb831a542e05e76e41850fc31c44e09de088b3c",
|
||||
"THIRD_PARTY_NOTICES.md": "8c862f2f6b71440616a887e6deb7444a1262cf7d9f144208cc04041c3f9a3371",
|
||||
"android/README.md": "bb4387da9a055e97f33bb29a883c543e0938fa858df3fd744abc80553a5ec65c",
|
||||
@@ -99,6 +99,27 @@
|
||||
"backend/control/views.py": "28f1cd84e29bfe7d311a7af52c4a87f23cffdee6a735e5b4ca7e185293c24a59",
|
||||
"backend/control/vpn_ai.py": "091c1379a8780c4804a40fbc6d6e0d076b9009c5fe3eba752926c7e164f5b19b",
|
||||
"backend/docker/entrypoint.sh": "1ccee7b022efc9f7ef99f0703a46e235a4a8ee085f113eaea74c63b3063ac33b",
|
||||
"backend/host-traffic-sampler/LICENSE": "b7e94910b8dc377b0a05ccde3c6e5941838dfc15c9dd790078d11728205b524e",
|
||||
"backend/host-traffic-sampler/README.md": "8103d07ab651832a1529669f65b12cecc0a5abaca9b95e948caed9ff3148dfcd",
|
||||
"backend/host-traffic-sampler/deploy_host_traffic_sampler.sh": "910e7234b6913e22b7e4aeb4b7ac7e74831e5038af1700e33073f42c14b0fe88",
|
||||
"backend/host-traffic-sampler/host-traffic-contract-fixture.json": "f873e3f62982783fc29cc4f3bc9d298f3420a9e67bae085aeb4e6eeafed58696",
|
||||
"backend/host-traffic-sampler/host_traffic_sampler.py": "d4b7f02ec39092cfc141e8275019c7b3b7458b6bf7096fe511742df9113bcab3",
|
||||
"backend/host-traffic-sampler/test_host_traffic_sampler.py": "0c1cb6cf306ed16976781b614ff27203a06bdb6eb20fa734c3681c9a4f5a3023",
|
||||
"backend/host-traffic-sampler/toplc-vpn-host-traffic.service": "f2ba0a79822457511717c2514ac7988d93d01bf71a39c027fd8267ecf6f8da44",
|
||||
"backend/host-traffic-standalone-20261106-r2/LICENSE": "b7e94910b8dc377b0a05ccde3c6e5941838dfc15c9dd790078d11728205b524e",
|
||||
"backend/host-traffic-standalone-20261106-r2/README.md": "275932318caa6ef5c69bdaeb12ec84f8f0b9a06aa3ae472cf70c9727980bf175",
|
||||
"backend/host-traffic-standalone-20261106-r2/SOURCE-PROVENANCE.json": "71fab3c4dfc25171f2503ed262184359b8cea38a5b8e6716f1ffc608d09a134f",
|
||||
"backend/host-traffic-standalone-20261106-r2/candidate-manifest.json": "c7b252a860af93f35c6db44da15073dee50cbce5ea23be9cf29d9949e5fdfc62",
|
||||
"backend/host-traffic-standalone-20261106-r2/control/host_traffic.py": "c66421de2fbb74ab3b20ca771f6e2463737163eb6e245d56cc3875053e696d03",
|
||||
"backend/host-traffic-standalone-20261106-r2/docker-compose.host-traffic-auth-r2.yml": "59a410949dd7900906aa6d6693a40759a90ddd23d34a7686b00715010afa5379",
|
||||
"backend/host-traffic-standalone-20261106-r2/tests/run_auth_regression.py": "4f2d8d0ea6be83fd177e3a0f2133cb3255653df2f43bc70af6b4e31b2894805f",
|
||||
"backend/host-traffic-standalone-20261106/LICENSE": "b7e94910b8dc377b0a05ccde3c6e5941838dfc15c9dd790078d11728205b524e",
|
||||
"backend/host-traffic-standalone-20261106/README.md": "ffe1a73fcffcbc9bc137f8215b035887bfa2de00dc05bde53b2a91e52684f393",
|
||||
"backend/host-traffic-standalone-20261106/control/host_traffic.py": "a63b10ba3c6ca4b465cd77e11c868df2b9876ab2b10ec358e1d5ee37d99fee12",
|
||||
"backend/host-traffic-standalone-20261106/control/host_traffic_store.py": "c5a6a986208879417ac51bb4b395794e1e0a235cac34f609a572804eb90091b8",
|
||||
"backend/host-traffic-standalone-20261106/control/urls.py": "4f055b0de4d6a7593cbf00db0bc15c8f8e8644afa4618bebca79c738ac916002",
|
||||
"backend/host-traffic-standalone-20261106/docker-compose.host-traffic.yml": "990656d4044c02106917479490e2619cccd1097dda65be8b75f1f84e570e60c6",
|
||||
"backend/host-traffic-standalone-20261106/tests/run_tests.py": "715f80bfe11643d4b01b84c09d02b13eb5d371680a4ddd0cee23c463150d9bab",
|
||||
"backend/manage.py": "21f021f4b8c848bb2df0b30af032945e47da34ebe0fb6beed4149356189d1a9d",
|
||||
"backend/requirements.txt": "fb0d4a17abb80eb2abf467346b3245d3b8fd83a2c6bebc9a08784cdc0fa19667",
|
||||
"backend/static/brand/README.md": "95d2193ccd5ce6e325eed8cc3e9763c9bf85ae545785504ab400ada705e7194e",
|
||||
@@ -183,8 +204,10 @@
|
||||
"windows/AppPaths.cs": "2bac68512acfb68b4f3dad0d30c9ee17eb6f576eeb73c6a453501d4ea184488e",
|
||||
"windows/Brand.cs": "621a1c5b75880cbf4f88b482dc58bdd3c98e0f4d156bf816d23d63d48e199bca",
|
||||
"windows/ChartFreshnessSelfTest.cs": "4af3f37b14296fc34097f5708f8f0f78fb1683c1b091459091c425a11c500a62",
|
||||
"windows/ClientRuntime.cs": "6b1babd9cbe4cafe463205905d90a83ce9180b8e43e278b9b47fb9ec7eecd03b",
|
||||
"windows/ClientRuntimeSelfTest.cs": "9677ffbb300f5b73b64290339d5a8abb29c2c0edfb586e3da6cea03f97ad713f",
|
||||
"windows/ClientShutdownScope.cs": "f5944b57ccb4616dbd32ee2952b56dd0c9feccb7c556d8954092c88354a78d41",
|
||||
"windows/ClientUpdater.cs": "b218513dc57b8513eb749aeab093e39911428a07f05363ae349555d22e53e4b8",
|
||||
"windows/ClientUpdater.cs": "6c6265bf7946e4d1323d6ff94596409b3281ed396376263aaff22cf223c53a42",
|
||||
"windows/ConnectionAcceptanceTrace.cs": "c9efd15e19672a5ac3b4b807c96a3de3db3ff2fd373e13494a548df51fecdd9a",
|
||||
"windows/ConnectionAuthorizationLease.cs": "3edbd5123c051c797c488b49bcd7204d8c1a0c5a0743bfec95ffa4ab0bdd9bfc",
|
||||
"windows/ConnectionAuthorizationSelfTest.cs": "d747ac77ef353a991fd50ae3f2229e063d27ede7b6e588d2e17a41a06b7abe90",
|
||||
@@ -211,7 +234,7 @@
|
||||
"windows/InstallationSelfTest.cs": "03cb0d797c4eeb5a0d44548d844e46f53e8943928c1f118ed6b5fed948eaf298",
|
||||
"windows/InstallationTransaction.cs": "319d379052bb8633c77b54012862afa8e2b9fabbb50bce647332298eb3915ac9",
|
||||
"windows/InstallerGuardianGate.cs": "416c5560d1fb413f02f0b0a924fb4be922652a601269c056f31c93f155c0014f",
|
||||
"windows/KnownTailnetEndpoints.cs": "f887bb90dd0e054dd295931d7f289f13067f50cbba89229fa5b4b36efb27fbcf",
|
||||
"windows/KnownTailnetEndpoints.cs": "3ee3b26955bbd14443c2d63bb26adf7b41a94908e0e60f2f8007c4046b752b16",
|
||||
"windows/LICENSE": "b7e94910b8dc377b0a05ccde3c6e5941838dfc15c9dd790078d11728205b524e",
|
||||
"windows/LearningExpirySoakSelfTest.cs": "c27890114e6597236ce407afb67f48ddd4f83b10cec3219d64e228f10309d23a",
|
||||
"windows/LearningMatrixSelfTest.cs": "edb37d73f3db2e2722d49f92cf141e1b13275c76bdfadf36ab65eacf1d83d8ec",
|
||||
@@ -225,12 +248,12 @@
|
||||
"windows/MainForm.Chrome.cs": "30dc6520a44a5120c78c472c9fb053e2e4dea8e254b5531d04a5342964969c7a",
|
||||
"windows/MainForm.Compact.cs": "2e2835ce952be24fdbe711032aebfe7f046e7c0d1967204d2e9981d9e694d6e1",
|
||||
"windows/MainForm.Dashboard.cs": "46edae6d3412cee5369287ce67e1951867f728ee0a8f469879287e4c5ebd064b",
|
||||
"windows/MainForm.Handover.cs": "4a914f4de335331f1f9d2397407328f17ae372e9119329e534af218555dc92e6",
|
||||
"windows/MainForm.NextGeneration.cs": "5a1c21e02e304a5135b66160855aba5961d5da7da68041ff1b79be9de4a41916",
|
||||
"windows/MainForm.Handover.cs": "7c661ddc14e42d33c6659aefff127d1ec0d2e0f1110eeab8ac7d9b7b9e30e94b",
|
||||
"windows/MainForm.NextGeneration.cs": "e2e74727e20f6054c2b592aa039224489f4458c7b8ae0b9f3d26194106cf70c1",
|
||||
"windows/MainForm.Selection.cs": "71d3884eb6535b1c8095379585a7479c5d7dd35d00e59da4dabfa673557f17fa",
|
||||
"windows/MainForm.TailnetTraffic.cs": "bc48728563f163cc8553b288bcccd71e7d756f8beb11c13cb486652024c4b8d4",
|
||||
"windows/MainForm.TransportSelection.cs": "7e7bf74f16cb902b71da5a13117db06e9cdf4ea6121511a5ebceaf017bd1f919",
|
||||
"windows/MainForm.cs": "d515ae6f05f992789b63132a91141dbb6ea50e3d794b86c8174da1396b746687",
|
||||
"windows/MainForm.cs": "924c7989a962b66555de1bff3727b0d0aaa9c21770b7d491c333b32b4c874dc5",
|
||||
"windows/NOTICE.md": "8c862f2f6b71440616a887e6deb7444a1262cf7d9f144208cc04041c3f9a3371",
|
||||
"windows/NetworkHandover.cs": "b43548be0051cf92dfd332e537951e4b5083f2a123be8021994513bbc3748d46",
|
||||
"windows/NetworkHandoverSelfTest.cs": "681d0154dc0aa5f49d7ce1f3088b465eea3ed82571b464951df8d4c89cecdf73",
|
||||
@@ -250,7 +273,7 @@
|
||||
"windows/NodeTrafficOneSecondSelfTest.cs": "640dc4091dbd0ac3d0b900b49e44d2876b8b1250461a652f50dbfbe4e007f78d",
|
||||
"windows/NodeTrafficRepaintSelfTest.cs": "06f359e55cc35c73cf53443ff452d57c585c7214ced8f84a9b9e385c2e699bf3",
|
||||
"windows/NodeTrafficSelfTest.cs": "284086275fbb7f81dbcbff2c7267379402c84cb2e4325658946520cf9b9b518d",
|
||||
"windows/NodeTransportConnector.cs": "91d53471f35470fc9a4578e2819863e56a790cda62a7dbfe891a71149d2386e1",
|
||||
"windows/NodeTransportConnector.cs": "a45a720a9afbf9b25601f4b484cec67f8cf945176a035385379d767183968b5d",
|
||||
"windows/PhysicalUplink.cs": "b0a0eca6b9f724972d0e445c2dc352326ea4d7357317b98639972d60dadc2e63",
|
||||
"windows/PlatformBootstrapTransport.cs": "0eef4a4272449c0e2adfac2e4652bd9cff9c1b2bc11011ca2049dde2f97e4e2b",
|
||||
"windows/PlatformBootstrapTransportSelfTest.cs": "59177ceb52391fb27f04599e138f49a1c461ad283bb930bffc4bcefa663ab23f",
|
||||
@@ -258,12 +281,12 @@
|
||||
"windows/PrivateAuxiliaryRoutingSelfTest.cs": "8b2e867f562017e680def8f74c7fba972404442816abae7bf54fcab5d47339df",
|
||||
"windows/PrivateAuxiliaryRuntime.cs": "dcfb406508e3d7e9a9163163cfe5e2724a6955a18ae4604e2d9f890da61308cf",
|
||||
"windows/PrivateTransportProbe.cs": "e29e9bd0180a37bdcecf7104fde5069be799aca92b747881d0485a62d382d9b3",
|
||||
"windows/Program.cs": "921dbd445f0461cfa7910961577c2ba735bb4b8903011e75435392c5ef16473c",
|
||||
"windows/Program.cs": "c530738bc80c6da198dcf51615773793a71eb780b1c7f3389eb8a0f6fadf08a0",
|
||||
"windows/ProxyDnsPolicy.cs": "997e2e922ad43956932c1bd0a6da3457bc308ee723f4f77ff8e52aa23fa954c0",
|
||||
"windows/ProxyProbe.cs": "5d27b5a6c6b192a0c0f3ec4637c5a876a71130497af57f7cb4a04ab4735ca1ec",
|
||||
"windows/PublicTailnetSelection.cs": "68b6dd3d5c77c3253046f9b90e22742c1f2852e07d07157daa296512370fada7",
|
||||
"windows/PublicTailnetSelectionSelfTest.cs": "7b5e7352fe4529e01ce537d488a5cfcc8f5259f98bbe307846cb36a7144cacac",
|
||||
"windows/README.md": "336e690f3b013f36baaca67bcbb70e4eab1c72b38e6084941230e582d7c58be2",
|
||||
"windows/README.md": "18c4125a27f5d63fbee3dab9bab099ad4b9cd863e639bb01ee6ec2fedc42c3bc",
|
||||
"windows/ReplacementContinuitySelfTest.cs": "107878ab2b367f1812377c0b209f6d620da390091c3882e4be53a48e517d86a1",
|
||||
"windows/RouteLeaseSelfTest.cs": "6189c66b9f66c58bed26de4441c58a9ec02b67257bfa04ed66d702acfcd054d9",
|
||||
"windows/RoutingRuleBatches.cs": "9997bfa766fffe7bed7352f307c1f6f118a9be9aa86653eaefae3b2bdaa26c1e",
|
||||
@@ -283,7 +306,7 @@
|
||||
"windows/TailnetReadinessSelfTest.cs": "92ba7abec5fa3f98550dd9460fb2c87b58cbdc4a55efd9f4b58ca8c5c16f67e7",
|
||||
"windows/TailnetTransport.cs": "c93769b845090f244eeedef2b49afa4bea500af809a995ffdcaf8c314ffb84eb",
|
||||
"windows/TailnetTransportProbe.cs": "c71a0d946cbefb2713e0b564ea95ae99cbd70f0ec19c8cfc416a12e16589f99a",
|
||||
"windows/TailnetTransportSelfTest.cs": "8ace8cc2f443c1ce576bbb9471cb46f107ac28f999090baa30431412d8a263f3",
|
||||
"windows/TailnetTransportSelfTest.cs": "0a61716193d185c0b86819c29813625e6c5ab7d28df0c700b368e708c12607d7",
|
||||
"windows/TokenStore.cs": "e07cf7d1a4cf7a1bba871c19e50b9d6355cb8c1546657346b0256c8215fed8bb",
|
||||
"windows/TrafficChart.cs": "0412f5d45d33ee95f0d0c80ea57a53e4708ff549e20373596035a47c7a0d1eb0",
|
||||
"windows/TransportPlan.cs": "f49b780fd5095cd494c040582d3cf1607548d1eb0572490bfe588dc55521a772",
|
||||
@@ -292,14 +315,14 @@
|
||||
"windows/TunConnectivitySelfTest.cs": "a7d7aff1d03e45dff921807cbfb8f83b5013c9df5c7e06b6662d84a8686b2f86",
|
||||
"windows/TunRouting.cs": "c6b3e1070a0ba0a3c42dbd12becba55404e540d06aba03cb1cc1053fa426a4c1",
|
||||
"windows/UpdateProgressForm.cs": "25286b76a235635704dbe8831367141939d063153d0828ee375f1c71d461f041",
|
||||
"windows/UpdateSelfTest.cs": "453165bb611efb8db0d8a8c9ea13f3553e0047aa22b838c43096e3d83fe18771",
|
||||
"windows/UpdateSelfTest.cs": "fcb73067484cad50618f0ce93e087fa36a1cc3b40a10173d26a2b0230b0b77e1",
|
||||
"windows/UpdateStreamSelfTest.cs": "ad059016c0197f33582b1969ab3280c5b9589a28d659613b3e97ce4a357d38c1",
|
||||
"windows/UsageHistorySeries.cs": "9e7515ceede1899e06116352de79edd6252c921048bcae9958bf9358d93b3069",
|
||||
"windows/VPNPlus.csproj": "c81156e80e7d5ceac088c8e167ce3e3f33cc8cdf61a125b905a6761ef2e43221",
|
||||
"windows/VPNPlus.csproj": "e4d0b0715a809053b0b1c8a35d6994ab05784334fbf65f4dfacf087697134812",
|
||||
"windows/VpnApiClient.cs": "5bb824cd89d4d8fa251f10a66f4c284c58118b773f877aa07c9700fe271216a8",
|
||||
"windows/WindowChrome.cs": "0eceea0879e792b8ae83a74eaf5658d4a7be6a798fbdb026ff8d19fa9aa6af2c",
|
||||
"windows/WindowChromeSelfTest.cs": "c17dd805a0102d12b71a3e32c77ceeb45e303e08612de5d3c5259c78327532be",
|
||||
"windows/XrayManager.cs": "8c87c1d84e42f00528da52ecbe9a0a4ecded445ac50e83442c187536af9555a5",
|
||||
"windows/XrayManager.cs": "38d9582cd30d430aa2f1cc42494f4cbdb2cb6190e96721fa3493ec6f828b6b36",
|
||||
"windows/XrayRoutingUpdater.cs": "91fd2b5db25477dbe4de7118faef79f9c51f9a8a3dd86e8b26c676092de3bca5",
|
||||
"windows/app.manifest": "4c9a2e8e2056c3bb0ae45a5f7b2e223298ee683a82b70ba4910e17f5728cf5b6",
|
||||
"windows/assets/company-logo-original.png": "04cf7f754a5353b96cddbed4a57a557154342c190a1785487e3bfb36cab04163",
|
||||
@@ -343,7 +366,8 @@
|
||||
"windows/release/RELEASE-NOTES-0.3.2.md": "29f2030b0be583a541dc0289ee9916d42156cf3bbd823bd5cf7867f097fb2abd",
|
||||
"windows/release/RELEASE-NOTES-0.3.3.md": "18e1f04a925b82668813cb7bde18d29790fa6218d6726887b0ad3cabec253dea",
|
||||
"windows/release/RELEASE-NOTES-0.3.4.md": "10f0a3edd111932ea92e25581208ac527990b515ee1c73bbd7bd4acba734936f",
|
||||
"windows/release/RELEASE-NOTES-0.3.5.md": "4b92799fbd145660732a1748828d03f0defe179709bc77b7e13e9de693ccc304"
|
||||
"windows/release/RELEASE-NOTES-0.3.5.md": "4b92799fbd145660732a1748828d03f0defe179709bc77b7e13e9de693ccc304",
|
||||
"windows/release/RELEASE-NOTES-0.3.6.md": "b5ce5826c244a9159783fc408e09cfd923140dc4ac8c716d8dff2e4c268776b1"
|
||||
},
|
||||
"IosSourceCommit": "b07d085413b1b6370245866fd82271b76590b6d6",
|
||||
"Kind": "clean-history-free-open-source-export",
|
||||
@@ -630,5 +654,18 @@
|
||||
"SourceOnly": true,
|
||||
"Version": "0.3.5"
|
||||
},
|
||||
"Windows036RuntimeRepairDelta": {
|
||||
"CandidateSha256": "001e2c92793d8508eed0eb5bfa82cdb51a243ac8aa7d2925e265f90c6454966e",
|
||||
"FrozenSha256": "521d3065e0d8a9e6417dd721d64b16c12032edec7fb2a6cf60e0a05314c961f2",
|
||||
"OptionalUnlicensedSceneRemainsOmitted": true,
|
||||
"OriginalAcceptanceTransferred": false,
|
||||
"OriginalSourceManifestSha256": "11d72a8778a76f90597aafec569bdd6d3a3f8e549ef8d09c9e70411ce916d58e",
|
||||
"OtherComponentsModified": false,
|
||||
"PrivateHistoryIncluded": false,
|
||||
"ProductionAccepted": false,
|
||||
"PublicBaseCommit": "23a87387b87aa82ffdafaf5cf87b4495d51207df",
|
||||
"SourceOnly": true,
|
||||
"Version": "0.3.6"
|
||||
},
|
||||
"WindowsSourceCommit": "0d463e6af91a3802c564b06dabb6bf86ebff5a38"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 UCVL (Youchuang Future)
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,27 @@
|
||||
# Account bandwidth policy source supplement
|
||||
|
||||
MIT source only; not an operational deployment or an enforcement claim.
|
||||
Add these six overlay files to a compatible legacy Django platform in an
|
||||
independent review branch. Existing platform modules and licenses remain intact.
|
||||
Ordinary account policy defaults are 500 KiB/s in each direction. Administrator
|
||||
values may range from 1 to 10240 KiB/s. The existing operator-approved exemption
|
||||
is bound to a fixed account identity and is not transferred by email changes.
|
||||
|
||||
The additive migration changes only shared_budget policy configuration. It
|
||||
preserves the existing exempt owner's policy and exemption, fills missing ordinary
|
||||
policies, and locks accounts before policy DDL to follow the registration order.
|
||||
It does not activate a limiter. Both budget switches must remain disabled until
|
||||
the separate executor supports the configured rate and real traffic is accepted.
|
||||
Old executors may still reject rates above 204800 bytes/s.
|
||||
|
||||
The included real-Django checks require your compatible legacy platform fixture
|
||||
at the sibling directory legacy-platform-fixture. Run tests/run_policy_checks.py
|
||||
with --stage red or green and a fresh --run-id. Tests build an isolated database;
|
||||
they do not connect to a deployed server. clone_validation.py exposes an explicit
|
||||
validate(before) entry and rolls back synthetic writes. Local SQLite checks do
|
||||
not substitute for PostgreSQL clone migration and concurrency acceptance.
|
||||
|
||||
No production database, credentials, real endpoint map, deployment driver,
|
||||
production binding, virtual environment or operational evidence is published.
|
||||
SOURCE-PROVENANCE.json records original and sanitized-source hashes, not private
|
||||
source history. No existing root module is replaced by this supplement.
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"DeploymentPerformed": false,
|
||||
"Feature": "account-rate-policy-default-500",
|
||||
"License": "MIT",
|
||||
"OriginalManifestSha256": "6bde5e669c1b1222b919a575083a6d53e266a27fc3f6ccd484b6a8b53d6ef5dc",
|
||||
"OriginalSourceSha256": {
|
||||
"overlay/shared_budget/allocator.py": "e8f4219ec616edc2c370c98986b3dd47ea86d8b2181aec385d504c3f3e218a87",
|
||||
"overlay/shared_budget/migrations/0002_account_rate_500.py": "78d6bf29212e91c172ced7d17ec051ce7accf741c0b3a087a61123366d992daa",
|
||||
"overlay/shared_budget/models.py": "375950395f3e1366cf0004c1e49bdc6de5b8b27aa82f5ca3ca293a4ca847bdbf",
|
||||
"overlay/shared_budget/policy.py": "40ef4d6deb764e6a301dd4fcd73b2fc2539da3ed44c3840351887b4da066f79b",
|
||||
"overlay/shared_budget/web_context.py": "70d4aaf2fa80c1dac19b54f0abf0d630a1acbcf27199e3af40da1433d0c8e5e3",
|
||||
"overlay/templates/includes/admin_budget.html": "2d78a88ffdeae943d4d08bde2d2bad55481d2d2c502ab44981dff2fef7a59b0d",
|
||||
"tests/clone_validation.py": "52d319ecca7cc9e562fb552f42735894f75abbf1f82ffcd0d562a8aa165ba720",
|
||||
"tests/run_policy_checks.py": "eb3bb110cf1062f7b707efadf9501e8463ccb291709b034c0a3c0c8f3e947509"
|
||||
},
|
||||
"PrivateHistoryIncluded": false,
|
||||
"ProductionAcceptanceAsserted": false,
|
||||
"SanitizedSourceSha256": {
|
||||
"backend/account-rate-500-20261106/LICENSE": "b7e94910b8dc377b0a05ccde3c6e5941838dfc15c9dd790078d11728205b524e",
|
||||
"backend/account-rate-500-20261106/README.md": "ee2b398587b860afa93b4e4901f8d52616d2bd2e15b86ee75df2456bce12a1f8",
|
||||
"backend/account-rate-500-20261106/overlay/shared_budget/allocator.py": "e8f4219ec616edc2c370c98986b3dd47ea86d8b2181aec385d504c3f3e218a87",
|
||||
"backend/account-rate-500-20261106/overlay/shared_budget/migrations/0002_account_rate_500.py": "78d6bf29212e91c172ced7d17ec051ce7accf741c0b3a087a61123366d992daa",
|
||||
"backend/account-rate-500-20261106/overlay/shared_budget/models.py": "375950395f3e1366cf0004c1e49bdc6de5b8b27aa82f5ca3ca293a4ca847bdbf",
|
||||
"backend/account-rate-500-20261106/overlay/shared_budget/policy.py": "40ef4d6deb764e6a301dd4fcd73b2fc2539da3ed44c3840351887b4da066f79b",
|
||||
"backend/account-rate-500-20261106/overlay/shared_budget/web_context.py": "70d4aaf2fa80c1dac19b54f0abf0d630a1acbcf27199e3af40da1433d0c8e5e3",
|
||||
"backend/account-rate-500-20261106/overlay/templates/includes/admin_budget.html": "2d78a88ffdeae943d4d08bde2d2bad55481d2d2c502ab44981dff2fef7a59b0d",
|
||||
"backend/account-rate-500-20261106/tests/clone_validation.py": "52d319ecca7cc9e562fb552f42735894f75abbf1f82ffcd0d562a8aa165ba720",
|
||||
"backend/account-rate-500-20261106/tests/run_policy_checks.py": "d99e54ddd1a293944b309df218c0846ae7ab933451aa7802cd0eafb4e3eb7592"
|
||||
},
|
||||
"Schema": 1,
|
||||
"SourceOnly": true
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
"""Opt-in v2 primary allocator with bounded replay state and explicit leases.
|
||||
|
||||
Credit issuance is not proof of deployed enforcement. At rate R and bucket B,
|
||||
issuance during T is bounded by B+R*T. Pre-issued credit has TTL <= 1 second;
|
||||
gate admission can therefore have an extra B+R*TTL release allowance, not an
|
||||
instantaneous strict configured-rate wire guarantee. Kernel/transport buffering is
|
||||
outside this account payload contract. Unused credits are burned, not refunded.
|
||||
|
||||
One durable node epoch fences restarted executors. One persisted response and
|
||||
sequence high-water per node/subscription/direction replaces a per-RPC ledger.
|
||||
Do not delete/reset same-epoch lane state, or reset node epochs. UUID request_id
|
||||
is correlation; the replay identity is (node, epoch, lane, sequence). Same seq
|
||||
retries retain their first monotonic request-start deadline at the executor.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import uuid
|
||||
from datetime import timedelta
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.db import DatabaseError, IntegrityError, connections, transaction
|
||||
from django.http import JsonResponse
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from django.views.decorators.http import require_http_methods
|
||||
|
||||
from .models import ACCOUNT_BANDWIDTH_EXCEPTION_KEY, AccountBandwidthExemption, AccountBandwidthPolicy
|
||||
from .policy import _limit_in_bytes
|
||||
from .helpers import (
|
||||
BURST_MS, DB, MAX_REQUEST_BYTES, MICRO, BudgetRejected, _database_now,
|
||||
_node_allowed, _require_primary_backend, _unique_json_pairs,
|
||||
)
|
||||
from .models import AccountBandwidthBucket, AccountBandwidthExecutor, AccountBandwidthLane
|
||||
from control.models import Node, Subscription
|
||||
|
||||
CONTRACT = 2
|
||||
POLICY_VERSION = "shared-account-budget-v2"
|
||||
MAX_SEQUENCE = 2**63 - 1
|
||||
MAX_TTL_MS = 1000
|
||||
MAX_RESPONSE_BYTES = 2048
|
||||
|
||||
|
||||
def _reply(payload, status=200):
|
||||
response = JsonResponse(payload, status=status)
|
||||
response["Cache-Control"] = "no-store"
|
||||
return response
|
||||
|
||||
|
||||
def _integer(value, minimum, maximum=MAX_SEQUENCE):
|
||||
return type(value) is int and minimum <= value <= maximum
|
||||
|
||||
|
||||
def _uuid(value):
|
||||
return (isinstance(value, str) and len(value) == 36 and str(uuid.UUID(value)) == value
|
||||
and uuid.UUID(value).int != 0)
|
||||
|
||||
|
||||
def _contract(payload, fields):
|
||||
if (not isinstance(payload, dict) or set(payload) != fields
|
||||
or type(payload["contract"]) is not int or payload["contract"] != CONTRACT
|
||||
or payload["policy_version"] != POLICY_VERSION):
|
||||
raise ValueError("unsupported budget v2 contract")
|
||||
|
||||
|
||||
def _parse_open(payload):
|
||||
_contract(payload, {"contract", "policy_version", "expected_epoch", "boot_id", "registration_id"})
|
||||
if not _integer(payload["expected_epoch"], 0) or not all(_uuid(payload[key]) for key in ("boot_id", "registration_id")):
|
||||
raise ValueError("invalid executor registration")
|
||||
return payload
|
||||
|
||||
|
||||
def _parse_credit(payload):
|
||||
_contract(payload, {"contract", "policy_version", "subscription_id", "credential_uuid", "direction",
|
||||
"requested_bytes", "request_id", "boot_id", "session_id", "ttl_ms", "executor_epoch", "sequence"})
|
||||
if (not all(_integer(payload[key], 1) for key in ("subscription_id", "executor_epoch", "sequence"))
|
||||
or not _integer(payload["requested_bytes"], 1, MAX_REQUEST_BYTES)
|
||||
or not _integer(payload["ttl_ms"], 50, MAX_TTL_MS)
|
||||
or payload["direction"] not in ("upload", "download")
|
||||
or not all(_uuid(payload[key]) for key in ("credential_uuid", "request_id", "boot_id", "session_id"))):
|
||||
raise ValueError("invalid budget v2 request")
|
||||
return payload
|
||||
|
||||
|
||||
def _timeouts():
|
||||
if connections[DB].vendor == "postgresql":
|
||||
with connections[DB].cursor() as cursor:
|
||||
cursor.execute("SET LOCAL lock_timeout = '100ms'")
|
||||
cursor.execute("SET LOCAL statement_timeout = '250ms'")
|
||||
|
||||
|
||||
def _current_node(node, lock=False):
|
||||
query = Node.objects.using(DB)
|
||||
if lock:
|
||||
query = query.select_for_update(nowait=True)
|
||||
current = query.filter(pk=node.pk).first()
|
||||
if not _node_allowed(current) or current.agent_token_digest != node.agent_token_digest:
|
||||
raise BudgetRejected("node_not_authorized", 401)
|
||||
return current
|
||||
|
||||
|
||||
def _check_clock(now, *floors):
|
||||
if any(floor is not None and now < floor for floor in floors):
|
||||
raise BudgetRejected("budget_clock_regressed", 503)
|
||||
|
||||
|
||||
def read_executor(node):
|
||||
_require_primary_backend()
|
||||
current = _current_node(node)
|
||||
state = AccountBandwidthExecutor.objects.using(DB).filter(node=current).first()
|
||||
_check_clock(_database_now(), state.clock_floor if state else None)
|
||||
return {"contract": CONTRACT, "policy_version": POLICY_VERSION, "node_slug": current.slug,
|
||||
"executor_epoch": state.epoch if state else 0}
|
||||
|
||||
|
||||
def _registration_response(state, node):
|
||||
return {"contract": CONTRACT, "policy_version": POLICY_VERSION, "node_slug": node.slug,
|
||||
"executor_epoch": state.epoch, "boot_id": str(state.boot_id), "registration_id": str(state.registration_id)}
|
||||
|
||||
|
||||
def open_executor(node, payload):
|
||||
payload = _parse_open(payload)
|
||||
_require_primary_backend()
|
||||
with transaction.atomic(using=DB):
|
||||
_timeouts()
|
||||
current = _current_node(node, lock=True)
|
||||
state = AccountBandwidthExecutor.objects.using(DB).filter(node=current).first()
|
||||
now = _database_now()
|
||||
_check_clock(now, state.clock_floor if state else None)
|
||||
if state:
|
||||
same_registration = (str(state.boot_id) == payload["boot_id"] and str(state.registration_id) == payload["registration_id"])
|
||||
if same_registration and payload["expected_epoch"] == state.epoch - 1:
|
||||
return _registration_response(state, current)
|
||||
if (payload["expected_epoch"] != state.epoch or state.epoch == MAX_SEQUENCE
|
||||
or str(state.boot_id) == payload["boot_id"] or str(state.registration_id) == payload["registration_id"]):
|
||||
raise BudgetRejected("fenced", 409)
|
||||
state.epoch += 1
|
||||
state.boot_id, state.registration_id = payload["boot_id"], payload["registration_id"]
|
||||
state.opened_at = state.clock_floor = now
|
||||
state.save(using=DB)
|
||||
else:
|
||||
if payload["expected_epoch"] != 0:
|
||||
raise BudgetRejected("fenced", 409)
|
||||
state = AccountBandwidthExecutor.objects.using(DB).create(node=current, epoch=1,
|
||||
boot_id=payload["boot_id"], registration_id=payload["registration_id"], opened_at=now, clock_floor=now)
|
||||
return _registration_response(state, current)
|
||||
|
||||
|
||||
def _authorize_subscription(node, payload):
|
||||
owner_id = Subscription.objects.using(DB).filter(pk=payload["subscription_id"]).values_list("user_id", flat=True).first()
|
||||
if owner_id is None:
|
||||
raise BudgetRejected("subscription_not_authorized")
|
||||
user = get_user_model().objects.using(DB).select_for_update().filter(pk=owner_id).first()
|
||||
subscription = Subscription.objects.using(DB).select_for_update(of=("self",)).select_related("plan").filter(pk=payload["subscription_id"]).first()
|
||||
if user is None or subscription is None or subscription.user_id != user.pk:
|
||||
raise BudgetRejected("subscription_not_authorized")
|
||||
# Same lock order as v1: account/subscription first, node NOWAIT afterwards.
|
||||
current = _current_node(node, lock=True)
|
||||
state = AccountBandwidthExecutor.objects.using(DB).filter(node=current).first()
|
||||
if state is None or state.epoch != payload["executor_epoch"] or str(state.boot_id) != payload["boot_id"]:
|
||||
raise BudgetRejected("fenced", 409)
|
||||
now = _database_now()
|
||||
_check_clock(now, state.clock_floor)
|
||||
subscription.user = user
|
||||
if (not user.service_enabled or subscription.status != Subscription.Status.ACTIVE
|
||||
or subscription.provisioning_state != Subscription.ProvisioningState.ACTIVE
|
||||
or str(subscription.credential_uuid) != payload["credential_uuid"]
|
||||
or subscription.route_mode not in Subscription.RouteMode.values or subscription.online_payment_pending
|
||||
or (subscription.starts_at and subscription.starts_at > now)
|
||||
or (subscription.expires_at and subscription.expires_at <= now)
|
||||
or (subscription.traffic_limit_bytes and subscription.used_bytes >= subscription.traffic_limit_bytes)
|
||||
or not subscription.nodes_for_subscription().using(DB).filter(pk=current.pk).exists()):
|
||||
raise BudgetRejected("subscription_not_authorized")
|
||||
return user, subscription, current, state, now
|
||||
|
||||
|
||||
def issue_credit_v2(node, payload):
|
||||
payload = _parse_credit(payload)
|
||||
_require_primary_backend()
|
||||
fingerprint = hashlib.sha256(json.dumps({"node_id": node.pk, **payload}, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
|
||||
with transaction.atomic(using=DB):
|
||||
_timeouts()
|
||||
user, subscription, current, executor, now = _authorize_subscription(node, payload)
|
||||
lane = AccountBandwidthLane.objects.using(DB).filter(node=current, subscription=subscription, direction=payload["direction"]).first()
|
||||
same_epoch = lane is not None and lane.executor_epoch == executor.epoch
|
||||
if same_epoch:
|
||||
if str(lane.session_id) != payload["session_id"] or str(lane.credential_uuid) != payload["credential_uuid"] or lane.user_id != user.pk:
|
||||
raise BudgetRejected("fenced", 409)
|
||||
_check_clock(now, lane.issued_at)
|
||||
if payload["sequence"] == lane.sequence:
|
||||
if fingerprint != lane.fingerprint:
|
||||
raise BudgetRejected("sequence_conflict", 409)
|
||||
return json.loads(lane.response)
|
||||
if payload["sequence"] != lane.sequence + 1:
|
||||
raise BudgetRejected("sequence_out_of_order", 409)
|
||||
elif payload["sequence"] != 1:
|
||||
raise BudgetRejected("sequence_out_of_order", 409)
|
||||
if lane is not None and lane.executor_epoch > executor.epoch:
|
||||
raise BudgetRejected("fenced", 409)
|
||||
# The stable User row is already locked: serialize policy creation and all lanes.
|
||||
policy, _ = AccountBandwidthPolicy.objects.using(DB).get_or_create(user=user)
|
||||
rate = _limit_in_bytes(getattr(policy, payload["direction"] + "_limit_kib_per_second"))
|
||||
exempt = AccountBandwidthExemption.objects.using(DB).filter(policy_key=ACCOUNT_BANDWIDTH_EXCEPTION_KEY, user_id=user.pk).exists()
|
||||
capacity = rate * BURST_MS * 1000
|
||||
bucket, _ = AccountBandwidthBucket.objects.using(DB).get_or_create(user=user, direction=payload["direction"],
|
||||
defaults={"available_microbytes": 0 if exempt else capacity, "rate_bytes_per_second": rate, "exempt": exempt, "refilled_at": now})
|
||||
_check_clock(now, bucket.refilled_at)
|
||||
if bucket.rate_bytes_per_second != rate or bucket.exempt != exempt:
|
||||
available = 0
|
||||
else:
|
||||
elapsed = now - bucket.refilled_at
|
||||
elapsed_us = (elapsed.days * 86400 + elapsed.seconds) * MICRO + elapsed.microseconds
|
||||
available = min(capacity, bucket.available_microbytes + elapsed_us * rate)
|
||||
granted = 0 if exempt else min(payload["requested_bytes"], available // MICRO)
|
||||
bucket.available_microbytes = 0 if exempt else available - granted * MICRO
|
||||
bucket.rate_bytes_per_second, bucket.exempt, bucket.refilled_at = rate, exempt, now
|
||||
bucket.save(using=DB)
|
||||
expiry = now + timedelta(milliseconds=payload["ttl_ms"])
|
||||
if subscription.expires_at:
|
||||
expiry = min(expiry, subscription.expires_at)
|
||||
response = {"contract": CONTRACT, "policy_version": POLICY_VERSION, "request_id": payload["request_id"],
|
||||
"node_slug": current.slug, "boot_id": payload["boot_id"], "session_id": payload["session_id"],
|
||||
"account_id": user.pk, "subscription_id": subscription.pk, "credential_uuid": str(subscription.credential_uuid),
|
||||
"direction": payload["direction"], "requested_bytes": payload["requested_bytes"], "ttl_ms": payload["ttl_ms"],
|
||||
"issued_at": now.isoformat(), "expires_at": expiry.isoformat(), "executor_epoch": executor.epoch,
|
||||
"sequence": payload["sequence"], "enforced": False, "exempt": exempt,
|
||||
"kind": "bandwidth_exemption_lease" if exempt else "byte_credit"}
|
||||
if exempt:
|
||||
response["exemption_policy_key"] = ACCOUNT_BANDWIDTH_EXCEPTION_KEY
|
||||
else:
|
||||
response.update(granted_bytes=granted, rate_bytes_per_second=rate, burst_bytes=capacity // MICRO)
|
||||
encoded = json.dumps(response, sort_keys=True, separators=(",", ":"))
|
||||
if len(encoded.encode()) > MAX_RESPONSE_BYTES:
|
||||
raise BudgetRejected("budget_unavailable", 503)
|
||||
values = dict(user=user, executor_epoch=executor.epoch, credential_uuid=subscription.credential_uuid,
|
||||
session_id=payload["session_id"], sequence=payload["sequence"], fingerprint=fingerprint,
|
||||
response=encoded, issued_at=now)
|
||||
if lane is None:
|
||||
AccountBandwidthLane.objects.using(DB).create(node=current, subscription=subscription, direction=payload["direction"], **values)
|
||||
else:
|
||||
for key, value in values.items():
|
||||
setattr(lane, key, value)
|
||||
lane.save(using=DB)
|
||||
executor.clock_floor = now
|
||||
executor.save(using=DB, update_fields=["clock_floor"])
|
||||
return response
|
||||
|
||||
|
||||
def _http(request, action):
|
||||
if getattr(settings, "ACCOUNT_BANDWIDTH_BUDGET_V2_ENABLED", False) is not True:
|
||||
return _reply({"error_code": "budget_disabled"}, 503)
|
||||
from control.views import _authenticate_node
|
||||
try:
|
||||
_require_primary_backend()
|
||||
node = _authenticate_node(request)
|
||||
if not _node_allowed(node):
|
||||
raise BudgetRejected("node_not_authorized", 401)
|
||||
if action == "read":
|
||||
return _reply(read_executor(node))
|
||||
if len(request.body) > 4096:
|
||||
raise ValueError("budget payload too large")
|
||||
payload = json.loads(request.body, object_pairs_hook=_unique_json_pairs)
|
||||
return _reply(open_executor(node, payload) if action == "open" else issue_credit_v2(node, payload))
|
||||
except BudgetRejected as exc:
|
||||
return _reply({"error_code": exc.code}, exc.status)
|
||||
except (ValueError, TypeError, OverflowError):
|
||||
return _reply({"error_code": "invalid_budget_request"}, 400)
|
||||
except (DatabaseError, IntegrityError):
|
||||
return _reply({"error_code": "budget_unavailable"}, 503)
|
||||
|
||||
|
||||
@csrf_exempt
|
||||
@require_http_methods(["GET", "POST"])
|
||||
def node_budget_executor(request):
|
||||
return _http(request, "read" if request.method == "GET" else "open")
|
||||
|
||||
|
||||
@csrf_exempt
|
||||
@require_http_methods(["POST"])
|
||||
def node_bandwidth_budget_v2(request):
|
||||
return _http(request, "credit")
|
||||
|
||||
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
"""Account configuration only; does not activate the disabled budget executor."""
|
||||
import django.core.validators
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
def lock_accounts_before_policy_ddl(apps, schema_editor):
|
||||
User = apps.get_model("accounts", "User")
|
||||
Policy = apps.get_model("shared_budget", "AccountBandwidthPolicy")
|
||||
if schema_editor.connection.vendor == "postgresql":
|
||||
# Serialize registration and policy edits for complete coverage. The
|
||||
# existing fixed-ID exemption and every owner policy byte stay intact.
|
||||
quote = schema_editor.connection.ops.quote_name
|
||||
with schema_editor.connection.cursor() as cursor:
|
||||
cursor.execute("LOCK TABLE " + quote(User._meta.db_table) + " IN SHARE MODE")
|
||||
cursor.execute("LOCK TABLE " + quote(Policy._meta.db_table) + " IN SHARE ROW EXCLUSIVE MODE")
|
||||
|
||||
|
||||
def set_ordinary_account_defaults(apps, schema_editor):
|
||||
User = apps.get_model("accounts", "User")
|
||||
Policy = apps.get_model("shared_budget", "AccountBandwidthPolicy")
|
||||
database = schema_editor.connection.alias
|
||||
ordinary = User.objects.using(database).exclude(pk=5)
|
||||
policies = Policy.objects.using(database)
|
||||
policies.exclude(user_id=5).update(upload_limit_kib_per_second=500, download_limit_kib_per_second=500)
|
||||
missing = ordinary.exclude(pk__in=policies.values("user_id")).values_list("pk", flat=True)
|
||||
policies.bulk_create([Policy(user_id=pk, upload_limit_kib_per_second=500, download_limit_kib_per_second=500)
|
||||
for pk in missing], batch_size=1000)
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [("shared_budget", "0001_initial")]
|
||||
operations = [
|
||||
# Must precede every DDL table lock: registration holds User first and
|
||||
# its post_save signal writes Policy. Acquiring Policy DDL first could
|
||||
# deadlock that transaction when we subsequently lock User.
|
||||
migrations.RunPython(lock_accounts_before_policy_ddl, migrations.RunPython.noop),
|
||||
migrations.RemoveConstraint(model_name="accountbandwidthpolicy", name="sb_policy_upload_bounded"),
|
||||
migrations.RemoveConstraint(model_name="accountbandwidthpolicy", name="sb_policy_download_bounded"),
|
||||
migrations.RemoveConstraint(model_name="accountbandwidthbucket", name="bandwidth_bucket_rate_bounded"),
|
||||
migrations.RemoveConstraint(model_name="accountbandwidthbucket", name="bandwidth_bucket_credit_bounded"),
|
||||
migrations.AlterField(model_name="accountbandwidthpolicy", name="upload_limit_kib_per_second",
|
||||
field=models.PositiveSmallIntegerField("账号上传上限(KiB/s)", default=500, db_default=500,
|
||||
validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(10240)])),
|
||||
migrations.AlterField(model_name="accountbandwidthpolicy", name="download_limit_kib_per_second",
|
||||
field=models.PositiveSmallIntegerField("账号下载上限(KiB/s)", default=500, db_default=500,
|
||||
validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(10240)])),
|
||||
migrations.AddConstraint(model_name="accountbandwidthpolicy", constraint=models.CheckConstraint(
|
||||
condition=models.Q(upload_limit_kib_per_second__gte=1, upload_limit_kib_per_second__lte=10240), name="sb_policy_upload_bounded")),
|
||||
migrations.AddConstraint(model_name="accountbandwidthpolicy", constraint=models.CheckConstraint(
|
||||
condition=models.Q(download_limit_kib_per_second__gte=1, download_limit_kib_per_second__lte=10240), name="sb_policy_download_bounded")),
|
||||
migrations.AddConstraint(model_name="accountbandwidthbucket", constraint=models.CheckConstraint(
|
||||
condition=models.Q(rate_bytes_per_second__gte=1, rate_bytes_per_second__lte=10485760), name="bandwidth_bucket_rate_bounded")),
|
||||
migrations.AddConstraint(model_name="accountbandwidthbucket", constraint=models.CheckConstraint(
|
||||
condition=models.Q(available_microbytes__lte=2097152000000), name="bandwidth_bucket_credit_bounded")),
|
||||
# Irreversible data policy: an automatic downgrade must not overwrite
|
||||
# later administrator choices or silently recreate 200 KiB/s limits.
|
||||
migrations.RunPython(set_ordinary_account_defaults),
|
||||
]
|
||||
@@ -0,0 +1,149 @@
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.validators import MaxValueValidator, MinValueValidator
|
||||
from django.db import models
|
||||
from control.models import Node, Subscription
|
||||
|
||||
from .policy import DEFAULT_KIB_PER_SECOND, MAX_KIB_PER_SECOND, MAX_BYTES_PER_SECOND, MAX_BUCKET_MICROBYTES
|
||||
|
||||
ACCOUNT_BANDWIDTH_EXCEPTION_KEY = "owner-approved-20261022"
|
||||
APPROVED_EXEMPT_USER_ID = 5
|
||||
|
||||
|
||||
class AccountBandwidthPolicy(models.Model):
|
||||
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
|
||||
primary_key=True, related_name="shared_bandwidth_policy")
|
||||
upload_limit_kib_per_second = models.PositiveSmallIntegerField(
|
||||
"账号上传上限(KiB/s)", default=DEFAULT_KIB_PER_SECOND, db_default=DEFAULT_KIB_PER_SECOND,
|
||||
validators=[MinValueValidator(1), MaxValueValidator(MAX_KIB_PER_SECOND)])
|
||||
download_limit_kib_per_second = models.PositiveSmallIntegerField(
|
||||
"账号下载上限(KiB/s)", default=DEFAULT_KIB_PER_SECOND, db_default=DEFAULT_KIB_PER_SECOND,
|
||||
validators=[MinValueValidator(1), MaxValueValidator(MAX_KIB_PER_SECOND)])
|
||||
|
||||
class Meta:
|
||||
verbose_name = "账户带宽策略"
|
||||
verbose_name_plural = "账户带宽策略"
|
||||
constraints = [
|
||||
models.CheckConstraint(condition=models.Q(upload_limit_kib_per_second__gte=1,
|
||||
upload_limit_kib_per_second__lte=MAX_KIB_PER_SECOND), name="sb_policy_upload_bounded"),
|
||||
models.CheckConstraint(condition=models.Q(download_limit_kib_per_second__gte=1,
|
||||
download_limit_kib_per_second__lte=MAX_KIB_PER_SECOND), name="sb_policy_download_bounded"),
|
||||
]
|
||||
|
||||
def __str__(self):
|
||||
return str(self.user)
|
||||
|
||||
|
||||
class ProtectedExemptionQuerySet(models.QuerySet):
|
||||
def update(self, **kwargs):
|
||||
raise ValidationError("受控豁免不能通过普通查询修改。")
|
||||
|
||||
def delete(self):
|
||||
raise ValidationError("受控豁免不能通过普通查询删除。")
|
||||
|
||||
def bulk_create(self, *args, **kwargs):
|
||||
raise ValidationError("受控豁免仅可通过审核后的数据迁移建立。")
|
||||
|
||||
def bulk_update(self, *args, **kwargs):
|
||||
raise ValidationError("受控豁免不能通过普通查询修改。")
|
||||
|
||||
|
||||
class AccountBandwidthExemption(models.Model):
|
||||
policy_key = models.CharField(primary_key=True, max_length=64,
|
||||
default=ACCOUNT_BANDWIDTH_EXCEPTION_KEY, editable=False)
|
||||
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT,
|
||||
related_name="shared_bandwidth_exemption", editable=False)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
objects = ProtectedExemptionQuerySet.as_manager()
|
||||
|
||||
class Meta:
|
||||
verbose_name = "受控账号免限速绑定"
|
||||
verbose_name_plural = "受控账号免限速绑定"
|
||||
default_permissions = ("view",)
|
||||
constraints = [models.CheckConstraint(
|
||||
condition=models.Q(policy_key=ACCOUNT_BANDWIDTH_EXCEPTION_KEY, user_id=APPROVED_EXEMPT_USER_ID),
|
||||
name="sb_single_approved_exemption")]
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
raise ValidationError("受控豁免仅可通过审核后的数据迁移建立。")
|
||||
|
||||
def delete(self, *args, **kwargs):
|
||||
raise ValidationError("受控豁免不能由普通后台操作删除。")
|
||||
|
||||
|
||||
class AccountBandwidthBucket(models.Model):
|
||||
"""Primary-DB account/direction credit, shared by every subscription/node.
|
||||
|
||||
Microbytes preserve sub-byte refill fractions without floating point. These
|
||||
rows and the grant ledger are authorizations, not traffic measurements.
|
||||
"""
|
||||
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT,
|
||||
related_name="bandwidth_budget_buckets")
|
||||
direction = models.CharField(max_length=8, choices=[("upload", "upload"), ("download", "download")])
|
||||
available_microbytes = models.PositiveBigIntegerField(default=0)
|
||||
rate_bytes_per_second = models.PositiveIntegerField()
|
||||
exempt = models.BooleanField(default=False)
|
||||
refilled_at = models.DateTimeField()
|
||||
|
||||
class Meta:
|
||||
default_permissions = ()
|
||||
constraints = [
|
||||
models.UniqueConstraint(fields=["user", "direction"], name="unique_account_bandwidth_bucket"),
|
||||
models.CheckConstraint(condition=models.Q(direction__in=["upload", "download"]),
|
||||
name="bandwidth_bucket_direction"),
|
||||
models.CheckConstraint(condition=models.Q(rate_bytes_per_second__gte=1,
|
||||
rate_bytes_per_second__lte=MAX_BYTES_PER_SECOND),
|
||||
name="bandwidth_bucket_rate_bounded"),
|
||||
models.CheckConstraint(condition=models.Q(available_microbytes__lte=MAX_BUCKET_MICROBYTES),
|
||||
name="bandwidth_bucket_credit_bounded"),
|
||||
]
|
||||
|
||||
|
||||
class AccountBandwidthExecutor(models.Model):
|
||||
"""One durable fencing generation per node; never reset/delete on restart."""
|
||||
|
||||
node = models.OneToOneField(Node, on_delete=models.PROTECT, primary_key=True,
|
||||
related_name="bandwidth_budget_executor")
|
||||
epoch = models.PositiveBigIntegerField()
|
||||
boot_id = models.UUIDField()
|
||||
registration_id = models.UUIDField()
|
||||
opened_at = models.DateTimeField()
|
||||
clock_floor = models.DateTimeField()
|
||||
|
||||
class Meta:
|
||||
default_permissions = ()
|
||||
constraints = [models.CheckConstraint(condition=models.Q(epoch__gte=1, epoch__lte=9223372036854775807),
|
||||
name="bandwidth_executor_epoch_bounded")]
|
||||
|
||||
|
||||
class AccountBandwidthLane(models.Model):
|
||||
"""Fixed one-response replay slot, not a per-RPC ledger.
|
||||
|
||||
Same-epoch sequence/session state must never be reset. Older-epoch rows may
|
||||
be reused only while holding the durable node executor fence.
|
||||
"""
|
||||
|
||||
node = models.ForeignKey(Node, on_delete=models.PROTECT, related_name="bandwidth_budget_lanes")
|
||||
subscription = models.ForeignKey(Subscription, on_delete=models.PROTECT, related_name="bandwidth_budget_lanes")
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="bandwidth_budget_lanes")
|
||||
direction = models.CharField(max_length=8, choices=[("upload", "upload"), ("download", "download")])
|
||||
executor_epoch = models.PositiveBigIntegerField()
|
||||
credential_uuid = models.UUIDField()
|
||||
session_id = models.UUIDField()
|
||||
sequence = models.PositiveBigIntegerField()
|
||||
fingerprint = models.CharField(max_length=64)
|
||||
response = models.CharField(max_length=2048)
|
||||
issued_at = models.DateTimeField()
|
||||
|
||||
class Meta:
|
||||
default_permissions = ()
|
||||
constraints = [
|
||||
models.UniqueConstraint(fields=["node", "subscription", "direction"], name="unique_account_bandwidth_lane"),
|
||||
models.CheckConstraint(condition=models.Q(direction__in=["upload", "download"]), name="bandwidth_lane_direction"),
|
||||
models.CheckConstraint(condition=models.Q(executor_epoch__gte=1, executor_epoch__lte=9223372036854775807,
|
||||
sequence__gte=1, sequence__lte=9223372036854775807),
|
||||
name="bandwidth_lane_identity_bounded"),
|
||||
]
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
DEFAULT_KIB_PER_SECOND = 500
|
||||
MAX_KIB_PER_SECOND = 10240
|
||||
MAX_BYTES_PER_SECOND = MAX_KIB_PER_SECOND * 1024
|
||||
# Keep the DB credit bound aligned with the allocator's existing 200 ms burst.
|
||||
MAX_BUCKET_MICROBYTES = MAX_BYTES_PER_SECOND * 200 * 1000
|
||||
|
||||
|
||||
def _limit_in_bytes(value):
|
||||
if type(value) is not int or not 1 <= value <= MAX_KIB_PER_SECOND:
|
||||
raise ValueError(f"Account proxy speed request must be an integer in 1–{MAX_KIB_PER_SECOND} KiB/s.")
|
||||
return value * 1024
|
||||
@@ -0,0 +1,72 @@
|
||||
"""Read-only, request-scoped portal guidance; never infers a live VPN connection."""
|
||||
from django.conf import settings
|
||||
from django.urls import reverse
|
||||
|
||||
from control.models import PlanApplication, Subscription
|
||||
from .models import AccountBandwidthExemption, AccountBandwidthExecutor
|
||||
from .policy import DEFAULT_KIB_PER_SECOND, MAX_KIB_PER_SECOND
|
||||
|
||||
|
||||
def portal_context(request):
|
||||
context = {"PLATFORM_NAME": "纵横家"}
|
||||
user = getattr(request, "user", None)
|
||||
if not user or not user.is_authenticated:
|
||||
return context
|
||||
|
||||
can_manage = bool(user.is_active and user.is_staff and (
|
||||
user.has_perm("shared_budget.view_accountbandwidthpolicy")
|
||||
or user.has_perm("shared_budget.change_accountbandwidthpolicy")))
|
||||
if can_manage:
|
||||
admin_budget = {
|
||||
"default_upload": DEFAULT_KIB_PER_SECOND, "default_download": DEFAULT_KIB_PER_SECOND,
|
||||
"maximum_limit": MAX_KIB_PER_SECOND,
|
||||
"allocator_enabled": getattr(settings, "ACCOUNT_BANDWIDTH_BUDGET_V2_ENABLED", False) is True,
|
||||
"policy_url": reverse("admin:shared_budget_accountbandwidthpolicy_changelist"),
|
||||
"execution_label": "待现场验收",
|
||||
}
|
||||
if user.has_perm("shared_budget.view_accountbandwidthexemption"):
|
||||
admin_budget["exemption_count"] = AccountBandwidthExemption.objects.count()
|
||||
admin_budget["exemption_url"] = reverse("admin:shared_budget_accountbandwidthexemption_changelist")
|
||||
admin_budget["registered_executors"] = AccountBandwidthExecutor.objects.count()
|
||||
context["admin_budget"] = admin_budget
|
||||
|
||||
match = getattr(request, "resolver_match", None)
|
||||
if not match or match.url_name != "portal-dashboard":
|
||||
return context
|
||||
# Every query is scoped to the signed-in user; no account ID is accepted
|
||||
# from query strings, form fields, or a selected client node.
|
||||
subscriptions = user.subscriptions.select_related("plan", "routing_policy").all()
|
||||
subscription = subscriptions.exclude(status__in=["cancelled", "expired"]).first() or subscriptions.first()
|
||||
pending = user.plan_applications.filter(status=PlanApplication.Status.PENDING).exists()
|
||||
journey = {"pending": pending, "ready": False, "step": 1,
|
||||
"primary_url": reverse("apply-plan"), "primary_label": "选择套餐并申请"}
|
||||
if not user.is_active or user.account_status in ("suspended", "departed"):
|
||||
journey.update(state="restricted", step=2, title="服务暂不可用",
|
||||
body="账号已暂停或停止服务,请联系管理员核实。当前页面不会提供订阅凭据。",
|
||||
primary_url=reverse("portal-dashboard") + "#application-history", primary_label="查看申请记录")
|
||||
elif subscription and subscription.is_usable:
|
||||
journey.update(state="ready", ready=True, step=3, title="订阅已准备好",
|
||||
body="下载 Windows 客户端后,用同一账号登录;也可展开个人订阅地址供兼容客户端使用。",
|
||||
primary_url=reverse("client-download-latest"), primary_label="下载 Windows 客户端")
|
||||
elif pending:
|
||||
journey.update(state="review", step=2, title="申请已提交,等待审核",
|
||||
body="不用重复提交。管理员核实身份并审核后,开通进度与订阅会显示在这里;暂未开放付款的套餐不会扣款。",
|
||||
primary_url=reverse("portal-dashboard") + "#application-history", primary_label="查看审核进度")
|
||||
elif subscription and subscription.online_payment_pending:
|
||||
journey.update(state="payment_pending", step=2, title="套餐暂未开放付款",
|
||||
body="申请只作登记,尚未扣款或开通付费服务。请等待管理员通知,不要向个人账号转账。",
|
||||
primary_url=reverse("portal-dashboard") + "#application-history", primary_label="查看申请记录")
|
||||
elif subscription and subscription.status == "active" and user.service_enabled:
|
||||
journey.update(state="provisioning", step=2, title="审核已通过,等待订阅就绪",
|
||||
body="节点配置仍在处理。请稍后刷新本页;实际连接状态只在客户端查看。",
|
||||
primary_url=reverse("portal-dashboard"), primary_label="刷新开通进度")
|
||||
elif subscription:
|
||||
journey.update(state="renew", step=2, title="订阅当前不可用",
|
||||
body="请核对下方有效期、流量和处理状态。需要续期或更换套餐时再提交申请。",
|
||||
primary_url=reverse("apply-plan"), primary_label="查看可申请套餐")
|
||||
else:
|
||||
journey.update(state="apply", title="先选择套餐,提交开通申请",
|
||||
body="注册只需一次。提交套餐申请后由管理员审核,通过后在这里获取订阅与客户端下载入口。")
|
||||
context["portal_journey"] = journey
|
||||
return context
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
{% if admin_budget %}
|
||||
<section class="admin-budget-panel" aria-labelledby="budget-heading">
|
||||
<div><span class="budget-eyebrow">账户共享带宽</span><h2 id="budget-heading">默认每方向 {{ admin_budget.default_upload }} KiB/s</h2>
|
||||
<p>同一账户的设备与节点共用上传、下载预算;单账户每方向可设 1–{{ admin_budget.maximum_limit|stringformat:"d" }} KiB/s。</p>
|
||||
<p>中央预算 API:{% if admin_budget.allocator_enabled %}<strong>已开启</strong>{% else %}<strong>未开启</strong>{% endif %} · 执行状态:<strong>{{ admin_budget.execution_label }}</strong></p>
|
||||
<p class="budget-detail">已注册执行器 {{ admin_budget.registered_executors }} 个。注册或开启 API 不代表真实限速已验收。{% if admin_budget.exemption_count != None %}受控豁免 {{ admin_budget.exemption_count }} 个,绑定固定账号 ID,不随邮箱转移。{% endif %}</p>
|
||||
</div>
|
||||
<div class="budget-links"><a class="budget-primary" href="{{ admin_budget.policy_url }}">管理账户限速</a>{% if admin_budget.exemption_url %}<a href="{{ admin_budget.exemption_url }}">查看只读豁免</a>{% endif %}</div>
|
||||
</section>
|
||||
{% endif %}
|
||||
@@ -0,0 +1,195 @@
|
||||
"""Real Django policy checks; all exercise writes are rolled back.
|
||||
|
||||
The deployment driver execs this source in a separate namespace and explicitly
|
||||
calls protected_snapshot()/validate(before); Django shell is not __main__.
|
||||
For a direct script entry, RATE500_BEFORE_JSON can supply the prior snapshot.
|
||||
No node process, network, user credential or limiter flag is changed here.
|
||||
"""
|
||||
import io
|
||||
import importlib
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
from types import SimpleNamespace
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib import admin
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.management import call_command
|
||||
from django.db import IntegrityError, connection, transaction
|
||||
from django.db import migrations
|
||||
from django.db.migrations.executor import MigrationExecutor
|
||||
from django.test import RequestFactory
|
||||
from django.template.loader import render_to_string
|
||||
from django.utils import timezone
|
||||
|
||||
|
||||
def protected_snapshot():
|
||||
from shared_budget.models import AccountBandwidthExemption, AccountBandwidthPolicy
|
||||
return {
|
||||
"owner_policy": list(AccountBandwidthPolicy.objects.filter(user_id=5).values()),
|
||||
"exemptions": list(AccountBandwidthExemption.objects.order_by("policy_key").values()),
|
||||
"user_count": get_user_model().objects.count(),
|
||||
}
|
||||
|
||||
|
||||
def validate(before=None):
|
||||
from shared_budget import policy
|
||||
from shared_budget.allocator import node_bandwidth_budget_v2, node_budget_executor
|
||||
from shared_budget.models import AccountBandwidthBucket, AccountBandwidthExemption, AccountBandwidthPolicy
|
||||
from shared_budget.web_context import portal_context
|
||||
|
||||
checks, errors = {}, {}
|
||||
|
||||
def check(name, action):
|
||||
try:
|
||||
action()
|
||||
checks[name] = True
|
||||
except Exception as error:
|
||||
checks[name] = False
|
||||
errors[name] = f"{type(error).__name__}: {error}"
|
||||
|
||||
def require(value, message):
|
||||
if not value:
|
||||
raise AssertionError(message)
|
||||
|
||||
def rejected(action, exception):
|
||||
try:
|
||||
with transaction.atomic():
|
||||
action()
|
||||
except exception:
|
||||
return
|
||||
raise AssertionError(f"expected {exception.__name__}")
|
||||
|
||||
check("all_ordinary_users_have_policy", lambda: require(
|
||||
get_user_model().objects.exclude(pk=5).exclude(
|
||||
pk__in=AccountBandwidthPolicy.objects.values("user_id")).count() == 0, "missing ordinary policy"))
|
||||
check("all_ordinary_accounts_500_each_direction", lambda: require(
|
||||
not AccountBandwidthPolicy.objects.exclude(user_id=5).exclude(
|
||||
upload_limit_kib_per_second=500, download_limit_kib_per_second=500).exists(), "ordinary policy is not 500/500"))
|
||||
check("owner_fixed_id5_exemption_unchanged", lambda: require(
|
||||
list(AccountBandwidthExemption.objects.values_list("policy_key", "user_id")) == [("owner-approved-20261022", 5)],
|
||||
"expected existing fixed-ID owner exemption"))
|
||||
if before is not None:
|
||||
after = protected_snapshot()
|
||||
for key in ("owner_policy", "exemptions", "user_count"):
|
||||
check("migration_preserves_" + key, lambda key=key: require(
|
||||
json.dumps(after[key], sort_keys=True, default=str) == json.dumps(before[key], sort_keys=True, default=str), key + " changed"))
|
||||
check("default_is_500", lambda: require(
|
||||
AccountBandwidthPolicy._meta.get_field("upload_limit_kib_per_second").default == 500
|
||||
and AccountBandwidthPolicy._meta.get_field("download_limit_kib_per_second").default == 500, "default != 500"))
|
||||
check("admin_max_10240", lambda: require(policy.MAX_KIB_PER_SECOND == 10240, "max != 10240"))
|
||||
def migration_lock_order():
|
||||
module = importlib.import_module("shared_budget.migrations.0002_account_rate_500")
|
||||
first = module.Migration.operations[0]
|
||||
require(isinstance(first, migrations.RunPython) and first.code is module.lock_accounts_before_policy_ddl,
|
||||
"account lock must be first operation, before policy DDL")
|
||||
statements = []
|
||||
class Cursor:
|
||||
def __enter__(self):
|
||||
return self
|
||||
def __exit__(self, *args):
|
||||
return False
|
||||
def execute(self, sql):
|
||||
statements.append(sql)
|
||||
state = MigrationExecutor(connection).loader.project_state([("shared_budget", "0001_initial")]).apps
|
||||
first.code(state, SimpleNamespace(connection=SimpleNamespace(vendor="postgresql", ops=connection.ops, cursor=Cursor)))
|
||||
require(len(statements) == 2 and '"accounts_user" IN SHARE MODE' in statements[0]
|
||||
and '"shared_budget_accountbandwidthpolicy" IN SHARE ROW EXCLUSIVE MODE' in statements[1], "User must lock before Policy")
|
||||
check("migration_locks_user_before_any_policy_ddl", migration_lock_order)
|
||||
check("policy_501_converts_without_200_clamp", lambda: require(policy._limit_in_bytes(501) == 513024, "501 conversion"))
|
||||
check("policy_max_converts", lambda: require(policy._limit_in_bytes(10240) == 10485760, "10240 conversion"))
|
||||
for value in (0, -1, 10241, True, "500"):
|
||||
check("policy_rejects_" + type(value).__name__ + "_" + str(value), lambda value=value: rejected(lambda: policy._limit_in_bytes(value), ValueError))
|
||||
check("allocator_stays_disabled", lambda: require(
|
||||
getattr(settings, "ACCOUNT_BANDWIDTH_BUDGET_V2_ENABLED", False) is False
|
||||
and getattr(settings, "ACCOUNT_BANDWIDTH_BUDGET_ENABLED", False) is False, "allocator enabled"))
|
||||
factory = RequestFactory()
|
||||
for label, endpoint in (("credit", node_bandwidth_budget_v2), ("executor", node_budget_executor)):
|
||||
def disabled(endpoint=endpoint):
|
||||
response = endpoint(factory.post("/", "{}", content_type="application/json"))
|
||||
require(response.status_code == 503 and json.loads(response.content)["error_code"] == "budget_disabled", "API not disabled")
|
||||
check("disabled_" + label + "_api", disabled)
|
||||
|
||||
with transaction.atomic():
|
||||
user = get_user_model().objects.create_user(username="rate500-test-" + uuid.uuid4().hex,
|
||||
email=uuid.uuid4().hex + "@example.invalid", display_name="Isolated policy verification")
|
||||
row = AccountBandwidthPolicy.objects.get(user=user)
|
||||
check("new_user_signal_500_each_direction", lambda: require(
|
||||
(row.upload_limit_kib_per_second, row.download_limit_kib_per_second) == (500, 500), "new user defaults"))
|
||||
request = factory.get("/")
|
||||
request.user = get_user_model()(is_active=True, is_staff=True, is_superuser=True)
|
||||
form_type = admin.site._registry[AccountBandwidthPolicy].get_form(request, row)
|
||||
for value in (501, 10240):
|
||||
def form_valid(value=value):
|
||||
form = form_type(data={"upload_limit_kib_per_second": value, "download_limit_kib_per_second": value}, instance=row)
|
||||
require(form.is_valid(), str(form.errors))
|
||||
check("real_admin_form_accepts_" + str(value), form_valid)
|
||||
def model_valid(value=value):
|
||||
with transaction.atomic():
|
||||
row.upload_limit_kib_per_second = row.download_limit_kib_per_second = value
|
||||
row.full_clean()
|
||||
row.save()
|
||||
row.refresh_from_db()
|
||||
require(row.upload_limit_kib_per_second == value and row.download_limit_kib_per_second == value, "not stored")
|
||||
check("model_and_db_accept_" + str(value), model_valid)
|
||||
for value in (0, 10241):
|
||||
def invalid(value=value):
|
||||
row.upload_limit_kib_per_second = value
|
||||
rejected(row.full_clean, ValidationError)
|
||||
rejected(lambda: AccountBandwidthPolicy.objects.filter(user=user).update(download_limit_kib_per_second=value), IntegrityError)
|
||||
check("python_and_db_reject_" + str(value), invalid)
|
||||
def bucket_at_max():
|
||||
with transaction.atomic():
|
||||
AccountBandwidthBucket.objects.create(user=user, direction="upload", rate_bytes_per_second=10485760,
|
||||
available_microbytes=2097152000000, refilled_at=timezone.now())
|
||||
check("bucket_db_accepts_admin_max_rate_and_credit", bucket_at_max)
|
||||
check("bucket_db_rejects_above_max", lambda: rejected(lambda: AccountBandwidthBucket.objects.create(
|
||||
user=user, direction="download", rate_bytes_per_second=10485761, available_microbytes=0,
|
||||
refilled_at=timezone.now()), IntegrityError))
|
||||
check("bucket_db_rejects_above_credit_max", lambda: rejected(lambda: AccountBandwidthBucket.objects.create(
|
||||
user=user, direction="download", rate_bytes_per_second=512000, available_microbytes=2097152000001,
|
||||
refilled_at=timezone.now()), IntegrityError))
|
||||
check("portal_context_matches_500_and_max", lambda: require(
|
||||
portal_context(request)["admin_budget"]["default_upload"] == 500
|
||||
and portal_context(request)["admin_budget"]["default_download"] == 500
|
||||
and portal_context(request)["admin_budget"]["maximum_limit"] == 10240, "portal values"))
|
||||
def portal_template():
|
||||
rendered = render_to_string("includes/admin_budget.html", portal_context(request))
|
||||
require("500 KiB/s" in rendered and "10,240" not in rendered and "10240 KiB/s" in rendered
|
||||
and "1–200" not in rendered and "未开启" in rendered, "template range/default/state")
|
||||
check("actual_portal_template_500_and_max", portal_template)
|
||||
def database_defaults():
|
||||
AccountBandwidthPolicy.objects.filter(user=user).delete()
|
||||
table = connection.ops.quote_name(AccountBandwidthPolicy._meta.db_table)
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute("INSERT INTO " + table + " (user_id) VALUES (%s)", [user.pk])
|
||||
saved = AccountBandwidthPolicy.objects.get(user=user)
|
||||
require((saved.upload_limit_kib_per_second, saved.download_limit_kib_per_second) == (500, 500), "DB defaults")
|
||||
check("raw_insert_db_defaults_500", database_defaults)
|
||||
transaction.set_rollback(True)
|
||||
|
||||
def no_pending_migrations():
|
||||
call_command("makemigrations", "shared_budget", check=True, dry_run=True, stdout=io.StringIO())
|
||||
check("real_models_have_no_pending_migration", no_pending_migrations)
|
||||
check("all_real_apps_have_no_pending_migration", lambda: call_command(
|
||||
"makemigrations", check=True, dry_run=True, stdout=io.StringIO()))
|
||||
check("policy_retains_positive_small_integer_type", lambda: require(all(
|
||||
AccountBandwidthPolicy._meta.get_field(field).get_internal_type() == "PositiveSmallIntegerField"
|
||||
for field in ("upload_limit_kib_per_second", "download_limit_kib_per_second")), "policy field type changed"))
|
||||
return {"passed": all(checks.values()), "checks": checks, "errors": errors,
|
||||
"ordinary_account_count": get_user_model().objects.exclude(pk=5).count(),
|
||||
"allocator_enabled": False, "wire_enforcement_verified": False,
|
||||
"exercise_writes_rolled_back": True, "production_modified": False,
|
||||
"known_executor_max_bytes_per_second": 204800,
|
||||
"scope": "legacy shared_budget policy configuration only; no deployed 500 KiB/s enforcement claim"}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
snapshot_file = os.environ.get("RATE500_BEFORE_JSON")
|
||||
before = json.load(open(snapshot_file, encoding="utf-8")) if snapshot_file else None
|
||||
result = validate(before)
|
||||
print("RATE500_CLONE_VALIDATION=" + json.dumps(result, ensure_ascii=False, sort_keys=True, default=str))
|
||||
if not result["passed"]:
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Build an isolated legacy project and run real Django/DB checks, never live DB."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--stage", choices=("red", "green"), required=True)
|
||||
parser.add_argument("--run-id")
|
||||
args = parser.parse_args()
|
||||
candidate = Path(__file__).resolve().parents[1]
|
||||
def candidate_inputs():
|
||||
return {str(path.relative_to(candidate)).replace("\\", "/"): hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
for directory in (candidate / "overlay", candidate / "tests") for path in directory.rglob("*")
|
||||
if path.is_file() and path.suffix in (".py", ".html")}
|
||||
inputs_before = candidate_inputs()
|
||||
baseline = candidate.parent / "legacy-platform-fixture"
|
||||
run = candidate / "evidence" / (args.run_id or args.stage)
|
||||
run.mkdir(parents=True, exist_ok=False)
|
||||
project = run / "project"
|
||||
shutil.copytree(baseline, project, ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
|
||||
if args.stage == "green":
|
||||
for source in (candidate / "overlay").rglob("*"):
|
||||
if source.is_file():
|
||||
target = project / source.relative_to(candidate / "overlay")
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(source, target)
|
||||
os.environ.update(DJANGO_SETTINGS_MODULE="rate500_test_settings", DJANGO_SECRET_KEY="isolated-not-production",
|
||||
DJANGO_DEBUG="false", DJANGO_ALLOWED_HOSTS="localhost,127.0.0.1,testserver",
|
||||
ACCOUNT_BANDWIDTH_BUDGET_V2_ENABLED="false", ACCOUNT_BANDWIDTH_BUDGET_ENABLED="false")
|
||||
(project / "rate500_test_settings.py").write_text(
|
||||
"from toplc_vpn.test_settings import *\nDATABASES['default']['NAME'] = " + repr(str(run / "test.sqlite3")) + "\n", encoding="utf-8")
|
||||
sys.path.insert(0, str(project))
|
||||
import django
|
||||
django.setup()
|
||||
from django.core.management import call_command
|
||||
from django.db import connection
|
||||
from django.db.migrations.executor import MigrationExecutor
|
||||
call_command("migrate", "shared_budget", "0001", verbosity=0)
|
||||
state = MigrationExecutor(connection).loader.project_state([("shared_budget", "0001_initial")]).apps
|
||||
User = state.get_model("accounts", "User")
|
||||
Policy = state.get_model("shared_budget", "AccountBandwidthPolicy")
|
||||
Exemption = state.get_model("shared_budget", "AccountBandwidthExemption")
|
||||
for key in (1, 2, 5, 7):
|
||||
User.objects.create(id=key, username="fixture-" + str(key), email="owner@example.invalid" if key == 5 else f"fixture-{key}@example.invalid")
|
||||
if key != 7:
|
||||
Policy.objects.create(user_id=key, upload_limit_kib_per_second=111 if key == 5 else 200,
|
||||
download_limit_kib_per_second=123 if key == 5 else 150)
|
||||
Exemption.objects.create(policy_key="owner-approved-20261022", user_id=5)
|
||||
spec = importlib.util.spec_from_file_location("clone_validation", candidate / "tests/clone_validation.py")
|
||||
validation = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(validation)
|
||||
before = validation.protected_snapshot()
|
||||
def business_snapshot():
|
||||
result = {}
|
||||
with connection.cursor() as cursor:
|
||||
for table in sorted(connection.introspection.table_names()):
|
||||
if table.startswith(("accounts_", "control_", "shared_budget_")) and table != "shared_budget_accountbandwidthpolicy":
|
||||
cursor.execute("SELECT * FROM " + connection.ops.quote_name(table))
|
||||
rows = sorted(json.dumps(row, default=str, sort_keys=True) for row in cursor.fetchall())
|
||||
result[table] = hashlib.sha256("\n".join(rows).encode()).hexdigest()
|
||||
return result
|
||||
business_before = business_snapshot()
|
||||
has_migration = (project / "shared_budget/migrations/0002_account_rate_500.py").exists()
|
||||
plan = []
|
||||
if has_migration:
|
||||
plan = [(migration.app_label, migration.name, backwards) for migration, backwards in MigrationExecutor(connection).migration_plan([
|
||||
("shared_budget", "0002_account_rate_500")])]
|
||||
call_command("migrate", "shared_budget", "0002_account_rate_500", verbosity=0)
|
||||
business_after = business_snapshot()
|
||||
call_command("migrate", verbosity=0)
|
||||
result = validation.validate(before)
|
||||
result["checks"]["additive_0002_migration_present"] = has_migration
|
||||
result["checks"]["migration_plan_only_shared_budget_0002"] = plan == [("shared_budget", "0002_account_rate_500", False)]
|
||||
result["checks"]["migration_preserves_all_other_business_rows"] = business_before == business_after
|
||||
result["business_before_sha256"] = business_before
|
||||
result["business_after_sha256"] = business_after
|
||||
result["migration_plan"] = plan
|
||||
result["candidate_inputs_sha256"] = inputs_before
|
||||
result["checks"]["candidate_inputs_unchanged_during_test"] = inputs_before == candidate_inputs()
|
||||
result["passed"] = all(result["checks"].values())
|
||||
result["stage"] = args.stage
|
||||
result["django_version"] = django.get_version()
|
||||
result["database_vendor"] = connection.vendor
|
||||
result["inputs_sha256"] = {str(path.relative_to(project)).replace("\\", "/"): hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
for path in project.rglob("*") if path.is_file() and path.suffix in (".py", ".html") and "__pycache__" not in path.parts}
|
||||
(run / "result.json").write_text(json.dumps(result, ensure_ascii=False, indent=2, default=str), encoding="utf-8")
|
||||
print(json.dumps({key: value for key, value in result.items() if key != "inputs_sha256"}, ensure_ascii=False, indent=2))
|
||||
raise SystemExit(0 if result["passed"] else 1)
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 UCVL (Youchuang Future)
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,28 @@
|
||||
# 独立服务器 WAN 秒级采样
|
||||
|
||||
该进程与原有 `toplc-node-agent/1.1.0` 分开运行。它不修改 Xray、用户计费、代理配置、Tailscale、系统路由、防火墙或账号限速。
|
||||
|
||||
- 每 1 秒依据 monotonic 时钟读取 Linux `/proc/net/dev`。接口取主路由表的默认物理 WAN(先 IPv4,后 IPv6),排除 loopback、Tailscale、Docker、bridge、veth、tun/tap、WireGuard 等逻辑接口。
|
||||
- `rx_bytes` 为服务器 WAN 入站;`tx_bytes` 为服务器 WAN 出站。语义为 `server_host_interface` / `linux_proc_net_dev_interface_bytes`。这包括该网口上的主机流量和协议开销,不能当作个人代理计费流量,也不能与 Tailscale 逻辑流量相加。
|
||||
- 用原始 counter 差值除以实际 monotonic 时间间隔计算 B/s。首点、boot/接口变更、counter 复位、过长或无效间隔使用 `null`,不会伪造 0。真实零增量仍为 0。
|
||||
- 单独上传线程每 5 秒把最多 60 条样本 POST 到固定 HTTPS `https://vpn.example.invalid/api/v1/node/host-traffic/`。TLS 验证始终开启,不跟随重定向、不使用环境代理。请求超时不阻塞采样。
|
||||
- 内存队列最多 60 条;满时丢旧,在新样本标明 gap 和丢失数量。已排队样本不被修改,确保超时后重试数据仍幂等。丢失/延迟不是连续假曲线。
|
||||
- 每次进程启动生成新 UUID counter epoch;boot/接口/计数器复位亦生成新 epoch,避免进程崩溃重启后 sequence 唯一键冲突。没有凭证缓存或持久化队列。
|
||||
- 仅解析原 `node.env` 中 `NODE_SLUG`、`NODE_TOKEN` 两项,不执行该文件、不导出或记录其它密钥。上传凭证只保留内存。系统服务需要 root 读取原来的 0600 文件,capabilities 全部去除并启用只读系统沙箱。
|
||||
|
||||
输入契约 `contract: 1`:顶层 `node_slug/boot_id/interface/kind/counter_semantics/samples`;每样本 `sequence/observed_at/monotonic_ns/counter_epoch/interval_seconds/rx_bytes/tx_bytes/rx_bytes_per_second/tx_bytes_per_second/quality/gap_before/dropped_samples_before`。原始字节计数限制在 SQLite signed int64 范围。成功 2xx 表示整批持久化,失败不确认队列。后端未提供此端点时上传会安全失败,队列保持有界。
|
||||
|
||||
## 审核和安装
|
||||
|
||||
安装前必须先完成中央 ingest 端点。部署包仅包含本独立服务,可先执行:
|
||||
|
||||
```sh
|
||||
python3 -B host_traffic_sampler.py --node-env /opt/toplc-vpn-node/node.env --check-config
|
||||
```
|
||||
|
||||
`--check-config` 只读取本机接口和配置,既不发送网络请求,也不打印 token。由 root 审核冻结包 SHA256 后执行同包 `deploy_host_traffic_sampler.sh --install EXPECTED_NODE_SLUG`;该脚本会拒绝既有 sampler 安装及目标 slug 不一致,校验原主 agent/compose/env/service 文件前后 hash 相同,不修改原服务。安装过程失败时保留现场以供检查,不应盲目重试或删除旧现场。
|
||||
|
||||
离线测试:`python3 -m unittest discover -s . -p test_host_traffic_sampler.py -v`。测试不连接网络、不读生产凭证。
|
||||
|
||||
|
||||
MIT source supplement: these files are published as a separate directory only. They do not replace the platform root, existing routes, source history or other licenses. Integration tests use an existing Django platform model fixture; production model snapshots, accounts, tokens, SQLite state and local output evidence are not included. Configure example endpoints for your deployment. Source publication does not assert production acceptance.
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/bin/sh
|
||||
# Installs only this new sampler. Does not alter agent/Xray/env/network rules.
|
||||
set -eu
|
||||
umask 077
|
||||
if [ "$#" -ne 2 ] || [ "$1" != "--install" ]; then
|
||||
echo 'Usage: deploy_host_traffic_sampler.sh --install EXPECTED_NODE_SLUG' >&2
|
||||
exit 2
|
||||
fi
|
||||
test "$(id -u)" = 0
|
||||
BUNDLE=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)
|
||||
export PYTHONDONTWRITEBYTECODE=1
|
||||
python3 - "$BUNDLE" "$2" <<'PY'
|
||||
import hashlib,json,os,pathlib,re,shutil,stat,subprocess,sys
|
||||
from datetime import datetime,timezone
|
||||
bundle=pathlib.Path(sys.argv[1]);expected=sys.argv[2]
|
||||
assert re.fullmatch(r'[A-Za-z0-9_-]{1,120}',expected),'Invalid expected node slug'
|
||||
destination=pathlib.Path('/opt/toplc-vpn-host-traffic')
|
||||
unit=pathlib.Path('/etc/systemd/system/toplc-vpn-host-traffic.service')
|
||||
for path in (destination,unit):
|
||||
assert not path.exists() and not path.is_symlink(),'Sampler already exists; review prior attempt before changing it'
|
||||
for ancestor in path.parents:
|
||||
assert not ancestor.is_symlink(),'Linked installation parent refused'
|
||||
manifest=json.loads((bundle/'manifest.json').read_text())
|
||||
assert manifest['kind']=='toplc-host-traffic-sampler-bundle' and manifest['version']=='1.0.0'
|
||||
expected_files={'host_traffic_sampler.py','test_host_traffic_sampler.py','toplc-vpn-host-traffic.service','README.md','host-traffic-contract-fixture.json','deploy_host_traffic_sampler.sh'}
|
||||
assert set(manifest['files'])==expected_files,'Bundle inventory differs'
|
||||
assert {p.name for p in bundle.iterdir()}==expected_files|{'manifest.json'},'Unmanifested bundle files'
|
||||
def digest(path):return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
for name,value in manifest['files'].items():
|
||||
path=bundle/name
|
||||
assert path.is_file() and not path.is_symlink() and digest(path)==value,'Bundle hash mismatch'
|
||||
env=pathlib.Path('/opt/toplc-vpn-node/node.env')
|
||||
assert env.is_file() and not env.is_symlink() and env.stat().st_uid==0 and stat.S_IMODE(env.stat().st_mode)==0o600,'Expected root0600 node.env'
|
||||
agent=pathlib.Path('/opt/toplc-vpn-node/agent.py')
|
||||
compose=pathlib.Path('/opt/toplc-vpn-node/docker-compose.yml')
|
||||
agent_unit=pathlib.Path('/etc/systemd/system/toplc-vpn-node-agent.service')
|
||||
protected=[env,agent,compose,agent_unit]
|
||||
before={str(path):digest(path) for path in protected}
|
||||
# Import from verified bundle; reads only slug/token and never executes node.env.
|
||||
sys.path.insert(0,str(bundle))
|
||||
import host_traffic_sampler as sampler
|
||||
credentials=sampler.load_credentials(env)
|
||||
assert credentials.node_slug==expected,'Existing node slug differs'
|
||||
configuration=subprocess.run(['/usr/bin/python3','-B',str(bundle/'host_traffic_sampler.py'),'--check-config'],capture_output=True,text=True,timeout=10)
|
||||
assert configuration.returncode==0,'Sampler configuration or physical WAN detection failed'
|
||||
safe=json.loads(configuration.stdout)
|
||||
assert safe['node_slug']==expected and safe['configuration_valid'] is True and safe['network_requested'] is False
|
||||
subprocess.run(['systemd-analyze','verify',str(bundle/'toplc-vpn-host-traffic.service')],check=True,capture_output=True,timeout=15)
|
||||
destination.mkdir(mode=0o750)
|
||||
for name in ('host_traffic_sampler.py','README.md'):
|
||||
shutil.copyfile(bundle/name,destination/name);os.chmod(destination/name,0o600)
|
||||
assert digest(destination/name)==manifest['files'][name]
|
||||
shutil.copyfile(bundle/'toplc-vpn-host-traffic.service',unit);os.chmod(unit,0o644)
|
||||
assert digest(unit)==manifest['files']['toplc-vpn-host-traffic.service']
|
||||
subprocess.run(['systemctl','daemon-reload'],check=True,timeout=20)
|
||||
subprocess.run(['systemctl','enable','--now','toplc-vpn-host-traffic.service'],check=True,capture_output=True,timeout=20)
|
||||
subprocess.run(['systemctl','is-active','--quiet','toplc-vpn-host-traffic.service'],check=True,timeout=10)
|
||||
after={str(path):digest(path) for path in protected}
|
||||
assert before==after,'Protected existing deployment files changed; inspect external activity'
|
||||
receipt={'kind':'toplc-host-traffic-sampler-install','version':'1.0.0','node_slug':expected,'interface':safe['interface'],'kind_semantics':'server_host_interface','counter_semantics':'linux_proc_net_dev_interface_bytes','sample_seconds':1,'upload_seconds':5,'queue_capacity':60,'protected_existing_files_unchanged':True,'network_rules_modified':False,'existing_agent_restarted':False,'xray_restarted':False,'new_sampler_active':True,'installed_at':datetime.now(timezone.utc).isoformat(),'bundle_files':manifest['files']}
|
||||
with (destination/'install-receipt.json').open('x') as handle:json.dump(receipt,handle,indent=2);handle.write('\n')
|
||||
print(json.dumps(receipt))
|
||||
PY
|
||||
@@ -0,0 +1,80 @@
|
||||
{
|
||||
"contract": 1,
|
||||
"node_slug": "node-example",
|
||||
"boot_id": "dd268f12-470c-4b7a-bb6a-3960072d659d",
|
||||
"interface": "eth0",
|
||||
"kind": "server_host_interface",
|
||||
"counter_semantics": "linux_proc_net_dev_interface_bytes",
|
||||
"samples": [
|
||||
{
|
||||
"sequence": 1,
|
||||
"observed_at": "2026-11-06T06:00:01+00:00",
|
||||
"monotonic_ns": 1000000000,
|
||||
"counter_epoch": "d1e2d7e0-f808-41d6-b901-6ed62d853f41",
|
||||
"interval_seconds": 0.0,
|
||||
"rx_bytes": 1000,
|
||||
"tx_bytes": 500,
|
||||
"rx_bytes_per_second": null,
|
||||
"tx_bytes_per_second": null,
|
||||
"quality": "baseline",
|
||||
"gap_before": false,
|
||||
"dropped_samples_before": 0
|
||||
},
|
||||
{
|
||||
"sequence": 2,
|
||||
"observed_at": "2026-11-06T06:00:02+00:00",
|
||||
"monotonic_ns": 2000000000,
|
||||
"counter_epoch": "d1e2d7e0-f808-41d6-b901-6ed62d853f41",
|
||||
"interval_seconds": 1.0,
|
||||
"rx_bytes": 1200,
|
||||
"tx_bytes": 600,
|
||||
"rx_bytes_per_second": 200.0,
|
||||
"tx_bytes_per_second": 100.0,
|
||||
"quality": "ok",
|
||||
"gap_before": false,
|
||||
"dropped_samples_before": 0
|
||||
},
|
||||
{
|
||||
"sequence": 3,
|
||||
"observed_at": "2026-11-06T06:00:03+00:00",
|
||||
"monotonic_ns": 3000000000,
|
||||
"counter_epoch": "d1e2d7e0-f808-41d6-b901-6ed62d853f41",
|
||||
"interval_seconds": 1.0,
|
||||
"rx_bytes": 2000,
|
||||
"tx_bytes": 900,
|
||||
"rx_bytes_per_second": 800.0,
|
||||
"tx_bytes_per_second": 300.0,
|
||||
"quality": "ok",
|
||||
"gap_before": false,
|
||||
"dropped_samples_before": 0
|
||||
},
|
||||
{
|
||||
"sequence": 4,
|
||||
"observed_at": "2026-11-06T06:00:04+00:00",
|
||||
"monotonic_ns": 4000000000,
|
||||
"counter_epoch": "07f62eea-dfd6-449f-a80e-b6557bdef373",
|
||||
"interval_seconds": 1.0,
|
||||
"rx_bytes": 20,
|
||||
"tx_bytes": 10,
|
||||
"rx_bytes_per_second": null,
|
||||
"tx_bytes_per_second": null,
|
||||
"quality": "reset",
|
||||
"gap_before": true,
|
||||
"dropped_samples_before": 0
|
||||
},
|
||||
{
|
||||
"sequence": 5,
|
||||
"observed_at": "2026-11-06T06:00:05+00:00",
|
||||
"monotonic_ns": 5000000000,
|
||||
"counter_epoch": "07f62eea-dfd6-449f-a80e-b6557bdef373",
|
||||
"interval_seconds": 1.0,
|
||||
"rx_bytes": 100,
|
||||
"tx_bytes": 50,
|
||||
"rx_bytes_per_second": 80.0,
|
||||
"tx_bytes_per_second": 40.0,
|
||||
"quality": "ok",
|
||||
"gap_before": false,
|
||||
"dropped_samples_before": 0
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One-second physical WAN byte samples; independent of Xray/config/billing.
|
||||
|
||||
Linux /proc/net/dev RX means bytes into the server's default physical WAN
|
||||
interface. TX means bytes out. These are host-interface counters, not per-user
|
||||
proxy usage, application payload, or Tailscale logical-interface counters.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from collections import deque
|
||||
import copy
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import signal
|
||||
import ssl
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
VERSION = "toplc-host-traffic/1.0.0"
|
||||
ENDPOINT = "https://vpn.example.invalid/api/v1/node/host-traffic/"
|
||||
MAX_COUNTER = 2**63 - 1
|
||||
MAX_SEQUENCE = 2**53 - 1
|
||||
MAX_BATCH_BYTES = 64 * 1024
|
||||
SAMPLE_SECONDS = 1.0
|
||||
UPLOAD_SECONDS = 5.0
|
||||
QUEUE_CAPACITY = 60
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Credentials:
|
||||
node_slug: str
|
||||
token: str = field(repr=False)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Snapshot:
|
||||
boot_id: str
|
||||
interface: str
|
||||
rx_bytes: int
|
||||
tx_bytes: int
|
||||
monotonic_ns: int
|
||||
observed_at: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Envelope:
|
||||
boot_id: str
|
||||
interface: str
|
||||
sample: dict
|
||||
|
||||
|
||||
def load_credentials(path: Path) -> Credentials:
|
||||
# Read only these two data values; never source/evaluate an env file or copy
|
||||
# Reality credentials into os.environ, output, state, or an upload payload.
|
||||
wanted = {}
|
||||
for line in Path(path).read_text(encoding="utf-8").splitlines():
|
||||
key, separator, value = line.partition("=")
|
||||
key = key.strip()
|
||||
if not separator or key not in {"NODE_SLUG", "NODE_TOKEN"}:
|
||||
continue
|
||||
value = value.strip()
|
||||
if len(value) >= 2 and value[0] == value[-1] and value[0] in {"'", '"'}:
|
||||
value = value[1:-1]
|
||||
if key in wanted:
|
||||
raise ValueError("Duplicate node credential field")
|
||||
wanted[key] = value
|
||||
slug, token = wanted.get("NODE_SLUG", ""), wanted.get("NODE_TOKEN", "")
|
||||
if not re.fullmatch(r"[A-Za-z0-9_-]{1,120}", slug):
|
||||
raise ValueError("Invalid or missing node slug")
|
||||
if not re.fullmatch(r"[A-Za-z0-9._~+/-]{1,512}=*", token):
|
||||
raise ValueError("Invalid or missing node token")
|
||||
return Credentials(slug, token)
|
||||
|
||||
|
||||
class ProcWanReader:
|
||||
EXCLUDED = ("lo", "tailscale", "docker", "veth", "br-", "virbr", "tun", "tap", "wg")
|
||||
|
||||
def __init__(self, proc: Path = Path("/proc"), sysfs: Path = Path("/sys")):
|
||||
self.proc, self.sysfs = Path(proc), Path(sysfs)
|
||||
|
||||
def physical(self, name: str) -> bool:
|
||||
if not re.fullmatch(r"[A-Za-z0-9_.-]{1,15}", name) or name.startswith(self.EXCLUDED):
|
||||
return False
|
||||
path = self.sysfs / "class/net" / name
|
||||
try:
|
||||
return (path / "device").exists() and (path / "type").read_text().strip() == "1"
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
def default_interface(self) -> str:
|
||||
routes = []
|
||||
try:
|
||||
for line in (self.proc / "net/route").read_text().splitlines()[1:]:
|
||||
fields = line.split()
|
||||
if len(fields) >= 8 and fields[1] == "00000000" and fields[7] == "00000000":
|
||||
if int(fields[3], 16) & 1 and self.physical(fields[0]):
|
||||
routes.append((int(fields[6]), fields[0]))
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
if not routes:
|
||||
try:
|
||||
for line in (self.proc / "net/ipv6_route").read_text().splitlines():
|
||||
fields = line.split()
|
||||
if len(fields) >= 10 and fields[0] == "0" * 32 and fields[1] == "00":
|
||||
if int(fields[8], 16) & 1 and self.physical(fields[9]):
|
||||
routes.append((int(fields[5], 16), fields[9]))
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
if not routes:
|
||||
raise OSError("No default physical WAN interface available")
|
||||
return min(routes)[1]
|
||||
|
||||
def read(self) -> Snapshot:
|
||||
interface = self.default_interface()
|
||||
boot_id = str(uuid.UUID((self.proc / "sys/kernel/random/boot_id").read_text().strip()))
|
||||
for line in (self.proc / "net/dev").read_text().splitlines():
|
||||
name, separator, counters = line.partition(":")
|
||||
if separator and name.strip() == interface:
|
||||
values = counters.split()
|
||||
if len(values) < 16:
|
||||
raise OSError("Incomplete physical WAN counters")
|
||||
return Snapshot(boot_id, interface, int(values[0]), int(values[8]),
|
||||
time.monotonic_ns(), datetime.now(timezone.utc).isoformat())
|
||||
raise OSError("Default physical WAN interface counters unavailable")
|
||||
|
||||
|
||||
class CounterTracker:
|
||||
def __init__(self):
|
||||
self.previous = None
|
||||
self.counter_epoch = str(uuid.uuid4())
|
||||
self.sequence = 0
|
||||
self.missing = 0
|
||||
|
||||
def note_missing(self, count: int = 1):
|
||||
self.sequence += count
|
||||
self.missing += count
|
||||
|
||||
def observe(self, snapshot: Snapshot) -> Envelope:
|
||||
for value in (snapshot.rx_bytes, snapshot.tx_bytes):
|
||||
if type(value) is not int or not 0 <= value <= MAX_COUNTER:
|
||||
raise ValueError("WAN counter outside signed-64-bit contract")
|
||||
if type(snapshot.monotonic_ns) is not int or snapshot.monotonic_ns < 1:
|
||||
raise ValueError("Positive monotonic timestamp required")
|
||||
boot_id = str(uuid.UUID(snapshot.boot_id))
|
||||
previous = self.previous
|
||||
elapsed = 0.0 if previous is None else (snapshot.monotonic_ns - previous.monotonic_ns) / 1e9
|
||||
quality, rx_rate, tx_rate = "baseline", None, None
|
||||
if previous is not None:
|
||||
if boot_id != str(uuid.UUID(previous.boot_id)):
|
||||
quality, elapsed = "boot_changed", 0.0
|
||||
elif snapshot.interface != previous.interface:
|
||||
quality = "interface_changed"
|
||||
elif snapshot.rx_bytes < previous.rx_bytes or snapshot.tx_bytes < previous.tx_bytes:
|
||||
quality = "reset"
|
||||
elif not 0.5 <= elapsed <= 3.0:
|
||||
quality = "gap"
|
||||
else:
|
||||
quality = "ok"
|
||||
rx_rate = (snapshot.rx_bytes - previous.rx_bytes) / elapsed
|
||||
tx_rate = (snapshot.tx_bytes - previous.tx_bytes) / elapsed
|
||||
if max(rx_rate, tx_rate) > 1e12:
|
||||
quality, rx_rate, tx_rate = "gap", None, None
|
||||
if quality in {"boot_changed", "interface_changed", "reset"}:
|
||||
self.counter_epoch = str(uuid.uuid4())
|
||||
elif quality == "gap" and elapsed <= 0:
|
||||
self.counter_epoch = str(uuid.uuid4())
|
||||
self.sequence += 1
|
||||
if self.sequence > MAX_SEQUENCE:
|
||||
# Practically unreachable (>285M years at 1 Hz); still no key reuse.
|
||||
self.counter_epoch, self.sequence = str(uuid.uuid4()), 1
|
||||
quality, rx_rate, tx_rate = "baseline", None, None
|
||||
row = {"sequence": self.sequence, "observed_at": snapshot.observed_at,
|
||||
"monotonic_ns": snapshot.monotonic_ns, "counter_epoch": self.counter_epoch,
|
||||
"interval_seconds": max(0.0, elapsed), "rx_bytes": snapshot.rx_bytes,
|
||||
"tx_bytes": snapshot.tx_bytes, "rx_bytes_per_second": rx_rate,
|
||||
"tx_bytes_per_second": tx_rate, "quality": quality,
|
||||
"gap_before": bool(self.missing or quality not in {"baseline", "ok"}),
|
||||
"dropped_samples_before": 0}
|
||||
self.previous, self.missing = snapshot, 0
|
||||
return Envelope(boot_id, snapshot.interface, row)
|
||||
|
||||
|
||||
class BoundedSampleQueue:
|
||||
def __init__(self, capacity: int = QUEUE_CAPACITY):
|
||||
if type(capacity) is not int or not 1 <= capacity <= QUEUE_CAPACITY:
|
||||
raise ValueError("Queue capacity outside contract")
|
||||
self.capacity, self.rows, self.lock = capacity, deque(), threading.Lock()
|
||||
|
||||
def put(self, envelope: Envelope):
|
||||
# Never mutate an already queued/transmitted record: an HTTP timeout may
|
||||
# hide a committed batch, and retry bytes must remain idempotent.
|
||||
row = copy.deepcopy(envelope.sample)
|
||||
with self.lock:
|
||||
if len(self.rows) >= self.capacity:
|
||||
dropped = self.rows.popleft()
|
||||
row["gap_before"] = True
|
||||
row["dropped_samples_before"] += 1 + dropped.sample["dropped_samples_before"]
|
||||
self.rows.append(Envelope(envelope.boot_id, envelope.interface, row))
|
||||
|
||||
def batch(self, limit: int = QUEUE_CAPACITY) -> list[Envelope]:
|
||||
with self.lock:
|
||||
if not self.rows:
|
||||
return []
|
||||
group = self.rows[0].boot_id, self.rows[0].interface
|
||||
result = []
|
||||
for row in self.rows:
|
||||
if len(result) >= min(limit, QUEUE_CAPACITY) or (row.boot_id, row.interface) != group:
|
||||
break
|
||||
result.append(copy.deepcopy(row))
|
||||
return result
|
||||
|
||||
def acknowledge(self, batch: list[Envelope]):
|
||||
keys = {(row.sample["counter_epoch"], row.sample["sequence"]) for row in batch}
|
||||
with self.lock:
|
||||
self.rows = deque(row for row in self.rows
|
||||
if (row.sample["counter_epoch"], row.sample["sequence"]) not in keys)
|
||||
|
||||
|
||||
def build_payload(batch: list[Envelope], node_slug: str) -> dict:
|
||||
if not 1 <= len(batch) <= QUEUE_CAPACITY:
|
||||
raise ValueError("Empty or oversized upload batch")
|
||||
first = batch[0]
|
||||
if any((row.boot_id, row.interface) != (first.boot_id, first.interface) for row in batch):
|
||||
raise ValueError("Mixed interface or boot in upload batch")
|
||||
return {"contract": 1, "node_slug": node_slug, "boot_id": first.boot_id,
|
||||
"interface": first.interface, "kind": "server_host_interface",
|
||||
"counter_semantics": "linux_proc_net_dev_interface_bytes",
|
||||
"samples": [copy.deepcopy(row.sample) for row in batch]}
|
||||
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
raise urllib.error.HTTPError(newurl, code, "Host traffic redirects are refused", headers, fp)
|
||||
|
||||
|
||||
class HttpTransport:
|
||||
def __init__(self, endpoint: str = ENDPOINT):
|
||||
parsed = urllib.parse.urlsplit(endpoint)
|
||||
if (parsed.scheme != "https" or parsed.hostname != "vpn.example.invalid"
|
||||
or parsed.port not in {None, 443} or parsed.username or parsed.password
|
||||
or parsed.path != "/api/v1/node/host-traffic/" or parsed.query or parsed.fragment):
|
||||
raise ValueError("Untrusted host traffic endpoint")
|
||||
self.endpoint = endpoint
|
||||
self.ssl_context = ssl.create_default_context()
|
||||
self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}),
|
||||
urllib.request.HTTPSHandler(context=self.ssl_context), NoRedirect())
|
||||
|
||||
def send(self, payload: dict, credentials: Credentials):
|
||||
body = json.dumps(payload, separators=(",", ":"), allow_nan=False).encode("utf-8")
|
||||
if len(body) > MAX_BATCH_BYTES:
|
||||
raise ValueError("Host traffic batch exceeds 64 KiB")
|
||||
request = urllib.request.Request(self.endpoint, data=body, method="POST", headers={
|
||||
"Authorization": "Bearer " + credentials.token, "X-Node-Slug": credentials.node_slug,
|
||||
"X-Agent-Version": VERSION, "User-Agent": VERSION, "Content-Type": "application/json"})
|
||||
with self.opener.open(request, timeout=8) as response:
|
||||
if not 200 <= response.status < 300:
|
||||
raise OSError("Host traffic batch was not committed")
|
||||
response.read(4096) # Body is not logged; HTTP 2xx acknowledges durable whole batch.
|
||||
|
||||
|
||||
class Uploader(threading.Thread):
|
||||
def __init__(self, queue: BoundedSampleQueue, credentials: Credentials, transport,
|
||||
stop: threading.Event, interval: float = UPLOAD_SECONDS, log=None):
|
||||
super().__init__(name="host-traffic-uploader", daemon=True)
|
||||
self.queue, self.credentials, self.transport, self.stop = queue, credentials, transport, stop
|
||||
self.interval = interval
|
||||
self.log = log or (lambda text: print(text, file=sys.stderr, flush=True))
|
||||
self.last_error_log = -1e30
|
||||
|
||||
def upload_once(self) -> bool:
|
||||
batch = self.queue.batch()
|
||||
if not batch:
|
||||
return True
|
||||
try:
|
||||
self.transport.send(build_payload(batch, self.credentials.node_slug), self.credentials)
|
||||
self.queue.acknowledge(batch)
|
||||
return True
|
||||
except Exception as error:
|
||||
# Never include request, headers, response body, exception text, or
|
||||
# credential objects. Failures are bounded and cannot block sampling.
|
||||
now = time.monotonic()
|
||||
if now - self.last_error_log >= 60:
|
||||
status = error.code if isinstance(error, urllib.error.HTTPError) else "none"
|
||||
self.log("host-traffic upload failed: type=" + type(error).__name__ + ",status=" + str(status))
|
||||
self.last_error_log = now
|
||||
return False
|
||||
|
||||
def run(self):
|
||||
while not self.stop.wait(self.interval):
|
||||
self.upload_once()
|
||||
|
||||
|
||||
def run_sampler(reader, queue: BoundedSampleQueue, tracker: CounterTracker,
|
||||
stop: threading.Event, log=None):
|
||||
log = log or (lambda text: print(text, file=sys.stderr, flush=True))
|
||||
deadline, last_error_log = time.monotonic(), -1e30
|
||||
while not stop.is_set():
|
||||
if stop.wait(max(0.0, deadline - time.monotonic())):
|
||||
break
|
||||
try:
|
||||
queue.put(tracker.observe(reader.read()))
|
||||
except (OSError, ValueError):
|
||||
tracker.note_missing()
|
||||
now = time.monotonic()
|
||||
if now - last_error_log >= 60:
|
||||
log("host-traffic sample unavailable; next valid sample will mark a gap")
|
||||
last_error_log = now
|
||||
deadline += SAMPLE_SECONDS
|
||||
now = time.monotonic()
|
||||
if deadline <= now:
|
||||
skipped = int((now - deadline) // SAMPLE_SECONDS) + 1
|
||||
tracker.note_missing(skipped)
|
||||
deadline += skipped * SAMPLE_SECONDS
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--node-env", type=Path, default=Path("/opt/toplc-vpn-node/node.env"))
|
||||
parser.add_argument("--check-config", action="store_true")
|
||||
args = parser.parse_args(argv)
|
||||
credentials = load_credentials(args.node_env)
|
||||
reader = ProcWanReader()
|
||||
if args.check_config:
|
||||
snapshot = reader.read()
|
||||
print(json.dumps({"version": VERSION, "node_slug": credentials.node_slug,
|
||||
"interface": snapshot.interface, "kind": "server_host_interface",
|
||||
"counter_semantics": "linux_proc_net_dev_interface_bytes", "configuration_valid": True,
|
||||
"network_requested": False, "token_printed": False}))
|
||||
return 0
|
||||
stop = threading.Event()
|
||||
for name in (signal.SIGTERM, signal.SIGINT):
|
||||
signal.signal(name, lambda *_: stop.set())
|
||||
queue, tracker = BoundedSampleQueue(), CounterTracker()
|
||||
uploader = Uploader(queue, credentials, HttpTransport(), stop)
|
||||
uploader.start()
|
||||
try:
|
||||
run_sampler(reader, queue, tracker, stop)
|
||||
finally:
|
||||
stop.set()
|
||||
uploader.join(timeout=9)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except (OSError, ValueError):
|
||||
print("host-traffic startup refused: invalid or unreadable configuration", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,211 @@
|
||||
"""Offline contract and failure-path tests; never opens a network connection."""
|
||||
import copy
|
||||
from datetime import datetime, timezone
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
HERE=Path(__file__).resolve().parent
|
||||
sys.path.insert(0,str(HERE))
|
||||
import host_traffic_sampler as target
|
||||
|
||||
BOOT='dd268f12-470c-4b7a-bb6a-3960072d659d'
|
||||
OTHER_BOOT='8de4d479-f314-4f3d-aa17-a160053b3ac9'
|
||||
|
||||
def snap(rx=1000,tx=500,seconds=1,interface='eth0',boot=BOOT):
|
||||
return target.Snapshot(boot,interface,rx,tx,int(seconds*1_000_000_000),'2026-11-06T06:00:00+00:00')
|
||||
|
||||
class TrackerTests(unittest.TestCase):
|
||||
def test_first_counter_is_baseline_not_zero_speed(self):
|
||||
row=target.CounterTracker().observe(snap()).sample
|
||||
self.assertEqual(row['quality'],'baseline')
|
||||
self.assertIsNone(row['rx_bytes_per_second']);self.assertIsNone(row['tx_bytes_per_second'])
|
||||
self.assertEqual(row['interval_seconds'],0)
|
||||
def test_real_elapsed_monotonic_rates_not_wall_clock(self):
|
||||
tracker=target.CounterTracker();tracker.observe(snap())
|
||||
current=snap(1600,800,2.2)
|
||||
current=target.Snapshot(current.boot_id,current.interface,current.rx_bytes,current.tx_bytes,current.monotonic_ns,'2020-01-01T00:00:00+00:00')
|
||||
row=tracker.observe(current).sample
|
||||
self.assertEqual(row['quality'],'ok');self.assertAlmostEqual(row['interval_seconds'],1.2)
|
||||
self.assertAlmostEqual(row['rx_bytes_per_second'],500);self.assertAlmostEqual(row['tx_bytes_per_second'],250)
|
||||
def test_zero_actual_delta_is_valid_zero(self):
|
||||
tracker=target.CounterTracker();tracker.observe(snap())
|
||||
row=tracker.observe(snap(seconds=2)).sample
|
||||
self.assertEqual(row['quality'],'ok');self.assertEqual(row['rx_bytes_per_second'],0)
|
||||
def test_either_counter_decrease_starts_new_epoch_without_negative_rates(self):
|
||||
for rx,tx in ((20,600),(1100,20)):
|
||||
tracker=target.CounterTracker();old=tracker.observe(snap())
|
||||
new=tracker.observe(snap(rx,tx,2))
|
||||
self.assertEqual(new.sample['quality'],'reset');self.assertNotEqual(old.sample['counter_epoch'],new.sample['counter_epoch'])
|
||||
self.assertIsNone(new.sample['rx_bytes_per_second']);self.assertIsNone(new.sample['tx_bytes_per_second'])
|
||||
def test_boot_and_interface_changes_are_gaps_with_new_epochs(self):
|
||||
for current,quality in ((snap(1500,700,2,boot=OTHER_BOOT),'boot_changed'),(snap(1500,700,2,interface='ens3'),'interface_changed')):
|
||||
tracker=target.CounterTracker();old=tracker.observe(snap());new=tracker.observe(current)
|
||||
self.assertEqual(new.sample['quality'],quality);self.assertTrue(new.sample['gap_before'])
|
||||
self.assertNotEqual(old.sample['counter_epoch'],new.sample['counter_epoch'])
|
||||
self.assertIsNone(new.sample['rx_bytes_per_second'])
|
||||
def test_long_or_nonpositive_intervals_do_not_make_fake_rates(self):
|
||||
for seconds in (1,0.5,1.1,5):
|
||||
tracker=target.CounterTracker();tracker.observe(snap());row=tracker.observe(snap(1500,800,seconds)).sample
|
||||
self.assertEqual(row['quality'],'gap');self.assertTrue(row['gap_before']);self.assertIsNone(row['rx_bytes_per_second'])
|
||||
def test_restart_uuid_separates_sequence_one(self):
|
||||
a=target.CounterTracker().observe(snap()).sample;b=target.CounterTracker().observe(snap()).sample
|
||||
self.assertEqual(a['sequence'],1);self.assertEqual(b['sequence'],1);self.assertNotEqual(a['counter_epoch'],b['counter_epoch'])
|
||||
def test_failed_capture_advances_sequence_and_marks_next_sample(self):
|
||||
tracker=target.CounterTracker();tracker.observe(snap());tracker.note_missing(2)
|
||||
row=tracker.observe(snap(1500,800,4)).sample
|
||||
self.assertEqual(row['sequence'],4);self.assertTrue(row['gap_before'])
|
||||
def test_int63_limit_and_invalid_counter_rejected(self):
|
||||
for value in (-1,2**63,True,1.2):
|
||||
with self.subTest(value=value),self.assertRaises(ValueError):target.CounterTracker().observe(snap(rx=value))
|
||||
|
||||
class QueueTests(unittest.TestCase):
|
||||
def test_queue_bounds_and_explicit_old_sample_gap(self):
|
||||
queue=target.BoundedSampleQueue(3);tracker=target.CounterTracker()
|
||||
for i in range(1,7):queue.put(tracker.observe(snap(1000+i,500+i,i)))
|
||||
rows=queue.batch()
|
||||
self.assertEqual(len(rows),3);self.assertEqual([x.sample['sequence'] for x in rows],[4,5,6])
|
||||
self.assertTrue(all(x.sample['gap_before'] for x in rows))
|
||||
self.assertEqual(sum(x.sample['dropped_samples_before'] for x in rows),3)
|
||||
def test_inflight_retry_record_is_immutable_when_queue_drops_older_samples(self):
|
||||
queue=target.BoundedSampleQueue(3);tracker=target.CounterTracker()
|
||||
for i in range(1,4):queue.put(tracker.observe(snap(1000+i,500+i,i)))
|
||||
inflight=queue.batch();original=copy.deepcopy(inflight[1].sample)
|
||||
queue.put(tracker.observe(snap(2000,1000,4)))
|
||||
self.assertEqual(queue.batch()[0].sample,original)
|
||||
def test_batch_group_does_not_mislabel_interface_or_boot(self):
|
||||
queue=target.BoundedSampleQueue();tracker=target.CounterTracker()
|
||||
queue.put(tracker.observe(snap()));queue.put(tracker.observe(snap(1600,700,2,interface='ens3')))
|
||||
first=queue.batch();self.assertEqual(len(first),1);self.assertEqual(first[0].interface,'eth0')
|
||||
queue.acknowledge(first);self.assertEqual(queue.batch()[0].interface,'ens3')
|
||||
def test_ack_does_not_remove_later_or_dropped_unacknowledged_rows(self):
|
||||
queue=target.BoundedSampleQueue(2);tracker=target.CounterTracker()
|
||||
queue.put(tracker.observe(snap()));sent=queue.batch()
|
||||
queue.put(tracker.observe(snap(1500,700,2)));queue.put(tracker.observe(snap(1700,900,3)))
|
||||
queue.acknowledge(sent)
|
||||
self.assertEqual([x.sample['sequence'] for x in queue.batch()],[2,3])
|
||||
def test_upload_failure_keeps_queue_and_sampling_independent(self):
|
||||
entered=threading.Event();release=threading.Event();stop=threading.Event()
|
||||
class SlowTransport:
|
||||
def send(self,*args):entered.set();release.wait(2);raise TimeoutError('offline failure')
|
||||
queue=target.BoundedSampleQueue();tracker=target.CounterTracker();queue.put(tracker.observe(snap()))
|
||||
worker=target.Uploader(queue,target.Credentials('node-example','secret-not-logged'),SlowTransport(),stop,interval=.01,log=lambda text:None)
|
||||
worker.start();self.assertTrue(entered.wait(1))
|
||||
started=time.monotonic()
|
||||
for i in range(2,70):queue.put(tracker.observe(snap(i*2000,i*500,i)))
|
||||
self.assertLess(time.monotonic()-started,.5);self.assertEqual(len(queue.batch()),60)
|
||||
stop.set();release.set();worker.join(2);self.assertFalse(worker.is_alive());self.assertEqual(len(queue.batch()),60)
|
||||
def test_transport_success_acknowledges_only_transmitted_prefix(self):
|
||||
queue=target.BoundedSampleQueue();tracker=target.CounterTracker();queue.put(tracker.observe(snap()))
|
||||
class Success:
|
||||
def send(self,payload,credentials):
|
||||
queue.put(tracker.observe(snap(1200,600,2)))
|
||||
worker=target.Uploader(queue,target.Credentials('node-example','secret-not-logged'),Success(),threading.Event(),log=lambda text:None)
|
||||
self.assertTrue(worker.upload_once());self.assertEqual([x.sample['sequence'] for x in queue.batch()],[2])
|
||||
|
||||
class ReaderAndContractTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp=tempfile.TemporaryDirectory();self.addCleanup(self.temp.cleanup);self.root=Path(self.temp.name)
|
||||
self.proc=self.root/'proc';self.sys=self.root/'sys';(self.proc/'net').mkdir(parents=True)
|
||||
(self.proc/'sys/kernel/random').mkdir(parents=True);(self.proc/'sys/kernel/random/boot_id').write_text(BOOT)
|
||||
(self.proc/'net/route').write_text('Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT\ntailscale0 00000000 0100007F 0003 0 0 0 00000000 0 0 0\ndocker0 00000000 0100007F 0003 0 0 1 00000000 0 0 0\nens3 00000000 0100007F 0003 0 0 10 00000000 0 0 0\neth0 00000000 0100007F 0003 0 0 20 00000000 0 0 0\n')
|
||||
(self.proc/'net/dev').write_text('Inter-| Receive | Transmit\n face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed\n eth0: 1000 1 0 0 0 0 0 0 500 1 0 0 0 0 0 0\n ens3: 2000 1 0 0 0 0 0 0 800 1 0 0 0 0 0 0\n tailscale0: 999999 1 0 0 0 0 0 0 888888 1 0 0 0 0 0 0\n')
|
||||
for name in ('eth0','ens3'):
|
||||
path=self.sys/'class/net'/name;(path/'device').mkdir(parents=True);(path/'type').write_text('1')
|
||||
def test_default_wan_uses_lowest_metric_physical_interface_only(self):
|
||||
reader=target.ProcWanReader(self.proc,self.sys);row=reader.read()
|
||||
self.assertEqual(row.interface,'ens3');self.assertEqual(row.rx_bytes,2000);self.assertEqual(row.tx_bytes,800)
|
||||
def test_no_default_physical_wan_raises_instead_of_zero_or_tailscale(self):
|
||||
(self.proc/'net/route').write_text('Iface Destination Gateway Flags RefCnt Use Metric Mask\ntailscale0 00000000 0100007F 0003 0 0 0 00000000\n')
|
||||
with self.assertRaises(OSError):target.ProcWanReader(self.proc,self.sys).read()
|
||||
def test_credentials_ignore_other_node_env_secrets_and_never_repr_token(self):
|
||||
path=self.root/'node.env';path.write_text('NODE_SLUG=node-example\nNODE_TOKEN="test-secret"\nREALITY_PRIVATE_KEY=do-not-use\nXRAY_PORT=11084\n')
|
||||
credentials=target.load_credentials(path)
|
||||
self.assertEqual(credentials.node_slug,'node-example');self.assertEqual(credentials.token,'test-secret')
|
||||
self.assertNotIn('test-secret',repr(credentials));self.assertFalse(hasattr(credentials,'private_key'))
|
||||
def test_header_injection_or_missing_credentials_refused(self):
|
||||
for content in ('NODE_SLUG=node-example\n','NODE_SLUG=evil user\nNODE_TOKEN=secret\n','NODE_SLUG=node-example\nNODE_TOKEN="bad token"\n'):
|
||||
path=self.root/'node.env';path.write_text(content)
|
||||
with self.assertRaises(ValueError):target.load_credentials(path)
|
||||
def test_contract_is_real_host_rx_tx_with_nullable_baseline(self):
|
||||
tracker=target.CounterTracker();batch=[tracker.observe(snap()),tracker.observe(snap(1600,800,2))]
|
||||
payload=target.build_payload(batch,'node-example')
|
||||
self.assertEqual(payload['contract'],1);self.assertEqual(payload['kind'],'server_host_interface')
|
||||
self.assertEqual(payload['counter_semantics'],'linux_proc_net_dev_interface_bytes');self.assertEqual(payload['interface'],'eth0')
|
||||
self.assertIsNone(payload['samples'][0]['rx_bytes_per_second']);self.assertEqual(payload['samples'][1]['rx_bytes_per_second'],600)
|
||||
self.assertLess(len(json.dumps(payload).encode()),65536)
|
||||
def test_untrusted_or_redirectable_endpoints_refused(self):
|
||||
for endpoint in ('http://vpn.example.invalid/api/v1/node/host-traffic/','https://evil.invalid/api/v1/node/host-traffic/','https://vpn.example.invalid@evil.invalid/api/v1/node/host-traffic/','https://vpn.example.invalid/api/v1/node/host-traffic/?q=secret'):
|
||||
with self.assertRaises(ValueError):target.HttpTransport(endpoint)
|
||||
def test_tls_default_verification_and_redirect_disabled(self):
|
||||
transport=target.HttpTransport()
|
||||
self.assertTrue(transport.ssl_context.check_hostname)
|
||||
self.assertEqual(transport.ssl_context.verify_mode,2)
|
||||
with self.assertRaises(Exception):target.NoRedirect().redirect_request(None,None,302,'found',{},'https://evil.invalid/')
|
||||
|
||||
class SamplingCadenceTests(unittest.TestCase):
|
||||
def check_cadence(self,read_cost):
|
||||
captured=[]
|
||||
class Clock:
|
||||
now=1.0
|
||||
clock=Clock()
|
||||
class Stop:
|
||||
def is_set(self):return len(captured)>=4
|
||||
def wait(self,delay):clock.now+=delay;return False
|
||||
class Reader:
|
||||
def read(self):
|
||||
captured.append(clock.now)
|
||||
value=snap(rx=int(clock.now)*1000,tx=int(clock.now)*500,seconds=clock.now)
|
||||
clock.now+=read_cost
|
||||
return value
|
||||
queue=target.BoundedSampleQueue()
|
||||
with patch.object(target.time,'monotonic',side_effect=lambda:clock.now):
|
||||
target.run_sampler(Reader(),queue,target.CounterTracker(),Stop(),log=lambda _:None)
|
||||
return captured,queue.batch()
|
||||
def test_sample_deadlines_are_monotonic_one_second(self):
|
||||
captured,rows=self.check_cadence(0)
|
||||
self.assertEqual(captured,[1,2,3,4]);self.assertEqual([x.sample['sequence'] for x in rows],[1,2,3,4])
|
||||
self.assertTrue(all(x.sample['interval_seconds']==1 for x in rows[1:]))
|
||||
def test_delayed_read_marks_missing_intervals_instead_of_fake_catchup(self):
|
||||
captured,rows=self.check_cadence(2.2)
|
||||
self.assertEqual(captured,[1,4,7,10]);self.assertEqual([x.sample['sequence'] for x in rows],[1,4,7,10])
|
||||
self.assertTrue(all(x.sample['gap_before'] for x in rows[1:]))
|
||||
|
||||
class PackageSafetyTests(unittest.TestCase):
|
||||
def test_sampler_uses_no_external_process_or_persistent_writes(self):
|
||||
import ast
|
||||
tree=ast.parse((HERE/'host_traffic_sampler.py').read_text())
|
||||
imports={node.names[0].name for node in ast.walk(tree) if isinstance(node,ast.Import)}
|
||||
self.assertNotIn('subprocess',imports)
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node,ast.Call) and isinstance(node.func,ast.Attribute):
|
||||
self.assertNotIn(node.func.attr,{'write_text','write_bytes','unlink','mkdir','rmdir','chmod','chown','system','popen'})
|
||||
def test_service_does_not_depend_on_or_restart_existing_agent(self):
|
||||
unit=(HERE/'toplc-vpn-host-traffic.service').read_text()
|
||||
self.assertIn('--node-env /opt/toplc-vpn-node/node.env',unit)
|
||||
self.assertIn('ProtectSystem=strict',unit);self.assertIn('CapabilityBoundingSet=\n',unit)
|
||||
self.assertNotIn('EnvironmentFile=',unit);self.assertNotIn('Requires=docker',unit)
|
||||
self.assertNotIn('ExecStartPre=',unit);self.assertNotIn('ExecStopPost=',unit)
|
||||
def test_installer_only_starts_own_service_and_refuses_existing_install(self):
|
||||
text=(HERE/'deploy_host_traffic_sampler.sh').read_text()
|
||||
self.assertIn("assert not path.exists() and not path.is_symlink()",text)
|
||||
self.assertIn("credentials.node_slug==expected",text)
|
||||
self.assertIn("assert before==after",text)
|
||||
self.assertIn("['systemctl','enable','--now','toplc-vpn-host-traffic.service']",text)
|
||||
self.assertNotIn("['systemctl','restart'",text)
|
||||
for command in ('iptables','nft ','tailscale up','docker restart','docker compose up'):
|
||||
self.assertNotIn(command,text)
|
||||
def test_example_payload_matches_sampler_schema_and_does_not_contain_credentials(self):
|
||||
payload=json.loads((HERE/'host-traffic-contract-fixture.json').read_text())
|
||||
self.assertEqual(payload['contract'],1)
|
||||
self.assertEqual(set(payload),{'contract','node_slug','boot_id','interface','kind','counter_semantics','samples'})
|
||||
self.assertEqual(set(payload['samples'][0]),{'sequence','observed_at','monotonic_ns','counter_epoch','interval_seconds','rx_bytes','tx_bytes','rx_bytes_per_second','tx_bytes_per_second','quality','gap_before','dropped_samples_before'})
|
||||
self.assertFalse(any(word in json.dumps(payload).lower() for word in ('token','password','private_key')))
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,38 @@
|
||||
[Unit]
|
||||
Description=TopLC VPN physical WAN one-second traffic sampler
|
||||
Documentation=file:/opt/toplc-vpn-host-traffic/README.md
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=root
|
||||
WorkingDirectory=/opt/toplc-vpn-host-traffic
|
||||
ExecStart=/usr/bin/python3 -B /opt/toplc-vpn-host-traffic/host_traffic_sampler.py --node-env /opt/toplc-vpn-node/node.env
|
||||
Restart=on-failure
|
||||
RestartSec=10
|
||||
TimeoutStopSec=12
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
ProtectKernelTunables=true
|
||||
ProtectKernelModules=true
|
||||
ProtectKernelLogs=true
|
||||
ProtectControlGroups=true
|
||||
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
|
||||
RestrictRealtime=true
|
||||
LockPersonality=true
|
||||
MemoryDenyWriteExecute=true
|
||||
CapabilityBoundingSet=
|
||||
AmbientCapabilities=
|
||||
SystemCallArchitectures=native
|
||||
UMask=0077
|
||||
MemoryMax=64M
|
||||
TasksMax=8
|
||||
CPUQuota=10%
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 UCVL (Youchuang Future)
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,28 @@
|
||||
# Host traffic R2:保留超级管理员已有监视权限
|
||||
|
||||
生产操作账号为启用的 superuser,但 is_staff=False。R1 的新监视 API 只接受 is_staff 导致 403;这里仅把该 API 的角色判断改为 `is_staff or is_superuser`。设备、会话、订阅、账号有效性检查全部保留。普通非 staff 非 superuser 仍 403,停用 superuser 仍 403。不修改任何账号角色或原有核心鉴权、profile、middleware、路由、限速、数据库 Schema。
|
||||
|
||||
R1 目录、源码和 manifest 不动。持久覆盖只增加本目录的 `control/host_traffic.py` 和 `docker-compose.host-traffic-auth-r2.yml`,后者叠在已部署四个 Compose 文件之后,替换唯一 `/app/control/host_traffic.py` 只读 bind。R1 的 URLs、store、独立 SQLite 状态目录和 startup=false 环境继续继承;保留 app UID100/GID101,不修改用户身份。
|
||||
|
||||
主任务核验 SHA、只上传新 R2 目录,设置代码文件 0644,再执行:
|
||||
|
||||
```sh
|
||||
cd /opt/toplc-vpn
|
||||
docker compose -f docker-compose.yml -f docker-compose.override.yml -f docker-compose.shared-budget-web.yml -f /opt/toplc-vpn/host-traffic-standalone-20261106/docker-compose.host-traffic.yml -f /opt/toplc-vpn/host-traffic-standalone-20261106-r2/docker-compose.host-traffic-auth-r2.yml config --quiet
|
||||
docker compose -f docker-compose.yml -f docker-compose.override.yml -f docker-compose.shared-budget-web.yml -f /opt/toplc-vpn/host-traffic-standalone-20261106/docker-compose.host-traffic.yml -f /opt/toplc-vpn/host-traffic-standalone-20261106-r2/docker-compose.host-traffic-auth-r2.yml up -d --no-deps --no-build --pull never web
|
||||
```
|
||||
|
||||
该命令仅重建 web,沿用已部署镜像和四文件配置,不启动任何迁移。主任务前后须核对 core source/schema/Node/RoutingPolicy/账号角色摘要、其它容器 PID/StartedAt/镜像一致;使用现有真实 token 验证 superuser 200、无 token401,返回3台真实秒级数据。不能因本地测试通过而声称生产验收完成。
|
||||
|
||||
本地真实 Django5.2.17 + 正式模型快照回归命令(不连服务器):
|
||||
|
||||
```powershell
|
||||
& 'output/proxy-aggregate-api-20261106/test-venv/Scripts/python.exe' 'services/toplc-vpn-platform/host-traffic-standalone-20261106-r2/tests/run_auth_regression.py'
|
||||
```
|
||||
|
||||
13 项 API 安全测试包含“非 staff 超级管理员200”“普通非 staff403”“停用超级管理员403”,以及原会话到期/撤销、设备禁用、账号状态、订阅到期/配额等检查。请求中的 Django SQL 仍全部 SELECT;测试角色修改只发生于本地 SQLite fixture。
|
||||
|
||||
|
||||
MIT source supplement: these files are published as a separate directory only. They do not replace the platform root, existing routes, source history or other licenses. Integration tests use an existing Django platform model fixture; production model snapshots, accounts, tokens, SQLite state and local output evidence are not included. Configure example endpoints for your deployment. Source publication does not assert production acceptance.
|
||||
|
||||
The frozen candidate manifest hashes describe original source bytes before MIT README supplements and public endpoint substitutions; SOURCE-PROVENANCE.json records both original and published hashes. The R2 API differs from frozen R1 only in allowing existing staff OR existing superuser. This source tool does not perform deployment or assert production acceptance.
|
||||
@@ -0,0 +1,64 @@
|
||||
{
|
||||
"DeploymentPerformedByThisTool": false,
|
||||
"Feature": "one-second-physical-wan-traffic",
|
||||
"FrozenR1WorkspaceChangedByThisTool": false,
|
||||
"License": "MIT",
|
||||
"OriginalPrivateR1Branch": "codex/host-traffic-20261106",
|
||||
"OriginalPrivateR1Commit": "30f06edec04cc8bf7394aeb302e09e6c37e27c86",
|
||||
"OriginalSourceSha256": {
|
||||
"host-traffic-sampler/README.md": "d7e189279e6cefdecd296b66a8d52524dc7a92250b423b41b721f155db0b84a4",
|
||||
"host-traffic-sampler/deploy_host_traffic_sampler.sh": "910e7234b6913e22b7e4aeb4b7ac7e74831e5038af1700e33073f42c14b0fe88",
|
||||
"host-traffic-sampler/host-traffic-contract-fixture.json": "f873e3f62982783fc29cc4f3bc9d298f3420a9e67bae085aeb4e6eeafed58696",
|
||||
"host-traffic-sampler/host_traffic_sampler.py": "16f0e42b7f67c121e225b5c3e0e01c64ed54dcc8ffe52234b8aaa15def575e49",
|
||||
"host-traffic-sampler/test_host_traffic_sampler.py": "0d160ab9640d58c9487d69183246ed7c2380322e367caebeff16364d3257a2bd",
|
||||
"host-traffic-sampler/toplc-vpn-host-traffic.service": "f2ba0a79822457511717c2514ac7988d93d01bf71a39c027fd8267ecf6f8da44",
|
||||
"host-traffic-standalone-20261106-r2/README.md": "0427c3c2448d553167fa361940865aee4bb1b7bb50691721a5989353b5edc997",
|
||||
"host-traffic-standalone-20261106-r2/candidate-manifest.json": "c7b252a860af93f35c6db44da15073dee50cbce5ea23be9cf29d9949e5fdfc62",
|
||||
"host-traffic-standalone-20261106-r2/control/host_traffic.py": "c66421de2fbb74ab3b20ca771f6e2463737163eb6e245d56cc3875053e696d03",
|
||||
"host-traffic-standalone-20261106-r2/docker-compose.host-traffic-auth-r2.yml": "59a410949dd7900906aa6d6693a40759a90ddd23d34a7686b00715010afa5379",
|
||||
"host-traffic-standalone-20261106-r2/tests/run_auth_regression.py": "4f2d8d0ea6be83fd177e3a0f2133cb3255653df2f43bc70af6b4e31b2894805f",
|
||||
"host-traffic-standalone-20261106/README.md": "6ab4f38aa115f8b1e2442bfefbec8a5a8210af889673614a80a91192608e12c0",
|
||||
"host-traffic-standalone-20261106/control/host_traffic.py": "a63b10ba3c6ca4b465cd77e11c868df2b9876ab2b10ec358e1d5ee37d99fee12",
|
||||
"host-traffic-standalone-20261106/control/host_traffic_store.py": "c5a6a986208879417ac51bb4b395794e1e0a235cac34f609a572804eb90091b8",
|
||||
"host-traffic-standalone-20261106/control/urls.py": "4f055b0de4d6a7593cbf00db0bc15c8f8e8644afa4618bebca79c738ac916002",
|
||||
"host-traffic-standalone-20261106/docker-compose.host-traffic.yml": "990656d4044c02106917479490e2619cccd1097dda65be8b75f1f84e570e60c6",
|
||||
"host-traffic-standalone-20261106/tests/run_tests.py": "715f80bfe11643d4b01b84c09d02b13eb5d371680a4ddd0cee23c463150d9bab"
|
||||
},
|
||||
"PrivateHistoryIncluded": false,
|
||||
"PrivateR1BaseBranch": null,
|
||||
"PrivateR1BaseCommit": null,
|
||||
"PrivateR1ReceiptSha256": null,
|
||||
"ProductionAcceptanceAsserted": false,
|
||||
"PublicBaseBranch": "codex/public-windows-0.3.5-20261106",
|
||||
"PublicBaseCommit": "7f7d4f6d35fc18a47207c6e197aa6b2fc828c91e",
|
||||
"PublicBaseReceiptSha256": "32e340ad4e82cf4e1f44891ed1daf426fb2de71cba937d53abbe6edd2dc88b43",
|
||||
"R2ApiRoleGate": "existing is_staff OR existing is_superuser",
|
||||
"R2CandidateSha256": "6d1243c6cdedf05b60420a45ebe6ad9feeec5a856ccbc307a02fd49fbb5811a3",
|
||||
"R2OriginalManifestSha256": "c7b252a860af93f35c6db44da15073dee50cbce5ea23be9cf29d9949e5fdfc62",
|
||||
"Schema": 1,
|
||||
"SelectedSourceSha256": {
|
||||
"backend/host-traffic-sampler/LICENSE": "b7e94910b8dc377b0a05ccde3c6e5941838dfc15c9dd790078d11728205b524e",
|
||||
"backend/host-traffic-sampler/README.md": "8103d07ab651832a1529669f65b12cecc0a5abaca9b95e948caed9ff3148dfcd",
|
||||
"backend/host-traffic-sampler/deploy_host_traffic_sampler.sh": "910e7234b6913e22b7e4aeb4b7ac7e74831e5038af1700e33073f42c14b0fe88",
|
||||
"backend/host-traffic-sampler/host-traffic-contract-fixture.json": "f873e3f62982783fc29cc4f3bc9d298f3420a9e67bae085aeb4e6eeafed58696",
|
||||
"backend/host-traffic-sampler/host_traffic_sampler.py": "d4b7f02ec39092cfc141e8275019c7b3b7458b6bf7096fe511742df9113bcab3",
|
||||
"backend/host-traffic-sampler/test_host_traffic_sampler.py": "0c1cb6cf306ed16976781b614ff27203a06bdb6eb20fa734c3681c9a4f5a3023",
|
||||
"backend/host-traffic-sampler/toplc-vpn-host-traffic.service": "f2ba0a79822457511717c2514ac7988d93d01bf71a39c027fd8267ecf6f8da44",
|
||||
"backend/host-traffic-standalone-20261106-r2/LICENSE": "b7e94910b8dc377b0a05ccde3c6e5941838dfc15c9dd790078d11728205b524e",
|
||||
"backend/host-traffic-standalone-20261106-r2/README.md": "275932318caa6ef5c69bdaeb12ec84f8f0b9a06aa3ae472cf70c9727980bf175",
|
||||
"backend/host-traffic-standalone-20261106-r2/candidate-manifest.json": "c7b252a860af93f35c6db44da15073dee50cbce5ea23be9cf29d9949e5fdfc62",
|
||||
"backend/host-traffic-standalone-20261106-r2/control/host_traffic.py": "c66421de2fbb74ab3b20ca771f6e2463737163eb6e245d56cc3875053e696d03",
|
||||
"backend/host-traffic-standalone-20261106-r2/docker-compose.host-traffic-auth-r2.yml": "59a410949dd7900906aa6d6693a40759a90ddd23d34a7686b00715010afa5379",
|
||||
"backend/host-traffic-standalone-20261106-r2/tests/run_auth_regression.py": "4f2d8d0ea6be83fd177e3a0f2133cb3255653df2f43bc70af6b4e31b2894805f",
|
||||
"backend/host-traffic-standalone-20261106/LICENSE": "b7e94910b8dc377b0a05ccde3c6e5941838dfc15c9dd790078d11728205b524e",
|
||||
"backend/host-traffic-standalone-20261106/README.md": "ffe1a73fcffcbc9bc137f8215b035887bfa2de00dc05bde53b2a91e52684f393",
|
||||
"backend/host-traffic-standalone-20261106/control/host_traffic.py": "a63b10ba3c6ca4b465cd77e11c868df2b9876ab2b10ec358e1d5ee37d99fee12",
|
||||
"backend/host-traffic-standalone-20261106/control/host_traffic_store.py": "c5a6a986208879417ac51bb4b395794e1e0a235cac34f609a572804eb90091b8",
|
||||
"backend/host-traffic-standalone-20261106/control/urls.py": "4f055b0de4d6a7593cbf00db0bc15c8f8e8644afa4618bebca79c738ac916002",
|
||||
"backend/host-traffic-standalone-20261106/docker-compose.host-traffic.yml": "990656d4044c02106917479490e2619cccd1097dda65be8b75f1f84e570e60c6",
|
||||
"backend/host-traffic-standalone-20261106/tests/run_tests.py": "715f80bfe11643d4b01b84c09d02b13eb5d371680a4ddd0cee23c463150d9bab"
|
||||
},
|
||||
"SourceOnly": true,
|
||||
"TargetBranch": "codex/public-host-traffic-20261106",
|
||||
"TargetRepository": "admin/ucvl-zonghengjia-open-source"
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"kind": "standalone-host-traffic-api-rbac-r2",
|
||||
"created_at": "2026-11-06T08:09:46.015404+00:00",
|
||||
"parent_candidate_sha256": "a4102ac16e95da335ca9c5a75e7de35a04cc63e7d29615d95b0fd89b5a5bf491",
|
||||
"r1_manifest_sha256": "876bb3436a82b125a3af0514e29f2f38d9ef823cc6acc20e33f622477378796c",
|
||||
"r1_api_sha256": "a63b10ba3c6ca4b465cd77e11c868df2b9876ab2b10ec358e1d5ee37d99fee12",
|
||||
"files_sha256": {
|
||||
"docker-compose.host-traffic-auth-r2.yml": "59a410949dd7900906aa6d6693a40759a90ddd23d34a7686b00715010afa5379",
|
||||
"README.md": "0427c3c2448d553167fa361940865aee4bb1b7bb50691721a5989353b5edc997",
|
||||
"control/host_traffic.py": "c66421de2fbb74ab3b20ca771f6e2463737163eb6e245d56cc3875053e696d03",
|
||||
"tests/run_auth_regression.py": "4f2d8d0ea6be83fd177e3a0f2133cb3255653df2f43bc70af6b4e31b2894805f"
|
||||
},
|
||||
"security_report_sha256": "486745abeadabbe1a5dcc6ee1e8c516d0316d9c0f588f594e7bd4c42105b5f18",
|
||||
"security_tests": {
|
||||
"passed": true,
|
||||
"tests_run": 13,
|
||||
"failures": 0,
|
||||
"errors": 0,
|
||||
"django_version": "5.2.17",
|
||||
"actual_production_models": true,
|
||||
"primary_database_dml_in_requests": false,
|
||||
"production_modified": false,
|
||||
"api_source_sha256": "c66421de2fbb74ab3b20ca771f6e2463737163eb6e245d56cc3875053e696d03"
|
||||
},
|
||||
"functional_change": "Only new API role gate permits existing staff OR existing superuser; all other checks unchanged",
|
||||
"production_modified": false,
|
||||
"candidate_sha256": "6d1243c6cdedf05b60420a45ebe6ad9feeec5a856ccbc307a02fd49fbb5811a3"
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Isolated endpoints for true one-second host WAN telemetry, never billing."""
|
||||
import hashlib
|
||||
import secrets
|
||||
import sqlite3
|
||||
|
||||
from django.http import JsonResponse
|
||||
from django.utils import timezone
|
||||
from django.views.decorators.cache import never_cache
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from django.views.decorators.http import require_GET, require_POST
|
||||
from django.views.decorators.vary import vary_on_headers
|
||||
|
||||
from .models import ClientSession, Node
|
||||
from . import host_traffic_store as store
|
||||
|
||||
|
||||
def _token(request):
|
||||
authorization = request.headers.get("Authorization", "")
|
||||
if not authorization.startswith("Bearer "):
|
||||
return None
|
||||
token = authorization[7:].strip()
|
||||
return token if 32 <= len(token) <= 256 else None
|
||||
|
||||
|
||||
def _client_allowed(request):
|
||||
token = _token(request)
|
||||
if token is None:
|
||||
return JsonResponse({"error": "Client access token required."}, status=401)
|
||||
digest = hashlib.sha256(token.encode()).hexdigest()
|
||||
session = ClientSession.objects.select_related("device", "subscription__user", "subscription__plan").filter(token_digest=digest, revoked_at__isnull=True).first()
|
||||
if session is None or not secrets.compare_digest(session.token_digest, digest) or not session.is_valid:
|
||||
return JsonResponse({"error": "Client login expired."}, status=401)
|
||||
if not session.device.active or session.device.subscription_id != session.subscription_id:
|
||||
return JsonResponse({"error": "Client device unavailable."}, status=403)
|
||||
user = session.subscription.user
|
||||
if not user.service_enabled or not (user.is_staff or user.is_superuser) or not session.subscription.is_usable:
|
||||
return JsonResponse({"error": "Server traffic monitoring is not permitted."}, status=403)
|
||||
return None
|
||||
|
||||
|
||||
@never_cache
|
||||
@vary_on_headers("Authorization")
|
||||
@require_GET
|
||||
def client_node_traffic(request):
|
||||
# Existing model properties enforce the same token/account/expiry/quota policy
|
||||
# as the production login helper, without its writes to last_seen/status.
|
||||
denial = _client_allowed(request)
|
||||
if denial is not None:
|
||||
return denial
|
||||
try:
|
||||
since = store.timestamp(request.GET["since"]) if "since" in request.GET else None
|
||||
nodes = list(Node.objects.filter(active=True, subscription_enabled=True).order_by("sort_order", "region", "name", "pk").values("id", "slug", "name", "region"))
|
||||
if len(nodes) > store.MAX_NODES:
|
||||
return JsonResponse({"error": "Host traffic node capacity exceeded."}, status=503)
|
||||
result = store.snapshot(nodes, timezone.now(), since)
|
||||
except store.InvalidSample:
|
||||
return JsonResponse({"error": "Invalid history range."}, status=400)
|
||||
except sqlite3.Error:
|
||||
return JsonResponse({"error": "Host traffic telemetry temporarily unavailable."}, status=503)
|
||||
response = JsonResponse(result, json_dumps_params={"separators": (",", ":"), "ensure_ascii": False})
|
||||
if len(response.content) > store.MAX_RESPONSE_BYTES:
|
||||
return JsonResponse({"error": "Host traffic response capacity exceeded."}, status=503)
|
||||
return response
|
||||
|
||||
|
||||
@csrf_exempt
|
||||
@never_cache
|
||||
@require_POST
|
||||
def node_host_traffic(request):
|
||||
token = _token(request)
|
||||
slug = request.headers.get("X-Node-Slug", "")
|
||||
if token is None or not 1 <= len(slug) <= 80:
|
||||
return JsonResponse({"error": "Node authentication failed."}, status=401)
|
||||
node = Node.objects.filter(slug=slug, active=True, subscription_enabled=True).first()
|
||||
if node is None or not node.check_agent_token(token):
|
||||
return JsonResponse({"error": "Node authentication failed."}, status=401)
|
||||
try:
|
||||
# Bound reads before deserializing JSON. Real nginx/Django limits remain
|
||||
# in force; this endpoint additionally permits only one small batch.
|
||||
declared = request.META.get("CONTENT_LENGTH", "")
|
||||
if declared and (not declared.isdigit() or int(declared) > store.MAX_BODY_BYTES):
|
||||
raise store.InvalidSample("batch too large")
|
||||
body = request.read(store.MAX_BODY_BYTES + 1)
|
||||
now = timezone.now()
|
||||
points = store.parse_batch(body, node.slug, now)
|
||||
result = store.ingest(node.pk, points, now)
|
||||
except (store.InvalidSample, UnicodeError, OverflowError, TypeError):
|
||||
return JsonResponse({"error": "Invalid host traffic sample batch."}, status=400)
|
||||
except sqlite3.Error:
|
||||
return JsonResponse({"error": "Host traffic telemetry temporarily unavailable."}, status=503)
|
||||
return JsonResponse(result)
|
||||
@@ -0,0 +1,9 @@
|
||||
# Append after the original three files AND R1 host-traffic overlay.
|
||||
# Docker Compose merges volumes by container target, replacing only this API.
|
||||
services:
|
||||
web:
|
||||
volumes:
|
||||
- type: bind
|
||||
source: /opt/toplc-vpn/host-traffic-standalone-20261106-r2/control/host_traffic.py
|
||||
target: /app/control/host_traffic.py
|
||||
read_only: true
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Actual Django 5.2.17 + production model snapshots; no remote operations."""
|
||||
import hashlib
|
||||
import json
|
||||
import runpy
|
||||
import shutil
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
R2 = Path(__file__).resolve().parents[1]
|
||||
R1 = R2.parent / "host-traffic-standalone-20261106"
|
||||
fixture = runpy.run_path(str(R1 / "tests/run_tests.py"), run_name="r1_fixture_bootstrap")
|
||||
runtime = fixture["RUNTIME"]
|
||||
source = R2 / "control/host_traffic.py"
|
||||
shutil.copy2(source, runtime / "control/host_traffic.py")
|
||||
from control import host_traffic
|
||||
assert hashlib.sha256(Path(host_traffic.__file__).read_bytes()).hexdigest() == hashlib.sha256(source.read_bytes()).hexdigest()
|
||||
Base = fixture["EndpointTests"]
|
||||
|
||||
|
||||
class AuthRegression(Base):
|
||||
def test_nonstaff_superuser_allowed(self):
|
||||
self.user.is_staff = False
|
||||
self.user.is_superuser = True
|
||||
self.user.save(update_fields=["is_staff", "is_superuser"])
|
||||
self.assertEqual(self.get().status_code, 200)
|
||||
self.user.refresh_from_db()
|
||||
self.assertFalse(self.user.is_staff)
|
||||
self.assertTrue(self.user.is_superuser)
|
||||
|
||||
def test_ordinary_nonstaff_still_denied(self):
|
||||
self.user.is_staff = False
|
||||
self.user.is_superuser = False
|
||||
self.user.save(update_fields=["is_staff", "is_superuser"])
|
||||
self.assertEqual(self.get().status_code, 403)
|
||||
|
||||
def test_disabled_nonstaff_superuser_still_denied(self):
|
||||
self.user.is_staff = False
|
||||
self.user.is_superuser = True
|
||||
self.user.is_active = False
|
||||
self.user.save(update_fields=["is_staff", "is_superuser", "is_active"])
|
||||
self.assertEqual(self.get().status_code, 403)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
runner = fixture["DiscoverRunner"](verbosity=1)
|
||||
database = runner.setup_databases()
|
||||
try:
|
||||
result = unittest.TextTestRunner(verbosity=2).run(unittest.defaultTestLoader.loadTestsFromTestCase(AuthRegression))
|
||||
out = R2.parents[2] / "output/host-traffic-standalone-20261106-r2"
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
report = {"passed": result.wasSuccessful(), "tests_run": result.testsRun,
|
||||
"failures": len(result.failures), "errors": len(result.errors),
|
||||
"django_version": fixture["django"].get_version(), "actual_production_models": True,
|
||||
"primary_database_dml_in_requests": False, "production_modified": False,
|
||||
"api_source_sha256": hashlib.sha256(source.read_bytes()).hexdigest()}
|
||||
(out / "auth-regression-result.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
|
||||
finally:
|
||||
runner.teardown_databases(database)
|
||||
fixture["runtime_context"].cleanup()
|
||||
raise SystemExit(0 if result.wasSuccessful() else 1)
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 UCVL (Youchuang Future)
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,49 @@
|
||||
# 独立服务器 WAN 秒级采样接线
|
||||
|
||||
此目录仅增加真实主网卡监控入口和独立 SQLite 时序存储。与主代理、账号限速、节点调度、订阅配置、Django 业务数据库及候选功能完全分离。需由主任务审查后部署,本目录没有自动远端部署动作。
|
||||
|
||||
输入为 `host-traffic-sampler` 独立服务每秒读取的 Linux 主 WAN 网卡 RX/TX 原始计数;每 5 秒批量上传。服务器出站为 TX,入站为 RX。界面中的 `upload` 因沿用网卡视角等于 TX/出站,`download` 等于 RX/入站。此数据包含整个主机的网卡开销,不是某个账户的代理计费。
|
||||
|
||||
## 两个入口
|
||||
|
||||
- `POST /api/v1/node/host-traffic/`:已有节点 Bearer token、`X-Node-Slug`、active+subscription_enabled 节点才可上报。最多 64 KiB、60 点。协议字段与相邻 `host-traffic-sampler/host-traffic-contract-fixture.json` 一致。整批提交后返回 `{status:"accepted",accepted:N,duplicates:M}`;相同 epoch+sequence 的不同内容使整批回滚。Node token 摘要只读验证,不回传令牌、不修改心跳、下发或计费。
|
||||
- `GET /api/v1/client/node-traffic/`:原 ClientSession Bearer token、有效设备和订阅、正常且启用的 staff 账号才可查看。沿用正式模型的到期、配额、付款和账号有效性判断,但不调用会写 last_seen/订阅状态的旧鉴权助手。401/403/200 均 no-store。没有登录或 profile 授权字段改动。
|
||||
|
||||
GET 保留 host contract 1:scope=`server_host_interface`,source=`linux_host_interface`,direction=`interface_perspective`,counter_since=`boot_or_interface_reset`。`refresh_seconds=5`,`sample_period_seconds=1`,`freshness_seconds=15`;节点动态取 active+subscription_enabled,不硬编码 VPN002/003/004。当前值超过 15 秒、缺数据或基线/复位/缺口时为 null,不能以零伪装在线。
|
||||
|
||||
独立库每节点保留最近一小时、最多 3600 个真实秒级点。首载只返回最近 5 分钟,每节点最多 300 点,并在全节点之间公平分配最多 2000 点的响应预算;JSON 硬上限 1 MiB。这样当前 3/4 节点首载约数百 KiB,在限速账户上也无需下载整个一小时。`available_storage_history_seconds=3600` 表明存储范围;`requested_history_seconds` 表示请求下限;`history_seconds` 是本次真实返回点的实际跨度,不假称首载一小时。`history_truncated`、`history_point_limit_per_node` 和每节点 `returned_history_since` 明示截断和范围。
|
||||
|
||||
每个返回点有真实 `sampled_at`、`interval_seconds`、`sequence`、`counter_epoch`、`interface`、`quality` 和 `gap_before`。TX 对应 `upload_bytes_per_second`,RX 对应 `download_bytes_per_second`。非 ok 点双向速率为 null;接口切换、启动、计数复位、漏样或时间缺口必须断开曲线。若新 epoch 的首次基线因离线队列丢弃,服务端把恢复后的首个观测仅作为 gap/null 基线,下一条才校验差分,避免永久重试失败。
|
||||
|
||||
可选 `?since=<带时区ISO8601>` 增量读取。过旧下限钳到最近一小时,未来超过 5 秒拒绝。过滤同时包含“观测时间或接收时间大于下限”的点,防止上一响应游标跳过延迟批次;客户端按 epoch+sequence 或 epoch+sampled_at 去重。当前值不受 since 过滤。首载五分钟,随后每 5 秒增量;客户端可以积累最多一小时的本次运行真实历史,但没有后台分页补齐一小时或下采样功能,不能伪造更早曲线。
|
||||
|
||||
## 持久性与部署边界
|
||||
|
||||
`control/urls.py` 必须从当前生产 `control/urls.py` 基线生成;只增加 host_traffic import 和两个 path,不能复制工作区候选 URLs。`candidate-manifest.json` 记录正式基线和候选 SHA。
|
||||
|
||||
示例 overlay 固定挂载本目录中两个新模块与最小 patched URLs,并独立挂载 `/opt/toplc-vpn/host-traffic-state`。需将 overlay 放在当前三个 Compose 文件之后,保持已有镜像、入口、端口和 `/app/releases` 挂载。只重建 web;不触碰 scheduler、vpn-ai、db、NPM 或 VPN 节点网络。`VPN_RUN_STARTUP_TASKS=false` 必须存在,避免 entrypoint 自动 migrate、collectstatic--clear、bootstrap_vpn。
|
||||
|
||||
部署前先在专用状态目录显式初始化独立数据库(不通过 GET 隐式创建):
|
||||
|
||||
```sh
|
||||
python3 control/host_traffic_store.py --init --path /opt/toplc-vpn/host-traffic-state/host-traffic.sqlite3
|
||||
```
|
||||
|
||||
为实际容器运行 UID 设置专用目录访问权限;数据库文件 0600。SQLite 使用 WAL、2 秒 busy_timeout;POST 每批一个事务,按节点+epoch+sequence 去重,最多 32 节点,各保留最近 3600 点且清除一小时前数据。GET 只以 `mode=ro`、`query_only=ON` 打开已初始化文件,并在一个只读事务中生成一致快照。没有 Django DB schema 或 migration。
|
||||
|
||||
部署和重建验证由主任务执行:确认 health200、无令牌401、无权限403、三节点新数据真实每秒、只出现专用 SQLite 写入、重建后 bind 持久、主网卡方向和既有节点/路由/限速配置摘要一致。回退仅移除本新增 overlay 并按原三个 Compose 文件重建 web;不删除业务数据或改变节点服务。
|
||||
|
||||
## 隔离验证
|
||||
|
||||
`tests/run_tests.py` 使用只读取得的正式 accounts/control 模型源码快照、实际 Django 5.2.17 和完整生产 middleware 链,在本地 SQLite 运行。两种 API 请求期间捕获的 Django SQL 必须全部为 SELECT;另检查独立数据库幂等、冲突整批回滚、counter reset、单调时钟、速率差分、上限、迟到批次、真实方向及 sampler fixture 端到端兼容。所有账号和令牌均为本地生成的虚构测试数据。
|
||||
|
||||
可复现命令(工作目录为项目根):
|
||||
|
||||
```powershell
|
||||
& 'output/proxy-aggregate-api-20261106/test-venv/Scripts/python.exe' 'services/toplc-vpn-platform/host-traffic-standalone-20261106/tests/run_tests.py'
|
||||
```
|
||||
|
||||
正式源码基线只在 `output/proxy-aggregate-api-20261106/baseline` 中做隔离测试输入,不能把其 models/views 当作待部署文件。公开导出此目录时不要导出本地运行环境、SQLite 数据或真实 token。
|
||||
|
||||
|
||||
MIT source supplement: these files are published as a separate directory only. They do not replace the platform root, existing routes, source history or other licenses. Integration tests use an existing Django platform model fixture; production model snapshots, accounts, tokens, SQLite state and local output evidence are not included. Configure example endpoints for your deployment. Source publication does not assert production acceptance.
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Isolated endpoints for true one-second host WAN telemetry, never billing."""
|
||||
import hashlib
|
||||
import secrets
|
||||
import sqlite3
|
||||
|
||||
from django.http import JsonResponse
|
||||
from django.utils import timezone
|
||||
from django.views.decorators.cache import never_cache
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from django.views.decorators.http import require_GET, require_POST
|
||||
from django.views.decorators.vary import vary_on_headers
|
||||
|
||||
from .models import ClientSession, Node
|
||||
from . import host_traffic_store as store
|
||||
|
||||
|
||||
def _token(request):
|
||||
authorization = request.headers.get("Authorization", "")
|
||||
if not authorization.startswith("Bearer "):
|
||||
return None
|
||||
token = authorization[7:].strip()
|
||||
return token if 32 <= len(token) <= 256 else None
|
||||
|
||||
|
||||
def _client_allowed(request):
|
||||
token = _token(request)
|
||||
if token is None:
|
||||
return JsonResponse({"error": "Client access token required."}, status=401)
|
||||
digest = hashlib.sha256(token.encode()).hexdigest()
|
||||
session = ClientSession.objects.select_related("device", "subscription__user", "subscription__plan").filter(token_digest=digest, revoked_at__isnull=True).first()
|
||||
if session is None or not secrets.compare_digest(session.token_digest, digest) or not session.is_valid:
|
||||
return JsonResponse({"error": "Client login expired."}, status=401)
|
||||
if not session.device.active or session.device.subscription_id != session.subscription_id:
|
||||
return JsonResponse({"error": "Client device unavailable."}, status=403)
|
||||
user = session.subscription.user
|
||||
if not user.service_enabled or not user.is_staff or not session.subscription.is_usable:
|
||||
return JsonResponse({"error": "Server traffic monitoring is not permitted."}, status=403)
|
||||
return None
|
||||
|
||||
|
||||
@never_cache
|
||||
@vary_on_headers("Authorization")
|
||||
@require_GET
|
||||
def client_node_traffic(request):
|
||||
# Existing model properties enforce the same token/account/expiry/quota policy
|
||||
# as the production login helper, without its writes to last_seen/status.
|
||||
denial = _client_allowed(request)
|
||||
if denial is not None:
|
||||
return denial
|
||||
try:
|
||||
since = store.timestamp(request.GET["since"]) if "since" in request.GET else None
|
||||
nodes = list(Node.objects.filter(active=True, subscription_enabled=True).order_by("sort_order", "region", "name", "pk").values("id", "slug", "name", "region"))
|
||||
if len(nodes) > store.MAX_NODES:
|
||||
return JsonResponse({"error": "Host traffic node capacity exceeded."}, status=503)
|
||||
result = store.snapshot(nodes, timezone.now(), since)
|
||||
except store.InvalidSample:
|
||||
return JsonResponse({"error": "Invalid history range."}, status=400)
|
||||
except sqlite3.Error:
|
||||
return JsonResponse({"error": "Host traffic telemetry temporarily unavailable."}, status=503)
|
||||
response = JsonResponse(result, json_dumps_params={"separators": (",", ":"), "ensure_ascii": False})
|
||||
if len(response.content) > store.MAX_RESPONSE_BYTES:
|
||||
return JsonResponse({"error": "Host traffic response capacity exceeded."}, status=503)
|
||||
return response
|
||||
|
||||
|
||||
@csrf_exempt
|
||||
@never_cache
|
||||
@require_POST
|
||||
def node_host_traffic(request):
|
||||
token = _token(request)
|
||||
slug = request.headers.get("X-Node-Slug", "")
|
||||
if token is None or not 1 <= len(slug) <= 80:
|
||||
return JsonResponse({"error": "Node authentication failed."}, status=401)
|
||||
node = Node.objects.filter(slug=slug, active=True, subscription_enabled=True).first()
|
||||
if node is None or not node.check_agent_token(token):
|
||||
return JsonResponse({"error": "Node authentication failed."}, status=401)
|
||||
try:
|
||||
# Bound reads before deserializing JSON. Real nginx/Django limits remain
|
||||
# in force; this endpoint additionally permits only one small batch.
|
||||
declared = request.META.get("CONTENT_LENGTH", "")
|
||||
if declared and (not declared.isdigit() or int(declared) > store.MAX_BODY_BYTES):
|
||||
raise store.InvalidSample("batch too large")
|
||||
body = request.read(store.MAX_BODY_BYTES + 1)
|
||||
now = timezone.now()
|
||||
points = store.parse_batch(body, node.slug, now)
|
||||
result = store.ingest(node.pk, points, now)
|
||||
except (store.InvalidSample, UnicodeError, OverflowError, TypeError):
|
||||
return JsonResponse({"error": "Invalid host traffic sample batch."}, status=400)
|
||||
except sqlite3.Error:
|
||||
return JsonResponse({"error": "Host traffic telemetry temporarily unavailable."}, status=503)
|
||||
return JsonResponse(result)
|
||||
@@ -0,0 +1,330 @@
|
||||
"""Bounded standalone WAN sample store. Does not use or write Django models."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import sqlite3
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
MAX_BODY_BYTES = 65536
|
||||
MAX_BATCH = 60
|
||||
MAX_NODES = 32
|
||||
MAX_POINTS = 3600
|
||||
HISTORY_SECONDS = 3600
|
||||
DEFAULT_HISTORY_SECONDS = 300
|
||||
MAX_RESPONSE_POINTS = 2000
|
||||
MAX_RESPONSE_BYTES = 1024 * 1024
|
||||
FRESHNESS_SECONDS = 15
|
||||
MAX_INT = 2**63 - 1
|
||||
MAX_SEQUENCE = 2**53 - 1
|
||||
MAX_RATE = 10**12
|
||||
INTERFACE = re.compile(r"[A-Za-z0-9_.-]{1,15}\Z")
|
||||
EXCLUDED = re.compile(r"(?:lo\Z|tailscale|tun|tap|utun|wg|docker|veth|virbr|br[.-])", re.I)
|
||||
QUALITIES = {"baseline", "ok", "reset", "gap", "interface_changed", "boot_changed"}
|
||||
SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS samples (
|
||||
id INTEGER PRIMARY KEY,
|
||||
node_id INTEGER NOT NULL,
|
||||
counter_epoch TEXT NOT NULL,
|
||||
sequence INTEGER NOT NULL,
|
||||
boot_id TEXT NOT NULL,
|
||||
interface TEXT NOT NULL,
|
||||
observed_us INTEGER NOT NULL,
|
||||
monotonic_ns INTEGER NOT NULL,
|
||||
interval_seconds REAL NOT NULL,
|
||||
rx_bytes INTEGER NOT NULL,
|
||||
tx_bytes INTEGER NOT NULL,
|
||||
rx_rate INTEGER,
|
||||
tx_rate INTEGER,
|
||||
quality TEXT NOT NULL,
|
||||
gap_before INTEGER NOT NULL,
|
||||
dropped_samples_before INTEGER NOT NULL,
|
||||
payload_sha256 TEXT NOT NULL,
|
||||
received_us INTEGER NOT NULL,
|
||||
UNIQUE(node_id,counter_epoch,sequence)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS samples_node_time ON samples(node_id,observed_us,id);
|
||||
CREATE INDEX IF NOT EXISTS samples_time ON samples(observed_us);
|
||||
PRAGMA user_version=1;
|
||||
"""
|
||||
|
||||
|
||||
class InvalidSample(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def store_path():
|
||||
return Path(os.environ.get("TOPLC_HOST_TRAFFIC_DB", "/var/lib/toplc-vpn-host-traffic/host-traffic.sqlite3"))
|
||||
|
||||
|
||||
def _require(value, message):
|
||||
if not value:
|
||||
raise InvalidSample(message)
|
||||
|
||||
|
||||
def _integer(value, maximum=MAX_INT):
|
||||
_require(type(value) is int and 0 <= value <= maximum, "invalid integer")
|
||||
return value
|
||||
|
||||
|
||||
def _finite(value, minimum, maximum):
|
||||
_require(type(value) in (int, float) and math.isfinite(value) and minimum <= value <= maximum, "invalid numeric value")
|
||||
return float(value)
|
||||
|
||||
|
||||
def _uuid(value):
|
||||
_require(isinstance(value, str) and len(value) <= 36, "invalid counter identity")
|
||||
try:
|
||||
return str(uuid.UUID(value))
|
||||
except (ValueError, AttributeError) as exc:
|
||||
raise InvalidSample("invalid counter identity") from exc
|
||||
|
||||
|
||||
def timestamp(value):
|
||||
_require(isinstance(value, str) and len(value) <= 40, "invalid observation timestamp")
|
||||
try:
|
||||
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
except ValueError as exc:
|
||||
raise InvalidSample("invalid observation timestamp") from exc
|
||||
_require(parsed.tzinfo is not None, "observation timestamp requires timezone")
|
||||
return parsed.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def microseconds(value):
|
||||
return int(value.timestamp() * 1_000_000)
|
||||
|
||||
|
||||
def iso_from_us(value):
|
||||
return datetime.fromtimestamp(value / 1_000_000, timezone.utc).isoformat()
|
||||
|
||||
|
||||
def parse_batch(body, expected_slug, now):
|
||||
_require(len(body) <= MAX_BODY_BYTES, "batch too large")
|
||||
try:
|
||||
payload = json.loads(body)
|
||||
except (ValueError, UnicodeDecodeError) as exc:
|
||||
raise InvalidSample("invalid JSON") from exc
|
||||
required = {"contract", "node_slug", "boot_id", "interface", "kind", "counter_semantics", "samples"}
|
||||
_require(isinstance(payload, dict) and set(payload) == required, "unexpected batch fields")
|
||||
_require(type(payload["contract"]) is int and payload["contract"] == 1, "invalid contract")
|
||||
_require(payload["node_slug"] == expected_slug, "node identity mismatch")
|
||||
_require(payload["kind"] == "server_host_interface" and payload["counter_semantics"] == "linux_proc_net_dev_interface_bytes", "invalid counter semantics")
|
||||
interface = payload["interface"]
|
||||
_require(isinstance(interface, str) and INTERFACE.fullmatch(interface) and not EXCLUDED.match(interface), "invalid WAN interface")
|
||||
boot = _uuid(payload["boot_id"])
|
||||
samples = payload["samples"]
|
||||
_require(isinstance(samples, list) and 1 <= len(samples) <= MAX_BATCH, "invalid batch count")
|
||||
points = []
|
||||
fields = {"sequence", "observed_at", "monotonic_ns", "counter_epoch", "interval_seconds", "rx_bytes", "tx_bytes", "rx_bytes_per_second", "tx_bytes_per_second", "quality"}
|
||||
optional = {"gap_before", "dropped_samples_before"}
|
||||
for item in samples:
|
||||
_require(isinstance(item, dict) and fields.issubset(item) and set(item).issubset(fields | optional), "unexpected sample fields")
|
||||
seq = _integer(item["sequence"], MAX_SEQUENCE)
|
||||
mono = _integer(item["monotonic_ns"])
|
||||
_require(mono > 0, "monotonic clock must be positive")
|
||||
epoch = _uuid(item["counter_epoch"])
|
||||
observed = timestamp(item["observed_at"])
|
||||
_require(now - timedelta(seconds=HISTORY_SECONDS) <= observed <= now + timedelta(seconds=5), "observation timestamp outside window")
|
||||
quality = item["quality"]
|
||||
_require(quality in QUALITIES, "invalid sample quality")
|
||||
interval = _finite(item["interval_seconds"], 0, HISTORY_SECONDS)
|
||||
rx = _integer(item["rx_bytes"])
|
||||
tx = _integer(item["tx_bytes"])
|
||||
rates = [item["rx_bytes_per_second"], item["tx_bytes_per_second"]]
|
||||
if quality == "ok":
|
||||
_require(.5 <= interval <= 3, "invalid regular sample interval")
|
||||
rates = [_finite(value, 0, MAX_RATE) for value in rates]
|
||||
else:
|
||||
_require(rates == [None, None], "baseline/reset/gap must not claim rates")
|
||||
gap = item.get("gap_before", False)
|
||||
_require(type(gap) is bool, "invalid gap flag")
|
||||
dropped = _integer(item.get("dropped_samples_before", 0), 1_000_000)
|
||||
normalized = dict(sequence=seq, observed_at=observed.isoformat(), monotonic_ns=mono,
|
||||
counter_epoch=epoch, interval_seconds=interval, rx_bytes=rx, tx_bytes=tx,
|
||||
rx_bytes_per_second=rates[0], tx_bytes_per_second=rates[1], quality=quality,
|
||||
gap_before=gap, dropped_samples_before=dropped, boot_id=boot, interface=interface)
|
||||
normalized["payload_sha256"] = hashlib.sha256(json.dumps(normalized, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
|
||||
normalized["observed_us"] = microseconds(observed)
|
||||
if points:
|
||||
_require(seq > points[-1]["sequence"] and observed >= timestamp(points[-1]["observed_at"]), "batch must be ordered")
|
||||
points.append(normalized)
|
||||
return points
|
||||
|
||||
|
||||
def initialize(path=None):
|
||||
path = Path(path) if path is not None else store_path()
|
||||
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
database = sqlite3.connect(path, timeout=2)
|
||||
try:
|
||||
database.execute("PRAGMA journal_mode=WAL")
|
||||
database.execute("PRAGMA busy_timeout=2000")
|
||||
database.execute("PRAGMA journal_size_limit=8388608")
|
||||
database.execute("PRAGMA wal_autocheckpoint=256")
|
||||
database.executescript(SCHEMA)
|
||||
finally:
|
||||
database.close()
|
||||
try:
|
||||
path.chmod(0o600)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _connect(path, readonly=False):
|
||||
path = Path(path)
|
||||
if not path.is_file():
|
||||
raise sqlite3.OperationalError("sample store is not initialized")
|
||||
# mode=ro never creates a database; initialization is an explicit deploy step.
|
||||
mode = "ro" if readonly else "rw"
|
||||
connection = sqlite3.connect(path.resolve().as_uri() + "?mode=" + mode, uri=True, timeout=2)
|
||||
connection.row_factory = sqlite3.Row
|
||||
connection.execute("PRAGMA busy_timeout=2000")
|
||||
if readonly:
|
||||
connection.execute("PRAGMA query_only=ON")
|
||||
else:
|
||||
connection.execute("PRAGMA wal_autocheckpoint=256")
|
||||
connection.execute("PRAGMA journal_size_limit=8388608")
|
||||
return connection
|
||||
|
||||
|
||||
def _derived(point, previous):
|
||||
quality = point["quality"]
|
||||
gap = bool(point["gap_before"] or point["dropped_samples_before"])
|
||||
rx_rate = tx_rate = None
|
||||
if previous is None:
|
||||
return None, None, quality if quality != "ok" else "gap", True
|
||||
same_epoch = point["counter_epoch"] == previous["counter_epoch"]
|
||||
if same_epoch:
|
||||
_require(point["boot_id"] == previous["boot_id"] and point["interface"] == previous["interface"], "identity change requires new epoch")
|
||||
_require(point["sequence"] > previous["sequence"] and point["monotonic_ns"] > previous["monotonic_ns"], "sequence/clock must advance")
|
||||
_require(point["rx_bytes"] >= previous["rx_bytes"] and point["tx_bytes"] >= previous["tx_bytes"], "counter reset requires new epoch")
|
||||
skipped = point["sequence"] != previous["sequence"] + 1
|
||||
gap = gap or skipped
|
||||
if quality == "ok" and not gap:
|
||||
elapsed = (point["monotonic_ns"] - previous["monotonic_ns"]) / 1_000_000_000
|
||||
_require(abs(elapsed - point["interval_seconds"]) <= max(.01, elapsed * .005), "interval and monotonic clock differ")
|
||||
computed = [(point["rx_bytes"] - previous["rx_bytes"]) / elapsed,
|
||||
(point["tx_bytes"] - previous["tx_bytes"]) / elapsed]
|
||||
for actual, claimed in zip(computed, [point["rx_bytes_per_second"], point["tx_bytes_per_second"]]):
|
||||
_require(math.isfinite(actual) and 0 <= actual <= MAX_RATE and abs(actual - claimed) <= max(2, actual * .005), "rate and counter delta differ")
|
||||
rx_rate, tx_rate = [round(value) for value in computed]
|
||||
elif quality == "ok":
|
||||
quality = "gap"
|
||||
else:
|
||||
# A sampler's bounded queue may have dropped a new epoch's baseline
|
||||
# while disconnected. Its first surviving observation is useful only
|
||||
# as a new baseline; never trust a rate that cannot be checked here.
|
||||
if quality == "ok":
|
||||
quality = "gap"
|
||||
gap = True
|
||||
return rx_rate, tx_rate, quality, gap
|
||||
|
||||
|
||||
def ingest(node_id, points, now, path=None):
|
||||
database = _connect(path if path is not None else store_path())
|
||||
accepted = duplicates = 0
|
||||
try:
|
||||
database.execute("BEGIN IMMEDIATE")
|
||||
cutoff = microseconds(now - timedelta(seconds=HISTORY_SECONDS))
|
||||
database.execute("DELETE FROM samples WHERE observed_us < ?", (cutoff,))
|
||||
known = database.execute("SELECT 1 FROM samples WHERE node_id=? LIMIT 1", (node_id,)).fetchone()
|
||||
count = database.execute("SELECT COUNT(DISTINCT node_id) FROM samples").fetchone()[0]
|
||||
_require(known is not None or count < MAX_NODES, "sample store node limit reached")
|
||||
for point in points:
|
||||
old = database.execute("SELECT payload_sha256 FROM samples WHERE node_id=? AND counter_epoch=? AND sequence=?", (node_id, point["counter_epoch"], point["sequence"])).fetchone()
|
||||
if old is not None:
|
||||
_require(old["payload_sha256"] == point["payload_sha256"], "conflicting repeated sample")
|
||||
duplicates += 1
|
||||
continue
|
||||
previous = database.execute("SELECT * FROM samples WHERE node_id=? ORDER BY observed_us DESC,id DESC LIMIT 1", (node_id,)).fetchone()
|
||||
if previous is not None:
|
||||
_require(point["observed_us"] >= previous["observed_us"], "late unordered sample")
|
||||
rx_rate, tx_rate, quality, gap = _derived(point, previous)
|
||||
database.execute("""INSERT INTO samples (node_id,counter_epoch,sequence,boot_id,interface,observed_us,monotonic_ns,interval_seconds,rx_bytes,tx_bytes,rx_rate,tx_rate,quality,gap_before,dropped_samples_before,payload_sha256,received_us) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||||
(node_id, point["counter_epoch"], point["sequence"], point["boot_id"], point["interface"], point["observed_us"], point["monotonic_ns"], point["interval_seconds"], point["rx_bytes"], point["tx_bytes"], rx_rate, tx_rate, quality, int(gap), point["dropped_samples_before"], point["payload_sha256"], microseconds(now)))
|
||||
accepted += 1
|
||||
database.execute("DELETE FROM samples WHERE node_id=? AND id NOT IN (SELECT id FROM samples WHERE node_id=? ORDER BY observed_us DESC,id DESC LIMIT ?)", (node_id, node_id, MAX_POINTS))
|
||||
database.commit()
|
||||
return {"status": "accepted", "accepted": accepted, "duplicates": duplicates}
|
||||
except BaseException:
|
||||
database.rollback()
|
||||
raise
|
||||
finally:
|
||||
database.close()
|
||||
|
||||
|
||||
def _history_point(row):
|
||||
return {"sampled_at": iso_from_us(row["observed_us"]), "interval_seconds": row["interval_seconds"], "sequence": row["sequence"],
|
||||
"upload_bytes_per_second": row["tx_rate"], "download_bytes_per_second": row["rx_rate"],
|
||||
"counter_epoch": row["counter_epoch"], "interface": row["interface"],
|
||||
"quality": row["quality"], "gap_before": bool(row["gap_before"]),
|
||||
"dropped_samples_before": row["dropped_samples_before"]}
|
||||
|
||||
|
||||
def snapshot(nodes, now, since=None, path=None):
|
||||
_require(len(nodes) <= MAX_NODES, "node response limit reached")
|
||||
cutoff = now - timedelta(seconds=HISTORY_SECONDS)
|
||||
incremental = since is not None
|
||||
since = max(cutoff, since) if incremental else now - timedelta(seconds=DEFAULT_HISTORY_SECONDS)
|
||||
_require(since <= now + timedelta(seconds=5), "history lower bound is in the future")
|
||||
point_limit = min(DEFAULT_HISTORY_SECONDS, MAX_RESPONSE_POINTS // max(1, len(nodes)))
|
||||
database = _connect(path if path is not None else store_path(), readonly=True)
|
||||
try:
|
||||
database.execute("BEGIN")
|
||||
output = []
|
||||
for node in nodes:
|
||||
node_id = node["id"]
|
||||
latest = database.execute("SELECT * FROM samples WHERE node_id=? AND observed_us>=? AND observed_us<=? ORDER BY observed_us DESC,id DESC LIMIT 1", (node_id, microseconds(cutoff), microseconds(now))).fetchone()
|
||||
# Include newly received backfill even when its observed time predates
|
||||
# the previous response's generated_at cursor. Polling never loses
|
||||
# true one-second points from a late five-second batch.
|
||||
if incremental:
|
||||
rows = database.execute("SELECT * FROM samples WHERE node_id=? AND observed_us>=? AND observed_us<=? AND (observed_us>=? OR received_us>=?) ORDER BY observed_us DESC,id DESC LIMIT ?", (node_id, microseconds(cutoff), microseconds(now), microseconds(since), microseconds(since), point_limit + 1)).fetchall()
|
||||
else:
|
||||
rows = database.execute("SELECT * FROM samples WHERE node_id=? AND observed_us>=? AND observed_us<=? ORDER BY observed_us DESC,id DESC LIMIT ?", (node_id, microseconds(since), microseconds(now), point_limit + 1)).fetchall()
|
||||
truncated = len(rows) > point_limit
|
||||
rows = rows[:point_limit]
|
||||
rows.reverse()
|
||||
if not incremental and rows:
|
||||
truncated = truncated or database.execute("SELECT 1 FROM samples WHERE node_id=? AND observed_us>=? AND observed_us<? LIMIT 1", (node_id, microseconds(cutoff), rows[0]["observed_us"])).fetchone() is not None
|
||||
stale = latest is None or not 0 <= (microseconds(now) - latest["observed_us"]) / 1_000_000 <= FRESHNESS_SECONDS or not 0 <= (microseconds(now) - latest["received_us"]) / 1_000_000 <= FRESHNESS_SECONDS
|
||||
valid = not stale and latest["quality"] == "ok" and latest["tx_rate"] is not None and latest["rx_rate"] is not None
|
||||
output.append({"slug": node["slug"], "name": node["name"], "region": node["region"],
|
||||
"current_upload_bytes_per_second": latest["tx_rate"] if valid else None,
|
||||
"current_download_bytes_per_second": latest["rx_rate"] if valid else None,
|
||||
"total_upload_bytes": latest["tx_bytes"] if latest is not None else None,
|
||||
"total_download_bytes": latest["rx_bytes"] if latest is not None else None,
|
||||
"sampled_at": iso_from_us(latest["observed_us"]) if latest is not None else None,
|
||||
"interval_seconds": latest["interval_seconds"] if latest is not None else None,
|
||||
"interface": latest["interface"] if latest is not None else None,
|
||||
"counter_epoch": latest["counter_epoch"] if latest is not None else None,
|
||||
"stale": bool(stale), "history_truncated": bool(truncated),
|
||||
"returned_history_since": iso_from_us(rows[0]["observed_us"]) if rows else None,
|
||||
"history": [_history_point(row) for row in rows]})
|
||||
oldest = min((timestamp(node["returned_history_since"]) for node in output if node["returned_history_since"]), default=now)
|
||||
return {"contract": 1, "scope": "server_host_interface", "source": "linux_host_interface",
|
||||
"direction": "interface_perspective", "counter_since": "boot_or_interface_reset",
|
||||
"refresh_seconds": 5, "sample_period_seconds": 1, "freshness_seconds": FRESHNESS_SECONDS,
|
||||
"history_seconds": min(HISTORY_SECONDS, max(0, math.ceil((now-oldest).total_seconds()))),
|
||||
"available_storage_history_seconds": HISTORY_SECONDS,
|
||||
"requested_history_seconds": max(0, math.ceil((now-since).total_seconds())),
|
||||
"history_point_limit_per_node": point_limit,
|
||||
"history_truncated": any(node["history_truncated"] for node in output),
|
||||
"history_since": since.isoformat(),
|
||||
"generated_at": now.isoformat(), "nodes": output}
|
||||
finally:
|
||||
database.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import argparse
|
||||
parser = argparse.ArgumentParser(description="Initialize only the standalone host traffic SQLite store.")
|
||||
parser.add_argument("--init", action="store_true", required=True)
|
||||
parser.add_argument("--path", type=Path)
|
||||
args = parser.parse_args()
|
||||
initialize(args.path)
|
||||
print("Standalone host traffic store initialized; Django database unchanged.")
|
||||
@@ -0,0 +1,25 @@
|
||||
from django.urls import path
|
||||
|
||||
from . import views, private_auxiliary, host_traffic
|
||||
|
||||
|
||||
urlpatterns = [
|
||||
path("api/v1/client/node-traffic/", host_traffic.client_node_traffic, name="client-node-traffic"),
|
||||
path("api/v1/node/host-traffic/", host_traffic.node_host_traffic, name="node-host-traffic"),
|
||||
path("api/v1/client/private-auxiliary/config/", private_auxiliary.client_config),
|
||||
path("api/v1/private-auxiliary/verify/", private_auxiliary.verify_device),
|
||||
path("", views.dashboard, name="portal-dashboard"),
|
||||
path("register/", views.register, name="register"),
|
||||
path("apply/", views.apply_plan, name="apply-plan"),
|
||||
path("sub/<str:token>/config.yaml", views.subscription_config, name="subscription-config"),
|
||||
path("api/v1/me/", views.api_me, name="api-me"),
|
||||
path("api/v1/client/login/", views.client_login, name="client-login"),
|
||||
path("api/v1/client/profile/", views.client_profile, name="client-profile"),
|
||||
path("api/v1/client/update/", views.client_update, name="client-update"),
|
||||
path("api/v1/client/config/", views.client_config, name="client-config"),
|
||||
path("api/v1/client/observations/", views.client_observations, name="client-observations"),
|
||||
path("api/v1/client/logout/", views.client_logout, name="client-logout"),
|
||||
path("api/v1/node/sync/", views.node_sync, name="node-sync"),
|
||||
path("downloads/windows/latest/", views.client_download_latest, name="client-download-latest"),
|
||||
path("health/", views.health, name="health"),
|
||||
]
|
||||
@@ -0,0 +1,24 @@
|
||||
# Add this overlay AFTER all three existing production compose files.
|
||||
# Keep the existing web image, command, ports and all existing volume entries.
|
||||
services:
|
||||
web:
|
||||
environment:
|
||||
VPN_RUN_STARTUP_TASKS: "false"
|
||||
TOPLC_HOST_TRAFFIC_DB: /var/lib/toplc-vpn-host-traffic/host-traffic.sqlite3
|
||||
volumes:
|
||||
- type: bind
|
||||
source: /opt/toplc-vpn/host-traffic-standalone-20261106/control/host_traffic.py
|
||||
target: /app/control/host_traffic.py
|
||||
read_only: true
|
||||
- type: bind
|
||||
source: /opt/toplc-vpn/host-traffic-standalone-20261106/control/host_traffic_store.py
|
||||
target: /app/control/host_traffic_store.py
|
||||
read_only: true
|
||||
- type: bind
|
||||
source: /opt/toplc-vpn/host-traffic-standalone-20261106/control/urls.py
|
||||
target: /app/control/urls.py
|
||||
read_only: true
|
||||
- type: bind
|
||||
source: /opt/toplc-vpn/host-traffic-state
|
||||
target: /var/lib/toplc-vpn-host-traffic
|
||||
read_only: false
|
||||
@@ -0,0 +1,424 @@
|
||||
"""Exercise actual candidate modules with production model snapshots in SQLite.
|
||||
|
||||
Only local temporary databases are used. No server connection or real token.
|
||||
Run with output/proxy-aggregate-api-20261106/test-venv/Scripts/python.exe.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sqlite3
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone as utc
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
CANDIDATE = Path(__file__).resolve().parents[1]
|
||||
ROOT = CANDIDATE.parents[2]
|
||||
BASELINE = ROOT / "output/proxy-aggregate-api-20261106/baseline"
|
||||
OUTPUT = ROOT / "output/host-traffic-standalone-20261106"
|
||||
OUTPUT.mkdir(parents=True, exist_ok=True)
|
||||
runtime_context = tempfile.TemporaryDirectory(prefix="django-tests-", dir=OUTPUT)
|
||||
RUNTIME = Path(runtime_context.name).resolve()
|
||||
assert RUNTIME.parent == OUTPUT.resolve()
|
||||
for package in ("accounts", "control"):
|
||||
(RUNTIME / package).mkdir()
|
||||
(RUNTIME / package / "__init__.py").write_text("")
|
||||
shutil.copy2(BASELINE / package / "models.py", RUNTIME / package / "models.py")
|
||||
shutil.copy2(BASELINE / "accounts/middleware.py", RUNTIME / "accounts/middleware.py")
|
||||
for module in ("host_traffic.py", "host_traffic_store.py"):
|
||||
shutil.copy2(CANDIDATE / "control" / module, RUNTIME / "control" / module)
|
||||
(RUNTIME / "test_urls.py").write_text('from django.urls import path\nfrom control import host_traffic\nurlpatterns=[path("api/v1/client/node-traffic/",host_traffic.client_node_traffic),path("api/v1/node/host-traffic/",host_traffic.node_host_traffic)]\n')
|
||||
sys.path.insert(0, str(RUNTIME))
|
||||
from django.conf import settings
|
||||
settings.configure(SECRET_KEY="local-isolated-fixture-only", USE_TZ=True, TIME_ZONE="UTC",
|
||||
DEBUG=False, ALLOWED_HOSTS=["testserver"], ROOT_URLCONF="test_urls", STATIC_URL="/static/",
|
||||
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
|
||||
AUTH_USER_MODEL="accounts.User", DEFAULT_AUTO_FIELD="django.db.models.BigAutoField",
|
||||
INSTALLED_APPS=["django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions",
|
||||
"django.contrib.messages", "accounts", "control"],
|
||||
MIGRATION_MODULES={"accounts": None, "control": None},
|
||||
MIDDLEWARE=["django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware",
|
||||
"django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware",
|
||||
"django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware",
|
||||
"accounts.middleware.LoginRateLimitMiddleware", "django.contrib.messages.middleware.MessageMiddleware",
|
||||
"django.middleware.clickjacking.XFrameOptionsMiddleware"])
|
||||
import django
|
||||
django.setup()
|
||||
from django.db import connection
|
||||
from django.test import TestCase, Client
|
||||
from django.test.runner import DiscoverRunner
|
||||
from django.test.utils import CaptureQueriesContext
|
||||
from django.utils import timezone
|
||||
from accounts.models import User, LoginAttempt
|
||||
from control.models import Plan, Subscription, Device, ClientSession, Node
|
||||
from control import host_traffic_store as store
|
||||
|
||||
NOW = datetime(2026, 11, 6, 8, 0, 0, tzinfo=utc.utc)
|
||||
BOOT = "11111111-1111-4111-8111-111111111111"
|
||||
EPOCH = "22222222-2222-4222-8222-222222222222"
|
||||
|
||||
|
||||
def point(sequence=1, *, at=None, rx=None, tx=None, quality=None, epoch=EPOCH):
|
||||
at = at if at is not None else NOW - timedelta(seconds=10-sequence)
|
||||
quality = quality or ("baseline" if sequence == 1 else "ok")
|
||||
return dict(sequence=sequence, observed_at=at.isoformat(), monotonic_ns=sequence*1_000_000_000,
|
||||
counter_epoch=epoch, interval_seconds=0 if quality != "ok" else 1,
|
||||
rx_bytes=sequence*1000 if rx is None else rx, tx_bytes=sequence*2000 if tx is None else tx,
|
||||
rx_bytes_per_second=1000 if quality == "ok" else None,
|
||||
tx_bytes_per_second=2000 if quality == "ok" else None,
|
||||
quality=quality, gap_before=False, dropped_samples_before=0)
|
||||
|
||||
|
||||
def batch(samples=None):
|
||||
return dict(contract=1, node_slug="fixture-node", boot_id=BOOT, interface="eth0",
|
||||
kind="server_host_interface", counter_semantics="linux_proc_net_dev_interface_bytes",
|
||||
samples=samples if samples is not None else [point(), point(2)])
|
||||
|
||||
|
||||
class StoreTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory(prefix="store-", dir=RUNTIME)
|
||||
self.path = Path(self.temp.name) / "samples.sqlite3"
|
||||
store.initialize(self.path)
|
||||
|
||||
def tearDown(self):
|
||||
self.temp.cleanup()
|
||||
|
||||
def parsed(self, payload):
|
||||
return store.parse_batch(json.dumps(payload).encode(), "fixture-node", NOW)
|
||||
|
||||
def write(self, payload=None, node=1):
|
||||
return store.ingest(node, self.parsed(payload or batch()), NOW, self.path)
|
||||
|
||||
def count(self):
|
||||
db = sqlite3.connect(self.path)
|
||||
try:
|
||||
return db.execute("SELECT COUNT(*) FROM samples").fetchone()[0]
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
def test_real_rx_tx_direction_and_first_sample_unknown(self):
|
||||
self.write()
|
||||
result = store.snapshot([dict(id=1, slug="fixture-node", name="VPN", region="fixture")], NOW, path=self.path)
|
||||
node = result["nodes"][0]
|
||||
self.assertEqual(node["current_upload_bytes_per_second"], 2000)
|
||||
self.assertEqual(node["current_download_bytes_per_second"], 1000)
|
||||
self.assertIsNone(node["history"][0]["upload_bytes_per_second"])
|
||||
self.assertEqual(len(node["history"]), 2)
|
||||
self.assertEqual(node["history"][1]["sampled_at"], point(2)["observed_at"])
|
||||
self.assertEqual(node["total_upload_bytes"], 4000)
|
||||
(OUTPUT / "client-node-traffic-fixture.json").write_text(json.dumps(result, indent=2), encoding="utf-8")
|
||||
|
||||
def test_duplicates_and_conflicting_duplicate_rollback(self):
|
||||
self.assertEqual(self.write()["accepted"], 2)
|
||||
self.assertEqual(self.write(), {"status": "accepted", "accepted": 0, "duplicates": 2})
|
||||
altered = batch()
|
||||
altered["samples"][0]["rx_bytes"] += 1
|
||||
with self.assertRaises(store.InvalidSample):
|
||||
self.write(altered)
|
||||
self.assertEqual(self.count(), 2)
|
||||
|
||||
def test_partial_batch_is_rolled_back(self):
|
||||
self.write()
|
||||
with self.assertRaises(store.InvalidSample):
|
||||
self.write(batch([point(3), point(4, rx=1)]))
|
||||
self.assertEqual(self.count(), 2)
|
||||
|
||||
def test_reset_requires_new_epoch_and_breaks_history(self):
|
||||
self.write()
|
||||
with self.assertRaises(store.InvalidSample):
|
||||
self.write(batch([point(3, rx=1, tx=1, quality="reset")]))
|
||||
self.write(batch([point(3, rx=1, tx=1, quality="reset", epoch=str(uuid.uuid4()))]))
|
||||
result = store.snapshot([dict(id=1, slug="fixture-node", name="VPN", region="fixture")], NOW, path=self.path)["nodes"][0]
|
||||
self.assertIsNone(result["current_upload_bytes_per_second"])
|
||||
self.assertTrue(result["history"][-1]["gap_before"])
|
||||
|
||||
def test_clock_and_rate_mismatch_rejected(self):
|
||||
self.write()
|
||||
for field, value in (("monotonic_ns", 100), ("interval_seconds", 2), ("rx_bytes_per_second", 500000)):
|
||||
value_point = point(3)
|
||||
value_point[field] = value
|
||||
with self.subTest(field=field), self.assertRaises(store.InvalidSample):
|
||||
self.write(batch([value_point]))
|
||||
self.assertEqual(self.count(), 2)
|
||||
|
||||
def test_body_bounds_and_field_validation(self):
|
||||
wrong = []
|
||||
for field, value in (("contract", True), ("node_slug", "other"), ("interface", "tailscale0"),
|
||||
("interface", "../eth0"), ("boot_id", "bad"), ("samples", []),
|
||||
("samples", [point()]*61)):
|
||||
payload = batch()
|
||||
payload[field] = value
|
||||
wrong.append(payload)
|
||||
for field, value in (("rx_bytes", -1), ("tx_bytes", 2**63), ("sequence", True),
|
||||
("observed_at", (NOW+timedelta(seconds=6)).isoformat()),
|
||||
("observed_at", (NOW-timedelta(seconds=3601)).isoformat()),
|
||||
("observed_at", "2026-11-06T08:00:00"), ("rx_bytes_per_second", float("nan")),
|
||||
("tx_bytes_per_second", float("inf")), ("interval_seconds", .1),
|
||||
("gap_before", 1), ("dropped_samples_before", -1), ("counter_epoch", "x")):
|
||||
payload = batch([point(2)])
|
||||
payload["samples"][0][field] = value
|
||||
wrong.append(payload)
|
||||
for index, payload in enumerate(wrong):
|
||||
with self.subTest(index=index), self.assertRaises((store.InvalidSample, TypeError)):
|
||||
self.parsed(payload)
|
||||
with self.assertRaises(store.InvalidSample):
|
||||
store.parse_batch(b"x"*65537, "fixture-node", NOW)
|
||||
|
||||
def test_since_stale_missing_and_no_read_initialization(self):
|
||||
self.write()
|
||||
nodes = [dict(id=i, slug=f"node-{i}", name="VPN", region="fixture") for i in [1, 2]]
|
||||
result = store.snapshot(nodes, NOW+timedelta(seconds=1), NOW+timedelta(seconds=.5), self.path)
|
||||
self.assertEqual(len(result["nodes"][0]["history"]), 0)
|
||||
result = store.snapshot(nodes, NOW, NOW-timedelta(seconds=8), self.path)
|
||||
# Both old observations arrived after the lower-bound cursor.
|
||||
self.assertEqual(len(result["nodes"][0]["history"]), 2)
|
||||
self.assertIsNone(result["nodes"][1]["sampled_at"])
|
||||
stale = store.snapshot(nodes, NOW+timedelta(seconds=20), path=self.path)["nodes"][0]
|
||||
self.assertTrue(stale["stale"])
|
||||
self.assertIsNone(stale["current_upload_bytes_per_second"])
|
||||
with self.assertRaises(sqlite3.Error):
|
||||
store.snapshot(nodes, NOW, path=self.path.parent / "does-not-exist.sqlite3")
|
||||
self.assertFalse((self.path.parent / "does-not-exist.sqlite3").exists())
|
||||
|
||||
def test_late_batch_incremental_read_uses_receipt_time(self):
|
||||
nodes = [dict(id=1, slug="n", name="n", region="n")]
|
||||
self.write(batch([point()]))
|
||||
before = store.snapshot(nodes, NOW, path=self.path)
|
||||
later = NOW+timedelta(seconds=5)
|
||||
delayed = batch([point(2), point(3), point(4), point(5), point(6)])
|
||||
store.ingest(1, store.parse_batch(json.dumps(delayed).encode(), "fixture-node", later), later, self.path)
|
||||
after = store.snapshot(nodes, later, datetime.fromisoformat(before["generated_at"]), self.path)
|
||||
self.assertEqual([p["sequence"] for p in after["nodes"][0]["history"]], [1,2,3,4,5,6])
|
||||
|
||||
def test_sequence_gap_does_not_invent_rate(self):
|
||||
self.write()
|
||||
self.write(batch([point(4)]))
|
||||
node = store.snapshot([dict(id=1, slug="n", name="n", region="n")], NOW, path=self.path)["nodes"][0]
|
||||
self.assertTrue(node["history"][-1]["gap_before"])
|
||||
self.assertIsNone(node["current_upload_bytes_per_second"])
|
||||
|
||||
def test_lost_new_epoch_baseline_can_reconnect(self):
|
||||
self.write()
|
||||
epoch = str(uuid.uuid4())
|
||||
self.write(batch([point(50, at=NOW-timedelta(seconds=2), epoch=epoch)]))
|
||||
# The first new epoch rate is deliberately unknown, then normal deltas
|
||||
# are usable again. It must not remain in a permanent HTTP400 loop.
|
||||
self.write(batch([point(51, at=NOW-timedelta(seconds=1), epoch=epoch)]))
|
||||
node = store.snapshot([dict(id=1, slug="n", name="n", region="n")], NOW, path=self.path)["nodes"][0]
|
||||
self.assertEqual(node["history"][-2]["quality"], "gap")
|
||||
self.assertIsNone(node["history"][-2]["upload_bytes_per_second"])
|
||||
self.assertEqual(node["history"][-1]["upload_bytes_per_second"], 2000)
|
||||
|
||||
def test_first_load_window_response_point_budget(self):
|
||||
# Seed one second of real data for a full hour, using bounded batches.
|
||||
for start in range(1, 3601, 60):
|
||||
points = [point(i, at=NOW-timedelta(seconds=3600-i)) for i in range(start, start+60)]
|
||||
self.write(batch(points))
|
||||
nodes = [dict(id=i, slug=f"node-{i}", name="VPN", region="fixture") for i in range(1, 33)]
|
||||
result = store.snapshot(nodes, NOW, path=self.path)
|
||||
self.assertEqual(result["available_storage_history_seconds"], 3600)
|
||||
self.assertEqual(result["requested_history_seconds"], 300)
|
||||
self.assertEqual(result["history_point_limit_per_node"], 62)
|
||||
self.assertEqual(len(result["nodes"][0]["history"]), 62)
|
||||
self.assertTrue(result["history_truncated"])
|
||||
# Populate every response node with maximal scalar field widths to
|
||||
# verify the hard byte budget independently of JSON whitespace.
|
||||
worst_point = copy.deepcopy(result["nodes"][0]["history"][-1])
|
||||
worst_point.update(sequence=2**53-1, sampled_at="2026-11-06T08:00:00.999999+00:00",
|
||||
interface="abcdefghijklmn0", interval_seconds=3599.999999,
|
||||
upload_bytes_per_second=10**12, download_bytes_per_second=10**12,
|
||||
quality="interface_changed", dropped_samples_before=1000000)
|
||||
for node in result["nodes"]:
|
||||
node["history"] = [worst_point] * result["history_point_limit_per_node"]
|
||||
node["name"] = "界" * 100
|
||||
node["region"] = "界" * 100
|
||||
self.assertLess(len(json.dumps(result, ensure_ascii=False, separators=(",", ":")).encode()), store.MAX_RESPONSE_BYTES)
|
||||
|
||||
def test_at_most_32_nodes(self):
|
||||
for node_id in range(1, 33):
|
||||
self.write(node=node_id)
|
||||
with self.assertRaises(store.InvalidSample):
|
||||
self.write(node=33)
|
||||
|
||||
def test_actual_sampler_fixture_round_trip(self):
|
||||
source = CANDIDATE.parent / "host-traffic-sampler/host-traffic-contract-fixture.json"
|
||||
payload = source.read_bytes()
|
||||
now = datetime(2026, 11, 6, 6, 0, 6, tzinfo=utc.utc)
|
||||
points = store.parse_batch(payload, "node-example", now)
|
||||
self.assertEqual(store.ingest(1, points, now, self.path)["accepted"], 5)
|
||||
self.assertEqual(store.ingest(1, points, now, self.path)["duplicates"], 5)
|
||||
result = store.snapshot([dict(id=1, slug="node-example", name="VPN", region="fixture")], now, path=self.path)
|
||||
self.assertEqual(result["nodes"][0]["current_upload_bytes_per_second"], 40)
|
||||
self.assertEqual(result["nodes"][0]["current_download_bytes_per_second"], 80)
|
||||
self.assertEqual([p["quality"] for p in result["nodes"][0]["history"]], ["baseline", "ok", "ok", "reset", "ok"])
|
||||
(OUTPUT / "sampler-client-roundtrip-fixture.json").write_text(json.dumps(result, indent=2), encoding="utf-8")
|
||||
|
||||
def test_point_cap_and_one_hour_retention(self):
|
||||
for start in range(1, 3602, 60):
|
||||
points = [point(i, at=NOW-timedelta(seconds=3601-i)) for i in range(start, min(start+60, 3602))]
|
||||
self.write(batch(points))
|
||||
self.assertEqual(self.count(), 3600)
|
||||
later = NOW + timedelta(seconds=3599)
|
||||
payload = batch([point(3602, at=later, quality="gap")])
|
||||
store.ingest(1, store.parse_batch(json.dumps(payload).encode(), "fixture-node", later), later, self.path)
|
||||
self.assertLessEqual(self.count(), 3)
|
||||
|
||||
|
||||
class EndpointTests(TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory(prefix="api-store-", dir=RUNTIME)
|
||||
self.path = Path(self.temp.name) / "samples.sqlite3"
|
||||
store.initialize(self.path)
|
||||
self.env = patch.dict(os.environ, TOPLC_HOST_TRAFFIC_DB=str(self.path))
|
||||
self.env.start()
|
||||
self.clock = patch.object(timezone, "now", return_value=NOW)
|
||||
self.clock.start()
|
||||
self.user = User.objects.create(username="fixture-staff", email="fixture@example.invalid", is_staff=True,
|
||||
is_active=True, account_status="active", identity_type="employee")
|
||||
self.plan = Plan.objects.create(name="fixture", slug="fixture")
|
||||
self.sub = Subscription.objects.create(user=self.user, plan=self.plan, status="active", provisioning_state="active")
|
||||
self.device = Device.objects.create(subscription=self.sub, device_id="fixture-device-1234567890", active=True)
|
||||
self.session, self.token = ClientSession.issue(self.sub, self.device)
|
||||
self.node = Node.objects.create(name="VPN-fixture", slug="fixture-node", region="fixture", server="example.invalid",
|
||||
port=11084, protocol="vless_reality", status="online", active=True, subscription_enabled=True)
|
||||
self.node_token = "node-fixture-token-" + "x"*32
|
||||
self.node.set_agent_token(self.node_token)
|
||||
self.node.save(update_fields=["agent_token_digest"])
|
||||
self.client = Client()
|
||||
|
||||
def tearDown(self):
|
||||
self.clock.stop()
|
||||
self.env.stop()
|
||||
self.temp.cleanup()
|
||||
|
||||
def get(self, token=None, **kwargs):
|
||||
with CaptureQueriesContext(connection) as queries:
|
||||
response = self.client.get("/api/v1/client/node-traffic/", HTTP_AUTHORIZATION="Bearer "+(token if token is not None else self.token), **kwargs)
|
||||
self.assertTrue(all(q["sql"].lstrip().upper().startswith("SELECT") for q in queries.captured_queries), queries.captured_queries)
|
||||
self.assertNotIn(self.token.encode(), response.content)
|
||||
self.assertNotIn(self.session.token_digest.encode(), response.content)
|
||||
self.assertIn("no-store", response.get("Cache-Control", ""))
|
||||
return response
|
||||
|
||||
def post(self, payload=None, token=None, slug="fixture-node"):
|
||||
with CaptureQueriesContext(connection) as queries:
|
||||
response = self.client.post("/api/v1/node/host-traffic/", data=json.dumps(payload or batch()), content_type="application/json",
|
||||
HTTP_AUTHORIZATION="Bearer "+(token if token is not None else self.node_token), HTTP_X_NODE_SLUG=slug)
|
||||
self.assertTrue(all(q["sql"].lstrip().upper().startswith("SELECT") for q in queries.captured_queries), queries.captured_queries)
|
||||
self.assertNotIn(self.node_token.encode(), response.content)
|
||||
return response
|
||||
|
||||
def test_staff_token_get_and_primary_database_unchanged(self):
|
||||
self.assertEqual(self.post().status_code, 200)
|
||||
response = self.get()
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.json()["nodes"][0]["current_upload_bytes_per_second"], 2000)
|
||||
self.session.refresh_from_db()
|
||||
self.assertEqual(self.session.last_seen_at, NOW)
|
||||
self.assertEqual(LoginAttempt.objects.count(), 0)
|
||||
|
||||
def test_missing_malformed_unknown_token(self):
|
||||
response = self.client.get("/api/v1/client/node-traffic/")
|
||||
self.assertEqual(response.status_code, 401)
|
||||
for token in ["x", "x"*31, "x"*257, "x"*40]:
|
||||
with self.subTest(token_length=len(token)):
|
||||
self.assertEqual(self.get(token).status_code, 401)
|
||||
|
||||
def test_expired_or_revoked_session(self):
|
||||
self.session.expires_at = NOW
|
||||
self.session.save(update_fields=["expires_at"])
|
||||
self.assertEqual(self.get().status_code, 401)
|
||||
self.session.expires_at = NOW+timedelta(days=1)
|
||||
self.session.revoked_at = NOW
|
||||
self.session.save(update_fields=["expires_at", "revoked_at"])
|
||||
self.assertEqual(self.get().status_code, 401)
|
||||
|
||||
def test_device_disabled(self):
|
||||
self.device.active = False
|
||||
self.device.save(update_fields=["active"])
|
||||
self.assertEqual(self.get().status_code, 403)
|
||||
|
||||
def test_staff_and_active_account_checks(self):
|
||||
for field, value in [("is_staff", False), ("is_active", False), ("account_status", "suspended"),
|
||||
("account_status", "departed"), ("account_status", "pending")]:
|
||||
original = getattr(self.user, field)
|
||||
setattr(self.user, field, value)
|
||||
self.user.save(update_fields=[field])
|
||||
with self.subTest(field=field, value=value):
|
||||
self.assertEqual(self.get().status_code, 403)
|
||||
setattr(self.user, field, original)
|
||||
self.user.save(update_fields=[field])
|
||||
|
||||
def test_subscription_expiry_suspension_provisioning_quota(self):
|
||||
for field, value in [("expires_at", NOW), ("status", "suspended"), ("provisioning_state", "pending")]:
|
||||
original = getattr(self.sub, field)
|
||||
setattr(self.sub, field, value)
|
||||
self.sub.save(update_fields=[field])
|
||||
self.assertEqual(self.get().status_code, 403)
|
||||
self.sub.refresh_from_db()
|
||||
self.assertEqual(getattr(self.sub, field), value)
|
||||
setattr(self.sub, field, original)
|
||||
self.sub.save(update_fields=[field])
|
||||
self.sub.traffic_limit_bytes = 10
|
||||
self.sub.upload_bytes = 10
|
||||
self.sub.save(update_fields=["traffic_limit_bytes", "upload_bytes"])
|
||||
self.assertEqual(self.get().status_code, 403)
|
||||
self.sub.refresh_from_db()
|
||||
self.assertEqual(self.sub.status, "active")
|
||||
|
||||
def test_node_auth_and_disabled_not_accepted(self):
|
||||
self.assertEqual(self.post(token="unknown"+"x"*32).status_code, 401)
|
||||
self.assertEqual(self.post(slug="different").status_code, 401)
|
||||
self.node.active = False
|
||||
self.node.save(update_fields=["active"])
|
||||
self.assertEqual(self.post().status_code, 401)
|
||||
|
||||
def test_dynamic_node_scope_only_active_and_subscribed(self):
|
||||
for i in range(2, 5):
|
||||
Node.objects.create(name=f"VPN{i}", slug=f"node-{i}", region="fixture", server="example.invalid", port=10000+i,
|
||||
protocol="vless_reality", active=(i != 3), subscription_enabled=(i != 4))
|
||||
self.assertEqual({n["slug"] for n in self.get().json()["nodes"]}, {"fixture-node", "node-2"})
|
||||
|
||||
def test_invalid_payload_size_and_method(self):
|
||||
self.assertEqual(self.client.post("/api/v1/client/node-traffic/").status_code, 405)
|
||||
self.assertEqual(self.client.get("/api/v1/node/host-traffic/").status_code, 405)
|
||||
self.assertEqual(self.client.post("/api/v1/node/host-traffic/", data="x"*65537,
|
||||
content_type="application/json", HTTP_AUTHORIZATION="Bearer "+self.node_token, HTTP_X_NODE_SLUG="fixture-node").status_code, 400)
|
||||
invalid = batch()
|
||||
invalid["node_slug"] = "other"
|
||||
self.assertEqual(self.post(invalid).status_code, 400)
|
||||
|
||||
def test_read_requires_initialized_store_and_since_validation(self):
|
||||
self.path.unlink()
|
||||
self.assertEqual(self.get().status_code, 503)
|
||||
self.assertFalse(self.path.exists())
|
||||
store.initialize(self.path)
|
||||
self.assertEqual(self.get(QUERY_STRING="since=bad").status_code, 400)
|
||||
self.assertEqual(self.get(QUERY_STRING="since=2099-01-01T00:00:00Z").status_code, 400)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
suite = unittest.TestSuite([unittest.defaultTestLoader.loadTestsFromTestCase(StoreTests),
|
||||
unittest.defaultTestLoader.loadTestsFromTestCase(EndpointTests)])
|
||||
runner = DiscoverRunner(verbosity=2)
|
||||
old_config = runner.setup_databases()
|
||||
try:
|
||||
result = unittest.TextTestRunner(verbosity=2).run(suite)
|
||||
report = {"passed": result.wasSuccessful(), "tests_run": result.testsRun,
|
||||
"failures": len(result.failures), "errors": len(result.errors),
|
||||
"django_version": django.get_version(), "actual_production_models": True,
|
||||
"production_servers_modified": False, "primary_database_dml_in_requests": False,
|
||||
"fixture": str(OUTPUT / "client-node-traffic-fixture.json")}
|
||||
(OUTPUT / "security-test-result.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
|
||||
finally:
|
||||
runner.teardown_databases(old_config)
|
||||
runtime_context.cleanup()
|
||||
sys.exit(0 if result.wasSuccessful() else 1)
|
||||
@@ -0,0 +1,76 @@
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Security;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal enum ClientRuntimeFault { Missing, Unreadable, Empty, CannotStart }
|
||||
|
||||
// An installation failure is local to every node. Never feed it into node or
|
||||
// transport health/cooldown, or retry it by changing the user's network route.
|
||||
internal sealed class ClientRuntimeException(string componentPath, ClientRuntimeFault fault, Exception? inner = null)
|
||||
: IOException(MessageFor(componentPath, fault), inner)
|
||||
{
|
||||
internal string ComponentPath { get; } = Path.GetFullPath(componentPath);
|
||||
internal ClientRuntimeFault Fault { get; } = fault;
|
||||
|
||||
private static string MessageFor(string path, ClientRuntimeFault fault)
|
||||
{
|
||||
var issue = fault switch
|
||||
{
|
||||
ClientRuntimeFault.Missing => "缺失",
|
||||
ClientRuntimeFault.Empty => "为空或已损坏",
|
||||
ClientRuntimeFault.CannotStart => "无法启动(程序文件或依赖异常)",
|
||||
_ => "无法读取(权限或文件占用)",
|
||||
};
|
||||
return $"本机客户端组件{issue}:{Path.GetFileName(path)}\n位置:{Path.GetFullPath(path)}\n\n"
|
||||
+ "请重新运行纵横家最新完整安装包,在原安装目录修复。账号和配置会保留。";
|
||||
}
|
||||
|
||||
// Only local installation identity. No token, node config or credentials.
|
||||
internal string Diagnostic => $"client_runtime fault={Fault} component={Clean(ComponentPath)}"
|
||||
+ $" process={Clean(Environment.ProcessPath ?? "unknown")} version={Clean(Application.ProductVersion)}";
|
||||
private static string Clean(string value) => value.Replace('\r', ' ').Replace('\n', ' ');
|
||||
}
|
||||
|
||||
internal static class ClientRuntime
|
||||
{
|
||||
internal static readonly string[] Components = ["xray.exe", "geoip.dat", "geosite.dat", "wintun.dll"];
|
||||
|
||||
internal static void Validate(string installationDirectory)
|
||||
{
|
||||
// Resolve exclusively beside this application, never the current
|
||||
// working directory, PATH, or an unrelated installed Xray binary.
|
||||
var directory = Path.Combine(Path.GetFullPath(installationDirectory), "xray");
|
||||
foreach (var name in Components)
|
||||
{
|
||||
var path = Path.Combine(directory, name);
|
||||
try
|
||||
{
|
||||
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read,
|
||||
FileShare.ReadWrite | FileShare.Delete);
|
||||
if (stream.Length == 0 || stream.ReadByte() < 0)
|
||||
throw new ClientRuntimeException(path, ClientRuntimeFault.Empty);
|
||||
}
|
||||
catch (ClientRuntimeException) { throw; }
|
||||
catch (Exception error) when (error is FileNotFoundException or DirectoryNotFoundException)
|
||||
{ throw new ClientRuntimeException(path, ClientRuntimeFault.Missing, error); }
|
||||
catch (Exception error) when (error is IOException or UnauthorizedAccessException or SecurityException)
|
||||
{ throw new ClientRuntimeException(path, ClientRuntimeFault.Unreadable, error); }
|
||||
}
|
||||
}
|
||||
|
||||
internal static bool Start(Process process)
|
||||
{
|
||||
try { return process.Start(); }
|
||||
// The executable can disappear or become blocked after preflight.
|
||||
// Classify only known local CreateProcess failures, not socket errors,
|
||||
// arbitrary IO, or remote Reality/TLS/configuration failures.
|
||||
catch (Win32Exception error) when (error.NativeErrorCode is 2 or 3 or 5 or 32 or 33 or 126 or 193 or 216 or 225 or 740)
|
||||
{
|
||||
var fault = error.NativeErrorCode is 2 or 3 ? ClientRuntimeFault.Missing
|
||||
: error.NativeErrorCode is 5 or 32 or 33 ? ClientRuntimeFault.Unreadable : ClientRuntimeFault.CannotStart;
|
||||
throw new ClientRuntimeException(process.StartInfo.FileName, fault, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
using System.Text.Json;
|
||||
using System.Security.AccessControl;
|
||||
using System.Security.Principal;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class ClientRuntimeSelfTest
|
||||
{
|
||||
internal static async Task<Dictionary<string, bool>> CheckAsync()
|
||||
{
|
||||
var checks = new Dictionary<string, bool>();
|
||||
var root = Path.Combine(Path.GetTempPath(), "ucvl-runtime-test-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(Path.Combine(root, "xray"));
|
||||
// Tiny inert fixture files; none are executed or treated as real Xray.
|
||||
void Seed() { foreach (var name in ClientRuntime.Components) File.WriteAllBytes(Path.Combine(root, "xray", name), [1, 2]); }
|
||||
ClientRuntimeException? ReadFault()
|
||||
{
|
||||
try { ClientRuntime.Validate(root); return null; }
|
||||
catch (ClientRuntimeException error) { return error; }
|
||||
}
|
||||
async Task<bool> RuntimeFailure(Func<Task> operation)
|
||||
{
|
||||
try { await operation(); return false; }
|
||||
catch (ClientRuntimeException) { return true; }
|
||||
}
|
||||
try
|
||||
{
|
||||
Seed();
|
||||
checks["four_readable_nonempty_components_accepted"] = ReadFault() is null;
|
||||
foreach (var name in ClientRuntime.Components)
|
||||
{
|
||||
var path = Path.Combine(root, "xray", name);
|
||||
File.Delete(path);
|
||||
var missing = ReadFault();
|
||||
checks["missing_" + name] = missing is { Fault: ClientRuntimeFault.Missing }
|
||||
&& missing.ComponentPath == path && missing.Message.Contains("完整安装包") && missing.Message.Contains(path);
|
||||
Seed();
|
||||
File.WriteAllBytes(path, []);
|
||||
checks["empty_" + name] = ReadFault() is { Fault: ClientRuntimeFault.Empty };
|
||||
Seed();
|
||||
using (var locked = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None))
|
||||
checks["locked_not_reported_missing_" + name] = ReadFault() is { Fault: ClientRuntimeFault.Unreadable };
|
||||
}
|
||||
var deniedPath = Path.Combine(root, "xray", "xray.exe");
|
||||
var originalAcl = new FileInfo(deniedPath).GetAccessControl();
|
||||
try
|
||||
{
|
||||
var deniedAcl = new FileInfo(deniedPath).GetAccessControl();
|
||||
deniedAcl.AddAccessRule(new FileSystemAccessRule(WindowsIdentity.GetCurrent().User!, FileSystemRights.ReadData,
|
||||
AccessControlType.Deny));
|
||||
new FileInfo(deniedPath).SetAccessControl(deniedAcl);
|
||||
checks["access_denied_not_reported_missing"] = ReadFault() is { Fault: ClientRuntimeFault.Unreadable };
|
||||
}
|
||||
finally { new FileInfo(deniedPath).SetAccessControl(originalAcl); }
|
||||
var error = new ClientRuntimeException(Path.Combine(root, "xray", "xray.exe"), ClientRuntimeFault.Missing);
|
||||
using (var absent = new System.Diagnostics.Process { StartInfo = new System.Diagnostics.ProcessStartInfo {
|
||||
FileName=Path.Combine(root, "xray", "missing-fixture.exe"), UseShellExecute=false, CreateNoWindow=true,
|
||||
} })
|
||||
{
|
||||
try { ClientRuntime.Start(absent); checks["disappeared_executable_is_local_failure"] = false; }
|
||||
catch (ClientRuntimeException failure) { checks["disappeared_executable_is_local_failure"] = failure.Fault == ClientRuntimeFault.Missing; }
|
||||
}
|
||||
using (var invalid = new System.Diagnostics.Process { StartInfo = new System.Diagnostics.ProcessStartInfo {
|
||||
FileName=Path.Combine(root, "xray", "xray.exe"), UseShellExecute=false, CreateNoWindow=true,
|
||||
} })
|
||||
{
|
||||
try { ClientRuntime.Start(invalid); checks["invalid_executable_is_local_failure"] = false; }
|
||||
catch (ClientRuntimeException failure) { checks["invalid_executable_is_local_failure"] = failure.Fault == ClientRuntimeFault.CannotStart; }
|
||||
}
|
||||
checks["diagnostic_contains_only_installation_identity"] = error.Diagnostic.Contains(error.ComponentPath)
|
||||
&& error.Diagnostic.Contains(" process=") && error.Diagnostic.Contains(" version=")
|
||||
&& !error.Diagnostic.Contains('\n') && !error.Diagnostic.Contains('\r');
|
||||
var response = JsonSerializer.Deserialize<ConfigResponse>("""
|
||||
{"config_contract":2,"connection_scope":"public","node":{"slug":"tokyo","name":"VPN002"},"route_mode":"smart",
|
||||
"tailscale_endpoint":{"contract":1,"node_slug":"tokyo","address":"100.64.0.2","port":10803},
|
||||
"config":{"inbounds":[],"outbounds":[
|
||||
{"tag":"proxy","protocol":"vless","settings":{"vnext":[{"address":"vpn002.example.invalid","port":11082,"users":[{"id":"11111111-1111-1111-1111-111111111111","encryption":"none","flow":"xtls-rprx-vision"}]}]},
|
||||
"streamSettings":{"network":"tcp","security":"reality","realitySettings":{"serverName":"one.one.one.one","publicKey":"fixture-key","shortId":"aabb"}}},
|
||||
{"tag":"direct","protocol":"freedom"},{"tag":"block","protocol":"blackhole"}],"routing":{"rules":[]}}}
|
||||
""")!;
|
||||
foreach (var stage in new[] { "route", "ping", "tailnet_start", "public_start" })
|
||||
{
|
||||
var preference = new TailnetPreference();
|
||||
var starts = 0; var stops = 0; var probes = 0;
|
||||
Task Start(string _, CancellationToken token) { starts++; if (stage is "tailnet_start" or "public_start") throw error; return Task.CompletedTask; }
|
||||
Task Stop() { stops++; return Task.CompletedTask; }
|
||||
Task<bool> Health(CancellationToken _) { probes++; return Task.FromResult(true); }
|
||||
void Route(string _) { if (stage == "route") throw error; }
|
||||
Task<bool> Ping(string _, int port, CancellationToken token) { if (stage == "ping") throw error; return Task.FromResult(true); }
|
||||
var selectedResponse = stage == "public_start" ? new ConfigResponse {
|
||||
Config=response.Config, ConfigContract=response.ConfigContract, ConnectionScope=response.ConnectionScope,
|
||||
Node=response.Node, RouteMode=response.RouteMode, TailscaleEndpoint=null,
|
||||
} : response;
|
||||
var rejected = await RuntimeFailure(() => NodeTransportConnector.ConnectAsync(selectedResponse, preference, Start, Stop,
|
||||
Health, Route, _ => { }, () => 100, CancellationToken.None, endpointProbe: Ping));
|
||||
checks[stage + "_local_failure_propagates"] = rejected;
|
||||
checks[stage + "_no_domain_or_cooldown_state_change"] = !preference.DomainOnly && preference.MayTry("tokyo", 101);
|
||||
checks[stage + "_no_cleanup_or_health_attempt"] = stops == 0 && probes == 0;
|
||||
checks[stage + "_no_second_start"] = starts == (stage is "tailnet_start" or "public_start" ? 1 : 0);
|
||||
}
|
||||
var tailnet = TailnetTransport.TryPrepare(response)!;
|
||||
var rebindStarts = 0; var rebindStops = 0;
|
||||
checks["rebind_local_failure_propagates_without_fallback"] = await RuntimeFailure(() => NodeTransportConnector.RebindAsync(
|
||||
tailnet, response.GetRuntimeConfigJson(), (_, _) => { rebindStarts++; throw error; },
|
||||
() => { rebindStops++; return Task.CompletedTask; }, _ => Task.FromResult(true), CancellationToken.None))
|
||||
&& rebindStarts == 1 && rebindStops == 0;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Only these four known inert files in the fresh GUID directory.
|
||||
foreach (var name in ClientRuntime.Components) File.Delete(Path.Combine(root, "xray", name));
|
||||
Directory.Delete(Path.Combine(root, "xray"));
|
||||
Directory.Delete(root);
|
||||
}
|
||||
return checks;
|
||||
}
|
||||
|
||||
internal static async Task<int> RunAsync()
|
||||
{
|
||||
var checks = await CheckAsync();
|
||||
var passed = checks.Values.All(value => value);
|
||||
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "client-runtime-self-test.json"),
|
||||
JsonSerializer.Serialize(new { passed, network_modified = false, installed_client_modified = false, installer_launched = false, checks },
|
||||
new JsonSerializerOptions { WriteIndented=true }));
|
||||
return passed ? 0 : 92;
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,9 @@ namespace UCVL.VPNPlus;
|
||||
internal static class ClientUpdater
|
||||
{
|
||||
private const long MaximumInstallerBytes = 200L * 1024 * 1024;
|
||||
// A 200 MiB package takes 1024 seconds on a slow 200 KiB/s link.
|
||||
// Keep a bounded transfer budget with headroom; idle reads still stop at 30s.
|
||||
internal static readonly TimeSpan DefaultTotalTimeout = TimeSpan.FromMinutes(20);
|
||||
|
||||
internal static bool IsNewerVersion(string candidate, string? current = null)
|
||||
{
|
||||
@@ -88,7 +91,7 @@ internal static class ClientUpdater
|
||||
// Bound the entire transfer and each body read independently; a stalled
|
||||
// download must not leave the update UI disabled indefinitely.
|
||||
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
deadline.CancelAfter(totalTimeout ?? TimeSpan.FromMinutes(10));
|
||||
deadline.CancelAfter(totalTimeout ?? DefaultTotalTimeout);
|
||||
var idleLimit = idleTimeout ?? TimeSpan.FromSeconds(30);
|
||||
try
|
||||
{
|
||||
|
||||
@@ -2,8 +2,8 @@ using System.Text.Json.Nodes;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
// Compatibility addresses explicitly supplied by the operator and authenticated
|
||||
// against these two existing nodes on 2026-09-26. Not new nodes or login grants.
|
||||
// Operator-supplied compatibility addresses for already-authorized nodes.
|
||||
// These are same-node transports, not new nodes or login grants.
|
||||
// The authenticated API config remains the authority for credentials and identity.
|
||||
internal static class KnownTailnetEndpoints
|
||||
{
|
||||
@@ -30,6 +30,7 @@ internal static class KnownTailnetEndpoints
|
||||
{
|
||||
"aliyun-tokyo-002" => (Host: "vpn002.example.invalid", PublicPort: 11082, Address: "100.64.0.2", Port: 10803),
|
||||
"aliyun-siliconvalley-003" => (Host: "vpn003.example.invalid", PublicPort: 11083, Address: "100.64.0.3", Port: 11083),
|
||||
"racknerd-newyork-004" => (Host: "004.vpn.example.invalid", PublicPort: 11084, Address: "100.64.0.44", Port: 11084),
|
||||
_ => default
|
||||
};
|
||||
reason = "known_node_unmapped";
|
||||
|
||||
@@ -38,14 +38,15 @@ internal sealed partial class MainForm
|
||||
|
||||
private async Task CheckUplinkAsync()
|
||||
{
|
||||
if (_preview || _uiOnly || _exiting || !_wantConnected || _busy || _uplinkChecking || _xray.IsTransitioning || !_xray.CanRebindNetwork) return;
|
||||
if (_runtimeRepairRequired || _preview || _uiOnly || _exiting || !_wantConnected || _busy || _uplinkChecking || _xray.IsTransitioning || !_xray.CanRebindNetwork) return;
|
||||
if (!PreflightClientRuntime(suppressDialogs: true)) return;
|
||||
_uplinkChecking = true;
|
||||
var refreshAuthorization = false;
|
||||
var operating = false;
|
||||
try
|
||||
{
|
||||
var reading = await Task.Run(() => PhysicalUplink.Read(_xray.BoundNetwork?.InterfaceIndex));
|
||||
if (_exiting || !_wantConnected || _busy || _xray.IsTransitioning) return;
|
||||
if (_runtimeRepairRequired || _exiting || !_wantConnected || _busy || _xray.IsTransitioning) return;
|
||||
if (!reading.Success) return;
|
||||
if (!_handover.Pending && PhysicalUplink.Fingerprint(reading.Network) == _xray.BoundNetworkFingerprint && reading.Network is not null)
|
||||
{
|
||||
@@ -61,7 +62,7 @@ internal sealed partial class MainForm
|
||||
_connectButton.Enabled = true;
|
||||
_connectButton.Text = "断开";
|
||||
var result = await _handover.ObserveAsync(reading, Environment.TickCount64, _handoverCancellation.Token);
|
||||
if (!_wantConnected || _exiting) return;
|
||||
if (_runtimeRepairRequired || !_wantConnected || _exiting) return;
|
||||
if (result == NetworkHandover.Result.Recovered)
|
||||
{
|
||||
if (_currentNodeUsesTailnet && !_xray.UsesTailnet)
|
||||
@@ -89,10 +90,11 @@ internal sealed partial class MainForm
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) { }
|
||||
catch (ClientRuntimeException error) { HandleClientRuntimeFailure(error, suppressDialogs: true); }
|
||||
catch (Exception error)
|
||||
{
|
||||
AppPaths.WriteError(error);
|
||||
if (_wantConnected && !_exiting)
|
||||
if (!_runtimeRepairRequired && _wantConnected && !_exiting)
|
||||
{
|
||||
SetConnectionState(false, "等待网络恢复", "本地网络尚未就绪,将自动重试;可点击断开取消。");
|
||||
DisplayTraffic(null, null, "等待网络恢复");
|
||||
|
||||
@@ -11,6 +11,12 @@ internal sealed partial class MainForm
|
||||
{
|
||||
_connectionAttemptCancellation?.Cancel();
|
||||
_accessToken = token;
|
||||
if (token is null)
|
||||
{
|
||||
_runtimeRepairRequired = false;
|
||||
_statusDetail.AccessibleDescription = null;
|
||||
_runtimeRepairTip.SetToolTip(_statusDetail, null);
|
||||
}
|
||||
_connectionAuthorization.Reset(expiresAt, DateTimeOffset.UtcNow, Environment.TickCount64);
|
||||
_connectionHealth.Invalidate();
|
||||
_sessionRevision++;
|
||||
@@ -46,7 +52,8 @@ internal sealed partial class MainForm
|
||||
// retries the same node's domain through the normal fresh-grant connector.
|
||||
private async Task CheckTailnetReadinessAsync()
|
||||
{
|
||||
if (_uiOnly || _preview) return;
|
||||
if (_runtimeRepairRequired || !_wantConnected || _uiOnly || _preview) return;
|
||||
if (!PreflightClientRuntime(suppressDialogs: true)) return;
|
||||
if (!_tailnetReadiness.TryBegin(ReadTailnetReadinessContext(), Environment.TickCount64, out var ticket))
|
||||
{
|
||||
_tailnetReconnectItem.Enabled = _tailnetReadiness.IsReady && !_busy && !_exiting;
|
||||
@@ -63,6 +70,7 @@ internal sealed partial class MainForm
|
||||
catch (Exception) { /* Fixed diagnostics below contain no credentials. */ }
|
||||
var result = _tailnetReadiness.Observe(ticket, ReadTailnetReadinessContext(), Environment.TickCount64, reachable);
|
||||
if (_exiting || IsDisposed || Disposing) return;
|
||||
if (_runtimeRepairRequired || !PreflightClientRuntime(suppressDialogs: true)) return;
|
||||
_tailnetReconnectItem.Enabled = _tailnetReadiness.IsReady && !_busy;
|
||||
if (result == TailnetReadinessPolicy.Result.Fallback && _currentNodeSlug is { } slug)
|
||||
{
|
||||
@@ -86,6 +94,7 @@ internal sealed partial class MainForm
|
||||
{
|
||||
if (_uiOnly || _preview || _exiting || _busy || !_wantConnected || !_xray.IsRunning
|
||||
|| _xray.UsesTailnet || !_tailnetReadiness.IsReady) return;
|
||||
if (!PreflightClientRuntime(suppressDialogs: false, clearRepair: true)) return;
|
||||
_tailnetReadiness.Reset();
|
||||
_tailnetReconnectItem.Enabled = false;
|
||||
_tailnetPreference.ResetForUserConnect();
|
||||
|
||||
+60
-3
@@ -78,6 +78,8 @@ internal sealed partial class MainForm : Form
|
||||
private bool _updateCheckRunning;
|
||||
private DateTimeOffset _nextUpdateCheckAt = DateTimeOffset.MinValue;
|
||||
private bool _installerLaunched;
|
||||
private bool _runtimeRepairRequired;
|
||||
private readonly ToolTip _runtimeRepairTip = new() { AutoPopDelay = 20_000 };
|
||||
|
||||
internal bool WindowExitSelfTestPassed { get; private set; }
|
||||
internal bool NetworkRecoveryFailed { get; private set; }
|
||||
@@ -489,6 +491,9 @@ internal sealed partial class MainForm : Form
|
||||
return;
|
||||
}
|
||||
|
||||
if (reconnect && _runtimeRepairRequired) return;
|
||||
if (!PreflightClientRuntime(suppressDialogs, clearRepair: !reconnect)) return;
|
||||
|
||||
ConnectionSelection selection;
|
||||
try
|
||||
{
|
||||
@@ -514,6 +519,7 @@ internal sealed partial class MainForm : Form
|
||||
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;
|
||||
var runtimeFailure = false;
|
||||
try
|
||||
{
|
||||
if (!_connectionAuthorization.AccountIsValid(DateTimeOffset.UtcNow, Environment.TickCount64))
|
||||
@@ -597,6 +603,7 @@ internal sealed partial class MainForm : Form
|
||||
break;
|
||||
}
|
||||
catch (LocalNetworkException) { throw; }
|
||||
catch (ClientRuntimeException) { throw; }
|
||||
catch (TailnetUnavailableException)
|
||||
{
|
||||
// Connector cleans up only a core it actually attempted.
|
||||
@@ -646,6 +653,11 @@ internal sealed partial class MainForm : Form
|
||||
_notifyIcon.Text = "纵横家 · 已连接";
|
||||
_notifyIcon.ShowBalloonTip(1800, "纵横家已连接", $"当前线路:{_currentNodeName}", ToolTipIcon.Info);
|
||||
}
|
||||
catch (ClientRuntimeException exception)
|
||||
{
|
||||
runtimeFailure = true;
|
||||
HandleClientRuntimeFailure(exception, suppressDialogs);
|
||||
}
|
||||
catch (Exception) when (connectionToken.IsCancellationRequested)
|
||||
{
|
||||
if (!_exiting) await DisconnectAsync();
|
||||
@@ -682,12 +694,52 @@ internal sealed partial class MainForm : Form
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (!_xray.IsRunning && reconnect && !connectionToken.IsCancellationRequested && !string.IsNullOrWhiteSpace(_accessToken)) { _wantConnected = true; _nextReconnect = DateTimeOffset.UtcNow.AddMinutes(2); }
|
||||
if (!runtimeFailure && !_xray.IsRunning && reconnect && !connectionToken.IsCancellationRequested && !string.IsNullOrWhiteSpace(_accessToken)) { _wantConnected = true; _nextReconnect = DateTimeOffset.UtcNow.AddMinutes(2); }
|
||||
if (ReferenceEquals(_connectionAttemptCancellation, attemptCancellation)) _connectionAttemptCancellation = null;
|
||||
SetBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleClientRuntimeFailure(ClientRuntimeException exception, bool suppressDialogs)
|
||||
{
|
||||
var firstNotice = !_runtimeRepairRequired;
|
||||
_runtimeRepairRequired = true;
|
||||
AppPaths.WriteLog(exception.Diagnostic);
|
||||
// Component repair requires the installer, not another node or route.
|
||||
// A running core retains its existing configuration and network state.
|
||||
var connected = _xray.IsRunning;
|
||||
_wantConnected = connected;
|
||||
_nextReconnect = DateTimeOffset.MaxValue;
|
||||
_connectionHealth.Invalidate();
|
||||
_connectionHealth.ResetFailures();
|
||||
_tailnetReadiness.Reset();
|
||||
_tailnetReconnectItem.Enabled = false;
|
||||
_handover.Reset();
|
||||
SetConnectionState(connected, connected ? "组件需修复 · 保留原连接" : "客户端组件需要修复",
|
||||
exception.Message.Replace('\n', ' '));
|
||||
_statusDetail.AccessibleDescription = exception.Message;
|
||||
_runtimeRepairTip.SetToolTip(_statusDetail, exception.Message);
|
||||
if (connected) _currentNodeLabel.Text = _currentNodeName ?? _currentNodeSlug ?? "原工作节点";
|
||||
if (!suppressDialogs) MessageBox.Show(exception.Message, "客户端安装需要修复", MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
||||
else if (firstNotice) _notifyIcon.ShowBalloonTip(7000, "客户端安装需要修复", exception.Message, ToolTipIcon.Warning);
|
||||
}
|
||||
|
||||
private bool PreflightClientRuntime(bool suppressDialogs, bool clearRepair = false)
|
||||
{
|
||||
try
|
||||
{
|
||||
_xray.ValidateRuntime();
|
||||
if (clearRepair)
|
||||
{
|
||||
_runtimeRepairRequired = false;
|
||||
_statusDetail.AccessibleDescription = null;
|
||||
_runtimeRepairTip.SetToolTip(_statusDetail, null);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (ClientRuntimeException error) { HandleClientRuntimeFailure(error, suppressDialogs); return false; }
|
||||
}
|
||||
|
||||
private async Task DisconnectAsync(bool cancelPending = true)
|
||||
{
|
||||
_wantConnected = false;
|
||||
@@ -788,6 +840,8 @@ internal sealed partial class MainForm : Form
|
||||
} finally { _healthChecking = false; }
|
||||
return;
|
||||
}
|
||||
// Keep authorization expiry enforcement above this local repair gate.
|
||||
if (_runtimeRepairRequired) return;
|
||||
await CheckUplinkAsync();
|
||||
if (_uplinkChecking || _handover.Pending || _handover.Settling) return;
|
||||
if (!_wantConnected || _busy || _xray.IsTransitioning || _healthChecking || _exiting || DateTimeOffset.UtcNow < _nextReconnect) return;
|
||||
@@ -801,6 +855,7 @@ internal sealed partial class MainForm : Form
|
||||
var revision = _connectionHealth.Revision;
|
||||
var testedCore = _xray.CoreId;
|
||||
var health = await _xray.CheckHealthWithRepairAsync(_lifetime.Token);
|
||||
if (_runtimeRepairRequired) return;
|
||||
var healthy = health.Healthy;
|
||||
var decision = _connectionHealth.Observe(revision, testedCore, _xray.CoreId,
|
||||
_wantConnected, _busy, _xray.IsTransitioning, _exiting, healthy, Environment.TickCount64, health.ProxyHealthy,
|
||||
@@ -836,6 +891,7 @@ internal sealed partial class MainForm : Form
|
||||
}
|
||||
ConnectionAcceptanceTrace.Record("health_failed", _currentNodeSlug, _xray.IsRunning, _xray.CoreId, _connectionHealth.Failures);
|
||||
if (decision != ConnectionHealthPolicy.Decision.Switch) return;
|
||||
if (!PreflightClientRuntime(suppressDialogs: true)) return;
|
||||
if (_currentNodeSlug is not null)
|
||||
{
|
||||
if (_currentNodeUsesTailnet)
|
||||
@@ -935,11 +991,11 @@ internal sealed partial class MainForm : Form
|
||||
|
||||
private void ShowAiStatus(string message)
|
||||
{
|
||||
if (_exiting || IsDisposed || Disposing) return;
|
||||
if (_runtimeRepairRequired || _exiting || IsDisposed || Disposing) return;
|
||||
var reportingCore = _xray.CoreId;
|
||||
PostUi(() =>
|
||||
{
|
||||
if (_dashboardView.Visible && _wantConnected && _xray.CoreId == reportingCore)
|
||||
if (!_runtimeRepairRequired && _dashboardView.Visible && _wantConnected && _xray.CoreId == reportingCore)
|
||||
_statusDetail.Text = NodePresentation.LearningDetail(_selectionUiConnected, _currentNodeName, message);
|
||||
});
|
||||
}
|
||||
@@ -1257,6 +1313,7 @@ internal sealed partial class MainForm : Form
|
||||
_api.Dispose();
|
||||
_notifyIcon.Visible = false;
|
||||
_notifyIcon.Dispose();
|
||||
_runtimeRepairTip.Dispose();
|
||||
}
|
||||
|
||||
protected override void WndProc(ref Message message)
|
||||
|
||||
@@ -54,7 +54,7 @@ internal static class NodeTransportConnector
|
||||
diagnostic?.Invoke(new("rebind_selected", tailnet ? "tailnet_verified" : "public_ingress", ""));
|
||||
return selected;
|
||||
}
|
||||
catch (Exception e) when (tailnet && e is not LocalNetworkException && !token.IsCancellationRequested)
|
||||
catch (Exception e) when (tailnet && e is not LocalNetworkException && e is not ClientRuntimeException && !token.IsCancellationRequested)
|
||||
{
|
||||
await stop(); // Full cleanup before same-node fallback; failure aborts.
|
||||
token.ThrowIfCancellationRequested();
|
||||
@@ -88,7 +88,7 @@ internal static class NodeTransportConnector
|
||||
requireRoute(TailnetTransport.Address(tailnet)!);
|
||||
token.ThrowIfCancellationRequested();
|
||||
}
|
||||
catch (Exception e) when (e is not OperationCanceledException)
|
||||
catch (Exception e) when (e is not OperationCanceledException && e is not ClientRuntimeException)
|
||||
{
|
||||
preference.Failed(response.Node.Slug, ticks());
|
||||
tailnet = null;
|
||||
@@ -106,7 +106,7 @@ internal static class NodeTransportConnector
|
||||
throw new IOException("代理内网 IP Ping 不通。");
|
||||
token.ThrowIfCancellationRequested();
|
||||
}
|
||||
catch (Exception e) when (e is not OperationCanceledException)
|
||||
catch (Exception e) when (e is not OperationCanceledException && e is not ClientRuntimeException)
|
||||
{
|
||||
preference.Failed(response.Node.Slug, ticks());
|
||||
tailnet = null;
|
||||
@@ -132,6 +132,7 @@ internal static class NodeTransportConnector
|
||||
return true;
|
||||
}
|
||||
catch (LocalNetworkException) { throw; }
|
||||
catch (ClientRuntimeException) { throw; }
|
||||
catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; }
|
||||
catch (Exception)
|
||||
{
|
||||
@@ -147,11 +148,13 @@ 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);
|
||||
var commitDomain = response.ConnectionScope != PrivateAuxiliaryRouting.Scope && response.RouteMode is "smart" or "global";
|
||||
try { await start(response.GetRuntimeConfigJson(), token); }
|
||||
catch (ClientRuntimeException) { throw; }
|
||||
catch { if (commitDomain) preference.CommitDomainFallback(); throw; }
|
||||
if (commitDomain) preference.CommitDomainFallback();
|
||||
token.ThrowIfCancellationRequested();
|
||||
Report("selected", "public_ingress");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,8 @@ internal static class Program
|
||||
if (args.Any(a => a.StartsWith("--installer-guardian-", StringComparison.OrdinalIgnoreCase))) return InstallerGuardianGate.Invalid;
|
||||
if (args.Length == 1 && args[0] == "--platform-bootstrap-self-test")
|
||||
return PlatformBootstrapTransportSelfTest.RunAsync().GetAwaiter().GetResult();
|
||||
if (args.Length == 1 && args[0] == "--client-runtime-self-test")
|
||||
return ClientRuntimeSelfTest.RunAsync().GetAwaiter().GetResult();
|
||||
if (args.Length == 1 && args[0] == "--tailnet-transport-self-test")
|
||||
return TailnetTransportSelfTest.RunAsync().GetAwaiter().GetResult();
|
||||
if (args.Length == 1 && args[0] == "--public-tailnet-selection-self-test")
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
# 纵横家 Windows 0.3.5 开源源码
|
||||
# 纵横家 Windows 0.3.6 开源源码
|
||||
|
||||
基于已冻结的 0.3.5 r22 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。
|
||||
基于已冻结的 0.3.6 r22 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。
|
||||
|
||||
## 构建
|
||||
|
||||
@@ -17,4 +17,4 @@ dotnet publish VPNPlus.csproj -c Release -r win-x64 --self-contained true
|
||||
|
||||
公司自有代码适用 LICENSE;公司 Logo/商标保留来源识别用途、不授予品牌权利;第三方许可文本在 licenses/ 中,原 THIRD_PARTY_NOTICES.md 保持原文。
|
||||
|
||||
0.3.5:为本机代理及各服务器显示独立流量趋势,清晰区分上传、下载及累计数值,保持固定紧凑主界面。保留0.3.4连接容错与授权有效期处理;本次只更新界面,不改变调度、节点优先级或网络路由,不宣称网络提速。清洁源码保留原MIT/GPL和第三方许可边界,不含用户提供的可选JPG;同包离线、合成界面与隔离文件事务验证不等于生产网络或覆盖安装验收。
|
||||
0.3.6:连接前检查本机Xray及必要运行文件;组件缺失时一次性明确提示修复安装,避免逐节点重复失败。延长受限速环境下完整升级包下载的总时间预算。保留0.3.5本机和服务器趋势图、连接容错、调度与路由规则,不宣称网络提速。清洁源码保留原MIT/GPL和第三方许可边界,不含用户提供的可选JPG;同包离线、合成界面与隔离文件事务验证不等于生产网络或覆盖安装验收。
|
||||
|
||||
@@ -203,6 +203,52 @@ internal static class TailnetTransportSelfTest
|
||||
r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["port"] = 11083;
|
||||
}), true)!;
|
||||
checks["known_silicon_exact_mapping"] = Host(silicon) == "100.64.0.3" && TailnetTransport.Port(silicon) == 11083;
|
||||
ConfigResponse NewYork(Action<JsonObject>? change = null) => Known(r => {
|
||||
r["node"]!["slug"] = "racknerd-newyork-004"; r["node"]!["name"] = "VPN004";
|
||||
r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"] = "004.vpn.example.invalid";
|
||||
r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["port"] = 11084;
|
||||
change?.Invoke(r);
|
||||
});
|
||||
var newYork = NewYork();
|
||||
var newYorkOriginal = newYork.GetRuntimeConfigJson();
|
||||
var newYorkPrepared = TailnetTransport.TryPrepare(newYork, true);
|
||||
checks["known_newyork_exact_mapping"] = newYorkPrepared is not null
|
||||
&& Host(newYorkPrepared) == "100.64.0.44" && TailnetTransport.Port(newYorkPrepared) == 11084;
|
||||
checks["known_newyork_requires_mapping_permission"] = TailnetTransport.TryPrepare(newYork) is null;
|
||||
checks["known_newyork_same_authorized_fallback"] = newYorkPrepared is not null
|
||||
&& TailnetTransport.SameAuthorizedFallback(newYorkPrepared, newYorkOriginal);
|
||||
var newYorkRestored = newYorkPrepared is null ? null : JsonNode.Parse(newYorkPrepared)!.AsObject();
|
||||
if (newYorkRestored is not null)
|
||||
{
|
||||
newYorkRestored.Remove(TailnetTransport.Marker);
|
||||
newYorkRestored["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"] = "004.vpn.example.invalid";
|
||||
newYorkRestored["outbounds"]![0]!["settings"]!["vnext"]![0]!["port"] = 11084;
|
||||
}
|
||||
checks["known_newyork_preserves_all_credentials_and_rules"] = newYorkRestored is not null
|
||||
&& JsonNode.DeepEquals(newYorkRestored, JsonNode.Parse(newYorkOriginal))
|
||||
&& newYork.GetRuntimeConfigJson() == newYorkOriginal;
|
||||
checks["known_newyork_changed_host_rejected"] = TailnetTransport.TryPrepare(NewYork(r =>
|
||||
r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"] = "other.example.com"), true) is null;
|
||||
checks["known_newyork_changed_port_rejected"] = TailnetTransport.TryPrepare(NewYork(r =>
|
||||
r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["port"] = 11083), true) is null;
|
||||
checks["known_newyork_changed_slug_rejected"] = TailnetTransport.TryPrepare(NewYork(r =>
|
||||
r["node"]!["slug"] = "unapproved-newyork"), true) is null;
|
||||
checks["known_newyork_explicit_null_disables_mapping"] = TailnetTransport.TryPrepare(NewYork(r => r["tailscale_endpoint"] = null), true) is null;
|
||||
checks["known_newyork_invalid_metadata_never_uses_mapping"] = TailnetTransport.TryPrepare(NewYork(r => r["tailscale_endpoint"] = new JsonObject()), true) is null;
|
||||
var newYorkExplicit = TailnetTransport.TryPrepare(NewYork(r => r["tailscale_endpoint"] = new JsonObject {
|
||||
["contract"] = 1, ["node_slug"] = "racknerd-newyork-004", ["address"] = "100.65.1.9", ["port"] = 2345
|
||||
}), true);
|
||||
checks["known_newyork_server_metadata_remains_authoritative"] = newYorkExplicit is not null
|
||||
&& Host(newYorkExplicit) == "100.65.1.9" && TailnetTransport.Port(newYorkExplicit) == 2345;
|
||||
var newYorkStarts = new List<string>(); var newYorkStops = 0; var newYorkProbes = 0;
|
||||
var newYorkSelected = await NodeTransportConnector.ConnectAsync(newYork, new(),
|
||||
(json, _) => { newYorkStarts.Add(json); return Task.CompletedTask; },
|
||||
() => { newYorkStops++; return Task.CompletedTask; },
|
||||
_ => { newYorkProbes++; return Task.FromResult(false); }, _ => { }, _ => { }, () => tick, CancellationToken.None,
|
||||
allowKnownEndpoints: true, endpointProbe: (address, port, _) => Task.FromResult(address == "100.64.0.44" && port == 11084));
|
||||
checks["known_newyork_failed_proxy_falls_back_only_same_authorized_node"] = !newYorkSelected
|
||||
&& newYorkStarts.Count == 2 && Host(newYorkStarts[0]) == "100.64.0.44"
|
||||
&& newYorkStarts[1] == newYorkOriginal && newYorkStops == 1 && newYorkProbes == 1;
|
||||
var future = TailnetTransport.TryPrepare(Known(r => r["tailscale_endpoint"] = new JsonObject {
|
||||
["contract"] = 1, ["node_slug"] = "aliyun-tokyo-002", ["address"] = "100.65.1.9", ["port"] = 2345
|
||||
}), true)!;
|
||||
|
||||
@@ -68,6 +68,9 @@ internal static class UpdateSelfTest
|
||||
};
|
||||
try
|
||||
{
|
||||
report["largest_allowed_package_fits_slow_200kib_link_with_headroom"] = ClientUpdater.DefaultTotalTimeout
|
||||
>= TimeSpan.FromSeconds(200.0 * 1024 * 1024 / (200 * 1024) + 60);
|
||||
report["update_total_deadline_remains_bounded"] = ClientUpdater.DefaultTotalTimeout <= TimeSpan.FromMinutes(20);
|
||||
var bytes = RandomNumberGenerator.GetBytes(300_000); // Test data, not an executable.
|
||||
var hash = Convert.ToHexString(SHA256.HashData(bytes));
|
||||
ClientUpdateInfo Info(string digest, bool available = true) => new() {
|
||||
|
||||
@@ -10,10 +10,10 @@
|
||||
<ApplicationIcon>assets\zonghengjia-app-v1.ico</ApplicationIcon>
|
||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||
<ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode>
|
||||
<Version>0.3.5</Version>
|
||||
<AssemblyVersion>0.3.5.0</AssemblyVersion>
|
||||
<FileVersion>0.3.5.0</FileVersion>
|
||||
<InformationalVersion>0.3.5</InformationalVersion>
|
||||
<Version>0.3.6</Version>
|
||||
<AssemblyVersion>0.3.6.0</AssemblyVersion>
|
||||
<FileVersion>0.3.6.0</FileVersion>
|
||||
<InformationalVersion>0.3.6</InformationalVersion>
|
||||
<Product>纵横家</Product>
|
||||
<Company>优创未来(UCVL)</Company>
|
||||
<Description>纵横家 Windows 智能网络客户端</Description>
|
||||
|
||||
+16
-18
@@ -75,10 +75,14 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
|
||||
public async Task RebindNetworkAsync(CancellationToken token)
|
||||
{
|
||||
ValidateRuntime();
|
||||
await _lifecycle.WaitAsync(token);
|
||||
var replacementStarted = false;
|
||||
try
|
||||
{
|
||||
ValidateRuntime();
|
||||
if (!CanRebindNetwork) throw new InvalidOperationException("没有可恢复的已授权线路。");
|
||||
replacementStarted = true;
|
||||
await StopCoreAsync(); // Restore old routes/DNS BEFORE any DNS/network requests.
|
||||
token.ThrowIfCancellationRequested();
|
||||
_baseConfigJson = await NodeTransportConnector.RebindAsync(_baseConfigJson!, _tailnetFallbackConfigJson,
|
||||
@@ -89,7 +93,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
endpointProbe: TailnetTransport.ProbeEndpointAsync,
|
||||
diagnostic: entry => AppPaths.WriteLog((entry with { Node = _nodeSlug }).SafeMessage));
|
||||
}
|
||||
catch { await StopCoreAsync(); throw; }
|
||||
catch { if (replacementStarted) await StopCoreAsync(); throw; }
|
||||
finally { _lifecycle.Release(); }
|
||||
}
|
||||
|
||||
@@ -202,6 +206,8 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
internal async Task StartAsync(string configJson, string routeMode, string nodeSlug, CancellationToken cancellationToken,
|
||||
string? tailnetFallbackConfigJson = null, string? preferredTailnetConfigJson = null)
|
||||
{
|
||||
// Fail locally before ownership/recovery or stopping a healthy core.
|
||||
ValidateRuntime();
|
||||
if (TailnetTransport.Address(configJson) is not null
|
||||
&& !TailnetTransport.SameAuthorizedFallback(configJson, tailnetFallbackConfigJson))
|
||||
throw new InvalidOperationException("Tailscale 原入口与已授权线路不匹配。");
|
||||
@@ -214,8 +220,12 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
await InitializeAsync(cancellationToken);
|
||||
await StartupLearningWarmup.RunAsync(async beginLearning => {
|
||||
await _lifecycle.WaitAsync(cancellationToken);
|
||||
var replacementStarted = false;
|
||||
try
|
||||
{
|
||||
// Recheck after waiting for the lifecycle; a file may change.
|
||||
ValidateRuntime();
|
||||
replacementStarted = true;
|
||||
await StopCoreAsync();
|
||||
_baseConfigJson = configJson;
|
||||
_tailnetFallbackConfigJson = preferred is not null ? original : tailnetFallbackConfigJson;
|
||||
@@ -226,7 +236,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
}
|
||||
catch
|
||||
{
|
||||
await StopCoreAsync().ConfigureAwait(false);
|
||||
if (replacementStarted) await StopCoreAsync().ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
finally { _lifecycle.Release(); }
|
||||
@@ -276,7 +286,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
private async Task StartCoreAsync(CancellationToken cancellationToken,
|
||||
Action<CancellationToken>? beginStartupLearning = null)
|
||||
{
|
||||
EnsureRuntime();
|
||||
ValidateRuntime();
|
||||
if (string.IsNullOrWhiteSpace(_baseConfigJson)) throw new InvalidOperationException("线路配置为空。");
|
||||
PrivateAuxiliaryRuntime.ValidateLifetime(_baseConfigJson);
|
||||
var privateAuxiliary = PrivateAuxiliaryRuntime.IsPrivate(_baseConfigJson);
|
||||
@@ -354,7 +364,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
_process.ErrorDataReceived += (_, eventArgs) => AppendXrayLog(eventArgs.Data);
|
||||
var startedProcess = _process;
|
||||
_process.Exited += (_, _) => _ = HandleCoreExitAsync(startedProcess);
|
||||
if (!_process.Start()) throw new InvalidOperationException("Xray 内核无法启动。");
|
||||
if (!ClientRuntime.Start(_process)) throw new ClientRuntimeException(XrayPath, ClientRuntimeFault.CannotStart);
|
||||
_process.BeginOutputReadLine();
|
||||
_process.BeginErrorReadLine();
|
||||
File.WriteAllText(AppPaths.PidFile, _process.Id.ToString());
|
||||
@@ -557,7 +567,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
StandardErrorEncoding = Encoding.UTF8,
|
||||
}
|
||||
};
|
||||
process.Start();
|
||||
ClientRuntime.Start(process);
|
||||
var stdout = process.StandardOutput.ReadToEndAsync(cancellationToken);
|
||||
var stderr = process.StandardError.ReadToEndAsync(cancellationToken);
|
||||
await process.WaitForExitAsync(cancellationToken);
|
||||
@@ -593,19 +603,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
return addresses;
|
||||
}
|
||||
|
||||
private void EnsureRuntime()
|
||||
{
|
||||
foreach (var file in new[]
|
||||
{
|
||||
XrayPath,
|
||||
Path.Combine(_xrayDirectory, "geoip.dat"),
|
||||
Path.Combine(_xrayDirectory, "geosite.dat"),
|
||||
Path.Combine(_xrayDirectory, "wintun.dll"),
|
||||
})
|
||||
{
|
||||
if (!File.Exists(file)) throw new FileNotFoundException($"客户端组件缺失:{Path.GetFileName(file)}");
|
||||
}
|
||||
}
|
||||
internal void ValidateRuntime() => ClientRuntime.Validate(AppContext.BaseDirectory);
|
||||
|
||||
private async Task RecoverStaleStateAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# 纵横家 Windows 0.3.6
|
||||
|
||||
本次维护修复本机运行组件故障被重复显示为多个节点连接失败的问题。
|
||||
|
||||
- 建立连接前检查程序目录中的运行组件,区分文件缺失、读取受限和空文件,显示具体位置及完整安装包修复方法。
|
||||
- 本机组件故障直接进入安装修复提示,保留仍在运行的连接,避免重复重试节点和误记 Tailscale 故障。
|
||||
- 自动升级的整包下载期限调整为 20 分钟,保留单次读取超时、取消、完整长度及 SHA-256 校验,适应低速网络。
|
||||
- 补齐 VPN004 的 Tailscale 兼容入口识别,沿用已授权的同节点配置,内网可达时优先使用内网入口。
|
||||
- 保留 0.3.5 的本机与服务器独立流量趋势图和紧凑累计数值。
|
||||
|
||||
完整安装包包含 Xray、Wintun 及路由数据文件。覆盖安装会保留账号、设备标识和用户配置。组件读取受限时应先排查该文件的访问权限,再运行完整安装包修复。
|
||||
|
||||
发布验证范围包括同包离线回归、缺件修复的隔离文件事务、运行组件故障的模拟连接及升级下载边界测试。离线和隔离结果不代表真实 TUN 切换、生产覆盖安装或多节点分流已经验收。
|
||||
Reference in New Issue
Block a user