commit 901f27baf5436a5318ef4e1e87f48782a0da73d1 Author: Zonghengjia Open Source Date: Sun Oct 11 23:23:20 2026 +0000 Publish reviewed history-free open-source snapshot (2026-10-12) diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..381a41b --- /dev/null +++ b/LICENSE @@ -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. diff --git a/PUBLICATION-AUDIT.json b/PUBLICATION-AUDIT.json new file mode 100644 index 0000000..9ac8ad6 --- /dev/null +++ b/PUBLICATION-AUDIT.json @@ -0,0 +1,103 @@ +{ + "ExampleEndpointChanges": [ + { + "Count": 4, + "Path": "windows/KnownTailnetEndpoints.cs" + }, + { + "Count": 3, + "Path": "windows/LearningSelfTest.cs" + }, + { + "Count": 1, + "Path": "windows/LearningTransportSelfTest.cs" + }, + { + "Count": 1, + "Path": "windows/NetworkHandoverSelfTest.cs" + }, + { + "Count": 1, + "Path": "windows/PlatformBootstrapTransport.cs" + }, + { + "Count": 5, + "Path": "windows/PlatformBootstrapTransportSelfTest.cs" + }, + { + "Count": 4, + "Path": "windows/PrivateAuxiliaryRouting.cs" + }, + { + "Count": 25, + "Path": "windows/PrivateAuxiliaryRoutingSelfTest.cs" + }, + { + "Count": 46, + "Path": "windows/TailnetTransportSelfTest.cs" + }, + { + "Count": 4, + "Path": "windows/release/RELEASE-NOTES-0.2.21.md" + }, + { + "Count": 11, + "Path": "backend/control/private_auxiliary.py" + }, + { + "Count": 2, + "Path": "backend/control/tests/test_dispatch.py" + }, + { + "Count": 1, + "Path": "backend/control/tests/test_learning_delivery.py" + }, + { + "Count": 1, + "Path": "backend/control/tests/test_office_permissions.py" + }, + { + "Count": 19, + "Path": "backend/control/tests/test_private_auxiliary.py" + }, + { + "Count": 7, + "Path": "backend/control/tests/test_tailscale_endpoint.py" + }, + { + "Count": 1, + "Path": "backend/toplc_vpn/settings.py" + }, + { + "Count": 1, + "Path": "ios/ACCEPTANCE.md" + }, + { + "Count": 2, + "Path": "ios/Tests/ClientConfigResponseTests.swift" + }, + { + "Count": 3, + "Path": "ios/Tests/NetworkAddressTests.swift" + }, + { + "Count": 2, + "Path": "ios/Tests/TunnelConfigurationBuilderTests.swift" + } + ], + "NoPrivateHistoryIncluded": true, + "Omitted": [ + "windows/assets/login-cloud-scene-v1.jpg", + "windows/release/INSTALLER-GUARDIAN-GATE-20260924.md", + "windows/release/PRODUCTION-NETWORK-BASELINE-20260924.md", + "windows/release/SOURCE-ONLY-0.2.21-20261011-r22.json", + "windows/release/TAILNET-PRIORITY-20260924.md", + "backend/release/SOURCE-ONLY-backend-phone-20261011.json", + "ios/Resources/Geo/geoip.dat", + "ios/Resources/Geo/geosite.dat", + "ios/release/CANDIDATE-20260924.json" + ], + "OriginalPrivateSourcesModified": false, + "ProductionAccepted": false, + "SourceOnly": true +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..d6f2463 --- /dev/null +++ b/README.md @@ -0,0 +1,18 @@ +# 纵横家开源源码 + +此仓库是无私有 Git 历史的清洁源码快照:Windows 0.2.21、Django 后台及 iPhone/iPad 1.0.2。公司自有代码按 MIT 开源;第三方组件遵守原许可,公司商标及 Logo 不在 MIT 授权范围。Android 保留原 GPL-3.0 公开仓库,不重复拷贝或改换许可。 + +| 目录 | 内容与状态 | +| --- | --- | +| windows/ | Windows Forms / .NET 8 源码;公开导出删除许可来源不明的可选登录插图,保留原创山水 fallback | +| backend/ | Django 后台源码与迁移;不含生产数据库、运行配置或凭据 | +| ios/ | iPhone/iPad Swift / Packet Tunnel 源码;未提供 IPA,未声称 Xcode/签名/实机验收通过 | +| android/ | 原 GPL-3.0 公开源码及固定候选提交链接 | + +这是源码开源,不是全平台正式软件发布或自动升级验收。没有修改生产部署、现用客户端、公司账号授权或稳定升级源。源码中的公司公开 API/下载域名保留兼容用途,但不会授予公司服务权限。 + +真实内部节点地址已在公开导出中一致替换为 CGNAT/RFC1918/RFC5737 示例及 example.invalid 域名;它们不是可连接的生产配置。自行部署必须配置自己的后台域名、节点、证书、数据库、密钥及访问策略,不应直接使用示例端点。 + +Windows 构建说明见 windows/README.md,后台说明见 backend/README.md,Apple 源码限制及资源恢复见 ios/README.md。依赖、许可例外见 THIRD_PARTY_NOTICES.md;漏洞报告与凭据处理见 SECURITY.md。SOURCE-PROVENANCE.json 记录来源与导出变更,PUBLICATION-AUDIT.json 仅记录脱敏路径与计数。 + +macOS 已交接由独立维护者负责,不包含在此次导出,也未在此重新开发、测试或发布。 diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..b5bf00a --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,7 @@ +# 安全与漏洞报告 + +源码公开不代表公司生产环境已授权访问。请勿在公开 issue/提交中放入密码、访问令牌、私钥、真实用户数据、订阅链接、生产数据库或可直接使用的代理配置。若发现敏感信息,请通过公司既有私密管理员渠道报告;不要公开利用细节或对公司节点进行未授权扫描。 + +自行部署应更换示例端点、设置独立高强度凭据、限制管理入口、保留日志与恢复保护,并先在隔离环境验证迁移及网络行为。收到漏洞报告后先评估影响并轮换泄露凭据,不能只删除源码文本了事。 + +本仓库提供源码,不承诺所有平台已签名、实机验收或稳定自动升级。第三方组件安全更新及各平台权限策略需由部署者维护。 diff --git a/SOURCE-PROVENANCE.json b/SOURCE-PROVENANCE.json new file mode 100644 index 0000000..ceb971a --- /dev/null +++ b/SOURCE-PROVENANCE.json @@ -0,0 +1,328 @@ +{ + "AndroidLinkedCommit": "c0737d5665d650f761ff7c461180027824bd99fd", + "BackendSourceCommit": "86a1bc4804bca33eda41cbe141d9585026c22315", + "ExportDiffersFromOriginalCandidates": true, + "FilesBeforeProvenanceAndAudit": { + "LICENSE": "b7e94910b8dc377b0a05ccde3c6e5941838dfc15c9dd790078d11728205b524e", + "README.md": "5bd226c3cf2855eabf3fae2758944b94fa14ceb16f8ad3a2449e4f97a7a794ae", + "SECURITY.md": "34e56cd9b8f6aa5fee45921c6eb831a542e05e76e41850fc31c44e09de088b3c", + "THIRD_PARTY_NOTICES.md": "8c862f2f6b71440616a887e6deb7444a1262cf7d9f144208cc04041c3f9a3371", + "android/README.md": "bb4387da9a055e97f33bb29a883c543e0938fa858df3fd744abc80553a5ec65c", + "backend/.dockerignore": "484cd709c637890498e035d1f5ed377951b0f7a2d5a51df6c9406805d152fd71", + "backend/Dockerfile": "ce061401380d284fa09dcabe3a006a34cdcc0cb28a47fe5606ccd07c68a8ccaf", + "backend/LICENSE": "b7e94910b8dc377b0a05ccde3c6e5941838dfc15c9dd790078d11728205b524e", + "backend/NOTICE.md": "8c862f2f6b71440616a887e6deb7444a1262cf7d9f144208cc04041c3f9a3371", + "backend/README.md": "06fadf28b6e193070f3c19ff54b07cf4cfa15a685e59cccb877c22c03be1e297", + "backend/accounts/__init__.py": "01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b", + "backend/accounts/admin.py": "a2508ff48d971fe1ff1fe50d1ce82193dcd5bc341db6e48744d87026ef0978f5", + "backend/accounts/apps.py": "e9da98e5d4e3f51f8e89fee094ba1c309f2e066377043c82f2af0f9597516c98", + "backend/accounts/forms.py": "25c49c0ab27652221607bea4911d0f36ae50a107375aaf8435a462456d3f9df5", + "backend/accounts/middleware.py": "ee38a9a67c210d8f0bd4c860a09ffb54f9ab8b1fd1bb8e699f68b53afa0f0a13", + "backend/accounts/migrations/0001_initial.py": "cf0de002fc88b9ada00390546d8f4109878d30c5cf6e69ea4c2227ed478bcba0", + "backend/accounts/migrations/0002_wecombindingevent_wecomloginstate_wecombinding.py": "62829a810b78e4ee672019d978cec6767029abfb26bca23f094d9edd69e8f648", + "backend/accounts/migrations/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "backend/accounts/models.py": "2b81f33da8d9665fcfef215586af6001c09b9cf86fd7365b5477cf8d6a22e5e7", + "backend/accounts/tests.py": "4ee91b443ec3f5684bff32db2f55a4102a8f36a82e68f7256224974c18a40c59", + "backend/accounts/wecom.py": "79a31bbe84eb675260bd5686c08d2b1ca7f205b7621268d0e7ae24fc10e5054a", + "backend/accounts/wecom_views.py": "9fd7f37a6afb1c2c3c419b128ff19fce72b8facac505b3f536d562872055711d", + "backend/control/__init__.py": "01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b", + "backend/control/admin.py": "e85cbcb4bde4d64c1483594e9e2d113d6b360668c5af7d9edef7662c239efbc2", + "backend/control/approval_audit.py": "7d9ab80877703aa59595b519ddc410d12a9360535d4f2889a0ad127f28f06afe", + "backend/control/apps.py": "4fb886af0a842a9b4810d0c4474719c821ed076b0b200c7eb8cf34dea08a9cae", + "backend/control/context_processors.py": "a2dec8d17ca48d4d9fdf163acd0a46865064244f78a34357ccfa4d9370f1348f", + "backend/control/dispatch.py": "afa59b621ca59a2cbdcd81baa72696a4f299a5931c44ef24cb1eb2eada4459fd", + "backend/control/forms.py": "0a589c91986dbee4fd9f69cfed13c466d1916b1f25613af3f44cd3741120c954", + "backend/control/git_releases.py": "6f76512dc2a7a2aedd7a9939dc389947b4270a5b03543a31027c2f234224f1a1", + "backend/control/learning.py": "a5c0230fc9f1c778cc13942a7effdef24e351f110dd17ad5061cf9aa29d1e610", + "backend/control/lifecycle.py": "5b17f72c98fdd2b6692f3f043ad5f47fcc42414b3faa333c939d24856c6809cf", + "backend/control/management/__init__.py": "01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b", + "backend/control/management/commands/__init__.py": "01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b", + "backend/control/management/commands/audit_plan_approvals.py": "b067894b06ba030e2a16ced7a3738df666e4deca05c36ab291a46ab14cc601ba", + "backend/control/management/commands/bootstrap_vpn.py": "55c94c6e3404d049527eed4994d962f38cd0e76d29fab1ef417d2024b27d25f8", + "backend/control/management/commands/configure_node.py": "af5722fea0e15bc2d93a8aeeebaee6f08b430ab66b5a3402eb15cb23ce9328e8", + "backend/control/management/commands/enforce_vpn.py": "89266d183db7d578ec1a7ca64a8afbc03af68e9f4e051f30ef2696687244109a", + "backend/control/management/commands/prepare_monthly_1024g.py": "671fcb414a7dfaee026714a50755a6027dfc187601cfd944aed9acc9a28162fc", + "backend/control/management/commands/prepare_plan_catalog.py": "9fdb7eb2c245a30252d9f567f05267cbcea95830b2ba59fb8afceb74d7f389de", + "backend/control/management/commands/vpn_ai_worker.py": "1ed1d8f3004df481b77b843005917613431c94e5b9fe41093d843b8c0a92c28d", + "backend/control/migrations/0001_initial.py": "ad77ea4031174529060be27d29201ee9e1372792257dc1f25e72efab1223b705", + "backend/control/migrations/0002_node_agent_token_digest_nodedeployment_nodereport.py": "637a612dbb22fbab280204ecb1c4b53be6de4d434c123e1f48359ee76cbb9fe1", + "backend/control/migrations/0003_clientsession.py": "b028510c2ed2e69b8601d0959b604e1d224f364e94c322710850c274bf12fb90", + "backend/control/migrations/0004_vpn_ai.py": "4305517b3d37eb4091b07677ec6bc8db3d40df41639fdab94c446dfd3c7f521b", + "backend/control/migrations/0005_route_rule_sources_and_presets.py": "47708d263fa89434d068cdf3cf6e4f4c77bfe2432e3edc261d421bd493c56533", + "backend/control/migrations/0006_node_traffic_sample.py": "b0f90ff6c71096ec36d7a088760ad0d8a2222c4b9edecd497e447d87ad1b1392", + "backend/control/migrations/0007_ai_dispatch.py": "faadc91c091d28bf68b6a0793f601e18e118cb67fea273e6d6a37859ffd90591", + "backend/control/migrations/0008_planapplication_subscription.py": "35fd77f022257474b8771b020a73554cff6377221a1bda857c59400196aaf82b", + "backend/control/migrations/0009_hourlyusagerecord.py": "f87a6c9d1f3021e9c9bdb38f5177836da441f9f399b66b5ab74d0d8af4fbedb0", + "backend/control/migrations/0010_plan_billing_months_plan_online_payment_required.py": "6c5818ea06f858208cccbc81de0e7a40fb620899fe4d18b845676cfc19e076df", + "backend/control/migrations/0011_plancatalogdraft.py": "bbb34171c8dd9c845f70af1f45b1c3685ca7bc0376c2b518a060cc40d1eaa465", + "backend/control/migrations/0012_team_management.py": "0a53e732535215fb763464545265b04d2b7ba500b5c75ea4a2aea541f5cbee80", + "backend/control/migrations/0013_node_office_permissions.py": "2ddf3247d20050fb1c4062de7868afd39371ce73ab59e1d3e75d3b8734891253", + "backend/control/migrations/0014_node_office_access_scope.py": "ff32587c0d6d4de93d50f5ad1931d77d8772aa3d258d94a145ee83ede67355d7", + "backend/control/migrations/0015_learning_delivery.py": "f15354bf3bf48bfe417a60e16ce7ebfba914059a1e35e8b57137a122137c27b6", + "backend/control/migrations/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "backend/control/models.py": "e1b03895c89c07258d36e488d2c0d80ed69b6a1460db5f1f6651513c39759e4b", + "backend/control/plan_catalog.py": "63f35df3d4155fc15e86c2e3d176a12364463c7201c2d42abdaed28ca6eb5765", + "backend/control/private_auxiliary.py": "7a6a299306fda82ec63f8f5aa71a04911be4c80da3bbe01dda9a0bdcfa9254d6", + "backend/control/services.py": "b45e8d76b907d0045a46b0517be894dfda6a8cdfb9458545dddb3fde03eed75e", + "backend/control/signals.py": "105d030ba710941145b185b393cb353a45a0976aac11a8396dac0af12035b60b", + "backend/control/tailscale_endpoint.py": "80ff1863af750b3eaec711f9da22ad362750eedc10617f4f66d44b769806d3c5", + "backend/control/team_models.py": "0d9b0aa1ceda65a2a98e798f70b2442048e8bcf7df46829764ada7448a390785", + "backend/control/team_services.py": "d3830aeb58f902fa9317b1dec5870e01fffed6eb05c3a62cf11bd563447a8942", + "backend/control/team_views.py": "1eaa72d6e7823ed0f9413ddc41e78605a0e932b6eba9fc3e1df0bb0f9844e83e", + "backend/control/templatetags/__init__.py": "01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b", + "backend/control/templatetags/vpn_admin_dashboard.py": "4ea06f93d7dd2f6aa8deb161e7e0482606dcde0b1e4cc54d965ff66eea0eba3a", + "backend/control/templatetags/vpn_tags.py": "343064fb1fbc7433cde18ab8887b34561f7d965e80660a97ac070e4fd0a448a7", + "backend/control/tests/__init__.py": "01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b", + "backend/control/tests/test_account_approval_safety.py": "9c69039d7929c134a5e3c52ed80636ef01d67f88e48ffa80becfc70afe9f3927", + "backend/control/tests/test_approval_audit.py": "ac54c5d40a08eff33e5d91dece03561074cc1e485bbec847d99e444ceef5e081", + "backend/control/tests/test_approval_concurrency.py": "b829e32aead894c1ffd0a03bd11fd93d1d6ce77da2fe585604623eb5ee32f27d", + "backend/control/tests/test_candidate_upgrade_compatibility.py": "3728217cb3baff187e7d6d923fcdfa0fdf6c88cb154c9c74d4b5114aa38ddb3c", + "backend/control/tests/test_dispatch.py": "4c9baf71f2c9f7837d7934d4b89e0448b2d5160c3a5bdc4de1148d732f177c33", + "backend/control/tests/test_employee_billing.py": "18ae4d25a62266577e932a7292fa9fc4e4f46a843a46808c698e866f7b70fea5", + "backend/control/tests/test_git_releases.py": "8482b3d98a74e3a548e753ee277d4e1b7dbc236c0d655049b8077daee62591f3", + "backend/control/tests/test_learning_delivery.py": "370e99db70b1df42a467b020186ffb416415a6a38860a65f293b790ceb0d6ab2", + "backend/control/tests/test_office_permissions.py": "8c0b41e966182f225d87083dc8933a353a05c7da2511a70b92e20348692fefba", + "backend/control/tests/test_office_scope_migration.py": "04ea941050794d64bfb93823513c6882b1e7ffb1de9d0a1d553f8585a47f76c4", + "backend/control/tests/test_plan_catalog.py": "c354d6b89c305c4bb6125a5f01c5e9bef5406fb535df1fe308ab3f1fc6e6acb9", + "backend/control/tests/test_platform.py": "7190aab4753a1e2956d7cf80ae9a1997cf1ceaa0d486364793dea9db8498ed7b", + "backend/control/tests/test_portal_brand.py": "18662f21264aa61f730eed0f5628db514fb6c0d910a7c1554831f31396a65870", + "backend/control/tests/test_private_auxiliary.py": "74c1faf23443964e62a6126657c101852165f4b883f8e9d3099c722cb50df63b", + "backend/control/tests/test_tailscale_endpoint.py": "2be7f6c0e6d48a2ce8e7321bc94361d369ef52342f6cbd6c73d855b86f880fe8", + "backend/control/tests/test_team_concurrency.py": "27eb1c8779a3ca65f0e2fda7a150d948c5a0a29dcd6f8c6b76300795699b24ad", + "backend/control/tests/test_teams.py": "6e3c9794d27938e2111df39d5112b6542bb46b852e968b8b415186f98f90bf24", + "backend/control/tests/test_usage_concurrency.py": "4b3f16f3ee9191ae8c982867a8a588839e855e1a6607aef2bfeabff15e1a14ab", + "backend/control/tests/test_usage_history.py": "f267ad3b9b73d6312e64bc6af6d6fa319e63539655a974eca0ada802c7b3b4f9", + "backend/control/tests/test_usage_lock_order.py": "29719e2f0da2c7d7c8fa188f86081a9a54969516e93518a3a61ae8b71ddcfcbc", + "backend/control/urls.py": "1dfb5d62fccaa82760211369a99c69d385a9be9354d638b0a6ce99cd8706ee61", + "backend/control/usage_accounting.py": "ae4e8af5dd18ab8e43c11fa5fc019277867aa1a4e1a16c539f23fd45301534bc", + "backend/control/usage_history.py": "d102efe6aad5bc9e7f77187d55a7ebe2ec111ed5053fc9ae6c15eb0b2f093f22", + "backend/control/views.py": "28f1cd84e29bfe7d311a7af52c4a87f23cffdee6a735e5b4ca7e185293c24a59", + "backend/control/vpn_ai.py": "091c1379a8780c4804a40fbc6d6e0d076b9009c5fe3eba752926c7e164f5b19b", + "backend/docker/entrypoint.sh": "1ccee7b022efc9f7ef99f0703a46e235a4a8ee085f113eaea74c63b3063ac33b", + "backend/manage.py": "21f021f4b8c848bb2df0b30af032945e47da34ebe0fb6beed4149356189d1a9d", + "backend/requirements.txt": "fb0d4a17abb80eb2abf467346b3245d3b8fd83a2c6bebc9a08784cdc0fa19667", + "backend/static/brand/README.md": "95d2193ccd5ce6e325eed8cc3e9763c9bf85ae545785504ab400ada705e7194e", + "backend/static/brand/ucvl.png": "04cf7f754a5353b96cddbed4a57a557154342c190a1785487e3bfb36cab04163", + "backend/static/brand/zonghengjia.png": "4f7a25046cd640e255423dca11baecc6466dcaf7f1e16315c4bdbb5cfd6f3ec6", + "backend/static/css/app.css": "a577c17a8153b4e273415b103fd177b0fe2c4947554eb34f402e246b10a8b5d2", + "backend/static/css/node_traffic.css": "b71307e7d35401c2ec9fd18ac33db5892bffc166ae4919b77e7c3729b6c3dbf7", + "backend/static/css/portal-brand.css": "c03b09fea1d8135a11dc9a8ef3f1d2dc92807be681bd170b0dda51380f3c9e85", + "backend/static/css/vpn_admin_dashboard.css": "ca71715dddb6e23c1310764a654549740de634b43a8a2e0986bda613273cf5dc", + "backend/static/js/node_traffic.js": "36d1f8ce8a452dbeaaa0ba93de13fcc63447b173938d92bc5e8fb501ad5030a3", + "backend/static/js/portal.js": "7a93a55413af74751d742707cf9c3a2e2b5b80e63df9efb138a2653760d62959", + "backend/static/js/vpn_admin_dashboard.js": "916157367e64a869c3b6a6037a41e64bc54fda33e6424e25cb92c6f4429f3413", + "backend/templates/admin/control/vpnairuntime/change_list.html": "a45a7843ab519ad98e55554955d83fdbfc5c26ec63f860a2a8617c0268a2e56e", + "backend/templates/admin/login.html": "6b37d35e222ee6917b6002a6d9d2a43664031d47fb91f972833f614b917ce19b", + "backend/templates/admin/node_traffic.html": "7b4d4d25c3d28494a47f3e3b97320b6c42bdc4dab11b38c83ee5a9fed1a53098", + "backend/templates/admin/vpn_dashboard.html": "cde4c93651e1b7e4254d8f0dcb33a36f38cb19be60f20c7350be2f95f757690e", + "backend/templates/admin/wecom_integrations.html": "b35e5319d06bdc31427ececaea288236fdef9bb235d8cf20ac2327008e02d382", + "backend/templates/base.html": "0b0f53b0c76d86164f1de4c6f0a32c13d1cec69fff9555ac7dcbb404ed2d94c6", + "backend/templates/includes/icon.html": "f0eda0267c12e544f828a915a15a8bd4677babe024fca29a78194b1830baae6a", + "backend/templates/includes/lifecycle.html": "ad87ec90c07e0ef22481e570d58e22b21c7f80eff34604dac90ec941cce0e459", + "backend/templates/portal/application_form.html": "5899eb37903943933019d4abc45dbd8cdcf094ba03ba5b1896b723d549142b48", + "backend/templates/portal/dashboard.html": "528e612118d33bcf45378f689a36651e41186d5d0d59362ccb34bc18029731c7", + "backend/templates/portal/team_detail.html": "5f35255537cb18cbf015f17042fb2255f8bbd460a3dfcb9b0d636e7506fa2d44", + "backend/templates/portal/teams.html": "95ef3a8ee7116ac516e287e90797e46513f8e70b755b0d7606151b464fe43a36", + "backend/templates/registration/login.html": "139884e9a56ced9e4ff5766e3e10001ce96dba1d957aa02f470df09af894d1db", + "backend/templates/registration/password_change_done.html": "17c27eb83b5a1a90ee0e7d3c57d6a4c9524417605584be566044d07ff4220a39", + "backend/templates/registration/password_change_form.html": "ff9367925f2a95af673497e499fcf2a5b73349ddce0d6562fc69bf0fb2b72edc", + "backend/templates/registration/register.html": "f15b7eeb77f0250740cbf4c482dd127c0506653e67fe2d762275f0ac57789d5a", + "backend/templates/registration/wecom_account.html": "3524a6ec0a28c819bdd887bf2c3c1587fa944df9a5b474a4ee20c577164e95e8", + "backend/toplc_vpn/__init__.py": "01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b", + "backend/toplc_vpn/asgi.py": "9720eff35ff1ddaa032cf06bad43df84e03fb806286887c33ee34eb4470f7aaf", + "backend/toplc_vpn/postgres_test_settings.py": "35eab74ed772882f7c03aeef38f053ae4387095fae0c766f88ced50996da29d1", + "backend/toplc_vpn/settings.py": "5b3e7f8cb5437621e5703d3476740c076804f563fa19a68117e2e3208183a85a", + "backend/toplc_vpn/test_settings.py": "dfd46c7df96e70bbb2444ba147254fc64130acfb81f26009895c43ab7374f08d", + "backend/toplc_vpn/urls.py": "4ba28cec14507e38b26504bf3c38b43909449ee3fd5e6528e0305ce66bbeab7a", + "backend/toplc_vpn/wsgi.py": "2d164718f4f482fce4622724f32753e9daec9c006637dee93424661e5e8c4d50", + "ios/.gitattributes": "ee74e21ce90cb57c41458eb7778a7b6bc305255d7bc301b74ff89cd3f49b3643", + "ios/.gitea/workflows/apple-build.yml": "f53667768d9c7c65b8e592c4b869a9feae0931aab289074a7712fe5dde9a1574", + "ios/.gitea/workflows/source-audit.yml": "d3f2682ba32c9aeaefafb4d312d466351fddd72085d700cc37580c4b861f3abf", + "ios/.gitignore": "eabbc12fa0f2b083d8966a1676e3fcaae3c41d2734e02f945955aca6c01ffe76", + "ios/ACCEPTANCE.md": "ce01f8225a1a0403b58c35a0dd2062e2b37732e43c612fdcc2a8ad4a7ea314d1", + "ios/App/AppState.swift": "a9fb53291af82a9971db96862f3be7c81bc6126b826b813e9c3640ff0d1f1eeb", + "ios/App/ContentView.swift": "7edec2c55bb5eacbdeedb288d61ecf7aadd708a66fc2a2eb8f70cdbd7c7c6d86", + "ios/App/Info.plist": "55a9c3dbd2e3925788619684eace456de8fcbdd4e0afb681237cdcff36d6bda9", + "ios/App/PlatformAPI.swift": "fb536785a5db6747860883f8f64761ca3ed04f5067c459f1dd9d6a3b7f5e0829", + "ios/App/SecureStore.swift": "6a101d663d07f17d8d7808c5c8973c075533edfa44cc7402c59c575436479b0d", + "ios/App/UCVLZonghengjia.entitlements": "6cf7eb189cd5bf0a4e9f4c448ce399714e9aaa98511a08ac1529769984d75caa", + "ios/App/UCVLZonghengjiaApp.swift": "81fefc25b95a1792d452d6353f52994c38e372e33e534181581e81eb31b5ab6c", + "ios/App/VPNController.swift": "5baed4715342dc34104501bafd36f54a187a65e941e0bc550b112bc5e4df3b5f", + "ios/LICENSE.md": "b7e94910b8dc377b0a05ccde3c6e5941838dfc15c9dd790078d11728205b524e", + "ios/NOTICE.md": "8c862f2f6b71440616a887e6deb7444a1262cf7d9f144208cc04041c3f9a3371", + "ios/PacketTunnel/Info.plist": "55a9c3dbd2e3925788619684eace456de8fcbdd4e0afb681237cdcff36d6bda9", + "ios/PacketTunnel/PacketTunnel.entitlements": "6cf7eb189cd5bf0a4e9f4c448ce399714e9aaa98511a08ac1529769984d75caa", + "ios/PacketTunnel/PacketTunnelProvider.swift": "d4705a6364897086b3854adf031a293eb596bc69836fa04e4340a2d30dae27dc", + "ios/PacketTunnel/XrayBridge.swift": "2d6bbed36747a770dceaa7663de2ef367136a062aa079247c47b7a2844af72df", + "ios/README.md": "edbe664c324b8328319c9e959545a9542a2facdaf3f99f015242fb2447287e83", + "ios/Resources/Assets.xcassets/AppIcon.appiconset/AppIcon-UCVL-opaque.png": "f086a4f183c9dc6a93b8ad6775a3511ec5ee1def3f45ebc9cdc15775d6f6bbfb", + "ios/Resources/Assets.xcassets/AppIcon.appiconset/AppIcon.png": "0b94081e0f46088810b699abc4398604286bb5fc24134691814af764e1c35b7b", + "ios/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json": "251028cc91c1b0a30b0452c815af11d4701bcc0ed4e30c5a6b4df01cff174736", + "ios/Resources/Assets.xcassets/Contents.json": "0fd49ba3c3585c709678e0046a821c3c60685ec7063720d30d3a3448be3a208b", + "ios/Resources/Assets.xcassets/UCVLLaunchBackground.colorset/Contents.json": "aaf47d9c2e10bd3e27d9deb00fbee7a02a7942bcba8901ce06b7fee7e577e2aa", + "ios/Resources/Assets.xcassets/UCVLLogo.imageset/Contents.json": "b0a4a637bf150232379f6419b17324e2513063ab389164220a5563350317a15e", + "ios/Resources/Assets.xcassets/UCVLLogo.imageset/UCVLLogo.png": "0b94081e0f46088810b699abc4398604286bb5fc24134691814af764e1c35b7b", + "ios/Resources/Geo/README.md": "d866fb7a1831c88af1b674fd231fd751d754d9086bf8f7840d207ad1ca166f58", + "ios/Scripts/fetch-libxray.sh": "74a1d026c72e53c1d54ad713f737762b66228ade83dae6d9202f33483b3ca8e4", + "ios/Scripts/generate-project.sh": "9d173600deed1d5175483a0d616378c69f85029c85a1e1d5a6b7e6cdc5a38d91", + "ios/Scripts/source-audit.py": "fa8726df29916c89628f73766c76c00017c1f8632d4a7e87fcbaaae1f5b5f8e1", + "ios/Scripts/verify-and-archive.sh": "9ee27f05f5e553768395e656270b86e0a00d72d3cbcad2d4423c2827a574391a", + "ios/Shared/ConnectionAttemptPolicy.swift": "8285ed94b726c53a0815b914fe123221b743ae788e14c5b4ab6e293a9f3bd900", + "ios/Shared/Models.swift": "b569320c9874b77613db10e4488a371486896ab98597772827e0fd667ba2b0cf", + "ios/Shared/NetworkAddress.swift": "bed06b14f1ef7b5c714486f4fcb9b2ef7c181f57e22e99df12ebc6c53ab03d5c", + "ios/Shared/TunnelConfigurationBuilder.swift": "d310a0a5465010c69fa7945b16b9f39063a9e96c228186cd6ca8a1a3b8385a32", + "ios/THIRD_PARTY_NOTICES.md": "ee0631fed9beb97d40eb0e4af82f746d74150cead1342aa6eddc39674ddae903", + "ios/Tests/ClientConfigResponseTests.swift": "db5466e7e40f606222dd0310be737e8a72d0274c94338b18f3a3b5ed8c542f56", + "ios/Tests/ConnectionAttemptPolicyTests.swift": "48dd15ba187f5f63b759f7e185f6ab06c37c913727c5f8863c77c2b5de1e72ad", + "ios/Tests/NetworkAddressTests.swift": "84fbdc158eae4edb7a86976bee874407f1d439e1034a7d6fbd45107e8aacbdd7", + "ios/Tests/TunnelConfigurationBuilderTests.swift": "b065b7b747fdca0edf6a58f6e12043cf4332b0fcfb6384e1dc19556fb392244b", + "ios/ThirdParty/Xray-core-MPL-2.0.txt": "2684de17300e0a434686f1ec7f8af6045207a4b457a3fe04b2b9ce655e7c5d50", + "ios/ThirdParty/libXray-MIT.txt": "fc13535fb01ab48c3c594d4c47c1067ebe7650ee86a35a23395b2d9ee58513e2", + "ios/project.yml": "2a88092fc27f503c05a5a1c163f345d568117d50cd04268115dae044431cffab", + "windows/ApiModels.cs": "6ba3dda38066f632a538301ca0bb0f4eba9c24826dc9fcfbeb9fcf0441b865b9", + "windows/AppPaths.cs": "2bac68512acfb68b4f3dad0d30c9ee17eb6f576eeb73c6a453501d4ea184488e", + "windows/Brand.cs": "621a1c5b75880cbf4f88b482dc58bdd3c98e0f4d156bf816d23d63d48e199bca", + "windows/ClientShutdownScope.cs": "f5944b57ccb4616dbd32ee2952b56dd0c9feccb7c556d8954092c88354a78d41", + "windows/ClientUpdater.cs": "b218513dc57b8513eb749aeab093e39911428a07f05363ae349555d22e53e4b8", + "windows/ConnectionAcceptanceTrace.cs": "c9efd15e19672a5ac3b4b807c96a3de3db3ff2fd373e13494a548df51fecdd9a", + "windows/ConnectionHealthPolicy.cs": "c17cf49eab51b691163ee8105f32bcaec121707ead862a773dbc372bf01e2a11", + "windows/ConnectionHealthSelfTest.cs": "5a483194f754ad51366acd9df00554c8ceecaa5dadba73972c4922b72dc7e2fe", + "windows/ConnectionRecoveryPolicy.cs": "860bd4cedf393f157fc1dd68e407776e1fe0fa1cc6cef7e99cd5581b64c6f5f6", + "windows/ConnectionSelection.cs": "def94b338b9e1fd940c19b8991e4268a4e59bec741ea624f5a6e4fb7a7d3bbcc", + "windows/ConnectionSelectionSelfTest.cs": "12bd82071989c5e539031f6e7921660edb4eb10a4136ac332cc84eca2e2d96de", + "windows/ConnectionSelfTest.cs": "6511feda4c81da766e745a499c682d2d0b3be0386c4ba424e7ddc04029ebca12", + "windows/DailyTrafficChart.cs": "5006497ef28cd8a7a00f8553d729220f559cc5205ea0471bdc16be5a7e97fc7d", + "windows/DashboardControls.cs": "f58f30cbd766c0b912afc9b3bda6bc3b88073cb40dc04986c0286790ff2bb758", + "windows/DashboardLayout.cs": "a761de5842c1aa03e68089dc90f73e0a2372532e5367b8e64198ba7b5bd6f8a8", + "windows/GitReleasePolicySelfTest.cs": "c43d0e63e9c00a7c6b376ed204bc6c400572085075397685c92862e8318fe369", + "windows/GitReleaseUpdater.cs": "dcd00a0feca6801aad4e346c7565d8bcd80b3fd24a4accbe5cd4643d04264b9b", + "windows/InstallationIntegration.cs": "af4e5d0cd78d66546079f452e110be627494550594e847d13b77178494fb3bda", + "windows/InstallationIntegrationSelfTest.cs": "a381a2e6b650e4b841551d3bf06ade4edcc267acca15cd812185f58f03bac5f6", + "windows/InstallationPackageSelfTest.cs": "4a1d401768e65f8d933b86500407ae8e1baa9e8575da01f97030059078fc2848", + "windows/InstallationRemoval.cs": "bdba7f9921f1645d9a0bc50e31cb55ef37da2d15330f763005936a60085733c7", + "windows/InstallationRemovalSelfTest.cs": "82968c3c5edde51db2e3e065f1093465b0b7a2e46ca1f0f4cdfb3dec8539941f", + "windows/InstallationSelfTest.cs": "03cb0d797c4eeb5a0d44548d844e46f53e8943928c1f118ed6b5fed948eaf298", + "windows/InstallationTransaction.cs": "319d379052bb8633c77b54012862afa8e2b9fabbb50bce647332298eb3915ac9", + "windows/InstallerGuardianGate.cs": "416c5560d1fb413f02f0b0a924fb4be922652a601269c056f31c93f155c0014f", + "windows/KnownTailnetEndpoints.cs": "5e31baaa0adedb48f6370f9466e1c82e8e8ed3701ed8165f46bd934369638271", + "windows/LICENSE": "b7e94910b8dc377b0a05ccde3c6e5941838dfc15c9dd790078d11728205b524e", + "windows/LearningExpirySoakSelfTest.cs": "c27890114e6597236ce407afb67f48ddd4f83b10cec3219d64e228f10309d23a", + "windows/LearningMatrixSelfTest.cs": "edb37d73f3db2e2722d49f92cf141e1b13275c76bdfadf36ab65eacf1d83d8ec", + "windows/LearningPolicy.cs": "858646bbbe65cf18a193c425fbd9cbfe114accf34abe5c981df866ec27a45fcf", + "windows/LearningProbeBudget.cs": "3001e1deda8a4337d1754a09bbc7569619f2730258d44d019d2fbcca472e51e5", + "windows/LearningSelfTest.cs": "786587e8a145bbcd86acfc77f8f204958a6576aa008a19637e521ebb93926b10", + "windows/LearningStore.cs": "cc1c6cf1b0c5b948e16be24a46dc2429a020cafa176a36ad9c450d887410169e", + "windows/LearningTransportSelfTest.cs": "05dcfd3fcfc6f25e20612c020583eb6c36934c1b251e50e70fcd29501ad0efe7", + "windows/MainForm.Chrome.cs": "b537ae6528d5fb592d99915af27bdf2dd819604543a9b5a91d8bf3190b52ca4f", + "windows/MainForm.Dashboard.cs": "9d4774789f74c97f9b47c676d37b1739718cefbd3b51e8dc74b5ab5d565e3dc7", + "windows/MainForm.Handover.cs": "a7c6e81186be1d7a154c6997b7d44621543c163ba703901d7974632dd462d25f", + "windows/MainForm.Selection.cs": "297186f274b45cd9bf14fbc15492cbe026aea8902ffda386029cbcb75901e469", + "windows/MainForm.cs": "becb27dfb9f94c17506f94f2d7479e5db51033a31b0f3dc1d755634c1310f46a", + "windows/NOTICE.md": "8c862f2f6b71440616a887e6deb7444a1262cf7d9f144208cc04041c3f9a3371", + "windows/NetworkHandover.cs": "b43548be0051cf92dfd332e537951e4b5083f2a123be8021994513bbc3748d46", + "windows/NetworkHandoverSelfTest.cs": "681d0154dc0aa5f49d7ce1f3088b465eea3ed82571b464951df8d4c89cecdf73", + "windows/NetworkLearningLeaseSelfTest.cs": "4b445d6fa320e5f5b883bd68916e99807b5543f1d3f91b24a504d4644c0877ec", + "windows/NetworkLearningLeases.cs": "9a48a50bd4aeeb53f6b64878c7260704ce3a73cd74e6dc91f61ff68ad013e027", + "windows/NetworkOwnerLease.cs": "3917753ad422f33c42461c4abfff40720dfa4d1301f1c8718a7545e381533450", + "windows/NetworkOwnerSelfTest.cs": "8ebcd2dfdc48aa4aa8983d2894a4cec715a4ab714fca38df1a4cc932bf25b440", + "windows/NetworkRecoveryTool.cs": "2dec1406ca0719af3eacedf2d8f83659927c44bc4a1eaccc1babe84c0d3d99cc", + "windows/NetworkRouteLease.cs": "0b57aa0e3499ec3f9f7f7a4c683cecca0f6d7f275734e126a5da4f7849cd7ae3", + "windows/NodeHealthProbe.cs": "c49e5cf6b3a62242ae0e486aa3fd267d50485269ec0bd769cf140e743850fec7", + "windows/NodeMatrixSelfTest.cs": "eed8e56036d300fdffd82b83cca87ea6b2806e8598b2c4fc916aded15197f20d", + "windows/NodePresentation.cs": "c70a8be06cce937f309fd10531d97b02b675a72509fff2419e412fbdf84977c0", + "windows/NodeTransportConnector.cs": "4f9b85d0caccf0604570df6a51a2962e5a728fbb553eacb698daa13bf33c628d", + "windows/PhysicalUplink.cs": "b0a0eca6b9f724972d0e445c2dc352326ea4d7357317b98639972d60dadc2e63", + "windows/PlatformBootstrapTransport.cs": "a1f54cd698c778eca74aca5406977c0e39673f9b33eaec3a9d3567a1d02e642a", + "windows/PlatformBootstrapTransportSelfTest.cs": "150dc9973bc5ffc981eb7b89723620cb32be0ebeea8c41e4088d65a6663b8710", + "windows/PrivateAuxiliaryRouting.cs": "60bf679c0d620a38203323852cd585b44e1b77613dac7708ea93306ffeb9d255", + "windows/PrivateAuxiliaryRoutingSelfTest.cs": "1a955b2d8e7e9ffe8ff0c6a7bc717877ccd0f7681ff8a65219bb2fe93c230382", + "windows/PrivateAuxiliaryRuntime.cs": "dcfb406508e3d7e9a9163163cfe5e2724a6955a18ae4604e2d9f890da61308cf", + "windows/PrivateTransportProbe.cs": "e29e9bd0180a37bdcecf7104fde5069be799aca92b747881d0485a62d382d9b3", + "windows/Program.cs": "cd3f3d5dbb194ac8bb89de151bec0c3494ecae2bb52dffdfee29296449c09c4c", + "windows/ProxyDnsPolicy.cs": "997e2e922ad43956932c1bd0a6da3457bc308ee723f4f77ff8e52aa23fa954c0", + "windows/ProxyProbe.cs": "5d27b5a6c6b192a0c0f3ec4637c5a876a71130497af57f7cb4a04ab4735ca1ec", + "windows/README.md": "bbefa88371cca54662456dac7f1aa48ef030a372695a25b5d1adadc3287f371c", + "windows/ReplacementContinuitySelfTest.cs": "107878ab2b367f1812377c0b209f6d620da390091c3882e4be53a48e517d86a1", + "windows/RouteLeaseSelfTest.cs": "6189c66b9f66c58bed26de4441c58a9ec02b67257bfa04ed66d702acfcd054d9", + "windows/RoutingRuleBatches.cs": "9997bfa766fffe7bed7352f307c1f6f118a9be9aa86653eaefae3b2bdaa26c1e", + "windows/RoutingUpdateSelfTest.cs": "48c99fc7a01037aa0368c53ccdb7eec0fea1edfac3bb2532c0de89631343206d", + "windows/ScenicTheme.cs": "faa259b527d9753bb7915f76f8b5f40f1e066b11d0a5c891e55fd6aaae48b071", + "windows/StartupSelfTest.cs": "54be29a94bcb4ac20da8fd232e93b363f29c21fcb15608bc8171772da524b68b", + "windows/SystemPowerShell.cs": "1f9247d2e4f8c9bad1d71105886d2ab33d8958006dcff7fadc63f27502eda6fe", + "windows/SystemProxy.cs": "beaf443f1e285e227e0c390d8e9114d5cf8464e0078a8bb842efa9eeb2b5e916", + "windows/THIRD_PARTY_NOTICES.md": "c7141fe279b2c364c868888db37bd995feba1552025e2259dc4662a01e5122bb", + "windows/TailnetTransport.cs": "6be740dd837fe4aae9e885d11a60474f2fe9d34a6434e74bca46c615df6a6bc8", + "windows/TailnetTransportProbe.cs": "d0811b7d9cddcbf622d88e502c7eb05c6afbddbbc0caf3077fa9ec769e52cf50", + "windows/TailnetTransportSelfTest.cs": "573b3271f377a04455339fb67837ed85f8a288b5f9efebd7e73d97fac08def53", + "windows/TokenStore.cs": "e07cf7d1a4cf7a1bba871c19e50b9d6355cb8c1546657346b0256c8215fed8bb", + "windows/TrafficChart.cs": "8ac141da28a350327874485004520c3a159246d2107f3b1152253f4254e76961", + "windows/TunConfigBuilder.cs": "f651c0525ee0e083d4e723f9409c0992b8cc274105bb8ad1e4c7d1c75f3b4354", + "windows/TunConnectivitySelfTest.cs": "a7d7aff1d03e45dff921807cbfb8f83b5013c9df5c7e06b6662d84a8686b2f86", + "windows/TunRouting.cs": "c6b3e1070a0ba0a3c42dbd12becba55404e540d06aba03cb1cc1053fa426a4c1", + "windows/UpdateProgressForm.cs": "25286b76a235635704dbe8831367141939d063153d0828ee375f1c71d461f041", + "windows/UpdateSelfTest.cs": "453165bb611efb8db0d8a8c9ea13f3553e0047aa22b838c43096e3d83fe18771", + "windows/UpdateStreamSelfTest.cs": "ad059016c0197f33582b1969ab3280c5b9589a28d659613b3e97ce4a357d38c1", + "windows/UsageHistorySeries.cs": "9e7515ceede1899e06116352de79edd6252c921048bcae9958bf9358d93b3069", + "windows/VPNPlus.csproj": "b85db9d1bbadc126d5e9112d4f78eb33fe8478fd5fb0c9818483a538af68d91b", + "windows/VpnApiClient.cs": "6e227467981bbc68aac7fb93fe32cfb96f06b0d06f04405209512f1a11c971af", + "windows/WindowChrome.cs": "f7f74759d9ca149c00abd3a7e2ac1556d6630df29eb1e6afc66884dff01f66b9", + "windows/WindowChromeSelfTest.cs": "9643c547733b3274c866122504cd733f1ea6b4c8ce7f0146b5298e7800c25c5b", + "windows/XrayManager.cs": "90b69de09884d037d21f05c411aef83087ce58ceeeffaca295e583ec6be91b50", + "windows/XrayRoutingUpdater.cs": "91fd2b5db25477dbe4de7118faef79f9c51f9a8a3dd86e8b26c676092de3bca5", + "windows/app.manifest": "4c9a2e8e2056c3bb0ae45a5f7b2e223298ee683a82b70ba4910e17f5728cf5b6", + "windows/assets/company-logo-original.png": "04cf7f754a5353b96cddbed4a57a557154342c190a1785487e3bfb36cab04163", + "windows/assets/landscape-header-v1.md": "61f89353147be00d59b4cab6372c3e0d51f14d89b61a8e201a9938f51041125b", + "windows/assets/landscape-header-v1.png": "e87b91f59038c1e9ccfe616fbc84a0f6cd8d00d6d98e71388c62562017d9dfd8", + "windows/assets/vpnplus-icon-256.png": "d940b0b189bb0d1caf77799a00dd9030f76b465559bd4072fc7b60aec677838b", + "windows/assets/vpnplus-logo-final.png": "0b94081e0f46088810b699abc4398604286bb5fc24134691814af764e1c35b7b", + "windows/assets/vpnplus-logo.png": "a4111cd777996ce6ec3962df40fe64285acd570936541b3bc98a789781d1c4be", + "windows/assets/vpnplus.ico": "4b517a83dd3385fb47bfd39911a21ff8c23116473e5ece1b1aa6a84530f37164", + "windows/assets/zonghengjia-app-icon-v1.png": "c78427d23baea91bbebdeafccde212b7d04033d2a10199cdc80e040c6f3d2574", + "windows/assets/zonghengjia-app-logo-v1.png": "4f7a25046cd640e255423dca11baecc6466dcaf7f1e16315c4bdbb5cfd6f3ec6", + "windows/assets/zonghengjia-app-v1.ico": "4da4732edab10c32b75ebd6919a695d9bec13c51844c82119017a43b80bb2df0", + "windows/build/Build-TailnetGuardianCandidate.ps1": "b293901ed1f8b96941ad72ca1305a3b18cdb91a4fb802f20596ef23b49666a2a", + "windows/build/GuardianApprovalPipe.cs": "32060a6920f2d1f66b96c43f61e925be238a54cac85fb3c4bdb91476e1946d5e", + "windows/build/GuardianGateFixture.cs": "b1762ff88076919307eea1b6b0050b7ff561d73759a4cf1283a866659313f9fc", + "windows/build/GuardianGateFixture.csproj": "a4ddf6cdc6730270df8c94c6508467906e04dd057fc39e54c690c77cc01420f4", + "windows/build/OwnedProcessGroup.cs": "00fc73e00dbc25bdf5ff6557f0d81786ba1ef235822ea290bead9b8a5ac66618", + "windows/build/ProductionInstallationBaseline.ps1": "02675e525dd5060a5b0ea20320665533cbb55f9b011b4fd67c99cd88804b983e", + "windows/build/ProductionNetworkBaseline.ps1": "aa3600f92ba19d3041b0c50696d1035efe68013dec7ae3f7973e75b5fc17f9b1", + "windows/build/Test-InstallerGuardianGate.ps1": "5289a4643cc41279eae8d32a7cfdabfdd528506b03cc9fadaf33880dea996694", + "windows/build/Test-ProductionInstallationBaseline.ps1": "7d5afbffd8e4ed595917fdc8054469cdf071cfe4c932955bb84840d867eec0f0", + "windows/build/Test-ProductionNetworkBaseline.ps1": "842d84027e8ec68e94ab860500a176b8d8f284b7ca0d4e55751d0e81818742ac", + "windows/installer/Acceptance.nsi": "52f56eb5de48eb60ea2170f740bcc0938b97bf83130c926df9c790f3360ba17d", + "windows/installer/GuardianGate.nsh": "a88d11a41ff8c52f6ef5270f3852b61c0536b446c2546a62eb4ddb7a3b67e722", + "windows/installer/InstallationIntegration.nsh": "dfd4687be5f094be4ca452fb4edfdb9d4eba2c9f0034c7a2e547b985a2e6ac44", + "windows/installer/PayloadTransaction.nsh": "7e00ebde7e87febfd3309abc7d61ccbc4a3b400c69ab69d5189c7b98d37ea0c7", + "windows/installer/RegistryAcceptance.nsi": "1982ccea32d06f536e4b9e8fbce56cdf06fc23221d3726f812e7f9b13fe7c456", + "windows/installer/RegistryCleanup.nsh": "eb1b7345e195dd04f91d778e9120b04af04b2e28be6712290011609b7481b58f", + "windows/installer/RemovalPayload.nsh": "2cfcac32faf79e988bd5c4f92fc37f3f9bbe1fb39875d8645d689edb9c209b7e", + "windows/installer/VPNPlus.nsi": "6e53ec57071e4c8b48f2c168396fc13a3caa9ce11a78c9426c1fd4c830f2798d", + "windows/licenses/NSIS-COPYING.txt": "388357c1215ff403c5ebde3a5ecd273e68f8b79a579996775245d1ee65442aba", + "windows/licenses/Wintun-License.txt": "183adac21e7d96c508c8fd34d394b7b6708bc81564ad1bad61ab66143a008cd2", + "windows/licenses/Xray-MPL-2.0.txt": "1f256ecad192880510e84ad60474eab7589218784b9a50bc7ceee34c2b91f1d5", + "windows/release/RELEASE-NOTES-0.2.21.md": "839f36685e39c04bf692ffd2896bab4538577c0b3bbddd0a3cc335fe13b65d4c" + }, + "IosSourceCommit": "b07d085413b1b6370245866fd82271b76590b6d6", + "Kind": "clean-history-free-open-source-export", + "MacosExcludedTransferredToSeparateMaintainer": true, + "OriginalAcceptanceNotTransferred": true, + "ProductionAccepted": false, + "ProductionDeployed": false, + "Repository": "admin/ucvl-zonghengjia-open-source", + "Schema": 1, + "SourceOnly": true, + "SourcePins": { + "BackendInputBinding": "e5b5213a44391435248f46fbc940b4ecceb0d05e2b8ce3f2b6ef42c2c8daf79d", + "IosInputBinding": "5670c70b38cbf3f440057ec7202724ffe062e885262615396240c4a9889402b5", + "WindowsInputBinding": "6248dd02abc273c0c28083c94e03302098505cc04b95a8f420a6e4e8794efc7e", + "WindowsManifestSha256": "c5cc769b94d7ae7e831b87d40728f8083bb44e2b3f80c4aace8f7bef9a48e1a0" + }, + "StableUpdateFeedChanged": false, + "ThirdPartyLicensePins": { + "NSIS-COPYING.txt": "388357c1215ff403c5ebde3a5ecd273e68f8b79a579996775245d1ee65442aba", + "Wintun-License.txt": "183adac21e7d96c508c8fd34d394b7b6708bc81564ad1bad61ab66143a008cd2", + "Xray-MPL-2.0.txt": "1f256ecad192880510e84ad60474eab7589218784b9a50bc7ceee34c2b91f1d5" + }, + "WindowsSourceCommit": "0d463e6af91a3802c564b06dabb6bf86ebff5a38" +} diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..a0b22dd --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,10 @@ +# 第三方许可及 MIT 范围 + +顶层及 Windows、后台、iOS 中 MIT 仅适用于 UCVL 有权授权的自有程序代码/文档与原创山水插画。第三方代码、库、数据、工具、商标、公司名称与 Logo 另行适用原权利及许可证,不因聚合仓库的 MIT 而被重新许可;此发布不授予公司商标权或服务访问权。 + +- Windows:windows/THIRD_PARTY_NOTICES.md 原文保留;windows/licenses/ 包含固定发行 payload 中的 Xray MPL-2.0、Wintun 预编译二进制再分发许可、NSIS 许可。这里不分发这些第三方可执行文件。 +- iOS:ios/THIRD_PARTY_NOTICES.md、ios/ThirdParty/libXray-MIT.txt、ios/ThirdParty/Xray-core-MPL-2.0.txt 原文保留。Vendor XCFramework 与未明确来源许可的 Geo 数据未打包。 +- Android:保留其既有 GPL-3.0 项目及 LGPL/MIT/lwIP/Wintun 等依赖许可,见 android/README.md 链接;不改为 MIT。 +- 后台:requirements.txt 记录依赖。安装的第三方依赖继续遵循各上游版本许可证,不属于公司 MIT 再许可范围。 + +来源许可不明的用户提供登录图片未纳入此导出。原候选安装包、签名、生产数据库、配置及凭据不在公开源码范围。 diff --git a/android/README.md b/android/README.md new file mode 100644 index 0000000..50c9951 --- /dev/null +++ b/android/README.md @@ -0,0 +1,8 @@ +# Android GPL-3.0 源码 + +保留原公开仓库:[ucvl-zonghengjia-android](https://pro.ucvl.cn/admin/ucvl-zonghengjia-android)。 + +- 固定 1.0.4 候选提交:c0737d5665d650f761ff7c461180027824bd99fd。 +- 候选标签:android-v1.0.4-candidate.1;候选不等于稳定自动升级已验收。 +- 根 GPL-3.0、上游版权、来源及各依赖原许可保持不变;不改为本聚合仓库的 MIT。 +- 签名私钥、运行配置、账户及服务器凭据不公开。此处只链接已有 GPL 源码,不复制旧本地 checkout 或重新发布 APK。 diff --git a/backend/.dockerignore b/backend/.dockerignore new file mode 100644 index 0000000..7c702d7 --- /dev/null +++ b/backend/.dockerignore @@ -0,0 +1,19 @@ +.env +.env.* +.git +__pycache__/ +*.py[cod] +*.sqlite3 +.pytest_cache/ +staticfiles/ +.venv/ +.tools/ +.test-runtime/ +backups/ +candidates/ +releases/ +acceptance/ +tools/ +*.dump +*.tgz +*.tar.gz diff --git a/backend/Dockerfile b/backend/Dockerfile new file mode 100644 index 0000000..7d3070d --- /dev/null +++ b/backend/Dockerfile @@ -0,0 +1,25 @@ +FROM python:3.12-slim-bookworm + +ARG PIP_INDEX_URL=https://pypi.org/simple + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + PIP_DISABLE_PIP_VERSION_CHECK=1 + +WORKDIR /app + +RUN addgroup --system app && adduser --system --ingroup app app + +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir --index-url "$PIP_INDEX_URL" -r /app/requirements.txt + +COPY . /app +RUN chmod +x /app/docker/entrypoint.sh \ + && mkdir -p /app/staticfiles \ + && chown -R app:app /app + +USER app + +EXPOSE 8000 +ENTRYPOINT ["/app/docker/entrypoint.sh"] +CMD ["gunicorn", "toplc_vpn.wsgi:application", "--bind", "0.0.0.0:8000", "--workers", "2", "--threads", "2", "--timeout", "60", "--access-logfile", "-", "--error-logfile", "-"] diff --git a/backend/LICENSE b/backend/LICENSE new file mode 100644 index 0000000..381a41b --- /dev/null +++ b/backend/LICENSE @@ -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. diff --git a/backend/NOTICE.md b/backend/NOTICE.md new file mode 100644 index 0000000..a0b22dd --- /dev/null +++ b/backend/NOTICE.md @@ -0,0 +1,10 @@ +# 第三方许可及 MIT 范围 + +顶层及 Windows、后台、iOS 中 MIT 仅适用于 UCVL 有权授权的自有程序代码/文档与原创山水插画。第三方代码、库、数据、工具、商标、公司名称与 Logo 另行适用原权利及许可证,不因聚合仓库的 MIT 而被重新许可;此发布不授予公司商标权或服务访问权。 + +- Windows:windows/THIRD_PARTY_NOTICES.md 原文保留;windows/licenses/ 包含固定发行 payload 中的 Xray MPL-2.0、Wintun 预编译二进制再分发许可、NSIS 许可。这里不分发这些第三方可执行文件。 +- iOS:ios/THIRD_PARTY_NOTICES.md、ios/ThirdParty/libXray-MIT.txt、ios/ThirdParty/Xray-core-MPL-2.0.txt 原文保留。Vendor XCFramework 与未明确来源许可的 Geo 数据未打包。 +- Android:保留其既有 GPL-3.0 项目及 LGPL/MIT/lwIP/Wintun 等依赖许可,见 android/README.md 链接;不改为 MIT。 +- 后台:requirements.txt 记录依赖。安装的第三方依赖继续遵循各上游版本许可证,不属于公司 MIT 再许可范围。 + +来源许可不明的用户提供登录图片未纳入此导出。原候选安装包、签名、生产数据库、配置及凭据不在公开源码范围。 diff --git a/backend/README.md b/backend/README.md new file mode 100644 index 0000000..b827ec6 --- /dev/null +++ b/backend/README.md @@ -0,0 +1,7 @@ +# 纵横家 Django 后台开源源码 + +来源为固定的 phone-20261010 源码 freeze(含 0001–0015 迁移),不是生产部署或正式迁移验收。公司自有代码按 MIT 开源,依赖保持原许可证;不含数据库、用户信息、环境变量、SSH/代理/企业微信/支付凭据、生产镜像或私有 Git 历史。 + +使用隔离的 Python 虚拟环境和 requirements.txt 安装依赖,按 toplc_vpn/settings.py 的环境变量入口提供自己的 Django secret、数据库、主机与代理配置。先审查配置与迁移,在自己的非生产数据库测试后再部署。不要直接接入现有生产数据或使用示例节点值。本仓库未提供一键安全生产部署承诺。 + +内部节点地址已一致替换为示例;公司公开 API/下载域名只为兼容保留。生产环境应自行配置账户审批、套餐、节点、策略、审计与服务访问控制。公开源码不授予公司服务器访问权限。 diff --git a/backend/accounts/__init__.py b/backend/accounts/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/backend/accounts/__init__.py @@ -0,0 +1 @@ + diff --git a/backend/accounts/admin.py b/backend/accounts/admin.py new file mode 100644 index 0000000..09ff0a7 --- /dev/null +++ b/backend/accounts/admin.py @@ -0,0 +1,163 @@ +from django.contrib import admin +from django.contrib import messages +from django.contrib.auth.admin import UserAdmin +from django.core.exceptions import ValidationError +from django.db import transaction + +from control.models import PlanApplication + +from .models import LoginAttempt, User, WeComBinding, WeComBindingEvent + + +@admin.register(WeComBinding) +class WeComBindingAdmin(admin.ModelAdmin): + list_display = ("user", "kind", "created_at", "last_login_at") + list_filter = ("kind",) + search_fields = ("user__username", "user__email") + readonly_fields = ("user", "corp_id", "kind", "subject_id", "created_at", "last_login_at") + + def has_add_permission(self, request): + return False + + def has_delete_permission(self, request, obj=None): + return False + + +@admin.register(WeComBindingEvent) +class WeComBindingEventAdmin(admin.ModelAdmin): + list_display = ("user", "action", "created_at") + readonly_fields = ("user", "action", "identity_digest", "created_at") + list_filter = ("action",) + + def has_add_permission(self, request): + return False + + def has_change_permission(self, request, obj=None): + return False + + def has_delete_permission(self, request, obj=None): + return False + + +def _approve_users_with_plan(modeladmin, request, queryset, identity_type): + success = 0 + for selected_user in queryset: + try: + with transaction.atomic(): + user = User.objects.select_for_update().get(pk=selected_user.pk) + applications = list( + PlanApplication.objects.select_for_update() + .filter(user=user, status=PlanApplication.Status.PENDING) + .order_by("-created_at", "-pk") + [:2] + ) + if not applications: + raise ValidationError("没有待审核的套餐申请,账号未启用。") + if len(applications) > 1: + raise ValidationError("存在多个待审核套餐申请,请核对后单独审核。") + application = applications[0] + user.identity_type = identity_type + user.save(update_fields=["identity_type"]) + application.approve(request.user) + success += 1 + except ValidationError as exc: + modeladmin.message_user(request, f"{selected_user}: {exc}", level=messages.ERROR) + if success: + modeladmin.message_user( + request, + f"已审核 {success} 个账号,并自动创建或更新订阅。", + level=messages.SUCCESS, + ) + + +@admin.action(description="设为内部员工并启用") +def approve_as_employee(modeladmin, request, queryset): + _approve_users_with_plan(modeladmin, request, queryset, User.IdentityType.EMPLOYEE) + + +@admin.action(description="设为外部联系人并启用") +def approve_as_external(modeladmin, request, queryset): + _approve_users_with_plan(modeladmin, request, queryset, User.IdentityType.EXTERNAL) + + +@admin.action(description="暂停服务") +def suspend_users(modeladmin, request, queryset): + queryset.update(account_status=User.AccountStatus.SUSPENDED) + + +@admin.action(description="标记离职") +def mark_departed(modeladmin, request, queryset): + for user in queryset: + user.account_status = User.AccountStatus.DEPARTED + user.save(update_fields=["account_status"]) + for subscription in user.subscriptions.exclude(status__in=["cancelled", "expired"]): + subscription.cancel(reason="用户被标记为离职") + + +@admin.register(User) +class TopLCUserAdmin(UserAdmin): + list_display = ( + "username", + "display_name", + "email", + "identity_type", + "account_status", + "is_staff", + "date_joined", + ) + list_filter = ("identity_type", "account_status", "is_staff", "is_active") + search_fields = ("username", "display_name", "email", "phone", "company_name") + ordering = ("-date_joined",) + actions = (approve_as_employee, approve_as_external, suspend_users, mark_departed) + fieldsets = UserAdmin.fieldsets + ( + ( + "业务身份", + { + "fields": ( + "display_name", + "phone", + "company_name", + "identity_type", + "account_status", + "approved_at", + "approved_by", + ) + }, + ), + ("未来 Odoo 对接", {"fields": ("odoo_user_id", "odoo_partner_id"), "classes": ("collapse",)}), + ) + add_fieldsets = UserAdmin.add_fieldsets + ( + ( + "业务身份", + { + "fields": ( + "display_name", + "email", + "phone", + "company_name", + "identity_type", + "account_status", + ) + }, + ), + ) + readonly_fields = ("approved_at", "approved_by") + + +@admin.register(LoginAttempt) +class LoginAttemptAdmin(admin.ModelAdmin): + list_display = ("key_preview", "failures", "blocked_until", "updated_at") + readonly_fields = ("key", "failures", "window_started_at", "blocked_until", "updated_at") + actions = ("clear_blocks",) + + def key_preview(self, obj): + return f"{obj.key[:16]}…" + + key_preview.short_description = "来源摘要" + + @admin.action(description="清除所选登录限制") + def clear_blocks(self, request, queryset): + queryset.delete() + + def has_add_permission(self, request): + return False diff --git a/backend/accounts/apps.py b/backend/accounts/apps.py new file mode 100644 index 0000000..b743369 --- /dev/null +++ b/backend/accounts/apps.py @@ -0,0 +1,8 @@ +from django.apps import AppConfig + + +class AccountsConfig(AppConfig): + default_auto_field = "django.db.models.BigAutoField" + name = "accounts" + verbose_name = "用户与权限" + diff --git a/backend/accounts/forms.py b/backend/accounts/forms.py new file mode 100644 index 0000000..4cb29a5 --- /dev/null +++ b/backend/accounts/forms.py @@ -0,0 +1,76 @@ +from django import forms +from django.contrib.auth.forms import AuthenticationForm, UserCreationForm +from django.db import transaction + +from control.models import Plan, PlanApplication + +from .models import User + + +class TopLCAuthenticationForm(AuthenticationForm): + username = forms.CharField(label="用户名", widget=forms.TextInput(attrs={"autofocus": True})) + password = forms.CharField(label="密码", strip=False, widget=forms.PasswordInput()) + + error_messages = { + "invalid_login": "用户名或密码不正确。", + "inactive": "该账号已被停用。", + } + + +class RegistrationForm(UserCreationForm): + display_name = forms.CharField(label="姓名", max_length=100) + email = forms.EmailField(label="邮箱") + phone = forms.CharField(label="手机", max_length=32, required=False) + company_name = forms.CharField(label="公司", max_length=160, required=False) + plan = forms.ModelChoiceField( + label="申请套餐", queryset=Plan.objects.none(), + help_text="注册时一并申请;内部员工核实身份后免费。标注“暂未开放付款”的套餐仅登记申请,不扣款、不立即开通付费服务。", + ) + accept_terms = forms.BooleanField(label="我同意遵守公司网络服务使用规则") + + class Meta(UserCreationForm.Meta): + model = User + fields = ( + "username", + "display_name", + "email", + "phone", + "company_name", + "password1", + "password2", + ) + labels = {"username": "用户名"} + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + plans = Plan.objects.filter( + active=True, employee_benefit=False, + audience__in=[Plan.Audience.EXTERNAL, Plan.Audience.ALL], + ).order_by("sort_order", "price_cny", "pk") + self.fields["plan"].queryset = plans + self.fields["plan"].label_from_instance = lambda plan: plan.application_label() + default = plans.first() + if default is not None: + self.fields["plan"].initial = default.pk + else: + self.fields["plan"].help_text = "暂未配置可申请套餐,请联系管理员;不会创建没有套餐申请的账号。" + + def clean_email(self): + email = self.cleaned_data["email"].strip().lower() + if User.objects.filter(email__iexact=email).exists(): + raise forms.ValidationError("该邮箱已经注册。") + return email + + def save(self, commit=True): + user = super().save(commit=False) + user.email = self.cleaned_data["email"] + user.display_name = self.cleaned_data["display_name"] + user.phone = self.cleaned_data.get("phone", "") + user.company_name = self.cleaned_data.get("company_name", "") + user.identity_type = User.IdentityType.EXTERNAL + user.account_status = User.AccountStatus.PENDING + if commit: + with transaction.atomic(): + user.save() + PlanApplication.submit(user=user, plan=self.cleaned_data["plan"], note="注册时提交的套餐申请") + return user diff --git a/backend/accounts/middleware.py b/backend/accounts/middleware.py new file mode 100644 index 0000000..836dc74 --- /dev/null +++ b/backend/accounts/middleware.py @@ -0,0 +1,108 @@ +import hashlib +import hmac +import ipaddress +import json +from datetime import timedelta + +from django.conf import settings +from django.db import transaction +from django.http import HttpResponse +from django.utils import timezone + +from .models import LoginAttempt + + +class LoginRateLimitMiddleware: + watched_paths = {"/login/", "/admin/login/", "/api/v1/client/login/", "/auth/wecom/start/", "/account/wecom/unbind/"} + max_failures = 7 + window = timedelta(minutes=15) + block_for = timedelta(minutes=15) + + def __init__(self, get_response): + self.get_response = get_response + + def __call__(self, request): + watched = request.method == "POST" and request.path in self.watched_paths + key = self._key_for_request(request) if watched else None + if watched and self._is_blocked(key): + response = HttpResponse("登录尝试过多,请 15 分钟后重试。", status=429, content_type="text/plain; charset=utf-8") + response["Retry-After"] = "900" + return response + + response = self.get_response(request) + + if watched: + if self._credential_was_accepted(request, response): + LoginAttempt.objects.filter(key=key).delete() + elif self._is_credential_failure(request, response): + self._record_failure(key) + return response + + @staticmethod + def _credential_was_accepted(request, response): + if request.path == "/api/v1/client/login/": + # The client login view returns 403 only after the supplied + # credentials have been verified. Account, subscription and + # device policy denials must not be treated as password failures. + return 200 <= response.status_code < 300 or response.status_code == 403 + return 300 <= response.status_code < 400 and request.user.is_authenticated + + @staticmethod + def _is_credential_failure(request, response): + if request.path in {"/auth/wecom/start/", "/account/wecom/unbind/"}: + return response.status_code == 403 + if request.path == "/api/v1/client/login/": + return response.status_code in {400, 401} + # Django's HTML login forms render validation errors with HTTP 200. + # CSRF/policy errors (403), redirects and server errors are excluded. + return response.status_code in {200, 400, 401} and not request.user.is_authenticated + + @staticmethod + def _client_ip(request): + candidate = request.META.get("HTTP_X_REAL_IP") or request.META.get("REMOTE_ADDR") or "unknown" + try: + return str(ipaddress.ip_address(candidate.strip())) + except ValueError: + return "unknown" + + @staticmethod + def _login_identifier(request): + if request.path in {"/auth/wecom/start/", "/account/wecom/unbind/"}: + return "wecom-account:" + str(request.user.pk if request.user.is_authenticated else "anonymous") + candidate = "" + if request.path == "/api/v1/client/login/": + try: + if len(request.body) > 16 * 1024: + return "unknown" + payload = json.loads(request.body or b"{}") + candidate = str(payload.get("login", "")) if isinstance(payload, dict) else "" + except (TypeError, ValueError, json.JSONDecodeError, UnicodeDecodeError): + candidate = "" + else: + candidate = str(request.POST.get("username") or request.POST.get("login") or "") + normalized = candidate.strip().casefold()[:254] + return normalized or "unknown" + + def _key_for_request(self, request): + # Scope the protection to one account at one network address. Offices, + # hotels and mobile hotspots commonly place many legitimate users + # behind the same public IP, so an IP-only key creates shared lockouts. + value = f"login:{self._client_ip(request)}:{self._login_identifier(request)}".encode() + return hmac.new(settings.SECRET_KEY.encode(), value, hashlib.sha256).hexdigest() + + def _is_blocked(self, key): + attempt = LoginAttempt.objects.filter(key=key).only("blocked_until").first() + return bool(attempt and attempt.blocked_until and attempt.blocked_until > timezone.now()) + + def _record_failure(self, key): + now = timezone.now() + with transaction.atomic(): + attempt, _created = LoginAttempt.objects.select_for_update().get_or_create(key=key) + if now - attempt.window_started_at > self.window: + attempt.failures = 0 + attempt.window_started_at = now + attempt.blocked_until = None + attempt.failures += 1 + if attempt.failures >= self.max_failures: + attempt.blocked_until = now + self.block_for + attempt.save(update_fields=["failures", "window_started_at", "blocked_until", "updated_at"]) diff --git a/backend/accounts/migrations/0001_initial.py b/backend/accounts/migrations/0001_initial.py new file mode 100644 index 0000000..301a95f --- /dev/null +++ b/backend/accounts/migrations/0001_initial.py @@ -0,0 +1,70 @@ +# Generated by Django 5.2.17 on 2026-08-29 12:09 + +import django.contrib.auth.models +import django.contrib.auth.validators +import django.db.models.deletion +import django.utils.timezone +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('auth', '0012_alter_user_first_name_max_length'), + ] + + operations = [ + migrations.CreateModel( + name='LoginAttempt', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('key', models.CharField(max_length=64, unique=True, verbose_name='来源摘要')), + ('failures', models.PositiveSmallIntegerField(default=0, verbose_name='失败次数')), + ('window_started_at', models.DateTimeField(auto_now_add=True, verbose_name='统计开始')), + ('blocked_until', models.DateTimeField(blank=True, null=True, verbose_name='封禁至')), + ('updated_at', models.DateTimeField(auto_now=True, verbose_name='更新时间')), + ], + options={ + 'verbose_name': '登录保护记录', + 'verbose_name_plural': '登录保护记录', + }, + ), + migrations.CreateModel( + name='User', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('password', models.CharField(max_length=128, verbose_name='password')), + ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), + ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), + ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), + ('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')), + ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')), + ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), + ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), + ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), + ('email', models.EmailField(max_length=254, unique=True, verbose_name='邮箱')), + ('display_name', models.CharField(max_length=100, verbose_name='姓名')), + ('phone', models.CharField(blank=True, max_length=32, verbose_name='手机')), + ('company_name', models.CharField(blank=True, max_length=160, verbose_name='公司')), + ('identity_type', models.CharField(choices=[('employee', '内部员工'), ('external', '外部联系人')], db_index=True, default='external', max_length=20, verbose_name='人员类型')), + ('account_status', models.CharField(choices=[('pending', '待审核'), ('active', '正常'), ('suspended', '已暂停'), ('departed', '已离职')], db_index=True, default='pending', max_length=20, verbose_name='账号状态')), + ('approved_at', models.DateTimeField(blank=True, null=True, verbose_name='审核时间')), + ('odoo_user_id', models.PositiveBigIntegerField(blank=True, db_index=True, null=True, verbose_name='Odoo 用户 ID')), + ('odoo_partner_id', models.PositiveBigIntegerField(blank=True, db_index=True, null=True, verbose_name='Odoo 联系人 ID')), + ('approved_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='approved_users', to=settings.AUTH_USER_MODEL, verbose_name='审核人')), + ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.group', verbose_name='groups')), + ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.permission', verbose_name='user permissions')), + ], + options={ + 'verbose_name': '用户', + 'verbose_name_plural': '用户', + 'ordering': ['-date_joined'], + }, + managers=[ + ('objects', django.contrib.auth.models.UserManager()), + ], + ), + ] diff --git a/backend/accounts/migrations/0002_wecombindingevent_wecomloginstate_wecombinding.py b/backend/accounts/migrations/0002_wecombindingevent_wecomloginstate_wecombinding.py new file mode 100644 index 0000000..a7c391a --- /dev/null +++ b/backend/accounts/migrations/0002_wecombindingevent_wecomloginstate_wecombinding.py @@ -0,0 +1,60 @@ +# Generated by Django 5.2.17 on 2026-09-13 06:48 + +import django.db.models.deletion +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('accounts', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='WeComBindingEvent', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('action', models.CharField(choices=[('bind', '绑定'), ('unbind', '解绑')], max_length=16, verbose_name='操作')), + ('identity_digest', models.CharField(max_length=64, verbose_name='身份摘要')), + ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='时间')), + ('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)), + ], + options={ + 'verbose_name': '企业微信绑定审计', + 'verbose_name_plural': '企业微信绑定审计', + }, + ), + migrations.CreateModel( + name='WeComLoginState', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('digest', models.CharField(max_length=64, unique=True)), + ('session_digest', models.CharField(db_index=True, max_length=64)), + ('purpose', models.CharField(choices=[('login', '登录'), ('bind', '绑定')], max_length=8)), + ('next_path', models.CharField(default='/', max_length=512)), + ('expires_at', models.DateTimeField(db_index=True)), + ('consumed_at', models.DateTimeField(null=True)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + ), + migrations.CreateModel( + name='WeComBinding', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('corp_id', models.CharField(max_length=128, verbose_name='企业 ID')), + ('kind', models.CharField(choices=[('member', '企业成员'), ('external', '非企业成员')], max_length=16, verbose_name='身份类型')), + ('subject_id', models.CharField(max_length=128, verbose_name='企业微信身份 ID')), + ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='绑定时间')), + ('last_login_at', models.DateTimeField(blank=True, null=True, verbose_name='最近扫码登录')), + ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='wecom_binding', to=settings.AUTH_USER_MODEL, verbose_name='平台账号')), + ], + options={ + 'verbose_name': '企业微信绑定', + 'verbose_name_plural': '企业微信绑定', + 'constraints': [models.UniqueConstraint(fields=('corp_id', 'kind', 'subject_id'), name='unique_wecom_identity')], + }, + ), + ] diff --git a/backend/accounts/migrations/__init__.py b/backend/accounts/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/accounts/models.py b/backend/accounts/models.py new file mode 100644 index 0000000..d547d06 --- /dev/null +++ b/backend/accounts/models.py @@ -0,0 +1,117 @@ +from django.contrib.auth.models import AbstractUser +from django.db import models + + +class User(AbstractUser): + class IdentityType(models.TextChoices): + EMPLOYEE = "employee", "内部员工" + EXTERNAL = "external", "外部联系人" + + class AccountStatus(models.TextChoices): + PENDING = "pending", "待审核" + ACTIVE = "active", "正常" + SUSPENDED = "suspended", "已暂停" + DEPARTED = "departed", "已离职" + + email = models.EmailField("邮箱", unique=True) + display_name = models.CharField("姓名", max_length=100) + phone = models.CharField("手机", max_length=32, blank=True) + company_name = models.CharField("公司", max_length=160, blank=True) + identity_type = models.CharField( + "人员类型", + max_length=20, + choices=IdentityType.choices, + default=IdentityType.EXTERNAL, + db_index=True, + ) + account_status = models.CharField( + "账号状态", + max_length=20, + choices=AccountStatus.choices, + default=AccountStatus.PENDING, + db_index=True, + ) + approved_at = models.DateTimeField("审核时间", null=True, blank=True) + approved_by = models.ForeignKey( + "self", + verbose_name="审核人", + null=True, + blank=True, + on_delete=models.SET_NULL, + related_name="approved_users", + ) + odoo_user_id = models.PositiveBigIntegerField("Odoo 用户 ID", null=True, blank=True, db_index=True) + odoo_partner_id = models.PositiveBigIntegerField("Odoo 联系人 ID", null=True, blank=True, db_index=True) + + class Meta: + verbose_name = "用户" + verbose_name_plural = "用户" + ordering = ["-date_joined"] + + def __str__(self): + return self.display_name or self.username + + @property + def service_enabled(self): + return self.is_active and self.account_status == self.AccountStatus.ACTIVE + + @property + def plan_application_allowed(self): + # Pending registrants may apply. A plan review must not double as + # permission to reverse a separately imposed suspension or departure. + return self.is_active and self.account_status in (self.AccountStatus.PENDING, self.AccountStatus.ACTIVE) + + +class LoginAttempt(models.Model): + key = models.CharField("来源摘要", max_length=64, unique=True) + failures = models.PositiveSmallIntegerField("失败次数", default=0) + window_started_at = models.DateTimeField("统计开始", auto_now_add=True) + blocked_until = models.DateTimeField("封禁至", null=True, blank=True) + updated_at = models.DateTimeField("更新时间", auto_now=True) + + class Meta: + verbose_name = "登录保护记录" + verbose_name_plural = "登录保护记录" + + def __str__(self): + return f"{self.key[:12]}… ({self.failures})" + + +class WeComBinding(models.Model): + class Kind(models.TextChoices): + MEMBER = "member", "企业成员" + EXTERNAL = "external", "非企业成员" + + user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="wecom_binding", verbose_name="平台账号") + corp_id = models.CharField("企业 ID", max_length=128) + kind = models.CharField("身份类型", max_length=16, choices=Kind.choices) + subject_id = models.CharField("企业微信身份 ID", max_length=128) + created_at = models.DateTimeField("绑定时间", auto_now_add=True) + last_login_at = models.DateTimeField("最近扫码登录", null=True, blank=True) + + class Meta: + verbose_name = "企业微信绑定" + verbose_name_plural = "企业微信绑定" + constraints = [models.UniqueConstraint(fields=["corp_id", "kind", "subject_id"], name="unique_wecom_identity")] + + +class WeComLoginState(models.Model): + digest = models.CharField(max_length=64, unique=True) + session_digest = models.CharField(max_length=64, db_index=True) + purpose = models.CharField(max_length=8, choices=[("login", "登录"), ("bind", "绑定")]) + user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) + next_path = models.CharField(max_length=512, default="/") + expires_at = models.DateTimeField(db_index=True) + consumed_at = models.DateTimeField(null=True) + created_at = models.DateTimeField(auto_now_add=True) + + +class WeComBindingEvent(models.Model): + user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) + action = models.CharField("操作", max_length=16, choices=[("bind", "绑定"), ("unbind", "解绑")]) + identity_digest = models.CharField("身份摘要", max_length=64) + created_at = models.DateTimeField("时间", auto_now_add=True) + + class Meta: + verbose_name = "企业微信绑定审计" + verbose_name_plural = "企业微信绑定审计" diff --git a/backend/accounts/tests.py b/backend/accounts/tests.py new file mode 100644 index 0000000..e822c98 --- /dev/null +++ b/backend/accounts/tests.py @@ -0,0 +1,237 @@ +from datetime import timedelta +from concurrent.futures import ThreadPoolExecutor +from threading import Barrier +from urllib.parse import parse_qs, urlsplit +from unittest.mock import patch + +from django.core.cache import cache +from django.test import Client, TestCase, TransactionTestCase, override_settings, skipUnlessDBFeature +from django.db import close_old_connections, connections +from django.urls import reverse +from django.utils import timezone + +from . import wecom +from .models import User, WeComBinding, WeComBindingEvent, WeComLoginState + + +@override_settings(SECURE_SSL_REDIRECT=False, PUBLIC_BASE_URL="https://vpn.example.invalid", + WECOM_ENABLED=True, WECOM_CORP_ID="fixture-corp", WECOM_AGENT_ID="100001", + WECOM_SECRET="fixture-secret-not-a-real-credential", + STORAGES={"default": {"BACKEND": "django.core.files.storage.FileSystemStorage"}, + "staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"}}) +class WeComTests(TestCase): + def setUp(self): + cache.clear() + self.user = User.objects.create_user(username="wx-user", email="wx@example.invalid", + password="fixture-password", account_status="active", identity_type="external") + + def start(self, purpose="login", client=None, **extra): + client = client or self.client + response = client.post(reverse("wecom-start"), {"purpose": purpose, **extra}) + self.assertEqual(response.status_code, 302, response.content) + self.assertEqual(urlsplit(response.url).netloc, "login.work.weixin.qq.com") + query = parse_qs(urlsplit(response.url).query) + self.assertEqual(query["redirect_uri"], ["https://vpn.example.invalid/auth/wecom/callback/"]) + self.assertEqual(query["login_type"], ["CorpApp"]) + self.assertNotIn("fixture-secret", response.url) + return query["state"][0] + + def callback(self, state, identity=None, client=None): + with patch("accounts.wecom_views.wecom.identity_from_code", + return_value=identity or ("fixture-corp", "member", "person-1")) as exchange: + response = (client or self.client).get(reverse("wecom-callback"), {"state": state, "code": "one-time-code"}) + return response, exchange + + def bind(self): + self.client.force_login(self.user) + state = self.start("bind", password="fixture-password") + response, _ = self.callback(state) + self.assertEqual(response.status_code, 302) + + def test_password_binding_does_not_promote_employee_or_admin(self): + self.bind() + self.user.refresh_from_db() + self.assertEqual(self.user.identity_type, "external") + self.assertFalse(self.user.is_staff) + self.assertFalse(self.user.is_superuser) + self.assertEqual(WeComBinding.objects.get().user_id, self.user.pk) + self.assertEqual(WeComBindingEvent.objects.get().action, "bind") + + def test_bound_user_can_scan_login_and_session_is_rotated(self): + self.bind() + self.client.logout() + state = self.start() + key = self.client.session.session_key + response, _ = self.callback(state) + self.assertEqual(response.status_code, 302) + self.assertEqual(self.client.session["_auth_user_id"], str(self.user.pk)) + self.assertNotEqual(self.client.session.session_key, key) + + def test_cross_browser_and_tampered_state_never_exchange_code(self): + state = self.start() + for value, client in ((state, Client()), (state + "x", self.client)): + response, exchange = self.callback(value, client=client) + self.assertEqual(response.status_code, 400) + exchange.assert_not_called() + + def test_expired_state_and_replay_are_rejected(self): + state = self.start() + WeComLoginState.objects.update(expires_at=timezone.now() - timedelta(seconds=1)) + response, exchange = self.callback(state) + self.assertEqual(response.status_code, 400) + exchange.assert_not_called() + state = self.start() + self.assertEqual(self.callback(state)[0].status_code, 403) # Unbound, but consumed. + response, exchange = self.callback(state) + self.assertEqual(response.status_code, 400) + exchange.assert_not_called() + + def test_unbound_scan_does_not_create_or_match_account(self): + response, _ = self.callback(self.start()) + self.assertEqual(response.status_code, 403) + self.assertEqual(User.objects.count(), 1) + self.assertFalse(WeComBinding.objects.exists()) + self.assertNotIn("_auth_user_id", self.client.session) + + def test_binding_requires_correct_password(self): + self.client.force_login(self.user) + self.assertEqual(self.client.post(reverse("wecom-start"), {"purpose": "bind", "password": "wrong"}).status_code, 403) + self.assertFalse(WeComLoginState.objects.exists()) + + def test_binding_password_bruteforce_is_throttled(self): + self.client.force_login(self.user) + for _ in range(7): + self.client.post(reverse("wecom-start"), {"purpose": "bind", "password": "wrong"}) + self.assertEqual(self.client.post(reverse("wecom-start"), {"purpose": "bind", "password": "wrong"}).status_code, 429) + + def test_duplicate_identity_is_not_stolen(self): + self.bind() + other = User.objects.create_user(username="other-wx", email="other-wx@example.invalid", password="other-password") + self.client.force_login(other) + state = self.start("bind", password="other-password") + self.assertEqual(self.callback(state)[0].status_code, 409) + self.assertEqual(WeComBinding.objects.get().user_id, self.user.pk) + + def test_changed_session_user_cannot_finish_binding(self): + self.client.force_login(self.user) + state = self.start("bind", password="fixture-password") + self.client.logout() + response, exchange = self.callback(state) + self.assertIn(response.status_code, (400, 403)) + exchange.assert_not_called() + self.assertFalse(WeComBinding.objects.exists()) + + def test_suspended_departed_disabled_accounts_cannot_scan_login(self): + self.bind() + self.client.logout() + for status, active in (("suspended", True), ("departed", True), ("active", False)): + User.objects.filter(pk=self.user.pk).update(account_status=status, is_active=active) + response, _ = self.callback(self.start()) + self.assertEqual(response.status_code, 403) + self.assertNotIn("_auth_user_id", self.client.session) + + def test_open_redirects_are_discarded(self): + for target in ("https://evil.invalid", "//evil.invalid", "/\\evil.invalid", "javascript:alert(1)"): + self.start(next=target) + self.assertEqual(WeComLoginState.objects.latest("pk").next_path, "/") + + def test_disabled_integration_keeps_password_login_and_hides_button(self): + with override_settings(WECOM_ENABLED=False): + response = self.client.get(reverse("login")) + self.assertEqual(response.status_code, 200) + self.assertNotContains(response, "企业微信扫码登录") + self.assertEqual(self.client.post(reverse("wecom-start")).status_code, 503) + + def test_csrf_protects_start_and_unbind(self): + client = Client(enforce_csrf_checks=True) + client.force_login(self.user) + for route in ("wecom-start", "wecom-unbind"): + self.assertEqual(client.post(reverse(route), {"purpose": "bind", "password": "fixture-password"}).status_code, 403) + self.assertEqual(client.get(reverse(route)).status_code, 405) + + def test_unbind_requires_password_and_preserves_account(self): + self.bind() + self.assertEqual(self.client.post(reverse("wecom-unbind"), {"password": "wrong"}).status_code, 403) + self.assertTrue(WeComBinding.objects.exists()) + self.assertEqual(self.client.post(reverse("wecom-unbind"), {"password": "fixture-password"}).status_code, 302) + self.assertFalse(WeComBinding.objects.exists()) + self.assertEqual(WeComBindingEvent.objects.count(), 2) + self.user.refresh_from_db() + self.assertTrue(self.user.check_password("fixture-password")) + + def test_member_and_external_ids_are_distinct_and_no_free_role_inferred(self): + with patch("accounts.wecom._api", side_effect=[ + {"access_token": "fixture-token", "expires_in": 7200}, {"openid": "outsider"}]): + self.assertEqual(wecom.identity_from_code("valid-code"), ("fixture-corp", "external", "outsider")) + self.assertEqual(self.user.identity_type, "external") + + def test_provider_failure_consumes_state_without_login(self): + state = self.start() + with patch("accounts.wecom_views.wecom.identity_from_code", side_effect=wecom.WeComUnavailable("验证暂不可用")): + response = self.client.get(reverse("wecom-callback"), {"state": state, "code": "code"}) + self.assertEqual(response.status_code, 503) + self.assertIsNotNone(WeComLoginState.objects.get().consumed_at) + self.assertNotIn("_auth_user_id", self.client.session) + + def test_admin_and_personal_pages_render(self): + self.assertContains(self.client.get(reverse("admin:login")), "企业微信扫码登录") + self.client.force_login(self.user) + self.assertContains(self.client.get(reverse("wecom-account")), "8 元") + + def test_integration_status_requires_admin_permission_and_never_exposes_secret(self): + self.client.force_login(self.user) + self.assertEqual(self.client.get(reverse("admin-integrations")).status_code, 302) + self.user.is_staff = True + self.user.is_superuser = True + self.user.save(update_fields=["is_staff", "is_superuser"]) + response = self.client.get(reverse("admin-integrations")) + self.assertContains(response, "8 元") + self.assertNotContains(response, "fixture-secret-not-a-real-credential") + + +@skipUnlessDBFeature("has_select_for_update") +@override_settings(SECURE_SSL_REDIRECT=False, PUBLIC_BASE_URL="https://vpn.example.invalid", + WECOM_ENABLED=True, WECOM_CORP_ID="fixture-corp", WECOM_AGENT_ID="100001", WECOM_SECRET="fixture-only") +class WeComConcurrencyTests(TransactionTestCase): + def client_and_state(self, user, purpose): + client = Client() + if purpose == "bind": + client.force_login(user) + response = client.post(reverse("wecom-start"), {"purpose": purpose, "password": "fixture-password"}) + self.assertEqual(response.status_code, 302) + return client, parse_qs(urlsplit(response.url).query)["state"][0] + + def run_callbacks(self, pairs): + barrier = Barrier(len(pairs)) + def run(pair): + client, state = pair + close_old_connections() + try: + barrier.wait(timeout=8) + return client.get(reverse("wecom-callback"), {"state": state, "code": "fixture-code"}).status_code + finally: + connections.close_all() + with patch("accounts.wecom_views.wecom.identity_from_code", return_value=("fixture-corp", "member", "same-person")) as provider: + with ThreadPoolExecutor(max_workers=len(pairs)) as pool: + futures = [pool.submit(run, pair) for pair in pairs] + statuses = [future.result(timeout=25) for future in futures] + return statuses, provider.call_count + + def test_two_accounts_cannot_concurrently_claim_one_identity(self): + users = [User.objects.create_user(username=f"bind-{i}", email=f"bind-{i}@example.invalid", + password="fixture-password", account_status="active") for i in range(2)] + statuses, calls = self.run_callbacks([self.client_and_state(user, "bind") for user in users]) + self.assertEqual(sorted(statuses), [302, 409]) + self.assertEqual(calls, 2) + self.assertEqual(WeComBinding.objects.count(), 1) + self.assertEqual(WeComBindingEvent.objects.count(), 1) + + def test_same_state_can_only_exchange_code_once_across_workers(self): + user = User.objects.create_user(username="login-owner", email="login-owner@example.invalid", account_status="active") + WeComBinding.objects.create(user=user, corp_id="fixture-corp", kind="member", subject_id="same-person") + client, state = self.client_and_state(user, "login") + other = Client() + other.cookies = client.cookies.copy() + statuses, calls = self.run_callbacks([(client, state), (other, state)]) + self.assertEqual(sorted(statuses), [302, 400]) + self.assertEqual(calls, 1) diff --git a/backend/accounts/wecom.py b/backend/accounts/wecom.py new file mode 100644 index 0000000..7f77388 --- /dev/null +++ b/backend/accounts/wecom.py @@ -0,0 +1,97 @@ +"""Company Web login. Secrets and codes stay server-side; identity never grants a role.""" +import hashlib +import json +import urllib.error +import urllib.parse +import urllib.request + +from django.conf import settings +from django.core.cache import cache +from django.utils.crypto import salted_hmac + + +class WeComUnavailable(Exception): + pass + + +def configured(): + base = urllib.parse.urlsplit(settings.PUBLIC_BASE_URL) + return bool(settings.WECOM_ENABLED and settings.WECOM_CORP_ID and settings.WECOM_AGENT_ID + and settings.WECOM_SECRET and base.scheme == "https" and base.hostname + and not base.username and not base.password and not base.query and not base.fragment + and base.path in ("", "/")) + + +def authorization_url(state): + if not configured(): + raise WeComUnavailable("企业微信登录尚未配置,请使用账号密码登录。") + params = dict(login_type="CorpApp", appid=settings.WECOM_CORP_ID, + agentid=settings.WECOM_AGENT_ID, state=state, lang="zh", + redirect_uri=settings.PUBLIC_BASE_URL + "/auth/wecom/callback/") + return "https://login.work.weixin.qq.com/wwlogin/sso/login?" + urllib.parse.urlencode(params) + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + return None + + +def _api(path, parameters): + # Only fixed provider endpoints; no user-controlled host or redirects carrying secrets. + url = "https://qyapi.weixin.qq.com/cgi-bin/" + path + "?" + urllib.parse.urlencode(parameters) + opener = urllib.request.build_opener(NoRedirect(), urllib.request.ProxyHandler({})) + try: + with opener.open(url, timeout=8) as response: + raw = response.read(65537) + if len(raw) > 65536: + raise ValueError("Oversized identity response") + body = json.loads(raw) + if not isinstance(body, dict) or body.get("errcode") != 0: + raise ValueError("Provider rejected identity request") + return body + except (OSError, ValueError, TypeError, urllib.error.URLError): + # Do not expose provider URLs, tokens, response bodies or auth codes in logs. + raise WeComUnavailable("企业微信验证暂不可用或授权已过期,请重新扫码。") from None + + +def identity_from_code(code): + if not configured() or not isinstance(code, str) or not 1 <= len(code.encode()) <= 512: + raise WeComUnavailable("企业微信授权无效,请重新扫码。") + token_key = "wecom-token:" + salted_hmac("wecom-config", settings.WECOM_CORP_ID + settings.WECOM_SECRET).hexdigest() + token = cache.get(token_key) + if not token: + body = _api("gettoken", {"corpid": settings.WECOM_CORP_ID, "corpsecret": settings.WECOM_SECRET}) + token = body.get("access_token") + if not isinstance(token, str) or not token: + raise WeComUnavailable("企业微信应用凭据不可用。") + try: + lifetime = int(body.get("expires_in", 7200)) + except (TypeError, ValueError): + raise WeComUnavailable("企业微信应用凭据返回异常。") from None + cache.set(token_key, token, max(1, min(lifetime, 7200) - 120)) + try: + body = _api("auth/getuserinfo", {"access_token": token, "code": code}) + except WeComUnavailable: + cache.delete(token_key) + raise + # userid is a company member. openid alone must NEVER qualify as an employee. + kind, subject = ("member", body.get("userid")) if body.get("userid") else ("external", body.get("openid")) + if not isinstance(subject, str) or not 1 <= len(subject) <= 128 or subject.strip() != subject: + raise WeComUnavailable("未取得可绑定的企业微信身份。") + if body.get("corpid", settings.WECOM_CORP_ID) != settings.WECOM_CORP_ID: + raise WeComUnavailable("企业微信身份不属于当前配置的企业。") + return settings.WECOM_CORP_ID, kind, subject + + +def identity_digest(identity): + return salted_hmac("wecom-binding-audit", json.dumps(identity), algorithm="sha256").hexdigest() + + +def state_digest(value): + return hashlib.sha256(value.encode()).hexdigest() + + +def session_digest(request): + if not request.session.session_key: + request.session.create() + return salted_hmac("wecom-session", request.session.session_key, algorithm="sha256").hexdigest() diff --git a/backend/accounts/wecom_views.py b/backend/accounts/wecom_views.py new file mode 100644 index 0000000..f44d6d5 --- /dev/null +++ b/backend/accounts/wecom_views.py @@ -0,0 +1,169 @@ +import secrets +from datetime import timedelta + +from django.contrib import messages +from django.contrib.auth import login +from django.contrib.auth.decorators import login_required +from django.contrib.auth.decorators import permission_required +from django.contrib.admin.views.decorators import staff_member_required +from django.db import IntegrityError, transaction +from django.http import HttpResponse +from django.conf import settings +from django.shortcuts import redirect, render +from django.utils import timezone +from django.utils.http import url_has_allowed_host_and_scheme +from django.views.decorators.cache import never_cache +from django.views.decorators.debug import sensitive_post_parameters, sensitive_variables +from django.views.decorators.http import require_GET, require_POST + +from . import wecom +from .models import User, WeComBinding, WeComBindingEvent, WeComLoginState + + +def denied(message, status=400): + response = HttpResponse(message, status=status, content_type="text/plain; charset=utf-8") + response["Cache-Control"] = "no-store" + response["Referrer-Policy"] = "no-referrer" + return response + + +def allowed_account(user): + return user.is_active and user.account_status not in (User.AccountStatus.SUSPENDED, User.AccountStatus.DEPARTED) + + +@never_cache +@require_POST +@sensitive_post_parameters("password") +def start(request): + if not wecom.configured(): + return denied("企业微信登录尚未配置,请先使用账号密码。", 503) + purpose = request.POST.get("purpose", "login") + if purpose not in ("login", "bind"): + return denied("无效操作。") + user = request.user + if purpose == "bind": + if not user.is_authenticated or not allowed_account(user): + return denied("请先登录有效的平台账号。", 403) + if not user.has_usable_password() or not user.check_password(request.POST.get("password", "")): + return denied("请验证当前平台密码后再绑定。", 403) + elif user.is_authenticated: + return redirect("portal-dashboard") + digest = wecom.session_digest(request) + now = timezone.now() + if WeComLoginState.objects.filter(session_digest=digest, created_at__gt=now - timedelta(minutes=5)).count() >= 10: + return denied("扫码请求过于频繁,请稍后再试。", 429) + next_path = request.POST.get("next", "/") + if (len(next_path) > 512 or not next_path.startswith("/") or "\\" in next_path + or not url_has_allowed_host_and_scheme(next_path, allowed_hosts=set(), require_https=True)): + next_path = "/" + state = secrets.token_urlsafe(32) + WeComLoginState.objects.create(digest=wecom.state_digest(state), session_digest=digest, + purpose=purpose, user=user if purpose == "bind" else None, + expires_at=now + timedelta(minutes=5), next_path=next_path) + return redirect(wecom.authorization_url(state)) + + +@never_cache +@require_GET +@sensitive_variables() +def callback(request): + raw_state = request.GET.get("state", "") + if not wecom.configured() or not 20 <= len(raw_state) <= 128 or not request.session.session_key: + return denied("扫码会话无效,请从本站重新扫码。") + state = WeComLoginState.objects.filter(digest=wecom.state_digest(raw_state), + session_digest=wecom.session_digest(request), consumed_at__isnull=True, + expires_at__gt=timezone.now()).first() + if not state: + return denied("扫码会话已过期或已使用,请重新扫码。") + if state.purpose == "bind" and (not request.user.is_authenticated or state.user_id != request.user.pk): + return denied("绑定账号已变化,请重新登录后绑定。", 403) + if state.purpose == "login" and request.user.is_authenticated: + return denied("当前已有登录账号,请先退出后再扫码。", 409) + # Atomic consume across workers: session pop alone is insufficient for simultaneous callbacks. + if WeComLoginState.objects.filter(pk=state.pk, consumed_at__isnull=True, + expires_at__gt=timezone.now()).update(consumed_at=timezone.now()) != 1: + return denied("扫码会话已使用,请重新扫码。") + try: + identity = wecom.identity_from_code(request.GET.get("code", "")) + except wecom.WeComUnavailable as exc: + return denied(str(exc), 503) + corp, kind, subject = identity + try: + with transaction.atomic(): + if state.purpose == "bind": + user = User.objects.select_for_update().get(pk=state.user_id) + if not allowed_account(user): + return denied("账号已停用,不能绑定。", 403) + existing = WeComBinding.objects.filter(user=user).first() + if existing and (existing.corp_id, existing.kind, existing.subject_id) != identity: + return denied("该平台账号已绑定其他身份,请先验证密码解绑。", 409) + if not existing: + WeComBinding.objects.create(user=user, corp_id=corp, kind=kind, subject_id=subject) + WeComBindingEvent.objects.create(user=user, action="bind", identity_digest=wecom.identity_digest(identity)) + # No name/email matching, account merging or promotion of identity_type/is_staff. + messages.success(request, "企业微信已绑定;员工身份与套餐仍按后台审核结果执行。") + return redirect("wecom-account") + candidate = WeComBinding.objects.filter(corp_id=corp, kind=kind, subject_id=subject).first() + if not candidate: + return denied("此企业微信尚未绑定平台账号。请先使用密码登录,在个人绑定页面完成绑定。", 403) + user = User.objects.select_for_update().get(pk=candidate.user_id) + binding = WeComBinding.objects.select_for_update().filter(pk=candidate.pk, + corp_id=corp, kind=kind, subject_id=subject).first() + if not binding or not allowed_account(user): + return denied("绑定已失效或平台账号已停用。", 403) + binding.last_login_at = timezone.now() + binding.save(update_fields=["last_login_at"]) + login(request, user, backend="django.contrib.auth.backends.ModelBackend") + except IntegrityError: + return denied("该企业微信身份已绑定其他账号,不能重复绑定。", 409) + response = redirect(state.next_path) + response["Referrer-Policy"] = "no-referrer" + return response + + +@login_required +@never_cache +@require_GET +def account(request): + return render(request, "registration/wecom_account.html", { + "binding": WeComBinding.objects.filter(user=request.user).first(), + "wecom_available": wecom.configured(), + }) + + +@login_required +@never_cache +@require_POST +@sensitive_post_parameters("password") +def unbind(request): + with transaction.atomic(): + user = User.objects.select_for_update().get(pk=request.user.pk) + if not allowed_account(user) or not user.has_usable_password() or not user.check_password(request.POST.get("password", "")): + return denied("请验证有效账号的当前密码后再解绑。", 403) + binding = WeComBinding.objects.select_for_update().filter(user=user).first() + if binding: + WeComBindingEvent.objects.create(user=user, action="unbind", + identity_digest=wecom.identity_digest((binding.corp_id, binding.kind, binding.subject_id))) + binding.delete() + WeComLoginState.objects.filter(user=user, consumed_at__isnull=True).update(consumed_at=timezone.now()) + messages.success(request, "企业微信已解绑。平台密码、套餐和配置保持不变。") + return redirect("wecom-account") + + +@staff_member_required +@permission_required("accounts.view_wecombinding", raise_exception=True) +@never_cache +@require_GET +def integrations(request): + from control.models import Plan, PlanApplication + return render(request, "admin/wecom_integrations.html", { + "title": "企业微信与套餐收款", "wecom_available": wecom.configured(), + "binding_count": WeComBinding.objects.count(), + "callback_url": settings.PUBLIC_BASE_URL + "/auth/wecom/callback/", + "config_checks": [("启用开关", settings.WECOM_ENABLED), + ("企业 CorpID", bool(settings.WECOM_CORP_ID)), + ("应用 AgentID", bool(settings.WECOM_AGENT_ID)), + ("应用 Secret(仅服务端)", bool(settings.WECOM_SECRET))], + "monthly_plan": Plan.objects.filter(slug="monthly-1024g").first(), + "pending_applications": PlanApplication.objects.filter(status="pending").count(), + }) diff --git a/backend/control/__init__.py b/backend/control/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/backend/control/__init__.py @@ -0,0 +1 @@ + diff --git a/backend/control/admin.py b/backend/control/admin.py new file mode 100644 index 0000000..ec78094 --- /dev/null +++ b/backend/control/admin.py @@ -0,0 +1,421 @@ +from django.contrib import admin, messages +from django.core.exceptions import ValidationError +from django.utils.html import format_html + +from .models import ( + ClientSession, + Device, + LearnedRouteRule, + Node, + NodeDeployment, + NodeTrafficSample, + Plan, + PlanCatalogDraft, + Team, + TeamMembership, + TeamAuditEvent, + PlanApplication, + RouteObservation, + RoutingPolicy, + Subscription, + UsageRecord, + VpnAiFinding, + VpnAiRuntime, +) + + +@admin.register(Plan) +class PlanAdmin(admin.ModelAdmin): + list_display = ("name", "audience", "employee_benefit", "price_cny", "traffic_limit_gb", "billing_months", "duration_days", "online_payment_required", "device_limit", "active") + list_filter = ("audience", "employee_benefit", "online_payment_required", "active") + search_fields = ("name", "slug", "description") + prepopulated_fields = {"slug": ("name",)} + ordering = ("sort_order", "price_cny") + + +@admin.register(PlanCatalogDraft) +class PlanCatalogDraftAdmin(admin.ModelAdmin): + list_display = ("name", "scope", "display_quota", "display_price", "member_limit", "device_limit", "concurrent_limit", "publication_state") + list_filter = ("scope",) + search_fields = ("name", "slug", "description") + readonly_fields = ("publication_state", "created_at", "updated_at") + fieldsets = ( + ("未上架的商业草案", {"fields": ("publication_state", "name", "slug", "scope", "traffic_limit_gb", "price_cny"), + "description": "这里只编辑草稿,不展示给客户、不产生订单、不修改现有套餐或订阅。团队成员共享账本尚未接入;不可用个人订阅代替团队共享。"}), + ("使用范围", {"fields": ("member_limit", "device_limit", "concurrent_limit", "description", "sort_order"), + "description": "无限流量仅指不设代理流量总额;带宽、设备及并发规则仍须确认。只有本公司的已核实内部员工免费,外部团队成员不自动免单。"}), + ("记录", {"fields": ("created_at", "updated_at")}), + ) + + @admin.display(description="流量档位") + def display_quota(self, obj): + return obj.quota_label + + @admin.display(description="月价") + def display_price(self, obj): + return obj.price_label + + @admin.display(description="上架状态") + def publication_state(self, obj): + return "仅草稿 · 未上架 · 不收款" + + +@admin.register(Team) +class TeamAdmin(admin.ModelAdmin): + list_display = ("name", "owner", "active", "plan_draft", "setup_member_limit", "package_state") + search_fields = ("name", "owner__username") + list_filter = ("active",) + readonly_fields = ("package_state",) + + def get_readonly_fields(self, request, obj=None): + return (*self.readonly_fields, "owner") if obj else self.readonly_fields + + def has_delete_permission(self, request, obj=None): + return False + + def save_model(self, request, obj, form, change): + super().save_model(request, obj, form, change) + TeamAuditEvent.objects.create(team=obj, actor=request.user, action="platform_configured") + + +@admin.register(TeamMembership) +class TeamMembershipAdmin(admin.ModelAdmin): + list_display = ("team", "user", "role", "status", "invited_by") + list_filter = ("role", "status") + + def has_add_permission(self, request): + return False + + def has_change_permission(self, request, obj=None): + return False + + def has_delete_permission(self, request, obj=None): + return False + + +@admin.register(TeamAuditEvent) +class TeamAuditEventAdmin(admin.ModelAdmin): + list_display = ("team", "actor", "subject", "action", "created_at") + list_filter = ("action",) + + def has_add_permission(self, request): + return False + + def has_change_permission(self, request, obj=None): + return False + + def has_delete_permission(self, request, obj=None): + return False + + +@admin.register(RoutingPolicy) +class RoutingPolicyAdmin(admin.ModelAdmin): + list_display = ("name", "is_global", "active", "updated_at") + list_filter = ("is_global", "active") + search_fields = ("name", "description") + + +@admin.register(Node) +class NodeAdmin(admin.ModelAdmin): + list_display = ("name", "region", "server", "port", "protocol", "status", "fallback_only", "subscription_enabled", "last_seen_at") + list_filter = ("protocol", "status", "active", "subscription_enabled", "region", "office_access_scope") + search_fields = ("name", "slug", "server", "region") + prepopulated_fields = {"slug": ("name",)} + readonly_fields = ("last_seen_at", "agent_version", "total_upload_bytes", "total_download_bytes", "created_at", "updated_at") + fieldsets = ( + ("基本信息", {"fields": ("name", "slug", "region", "server", "port", "protocol", "status", "active", "subscription_enabled", "sort_order", "fallback_only")}), + ("协议参数", {"fields": ("sni", "reality_public_key", "reality_short_id", "flow", "transport", "client_fingerprint", "skip_cert_verify")}), + ("办公室权限(接入验证中)", {"fields": ("office_only", "office_access_scope", "office_users"), "description": "公司网络模式依据当前接入的登记站点,不按人员所属办公室判断;白名单字段仅供保留原白名单模式使用。两种模式都只是验证候选,尚不进入普通订阅或自动调度;真实站点验证及加密入口通过前不得上线。"}), + ("运行状态", {"fields": ("last_seen_at", "agent_version", "total_upload_bytes", "total_download_bytes", "created_at", "updated_at")}), + ) + + +class DeviceInline(admin.TabularInline): + model = Device + extra = 0 + readonly_fields = ("device_id", "last_seen_at", "upload_bytes", "download_bytes", "created_at") + + +class NodeDeploymentInline(admin.TabularInline): + model = NodeDeployment + extra = 0 + can_delete = False + readonly_fields = ("node", "deployed", "applied_at", "revoked_at", "last_error", "updated_at") + + +@admin.action(description="开通所选订阅") +def activate_subscriptions(modeladmin, request, queryset): + success = 0 + for subscription in queryset: + try: + subscription.activate() + success += 1 + except ValidationError as exc: + modeladmin.message_user(request, f"{subscription}: {exc}", level=messages.ERROR) + if success: + modeladmin.message_user(request, f"已开通 {success} 个订阅。", level=messages.SUCCESS) + + +@admin.action(description="暂停所选订阅") +def suspend_subscriptions(modeladmin, request, queryset): + for subscription in queryset: + subscription.suspend(reason="管理员暂停") + + +@admin.action(description="取消并撤销所选订阅") +def cancel_subscriptions(modeladmin, request, queryset): + for subscription in queryset: + subscription.cancel(reason="管理员取消") + + +@admin.action(description="重置订阅地址") +def rotate_subscription_tokens(modeladmin, request, queryset): + for subscription in queryset: + subscription.rotate_subscription() + + +@admin.register(Subscription) +class SubscriptionAdmin(admin.ModelAdmin): + list_display = ("user", "plan", "status", "usage_summary", "expires_at", "route_mode", "provisioning_state") + list_filter = ("status", "plan", "route_mode", "provisioning_state") + search_fields = ("user__username", "user__display_name", "user__email", "credential_uuid") + autocomplete_fields = ("user", "plan", "routing_policy", "allowed_nodes") + filter_horizontal = ("allowed_nodes",) + readonly_fields = ( + "credential_uuid", + "subscription_link", + "upload_bytes", + "download_bytes", + "created_at", + "updated_at", + ) + actions = (activate_subscriptions, suspend_subscriptions, cancel_subscriptions, rotate_subscription_tokens) + inlines = (DeviceInline, NodeDeploymentInline) + fieldsets = ( + ("订阅", {"fields": ("user", "plan", "status", "starts_at", "expires_at", "state_reason")}), + ("额度", {"fields": ("traffic_limit_bytes", "upload_bytes", "download_bytes", "device_limit")}), + ("路由与节点", {"fields": ("route_mode", "routing_policy", "allowed_nodes")}), + ("下发与凭据", {"fields": ("provisioning_state", "credential_uuid", "subscription_link")}), + ("审计", {"fields": ("created_at", "updated_at"), "classes": ("collapse",)}), + ) + + @admin.display(description="流量") + def usage_summary(self, obj): + used_gb = obj.used_bytes / 1024**3 + if obj.traffic_limit_bytes: + return f"{used_gb:.2f} / {obj.traffic_limit_bytes / 1024**3:.0f} GB" + return f"{used_gb:.2f} GB / 不限" + + @admin.display(description="订阅地址") + def subscription_link(self, obj): + if not obj.pk: + return "保存后生成" + return format_html('打开订阅', obj.subscription_url) + + +@admin.action(description="批准所选申请") +def approve_applications(modeladmin, request, queryset): + success = 0 + for application in queryset: + try: + application.approve(request.user) + success += 1 + except ValidationError as exc: + modeladmin.message_user(request, f"{application}: {exc}", level=messages.ERROR) + if success: + modeladmin.message_user(request, f"已批准并开通 {success} 个申请。", level=messages.SUCCESS) + + +@admin.action(description="拒绝所选申请") +def reject_applications(modeladmin, request, queryset): + queryset.filter(status=PlanApplication.Status.PENDING).update(status=PlanApplication.Status.REJECTED) + + +@admin.register(PlanApplication) +class PlanApplicationAdmin(admin.ModelAdmin): + list_display = ("user", "plan", "status", "payment_status", "subscription", "created_at", "reviewed_by") + list_filter = ("status", "payment_status", "plan") + search_fields = ("user__username", "user__display_name", "user__email", "note") + autocomplete_fields = ("user", "plan", "reviewed_by") + readonly_fields = ("status", "subscription", "reviewed_by", "reviewed_at", "created_at", "updated_at") + actions = (approve_applications, reject_applications) + + +@admin.register(UsageRecord) +class UsageRecordAdmin(admin.ModelAdmin): + list_display = ("day", "subscription", "node", "upload_gb", "download_gb", "total_gb") + list_filter = ("day", "node") + search_fields = ("subscription__user__username", "subscription__user__display_name", "node__name") + autocomplete_fields = ("subscription", "node") + date_hierarchy = "day" + + @admin.display(description="上传 GB") + def upload_gb(self, obj): + return f"{obj.upload_bytes / 1024**3:.3f}" + + @admin.display(description="下载 GB") + def download_gb(self, obj): + return f"{obj.download_bytes / 1024**3:.3f}" + + @admin.display(description="合计 GB") + def total_gb(self, obj): + return f"{(obj.upload_bytes + obj.download_bytes) / 1024**3:.3f}" + + +@admin.register(NodeTrafficSample) +class NodeTrafficSampleAdmin(admin.ModelAdmin): + list_display = ( + "sampled_at", "node", "upload_speed", "download_speed", + "active_subscriptions", "interval_seconds", + ) + list_filter = ("node", "sampled_at") + readonly_fields = ( + "node", "report", "sampled_at", "interval_seconds", "upload_bytes", "download_bytes", + "upload_bytes_per_second", "download_bytes_per_second", "active_subscriptions", + ) + date_hierarchy = "sampled_at" + + @admin.display(description="上传 Mbps") + def upload_speed(self, obj): + return f"{obj.upload_bytes_per_second * 8 / 1_000_000:.3f}" + + @admin.display(description="下载 Mbps") + def download_speed(self, obj): + return f"{obj.download_bytes_per_second * 8 / 1_000_000:.3f}" + + def has_add_permission(self, request): + return False + + def has_change_permission(self, request, obj=None): + return False + + +@admin.register(Device) +class DeviceAdmin(admin.ModelAdmin): + list_display = ("name", "device_id", "subscription", "platform", "active", "last_seen_at") + list_filter = ("active", "platform") + search_fields = ("name", "device_id", "subscription__user__username") + autocomplete_fields = ("subscription",) + + +@admin.register(ClientSession) +class ClientSessionAdmin(admin.ModelAdmin): + list_display = ("subscription", "device", "created_at", "last_seen_at", "expires_at", "revoked_at") + list_filter = ("created_at", "expires_at", "revoked_at") + search_fields = ("subscription__user__username", "subscription__user__display_name", "device__name", "device__device_id") + readonly_fields = ("subscription", "device", "token_digest", "created_at", "last_seen_at", "expires_at", "revoked_at") + + +@admin.register(NodeDeployment) +class NodeDeploymentAdmin(admin.ModelAdmin): + list_display = ("subscription", "node", "deployed", "applied_at", "revoked_at", "updated_at") + list_filter = ("deployed", "node") + search_fields = ("subscription__user__username", "node__name", "last_error") + readonly_fields = ("subscription", "node", "deployed", "applied_at", "revoked_at", "last_error", "updated_at") + + +@admin.register(RouteObservation) +class RouteObservationAdmin(admin.ModelAdmin): + list_display = ("target", "port", "access_kind", "network", "outcome", "failure_kind", "device", "node", "received_at") + list_filter = ("access_kind", "target_type", "network", "outcome", "failure_kind", "node", "received_at") + search_fields = ("target", "device__name", "device__device_id", "subscription__user__username") + readonly_fields = ( + "report_id", "subscription", "device", "node", "target_type", "target", "port", "access_kind", "network", + "outcome", "failure_kind", "client_version", "received_at", + ) + date_hierarchy = "received_at" + + def has_add_permission(self, request): + return False + + def has_change_permission(self, request, obj=None): + return False + + +@admin.action(description="启用为公司智能路由") +def activate_learned_rules(modeladmin, request, queryset): + queryset.update( + status=LearnedRouteRule.Status.ACTIVE, + source=LearnedRouteRule.Source.MANUAL, + manually_locked=True, + ) + + +@admin.action(description="禁用并锁定所选 AI 路由") +def disable_learned_rules(modeladmin, request, queryset): + queryset.update(status=LearnedRouteRule.Status.DISABLED, manually_locked=True) + + +@admin.action(description="交还 vpn-ai 自动管理") +def unlock_learned_rules(modeladmin, request, queryset): + queryset.update(manually_locked=False) + + +@admin.register(LearnedRouteRule) +class LearnedRouteRuleAdmin(admin.ModelAdmin): + list_display = ( + "target", "target_type", "match_mode", "source", "status", "confidence", + "distinct_devices", "failure_reports", "valid_until", "manually_locked", + ) + list_filter = ("source", "status", "target_type", "match_mode", "manually_locked", "valid_until") + search_fields = ("target", "reason") + readonly_fields = ("confidence", "failure_reports", "proxy_success_reports", "distinct_devices", "reason", "first_seen_at", "last_evaluated_at", "updated_at") + actions = (activate_learned_rules, disable_learned_rules, unlock_learned_rules) + + def has_add_permission(self, request): + return False + + def save_model(self, request, obj, form, change): + if not change and obj.source == LearnedRouteRule.Source.AI: + obj.source = LearnedRouteRule.Source.MANUAL + obj.manually_locked = True + super().save_model(request, obj, form, change) + + +@admin.action(description="将所选诊断标记为已忽略") +def ignore_ai_findings(modeladmin, request, queryset): + queryset.update(status=VpnAiFinding.Status.IGNORED) + + +@admin.register(VpnAiFinding) +class VpnAiFindingAdmin(admin.ModelAdmin): + list_display = ("title", "category", "severity", "status", "last_seen_at") + list_filter = ("category", "severity", "status", "last_seen_at") + search_fields = ("title", "summary", "fingerprint") + readonly_fields = ("fingerprint", "category", "severity", "title", "summary", "evidence", "first_seen_at", "last_seen_at", "resolved_at") + actions = (ignore_ai_findings,) + + def has_add_permission(self, request): + return False + + +@admin.register(VpnAiRuntime) +class VpnAiRuntimeAdmin(admin.ModelAdmin): + change_list_template = "admin/control/vpnairuntime/change_list.html" + list_display = ("service_name", "health_label", "version", "last_heartbeat_at", "last_cycle_at", "cycle_count", "active_rules", "open_findings") + readonly_fields = ( + "service_name", "version", "worker_id", "started_at", "last_heartbeat_at", "last_cycle_at", + "cycle_count", "observations_7d", "active_rules", "open_findings", "last_error", "updated_at", "dispatch_snapshot", + ) + + @admin.display(description="运行状态") + def health_label(self, obj): + return "正常" if obj.is_healthy else "心跳异常" + + def has_add_permission(self, request): + return False + + def has_delete_permission(self, request, obj=None): + return False + + def changelist_view(self, request, extra_context=None): + runtime = VpnAiRuntime.objects.first() + from .learning import learning_summary + extra_context = { + **(extra_context or {}), + "vpn_ai_runtime": runtime, + "learning": learning_summary(), + "recent_findings": VpnAiFinding.objects.select_related().all()[:8], + "recent_rules": LearnedRouteRule.objects.all()[:8], + } + return super().changelist_view(request, extra_context=extra_context) diff --git a/backend/control/approval_audit.py b/backend/control/approval_audit.py new file mode 100644 index 0000000..816911e --- /dev/null +++ b/backend/control/approval_audit.py @@ -0,0 +1,67 @@ +"""Read-only deployment preflight; never approves, backfills or grants access.""" +from django.db import connections +from django.db.models import Count, F, Q + +from control.models import PlanApplication, Subscription + + +def audit_plan_approvals(*, using="default", sample_limit=50): + if not 1 <= sample_limit <= 1000: + raise ValueError("sample_limit must be between 1 and 1000") + connection = connections[using] + with connection.cursor() as cursor: + columns = connection.introspection.get_table_description(cursor, PlanApplication._meta.db_table) + has_link = "subscription_id" in {column.name for column in columns} + applications = PlanApplication.objects.using(using).order_by() + subscriptions = Subscription.objects.using(using).order_by() + findings = [] + + def record(code, rows, fields, *, level="attention"): + count = rows.count() + if count: + findings.append({"code": code, "level": level, "count": count, + "samples": list(rows.order_by(*fields).values(*fields)[:sample_limit]), + "samples_truncated": count > sample_limit}) + + open_statuses = [Subscription.Status.PENDING, Subscription.Status.ACTIVE, Subscription.Status.SUSPENDED] + duplicate_open = subscriptions.filter(status__in=open_statuses).values("user_id").annotate(total=Count("pk")).filter(total__gt=1) + duplicate_pending = applications.filter(status=PlanApplication.Status.PENDING).values("user_id").annotate(total=Count("pk")).filter(total__gt=1) + record("multiple_open_subscriptions", duplicate_open, ["user_id"], level="blocker") + record("multiple_pending_applications", duplicate_pending, ["user_id"]) + pending = applications.filter(status=PlanApplication.Status.PENDING) + stopped_accounts = pending.filter( + Q(user__is_active=False) | ~Q(user__account_status__in=["pending", "active"]) + ) + record("pending_account_no_longer_eligible", stopped_accounts, ["id", "user_id", "plan_id"]) + ineligible = pending.filter( + Q(plan__active=False) + | (~Q(plan__audience="all") & ~Q(plan__audience=F("user__identity_type"))) + | (Q(plan__employee_benefit=True) & ~Q(user__identity_type="employee")) + ) + record("pending_plan_no_longer_eligible", ineligible, ["id", "user_id", "plan_id"]) + approved = applications.filter(status=PlanApplication.Status.APPROVED) + # Explicit values/count queries work on both pre-0008 and post-0008 schemas: + # never instantiate the current model when the new column is absent. + unlinked = approved.filter(subscription_id__isnull=True) if has_link else approved + record("legacy_approved_application_without_link", unlinked, ["id", "user_id", "plan_id"]) + linked_count = 0 + if has_link: + linked = applications.filter(subscription_id__isnull=False) + linked_count = linked.count() + record("subscription_belongs_to_another_user", linked.exclude(user_id=F("subscription__user_id")), + ["id", "user_id", "subscription_id"], level="blocker") + record("unapproved_application_has_subscription_link", linked.exclude(status=PlanApplication.Status.APPROVED), + ["id", "user_id", "subscription_id"], level="blocker") + return { + "kind": "read_only_plan_approval_preflight", "database_modified": False, + "data_scope": "IDs and counts only; no names, email, credentials or subscription tokens", + "consistency": "Point-in-time query observations; rerun with approval writes paused before deployment", + "subscription_link_column_present": has_link, "migration_0008_required": not has_link, + "counts": {"applications": applications.count(), "pending": pending.count(), + "subscriptions": subscriptions.count(), "linked_applications": linked_count}, + "schema_rollback_would_drop_link_count": linked_count, + "schema_rollback_requires_link_backup": linked_count > 0, + "findings": findings, "review_required": bool(findings), + "automatic_repair_performed": False, + "deployment_approved": False, + } diff --git a/backend/control/apps.py b/backend/control/apps.py new file mode 100644 index 0000000..e0b71cc --- /dev/null +++ b/backend/control/apps.py @@ -0,0 +1,11 @@ +from django.apps import AppConfig + + +class ControlConfig(AppConfig): + default_auto_field = "django.db.models.BigAutoField" + name = "control" + verbose_name = "VPN 服务" + + def ready(self): + from . import signals # noqa: F401 + diff --git a/backend/control/context_processors.py b/backend/control/context_processors.py new file mode 100644 index 0000000..4933ff2 --- /dev/null +++ b/backend/control/context_processors.py @@ -0,0 +1,10 @@ +from django.conf import settings +from accounts.wecom import configured + + +def platform_settings(request): + return { + "PLATFORM_NAME": "优创·纵横家", + "PUBLIC_BASE_URL": settings.PUBLIC_BASE_URL, + "WECOM_AVAILABLE": configured(), + } diff --git a/backend/control/dispatch.py b/backend/control/dispatch.py new file mode 100644 index 0000000..5f9249a --- /dev/null +++ b/backend/control/dispatch.py @@ -0,0 +1,77 @@ +"""vpn-ai's bounded, telemetry-driven dispatcher; never moves a healthy live stream. + +Traffic is an EWMA of real reports. Recent session reservations smooth arrivals +between report intervals; they are NOT presented as measured TCP connections. +""" +from datetime import timedelta + +from django.db import transaction +from django.db.models import Count +from django.utils import timezone + +from .models import ClientSession, Node, NodeTrafficSample, VpnAiRuntime + +FRESHNESS = timedelta(minutes=3) +RESERVATION_BYTES_PER_SECOND = 128 * 1024 + + +def build_dispatch_snapshot(now=None): + now = now or timezone.now() + reservations = dict(ClientSession.objects.filter( + assigned_node__isnull=False, revoked_at__isnull=True, + expires_at__gt=now, last_seen_at__gte=now - timedelta(minutes=5), + ).values("assigned_node_id").annotate(total=Count("device_id", distinct=True)).values_list("assigned_node_id", "total")) + items = [] + for node in Node.objects.filter(active=True, subscription_enabled=True, protocol=Node.Protocol.VLESS_REALITY): + samples = list(NodeTrafficSample.objects.filter(node=node, sampled_at__gte=now-FRESHNESS).order_by("-sampled_at")[:3]) + rate = None + for sample in reversed(samples): + measured = sample.upload_bytes_per_second + sample.download_bytes_per_second + rate = measured if rate is None else 0.5 * measured + 0.5 * rate + healthy = bool(node.status == Node.Status.ONLINE and node.last_seen_at and node.last_seen_at >= now-FRESHNESS) + items.append({ + "id": node.pk, "slug": node.slug, "name": node.name, + "healthy": healthy, "fallback_only": node.fallback_only, + "rate_bps": round(rate) if rate is not None else None, + "rate_text": f"{rate / 1024:.1f} KB/s" if rate is not None else "暂无新鲜采样", + "reservations": reservations.get(node.pk, 0), + "reason": "心跳过期或节点停用" if not healthy else ("最终备用" if node.fallback_only else "正常参与负载调度"), + }) + return {"algorithm": "load-ewma-v1", "generated_at": now.isoformat(), "nodes": items, + "health_scope": "agent_heartbeat_not_end_to_end", + "policy": "启用的主节点按近期吞吐与会话预留分配;当前连接保持;仅标记为备用的节点在主池不可用时参与,不按国家判定。在线心跳不代表端到端出口已验证。"} + + +@transaction.atomic +def choose_node(session, excluded=(), new_connection=False): + # Lock one small shared row to serialize concurrent reservations. Never + # change account/node status on the strength of one client's failure. + runtime, _ = VpnAiRuntime.objects.get_or_create(service_name="vpn-ai") + VpnAiRuntime.objects.select_for_update().get(pk=runtime.pk) + session = ClientSession.objects.select_for_update().get(pk=session.pk) + now = timezone.now() + snapshot = build_dispatch_snapshot(now) + telemetry = {item["id"]: item for item in snapshot["nodes"]} + allowed = list(session.subscription.nodes_for_subscription().filter(protocol=Node.Protocol.VLESS_REALITY).exclude(slug__in=list(excluded)[:32])) + healthy = [node for node in allowed if telemetry.get(node.pk, {}).get("healthy")] + if not healthy: + return None, {"reason": "没有心跳正常且属于本订阅的可用节点。"} + current = next((node for node in healthy if node.pk == session.assigned_node_id), None) + if current and not new_connection: + return current, {**session.dispatch_decision, "sticky": True} + primary = [node for node in healthy if not node.fallback_only] + pool = primary or healthy + def score(node): + item = telemetry[node.pk] + # Unknown throughput is not zero. Prefer measured primary nodes, but + # an unmeasured healthy primary still precedes any emergency reserve. + rate = item["rate_bps"] + return (rate is None, (rate or 0) + item["reservations"] * RESERVATION_BYTES_PER_SECOND, node.sort_order, node.pk) + node = min(pool, key=score) + decision = {"at": now.isoformat(), "algorithm": snapshot["algorithm"], "sticky": False, + "reason": "主节点不可用,启用最终备用" if not primary else "主节点中按近期吞吐和会话预留分配", + "rate_bps": telemetry[node.pk]["rate_bps"], "reservations": telemetry[node.pk]["reservations"]} + session.assigned_node = node + session.dispatch_decision = decision + session.save(update_fields=["assigned_node", "dispatch_decision"]) + return node, decision diff --git a/backend/control/forms.py b/backend/control/forms.py new file mode 100644 index 0000000..e05047d --- /dev/null +++ b/backend/control/forms.py @@ -0,0 +1,35 @@ +from django import forms + +from .models import Plan, PlanApplication + + +class PlanApplicationForm(forms.ModelForm): + class Meta: + model = PlanApplication + fields = ("plan", "note") + labels = {"note": "申请说明(可选)"} + widgets = {"note": forms.Textarea(attrs={"rows": 4, "placeholder": "请填写使用需求或员工信息"})} + + def __init__(self, *args, user=None, **kwargs): + super().__init__(*args, **kwargs) + self.user = user + plans = Plan.objects.filter(active=True) + if user and user.identity_type == "employee": + plans = plans.filter(audience__in=[Plan.Audience.EMPLOYEE, Plan.Audience.ALL]) + else: + plans = plans.filter(audience__in=[Plan.Audience.EXTERNAL, Plan.Audience.ALL], employee_benefit=False) + self.fields["plan"].queryset = plans.order_by("sort_order", "price_cny") + self.fields["plan"].label_from_instance = lambda plan: plan.application_label(user) + self.fields["plan"].help_text = "内部员工核实身份并审核后免费开通;标注“暂未开放付款”的套餐仅登记申请,不扣款、不立即开通付费服务。" + + def save(self, commit=True): + application = super().save(commit=False) + application.user = self.user + application.payment_status = ( + PlanApplication.PaymentStatus.NOT_REQUIRED + if application.plan.price_for_user(self.user) == 0 + else PlanApplication.PaymentStatus.UNPAID + ) + if commit: + return PlanApplication.submit(user=self.user, plan=application.plan, note=application.note) + return application diff --git a/backend/control/git_releases.py b/backend/control/git_releases.py new file mode 100644 index 0000000..5704f73 --- /dev/null +++ b/backend/control/git_releases.py @@ -0,0 +1,104 @@ +"""Read-only compatibility bridge for old desktop update clients. + +Company Git is the sole authority and byte download origin. No local installer, +platform release manifest, client token, proxy credential, or redirected origin +is used. New clients contact Git directly and do not need this bridge. +""" +import json +import re +import urllib.error +import urllib.request + +from django.core.cache import cache + + +ORIGIN = "https://pro.ucvl.cn" +REPOSITORY = "/admin/ucvl-software-downloads" +RELEASES_API = f"{ORIGIN}/api/v1/repos{REPOSITORY}/releases?limit=50" +CACHE_KEY = "ucvl:git-windows-release:v1" +TAG = re.compile(r"windows-v(\d{1,5})\.(\d{1,5})\.(\d{1,5})\Z") + + +class GitReleaseUnavailable(ValueError): + pass + + +class _NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + return None + + +def _fetch(url, maximum): + if url != RELEASES_API and not url.startswith(f"{ORIGIN}{REPOSITORY}/releases/download/windows-v"): + raise GitReleaseUnavailable("Unapproved update origin") + opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), _NoRedirect()) + request = urllib.request.Request(url, headers={ + "User-Agent": "UCVL-LegacyUpdateBridge/1", "Accept-Encoding": "identity", + }) + try: + with opener.open(request, timeout=5) as response: + if response.status != 200 or response.geturl() != url: + raise GitReleaseUnavailable("Unexpected Git response") + payload = response.read(maximum + 1) + if len(payload) > maximum: + raise GitReleaseUnavailable("Git response exceeds limit") + return payload + except (OSError, urllib.error.URLError) as error: + raise GitReleaseUnavailable("Company Git is unavailable") from error + + +def _load_latest_windows_release(): + try: + releases = json.loads(_fetch(RELEASES_API, 2 * 1024 * 1024)) + if not isinstance(releases, list) or len(releases) > 50: + raise GitReleaseUnavailable("Invalid release list") + candidates = [] + for release in releases: + if not isinstance(release, dict) or release.get("draft", False) or release.get("prerelease", False): + continue + match = TAG.fullmatch(str(release.get("tag_name", ""))) + if match: + candidates.append((tuple(map(int, match.groups())), release)) + if not candidates: + raise GitReleaseUnavailable("No stable Windows release") + version_parts, release = max(candidates, key=lambda candidate: candidate[0]) + version = ".".join(map(str, version_parts)) + # Reject ambiguous zero-padded spellings; never borrow hashes/assets + # from a different release when the newest stable package is invalid. + tag = f"windows-v{version}" + if release["tag_name"] != tag: + raise GitReleaseUnavailable("Noncanonical version") + filename = f"UCVL-Zonghengjia-{version}-win-x64-setup.exe" + names = (filename, filename + ".sha256") + assets = release.get("assets", []) + if not isinstance(assets, list): + raise GitReleaseUnavailable("Invalid assets") + selected = {} + for name in names: + matches = [asset for asset in assets if isinstance(asset, dict) and asset.get("name") == name] + if len(matches) != 1: + raise GitReleaseUnavailable("Missing or duplicate Windows asset") + selected[name] = matches[0] + size = selected[filename].get("size") + if type(size) is not int or not 0 < size <= 200 * 1024 * 1024: + raise GitReleaseUnavailable("Invalid package size") + download_url = f"{ORIGIN}{REPOSITORY}/releases/download/{tag}/{filename}" + # Gitea currently advertises an internal ROOT_URL. Construct the approved + # public URL; never follow browser_download_url supplied in its metadata. + checksum = _fetch(download_url + ".sha256", 4096).decode("ascii").strip() + match = re.fullmatch(r"([a-fA-F0-9]{64})\s+\*?" + re.escape(filename), checksum) + if not match: + raise GitReleaseUnavailable("Checksum does not identify this package") + return {"version": version, "filename": filename, "sha256": match[1].lower(), + "size": size, "download_url": download_url, + "notes": str(release.get("body", ""))[:1000], "mandatory": False} + except (TypeError, KeyError, UnicodeError, json.JSONDecodeError) as error: + raise GitReleaseUnavailable("Invalid Git release metadata") from error + + +def get_latest_windows_release(): + manifest = cache.get(CACHE_KEY) + if manifest is None: + manifest = _load_latest_windows_release() + cache.set(CACHE_KEY, manifest, timeout=60) + return dict(manifest) diff --git a/backend/control/learning.py b/backend/control/learning.py new file mode 100644 index 0000000..510b664 --- /dev/null +++ b/backend/control/learning.py @@ -0,0 +1,90 @@ +"""Minimal, versioned routing delivery. No destinations are contacted by the server.""" +import hashlib +import json +from datetime import timedelta + +from django.db.models import Q +from django.http import JsonResponse +from django.utils import timezone +from django.views.decorators.csrf import csrf_exempt +from django.views.decorators.http import require_http_methods + +from .models import LearnedRouteRule, RouteObservation, RoutePolicyReceipt + + +def manifest(): + from .views import _normalize_observation_target + rules = [] + for rule in LearnedRouteRule.objects.filter(status="active").filter( + Q(valid_until__isnull=True) | Q(valid_until__gt=timezone.now()) + ).order_by("target_type", "target"): + try: + target = _normalize_observation_target(rule.target_type, rule.target) + except ValueError: + continue + # Deliver exact destinations only, never scripts, proxy credentials or wildcards. + rules.append({"target_type": rule.target_type, "target": target, "match_mode": rule.match_mode}) + if len(rules) > 2048: + raise ValueError("智能规则超过客户端安全容量,保留现用策略。") + encoded = json.dumps(rules, sort_keys=True, separators=(",", ":")).encode() + return {"contract": 1, "mode": "direct_first_candidates", "revision": hashlib.sha256(encoded).hexdigest(), "rules": rules, + "poll_after_seconds": 60, "generated_at": timezone.now().isoformat()} + + +@csrf_exempt +@require_http_methods(["GET", "POST"]) +def client_rules(request): + from .views import _authenticate_client_session + session, error = _authenticate_client_session(request) + if error: + return error + if request.method == "GET": + try: + result = manifest() + except ValueError as exc: + return JsonResponse({"error": str(exc)}, status=503) + RoutePolicyReceipt.objects.update_or_create(device=session.device, defaults={ + "offered_revision": result["revision"], "offered_at": timezone.now(), + }) + response = JsonResponse(result) + else: + try: + if len(request.body) > 1024: + raise ValueError + payload = json.loads(request.body) + if not isinstance(payload, dict) or payload.get("status") not in {"cached", "applied", "failed"}: + raise ValueError + receipt = RoutePolicyReceipt.objects.filter(device=session.device, + offered_revision=payload.get("revision", "")).exclude(offered_revision="").first() + if receipt is None: + raise ValueError + receipt.last_status = payload["status"] + receipt.client_version = str(payload.get("client_version", ""))[:30] + if receipt.last_status == "applied": + receipt.applied_revision = receipt.offered_revision + receipt.applied_at = timezone.now() + receipt.save() + except (ValueError, TypeError): + return JsonResponse({"error": "规则回执无效。"}, status=400) + response = JsonResponse({"status": "accepted"}) + response["Cache-Control"] = "no-store" + return response + + +def learning_summary(): + now = timezone.now() + observed = RouteObservation.objects.filter(received_at__gte=now - timedelta(days=7)) + current = manifest()["revision"] + receipts = RoutePolicyReceipt.objects.filter(device__active=True) + return { + "observations": observed.count(), + "last_observation": observed.order_by("-received_at").values_list("received_at", flat=True).first(), + "verified": observed.filter(outcome="proxy_succeeded", evidence_kind="tls", related_report_id__isnull=False).count(), + "learned": LearnedRouteRule.objects.filter(source="ai", status="active").filter(Q(valid_until__isnull=True) | Q(valid_until__gt=now)).count(), + "manual": LearnedRouteRule.objects.filter(source__in=["manual", "preset"], status="active").count(), + "revision": current, + "offered": receipts.filter(offered_revision=current, offered_at__gte=now - timedelta(days=1)).count(), + "applied": receipts.filter(applied_revision=current, last_status="applied", applied_at__gte=now - timedelta(days=1)).count(), + "failed": receipts.filter(last_status="failed", offered_at__gte=now - timedelta(days=1)).count(), + "cached": receipts.filter(last_status="cached", offered_revision=current, offered_at__gte=now - timedelta(days=1)).count(), + } diff --git a/backend/control/lifecycle.py b/backend/control/lifecycle.py new file mode 100644 index 0000000..9895ac8 --- /dev/null +++ b/backend/control/lifecycle.py @@ -0,0 +1,52 @@ +"""User-facing lifecycle; a display state is never authorization to provision.""" +from django.utils import timezone + + +STEPS = ("选择套餐", "付款确认", "审核开通", "使用中", "到期续费") + + +def lifecycle(stage, title, next_step, *, tone="normal", free=False): + labels = list(STEPS) + if free: + labels[1] = "无需付款" + return {"title": title, "next_step": next_step, "tone": tone, + "steps": [{"label": label, "state": "done" if index < stage else "current" if index == stage else "future"} + for index, label in enumerate(labels)]} + + +def personal_lifecycle(user, subscription=None, application=None): + free = user.identity_type == "employee" + if not user.plan_application_allowed: + return lifecycle(0, "账号已停用或暂停", "联系平台管理员核实账号;购买套餐不会解除停权。", tone="attention", free=free) + if subscription is not None: + if subscription.status == "cancelled": + return lifecycle(0, "服务已取消", "选择新的套餐;取消不是已经走完付款和使用流程。", tone="attention", free=free) + if subscription.status == "expired" or (subscription.expires_at and subscription.expires_at <= timezone.now()): + return lifecycle(4, "已到期 / 已结束", "选择续费或新的套餐;不会自动扣款。", tone="attention", free=free) + if subscription.status == "suspended": + return lifecycle(3 if subscription.starts_at else 2, "服务已暂停", "查看暂停原因并联系管理员;当前不可使用。", tone="attention", free=free) + if subscription.online_payment_pending: + return lifecycle(1, "待付款 · 支付暂未开放", "支付接通后再完成付款;未扣款、未开通。", tone="attention") + if subscription.is_usable: + if subscription.expires_at and (subscription.expires_at - timezone.now()).total_seconds() <= 7 * 86400: + return lifecycle(3, "即将到期 · 当前可用", "到期前申请续费;当前期限以套餐到期时间为准。", tone="attention", free=free) + return lifecycle(3, "使用中", "可查看代理用量及设备;实际连接状态以客户端为准。", free=free) + if subscription.traffic_limit_bytes and subscription.used_bytes >= subscription.traffic_limit_bytes: + return lifecycle(3, "流量已用完", "当前不可用;申请调整额度或联系管理员,不会自动加购扣费。", tone="attention", free=free) + return lifecycle(2, "待开通 / 正在下发", "等待审核或节点下发完成;当前还不能使用。", free=free) + if application is not None: + if application.status in ("rejected", "cancelled"): + return lifecycle(0, "申请未通过 / 已取消", "核对申请原因后重新选择套餐。", tone="attention", free=free) + amount = application.plan.price_for_user(user) + if amount > 0 and application.plan.online_payment_required: + return lifecycle(1, "待付款 · 支付暂未开放", "仅登记了申请,未扣款;支付接通后再继续。", tone="attention") + if amount > 0 and application.payment_status != "paid": + return lifecycle(1, "待付款确认", "联系管理员确认付款和申请进度;本页不会自动扣款。") + return lifecycle(2, "等待审核开通", "审核通过后自动关联个人订阅。", free=(amount == 0)) + return lifecycle(0, "尚未选择套餐", "先选择个人套餐,或切换到团队查看你的团队服务。", free=free) + + +def team_lifecycle(team): + if team.plan_draft_id: + return lifecycle(1, "意向套餐 · 待开通", "团队支付、共享用量及代理授权尚未接通;目前只做团队管理,不收费。", tone="attention") + return lifecycle(0, "团队筹备中 · 尚未选套餐", "由所有者联系平台管理员配置意向套餐;创建团队不等于购买成功。") diff --git a/backend/control/management/__init__.py b/backend/control/management/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/backend/control/management/__init__.py @@ -0,0 +1 @@ + diff --git a/backend/control/management/commands/__init__.py b/backend/control/management/commands/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/backend/control/management/commands/__init__.py @@ -0,0 +1 @@ + diff --git a/backend/control/management/commands/audit_plan_approvals.py b/backend/control/management/commands/audit_plan_approvals.py new file mode 100644 index 0000000..f7e2777 --- /dev/null +++ b/backend/control/management/commands/audit_plan_approvals.py @@ -0,0 +1,23 @@ +import json + +from django.core.management.base import BaseCommand, CommandError + +from control.approval_audit import audit_plan_approvals + + +class Command(BaseCommand): + help = "只读检查套餐申请/订阅冲突及 0008 回退风险,不审批、不回填、不修改数据" + + def add_arguments(self, parser): + parser.add_argument("--sample-limit", type=int, default=50) + parser.add_argument("--fail-on-review", action="store_true", + help="先输出 JSON;存在待人工复核项时返回非零状态") + + def handle(self, *args, **options): + limit = options["sample_limit"] + if not 1 <= limit <= 1000: + raise CommandError("sample-limit 必须为 1 至 1000。") + report = audit_plan_approvals(sample_limit=limit) + self.stdout.write(json.dumps(report, ensure_ascii=False, indent=2)) + if options["fail_on_review"] and report["review_required"]: + raise CommandError("只读检查发现待人工复核项;未修改任何申请或订阅。") diff --git a/backend/control/management/commands/bootstrap_vpn.py b/backend/control/management/commands/bootstrap_vpn.py new file mode 100644 index 0000000..b97c270 --- /dev/null +++ b/backend/control/management/commands/bootstrap_vpn.py @@ -0,0 +1,72 @@ +import os + +from django.contrib.auth import get_user_model +from django.core.management.base import BaseCommand + +from control.models import Plan, RoutingPolicy + + +class Command(BaseCommand): + help = "创建默认套餐、全局路由策略和首个管理员" + + def handle(self, *args, **options): + Plan.objects.get_or_create( + slug="employee-benefit", + defaults={ + "name": "员工福利", + "audience": Plan.Audience.EMPLOYEE, + "employee_benefit": True, + "price_cny": 0, + "traffic_limit_gb": 0, + "duration_days": 0, + "device_limit": 3, + "description": "公司内部员工免费使用,离职后由管理员立即停权。", + "sort_order": 1, + }, + ) + Plan.objects.get_or_create( + slug="external-monthly", + defaults={ + "name": "外部联系人月度套餐", + "audience": Plan.Audience.EXTERNAL, + "price_cny": 39, + "traffic_limit_gb": 100, + "duration_days": 30, + "device_limit": 3, + "description": "外部联系人付费套餐,付款确认后开通。", + "sort_order": 10, + }, + ) + RoutingPolicy.objects.get_or_create( + name="公司全局策略", + defaults={ + "is_global": True, + "rules": [ + "DOMAIN-SUFFIX,cn,DIRECT", + "GEOIP,CN,DIRECT", + "MATCH,节点选择", + ], + "description": "国内直连,其余流量使用节点;可在后台调整。", + }, + ) + + username = os.getenv("VPN_ADMIN_USERNAME", "").strip() + password = os.getenv("VPN_ADMIN_PASSWORD", "") + email = os.getenv("VPN_ADMIN_EMAIL", "").strip().lower() + if not username or not password or not email: + self.stdout.write("未提供完整管理员环境变量,跳过管理员创建。") + return + User = get_user_model() + if User.objects.filter(username=username).exists(): + self.stdout.write(f"管理员 {username} 已存在。") + return + User.objects.create_superuser( + username=username, + email=email, + password=password, + display_name="VPN 管理员", + identity_type=User.IdentityType.EMPLOYEE, + account_status=User.AccountStatus.ACTIVE, + ) + self.stdout.write(self.style.SUCCESS(f"已创建管理员 {username}。")) + diff --git a/backend/control/management/commands/configure_node.py b/backend/control/management/commands/configure_node.py new file mode 100644 index 0000000..729de8b --- /dev/null +++ b/backend/control/management/commands/configure_node.py @@ -0,0 +1,46 @@ +import os + +from django.core.management.base import BaseCommand, CommandError + +from control.models import Node + + +class Command(BaseCommand): + help = "创建或更新节点,并设置主动同步令牌" + + def add_arguments(self, parser): + parser.add_argument("--slug", required=True) + parser.add_argument("--name", required=True) + parser.add_argument("--region", required=True) + parser.add_argument("--server", required=True) + parser.add_argument("--port", required=True, type=int) + parser.add_argument("--sni", required=True) + parser.add_argument("--public-key", required=True) + parser.add_argument("--short-id", required=True) + + def handle(self, *args, **options): + token = os.getenv("VPN_NODE_TOKEN", "") + if len(token) < 32: + raise CommandError("VPN_NODE_TOKEN 必须至少 32 个字符。") + node = Node.objects.filter(slug=options["slug"]).first() + created = node is None + if created: + node = Node(slug=options["slug"]) + node.name = options["name"] + node.region = options["region"] + node.server = options["server"] + node.port = options["port"] + node.protocol = Node.Protocol.VLESS_REALITY + node.status = Node.Status.PREPARING + node.active = True + node.subscription_enabled = True + node.sni = options["sni"] + node.reality_public_key = options["public_key"] + node.reality_short_id = options["short_id"] + node.flow = "xtls-rprx-vision" + node.transport = "tcp" + node.client_fingerprint = "chrome" + node.set_agent_token(token) + node.full_clean() + node.save() + self.stdout.write(self.style.SUCCESS(f"节点 {node.slug} {'已创建' if created else '已更新'}。")) diff --git a/backend/control/management/commands/enforce_vpn.py b/backend/control/management/commands/enforce_vpn.py new file mode 100644 index 0000000..0900b0c --- /dev/null +++ b/backend/control/management/commands/enforce_vpn.py @@ -0,0 +1,43 @@ +from django.core.management.base import BaseCommand +from django.utils import timezone + +from datetime import timedelta + +from control.models import Node, NodeReport, NodeTrafficSample, Subscription + + +class Command(BaseCommand): + help = "执行到期、超额、暂停和离职停权" + + def handle(self, *args, **options): + changed = 0 + now = timezone.now() + subscriptions = Subscription.objects.select_related("user").filter( + status__in=[Subscription.Status.ACTIVE, Subscription.Status.SUSPENDED] + ) + for subscription in subscriptions.iterator(): + user = subscription.user + if user.account_status == user.AccountStatus.DEPARTED: + subscription.cancel(reason="用户已离职") + changed += 1 + elif user.account_status == user.AccountStatus.SUSPENDED and subscription.status == Subscription.Status.ACTIVE: + subscription.suspend(reason="用户账号已暂停") + changed += 1 + elif subscription.status == Subscription.Status.ACTIVE and subscription.expires_at and subscription.expires_at <= now: + subscription.status = Subscription.Status.EXPIRED + subscription.state_reason = "套餐已到期" + subscription.provisioning_state = Subscription.ProvisioningState.REVOKE_PENDING + subscription.save(update_fields=["status", "state_reason", "provisioning_state", "updated_at"]) + changed += 1 + elif ( + subscription.status == Subscription.Status.ACTIVE + and subscription.traffic_limit_bytes + and subscription.used_bytes >= subscription.traffic_limit_bytes + ): + subscription.suspend(reason="流量额度已用完") + changed += 1 + offline_before = now - timedelta(minutes=5) + Node.objects.filter(status=Node.Status.ONLINE, last_seen_at__lt=offline_before).update(status=Node.Status.OFFLINE) + NodeTrafficSample.objects.filter(sampled_at__lt=now - timedelta(days=30)).delete() + NodeReport.objects.filter(received_at__lt=now - timedelta(days=7)).delete() + self.stdout.write(f"已处理 {changed} 个订阅状态。") diff --git a/backend/control/management/commands/prepare_monthly_1024g.py b/backend/control/management/commands/prepare_monthly_1024g.py new file mode 100644 index 0000000..4cd04bd --- /dev/null +++ b/backend/control/management/commands/prepare_monthly_1024g.py @@ -0,0 +1,32 @@ +from decimal import Decimal + +from django.core.management.base import BaseCommand, CommandError +from django.db import transaction + +from control.models import Plan + + +class Command(BaseCommand): + help = "准备1024G/月、8元套餐;--list 上架展示与申请,内部员工免费;不启用收款,不修改现有订阅。" + + def add_arguments(self, parser): + parser.add_argument("--list", action="store_true", dest="list_plan", help="开放展示和申请;外部付费权限仍关闭。") + + def handle(self, *args, **options): + expected = dict(name="1024G 月度套餐", audience=Plan.Audience.ALL, + employee_benefit=False, price_cny=Decimal("8.00"), traffic_limit_gb=1024, + billing_months=1, duration_days=0, device_limit=3, + online_payment_required=True) + defaults = dict(expected, active=options["list_plan"], + description="外部人员8元/月、1024G;内部员工免费。仅计算代理流量。按开通日起一个月,到期不自动扣款。暂未开放付款,仅登记申请;内部员工核实身份并审核后免费开通。") + with transaction.atomic(): + plan, created = Plan.objects.get_or_create(slug="monthly-1024g", defaults=defaults) + plan = Plan.objects.select_for_update().get(pk=plan.pk) + if not created and any(getattr(plan, field) != value for field, value in expected.items()): + raise CommandError("已有同标识套餐但配置不同,未覆盖;请先人工核对。") + if options["list_plan"] and not plan.active: + plan.active = True + plan.full_clean() + plan.save(update_fields=["active", "updated_at"]) + state = "已上架展示与申请;暂未开放付款和外部付费权限" if plan.active else "草稿已准备,尚未上架" + self.stdout.write(f"1024G / 月 / 8元套餐:{state}。内部员工免费,现有订阅不变。") diff --git a/backend/control/management/commands/prepare_plan_catalog.py b/backend/control/management/commands/prepare_plan_catalog.py new file mode 100644 index 0000000..d052937 --- /dev/null +++ b/backend/control/management/commands/prepare_plan_catalog.py @@ -0,0 +1,32 @@ +from django.core.management.base import BaseCommand, CommandError +from django.db import transaction + +from control.models import PlanCatalogDraft +from control.plan_catalog import proposed_catalog + + +class Command(BaseCommand): + help = "预览12档个人流量、个人无限流量、5档团队及团队无限流量;--create 仅创建草稿,不上架、不收费。" + + def add_arguments(self, parser): + parser.add_argument("--create", action="store_true", help="创建独立草稿;不改现有Plan/订阅/价格。") + + def handle(self, *args, **options): + proposals = proposed_catalog() + created_count = 0 + if options["create"]: + with transaction.atomic(): + for spec in proposals: + defaults = {key: value for key, value in spec.items() if key != "slug"} + draft, created = PlanCatalogDraft.objects.get_or_create(slug=spec["slug"], defaults=defaults) + draft = PlanCatalogDraft.objects.select_for_update().get(pk=draft.pk) + # Protect the seed identity. Preserve later pricing/limits/notes + # instead of resetting choices made by an administrator. + if any(getattr(draft, key) != spec[key] for key in ("scope", "traffic_limit_gb")): + raise CommandError(f"草稿标识 {spec['slug']} 已有不同流量或类型,本批次不写入;请人工核对。") + draft.full_clean() + created_count += int(created) + for spec in proposals: + self.stdout.write(f"{spec['name']} | {spec['traffic_limit_gb']} GB (0=不限代理流量)") + mode = f"创建{created_count}项,保留{len(proposals) - created_count}项已有草稿" if options["create"] else "仅预览,未写入" + self.stdout.write(f"共{len(proposals)}项:{mode}。月价留空待确认;独立草稿不参与注册/申请/节点下发。原8元1024G套餐及所有订阅不变。") diff --git a/backend/control/management/commands/vpn_ai_worker.py b/backend/control/management/commands/vpn_ai_worker.py new file mode 100644 index 0000000..a6e4041 --- /dev/null +++ b/backend/control/management/commands/vpn_ai_worker.py @@ -0,0 +1,74 @@ +import os +import signal +import socket +import time +from pathlib import Path + +from django.core.management.base import BaseCommand +from django.db import close_old_connections, connection +from django.utils import timezone + +from control.models import VpnAiRuntime +from control.vpn_ai import run_vpn_ai_cycle + + +class Command(BaseCommand): + help = "运行优创⁺纵横家专属 vpn-ai 学习、运维与诊断工作进程。" + + def add_arguments(self, parser): + parser.add_argument("--interval", type=int, default=60) + parser.add_argument("--once", action="store_true") + + def handle(self, *args, **options): + interval = max(15, min(options["interval"], 3600)) + once = options["once"] + stopping = False + + def request_stop(*_): + nonlocal stopping + stopping = True + + signal.signal(signal.SIGTERM, request_stop) + signal.signal(signal.SIGINT, request_stop) + worker_id = f"{socket.gethostname()}:{os.getpid()}" + runtime, _ = VpnAiRuntime.objects.get_or_create(service_name="vpn-ai") + runtime.version = "0.2.0" + runtime.worker_id = worker_id + runtime.started_at = timezone.now() + runtime.last_heartbeat_at = timezone.now() + runtime.last_error = "" + runtime.save() + self.stdout.write(self.style.SUCCESS(f"vpn-ai 已启动:{worker_id}")) + + while not stopping: + close_old_connections() + lock_acquired = False + try: + with connection.cursor() as cursor: + cursor.execute("SELECT pg_try_advisory_lock(%s)", [9262026]) + lock_acquired = bool(cursor.fetchone()[0]) + if lock_acquired: + runtime.refresh_from_db() + run_vpn_ai_cycle(runtime) + Path("/tmp/ucvl-vpn-ai-heartbeat").touch() + except Exception as exc: + runtime.last_heartbeat_at = timezone.now() + runtime.last_error = f"{type(exc).__name__}: {exc}"[:2000] + runtime.save(update_fields=["last_heartbeat_at", "last_error", "updated_at"]) + self.stderr.write(self.style.ERROR(runtime.last_error)) + finally: + if lock_acquired: + try: + with connection.cursor() as cursor: + cursor.execute("SELECT pg_advisory_unlock(%s)", [9262026]) + except Exception: + pass + close_old_connections() + if once: + break + for _ in range(interval): + if stopping: + break + time.sleep(1) + + self.stdout.write("vpn-ai 已停止。") diff --git a/backend/control/migrations/0001_initial.py b/backend/control/migrations/0001_initial.py new file mode 100644 index 0000000..7e0e587 --- /dev/null +++ b/backend/control/migrations/0001_initial.py @@ -0,0 +1,195 @@ +# Generated by Django 5.2.17 on 2026-08-29 12:09 + +import django.db.models.deletion +import uuid +from decimal import Decimal +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='Node', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=100, verbose_name='节点名称')), + ('slug', models.SlugField(max_length=80, unique=True, verbose_name='节点标识')), + ('region', models.CharField(max_length=100, verbose_name='地区')), + ('server', models.CharField(max_length=255, verbose_name='服务器地址')), + ('port', models.PositiveIntegerField(verbose_name='端口')), + ('protocol', models.CharField(choices=[('vless_reality', 'VLESS Reality'), ('trojan_tls', 'Trojan TLS'), ('hysteria2', 'Hysteria2')], max_length=30, verbose_name='协议')), + ('status', models.CharField(choices=[('preparing', '准备中'), ('online', '在线'), ('maintenance', '维护'), ('offline', '离线')], db_index=True, default='preparing', max_length=20, verbose_name='状态')), + ('active', models.BooleanField(default=True, verbose_name='启用')), + ('subscription_enabled', models.BooleanField(default=False, verbose_name='加入订阅')), + ('sort_order', models.PositiveSmallIntegerField(default=10, verbose_name='排序')), + ('sni', models.CharField(blank=True, max_length=255, verbose_name='SNI/域名')), + ('reality_public_key', models.CharField(blank=True, max_length=255, verbose_name='Reality 公钥')), + ('reality_short_id', models.CharField(blank=True, max_length=64, verbose_name='Reality Short ID')), + ('flow', models.CharField(blank=True, default='xtls-rprx-vision', max_length=80, verbose_name='Flow')), + ('transport', models.CharField(default='tcp', max_length=30, verbose_name='传输层')), + ('client_fingerprint', models.CharField(default='chrome', max_length=30, verbose_name='客户端指纹')), + ('skip_cert_verify', models.BooleanField(default=False, verbose_name='跳过证书校验')), + ('last_seen_at', models.DateTimeField(blank=True, null=True, verbose_name='最后上报')), + ('agent_version', models.CharField(blank=True, max_length=64, verbose_name='节点代理版本')), + ('total_upload_bytes', models.PositiveBigIntegerField(default=0, verbose_name='累计上传')), + ('total_download_bytes', models.PositiveBigIntegerField(default=0, verbose_name='累计下载')), + ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')), + ('updated_at', models.DateTimeField(auto_now=True, verbose_name='更新时间')), + ], + options={ + 'verbose_name': '节点', + 'verbose_name_plural': '节点', + 'ordering': ['sort_order', 'region', 'name'], + }, + ), + migrations.CreateModel( + name='Plan', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=100, verbose_name='套餐名称')), + ('slug', models.SlugField(max_length=80, unique=True, verbose_name='标识')), + ('audience', models.CharField(choices=[('employee', '内部员工'), ('external', '外部联系人'), ('all', '全部用户')], default='all', max_length=20, verbose_name='适用人群')), + ('employee_benefit', models.BooleanField(default=False, verbose_name='员工福利')), + ('price_cny', models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=10, verbose_name='价格(元)')), + ('traffic_limit_gb', models.PositiveIntegerField(default=0, help_text='0 表示不限流量', verbose_name='流量额度(GB)')), + ('duration_days', models.PositiveIntegerField(default=30, help_text='0 表示不自动到期', verbose_name='有效天数')), + ('device_limit', models.PositiveSmallIntegerField(default=3, verbose_name='设备数')), + ('active', models.BooleanField(default=True, verbose_name='启用')), + ('description', models.TextField(blank=True, verbose_name='说明')), + ('sort_order', models.PositiveSmallIntegerField(default=10, verbose_name='排序')), + ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')), + ('updated_at', models.DateTimeField(auto_now=True, verbose_name='更新时间')), + ], + options={ + 'verbose_name': '套餐', + 'verbose_name_plural': '套餐', + 'ordering': ['sort_order', 'price_cny', 'name'], + }, + ), + migrations.CreateModel( + name='RoutingPolicy', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=100, verbose_name='策略名称')), + ('is_global', models.BooleanField(db_index=True, default=False, verbose_name='全局默认')), + ('active', models.BooleanField(default=True, verbose_name='启用')), + ('rules', models.JSONField(default=list, help_text='按顺序填写规则,例如 DOMAIN-SUFFIX,cn,DIRECT。未填写 MATCH 时系统自动补充。', verbose_name='Mihomo 路由规则')), + ('description', models.TextField(blank=True, verbose_name='说明')), + ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')), + ('updated_at', models.DateTimeField(auto_now=True, verbose_name='更新时间')), + ], + options={ + 'verbose_name': '路由策略', + 'verbose_name_plural': '路由策略', + 'ordering': ['-is_global', 'name'], + }, + ), + migrations.CreateModel( + name='PlanApplication', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('status', models.CharField(choices=[('pending', '待处理'), ('approved', '已批准'), ('rejected', '已拒绝'), ('cancelled', '已取消')], db_index=True, default='pending', max_length=20, verbose_name='处理状态')), + ('payment_status', models.CharField(choices=[('not_required', '无需付款'), ('unpaid', '待付款'), ('paid', '已付款'), ('refunded', '已退款')], default='unpaid', max_length=20, verbose_name='付款状态')), + ('note', models.TextField(blank=True, verbose_name='申请说明')), + ('reviewer_note', models.TextField(blank=True, verbose_name='审核备注')), + ('reviewed_at', models.DateTimeField(blank=True, null=True, verbose_name='审核时间')), + ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='申请时间')), + ('updated_at', models.DateTimeField(auto_now=True, verbose_name='更新时间')), + ('plan', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='applications', to='control.plan', verbose_name='申请套餐')), + ('reviewed_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='reviewed_plan_applications', to=settings.AUTH_USER_MODEL, verbose_name='审核人')), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='plan_applications', to=settings.AUTH_USER_MODEL, verbose_name='申请人')), + ], + options={ + 'verbose_name': '套餐申请', + 'verbose_name_plural': '套餐申请', + 'ordering': ['-created_at'], + }, + ), + migrations.CreateModel( + name='Subscription', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('status', models.CharField(choices=[('pending', '待开通'), ('active', '使用中'), ('suspended', '已暂停'), ('expired', '已到期'), ('cancelled', '已取消')], db_index=True, default='pending', max_length=20, verbose_name='状态')), + ('starts_at', models.DateTimeField(blank=True, null=True, verbose_name='开始时间')), + ('expires_at', models.DateTimeField(blank=True, db_index=True, null=True, verbose_name='到期时间')), + ('traffic_limit_bytes', models.PositiveBigIntegerField(default=0, verbose_name='流量额度(字节)')), + ('upload_bytes', models.PositiveBigIntegerField(default=0, verbose_name='已用上传')), + ('download_bytes', models.PositiveBigIntegerField(default=0, verbose_name='已用下载')), + ('device_limit', models.PositiveSmallIntegerField(default=3, verbose_name='设备数')), + ('route_mode', models.CharField(choices=[('global', '使用全局策略'), ('custom', '使用专用策略'), ('dedicated', '指定节点')], default='global', max_length=20, verbose_name='路由模式')), + ('credential_uuid', models.UUIDField(default=uuid.uuid4, editable=False, unique=True, verbose_name='节点凭据')), + ('token_version', models.PositiveIntegerField(default=1, editable=False, verbose_name='订阅令牌版本')), + ('provisioning_state', models.CharField(choices=[('pending', '等待下发'), ('active', '已下发'), ('failed', '下发失败'), ('revoke_pending', '等待撤销'), ('revoked', '已撤销')], default='pending', max_length=24, verbose_name='节点下发状态')), + ('state_reason', models.CharField(blank=True, max_length=255, verbose_name='状态说明')), + ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')), + ('updated_at', models.DateTimeField(auto_now=True, verbose_name='更新时间')), + ('allowed_nodes', models.ManyToManyField(blank=True, related_name='subscriptions', to='control.node', verbose_name='指定节点')), + ('plan', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='subscriptions', to='control.plan', verbose_name='套餐')), + ('routing_policy', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='subscriptions', to='control.routingpolicy', verbose_name='专用路由策略')), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='subscriptions', to=settings.AUTH_USER_MODEL, verbose_name='用户')), + ], + options={ + 'verbose_name': '订阅', + 'verbose_name_plural': '订阅', + 'ordering': ['-created_at'], + }, + ), + migrations.CreateModel( + name='Device', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('device_id', models.CharField(max_length=128, verbose_name='设备标识')), + ('name', models.CharField(blank=True, max_length=100, verbose_name='设备名称')), + ('platform', models.CharField(blank=True, max_length=50, verbose_name='平台')), + ('active', models.BooleanField(default=True, verbose_name='允许使用')), + ('last_seen_at', models.DateTimeField(blank=True, null=True, verbose_name='最后在线')), + ('upload_bytes', models.PositiveBigIntegerField(default=0, verbose_name='上传')), + ('download_bytes', models.PositiveBigIntegerField(default=0, verbose_name='下载')), + ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='首次出现')), + ('subscription', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='devices', to='control.subscription', verbose_name='订阅')), + ], + options={ + 'verbose_name': '设备', + 'verbose_name_plural': '设备', + 'ordering': ['-last_seen_at', 'name'], + }, + ), + migrations.CreateModel( + name='UsageRecord', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('day', models.DateField(verbose_name='日期')), + ('upload_bytes', models.PositiveBigIntegerField(default=0, verbose_name='上传')), + ('download_bytes', models.PositiveBigIntegerField(default=0, verbose_name='下载')), + ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')), + ('updated_at', models.DateTimeField(auto_now=True, verbose_name='更新时间')), + ('node', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='usage_records', to='control.node', verbose_name='节点')), + ('subscription', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='usage_records', to='control.subscription', verbose_name='订阅')), + ], + options={ + 'verbose_name': '每日流量', + 'verbose_name_plural': '每日流量', + 'ordering': ['-day', 'subscription_id'], + }, + ), + migrations.AddIndex( + model_name='subscription', + index=models.Index(fields=['status', 'expires_at'], name='control_sub_status_4860b4_idx'), + ), + migrations.AddConstraint( + model_name='device', + constraint=models.UniqueConstraint(fields=('subscription', 'device_id'), name='unique_subscription_device'), + ), + migrations.AddConstraint( + model_name='usagerecord', + constraint=models.UniqueConstraint(fields=('subscription', 'node', 'day'), name='unique_subscription_node_day'), + ), + ] diff --git a/backend/control/migrations/0002_node_agent_token_digest_nodedeployment_nodereport.py b/backend/control/migrations/0002_node_agent_token_digest_nodedeployment_nodereport.py new file mode 100644 index 0000000..c3febce --- /dev/null +++ b/backend/control/migrations/0002_node_agent_token_digest_nodedeployment_nodereport.py @@ -0,0 +1,53 @@ +# Generated by Django 5.2.17 on 2026-08-29 12:34 + +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('control', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='node', + name='agent_token_digest', + field=models.CharField(blank=True, editable=False, max_length=64, verbose_name='节点令牌摘要'), + ), + migrations.CreateModel( + name='NodeDeployment', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('deployed', models.BooleanField(default=False, verbose_name='已在节点生效')), + ('applied_at', models.DateTimeField(blank=True, null=True, verbose_name='最近生效时间')), + ('revoked_at', models.DateTimeField(blank=True, null=True, verbose_name='最近撤销时间')), + ('last_error', models.CharField(blank=True, max_length=500, verbose_name='最近错误')), + ('updated_at', models.DateTimeField(auto_now=True, verbose_name='更新时间')), + ('node', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='deployments', to='control.node', verbose_name='节点')), + ('subscription', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='node_deployments', to='control.subscription', verbose_name='订阅')), + ], + options={ + 'verbose_name': '节点下发状态', + 'verbose_name_plural': '节点下发状态', + 'ordering': ['node', 'subscription'], + 'constraints': [models.UniqueConstraint(fields=('subscription', 'node'), name='unique_subscription_node_deployment')], + }, + ), + migrations.CreateModel( + name='NodeReport', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('report_id', models.UUIDField(verbose_name='报告 ID')), + ('received_at', models.DateTimeField(auto_now_add=True, verbose_name='接收时间')), + ('node', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='reports', to='control.node', verbose_name='节点')), + ], + options={ + 'verbose_name': '节点上报去重记录', + 'verbose_name_plural': '节点上报去重记录', + 'ordering': ['-received_at'], + 'constraints': [models.UniqueConstraint(fields=('node', 'report_id'), name='unique_node_report')], + }, + ), + ] diff --git a/backend/control/migrations/0003_clientsession.py b/backend/control/migrations/0003_clientsession.py new file mode 100644 index 0000000..3bf2ee9 --- /dev/null +++ b/backend/control/migrations/0003_clientsession.py @@ -0,0 +1,31 @@ +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("control", "0002_node_agent_token_digest_nodedeployment_nodereport"), + ] + + operations = [ + migrations.CreateModel( + name="ClientSession", + fields=[ + ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")), + ("token_digest", models.CharField(editable=False, max_length=64, unique=True, verbose_name="访问令牌摘要")), + ("expires_at", models.DateTimeField(db_index=True, verbose_name="令牌到期时间")), + ("last_seen_at", models.DateTimeField(auto_now_add=True, verbose_name="最后访问")), + ("revoked_at", models.DateTimeField(blank=True, db_index=True, null=True, verbose_name="撤销时间")), + ("created_at", models.DateTimeField(auto_now_add=True, verbose_name="创建时间")), + ( + "device", + models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name="sessions", to="control.device", verbose_name="设备"), + ), + ( + "subscription", + models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name="client_sessions", to="control.subscription", verbose_name="订阅"), + ), + ], + options={"verbose_name": "客户端会话", "verbose_name_plural": "客户端会话", "ordering": ["-last_seen_at"]}, + ), + ] diff --git a/backend/control/migrations/0004_vpn_ai.py b/backend/control/migrations/0004_vpn_ai.py new file mode 100644 index 0000000..97a8e93 --- /dev/null +++ b/backend/control/migrations/0004_vpn_ai.py @@ -0,0 +1,108 @@ +from decimal import Decimal + +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("control", "0003_clientsession"), + ] + + operations = [ + migrations.CreateModel( + name="LearnedRouteRule", + fields=[ + ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")), + ("target_type", models.CharField(choices=[("domain", "域名"), ("ip", "IP 地址")], max_length=10, verbose_name="目标类型")), + ("target", models.CharField(max_length=253, verbose_name="目标")), + ("status", models.CharField(choices=[("pending", "学习中"), ("active", "已自动启用"), ("disabled", "已禁用")], db_index=True, default="pending", max_length=12, verbose_name="状态")), + ("confidence", models.DecimalField(decimal_places=4, default=Decimal("0"), max_digits=5, verbose_name="置信度")), + ("failure_reports", models.PositiveIntegerField(default=0, verbose_name="直连失败数")), + ("proxy_success_reports", models.PositiveIntegerField(default=0, verbose_name="代理成功数")), + ("distinct_devices", models.PositiveIntegerField(default=0, verbose_name="设备数")), + ("reason", models.CharField(blank=True, max_length=500, verbose_name="学习依据")), + ("valid_until", models.DateTimeField(blank=True, db_index=True, null=True, verbose_name="有效期至")), + ("manually_locked", models.BooleanField(default=False, help_text="启用后 AI 不再自动改变状态。", verbose_name="人工锁定")), + ("first_seen_at", models.DateTimeField(auto_now_add=True, verbose_name="首次发现")), + ("last_evaluated_at", models.DateTimeField(blank=True, null=True, verbose_name="最近评估")), + ("updated_at", models.DateTimeField(auto_now=True, verbose_name="更新时间")), + ], + options={ + "verbose_name": "AI 学习路由规则", + "verbose_name_plural": "AI 学习路由规则", + "ordering": ["-status", "-confidence", "target"], + "constraints": [models.UniqueConstraint(fields=("target_type", "target"), name="unique_learned_route_target")], + }, + ), + migrations.CreateModel( + name="VpnAiFinding", + fields=[ + ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")), + ("fingerprint", models.CharField(editable=False, max_length=255, unique=True, verbose_name="诊断指纹")), + ("category", models.CharField(choices=[("routing", "路由学习"), ("node", "节点运维"), ("subscription", "订阅诊断"), ("security", "安全")], max_length=20, verbose_name="类别")), + ("severity", models.CharField(choices=[("info", "提示"), ("warning", "警告"), ("critical", "严重")], max_length=12, verbose_name="等级")), + ("status", models.CharField(choices=[("open", "待处理"), ("resolved", "已恢复"), ("ignored", "已忽略")], db_index=True, default="open", max_length=12, verbose_name="状态")), + ("title", models.CharField(max_length=200, verbose_name="标题")), + ("summary", models.TextField(verbose_name="诊断说明")), + ("evidence", models.JSONField(blank=True, default=dict, verbose_name="证据")), + ("first_seen_at", models.DateTimeField(auto_now_add=True, verbose_name="首次发现")), + ("last_seen_at", models.DateTimeField(auto_now=True, verbose_name="最近发现")), + ("resolved_at", models.DateTimeField(blank=True, null=True, verbose_name="恢复时间")), + ], + options={ + "verbose_name": "vpn-ai 诊断", + "verbose_name_plural": "vpn-ai 诊断", + "ordering": ["status", "-severity", "-last_seen_at"], + }, + ), + migrations.CreateModel( + name="VpnAiRuntime", + fields=[ + ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")), + ("service_name", models.CharField(default="vpn-ai", max_length=100, unique=True, verbose_name="服务名称")), + ("version", models.CharField(default="0.2.0", max_length=30, verbose_name="版本")), + ("worker_id", models.CharField(blank=True, max_length=100, verbose_name="工作实例")), + ("started_at", models.DateTimeField(blank=True, null=True, verbose_name="启动时间")), + ("last_heartbeat_at", models.DateTimeField(blank=True, db_index=True, null=True, verbose_name="最近心跳")), + ("last_cycle_at", models.DateTimeField(blank=True, null=True, verbose_name="最近巡检")), + ("cycle_count", models.PositiveBigIntegerField(default=0, verbose_name="巡检次数")), + ("observations_7d", models.PositiveIntegerField(default=0, verbose_name="近 7 天观测")), + ("active_rules", models.PositiveIntegerField(default=0, verbose_name="生效规则")), + ("open_findings", models.PositiveIntegerField(default=0, verbose_name="待处理诊断")), + ("last_error", models.TextField(blank=True, verbose_name="最近错误")), + ("updated_at", models.DateTimeField(auto_now=True, verbose_name="更新时间")), + ], + options={ + "verbose_name": "vpn-ai 控制台", + "verbose_name_plural": "vpn-ai 控制台", + }, + ), + migrations.CreateModel( + name="RouteObservation", + fields=[ + ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")), + ("report_id", models.UUIDField(unique=True, verbose_name="客户端报告 ID")), + ("target_type", models.CharField(choices=[("domain", "域名"), ("ip", "IP 地址")], max_length=10, verbose_name="目标类型")), + ("target", models.CharField(db_index=True, max_length=253, verbose_name="目标")), + ("port", models.PositiveIntegerField(verbose_name="端口")), + ("network", models.CharField(choices=[("tcp", "TCP"), ("udp", "UDP")], max_length=6, verbose_name="网络协议")), + ("outcome", models.CharField(choices=[("direct_failed", "直连失败"), ("proxy_succeeded", "代理成功"), ("proxy_failed", "代理失败")], db_index=True, max_length=24, verbose_name="结果")), + ("failure_kind", models.CharField(choices=[("timeout", "超时"), ("reset", "连接重置"), ("dns", "DNS 异常"), ("tls", "TLS 异常"), ("unreachable", "不可达"), ("other", "其他")], default="other", max_length=20, verbose_name="失败类型")), + ("client_version", models.CharField(blank=True, max_length=30, verbose_name="客户端版本")), + ("received_at", models.DateTimeField(auto_now_add=True, db_index=True, verbose_name="接收时间")), + ("device", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name="route_observations", to="control.device", verbose_name="设备")), + ("node", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="route_observations", to="control.node", verbose_name="节点")), + ("subscription", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name="route_observations", to="control.subscription", verbose_name="订阅")), + ], + options={ + "verbose_name": "AI 路由观测", + "verbose_name_plural": "AI 路由观测", + "ordering": ["-received_at"], + "indexes": [ + models.Index(fields=["target_type", "target", "received_at"], name="route_obs_target_time_idx"), + models.Index(fields=["device", "received_at"], name="route_obs_device_time_idx"), + ], + }, + ), + ] diff --git a/backend/control/migrations/0005_route_rule_sources_and_presets.py b/backend/control/migrations/0005_route_rule_sources_and_presets.py new file mode 100644 index 0000000..151b21f --- /dev/null +++ b/backend/control/migrations/0005_route_rule_sources_and_presets.py @@ -0,0 +1,109 @@ +from decimal import Decimal + +from django.db import migrations, models + + +PRESET_DOMAINS = ( + ("openai.com", "OpenAI / Codex"), + ("chatgpt.com", "ChatGPT"), + ("oaistatic.com", "OpenAI 静态资源"), + ("oaiusercontent.com", "OpenAI 用户内容"), + ("google.com", "Google"), + ("googleapis.com", "Google API"), + ("gstatic.com", "Google 静态资源"), + ("googleusercontent.com", "Google 用户内容"), + ("ggpht.com", "Google 图片资源"), + ("googlevideo.com", "Google 视频资源"), + ("youtube.com", "YouTube"), + ("youtu.be", "YouTube 短链接"), + ("ytimg.com", "YouTube 图片资源"), +) + + +def seed_preset_route_rules(apps, schema_editor): + LearnedRouteRule = apps.get_model("control", "LearnedRouteRule") + for target, label in PRESET_DOMAINS: + LearnedRouteRule.objects.update_or_create( + target_type="domain", + target=target, + defaults={ + "source": "preset", + "match_mode": "suffix", + "status": "active", + "confidence": Decimal("1.0000"), + "failure_reports": 0, + "proxy_success_reports": 0, + "distinct_devices": 0, + "reason": f"系统预置:{label} 的已知需代理域名;直接下发,不等待失败学习。", + "valid_until": None, + "manually_locked": True, + }, + ) + + +def remove_preset_route_rules(apps, schema_editor): + LearnedRouteRule = apps.get_model("control", "LearnedRouteRule") + LearnedRouteRule.objects.filter( + source="preset", + target__in=[target for target, _ in PRESET_DOMAINS], + ).delete() + + +class Migration(migrations.Migration): + dependencies = [("control", "0004_vpn_ai")] + + operations = [ + migrations.AlterModelOptions( + name="learnedrouterule", + options={ + "ordering": ["-status", "-confidence", "target"], + "verbose_name": "智能代理规则", + "verbose_name_plural": "智能代理规则", + }, + ), + migrations.AddField( + model_name="routeobservation", + name="access_kind", + field=models.CharField( + choices=[("http", "HTTP/HTTPS 网页"), ("socket", "Socket 连接")], + db_index=True, + default="socket", + max_length=10, + verbose_name="访问方式", + ), + ), + migrations.AlterField( + model_name="learnedrouterule", + name="status", + field=models.CharField( + choices=[("pending", "学习中"), ("active", "已生效"), ("disabled", "已禁用")], + db_index=True, + default="pending", + max_length=12, + verbose_name="状态", + ), + ), + migrations.AddField( + model_name="learnedrouterule", + name="source", + field=models.CharField( + choices=[("preset", "系统预置"), ("ai", "AI 学习"), ("manual", "管理员添加")], + db_index=True, + default="ai", + max_length=12, + verbose_name="规则来源", + ), + ), + migrations.AddField( + model_name="learnedrouterule", + name="match_mode", + field=models.CharField( + choices=[("exact", "精确目标"), ("suffix", "域名及其子域")], + default="exact", + help_text="域名预置规则通常选择“域名及其子域”;IP 地址只能精确匹配。", + max_length=12, + verbose_name="匹配方式", + ), + ), + migrations.RunPython(seed_preset_route_rules, remove_preset_route_rules), + ] diff --git a/backend/control/migrations/0006_node_traffic_sample.py b/backend/control/migrations/0006_node_traffic_sample.py new file mode 100644 index 0000000..8ab347e --- /dev/null +++ b/backend/control/migrations/0006_node_traffic_sample.py @@ -0,0 +1,33 @@ +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + dependencies = [("control", "0005_route_rule_sources_and_presets")] + + operations = [ + migrations.CreateModel( + name="NodeTrafficSample", + fields=[ + ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")), + ("sampled_at", models.DateTimeField(auto_now_add=True, db_index=True, verbose_name="采样时间")), + ("interval_seconds", models.PositiveSmallIntegerField(default=60, verbose_name="采样间隔(秒)")), + ("upload_bytes", models.PositiveBigIntegerField(default=0, verbose_name="区间上传")), + ("download_bytes", models.PositiveBigIntegerField(default=0, verbose_name="区间下载")), + ("upload_bytes_per_second", models.PositiveBigIntegerField(default=0, verbose_name="上传速度(B/s)")), + ("download_bytes_per_second", models.PositiveBigIntegerField(default=0, verbose_name="下载速度(B/s)")), + ("active_subscriptions", models.PositiveSmallIntegerField(default=0, verbose_name="已下发订阅数")), + ("node", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name="traffic_samples", to="control.node", verbose_name="节点")), + ("report", models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="traffic_sample", to="control.nodereport", verbose_name="节点报告")), + ], + options={ + "verbose_name": "节点流量采样", + "verbose_name_plural": "节点流量采样", + "ordering": ["-sampled_at"], + }, + ), + migrations.AddIndex( + model_name="nodetrafficsample", + index=models.Index(fields=["node", "sampled_at"], name="node_traffic_node_sample_idx"), + ), + ] diff --git a/backend/control/migrations/0007_ai_dispatch.py b/backend/control/migrations/0007_ai_dispatch.py new file mode 100644 index 0000000..4dec415 --- /dev/null +++ b/backend/control/migrations/0007_ai_dispatch.py @@ -0,0 +1,12 @@ +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + dependencies = [("control", "0006_node_traffic_sample")] + operations = [ + migrations.AddField(model_name="node", name="fallback_only", field=models.BooleanField(default=False, verbose_name="仅最终备用", help_text="不参与日常负载分配,主节点不可用时才使用。")), + migrations.AddField(model_name="clientsession", name="assigned_node", field=models.ForeignKey(null=True, blank=True, on_delete=django.db.models.deletion.SET_NULL, related_name="assigned_sessions", to="control.node", verbose_name="AI 分配节点")), + migrations.AddField(model_name="clientsession", name="dispatch_decision", field=models.JSONField(default=dict, blank=True, verbose_name="最近调度依据")), + migrations.AddField(model_name="vpnairuntime", name="dispatch_snapshot", field=models.JSONField(default=dict, blank=True, verbose_name="负载调度快照")), + ] diff --git a/backend/control/migrations/0008_planapplication_subscription.py b/backend/control/migrations/0008_planapplication_subscription.py new file mode 100644 index 0000000..9ffb9c7 --- /dev/null +++ b/backend/control/migrations/0008_planapplication_subscription.py @@ -0,0 +1,22 @@ +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + dependencies = [("control", "0007_ai_dispatch")] + + operations = [ + migrations.AddField( + model_name="planapplication", + name="subscription", + field=models.ForeignKey( + blank=True, + editable=False, + null=True, + on_delete=django.db.models.deletion.PROTECT, + related_name="plan_applications", + to="control.subscription", + verbose_name="自动开通的订阅", + ), + ), + ] diff --git a/backend/control/migrations/0009_hourlyusagerecord.py b/backend/control/migrations/0009_hourlyusagerecord.py new file mode 100644 index 0000000..2922c8e --- /dev/null +++ b/backend/control/migrations/0009_hourlyusagerecord.py @@ -0,0 +1,21 @@ +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + dependencies = [("control", "0008_planapplication_subscription")] + operations = [migrations.CreateModel( + name="HourlyUsageRecord", + fields=[ + ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")), + ("hour", models.DateTimeField()), + ("upload_bytes", models.PositiveBigIntegerField(default=0)), + ("download_bytes", models.PositiveBigIntegerField(default=0)), + ("node", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="hourly_usage_records", to="control.node")), + ("subscription", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name="hourly_usage_records", to="control.subscription")), + ], + options={ + "indexes": [models.Index(fields=["subscription", "hour"], name="usage_subscription_hour")], + "constraints": [models.UniqueConstraint(fields=("subscription", "node", "hour"), name="unique_subscription_node_hour")], + }, + )] diff --git a/backend/control/migrations/0010_plan_billing_months_plan_online_payment_required.py b/backend/control/migrations/0010_plan_billing_months_plan_online_payment_required.py new file mode 100644 index 0000000..7b8c42a --- /dev/null +++ b/backend/control/migrations/0010_plan_billing_months_plan_online_payment_required.py @@ -0,0 +1,23 @@ +# Generated by Django 5.2.17 on 2026-09-13 06:48 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('control', '0009_hourlyusagerecord'), + ] + + operations = [ + migrations.AddField( + model_name='plan', + name='billing_months', + field=models.PositiveSmallIntegerField(default=0, help_text='大于0时从开通日起按自然月计算,覆盖有效天数;到期不自动扣款。', verbose_name='按月周期'), + ), + migrations.AddField( + model_name='plan', + name='online_payment_required', + field=models.BooleanField(default=False, help_text='可展示并接受申请;收款接入验收前不接受付款、不开放付费权限,不得人工改付款状态绕过。内部员工仍免费。', verbose_name='要求在线收款'), + ), + ] diff --git a/backend/control/migrations/0011_plancatalogdraft.py b/backend/control/migrations/0011_plancatalogdraft.py new file mode 100644 index 0000000..0801023 --- /dev/null +++ b/backend/control/migrations/0011_plancatalogdraft.py @@ -0,0 +1,37 @@ +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [("control", "0010_plan_billing_months_plan_online_payment_required")] + + operations = [ + migrations.CreateModel( + name="PlanCatalogDraft", + fields=[ + ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")), + ("name", models.CharField(max_length=100, verbose_name="套餐名称")), + ("slug", models.SlugField(max_length=80, unique=True, verbose_name="草稿标识")), + ("scope", models.CharField(choices=[("personal", "个人"), ("team", "团队共享(待接入)")], max_length=20, verbose_name="套餐类型")), + ("traffic_limit_gb", models.PositiveIntegerField(help_text="0 表示不限代理流量,不代表无限带宽、人数或设备。", verbose_name="月代理流量(GB)")), + ("price_cny", models.DecimalField(blank=True, decimal_places=2, help_text="留空表示待定价,不是0元免费;填写也不会自动上架。", max_digits=10, null=True, verbose_name="拟定月价(元)")), + ("member_limit", models.PositiveIntegerField(blank=True, help_text="个人为1;团队留空表示待确认。", null=True, verbose_name="成员上限")), + ("device_limit", models.PositiveIntegerField(blank=True, help_text="团队为全部成员总数;留空表示待确认,不是无限。", null=True, verbose_name="总设备上限")), + ("concurrent_limit", models.PositiveIntegerField(blank=True, help_text="留空表示待确认,不是无限。", null=True, verbose_name="同时在线上限")), + ("description", models.TextField(blank=True, verbose_name="草案说明")), + ("sort_order", models.PositiveSmallIntegerField(default=10, verbose_name="排序")), + ("created_at", models.DateTimeField(auto_now_add=True, verbose_name="创建时间")), + ("updated_at", models.DateTimeField(auto_now=True, verbose_name="更新时间")), + ], + options={ + "verbose_name": "套餐草稿(未上架)", + "verbose_name_plural": "套餐草稿(未上架)", + "ordering": ["sort_order", "pk"], + "constraints": [ + models.CheckConstraint(condition=models.Q(price_cny__isnull=True) | models.Q(price_cny__gte=0), name="catalog_draft_price_nonnegative"), + models.CheckConstraint(condition=models.Q(member_limit__isnull=True) | models.Q(member_limit__gt=0), name="catalog_draft_members_positive"), + models.CheckConstraint(condition=models.Q(device_limit__isnull=True) | models.Q(device_limit__gt=0), name="catalog_draft_devices_positive"), + models.CheckConstraint(condition=models.Q(concurrent_limit__isnull=True) | models.Q(concurrent_limit__gt=0), name="catalog_draft_concurrent_positive"), + ], + }, + ), + ] diff --git a/backend/control/migrations/0012_team_management.py b/backend/control/migrations/0012_team_management.py new file mode 100644 index 0000000..bb5016c --- /dev/null +++ b/backend/control/migrations/0012_team_management.py @@ -0,0 +1,37 @@ +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + dependencies = [("control", "0011_plancatalogdraft"), migrations.swappable_dependency(settings.AUTH_USER_MODEL)] + operations = [ + migrations.CreateModel(name="Team", fields=[ + ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")), + ("name", models.CharField(max_length=100, verbose_name="团队名称")), + ("active", models.BooleanField(default=True, help_text="仅管理空间,不等于代理服务已开通;不改变成员的个人账号或个人订阅。", verbose_name="启用团队管理")), + ("setup_member_limit", models.PositiveIntegerField(default=3, help_text="包含已加入及待接受邀请;只是管理空间人数,不是已购买席位,不开通代理。", verbose_name="筹备成员上限(含所有者)")), + ("created_at", models.DateTimeField(auto_now_add=True, verbose_name="创建时间")), + ("updated_at", models.DateTimeField(auto_now=True, verbose_name="更新时间")), + ("owner", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="owned_vpn_teams", to=settings.AUTH_USER_MODEL, verbose_name="所有者")), + ("plan_draft", models.ForeignKey(blank=True, limit_choices_to={"scope": "team"}, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="interested_teams", to="control.plancatalogdraft", verbose_name="意向团队套餐(未开通)")), + ], options={"verbose_name": "团队管理", "verbose_name_plural": "团队管理", "ordering": ["-created_at"], "constraints": [models.CheckConstraint(condition=models.Q(setup_member_limit__gt=0), name="team_setup_members_positive")]}), + migrations.CreateModel(name="TeamMembership", fields=[ + ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")), + ("role", models.CharField(choices=[("admin", "团队管理员"), ("member", "成员")], default="member", max_length=12, verbose_name="团队角色")), + ("status", models.CharField(choices=[("invited", "待本人接受"), ("active", "已加入"), ("removed", "已退出/移除")], default="invited", max_length=12, verbose_name="加入状态")), + ("created_at", models.DateTimeField(auto_now_add=True)), + ("updated_at", models.DateTimeField(auto_now=True)), + ("invited_by", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="sent_vpn_team_invites", to=settings.AUTH_USER_MODEL, verbose_name="邀请人")), + ("team", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name="memberships", to="control.team", verbose_name="团队")), + ("user", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="vpn_team_memberships", to=settings.AUTH_USER_MODEL, verbose_name="成员账号")), + ], options={"verbose_name": "团队成员", "verbose_name_plural": "团队成员", "constraints": [models.UniqueConstraint(fields=("team", "user"), name="unique_team_member")]}), + migrations.CreateModel(name="TeamAuditEvent", fields=[ + ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")), + ("action", models.CharField(max_length=32, verbose_name="操作")), + ("created_at", models.DateTimeField(auto_now_add=True, verbose_name="时间")), + ("actor", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="team_actions", to=settings.AUTH_USER_MODEL, verbose_name="操作人")), + ("subject", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="team_subject_actions", to=settings.AUTH_USER_MODEL, verbose_name="目标成员")), + ("team", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="audit_events", to="control.team", verbose_name="团队")), + ], options={"verbose_name": "团队权限审计", "verbose_name_plural": "团队权限审计", "ordering": ["-created_at", "-pk"]}), + ] diff --git a/backend/control/migrations/0013_node_office_permissions.py b/backend/control/migrations/0013_node_office_permissions.py new file mode 100644 index 0000000..db6a41e --- /dev/null +++ b/backend/control/migrations/0013_node_office_permissions.py @@ -0,0 +1,16 @@ +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("control", "0012_team_management"), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + operations = [ + migrations.AddField(model_name="node", name="office_only", + field=models.BooleanField(default=False, db_default=False, verbose_name="仅办公室内网")), + migrations.AddField(model_name="node", name="office_users", + field=models.ManyToManyField(blank=True, related_name="authorized_office_nodes", + to=settings.AUTH_USER_MODEL, verbose_name="办公室授权员工")), + ] diff --git a/backend/control/migrations/0014_node_office_access_scope.py b/backend/control/migrations/0014_node_office_access_scope.py new file mode 100644 index 0000000..42b47d5 --- /dev/null +++ b/backend/control/migrations/0014_node_office_access_scope.py @@ -0,0 +1,26 @@ +from django.db import migrations, models + + +CHOICES = [ + ("company_network", "公司网络内的在职内部账号"), + ("explicit_users", "保留原人工白名单"), +] +HELP = "公司网络模式不按员工所属办公室筛人。这里只生成网络验证候选,仍需通过登记站点的加密验证;公网IP、GPS、网关品牌都不能直接放行。" + + +class Migration(migrations.Migration): + dependencies = [("control", "0013_node_office_permissions")] + operations = [ + # Preserve every existing node's old candidate boundary. New nodes use + # network scope; neither scope changes the legacy config exclusion. + migrations.AddField( + model_name="node", name="office_access_scope", + field=models.CharField(choices=CHOICES, default="explicit_users", db_default="explicit_users", max_length=24, + verbose_name="办公室候选范围", help_text=HELP), + ), + migrations.AlterField( + model_name="node", name="office_access_scope", + field=models.CharField(choices=CHOICES, default="company_network", db_default="company_network", max_length=24, + verbose_name="办公室候选范围", help_text=HELP), + ), + ] diff --git a/backend/control/migrations/0015_learning_delivery.py b/backend/control/migrations/0015_learning_delivery.py new file mode 100644 index 0000000..a38fa33 --- /dev/null +++ b/backend/control/migrations/0015_learning_delivery.py @@ -0,0 +1,21 @@ +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + dependencies = [("control", "0014_node_office_access_scope")] + operations = [ + migrations.AddField(model_name="routeobservation", name="evidence_kind", field=models.CharField(blank=True, db_default="", max_length=12, verbose_name="验证方式")), + migrations.AddField(model_name="routeobservation", name="related_report_id", field=models.UUIDField(blank=True, null=True, verbose_name="对应直连失败报告")), + migrations.AddField(model_name="routeobservation", name="scope", field=models.CharField(default="public", db_default="public", max_length=20, verbose_name="观测范围")), + migrations.CreateModel(name="RoutePolicyReceipt", fields=[ + ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")), + ("offered_revision", models.CharField(blank=True, max_length=64)), + ("applied_revision", models.CharField(blank=True, max_length=64)), + ("offered_at", models.DateTimeField(blank=True, null=True)), + ("applied_at", models.DateTimeField(blank=True, null=True)), + ("last_status", models.CharField(default="offered", max_length=20)), + ("client_version", models.CharField(blank=True, max_length=30)), + ("device", models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name="route_policy_receipt", to="control.device")), + ]), + ] diff --git a/backend/control/migrations/__init__.py b/backend/control/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/control/models.py b/backend/control/models.py new file mode 100644 index 0000000..e1fcb1e --- /dev/null +++ b/backend/control/models.py @@ -0,0 +1,1052 @@ +import hashlib +import calendar +import secrets +import uuid +from datetime import timedelta +from decimal import Decimal + +from django.conf import settings +from django.contrib.auth import get_user_model +from django.core import signing +from django.core.exceptions import ValidationError +from django.db import models, transaction +from django.utils import timezone + + +class PlanCatalogDraft(models.Model): + """Commercial proposals only. Never used for applications or provisioning. + + In particular, a team proposal must not become a per-user subscription + with a misleading shared-quota name. Prices may remain genuinely unknown. + """ + + class Scope(models.TextChoices): + PERSONAL = "personal", "个人" + TEAM = "team", "团队共享(待接入)" + + name = models.CharField("套餐名称", max_length=100) + slug = models.SlugField("草稿标识", max_length=80, unique=True) + scope = models.CharField("套餐类型", max_length=20, choices=Scope.choices) + traffic_limit_gb = models.PositiveIntegerField("月代理流量(GB)", help_text="0 表示不限代理流量,不代表无限带宽、人数或设备。") + price_cny = models.DecimalField("拟定月价(元)", max_digits=10, decimal_places=2, null=True, blank=True, + help_text="留空表示待定价,不是0元免费;填写也不会自动上架。") + member_limit = models.PositiveIntegerField("成员上限", null=True, blank=True, help_text="个人为1;团队留空表示待确认。") + device_limit = models.PositiveIntegerField("总设备上限", null=True, blank=True, help_text="团队为全部成员总数;留空表示待确认,不是无限。") + concurrent_limit = models.PositiveIntegerField("同时在线上限", null=True, blank=True, help_text="留空表示待确认,不是无限。") + description = models.TextField("草案说明", blank=True) + sort_order = models.PositiveSmallIntegerField("排序", default=10) + created_at = models.DateTimeField("创建时间", auto_now_add=True) + updated_at = models.DateTimeField("更新时间", auto_now=True) + + class Meta: + verbose_name = "套餐草稿(未上架)" + verbose_name_plural = "套餐草稿(未上架)" + ordering = ["sort_order", "pk"] + constraints = [ + models.CheckConstraint(condition=models.Q(price_cny__isnull=True) | models.Q(price_cny__gte=0), name="catalog_draft_price_nonnegative"), + models.CheckConstraint(condition=models.Q(member_limit__isnull=True) | models.Q(member_limit__gt=0), name="catalog_draft_members_positive"), + models.CheckConstraint(condition=models.Q(device_limit__isnull=True) | models.Q(device_limit__gt=0), name="catalog_draft_devices_positive"), + models.CheckConstraint(condition=models.Q(concurrent_limit__isnull=True) | models.Q(concurrent_limit__gt=0), name="catalog_draft_concurrent_positive"), + ] + + def __str__(self): + return self.name + + @property + def quota_label(self): + if self.traffic_limit_gb == 0: + return "无限代理流量" + if self.traffic_limit_gb % 1024 == 0: + return f"{self.traffic_limit_gb // 1024} TB/月" + return f"{self.traffic_limit_gb} GB/月" + + @property + def price_label(self): + return "待定价" if self.price_cny is None else f"{self.price_cny:.2f} 元/月(草稿)" + + def clean(self): + errors = {} + if self.price_cny is not None and self.price_cny < 0: + errors["price_cny"] = "月价不能为负数;未定价请留空。" + for field in ("member_limit", "device_limit", "concurrent_limit"): + value = getattr(self, field) + if value is not None and value < 1: + errors[field] = "必须大于0;待确认请留空。" + if self.scope == self.Scope.PERSONAL and self.member_limit != 1: + errors["member_limit"] = "个人套餐固定为1名使用者。" + if self.concurrent_limit and self.device_limit and self.concurrent_limit > self.device_limit: + errors["concurrent_limit"] = "同时在线上限不能超过总设备上限。" + if errors: + raise ValidationError(errors) + + +class Plan(models.Model): + class Audience(models.TextChoices): + EMPLOYEE = "employee", "内部员工" + EXTERNAL = "external", "外部联系人" + ALL = "all", "全部用户" + + name = models.CharField("套餐名称", max_length=100) + slug = models.SlugField("标识", max_length=80, unique=True) + audience = models.CharField("适用人群", max_length=20, choices=Audience.choices, default=Audience.ALL) + employee_benefit = models.BooleanField("员工福利", default=False) + price_cny = models.DecimalField("价格(元)", max_digits=10, decimal_places=2, default=Decimal("0.00")) + traffic_limit_gb = models.PositiveIntegerField("流量额度(GB)", default=0, help_text="0 表示不限流量") + duration_days = models.PositiveIntegerField("有效天数", default=30, help_text="0 表示不自动到期") + billing_months = models.PositiveSmallIntegerField("按月周期", default=0, help_text="大于0时从开通日起按自然月计算,覆盖有效天数;到期不自动扣款。") + online_payment_required = models.BooleanField("要求在线收款", default=False, help_text="可展示并接受申请;收款接入验收前不接受付款、不开放付费权限,不得人工改付款状态绕过。内部员工仍免费。") + device_limit = models.PositiveSmallIntegerField("设备数", default=3) + active = models.BooleanField("启用", default=True) + description = models.TextField("说明", blank=True) + sort_order = models.PositiveSmallIntegerField("排序", default=10) + created_at = models.DateTimeField("创建时间", auto_now_add=True) + updated_at = models.DateTimeField("更新时间", auto_now=True) + + class Meta: + verbose_name = "套餐" + verbose_name_plural = "套餐" + ordering = ["sort_order", "price_cny", "name"] + + def __str__(self): + return self.name + + @property + def traffic_limit_bytes(self): + return self.traffic_limit_gb * 1024 * 1024 * 1024 + + def price_for_user(self, user): + # The identity field is admin-managed; never infer it from is_staff, email or QR binding. + return Decimal("0.00") if getattr(user, "identity_type", None) == "employee" else self.price_cny + + def application_label(self, user=None): + amount = self.price_for_user(user) + if amount == 0: + price = "内部员工免费" if getattr(user, "identity_type", None) == "employee" else "免费" + else: + period = ("月" if self.billing_months == 1 else f"{self.billing_months}个月") if self.billing_months else (f"{self.duration_days}天" if self.duration_days else "次") + price = f"{amount:.2f}元/{period}" + quota = f"{self.traffic_limit_gb}G" if self.traffic_limit_gb else "不限流量" + waiting = " · 暂未开放付款" if self.online_payment_required and amount > 0 else "" + return f"{self.name} · {quota} · {price}{waiting}" + + def period_end(self, start): + if self.billing_months: + local = timezone.localtime(start) + index = local.year * 12 + local.month - 1 + self.billing_months + year, month = divmod(index, 12) + month += 1 + return local.replace(year=year, month=month, + day=min(local.day, calendar.monthrange(year, month)[1])) + return start + timedelta(days=self.duration_days) if self.duration_days else None + + def clean(self): + if self.price_cny < 0: + raise ValidationError({"price_cny": "套餐价格不能为负数。"}) + if self.billing_months > 12: + raise ValidationError({"billing_months": "周期最多为12个月。"}) + + +class RoutingPolicy(models.Model): + name = models.CharField("策略名称", max_length=100) + is_global = models.BooleanField("全局默认", default=False, db_index=True) + active = models.BooleanField("启用", default=True) + rules = models.JSONField( + "Mihomo 路由规则", + default=list, + help_text="按顺序填写规则,例如 DOMAIN-SUFFIX,cn,DIRECT。未填写 MATCH 时系统自动补充。", + ) + description = models.TextField("说明", blank=True) + created_at = models.DateTimeField("创建时间", auto_now_add=True) + updated_at = models.DateTimeField("更新时间", auto_now=True) + + class Meta: + verbose_name = "路由策略" + verbose_name_plural = "路由策略" + ordering = ["-is_global", "name"] + + def __str__(self): + return f"{self.name}{'(全局)' if self.is_global else ''}" + + def clean(self): + if not isinstance(self.rules, list) or any(not isinstance(rule, str) for rule in self.rules): + raise ValidationError({"rules": "路由规则必须是字符串数组。"}) + + def save(self, *args, **kwargs): + with transaction.atomic(): + if self.is_global: + RoutingPolicy.objects.exclude(pk=self.pk).filter(is_global=True).update(is_global=False) + return super().save(*args, **kwargs) + + +class Node(models.Model): + class Protocol(models.TextChoices): + VLESS_REALITY = "vless_reality", "VLESS Reality" + TROJAN_TLS = "trojan_tls", "Trojan TLS" + HYSTERIA2 = "hysteria2", "Hysteria2" + + class Status(models.TextChoices): + PREPARING = "preparing", "准备中" + ONLINE = "online", "在线" + MAINTENANCE = "maintenance", "维护" + OFFLINE = "offline", "离线" + + class OfficeAccessScope(models.TextChoices): + COMPANY_NETWORK = "company_network", "公司网络内的在职内部账号" + EXPLICIT_USERS = "explicit_users", "保留原人工白名单" + + name = models.CharField("节点名称", max_length=100) + slug = models.SlugField("节点标识", max_length=80, unique=True) + region = models.CharField("地区", max_length=100) + server = models.CharField("服务器地址", max_length=255) + port = models.PositiveIntegerField("端口") + protocol = models.CharField("协议", max_length=30, choices=Protocol.choices) + status = models.CharField("状态", max_length=20, choices=Status.choices, default=Status.PREPARING, db_index=True) + active = models.BooleanField("启用", default=True) + subscription_enabled = models.BooleanField("加入订阅", default=False) + sort_order = models.PositiveSmallIntegerField("排序", default=10) + fallback_only = models.BooleanField("仅最终备用", default=False, help_text="不参与日常负载分配,主节点不可用时才使用。") + office_only = models.BooleanField("仅办公室内网", default=False, db_default=False) + office_access_scope = models.CharField( + "办公室候选范围", max_length=24, choices=OfficeAccessScope.choices, + default=OfficeAccessScope.COMPANY_NETWORK, db_default="company_network", + help_text="公司网络模式不按员工所属办公室筛人。这里只生成网络验证候选,仍需通过登记站点的加密验证;公网IP、GPS、网关品牌都不能直接放行。", + ) + office_users = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="authorized_office_nodes", verbose_name="办公室授权员工") + sni = models.CharField("SNI/域名", max_length=255, blank=True) + reality_public_key = models.CharField("Reality 公钥", max_length=255, blank=True) + reality_short_id = models.CharField("Reality Short ID", max_length=64, blank=True) + flow = models.CharField("Flow", max_length=80, blank=True, default="xtls-rprx-vision") + transport = models.CharField("传输层", max_length=30, default="tcp") + client_fingerprint = models.CharField("客户端指纹", max_length=30, default="chrome") + skip_cert_verify = models.BooleanField("跳过证书校验", default=False) + last_seen_at = models.DateTimeField("最后上报", null=True, blank=True) + agent_version = models.CharField("节点代理版本", max_length=64, blank=True) + agent_token_digest = models.CharField("节点令牌摘要", max_length=64, blank=True, editable=False) + total_upload_bytes = models.PositiveBigIntegerField("累计上传", default=0) + total_download_bytes = models.PositiveBigIntegerField("累计下载", default=0) + created_at = models.DateTimeField("创建时间", auto_now_add=True) + updated_at = models.DateTimeField("更新时间", auto_now=True) + + class Meta: + verbose_name = "节点" + verbose_name_plural = "节点" + ordering = ["sort_order", "region", "name"] + + def __str__(self): + return f"{self.name} · {self.region}" + + def clean(self): + if not 1 <= self.port <= 65535: + raise ValidationError({"port": "端口必须在 1 到 65535 之间。"}) + if self.protocol == self.Protocol.VLESS_REALITY: + missing = [name for name in ("sni", "reality_public_key", "reality_short_id") if not getattr(self, name)] + if missing: + raise ValidationError("VLESS Reality 节点必须填写 SNI、公钥和 Short ID。") + + def set_agent_token(self, token): + self.agent_token_digest = hashlib.sha256(token.encode("utf-8")).hexdigest() + + def check_agent_token(self, token): + if not token or not self.agent_token_digest: + return False + supplied = hashlib.sha256(token.encode("utf-8")).hexdigest() + return secrets.compare_digest(self.agent_token_digest, supplied) + + def to_mihomo_proxy(self, subscription): + common = { + "name": self.name, + "server": self.server, + "port": self.port, + "udp": True, + } + credential = str(subscription.credential_uuid) + if self.protocol == self.Protocol.VLESS_REALITY: + return { + **common, + "type": "vless", + "uuid": credential, + "network": self.transport, + "tls": True, + "servername": self.sni, + "flow": self.flow, + "client-fingerprint": self.client_fingerprint, + "reality-opts": { + "public-key": self.reality_public_key, + "short-id": self.reality_short_id, + }, + } + if self.protocol == self.Protocol.TROJAN_TLS: + return { + **common, + "type": "trojan", + "password": credential, + "sni": self.sni, + "skip-cert-verify": self.skip_cert_verify, + } + if self.protocol == self.Protocol.HYSTERIA2: + return { + **common, + "type": "hysteria2", + "password": credential, + "sni": self.sni, + "skip-cert-verify": self.skip_cert_verify, + } + raise ValidationError(f"节点协议 {self.protocol} 暂不支持生成订阅。") + + +class Subscription(models.Model): + class Status(models.TextChoices): + PENDING = "pending", "待开通" + ACTIVE = "active", "使用中" + SUSPENDED = "suspended", "已暂停" + EXPIRED = "expired", "已到期" + CANCELLED = "cancelled", "已取消" + + class RouteMode(models.TextChoices): + GLOBAL = "global", "使用全局策略" + CUSTOM = "custom", "使用专用策略" + DEDICATED = "dedicated", "指定节点" + + class ProvisioningState(models.TextChoices): + PENDING = "pending", "等待下发" + ACTIVE = "active", "已下发" + FAILED = "failed", "下发失败" + REVOKE_PENDING = "revoke_pending", "等待撤销" + REVOKED = "revoked", "已撤销" + + user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name="用户", on_delete=models.PROTECT, related_name="subscriptions") + plan = models.ForeignKey(Plan, verbose_name="套餐", on_delete=models.PROTECT, related_name="subscriptions") + status = models.CharField("状态", max_length=20, choices=Status.choices, default=Status.PENDING, db_index=True) + starts_at = models.DateTimeField("开始时间", null=True, blank=True) + expires_at = models.DateTimeField("到期时间", null=True, blank=True, db_index=True) + traffic_limit_bytes = models.PositiveBigIntegerField("流量额度(字节)", default=0) + upload_bytes = models.PositiveBigIntegerField("已用上传", default=0) + download_bytes = models.PositiveBigIntegerField("已用下载", default=0) + device_limit = models.PositiveSmallIntegerField("设备数", default=3) + route_mode = models.CharField("路由模式", max_length=20, choices=RouteMode.choices, default=RouteMode.GLOBAL) + routing_policy = models.ForeignKey( + RoutingPolicy, + verbose_name="专用路由策略", + null=True, + blank=True, + on_delete=models.SET_NULL, + related_name="subscriptions", + ) + allowed_nodes = models.ManyToManyField(Node, verbose_name="指定节点", blank=True, related_name="subscriptions") + credential_uuid = models.UUIDField("节点凭据", default=uuid.uuid4, unique=True, editable=False) + token_version = models.PositiveIntegerField("订阅令牌版本", default=1, editable=False) + provisioning_state = models.CharField( + "节点下发状态", + max_length=24, + choices=ProvisioningState.choices, + default=ProvisioningState.PENDING, + ) + state_reason = models.CharField("状态说明", max_length=255, blank=True) + created_at = models.DateTimeField("创建时间", auto_now_add=True) + updated_at = models.DateTimeField("更新时间", auto_now=True) + + class Meta: + verbose_name = "订阅" + verbose_name_plural = "订阅" + ordering = ["-created_at"] + indexes = [models.Index(fields=["status", "expires_at"])] + + def __str__(self): + return f"{self.user} · {self.plan}" + + def clean(self): + if self.route_mode == self.RouteMode.CUSTOM and not self.routing_policy: + raise ValidationError({"routing_policy": "专用路由模式必须选择路由策略。"}) + if self.plan_id and self.user_id: + if self.status == self.Status.ACTIVE and self.online_payment_pending: + raise ValidationError({"status": "在线收款尚未接通,此付费套餐不能人工开通。"}) + if self.plan.audience == Plan.Audience.EMPLOYEE and self.user.identity_type != "employee": + raise ValidationError({"plan": "该套餐仅限内部员工。"}) + duplicate = Subscription.objects.exclude(pk=self.pk).filter( + user_id=self.user_id, + status__in=[self.Status.PENDING, self.Status.ACTIVE, self.Status.SUSPENDED], + ) + if duplicate.exists(): + raise ValidationError("该用户已有未结束的订阅。") + + def save(self, *args, **kwargs): + if self._state.adding and self.plan_id: + self.apply_plan_snapshot() + return super().save(*args, **kwargs) + + @property + def used_bytes(self): + return self.upload_bytes + self.download_bytes + + @property + def remaining_bytes(self): + if not self.traffic_limit_bytes: + return None + return max(0, self.traffic_limit_bytes - self.used_bytes) + + @property + def usage_percent(self): + if not self.traffic_limit_bytes: + return 0 + return min(100, round(self.used_bytes * 100 / self.traffic_limit_bytes, 1)) + + @property + def online_payment_pending(self): + # No verified-receipt adapter exists yet. Never treat an editable PAID + # flag, an enabled catalog entry, or a manually active row as a receipt. + return self.plan.online_payment_required and self.plan.price_for_user(self.user) > 0 + + @property + def is_usable(self): + if ( + self.status != self.Status.ACTIVE + or self.provisioning_state != self.ProvisioningState.ACTIVE + or not self.user.service_enabled + or self.online_payment_pending + ): + return False + if self.expires_at and self.expires_at <= timezone.now(): + return False + if self.traffic_limit_bytes and self.used_bytes >= self.traffic_limit_bytes: + return False + return True + + @property + def subscription_token(self): + if not self.pk: + return "" + return signing.dumps( + {"subscription_id": self.pk, "version": self.token_version}, + salt="toplc-vpn-subscription", + compress=True, + ) + + @property + def subscription_url(self): + if not self.pk: + return "" + return f"{settings.PUBLIC_BASE_URL}/sub/{self.subscription_token}/config.yaml" + + def apply_plan_snapshot(self): + self.traffic_limit_bytes = self.plan.traffic_limit_bytes + self.device_limit = self.plan.device_limit + + def activate(self): + if self.plan.online_payment_required and self.plan.price_for_user(self.user) > 0: + raise ValidationError("在线收款尚未接通,此套餐不能人工开通。") + if not self.user.service_enabled: + raise ValidationError("用户账号尚未审核为正常状态。") + now = timezone.now() + self.apply_plan_snapshot() + self.status = self.Status.ACTIVE + self.starts_at = self.starts_at or now + self.expires_at = self.plan.period_end(self.starts_at) + self.provisioning_state = self.ProvisioningState.PENDING + self.state_reason = "" + self.save() + + def suspend(self, reason=""): + self.status = self.Status.SUSPENDED + self.provisioning_state = self.ProvisioningState.REVOKE_PENDING + self.state_reason = reason + self.save(update_fields=["status", "provisioning_state", "state_reason", "updated_at"]) + + def cancel(self, reason=""): + self.status = self.Status.CANCELLED + self.provisioning_state = self.ProvisioningState.REVOKE_PENDING + self.state_reason = reason + self.credential_uuid = uuid.uuid4() + self.token_version += 1 + self.save( + update_fields=[ + "status", + "provisioning_state", + "state_reason", + "credential_uuid", + "token_version", + "updated_at", + ] + ) + + def rotate_subscription(self): + self.token_version += 1 + self.save(update_fields=["token_version", "updated_at"]) + + def nodes_for_subscription(self): + nodes = Node.objects.filter(active=True, subscription_enabled=True, status=Node.Status.ONLINE) + # Legacy profiles/configs must NEVER get a LAN node solely because their + # subscription includes all nodes. Local identity proof is not wired yet. + nodes = nodes.filter(office_only=False) + if self.route_mode == self.RouteMode.DEDICATED: + nodes = nodes.filter(pk__in=self.allowed_nodes.values("pk")) + return nodes.order_by("sort_order", "name") + + def office_nodes_for_authorization(self): + """Permission candidates only, NOT proof of office presence or a config grant. + + Membership of a particular office/department is NOT required in company- + network mode. Keep separate from nodes_for_subscription until the enrolled + site/network proof and encrypted ingress are implemented and tested. + """ + user = self.user + if not self.is_usable or user.identity_type != "employee" or not user.service_enabled: + return Node.objects.none() + nodes = Node.objects.filter(office_only=True, active=True, + subscription_enabled=True, status=Node.Status.ONLINE).filter( + models.Q(office_access_scope=Node.OfficeAccessScope.COMPANY_NETWORK) + | models.Q(office_access_scope=Node.OfficeAccessScope.EXPLICIT_USERS, office_users=user) + ) + if self.route_mode == self.RouteMode.DEDICATED: + nodes = nodes.filter(pk__in=self.allowed_nodes.values("pk")) + return nodes.order_by("sort_order", "name").distinct() + + def effective_routing_policy(self): + if self.route_mode == self.RouteMode.CUSTOM and self.routing_policy_id: + return self.routing_policy + return RoutingPolicy.objects.filter(is_global=True, active=True).first() + + +class PlanApplication(models.Model): + class Status(models.TextChoices): + PENDING = "pending", "待处理" + APPROVED = "approved", "已批准" + REJECTED = "rejected", "已拒绝" + CANCELLED = "cancelled", "已取消" + + class PaymentStatus(models.TextChoices): + NOT_REQUIRED = "not_required", "无需付款" + UNPAID = "unpaid", "待付款" + PAID = "paid", "已付款" + REFUNDED = "refunded", "已退款" + + user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name="申请人", on_delete=models.PROTECT, related_name="plan_applications") + plan = models.ForeignKey(Plan, verbose_name="申请套餐", on_delete=models.PROTECT, related_name="applications") + subscription = models.ForeignKey( + Subscription, + verbose_name="自动开通的订阅", + null=True, + blank=True, + editable=False, + on_delete=models.PROTECT, + related_name="plan_applications", + ) + status = models.CharField("处理状态", max_length=20, choices=Status.choices, default=Status.PENDING, db_index=True) + payment_status = models.CharField("付款状态", max_length=20, choices=PaymentStatus.choices, default=PaymentStatus.UNPAID) + note = models.TextField("申请说明", blank=True) + reviewer_note = models.TextField("审核备注", blank=True) + reviewed_by = models.ForeignKey( + settings.AUTH_USER_MODEL, + verbose_name="审核人", + null=True, + blank=True, + on_delete=models.SET_NULL, + related_name="reviewed_plan_applications", + ) + reviewed_at = models.DateTimeField("审核时间", null=True, blank=True) + created_at = models.DateTimeField("申请时间", auto_now_add=True) + updated_at = models.DateTimeField("更新时间", auto_now=True) + + class Meta: + verbose_name = "套餐申请" + verbose_name_plural = "套餐申请" + ordering = ["-created_at"] + + def __str__(self): + return f"{self.user} 申请 {self.plan}" + + def approve(self, reviewer): + with transaction.atomic(): + # All approval entry points lock user -> application -> plan -> subscription. + # Do not FOR UPDATE a nullable select_related join (PostgreSQL rejects it). + owner_id = type(self).objects.values_list("user_id", flat=True).get(pk=self.pk) + user = get_user_model().objects.select_for_update().get(pk=owner_id) + application = type(self).objects.select_for_update().get(pk=self.pk) + if application.user_id != user.pk: + raise ValidationError("申请归属已改变,请刷新后重试。") + if application.status == self.Status.APPROVED and application.subscription_id: + self.refresh_from_db() + return application.subscription + if application.status != self.Status.PENDING: + raise ValidationError("只有待处理申请可以批准。") + if not user.plan_application_allowed: + raise ValidationError("申请人账号已暂停、离职、停用或状态异常;请先在用户管理中核实,套餐审核不会恢复账号。") + application.plan = Plan.objects.select_for_update().get(pk=application.plan_id) + if not application.plan.active: + raise ValidationError("该套餐已停用,不能批准。") + if application.plan.audience not in [Plan.Audience.ALL, user.identity_type]: + raise ValidationError("套餐适用身份与申请人当前身份不符,请先核实身份或更换套餐。") + if application.plan.employee_benefit and user.identity_type != "employee": + raise ValidationError("员工福利套餐必须先核实内部员工身份。") + amount = application.plan.price_for_user(user) + if amount > 0 and application.plan.online_payment_required: + raise ValidationError("在线收款尚未接通,不能人工标记付款来开通此套餐。") + if amount > 0 and application.payment_status != self.PaymentStatus.PAID: + raise ValidationError("付费套餐必须先标记为已付款。") + if amount == 0 and application.payment_status in (self.PaymentStatus.UNPAID, self.PaymentStatus.NOT_REQUIRED): + application.payment_status = self.PaymentStatus.NOT_REQUIRED + + user.account_status = user.AccountStatus.ACTIVE + user.approved_at = timezone.now() + user.approved_by = reviewer + user.save(update_fields=["account_status", "approved_at", "approved_by"]) + + open_statuses = [Subscription.Status.PENDING, Subscription.Status.ACTIVE, Subscription.Status.SUSPENDED] + open_subscriptions = list( + Subscription.objects.select_for_update() + .filter(user=user, status__in=open_statuses) + .order_by("-updated_at", "-pk") + ) + if len(open_subscriptions) > 1: + raise ValidationError("存在多个未结束订阅,请管理员核查;本次未取消任何订阅。") + subscription = open_subscriptions[0] if open_subscriptions else Subscription(user=user, plan=application.plan) + subscription.user = user + + now = timezone.now() + subscription.plan = application.plan + subscription.apply_plan_snapshot() + subscription.status = Subscription.Status.ACTIVE + # A plan change is not an implicit renewal or a quota reset. Preserve + # existing period, usage, credential, devices, and routing policy. + if subscription.starts_at is None: + subscription.starts_at = now + subscription.expires_at = application.plan.period_end(now) + subscription.provisioning_state = Subscription.ProvisioningState.PENDING + subscription.state_reason = "" + subscription.full_clean() + subscription.save() + application.status = self.Status.APPROVED + application.subscription = subscription + application.reviewed_by = reviewer + application.reviewed_at = now + application.save( + update_fields=["status", "payment_status", "subscription", "reviewed_by", "reviewed_at", "updated_at"] + ) + self.status = application.status + self.subscription = subscription + self.reviewed_by = reviewer + self.reviewed_at = now + self.payment_status = application.payment_status + return subscription + + @classmethod + def submit(cls, *, user, plan, note=""): + with transaction.atomic(): + user = get_user_model().objects.select_for_update().get(pk=user.pk) + if not user.plan_application_allowed: + raise ValidationError("账号当前不可申请套餐,请联系管理员核实账号状态。") + plan = Plan.objects.select_for_update().get(pk=plan.pk) + audiences = [Plan.Audience.ALL, user.identity_type] + if not plan.active or plan.audience not in audiences or ( + plan.employee_benefit and user.identity_type != "employee" + ): + raise ValidationError("该套餐当前不可申请,请重新选择。") + if cls.objects.filter(user=user, status=cls.Status.PENDING).exists(): + raise ValidationError("您已有待处理申请,请等待管理员审核。") + if user.subscriptions.filter( + plan=plan, status__in=[Subscription.Status.PENDING, Subscription.Status.ACTIVE, Subscription.Status.SUSPENDED] + ).exists(): + raise ValidationError("您当前已经在使用该套餐,无需重复申请。") + return cls.objects.create( + user=user, plan=plan, note=note, + payment_status=cls.PaymentStatus.NOT_REQUIRED if plan.price_for_user(user) == 0 else cls.PaymentStatus.UNPAID, + ) + + +class UsageRecord(models.Model): + subscription = models.ForeignKey(Subscription, verbose_name="订阅", on_delete=models.CASCADE, related_name="usage_records") + node = models.ForeignKey(Node, verbose_name="节点", on_delete=models.PROTECT, related_name="usage_records") + day = models.DateField("日期") + upload_bytes = models.PositiveBigIntegerField("上传", default=0) + download_bytes = models.PositiveBigIntegerField("下载", default=0) + created_at = models.DateTimeField("创建时间", auto_now_add=True) + updated_at = models.DateTimeField("更新时间", auto_now=True) + + class Meta: + verbose_name = "每日流量" + verbose_name_plural = "每日流量" + ordering = ["-day", "subscription_id"] + constraints = [ + models.UniqueConstraint(fields=["subscription", "node", "day"], name="unique_subscription_node_day") + ] + + def __str__(self): + return f"{self.subscription} · {self.day}" + + +class HourlyUsageRecord(models.Model): + """Proxy deltas grouped by server receipt hour, not a second billing ledger.""" + subscription = models.ForeignKey(Subscription, on_delete=models.CASCADE, related_name="hourly_usage_records") + node = models.ForeignKey(Node, on_delete=models.PROTECT, related_name="hourly_usage_records") + hour = models.DateTimeField() + upload_bytes = models.PositiveBigIntegerField(default=0) + download_bytes = models.PositiveBigIntegerField(default=0) + + class Meta: + constraints = [models.UniqueConstraint(fields=["subscription", "node", "hour"], name="unique_subscription_node_hour")] + indexes = [models.Index(fields=["subscription", "hour"], name="usage_subscription_hour")] + + +class Device(models.Model): + subscription = models.ForeignKey(Subscription, verbose_name="订阅", on_delete=models.CASCADE, related_name="devices") + device_id = models.CharField("设备标识", max_length=128) + name = models.CharField("设备名称", max_length=100, blank=True) + platform = models.CharField("平台", max_length=50, blank=True) + active = models.BooleanField("允许使用", default=True) + last_seen_at = models.DateTimeField("最后在线", null=True, blank=True) + upload_bytes = models.PositiveBigIntegerField("上传", default=0) + download_bytes = models.PositiveBigIntegerField("下载", default=0) + created_at = models.DateTimeField("首次出现", auto_now_add=True) + + class Meta: + verbose_name = "设备" + verbose_name_plural = "设备" + constraints = [models.UniqueConstraint(fields=["subscription", "device_id"], name="unique_subscription_device")] + ordering = ["-last_seen_at", "name"] + + def __str__(self): + return self.name or self.device_id + + +class ClientSession(models.Model): + subscription = models.ForeignKey( + Subscription, + verbose_name="订阅", + on_delete=models.CASCADE, + related_name="client_sessions", + ) + device = models.ForeignKey( + Device, + verbose_name="设备", + on_delete=models.CASCADE, + related_name="sessions", + ) + token_digest = models.CharField("访问令牌摘要", max_length=64, unique=True, editable=False) + expires_at = models.DateTimeField("令牌到期时间", db_index=True) + last_seen_at = models.DateTimeField("最后访问", auto_now_add=True) + revoked_at = models.DateTimeField("撤销时间", null=True, blank=True, db_index=True) + created_at = models.DateTimeField("创建时间", auto_now_add=True) + assigned_node = models.ForeignKey(Node, null=True, blank=True, on_delete=models.SET_NULL, related_name="assigned_sessions", verbose_name="AI 分配节点") + dispatch_decision = models.JSONField("最近调度依据", default=dict, blank=True) + + class Meta: + verbose_name = "客户端会话" + verbose_name_plural = "客户端会话" + ordering = ["-last_seen_at"] + + def __str__(self): + return f"{self.subscription.user} · {self.device}" + + @staticmethod + def digest_token(token): + return hashlib.sha256(token.encode("utf-8")).hexdigest() + + @classmethod + def issue(cls, subscription, device, lifetime=timedelta(days=30)): + token = secrets.token_urlsafe(32) + session = cls.objects.create( + subscription=subscription, + device=device, + token_digest=cls.digest_token(token), + expires_at=timezone.now() + lifetime, + ) + return session, token + + @property + def is_valid(self): + return self.revoked_at is None and self.expires_at > timezone.now() + + +class NodeDeployment(models.Model): + subscription = models.ForeignKey( + Subscription, + verbose_name="订阅", + on_delete=models.CASCADE, + related_name="node_deployments", + ) + node = models.ForeignKey(Node, verbose_name="节点", on_delete=models.CASCADE, related_name="deployments") + deployed = models.BooleanField("已在节点生效", default=False) + applied_at = models.DateTimeField("最近生效时间", null=True, blank=True) + revoked_at = models.DateTimeField("最近撤销时间", null=True, blank=True) + last_error = models.CharField("最近错误", max_length=500, blank=True) + updated_at = models.DateTimeField("更新时间", auto_now=True) + + class Meta: + verbose_name = "节点下发状态" + verbose_name_plural = "节点下发状态" + constraints = [ + models.UniqueConstraint(fields=["subscription", "node"], name="unique_subscription_node_deployment") + ] + ordering = ["node", "subscription"] + + def __str__(self): + return f"{self.subscription} · {self.node}" + + +class NodeReport(models.Model): + node = models.ForeignKey(Node, verbose_name="节点", on_delete=models.CASCADE, related_name="reports") + report_id = models.UUIDField("报告 ID") + received_at = models.DateTimeField("接收时间", auto_now_add=True) + + class Meta: + verbose_name = "节点上报去重记录" + verbose_name_plural = "节点上报去重记录" + constraints = [models.UniqueConstraint(fields=["node", "report_id"], name="unique_node_report")] + ordering = ["-received_at"] + + def __str__(self): + return f"{self.node.slug} · {self.report_id}" + + +class NodeTrafficSample(models.Model): + node = models.ForeignKey( + Node, + verbose_name="节点", + on_delete=models.CASCADE, + related_name="traffic_samples", + ) + report = models.OneToOneField( + NodeReport, + verbose_name="节点报告", + on_delete=models.SET_NULL, + null=True, + blank=True, + related_name="traffic_sample", + ) + sampled_at = models.DateTimeField("采样时间", auto_now_add=True, db_index=True) + interval_seconds = models.PositiveSmallIntegerField("采样间隔(秒)", default=60) + upload_bytes = models.PositiveBigIntegerField("区间上传", default=0) + download_bytes = models.PositiveBigIntegerField("区间下载", default=0) + upload_bytes_per_second = models.PositiveBigIntegerField("上传速度(B/s)", default=0) + download_bytes_per_second = models.PositiveBigIntegerField("下载速度(B/s)", default=0) + active_subscriptions = models.PositiveSmallIntegerField("已下发订阅数", default=0) + + class Meta: + verbose_name = "节点流量采样" + verbose_name_plural = "节点流量采样" + ordering = ["-sampled_at"] + indexes = [ + models.Index(fields=["node", "sampled_at"], name="node_traffic_node_sample_idx"), + ] + + def __str__(self): + return f"{self.node.slug} · {self.sampled_at:%Y-%m-%d %H:%M:%S}" + + +class RouteObservation(models.Model): + class AccessKind(models.TextChoices): + HTTP = "http", "HTTP/HTTPS 网页" + SOCKET = "socket", "Socket 连接" + + class TargetType(models.TextChoices): + DOMAIN = "domain", "域名" + IP = "ip", "IP 地址" + + class Network(models.TextChoices): + TCP = "tcp", "TCP" + UDP = "udp", "UDP" + + class Outcome(models.TextChoices): + DIRECT_FAILED = "direct_failed", "直连失败" + PROXY_SUCCEEDED = "proxy_succeeded", "代理成功" + PROXY_FAILED = "proxy_failed", "代理失败" + + class FailureKind(models.TextChoices): + TIMEOUT = "timeout", "超时" + RESET = "reset", "连接重置" + DNS = "dns", "DNS 异常" + TLS = "tls", "TLS 异常" + UNREACHABLE = "unreachable", "不可达" + OTHER = "other", "其他" + + report_id = models.UUIDField("客户端报告 ID", unique=True) + subscription = models.ForeignKey( + Subscription, + verbose_name="订阅", + on_delete=models.CASCADE, + related_name="route_observations", + ) + device = models.ForeignKey( + Device, + verbose_name="设备", + on_delete=models.CASCADE, + related_name="route_observations", + ) + node = models.ForeignKey( + Node, + verbose_name="节点", + on_delete=models.SET_NULL, + null=True, + blank=True, + related_name="route_observations", + ) + target_type = models.CharField("目标类型", max_length=10, choices=TargetType.choices) + target = models.CharField("目标", max_length=253, db_index=True) + port = models.PositiveIntegerField("端口") + access_kind = models.CharField( + "访问方式", + max_length=10, + choices=AccessKind.choices, + default=AccessKind.SOCKET, + db_index=True, + ) + network = models.CharField("网络协议", max_length=6, choices=Network.choices) + outcome = models.CharField("结果", max_length=24, choices=Outcome.choices, db_index=True) + failure_kind = models.CharField( + "失败类型", + max_length=20, + choices=FailureKind.choices, + default=FailureKind.OTHER, + ) + client_version = models.CharField("客户端版本", max_length=30, blank=True) + evidence_kind = models.CharField("验证方式", max_length=12, blank=True, db_default="") + related_report_id = models.UUIDField("对应直连失败报告", null=True, blank=True) + scope = models.CharField("观测范围", max_length=20, default="public", db_default="public") + received_at = models.DateTimeField("接收时间", auto_now_add=True, db_index=True) + + class Meta: + verbose_name = "AI 路由观测" + verbose_name_plural = "AI 路由观测" + ordering = ["-received_at"] + indexes = [ + models.Index(fields=["target_type", "target", "received_at"], name="route_obs_target_time_idx"), + models.Index(fields=["device", "received_at"], name="route_obs_device_time_idx"), + ] + + def __str__(self): + return f"{self.target}:{self.port} · {self.get_outcome_display()}" + + +class RoutePolicyReceipt(models.Model): + device = models.OneToOneField(Device, on_delete=models.CASCADE, related_name="route_policy_receipt") + offered_revision = models.CharField(max_length=64, blank=True) + applied_revision = models.CharField(max_length=64, blank=True) + offered_at = models.DateTimeField(null=True, blank=True) + applied_at = models.DateTimeField(null=True, blank=True) + last_status = models.CharField(max_length=20, default="offered") + client_version = models.CharField(max_length=30, blank=True) + + +class LearnedRouteRule(models.Model): + class Source(models.TextChoices): + PRESET = "preset", "系统预置" + AI = "ai", "AI 学习" + MANUAL = "manual", "管理员添加" + + class MatchMode(models.TextChoices): + EXACT = "exact", "精确目标" + SUFFIX = "suffix", "域名及其子域" + + class Status(models.TextChoices): + PENDING = "pending", "学习中" + ACTIVE = "active", "已生效" + DISABLED = "disabled", "已禁用" + + target_type = models.CharField("目标类型", max_length=10, choices=RouteObservation.TargetType.choices) + target = models.CharField("目标", max_length=253) + source = models.CharField("规则来源", max_length=12, choices=Source.choices, default=Source.AI, db_index=True) + match_mode = models.CharField( + "匹配方式", + max_length=12, + choices=MatchMode.choices, + default=MatchMode.EXACT, + help_text="域名预置规则通常选择“域名及其子域”;IP 地址只能精确匹配。", + ) + status = models.CharField("状态", max_length=12, choices=Status.choices, default=Status.PENDING, db_index=True) + confidence = models.DecimalField("置信度", max_digits=5, decimal_places=4, default=Decimal("0")) + failure_reports = models.PositiveIntegerField("直连失败数", default=0) + proxy_success_reports = models.PositiveIntegerField("代理成功数", default=0) + distinct_devices = models.PositiveIntegerField("设备数", default=0) + reason = models.CharField("学习依据", max_length=500, blank=True) + valid_until = models.DateTimeField("有效期至", null=True, blank=True, db_index=True) + manually_locked = models.BooleanField("人工锁定", default=False, help_text="启用后 AI 不再自动改变状态。") + first_seen_at = models.DateTimeField("首次发现", auto_now_add=True) + last_evaluated_at = models.DateTimeField("最近评估", null=True, blank=True) + updated_at = models.DateTimeField("更新时间", auto_now=True) + + class Meta: + verbose_name = "智能代理规则" + verbose_name_plural = "智能代理规则" + ordering = ["-status", "-confidence", "target"] + constraints = [ + models.UniqueConstraint(fields=["target_type", "target"], name="unique_learned_route_target") + ] + + def __str__(self): + return f"{self.target} · {self.get_status_display()}" + + def clean(self): + if self.target_type == RouteObservation.TargetType.IP and self.match_mode != self.MatchMode.EXACT: + raise ValidationError({"match_mode": "IP 地址只能使用精确目标匹配。"}) + + @property + def is_effective(self): + return self.status == self.Status.ACTIVE and (not self.valid_until or self.valid_until > timezone.now()) + + +class VpnAiFinding(models.Model): + class Category(models.TextChoices): + ROUTING = "routing", "路由学习" + NODE = "node", "节点运维" + SUBSCRIPTION = "subscription", "订阅诊断" + SECURITY = "security", "安全" + + class Severity(models.TextChoices): + INFO = "info", "提示" + WARNING = "warning", "警告" + CRITICAL = "critical", "严重" + + class Status(models.TextChoices): + OPEN = "open", "待处理" + RESOLVED = "resolved", "已恢复" + IGNORED = "ignored", "已忽略" + + fingerprint = models.CharField("诊断指纹", max_length=255, unique=True, editable=False) + category = models.CharField("类别", max_length=20, choices=Category.choices) + severity = models.CharField("等级", max_length=12, choices=Severity.choices) + status = models.CharField("状态", max_length=12, choices=Status.choices, default=Status.OPEN, db_index=True) + title = models.CharField("标题", max_length=200) + summary = models.TextField("诊断说明") + evidence = models.JSONField("证据", default=dict, blank=True) + first_seen_at = models.DateTimeField("首次发现", auto_now_add=True) + last_seen_at = models.DateTimeField("最近发现", auto_now=True) + resolved_at = models.DateTimeField("恢复时间", null=True, blank=True) + + class Meta: + verbose_name = "vpn-ai 诊断" + verbose_name_plural = "vpn-ai 诊断" + ordering = ["status", "-severity", "-last_seen_at"] + + def __str__(self): + return self.title + + +class VpnAiRuntime(models.Model): + service_name = models.CharField("服务名称", max_length=100, unique=True, default="vpn-ai") + version = models.CharField("版本", max_length=30, default="0.2.0") + worker_id = models.CharField("工作实例", max_length=100, blank=True) + started_at = models.DateTimeField("启动时间", null=True, blank=True) + last_heartbeat_at = models.DateTimeField("最近心跳", null=True, blank=True, db_index=True) + last_cycle_at = models.DateTimeField("最近巡检", null=True, blank=True) + cycle_count = models.PositiveBigIntegerField("巡检次数", default=0) + observations_7d = models.PositiveIntegerField("近 7 天观测", default=0) + active_rules = models.PositiveIntegerField("生效规则", default=0) + open_findings = models.PositiveIntegerField("待处理诊断", default=0) + last_error = models.TextField("最近错误", blank=True) + dispatch_snapshot = models.JSONField("负载调度快照", default=dict, blank=True) + updated_at = models.DateTimeField("更新时间", auto_now=True) + + class Meta: + verbose_name = "vpn-ai 控制台" + verbose_name_plural = "vpn-ai 控制台" + + def __str__(self): + return self.service_name + + @property + def is_healthy(self): + return bool(self.last_heartbeat_at and self.last_heartbeat_at >= timezone.now() - timedelta(minutes=3)) + + +# Management-only team models are discovered by Django without coupling them +# to the live per-person credential/provisioning path. +from .team_models import Team, TeamMembership, TeamAuditEvent # noqa: E402,F401 diff --git a/backend/control/plan_catalog.py b/backend/control/plan_catalog.py new file mode 100644 index 0000000..0baf789 --- /dev/null +++ b/backend/control/plan_catalog.py @@ -0,0 +1,26 @@ +"""Proposed quota tiers. The approved 8 CNY/1024 GB Plan is not modified.""" + +from .models import PlanCatalogDraft + + +PERSONAL_QUOTAS_GB = (64, 128, 256, 512, 768, 1536, 2048, 3072, 4096, 5120, 8192, 10240) +TEAM_MEMBER_COUNTS = (3, 5, 10, 20, 50) + + +def proposed_catalog(): + proposals = [] + for index, quota in enumerate((*PERSONAL_QUOTAS_GB, 0), start=1): + name = f"个人 {quota}G 月度套餐" if quota else "个人无限流量月度套餐" + slug = f"personal-monthly-{quota}g" if quota else "personal-monthly-unlimited" + proposals.append(dict(name=name, slug=slug, scope=PlanCatalogDraft.Scope.PERSONAL, + traffic_limit_gb=quota, price_cny=None, member_limit=1, device_limit=3, + concurrent_limit=2, sort_order=100 + index, + description="个人月度草案,仅统计代理流量;建议3台绑定设备、2台同时在线,尚未实施。原8元/月1024G套餐保持不变。无限流量不代表无限带宽或设备。月价须确认;未上架、不收款、不自动续扣。")) + for index, members in enumerate((*TEAM_MEMBER_COUNTS, 0), start=1): + name = f"团队 {members}人 {members}T 月度套餐" if members else "团队无限流量月度套餐" + slug = f"team-monthly-{members}-members" if members else "team-monthly-unlimited" + proposals.append(dict(name=name, slug=slug, scope=PlanCatalogDraft.Scope.TEAM, + traffic_limit_gb=members * 1024, price_cny=None, member_limit=members or None, + device_limit=members * 3 or None, concurrent_limit=members * 2 or None, sort_order=200 + index, + description="拟按人数购买、独立账号共用团队代理流量池;建议每人3台绑定设备、2台同时在线,均待确认与实施。每人1TB组成共享池,可增购流量。团队共享账本尚未接入,不得直接用个人订阅开通。仅本公司的核实内部员工免费。无限流量档人数/带宽/月价另定。未上架、不收款、不自动续扣。")) + return proposals diff --git a/backend/control/private_auxiliary.py b/backend/control/private_auxiliary.py new file mode 100644 index 0000000..0aa8056 --- /dev/null +++ b/backend/control/private_auxiliary.py @@ -0,0 +1,198 @@ +"""Private auxiliary contract, disabled until the board's auth adapter is accepted. + +No public Node/NodeDeployment registration, shared subscription UUID, office/GPS +lookup, route advertisement, or production credential is created here. +""" +import hashlib +import json +import re +import secrets +from datetime import timedelta + +from django.conf import settings +from django.http import JsonResponse +from django.utils import timezone +from django.utils.crypto import salted_hmac +from django.views.decorators.csrf import csrf_exempt +from django.views.decorators.http import require_http_methods + +from .models import ClientSession, Subscription +from .services import client_routing_rules + +SLUG = "jinan-private-aux" +NAME = "优创未来·济南办(Zero3)" +ADDRESS = "192.168.50.111" +SCOPE = "private_auxiliary" + + +def registered_address(): + address = getattr(settings, "VPN_PRIVATE_AUXILIARY_ADDRESS", ADDRESS) + return address if address in (ADDRESS, "192.168.50.170") else None + + +def registered_name(): + return "济南(博翠明湖)" if registered_address() == "192.168.50.170" else NAME + + +def connect_address(): + """Keep the phone's Ethernet registration distinct from its tailnet front door.""" + registered = registered_address() + endpoint = getattr(settings, "VPN_PRIVATE_AUXILIARY_CONNECT_ADDRESS", "") + if not isinstance(endpoint, str): + return None + endpoint = endpoint or registered + if endpoint == registered: + return registered + if registered == "192.168.50.170" and endpoint == "100.64.0.4": + return endpoint + if registered == "192.168.50.170" and endpoint == "vpn.toplc.cn": + return endpoint + return None + + +def connection_endpoints(): + address = connect_address() + if registered_address() == "192.168.50.170": + endpoints = [{"address": "100.64.0.4", "probe_ipv4": "100.64.0.4", "port": 18081}, + {"address": "vpn.toplc.cn", "probe_ipv4": "192.0.2.1", "port": 11080}] + if address == "192.168.50.170": + endpoints.insert(0, {"address": address, "probe_ipv4": address, "port": 18081}) + return endpoints + return [{"address": ADDRESS, "probe_ipv4": ADDRESS, "port": 18081}] + + +def site_config(for_verification=False): + """Only a deliberately registered leaf/key pair can advertise the endpoint.""" + if not getattr(settings, "VPN_PRIVATE_AUXILIARY_ENABLED", False) and not ( + for_verification and getattr(settings, "VPN_PRIVATE_AUXILIARY_VALIDATION_DEVICE_ID", 0) > 0 + ): + return None + if registered_address() is None or connect_address() is None: + return None + pin = getattr(settings, "VPN_PRIVATE_AUXILIARY_TLS_LEAF_SHA256", "") + agent_hash = getattr(settings, "VPN_PRIVATE_AUXILIARY_AGENT_TOKEN_SHA256", "") + if not isinstance(pin, str) or not re.fullmatch(r"[a-fA-F0-9]{64}", pin): + return None + if not isinstance(agent_hash, str) or not re.fullmatch(r"[a-fA-F0-9]{64}", agent_hash): + return None + return pin.lower(), agent_hash.lower() + + +def permitted(subscription): + # Private metering and dedicated/custom policy admission are NOT yet wired. + # Never let this auxiliary bypass a paid quota or a restricted subscription. + return (subscription.is_usable and subscription.user.identity_type == "employee" + and subscription.route_mode == Subscription.RouteMode.GLOBAL + and subscription.traffic_limit_bytes == 0) + + +def profile_grants(subscription): + site = site_config() + if not site or not permitted(subscription): + return [] + primary = next(e for e in connection_endpoints() if e["address"] == connect_address()) + return [{"slug": SLUG, "name": registered_name(), "region": "济南", "status": "candidate", + "probe_ipv4": primary["probe_ipv4"], "probe_port": primary["port"], + "connect_address": primary["address"], "connection_endpoints": connection_endpoints(), + "tls_leaf_sha256": site[0], "contract": 1, + "expires_at": (timezone.now() + timedelta(minutes=15)).isoformat()}] + + +def device_credential(session): + # This is NOT the management bearer. Binding includes the login-session + # digest and device; logout/key rotation invalidates the derived credential. + payload = f"{SLUG}|{session.pk}|{session.device_id}|{session.token_digest}" + mac = salted_hmac("ucvl.private-auxiliary.v1", payload, algorithm="sha256").hexdigest() + return f"{session.pk}.{mac}" + + +def credential_username(session): + return f"ucvl-device-{session.device_id}" + + +def reply(payload, status=200): + response = JsonResponse(payload, status=status) + response["Cache-Control"] = "no-store" + return response + + +@require_http_methods(["GET"]) +def client_config(request): + from .views import _authenticate_client_session + session, error = _authenticate_client_session(request) + if error: + return error + site = site_config() + route = request.GET.get("route", "smart") + if not site or not permitted(session.subscription) or request.GET.get("node") != SLUG: + # 404 means private-only unavailable -> automatic public fallback; + # reserve 401/403 above for invalid global account/device/session. + return reply({"error": "私有辅助节点暂未开放。"}, 404) + if route not in ("smart", "global"): + return reply({"error": "私有辅助节点仅支持智能或全局 TCP 代理。"}, 400) + selected_address = request.GET.get("endpoint", connect_address()) + selected = next((e for e in connection_endpoints() if e["address"] == selected_address), None) + if selected is None: + return reply({"error": "所选连接入口未登记。"}, 400) + expiry = min(timezone.now() + timedelta(minutes=10), session.expires_at) + if session.subscription.expires_at: + expiry = min(expiry, session.subscription.expires_at) + sniff = {"enabled": True, "destOverride": ["http", "tls"], "routeOnly": True} + config = { + "log": {"loglevel": "warning"}, + "inbounds": [ + {"tag": "socks-in", "listen": "127.0.0.1", "port": 10808, "protocol": "socks", + "settings": {"auth": "noauth", "udp": False}, "sniffing": sniff}, + {"tag": "http-in", "listen": "127.0.0.1", "port": 10809, "protocol": "http", + "settings": {}, "sniffing": sniff}], + "outbounds": [ + {"tag": "proxy", "protocol": "socks", "settings": {"servers": [ + {"address": selected["address"], "port": selected["port"], "users": [ + {"user": credential_username(session), "pass": device_credential(session)}]}]}, + "streamSettings": {"network": "tcp", "security": "tls", "tlsSettings": { + "serverName": "zero3-test", "minVersion": "1.2", "pinnedPeerCertSha256": site[0]}}}, + {"tag": "direct", "protocol": "freedom"}, {"tag": "block", "protocol": "blackhole"}], + "routing": {"domainStrategy": "IPIfNonMatch", "rules": client_routing_rules(route)}} + return reply({"connection_scope": SCOPE, "config_contract": 3, + "config_expires_at": expiry.isoformat(), "node": {"slug": SLUG, "name": registered_name(), "region": "济南"}, + "route_mode": route, "config": config}) + + +@csrf_exempt +@require_http_methods(["POST"]) +def verify_device(request): + """Board checks CONNECT and every <=30s. Optional single-device acceptance + does not advertise the node or supply proxy credentials to ordinary clients. + """ + site = site_config(for_verification=True) + header = request.headers.get("Authorization", "") + agent = header[7:] if header.startswith("Bearer ") else "" + if not site or not 32 <= len(agent) <= 256 or not secrets.compare_digest( + hashlib.sha256(agent.encode()).hexdigest(), site[1]): + return reply({"allow": False}, 401) + if len(request.body) > 2048: + return reply({"allow": False}, 400) + try: + body = json.loads(request.body) + if not isinstance(body, dict) or body.get("node") != SLUG or body.get("tls_leaf_sha256") != site[0]: + raise ValueError + token = body["credential"] + if not isinstance(token, str) or not re.fullmatch(r"[1-9][0-9]{0,18}\.[a-f0-9]{64}", token): + raise ValueError + session = ClientSession.objects.select_related("device", "subscription__user", "subscription__plan").get( + pk=int(token.partition(".")[0])) + valid = (session.is_valid and session.device.active and session.device.subscription_id == session.subscription_id + and permitted(session.subscription) and body.get("username") == credential_username(session) + and secrets.compare_digest(token, device_credential(session))) + if not getattr(settings, "VPN_PRIVATE_AUXILIARY_ENABLED", False): + valid = valid and session.device_id == getattr(settings, "VPN_PRIVATE_AUXILIARY_VALIDATION_DEVICE_ID", 0) + if not valid: + return reply({"allow": False}, 403) + ttl = min(30, int((session.expires_at - timezone.now()).total_seconds())) + if session.subscription.expires_at: + ttl = min(ttl, int((session.subscription.expires_at - timezone.now()).total_seconds())) + if ttl <= 0: + return reply({"allow": False}, 403) + return reply({"allow": True, "lease_seconds": ttl}) + except (KeyError, TypeError, ValueError, ClientSession.DoesNotExist): + return reply({"allow": False}, 403) diff --git a/backend/control/services.py b/backend/control/services.py new file mode 100644 index 0000000..249cba9 --- /dev/null +++ b/backend/control/services.py @@ -0,0 +1,217 @@ +from django.db.models import Q +from django.utils import timezone + +import yaml + +from .models import LearnedRouteRule, RouteObservation, Subscription + + +def desired_subscriptions_for_node(node): + # Candidate visibility is not permission to install reusable account UUIDs + # on an office relay. The legacy node-sync protocol carries no enrolled-site + # proof or per-device lease; leave office provisioning fail-closed until that + # separate protocol is implemented and accepted. + if node.office_only: + return Subscription.objects.none() + return ( + Subscription.objects.select_related("user", "plan") + .filter( + status=Subscription.Status.ACTIVE, + user__is_active=True, + user__account_status="active", + ) + .exclude( + Q(plan__online_payment_required=True, plan__price_cny__gt=0) + & ~Q(user__identity_type="employee") + ) + .filter( + Q(route_mode__in=[Subscription.RouteMode.GLOBAL, Subscription.RouteMode.CUSTOM]) + | Q(route_mode=Subscription.RouteMode.DEDICATED, allowed_nodes=node) + ) + .distinct() + .order_by("pk") + ) + + +def render_mihomo(subscription): + proxies = [node.to_mihomo_proxy(subscription) for node in subscription.nodes_for_subscription()] + node_names = [proxy["name"] for proxy in proxies] + if not proxies: + raise ValueError("当前订阅没有可用节点。") + + rules = [] + policy = subscription.effective_routing_policy() + if policy: + rules.extend(rule.strip() for rule in policy.rules if rule and rule.strip()) + if not any(rule.upper().startswith("MATCH,") for rule in rules): + rules.append("MATCH,节点选择") + + config = { + "mixed-port": 7890, + "allow-lan": False, + "mode": "rule", + "log-level": "info", + "ipv6": True, + "unified-delay": True, + "tcp-concurrent": True, + "proxies": proxies, + "proxy-groups": [ + { + "name": "节点选择", + "type": "select", + "proxies": ["自动选择", *node_names, "DIRECT"], + }, + { + "name": "自动选择", + "type": "fallback", + "proxies": node_names, + "url": "https://www.gstatic.com/generate_204", + "interval": 300, + }, + ], + "rules": rules, + } + return yaml.safe_dump(config, allow_unicode=True, sort_keys=False, width=120) + + +def client_routing_rules(route_mode): + if route_mode not in {"smart", "global", "direct"}: + raise ValueError("不支持的路由模式。") + + routing_rules = [ + { + "type": "field", + "ip": ["geoip:private"], + "outboundTag": "direct", + } + ] + if route_mode == "smart": + learned_rules = LearnedRouteRule.objects.filter( + status=LearnedRouteRule.Status.ACTIVE, + ).exclude(source=LearnedRouteRule.Source.AI).filter( + Q(valid_until__isnull=True) | Q(valid_until__gt=timezone.now())) + learned_domains = [ + ( + f"domain:{rule.target}" + if rule.match_mode == LearnedRouteRule.MatchMode.SUFFIX + else f"full:{rule.target}" + ) + for rule in learned_rules.filter(target_type=RouteObservation.TargetType.DOMAIN).only( + "target", "match_mode" + ) + ] + learned_ips = [ + f"{target}/{'128' if ':' in target else '32'}" + for target in learned_rules.filter(target_type=RouteObservation.TargetType.IP).values_list("target", flat=True) + ] + if learned_domains: + routing_rules.append({"type": "field", "domain": learned_domains, "outboundTag": "proxy", "ruleTag": "ucvl-learned"}) + if learned_ips: + routing_rules.append({"type": "field", "ip": learned_ips, "outboundTag": "proxy", "ruleTag": "ucvl-learned"}) + routing_rules.extend( + [ + { + "type": "field", + "domain": ["geosite:category-ads-all"], + "outboundTag": "block", + }, + { + "type": "field", + "domain": ["geosite:cn"], + "outboundTag": "direct", + }, + { + "type": "field", + "ip": ["geoip:cn"], + "outboundTag": "direct", + }, + { + "type": "field", + "network": "tcp,udp", + "outboundTag": "direct", + }, + ] + ) + elif route_mode == "direct": + routing_rules.append( + { + "type": "field", + "network": "tcp,udp", + "outboundTag": "direct", + } + ) + + return routing_rules + + +def render_xray_client(subscription, node, route_mode="smart"): + if node.office_only: + raise ValueError("办公室节点接入验证尚未完成,不能生成普通客户端配置。") + if node.protocol != node.Protocol.VLESS_REALITY: + raise ValueError("优创⁺纵横家客户端当前仅支持 VLESS Reality 节点。") + routing_rules = client_routing_rules(route_mode) + sniffing = { + "enabled": True, + "destOverride": ["http", "tls", "quic"], + "routeOnly": True, + } + return { + "log": {"loglevel": "warning"}, + "inbounds": [ + { + "tag": "socks-in", + "listen": "127.0.0.1", + "port": 10808, + "protocol": "socks", + "settings": {"auth": "noauth", "udp": True}, + "sniffing": sniffing, + }, + { + "tag": "http-in", + "listen": "127.0.0.1", + "port": 10809, + "protocol": "http", + "settings": {}, + "sniffing": sniffing, + }, + ], + "outbounds": [ + { + "tag": "proxy", + "protocol": "vless", + "settings": { + "vnext": [ + { + "address": node.server, + "port": node.port, + "users": [ + { + "id": str(subscription.credential_uuid), + "encryption": "none", + "flow": node.flow, + } + ], + } + ] + }, + "streamSettings": { + "network": node.transport, + "security": "reality", + "realitySettings": { + "show": False, + "fingerprint": node.client_fingerprint, + "serverName": node.sni, + "password": node.reality_public_key, + "shortId": node.reality_short_id, + "spiderX": "", + }, + }, + }, + {"tag": "direct", "protocol": "freedom"}, + {"tag": "block", "protocol": "blackhole"}, + ], + "routing": { + "domainStrategy": "IPIfNonMatch", + "rules": routing_rules, + }, + } diff --git a/backend/control/signals.py b/backend/control/signals.py new file mode 100644 index 0000000..a63de94 --- /dev/null +++ b/backend/control/signals.py @@ -0,0 +1,32 @@ +from django.db import transaction +from django.db.models import Sum +from django.db.models.signals import post_delete, post_save +from django.dispatch import receiver + +from .models import Subscription, UsageRecord +from .usage_accounting import lock_usage_subscriptions + + +def recompute_subscription_usage(subscription_id): + with transaction.atomic(): + lock_usage_subscriptions([subscription_id]) + # Aggregate AFTER acquiring the shared parent lock. Independent node + # rows are not sufficient to serialize a subscription-wide total. + totals = UsageRecord.objects.filter(subscription_id=subscription_id).aggregate( + upload=Sum("upload_bytes"), + download=Sum("download_bytes"), + ) + Subscription.objects.filter(pk=subscription_id).update( + upload_bytes=totals["upload"] or 0, + download_bytes=totals["download"] or 0, + ) + + +@receiver(post_save, sender=UsageRecord) +def usage_saved(sender, instance, **kwargs): + recompute_subscription_usage(instance.subscription_id) + + +@receiver(post_delete, sender=UsageRecord) +def usage_deleted(sender, instance, **kwargs): + recompute_subscription_usage(instance.subscription_id) diff --git a/backend/control/tailscale_endpoint.py b/backend/control/tailscale_endpoint.py new file mode 100644 index 0000000..ba5ca83 --- /dev/null +++ b/backend/control/tailscale_endpoint.py @@ -0,0 +1,67 @@ +"""Optional same-node transport hint; never an authorization or dispatch policy.""" +import ipaddress +import json +import re + +from django.conf import settings + +from .models import Node + + +_TAILSCALE_IPV4 = ipaddress.ip_network("100.64.0.0/10") + + +def _unique_object(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError("Duplicate endpoint setting") + result[key] = value + return result + + +def _configured_endpoints(): + # Parse only administrator-supplied settings, never request parameters. + raw = getattr(settings, "VPN_TAILSCALE_ENDPOINTS_JSON", "") + if not isinstance(raw, str) or not raw or len(raw) > 16384: + return {} + try: + entries = json.loads(raw, object_pairs_hook=_unique_object) + if not isinstance(entries, dict) or len(entries) > 64: + return {} + for slug, endpoint in entries.items(): + if not re.fullmatch(r"[a-zA-Z0-9_-]{1,100}", slug): + return {} + if not isinstance(endpoint, dict) or set(endpoint) != {"address", "port"}: + return {} + address, port = endpoint["address"], endpoint["port"] + if not isinstance(address, str): + return {} + parsed = ipaddress.IPv4Address(address) + if (str(parsed) != address or parsed not in _TAILSCALE_IPV4 + or parsed in (_TAILSCALE_IPV4.network_address, _TAILSCALE_IPV4.broadcast_address) + or address == "100.100.100.100"): + return {} + if type(port) is not int or not 1 <= port <= 65535: + return {} + return entries + except (ValueError, TypeError, RecursionError): + # Invalid optional configuration must not break the existing public entry. + return {} + + +def client_tailscale_endpoint(session, node): + """Called after config authentication/rendering; recheck the grant defensively.""" + if getattr(settings, "VPN_TAILSCALE_ENDPOINT_ENABLED", False) is not True: + return None + subscription = session.subscription + if (not session.is_valid or not session.device.active + or session.device.subscription_id != session.subscription_id + or subscription.user.identity_type != "employee" or not subscription.is_usable): + return None + endpoint = _configured_endpoints().get(node.slug) + if endpoint is None or not subscription.nodes_for_subscription().filter( + pk=node.pk, protocol=Node.Protocol.VLESS_REALITY).exists(): + return None + return {"contract": 1, "node_slug": node.slug, + "address": endpoint["address"], "port": endpoint["port"]} diff --git a/backend/control/team_models.py b/backend/control/team_models.py new file mode 100644 index 0000000..027c990 --- /dev/null +++ b/backend/control/team_models.py @@ -0,0 +1,75 @@ +from django.conf import settings +from django.core.exceptions import ValidationError +from django.db import models + + +class Team(models.Model): + name = models.CharField("团队名称", max_length=100) + owner = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name="所有者", on_delete=models.PROTECT, related_name="owned_vpn_teams") + active = models.BooleanField("启用团队管理", default=True, + help_text="仅管理空间,不等于代理服务已开通;不改变成员的个人账号或个人订阅。") + plan_draft = models.ForeignKey("control.PlanCatalogDraft", verbose_name="意向团队套餐(未开通)", + on_delete=models.PROTECT, null=True, blank=True, + limit_choices_to={"scope": "team"}, related_name="interested_teams") + setup_member_limit = models.PositiveIntegerField("筹备成员上限(含所有者)", default=3, + help_text="包含已加入及待接受邀请;只是管理空间人数,不是已购买席位,不开通代理。") + created_at = models.DateTimeField("创建时间", auto_now_add=True) + updated_at = models.DateTimeField("更新时间", auto_now=True) + + class Meta: + verbose_name = "团队管理" + verbose_name_plural = "团队管理" + ordering = ["-created_at"] + constraints = [models.CheckConstraint(condition=models.Q(setup_member_limit__gt=0), name="team_setup_members_positive")] + + def __str__(self): + return self.name + + @property + def package_state(self): + return "意向套餐 · 待开通" if self.plan_draft_id else "尚未配置团队套餐" + + def clean(self): + if self.setup_member_limit < 1: + raise ValidationError({"setup_member_limit": "成员上限至少为1(所有者)。"}) + if self.plan_draft_id and self.plan_draft.scope != "team": + raise ValidationError({"plan_draft": "只能关联团队套餐草稿,不能把个人套餐变成共享套餐。"}) + if self.pk and 1 + self.memberships.filter(status__in=["active", "invited"]).exclude(user_id=self.owner_id).count() > self.setup_member_limit: + raise ValidationError({"setup_member_limit": "上限不能低于现有成员和待接受邀请总数。"}) + + +class TeamMembership(models.Model): + class Role(models.TextChoices): + ADMIN = "admin", "团队管理员" + MEMBER = "member", "成员" + + class Status(models.TextChoices): + INVITED = "invited", "待本人接受" + ACTIVE = "active", "已加入" + REMOVED = "removed", "已退出/移除" + + team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="memberships", verbose_name="团队") + user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="vpn_team_memberships", verbose_name="成员账号") + role = models.CharField("团队角色", choices=Role.choices, max_length=12, default=Role.MEMBER) + status = models.CharField("加入状态", choices=Status.choices, max_length=12, default=Status.INVITED) + invited_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="sent_vpn_team_invites", verbose_name="邀请人") + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + + class Meta: + verbose_name = "团队成员" + verbose_name_plural = "团队成员" + constraints = [models.UniqueConstraint(fields=["team", "user"], name="unique_team_member")] + + +class TeamAuditEvent(models.Model): + team = models.ForeignKey(Team, on_delete=models.PROTECT, related_name="audit_events", verbose_name="团队") + actor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="team_actions", verbose_name="操作人") + subject = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.PROTECT, related_name="team_subject_actions", verbose_name="目标成员") + action = models.CharField("操作", max_length=32) + created_at = models.DateTimeField("时间", auto_now_add=True) + + class Meta: + verbose_name = "团队权限审计" + verbose_name_plural = "团队权限审计" + ordering = ["-created_at", "-pk"] diff --git a/backend/control/team_services.py b/backend/control/team_services.py new file mode 100644 index 0000000..c67208f --- /dev/null +++ b/backend/control/team_services.py @@ -0,0 +1,122 @@ +"""Management-space permissions. No shared VPN credentials or payment grants.""" +from django.contrib.auth import get_user_model +from django.core.exceptions import PermissionDenied, ValidationError +from django.db import transaction +from django.db.models import Q +from django.shortcuts import get_object_or_404 + +from .team_models import Team, TeamMembership, TeamAuditEvent + + +def visible_teams(user): + if not user.service_enabled: + return Team.objects.none() + return Team.objects.filter(active=True).filter( + Q(owner=user) | Q(memberships__user=user, memberships__status="active") + ).select_related("plan_draft", "owner").distinct() + + +def role_for(team, user): + if not user.service_enabled or not team.active: + return None + if team.owner_id == user.pk: + return "owner" + return team.memberships.filter(user=user, status="active").values_list("role", flat=True).first() + + +def locked_team_for_actor(team_id, actor): + # A common parent lock serializes membership changes and permission checks. + # All team mutations use it; stale browser pages cannot retain revoked roles. + team = get_object_or_404(Team.objects.select_for_update(), pk=team_id, active=True) + actor = get_user_model().objects.get(pk=actor.pk) + role = role_for(team, actor) + if role is None: + raise PermissionDenied("无权访问该团队。") + return team, actor, role + + +@transaction.atomic +def create_team(actor, name): + actor = get_user_model().objects.select_for_update().get(pk=actor.pk) + if not actor.service_enabled: + raise PermissionDenied("账号需审核正常后才能创建团队。") + if Team.objects.filter(owner=actor, active=True).count() >= 5: + raise ValidationError("最多筹备5个团队;如需更多请联系平台管理员。") + team = Team(name=name.strip(), owner=actor) + team.full_clean() + team.save() + TeamAuditEvent.objects.create(team=team, actor=actor, action="created") + return team + + +@transaction.atomic +def invite_member(team_id, actor, username): + team, actor, role = locked_team_for_actor(team_id, actor) + if role not in ("owner", "admin"): + raise PermissionDenied("只有团队管理者可以邀请成员。") + target = get_user_model().objects.filter(username=username.strip(), is_active=True, account_status="active").first() + if not target or target.pk in (team.owner_id, actor.pk): + raise ValidationError("无法邀请该账号,请确认账号已注册、审核正常且不是自己或所有者。") + membership = team.memberships.filter(user=target).first() + if membership and membership.status in ("active", "invited"): + raise ValidationError("该账号已加入或已有待接受邀请。") + occupied = 1 + team.memberships.exclude(user_id=team.owner_id).filter(status__in=("active", "invited")).count() + if occupied >= team.setup_member_limit: + raise ValidationError("团队筹备成员名额已满(包含待接受邀请)。") + if membership is None: + membership = TeamMembership(team=team, user=target) + membership.role = "member" # Only an owner can promote after consent. + membership.status = "invited" + membership.invited_by = actor + membership.save() + TeamAuditEvent.objects.create(team=team, actor=actor, subject=target, action="invited") + return membership + + +@transaction.atomic +def respond_invitation(membership_id, actor, accept): + invite = get_object_or_404(TeamMembership, pk=membership_id, user=actor, status="invited") + team = get_object_or_404(Team.objects.select_for_update(), pk=invite.team_id, active=True) + actor = get_user_model().objects.get(pk=actor.pk) + if not actor.service_enabled: + raise PermissionDenied("账号当前不能加入团队。") + invite.refresh_from_db() + if invite.user_id != actor.pk or invite.status != "invited": + raise ValidationError("邀请已失效,请刷新页面。") + if accept and 1 + team.memberships.exclude(user_id=team.owner_id).filter(status="active").count() >= team.setup_member_limit: + raise ValidationError("团队成员名额已满。") + invite.role = "member" + invite.status = "active" if accept else "removed" + invite.save(update_fields=["role", "status", "updated_at"]) + TeamAuditEvent.objects.create(team=team, actor=actor, subject=actor, action="accepted" if accept else "declined") + return team + + +@transaction.atomic +def change_member(team_id, membership_id, actor, action): + team, actor, role = locked_team_for_actor(team_id, actor) + member = get_object_or_404(TeamMembership, pk=membership_id, team=team) + if member.user_id == team.owner_id: + raise PermissionDenied("不能通过成员操作变更所有者。") + if action in ("promote", "demote"): + if role != "owner" or member.status != "active": + raise PermissionDenied("只有所有者可以调整已加入成员的团队角色。") + member.role = "admin" if action == "promote" else "member" + elif action == "remove": + if role == "owner": + pass + elif role == "admin" and member.role == "member" and member.user_id != actor.pk: + pass + else: + raise PermissionDenied("无权移除此成员。") + member.status = "removed" + member.role = "member" + elif action == "leave": + if member.user_id != actor.pk or member.status != "active": + raise PermissionDenied("只能退出自己的成员身份。") + member.status = "removed" + member.role = "member" + else: + raise ValidationError("未知操作。") + member.save(update_fields=["role", "status", "updated_at"]) + TeamAuditEvent.objects.create(team=team, actor=actor, subject=member.user, action=action) diff --git a/backend/control/team_views.py b/backend/control/team_views.py new file mode 100644 index 0000000..6daaddf --- /dev/null +++ b/backend/control/team_views.py @@ -0,0 +1,99 @@ +from django import forms +from django.contrib import messages +from django.contrib.auth.decorators import login_required +from django.core.exceptions import ValidationError +from django.shortcuts import get_object_or_404, redirect, render +from django.views.decorators.cache import never_cache +from django.views.decorators.http import require_http_methods, require_POST + +from .team_models import TeamMembership +from .team_services import visible_teams, role_for, create_team, invite_member, respond_invitation, change_member +from .lifecycle import team_lifecycle + + +class CreateTeamForm(forms.Form): + name = forms.CharField(label="团队名称", max_length=100) + + +class InviteMemberForm(forms.Form): + username = forms.CharField(label="成员的平台用户名", max_length=150, + help_text="成员须已注册且审核正常。邀请显示在对方的团队页,需要本人接受。") + + +@never_cache +@login_required +@require_http_methods(["GET", "POST"]) +def teams(request): + form = CreateTeamForm(request.POST or None) + if request.method == "POST" and form.is_valid(): + try: + team = create_team(request.user, form.cleaned_data["name"]) + except ValidationError as exc: + form.add_error(None, exc) + else: + messages.success(request, "团队管理空间已建立;未付款、未开通团队代理。") + return redirect("team-detail", team_id=team.pk) + invitations = TeamMembership.objects.none() + if request.user.service_enabled: + invitations = request.user.vpn_team_memberships.filter(status="invited", team__active=True).select_related("team", "team__owner") + return render(request, "portal/teams.html", {"teams": visible_teams(request.user), "invitations": invitations, "form": form}) + + +@never_cache +@login_required +@require_http_methods(["GET", "POST"]) +def detail(request, team_id): + team = get_object_or_404(visible_teams(request.user), pk=team_id) + role = role_for(team, request.user) + form = InviteMemberForm(request.POST or None) + if request.method == "POST" and form.is_valid(): + try: + invite_member(team.pk, request.user, form.cleaned_data["username"]) + except ValidationError as exc: + form.add_error(None, exc) + else: + messages.success(request, "邀请已登记,等待对方登录后接受。") + return redirect("team-detail", team_id=team.pk) + management = role in ("owner", "admin") + # Never load the full roster into a member's template context. + members = team.memberships.filter(status__in=("active", "invited")).select_related("user") if management else TeamMembership.objects.none() + mine = team.memberships.filter(user=request.user, status="active").first() + return render(request, "portal/team_detail.html", {"team": team, "role": role, "management": management, + "members": members, "my_membership": mine, "form": form, "lifecycle": team_lifecycle(team), + "member_count": 1 + team.memberships.exclude(user_id=team.owner_id).filter(status="active").count()}) + + +@login_required +@require_POST +def invitation(request, membership_id): + action = request.POST.get("action") + if action not in ("accept", "decline"): + messages.error(request, "操作无效,邀请状态未改变。") + return redirect("teams") + try: + team = respond_invitation(membership_id, request.user, action == "accept") + except ValidationError as exc: + messages.error(request, ";".join(exc.messages)) + return redirect("teams") + messages.success(request, "已加入团队,角色为普通成员;个人套餐不变,团队服务仍以套餐状态为准。" if action == "accept" else "已拒绝邀请,没有加入团队;个人账号和套餐不变。") + return redirect("team-detail", team_id=team.pk) if action == "accept" else redirect("teams") + + +@login_required +@require_POST +def member_action(request, team_id, membership_id): + try: + change_member(team_id, membership_id, request.user, request.POST.get("action")) + except ValidationError as exc: + messages.error(request, ";".join(exc.messages)) + else: + results = { + "promote": "已设为团队管理员;仅有本团队管理权限,不是平台管理员。", + "demote": "已改为普通成员;团队管理权限已撤销。", + "remove": "成员或邀请已移除;不删除对方个人账号、不改变个人套餐。", + "leave": "已退出团队;个人账号和个人套餐保持不变。", + } + messages.success(request, results[request.POST["action"]]) + if request.POST.get("action") == "leave": + return redirect("teams") + return redirect("team-detail", team_id=team_id) diff --git a/backend/control/templatetags/__init__.py b/backend/control/templatetags/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/backend/control/templatetags/__init__.py @@ -0,0 +1 @@ + diff --git a/backend/control/templatetags/vpn_admin_dashboard.py b/backend/control/templatetags/vpn_admin_dashboard.py new file mode 100644 index 0000000..28ebd85 --- /dev/null +++ b/backend/control/templatetags/vpn_admin_dashboard.py @@ -0,0 +1,114 @@ +from datetime import timedelta + +from django import template +from django.contrib.auth import get_user_model +from django.db.models import Q, Sum +from django.utils import timezone + +from accounts.models import LoginAttempt +from control.models import ( + ClientSession, + Device, + LearnedRouteRule, + Node, + NodeDeployment, + Plan, + PlanApplication, + RouteObservation, + Subscription, + UsageRecord, + VpnAiFinding, + VpnAiRuntime, +) + + +register = template.Library() + + +def _format_bytes(value): + value = int(value or 0) + units = ("B", "KB", "MB", "GB", "TB") + size = float(value) + for unit in units: + if size < 1024 or unit == units[-1]: + return f"{size:.0f} {unit}" if unit in {"B", "KB"} else f"{size:.2f} {unit}" + size /= 1024 + return "0 B" + + +@register.simple_tag +def vpn_dashboard_metrics(): + now = timezone.now() + User = get_user_model() + traffic = UsageRecord.objects.filter(day=timezone.localdate()).aggregate( + upload=Sum("upload_bytes"), + download=Sum("download_bytes"), + ) + runtime = VpnAiRuntime.objects.first() + deployment_errors = NodeDeployment.objects.exclude(last_error="").count() + findings_open = VpnAiFinding.objects.filter(status=VpnAiFinding.Status.OPEN) + + metrics = { + "users_active": User.objects.filter(account_status=User.AccountStatus.ACTIVE, is_active=True).count(), + "users_pending": User.objects.filter(account_status=User.AccountStatus.PENDING).count(), + "plans_active": Plan.objects.filter(active=True).count(), + "applications_pending": PlanApplication.objects.filter(status=PlanApplication.Status.PENDING).count(), + "subscriptions_active": Subscription.objects.filter(status=Subscription.Status.ACTIVE).count(), + "subscriptions_pending": Subscription.objects.filter(status=Subscription.Status.PENDING).count(), + "subscriptions_problem": Subscription.objects.filter( + Q(status=Subscription.Status.SUSPENDED) + | Q(provisioning_state=Subscription.ProvisioningState.FAILED) + ).count(), + "nodes_online": Node.objects.filter(active=True, status=Node.Status.ONLINE).count(), + "nodes_total": Node.objects.filter(active=True).count(), + "deployment_errors": deployment_errors, + "devices_active": Device.objects.filter(active=True).count(), + "sessions_active": ClientSession.objects.filter(revoked_at__isnull=True, expires_at__gt=now).count(), + "today_traffic": _format_bytes((traffic["upload"] or 0) + (traffic["download"] or 0)), + "observations_7d": RouteObservation.objects.filter(received_at__gte=now - timedelta(days=7)).count(), + "http_observations_7d": RouteObservation.objects.filter( + received_at__gte=now - timedelta(days=7), + access_kind=RouteObservation.AccessKind.HTTP, + ).count(), + "socket_observations_7d": RouteObservation.objects.filter( + received_at__gte=now - timedelta(days=7), + access_kind=RouteObservation.AccessKind.SOCKET, + ).count(), + "rules_preset": LearnedRouteRule.objects.filter( + source=LearnedRouteRule.Source.PRESET, + status=LearnedRouteRule.Status.ACTIVE, + ).count(), + "rules_learning": LearnedRouteRule.objects.filter( + source=LearnedRouteRule.Source.AI, + status=LearnedRouteRule.Status.PENDING, + ).count(), + "rules_active": LearnedRouteRule.objects.filter(status=LearnedRouteRule.Status.ACTIVE).count(), + "findings_open": findings_open.count(), + "findings_critical": findings_open.filter(severity=VpnAiFinding.Severity.CRITICAL).count(), + "login_blocks": LoginAttempt.objects.filter(blocked_until__gt=now).count(), + "runtime": runtime, + "runtime_healthy": bool(runtime and runtime.is_healthy), + } + + if metrics["users_pending"]: + metrics["next_action"] = f"先审核 {metrics['users_pending']} 个待处理账号" + metrics["next_url"] = "/admin/accounts/user/?account_status__exact=pending" + elif metrics["applications_pending"]: + metrics["next_action"] = f"处理 {metrics['applications_pending']} 个套餐申请" + metrics["next_url"] = "/admin/control/planapplication/?status__exact=pending" + elif metrics["subscriptions_problem"]: + metrics["next_action"] = f"检查 {metrics['subscriptions_problem']} 个订阅或下发异常" + metrics["next_url"] = "/admin/control/subscription/" + elif metrics["deployment_errors"]: + metrics["next_action"] = f"处理 {metrics['deployment_errors']} 个节点下发异常" + metrics["next_url"] = "/admin/control/nodedeployment/" + elif metrics["findings_critical"]: + metrics["next_action"] = f"处理 {metrics['findings_critical']} 个严重诊断" + metrics["next_url"] = "/admin/control/vpnaifinding/?severity__exact=critical&status__exact=open" + elif metrics["rules_learning"]: + metrics["next_action"] = f"复核 {metrics['rules_learning']} 条 AI 候选规则" + metrics["next_url"] = "/admin/control/learnedrouterule/?source__exact=ai&status__exact=pending" + else: + metrics["next_action"] = "主流程正常,暂无必须处理事项" + metrics["next_url"] = "/admin/control/vpnairuntime/" + return metrics diff --git a/backend/control/templatetags/vpn_tags.py b/backend/control/templatetags/vpn_tags.py new file mode 100644 index 0000000..37fd14e --- /dev/null +++ b/backend/control/templatetags/vpn_tags.py @@ -0,0 +1,36 @@ +from django import template + + +register = template.Library() + + +@register.filter +def bytes_human(value): + try: + size = float(value or 0) + except (TypeError, ValueError): + return "0 B" + units = ["B", "KB", "MB", "GB", "TB"] + for unit in units: + if abs(size) < 1024 or unit == units[-1]: + return f"{size:.0f} {unit}" if unit in {"B", "KB"} else f"{size:.2f} {unit}" + size /= 1024 + return "0 B" + + +@register.filter +def status_class(value): + return { + "active": "success", + "approved": "success", + "paid": "success", + "online": "success", + "pending": "warning", + "unpaid": "warning", + "suspended": "danger", + "cancelled": "muted", + "expired": "muted", + "rejected": "danger", + "departed": "danger", + }.get(value, "muted") + diff --git a/backend/control/tests/__init__.py b/backend/control/tests/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/backend/control/tests/__init__.py @@ -0,0 +1 @@ + diff --git a/backend/control/tests/test_account_approval_safety.py b/backend/control/tests/test_account_approval_safety.py new file mode 100644 index 0000000..ac927c4 --- /dev/null +++ b/backend/control/tests/test_account_approval_safety.py @@ -0,0 +1,129 @@ +"""Approval must not silently undo an independent account suspension/departure.""" +from concurrent.futures import ThreadPoolExecutor +from threading import Event + +from django.contrib.auth import get_user_model +from django.core.exceptions import ValidationError +from django.db import close_old_connections, connection, connections, transaction +from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature + +from control.approval_audit import audit_plan_approvals +from control.models import Plan, PlanApplication, Subscription + + +class AccountApprovalSafetyTests(TestCase): + def setUp(self): + self.owner = get_user_model().objects.create_user( + username="approval-owner-fixture", email="approval-owner@example.invalid", identity_type="employee" + ) + self.reviewer = get_user_model().objects.create_superuser( + username="approval-reviewer-fixture", email="approval-reviewer@example.invalid", password="fixture-only" + ) + self.plan = Plan.objects.create(name="Approval fixture", slug="approval-fixture") + + def test_stale_submit_cannot_create_requests_for_suspended_departed_disabled_or_invalid_account(self): + for status, active in (("suspended", True), ("departed", True), ("pending", False), ("unknown", True)): + with self.subTest(status=status, is_active=active), transaction.atomic(): + get_user_model().objects.filter(pk=self.owner.pk).update(account_status=status, is_active=active) + # self.owner intentionally still contains the old eligible state. + with self.assertRaises(ValidationError): + PlanApplication.submit(user=self.owner, plan=self.plan) + self.assertFalse(PlanApplication.objects.filter(user=self.owner).exists()) + + def test_approval_cannot_reactivate_stopped_accounts_or_change_previous_subscription(self): + subscription = Subscription.objects.create( + user=self.owner, plan=self.plan, status="suspended", upload_bytes=123, download_bytes=456 + ) + application = PlanApplication.objects.create(user=self.owner, plan=self.plan, payment_status="not_required") + before_sub = Subscription.objects.values().get(pk=subscription.pk) + before_app = PlanApplication.objects.values().get(pk=application.pk) + for status, active in (("suspended", True), ("departed", True), ("active", False), ("unknown", True)): + with self.subTest(status=status, is_active=active), transaction.atomic(): + get_user_model().objects.filter(pk=self.owner.pk).update(account_status=status, is_active=active) + before_owner = get_user_model().objects.values().get(pk=self.owner.pk) + with self.assertRaises(ValidationError): + application.approve(self.reviewer) + self.assertEqual(get_user_model().objects.values().get(pk=self.owner.pk), before_owner) + self.assertEqual(Subscription.objects.values().get(pk=subscription.pk), before_sub) + self.assertEqual(PlanApplication.objects.values().get(pk=application.pk), before_app) + + def test_already_approved_replay_is_read_only_after_departure(self): + application = PlanApplication.submit(user=self.owner, plan=self.plan) + subscription = application.approve(self.reviewer) + get_user_model().objects.filter(pk=self.owner.pk).update(account_status="departed") + subscription.cancel(reason="fixture departure") + before_owner = get_user_model().objects.values().get(pk=self.owner.pk) + before_sub = Subscription.objects.values().get(pk=subscription.pk) + self.assertEqual(application.approve(self.reviewer).pk, subscription.pk) + self.assertEqual(get_user_model().objects.values().get(pk=self.owner.pk), before_owner) + self.assertEqual(Subscription.objects.values().get(pk=subscription.pk), before_sub) + + def test_audit_reports_stopped_pending_accounts_using_only_ids_and_without_repair(self): + application = PlanApplication.objects.create(user=self.owner, plan=self.plan) + get_user_model().objects.filter(pk=self.owner.pk).update(account_status="departed") + before_app = PlanApplication.objects.values().get(pk=application.pk) + statements = [] + + def readonly(execute, sql, params, many, context): + statements.append(sql) + self.assertTrue(sql.lstrip().upper().startswith(("SELECT", "PRAGMA")), sql) + return execute(sql, params, many, context) + + with connection.execute_wrapper(readonly): + report = audit_plan_approvals(sample_limit=1) + self.assertTrue(statements) + finding = next(f for f in report["findings"] if f["code"] == "pending_account_no_longer_eligible") + self.assertEqual(finding["count"], 1) + self.assertEqual(finding["samples"], [{"id": application.pk, "user_id": self.owner.pk, "plan_id": self.plan.pk}]) + self.assertNotIn(self.owner.username, str(report)) + self.assertNotIn(self.owner.email, str(report)) + self.assertFalse(report["database_modified"]) + self.assertEqual(PlanApplication.objects.values().get(pk=application.pk), before_app) + + +@skipUnlessDBFeature("has_select_for_update") +class AccountApprovalLockTests(TransactionTestCase): + def test_approval_waits_for_account_lock_and_observes_committed_suspension(self): + user_model = get_user_model() + owner = user_model.objects.create_user(username="lock-owner-fixture", email="lock-owner@example.invalid") + reviewer = user_model.objects.create_superuser( + username="lock-reviewer-fixture", email="lock-reviewer@example.invalid", password="fixture-only" + ) + plan = Plan.objects.create(name="Lock fixture", slug="lock-fixture") + application = PlanApplication.submit(user=owner, plan=plan) + locking_query_started = Event() + + def approve(): + close_old_connections() + try: + def observe(execute, sql, params, many, context): + if "FOR UPDATE" in sql.upper() and "accounts_user" in sql: + locking_query_started.set() + return execute(sql, params, many, context) + + with connections["default"].cursor() as cursor: + cursor.execute("SET lock_timeout = '5s'") + with connections["default"].execute_wrapper(observe): + try: + application.approve(reviewer) + except ValidationError: + return "account_rejected" + return "approved" + finally: + connections.close_all() + + with ThreadPoolExecutor(max_workers=1) as pool: + with transaction.atomic(): + locked_owner = user_model.objects.select_for_update().get(pk=owner.pk) + locked_owner.account_status = "suspended" + locked_owner.save(update_fields=["account_status"]) + future = pool.submit(approve) + self.assertTrue(locking_query_started.wait(timeout=8)) + self.assertFalse(future.done()) + self.assertEqual(future.result(timeout=12), "account_rejected") + owner.refresh_from_db() + application.refresh_from_db() + self.assertEqual(owner.account_status, "suspended") + self.assertEqual(application.status, "pending") + self.assertIsNone(application.subscription_id) + self.assertFalse(Subscription.objects.filter(user=owner).exists()) diff --git a/backend/control/tests/test_approval_audit.py b/backend/control/tests/test_approval_audit.py new file mode 100644 index 0000000..38c2d95 --- /dev/null +++ b/backend/control/tests/test_approval_audit.py @@ -0,0 +1,156 @@ +import io +import json +from django.contrib.auth import get_user_model +from django.core.management import call_command +from django.core.management.base import CommandError +from django.db import connection +from django.test import TestCase, TransactionTestCase +from django.db.migrations.executor import MigrationExecutor + +from control.approval_audit import audit_plan_approvals +from control.models import Plan, PlanApplication, Subscription + + +class ApprovalAuditTests(TestCase): + def setUp(self): + self.owner = get_user_model().objects.create_user(username="audit-owner", email="private@example.invalid") + self.plan = Plan.objects.create(name="Private plan", slug="audit-plan", audience="all") + + def audit(self, **options): + queries = [] + def readonly(execute, sql, params, many, context): + queries.append(sql) + self.assertTrue(sql.lstrip().upper().startswith(("SELECT", "PRAGMA")), sql) + return execute(sql, params, many, context) + with connection.execute_wrapper(readonly): + result = audit_plan_approvals(**options) + self.assertTrue(queries) + encoded = json.dumps(result) + self.assertNotIn(self.owner.email, encoded) + self.assertNotIn(self.owner.username, encoded) + self.assertNotIn(self.plan.name, encoded) + self.assertFalse(result["database_modified"]) + return result + + def test_empty_state_is_not_release_approval(self): + report = self.audit() + self.assertFalse(report["review_required"]) + self.assertFalse(report["deployment_approved"]) + + def test_duplicate_subscriptions_and_pending_applications_are_reported_not_fixed(self): + for _ in range(2): + Subscription.objects.create(user=self.owner, plan=self.plan) + PlanApplication.objects.create(user=self.owner, plan=self.plan) + codes = {finding["code"] for finding in self.audit()["findings"]} + self.assertEqual(codes, {"multiple_open_subscriptions", "multiple_pending_applications"}) + self.assertEqual(Subscription.objects.count(), 2) + self.assertEqual(PlanApplication.objects.count(), 2) + + def test_old_approved_request_is_not_automatically_backfilled(self): + app = PlanApplication.objects.create(user=self.owner, plan=self.plan, status="approved") + report = self.audit() + self.assertEqual(report["findings"][0]["code"], "legacy_approved_application_without_link") + app.refresh_from_db() + self.assertIsNone(app.subscription_id) + self.assertFalse(Subscription.objects.exists()) + + def test_current_plan_change_is_not_a_false_historical_mismatch(self): + current = Plan.objects.create(name="Current", slug="current") + subscription = Subscription.objects.create(user=self.owner, plan=current, upload_bytes=123) + PlanApplication.objects.create(user=self.owner, plan=self.plan, status="approved", subscription=subscription) + report = self.audit() + self.assertFalse(report["findings"]) + self.assertTrue(report["schema_rollback_requires_link_backup"]) + self.assertEqual(report["schema_rollback_would_drop_link_count"], 1) + subscription.refresh_from_db() + self.assertEqual(subscription.upload_bytes, 123) + + def test_cross_user_and_unapproved_links_are_blockers(self): + other = get_user_model().objects.create_user(username="other", email="other@example.invalid") + subscription = Subscription.objects.create(user=other, plan=self.plan) + PlanApplication.objects.create(user=self.owner, plan=self.plan, subscription=subscription) + findings = self.audit()["findings"] + self.assertEqual({f["code"] for f in findings}, { + "subscription_belongs_to_another_user", "unapproved_application_has_subscription_link"}) + self.assertTrue(all(f["level"] == "blocker" for f in findings)) + + def test_ineligible_plans_and_bounded_samples(self): + Plan.objects.filter(pk=self.plan.pk).update(active=False) + for _ in range(3): + PlanApplication.objects.create(user=self.owner, plan=self.plan) + findings = {f["code"]: f for f in self.audit(sample_limit=1)["findings"]} + finding = findings["pending_plan_no_longer_eligible"] + self.assertEqual(finding["count"], 3) + self.assertEqual(len(finding["samples"]), 1) + self.assertTrue(finding["samples_truncated"]) + + def test_identity_and_employee_benefit_checks_do_not_flag_unpaid_eligible_requests(self): + employee_only = Plan.objects.create(name="Staff", slug="staff", audience="employee") + benefit = Plan.objects.create(name="Benefit", slug="benefit", audience="all", employee_benefit=True) + other = get_user_model().objects.create_user(username="other-audit", email="other-audit@example.invalid") + third = get_user_model().objects.create_user(username="third-audit", email="third-audit@example.invalid") + first = PlanApplication.objects.create(user=self.owner, plan=employee_only) + second = PlanApplication.objects.create(user=other, plan=benefit) + Plan.objects.filter(pk=self.plan.pk).update(price_cny=100) + PlanApplication.objects.create(user=third, plan=self.plan, payment_status="unpaid") + findings = self.audit()["findings"] + self.assertEqual(len(findings), 1) + self.assertEqual(findings[0]["code"], "pending_plan_no_longer_eligible") + self.assertEqual({row["id"] for row in findings[0]["samples"]}, {first.pk, second.pk}) + + def test_ended_subscriptions_do_not_count_as_conflicting_open_subscriptions(self): + for status in ("cancelled", "expired", "active"): + Subscription.objects.create(user=self.owner, plan=self.plan, status=status) + self.assertFalse(self.audit()["review_required"]) + + def test_command_can_fail_after_printing_review_json(self): + PlanApplication.objects.create(user=self.owner, plan=self.plan, status="approved") + output = io.StringIO() + with self.assertRaises(CommandError): + call_command("audit_plan_approvals", fail_on_review=True, stdout=output) + self.assertTrue(json.loads(output.getvalue())["review_required"]) + + def test_limit_validation_precedes_queries(self): + for limit in (0, 1001): + with self.assertNumQueries(0), self.assertRaises(ValueError): + audit_plan_approvals(sample_limit=limit) + + +class ApprovalSchemaRehearsalTests(TransactionTestCase): + """Only Django's disposable test database; never migrate a deployment here.""" + def test_0007_forward_reverse_and_old_schema_audit_preserve_existing_data(self): + old_target = [("control", "0007_ai_dispatch")] + new_target = [("control", "0008_planapplication_subscription")] + executor = MigrationExecutor(connection) + latest_targets = executor.loader.graph.leaf_nodes() + self.assertTrue(connection.settings_dict["NAME"].startswith(("test_", "file:memory"))) + try: + executor.migrate(old_target) + old_apps = executor.loader.project_state(old_target).apps + User = old_apps.get_model("accounts", "User") + OldPlan = old_apps.get_model("control", "Plan") + OldSub = old_apps.get_model("control", "Subscription") + OldApp = old_apps.get_model("control", "PlanApplication") + owner = User.objects.create(username="legacy", email="legacy@example.invalid") + plan = OldPlan.objects.create(name="Legacy", slug="legacy") + sub = OldSub.objects.create(user_id=owner.pk, plan_id=plan.pk, upload_bytes=123, download_bytes=456) + app = OldApp.objects.create(user_id=owner.pk, plan_id=plan.pk, status="approved") + before = OldSub.objects.values().get(pk=sub.pk) + report = audit_plan_approvals() + self.assertTrue(report["migration_0008_required"]) + self.assertEqual(report["counts"]["applications"], 1) + MigrationExecutor(connection).migrate(new_target) + self.assertIsNone(PlanApplication.objects.get(pk=app.pk).subscription_id) + self.assertEqual(Subscription.objects.values().get(pk=sub.pk), before) + # No inferred backfill: association is only set explicitly in fixture. + PlanApplication.objects.filter(pk=app.pk).update(subscription_id=sub.pk) + self.assertEqual(audit_plan_approvals()["schema_rollback_would_drop_link_count"], 1) + MigrationExecutor(connection).migrate(old_target) + self.assertEqual(OldSub.objects.values().get(pk=sub.pk), before) + self.assertEqual(OldApp.objects.filter(pk=app.pk).count(), 1) + MigrationExecutor(connection).migrate(new_target) + self.assertIsNone(PlanApplication.objects.get(pk=app.pk).subscription_id) + self.assertEqual(Subscription.objects.values().get(pk=sub.pk), before) + finally: + # A rehearsal of 0008 must not leave later tests running against an old schema. + MigrationExecutor(connection).migrate(latest_targets) diff --git a/backend/control/tests/test_approval_concurrency.py b/backend/control/tests/test_approval_concurrency.py new file mode 100644 index 0000000..cb525aa --- /dev/null +++ b/backend/control/tests/test_approval_concurrency.py @@ -0,0 +1,100 @@ +"""Real row-lock regressions. SQLite explicitly skips these; it is not evidence.""" +from concurrent.futures import ThreadPoolExecutor +from threading import Barrier + +from django.contrib.auth import get_user_model +from django.core.exceptions import ValidationError +from django.db import close_old_connections, connections +from django.test import TransactionTestCase, skipUnlessDBFeature + +from control.models import Plan, PlanApplication, Subscription + + +@skipUnlessDBFeature("has_select_for_update") +class ApprovalConcurrencyTests(TransactionTestCase): + def setUp(self): + user_model = get_user_model() + self.reviewer = user_model.objects.create_superuser( + username="reviewer", email="reviewer@example.invalid", password="fixture-only" + ) + self.owner = user_model.objects.create_user( + username="concurrent-owner", email="owner@example.invalid", password="fixture-only" + ) + self.plan = Plan.objects.create( + name="Concurrent plan", slug="concurrent-plan", audience=Plan.Audience.ALL, + price_cny=0, duration_days=30, + ) + + def run_concurrently(self, *actions): + barrier = Barrier(len(actions)) + + def run(action): + close_old_connections() + try: + barrier.wait(timeout=8) + return action() + finally: + connections.close_all() + + with ThreadPoolExecutor(max_workers=len(actions)) as pool: + futures = [pool.submit(run, action) for action in actions] + return [future.result(timeout=25) for future in futures] + + def approve(self, application_id): + application = PlanApplication.objects.get(pk=application_id) + reviewer = get_user_model().objects.get(pk=self.reviewer.pk) + return application.approve(reviewer).pk + + def test_two_approvals_of_same_application_are_idempotent(self): + application = PlanApplication.submit(user=self.owner, plan=self.plan) + results = self.run_concurrently( + lambda: self.approve(application.pk), lambda: self.approve(application.pk) + ) + self.assertEqual(results[0], results[1]) + self.assertEqual(Subscription.objects.filter(user=self.owner).count(), 1) + application.refresh_from_db() + self.assertEqual(application.subscription_id, results[0]) + self.assertEqual(application.status, PlanApplication.Status.APPROVED) + + def test_concurrent_submissions_create_only_one_pending_application(self): + def submit(): + try: + return PlanApplication.submit(user=self.owner, plan=self.plan).pk + except ValidationError: + return None + + results = self.run_concurrently(submit, submit) + self.assertEqual(sum(value is not None for value in results), 1) + self.assertEqual(PlanApplication.objects.filter(user=self.owner).count(), 1) + + def test_legacy_distinct_pending_applications_reuse_subscription(self): + # Old databases may already have two pending applications. Approving them + # from different admin pages must not create two subscriptions or deadlock. + other_plan = Plan.objects.create( + name="Second plan", slug="second-plan", audience=Plan.Audience.ALL, price_cny=0 + ) + first = PlanApplication.objects.create( + user=self.owner, plan=self.plan, payment_status=PlanApplication.PaymentStatus.NOT_REQUIRED + ) + second = PlanApplication.objects.create( + user=self.owner, plan=other_plan, payment_status=PlanApplication.PaymentStatus.NOT_REQUIRED + ) + results = self.run_concurrently(lambda: self.approve(first.pk), lambda: self.approve(second.pk)) + self.assertEqual(results[0], results[1]) + self.assertEqual(Subscription.objects.filter(user=self.owner).count(), 1) + self.assertEqual(PlanApplication.objects.filter( + user=self.owner, subscription_id=results[0], status=PlanApplication.Status.APPROVED + ).count(), 2) + + def test_stale_application_cannot_revert_current_plan_or_usage(self): + application = PlanApplication.submit(user=self.owner, plan=self.plan) + subscription_id = self.approve(application.pk) + new_plan = Plan.objects.create(name="Later plan", slug="later-plan", audience=Plan.Audience.ALL) + Subscription.objects.filter(pk=subscription_id).update(plan=new_plan, upload_bytes=123, download_bytes=456) + results = self.run_concurrently( + lambda: self.approve(application.pk), lambda: self.approve(application.pk) + ) + subscription = Subscription.objects.get(pk=subscription_id) + self.assertEqual(results, [subscription_id, subscription_id]) + self.assertEqual((subscription.upload_bytes, subscription.download_bytes), (123, 456)) + self.assertEqual(subscription.plan_id, new_plan.pk) diff --git a/backend/control/tests/test_candidate_upgrade_compatibility.py b/backend/control/tests/test_candidate_upgrade_compatibility.py new file mode 100644 index 0000000..5292ce6 --- /dev/null +++ b/backend/control/tests/test_candidate_upgrade_compatibility.py @@ -0,0 +1,227 @@ +"""Historical 0010 ORM against candidate schema, in disposable test DBs only. + +This is application rollback compatibility, not permission to reverse a live +schema migration (which would drop team/office/receipt data). +""" + +from contextlib import contextmanager +from datetime import timedelta +from uuid import uuid4 + +from django.db import connection +from django.db.migrations.executor import MigrationExecutor +from django.test import TransactionTestCase +from django.utils import timezone + + +class CandidateUpgradeCompatibilityTests(TransactionTestCase): + old_target = [("control", "0010_plan_billing_months_plan_online_payment_required")] + candidate_target = [("control", "0015_learning_delivery")] + + @contextmanager + def baseline(self): + self.assertTrue( + str(connection.settings_dict["NAME"]).startswith(("test_", "file:memory")), + "Migration rehearsals must only target the disposable test database", + ) + executor = MigrationExecutor(connection) + latest = executor.loader.graph.leaf_nodes() + try: + executor.migrate(self.old_target) + old = executor.loader.project_state(self.old_target).apps + model = lambda name: old.get_model("control", name) + now = timezone.now() + user = old.get_model("accounts", "User").objects.create( + username="upgrade-fixture", email="upgrade@example.invalid", + identity_type="employee", account_status="active", + ) + node = model("Node").objects.create( + name="Fixture", slug="upgrade-fixture", region="test", + server="192.0.2.1", port=11081, protocol="vless_reality", + status="online", active=True, subscription_enabled=True, + total_upload_bytes=456, total_download_bytes=789, + ) + plan = model("Plan").objects.create( + name="Fixture", slug="upgrade-fixture", device_limit=3, + price_cny=8, traffic_limit_gb=1024, billing_months=1, + ) + sub = model("Subscription").objects.create( + user=user, plan=plan, status="active", provisioning_state="active", + starts_at=now, expires_at=now + timedelta(days=30), + upload_bytes=123, download_bytes=456, device_limit=3, + traffic_limit_bytes=1024 ** 4, token_version=7, + ) + sub.allowed_nodes.add(node) + model("PlanApplication").objects.create( + user=user, plan=plan, subscription=sub, status="approved", + payment_status="not_required", reviewed_by=user, reviewed_at=now, + ) + devices = [model("Device").objects.create( + subscription=sub, device_id=f"upgrade-{i}", active=True, + upload_bytes=12 + i, download_bytes=23 + i, + ) for i in range(2)] + model("ClientSession").objects.create( + subscription=sub, device=devices[0], token_digest="a" * 64, + expires_at=now + timedelta(days=30), assigned_node=node, + dispatch_decision={"reason": "fixture-sticky-assignment"}, + ) + model("NodeDeployment").objects.create(subscription=sub, node=node, deployed=True) + model("UsageRecord").objects.create( + subscription=sub, node=node, day=now.date(), upload_bytes=123, download_bytes=456, + ) + model("HourlyUsageRecord").objects.create( + subscription=sub, node=node, hour=now.replace(minute=0, second=0, microsecond=0), + upload_bytes=123, download_bytes=456, + ) + model("LearnedRouteRule").objects.create( + target_type="domain", target="manual.example.com", source="manual", + status="active", manually_locked=True, reason="Keep manual policy", + ) + observation_fields = dict( + subscription_id=sub.pk, node_id=node.pk, target_type="domain", + target="legacy.example.com", port=443, network="tcp", + ) + for device in devices: + for outcome in ["direct_failed"] * 4 + ["proxy_succeeded"]: + model("RouteObservation").objects.create( + **observation_fields, report_id=uuid4(), device=device, outcome=outcome, + ) + yield old, user, node, sub, devices, observation_fields + finally: + MigrationExecutor(connection).migrate(latest) + + def upgrade(self): + executor = MigrationExecutor(connection) + executor.migrate(self.candidate_target) + return executor.loader.project_state(self.candidate_target).apps + + def test_forward_upgrade_preserves_existing_business_rows_and_credentials(self): + with self.baseline() as (old, user, node, sub, devices, _): + keys = [("accounts", "User")] + [("control", name) for name in ( + "Node", "Plan", "Subscription", "PlanApplication", "Device", "ClientSession", + "NodeDeployment", "UsageRecord", "HourlyUsageRecord", "LearnedRouteRule", + "RouteObservation", + )] + before = {key: list(old.get_model(*key).objects.order_by("pk").values()) for key in keys} + current = self.upgrade() + for key, rows in before.items(): + with self.subTest(model=key): + self.assertTrue(rows) + self.assertEqual(list(current.get_model(*key).objects.order_by("pk").values( + *rows[0].keys() + )), rows) + new_node = current.get_model("control", "Node").objects.get(pk=node.pk) + self.assertFalse(new_node.office_only) + self.assertEqual(new_node.office_access_scope, "explicit_users") + self.assertFalse(new_node.office_users.exists()) + new_sub = current.get_model("control", "Subscription").objects.get(pk=sub.pk) + self.assertEqual(list(new_sub.allowed_nodes.values_list("pk", flat=True)), [node.pk]) + observations = current.get_model("control", "RouteObservation").objects + self.assertEqual(set(observations.values_list( + "evidence_kind", "related_report_id", "scope" + )), {("", None, "public")}) + + def test_old_orm_writes_work_without_losing_new_metadata(self): + with self.baseline() as (old, user, node, sub, devices, observation_fields): + current = self.upgrade() + model = lambda name: current.get_model("control", name) + old_node = old.get_model("control", "Node") + old_observation = old.get_model("control", "RouteObservation") + # Full save() through the old model omits columns it does not know. + # Persistent DB defaults must make those INSERTs valid on PostgreSQL. + inserted = old_node.objects.create( + name="Old application insert", slug="old-app-insert", + server="192.0.2.2", port=11082, protocol="vless_reality", + ) + inserted_new = model("Node").objects.get(pk=inserted.pk) + self.assertFalse(inserted_new.office_only) + self.assertEqual(inserted_new.office_access_scope, "company_network") + inserted_observation = old_observation.objects.create( + **observation_fields, device_id=devices[0].pk, report_id=uuid4(), + outcome="proxy_succeeded", + ) + inserted_new_observation = model("RouteObservation").objects.get(pk=inserted_observation.pk) + self.assertEqual(inserted_new_observation.evidence_kind, "") + self.assertEqual(inserted_new_observation.scope, "public") + self.assertIsNone(inserted_new_observation.related_report_id) + + private = model("Node").objects.get(pk=node.pk) + private.office_only = True + private.office_access_scope = "explicit_users" + private.save() + private.office_users.add(user.pk) + legacy = old_node.objects.get(pk=node.pk) + legacy.name = "Old application edit" + legacy.total_upload_bytes += 1 + legacy.save() + private.refresh_from_db() + self.assertTrue(private.office_only) + self.assertEqual(private.office_access_scope, "explicit_users") + self.assertEqual(list(private.office_users.values_list("pk", flat=True)), [user.pk]) + self.assertEqual(private.name, "Old application edit") + self.assertEqual(private.total_upload_bytes, 457) + + # Retain new-version metadata during old-code activity. Do not reverse + # schema migrations as an alleged "safe rollback" after new writes. + receipt = model("RoutePolicyReceipt").objects.create( + device_id=devices[0].pk, offered_revision="b" * 64, + applied_revision="b" * 64, last_status="cached", client_version="fixture", + ) + draft = model("PlanCatalogDraft").objects.create( + name="Team fixture", slug="team-upgrade-fixture", scope="team", traffic_limit_gb=1024, + ) + team = model("Team").objects.create(name="Fixture team", owner_id=user.pk, plan_draft=draft) + member_user = old.get_model("accounts", "User").objects.create( + username="member-fixture", email="member@example.invalid", + identity_type="employee", account_status="active", + ) + member = model("TeamMembership").objects.create( + team=team, user_id=member_user.pk, invited_by_id=user.pk, role="admin", status="active", + ) + audit = model("TeamAuditEvent").objects.create( + team=team, actor_id=user.pk, subject_id=user.pk, action="fixture", + ) + new_objects = [receipt, draft, team, member, audit] + snapshots = [(obj, type(obj).objects.values().get(pk=obj.pk)) for obj in new_objects] + old_sub = old.get_model("control", "Subscription").objects.get(pk=sub.pk) + old_sub.download_bytes += 10 + old_sub.save() + old_session = old.get_model("control", "ClientSession").objects.get(device_id=devices[0].pk) + old_session.last_seen_at = timezone.now() + old_session.save() + model("RouteObservation").objects.filter(pk=inserted_observation.pk).update( + scope="private_auxiliary", evidence_kind="tls", related_report_id=uuid4(), + ) + proof_before = model("RouteObservation").objects.values( + "scope", "evidence_kind", "related_report_id" + ).get(pk=inserted_observation.pk) + legacy_proof = old_observation.objects.get(pk=inserted_observation.pk) + legacy_proof.client_version = "old-fixture" + legacy_proof.save() + self.assertEqual(model("RouteObservation").objects.values( + "scope", "evidence_kind", "related_report_id" + ).get(pk=inserted_observation.pk), proof_before) + for obj, values in snapshots: + self.assertEqual(type(obj).objects.values().get(pk=obj.pk), values) + + def test_legacy_successes_do_not_turn_into_verified_proxy_evidence(self): + with self.baseline() as (old, user, node, sub, devices, observation_fields): + current = self.upgrade() + # More legacy reports arrive after the schema upgrade, including two + # different devices: neither SQL defaults nor migration may invent TLS. + for device in devices: + old.get_model("control", "RouteObservation").objects.create( + **observation_fields, device_id=device.pk, + report_id=uuid4(), outcome="proxy_succeeded", + ) + from control.learning import manifest + from control.vpn_ai import evaluate_route_learning + + evaluate_route_learning(timezone.now()) + rule = current.get_model("control", "LearnedRouteRule").objects.get(target="legacy.example.com") + self.assertEqual(rule.failure_reports, 8) + self.assertEqual(rule.proxy_success_reports, 4) + self.assertEqual(rule.distinct_devices, 2) + self.assertEqual(rule.status, "pending") + self.assertIsNone(rule.valid_until) + self.assertNotIn("legacy.example.com", {item["target"] for item in manifest()["rules"]}) diff --git a/backend/control/tests/test_dispatch.py b/backend/control/tests/test_dispatch.py new file mode 100644 index 0000000..42a5ba1 --- /dev/null +++ b/backend/control/tests/test_dispatch.py @@ -0,0 +1,118 @@ +from datetime import timedelta +from django.contrib.auth import get_user_model +from django.test import TestCase, override_settings +from django.urls import reverse +from django.utils import timezone +from control.dispatch import choose_node, build_dispatch_snapshot +from control.models import ClientSession, Device, Node, NodeTrafficSample, Plan, Subscription, UsageRecord + + +@override_settings(SECURE_SSL_REDIRECT=False) +class DispatchTests(TestCase): + def setUp(self): + self.user = get_user_model().objects.create_user(username="dispatch-test", account_status="active") + self.plan = Plan.objects.create(name="测试", slug="dispatch-test") + self.sub = Subscription.objects.create(user=self.user, plan=self.plan, status="active", provisioning_state="active") + self.nodes = [] + for index, rate in enumerate([1000000, 1000, 0]): + node = Node.objects.create(name=f"VPN00{index+1}", slug=f"n{index}", region="测试", server=f"00{index}.vpn.toplc.cn", + port=11080+index, protocol="vless_reality", status="online", active=True, subscription_enabled=True, + last_seen_at=timezone.now(), fallback_only=index == 2, sni="example.com", reality_public_key="test", reality_short_id="1234") + NodeTrafficSample.objects.create(node=node, download_bytes_per_second=rate) + self.nodes.append(node) + self.session, self.token = self.new_session("one") + + def new_session(self, device): + return ClientSession.issue(self.sub, Device.objects.create(subscription=self.sub, device_id=device)) + + def test_chooses_lower_load_not_unused_reserve(self): + node, decision = choose_node(self.session) + self.assertEqual(node, self.nodes[1]) + self.assertEqual(decision["rate_bps"], 1000) + + def test_healthy_session_stays_even_when_load_changes(self): + node, _ = choose_node(self.session) + NodeTrafficSample.objects.filter(node=node).update(download_bytes_per_second=99000000) + selected, decision = choose_node(self.session) + self.assertEqual(selected, node) + self.assertTrue(decision["sticky"]) + + def test_exclusions_are_per_request_and_configured_reserve_is_last(self): + first, _ = choose_node(self.session) + second, _ = choose_node(self.session, [first.slug]) + self.assertEqual(second, self.nodes[0]) + last, _ = choose_node(self.session, [n.slug for n in self.nodes[:2]]) + self.assertEqual(last, self.nodes[2]) + self.assertEqual(Node.objects.filter(status="online").count(), 3) + + def test_new_us_003_can_participate_as_a_primary(self): + node = self.nodes[2] + node.name, node.region, node.fallback_only = "VPN003", "美国", False + node.save(update_fields=["name", "region", "fallback_only"]) + self.assertEqual(choose_node(self.session)[0], node) + self.assertEqual(build_dispatch_snapshot()["health_scope"], "agent_heartbeat_not_end_to_end") + + def test_retired_000_is_never_selected_even_with_lowest_load(self): + retired = Node.objects.create(name="VPN000", slug="retired-000", region="美国", + server="000.vpn.toplc.cn", port=11080, protocol="vless_reality", status="online", + active=False, subscription_enabled=False, last_seen_at=timezone.now(), + fallback_only=False, sni="example.com", reality_public_key="test", reality_short_id="1234") + NodeTrafficSample.objects.create(node=retired, download_bytes_per_second=0) + self.assertNotEqual(choose_node(self.session)[0], retired) + self.assertNotIn(retired.pk, [item["id"] for item in build_dispatch_snapshot()["nodes"]]) + + def test_new_connection_can_rebalance_without_moving_old_connection(self): + node, _ = choose_node(self.session) + NodeTrafficSample.objects.filter(node=node).update(download_bytes_per_second=99000000) + self.assertEqual(choose_node(self.session)[0], node) + self.assertEqual(choose_node(self.session, new_connection=True)[0], self.nodes[0]) + + def test_stale_heartbeat_is_not_healthy(self): + Node.objects.filter(pk__in=[n.pk for n in self.nodes[:2]]).update(last_seen_at=timezone.now()-timedelta(minutes=4)) + self.assertEqual(choose_node(self.session)[0], self.nodes[2]) + Node.objects.update(status="offline") + self.assertIsNone(choose_node(self.session)[0]) + + def test_reservations_spread_equal_load_arrivals(self): + NodeTrafficSample.objects.all().update(download_bytes_per_second=0) + first, _ = choose_node(self.session) + second, _ = choose_node(self.new_session("two")[0]) + self.assertNotEqual(first, second) + self.assertFalse(second.fallback_only) + + def test_dedicated_subscription_never_escapes_allowed_nodes(self): + self.sub.route_mode = Subscription.RouteMode.DEDICATED + self.sub.save() + self.sub.allowed_nodes.set([self.nodes[0]]) + self.assertEqual(choose_node(self.session)[0], self.nodes[0]) + self.assertIsNone(choose_node(self.session, [self.nodes[0].slug])[0]) + + def test_unknown_load_is_not_zero(self): + NodeTrafficSample.objects.filter(node=self.nodes[1]).delete() + self.assertEqual(choose_node(self.session)[0], self.nodes[0]) + self.assertIsNone(next(n for n in build_dispatch_snapshot()["nodes"] if n["id"] == self.nodes[1].pk)["rate_bps"]) + + @override_settings(VPN_PUBLIC_GATEWAY_HOST="vpn.toplc.cn", VPN_PUBLIC_GATEWAY_IPV4="192.0.2.1") + def test_config_auto_returns_actual_domain_and_node(self): + response = self.client.get("/api/v1/client/config/?node=auto&route=smart", HTTP_AUTHORIZATION=f"Bearer {self.token}") + self.assertEqual(response.status_code, 200, response.content) + self.assertEqual(response.json()["config_contract"], 2) + self.assertEqual(response.json()["gateway"], {"host": "vpn.toplc.cn", "ipv4": "192.0.2.1"}) + self.assertEqual(response.json()["node"]["slug"], self.nodes[1].slug) + self.assertEqual(response.json()["config"]["outbounds"][0]["settings"]["vnext"][0]["address"], self.nodes[1].server) + + @override_settings(VPN_PUBLIC_GATEWAY_HOST="vpn.toplc.cn", VPN_PUBLIC_GATEWAY_IPV4="100.73.44.33") + def test_config_never_publishes_overlay_gateway_address(self): + response = self.client.get("/api/v1/client/config/?node=auto&route=smart", HTTP_AUTHORIZATION=f"Bearer {self.token}") + self.assertEqual(response.status_code, 200, response.content) + self.assertEqual(response.json()["gateway"], {"host": "vpn.toplc.cn", "ipv4": None}) + + def test_history_aggregates_nodes_only_for_own_subscription(self): + from control.views import _client_profile_payload + for node in self.nodes: + UsageRecord.objects.create(subscription=self.sub, node=node, day=timezone.localdate(), upload_bytes=10, download_bytes=20) + history = _client_profile_payload(self.sub)["usage_history"] + self.assertEqual(len(history), 7) + self.assertEqual(history[-1]["upload_bytes"], 30) + self.assertEqual(history[-1]["download_bytes"], 60) + self.assertEqual(history[0]["upload_bytes"], 0) diff --git a/backend/control/tests/test_employee_billing.py b/backend/control/tests/test_employee_billing.py new file mode 100644 index 0000000..a16592b --- /dev/null +++ b/backend/control/tests/test_employee_billing.py @@ -0,0 +1,197 @@ +from datetime import datetime +from decimal import Decimal +from zoneinfo import ZoneInfo + +from django.core.exceptions import ValidationError +from django.core.management import call_command +from django.core.management.base import CommandError +from django.test import TestCase, override_settings +from django.urls import reverse + +from accounts.forms import RegistrationForm +from accounts.models import User +from control.forms import PlanApplicationForm +from control.models import Node, Plan, PlanApplication, Subscription +from control.services import desired_subscriptions_for_node + + +@override_settings(SECURE_SSL_REDIRECT=False, WECOM_ENABLED=False, + STORAGES={"default": {"BACKEND": "django.core.files.storage.FileSystemStorage"}, + "staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"}}) +class EmployeeBillingTests(TestCase): + def setUp(self): + self.employee = User.objects.create_user(username="employee", email="employee@example.invalid", + identity_type="employee", account_status="active") + self.external = User.objects.create_user(username="outside", email="outside@example.invalid", account_status="active") + self.reviewer = User.objects.create_superuser(username="reviewer-bill", email="reviewer-bill@example.invalid", password="fixture") + self.plan = Plan.objects.create(name="Monthly fixture", slug="month-fixture", audience="all", + price_cny=Decimal("8.00"), traffic_limit_gb=1024, billing_months=1, duration_days=0) + + def test_internal_employee_is_free_and_auto_subscribed_on_approval(self): + app = PlanApplication.submit(user=self.employee, plan=self.plan) + self.assertEqual(app.payment_status, "not_required") + subscription = app.approve(self.reviewer) + app.refresh_from_db() + self.assertEqual(app.subscription_id, subscription.pk) + self.assertEqual(subscription.traffic_limit_bytes, 1024 ** 4) + self.assertEqual(app.payment_status, "not_required") + + def test_external_needs_payment_and_admin_flag_alone_is_not_free(self): + self.external.is_staff = True + self.external.save(update_fields=["is_staff"]) + self.assertEqual(self.plan.price_for_user(self.external), Decimal("8.00")) + app = PlanApplication.submit(user=self.external, plan=self.plan) + self.assertEqual(app.payment_status, "unpaid") + with self.assertRaises(ValidationError): + app.approve(self.reviewer) + + def test_employee_reclassification_waives_pending_unpaid_request(self): + app = PlanApplication.submit(user=self.external, plan=self.plan) + User.objects.filter(pk=self.external.pk).update(identity_type="employee") + app.approve(self.reviewer) + app.refresh_from_db() + self.assertEqual(app.payment_status, "not_required") + + def test_losing_employee_identity_cannot_keep_free_payment_status(self): + app = PlanApplication.submit(user=self.employee, plan=self.plan) + User.objects.filter(pk=self.employee.pk).update(identity_type="external") + with self.assertRaises(ValidationError): + app.approve(self.reviewer) + self.assertFalse(Subscription.objects.exists()) + + def test_paid_history_is_not_relabelled_as_refunded_or_free(self): + app = PlanApplication.objects.create(user=self.employee, plan=self.plan, payment_status="paid") + app.approve(self.reviewer) + app.refresh_from_db() + self.assertEqual(app.payment_status, "paid") + + def test_one_calendar_month_clamps_end_of_month(self): + zone = ZoneInfo("Asia/Shanghai") + for year, last_day in ((2026, 28), (2028, 29)): + start = datetime(year, 1, 31, 15, 12, tzinfo=zone) + self.assertEqual(self.plan.period_end(start), datetime(year, 2, last_day, 15, 12, tzinfo=zone)) + + def test_legacy_30_day_plans_are_unchanged(self): + self.plan.billing_months = 0 + self.plan.duration_days = 30 + start = datetime(2026, 1, 31, tzinfo=ZoneInfo("Asia/Shanghai")) + self.assertEqual((self.plan.period_end(start) - start).days, 30) + + def test_prepare_draft_is_idempotent_and_does_not_change_existing_subscription(self): + sub = Subscription.objects.create(user=self.employee, plan=self.plan, upload_bytes=99) + call_command("prepare_monthly_1024g", verbosity=0) + call_command("prepare_monthly_1024g", verbosity=0) + draft = Plan.objects.get(slug="monthly-1024g") + self.assertEqual(draft.price_cny, Decimal("8.00")) + self.assertEqual(draft.traffic_limit_gb, 1024) + self.assertEqual(draft.billing_months, 1) + self.assertFalse(draft.active) + self.assertTrue(draft.online_payment_required) + self.assertNotIn(draft, RegistrationForm().fields["plan"].queryset) + self.assertNotIn(draft, PlanApplicationForm(user=self.external).fields["plan"].queryset) + sub.refresh_from_db() + self.assertEqual(sub.upload_bytes, 99) + self.assertEqual(sub.plan_id, self.plan.pk) + + def test_draft_does_not_override_existing_commercial_settings(self): + call_command("prepare_monthly_1024g", verbosity=0) + Plan.objects.filter(slug="monthly-1024g").update(price_cny=9) + with self.assertRaises(CommandError): + call_command("prepare_monthly_1024g", verbosity=0) + self.assertEqual(Plan.objects.get(slug="monthly-1024g").price_cny, Decimal("9.00")) + + def test_online_plan_accepts_pending_requests_but_not_forged_payment(self): + self.plan.online_payment_required = True + self.plan.save() + self.plan.full_clean() + app = PlanApplication.submit(user=self.external, plan=self.plan) + self.assertEqual(app.payment_status, "unpaid") + self.assertEqual(app.status, "pending") + self.assertFalse(Subscription.objects.exists()) + app.payment_status = "paid" + app.save() + with self.assertRaises(ValidationError): + app.approve(self.reviewer) + app.refresh_from_db() + self.assertEqual(app.status, "pending") + self.assertIsNone(app.subscription_id) + with self.assertRaises(ValidationError): + Subscription(user=self.external, plan=self.plan).activate() + + def test_list_command_enables_catalog_idempotently_without_downgrading_or_repricing(self): + call_command("prepare_monthly_1024g", verbosity=0) + call_command("prepare_monthly_1024g", list_plan=True, verbosity=0) + call_command("prepare_monthly_1024g", list_plan=True, verbosity=0) + call_command("prepare_monthly_1024g", verbosity=0) + plan = Plan.objects.get(slug="monthly-1024g") + self.assertTrue(plan.active) + self.assertEqual(plan.price_cny, Decimal("8.00")) + self.assertIn(plan, RegistrationForm().fields["plan"].queryset) + self.assertIn(plan, PlanApplicationForm(user=self.external).fields["plan"].queryset) + Plan.objects.filter(pk=plan.pk).update(price_cny=9) + with self.assertRaises(CommandError): + call_command("prepare_monthly_1024g", list_plan=True, verbosity=0) + plan.refresh_from_db() + self.assertEqual(plan.price_cny, Decimal("9.00")) + + def test_employee_online_plan_is_free_and_can_be_auto_subscribed(self): + self.plan.online_payment_required = True + self.plan.save() + app = PlanApplication.submit(user=self.employee, plan=self.plan) + subscription = app.approve(self.reviewer) + self.assertEqual(app.payment_status, "not_required") + self.assertEqual(subscription.status, "active") + self.assertEqual(subscription.traffic_limit_bytes, 1024 ** 4) + self.assertEqual(app.approve(self.reviewer).pk, subscription.pk) + self.assertEqual(Subscription.objects.count(), 1) + + def test_external_cannot_activate_online_plan_through_admin_form_or_raw_row(self): + self.plan.online_payment_required = True + self.plan.save() + sub = Subscription(user=self.external, plan=self.plan, status="active", provisioning_state="active") + with self.assertRaises(ValidationError): + sub.full_clean() + # ORM writes bypass ModelForm validation: read/config and node gates + # still must not accept this row as proof that money was received. + sub.save() + self.assertFalse(sub.is_usable) + node = Node.objects.create(name="fixture", slug="node-fixture", server="example.invalid", port=11082) + self.assertNotIn(sub, desired_subscriptions_for_node(node)) + employee_sub = Subscription.objects.create(user=self.employee, plan=self.plan, status="active", provisioning_state="active") + self.assertTrue(employee_sub.is_usable) + self.assertIn(employee_sub, desired_subscriptions_for_node(node)) + + def test_listed_plan_labels_and_portal_are_honest_about_payment(self): + call_command("prepare_monthly_1024g", list_plan=True, verbosity=0) + plan = Plan.objects.get(slug="monthly-1024g") + self.assertIn("8.00元/月", plan.application_label()) + self.assertIn("暂未开放付款", plan.application_label(self.external)) + self.assertIn("内部员工免费", plan.application_label(self.employee)) + self.assertNotIn("暂未开放付款", plan.application_label(self.employee)) + response = self.client.get(reverse("register")) + self.assertContains(response, "8.00元/月") + self.assertContains(response, "暂未开放付款") + self.client.force_login(self.external) + response = self.client.get(reverse("portal-dashboard")) + self.assertContains(response, "1024G 月度套餐") + self.assertContains(response, "暂未开放付款") + response = self.client.post(reverse("apply-plan"), {"plan": plan.pk, "note": "fixture request"}, follow=True) + self.assertContains(response, "未扣款、未开通付费服务") + self.assertEqual(PlanApplication.objects.get(user=self.external).payment_status, "unpaid") + self.assertFalse(Subscription.objects.exists()) + + def test_registration_submits_listed_plan_without_granting_employee_or_subscription(self): + call_command("prepare_monthly_1024g", list_plan=True, verbosity=0) + plan = Plan.objects.get(slug="monthly-1024g") + response = self.client.post(reverse("register"), { + "username": "new-applicant", "display_name": "Fixture Applicant", + "email": "new-applicant@example.invalid", "password1": "testing-Qp78-vNw4!", + "password2": "testing-Qp78-vNw4!", "plan": plan.pk, "accept_terms": "on", + "identity_type": "employee", "payment_status": "paid", + }, follow=True) + self.assertContains(response, "暂未开放付款,未扣款、未开通付费服务") + user = User.objects.get(username="new-applicant") + self.assertEqual(user.identity_type, "external") + self.assertEqual(user.account_status, "pending") + self.assertEqual(PlanApplication.objects.get(user=user).payment_status, "unpaid") + self.assertFalse(Subscription.objects.filter(user=user).exists()) diff --git a/backend/control/tests/test_git_releases.py b/backend/control/tests/test_git_releases.py new file mode 100644 index 0000000..f3deb21 --- /dev/null +++ b/backend/control/tests/test_git_releases.py @@ -0,0 +1,167 @@ +import copy +import json +import urllib.error +from unittest.mock import MagicMock, patch + +from django.core.cache import cache +from django.test import SimpleTestCase, override_settings +from django.urls import reverse + +from control import git_releases +from control.views import _version_tuple + + +@override_settings(SECURE_SSL_REDIRECT=False, CACHES={"default": { + "BACKEND": "django.core.cache.backends.locmem.LocMemCache", "LOCATION": "git-release-unit-tests", +}}) +class GitReleaseBridgeTests(SimpleTestCase): + def setUp(self): + cache.clear() + self.name = "UCVL-Zonghengjia-0.2.15-win-x64-setup.exe" + self.url = f"https://pro.ucvl.cn/admin/ucvl-software-downloads/releases/download/windows-v0.2.15/{self.name}" + self.release = {"tag_name": "windows-v0.2.15", "draft": False, "prerelease": False, + "body": "Stable notes", "assets": [ + {"name": self.name, "size": 100, "browser_download_url": "http://172.16.0.21:3000/ignored"}, + {"name": self.name + ".sha256", "size": 109}]} + self.checksum = ("a" * 64 + " " + self.name + "\n").encode("ascii") + + def fetch(self, releases=None, checksum=None): + return patch("control.git_releases._fetch", side_effect=[ + json.dumps([self.release] if releases is None else releases).encode(), + self.checksum if checksum is None else checksum, + ]) + + def test_canonical_public_git_url_not_internal_asset_url(self): + with self.fetch() as fetch: + manifest = git_releases.get_latest_windows_release() + self.assertEqual(manifest["download_url"], self.url) + self.assertEqual(manifest["sha256"], "a" * 64) + self.assertEqual(fetch.call_args_list[1].args[0], self.url + ".sha256") + + def test_ignores_draft_preview_and_other_platform_releases(self): + values = [self.release, + {"tag_name": "windows-v99.0.0", "prerelease": True}, + {"tag_name": "windows-v98.0.0", "draft": True}, + {"tag_name": "android-v99.0.0"}, {"tag_name": "mac-v99.0.0-green.1"}] + with self.fetch(values): + self.assertEqual(git_releases.get_latest_windows_release()["version"], "0.2.15") + + def test_numeric_order_not_api_order(self): + old = {"tag_name": "windows-v0.2.9", "draft": False, "prerelease": False, "assets": []} + with self.fetch([old, self.release]): + self.assertEqual(git_releases.get_latest_windows_release()["version"], "0.2.15") + + def test_invalid_newest_is_not_silently_replaced_with_old_package(self): + with self.fetch([self.release, {"tag_name": "windows-v0.2.16", "assets": []}]): + with self.assertRaises(git_releases.GitReleaseUnavailable): + git_releases.get_latest_windows_release() + + def test_missing_duplicate_or_nonlist_assets_rejected(self): + for assets in ([], self.release["assets"] * 2, {}, None): + with self.subTest(assets=assets), self.fetch([{**self.release, "assets": assets}]): + with self.assertRaises(git_releases.GitReleaseUnavailable): + git_releases.get_latest_windows_release() + + def test_untrusted_asset_urls_are_never_used(self): + value = copy.deepcopy(self.release) + value["assets"][1]["browser_download_url"] = "http://169.254.169.254/latest/meta-data/" + with self.fetch([value]) as fetch: + git_releases.get_latest_windows_release() + self.assertEqual(fetch.call_args_list[1].args[0], self.url + ".sha256") + + def test_checksum_requires_matching_filename(self): + for checksum in (b"a" * 64, b"a" * 64 + b" another.exe", b"z" * 64 + b" " + self.name.encode()): + with self.subTest(checksum=checksum), self.fetch(checksum=checksum): + with self.assertRaises(git_releases.GitReleaseUnavailable): + git_releases.get_latest_windows_release() + + def test_noninteger_or_oversize_package_rejected(self): + for size in (0, -1, True, "100", 201 * 1024 * 1024): + value = copy.deepcopy(self.release) + value["assets"][0]["size"] = size + with self.subTest(size=size), self.fetch([value]): + with self.assertRaises(git_releases.GitReleaseUnavailable): + git_releases.get_latest_windows_release() + + def test_cache_avoids_refetch_and_returns_independent_manifest(self): + with self.fetch() as fetch: + manifest = git_releases.get_latest_windows_release() + manifest["version"] = "mutated" + self.assertEqual(git_releases.get_latest_windows_release()["version"], "0.2.15") + self.assertEqual(fetch.call_count, 2) + + def test_fetch_has_no_proxy_or_authorization(self): + response = MagicMock(status=200) + response.geturl.return_value = git_releases.RELEASES_API + response.read.return_value = b"[]" + opener = MagicMock() + opener.open.return_value.__enter__.return_value = response + with patch("urllib.request.build_opener", return_value=opener) as build: + self.assertEqual(git_releases._fetch(git_releases.RELEASES_API, 1024), b"[]") + self.assertEqual(build.call_args.args[0].proxies, {}) + request = opener.open.call_args.args[0] + self.assertIsNone(request.get_header("Authorization")) + self.assertEqual(opener.open.call_args.kwargs["timeout"], 5) + + def test_fetch_rejects_redirect_size_and_other_origin(self): + with self.assertRaises(git_releases.GitReleaseUnavailable): + git_releases._fetch("https://example.org/", 1024) + for status, url, content in ((302, git_releases.RELEASES_API, b""), + (200, "http://pro.ucvl.cn/", b"[]"), + (200, git_releases.RELEASES_API, b"x" * 1025)): + response = MagicMock(status=status) + response.geturl.return_value = url + response.read.return_value = content + opener = MagicMock() + opener.open.return_value.__enter__.return_value = response + with patch("urllib.request.build_opener", return_value=opener): + with self.assertRaises(git_releases.GitReleaseUnavailable): + git_releases._fetch(git_releases.RELEASES_API, 1024) + + def test_fetch_network_error_is_sanitized(self): + opener = MagicMock() + opener.open.side_effect = urllib.error.URLError("private detail") + with patch("urllib.request.build_opener", return_value=opener): + with self.assertRaisesRegex(git_releases.GitReleaseUnavailable, "Company Git is unavailable"): + git_releases._fetch(git_releases.RELEASES_API, 1024) + + def test_old_client_update_payload_comes_from_git(self): + with self.fetch(): + response = self.client.get(reverse("client-update"), {"platform": "windows", "current": "0.2.13"}) + self.assertEqual(response.status_code, 200) + self.assertTrue(response.json()["available"]) + self.assertEqual(response.json()["download_url"], self.url) + self.assertEqual(response["Cache-Control"], "no-store") + + def test_build_metadata_does_not_repeat_current_update_prompt(self): + self.assertEqual(_version_tuple("0.2.15+abcdef"), (0, 2, 15)) + with self.fetch(): + response = self.client.get(reverse("client-update"), {"current": "0.2.15+abcdef"}) + self.assertFalse(response.json()["available"]) + + def test_stable_replaces_same_version_preview_without_downgrade(self): + with self.fetch(): + current_preview = self.client.get(reverse("client-update"), {"current": "0.2.15-preview.1"}) + future_preview = self.client.get(reverse("client-update"), {"current": "0.2.16-preview.1"}) + self.assertTrue(current_preview.json()["available"]) + self.assertFalse(future_preview.json()["available"]) + + def test_old_download_url_only_redirects_never_streams_local_file(self): + with self.fetch(), patch("builtins.open", side_effect=AssertionError("No local installer reads")): + response = self.client.get(reverse("client-download-latest")) + self.assertEqual(response.status_code, 302) + self.assertEqual(response["Location"], self.url) + self.assertFalse(response.streaming) + + def test_git_outage_does_not_fall_back_to_local_release(self): + with patch("control.views.get_latest_windows_release", side_effect=git_releases.GitReleaseUnavailable): + for route in ("client-update", "client-download-latest"): + response = self.client.get(reverse(route)) + self.assertEqual(response.status_code, 503) + self.assertEqual(response["Cache-Control"], "no-store") + + def test_other_platforms_not_advertised_as_windows(self): + with patch("control.views.get_latest_windows_release") as release: + response = self.client.get(reverse("client-update"), {"platform": "ios"}) + self.assertEqual(response.status_code, 404) + release.assert_not_called() diff --git a/backend/control/tests/test_learning_delivery.py b/backend/control/tests/test_learning_delivery.py new file mode 100644 index 0000000..8809b89 --- /dev/null +++ b/backend/control/tests/test_learning_delivery.py @@ -0,0 +1,97 @@ +import json +import uuid +from datetime import timedelta + +from django.contrib.auth import get_user_model +from django.test import TestCase, override_settings +from django.urls import reverse +from django.utils import timezone +from control.models import ClientSession, Device, LearnedRouteRule, Node, Plan, RouteObservation, RoutePolicyReceipt, Subscription +from control.learning import manifest, learning_summary +from control.vpn_ai import evaluate_route_learning + + +@override_settings(SECURE_SSL_REDIRECT=False) +class LearningDeliveryTests(TestCase): + def setUp(self): + user = get_user_model().objects.create_user(username="learner", account_status="active", identity_type="employee") + plan = Plan.objects.create(name="Fixture", slug="learning-fixture", device_limit=3) + self.sub = Subscription.objects.create(user=user, plan=plan, status="active", provisioning_state="active", device_limit=3) + self.node = Node.objects.create(name="Node", slug="learning-node", server="8.8.8.8", port=443, + protocol="vless_reality", status="online", active=True, subscription_enabled=True) + self.devices = [Device.objects.create(subscription=self.sub, device_id=f"learn-{i}", name="fixture") for i in range(3)] + self.tokens = [ClientSession.issue(self.sub, d)[1] for d in self.devices] + + def send(self, index=0, **fields): + payload = {"report_id": str(uuid.uuid4()), "target_type": "domain", "target": "learn.example.com", "port": 443, + "network": "tcp", "outcome": "direct_failed", "node": self.node.slug, **fields} + return self.client.post(reverse("client-observations"), json.dumps({"observations": [payload]}), + content_type="application/json", HTTP_AUTHORIZATION="Bearer " + self.tokens[index]), payload + + def test_failure_only_never_promotes(self): + for i in range(2): + for _ in range(4): self.assertEqual(self.send(i)[0].status_code, 200) + evaluate_route_learning(timezone.now()) + self.assertEqual(LearnedRouteRule.objects.get(target="learn.example.com").status, "pending") + + def test_two_correlated_tls_devices_create_candidate(self): + for i in range(2): + response, failure = self.send(i) + self.assertEqual(response.status_code, 200) + response, _ = self.send(i, outcome="proxy_succeeded", evidence_kind="tls", related_report_id=failure["report_id"]) + self.assertEqual(response.status_code, 200) + evaluate_route_learning(timezone.now()) + self.assertEqual(LearnedRouteRule.objects.get(target="learn.example.com").status, "active") + self.assertEqual(manifest()["mode"], "direct_first_candidates") + self.assertTrue(any(r["target"] == "learn.example.com" for r in manifest()["rules"])) + + def test_proof_must_belong_to_same_device_target_node_and_time(self): + _, failure = self.send() + for index, extras in [(1, {}), (0, {"target": "other.example.com"}), (0, {"port": 80}), + (0, {"node": "unauthorized-node"}), (0, {"network": "udp"})]: + response, _ = self.send(index, outcome="proxy_succeeded", evidence_kind="tls", related_report_id=failure["report_id"], **extras) + self.assertEqual(response.status_code, 400) + RouteObservation.objects.filter(report_id=failure["report_id"]).update(received_at=timezone.now()-timedelta(minutes=11)) + self.assertEqual(self.send(outcome="proxy_succeeded", evidence_kind="tls", related_report_id=failure["report_id"])[0].status_code, 400) + + def test_legacy_success_unverified_and_private_scope_cannot_promote(self): + for i in range(2): + self.send(i) + self.send(i, outcome="proxy_succeeded") + self.send(i, target="private.example.com", scope="private_auxiliary") + evaluate_route_learning(timezone.now()) + self.assertEqual(LearnedRouteRule.objects.get(target="learn.example.com").status, "pending") + self.assertFalse(LearnedRouteRule.objects.filter(target="private.example.com").exists()) + + def test_private_and_url_targets_rejected(self): + for target in ["127.0.0.1", "192.168.50.111", "vpn.toplc.cn", "host.local", "host.invalid", "https://example.com/a?secret=x"]: + self.assertEqual(self.send(target=target)[0].status_code, 400) + + def test_authenticated_receipt_and_version_revocation(self): + path = reverse("client-routing-rules") + self.assertEqual(self.client.get(path).status_code, 401) + auth = {"HTTP_AUTHORIZATION": "Bearer " + self.tokens[0]} + reply = self.client.get(path, **auth) + self.assertEqual(reply.status_code, 200) + version = reply.json()["revision"] + self.assertEqual(reply["Cache-Control"], "no-store") + def ack(revision): return self.client.post(path, json.dumps({"revision": revision, "status": "cached"}), content_type="application/json", **auth) + self.assertEqual(ack("f"*64).status_code, 400) + self.assertEqual(ack(version).status_code, 200) + self.assertEqual(learning_summary()["cached"], 1) + rule = LearnedRouteRule.objects.create(target="learn.example.com", target_type="domain", source="ai", status="active") + changed = self.client.get(path, **auth).json()["revision"] + self.assertNotEqual(version, changed) + self.assertEqual(ack(version).status_code, 400) + rule.status = "disabled"; rule.save() + self.assertEqual(manifest()["revision"], version) + self.devices[0].active = False; self.devices[0].save() + self.assertEqual(self.client.get(path, **auth).status_code, 403) + + def test_idempotence_and_budget(self): + _, first = self.send() + self.assertEqual(self.send(report_id=first["report_id"])[0].json()["accepted"], 0) + self.assertEqual(self.send(1, report_id=first["report_id"])[0].status_code, 400) + RouteObservation.objects.bulk_create([RouteObservation(report_id=uuid.uuid4(), subscription=self.sub, device=self.devices[0], + target_type="domain", target="learn.example.com", port=443, network="tcp", outcome="direct_failed") for _ in range(119)]) + self.assertEqual(self.send()[0].status_code, 429) diff --git a/backend/control/tests/test_office_permissions.py b/backend/control/tests/test_office_permissions.py new file mode 100644 index 0000000..0c8edee --- /dev/null +++ b/backend/control/tests/test_office_permissions.py @@ -0,0 +1,180 @@ +from datetime import timedelta +from django.contrib.auth import get_user_model +from django.test import TestCase +from django.utils import timezone +from control.models import ClientSession, Device, Node, NodeDeployment, Plan, Subscription +from control.services import desired_subscriptions_for_node, render_xray_client + + +class OfficePermissionsTests(TestCase): + def setUp(self): + self.user = get_user_model().objects.create_user(username="office", identity_type="employee", account_status="active") + plan = Plan.objects.create(name="office", slug="office") + self.sub = Subscription.objects.create(user=self.user, plan=plan, status="active", provisioning_state="active") + self.node = Node.objects.create(name="优创未来·济南办", slug="office", region="济南", server="192.168.50.111", port=11081, + protocol="vless_reality", status="online", subscription_enabled=True, office_only=True, + office_access_scope=Node.OfficeAccessScope.EXPLICIT_USERS) + + def test_empty_whitelist_respects_configured_scope(self): + self.assertFalse(self.sub.office_nodes_for_authorization().exists()) + + def test_whitelist_is_not_local_presence_or_legacy_config_grant(self): + self.node.office_users.add(self.user) + self.assertTrue(self.sub.office_nodes_for_authorization().exists()) + self.assertFalse(self.sub.nodes_for_subscription().exists()) + + def test_external_even_whitelisted_denied(self): + self.node.office_users.add(self.user) + self.user.identity_type = "external" + self.user.save() + self.assertFalse(self.sub.office_nodes_for_authorization().exists()) + + def test_departed_employee_denied(self): + self.node.office_users.add(self.user) + self.user.account_status = "departed" + self.user.save() + self.assertFalse(self.sub.office_nodes_for_authorization().exists()) + + def test_whitelist_removal_respects_configured_scope(self): + self.node.office_users.add(self.user) + self.node.office_users.remove(self.user) + self.assertFalse(self.sub.office_nodes_for_authorization().exists()) + + def test_dedicated_subscription_still_restricts_office(self): + self.node.office_users.add(self.user) + self.sub.route_mode = Subscription.RouteMode.DEDICATED + self.sub.save() + self.assertFalse(self.sub.office_nodes_for_authorization().exists()) + self.sub.allowed_nodes.add(self.node) + self.assertTrue(self.sub.office_nodes_for_authorization().exists()) + + def test_other_employee_candidate_boundary(self): + self.node.office_users.add(self.user) + other = get_user_model().objects.create_user(username="another-office", email="other@example.invalid", + identity_type="employee", account_status="active") + other_sub = Subscription.objects.create(user=other, plan=self.sub.plan, status="active", provisioning_state="active") + self.assertFalse(other_sub.office_nodes_for_authorization().exists()) + + def test_account_state_checked_even_with_office_membership(self): + self.node.office_users.add(self.user) + for status in ("pending", "suspended", "departed"): + with self.subTest(status=status): + self.user.account_status = status + self.user.save() + self.assertFalse(self.sub.office_nodes_for_authorization().exists()) + self.user.account_status = "active" + self.user.is_active = False + self.user.save() + self.assertFalse(self.sub.office_nodes_for_authorization().exists()) + + def test_offline_disabled_or_unpublished_node_cannot_be_authorized(self): + self.node.office_users.add(self.user) + for field, value in (("active", False), ("status", "offline"), ("subscription_enabled", False)): + with self.subTest(field=field): + previous = getattr(self.node, field) + setattr(self.node, field, value) + self.node.save() + self.assertFalse(self.sub.office_nodes_for_authorization().exists()) + setattr(self.node, field, previous) + self.node.save() + + def test_expired_or_exhausted_subscription_cannot_use_office(self): + self.node.office_users.add(self.user) + self.sub.expires_at = timezone.now() - timedelta(seconds=1) + self.sub.save() + self.assertFalse(self.sub.office_nodes_for_authorization().exists()) + self.sub.expires_at = None + self.sub.traffic_limit_bytes = 100 + self.sub.upload_bytes = 100 + self.sub.save() + self.assertFalse(self.sub.office_nodes_for_authorization().exists()) + + def test_legacy_api_cannot_bypass_pending_local_node_validation(self): + self.node.office_users.add(self.user) + device = Device.objects.create(subscription=self.sub, device_id="office-api-boundary") + _, token = ClientSession.issue(self.sub, device) + headers = {"HTTP_AUTHORIZATION": f"Bearer {token}"} + profile = self.client.get("/api/v1/client/profile/", **headers) + self.assertEqual(profile.status_code, 200) + self.assertEqual(profile.json()["profile"]["nodes"], []) + for selection in (self.node.slug, "auto"): + with self.subTest(selection=selection): + response = self.client.get("/api/v1/client/config/", {"node": selection, "route": "smart"}, **headers) + self.assertEqual(response.status_code, 404) + self.assertNotIn("config", response.json()) + device.active = False + device.save() + self.assertEqual(self.client.get("/api/v1/client/profile/", **headers).status_code, 403) + + def test_agent_sync_does_not_provision_office_candidates(self): + self.node.office_users.add(self.user) + self.node.set_agent_token("synthetic-office-agent-token") + self.node.save(update_fields=["agent_token_digest"]) + self.sub.allowed_nodes.add(self.node) + for mode in Subscription.RouteMode.values: + with self.subTest(mode=mode): + self.sub.route_mode = mode + self.sub.save(update_fields=["route_mode"]) + self.assertFalse(desired_subscriptions_for_node(self.node).exists()) + response = self.client.get("/api/v1/node/sync/", + HTTP_X_NODE_SLUG=self.node.slug, + HTTP_AUTHORIZATION="Bearer synthetic-office-agent-token") + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()["clients"], []) + self.assertNotContains(response, str(self.sub.credential_uuid)) + self.assertFalse(NodeDeployment.objects.filter(node=self.node).exists()) + + def test_direct_renderer_cannot_bypass_pending_site_validation(self): + self.node.office_users.add(self.user) + for mode in ("smart", "global", "direct"): + with self.subTest(mode=mode), self.assertRaisesMessage(ValueError, "办公室"): + render_xray_client(self.sub, self.node, route_mode=mode) + + def test_public_node_provisioning_and_rendering_are_unchanged(self): + self.node.office_only = False + self.node.save(update_fields=["office_only"]) + self.assertIn(self.sub, desired_subscriptions_for_node(self.node)) + self.assertIn(self.node, self.sub.nodes_for_subscription()) + config = render_xray_client(self.sub, self.node) + self.assertEqual(config["outbounds"][0]["settings"]["vnext"][0]["users"][0]["id"], + str(self.sub.credential_uuid)) + + +class OfficeNetworkScopeTests(OfficePermissionsTests): + """Site presence decides availability, not the employee's home office.""" + + def setUp(self): + super().setUp() + self.node.office_access_scope = Node.OfficeAccessScope.COMPANY_NETWORK + self.node.save(update_fields=["office_access_scope"]) + + def test_empty_whitelist_respects_configured_scope(self): + # Override the legacy-mode expectation: it is a candidate, NOT a grant. + self.assertTrue(self.sub.office_nodes_for_authorization().exists()) + self.assertFalse(self.sub.nodes_for_subscription().exists()) + + def test_whitelist_removal_respects_configured_scope(self): + # Network mode must not depend on stale per-person membership lists. + self.node.office_users.add(self.user) + self.node.office_users.remove(self.user) + self.assertTrue(self.sub.office_nodes_for_authorization().exists()) + self.user.account_status = "departed" + self.user.save() + self.assertFalse(self.sub.office_nodes_for_authorization().exists()) + + def test_other_employee_candidate_boundary(self): + # A visiting employee needs the same site proof, not reassignment in HR. + other = get_user_model().objects.create_user(username="visiting", email="visiting@example.invalid", + identity_type="employee", account_status="active") + other_sub = Subscription.objects.create(user=other, plan=self.sub.plan, status="active", provisioning_state="active") + self.assertTrue(other_sub.office_nodes_for_authorization().exists()) + self.assertFalse(other_sub.nodes_for_subscription().exists()) + + def test_unknown_scope_fails_closed(self): + self.node.office_access_scope = "unknown" + self.node.save() + self.node.office_users.add(self.user) + self.assertFalse(self.sub.office_nodes_for_authorization().exists()) + + def test_new_node_defaults_to_company_network(self): + self.assertEqual(Node().office_access_scope, Node.OfficeAccessScope.COMPANY_NETWORK) diff --git a/backend/control/tests/test_office_scope_migration.py b/backend/control/tests/test_office_scope_migration.py new file mode 100644 index 0000000..777ebc8 --- /dev/null +++ b/backend/control/tests/test_office_scope_migration.py @@ -0,0 +1,57 @@ +"""Office candidate-scope migration rehearsal in Django's disposable test DB.""" + +from django.db import connection +from django.db.migrations.executor import MigrationExecutor +from django.test import TransactionTestCase + + +class OfficeScopeMigrationTests(TransactionTestCase): + def test_old_boundaries_survive_forward_reverse_and_new_default(self): + self.assertTrue(str(connection.settings_dict["NAME"]).startswith( + ("test_", "file:memory") + ), "Migration rehearsals must only target the disposable test database") + old_target = [("control", "0013_node_office_permissions")] + new_target = [("control", "0014_node_office_access_scope")] + executor = MigrationExecutor(connection) + latest_targets = executor.loader.graph.leaf_nodes() + try: + executor.migrate(old_target) + old_apps = executor.loader.project_state(old_target).apps + OldUser = old_apps.get_model("accounts", "User") + OldNode = old_apps.get_model("control", "Node") + user = OldUser.objects.create(username="office-migration", email="migration@example.invalid") + common = dict(region="test", server="192.0.2.1", port=11081, + protocol="vless_reality", status="online", subscription_enabled=True) + listed = OldNode.objects.create(name="listed", slug="listed", office_only=True, + total_upload_bytes=123, **common) + empty = OldNode.objects.create(name="empty", slug="empty", office_only=True, **common) + public = OldNode.objects.create(name="public", slug="public", office_only=False, **common) + listed.office_users.add(user) + old_ids = [listed.pk, empty.pk, public.pk] + before = list(OldNode.objects.filter(pk__in=old_ids).order_by("pk").values()) + + forward = MigrationExecutor(connection) + forward.migrate(new_target) + NewNode = forward.loader.project_state(new_target).apps.get_model("control", "Node") + self.assertEqual(list(NewNode.objects.filter(pk__in=old_ids).order_by("pk").values( + *before[0].keys() + )), before) + self.assertEqual(set(NewNode.objects.filter(pk__in=old_ids).values_list( + "office_access_scope", flat=True + )), {"explicit_users"}) + self.assertEqual(list(NewNode.objects.get(pk=listed.pk).office_users.values_list("pk", flat=True)), [user.pk]) + self.assertFalse(NewNode.objects.get(pk=empty.pk).office_users.exists()) + + new = NewNode.objects.create(name="new-site", slug="new-site", office_only=True, **common) + self.assertEqual(new.office_access_scope, "company_network") + self.assertFalse(new.office_users.exists()) + + MigrationExecutor(connection).migrate(old_target) + self.assertEqual(list(OldNode.objects.filter(pk__in=old_ids).order_by("pk").values()), before) + self.assertEqual(list(OldNode.objects.get(pk=listed.pk).office_users.values_list("pk", flat=True)), [user.pk]) + self.assertTrue(OldNode.objects.get(pk=new.pk).office_only) + # Re-applying after schema rollback must not silently broaden any node. + MigrationExecutor(connection).migrate(new_target) + self.assertEqual(set(NewNode.objects.values_list("office_access_scope", flat=True)), {"explicit_users"}) + finally: + MigrationExecutor(connection).migrate(latest_targets) diff --git a/backend/control/tests/test_plan_catalog.py b/backend/control/tests/test_plan_catalog.py new file mode 100644 index 0000000..54cc7b0 --- /dev/null +++ b/backend/control/tests/test_plan_catalog.py @@ -0,0 +1,171 @@ +from decimal import Decimal +from io import StringIO + +from django.core.exceptions import ValidationError +from django.core.management import call_command +from django.core.management.base import CommandError +from django.db import IntegrityError, transaction +from django.test import TestCase, override_settings +from django.urls import reverse + +from accounts.forms import RegistrationForm +from accounts.models import User +from control.forms import PlanApplicationForm +from control.models import Node, Plan, PlanApplication, PlanCatalogDraft, Subscription +from control.plan_catalog import proposed_catalog +from control.services import desired_subscriptions_for_node + + +@override_settings(SECURE_SSL_REDIRECT=False, WECOM_ENABLED=False, + STORAGES={"default": {"BACKEND": "django.core.files.storage.FileSystemStorage"}, + "staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"}}) +class PlanCatalogDraftTests(TestCase): + def setUp(self): + self.employee = User.objects.create_user(username="catalog-employee", email="catalog-employee@example.invalid", identity_type="employee", account_status="active") + self.external = User.objects.create_user(username="catalog-external", email="catalog-external@example.invalid", account_status="active") + self.admin = User.objects.create_superuser(username="catalog-admin", email="catalog@example.invalid", password="fixture") + call_command("prepare_monthly_1024g", list_plan=True, stdout=StringIO()) + self.original = Plan.objects.get(slug="monthly-1024g") + + def seed(self): + call_command("prepare_plan_catalog", create=True, stdout=StringIO()) + + def test_default_is_read_only_preview(self): + output = StringIO() + call_command("prepare_plan_catalog", stdout=output) + self.assertIn("共19项", output.getvalue()) + self.assertIn("仅预览,未写入", output.getvalue()) + self.assertEqual(PlanCatalogDraft.objects.count(), 0) + + def test_exactly_twelve_additional_personal_quotas_plus_unlimited(self): + self.seed() + personal = PlanCatalogDraft.objects.filter(scope="personal") + self.assertEqual(personal.count(), 13) + self.assertEqual(personal.filter(traffic_limit_gb__gt=0).count(), 12) + self.assertEqual(personal.filter(traffic_limit_gb=1024).count(), 0) + self.assertEqual(personal.filter(traffic_limit_gb=0).count(), 1) + self.assertEqual(personal.exclude(member_limit=1, device_limit=3).count(), 0) + self.assertEqual(personal.filter(price_cny__isnull=True).count(), 13) + + def test_team_quota_and_caps_are_per_member_proposals_not_confirmed_prices(self): + self.seed() + teams = PlanCatalogDraft.objects.filter(scope="team") + self.assertSetEqual(set(teams.values_list("traffic_limit_gb", flat=True)), {0, 3*1024, 5*1024, 10*1024, 20*1024, 50*1024}) + for draft in teams: + self.assertIsNone(draft.price_cny) + if draft.traffic_limit_gb: + self.assertEqual(draft.traffic_limit_gb, draft.member_limit * 1024) + self.assertEqual(draft.device_limit, draft.member_limit * 3) + self.assertEqual(draft.concurrent_limit, draft.member_limit * 2) + else: + self.assertIsNone(draft.member_limit) + self.assertIsNone(draft.device_limit) + self.assertIsNone(draft.concurrent_limit) + self.assertIn("共享账本尚未接入", draft.description) + + def test_seed_idempotent_and_preserves_admin_pricing_and_notes(self): + self.seed() + draft = PlanCatalogDraft.objects.get(slug="team-monthly-20-members") + draft.price_cny = Decimal("100.00") # synthetic proposal, not a released price + draft.member_limit, draft.device_limit, draft.concurrent_limit = 20, 40, 10 + draft.name, draft.description = "管理员草案", "人工确认内容" + draft.save() + before = list(PlanCatalogDraft.objects.values()) + self.seed() + self.assertEqual(list(PlanCatalogDraft.objects.values()), before) + self.assertEqual(PlanCatalogDraft.objects.count(), 19) + + def test_conflicting_quota_rolls_back_whole_seed_batch(self): + spec = proposed_catalog()[-1].copy() + spec["traffic_limit_gb"] = 42 + conflict = PlanCatalogDraft.objects.create(**spec) + with self.assertRaises(CommandError): + self.seed() + self.assertEqual(PlanCatalogDraft.objects.count(), 1) + conflict.refresh_from_db() + self.assertEqual(conflict.traffic_limit_gb, 42) + + def test_original_plans_subscriptions_usage_and_tokens_are_unchanged(self): + subscription = PlanApplication.submit(user=self.employee, plan=self.original).approve(self.admin) + Subscription.objects.filter(pk=subscription.pk).update(upload_bytes=12345, download_bytes=67890) + before_plans = list(Plan.objects.values()) + before_subscriptions = list(Subscription.objects.values()) + before_applications = list(PlanApplication.objects.values()) + self.seed() + self.assertEqual(list(Plan.objects.values()), before_plans) + self.assertEqual(list(Subscription.objects.values()), before_subscriptions) + self.assertEqual(list(PlanApplication.objects.values()), before_applications) + self.original.refresh_from_db() + self.assertEqual(self.original.price_cny, Decimal("8.00")) + self.assertEqual(self.original.traffic_limit_gb, 1024) + + def test_drafts_never_enter_registration_application_or_node_configuration(self): + before_register = list(RegistrationForm().fields["plan"].queryset.values_list("pk", flat=True)) + before_apply = list(PlanApplicationForm(user=self.external).fields["plan"].queryset.values_list("pk", flat=True)) + self.seed() + self.assertEqual(list(RegistrationForm().fields["plan"].queryset.values_list("pk", flat=True)), before_register) + self.assertEqual(list(PlanApplicationForm(user=self.external).fields["plan"].queryset.values_list("pk", flat=True)), before_apply) + node = Node.objects.create(name="fixture", slug="catalog-fixture", server="example.invalid", port=11082) + self.assertFalse(desired_subscriptions_for_node(node).exists()) + self.assertEqual(PlanApplication.objects.count(), 0) + + def test_external_cannot_read_draft_admin(self): + self.seed() + self.client.force_login(self.external) + response = self.client.get(reverse("admin:control_plancatalogdraft_changelist")) + self.assertEqual(response.status_code, 302) + self.assertIn("/admin/login/", response.url) + response = self.client.get(reverse("portal-dashboard")) + self.assertNotContains(response, "团队无限流量月度套餐") + self.assertNotContains(response, "个人无限流量月度套餐") + + def test_admin_sees_pending_not_free_and_cannot_publish_from_draft(self): + self.seed() + self.client.force_login(self.admin) + response = self.client.get(reverse("admin:control_plancatalogdraft_changelist")) + self.assertContains(response, "待定价", count=19) + self.assertContains(response, "仅草稿 · 未上架 · 不收款") + draft = PlanCatalogDraft.objects.get(slug="team-monthly-unlimited") + response = self.client.get(reverse("admin:control_plancatalogdraft_change", args=[draft.pk])) + self.assertContains(response, "团队成员共享账本尚未接入") + self.assertNotContains(response, 'name="active"') + + def test_unlimited_and_pending_labels(self): + draft = PlanCatalogDraft(**proposed_catalog()[-1]) + self.assertEqual(draft.quota_label, "无限代理流量") + self.assertEqual(draft.price_label, "待定价") + draft.traffic_limit_gb = 20 * 1024 + self.assertEqual(draft.quota_label, "20 TB/月") + draft.price_cny = Decimal("8.00") + self.assertIn("草稿", draft.price_label) + + def test_validation_rejects_negative_price_zero_caps_and_invalid_personal_seats(self): + for field, value in (("price_cny", Decimal("-1")), ("member_limit", 0), ("device_limit", 0), ("concurrent_limit", 0), ("member_limit", 2), ("concurrent_limit", 4)): + with self.subTest(field=field, value=value): + draft = PlanCatalogDraft(**proposed_catalog()[0]) + setattr(draft, field, value) + with self.assertRaises(ValidationError): + draft.full_clean() + + def test_database_rejects_negative_price_or_zero_limits(self): + for field, value in (("price_cny", -1), ("member_limit", 0), ("device_limit", 0), ("concurrent_limit", 0)): + with self.subTest(field=field): + spec = proposed_catalog()[0].copy() + spec[field] = value + with self.assertRaises(IntegrityError), transaction.atomic(): + PlanCatalogDraft.objects.create(**spec) + + def test_live_unlimited_plan_keeps_expiry_and_device_limit_and_tracks_usage(self): + # Exercise existing unlimited semantics without publishing the new draft. + plan = Plan.objects.create(name="Unlimited fixture", slug="unlimited-fixture", traffic_limit_gb=0, + billing_months=1, duration_days=0, device_limit=3) + subscription = PlanApplication.submit(user=self.employee, plan=plan).approve(self.admin) + subscription.provisioning_state = "active" + subscription.upload_bytes = 50 * 1024**4 + subscription.save() + self.assertIsNone(subscription.remaining_bytes) + self.assertEqual(subscription.usage_percent, 0) + self.assertEqual(subscription.device_limit, 3) + self.assertIsNotNone(subscription.expires_at) + self.assertEqual(subscription.used_bytes, 50 * 1024**4) + self.assertTrue(subscription.is_usable) diff --git a/backend/control/tests/test_platform.py b/backend/control/tests/test_platform.py new file mode 100644 index 0000000..3c4ce8e --- /dev/null +++ b/backend/control/tests/test_platform.py @@ -0,0 +1,906 @@ +import json +import uuid +from unittest.mock import patch + +from django.contrib.auth import get_user_model +from django.core.exceptions import ValidationError +from django.core.management import call_command +from django.test import TestCase, override_settings +from django.urls import reverse +from django.utils import timezone + +from accounts.models import LoginAttempt +from accounts.admin import approve_as_external +from accounts.forms import RegistrationForm +from control.models import ( + ClientSession, + Device, + LearnedRouteRule, + Node, + NodeReport, + NodeTrafficSample, + Plan, + PlanApplication, + RouteObservation, + RoutingPolicy, + Subscription, + UsageRecord, + HourlyUsageRecord, + VpnAiRuntime, +) +from control.vpn_ai import run_vpn_ai_cycle + + +@override_settings( + SECURE_SSL_REDIRECT=False, + PUBLIC_BASE_URL="https://vpn.toplc.cn", + STORAGES={ + "default": {"BACKEND": "django.core.files.storage.FileSystemStorage"}, + "staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"}, + }, +) +class PlatformFlowTests(TestCase): + def setUp(self): + User = get_user_model() + self.admin = User.objects.create_superuser( + username="admin", + email="admin@example.com", + password="A-strong-admin-password-123", + display_name="管理员", + identity_type=User.IdentityType.EMPLOYEE, + account_status=User.AccountStatus.ACTIVE, + ) + self.user = User.objects.create_user( + username="tester", + email="tester@example.com", + password="A-strong-user-password-123", + display_name="测试用户", + identity_type=User.IdentityType.EXTERNAL, + account_status=User.AccountStatus.ACTIVE, + ) + self.plan = Plan.objects.create( + name="测试月度套餐", + slug="test-monthly", + audience=Plan.Audience.EXTERNAL, + price_cny=10, + traffic_limit_gb=10, + duration_days=30, + device_limit=2, + ) + self.policy = RoutingPolicy.objects.create( + name="默认策略", + is_global=True, + rules=["GEOIP,CN,DIRECT", "MATCH,节点选择"], + ) + self.node = Node.objects.create( + name="测试节点", + slug="test-node", + region="测试区", + server="203.0.113.10", + port=443, + protocol=Node.Protocol.VLESS_REALITY, + status=Node.Status.ONLINE, + active=True, + subscription_enabled=True, + sni="www.example.com", + reality_public_key="public-key", + reality_short_id="0123456789abcdef", + ) + self.node.set_agent_token("node-test-token-that-is-long-enough-123") + self.node.save(update_fields=["agent_token_digest"]) + + def create_active_subscription(self): + subscription = Subscription.objects.create(user=self.user, plan=self.plan) + subscription.activate() + subscription.provisioning_state = Subscription.ProvisioningState.ACTIVE + subscription.save(update_fields=["provisioning_state"]) + return subscription + + def test_paid_application_requires_payment(self): + application = PlanApplication.objects.create(user=self.user, plan=self.plan) + with self.assertRaises(ValidationError): + application.approve(self.admin) + application.payment_status = PlanApplication.PaymentStatus.PAID + application.save(update_fields=["payment_status"]) + subscription = application.approve(self.admin) + self.assertEqual(subscription.status, Subscription.Status.ACTIVE) + self.assertEqual(subscription.traffic_limit_bytes, 10 * 1024**3) + application.refresh_from_db() + self.assertEqual(application.subscription, subscription) + + def test_application_approval_is_idempotent(self): + application = PlanApplication.objects.create( + user=self.user, + plan=self.plan, + payment_status=PlanApplication.PaymentStatus.PAID, + ) + first = application.approve(self.admin) + second = application.approve(self.admin) + self.assertEqual(first.pk, second.pk) + self.assertEqual(Subscription.objects.filter(user=self.user).count(), 1) + + def test_plan_change_reuses_subscription_and_preserves_period_usage(self): + subscription = self.create_active_subscription() + subscription.upload_bytes = 1024 + subscription.download_bytes = 2048 + subscription.save(update_fields=["upload_bytes", "download_bytes"]) + original_period = (subscription.starts_at, subscription.expires_at) + original_credential = (subscription.credential_uuid, subscription.token_version) + new_plan = Plan.objects.create( + name="升级套餐", + slug="upgraded-monthly", + audience=Plan.Audience.EXTERNAL, + price_cny=20, + traffic_limit_gb=30, + duration_days=60, + device_limit=5, + ) + application = PlanApplication.objects.create( + user=self.user, + plan=new_plan, + payment_status=PlanApplication.PaymentStatus.PAID, + ) + + changed = application.approve(self.admin) + + self.assertEqual(changed.pk, subscription.pk) + self.assertEqual(changed.plan, new_plan) + self.assertEqual(changed.status, Subscription.Status.ACTIVE) + self.assertEqual(changed.provisioning_state, Subscription.ProvisioningState.PENDING) + self.assertEqual(changed.traffic_limit_bytes, 30 * 1024**3) + self.assertEqual(changed.device_limit, 5) + self.assertEqual(changed.used_bytes, 3072) + self.assertEqual((changed.starts_at, changed.expires_at), original_period) + self.assertEqual((changed.credential_uuid, changed.token_version), original_credential) + + def test_active_subscriber_can_apply_for_a_different_plan(self): + self.create_active_subscription() + new_plan = Plan.objects.create( + name="可申请的新套餐", + slug="change-request-plan", + audience=Plan.Audience.EXTERNAL, + price_cny=0, + traffic_limit_gb=20, + duration_days=30, + device_limit=3, + ) + self.client.force_login(self.user) + + response = self.client.post(reverse("apply-plan"), {"plan": new_plan.pk, "note": "升级"}) + + self.assertRedirects(response, reverse("portal-dashboard")) + application = PlanApplication.objects.get(user=self.user, status=PlanApplication.Status.PENDING) + self.assertEqual(application.plan, new_plan) + + def test_user_admin_approval_creates_subscription_from_pending_application(self): + self.user.account_status = self.user.AccountStatus.PENDING + self.user.save(update_fields=["account_status"]) + application = PlanApplication.objects.create( + user=self.user, + plan=self.plan, + payment_status=PlanApplication.PaymentStatus.PAID, + ) + self.client.force_login(self.admin) + + response = self.client.post( + reverse("admin:accounts_user_changelist"), + {"action": approve_as_external.__name__, "_selected_action": [self.user.pk]}, + follow=True, + ) + + self.assertEqual(response.status_code, 200) + self.user.refresh_from_db() + application.refresh_from_db() + self.assertEqual(self.user.account_status, self.user.AccountStatus.ACTIVE) + self.assertEqual(application.status, PlanApplication.Status.APPROVED) + self.assertIsNotNone(application.subscription_id) + + def test_user_admin_approval_without_application_does_not_enable_account(self): + self.user.account_status = self.user.AccountStatus.PENDING + self.user.save(update_fields=["account_status"]) + self.client.force_login(self.admin) + + response = self.client.post( + reverse("admin:accounts_user_changelist"), + {"action": approve_as_external.__name__, "_selected_action": [self.user.pk]}, + follow=True, + ) + + self.assertEqual(response.status_code, 200) + self.user.refresh_from_db() + self.assertEqual(self.user.account_status, self.user.AccountStatus.PENDING) + self.assertFalse(Subscription.objects.filter(user=self.user).exists()) + + def test_approval_refuses_duplicate_subscriptions_without_cancelling_any(self): + first = self.create_active_subscription() + duplicate = Subscription.objects.create(user=self.user, plan=self.plan) + application = PlanApplication.objects.create( + user=self.user, plan=self.plan, payment_status=PlanApplication.PaymentStatus.PAID, + ) + credentials = (first.credential_uuid, duplicate.credential_uuid) + with self.assertRaisesMessage(ValidationError, "多个未结束订阅"): + application.approve(self.admin) + first.refresh_from_db() + duplicate.refresh_from_db() + application.refresh_from_db() + self.assertEqual(first.status, Subscription.Status.ACTIVE) + self.assertEqual(duplicate.status, Subscription.Status.PENDING) + self.assertEqual((first.credential_uuid, duplicate.credential_uuid), credentials) + self.assertEqual(application.status, PlanApplication.Status.PENDING) + + def test_failed_subscription_save_rolls_back_user_approval(self): + self.user.account_status = self.user.AccountStatus.PENDING + self.user.save(update_fields=["account_status"]) + application = PlanApplication.objects.create( + user=self.user, plan=self.plan, payment_status=PlanApplication.PaymentStatus.PAID, + ) + with patch.object(Subscription, "full_clean", side_effect=ValidationError("test validation failure")): + with self.assertRaises(ValidationError): + application.approve(self.admin) + self.user.refresh_from_db() + application.refresh_from_db() + self.assertEqual(self.user.account_status, self.user.AccountStatus.PENDING) + self.assertEqual(application.status, PlanApplication.Status.PENDING) + self.assertFalse(Subscription.objects.filter(user=self.user).exists()) + + def test_disabled_plan_cannot_be_approved(self): + application = PlanApplication.objects.create( + user=self.user, plan=self.plan, payment_status=PlanApplication.PaymentStatus.PAID, + ) + Plan.objects.filter(pk=self.plan.pk).update(active=False) + with self.assertRaisesMessage(ValidationError, "已停用"): + application.approve(self.admin) + self.assertFalse(Subscription.objects.filter(user=self.user).exists()) + + def test_pending_application_submission_is_not_duplicated(self): + PlanApplication.submit(user=self.user, plan=self.plan) + with self.assertRaisesMessage(ValidationError, "已有待处理申请"): + PlanApplication.submit(user=self.user, plan=self.plan) + self.assertEqual(PlanApplication.objects.filter(user=self.user).count(), 1) + + def test_approval_rechecks_audience_changed_after_submission(self): + application = PlanApplication.submit(user=self.user, plan=self.plan) + application.payment_status = PlanApplication.PaymentStatus.PAID + application.save(update_fields=["payment_status"]) + Plan.objects.filter(pk=self.plan.pk).update(audience=Plan.Audience.EMPLOYEE) + with self.assertRaisesMessage(ValidationError, "适用身份"): + application.approve(self.admin) + application.refresh_from_db() + self.assertEqual(application.status, PlanApplication.Status.PENDING) + self.assertFalse(self.user.subscriptions.exists()) + + def test_all_audience_plan_remains_approvable(self): + Plan.objects.filter(pk=self.plan.pk).update(audience=Plan.Audience.ALL) + application = PlanApplication.objects.create( + user=self.user, plan=self.plan, payment_status=PlanApplication.PaymentStatus.PAID, + ) + self.assertEqual(application.approve(self.admin).plan_id, self.plan.pk) + + def test_active_user_dashboard_has_change_plan_link(self): + self.create_active_subscription() + self.client.force_login(self.user) + self.assertContains(self.client.get(reverse("portal-dashboard")), "申请更换套餐") + + def test_employee_benefit_not_self_assigned_by_registration(self): + benefit = Plan.objects.create(name="员工福利", slug="private-benefit", employee_benefit=True) + form = RegistrationForm() + self.assertNotIn(benefit, form.fields["plan"].queryset) + with self.assertRaisesMessage(ValidationError, "不可申请"): + PlanApplication.submit(user=self.user, plan=benefit) + + def test_registration_without_plan_does_not_create_account(self): + data = self.registration_data() + data.pop("plan") + response = self.client.post(reverse("register"), data) + self.assertEqual(response.status_code, 200) + self.assertIn("plan", response.context["form"].errors) + self.assertFalse(get_user_model().objects.filter(username="newcontact").exists()) + + def test_registration_rollback_if_application_fails(self): + with patch.object(PlanApplication, "submit", side_effect=ValidationError("套餐已经停用")): + response = self.client.post(reverse("register"), self.registration_data()) + self.assertEqual(response.status_code, 200) + self.assertFalse(get_user_model().objects.filter(username="newcontact").exists()) + + def test_free_registration_approval_automatically_creates_subscription(self): + self.plan.price_cny = 0 + self.plan.save(update_fields=["price_cny"]) + response = self.client.post(reverse("register"), self.registration_data()) + self.assertRedirects(response, reverse("portal-dashboard")) + created = get_user_model().objects.get(username="newcontact") + application = PlanApplication.objects.get(user=created) + self.assertEqual(application.payment_status, PlanApplication.PaymentStatus.NOT_REQUIRED) + subscription = application.approve(self.admin) + self.assertEqual(subscription.user_id, created.pk) + self.assertEqual(subscription.status, Subscription.Status.ACTIVE) + self.assertEqual(subscription.provisioning_state, Subscription.ProvisioningState.PENDING) + + def test_subscription_endpoint_returns_mihomo_yaml(self): + subscription = self.create_active_subscription() + response = self.client.get(reverse("subscription-config", args=[subscription.subscription_token])) + self.assertEqual(response.status_code, 200) + self.assertContains(response, "type: vless") + self.assertContains(response, str(subscription.credential_uuid)) + self.assertEqual(response["Cache-Control"], "no-store") + + def test_rotating_token_invalidates_old_url(self): + subscription = self.create_active_subscription() + old_token = subscription.subscription_token + subscription.rotate_subscription() + response = self.client.get(reverse("subscription-config", args=[old_token])) + self.assertEqual(response.status_code, 404) + + def test_windows_client_login_profile_config_and_logout(self): + subscription = self.create_active_subscription() + login_response = self.client.post( + reverse("client-login"), + data=json.dumps( + { + "login": self.user.email, + "password": "A-strong-user-password-123", + "device_id": "windows-device-0001", + "device_name": "测试电脑", + "app_version": "0.1.0", + } + ), + content_type="application/json", + ) + self.assertEqual(login_response.status_code, 200) + token = login_response.json()["access_token"] + self.assertNotIn(token, ClientSession.objects.get().token_digest) + headers = {"HTTP_AUTHORIZATION": f"Bearer {token}"} + + profile_response = self.client.get(reverse("client-profile"), **headers) + self.assertEqual(profile_response.status_code, 200) + self.assertEqual(profile_response.json()["profile"]["nodes"][0]["slug"], self.node.slug) + + config_response = self.client.get( + reverse("client-config"), + {"node": self.node.slug, "route": "smart"}, + **headers, + ) + self.assertEqual(config_response.status_code, 200) + config = config_response.json()["config"] + self.assertEqual(config["inbounds"][0]["port"], 10808) + self.assertEqual(config["outbounds"][0]["protocol"], "vless") + self.assertEqual( + config["outbounds"][0]["settings"]["vnext"][0]["users"][0]["id"], + str(subscription.credential_uuid), + ) + self.assertEqual(config["routing"]["rules"][-1]["outboundTag"], "direct") + self.assertEqual(config["routing"]["rules"][-1]["network"], "tcp,udp") + + logout_response = self.client.post(reverse("client-logout"), **headers) + self.assertEqual(logout_response.status_code, 200) + self.assertIsNotNone(ClientSession.objects.get().revoked_at) + self.assertEqual(self.client.get(reverse("client-profile"), **headers).status_code, 401) + + def test_windows_client_enforces_device_limit(self): + subscription = self.create_active_subscription() + subscription.device_limit = 1 + subscription.save(update_fields=["device_limit"]) + Device.objects.create( + subscription=subscription, + device_id="existing-device-0001", + name="已有设备", + platform="Windows", + ) + response = self.client.post( + reverse("client-login"), + data=json.dumps( + { + "login": self.user.username, + "password": "A-strong-user-password-123", + "device_id": "second-device-0002", + "device_name": "第二台电脑", + } + ), + content_type="application/json", + ) + self.assertEqual(response.status_code, 403) + self.assertIn("设备数量", response.json()["error"]) + + def test_client_business_denials_do_not_count_as_password_failures(self): + for number in range(9): + response = self.client.post( + reverse("client-login"), + data=json.dumps( + { + "login": self.user.email, + "password": "A-strong-user-password-123", + "device_id": f"no-subscription-device-{number:04d}", + } + ), + content_type="application/json", + HTTP_X_REAL_IP="198.51.100.10", + ) + self.assertEqual(response.status_code, 403) + self.assertIn("没有可用订阅", response.json()["error"]) + self.assertFalse(LoginAttempt.objects.exists()) + + def test_client_rate_limit_is_scoped_by_network_and_login_identifier(self): + for number in range(7): + response = self.client.post( + reverse("client-login"), + data=json.dumps( + { + "login": self.user.email, + "password": "definitely-the-wrong-password", + "device_id": f"wrong-password-device-{number:04d}", + } + ), + content_type="application/json", + HTTP_X_REAL_IP="198.51.100.20", + ) + self.assertEqual(response.status_code, 401) + + blocked = self.client.post( + reverse("client-login"), + data=json.dumps( + { + "login": self.user.email, + "password": "definitely-the-wrong-password", + "device_id": "blocked-device-0001", + } + ), + content_type="application/json", + HTTP_X_REAL_IP="198.51.100.20", + ) + self.assertEqual(blocked.status_code, 429) + + other_login = self.client.post( + reverse("client-login"), + data=json.dumps( + { + "login": "another-user@example.com", + "password": "definitely-the-wrong-password", + "device_id": "other-login-device-0001", + } + ), + content_type="application/json", + HTTP_X_REAL_IP="198.51.100.20", + ) + self.assertEqual(other_login.status_code, 401) + self.assertEqual(LoginAttempt.objects.count(), 2) + + def test_verified_credentials_clear_previous_failures_without_subscription(self): + for number in range(2): + response = self.client.post( + reverse("client-login"), + data=json.dumps( + { + "login": self.user.email, + "password": "definitely-the-wrong-password", + "device_id": f"retry-device-{number:04d}", + } + ), + content_type="application/json", + HTTP_X_REAL_IP="198.51.100.30", + ) + self.assertEqual(response.status_code, 401) + self.assertEqual(LoginAttempt.objects.get().failures, 2) + + verified = self.client.post( + reverse("client-login"), + data=json.dumps( + { + "login": self.user.email, + "password": "A-strong-user-password-123", + "device_id": "retry-device-verified", + } + ), + content_type="application/json", + HTTP_X_REAL_IP="198.51.100.30", + ) + self.assertEqual(verified.status_code, 403) + self.assertFalse(LoginAttempt.objects.exists()) + + def test_android_client_is_recorded_as_android_device(self): + self.create_active_subscription() + response = self.client.post( + reverse("client-login"), + data=json.dumps( + { + "login": self.user.email, + "password": "A-strong-user-password-123", + "device_id": "android-device-0001", + "device_name": "测试手机", + "app_version": "1.0.0", + "platform": "android", + } + ), + content_type="application/json", + ) + self.assertEqual(response.status_code, 200) + device = Device.objects.get(device_id="android-device-0001") + self.assertEqual(device.name, "测试手机") + self.assertEqual(device.platform, "Android · 优创⁺纵横家 1.0.0") + + def test_ios_client_is_recorded_as_apple_device(self): + self.create_active_subscription() + response = self.client.post( + reverse("client-login"), + data=json.dumps( + { + "login": self.user.email, + "password": "A-strong-user-password-123", + "device_id": "ios-device-00000001", + "device_name": "测试 iPhone", + "app_version": "1.0.0", + "platform": "ios", + } + ), + content_type="application/json", + ) + self.assertEqual(response.status_code, 200) + device = Device.objects.get(device_id="ios-device-00000001") + self.assertEqual(device.name, "测试 iPhone") + self.assertEqual(device.platform, "iPhone / iPad · 优创⁺纵横家 1.0.0") + + def test_vpn_ai_accepts_minimal_observations_and_learns_across_devices(self): + subscription = self.create_active_subscription() + sessions = [] + for number in (1, 2): + device = Device.objects.create( + subscription=subscription, + device_id=f"learning-device-{number:04d}", + name=f"学习设备 {number}", + ) + session, token = ClientSession.issue(subscription, device) + sessions.append((session, token)) + + for _, token in sessions: + direct_report_id = str(uuid.uuid4()) + for outcome in ("direct_failed", "proxy_succeeded"): + response = self.client.post( + reverse("client-observations"), + data=json.dumps( + { + "observations": [ + { + "report_id": direct_report_id if outcome == "direct_failed" else str(uuid.uuid4()), + "related_report_id": direct_report_id if outcome == "proxy_succeeded" else None, + "evidence_kind": "tls" if outcome == "proxy_succeeded" else "", + "target_type": "domain", + "target": "blocked.example.com", + "port": 443, + "network": "tcp", + "outcome": outcome, + "failure_kind": "timeout" if outcome == "direct_failed" else "other", + "node": self.node.slug, + "client_version": "0.2.6", + } + ] + } + ), + content_type="application/json", + HTTP_AUTHORIZATION=f"Bearer {token}", + ) + self.assertEqual(response.status_code, 200) + + self.node.last_seen_at = timezone.now() + self.node.save(update_fields=["last_seen_at"]) + runtime = VpnAiRuntime.objects.create(service_name="vpn-ai") + run_vpn_ai_cycle(runtime) + rule = LearnedRouteRule.objects.get(target="blocked.example.com") + self.assertEqual(rule.status, LearnedRouteRule.Status.ACTIVE) + self.assertEqual(rule.distinct_devices, 2) + self.assertEqual(rule.failure_reports, 2) + self.assertEqual(rule.proxy_success_reports, 2) + + config_response = self.client.get( + reverse("client-config"), + {"node": self.node.slug, "route": "smart"}, + HTTP_AUTHORIZATION=f"Bearer {sessions[0][1]}", + ) + # Learning candidates must not silently force proxy on older clients. + self.assertNotIn("full:blocked.example.com", json.dumps(config_response.json())) + candidates = self.client.get(reverse("client-routing-rules"), HTTP_AUTHORIZATION=f"Bearer {sessions[0][1]}") + self.assertTrue(any(rule["target"] == "blocked.example.com" for rule in candidates.json()["rules"])) + + def test_preset_openai_and_google_domains_are_immediately_active(self): + subscription = self.create_active_subscription() + device = Device.objects.create( + subscription=subscription, + device_id="preset-rule-device", + name="预置规则设备", + ) + _, token = ClientSession.issue(subscription, device) + + preset = LearnedRouteRule.objects.get(target="openai.com") + self.assertEqual(preset.source, LearnedRouteRule.Source.PRESET) + self.assertEqual(preset.match_mode, LearnedRouteRule.MatchMode.SUFFIX) + self.assertEqual(preset.status, LearnedRouteRule.Status.ACTIVE) + self.assertTrue(preset.manually_locked) + + response = self.client.get( + reverse("client-config"), + {"node": self.node.slug, "route": "smart"}, + HTTP_AUTHORIZATION=f"Bearer {token}", + ) + proxy_rule = next( + rule + for rule in response.json()["config"]["routing"]["rules"] + if rule.get("outboundTag") == "proxy" and "domain:openai.com" in rule.get("domain", []) + ) + self.assertIn("domain:chatgpt.com", proxy_rule["domain"]) + self.assertIn("domain:google.com", proxy_rule["domain"]) + self.assertIn("domain:googleapis.com", proxy_rule["domain"]) + + def test_admin_index_uses_fishbone_workflow(self): + self.client.force_login(self.admin) + response = self.client.get(reverse("admin:index")) + self.assertEqual(response.status_code, 200) + self.assertTemplateUsed(response, "admin/vpn_dashboard.html") + self.assertContains(response, "服务开通鱼骨流程") + self.assertContains(response, "AI 智能代理动作流程") + self.assertContains(response, "持续状态 1") + self.assertContains(response, "持续状态 5") + self.assertContains(response, "直连可用状态") + self.assertContains(response, "只要检测结果不变,状态就保持不变") + self.assertContains(response, "节点运维鱼骨流程") + self.assertContains(response, "安全审计鱼骨闭环") + self.assertContains(response, 'role="tablist"') + self.assertContains(response, 'data-workflow-tab=', count=4) + self.assertContains(response, "OpenAI/Codex") + + def test_vpn_ai_rejects_private_and_company_targets(self): + subscription = self.create_active_subscription() + device = Device.objects.create(subscription=subscription, device_id="private-target-device", name="设备") + _, token = ClientSession.issue(subscription, device) + for target_type, target in (("ip", "127.0.0.1"), ("domain", "vpn.toplc.cn")): + response = self.client.post( + reverse("client-observations"), + data=json.dumps( + { + "observations": [ + { + "report_id": str(uuid.uuid4()), + "target_type": target_type, + "target": target, + "port": 443, + "network": "tcp", + "outcome": "direct_failed", + } + ] + } + ), + content_type="application/json", + HTTP_AUTHORIZATION=f"Bearer {token}", + ) + self.assertEqual(response.status_code, 400) + self.assertEqual(RouteObservation.objects.count(), 0) + + def test_observation_classifies_http_and_socket_access(self): + subscription = self.create_active_subscription() + device = Device.objects.create(subscription=subscription, device_id="access-kind-device", name="识别设备") + _, token = ClientSession.issue(subscription, device) + + for port, expected in ((443, RouteObservation.AccessKind.HTTP), (5222, RouteObservation.AccessKind.SOCKET)): + response = self.client.post( + reverse("client-observations"), + data=json.dumps( + { + "observations": [ + { + "report_id": str(uuid.uuid4()), + "target_type": "domain", + "target": f"failure-{port}.example.com", + "port": port, + "network": "tcp", + "outcome": "direct_failed", + } + ] + } + ), + content_type="application/json", + HTTP_AUTHORIZATION=f"Bearer {token}", + ) + self.assertEqual(response.status_code, 200) + self.assertEqual(RouteObservation.objects.get(target=f"failure-{port}.example.com").access_kind, expected) + + def test_usage_rollup_and_quota_enforcement(self): + subscription = self.create_active_subscription() + UsageRecord.objects.create( + subscription=subscription, + node=self.node, + day=timezone.localdate(), + upload_bytes=4 * 1024**3, + download_bytes=6 * 1024**3, + ) + subscription.refresh_from_db() + self.assertEqual(subscription.used_bytes, 10 * 1024**3) + response = self.client.get(reverse("subscription-config", args=[subscription.subscription_token])) + self.assertEqual(response.status_code, 403) + subscription.refresh_from_db() + self.assertEqual(subscription.status, Subscription.Status.SUSPENDED) + + def test_departed_user_is_cancelled_by_enforcement(self): + subscription = self.create_active_subscription() + self.user.account_status = self.user.AccountStatus.DEPARTED + self.user.save(update_fields=["account_status"]) + call_command("enforce_vpn") + subscription.refresh_from_db() + self.assertEqual(subscription.status, Subscription.Status.CANCELLED) + self.assertEqual(subscription.provisioning_state, Subscription.ProvisioningState.REVOKE_PENDING) + + def registration_data(self): + return { + "username": "newcontact", + "display_name": "新联系人", + "email": "newcontact@example.com", + "phone": "13800000000", + "company_name": "测试公司", + "password1": "A-new-contact-password-123", + "password2": "A-new-contact-password-123", + "accept_terms": "on", + "plan": self.plan.pk, + } + + def test_registration_creates_pending_external_user(self): + response = self.client.post(reverse("register"), self.registration_data()) + self.assertRedirects(response, reverse("portal-dashboard")) + created = get_user_model().objects.get(username="newcontact") + self.assertEqual(created.account_status, created.AccountStatus.PENDING) + self.assertEqual(created.identity_type, created.IdentityType.EXTERNAL) + application = PlanApplication.objects.get(user=created) + self.assertEqual(application.plan, self.plan) + self.assertEqual(application.payment_status, PlanApplication.PaymentStatus.UNPAID) + self.assertEqual(application.status, PlanApplication.Status.PENDING) + self.assertFalse(Subscription.objects.filter(user=created).exists()) + + def test_node_sync_applies_revokes_and_reports_usage_idempotently(self): + subscription = Subscription.objects.create(user=self.user, plan=self.plan) + subscription.activate() + headers = { + "HTTP_X_NODE_SLUG": self.node.slug, + "HTTP_AUTHORIZATION": "Bearer node-test-token-that-is-long-enough-123", + "HTTP_X_AGENT_VERSION": "test-agent", + } + + desired = self.client.get(reverse("node-sync"), **headers) + self.assertEqual(desired.status_code, 200) + self.assertEqual(desired.json()["clients"][0]["subscription_id"], subscription.pk) + + report_id = str(uuid.uuid4()) + report = { + "report_id": report_id, + "success": True, + "applied_subscription_ids": [subscription.pk], + "usage": [{"subscription_id": subscription.pk, "upload_bytes": 1024, "download_bytes": 2048}], + } + applied = self.client.post( + reverse("node-sync"), + data=json.dumps(report), + content_type="application/json", + **headers, + ) + self.assertEqual(applied.status_code, 200) + subscription.refresh_from_db() + self.assertEqual(subscription.provisioning_state, Subscription.ProvisioningState.ACTIVE) + self.assertEqual(subscription.used_bytes, 3072) + sample = NodeTrafficSample.objects.get() + self.assertEqual(sample.upload_bytes, 1024) + self.assertEqual(sample.download_bytes, 2048) + self.assertEqual(sample.interval_seconds, 60) + self.assertEqual(sample.upload_bytes_per_second, 1024 // 60) + self.assertEqual(sample.download_bytes_per_second, 2048 // 60) + self.assertEqual(sample.active_subscriptions, 1) + + duplicate = self.client.post( + reverse("node-sync"), + data=json.dumps(report), + content_type="application/json", + **headers, + ) + self.assertEqual(duplicate.json()["status"], "already_processed") + subscription.refresh_from_db() + self.assertEqual(subscription.used_bytes, 3072) + self.assertEqual(NodeTrafficSample.objects.count(), 1) + hourly = HourlyUsageRecord.objects.get(subscription=subscription) + self.assertEqual(hourly.upload_bytes, 1024) + self.assertEqual(hourly.download_bytes, 2048) + self.assertEqual(hourly.hour.minute, 0) + + subscription.suspend("test revoke") + desired = self.client.get(reverse("node-sync"), **headers) + self.assertEqual(desired.json()["clients"], []) + revoked = self.client.post( + reverse("node-sync"), + data=json.dumps( + { + "report_id": str(uuid.uuid4()), + "success": True, + "applied_subscription_ids": [], + "usage": [], + } + ), + content_type="application/json", + **headers, + ) + self.assertEqual(revoked.status_code, 200) + subscription.refresh_from_db() + self.assertEqual(subscription.provisioning_state, Subscription.ProvisioningState.REVOKED) + self.assertEqual(NodeTrafficSample.objects.count(), 2) + + def test_hourly_failure_rolls_back_daily_report_and_can_retry(self): + subscription = Subscription.objects.create(user=self.user, plan=self.plan) + subscription.activate() + headers = {"HTTP_X_NODE_SLUG": self.node.slug, + "HTTP_AUTHORIZATION": "Bearer node-test-token-that-is-long-enough-123"} + report = {"report_id": str(uuid.uuid4()), "success": True, + "applied_subscription_ids": [subscription.pk], + "usage": [{"subscription_id": subscription.pk, "upload_bytes": 10, "download_bytes": 20}]} + with patch.object(HourlyUsageRecord, "save", side_effect=RuntimeError("test write failure")): + with self.assertRaises(RuntimeError): + self.client.post(reverse("node-sync"), data=json.dumps(report), content_type="application/json", **headers) + self.assertFalse(UsageRecord.objects.filter(subscription=subscription).exists()) + self.assertFalse(NodeReport.objects.filter(report_id=report["report_id"]).exists()) + subscription.refresh_from_db() + self.assertEqual(subscription.used_bytes, 0) + response = self.client.post(reverse("node-sync"), data=json.dumps(report), content_type="application/json", **headers) + self.assertEqual(response.status_code, 200) + subscription.refresh_from_db() + self.assertEqual(subscription.used_bytes, 30) + self.assertEqual(HourlyUsageRecord.objects.get(subscription=subscription).download_bytes, 20) + + def test_admin_node_traffic_dashboard_and_data(self): + self.node.last_seen_at = timezone.now() + self.node.total_upload_bytes = 4096 + self.node.total_download_bytes = 8192 + self.node.save(update_fields=["last_seen_at", "total_upload_bytes", "total_download_bytes"]) + report = NodeReport.objects.create(node=self.node, report_id=uuid.uuid4()) + NodeTrafficSample.objects.create( + node=self.node, + report=report, + interval_seconds=60, + upload_bytes=6000, + download_bytes=12000, + upload_bytes_per_second=100, + download_bytes_per_second=200, + active_subscriptions=3, + ) + + anonymous = self.client.get(reverse("admin-node-traffic")) + self.assertEqual(anonymous.status_code, 302) + self.client.force_login(self.admin) + dashboard = self.client.get(reverse("admin-node-traffic")) + self.assertEqual(dashboard.status_code, 200) + self.assertTemplateUsed(dashboard, "admin/node_traffic.html") + self.assertContains(dashboard, "节点实时流量监控") + + data = self.client.get(reverse("admin-node-traffic-data"), {"minutes": 15}) + self.assertEqual(data.status_code, 200) + self.assertEqual(data["Cache-Control"], "no-store") + payload = data.json() + self.assertEqual(payload["range_minutes"], 15) + self.assertEqual(payload["nodes"][0]["slug"], self.node.slug) + self.assertTrue(payload["nodes"][0]["online"]) + self.assertEqual(payload["nodes"][0]["current_download_bytes_per_second"], 200) + self.assertEqual(payload["nodes"][0]["active_subscriptions"], 3) + self.assertNotIn("server", payload["nodes"][0]) + + def test_node_sync_rejects_bad_token(self): + response = self.client.get( + reverse("node-sync"), + HTTP_X_NODE_SLUG=self.node.slug, + HTTP_AUTHORIZATION="Bearer wrong-token", + ) + self.assertEqual(response.status_code, 401) + + def test_configure_node_creates_complete_node(self): + with patch.dict("os.environ", {"VPN_NODE_TOKEN": "management-command-node-token-123456"}): + call_command( + "configure_node", + slug="command-node", + name="命令节点", + region="测试地区", + server="198.51.100.20", + port=443, + sni="vpn.toplc.cn", + public_key="test-public-key", + short_id="0123456789abcdef", + ) + node = Node.objects.get(slug="command-node") + self.assertEqual(node.port, 443) + self.assertTrue(node.check_agent_token("management-command-node-token-123456")) diff --git a/backend/control/tests/test_portal_brand.py b/backend/control/tests/test_portal_brand.py new file mode 100644 index 0000000..c8d4552 --- /dev/null +++ b/backend/control/tests/test_portal_brand.py @@ -0,0 +1,91 @@ +from datetime import timedelta + +from django.contrib.staticfiles import finders +from django.test import TestCase, override_settings +from django.urls import reverse +from django.utils import timezone + +from accounts.models import User +from control.models import Plan, PlanApplication, Subscription + + +@override_settings(SECURE_SSL_REDIRECT=False, WECOM_ENABLED=False, + PUBLIC_BASE_URL="https://preview.example.invalid", + STORAGES={"default": {"BACKEND": "django.core.files.storage.FileSystemStorage"}, + "staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"}}) +class PortalBrandTests(TestCase): + def setUp(self): + self.user = User.objects.create_user(username="portal-preview", email="preview@example.invalid", + account_status="active", identity_type="employee") + self.plan = Plan.objects.create(name="服务套餐", slug="portal-brand", traffic_limit_gb=1024, + price_cny=8, billing_months=1, online_payment_required=True) + self.client.force_login(self.user) + + def test_empty_dashboard_brand_and_account_status(self): + response = self.client.get(reverse("portal-dashboard")) + self.assertIn("no-store", response.headers["Cache-Control"]) + for text in ("brand/zonghengjia.png", "brand/ucvl.png", "css/portal-brand.css", + "账户状态", "还没有可用订阅", "内部员工免费", "开通流程", "套餐申请记录"): + self.assertContains(response, text) + self.assertNotContains(response, "brand-mark\">T") + self.assertNotContains(response, "已安全连接") + self.assertNotContains(response, reverse("admin:index")) + self.assertContains(response, reverse("wecom-account")) + self.assertContains(response, 'name="csrfmiddlewaretoken"') + + def test_active_subscription_keeps_real_usage_and_copy_address(self): + sub = Subscription.objects.create(user=self.user, plan=self.plan, status="active", + provisioning_state="active", upload_bytes=1024, download_bytes=2048) + response = self.client.get(reverse("portal-dashboard")) + self.assertContains(response, "3 KB") + self.assertContains(response, sub.subscription_url) + self.assertContains(response, "实际连接状态请在客户端查看") + self.assertContains(response, 'aria-live="polite"') + sub.refresh_from_db() + self.assertEqual(sub.used_bytes, 3072) + + def test_expired_subscription_does_not_show_copyable_credentials(self): + Subscription.objects.create(user=self.user, plan=self.plan, status="active", + expires_at=timezone.now() - timedelta(days=1)) + response = self.client.get(reverse("portal-dashboard")) + self.assertContains(response, "已到期") + self.assertNotContains(response, 'id="subscription-url"') + + def test_external_catalog_keeps_payment_warning_and_no_employee_plan(self): + self.user.identity_type = "external" + self.user.save(update_fields=["identity_type"]) + Plan.objects.create(name="不可对外的员工套餐", slug="employees-private", employee_benefit=True) + response = self.client.get(reverse("portal-dashboard")) + self.assertContains(response, "8.00元/月") + self.assertContains(response, "暂未开放付款") + self.assertNotContains(response, "不可对外的员工套餐") + self.assertFalse(Subscription.objects.exists()) + + def test_only_staff_sees_management_link(self): + self.user.is_staff = True + self.user.save(update_fields=["is_staff"]) + self.assertContains(self.client.get(reverse("portal-dashboard")), reverse("admin:index")) + + def test_history_and_escaping_are_preserved(self): + self.user.display_name = '' + self.user.save(update_fields=["display_name"]) + PlanApplication.objects.create(user=self.user, plan=self.plan, status="pending", payment_status="not_required") + response = self.client.get(reverse("portal-dashboard")) + self.assertContains(response, "<script>") + self.assertNotContains(response, '') + self.assertContains(response, "待处理") + self.assertContains(response, "无需付款") + + def test_auth_and_account_pages_share_local_brand(self): + for name in ("apply-plan", "wecom-account", "password_change"): + self.assertContains(self.client.get(reverse(name)), "brand/zonghengjia.png") + self.client.logout() + for name in ("login", "register"): + response = self.client.get(reverse(name)) + self.assertContains(response, "brand/zonghengjia.png") + self.assertNotContains(response, "使用 TopLC 网络服务账号") + self.assertEqual(self.client.get(reverse("portal-dashboard")).status_code, 302) + + def test_static_assets_exist(self): + for asset in ("brand/zonghengjia.png", "brand/ucvl.png", "css/portal-brand.css", "js/portal.js"): + self.assertIsNotNone(finders.find(asset), asset) diff --git a/backend/control/tests/test_private_auxiliary.py b/backend/control/tests/test_private_auxiliary.py new file mode 100644 index 0000000..eb49512 --- /dev/null +++ b/backend/control/tests/test_private_auxiliary.py @@ -0,0 +1,228 @@ +import hashlib +from datetime import timedelta +from django.contrib.auth import get_user_model +from django.test import TestCase, override_settings +from django.utils import timezone +from control.models import ClientSession, Device, Node, Plan, Subscription +from control.private_auxiliary import SLUG, device_credential, credential_username + +AGENT = "synthetic-board-key-for-local-tests-only-0123456789" +PIN = "a" * 64 + + +@override_settings(VPN_PRIVATE_AUXILIARY_ENABLED=True, VPN_PRIVATE_AUXILIARY_TLS_LEAF_SHA256=PIN, + VPN_PRIVATE_AUXILIARY_AGENT_TOKEN_SHA256=hashlib.sha256(AGENT.encode()).hexdigest()) +class PrivateAuxiliaryTests(TestCase): + def setUp(self): + self.user = get_user_model().objects.create_user(username="private-fixture", identity_type="employee", account_status="active") + plan = Plan.objects.create(name="private-fixture", slug="private-fixture") + self.sub = Subscription.objects.create(user=self.user, plan=plan, status="active", provisioning_state="active") + self.device = Device.objects.create(subscription=self.sub, device_id="private-fixture-device") + self.session, self.token = ClientSession.issue(self.sub, self.device) + self.headers = {"HTTP_AUTHORIZATION": f"Bearer {self.token}"} + + def config(self, **params): + return self.client.get("/api/v1/client/private-auxiliary/config/", {"node": SLUG, "route": "smart", **params}, secure=True, **self.headers) + + def grants(self): + response = self.client.get("/api/v1/client/profile/", secure=True, **self.headers) + return response.json()["profile"]["private_auxiliary_nodes"] + + def verify(self, credential=None, **fields): + return self.client.post("/api/v1/private-auxiliary/verify/", { + "node": SLUG, "tls_leaf_sha256": PIN, "username": credential_username(self.session), + "credential": device_credential(self.session) if credential is None else credential, **fields}, + content_type="application/json", secure=True, HTTP_AUTHORIZATION=f"Bearer {AGENT}") + + def test_disabled_by_default(self): + with override_settings(VPN_PRIVATE_AUXILIARY_ENABLED=False): + self.assertEqual(self.grants(), []) + self.assertEqual(self.config().status_code, 404) + self.assertEqual(self.verify().status_code, 401) + + def test_registration_required(self): + for value in ("", "invalid", "b" * 63): + with self.subTest(value=value), override_settings(VPN_PRIVATE_AUXILIARY_TLS_LEAF_SHA256=value): + self.assertEqual(self.grants(), []) + self.assertEqual(self.config().status_code, 404) + + def test_separate_candidate_not_public_node(self): + grants = self.grants() + self.assertEqual(len(grants), 1) + self.assertEqual(grants[0]["probe_ipv4"], "192.168.50.111") + self.assertEqual(grants[0]["status"], "candidate") + self.assertFalse(Node.objects.filter(slug=SLUG).exists()) + self.assertEqual(self.client.get("/api/v1/client/config/", {"node": SLUG}, secure=True, **self.headers).status_code, 404) + self.assertEqual(self.client.get("/api/v1/client/profile/", secure=True, **self.headers).json()["profile"]["nodes"], []) + + def test_device_configuration_is_tls_not_reused_public_uuid(self): + response = self.config() + self.assertEqual(response.status_code, 200) + self.assertEqual(response["Cache-Control"], "no-store") + body = response.json() + self.assertEqual(body["connection_scope"], "private_auxiliary") + self.assertEqual(body["config_contract"], 3) + proxy = body["config"]["outbounds"][0] + self.assertEqual(proxy["protocol"], "socks") + self.assertEqual(proxy["streamSettings"]["tlsSettings"]["pinnedPeerCertSha256"], PIN) + self.assertNotIn(str(self.sub.credential_uuid), response.content.decode()) + self.assertNotIn(self.token, response.content.decode()) + self.assertNotIn(AGENT, response.content.decode()) + self.assertLess(len(proxy["settings"]["servers"][0]["users"][0]["pass"]), 255) + + def test_renewal_does_not_rotate_stream_credential(self): + self.assertEqual(self.config().json()["config"], self.config().json()["config"]) + + @override_settings(VPN_PRIVATE_AUXILIARY_ADDRESS="192.168.50.170") + def test_registered_phone_keeps_device_authorization(self): + grant = self.grants()[0] + self.assertEqual(grant["slug"], SLUG) + self.assertEqual(grant["probe_ipv4"], "192.168.50.170") + self.assertEqual(grant["name"], "济南(博翠明湖)") + body = self.config().json() + self.assertEqual(body["node"]["name"], grant["name"]) + proxy = body["config"]["outbounds"][0] + self.assertEqual(proxy["settings"]["servers"][0]["address"], "192.168.50.170") + self.assertEqual(proxy["settings"]["servers"][0]["users"][0]["pass"], device_credential(self.session)) + self.assertEqual(proxy["streamSettings"]["tlsSettings"]["pinnedPeerCertSha256"], PIN) + self.assertTrue(self.verify().json()["allow"]) + + @override_settings(VPN_PRIVATE_AUXILIARY_ADDRESS="192.168.50.170", + VPN_PRIVATE_AUXILIARY_CONNECT_ADDRESS="100.64.0.4") + def test_phone_tailnet_front_door_keeps_pin_and_device_authorization(self): + grant = self.grants()[0] + self.assertEqual(grant["probe_ipv4"], "100.64.0.4") + self.assertEqual(grant["name"], "济南(博翠明湖)") + proxy = self.config().json()["config"]["outbounds"][0] + self.assertEqual(proxy["settings"]["servers"][0]["address"], "100.64.0.4") + self.assertEqual(proxy["settings"]["servers"][0]["port"], 18081) + self.assertEqual(proxy["streamSettings"]["tlsSettings"]["pinnedPeerCertSha256"], PIN) + self.assertEqual(proxy["settings"]["servers"][0]["users"][0]["pass"], device_credential(self.session)) + self.assertTrue(self.verify().json()["allow"]) + self.assertEqual(len(self.grants()), 1) + self.assertEqual(grant["connection_endpoints"], [ + {"address": "100.64.0.4", "probe_ipv4": "100.64.0.4", "port": 18081}, + {"address": "vpn.toplc.cn", "probe_ipv4": "192.0.2.1", "port": 11080}]) + public = self.config(endpoint="vpn.toplc.cn") + self.assertEqual(public.status_code, 200) + public_proxy = public.json()["config"]["outbounds"][0] + self.assertEqual(public_proxy["settings"]["servers"][0]["address"], "vpn.toplc.cn") + self.assertEqual(public_proxy["settings"]["servers"][0]["port"], 11080) + self.assertEqual(public_proxy["settings"]["servers"][0]["users"], proxy["settings"]["servers"][0]["users"]) + self.assertEqual(public_proxy["streamSettings"], proxy["streamSettings"]) + for unknown in ("other.invalid", "192.0.2.1", "100.84.199.105", "192.168.8.167"): + self.assertEqual(self.config(endpoint=unknown).status_code, 400) + + def test_front_door_not_arbitrary_or_mismatched_registration(self): + for registered, endpoint in (("192.168.50.111", "100.64.0.4"), + ("192.168.50.170", "192.168.8.167"), + ("192.168.50.170", "8.8.8.8"), + ("192.168.50.170", None)): + with self.subTest(registered=registered, endpoint=endpoint), override_settings( + VPN_PRIVATE_AUXILIARY_ADDRESS=registered, VPN_PRIVATE_AUXILIARY_CONNECT_ADDRESS=endpoint): + self.assertEqual(self.grants(), []) + self.assertEqual(self.config().status_code, 404) + self.assertEqual(self.verify().status_code, 401) + + def test_unregistered_address_never_advertised(self): + for address in ("", "0.0.0.0", "192.168.8.167", "100.64.0.4", "8.8.8.8"): + with self.subTest(address=address), override_settings(VPN_PRIVATE_AUXILIARY_ADDRESS=address): + self.assertEqual(self.grants(), []) + self.assertEqual(self.config().status_code, 404) + self.assertEqual(self.verify().status_code, 401) + + def test_only_registered_node_and_supported_modes(self): + for slug in ("auto", "vpn001", "other", "192.168.50.111"): + self.assertEqual(self.config(node=slug).status_code, 404) + self.assertEqual(self.config(route="direct").status_code, 400) + self.assertEqual(self.config(route="global").status_code, 200) + + def test_external_account_cannot_use_auxiliary(self): + self.user.identity_type = "external"; self.user.save() + self.assertEqual(self.grants(), []) + self.assertEqual(self.config().status_code, 404) + self.assertEqual(self.verify().status_code, 403) + + def test_inactive_departed_or_suspended_account_denied(self): + for state in ("pending", "suspended", "departed"): + self.user.account_status = state; self.user.save() + self.assertEqual(self.config().status_code, 403) + self.assertEqual(self.verify().status_code, 403) + + def test_paid_quota_not_bypassed_before_private_metering(self): + self.sub.traffic_limit_bytes = 1024; self.sub.save() + self.assertEqual(self.grants(), []) + self.assertEqual(self.config().status_code, 404) + self.assertEqual(self.verify().status_code, 403) + + def test_dedicated_or_custom_access_not_broadened(self): + for mode in ("dedicated", "custom"): + self.sub.route_mode = mode; self.sub.save() + self.assertEqual(self.grants(), []) + self.assertEqual(self.config().status_code, 404) + self.assertEqual(self.verify().status_code, 403) + + def test_revoked_device_denied(self): + self.device.active = False; self.device.save() + self.assertEqual(self.config().status_code, 403) + self.assertEqual(self.verify().status_code, 403) + + def test_logout_rejects_existing_proxy_credential(self): + self.assertTrue(self.verify().json()["allow"]) + self.session.revoked_at = timezone.now(); self.session.save() + self.assertEqual(self.config().status_code, 401) + self.assertEqual(self.verify().status_code, 403) + + def test_expired_session_denied(self): + self.session.expires_at = timezone.now() - timedelta(seconds=1); self.session.save() + self.assertEqual(self.config().status_code, 401) + self.assertEqual(self.verify().status_code, 403) + + def test_valid_board_lease_is_short_and_no_identity_leak(self): + reply = self.verify() + self.assertEqual(reply.status_code, 200) + self.assertEqual(reply.json(), {"allow": True, "lease_seconds": 30}) + self.assertEqual(reply["Cache-Control"], "no-store") + + def test_wrong_password_pin_site_or_username_denied(self): + for fields in ({"credential": "1." + "0" * 64}, {"tls_leaf_sha256": "b" * 64}, + {"node": "other"}, {"username": "zero3-test"}): + self.assertEqual(self.verify(**fields).status_code, 403) + + def test_management_bearer_not_board_credential(self): + self.assertEqual(self.verify(credential=self.token).status_code, 403) + + def test_different_device_session_has_different_credential(self): + device = Device.objects.create(subscription=self.sub, device_id="second-private-fixture") + session, _ = ClientSession.issue(self.sub, device) + self.assertNotEqual(device_credential(session), device_credential(self.session)) + self.assertEqual(self.verify(credential=device_credential(session)).status_code, 403) + + def test_board_endpoint_requires_its_own_secret(self): + response = self.client.post("/api/v1/private-auxiliary/verify/", {}, content_type="application/json", secure=True, **self.headers) + self.assertEqual(response.status_code, 401) + + def test_single_device_validation_does_not_advertise_or_issue_config(self): + with override_settings(VPN_PRIVATE_AUXILIARY_ENABLED=False, VPN_PRIVATE_AUXILIARY_VALIDATION_DEVICE_ID=self.device.pk): + self.assertEqual(self.grants(), []) + self.assertEqual(self.config().status_code, 404) + self.assertTrue(self.verify().json()["allow"]) + other = Device.objects.create(subscription=self.sub, device_id="not-acceptance-device") + session, _ = ClientSession.issue(self.sub, other) + self.assertEqual(self.verify(credential=device_credential(session), username=credential_username(session)).status_code, 403) + + def test_validation_still_checks_employee_and_revocation(self): + with override_settings(VPN_PRIVATE_AUXILIARY_ENABLED=False, VPN_PRIVATE_AUXILIARY_VALIDATION_DEVICE_ID=self.device.pk): + self.session.revoked_at = timezone.now(); self.session.save() + self.assertEqual(self.verify().status_code, 403) + + def test_malformed_body_fails_closed(self): + for body in ('[]', 'null', '"string"', '{bad', '{}'): + self.assertEqual(self.client.post("/api/v1/private-auxiliary/verify/", body, + content_type="application/json", secure=True, HTTP_AUTHORIZATION=f"Bearer {AGENT}").status_code, 403) + self.assertEqual(self.client.post("/api/v1/private-auxiliary/verify/", 'x' * 2049, + content_type="application/json", secure=True, HTTP_AUTHORIZATION=f"Bearer {AGENT}").status_code, 400) + + def test_node_agent_key_rotation_revokes_old_agent(self): + with override_settings(VPN_PRIVATE_AUXILIARY_AGENT_TOKEN_SHA256="b" * 64): + self.assertEqual(self.verify().status_code, 401) diff --git a/backend/control/tests/test_tailscale_endpoint.py b/backend/control/tests/test_tailscale_endpoint.py new file mode 100644 index 0000000..6b84475 --- /dev/null +++ b/backend/control/tests/test_tailscale_endpoint.py @@ -0,0 +1,222 @@ +import json +from datetime import timedelta + +from django.contrib.auth import get_user_model +from django.test import TestCase, override_settings +from django.utils import timezone + +from control.models import ClientSession, Device, Node, NodeTrafficSample, Plan, Subscription +from control.tailscale_endpoint import client_tailscale_endpoint + + +ENDPOINTS = { + "aliyun-tokyo-002": {"address": "100.64.0.2", "port": 10803}, + "aliyun-siliconvalley-003": {"address": "100.64.0.3", "port": 11083}, +} + + +@override_settings(SECURE_SSL_REDIRECT=False, VPN_TAILSCALE_ENDPOINT_ENABLED=True, + VPN_TAILSCALE_ENDPOINTS_JSON=json.dumps(ENDPOINTS)) +class TailscaleEndpointTests(TestCase): + def setUp(self): + self.user = get_user_model().objects.create_user( + username="tailscale-employee", identity_type="employee", account_status="active") + self.plan = Plan.objects.create(name="测试", slug="tailscale-test") + 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") + self.session, self.token = ClientSession.issue(self.sub, self.device) + self.nodes = [] + for index, slug in enumerate(ENDPOINTS): + node = Node.objects.create(name=f"VPN00{index + 2}", slug=slug, region="测试", + server=f"00{index + 2}.vpn.toplc.cn", port=11082 + index, + protocol="vless_reality", status="online", active=True, subscription_enabled=True, + last_seen_at=timezone.now(), sni="example.com", reality_public_key="fixture-public-key", + reality_short_id="1234") + NodeTrafficSample.objects.create(node=node, download_bytes_per_second=1000 - index) + self.nodes.append(node) + + def request_config(self, node=None, **query): + return self.client.get("/api/v1/client/config/", {"node": node or self.nodes[0].slug, **query}, + HTTP_AUTHORIZATION=f"Bearer {self.token}") + + def assert_public_unchanged(self): + with override_settings(VPN_TAILSCALE_ENDPOINT_ENABLED=False): + baseline = self.request_config() + response = self.request_config() + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json(), baseline.json()) + self.assertEqual(response["Cache-Control"], "no-store") + + def test_employee_gets_only_same_node_endpoint_without_changing_public_config(self): + for node in self.nodes: + with self.subTest(node=node.slug): + with override_settings(VPN_TAILSCALE_ENDPOINT_ENABLED=False): + baseline = self.request_config(node.slug).json() + response = self.request_config(node.slug) + payload = response.json() + self.assertEqual(payload.pop("tailscale_endpoint"), + {"contract": 1, "node_slug": node.slug, **ENDPOINTS[node.slug]}) + self.assertEqual(payload, baseline) + self.assertEqual(payload["config_contract"], 2) + self.assertEqual(response["Cache-Control"], "no-store") + upstream = payload["config"]["outbounds"][0]["settings"]["vnext"][0] + self.assertEqual((upstream["address"], upstream["port"]), (node.server, node.port)) + self.assertNotEqual(ENDPOINTS[self.nodes[0].slug]["port"], self.nodes[0].port) + + def test_switch_requires_actual_boolean_true(self): + for disabled in (False, None, 0, 1, "true", "false"): + with self.subTest(disabled=disabled), override_settings(VPN_TAILSCALE_ENDPOINT_ENABLED=disabled): + self.assert_public_unchanged() + + def test_missing_or_invalid_json_keeps_public_response(self): + for raw in ("", "{}", "{bad", "null", "[]", "42", json.dumps("object"), None, + {}, " " * 16385, "[" * 1200 + "]" * 1200, + '{"x":{"address":"100.65.1.1","port":443},"x":{"address":"100.65.1.2","port":443}}'): + with self.subTest(raw_type=type(raw).__name__), override_settings(VPN_TAILSCALE_ENDPOINTS_JSON=raw): + self.assert_public_unchanged() + + def test_invalid_address_and_port_fail_closed(self): + invalid_addresses = ("8.8.8.8", "192.168.50.111", "127.0.0.1", "::1", "fd7a:115c:a1e0::1", + "100.63.255.255", "100.128.0.1", "100.64.0.0", "100.127.255.255", "100.100.100.100", + "100.099.142.38", " 100.64.0.2", "100.64.0.2/32", "host.example.com", 123, None) + invalid_ports = (0, -1, 65536, "10803", True, False, 10803.0, None) + for field, values in (("address", invalid_addresses), ("port", invalid_ports)): + for value in values: + entry = {**ENDPOINTS[self.nodes[0].slug], field: value} + with self.subTest(field=field, value=value), override_settings( + VPN_TAILSCALE_ENDPOINTS_JSON=json.dumps({self.nodes[0].slug: entry})): + self.assert_public_unchanged() + + def test_invalid_or_ambiguous_allowlist_is_rejected_as_a_whole(self): + malformed = ( + {**ENDPOINTS, "bad slug": {"address": "100.65.1.1", "port": 443}}, + {**ENDPOINTS, "extra": {"address": "192.168.1.1", "port": 443}}, + {self.nodes[0].slug: {**ENDPOINTS[self.nodes[0].slug], "credential": "forbidden-fixture"}}, + {self.nodes[0].slug: {"address": "100.64.0.2"}}, + {self.nodes[0].slug: []}, + {f"n{i}": {"address": "100.65.1.1", "port": 443} for i in range(65)}, + ) + for entries in malformed: + with self.subTest(entries=len(entries)), override_settings(VPN_TAILSCALE_ENDPOINTS_JSON=json.dumps(entries)): + self.assert_public_unchanged() + duplicate_port = '{"aliyun-tokyo-002":{"address":"100.64.0.2","port":10803,"port":443}}' + with override_settings(VPN_TAILSCALE_ENDPOINTS_JSON=duplicate_port): + self.assert_public_unchanged() + + def test_nonemployee_receives_only_public_config(self): + self.user.identity_type = "external" + self.user.save(update_fields=["identity_type"]) + self.assert_public_unchanged() + + def test_missing_authentication_never_exposes_endpoint(self): + response = self.client.get("/api/v1/client/config/", {"node": self.nodes[0].slug}) + self.assertEqual(response.status_code, 401) + self.assertNotIn("tailscale_endpoint", response.json()) + + def test_revoked_and_expired_session_never_exposes_endpoint(self): + for changes in ({"revoked_at": timezone.now()}, {"expires_at": timezone.now() - timedelta(seconds=1)}): + with self.subTest(changes=list(changes)): + ClientSession.objects.filter(pk=self.session.pk).update(**changes) + response = self.request_config() + self.assertEqual(response.status_code, 401) + self.assertNotIn("tailscale_endpoint", response.json()) + ClientSession.objects.filter(pk=self.session.pk).update( + revoked_at=None, expires_at=timezone.now() + timedelta(days=1)) + + def test_disabled_device_never_exposes_endpoint(self): + self.device.active = False + self.device.save(update_fields=["active"]) + response = self.request_config() + self.assertEqual(response.status_code, 403) + self.assertNotIn("tailscale_endpoint", response.json()) + + def test_unusable_subscription_never_exposes_endpoint(self): + cases = ({"status": "suspended"}, {"provisioning_state": "pending"}, + {"expires_at": timezone.now() - timedelta(seconds=1)}, + {"traffic_limit_bytes": 1, "upload_bytes": 1}) + for changes in cases: + with self.subTest(changes=list(changes)): + Subscription.objects.filter(pk=self.sub.pk).update(**changes) + response = self.request_config() + self.assertEqual(response.status_code, 403) + self.assertNotIn("tailscale_endpoint", response.json()) + Subscription.objects.filter(pk=self.sub.pk).update(status="active", provisioning_state="active", + expires_at=None, traffic_limit_bytes=0, upload_bytes=0, state_reason="") + + def test_disabled_employee_account_never_exposes_endpoint(self): + for changes in ({"is_active": False}, {"account_status": "suspended"}, {"account_status": "departed"}): + with self.subTest(changes=changes): + get_user_model().objects.filter(pk=self.user.pk).update(**changes) + response = self.request_config() + self.assertEqual(response.status_code, 403) + self.assertNotIn("tailscale_endpoint", response.json()) + get_user_model().objects.filter(pk=self.user.pk).update(is_active=True, account_status="active") + + def test_dedicated_subscription_does_not_expand_node_permissions(self): + self.sub.route_mode = Subscription.RouteMode.DEDICATED + self.sub.save(update_fields=["route_mode"]) + self.sub.allowed_nodes.set([self.nodes[1]]) + self.assertEqual(self.request_config(self.nodes[0].slug).status_code, 404) + response = self.request_config(self.nodes[1].slug) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()["tailscale_endpoint"]["node_slug"], self.nodes[1].slug) + self.assertIsNone(client_tailscale_endpoint(self.session, self.nodes[0])) + + def test_unavailable_office_or_nonreality_node_never_exposes_endpoint(self): + for changes in ({"active": False}, {"subscription_enabled": False}, {"status": "offline"}, + {"office_only": True}, {"protocol": "socks5"}): + with self.subTest(changes=changes): + Node.objects.filter(pk=self.nodes[0].pk).update(**changes) + self.assertEqual(self.request_config().status_code, 404) + self.assertIsNone(client_tailscale_endpoint(self.session, self.nodes[0])) + Node.objects.filter(pk=self.nodes[0].pk).update(active=True, subscription_enabled=True, + status="online", office_only=False, protocol="vless_reality") + + def test_helper_rechecks_session_device_and_subscription(self): + self.session.revoked_at = timezone.now() + self.assertIsNone(client_tailscale_endpoint(self.session, self.nodes[0])) + self.session.revoked_at = None + self.session.expires_at = timezone.now() - timedelta(seconds=1) + self.assertIsNone(client_tailscale_endpoint(self.session, self.nodes[0])) + self.session.expires_at = timezone.now() + timedelta(days=1) + self.session.device.active = False + self.assertIsNone(client_tailscale_endpoint(self.session, self.nodes[0])) + self.session.device.active = True + self.session.device.subscription_id = self.sub.pk + 12345 + self.assertIsNone(client_tailscale_endpoint(self.session, self.nodes[0])) + self.session.device.subscription_id = self.sub.pk + self.session.subscription.provisioning_state = "pending" + self.assertIsNone(client_tailscale_endpoint(self.session, self.nodes[0])) + + def test_auto_endpoint_follows_final_choice_and_keeps_sticky_node(self): + first = self.request_config("auto").json() + selected = first["node"]["slug"] + self.assertEqual(first["tailscale_endpoint"], {"contract": 1, "node_slug": selected, **ENDPOINTS[selected]}) + NodeTrafficSample.objects.filter(node__slug=selected).update(download_bytes_per_second=99999999) + second = self.request_config("auto").json() + self.assertEqual(second["node"]["slug"], selected) + self.assertTrue(second["dispatch"]["sticky"]) + self.assertEqual(second["tailscale_endpoint"], first["tailscale_endpoint"]) + excluded = self.request_config("auto", exclude=selected).json() + self.assertNotEqual(excluded["node"]["slug"], selected) + self.assertEqual(excluded["tailscale_endpoint"]["node_slug"], excluded["node"]["slug"]) + + def test_request_parameters_cannot_replace_administrator_mapping(self): + response = self.request_config(address="100.65.1.9", port=1234, tailscale_endpoint="arbitrary") + self.assertEqual(response.json()["tailscale_endpoint"], + {"contract": 1, "node_slug": self.nodes[0].slug, **ENDPOINTS[self.nodes[0].slug]}) + + def test_no_mapping_for_chosen_node_keeps_public_response(self): + with override_settings(VPN_TAILSCALE_ENDPOINTS_JSON=json.dumps( + {self.nodes[1].slug: ENDPOINTS[self.nodes[1].slug]})): + self.assert_public_unchanged() + + def test_route_modes_do_not_change_the_endpoint_or_public_configuration(self): + for route in ("smart", "global", "direct"): + with self.subTest(route=route): + with override_settings(VPN_TAILSCALE_ENDPOINT_ENABLED=False): + baseline = self.request_config(route=route).json() + payload = self.request_config(route=route).json() + self.assertEqual(payload.pop("tailscale_endpoint")["node_slug"], self.nodes[0].slug) + self.assertEqual(payload, baseline) diff --git a/backend/control/tests/test_team_concurrency.py b/backend/control/tests/test_team_concurrency.py new file mode 100644 index 0000000..7922879 --- /dev/null +++ b/backend/control/tests/test_team_concurrency.py @@ -0,0 +1,53 @@ +from concurrent.futures import ThreadPoolExecutor +from threading import Barrier + +from django.core.exceptions import ValidationError +from django.db import close_old_connections, connections +from django.test import TransactionTestCase, skipUnlessDBFeature + +from accounts.models import User +from control.models import TeamMembership +from control.team_services import create_team, invite_member, respond_invitation + + +@skipUnlessDBFeature("has_select_for_update") +class TeamConcurrencyTests(TransactionTestCase): + def setUp(self): + self.owner, self.first, self.second = [User.objects.create_user(username=n, email=f"{n}@example.invalid", account_status="active") + for n in ("owner-lock", "first-lock", "second-lock")] + self.team = create_team(self.owner, "Concurrency fixture") + self.team.setup_member_limit = 2 + self.team.save() + + def parallel(self, *actions): + barrier = Barrier(len(actions)) + def run(action): + close_old_connections() + try: + barrier.wait(timeout=8) + try: + action() + return True + except ValidationError: + return False + finally: + connections.close_all() + with ThreadPoolExecutor(max_workers=len(actions)) as pool: + futures = [pool.submit(run, action) for action in actions] + return [future.result(timeout=25) for future in futures] + + def test_simultaneous_invites_do_not_overbook_last_place(self): + outcomes = self.parallel(lambda: invite_member(self.team.pk, self.owner, self.first.username), + lambda: invite_member(self.team.pk, self.owner, self.second.username)) + self.assertEqual(sum(outcomes), 1) + self.assertEqual(TeamMembership.objects.filter(team=self.team, status="invited").count(), 1) + + def test_simultaneous_legacy_invite_acceptance_cannot_exceed_capacity(self): + # Existing/imported invites may exceed a reduced capacity; acceptance + # still locks and checks the team rather than trusting the old invite. + one = TeamMembership.objects.create(team=self.team, user=self.first, invited_by=self.owner) + two = TeamMembership.objects.create(team=self.team, user=self.second, invited_by=self.owner) + outcomes = self.parallel(lambda: respond_invitation(one.pk, self.first, True), + lambda: respond_invitation(two.pk, self.second, True)) + self.assertEqual(sum(outcomes), 1) + self.assertEqual(TeamMembership.objects.filter(team=self.team, status="active").count(), 1) diff --git a/backend/control/tests/test_teams.py b/backend/control/tests/test_teams.py new file mode 100644 index 0000000..4990f20 --- /dev/null +++ b/backend/control/tests/test_teams.py @@ -0,0 +1,261 @@ +from datetime import timedelta +from io import StringIO + +from django.core.exceptions import PermissionDenied, ValidationError +from django.core.management import call_command +from django.test import Client, TestCase, override_settings +from django.urls import reverse +from django.utils import timezone + +from accounts.models import User +from control.models import Team, TeamMembership, TeamAuditEvent, Plan, PlanCatalogDraft, PlanApplication, Subscription +from control.team_services import create_team, invite_member, respond_invitation, change_member, visible_teams +from control.lifecycle import personal_lifecycle, team_lifecycle + + +@override_settings(SECURE_SSL_REDIRECT=False, WECOM_ENABLED=False, + STORAGES={"default": {"BACKEND": "django.core.files.storage.FileSystemStorage"}, + "staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"}}) +class TeamPermissionTests(TestCase): + def setUp(self): + self.owner, self.manager, self.member, self.outside = [ + User.objects.create_user(username=name, email=f"{name}@example.invalid", display_name=name, account_status="active") + for name in ("owner-fixture", "manager-fixture", "member-fixture", "outside-fixture")] + self.team = create_team(self.owner, "TEAM-PRIVATE-ALPHA") + self.team.setup_member_limit = 5 + self.team.save() + self.manager_link = invite_member(self.team.pk, self.owner, self.manager.username) + respond_invitation(self.manager_link.pk, self.manager, True) + change_member(self.team.pk, self.manager_link.pk, self.owner, "promote") + self.member_link = invite_member(self.team.pk, self.manager, self.member.username) + respond_invitation(self.member_link.pk, self.member, True) + self.url = reverse("team-detail", args=[self.team.pk]) + + def test_create_sets_owner_from_session_not_posted_fields(self): + self.client.force_login(self.outside) + response = self.client.post(reverse("teams"), {"name": "created", "owner": self.owner.pk, "is_staff": True, "identity_type": "employee", "active": True}) + self.assertEqual(response.status_code, 302) + self.assertEqual(Team.objects.get(name="created").owner_id, self.outside.pk) + self.outside.refresh_from_db() + self.assertFalse(self.outside.is_staff) + self.assertEqual(self.outside.identity_type, "external") + + def test_outsider_and_unrelated_staff_cannot_read_or_manage_team(self): + self.outside.is_staff = True + self.outside.save() + self.client.force_login(self.outside) + self.assertEqual(self.client.get(self.url).status_code, 404) + self.assertNotContains(self.client.get(reverse("teams")), self.team.name) + self.assertEqual(self.client.post(self.url, {"username": self.outside.username}).status_code, 404) + with self.assertRaises(PermissionDenied): + change_member(self.team.pk, self.member_link.pk, self.outside, "promote") + + def test_member_cannot_invite_promote_demote_or_remove_other_members(self): + for action in ("promote", "demote", "remove"): + with self.subTest(action=action), self.assertRaises(PermissionDenied): + change_member(self.team.pk, self.manager_link.pk, self.member, action) + with self.assertRaises(PermissionDenied): + invite_member(self.team.pk, self.member, self.outside.username) + + def test_manager_cannot_promote_self_change_owner_or_remove_other_admin(self): + with self.assertRaises(PermissionDenied): + change_member(self.team.pk, self.manager_link.pk, self.manager, "promote") + with self.assertRaises(PermissionDenied): + change_member(self.team.pk, self.manager_link.pk, self.manager, "remove") + change_member(self.team.pk, self.member_link.pk, self.owner, "promote") + with self.assertRaises(PermissionDenied): + change_member(self.team.pk, self.member_link.pk, self.manager, "remove") + self.team.refresh_from_db() + self.assertEqual(self.team.owner_id, self.owner.pk) + + def test_cross_team_member_id_is_rejected(self): + other = create_team(self.outside, "SECOND-PRIVATE") + foreign = invite_member(other.pk, self.outside, self.member.username) + self.client.force_login(self.owner) + response = self.client.post(reverse("team-member-action", args=[self.team.pk, foreign.pk]), {"action": "remove"}) + self.assertEqual(response.status_code, 404) + foreign.refresh_from_db() + self.assertEqual(foreign.status, "invited") + + def test_invited_user_cannot_read_until_personally_accepting(self): + invite = invite_member(self.team.pk, self.owner, self.outside.username) + self.client.force_login(self.outside) + self.assertEqual(self.client.get(self.url).status_code, 404) + self.assertContains(self.client.get(reverse("teams")), "接受邀请") + self.client.post(reverse("team-invitation", args=[invite.pk]), {"action": "accept", "role": "admin"}) + invite.refresh_from_db() + self.assertEqual((invite.status, invite.role), ("active", "member")) + self.assertEqual(self.client.get(self.url).status_code, 200) + + def test_cannot_accept_someone_elses_invitation(self): + invite = invite_member(self.team.pk, self.owner, self.outside.username) + self.client.force_login(self.member) + self.assertEqual(self.client.post(reverse("team-invitation", args=[invite.pk]), {"action": "accept"}).status_code, 404) + invite.refresh_from_db() + self.assertEqual(invite.status, "invited") + + def test_get_requests_and_missing_csrf_never_mutate_roles(self): + action_url = reverse("team-member-action", args=[self.team.pk, self.member_link.pk]) + self.client.force_login(self.owner) + self.assertEqual(self.client.get(action_url, {"action": "promote"}).status_code, 405) + strict = Client(enforce_csrf_checks=True) + strict.force_login(self.owner) + self.assertEqual(strict.post(action_url, {"action": "promote"}).status_code, 403) + self.member_link.refresh_from_db() + self.assertEqual(self.member_link.role, "member") + + def test_stale_manager_immediately_loses_write_permission(self): + change_member(self.team.pk, self.manager_link.pk, self.owner, "demote") + with self.assertRaises(PermissionDenied): + invite_member(self.team.pk, self.manager, self.outside.username) + + def test_removed_member_loses_read_and_invitation_needs_fresh_consent(self): + change_member(self.team.pk, self.member_link.pk, self.manager, "remove") + self.client.force_login(self.member) + self.assertEqual(self.client.get(self.url).status_code, 404) + link = invite_member(self.team.pk, self.owner, self.member.username) + self.assertEqual(link.status, "invited") + self.assertEqual(self.client.get(self.url).status_code, 404) + + def test_team_role_does_not_grant_staff_employee_or_modify_personal_subscription(self): + plan = Plan.objects.create(name="Personal fixture", slug="personal-fixture") + sub = Subscription.objects.create(user=self.member, plan=plan, upload_bytes=123) + before = list(Subscription.objects.values()) + change_member(self.team.pk, self.member_link.pk, self.owner, "promote") + change_member(self.team.pk, self.member_link.pk, self.owner, "remove") + self.assertEqual(list(Subscription.objects.values()), before) + self.member.refresh_from_db() + self.assertFalse(self.member.is_staff) + self.assertFalse(self.member.is_superuser) + self.assertEqual(self.member.identity_type, "external") + + def test_regular_member_gets_no_roster_or_personal_credentials(self): + self.client.force_login(self.member) + response = self.client.get(self.url) + self.assertContains(response, "团队套餐情况") + self.assertNotContains(response, self.manager.username) + self.assertNotContains(response, self.owner.email) + self.assertNotContains(response, "发送站内邀请") + self.assertEqual(list(response.context["members"]), []) + self.assertIn("no-store", response.headers["Cache-Control"]) + + def test_suspended_accounts_cannot_create_accept_read_or_mutate(self): + User.objects.filter(pk=self.manager.pk).update(account_status="suspended") + with self.assertRaises(PermissionDenied): + invite_member(self.team.pk, self.manager, self.outside.username) + with self.assertRaises(PermissionDenied): + create_team(self.manager, "not allowed") + self.client.force_login(self.manager) + self.assertEqual(self.client.get(self.url).status_code, 404) + + def test_pending_invites_count_toward_capacity_and_decline_frees_slot(self): + self.team.setup_member_limit = 4 + self.team.save() + invite = invite_member(self.team.pk, self.owner, self.outside.username) + extra = User.objects.create_user(username="extra", email="extra@example.invalid", account_status="active") + with self.assertRaises(ValidationError): + invite_member(self.team.pk, self.owner, extra.username) + respond_invitation(invite.pk, self.outside, False) + self.assertEqual(invite_member(self.team.pk, self.owner, extra.username).status, "invited") + + def test_self_leave_preserves_account_and_cannot_remove_other_person(self): + with self.assertRaises(PermissionDenied): + change_member(self.team.pk, self.manager_link.pk, self.member, "leave") + change_member(self.team.pk, self.member_link.pk, self.member, "leave") + self.assertFalse(visible_teams(self.member).exists()) + self.member.refresh_from_db() + self.assertTrue(self.member.service_enabled) + + def test_personal_draft_cannot_be_assigned_as_team_package(self): + call_command("prepare_plan_catalog", create=True, stdout=StringIO()) + self.team.plan_draft = PlanCatalogDraft.objects.filter(scope="personal").first() + with self.assertRaises(ValidationError): + self.team.full_clean() + + def test_unprovisioned_team_plan_not_shown_as_active_or_zero_real_usage(self): + call_command("prepare_plan_catalog", create=True, stdout=StringIO()) + self.team.plan_draft = PlanCatalogDraft.objects.filter(scope="team", traffic_limit_gb__gt=0).first() + self.team.save() + self.client.force_login(self.member) + response = self.client.get(self.url) + for text in ("意向套餐", "待开通", "待定价", "共享用量", "尚未接入", "套餐生命周期", 'aria-current="step"'): + self.assertContains(response, text) + self.assertNotContains(response, "已付款") + self.assertNotContains(response, "0 GB") + + def test_privileged_actions_record_minimal_audit_without_credentials(self): + change_member(self.team.pk, self.member_link.pk, self.owner, "promote") + event = TeamAuditEvent.objects.first() + self.assertEqual(event.action, "promote") + self.assertEqual(event.actor_id, self.owner.pk) + self.assertEqual(event.subject_id, self.member.pk) + self.assertFalse(hasattr(event, "password")) + + def test_operation_result_and_real_role_change_without_fake_subscription_progress(self): + self.client.force_login(self.owner) + response = self.client.post(reverse("team-member-action", args=[self.team.pk, self.member_link.pk]), {"action": "promote"}, follow=True) + self.assertContains(response, "已设为团队管理员") + self.assertContains(response, "筹备中") + self.member_link.refresh_from_db() + self.assertEqual(self.member_link.role, "admin") + self.assertFalse(Subscription.objects.exists()) + + def test_failed_operation_does_not_change_state_or_claim_success(self): + self.client.force_login(self.owner) + response = self.client.post(reverse("team-member-action", args=[self.team.pk, self.member_link.pk]), {"action": "purchase-and-promote"}, follow=True) + self.assertContains(response, "未知操作") + self.assertNotContains(response, "已设为团队管理员") + self.member_link.refresh_from_db() + self.assertEqual(self.member_link.role, "member") + + def test_django_admin_member_edit_is_read_only_even_for_superuser(self): + root = User.objects.create_superuser(username="team-root", email="root@example.invalid", password="fixture") + self.client.force_login(root) + self.assertEqual(self.client.post(reverse("admin:control_teammembership_add"), {}).status_code, 403) + response = self.client.post(reverse("admin:control_teammembership_change", args=[self.member_link.pk]), {"role": "admin"}) + self.assertEqual(response.status_code, 403) + + +class LifecycleTests(TestCase): + def setUp(self): + self.user = User.objects.create_user(username="lifecycle", email="lifecycle@example.invalid", account_status="active") + self.plan = Plan.objects.create(name="Fixture", slug="lifecycle", price_cny=8, online_payment_required=True, billing_months=1) + + def test_unpaid_application_does_not_look_active(self): + app = PlanApplication.submit(user=self.user, plan=self.plan) + state = personal_lifecycle(self.user, application=app) + self.assertEqual(state["steps"][1]["state"], "current") + self.assertIn("暂未开放", state["title"]) + + def test_employee_payment_is_skipped_but_review_remains(self): + self.user.identity_type = "employee" + self.user.save() + app = PlanApplication.submit(user=self.user, plan=self.plan) + state = personal_lifecycle(self.user, application=app) + self.assertEqual(state["steps"][1], {"label": "无需付款", "state": "done"}) + self.assertEqual(state["steps"][2]["state"], "current") + + def test_active_expiring_and_expired_are_distinct(self): + self.user.identity_type = "employee" + self.user.save() + sub = Subscription.objects.create(user=self.user, plan=self.plan, status="active", provisioning_state="active", expires_at=timezone.now()+timedelta(days=30)) + self.assertEqual(personal_lifecycle(self.user, sub)["title"], "使用中") + sub.expires_at = timezone.now()+timedelta(days=3) + self.assertIn("即将到期", personal_lifecycle(self.user, sub)["title"]) + sub.expires_at = timezone.now()-timedelta(seconds=1) + self.assertEqual(personal_lifecycle(self.user, sub)["steps"][4]["state"], "current") + + def test_suspended_user_does_not_receive_active_lifecycle(self): + self.user.account_status = "suspended" + self.assertIn("账号已停用", personal_lifecycle(self.user)["title"]) + + def test_cancelled_before_payment_does_not_show_completed_payment_or_usage(self): + sub = Subscription.objects.create(user=self.user, plan=self.plan, status="cancelled") + state = personal_lifecycle(self.user, sub) + self.assertEqual(state["title"], "服务已取消") + self.assertEqual(state["steps"][1]["state"], "future") + self.assertEqual(state["steps"][3]["state"], "future") + + def test_team_with_no_package_is_preparation_not_active(self): + team = Team.objects.create(owner=self.user, name="Preparing") + self.assertIn("筹备中", team_lifecycle(team)["title"]) diff --git a/backend/control/tests/test_usage_concurrency.py b/backend/control/tests/test_usage_concurrency.py new file mode 100644 index 0000000..ffdb190 --- /dev/null +++ b/backend/control/tests/test_usage_concurrency.py @@ -0,0 +1,118 @@ +"""Row-lock regressions for real PostgreSQL; never call production services.""" +import json +import uuid +from concurrent.futures import ThreadPoolExecutor +from threading import Barrier, Event + +from django.contrib.auth import get_user_model +from django.db import close_old_connections, connection, connections, transaction +from django.test import Client, TransactionTestCase, override_settings, skipUnlessDBFeature +from django.urls import reverse +from django.utils import timezone + +from control.models import HourlyUsageRecord, Node, NodeReport, NodeTrafficSample, Plan, Subscription, UsageRecord + + +@override_settings(SECURE_SSL_REDIRECT=False) +@skipUnlessDBFeature("has_select_for_update") +class UsageConcurrencyTests(TransactionTestCase): + def setUp(self): + user = get_user_model().objects.create_user( + username="usage-owner", password="fixture-only", account_status="active" + ) + plan = Plan.objects.create(name="Usage fixture", slug="usage-fixture", audience=Plan.Audience.ALL) + self.subscription = Subscription.objects.create(user=user, plan=plan) + self.subscription.activate() + self.nodes = [] + for index in range(2): + node = Node.objects.create( + name=f"Fixture {index}", slug=f"usage-node-{index}", server="192.0.2.1", port=11080+index, + protocol=Node.Protocol.VLESS_REALITY, status=Node.Status.ONLINE, + active=True, subscription_enabled=True, sni="example.invalid", + reality_public_key="fixture", reality_short_id="0123456789abcdef", + ) + node.set_agent_token("node-concurrency-fixture-not-a-real-token") + node.save(update_fields=["agent_token_digest"]) + self.nodes.append(node) + + @staticmethod + def in_thread(action): + close_old_connections() + try: + return action() + finally: + connections.close_all() + + def run_together(self, *actions): + barrier = Barrier(len(actions)) + def run(action): + barrier.wait(timeout=8) + return action() + with ThreadPoolExecutor(max_workers=len(actions)) as pool: + futures = [pool.submit(self.in_thread, lambda action=action: run(action)) for action in actions] + return [future.result(timeout=25) for future in futures] + + def post(self, node, report_id, upload=10, download=20): + response = Client().post(reverse("node-sync"), data=json.dumps({ + "report_id": str(report_id), "success": True, + "applied_subscription_ids": [self.subscription.pk], + "usage": [{"subscription_id": self.subscription.pk, "upload_bytes": upload, "download_bytes": download}], + }), content_type="application/json", HTTP_X_NODE_SLUG=node.slug, + HTTP_AUTHORIZATION="Bearer node-concurrency-fixture-not-a-real-token") + return response.status_code, response.json()["status"] + + def assert_totals(self, upload, download): + self.subscription.refresh_from_db() + self.assertEqual((self.subscription.upload_bytes, self.subscription.download_bytes), (upload, download)) + self.assertEqual(sum(row.upload_bytes for row in UsageRecord.objects.all()), upload) + self.assertEqual(sum(row.download_bytes for row in UsageRecord.objects.all()), download) + + def test_recompute_does_not_overwrite_a_concurrently_committed_node(self): + # Writer A holds its subscription update open. B reaches the parent row + # while A is still uncommitted. Aggregate-before-lock loses A's delta; + # lock-before-aggregate waits and sees A after commit. No timing sleeps. + first_ready, second_locks_parent = Event(), Event() + def first(): + with transaction.atomic(): + UsageRecord.objects.create(subscription=self.subscription, node=self.nodes[0], + day=timezone.localdate(), upload_bytes=10, download_bytes=20) + first_ready.set() + self.assertTrue(second_locks_parent.wait(10), "Second writer did not reach the parent lock") + def second(): + self.assertTrue(first_ready.wait(10)) + def observe(execute, sql, params, many, context): + upper = sql.upper() + if '"CONTROL_SUBSCRIPTION"' in upper and ( + upper.startswith("UPDATE") or "FOR UPDATE" in upper or "FOR NO KEY UPDATE" in upper + ): + second_locks_parent.set() + return execute(sql, params, many, context) + with connection.execute_wrapper(observe), transaction.atomic(): + UsageRecord.objects.create(subscription=self.subscription, node=self.nodes[1], + day=timezone.localdate(), upload_bytes=30, download_bytes=40) + self.run_together(first, second) + self.assert_totals(40, 60) + + def test_simultaneous_duplicate_report_is_billed_once(self): + report_id = uuid.uuid4() + results = self.run_together(*(lambda: self.post(self.nodes[0], report_id) for _ in range(3))) + self.assertEqual(sorted(results), [(200, "accepted"), (200, "already_processed"), (200, "already_processed")]) + self.assert_totals(10, 20) + self.assertEqual((NodeReport.objects.count(), NodeTrafficSample.objects.count()), (1, 1)) + self.assertEqual(HourlyUsageRecord.objects.get().download_bytes, 20) + + def test_distinct_first_reports_same_node_do_not_lose_or_duplicate_usage(self): + results = self.run_together(*(lambda: self.post(self.nodes[0], uuid.uuid4()) for _ in range(3))) + self.assertEqual(results, [(200, "accepted")] * 3) + self.assert_totals(30, 60) + self.assertEqual((NodeReport.objects.count(), NodeTrafficSample.objects.count()), (3, 3)) + self.assertEqual(HourlyUsageRecord.objects.get().download_bytes, 60) + self.nodes[0].refresh_from_db() + self.assertEqual(self.nodes[0].total_download_bytes, 60) + + def test_different_nodes_accumulate_into_one_subscription(self): + results = self.run_together(*(lambda node=node: self.post(node, uuid.uuid4()) for node in self.nodes)) + self.assertEqual(results, [(200, "accepted")] * 2) + self.assert_totals(20, 40) + self.assertEqual(HourlyUsageRecord.objects.count(), 2) + self.assertEqual(sum(row.download_bytes for row in HourlyUsageRecord.objects.all()), 40) diff --git a/backend/control/tests/test_usage_history.py b/backend/control/tests/test_usage_history.py new file mode 100644 index 0000000..2d2ee44 --- /dev/null +++ b/backend/control/tests/test_usage_history.py @@ -0,0 +1,77 @@ +from datetime import datetime, timedelta, timezone as dt_timezone +from django.contrib.auth import get_user_model +from django.test import TestCase, override_settings +from control.models import ClientSession, Device, HourlyUsageRecord, Node, Plan, Subscription, UsageRecord +from control.usage_history import client_usage_history + + +@override_settings(TIME_ZONE="Asia/Shanghai", SECURE_SSL_REDIRECT=False) +class UsageHistoryTests(TestCase): + def setUp(self): + self.user = get_user_model().objects.create_user(username="history-user", email="history@example.com", account_status="active") + self.plan = Plan.objects.create(name="History", slug="history") + self.sub = Subscription.objects.create(user=self.user, plan=self.plan, status="active", provisioning_state="active") + self.other = Subscription.objects.create(user=get_user_model().objects.create_user(username="other", email="other@example.com"), plan=self.plan) + self.nodes = [Node.objects.create(name=f"N{i}", slug=f"history-{i}", server="example.com", port=11081+i) for i in range(2)] + self.now = datetime(2026, 10, 1, 0, 35, tzinfo=dt_timezone(timedelta(hours=8))) + + def test_exact_range_sizes_and_legacy_contract(self): + legacy, ranges = client_usage_history(self.sub, self.now) + self.assertEqual(len(legacy), 7) + self.assertEqual([len(r["points"]) for r in ranges.values()], [12, 24, 7, 30]) + self.assertEqual(ranges["30d"]["points"][0]["time"], "2026-09-02") + self.assertEqual(ranges["30d"]["points"][-1]["time"], "2026-10-01") + self.assertEqual(ranges["12h"]["points"][0]["time"], "2026-09-30T13:00:00+08:00") + self.assertEqual(ranges["1d"]["points"][-1]["time"], "2026-10-01T00:00:00+08:00") + + def test_hourly_scope_sums_nodes_without_other_subscriptions(self): + hour = self.now.replace(minute=0) + for node in self.nodes: + HourlyUsageRecord.objects.create(subscription=self.sub, node=node, hour=hour, upload_bytes=10, download_bytes=20) + HourlyUsageRecord.objects.create(subscription=self.other, node=self.nodes[0], hour=hour, upload_bytes=999) + point = client_usage_history(self.sub, self.now)[1]["12h"]["points"][-1] + self.assertEqual((point["upload_bytes"], point["download_bytes"]), (20, 40)) + self.sub.refresh_from_db() + self.assertEqual(self.sub.used_bytes, 0, "The hourly chart must not become a second billing ledger") + + def test_no_backfill_from_daily_and_missing_is_not_zero(self): + UsageRecord.objects.create(subscription=self.sub, node=self.nodes[0], day=self.now.date(), upload_bytes=500) + HourlyUsageRecord.objects.create(subscription=self.sub, node=self.nodes[0], hour=self.now.replace(minute=0)) + legacy, ranges = client_usage_history(self.sub, self.now) + self.assertEqual(legacy[-1]["upload_bytes"], 500) + self.assertIsNone(ranges["12h"]["points"][-2]["upload_bytes"]) + self.assertEqual(ranges["12h"]["points"][-1]["upload_bytes"], 0) + + def test_month_scope_and_outside_boundaries(self): + for delta in [0, 29, 30, -1]: + UsageRecord.objects.create(subscription=self.sub, node=self.nodes[0], day=self.now.date()-timedelta(days=delta), upload_bytes=100) + UsageRecord.objects.create(subscription=self.other, node=self.nodes[0], day=self.now.date(), upload_bytes=999) + ranges = client_usage_history(self.sub, self.now)[1] + self.assertEqual(sum(p["upload_bytes"] for p in ranges["30d"]["points"]), 200) + self.assertEqual(sum(p["upload_bytes"] for p in ranges["7d"]["points"]), 100) + + def test_hour_boundaries_exclude_future_and_old_data(self): + hour = self.now.replace(minute=0) + for delta in [0, 11, 12, 23, 24, -1]: + HourlyUsageRecord.objects.create(subscription=self.sub, node=self.nodes[0], hour=hour-timedelta(hours=delta), upload_bytes=10) + ranges = client_usage_history(self.sub, self.now)[1] + self.assertEqual(sum(p["upload_bytes"] or 0 for p in ranges["12h"]["points"]), 20) + self.assertEqual(sum(p["upload_bytes"] or 0 for p in ranges["1d"]["points"]), 40) + + def test_empty_payload_is_bounded_and_two_queries(self): + with self.assertNumQueries(2): + _, ranges = client_usage_history(self.sub, self.now) + self.assertTrue(all(p["upload_bytes"] is None for p in ranges["12h"]["points"])) + self.assertEqual(ranges["12h"]["scope"], "subscription") + + def test_profile_requires_authentication_and_ignores_user_supplied_scope(self): + self.assertEqual(self.client.get("/api/v1/client/profile/").status_code, 401) + _, token = ClientSession.issue(self.sub, Device.objects.create(subscription=self.sub, device_id="history-test")) + response = self.client.get(f"/api/v1/client/profile/?subscription_id={self.other.pk}", HTTP_AUTHORIZATION=f"Bearer {token}") + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()["profile"]["username"], self.user.username) + self.assertIn("usage_history_ranges", response.json()["profile"]) + + def test_utc_input_is_bucketed_in_server_timezone(self): + utc = self.now.astimezone(dt_timezone.utc) + self.assertEqual(client_usage_history(self.sub, self.now), client_usage_history(self.sub, utc)) diff --git a/backend/control/tests/test_usage_lock_order.py b/backend/control/tests/test_usage_lock_order.py new file mode 100644 index 0000000..fa93686 --- /dev/null +++ b/backend/control/tests/test_usage_lock_order.py @@ -0,0 +1,51 @@ +"""Sequential invariants only; SQLite cannot certify concurrent row locking.""" +from unittest.mock import patch + +from django.contrib.auth import get_user_model +from django.db import connection, transaction +from django.db.models.query import QuerySet +from django.test import TestCase + +from control.models import Plan, Subscription, UsageRecord +from control.signals import recompute_subscription_usage +from control.usage_accounting import lock_usage_subscriptions, non_key_lock_options + + +class UsageLockOrderTests(TestCase): + def setUp(self): + self.owner = get_user_model().objects.create_user(username="lock-fixture") + self.plan = Plan.objects.create(name="Fixture", slug="lock-fixture", audience=Plan.Audience.ALL) + self.subscription = Subscription.objects.create(user=self.owner, plan=self.plan) + + def test_parent_lock_is_requested_before_aggregate_and_stale_total_is_repaired(self): + Subscription.objects.filter(pk=self.subscription.pk).update(upload_bytes=999, download_bytes=999) + sequence = [] + original_lock, original_aggregate = QuerySet.select_for_update, QuerySet.aggregate + def locked(queryset, *args, **kwargs): + if queryset.model is Subscription: + self.assertTrue(connection.in_atomic_block) + sequence.append("parent-lock") + return original_lock(queryset, *args, **kwargs) + def aggregated(queryset, *args, **kwargs): + if queryset.model is UsageRecord: + self.assertEqual(sequence, ["parent-lock"]) + self.assertTrue(connection.in_atomic_block) + sequence.append("aggregate") + return original_aggregate(queryset, *args, **kwargs) + with patch.object(QuerySet, "select_for_update", new=locked), patch.object(QuerySet, "aggregate", new=aggregated): + recompute_subscription_usage(self.subscription.pk) + self.assertEqual(sequence, ["parent-lock", "aggregate"]) + self.subscription.refresh_from_db() + self.assertEqual(self.subscription.used_bytes, 0) + + def test_multi_subscription_lock_order_is_sorted_and_deduplicated(self): + another = Subscription.objects.create(user=self.owner, plan=self.plan) + with transaction.atomic(): + locked = lock_usage_subscriptions([another.pk, self.subscription.pk, another.pk]) + self.assertEqual([item.pk for item in locked], sorted([self.subscription.pk, another.pk])) + + def test_no_key_lock_only_requested_on_supported_databases(self): + with patch.object(connection.features, "has_select_for_no_key_update", True): + self.assertEqual(non_key_lock_options(), {"no_key": True}) + with patch.object(connection.features, "has_select_for_no_key_update", False): + self.assertEqual(non_key_lock_options(), {}) diff --git a/backend/control/urls.py b/backend/control/urls.py new file mode 100644 index 0000000..ec912c0 --- /dev/null +++ b/backend/control/urls.py @@ -0,0 +1,28 @@ +from django.urls import path + +from . import views, team_views, private_auxiliary, learning + + +urlpatterns = [ + path("", views.dashboard, name="portal-dashboard"), + path("teams/", team_views.teams, name="teams"), + path("teams//", team_views.detail, name="team-detail"), + path("teams/invitations//", team_views.invitation, name="team-invitation"), + path("teams//members//", team_views.member_action, name="team-member-action"), + path("register/", views.register, name="register"), + path("apply/", views.apply_plan, name="apply-plan"), + path("sub//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/private-auxiliary/config/", private_auxiliary.client_config, name="private-auxiliary-config"), + path("api/v1/private-auxiliary/verify/", private_auxiliary.verify_device, name="private-auxiliary-verify"), + path("api/v1/client/observations/", views.client_observations, name="client-observations"), + path("api/v1/client/routing-rules/", learning.client_rules, name="client-routing-rules"), + 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"), +] diff --git a/backend/control/usage_accounting.py b/backend/control/usage_accounting.py new file mode 100644 index 0000000..e36a6fd --- /dev/null +++ b/backend/control/usage_accounting.py @@ -0,0 +1,18 @@ +"""Shared lock order for subscription counters; daily rows remain the ledger.""" +from django.db import connection + +from .models import Subscription + + +def non_key_lock_options(): + # PostgreSQL FOR UPDATE conflicts with FK key-share checks on new ledger + # rows. We change counters, not primary keys, so NO KEY UPDATE is sufficient. + return {"no_key": True} if connection.features.has_select_for_no_key_update else {} + + +def lock_usage_subscriptions(subscription_ids): + # Call inside an atomic transaction, before aggregation or ledger updates. + # A consistent order is necessary when two nodes report the same accounts + # in opposite payload orders. + return list(Subscription.objects.filter(pk__in=set(subscription_ids)).order_by("pk") + .select_for_update(**non_key_lock_options())) diff --git a/backend/control/usage_history.py b/backend/control/usage_history.py new file mode 100644 index 0000000..ad927fb --- /dev/null +++ b/backend/control/usage_history.py @@ -0,0 +1,41 @@ +"""Small, subscription-scoped chart payload; no browsing or physical NIC data.""" +from datetime import timedelta +from django.conf import settings +from django.db.models import Sum +from django.utils import timezone +from .models import HourlyUsageRecord, UsageRecord + + +def client_usage_history(subscription, now=None): + now = timezone.localtime(now or timezone.now()) + today = now.date() + hour = now.replace(minute=0, second=0, microsecond=0) + daily = {r["day"]: r for r in UsageRecord.objects.filter( + subscription=subscription, day__gte=today-timedelta(days=29), day__lte=today + ).values("day").annotate(upload=Sum("upload_bytes"), download=Sum("download_bytes"))} + hourly = {r["hour"]: r for r in HourlyUsageRecord.objects.filter( + subscription=subscription, hour__gte=hour-timedelta(hours=23), hour__lte=hour + ).values("hour").annotate(upload=Sum("upload_bytes"), download=Sum("download_bytes"))} + + def days(count): + return [{"day": day.isoformat(), "upload_bytes": daily.get(day, {}).get("upload", 0), + "download_bytes": daily.get(day, {}).get("download", 0)} + for day in (today-timedelta(days=n) for n in range(count-1, -1, -1))] + + def series(count, hourly_mode): + if hourly_mode: + points = [{"time": bucket.isoformat(), + # No recorded report is unknown, not a made-up zero or daily interpolation. + "upload_bytes": hourly.get(bucket, {}).get("upload"), + "download_bytes": hourly.get(bucket, {}).get("download")} + for bucket in (hour-timedelta(hours=n) for n in range(count-1, -1, -1))] + else: + points = [{"time": row["day"], "upload_bytes": row["upload_bytes"], + "download_bytes": row["download_bytes"]} for row in days(count)] + return {"scope": "subscription", "bucket": "hour" if hourly_mode else "day", + "timezone": settings.TIME_ZONE, "generated_at": now.isoformat(), "points": points, + "note": "按上报入账小时统计;含当前小时;缺口表示无小时明细" if hourly_mode + else "按自然日统计;含今日;当天尚未结束"} + + return days(7), {"12h": series(12, True), "1d": series(24, True), + "7d": series(7, False), "30d": series(30, False)} diff --git a/backend/control/views.py b/backend/control/views.py new file mode 100644 index 0000000..867609b --- /dev/null +++ b/backend/control/views.py @@ -0,0 +1,927 @@ +import hashlib +import ipaddress +import json +import re +import secrets +import uuid +from datetime import timedelta + +from django.conf import settings +from django.contrib import admin, messages +from django.contrib.admin.views.decorators import staff_member_required +from django.contrib.auth import authenticate, get_user_model, login +from django.contrib.auth.decorators import login_required +from django.core import signing +from django.core.exceptions import ValidationError +from django.db import connection, transaction +from django.db.models import F, Q, Sum +from django.http import Http404, HttpResponse, JsonResponse +from django.shortcuts import get_object_or_404, redirect, render +from django.utils import timezone +from django.views.decorators.http import require_http_methods +from django.views.decorators.cache import never_cache +from django.views.decorators.csrf import csrf_exempt + +from accounts.forms import RegistrationForm + +from .forms import PlanApplicationForm +from .git_releases import GitReleaseUnavailable, get_latest_windows_release +from .models import ( + ClientSession, + Device, + Node, + NodeDeployment, + NodeReport, + NodeTrafficSample, + Plan, + PlanApplication, + RouteObservation, + Subscription, + UsageRecord, + HourlyUsageRecord, +) +from .usage_history import client_usage_history +from .usage_accounting import lock_usage_subscriptions, non_key_lock_options +from .lifecycle import personal_lifecycle +from .team_services import visible_teams +from .services import desired_subscriptions_for_node, render_mihomo, render_xray_client +from .tailscale_endpoint import client_tailscale_endpoint + + +@require_http_methods(["GET", "POST"]) +def register(request): + if request.user.is_authenticated: + return redirect("portal-dashboard") + form = RegistrationForm(request.POST or None) + if request.method == "POST" and form.is_valid(): + try: + user = form.save() + except ValidationError as exc: + form.add_error(None, exc) + else: + login(request, user) + if form.cleaned_data["plan"].online_payment_required and form.cleaned_data["plan"].price_for_user(user) > 0: + messages.success(request, "注册成功,套餐申请已登记。此套餐暂未开放付款,未扣款、未开通付费服务;内部员工请联系管理员核实身份。") + else: + messages.success(request, "注册成功,套餐申请已一并提交。免费套餐审核后自动开通;付费套餐须确认付款后审核。") + return redirect("portal-dashboard") + return render(request, "registration/register.html", {"form": form}) + + +@never_cache +@login_required +def dashboard(request): + subscriptions = request.user.subscriptions.select_related("plan", "routing_policy").all() + subscription = subscriptions.exclude(status__in=[Subscription.Status.CANCELLED, Subscription.Status.EXPIRED]).first() + if not subscription: + subscription = subscriptions.first() + if subscription: + _enforce_subscription(subscription) + applications = list(request.user.plan_applications.select_related("plan").all()[:10]) + plans = Plan.objects.filter(active=True) + if request.user.identity_type == "employee": + plans = plans.filter(audience__in=[Plan.Audience.EMPLOYEE, Plan.Audience.ALL]) + else: + plans = plans.filter(audience__in=[Plan.Audience.EXTERNAL, Plan.Audience.ALL], employee_benefit=False) + return render( + request, + "portal/dashboard.html", + { + "subscription": subscription, + "applications": applications, + "lifecycle": personal_lifecycle(request.user, subscription, applications[0] if applications else None), + "user_teams": visible_teams(request.user), + "plans": plans, + "plan_cards": [{"plan": plan, "label": plan.application_label(request.user), + "payment_pending": plan.online_payment_required and plan.price_for_user(request.user) > 0} + for plan in plans], + }, + ) + + +@login_required +@require_http_methods(["GET", "POST"]) +def apply_plan(request): + if request.user.plan_applications.filter(status=PlanApplication.Status.PENDING).exists(): + messages.info(request, "您已有待处理申请,请等待管理员审核。") + return redirect("portal-dashboard") + current_subscription = ( + request.user.subscriptions.filter( + status__in=[Subscription.Status.PENDING, Subscription.Status.ACTIVE, Subscription.Status.SUSPENDED] + ) + .select_related("plan") + .first() + ) + form = PlanApplicationForm(request.POST or None, user=request.user) + if request.method == "POST" and form.is_valid(): + if current_subscription and form.cleaned_data["plan"].pk == current_subscription.plan_id: + messages.info(request, "您当前已经在使用该套餐,无需重复申请。") + return redirect("portal-dashboard") + try: + application = form.save() + except ValidationError as exc: + form.add_error(None, exc) + else: + if application.plan.online_payment_required and application.payment_status == PlanApplication.PaymentStatus.UNPAID: + messages.success(request, "套餐申请已登记。此套餐暂未开放付款,未扣款、未开通付费服务;原有订阅不变。") + elif application.payment_status == PlanApplication.PaymentStatus.UNPAID: + messages.success(request, "套餐申请已提交。管理员确认付款并审核后会自动更新订阅。") + else: + messages.success(request, "套餐申请已提交,管理员审核后会自动创建或更新订阅。") + return redirect("portal-dashboard") + return render( + request, + "portal/application_form.html", + {"form": form, "current_subscription": current_subscription}, + ) + + +def subscription_config(request, token): + try: + payload = signing.loads(token, salt="toplc-vpn-subscription") + subscription_id = int(payload["subscription_id"]) + token_version = int(payload["version"]) + except (signing.BadSignature, KeyError, TypeError, ValueError): + raise Http404("订阅地址无效") + + subscription = get_object_or_404( + Subscription.objects.select_related("user", "plan", "routing_policy"), + pk=subscription_id, + ) + if subscription.token_version != token_version: + raise Http404("订阅地址已失效") + _enforce_subscription(subscription) + if not subscription.is_usable: + return HttpResponse("订阅尚未启用、已暂停或已到期。\n", status=403, content_type="text/plain; charset=utf-8") + try: + body = render_mihomo(subscription) + except ValueError as exc: + return HttpResponse(f"{exc}\n", status=503, content_type="text/plain; charset=utf-8") + + response = HttpResponse(body, content_type="text/yaml; charset=utf-8") + response["Content-Disposition"] = 'inline; filename="toplc-mihomo.yaml"' + response["Profile-Update-Interval"] = "24" + expire = int(subscription.expires_at.timestamp()) if subscription.expires_at else 0 + response["Subscription-Userinfo"] = ( + f"upload={subscription.upload_bytes}; download={subscription.download_bytes}; " + f"total={subscription.traffic_limit_bytes}; expire={expire}" + ) + response["Cache-Control"] = "no-store" + return response + + +@login_required +def api_me(request): + subscription = request.user.subscriptions.exclude( + status__in=[Subscription.Status.CANCELLED, Subscription.Status.EXPIRED] + ).first() + return JsonResponse( + { + "username": request.user.username, + "display_name": request.user.display_name, + "identity_type": request.user.identity_type, + "account_status": request.user.account_status, + "subscription": ( + { + "status": subscription.status, + "plan": subscription.plan.name, + "used_bytes": subscription.used_bytes, + "traffic_limit_bytes": subscription.traffic_limit_bytes, + "expires_at": subscription.expires_at.isoformat() if subscription.expires_at else None, + } + if subscription + else None + ), + } + ) + + +@require_http_methods(["GET"]) +def client_update(request): + platform = request.GET.get("platform", "windows").strip().lower() + if platform != "windows": + return JsonResponse({"error": "暂无该平台的更新。"}, status=404) + current = request.GET.get("current", "").strip()[:30] + try: + manifest = get_latest_windows_release() + except GitReleaseUnavailable: + response = JsonResponse({"error": "公司 Git 更新服务暂时不可用,请稍后重试。"}, status=503) + response["Cache-Control"] = "no-store" + return response + + payload = { + "available": _newer_stable_release(manifest["version"], current), + "version": manifest["version"], + "download_url": manifest["download_url"], + "sha256": manifest["sha256"], + "size": manifest["size"], + "notes": manifest.get("notes", ""), + "mandatory": bool(manifest.get("mandatory", False)), + } + response = JsonResponse(payload) + response["Cache-Control"] = "no-store" + return response + + +@require_http_methods(["GET"]) +def client_download_latest(request): + try: + manifest = get_latest_windows_release() + except GitReleaseUnavailable: + response = JsonResponse({"error": "请稍后从公司 Git 下载软件。"}, status=503) + response["Cache-Control"] = "no-store" + return response + # Backward-compatible URL only. The platform never opens/streams a local + # installer and never republishes release bytes. + response = redirect(manifest["download_url"]) + response["Cache-Control"] = "no-store" + return response + + +def _version_tuple(value): + match = re.fullmatch(r"v?(\d{1,5})\.(\d{1,5})\.(\d{1,5})(?:[-+][A-Za-z0-9.-]+)?", str(value)) + return tuple(map(int, match.groups())) if match else (0, 0, 0) + + +def _newer_stable_release(stable, current): + offered, installed = _version_tuple(stable), _version_tuple(current) + return offered > installed or (offered == installed and bool(re.match(r"^v?\d+\.\d+\.\d+-", str(current)))) + + +@csrf_exempt +@require_http_methods(["POST"]) +def client_login(request): + try: + if len(request.body) > 16 * 1024: + raise ValueError + payload = json.loads(request.body or b"{}") + login_id = str(payload["login"]).strip() + password = str(payload["password"]) + device_id = str(payload["device_id"]).strip() + client_platform = str(payload.get("platform", "windows")).strip().lower() + if client_platform not in {"windows", "android", "ios"}: + raise ValueError + platform_label = { + "windows": "Windows", + "android": "Android", + "ios": "iPhone / iPad", + }[client_platform] + default_device_name = f"{platform_label} 设备" + device_name = str(payload.get("device_name", default_device_name)).strip()[:100] or default_device_name + app_version = str(payload.get("app_version", "")).strip()[:30] + if not 1 <= len(login_id) <= 254 or not 8 <= len(password) <= 512: + raise ValueError + if not 16 <= len(device_id) <= 128 or any(ch not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.:" for ch in device_id): + raise ValueError + except (KeyError, TypeError, ValueError, json.JSONDecodeError): + return JsonResponse({"error": "请求参数无效。"}, status=400) + + User = get_user_model() + user = User.objects.filter(Q(username__iexact=login_id) | Q(email__iexact=login_id)).first() + authenticated = authenticate(request, username=user.username, password=password) if user else None + if not authenticated: + return JsonResponse({"error": "用户名、邮箱或密码不正确。"}, status=401) + if not authenticated.service_enabled: + return JsonResponse({"error": "账号尚未开通或已被停用。"}, status=403) + + subscription = ( + authenticated.subscriptions.exclude(status__in=[Subscription.Status.CANCELLED, Subscription.Status.EXPIRED]) + .select_related("plan", "user") + .first() + ) + if not subscription: + return JsonResponse({"error": "账号没有可用订阅。"}, status=403) + _enforce_subscription(subscription) + subscription.refresh_from_db() + if not subscription.is_usable: + return JsonResponse({"error": subscription.state_reason or "订阅尚未生效、已暂停或已到期。"}, status=403) + + now = timezone.now() + with transaction.atomic(): + subscription = Subscription.objects.select_for_update().select_related("plan", "user").get(pk=subscription.pk) + device = Device.objects.select_for_update().filter(subscription=subscription, device_id=device_id).first() + if device and not device.active: + return JsonResponse({"error": "该设备已被管理员禁用。"}, status=403) + if not device: + active_devices = Device.objects.filter(subscription=subscription, active=True).count() + if active_devices >= subscription.device_limit: + return JsonResponse({"error": f"设备数量已达到套餐上限({subscription.device_limit} 台)。"}, status=403) + device = Device.objects.create( + subscription=subscription, + device_id=device_id, + name=device_name, + platform=f"{platform_label} · 优创⁺纵横家 {app_version}".strip(" ·"), + active=True, + last_seen_at=now, + ) + else: + device.name = device_name + device.platform = f"{platform_label} · 优创⁺纵横家 {app_version}".strip(" ·") + device.last_seen_at = now + device.save(update_fields=["name", "platform", "last_seen_at"]) + + ClientSession.objects.filter(device=device, revoked_at__isnull=True).update(revoked_at=now) + session, token = ClientSession.issue(subscription, device, lifetime=timedelta(days=30)) + + response = JsonResponse( + { + "access_token": token, + "token_type": "Bearer", + "expires_at": session.expires_at.isoformat(), + "profile": _client_profile_payload(subscription), + } + ) + response["Cache-Control"] = "no-store" + return response + + +@require_http_methods(["GET"]) +def client_profile(request): + session, error_response = _authenticate_client_session(request) + if error_response: + return error_response + response = JsonResponse({"profile": _client_profile_payload(session.subscription)}) + response["Cache-Control"] = "no-store" + return response + + +def _client_gateway_payload(): + """Return the stable public NPM entrypoint without exposing private overlay IPs.""" + host = str(getattr(settings, "VPN_PUBLIC_GATEWAY_HOST", "vpn.toplc.cn") or "vpn.toplc.cn").strip() + configured_ipv4 = str(getattr(settings, "VPN_PUBLIC_GATEWAY_IPV4", "") or "").strip() + public_ipv4 = None + if configured_ipv4: + try: + address = ipaddress.ip_address(configured_ipv4) + if address.version == 4 and address.is_global: + public_ipv4 = configured_ipv4 + except ValueError: + pass + return {"host": host, "ipv4": public_ipv4} + + +@require_http_methods(["GET"]) +def client_config(request): + session, error_response = _authenticate_client_session(request) + if error_response: + return error_response + subscription = session.subscription + node_slug = request.GET.get("node", "").strip() + route_mode = request.GET.get("route", "smart").strip().lower() + nodes = subscription.nodes_for_subscription().filter(protocol=Node.Protocol.VLESS_REALITY) + dispatch = None + if node_slug == "auto": + from .dispatch import choose_node + node, dispatch = choose_node(session, request.GET.get("exclude", "")[:3000].split(","), request.GET.get("new_connection") == "1") + else: + node = nodes.filter(slug=node_slug).first() if node_slug else nodes.first() + if not node: + return JsonResponse({"error": "所选线路不可用。"}, status=404) + try: + config = render_xray_client(subscription, node, route_mode=route_mode) + except ValueError as exc: + return JsonResponse({"error": str(exc)}, status=400) + payload = { + "config_contract": 2, + "gateway": _client_gateway_payload(), + "node": {"slug": node.slug, "name": node.name, "region": node.region}, + "route_mode": route_mode, + "config": config, + "dispatch": dispatch, + } + tailscale_endpoint = client_tailscale_endpoint(session, node) + if tailscale_endpoint is not None: + payload["tailscale_endpoint"] = tailscale_endpoint + response = JsonResponse(payload) + response["Cache-Control"] = "no-store" + return response + + +@csrf_exempt +@require_http_methods(["POST"]) +def client_observations(request): + session, error_response = _authenticate_client_session(request) + if error_response: + return error_response + try: + if len(request.body) > 32 * 1024: + raise ValueError + payload = json.loads(request.body or b"{}") + observations = payload["observations"] + if not isinstance(observations, list) or not 1 <= len(observations) <= 20: + raise ValueError + except (KeyError, TypeError, ValueError, json.JSONDecodeError): + return JsonResponse({"error": "观测数据格式无效。"}, status=400) + + allowed_nodes = { + node.slug: node + for node in session.subscription.nodes_for_subscription().filter(protocol=Node.Protocol.VLESS_REALITY) + } + accepted = 0 + try: + with transaction.atomic(): + # Serialize this device's ingestion budget. No unbounded telemetry flood. + Device.objects.select_for_update().get(pk=session.device_id) + if RouteObservation.objects.filter(device=session.device, + received_at__gte=timezone.now() - timedelta(hours=1)).count() + len(observations) > 120: + response = JsonResponse({"error": "观测频率过高,请稍后重试。"}, status=429) + response["Retry-After"] = "60" + return response + for item in observations: + if not isinstance(item, dict): + raise ValueError + report_id = uuid.UUID(str(item["report_id"])) + target_type = str(item["target_type"]).strip().lower() + target = _normalize_observation_target(target_type, str(item["target"])) + port = int(item["port"]) + access_kind = str( + item.get( + "access_kind", + RouteObservation.AccessKind.HTTP + if port in {80, 443} + else RouteObservation.AccessKind.SOCKET, + ) + ).strip().lower() + network = str(item["network"]).strip().lower() + outcome = str(item["outcome"]).strip().lower() + failure_kind = str(item.get("failure_kind", RouteObservation.FailureKind.OTHER)).strip().lower() + client_version = str(item.get("client_version", ""))[:30] + node_slug = str(item.get("node", "")).strip() + scope = str(item.get("scope", "public")) + evidence_kind = str(item.get("evidence_kind", "")) + related_id = uuid.UUID(str(item["related_report_id"])) if item.get("related_report_id") else None + if scope not in {"public", "private_auxiliary"} or evidence_kind not in {"", "tls"}: + raise ValueError + if not 1 <= port <= 65535: + raise ValueError + if access_kind not in RouteObservation.AccessKind.values: + raise ValueError + if network not in RouteObservation.Network.values: + raise ValueError + if outcome not in RouteObservation.Outcome.values: + raise ValueError + if failure_kind not in RouteObservation.FailureKind.values: + raise ValueError + node = allowed_nodes.get(node_slug) if node_slug else None + if scope == "private_auxiliary": + from .private_auxiliary import permitted + if not permitted(session.subscription): + raise ValueError + node = None # Private evidence cannot affect public node scores/rules. + elif node_slug and node is None: + raise ValueError + if evidence_kind == "tls": + if outcome != "proxy_succeeded" or network != "tcp" or port != 443 or node is None: + raise ValueError + pair = RouteObservation.objects.filter(report_id=related_id, device=session.device, + target_type=target_type, target=target, port=port, network=network, node=node, + scope="public", outcome="direct_failed", + received_at__gte=timezone.now() - timedelta(minutes=10)).first() + if pair is None: + raise ValueError + prior = RouteObservation.objects.filter(report_id=report_id).first() + if prior and prior.device_id != session.device_id: + raise ValueError + _, created = RouteObservation.objects.get_or_create( + report_id=report_id, + defaults={ + "subscription": session.subscription, + "device": session.device, + "node": node, + "target_type": target_type, + "target": target, + "port": port, + "access_kind": access_kind, + "network": network, + "outcome": outcome, + "failure_kind": failure_kind, + "client_version": client_version, + "scope": scope, + "evidence_kind": evidence_kind, + "related_report_id": related_id, + }, + ) + accepted += int(created) + except (KeyError, TypeError, ValueError): + return JsonResponse({"error": "观测数据内容无效。"}, status=400) + return JsonResponse({"status": "accepted", "accepted": accepted}) + + +@csrf_exempt +@require_http_methods(["POST"]) +def client_logout(request): + session, error_response = _authenticate_client_session(request, require_usable=False) + if error_response: + return error_response + session.revoked_at = timezone.now() + session.save(update_fields=["revoked_at"]) + return JsonResponse({"status": "logged_out"}) + + +def health(request): + try: + with connection.cursor() as cursor: + cursor.execute("SELECT 1") + cursor.fetchone() + except Exception: + return JsonResponse({"status": "unhealthy", "database": "down"}, status=503) + return JsonResponse({"status": "ok", "database": "ok"}) + + +@staff_member_required +def node_traffic_dashboard(request): + context = admin.site.each_context(request) + context.update( + { + "title": "节点实时流量监控", + "node_count": Node.objects.filter(active=True).count(), + } + ) + return render(request, "admin/node_traffic.html", context) + + +@staff_member_required +@require_http_methods(["GET"]) +def node_traffic_data(request): + try: + range_minutes = int(request.GET.get("minutes", "60")) + except ValueError: + range_minutes = 60 + if range_minutes not in {15, 60, 360, 1440}: + range_minutes = 60 + + now = timezone.now() + since = now - timedelta(minutes=range_minutes) + nodes = list(Node.objects.filter(active=True).order_by("sort_order", "region", "name")) + samples_by_node = {node.pk: [] for node in nodes} + samples = NodeTrafficSample.objects.filter( + node_id__in=samples_by_node, + sampled_at__gte=since, + ).order_by("sampled_at") + for sample in samples.iterator(): + samples_by_node[sample.node_id].append(sample) + + online_after = now - timedelta(minutes=5) + payload_nodes = [] + for node in nodes: + node_samples = samples_by_node[node.pk] + latest = node_samples[-1] if node_samples else None + payload_nodes.append( + { + "id": node.pk, + "slug": node.slug, + "name": node.name, + "region": node.region, + "status": node.status, + "online": bool( + node.status == Node.Status.ONLINE + and node.last_seen_at + and node.last_seen_at >= online_after + ), + "last_seen_at": node.last_seen_at.isoformat() if node.last_seen_at else None, + "current_upload_bytes_per_second": latest.upload_bytes_per_second if latest else 0, + "current_download_bytes_per_second": latest.download_bytes_per_second if latest else 0, + "total_upload_bytes": node.total_upload_bytes, + "total_download_bytes": node.total_download_bytes, + "active_subscriptions": latest.active_subscriptions if latest else 0, + "samples": [ + { + "at": sample.sampled_at.isoformat(), + "upload_bytes": sample.upload_bytes, + "download_bytes": sample.download_bytes, + "upload_bytes_per_second": sample.upload_bytes_per_second, + "download_bytes_per_second": sample.download_bytes_per_second, + } + for sample in node_samples + ], + } + ) + + response = JsonResponse( + { + "generated_at": now.isoformat(), + "range_minutes": range_minutes, + "nodes": payload_nodes, + } + ) + response["Cache-Control"] = "no-store" + return response + + +@csrf_exempt +@require_http_methods(["GET", "POST"]) +def node_sync(request): + node = _authenticate_node(request) + if not node: + return JsonResponse({"error": "node authentication failed"}, status=401) + + now = timezone.now() + Node.objects.filter(pk=node.pk).update( + last_seen_at=now, + status=Node.Status.ONLINE, + agent_version=request.headers.get("X-Agent-Version", "")[:64], + ) + + desired = list(desired_subscriptions_for_node(node)) + if request.method == "GET": + NodeDeployment.objects.bulk_create( + [NodeDeployment(node=node, subscription=subscription) for subscription in desired], + ignore_conflicts=True, + ) + return JsonResponse( + { + "node": node.slug, + "generated_at": now.isoformat(), + "clients": [ + { + "subscription_id": subscription.pk, + "email": f"sub-{subscription.pk}", + "uuid": str(subscription.credential_uuid), + "flow": "xtls-rprx-vision", + } + for subscription in desired + ], + } + ) + + try: + payload = json.loads(request.body or b"{}") + report_id = uuid.UUID(str(payload["report_id"])) + applied_ids = {int(value) for value in payload.get("applied_subscription_ids", [])} + success = bool(payload.get("success", True)) + error = str(payload.get("error", ""))[:500] + usage = payload.get("usage", []) + if not isinstance(usage, list): + raise ValueError("usage must be a list") + except (KeyError, TypeError, ValueError, json.JSONDecodeError): + return JsonResponse({"error": "invalid report payload"}, status=400) + + desired_ids = {subscription.pk for subscription in desired} + + normalized_usage = [] + try: + for item in usage: + subscription_id = int(item["subscription_id"]) + upload_bytes = int(item.get("upload_bytes", 0)) + download_bytes = int(item.get("download_bytes", 0)) + if min(upload_bytes, download_bytes) < 0: + raise ValueError + if upload_bytes > 10 * 1024**4 or download_bytes > 10 * 1024**4: + raise ValueError + normalized_usage.append((subscription_id, upload_bytes, download_bytes)) + except (KeyError, TypeError, ValueError): + return JsonResponse({"error": "invalid usage item"}, status=400) + + known_deployment_ids = set( + NodeDeployment.objects.filter(node=node).values_list("subscription_id", flat=True) + ) | desired_ids + if not applied_ids.issubset(known_deployment_ids): + return JsonResponse({"error": "applied subscription is not associated with this node"}, status=400) + if any(subscription_id not in known_deployment_ids for subscription_id, _, _ in normalized_usage): + return JsonResponse({"error": "usage item is not associated with this node"}, status=400) + + with transaction.atomic(): + # Serialize first reports as well as existing deployment rows. Otherwise + # two first reports can both try to create the same NodeDeployment. + Node.objects.select_for_update(**non_key_lock_options()).get(pk=node.pk) + report, created = NodeReport.objects.get_or_create(node=node, report_id=report_id) + if not created: + return JsonResponse({"status": "already_processed"}) + + lock_usage_subscriptions(known_deployment_ids | desired_ids) + + deployments = { + deployment.subscription_id: deployment + for deployment in NodeDeployment.objects.select_for_update().filter(node=node) + } + touched_subscription_ids = set(deployments) + for subscription in desired: + deployment = deployments.get(subscription.pk) + if not deployment: + deployment = NodeDeployment(node=node, subscription=subscription) + deployments[subscription.pk] = deployment + touched_subscription_ids.add(subscription.pk) + + if success: + for subscription_id, deployment in deployments.items(): + should_be_deployed = subscription_id in applied_ids + if should_be_deployed: + deployment.deployed = True + deployment.applied_at = now + deployment.revoked_at = None + elif deployment.deployed: + deployment.deployed = False + deployment.revoked_at = now + deployment.last_error = "" + deployment.save() + else: + for subscription_id in desired_ids: + deployment = deployments[subscription_id] + deployment.last_error = error or "节点应用配置失败" + deployment.save(update_fields=["last_error", "updated_at"]) + + affected_usage_ids = set() + total_upload = 0 + total_download = 0 + for subscription_id, upload_bytes, download_bytes in normalized_usage: + record, _ = UsageRecord.objects.select_for_update().get_or_create( + subscription_id=subscription_id, + node=node, + day=timezone.localdate(), + ) + record.upload_bytes += upload_bytes + record.download_bytes += download_bytes + record.save(update_fields=["upload_bytes", "download_bytes", "updated_at"]) + # Same idempotent transaction as the daily ledger. Never rebill these + # rows; delayed deltas belong to their receipt hour, not guessed times. + hourly, _ = HourlyUsageRecord.objects.select_for_update().get_or_create( + subscription_id=subscription_id, node=node, + hour=now.replace(minute=0, second=0, microsecond=0), + ) + hourly.upload_bytes += upload_bytes + hourly.download_bytes += download_bytes + hourly.save(update_fields=["upload_bytes", "download_bytes"]) + affected_usage_ids.add(subscription_id) + total_upload += upload_bytes + total_download += download_bytes + + if total_upload or total_download: + Node.objects.filter(pk=node.pk).update( + total_upload_bytes=F("total_upload_bytes") + total_upload, + total_download_bytes=F("total_download_bytes") + total_download, + ) + + previous_sample = ( + NodeTrafficSample.objects.filter(node=node) + .order_by("-sampled_at") + .only("sampled_at") + .first() + ) + interval_seconds = 60 + if previous_sample: + interval_seconds = max(1, min(3600, round((now - previous_sample.sampled_at).total_seconds()))) + NodeTrafficSample.objects.create( + node=node, + report=report, + interval_seconds=interval_seconds, + upload_bytes=total_upload, + download_bytes=total_download, + upload_bytes_per_second=total_upload // interval_seconds, + download_bytes_per_second=total_download // interval_seconds, + active_subscriptions=len(applied_ids), + ) + + for subscription in Subscription.objects.select_for_update().filter(pk__in=touched_subscription_ids): + has_deployment = subscription.node_deployments.filter(deployed=True).exists() + if subscription.status == Subscription.Status.ACTIVE: + state = ( + Subscription.ProvisioningState.ACTIVE + if has_deployment + else Subscription.ProvisioningState.FAILED if not success else Subscription.ProvisioningState.PENDING + ) + reason = "" if has_deployment else error + Subscription.objects.filter(pk=subscription.pk).update( + provisioning_state=state, + state_reason=reason, + ) + elif subscription.provisioning_state == Subscription.ProvisioningState.REVOKE_PENDING and not has_deployment: + Subscription.objects.filter(pk=subscription.pk).update( + provisioning_state=Subscription.ProvisioningState.REVOKED + ) + + return JsonResponse({"status": "accepted", "usage_items": len(normalized_usage)}) + + +def _authenticate_node(request): + slug = request.headers.get("X-Node-Slug", "").strip() + authorization = request.headers.get("Authorization", "") + if not authorization.startswith("Bearer "): + return None + token = authorization[7:].strip() + try: + node = Node.objects.get(slug=slug, active=True) + except Node.DoesNotExist: + return None + return node if node.check_agent_token(token) else None + + +def _authenticate_client_session(request, require_usable=True): + authorization = request.headers.get("Authorization", "") + if not authorization.startswith("Bearer "): + return None, JsonResponse({"error": "缺少客户端访问令牌。"}, status=401) + token = authorization[7:].strip() + if not 32 <= len(token) <= 256: + return None, JsonResponse({"error": "客户端访问令牌无效。"}, status=401) + digest = hashlib.sha256(token.encode("utf-8")).hexdigest() + session = ( + ClientSession.objects.select_related("device", "subscription__user", "subscription__plan") + .filter(token_digest=digest, revoked_at__isnull=True) + .first() + ) + if not session or not secrets.compare_digest(session.token_digest, digest) or not session.is_valid: + return None, JsonResponse({"error": "登录已失效,请重新登录。"}, status=401) + if not session.device.active: + return None, JsonResponse({"error": "该设备已被管理员禁用。"}, status=403) + if require_usable: + _enforce_subscription(session.subscription) + session.subscription.refresh_from_db() + if not session.subscription.is_usable: + return None, JsonResponse( + {"error": session.subscription.state_reason or "订阅不可用。"}, + status=403, + ) + now = timezone.now() + ClientSession.objects.filter(pk=session.pk).update(last_seen_at=now) + Device.objects.filter(pk=session.device_id).update(last_seen_at=now) + session.last_seen_at = now + session.device.last_seen_at = now + return session, None + + +def _client_profile_payload(subscription): + from .private_auxiliary import profile_grants + nodes = subscription.nodes_for_subscription().filter(protocol=Node.Protocol.VLESS_REALITY) + history, ranges = client_usage_history(subscription) + return { + "username": subscription.user.username, + "display_name": subscription.user.display_name, + "email": subscription.user.email, + "identity_type": subscription.user.identity_type, + "dispatch_mode": "vpn-ai", + "private_auxiliary_nodes": profile_grants(subscription), + "usage_history": history, + "usage_history_ranges": ranges, + "subscription": { + "status": subscription.status, + "plan": subscription.plan.name, + "used_bytes": subscription.used_bytes, + "traffic_limit_bytes": subscription.traffic_limit_bytes, + "expires_at": subscription.expires_at.isoformat() if subscription.expires_at else None, + "device_limit": subscription.device_limit, + }, + "nodes": [ + { + "slug": node.slug, + "name": node.name, + "region": node.region, + "status": node.status, + } + for node in nodes + ], + "route_modes": [ + {"id": "smart", "name": "AI 智能代理"}, + {"id": "global", "name": "全局代理"}, + {"id": "direct", "name": "仅直连"}, + ], + } + + +def _normalize_observation_target(target_type, target): + target = target.strip().rstrip(".").lower() + if target_type == RouteObservation.TargetType.IP: + address = ipaddress.ip_address(target) + if not address.is_global: + raise ValueError + return address.compressed + if target_type != RouteObservation.TargetType.DOMAIN: + raise ValueError + try: + ipaddress.ip_address(target) + except ValueError: + pass + else: + raise ValueError # Cannot disguise a private IP as a domain. + try: + target = target.encode("idna").decode("ascii") + except UnicodeError as exc: + raise ValueError from exc + if not 1 <= len(target) <= 253 or "." not in target: + raise ValueError + protected_domains = {"toplc.cn", "ucvl.cn", "ucvl.net", "localhost"} + if target in protected_domains or target.endswith((".local", ".toplc.cn", ".ucvl.cn", ".ucvl.net", + ".localhost", ".lan", ".internal", ".home", ".invalid", ".test", ".example", ".arpa", ".onion")): + raise ValueError + if any( + not re.fullmatch(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", label) + for label in target.split(".") + ): + raise ValueError + return target + + +def _enforce_subscription(subscription): + now = timezone.now() + update_fields = [] + if subscription.status == Subscription.Status.ACTIVE: + if subscription.expires_at and subscription.expires_at <= now: + subscription.status = Subscription.Status.EXPIRED + subscription.state_reason = "套餐已到期" + subscription.provisioning_state = Subscription.ProvisioningState.REVOKE_PENDING + update_fields.extend(["status", "state_reason", "provisioning_state"]) + elif subscription.traffic_limit_bytes and subscription.used_bytes >= subscription.traffic_limit_bytes: + subscription.status = Subscription.Status.SUSPENDED + subscription.state_reason = "流量额度已用完" + subscription.provisioning_state = Subscription.ProvisioningState.REVOKE_PENDING + update_fields.extend(["status", "state_reason", "provisioning_state"]) + if update_fields: + subscription.save(update_fields=[*update_fields, "updated_at"]) diff --git a/backend/control/vpn_ai.py b/backend/control/vpn_ai.py new file mode 100644 index 0000000..0edf4e1 --- /dev/null +++ b/backend/control/vpn_ai.py @@ -0,0 +1,213 @@ +from datetime import timedelta +from decimal import Decimal + +from django.db.models import Count, Q +from django.utils import timezone + +from .models import LearnedRouteRule, Node, RouteObservation, Subscription, VpnAiFinding, VpnAiRuntime + + +LEARNING_WINDOW = timedelta(days=7) +RULE_LIFETIME = timedelta(days=30) + + +def _open_finding(*, fingerprint, category, severity, title, summary, evidence): + finding, _ = VpnAiFinding.objects.update_or_create( + fingerprint=fingerprint, + defaults={ + "category": category, + "severity": severity, + "status": VpnAiFinding.Status.OPEN, + "title": title, + "summary": summary, + "evidence": evidence, + "resolved_at": None, + }, + ) + return finding + + +def _resolve_missing_findings(category, active_fingerprints, now): + VpnAiFinding.objects.filter(category=category, status=VpnAiFinding.Status.OPEN).exclude( + fingerprint__in=active_fingerprints + ).update(status=VpnAiFinding.Status.RESOLVED, resolved_at=now) + + +def _learning_confidence(failures, devices, proxy_successes): + failure_score = min(1.0, failures / 6) * 0.45 + device_score = min(1.0, devices / 2) * 0.40 + success_score = min(1.0, proxy_successes / 2) * 0.15 + return Decimal(str(round(failure_score + device_score + success_score, 4))) + + +def evaluate_route_learning(now): + since = now - LEARNING_WINDOW + aggregates = ( + RouteObservation.objects.filter(received_at__gte=since, scope="public") + .values("target_type", "target") + .annotate( + failures=Count("id", filter=Q(outcome=RouteObservation.Outcome.DIRECT_FAILED)), + proxy_successes=Count("id", filter=Q(outcome=RouteObservation.Outcome.PROXY_SUCCEEDED)), + devices=Count("device_id", distinct=True), + verified_devices=Count("device_id", distinct=True, filter=Q( + outcome=RouteObservation.Outcome.PROXY_SUCCEEDED, evidence_kind="tls", related_report_id__isnull=False)), + ) + ) + active_route_findings = set() + for item in aggregates: + failures = item["failures"] + devices = item["devices"] + successes = item["proxy_successes"] + confidence = _learning_confidence(failures, devices, successes) + rule, _ = LearnedRouteRule.objects.get_or_create( + target_type=item["target_type"], + target=item["target"], + defaults={ + "source": LearnedRouteRule.Source.AI, + "match_mode": LearnedRouteRule.MatchMode.EXACT, + }, + ) + rule.failure_reports = failures + rule.proxy_success_reports = successes + rule.distinct_devices = devices + rule.confidence = confidence + rule.last_evaluated_at = now + if rule.source == LearnedRouteRule.Source.PRESET and rule.manually_locked: + # Preset rules are trusted company baselines. vpn-ai may attach + # observation counters for visibility, but must not relearn, + # expire, or rewrite their reason and status. + rule.save( + update_fields=[ + "failure_reports", + "proxy_success_reports", + "distinct_devices", + "confidence", + "last_evaluated_at", + "updated_at", + ] + ) + continue + rule.reason = ( + f"近 7 天:直连失败 {failures} 次、涉及 {devices} 台设备、" + f"代理成功确认 {successes} 次;置信度 {confidence}." + ) + if not rule.manually_locked: + # Company rules still require independent evidence from at least two + # devices. A direct failure followed by a successful proxy probe on + # both devices is stronger evidence than repeated failures alone. + # Failure-only reports can be a local outage, a dead website or DNS + # policy. Require correlated, certificate-verified proxy TLS on two + # devices; legacy unverified reports remain visible but cannot promote. + should_activate = item["verified_devices"] >= 2 and failures >= 2 + rule.status = LearnedRouteRule.Status.ACTIVE if should_activate else LearnedRouteRule.Status.PENDING + rule.valid_until = now + RULE_LIFETIME if should_activate else None + rule.save() + + if rule.status == LearnedRouteRule.Status.ACTIVE: + fingerprint = f"route:{rule.target_type}:{rule.target}" + active_route_findings.add(fingerprint) + _open_finding( + fingerprint=fingerprint, + category=VpnAiFinding.Category.ROUTING, + severity=VpnAiFinding.Severity.INFO, + title=f"已学习代理目标:{rule.target}", + summary="vpn-ai 已依据多设备连接结果启用公司级智能代理规则。", + evidence={ + "target_type": rule.target_type, + "target": rule.target, + "confidence": str(confidence), + "failures": failures, + "devices": devices, + "proxy_successes": successes, + "valid_until": rule.valid_until.isoformat() if rule.valid_until else None, + }, + ) + + LearnedRouteRule.objects.filter( + status=LearnedRouteRule.Status.ACTIVE, + manually_locked=False, + valid_until__lte=now, + ).update(status=LearnedRouteRule.Status.PENDING, valid_until=None) + _resolve_missing_findings(VpnAiFinding.Category.ROUTING, active_route_findings, now) + + +def diagnose_nodes(now): + stale_before = now - timedelta(minutes=10) + offline_before = now - timedelta(minutes=15) + active_fingerprints = set() + nodes = Node.objects.filter(active=True, subscription_enabled=True).exclude(status=Node.Status.MAINTENANCE) + for node in nodes: + if not node.last_seen_at or node.last_seen_at < stale_before: + fingerprint = f"node:stale:{node.pk}" + active_fingerprints.add(fingerprint) + minutes = None if not node.last_seen_at else round((now - node.last_seen_at).total_seconds() / 60) + _open_finding( + fingerprint=fingerprint, + category=VpnAiFinding.Category.NODE, + severity=( + VpnAiFinding.Severity.CRITICAL + if not node.last_seen_at or node.last_seen_at < offline_before + else VpnAiFinding.Severity.WARNING + ), + title=f"节点心跳异常:{node.name}", + summary="节点代理未在预期时间内上报,vpn-ai 已记录并持续复查。", + evidence={ + "node": node.slug, + "last_seen_at": node.last_seen_at.isoformat() if node.last_seen_at else None, + "minutes_since_seen": minutes, + }, + ) + if node.status == Node.Status.ONLINE and (not node.last_seen_at or node.last_seen_at < offline_before): + Node.objects.filter(pk=node.pk, status=Node.Status.ONLINE).update(status=Node.Status.OFFLINE) + _resolve_missing_findings(VpnAiFinding.Category.NODE, active_fingerprints, now) + + +def diagnose_subscriptions(now): + active_fingerprints = set() + subscriptions = Subscription.objects.select_related("user", "plan").filter(status=Subscription.Status.ACTIVE) + for subscription in subscriptions: + if subscription.traffic_limit_bytes: + percent = subscription.used_bytes * 100 / subscription.traffic_limit_bytes + if percent >= 90: + fingerprint = f"subscription:quota:{subscription.pk}" + active_fingerprints.add(fingerprint) + _open_finding( + fingerprint=fingerprint, + category=VpnAiFinding.Category.SUBSCRIPTION, + severity=VpnAiFinding.Severity.WARNING, + title=f"订阅流量接近上限:{subscription.user}", + summary="当前周期流量使用率已达到或超过 90%。", + evidence={"subscription_id": subscription.pk, "usage_percent": round(percent, 2)}, + ) + if subscription.expires_at and subscription.expires_at <= now + timedelta(days=3): + fingerprint = f"subscription:expiry:{subscription.pk}" + active_fingerprints.add(fingerprint) + _open_finding( + fingerprint=fingerprint, + category=VpnAiFinding.Category.SUBSCRIPTION, + severity=VpnAiFinding.Severity.WARNING, + title=f"订阅即将到期:{subscription.user}", + summary="订阅将在 3 天内到期,请管理员确认续期或停用安排。", + evidence={"subscription_id": subscription.pk, "expires_at": subscription.expires_at.isoformat()}, + ) + _resolve_missing_findings(VpnAiFinding.Category.SUBSCRIPTION, active_fingerprints, now) + + +def run_vpn_ai_cycle(runtime): + from .dispatch import build_dispatch_snapshot + now = timezone.now() + evaluate_route_learning(now) + diagnose_nodes(now) + diagnose_subscriptions(now) + since = now - LEARNING_WINDOW + runtime.last_heartbeat_at = now + runtime.last_cycle_at = now + runtime.cycle_count += 1 + runtime.observations_7d = RouteObservation.objects.filter(received_at__gte=since).count() + runtime.active_rules = LearnedRouteRule.objects.filter( + status=LearnedRouteRule.Status.ACTIVE + ).filter(Q(valid_until__isnull=True) | Q(valid_until__gt=now)).count() + runtime.open_findings = VpnAiFinding.objects.filter(status=VpnAiFinding.Status.OPEN).count() + runtime.last_error = "" + runtime.dispatch_snapshot = build_dispatch_snapshot(now) + runtime.save() diff --git a/backend/docker/entrypoint.sh b/backend/docker/entrypoint.sh new file mode 100644 index 0000000..8cbf3aa --- /dev/null +++ b/backend/docker/entrypoint.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env sh +set -eu + +python - <<'PY' +import os +import time + +import psycopg + +for attempt in range(30): + try: + with psycopg.connect( + dbname=os.environ["POSTGRES_DB"], + user=os.environ["POSTGRES_USER"], + password=os.environ["POSTGRES_PASSWORD"], + host=os.environ.get("POSTGRES_HOST", "db"), + port=os.environ.get("POSTGRES_PORT", "5432"), + connect_timeout=3, + ): + break + except psycopg.OperationalError: + if attempt == 29: + raise + time.sleep(2) +PY + +if [ "${VPN_RUN_STARTUP_TASKS:-true}" = "true" ]; then + python manage.py migrate --noinput + python manage.py collectstatic --noinput --clear + python manage.py bootstrap_vpn +fi + +exec "$@" diff --git a/backend/manage.py b/backend/manage.py new file mode 100644 index 0000000..5d3b4f2 --- /dev/null +++ b/backend/manage.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +import os +import sys + + +def main(): + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "toplc_vpn.settings") + from django.core.management import execute_from_command_line + + execute_from_command_line(sys.argv) + + +if __name__ == "__main__": + main() + diff --git a/backend/requirements.txt b/backend/requirements.txt new file mode 100644 index 0000000..832652a --- /dev/null +++ b/backend/requirements.txt @@ -0,0 +1,7 @@ +Django==5.2.17 +argon2-cffi>=25.1,<26 +gunicorn>=23.0,<24 +psycopg[binary]>=3.2,<3.3 +PyYAML>=6.0,<7 +whitenoise>=6.9,<7 + diff --git a/backend/static/brand/README.md b/backend/static/brand/README.md new file mode 100644 index 0000000..eb7800e --- /dev/null +++ b/backend/static/brand/README.md @@ -0,0 +1,8 @@ +# 纵横家用户门户品牌资源 + +复用公司已有客户端标识,不生成或改造商标图案,无外部 CDN 依赖。 + +- `zonghengjia.png`:来自 Windows 项目 `assets/zonghengjia-app-logo-v1.png`,替换网页原来的绿色 T 占位标识,同时用于 favicon。 +- `ucvl.png`:来自 Windows 项目 `assets/company-logo-original.png`,用于 Powered by 优创未来。 + +两张 PNG 按原始字节复制,透明背景不变;显示尺寸和移动端排版由 `css/portal-brand.css` 控制。 diff --git a/backend/static/brand/ucvl.png b/backend/static/brand/ucvl.png new file mode 100644 index 0000000..b64f330 Binary files /dev/null and b/backend/static/brand/ucvl.png differ diff --git a/backend/static/brand/zonghengjia.png b/backend/static/brand/zonghengjia.png new file mode 100644 index 0000000..f39d476 Binary files /dev/null and b/backend/static/brand/zonghengjia.png differ diff --git a/backend/static/css/app.css b/backend/static/css/app.css new file mode 100644 index 0000000..f61375b --- /dev/null +++ b/backend/static/css/app.css @@ -0,0 +1,121 @@ +:root { + --ink: #122018; + --muted: #64736a; + --paper: #f5f7f3; + --card: #ffffff; + --line: #dfe6df; + --brand: #1d6b47; + --brand-dark: #144d35; + --accent: #d6f56d; + --danger: #b94343; + --warning: #a56a10; + --shadow: 0 18px 50px rgba(22, 49, 35, .08); +} +* { box-sizing: border-box; } +html { min-height: 100%; background: var(--paper); } +body { margin: 0; min-height: 100vh; color: var(--ink); background: radial-gradient(circle at 85% 0%, rgba(214,245,109,.18), transparent 28%), var(--paper); font: 15px/1.6 -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; } +a { color: var(--brand); text-decoration: none; } +a:hover { color: var(--brand-dark); } +.shell { width: min(1180px, calc(100% - 40px)); margin: 0 auto; } +.site-header { background: rgba(255,255,255,.9); border-bottom: 1px solid var(--line); backdrop-filter: blur(14px); position: sticky; top: 0; z-index: 20; } +.header-inner { min-height: 72px; display: flex; align-items: center; justify-content: space-between; } +.brand { display: flex; align-items: center; gap: 11px; color: var(--ink); } +.brand-mark { width: 39px; height: 39px; border-radius: 12px; display: grid; place-items: center; color: #fff; font-weight: 800; background: var(--brand); box-shadow: 0 8px 22px rgba(29,107,71,.22); } +.brand strong, .brand small { display: block; line-height: 1.15; } +.brand strong { letter-spacing: .03em; } +.brand small { color: var(--muted); margin-top: 4px; font-size: 11px; } +.nav { display: flex; align-items: center; gap: 22px; } +.nav form { margin: 0; } +.nav a, .link-button { color: #405047; font-weight: 600; } +.link-button { border: 0; background: transparent; cursor: pointer; padding: 0; font: inherit; } +.nav-primary { border: 1px solid var(--brand); border-radius: 999px; padding: 7px 16px; } +.page { min-height: calc(100vh - 146px); padding: 58px 0 80px; } +.site-footer { border-top: 1px solid var(--line); color: var(--muted); padding: 24px 0; font-size: 13px; } +.eyebrow, .card-kicker { display: block; color: var(--brand); font-size: 12px; font-weight: 800; letter-spacing: .14em; text-transform: uppercase; } +h1, h2, p { margin-top: 0; } +h1 { font-size: clamp(34px, 5vw, 58px); line-height: 1.12; letter-spacing: -.04em; margin-bottom: 18px; } +h2 { font-size: 22px; line-height: 1.25; letter-spacing: -.02em; } +.muted { color: var(--muted); } +.auth-layout { min-height: 580px; display: grid; grid-template-columns: 1.15fr .85fr; gap: 9vw; align-items: center; } +.auth-copy > p { max-width: 620px; font-size: 17px; color: var(--muted); } +.feature-line { display: flex; align-items: center; gap: 16px; padding: 15px 0; border-top: 1px solid var(--line); max-width: 540px; font-weight: 650; } +.feature-line span { color: var(--brand); font-size: 12px; font-weight: 800; } +.auth-card, .narrow-card, .card { background: var(--card); border: 1px solid rgba(216,226,217,.9); border-radius: 24px; box-shadow: var(--shadow); } +.auth-card { padding: 42px; } +.narrow-card { max-width: 780px; margin: 0 auto; padding: 46px; } +.narrow-card.compact { max-width: 620px; } +.form-grid { display: grid; gap: 18px; } +.form-grid.two-column { grid-template-columns: 1fr 1fr; } +.form-grid .full { grid-column: 1 / -1; } +.form-grid label, .form-grid p { display: grid; gap: 7px; font-weight: 700; margin: 0; } +input, select, textarea { width: 100%; border: 1px solid #cfd9d1; background: #fbfcfa; color: var(--ink); border-radius: 12px; padding: 12px 14px; font: inherit; outline: none; transition: border .15s, box-shadow .15s; } +input:focus, select:focus, textarea:focus { border-color: var(--brand); box-shadow: 0 0 0 4px rgba(29,107,71,.1); } +input[type="checkbox"] { width: auto; } +.checkbox-label { display: flex !important; flex-direction: row; align-items: center; font-weight: 500 !important; } +.form-grid small, .helptext { color: var(--muted); font-weight: 400; font-size: 12px; } +.form-grid ul { margin: 0; padding-left: 19px; color: var(--muted); font-size: 12px; font-weight: 400; } +.field-error, .errorlist { color: var(--danger) !important; font-size: 13px; } +.errorlist { margin: 0; } +.form-error { border-radius: 12px; background: #fff1f1; color: var(--danger); padding: 12px 14px; } +.button { appearance: none; border: 1px solid transparent; border-radius: 12px; padding: 11px 18px; font: inherit; font-weight: 750; cursor: pointer; display: inline-flex; justify-content: center; align-items: center; } +.button.primary { background: var(--brand); color: white; } +.button.primary:hover { background: var(--brand-dark); color: white; } +.button.secondary { color: var(--brand); border-color: #bdd0c3; background: #f5faf6; } +.button.ghost { color: var(--muted); background: transparent; } +.button.wide { width: 100%; } +.auth-foot { margin: 23px 0 0; text-align: center; color: var(--muted); } +.hero-row, .section-title, .card-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 24px; } +.hero-row h1 { font-size: 42px; margin: 8px 0; } +.status-pill { display: inline-flex; align-items: center; border-radius: 999px; padding: 5px 11px; font-size: 12px; font-weight: 800; background: #eef1ef; color: #5a665f; white-space: nowrap; } +.status-pill.success { background: #e6f5eb; color: #1f754a; } +.status-pill.warning { background: #fff3d9; color: #94610c; } +.status-pill.danger { background: #ffebeb; color: #a43b3b; } +.dashboard-grid { display: grid; grid-template-columns: 2fr 1fr; gap: 20px; margin-top: 30px; } +.card { padding: 28px; } +.card h2 { margin: 7px 0 0; } +.metrics { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; margin: 28px 0 20px; } +.metrics div { background: #f6f8f5; border-radius: 16px; padding: 16px; } +.metrics small, .metrics strong { display: block; } +.metrics small { color: var(--muted); margin-bottom: 6px; } +.metrics strong { font-size: 19px; } +.progress { height: 8px; overflow: hidden; border-radius: 99px; background: #e9eee9; } +.progress span { display: block; height: 100%; background: linear-gradient(90deg, var(--brand), #79a93a); border-radius: inherit; } +.detail-list { margin: 25px 0 0; } +.detail-list div { display: flex; justify-content: space-between; border-top: 1px solid var(--line); padding: 13px 0; } +.detail-list dt { color: var(--muted); } +.detail-list dd { margin: 0; font-weight: 750; } +.subscription-card { margin-top: 20px; } +.copy-row { margin-top: 22px; display: grid; grid-template-columns: 1fr auto; gap: 10px; } +.copy-row input { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; } +.notice-line, .empty-note { border-radius: 12px; padding: 11px 14px; background: #fff7e8; color: #855811; margin: 16px 0 0; } +.empty-state { text-align: center; background: white; border: 1px dashed #b7c7ba; border-radius: 24px; padding: 64px 24px; margin-top: 28px; } +.empty-icon { width: 54px; height: 54px; margin: 0 auto 18px; display: grid; place-items: center; border-radius: 18px; color: var(--brand); background: #eaf5ed; font-size: 26px; } +.section-block { margin-top: 46px; } +.section-title { align-items: center; margin-bottom: 18px; } +.section-title h2 { margin: 6px 0 0; } +.table-wrap { overflow-x: auto; background: white; border: 1px solid var(--line); border-radius: 18px; } +table { border-collapse: collapse; width: 100%; } +th, td { text-align: left; border-bottom: 1px solid var(--line); padding: 14px 17px; } +th { color: var(--muted); font-size: 12px; letter-spacing: .05em; } +tr:last-child td { border-bottom: 0; } +.message-stack { display: grid; gap: 8px; margin-bottom: 24px; } +.message { padding: 12px 15px; border-radius: 12px; background: #e9f4ec; color: #236845; } +.message.error { background: #ffeded; color: #a43b3b; } +@media (max-width: 850px) { + .auth-layout, .dashboard-grid { grid-template-columns: 1fr; } + .auth-layout { gap: 36px; } + .metrics { grid-template-columns: 1fr 1fr; } + .form-grid.two-column { grid-template-columns: 1fr; } + .form-grid .full { grid-column: auto; } +} +@media (max-width: 580px) { + .shell { width: min(100% - 24px, 1180px); } + .page { padding-top: 34px; } + .nav { gap: 12px; font-size: 13px; } + .auth-copy { display: none; } + .auth-card, .narrow-card, .card { padding: 23px; border-radius: 18px; } + .hero-row h1 { font-size: 32px; } + .metrics { grid-template-columns: 1fr; } + .copy-row { grid-template-columns: 1fr; } +} + diff --git a/backend/static/css/node_traffic.css b/backend/static/css/node_traffic.css new file mode 100644 index 0000000..e4aec8d --- /dev/null +++ b/backend/static/css/node_traffic.css @@ -0,0 +1,233 @@ +:root { + --traffic-navy: #08234a; + --traffic-blue: #1478e6; + --traffic-cyan: #09b7dc; + --traffic-green: #0c9b71; + --traffic-red: #d64a61; + --traffic-muted: #6d8299; + --traffic-border: #d8e5f0; + --traffic-bg: #f2f7fb; +} + +#content { padding: 0; } +#content-main { float: none; } + +.traffic-monitor { + min-height: calc(100vh - 120px); + padding: 28px clamp(18px, 3vw, 48px) 44px; + color: var(--traffic-navy); + background: + radial-gradient(circle at 88% 2%, rgba(9, 183, 220, .13), transparent 28%), + linear-gradient(180deg, #f8fbfe 0%, var(--traffic-bg) 100%); + box-sizing: border-box; +} + +.traffic-hero, +.traffic-toolbar, +.traffic-chart-heading, +.traffic-help, +.traffic-summary, +.traffic-node-strip { display: flex; } + +.traffic-hero { + justify-content: space-between; + align-items: flex-start; + gap: 24px; + margin-bottom: 22px; +} + +.traffic-eyebrow { + color: var(--traffic-blue); + font-size: 13px; + font-weight: 800; + letter-spacing: .08em; +} + +.traffic-hero h1 { + margin: 7px 0 8px; + font-size: clamp(26px, 3vw, 38px); + line-height: 1.15; + color: var(--traffic-navy); +} + +.traffic-hero p { + max-width: 760px; + margin: 0; + color: var(--traffic-muted); + font-size: 15px; + line-height: 1.7; +} + +.traffic-live { + display: inline-flex; + align-items: center; + gap: 9px; + flex: 0 0 auto; + padding: 10px 14px; + border: 1px solid #cfe9df; + border-radius: 999px; + color: var(--traffic-green); + background: #edf9f5; + font-weight: 700; +} + +.traffic-live i, +.node-online-dot { + width: 9px; + height: 9px; + border-radius: 50%; + background: currentColor; + box-shadow: 0 0 0 5px rgba(12, 155, 113, .12); +} +.node-online-dot { color: var(--traffic-green); } + +.traffic-live.is-error { color: var(--traffic-red); border-color: #f0ccd3; background: #fff2f4; } + +.traffic-toolbar { + align-items: center; + justify-content: space-between; + gap: 18px; + margin-bottom: 18px; +} + +.traffic-range { + display: inline-flex; + gap: 4px; + padding: 4px; + border: 1px solid var(--traffic-border); + border-radius: 12px; + background: #fff; +} + +.traffic-range button { + min-width: 76px; + padding: 8px 13px; + border: 0; + border-radius: 8px; + color: #60758a; + background: transparent; + cursor: pointer; + font: inherit; + font-weight: 700; +} + +.traffic-range button.is-active { color: #fff; background: var(--traffic-blue); box-shadow: 0 4px 12px rgba(20, 120, 230, .25); } +.traffic-refresh { display: flex; gap: 12px; color: var(--traffic-muted); font-size: 13px; } +.traffic-refresh b { color: var(--traffic-blue); } + +.traffic-node-strip { + gap: 12px; + overflow-x: auto; + padding: 2px 2px 12px; + scrollbar-width: thin; +} + +.traffic-node, +.traffic-loading { + min-width: 245px; + border: 1px solid var(--traffic-border); + border-radius: 15px; + padding: 15px 17px; + background: rgba(255, 255, 255, .88); + box-sizing: border-box; +} + +.traffic-node { text-align: left; color: var(--traffic-navy); cursor: pointer; font: inherit; transition: transform .18s, border-color .18s, box-shadow .18s; } +.traffic-node:hover { transform: translateY(-2px); border-color: #a9cdec; } +.traffic-node.is-active { border-color: var(--traffic-blue); box-shadow: 0 8px 24px rgba(21, 95, 164, .13); } +.traffic-node-head { display: flex; justify-content: space-between; gap: 10px; } +.traffic-node-name { display: flex; align-items: center; gap: 9px; font-size: 16px; font-weight: 800; } +.traffic-node.is-offline .node-online-dot { color: var(--traffic-red); box-shadow: 0 0 0 5px rgba(214, 74, 97, .1); } +.traffic-node-region { display: block; margin: 7px 0 11px 18px; color: var(--traffic-muted); font-size: 12px; } +.traffic-node-speed { display: flex; justify-content: space-between; gap: 12px; color: #48647d; font-size: 12px; } +.traffic-node-speed b { display: block; margin-top: 3px; color: var(--traffic-navy); font-size: 14px; } + +.traffic-loading { min-width: 100%; color: var(--traffic-muted); text-align: center; } + +.traffic-summary { + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + gap: 14px; + margin: 8px 0 16px; +} + +.metric-card { + position: relative; + overflow: hidden; + padding: 18px 20px; + border: 1px solid var(--traffic-border); + border-radius: 16px; + background: #fff; + box-shadow: 0 7px 24px rgba(15, 65, 105, .05); +} + +.metric-card::after { + position: absolute; + content: ""; + top: 0; right: 0; + width: 72px; height: 72px; + border-radius: 0 0 0 72px; + background: rgba(20, 120, 230, .06); +} + +.metric-card--down::after { background: rgba(20, 120, 230, .11); } +.metric-card--up::after { background: rgba(9, 183, 220, .12); } +.metric-card span { color: var(--traffic-muted); font-size: 13px; font-weight: 700; } +.metric-card strong { display: block; margin: 8px 0 5px; color: var(--traffic-navy); font-size: clamp(22px, 2.2vw, 31px); line-height: 1; } +.metric-card small { color: #8a9bad; } + +.traffic-chart-card { + padding: 22px 24px 18px; + border: 1px solid var(--traffic-border); + border-radius: 18px; + background: #fff; + box-shadow: 0 9px 30px rgba(15, 65, 105, .06); +} + +.traffic-chart-heading { align-items: flex-start; justify-content: space-between; gap: 20px; } +.traffic-chart-heading h2 { margin: 5px 0 0; color: var(--traffic-navy); font-size: 21px; } +.traffic-legend { display: flex; gap: 18px; color: var(--traffic-muted); font-size: 13px; } +.traffic-legend span { display: inline-flex; align-items: center; gap: 7px; } +.traffic-legend i { width: 22px; height: 3px; border-radius: 4px; } +.legend-download { background: var(--traffic-blue); } +.legend-upload { background: var(--traffic-cyan); } + +.traffic-chart-wrap { position: relative; height: clamp(280px, 40vh, 430px); margin-top: 16px; } +#traffic-chart { display: block; width: 100%; height: 100%; } +.traffic-empty { position: absolute; inset: 0; display: grid; place-items: center; color: #8da0b1; pointer-events: none; } +.traffic-tooltip { position: absolute; z-index: 3; min-width: 150px; padding: 9px 11px; border: 1px solid var(--traffic-border); border-radius: 9px; color: var(--traffic-navy); background: rgba(255,255,255,.96); box-shadow: 0 8px 22px rgba(8,35,74,.14); font-size: 12px; pointer-events: none; } +.traffic-tooltip b { display: block; margin-bottom: 4px; } +.traffic-tooltip span { display: block; line-height: 1.6; } + +.traffic-help { + align-items: center; + gap: 28px; + margin-top: 16px; + padding: 16px 20px; + border: 1px solid #dbe8f2; + border-radius: 14px; + color: var(--traffic-muted); + background: rgba(255,255,255,.68); +} +.traffic-help div { display: flex; gap: 8px; flex: 1; } +.traffic-help b { flex: 0 0 auto; color: var(--traffic-navy); } +.traffic-help a { flex: 0 0 auto; padding: 9px 14px; border-radius: 9px; color: #fff; background: var(--traffic-blue); text-decoration: none; font-weight: 700; } + +@media (max-width: 980px) { + .traffic-summary { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .traffic-help { align-items: stretch; flex-direction: column; gap: 10px; } + .traffic-help a { align-self: flex-start; } +} + +@media (max-width: 650px) { + .traffic-monitor { padding: 18px 12px 30px; } + .traffic-hero, .traffic-toolbar { align-items: stretch; flex-direction: column; } + .traffic-live { align-self: flex-start; } + .traffic-range { display: grid; grid-template-columns: repeat(4, 1fr); } + .traffic-range button { min-width: 0; padding-inline: 7px; } + .traffic-refresh { justify-content: space-between; } + .traffic-summary { grid-template-columns: 1fr; } + .traffic-chart-card { padding: 18px 12px 12px; } + .traffic-chart-heading { align-items: flex-start; flex-direction: column; } + .traffic-chart-wrap { height: 300px; } +} diff --git a/backend/static/css/portal-brand.css b/backend/static/css/portal-brand.css new file mode 100644 index 0000000..bd1aede --- /dev/null +++ b/backend/static/css/portal-brand.css @@ -0,0 +1,159 @@ +/* Shared portal brand layer; no external fonts, icon services or scripts. */ +:root { + --ink: #142d52; --muted: #61738f; --paper: #f4f8fe; --line: #dce7f5; + --brand: #095fe5; --brand-dark: #0648b0; --accent: #06b6e8; + --shadow: 0 4px 18px rgba(29,71,133,.045); +} +body { background: radial-gradient(ellipse at 85% 0%, #e5f3ff 0, transparent 40%), var(--paper); font-size: 14px; line-height: 1.65; } +:focus-visible { outline: 3px solid #0078d4; outline-offset: 4px; } +.shell { width: min(1160px, calc(100% - 48px)); } +.skip-link { position: absolute; left: 20px; top: -70px; padding: 10px 16px; background: white; z-index: 50; } +.skip-link:focus { top: 10px; } +.site-header { background: rgba(255,255,255,.94); position: static; } +.header-inner { min-height: 86px; gap: 24px; } +.brand { gap: 12px; flex-shrink: 0; } +.brand-mark { width: 52px; height: 52px; object-fit: contain; background: none; box-shadow: none; border-radius: 0; } +.brand strong, .brand small { line-height: 1.3; } +.brand strong { font-size: 23px; letter-spacing: .025em; color: #102e60; } +.brand small { font-size: 12px; letter-spacing: .08em; } +.company-brand { display: flex; align-items: center; gap: 10px; font-size: 13px; } +.company-brand img { object-fit: contain; } +.company-brand b { font-weight: 600; white-space: nowrap; } +.company-brand small { display: block; color: var(--muted); font-size: 10px; letter-spacing: .16em; } +.nav-bar { border-top: 1px solid #edf3fa; background: #fbfdff; } +.nav-inner { display: flex; align-items: center; justify-content: space-between; gap: 16px; min-height: 46px; } +.nav-caption { color: var(--muted); font-size: 12px; } +.nav { flex-wrap: wrap; gap: 4px 20px; } +.nav a, .link-button { color: #46607f; padding: 10px 0; display: inline-block; } +.nav [aria-current="page"] { color: var(--brand); box-shadow: inset 0 -2px var(--brand); } +.nav a:hover, .link-button:hover { color: var(--brand); } +.nav a.nav-primary { padding: 5px 14px; border: 0; border-radius: 8px; color: var(--brand); background: #eaf3ff; } +.page { min-height: calc(100vh - 207px); padding: 32px 0 48px; } +.site-footer { padding: 20px 0; font-size: 12px; background: #f9fbff; } +.footer-inner { display: flex; justify-content: space-between; gap: 16px; } +.eyebrow, .card-kicker { font-size: 11px; font-weight: 750; letter-spacing: .1em; } +h1 { font-size: clamp(28px, 3.2vw, 40px); line-height: 1.4; letter-spacing: -.025em; margin-bottom: 16px; } +h2 { font-size: 20px; line-height: 1.4; } +.icon { width: 24px; height: 24px; flex-shrink: 0; } +.auth-layout { min-height: 510px; grid-template-columns: 1.1fr 1fr; gap: 70px; } +.auth-copy .eyebrow { margin-bottom: 14px; } +.auth-copy > p { max-width: 510px; font-size: 15px; } +.feature-line { max-width: 480px; font-weight: 500; } +.auth-card, .narrow-card, .card { min-width: 0; border-color: var(--line); border-radius: 16px; } +.auth-card, .narrow-card { padding: 34px; } +.narrow-card.compact { max-width: 640px; } +.form-grid label, .form-grid p { font-weight: 650; min-width: 0; } +input, select, textarea { min-width: 0; border-color: #c9d8ea; background: #fbfdff; border-radius: 9px; padding: 11px 13px; } +input:focus, select:focus, textarea:focus { box-shadow: 0 0 0 3px #095fe512; } +.form-error { border-radius: 9px; } +.button { border-radius: 9px; padding: 10px 18px; font-weight: 650; gap: 8px; min-height: 42px; } +.button .icon { width: 18px; height: 18px; } +.button.primary { background: linear-gradient(120deg, #0870f5, #095bda); box-shadow: 0 3px 8px #095fe51a; } +.button.secondary { border-color: #cadcf6; background: #f5f9ff; } +.button.secondary:hover { background: #eaf3ff; } +.wecom-login { margin-top: 14px; } +.hero-row, .section-title, .card-head { gap: 20px; } +.hero-row { align-items: center; margin-bottom: 24px; } +.hero-row h1 { font-size: 28px; margin: 3px 0 6px; overflow-wrap: anywhere; } +.hero-row p { margin-bottom: 0; } +.account-meta { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; color: var(--muted); overflow-wrap: anywhere; } +.identity-badge { background: #e5efff; color: #1658ab; border-radius: 6px; padding: 2px 9px; font-size: 12px; } +.status-pill { padding: 4px 10px; font-weight: 650; background: #edf1f7; color: #5d6c82; } +.status-pill.success { background: #e5f6ef; color: #147653; } +.status-pill.warning { background: #fff2d7; color: #805509; } +.account-status { display: flex; align-items: center; gap: 9px; color: var(--muted); font-size: 12px; flex-shrink: 0; } +.dashboard-grid { gap: 18px; margin-top: 0; } +.card { padding: 24px; } +.card h2 { margin: 5px 0 0; } +.heading-icon { display: flex; align-items: center; gap: 12px; } +.icon-tile { display: inline-flex; align-items: center; justify-content: center; width: 44px; height: 44px; flex-shrink: 0; border: 1px solid #dfebff; border-radius: 12px; background: #f0f6ff; color: var(--brand); } +.metrics { grid-template-columns: repeat(2, 1fr); margin: 22px 0 16px; } +.metrics div { background: #f6f9fe; border-radius: 10px; padding: 14px; } +.metrics small { margin-bottom: 5px; } +.metrics strong { font-size: 20px; color: #155fca; overflow-wrap: anywhere; } +.progress { height: 7px; background: #e8eff9; } +.progress span { max-width: 100%; background: linear-gradient(90deg, var(--brand), var(--accent)); } +.detail-list { margin-top: 20px; } +.detail-list div { gap: 12px; padding: 12px 0; } +.detail-list dd { font-weight: 650; } +.subscription-card { margin-top: 18px; } +.subscription-card h2 { font-size: 18px; } +.subscription-card p { margin-bottom: 0; } +.copy-row { margin-top: 18px; } +.copy-feedback { min-height: 20px; font-size: 12px; color: var(--muted); margin: 6px 0 0; } +.notice-line, .empty-note { border-radius: 9px; padding: 10px 13px; background: #fff8e9; color: #805510; margin: 14px 0; font-size: 13px; } +.empty-state { display: grid; grid-template-columns: 1.35fr 1fr; gap: 36px; text-align: left; background: linear-gradient(115deg, #fff 45%, #f2f8ff); border: 1px solid var(--line); border-radius: 16px; padding: 30px; margin-top: 0; box-shadow: var(--shadow); } +.empty-state h2 { font-size: 24px; margin: 12px 0 8px; } +.empty-state p { color: var(--muted); max-width: 470px; margin-bottom: 18px; } +.setup-steps { list-style: none; margin: 0; padding: 4px 0 4px 30px; border-left: 1px solid var(--line); display: grid; align-content: center; gap: 20px; } +.setup-steps li { display: flex; align-items: flex-start; gap: 12px; } +.step-number { display: grid; place-items: center; width: 28px; height: 28px; flex-shrink: 0; background: #e9f2ff; border-radius: 8px; color: var(--brand); font-size: 12px; font-weight: 750; } +.setup-steps small { display: block; color: var(--muted); font-size: 12px; margin-top: 3px; } +.section-block { margin-top: 26px; } +.lifecycle { margin-bottom: 20px; } +.lifecycle-track { display: flex; list-style: none; padding: 0; margin: 20px 0; gap: 0; overflow-x: auto; } +.lifecycle-track li { flex: 1; min-width: 90px; display: flex; flex-direction: column; align-items: center; gap: 8px; border-top: 3px solid #e1e9f4; padding: 12px 6px 2px; color: #64748b; font-size: 13px; text-align: center; } +.lifecycle-track li.done { border-color: #329f87; color: #176c55; } +.lifecycle-track li.current { border-color: #095fe5; color: #095fe5; font-weight: 700; background: #eef5ff; border-radius: 0 0 8px 8px; } +.lifecycle-dot { display: grid; place-items: center; width: 26px; height: 26px; border: 1px solid currentColor; border-radius: 50%; } +.lifecycle.attention .notice-line { color: #895700; background: #fff9eb; } +.team-shortcuts { margin: 0 0 20px; flex-wrap: wrap; gap: 14px; } +.section-title { margin-bottom: 14px; } +.section-title h2 { margin: 0; font-size: 18px; } +.section-title .icon { color: var(--brand); width: 21px; height: 21px; } +.section-subtitle { color: var(--muted); margin: 4px 0 0; font-size: 12px; } +.plan-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 280px), 1fr)); gap: 16px; } +.plan-card { display: flex; flex-direction: column; } +.plan-card h2 { font-size: 18px; } +.plan-card .plan-label { color: var(--brand); font-size: 17px; font-weight: 650; margin: 16px 0 10px; } +.plan-card .button { margin-top: auto; align-self: flex-start; } +.plan-card .muted { font-size: 13px; } +.table-wrap { border-radius: 12px; } +th, td { padding: 13px 16px; } +th { background: #f8fbff; white-space: nowrap; } +td { font-size: 13px; } +.records-empty { display: flex; align-items: center; gap: 16px; padding: 22px 24px; } +.records-empty p { margin: 3px 0 0; font-size: 13px; } +.message { border-radius: 9px; } +@media (max-width: 900px) { + .auth-layout { gap: 32px; } + .dashboard-grid { grid-template-columns: 1fr; } + .nav-caption { display: none; } + .nav-inner { justify-content: flex-end; } +} +@media (max-width: 640px) { + .shell { width: calc(100% - 28px); } + .page { padding: 24px 0 32px; } + .header-inner { min-height: 78px; gap: 12px; } + .brand { gap: 8px; } + .brand strong { font-size: 19px; } + .brand small { font-size: 10px; } + .brand-mark { width: 42px; height: 48px; } + .company-brand { font-size: 10px; gap: 6px; } + .company-brand img { width: 28px; height: 26px; } + .company-brand small { display: none; } + .company-brand > span { max-width: 68px; } + .company-brand .powered-label { display: block; } + .nav { gap: 0 16px; font-size: 12px; } + .nav-inner { justify-content: flex-start; } + .auth-layout, .empty-state { grid-template-columns: 1fr; } + .auth-layout { min-height: 0; } + .auth-copy { display: none; } + .auth-card, .narrow-card, .card { padding: 20px; border-radius: 12px; } + .hero-row { gap: 12px; flex-wrap: wrap; margin-bottom: 18px; } + .hero-row h1 { font-size: 24px; } + .account-meta { font-size: 12px; } + .empty-state { padding: 22px; gap: 22px; } + .empty-state h2 { font-size: 22px; } + .setup-steps { border-left: 0; border-top: 1px solid var(--line); padding: 20px 0 0; gap: 16px; } + .form-grid.two-column { grid-template-columns: 1fr; } + .form-grid .full { grid-column: auto; } + .metrics { grid-template-columns: 1fr 1fr; } + .metrics strong { font-size: 18px; } + .lifecycle-track li { min-width: 0; padding: 10px 2px 2px; font-size: 11px; } + .copy-row { grid-template-columns: 1fr; } + .section-title { gap: 12px; } + .section-title .button { padding: 8px 12px; font-size: 12px; } + .footer-inner { flex-direction: column; gap: 4px; } +} +@media (prefers-reduced-motion: reduce) { *, *::before, *::after { transition: none !important; scroll-behavior: auto !important; } } diff --git a/backend/static/css/vpn_admin_dashboard.css b/backend/static/css/vpn_admin_dashboard.css new file mode 100644 index 0000000..a2b5a22 --- /dev/null +++ b/backend/static/css/vpn_admin_dashboard.css @@ -0,0 +1,144 @@ +:root { + --vpn-navy: #062247; + --vpn-blue: #087fda; + --vpn-cyan: #12b9ea; + --vpn-line: #a9c9df; + --vpn-bg: #f3f7fb; + --vpn-ok: #16875b; + --vpn-warn: #b66b00; + --vpn-bad: #bf3e4c; +} + +#content { padding: 0; } +#content-main { float: none; width: auto; } +.vpn-dashboard { background: var(--vpn-bg); min-height: calc(100vh - 70px); padding: 26px clamp(18px, 3vw, 46px) 46px; color: #17334f; } +.dashboard-hero { display: flex; align-items: stretch; justify-content: space-between; gap: 28px; margin-bottom: 22px; } +.dashboard-hero h1 { margin: 5px 0 7px; color: var(--vpn-navy); font-size: clamp(25px, 2.4vw, 38px); line-height: 1.2; } +.dashboard-hero p { margin: 0; color: #60778c; font-size: 15px; } +.eyebrow, .step-label { color: var(--vpn-blue); font-weight: 700; letter-spacing: .08em; } +.next-action { align-items: flex-start; background: #fff; border: 1px solid #dce8f1; border-left: 5px solid var(--vpn-ok); border-radius: 14px; box-shadow: 0 8px 24px rgba(28, 67, 99, .08); color: #39536b !important; display: flex; flex-direction: column; justify-content: center; min-width: 300px; padding: 15px 20px; text-decoration: none; } +.next-action.is-warning { border-left-color: var(--vpn-warn); } +.next-action span { color: #7890a5; font-size: 12px; } +.next-action strong { color: var(--vpn-navy); font-size: 16px; margin-top: 4px; } + +.workflow-tabs { background: #dfeaf2; border: 1px solid #cadbe7; border-radius: 16px; display: grid; gap: 1px; grid-template-columns: repeat(4, minmax(0, 1fr)); margin-bottom: 22px; overflow: hidden; padding: 1px; } +.workflow-tab { background: #f8fbfd; border: 0; color: #536e84; cursor: pointer; display: flex; flex-direction: column; min-height: 88px; padding: 14px 18px; position: relative; text-align: left; } +.workflow-tab::after { background: transparent; bottom: 0; content: ""; height: 4px; left: 0; position: absolute; right: 0; } +.workflow-tab:hover { background: #fff; } +.workflow-tab:focus-visible { box-shadow: inset 0 0 0 3px rgba(8, 127, 218, .35); outline: 0; z-index: 2; } +.workflow-tab.is-active { background: #fff; color: var(--vpn-blue); } +.workflow-tab.is-active::after { background: linear-gradient(90deg, var(--vpn-cyan), var(--vpn-blue)); } +.workflow-tab span { font-size: 11px; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; } +.workflow-tab strong { color: var(--vpn-navy); font-size: 17px; margin: 3px 0 4px; } +.workflow-tab small { color: #748a9c; font-size: 12px; } +.workflow-tab-panel[hidden] { display: none; } + +.workflow-panel { background: #fff; border: 1px solid #dbe7f0; border-radius: 18px; box-shadow: 0 10px 30px rgba(16, 55, 86, .07); margin-bottom: 22px; overflow: hidden; padding: 22px 22px 8px; } +.workflow-panel--ai { border-top: 4px solid var(--vpn-cyan); } +.workflow-panel--nodes { border-top: 4px solid var(--vpn-blue); } +.workflow-panel--security { border-top: 4px solid var(--vpn-warn); } +.section-heading { align-items: center; display: flex; justify-content: space-between; gap: 18px; } +.section-heading h2 { color: var(--vpn-navy); font-size: 22px; margin: 3px 0 0; } +.section-heading p, .workflow-note { color: #6b8093; margin: 0; } +.workflow-note { background: #eef9fd; border-radius: 9px; margin-top: 14px; padding: 10px 13px; } +.runtime-pill { align-items: center; background: #fff4f4; border-radius: 999px; color: var(--vpn-bad); display: flex; font-weight: 700; gap: 7px; padding: 8px 13px; } +.runtime-pill i { background: currentColor; border-radius: 50%; height: 8px; width: 8px; } +.runtime-pill.is-ok { background: #eaf8f1; color: var(--vpn-ok); } + +.ai-flow-legend { display: flex; gap: 10px; justify-content: center; margin: 18px 0 6px; } +.ai-flow-legend span { border-radius: 999px; font-size: 11px; font-weight: 700; padding: 5px 11px; } +.legend-start { background: var(--vpn-navy); color: #fff; } +.legend-action { background: #e9f5fd; color: var(--vpn-blue); } +.legend-state { background: #fff5dc; color: #926000; } +.ai-action-flow { align-items: center; display: flex; flex-direction: column; margin: 10px auto 24px; max-width: 1120px; padding: 8px 14px; } +.ai-flow-terminal, .ai-flow-action, .ai-flow-state { border-radius: 14px; box-sizing: border-box; display: flex; flex-direction: column; min-height: 82px; justify-content: center; padding: 13px 18px; text-align: center; width: 400px; } +.ai-flow-terminal { background: linear-gradient(135deg, var(--vpn-navy), #0a4a82); color: #fff; width: 340px; } +.ai-flow-terminal--end { background: linear-gradient(135deg, var(--vpn-blue), #0d61ba); } +.ai-flow-terminal span, .ai-flow-action span, .ai-flow-state span { font-size: 11px; font-weight: 800; letter-spacing: .06em; } +.ai-flow-terminal strong, .ai-flow-action strong, .ai-flow-state strong { font-size: 15px; line-height: 1.35; margin-top: 4px; } +.ai-flow-action { background: #edf8ff; border: 2px solid #8dccf0; box-shadow: 0 7px 18px rgba(15, 99, 156, .08); color: var(--vpn-navy) !important; text-decoration: none; } +.ai-flow-action span { color: var(--vpn-blue); } +.ai-flow-action small, .ai-flow-state small, .ai-flow-side-result small { color: #71879a; font-size: 12px; margin-top: 4px; } +.ai-flow-action:hover { background: #e2f4ff; border-color: var(--vpn-blue); } +.ai-flow-state { background: #fff8e8; border: 2px solid #e6bd68; color: #543b0c; position: relative; } +.ai-flow-state::before { background: #fff8e8; border-left: 2px solid #e6bd68; border-top: 2px solid #e6bd68; content: ""; height: 18px; left: 50%; position: absolute; top: -11px; transform: translateX(-50%) rotate(45deg); width: 18px; } +.ai-flow-state span { color: #9a6807; } +.ai-flow-arrow { height: 39px; position: relative; width: 4px; } +.ai-flow-arrow::before { background: var(--vpn-blue); bottom: 7px; content: ""; left: 1px; position: absolute; top: 0; width: 2px; } +.ai-flow-arrow::after { border-left: 6px solid transparent; border-right: 6px solid transparent; border-top: 8px solid var(--vpn-blue); bottom: 0; content: ""; left: -4px; position: absolute; } +.ai-flow-arrow span { background: #fff; border: 1px solid #b8d6e9; border-radius: 999px; color: var(--vpn-blue); font-size: 11px; font-weight: 800; left: 13px; padding: 2px 7px; position: absolute; top: 8px; z-index: 2; } +.ai-flow-decision-row { display: grid; gap: 64px; grid-template-columns: 1fr 400px 1fr; position: relative; width: 100%; } +.ai-flow-state { grid-column: 2; } +.ai-flow-side-result { align-self: center; border: 1px solid; border-radius: 12px; display: flex; flex-direction: column; min-height: 70px; justify-content: center; padding: 11px 14px; position: relative; text-align: center; text-decoration: none; } +.ai-flow-side-result b { border-radius: 999px; color: currentColor; font-size: 11px; left: 50%; padding: 2px 7px; position: absolute; top: -12px; transform: translateX(-50%); } +.ai-flow-side-result strong { color: #183a58; font-size: 13px; } +.ai-flow-side-result--left { grid-column: 1; } +.ai-flow-side-result--right { grid-column: 3; } +.ai-flow-side-result--left::after, .ai-flow-side-result--right::before { border-top: 2px solid #9bc3da; content: ""; position: absolute; top: 50%; width: 64px; } +.ai-flow-side-result--left::after { right: -65px; } +.ai-flow-side-result--right::before { left: -65px; } +.ai-flow-side-result.status-ok b { background: #dff4e9; } +.ai-flow-side-result.status-warn b { background: #ffedc6; } +.ai-flow-side-result.status-bad b { background: #ffe0e3; } + +.fishbone-scroll { overflow-x: auto; padding: 12px 2px 2px; scrollbar-color: #b7cddd transparent; } +.fishbone { --stage-count: 5; height: 360px; min-width: 1190px; position: relative; } +.fishbone-spine { background: linear-gradient(90deg, var(--vpn-cyan), var(--vpn-blue)); border-radius: 8px; height: 8px; left: 112px; position: absolute; right: 112px; top: 184px; } +.fishbone-spine::after { border-bottom: 11px solid transparent; border-left: 18px solid var(--vpn-blue); border-top: 11px solid transparent; content: ""; position: absolute; right: -14px; top: -7px; } +.fishbone-start, .fishbone-end { background: var(--vpn-navy); border: 4px solid #d9ecf8; border-radius: 50%; color: white; display: flex; flex-direction: column; height: 90px; justify-content: center; position: absolute; text-align: center; top: 142px; width: 90px; z-index: 3; } +.fishbone-start { left: 0; } +.fishbone-end { right: 0; } +.fishbone-end { background: linear-gradient(135deg, var(--vpn-blue), #0c5db8); } +.fishbone-start span, .fishbone-end span { font-size: 11px; opacity: .72; } +.fishbone-start strong, .fishbone-end strong { font-size: 13px; line-height: 1.3; padding: 0 7px; } +.bone-stage { position: absolute; top: 0; transform: translateX(-50%); width: 170px; } +.stage-status { background: #f7fbfe; border: 1px solid #cfe2ef; border-radius: 11px; box-shadow: 0 6px 15px rgba(28, 75, 108, .07); color: #526c82 !important; display: flex; flex-direction: column; min-height: 53px; padding: 10px 12px; position: absolute; text-align: center; text-decoration: none; top: 8px; width: 146px; } +.stage-status::after { background: currentColor; content: ""; height: 50px; left: 50%; opacity: .35; position: absolute; top: 100%; width: 2px; } +.stage-status span { font-size: 11px; } +.stage-status strong { color: #183a58; font-size: 13px; line-height: 1.3; margin-top: 3px; } +.status-ok { background: #edf9f3; border-color: #bde3d1; color: var(--vpn-ok) !important; } +.status-warn { background: #fff7e9; border-color: #f0d39b; color: var(--vpn-warn) !important; } +.status-bad { background: #fff0f1; border-color: #efbec4; color: var(--vpn-bad) !important; } +.status-info { background: #eef8fd; border-color: #bfdeef; color: var(--vpn-blue) !important; } +.stage-node { align-items: center; background: white; border: 4px solid var(--vpn-blue); border-radius: 50%; box-shadow: 0 5px 15px rgba(8, 88, 151, .18); color: var(--vpn-navy) !important; display: flex; flex-direction: column; height: 78px; justify-content: center; left: 38px; position: absolute; text-align: center; text-decoration: none; top: 143px; width: 78px; z-index: 4; } +.stage-node:hover { background: #edf8ff; transform: translateY(-2px); } +.stage-node b { color: var(--vpn-blue); font-size: 12px; } +.stage-node span { font-size: 13px; font-weight: 700; line-height: 1.2; max-width: 68px; } +.stage-actions { background: #f8fbfd; border: 1px solid #d8e6ef; border-radius: 10px; display: flex; flex-direction: column; gap: 5px; left: 1px; min-height: 58px; padding: 10px 12px; position: absolute; top: 267px; width: 144px; } +.stage-actions::before { background: var(--vpn-line); content: ""; height: 64px; left: 50%; position: absolute; top: -65px; transform: rotate(31deg); transform-origin: bottom; width: 2px; z-index: 1; } +.stage-actions a, .stage-actions span { font-size: 12px; line-height: 1.25; position: relative; text-align: center; z-index: 2; } +.stage-actions a { color: #0869ae; font-weight: 650; text-decoration: none; } +.stage-actions span { color: #73899a; } + +.isolated-tools { display: grid; gap: 16px; grid-template-columns: repeat(3, minmax(0, 1fr)); } +.isolated-tools a { background: #fff; border: 1px solid #dbe7f0; border-radius: 14px; color: #4d667b !important; display: flex; flex-direction: column; min-height: 98px; padding: 17px 20px; text-decoration: none; } +.isolated-tools a:hover { border-color: #8bc9ea; box-shadow: 0 8px 24px rgba(21, 82, 123, .08); } +.isolated-tools span { color: var(--vpn-blue); font-size: 12px; font-weight: 700; } +.isolated-tools strong { color: var(--vpn-navy); font-size: 17px; margin: 5px 0; } +.isolated-tools small { color: #71879a; } + +@media (max-width: 900px) { + .vpn-dashboard { padding: 18px 12px 34px; } + .dashboard-hero, .section-heading { align-items: stretch; flex-direction: column; } + .next-action { min-width: 0; } + .isolated-tools { grid-template-columns: 1fr; } + .workflow-panel { padding-left: 14px; padding-right: 14px; } + .workflow-tabs { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .ai-flow-decision-row { gap: 24px; grid-template-columns: minmax(145px, 1fr) minmax(260px, 1.5fr) minmax(145px, 1fr); } + .ai-flow-terminal, .ai-flow-action, .ai-flow-state { max-width: 100%; width: 360px; } + .ai-flow-decision-row .ai-flow-state { width: auto; } + .ai-flow-side-result--left::after, .ai-flow-side-result--right::before { width: 24px; } + .ai-flow-side-result--left::after { right: -25px; } + .ai-flow-side-result--right::before { left: -25px; } +} + +@media (max-width: 520px) { + .workflow-tabs { display: flex; overflow-x: auto; } + .workflow-tab { flex: 0 0 190px; } + .ai-flow-legend { flex-wrap: wrap; } + .ai-action-flow { align-items: stretch; padding-left: 0; padding-right: 0; } + .ai-flow-terminal, .ai-flow-action, .ai-flow-state { margin: 0 auto; width: min(100%, 360px); } + .ai-flow-decision-row { display: flex; flex-direction: column; gap: 12px; } + .ai-flow-side-result { margin: 0 auto; order: 2; width: min(86%, 320px); } + .ai-flow-side-result--left::after, .ai-flow-side-result--right::before { display: none; } +} diff --git a/backend/static/js/node_traffic.js b/backend/static/js/node_traffic.js new file mode 100644 index 0000000..53de945 --- /dev/null +++ b/backend/static/js/node_traffic.js @@ -0,0 +1,214 @@ +(() => { + "use strict"; + + const root = document.querySelector(".traffic-monitor"); + if (!root) return; + + const endpoint = root.dataset.endpoint; + const nodeStrip = document.getElementById("traffic-nodes"); + const canvas = document.getElementById("traffic-chart"); + const empty = document.getElementById("traffic-empty"); + const tooltip = document.getElementById("traffic-tooltip"); + const ctx = canvas.getContext("2d"); + const state = { minutes: 60, nodes: [], selectedId: null, points: [] }; + let loading = false; + + const formatRate = (bytesPerSecond) => { + const bits = Number(bytesPerSecond || 0) * 8; + if (bits >= 1e9) return `${(bits / 1e9).toFixed(2)} Gbps`; + if (bits >= 1e6) return `${(bits / 1e6).toFixed(2)} Mbps`; + if (bits >= 1e3) return `${(bits / 1e3).toFixed(1)} Kbps`; + return `${Math.round(bits)} bps`; + }; + + const formatBytes = (bytes) => { + let value = Number(bytes || 0); + const units = ["B", "KB", "MB", "GB", "TB"]; + let unit = 0; + while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit += 1; } + return `${value.toFixed(unit === 0 ? 0 : value >= 100 ? 0 : value >= 10 ? 1 : 2)} ${units[unit]}`; + }; + + const formatTime = (value, includeDate = false) => { + if (!value) return "尚未上报"; + return new Intl.DateTimeFormat("zh-CN", { + month: includeDate ? "2-digit" : undefined, + day: includeDate ? "2-digit" : undefined, + hour: "2-digit", + minute: "2-digit", + second: includeDate ? undefined : "2-digit", + hour12: false, + }).format(new Date(value)); + }; + + const selectedNode = () => state.nodes.find((node) => node.id === state.selectedId) || state.nodes[0]; + + function renderNodes() { + if (!state.nodes.length) { + nodeStrip.innerHTML = '
尚未配置可用节点
'; + return; + } + nodeStrip.innerHTML = state.nodes.map((node) => ` + + `).join(""); + nodeStrip.querySelectorAll("[data-node-id]").forEach((button) => { + button.addEventListener("click", () => { + state.selectedId = Number(button.dataset.nodeId); + render(); + }); + }); + } + + function renderSummary(node) { + const set = (id, value) => { document.getElementById(id).textContent = value; }; + if (!node) { + ["current-download", "current-upload", "total-traffic", "active-subscriptions"].forEach((id) => set(id, "--")); + set("chart-title", "请选择节点"); + return; + } + set("current-download", formatRate(node.current_download_bytes_per_second)); + set("current-upload", formatRate(node.current_upload_bytes_per_second)); + set("total-traffic", formatBytes(node.total_upload_bytes + node.total_download_bytes)); + set("total-breakdown", `上传 ${formatBytes(node.total_upload_bytes)} · 下载 ${formatBytes(node.total_download_bytes)}`); + set("active-subscriptions", `${node.active_subscriptions} 个`); + set("last-seen", node.last_seen_at ? `最后上报 ${formatTime(node.last_seen_at)}` : "等待节点上报"); + set("chart-title", `${node.name} · ${node.region}`); + } + + function escapeHtml(value) { + return String(value ?? "").replace(/[&<>'"]/g, (char) => ({ + "&": "&", "<": "<", ">": ">", "'": "'", '"': """, + })[char]); + } + + function drawChart(node) { + const samples = node?.samples || []; + empty.hidden = samples.length > 0; + tooltip.hidden = true; + const rect = canvas.getBoundingClientRect(); + const dpr = Math.max(1, window.devicePixelRatio || 1); + canvas.width = Math.round(rect.width * dpr); + canvas.height = Math.round(rect.height * dpr); + ctx.setTransform(dpr, 0, 0, dpr, 0, 0); + ctx.clearRect(0, 0, rect.width, rect.height); + state.points = []; + if (!samples.length || rect.width < 120 || rect.height < 100) return; + + const pad = { top: 18, right: 18, bottom: 30, left: 67 }; + const width = rect.width - pad.left - pad.right; + const height = rect.height - pad.top - pad.bottom; + const start = Date.now() - state.minutes * 60 * 1000; + const end = Date.now(); + const maxBps = Math.max(1, ...samples.flatMap((sample) => [sample.upload_bytes_per_second, sample.download_bytes_per_second])); + const topBps = maxBps * 1.15; + const xFor = (at) => pad.left + Math.max(0, Math.min(1, (new Date(at).getTime() - start) / (end - start))) * width; + const yFor = (value) => pad.top + height - (Number(value || 0) / topBps) * height; + + ctx.font = "12px system-ui, sans-serif"; + ctx.lineWidth = 1; + for (let row = 0; row <= 4; row += 1) { + const y = pad.top + (height * row / 4); + ctx.strokeStyle = "#e6eef5"; + ctx.beginPath(); ctx.moveTo(pad.left, y); ctx.lineTo(rect.width - pad.right, y); ctx.stroke(); + ctx.fillStyle = "#8294a7"; + ctx.textAlign = "right"; + ctx.fillText(formatRate(topBps * (1 - row / 4)), pad.left - 10, y + 4); + } + for (let col = 0; col <= 4; col += 1) { + const x = pad.left + width * col / 4; + ctx.fillStyle = "#8294a7"; + ctx.textAlign = col === 0 ? "left" : col === 4 ? "right" : "center"; + ctx.fillText(formatTime(start + (end - start) * col / 4, state.minutes >= 1440), x, rect.height - 7); + } + + const drawSeries = (field, color, fillColor) => { + const gradient = ctx.createLinearGradient(0, pad.top, 0, pad.top + height); + gradient.addColorStop(0, fillColor); + gradient.addColorStop(1, "rgba(255,255,255,0)"); + ctx.beginPath(); + samples.forEach((sample, index) => { + const x = xFor(sample.at); const y = yFor(sample[field]); + index ? ctx.lineTo(x, y) : ctx.moveTo(x, y); + }); + const last = samples[samples.length - 1]; const first = samples[0]; + ctx.lineTo(xFor(last.at), pad.top + height); + ctx.lineTo(xFor(first.at), pad.top + height); + ctx.closePath(); ctx.fillStyle = gradient; ctx.fill(); + ctx.beginPath(); + samples.forEach((sample, index) => { + const x = xFor(sample.at); const y = yFor(sample[field]); + index ? ctx.lineTo(x, y) : ctx.moveTo(x, y); + }); + ctx.strokeStyle = color; ctx.lineWidth = 2.5; ctx.lineJoin = "round"; ctx.lineCap = "round"; ctx.stroke(); + }; + drawSeries("download_bytes_per_second", "#1478e6", "rgba(20,120,230,.16)"); + drawSeries("upload_bytes_per_second", "#09b7dc", "rgba(9,183,220,.09)"); + state.points = samples.map((sample) => ({ x: xFor(sample.at), sample })); + } + + function render() { + if (!state.selectedId && state.nodes.length) state.selectedId = state.nodes[0].id; + if (state.selectedId && !state.nodes.some((node) => node.id === state.selectedId)) state.selectedId = state.nodes[0]?.id || null; + renderNodes(); + const node = selectedNode(); + renderSummary(node); + drawChart(node); + } + + async function refresh() { + if (loading) return; + loading = true; + const live = document.getElementById("traffic-live"); + try { + const response = await fetch(`${endpoint}?minutes=${state.minutes}`, { credentials: "same-origin", cache: "no-store" }); + if (!response.ok) throw new Error(`HTTP ${response.status}`); + const data = await response.json(); + state.nodes = data.nodes || []; + live.classList.remove("is-error"); + live.querySelector("span").textContent = "监控数据连接正常"; + document.getElementById("traffic-updated").textContent = `刷新于 ${formatTime(data.generated_at)}`; + render(); + } catch (error) { + live.classList.add("is-error"); + live.querySelector("span").textContent = "监控数据暂时中断"; + } finally { + loading = false; + } + } + + document.querySelectorAll("[data-minutes]").forEach((button) => { + button.addEventListener("click", () => { + document.querySelectorAll("[data-minutes]").forEach((item) => item.classList.remove("is-active")); + button.classList.add("is-active"); + state.minutes = Number(button.dataset.minutes); + refresh(); + }); + }); + + canvas.addEventListener("mousemove", (event) => { + if (!state.points.length) return; + const rect = canvas.getBoundingClientRect(); + const mouseX = event.clientX - rect.left; + const point = state.points.reduce((best, candidate) => Math.abs(candidate.x - mouseX) < Math.abs(best.x - mouseX) ? candidate : best); + if (Math.abs(point.x - mouseX) > 36) { tooltip.hidden = true; return; } + tooltip.innerHTML = `${formatTime(point.sample.at, true)}下载 ${formatRate(point.sample.download_bytes_per_second)}上传 ${formatRate(point.sample.upload_bytes_per_second)}`; + tooltip.hidden = false; + tooltip.style.left = `${Math.min(rect.width - 175, Math.max(4, point.x + 10))}px`; + tooltip.style.top = "18px"; + }); + canvas.addEventListener("mouseleave", () => { tooltip.hidden = true; }); + window.addEventListener("resize", () => drawChart(selectedNode())); + + refresh(); + window.setInterval(refresh, 5000); +})(); diff --git a/backend/static/js/portal.js b/backend/static/js/portal.js new file mode 100644 index 0000000..00f1590 --- /dev/null +++ b/backend/static/js/portal.js @@ -0,0 +1,16 @@ +/* Subscription URLs are credentials: no logging, analytics or network calls. */ +document.querySelectorAll('[data-copy-target]').forEach(function (button) { + button.addEventListener('click', async function () { + const input = document.getElementById(button.dataset.copyTarget); + const feedback = document.getElementById('copy-feedback'); + if (!input) return; + try { + await navigator.clipboard.writeText(input.value); + if (feedback) feedback.textContent = '已复制订阅地址,请勿转发给他人。'; + } catch (_) { + input.focus(); + input.select(); + if (feedback) feedback.textContent = '浏览器未允许自动复制,已选中地址,请手动复制。'; + } + }); +}); diff --git a/backend/static/js/vpn_admin_dashboard.js b/backend/static/js/vpn_admin_dashboard.js new file mode 100644 index 0000000..f398bc5 --- /dev/null +++ b/backend/static/js/vpn_admin_dashboard.js @@ -0,0 +1,43 @@ +(function () { + "use strict"; + + const tabs = Array.from(document.querySelectorAll("[data-workflow-tab]")); + if (!tabs.length) return; + + const panels = new Map( + tabs.map((tab) => [tab.dataset.workflowTab, document.getElementById(tab.dataset.workflowTab)]) + ); + + function activate(tab, moveFocus) { + tabs.forEach((item) => { + const selected = item === tab; + item.classList.toggle("is-active", selected); + item.setAttribute("aria-selected", String(selected)); + item.tabIndex = selected ? 0 : -1; + const panel = panels.get(item.dataset.workflowTab); + if (panel) { + panel.hidden = !selected; + panel.classList.toggle("is-active", selected); + } + }); + if (moveFocus) tab.focus(); + if (history.replaceState) history.replaceState(null, "", `#${tab.dataset.workflowTab}`); + } + + tabs.forEach((tab, index) => { + tab.addEventListener("click", () => activate(tab, false)); + tab.addEventListener("keydown", (event) => { + let target = null; + if (event.key === "ArrowRight") target = tabs[(index + 1) % tabs.length]; + if (event.key === "ArrowLeft") target = tabs[(index - 1 + tabs.length) % tabs.length]; + if (event.key === "Home") target = tabs[0]; + if (event.key === "End") target = tabs[tabs.length - 1]; + if (!target) return; + event.preventDefault(); + activate(target, true); + }); + }); + + const initial = tabs.find((tab) => `#${tab.dataset.workflowTab}` === window.location.hash); + if (initial) activate(initial, false); +})(); diff --git a/backend/templates/admin/control/vpnairuntime/change_list.html b/backend/templates/admin/control/vpnairuntime/change_list.html new file mode 100644 index 0000000..bb4d7ba --- /dev/null +++ b/backend/templates/admin/control/vpnairuntime/change_list.html @@ -0,0 +1,65 @@ +{% extends "admin/change_list.html" %} +{% load i18n %} + +{% block content_title %} +

优创⁺纵横家 · vpn-ai 控制台

+{% endblock %} + +{% block result_list %} +
+

自动学习与规则分发

+

{% if learning.observations %}已接收观测{% else %}尚未收到客户端观测,不能认定自动学习正常{% endif %} · 最近观测:{{ learning.last_observation|default:"暂无" }}

+

近7天观测 {{ learning.observations }} → 代理TLS验证 {{ learning.verified }} → 已学习候选 {{ learning.learned }} → 近24小时已下发 {{ learning.offered }} 台 → 客户端确认缓存 {{ learning.cached }} 台(失败 {{ learning.failed }} 台)。

+

人工/预置规则 {{ learning.manual }} 条,单独统计,不计为AI学习。当前规则版本:{{ learning.revision|slice:":12" }}。

+

智能模式先直连。仅本机直连失败且代理TLS验证成功,才临时代理该精确目标;切网清除本地判断,超时重新学习。两台设备分别验证后形成共享候选,候选下发不等于全员强制代理。只收集目标域名或公网IP、端口与连接结果,不采集完整URL、请求内容或密码。TLS成功不代表已登录网站。新客户端每60秒同步,既有连接不搬迁。缓存数量是客户端回执,不是服务端直接验收。

+
+
+

vpn-ai 自动负载调度

+

当前启用的工作节点按近期负载分配;是否仅作备用由节点配置决定,不按国家判定。健康连接不因负载变化切换出口。在线心跳不代表端到端出口已验证;流量为节点上报值,会话预留不是实际 TCP 连接数。

+

更新:{{ vpn_ai_runtime.dispatch_snapshot.generated_at|default:"等待首次巡检" }}

+ + {% for node in vpn_ai_runtime.dispatch_snapshot.nodes %}{% endfor %} +
节点近期吞吐会话预留调度状态
{{ node.name }}{{ node.rate_text }}{{ node.reservations }}{{ node.reason }}
+
+
+
+
运行状态
+ + {% if vpn_ai_runtime.is_healthy %}正常运行{% else %}心跳异常{% endif %} + +
+
近 7 天观测
{{ vpn_ai_runtime.observations_7d|default:0 }}
+
生效智能规则
{{ vpn_ai_runtime.active_rules|default:0 }}
+
待处理诊断
{{ vpn_ai_runtime.open_findings|default:0 }}
+
+ +{% if vpn_ai_runtime.last_error %} +
最近错误:{{ vpn_ai_runtime.last_error }}
+{% endif %} + +
+

最近诊断

+ + + + {% for finding in recent_findings %} + + {% empty %}{% endfor %} + +
标题类别等级状态最近发现
{{ finding.title }}{{ finding.get_category_display }}{{ finding.get_severity_display }}{{ finding.get_status_display }}{{ finding.last_seen_at }}
暂无诊断记录。
+
+ +
+

最近智能代理规则

+ + + + {% for rule in recent_rules %} + + {% empty %}{% endfor %} + +
目标来源状态置信度设备数失败数
{{ rule.target }}{{ rule.get_source_display }}{{ rule.get_status_display }}{{ rule.confidence }}{{ rule.distinct_devices }}{{ rule.failure_reports }}
尚无智能代理规则。
+
+ +{{ block.super }} +{% endblock %} diff --git a/backend/templates/admin/login.html b/backend/templates/admin/login.html new file mode 100644 index 0000000..1bde392 --- /dev/null +++ b/backend/templates/admin/login.html @@ -0,0 +1,12 @@ +{% extends "admin/login.html" %} +{% block content %} +{{ block.super }} +{% if WECOM_AVAILABLE %} +
+
{% csrf_token %} + +
+

仅已绑定且具有后台权限的账号可以进入管理中心。

+
+{% endif %} +{% endblock %} diff --git a/backend/templates/admin/node_traffic.html b/backend/templates/admin/node_traffic.html new file mode 100644 index 0000000..64f4b0d --- /dev/null +++ b/backend/templates/admin/node_traffic.html @@ -0,0 +1,96 @@ +{% extends "admin/base_site.html" %} +{% load static %} + +{% block extrastyle %} +{{ block.super }} + +{% endblock %} + +{% block extrahead %} +{{ block.super }} + +{% endblock %} + +{% block breadcrumbs %} + +{% endblock %} + +{% block content %} +
+
+
+ 节点运维 · 容量与流量 +

节点实时流量监控

+

查看每个业务节点的实时吞吐、在线状态和历史趋势。页面仅展示纵横家节点名称,不显示底层专网地址。

+
+
正在连接监控数据
+
+ +
+
+ + + + +
+
尚未刷新每 5 秒自动刷新
+
+ +
+
正在读取 {{ node_count }} 个节点……
+
+ +
+
+ 实时下载 + -- + 当前采样速度 +
+
+ 实时上传 + -- + 当前采样速度 +
+
+ 累计流量 + -- + 上传 -- · 下载 -- +
+
+ 已下发订阅 + -- + 等待节点上报 +
+
+ +
+
+
+ 实时趋势 +

请选择节点

+
+
+ 下载 + 上传 +
+
+
+ +
等待节点上报流量数据
+ +
+
+ +
+
怎么看图?蓝线是下载,青线是上传;折线升高代表节点当前承载的流量变大。
+
何时扩容?速度长期接近线路带宽、用户明显变慢或节点反复离线时,再进入节点配置评估扩容。
+ 进入节点配置 +
+
+{% endblock %} diff --git a/backend/templates/admin/vpn_dashboard.html b/backend/templates/admin/vpn_dashboard.html new file mode 100644 index 0000000..b362531 --- /dev/null +++ b/backend/templates/admin/vpn_dashboard.html @@ -0,0 +1,300 @@ +{% extends "admin/base_site.html" %} +{% load static vpn_admin_dashboard %} + +{% block extrastyle %} +{{ block.super }} + +{% endblock %} + +{% block breadcrumbs %}{% endblock %} +{% block nav-sidebar %}{% endblock %} + +{% block content %} +

企业微信扫码 / 个人绑定 / 8元1024G月套餐 · 内部员工免费,收款接通前不开放付费购买。

+

{% if perms.control.view_team %}团队管理 · {% endif %}{% if perms.control.view_plancatalogdraft %}个人 / 团队套餐草稿 · {% endif %}{% if perms.control.view_teamauditevent %}团队权限审计{% endif %}

+{% vpn_dashboard_metrics as vpn %} +
+
+
+ 优创⁺纵横家 · 运营总览 +

从人员开通到智能代理闭环

+

按流程从左向右操作;状态在上方,配置入口在对应步骤下方。

+
+ + 下一步 + {{ vpn.next_action }} + +
+ + + +
+
+
+ 流程一 +

服务开通鱼骨流程

+
+

人员进入后,依次完成套餐、订阅、节点和设备交付。

+
+ +
+ + + + + + + +
+ AI 运维vpn-ai 控制台心跳、巡检和诊断状态 + 安全与审计{{ vpn.login_blocks }} 个登录封禁登录保护与客户端会话 + 高级配置专用路由策略仅在特殊用户或线路需要时配置 +
+
+ +{% endblock %} diff --git a/backend/templates/admin/wecom_integrations.html b/backend/templates/admin/wecom_integrations.html new file mode 100644 index 0000000..273a1e9 --- /dev/null +++ b/backend/templates/admin/wecom_integrations.html @@ -0,0 +1,20 @@ +{% extends "admin/base_site.html" %} +{% block content %} +

企业微信与套餐收款

+

企业微信扫码与个人绑定

+

{% if wecom_available %}配置已齐备,仍需真实扫码联调验证。{% else %}未启用或配置缺失;原有密码登录不受影响。{% endif %}

+{% for label, ready in config_checks %}{% endfor %}
{{ label }}{% if ready %}已设置{% else %}未设置{% endif %}
+

固定回调地址:{{ callback_url }}。请在公司自建应用中配置对应的可信域名、可见范围和服务器可信IP。

+

已绑定 {{ binding_count }} 个账号。查看绑定 · 绑定审计

+

扫码只核验身份,不修改内部/外部人员分类,也不授予后台权限。首次绑定与解绑必须验证平台密码。

+

1024G 月度套餐

+

外部人员 8 元/自然月 · 内部员工免费。1024G 按现有系统单位计为 1024 × 1024³ 字节,仅计代理流量。

+

从开通时起按自然月计算,月末不足同一天时取目标月份最后一天;到期不自动扣款。不改变已有员工福利套餐与订阅。

+{% if monthly_plan %}

套餐:{{ monthly_plan.name }},{% if monthly_plan.active %}已上架展示与申请,暂未开放付款{% else %}未上架{% endif %}。

+{% else %}

套餐尚未生成。部署时运行 python manage.py prepare_monthly_1024g --list 可开放展示与申请;不会覆盖同标识的不同商业配置。

{% endif %} +

待审核套餐申请:{{ pending_applications }}。身份与套餐审核通过后仍按现有流程自动关联订阅。

+

收款接入 · 尚未完成

+

企业微信不是独立收款余额。需要公司认可的微信支付商户;可以使用与企业微信关联的商户,按商户规则结算,不能直接转入聊天账号。

+

当前未实现或启用真实下单、回调验签、到账自动开通和退款,不会展示可付款二维码。在线套餐可上架展示并登记申请,但外部付费权限保持关闭,禁止人工改付款状态绕过。内部员工核实身份并审核后免费开通。

+

待确认:商户主体与商户号、收款产品/应用绑定、服务器密钥存放位置、通知回调域名。接入后必须验证金额、商户、订单归属、幂等回调、退款及审批权限,再开放购买。

+{% endblock %} diff --git a/backend/templates/base.html b/backend/templates/base.html new file mode 100644 index 0000000..6b0bc68 --- /dev/null +++ b/backend/templates/base.html @@ -0,0 +1,59 @@ +{% load static %} + + + + + + + + {% block title %}{{ PLATFORM_NAME }}{% endblock %} + + + + + + + + +
+ {% if messages %} +
+ {% for message in messages %}
{{ message }}
{% endfor %} +
+ {% endif %} + {% block content %}{% endblock %} +
+ +
+ +
+ {% block scripts %}{% endblock %} + + diff --git a/backend/templates/includes/icon.html b/backend/templates/includes/icon.html new file mode 100644 index 0000000..150d84e --- /dev/null +++ b/backend/templates/includes/icon.html @@ -0,0 +1,7 @@ + diff --git a/backend/templates/includes/lifecycle.html b/backend/templates/includes/lifecycle.html new file mode 100644 index 0000000..6e6878d --- /dev/null +++ b/backend/templates/includes/lifecycle.html @@ -0,0 +1,5 @@ +
+
当前进度

{{ lifecycle.title }}

+
    {% for step in lifecycle.steps %}
  1. {{ forloop.counter }}{{ step.label }}
  2. {% endfor %}
+

下一步:{{ lifecycle.next_step }}

+
diff --git a/backend/templates/portal/application_form.html b/backend/templates/portal/application_form.html new file mode 100644 index 0000000..790fc93 --- /dev/null +++ b/backend/templates/portal/application_form.html @@ -0,0 +1,20 @@ +{% extends "base.html" %} +{% block title %}申请套餐 · {{ PLATFORM_NAME }}{% endblock %} +{% block content %} +
+ 服务申请 +

选择套餐

+ {% if current_subscription %} +

当前套餐:{{ current_subscription.plan.name }}。申请不会立即改变现有订阅;满足开通条件并审核后自动更新,无需管理员再次手工添加。

+ {% else %} +

免费套餐审核后直接开通;付费套餐需管理员确认付款。审核后系统会自动创建订阅。

+ {% endif %} +

内部员工核实身份后免费。标注“暂未开放付款”的在线套餐只登记申请,暂不收款、不开放付费权限;不要向任何个人账号转账。

+
+ {% csrf_token %} + {{ form.as_p }} + + 取消 +
+
+{% endblock %} diff --git a/backend/templates/portal/dashboard.html b/backend/templates/portal/dashboard.html new file mode 100644 index 0000000..3480136 --- /dev/null +++ b/backend/templates/portal/dashboard.html @@ -0,0 +1,110 @@ +{% extends "base.html" %} +{% load vpn_tags static %} +{% block title %}用户中心 · {{ PLATFORM_NAME }}{% endblock %} +{% block content %} +
+
+ 个人中心 +

{{ user.display_name|default:user.username }},你好

+ +
+ +
+ +{% include 'includes/lifecycle.html' %} +{% if user_teams %}{% endif %} + +{% if subscription %} +
+
+
+
{% include 'includes/icon.html' with name='plan' %}
当前订阅

{{ subscription.plan.name }}

+ {{ subscription.get_status_display }} +
+
+
本期已用代理流量{{ subscription.used_bytes|bytes_human }}
+
流量额度{% if subscription.traffic_limit_bytes %}{{ subscription.traffic_limit_bytes|bytes_human }}{% else %}不限{% endif %}
+
设备数量{{ subscription.devices.count }} / {{ subscription.device_limit }}
+
到期时间{% if subscription.expires_at %}{{ subscription.expires_at|date:"Y-m-d H:i" }}{% else %}长期有效{% endif %}
+
+ {% if subscription.traffic_limit_bytes %} +
+ {% endif %} + {% if subscription.state_reason %}

{{ subscription.state_reason }}

{% endif %} +
+ +
+
{% include 'includes/icon.html' with name='network' %}线路策略
+

{{ subscription.get_route_mode_display }}

+

{% if subscription.effective_routing_policy %}{{ subscription.effective_routing_policy.name }}{% else %}尚未设置全局策略{% endif %}

+
+
节点下发
{{ subscription.get_provisioning_state_display }}
+
可用节点
{{ subscription.nodes_for_subscription.count }}
+
+

这里展示订阅配置,实际连接状态请在客户端查看。

+
+
+ +
+
+ Mihomo / Clash Meta 订阅 +

专属订阅地址

+

这是个人凭据,请勿转发。重置后旧地址立即失效。

+
+ {% if subscription.status == "active" %} +
+ + +
+

+ {% else %} +
订阅当前不可用:{{ subscription.get_status_display }}
+ {% endif %} +
+{% else %} +
+
+ {% include 'includes/icon.html' with name='shield' %} +

开启你的专属网络服务

+

还没有可用订阅。选择适合的套餐,提交申请后可在这里查看审核进度和订阅信息。

+ 申请套餐 {% include 'includes/icon.html' with name='arrow' %} +
+
    +
  1. 01
    选择套餐内部员工核实身份后免费,外部人员按套餐计费
  2. +
  3. 02
    提交申请 · 等待审核暂未开放付款的套餐只登记申请,不扣款
  4. +
  5. 03
    获取订阅 · 开始使用满足开通条件并审核后,系统自动关联订阅
  6. +
+
+{% endif %} + +{% if plan_cards %} +
+
{% include 'includes/icon.html' with name='plan' %}

可申请套餐

按需选择 · 审核后自动关联订阅 · 仅计代理流量

+
+ {% for card in plan_cards %} +
+

{{ card.plan.name }}

+

{{ card.label }}

+

仅计代理流量 · 设备上限 {{ card.plan.device_limit }} 台{% if card.plan.billing_months %} · 从开通日起按月计,到期不自动扣款{% endif %}

+ {% if card.payment_pending %}

暂未开放付款:可登记申请,不扣款、不立即开通付费服务。

{% else %}

提交申请后由管理员审核,批准后自动关联订阅。

{% endif %} + 选择并申请 +
+ {% endfor %} +
+
+{% endif %} + +
+
{% include 'includes/icon.html' with name='history' %}

套餐申请记录

{% if subscription %}申请更换套餐{% else %}新申请{% endif %}
+ {% if applications %} +
+ {% for application in applications %}{% endfor %} +
申请时间套餐处理状态付款状态
{{ application.created_at|date:"Y-m-d H:i" }}{{ application.plan.name }}{{ application.get_status_display }}{% if application.plan.online_payment_required and application.payment_status == 'unpaid' %}暂未开放付款{% else %}{{ application.get_payment_status_display }}{% endif %}
+ {% else %} +
{% include 'includes/icon.html' with name='history' %}
暂无申请记录

提交套餐申请后,处理进度会显示在这里。

+ {% endif %} +
+{% endblock %} +{% block scripts %} + +{% endblock %} diff --git a/backend/templates/portal/team_detail.html b/backend/templates/portal/team_detail.html new file mode 100644 index 0000000..7beec00 --- /dev/null +++ b/backend/templates/portal/team_detail.html @@ -0,0 +1,9 @@ +{% extends 'base.html' %} +{% block title %}{{ team.name }} · 团队{% endblock %} +{% block content %} +
团队中心

{{ team.name }}

所有团队
+{% include 'includes/lifecycle.html' %} +

团队套餐情况

{% if team.plan_draft %}

意向套餐:{{ team.plan_draft.name }}

拟定月共享代理流量{{ team.plan_draft.quota_label }}
月价{{ team.plan_draft.price_label }}
使用时长尚未开通
共享用量尚未接入
{% else %}

尚未配置团队套餐。{% if management %}请联系平台管理员核实人数、设备和流量需求。{% else %}请联系团队所有者。{% endif %}

{% endif %}

团队成员与套餐筹备信息不等于购买成功。没有团队订阅地址;不会复用或展示他人的个人凭据,也不会把个人流量相加冒充团队共享账本。

已加入 {{ member_count }} 人 / 筹备上限 {{ team.setup_member_limit }} 人(含所有者);不是已付费席位。

+{% if management %}

成员管理

所有者:{{ team.owner.display_name|default:team.owner.username }}(不可通过成员按钮变更)

{% for member in members %}{% empty %}{% endfor %}
成员角色状态操作
{{ member.user.display_name|default:member.user.username }}{{ member.get_role_display }}{{ member.get_status_display }}
{% csrf_token %}{% if role == 'owner' and member.status == 'active' %}{% if member.role == 'member' %}{% else %}{% endif %}{% endif %}{% if role == 'owner' or member.role == 'member' %}{% endif %}
还没有其他成员

邀请成员

{% csrf_token %}{{ form.as_p }}
{% else %}

你可以查看团队套餐概要和自己的身份,不能查看其他成员资料、邀请或修改角色。

{% endif %} +{% if my_membership %}
{% csrf_token %}

仅退出团队成员身份,个人账号和个人套餐不变。

{% endif %} +{% endblock %} diff --git a/backend/templates/portal/teams.html b/backend/templates/portal/teams.html new file mode 100644 index 0000000..90c5bd1 --- /dev/null +++ b/backend/templates/portal/teams.html @@ -0,0 +1,8 @@ +{% extends 'base.html' %} +{% block title %}团队 · {{ PLATFORM_NAME }}{% endblock %} +{% block content %} +
团队中心

我的团队

独立账号,共同协作。团队管理权限与平台管理员、内部员工身份分开。

查看个人套餐
+{% if invitations %}

待接受邀请

{% for invitation in invitations %}

{{ invitation.team.name }}

所有者:{{ invitation.team.owner.display_name|default:invitation.team.owner.username }}

接受后成为普通成员,不会自动购买套餐或获得平台管理权限。

{% csrf_token %}
{% endfor %}
{% endif %} +
{% for team in teams %}
{% if team.owner_id == user.pk %}所有者{% else %}已加入{% endif %}

{{ team.name }}

{{ team.package_state }}

{% if team.plan_draft %}

意向:{{ team.plan_draft.name }} · {{ team.plan_draft.price_label }}

{% endif %}查看团队与套餐
{% empty %}

还没有团队

可接受已有团队的邀请,或建立一个团队管理空间。个人套餐保持不变。

{% endfor %}
+{% if user.service_enabled %}

创建团队

初始可筹备3人(包含你),不收费、不修改个人订阅;需要更多人数由平台管理员核实配置。

{% csrf_token %}{{ form.as_p }}
{% else %}

账号需审核正常后才能创建或加入团队。

{% endif %} +{% endblock %} diff --git a/backend/templates/registration/login.html b/backend/templates/registration/login.html new file mode 100644 index 0000000..32da9ec --- /dev/null +++ b/backend/templates/registration/login.html @@ -0,0 +1,35 @@ +{% extends "base.html" %} +{% block title %}登录 · {{ PLATFORM_NAME }}{% endblock %} +{% block content %} +
+
+ 安全连接,从这里开始 +

连接你的工作网络,
清晰、稳定、可控。

+

统一查看服务状态、使用流量、有效期和订阅地址。公司员工与外部联系人使用同一入口。

+
01 每人独立订阅与流量统计
+
02 全局线路策略与个人专用线路
+
03 到期、超额或停权立即生效
+
+
+

账号登录

+

使用纵横家账号,安全访问你的专属服务

+
+ {% csrf_token %} + {% if form.non_field_errors %}
{{ form.non_field_errors }}
{% endif %} + + + {% if next %}{% endif %} + +
+ {% if WECOM_AVAILABLE %} + +

首次使用请先密码登录,在“个人绑定”中关联企业微信。

+ {% endif %} +

还没有账号?提交注册申请

+
+
+{% endblock %} diff --git a/backend/templates/registration/password_change_done.html b/backend/templates/registration/password_change_done.html new file mode 100644 index 0000000..875d732 --- /dev/null +++ b/backend/templates/registration/password_change_done.html @@ -0,0 +1,10 @@ +{% extends "base.html" %} +{% block title %}密码已修改 · {{ PLATFORM_NAME }}{% endblock %} +{% block content %} +
+

密码已修改

+

新密码已经生效。

+ 返回用户中心 +
+{% endblock %} + diff --git a/backend/templates/registration/password_change_form.html b/backend/templates/registration/password_change_form.html new file mode 100644 index 0000000..f5ad082 --- /dev/null +++ b/backend/templates/registration/password_change_form.html @@ -0,0 +1,13 @@ +{% extends "base.html" %} +{% block title %}修改密码 · {{ PLATFORM_NAME }}{% endblock %} +{% block content %} +
+

修改密码

+
+ {% csrf_token %} + {{ form.as_p }} + +
+
+{% endblock %} + diff --git a/backend/templates/registration/register.html b/backend/templates/registration/register.html new file mode 100644 index 0000000..d5772dd --- /dev/null +++ b/backend/templates/registration/register.html @@ -0,0 +1,22 @@ +{% extends "base.html" %} +{% block title %}注册 · {{ PLATFORM_NAME }}{% endblock %} +{% block content %} +
+ 新用户申请 +

创建服务账号

+

注册时选择套餐,一并提交申请。内部员工核实身份并审核后免费开通;外部人员的在线付费套餐暂未开放付款,仅登记申请,不立即开通。

+
+ {% csrf_token %} + {% if form.non_field_errors %}
{{ form.non_field_errors }}
{% endif %} + {% for field in form %} + + {% endfor %} + +
+

已经有账号?返回登录

+
+{% endblock %} diff --git a/backend/templates/registration/wecom_account.html b/backend/templates/registration/wecom_account.html new file mode 100644 index 0000000..7498c04 --- /dev/null +++ b/backend/templates/registration/wecom_account.html @@ -0,0 +1,24 @@ +{% extends "base.html" %} +{% block title %}个人绑定 · {{ PLATFORM_NAME }}{% endblock %} +{% block content %} +
账号与安全

企业微信绑定

+

平台账号 {{ user.username }} · {{ user.get_identity_type_display }}

+返回用户中心
+
+{% if user.identity_type == "employee" %}

内部员工免费,套餐和服务权限仍以后台审核为准。

+{% else %}

外部人员 1024G/月套餐为 8 元。绑定企业微信不会自动变更计费身份。

{% endif %} +{% if binding %} +

已绑定 · {{ binding.get_kind_display }}

+

绑定时间:{{ binding.created_at|date:"Y-m-d H:i" }}。绑定不改变套餐或管理员权限。

+
+{% csrf_token %} +
+{% elif wecom_available %} +

尚未绑定

验证平台密码后打开企业微信扫码页。同一企业微信身份只能绑定一个平台账号。

+
+{% csrf_token %} + +
+{% else %}

企业微信尚未接通

管理员配置公司自建应用及可信回调域名后启用。账号密码登录仍可使用。

{% endif %} +
+{% endblock %} diff --git a/backend/toplc_vpn/__init__.py b/backend/toplc_vpn/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/backend/toplc_vpn/__init__.py @@ -0,0 +1 @@ + diff --git a/backend/toplc_vpn/asgi.py b/backend/toplc_vpn/asgi.py new file mode 100644 index 0000000..dd607ba --- /dev/null +++ b/backend/toplc_vpn/asgi.py @@ -0,0 +1,7 @@ +import os + +from django.core.asgi import get_asgi_application + + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "toplc_vpn.settings") +application = get_asgi_application() diff --git a/backend/toplc_vpn/postgres_test_settings.py b/backend/toplc_vpn/postgres_test_settings.py new file mode 100644 index 0000000..c3da8a2 --- /dev/null +++ b/backend/toplc_vpn/postgres_test_settings.py @@ -0,0 +1,18 @@ +"""Disposable local/CI database only; never reads production DATABASE_URL.""" +import os + +from .test_settings import * # noqa: F403 + +DATABASES = { + "default": { + "ENGINE": "django.db.backends.postgresql", + "HOST": "127.0.0.1", + "PORT": os.environ.get("UCVL_TEST_PG_PORT", "55439"), + "NAME": "ucvl_acceptance", + "USER": "ucvl_test", + "PASSWORD": os.environ.get("UCVL_TEST_PG_PASSWORD", ""), + "CONN_MAX_AGE": 0, + "OPTIONS": {"connect_timeout": 5, "options": "-c statement_timeout=15000"}, + "TEST": {"NAME": "test_ucvl_acceptance"}, + } +} diff --git a/backend/toplc_vpn/settings.py b/backend/toplc_vpn/settings.py new file mode 100644 index 0000000..da0fee7 --- /dev/null +++ b/backend/toplc_vpn/settings.py @@ -0,0 +1,156 @@ +import os +from pathlib import Path + + +BASE_DIR = Path(__file__).resolve().parent.parent + + +def env_bool(name, default=False): + return os.getenv(name, str(default)).strip().lower() in {"1", "true", "yes", "on"} + + +def env_list(name, default=""): + return [item.strip() for item in os.getenv(name, default).split(",") if item.strip()] + + +SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", "") +DEBUG = env_bool("DJANGO_DEBUG", False) +if not SECRET_KEY: + if DEBUG: + SECRET_KEY = "development-only-insecure-secret-key" + else: + raise RuntimeError("DJANGO_SECRET_KEY is required when DJANGO_DEBUG is false") + +ALLOWED_HOSTS = env_list("DJANGO_ALLOWED_HOSTS", "vpn.toplc.cn,localhost,127.0.0.1") +CSRF_TRUSTED_ORIGINS = env_list("DJANGO_CSRF_TRUSTED_ORIGINS", "https://vpn.toplc.cn") + +INSTALLED_APPS = [ + "django.contrib.admin", + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.sessions", + "django.contrib.messages", + "django.contrib.staticfiles", + "accounts.apps.AccountsConfig", + "control.apps.ControlConfig", +] + +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", +] + +ROOT_URLCONF = "toplc_vpn.urls" +TEMPLATES = [ + { + "BACKEND": "django.template.backends.django.DjangoTemplates", + "DIRS": [BASE_DIR / "templates"], + "APP_DIRS": True, + "OPTIONS": { + "context_processors": [ + "django.template.context_processors.request", + "django.contrib.auth.context_processors.auth", + "django.contrib.messages.context_processors.messages", + "control.context_processors.platform_settings", + ], + }, + } +] + +WSGI_APPLICATION = "toplc_vpn.wsgi.application" +ASGI_APPLICATION = "toplc_vpn.asgi.application" + +DATABASES = { + "default": { + "ENGINE": "django.db.backends.postgresql", + "NAME": os.getenv("POSTGRES_DB", "toplc_vpn"), + "USER": os.getenv("POSTGRES_USER", "toplc_vpn"), + "PASSWORD": os.getenv("POSTGRES_PASSWORD", ""), + "HOST": os.getenv("POSTGRES_HOST", "db"), + "PORT": os.getenv("POSTGRES_PORT", "5432"), + "CONN_MAX_AGE": 60, + "CONN_HEALTH_CHECKS": True, + } +} + +AUTH_PASSWORD_VALIDATORS = [ + {"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"}, + {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", "OPTIONS": {"min_length": 10}}, + {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"}, + {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"}, +] +PASSWORD_HASHERS = [ + "django.contrib.auth.hashers.Argon2PasswordHasher", + "django.contrib.auth.hashers.PBKDF2PasswordHasher", +] + +AUTH_USER_MODEL = "accounts.User" +LOGIN_URL = "login" +LOGIN_REDIRECT_URL = "portal-dashboard" +LOGOUT_REDIRECT_URL = "login" + +LANGUAGE_CODE = "zh-hans" +TIME_ZONE = "Asia/Shanghai" +USE_I18N = True +USE_TZ = True + +STATIC_URL = "/static/" +STATIC_ROOT = BASE_DIR / "staticfiles" +STATICFILES_DIRS = [BASE_DIR / "static"] +STORAGES = { + "default": {"BACKEND": "django.core.files.storage.FileSystemStorage"}, + "staticfiles": {"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage"}, +} + +DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" +PUBLIC_BASE_URL = os.getenv("VPN_PUBLIC_BASE_URL", "https://vpn.toplc.cn").rstrip("/") +# Credentials are injected server-side; no admin form or browser receives the secret. +WECOM_ENABLED = env_bool("WECOM_ENABLED", False) +WECOM_CORP_ID = os.getenv("WECOM_CORP_ID", "").strip() +WECOM_AGENT_ID = os.getenv("WECOM_AGENT_ID", "").strip() +WECOM_SECRET = os.getenv("WECOM_SECRET", "").strip() +VPN_PUBLIC_GATEWAY_HOST = os.getenv("VPN_PUBLIC_GATEWAY_HOST", "vpn.toplc.cn").strip() +VPN_PUBLIC_GATEWAY_IPV4 = os.getenv("VPN_PUBLIC_GATEWAY_IPV4", "").strip() +# Optional employee-only same-node transport hint. Enabling also requires the +# node/Tailnet firewall to explicitly authorize client sources; sharing is not login. +VPN_TAILSCALE_ENDPOINT_ENABLED = env_bool("VPN_TAILSCALE_ENDPOINT_ENABLED", False) +VPN_TAILSCALE_ENDPOINTS_JSON = os.getenv("VPN_TAILSCALE_ENDPOINTS_JSON", "") +# Private auxiliary is NOT a public/core node. Keep disabled until board-side +# per-device authorization/renewal/revocation and reboot acceptance are complete. +VPN_PRIVATE_AUXILIARY_ENABLED = env_bool("VPN_PRIVATE_AUXILIARY_ENABLED", False) +VPN_PRIVATE_AUXILIARY_VALIDATION_DEVICE_ID = int(os.getenv("VPN_PRIVATE_AUXILIARY_VALIDATION_DEVICE_ID", "0")) +VPN_PRIVATE_AUXILIARY_TLS_LEAF_SHA256 = os.getenv("VPN_PRIVATE_AUXILIARY_TLS_LEAF_SHA256", "").strip() +VPN_PRIVATE_AUXILIARY_AGENT_TOKEN_SHA256 = os.getenv("VPN_PRIVATE_AUXILIARY_AGENT_TOKEN_SHA256", "").strip() +VPN_PRIVATE_AUXILIARY_ADDRESS = os.getenv("VPN_PRIVATE_AUXILIARY_ADDRESS", "192.168.50.111").strip() +VPN_PRIVATE_AUXILIARY_CONNECT_ADDRESS = os.getenv("VPN_PRIVATE_AUXILIARY_CONNECT_ADDRESS", "").strip() + +SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") +USE_X_FORWARDED_HOST = True +SECURE_SSL_REDIRECT = env_bool("DJANGO_SECURE_SSL_REDIRECT", True) +SECURE_HSTS_SECONDS = int(os.getenv("DJANGO_HSTS_SECONDS", "31536000")) +SECURE_HSTS_INCLUDE_SUBDOMAINS = False +SECURE_HSTS_PRELOAD = False +SESSION_COOKIE_SECURE = not DEBUG +SESSION_COOKIE_HTTPONLY = True +SESSION_COOKIE_SAMESITE = "Lax" +CSRF_COOKIE_SECURE = not DEBUG +CSRF_COOKIE_SAMESITE = "Lax" +X_FRAME_OPTIONS = "DENY" +SECURE_CONTENT_TYPE_NOSNIFF = True +SECURE_REFERRER_POLICY = "same-origin" + +EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend" + +LOGGING = { + "version": 1, + "disable_existing_loggers": False, + "handlers": {"console": {"class": "logging.StreamHandler"}}, + "root": {"handlers": ["console"], "level": "INFO"}, +} diff --git a/backend/toplc_vpn/test_settings.py b/backend/toplc_vpn/test_settings.py new file mode 100644 index 0000000..74bedf3 --- /dev/null +++ b/backend/toplc_vpn/test_settings.py @@ -0,0 +1,12 @@ +from .settings import * # noqa: F403 + + +DATABASES = { + "default": { + "ENGINE": "django.db.backends.sqlite3", + "NAME": ":memory:", + } +} + +PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"] +SECURE_SSL_REDIRECT = False diff --git a/backend/toplc_vpn/urls.py b/backend/toplc_vpn/urls.py new file mode 100644 index 0000000..387a792 --- /dev/null +++ b/backend/toplc_vpn/urls.py @@ -0,0 +1,37 @@ +from django.contrib import admin +from django.contrib.auth import views as auth_views +from django.urls import include, path + +from accounts.forms import TopLCAuthenticationForm +from accounts import wecom_views +from control import views as control_views + + +admin.site.site_header = "优创⁺纵横家 管理中心" +admin.site.site_title = "优创⁺纵横家" +admin.site.index_title = "业务流程" +admin.site.index_template = "admin/vpn_dashboard.html" +admin.site.enable_nav_sidebar = False + +urlpatterns = [ + path("admin/integrations/", wecom_views.integrations, name="admin-integrations"), + path("auth/wecom/start/", wecom_views.start, name="wecom-start"), + path("auth/wecom/callback/", wecom_views.callback, name="wecom-callback"), + path("account/wecom/", wecom_views.account, name="wecom-account"), + path("account/wecom/unbind/", wecom_views.unbind, name="wecom-unbind"), + path("admin/node-traffic/data/", control_views.node_traffic_data, name="admin-node-traffic-data"), + path("admin/node-traffic/", control_views.node_traffic_dashboard, name="admin-node-traffic"), + path("admin/", admin.site.urls), + path( + "login/", + auth_views.LoginView.as_view( + template_name="registration/login.html", + authentication_form=TopLCAuthenticationForm, + ), + name="login", + ), + path("logout/", auth_views.LogoutView.as_view(), name="logout"), + path("password/change/", auth_views.PasswordChangeView.as_view(), name="password_change"), + path("password/change/done/", auth_views.PasswordChangeDoneView.as_view(), name="password_change_done"), + path("", include("control.urls")), +] diff --git a/backend/toplc_vpn/wsgi.py b/backend/toplc_vpn/wsgi.py new file mode 100644 index 0000000..3a7537e --- /dev/null +++ b/backend/toplc_vpn/wsgi.py @@ -0,0 +1,8 @@ +import os + +from django.core.wsgi import get_wsgi_application + + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "toplc_vpn.settings") +application = get_wsgi_application() + diff --git a/ios/.gitattributes b/ios/.gitattributes new file mode 100644 index 0000000..2de85a2 --- /dev/null +++ b/ios/.gitattributes @@ -0,0 +1,10 @@ +* text=auto +*.swift text eol=lf +*.sh text eol=lf +*.py text eol=lf +*.md text eol=lf +*.yml text eol=lf +*.plist text eol=lf +*.json text eol=lf +*.dat binary +*.png binary diff --git a/ios/.gitea/workflows/apple-build.yml b/ios/.gitea/workflows/apple-build.yml new file mode 100644 index 0000000..7161586 --- /dev/null +++ b/ios/.gitea/workflows/apple-build.yml @@ -0,0 +1,18 @@ +name: iOS Xcode acceptance + +on: + workflow_dispatch: + +jobs: + xcode-acceptance: + runs-on: macos + steps: + - uses: actions/checkout@v4 + - name: Install XcodeGen + run: brew install xcodegen + - name: Restore verified libXray + run: ./Scripts/fetch-libxray.sh + - name: Generate project and run tests + env: + DEVELOPMENT_TEAM: ${{ secrets.APPLE_DEVELOPMENT_TEAM }} + run: ./Scripts/verify-and-archive.sh diff --git a/ios/.gitea/workflows/source-audit.yml b/ios/.gitea/workflows/source-audit.yml new file mode 100644 index 0000000..d9952e7 --- /dev/null +++ b/ios/.gitea/workflows/source-audit.yml @@ -0,0 +1,15 @@ +name: iOS source audit + +on: + push: + branches: [main, "codex/**"] + pull_request: + +jobs: + audit: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Audit source, entitlements and secrets + run: python3 Scripts/source-audit.py + diff --git a/ios/.gitignore b/ios/.gitignore new file mode 100644 index 0000000..11908b3 --- /dev/null +++ b/ios/.gitignore @@ -0,0 +1,15 @@ +DerivedData/ +build/ +*.xcarchive +*.ipa +*.mobileprovision +*.p12 +*.cer +xcuserdata/ +.DS_Store +Vendor/libxray-apple-cgo-v26.7.28.zip +Vendor/libxray-apple-cgo-v26.7.28/ +Vendor/libXray-source-v26.7.28/ +Vendor/Xray-core-source/ +Vendor/LibXray.xcframework/ +BuildArtifacts/ diff --git a/ios/ACCEPTANCE.md b/ios/ACCEPTANCE.md new file mode 100644 index 0000000..029883b --- /dev/null +++ b/ios/ACCEPTANCE.md @@ -0,0 +1,50 @@ +# 优创⁺纵横家 iPhone / iPad 验收记录 + +## 2026-09-09:1.0.2 源码候选(非 IPA) + +工程 `MARKETING_VERSION` 为 1.0.2,README 已与之同步,源码审计新增文档版本一致性检查并通过。现有错误分类源码区分平台/本机授权/节点失败及 401/403 授权失效;XCTest 已编写,仍未运行。这次只修正文档和静态校验,没有新的 iOS 二进制构建、签名、安装包、真机连接或公开发布。未取得 Mac/Xcode/开发者团队条件,不能把 Windows 测试当成苹果验收。 + +## 2026-09-04:1.0.1 历史记录 + +日期:2026-09-04 + +结论:`SOURCE_CANDIDATE`。源码与依赖完整性静态检查通过;由于没有 macOS/Xcode、Apple Developer Team、Network Extension Provisioning Profile 和 iPhone 真机,本记录不代表可安装 IPA 或真机网络验收通过。 + +## 已通过 + +- 主应用与 Packet Tunnel Extension 使用独立 Bundle ID。 +- 两个目标声明 `packet-tunnel-provider` entitlement。 +- 登录令牌保存在 Keychain,源代码没有公司账号、密码、令牌、证书或私钥。 +- 后台以 `node=auto&new_connection=1` 分配节点,客户端隐藏节点选择,只显示实际工作节点。 +- 最多三次失败切换;每次失败把已失败节点加入 `exclude`,断开并等待系统 VPN 恢复后再试。 +- 001/002 节点由 NPM TCP Stream 端口分流;节点子域无 A 记录时,主应用通过阿里/腾讯 DoH 获取统一入口 `vpn.toplc.cn` 的真实公网 IPv4,拒绝 Clash Fake-IP (`198.18.0.0/15`)、私网、Tailscale 和其它保留地址。 +- Packet Tunnel 在接管默认路由前排除该公网 IPv4,并将运行时 VLESS 地址改为同一 IP;Reality SNI 保持不变。 +- 支持后台 `config_contract=2` 统一 NPM 网关字段,同时兼容未返回该字段的旧后台。 +- VPN 连接状态变为 connected 后,再访问 OpenAI / ChatGPT HTTPS 入口;两个入口均失败才判定当前节点不可用。 +- 出口探测返回后再次确认系统 VPN 仍处于 connected,避免隧道已退出时出现假成功。 +- libXray v26.7.28 本地官方归档 SHA256:`07F7ED7697277930E1C517755855950F594F41435B0DFC5917A66EEA6278AEB9`。 +- 注册入口、套餐与流量、AI 智能代理/全局代理/本地直连、退出账号与网络恢复流程均已在源码中接通。 +- Windows 侧对 NPM 公网入口 `192.0.2.1` 复核:`vpn.toplc.cn` HTTPS 健康接口正常,TCP `11081`、`11082`、`11083` 均可建立连接。该检查只证明 NPM 入口与端口在线,不替代 VLESS Reality 握手或 iPhone 真机出口验收。 + +## 必须在 Mac 和真机完成后才能发布 IPA + +1. 使用当前 Xcode 编译主应用、扩展和单元测试,修复所有 warning/error。 +2. 为两个 App ID 开启 Network Extensions / Packet Tunnel Provider,并使用同一 Team 签名。 +3. 在至少一台真实 iPhone 上确认系统 VPN 授权、登录、连接、OpenAI/ChatGPT 出口、节点失败切换、断开恢复、锁屏/唤醒和换 Wi‑Fi/蜂窝网络。 +4. 验证强制结束、设备重启、账号停用、套餐到期和无可用节点时不会留下失效默认路由。 +5. 选择 Ad Hoc、MDM/Custom App 或符合资质的 Enterprise 内部分发,导出并安装最终 IPA;记录 IPA SHA256。 + +## 本地静态复核 + +在 Windows 工作区执行: + +```powershell +py -3 .\Scripts\source-audit.py +``` + +只有输出 `"result": "PASS"` 才允许把本次源码候选版上传 Git。该命令明确不替代 Xcode 编译、苹果签名和 iPhone 真机测试。 +# 2026-09-08 补充:1.0.2 源码候选 + +新增连接错误分类:控制接口未返回节点、系统授权取消、本地配置错误不再循环记成全部节点故障;401/403 直接撤销会话,只有已分配节点的传输失败才尝试其它节点。阻止重复触发登录、刷新、连接和退出操作。新增 4 项 XCTest 源码。 + +本机仅执行 `Scripts/source-audit.py` 并通过;没有 Swift/Xcode 编译、XCTest 执行、签名、IPA 或 iPhone 真机验收。仍缺 Mac/Xcode、开发者团队和设备条件,不能称为已完成安装版。旧记录保留如下。 diff --git a/ios/App/AppState.swift b/ios/App/AppState.swift new file mode 100644 index 0000000..2f8c248 --- /dev/null +++ b/ios/App/AppState.swift @@ -0,0 +1,222 @@ +import Combine +import Foundation +import NetworkExtension + +@MainActor +final class AppState: ObservableObject { + @Published var profile: ClientProfile? + @Published var currentNode: VPNNode? + @Published var selectedRouteID = "smart" + @Published var busy = false + @Published var message = "" + @Published var errorMessage = "" + + let vpn = VPNController() + private let api = PlatformAPI.shared + private var cancellables = Set() + + init() { + vpn.$status + .sink { [weak self] _ in self?.objectWillChange.send() } + .store(in: &cancellables) + } + + func start() async { + await vpn.restore() + guard let token = SecureStore.token() else { return } + await refresh(token: token, initial: true) + } + + func login(identifier: String, password: String) async { + guard !busy else { return } + let identifier = identifier.trimmingCharacters(in: .whitespacesAndNewlines) + guard !identifier.isEmpty, !password.isEmpty else { + errorMessage = "请输入用户名(或邮箱)和密码。" + return + } + busy = true + message = "正在安全登录…" + errorMessage = "" + defer { busy = false } + do { + let response = try await api.login(login: identifier, password: password) + try SecureStore.saveToken(response.accessToken) + SecureStore.lastLogin = identifier + apply(response.profile) + message = "账号和线路已同步" + } catch { + errorMessage = friendly(error) + } + } + + func refresh() async { + guard !busy else { return } + guard let token = SecureStore.token() else { + logoutLocal() + return + } + await refresh(token: token, initial: false) + } + + func toggleConnection() async { + guard !busy else { return } + // Acquire before the first await, including disconnect/direct branches. + // A second tap must not start another operation during network restoration. + busy = true + defer { busy = false } + if vpn.isConnected { + await vpn.disconnectAndWait() + currentNode = nil + message = "正在断开,系统将自动恢复原网络" + return + } + guard let profile, + let route = profile.routeModes.first(where: { $0.id == selectedRouteID }) + else { + errorMessage = "没有可用的代理模式。" + return + } + if route.id == "direct" { + await vpn.disconnectAndWait() + currentNode = nil + message = "当前为本地直连,不经过 VPN 节点" + return + } + guard let token = SecureStore.token() else { + logoutLocal() + return + } + message = "vpn-ai 正在选择工作节点…" + errorMessage = "" + var excludedNodes: [String] = [] + var lastError: Error = UCVLError.connection("没有可用节点。") + let maximumAttempts = max(1, min(profile.nodes.count, 3)) + + for attempt in 1...maximumAttempts { + var attemptedNode: VPNNode? + do { + let response = try await api.config(token: token, route: route.id, excluding: excludedNodes) + attemptedNode = response.node + let configJSON = try response.configJSONString() + guard let remoteHost = TunnelConfigurationBuilder.remoteAddress(from: configJSON) else { + throw UCVLError.invalidConfiguration("后台线路配置缺少节点域名。") + } + let gatewayHost = response.gateway?.host.trimmingCharacters(in: .whitespacesAndNewlines) + let pinnedGatewayIPv4 = response.gateway?.ipv4?.trimmingCharacters(in: .whitespacesAndNewlines) + let remoteAddress: String + if let pinnedGatewayIPv4, NetworkAddress.isPublicIPv4(pinnedGatewayIPv4) { + remoteAddress = pinnedGatewayIPv4 + } else { + let hostToResolve = (gatewayHost?.isEmpty == false ? gatewayHost : nil) ?? remoteHost + remoteAddress = try await api.resolvePublicIPv4(host: hostToResolve) + } + currentNode = response.node + message = "正在连接 \(response.node.displayName)(第 \(attempt) 次验证)…" + try await vpn.connect( + configJSON: configJSON, + resolvedRemoteAddress: remoteAddress, + node: response.node, + route: route + ) + try await api.verifyProxyEgress() + guard vpn.status == .connected else { + throw UCVLError.connection("出口验证返回时 VPN 已断开,正在切换备用节点。") + } + message = "已连接 \(response.node.displayName),出口验证通过" + return + } catch { + lastError = error + let decision = ConnectionAttemptPolicy.decide(error: error, hasAssignedNode: attemptedNode != nil) + currentNode = nil + await vpn.disconnectAndWait() + if decision == .revokeAuthorization { + logoutLocal() + errorMessage = friendly(error) + message = "账号授权已失效,已停止连接,请重新登录" + return + } + if decision == .stop { + errorMessage = friendly(error) + message = "连接未完成;未将本机设置或平台请求错误记为全部节点故障" + return + } + if let slug = attemptedNode?.slug, !excludedNodes.contains(slug) { + excludedNodes.append(slug) + } + } + } + errorMessage = friendly(lastError) + message = "所有可用节点均未通过验证,已恢复本地网络" + } + + func logout() async { + guard !busy else { return } + busy = true + defer { busy = false } + await vpn.disconnectAndWait() + if let token = SecureStore.token() { + await api.logout(token: token) + } + logoutLocal() + } + + var statusTitle: String { + switch vpn.status { + case .connected: return "已安全连接" + case .connecting: return "正在连接" + case .disconnecting: return "正在断开" + case .reasserting: return "正在恢复连接" + case .disconnected: return selectedRouteID == "direct" ? "本地直连" : "未连接" + case .invalid: return "未配置" + @unknown default: return "状态更新中" + } + } + + var statusIsActive: Bool { vpn.status == .connected } + + private func refresh(token: String, initial: Bool) async { + busy = true + message = "正在同步账号和线路…" + defer { busy = false } + do { + apply(try await api.profile(token: token)) + message = "账号和线路已同步" + } catch UCVLError.api(let status, let message) where status == 401 || status == 403 { + await vpn.disconnectAndWait() + SecureStore.clearToken() + profile = nil + errorMessage = message + } catch { + errorMessage = friendly(error) + if initial { profile = nil } + } + } + + private func apply(_ value: ClientProfile) { + profile = value + if vpn.isConnected, let slug = vpn.activeNodeSlug { + currentNode = value.nodes.first(where: { $0.slug == slug }) + } + if !value.routeModes.contains(where: { $0.id == selectedRouteID }) { + selectedRouteID = value.routeModes.first?.id ?? "smart" + } + } + + private func logoutLocal() { + SecureStore.clearToken() + profile = nil + currentNode = nil + selectedRouteID = "smart" + message = "" + } + + private func friendly(_ error: Error) -> String { + if let localized = error as? LocalizedError, let description = localized.errorDescription { + return description + } + if (error as NSError).code == NSURLErrorTimedOut { + return "连接平台超时,请稍后重试。" + } + return error.localizedDescription + } +} diff --git a/ios/App/ContentView.swift b/ios/App/ContentView.swift new file mode 100644 index 0000000..d6f5955 --- /dev/null +++ b/ios/App/ContentView.swift @@ -0,0 +1,294 @@ +import SwiftUI + +struct ContentView: View { + @EnvironmentObject private var state: AppState + + var body: some View { + ZStack { + UCVLColors.background.ignoresSafeArea() + if let profile = state.profile { + DashboardView(profile: profile) + } else { + LoginView() + } + } + .tint(UCVLColors.royal) + .alert("提示", isPresented: Binding( + get: { !state.errorMessage.isEmpty }, + set: { if !$0 { state.errorMessage = "" } } + )) { + Button("确定", role: .cancel) { state.errorMessage = "" } + } message: { + Text(state.errorMessage) + } + } +} + +private struct BrandHeader: View { + var compact = false + + var body: some View { + VStack(spacing: compact ? 8 : 16) { + Image("UCVLLogo") + .resizable() + .scaledToFit() + .frame(width: compact ? 84 : 132, height: compact ? 84 : 132) + .accessibilityLabel("优创未来 Logo") + Text("优创⁺纵横家") + .font(compact ? .title2.bold() : .largeTitle.bold()) + .foregroundStyle(.white) + Text("优创未来安全网络") + .font(.subheadline) + .foregroundStyle(UCVLColors.sky) + } + } +} + +private struct LoginView: View { + @EnvironmentObject private var state: AppState + @State private var identifier = SecureStore.lastLogin + @State private var password = "" + + var body: some View { + ScrollView { + VStack(spacing: 28) { + BrandHeader() + .padding(.top, 34) + VStack(alignment: .leading, spacing: 18) { + Text("公司统一账号登录") + .font(.title2.bold()) + .foregroundStyle(UCVLColors.navy) + TextField("用户名或邮箱", text: $identifier) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .keyboardType(.emailAddress) + .textContentType(.username) + .ucvlField() + SecureField("密码", text: $password) + .textContentType(.password) + .ucvlField() + .onSubmit { Task { await state.login(identifier: identifier, password: password) } } + Button { + Task { + await state.login(identifier: identifier, password: password) + if state.profile != nil { password = "" } + } + } label: { + HStack { + if state.busy { ProgressView().tint(.white) } + Text(state.busy ? "正在登录…" : "安全登录").fontWeight(.semibold) + } + .frame(maxWidth: .infinity) + .padding(.vertical, 14) + } + .buttonStyle(.borderedProminent) + .disabled(state.busy) + Text("账号停用后,设备授权与线路将自动失效。") + .font(.footnote) + .foregroundStyle(.secondary) + HStack { + Text("还没有账号?") + .font(.footnote) + .foregroundStyle(.secondary) + Link("注册新用户", destination: URL(string: "https://vpn.toplc.cn/register/")!) + .font(.footnote.weight(.semibold)) + } + } + .padding(24) + .background(.white, in: RoundedRectangle(cornerRadius: 24, style: .continuous)) + .shadow(color: .black.opacity(0.14), radius: 24, y: 12) + .frame(maxWidth: 540) + Text("vpn.toplc.cn · © 2026 UCVL") + .font(.footnote) + .foregroundStyle(UCVLColors.sky) + .padding(.bottom, 30) + } + .padding(.horizontal, 20) + } + } +} + +private struct DashboardView: View { + @EnvironmentObject private var state: AppState + let profile: ClientProfile + + var body: some View { + ScrollView { + VStack(spacing: 18) { + HStack(spacing: 16) { + BrandHeader(compact: true) + Spacer() + VStack(alignment: .trailing, spacing: 4) { + Text("你好,\(profile.displayName.isEmpty ? profile.username : profile.displayName)") + .font(.headline) + .foregroundStyle(.white) + Text("\(profile.email) · \(profile.identityType == "employee" ? "内部员工" : "外部联系人")") + .font(.caption) + .foregroundStyle(UCVLColors.sky) + } + } + .padding(.vertical, 8) + + StatusCard() + + UCVLCard(title: "工作节点与代理模式", systemImage: "point.3.connected.trianglepath.dotted") { + VStack(spacing: 14) { + HStack { + Text("当前工作节点") + Spacer() + Text(state.currentNode?.displayName ?? "由 vpn-ai 自动选择") + .foregroundStyle(state.currentNode == nil ? .secondary : UCVLColors.royal) + .multilineTextAlignment(.trailing) + } + Divider() + HStack { + Text("代理模式") + Spacer() + Picker("代理模式", selection: $state.selectedRouteID) { + ForEach(profile.routeModes) { route in Text(route.name).tag(route.id) } + } + .pickerStyle(.menu) + .disabled(state.vpn.isConnected || state.busy) + } + Button { + Task { await state.toggleConnection() } + } label: { + HStack { + if state.busy { ProgressView().tint(.white) } + Image(systemName: state.vpn.isConnected ? "stop.fill" : "bolt.shield.fill") + Text(state.vpn.isConnected ? "断开连接" : "连接") + } + .frame(maxWidth: .infinity) + .padding(.vertical, 12) + } + .buttonStyle(.borderedProminent) + .tint(state.vpn.isConnected ? UCVLColors.navy : UCVLColors.royal) + .disabled(state.busy || profile.nodes.isEmpty) + } + } + + UsageCard(subscription: profile.subscription) + + HStack(spacing: 12) { + Button { Task { await state.refresh() } } label: { + Label("刷新", systemImage: "arrow.clockwise") + .frame(maxWidth: .infinity) + } + .buttonStyle(.bordered) + .disabled(state.busy) + Button(role: .destructive) { Task { await state.logout() } } label: { + Label("退出账号", systemImage: "rectangle.portrait.and.arrow.right") + .frame(maxWidth: .infinity) + } + .buttonStyle(.bordered) + .disabled(state.busy) + } + } + .frame(maxWidth: 760) + .padding(.horizontal, 18) + .padding(.vertical, 18) + } + } +} + +private struct StatusCard: View { + @EnvironmentObject private var state: AppState + + var body: some View { + UCVLCard(title: "连接状态", systemImage: "network.badge.shield.half.filled") { + HStack(spacing: 14) { + Circle() + .fill(state.statusIsActive ? Color.green : Color.gray) + .frame(width: 13, height: 13) + VStack(alignment: .leading, spacing: 4) { + Text(state.statusTitle).font(.title3.bold()) + Text(state.message.isEmpty ? "点击连接,vpn-ai 将自动选择并验证工作节点" : state.message) + .font(.subheadline) + .foregroundStyle(.secondary) + } + Spacer() + } + } + } +} + +private struct UsageCard: View { + let subscription: SubscriptionProfile + + private var fraction: Double { + guard subscription.trafficLimitBytes > 0 else { return 0 } + return min(1, max(0, Double(subscription.usedBytes) / Double(subscription.trafficLimitBytes))) + } + + var body: some View { + UCVLCard(title: "本期流量", systemImage: "chart.bar.fill") { + VStack(alignment: .leading, spacing: 12) { + HStack { + Text(format(subscription.usedBytes)) + Spacer() + Text(subscription.trafficLimitBytes > 0 ? format(subscription.trafficLimitBytes) : "不限流量") + .foregroundStyle(UCVLColors.royal) + } + ProgressView(value: fraction) + .tint(UCVLColors.royal) + Text("套餐:\(subscription.plan) · 设备上限 \(subscription.deviceLimit) 台\(expiryText)") + .font(.footnote) + .foregroundStyle(.secondary) + } + } + } + + private var expiryText: String { + guard let expiresAt = subscription.expiresAt else { return " · 长期有效" } + return " · 到期 \(String(expiresAt.prefix(10)))" + } + + private func format(_ value: Int64) -> String { + ByteCountFormatter.string(fromByteCount: value, countStyle: .file) + } +} + +private struct UCVLCard: View { + let title: String + let systemImage: String + let content: Content + + init(title: String, systemImage: String, @ViewBuilder content: () -> Content) { + self.title = title + self.systemImage = systemImage + self.content = content() + } + + var body: some View { + VStack(alignment: .leading, spacing: 16) { + Label(title, systemImage: systemImage) + .font(.headline) + .foregroundStyle(UCVLColors.navy) + content + } + .padding(20) + .background(.white, in: RoundedRectangle(cornerRadius: 22, style: .continuous)) + .shadow(color: .black.opacity(0.08), radius: 14, y: 7) + } +} + +private enum UCVLColors { + static let navy = Color(red: 0.02, green: 0.10, blue: 0.26) + static let royal = Color(red: 0.02, green: 0.39, blue: 0.86) + static let sky = Color(red: 0.17, green: 0.73, blue: 0.98) + static let background = LinearGradient( + colors: [navy, Color(red: 0.03, green: 0.25, blue: 0.48)], + startPoint: .topLeading, + endPoint: .bottomTrailing + ) +} + +private extension View { + func ucvlField() -> some View { + self + .padding(.horizontal, 14) + .frame(height: 52) + .background(Color.gray.opacity(0.08), in: RoundedRectangle(cornerRadius: 13)) + .overlay(RoundedRectangle(cornerRadius: 13).stroke(Color.gray.opacity(0.2))) + } +} diff --git a/ios/App/Info.plist b/ios/App/Info.plist new file mode 100644 index 0000000..899d535 --- /dev/null +++ b/ios/App/Info.plist @@ -0,0 +1,3 @@ + + + diff --git a/ios/App/PlatformAPI.swift b/ios/App/PlatformAPI.swift new file mode 100644 index 0000000..d0acda3 --- /dev/null +++ b/ios/App/PlatformAPI.swift @@ -0,0 +1,195 @@ +import Foundation +import UIKit + +actor PlatformAPI { + static let shared = PlatformAPI() + + private let baseURL = URL(string: "https://vpn.toplc.cn/")! + private let session: URLSession + private let decoder = JSONDecoder() + private let encoder = JSONEncoder() + + init() { + let configuration = URLSessionConfiguration.ephemeral + configuration.timeoutIntervalForRequest = 20 + configuration.timeoutIntervalForResource = 30 + configuration.waitsForConnectivity = true + configuration.httpAdditionalHeaders = [ + "Accept": "application/json", + "User-Agent": "UCVL-Zonghengjia/1.0.2 iOS", + ] + session = URLSession(configuration: configuration) + } + + func login(login: String, password: String) async throws -> LoginResponse { + let payload: [String: String] = [ + "login": login, + "password": password, + "device_id": SecureStore.deviceID(), + "device_name": await MainActor.run { UIDevice.current.name }, + "app_version": Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0.2", + "platform": "ios", + ] + return try await send( + path: "api/v1/client/login/", + method: "POST", + body: try encoder.encode(payload), + token: nil, + as: LoginResponse.self + ) + } + + func profile(token: String) async throws -> ClientProfile { + let envelope = try await send( + path: "api/v1/client/profile/", + method: "GET", + body: nil, + token: token, + as: ProfileEnvelope.self + ) + return envelope.profile + } + + func config(token: String, route: String, excluding excludedNodes: [String] = []) async throws -> ClientConfigResponse { + var components = URLComponents(url: baseURL.appendingPathComponent("api/v1/client/config/"), resolvingAgainstBaseURL: false)! + components.queryItems = [ + URLQueryItem(name: "node", value: "auto"), + URLQueryItem(name: "route", value: route), + URLQueryItem(name: "new_connection", value: "1"), + ] + if !excludedNodes.isEmpty { + components.queryItems?.append( + URLQueryItem(name: "exclude", value: excludedNodes.sorted().joined(separator: ",")) + ) + } + return try await send(url: components.url!, method: "GET", body: nil, token: token, as: ClientConfigResponse.self) + } + + func verifyProxyEgress() async throws { + let endpoints = [ + URL(string: "https://api.openai.com/v1/models")!, + URL(string: "https://chatgpt.com/api/auth/session")!, + ] + let configuration = URLSessionConfiguration.ephemeral + configuration.timeoutIntervalForRequest = 12 + configuration.timeoutIntervalForResource = 15 + configuration.waitsForConnectivity = false + configuration.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData + let verifier = URLSession(configuration: configuration) + defer { verifier.invalidateAndCancel() } + + for endpoint in endpoints { + var request = URLRequest(url: endpoint) + request.httpMethod = "GET" + request.setValue("no-cache", forHTTPHeaderField: "Cache-Control") + do { + let (_, response) = try await verifier.data(for: request) + if let http = response as? HTTPURLResponse, (200..<500).contains(http.statusCode) { + return + } + } catch { + continue + } + } + throw UCVLError.connection("当前节点未通过 OpenAI/ChatGPT 出口验证,正在切换其它节点。") + } + + func resolvePublicIPv4(host: String) async throws -> String { + if NetworkAddress.isPublicIPv4(host) { return host } + // 001/002 是后台节点名称。NPM TCP Stream 依靠 11081/11082 等端口 + // 分流,不要求每个节点子域名都单独发布 A 记录;解析不到时使用统一入口。 + let candidateHosts = host == "vpn.toplc.cn" ? [host] : [host, "vpn.toplc.cn"] + let resolvers = [ + "https://dns.alidns.com/resolve", + "https://doh.pub/resolve", + ] + + for candidateHost in candidateHosts { + for resolver in resolvers { + guard var components = URLComponents(string: resolver) else { continue } + components.queryItems = [ + URLQueryItem(name: "name", value: candidateHost), + URLQueryItem(name: "type", value: "A"), + ] + guard let url = components.url else { continue } + var request = URLRequest(url: url) + request.httpMethod = "GET" + request.setValue("application/dns-json", forHTTPHeaderField: "Accept") + do { + let (data, response) = try await session.data(for: request) + guard let http = response as? HTTPURLResponse, + (200..<300).contains(http.statusCode), + let result = try? decoder.decode(DNSResponse.self, from: data) + else { continue } + if let address = result.answer? + .first(where: { $0.type == 1 && NetworkAddress.isPublicIPv4($0.data) })? + .data { + return address + } + } catch { + continue + } + } + } + throw UCVLError.connection("无法取得 NPM 入口 vpn.toplc.cn 的真实公网 IPv4;已拒绝 Fake-IP/内网地址。") + } + + func logout(token: String) async { + _ = try? await send( + path: "api/v1/client/logout/", + method: "POST", + body: Data(), + token: token, + as: EmptyResponse.self + ) + } + + private func send( + path: String, + method: String, + body: Data?, + token: String?, + as type: T.Type + ) async throws -> T { + try await send(url: baseURL.appendingPathComponent(path), method: method, body: body, token: token, as: type) + } + + private func send( + url: URL, + method: String, + body: Data?, + token: String?, + as type: T.Type + ) async throws -> T { + var request = URLRequest(url: url) + request.httpMethod = method + request.httpBody = body + request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") + if let token { request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") } + + let (data, response) = try await session.data(for: request) + guard let http = response as? HTTPURLResponse else { throw UCVLError.invalidResponse } + guard (200..<300).contains(http.statusCode) else { + let message = (try? decoder.decode(APIErrorEnvelope.self, from: data).error) + ?? "服务暂时不可用(\(http.statusCode))。" + throw UCVLError.api(status: http.statusCode, message: message) + } + guard let value = try? decoder.decode(type, from: data) else { throw UCVLError.invalidResponse } + return value + } +} + +private struct EmptyResponse: Decodable {} + +private struct DNSResponse: Decodable { + let answer: [DNSAnswer]? + + enum CodingKeys: String, CodingKey { + case answer = "Answer" + } +} + +private struct DNSAnswer: Decodable { + let type: Int + let data: String +} diff --git a/ios/App/SecureStore.swift b/ios/App/SecureStore.swift new file mode 100644 index 0000000..6a5148e --- /dev/null +++ b/ios/App/SecureStore.swift @@ -0,0 +1,75 @@ +import Foundation +import Security + +enum SecureStore { + private static let service = "cn.toplc.zonghengjia.credentials" + private static let tokenAccount = "access-token" + private static let deviceAccount = "device-id" + private static let lastLoginKey = "ucvl.last-login" + + static var lastLogin: String { + get { UserDefaults.standard.string(forKey: lastLoginKey) ?? "" } + set { UserDefaults.standard.set(newValue, forKey: lastLoginKey) } + } + + static func token() -> String? { + read(account: tokenAccount) + } + + static func saveToken(_ token: String) throws { + try write(token, account: tokenAccount) + } + + static func clearToken() { + delete(account: tokenAccount) + } + + static func deviceID() -> String { + if let stored = read(account: deviceAccount), !stored.isEmpty { + return stored + } + let created = "ios-\(UUID().uuidString.lowercased())" + try? write(created, account: deviceAccount) + return created + } + + private static func read(account: String) -> String? { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + kSecMatchLimit as String: kSecMatchLimitOne, + kSecReturnData as String: true, + ] + var result: CFTypeRef? + guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess, + let data = result as? Data + else { return nil } + return String(data: data, encoding: .utf8) + } + + private static func write(_ value: String, account: String) throws { + guard let data = value.data(using: .utf8) else { return } + delete(account: account) + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly, + kSecValueData as String: data, + ] + let status = SecItemAdd(query as CFDictionary, nil) + guard status == errSecSuccess else { + throw UCVLError.invalidConfiguration("无法安全保存登录授权(\(status))。") + } + } + + private static func delete(account: String) { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + ] + SecItemDelete(query as CFDictionary) + } +} diff --git a/ios/App/UCVLZonghengjia.entitlements b/ios/App/UCVLZonghengjia.entitlements new file mode 100644 index 0000000..c3f437e --- /dev/null +++ b/ios/App/UCVLZonghengjia.entitlements @@ -0,0 +1,10 @@ + + + + + com.apple.developer.networking.networkextension + + packet-tunnel-provider + + + diff --git a/ios/App/UCVLZonghengjiaApp.swift b/ios/App/UCVLZonghengjiaApp.swift new file mode 100644 index 0000000..4f3cafe --- /dev/null +++ b/ios/App/UCVLZonghengjiaApp.swift @@ -0,0 +1,14 @@ +import SwiftUI + +@main +struct UCVLZonghengjiaApp: App { + @StateObject private var state = AppState() + + var body: some Scene { + WindowGroup { + ContentView() + .environmentObject(state) + .task { await state.start() } + } + } +} diff --git a/ios/App/VPNController.swift b/ios/App/VPNController.swift new file mode 100644 index 0000000..5934732 --- /dev/null +++ b/ios/App/VPNController.swift @@ -0,0 +1,157 @@ +import Foundation +import NetworkExtension + +@MainActor +final class VPNController: ObservableObject { + @Published private(set) var status: NEVPNStatus = .invalid + @Published private(set) var activeNodeSlug: String? + private var manager: NETunnelProviderManager? + private var observer: NSObjectProtocol? + + init() { + observer = NotificationCenter.default.addObserver( + forName: .NEVPNStatusDidChange, + object: nil, + queue: .main + ) { [weak self] note in + guard let connection = note.object as? NEVPNConnection else { return } + Task { @MainActor in self?.status = connection.status } + } + } + + deinit { + if let observer { NotificationCenter.default.removeObserver(observer) } + } + + func restore() async { + do { + manager = try await loadManager() + status = manager?.connection.status ?? .invalid + if isConnected, + let tunnelProtocol = manager?.protocolConfiguration as? NETunnelProviderProtocol, + let configuration = tunnelProtocol.providerConfiguration { + activeNodeSlug = configuration["nodeSlug"] as? String + } + } catch { + status = .invalid + activeNodeSlug = nil + } + } + + func connect(configJSON: String, resolvedRemoteAddress: String, node: VPNNode, route: RouteMode) async throws { + guard route.id != "direct" else { + disconnect() + return + } + let selected = try await loadManager() + let tunnelProtocol = NETunnelProviderProtocol() + tunnelProtocol.providerBundleIdentifier = "cn.toplc.zonghengjia.PacketTunnel" + tunnelProtocol.serverAddress = node.name + tunnelProtocol.disconnectOnSleep = false + tunnelProtocol.includeAllNetworks = false + tunnelProtocol.providerConfiguration = [ + "configJSON": configJSON, + "resolvedRemoteAddress": resolvedRemoteAddress, + "nodeSlug": node.slug, + "nodeName": node.name, + "routeMode": route.id, + ] + + selected.localizedDescription = "优创⁺纵横家" + selected.protocolConfiguration = tunnelProtocol + selected.isEnabled = true + try await save(selected) + try await reload(selected) + manager = selected + activeNodeSlug = node.slug + do { + try selected.connection.startVPNTunnel() + } catch { + activeNodeSlug = nil + throw UCVLError.vpnPermission("系统 VPN 启动失败,请在“设置”中允许优创⁺纵横家添加 VPN 配置。") + } + do { + try await waitUntilConnected(selected.connection) + } catch { + selected.connection.stopVPNTunnel() + activeNodeSlug = nil + throw error + } + } + + func disconnect() { + manager?.connection.stopVPNTunnel() + activeNodeSlug = nil + } + + func disconnectAndWait(timeout: TimeInterval = 8) async { + disconnect() + let deadline = Date().addingTimeInterval(timeout) + while Date() < deadline { + let current = manager?.connection.status ?? .disconnected + status = current + if current == .disconnected || current == .invalid { return } + try? await Task.sleep(nanoseconds: 200_000_000) + } + } + + var isConnected: Bool { + status == .connected || status == .connecting || status == .reasserting + } + + private func waitUntilConnected(_ connection: NEVPNConnection, timeout: TimeInterval = 25) async throws { + let deadline = Date().addingTimeInterval(timeout) + var observedTransition = false + while Date() < deadline { + let current = connection.status + status = current + switch current { + case .connected: + return + case .connecting, .reasserting: + observedTransition = true + case .disconnected where observedTransition: + throw UCVLError.connection("Apple 系统 VPN 扩展启动后退出。") + case .invalid: + throw UCVLError.connection("Apple 系统 VPN 配置无效。") + default: + break + } + try await Task.sleep(nanoseconds: 250_000_000) + } + throw UCVLError.connection("Apple 系统 VPN 连接超时。") + } + + private func loadManager() async throws -> NETunnelProviderManager { + let managers: [NETunnelProviderManager] = try await withCheckedThrowingContinuation { continuation in + NETunnelProviderManager.loadAllFromPreferences { managers, error in + if let error { continuation.resume(throwing: error) } + else { continuation.resume(returning: managers ?? []) } + } + } + if let existing = managers.first(where: { + ($0.protocolConfiguration as? NETunnelProviderProtocol)?.providerBundleIdentifier == "cn.toplc.zonghengjia.PacketTunnel" + }) { + return existing + } + return NETunnelProviderManager() + } + + private func save(_ manager: NETunnelProviderManager) async throws { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + manager.saveToPreferences { error in + if let error { continuation.resume(throwing: error) } + else { continuation.resume(returning: ()) } + } + } + } + + private func reload(_ manager: NETunnelProviderManager) async throws { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + manager.loadFromPreferences { error in + if let error { continuation.resume(throwing: error) } + else { continuation.resume(returning: ()) } + } + } + } +} diff --git a/ios/LICENSE.md b/ios/LICENSE.md new file mode 100644 index 0000000..381a41b --- /dev/null +++ b/ios/LICENSE.md @@ -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. diff --git a/ios/NOTICE.md b/ios/NOTICE.md new file mode 100644 index 0000000..a0b22dd --- /dev/null +++ b/ios/NOTICE.md @@ -0,0 +1,10 @@ +# 第三方许可及 MIT 范围 + +顶层及 Windows、后台、iOS 中 MIT 仅适用于 UCVL 有权授权的自有程序代码/文档与原创山水插画。第三方代码、库、数据、工具、商标、公司名称与 Logo 另行适用原权利及许可证,不因聚合仓库的 MIT 而被重新许可;此发布不授予公司商标权或服务访问权。 + +- Windows:windows/THIRD_PARTY_NOTICES.md 原文保留;windows/licenses/ 包含固定发行 payload 中的 Xray MPL-2.0、Wintun 预编译二进制再分发许可、NSIS 许可。这里不分发这些第三方可执行文件。 +- iOS:ios/THIRD_PARTY_NOTICES.md、ios/ThirdParty/libXray-MIT.txt、ios/ThirdParty/Xray-core-MPL-2.0.txt 原文保留。Vendor XCFramework 与未明确来源许可的 Geo 数据未打包。 +- Android:保留其既有 GPL-3.0 项目及 LGPL/MIT/lwIP/Wintun 等依赖许可,见 android/README.md 链接;不改为 MIT。 +- 后台:requirements.txt 记录依赖。安装的第三方依赖继续遵循各上游版本许可证,不属于公司 MIT 再许可范围。 + +来源许可不明的用户提供登录图片未纳入此导出。原候选安装包、签名、生产数据库、配置及凭据不在公开源码范围。 diff --git a/ios/PacketTunnel/Info.plist b/ios/PacketTunnel/Info.plist new file mode 100644 index 0000000..899d535 --- /dev/null +++ b/ios/PacketTunnel/Info.plist @@ -0,0 +1,3 @@ + + + diff --git a/ios/PacketTunnel/PacketTunnel.entitlements b/ios/PacketTunnel/PacketTunnel.entitlements new file mode 100644 index 0000000..c3f437e --- /dev/null +++ b/ios/PacketTunnel/PacketTunnel.entitlements @@ -0,0 +1,10 @@ + + + + + com.apple.developer.networking.networkextension + + packet-tunnel-provider + + + diff --git a/ios/PacketTunnel/PacketTunnelProvider.swift b/ios/PacketTunnel/PacketTunnelProvider.swift new file mode 100644 index 0000000..62df280 --- /dev/null +++ b/ios/PacketTunnel/PacketTunnelProvider.swift @@ -0,0 +1,171 @@ +import Darwin +import Foundation +import NetworkExtension + +final class PacketTunnelProvider: NEPacketTunnelProvider { + private let coreQueue = DispatchQueue(label: "cn.toplc.zonghengjia.xray-core", qos: .userInitiated) + + override func startTunnel( + options: [String: NSObject]? = nil, + completionHandler: @escaping (Error?) -> Void + ) { + guard let tunnelProtocol = protocolConfiguration as? NETunnelProviderProtocol, + let providerConfiguration = tunnelProtocol.providerConfiguration, + let rawJSON = providerConfiguration["configJSON"] as? String + else { + completionHandler(UCVLError.invalidConfiguration("没有收到线路配置,请返回应用重新连接。")) + return + } + + guard let remoteHost = TunnelConfigurationBuilder.remoteAddress(from: rawJSON) else { + completionHandler(UCVLError.invalidConfiguration("线路配置缺少节点地址。")) + return + } + + let providedRemoteAddress = providerConfiguration["resolvedRemoteAddress"] as? String + coreQueue.async { [weak self] in + guard let self else { return } + do { + let resolvedRemoteAddress: String + if let providedRemoteAddress, NetworkAddress.isPublicIPv4(providedRemoteAddress) { + resolvedRemoteAddress = providedRemoteAddress + } else { + resolvedRemoteAddress = try Self.resolveIPv4Address(remoteHost) + } + let settings = self.makeNetworkSettings(remoteAddress: resolvedRemoteAddress) + self.setTunnelNetworkSettings(settings) { [weak self] error in + guard let self else { return } + if let error { + completionHandler(error) + return + } + self.coreQueue.async { + do { + guard let tunnelFD = Self.findTunnelFileDescriptor() else { + throw UCVLError.invalidConfiguration("无法取得 Apple utun 虚拟网卡。") + } + guard let geoIP = Bundle.main.url(forResource: "geoip", withExtension: "dat"), + Bundle.main.url(forResource: "geosite", withExtension: "dat") != nil + else { + throw UCVLError.invalidConfiguration("路由规则资源缺失。") + } + let config = try TunnelConfigurationBuilder.makeConfiguration( + rawJSON: rawJSON, + tunnelFileDescriptor: tunnelFD, + assetDirectory: geoIP.deletingLastPathComponent().path, + resolvedRemoteAddress: resolvedRemoteAddress + ) + XrayBridge.stop() + try XrayBridge.start(configJSON: config) + completionHandler(nil) + } catch { + XrayBridge.stop() + completionHandler(error) + } + } + } + } catch { + completionHandler(error) + } + } + } + + override func stopTunnel( + with reason: NEProviderStopReason, + completionHandler: @escaping () -> Void + ) { + coreQueue.async { + XrayBridge.stop() + completionHandler() + } + } + + override func handleAppMessage(_ messageData: Data, completionHandler: ((Data?) -> Void)? = nil) { + let response = ["running": XrayBridge.isRunning()] + completionHandler?(try? JSONSerialization.data(withJSONObject: response)) + } + + override func sleep(completionHandler: @escaping () -> Void) { + completionHandler() + } + + override func wake() {} + + private func makeNetworkSettings(remoteAddress: String) -> NEPacketTunnelNetworkSettings { + let settings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: remoteAddress) + let ipv4 = NEIPv4Settings(addresses: ["198.18.0.1"], subnetMasks: ["255.255.0.0"]) + ipv4.includedRoutes = [NEIPv4Route.default()] + if Self.isIPv4Address(remoteAddress) { + ipv4.excludedRoutes = [NEIPv4Route(destinationAddress: remoteAddress, subnetMask: "255.255.255.255")] + } + settings.ipv4Settings = ipv4 + + let ipv6 = NEIPv6Settings(addresses: ["fd00:7563:766c::1"], networkPrefixLengths: [64]) + ipv6.includedRoutes = [NEIPv6Route.default()] + settings.ipv6Settings = ipv6 + + let dns = NEDNSSettings(servers: ["1.1.1.1", "8.8.8.8"]) + dns.matchDomains = [""] + settings.dnsSettings = dns + settings.mtu = 1500 + return settings + } + + private static func findTunnelFileDescriptor() -> Int32? { + for fileDescriptor in Int32(0)...Int32(1024) { + var interfaceName = [CChar](repeating: 0, count: Int(IFNAMSIZ)) + var length = socklen_t(interfaceName.count) + let result = interfaceName.withUnsafeMutableBytes { pointer in + getsockopt( + fileDescriptor, + SYSPROTO_CONTROL, + 2, + pointer.baseAddress, + &length + ) + } + if result == 0, String(cString: interfaceName).hasPrefix("utun") { + return fileDescriptor + } + } + return nil + } + + private static func isIPv4Address(_ value: String) -> Bool { + var address = in_addr() + return value.withCString { inet_pton(AF_INET, $0, &address) } == 1 + } + + private static func resolveIPv4Address(_ host: String) throws -> String { + if NetworkAddress.isPublicIPv4(host) { return host } + + var hints = addrinfo() + hints.ai_flags = AI_ADDRCONFIG + hints.ai_family = AF_INET + hints.ai_socktype = Int32(SOCK_STREAM.rawValue) + hints.ai_protocol = IPPROTO_TCP + var results: UnsafeMutablePointer? + let status = host.withCString { getaddrinfo($0, nil, &hints, &results) } + guard status == 0, let first = results else { + let reason = status == 0 ? "没有 IPv4 地址" : String(cString: gai_strerror(status)) + throw UCVLError.invalidConfiguration("无法解析节点域名 \(host):\(reason)。") + } + defer { freeaddrinfo(first) } + + var cursor: UnsafeMutablePointer? = first + while let current = cursor { + cursor = current.pointee.ai_next + guard current.pointee.ai_family == AF_INET, + let socketAddress = current.pointee.ai_addr + else { continue } + var address = socketAddress.withMemoryRebound(to: sockaddr_in.self, capacity: 1) { + $0.pointee.sin_addr + } + var text = [CChar](repeating: 0, count: Int(INET_ADDRSTRLEN)) + guard inet_ntop(AF_INET, &address, &text, socklen_t(INET_ADDRSTRLEN)) != nil else { continue } + let value = String(cString: text) + if NetworkAddress.isPublicIPv4(value) { return value } + } + throw UCVLError.invalidConfiguration("节点域名 \(host) 没有可用的 IPv4 地址。") + } +} diff --git a/ios/PacketTunnel/XrayBridge.swift b/ios/PacketTunnel/XrayBridge.swift new file mode 100644 index 0000000..8f97b81 --- /dev/null +++ b/ios/PacketTunnel/XrayBridge.swift @@ -0,0 +1,46 @@ +import Darwin +import Foundation +import LibXray + +enum XrayBridge { + static func start(configJSON: String) throws { + _ = try invoke(method: "runXrayFromJson", payload: ["configJSON": configJSON]) + } + + static func stop() { + _ = try? invoke(method: "stopXray", payload: nil) + } + + static func isRunning() -> Bool { + guard let data = try? invoke(method: "getXrayState", payload: nil) else { return false } + return data["running"] as? Bool ?? false + } + + @discardableResult + private static func invoke(method: String, payload: [String: Any]?) throws -> [String: Any] { + var request: [String: Any] = ["apiVersion": 1, "method": method] + if let payload { request["payload"] = payload } + let requestData = try JSONSerialization.data(withJSONObject: request, options: []) + let requestText = String(decoding: requestData, as: UTF8.self) + guard let requestPointer = requestText.withCString({ strdup($0) }) else { + throw UCVLError.invalidConfiguration("无法调用 Xray 核心。") + } + defer { free(requestPointer) } + guard let responsePointer = CGoInvoke(requestPointer) else { + throw UCVLError.invalidConfiguration("Xray 核心没有返回结果。") + } + defer { CGoFree(responsePointer) } + + let responseText = String(cString: responsePointer) + guard let responseData = responseText.data(using: .utf8), + let response = try JSONSerialization.jsonObject(with: responseData) as? [String: Any] + else { + throw UCVLError.invalidConfiguration("Xray 核心返回格式错误。") + } + guard response["success"] as? Bool == true else { + let error = response["error"] as? String ?? "Xray 核心启动失败。" + throw UCVLError.invalidConfiguration(error) + } + return response["data"] as? [String: Any] ?? [:] + } +} diff --git a/ios/README.md b/ios/README.md new file mode 100644 index 0000000..c27eadc --- /dev/null +++ b/ios/README.md @@ -0,0 +1,15 @@ +# 纵横家 iPhone / iPad 1.0.2 源码候选版(开源) + +Swift 主应用与 Apple Packet Tunnel 扩展源码,版本 `1.0.2`,最低 iOS 15。仅为源码快照和静态结构检查;没有可安装 IPA,未执行 Xcode 编译、XCTest、Apple 签名或 iPhone/iPad 真机 VPN 验收。macOS 客户端不在本目录范围。 + +## 构建前提 + +需要 Mac、Xcode、XcodeGen,以及获授权的 Apple Developer Team、Network Extension 权限和 Provisioning Profile。本快照通过 Git API 创建,脚本执行位不保留;在 Mac 的本目录先运行 `chmod +x Scripts/*.sh`,再运行 `./Scripts/generate-project.sh` 生成工程。`./Scripts/verify-and-archive.sh` 提供测试/归档入口,不代表这里已执行通过。公开示例端点需替换成自己的配置。 + +Scripts/fetch-libxray.sh 从原固定官方版本 v26.7.28 下载 Apple cgo XCFramework,并核验其源码中固定的 SHA-256;Vendor/ 二进制不在本仓库。下载脚本仅恢复 libXray,不能恢复 Geo 数据,也不提供 Apple 签名材料。 + +## 未打包的 Geo 数据 + +Resources/Geo/geoip.dat 与 geosite.dat 未纳入公开导出:旧源码未完整记录数据项目/版本及许可。project.yml 仍保留 Resources/Geo 的资源接入位置,但构建前须自行从可信官方数据源取得对应数据、核验下载校验值与许可,并放入该目录。此仓库不猜测或声称存在已验证的 Geo 下载 URL/hash,不能把 libXray 归档校验值当作 Geo 校验值。 + +公司自有代码适用 LICENSE.md/MIT;ThirdParty/ 和 THIRD_PARTY_NOTICES.md 保留原始第三方许可证与说明。公司商标/Logo 不在 MIT 授权范围。公司公开 API 域名只为源码兼容保留,不授予服务访问权限。 diff --git a/ios/Resources/Assets.xcassets/AppIcon.appiconset/AppIcon-UCVL-opaque.png b/ios/Resources/Assets.xcassets/AppIcon.appiconset/AppIcon-UCVL-opaque.png new file mode 100644 index 0000000..93cee31 Binary files /dev/null and b/ios/Resources/Assets.xcassets/AppIcon.appiconset/AppIcon-UCVL-opaque.png differ diff --git a/ios/Resources/Assets.xcassets/AppIcon.appiconset/AppIcon.png b/ios/Resources/Assets.xcassets/AppIcon.appiconset/AppIcon.png new file mode 100644 index 0000000..985a9d9 Binary files /dev/null and b/ios/Resources/Assets.xcassets/AppIcon.appiconset/AppIcon.png differ diff --git a/ios/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..1f2ba2d --- /dev/null +++ b/ios/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images" : [ + { + "filename" : "AppIcon-UCVL-opaque.png", + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/ios/Resources/Assets.xcassets/Contents.json b/ios/Resources/Assets.xcassets/Contents.json new file mode 100644 index 0000000..73c0059 --- /dev/null +++ b/ios/Resources/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/ios/Resources/Assets.xcassets/UCVLLaunchBackground.colorset/Contents.json b/ios/Resources/Assets.xcassets/UCVLLaunchBackground.colorset/Contents.json new file mode 100644 index 0000000..6e12d02 --- /dev/null +++ b/ios/Resources/Assets.xcassets/UCVLLaunchBackground.colorset/Contents.json @@ -0,0 +1,20 @@ +{ + "colors" : [ + { + "color" : { + "color-space" : "srgb", + "components" : { + "alpha" : "1.000", + "blue" : "0.169", + "green" : "0.102", + "red" : "0.020" + } + }, + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/ios/Resources/Assets.xcassets/UCVLLogo.imageset/Contents.json b/ios/Resources/Assets.xcassets/UCVLLogo.imageset/Contents.json new file mode 100644 index 0000000..bc38c65 --- /dev/null +++ b/ios/Resources/Assets.xcassets/UCVLLogo.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "filename" : "UCVLLogo.png", + "idiom" : "universal", + "scale" : "1x" + }, + { + "idiom" : "universal", + "scale" : "2x" + }, + { + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/ios/Resources/Assets.xcassets/UCVLLogo.imageset/UCVLLogo.png b/ios/Resources/Assets.xcassets/UCVLLogo.imageset/UCVLLogo.png new file mode 100644 index 0000000..985a9d9 Binary files /dev/null and b/ios/Resources/Assets.xcassets/UCVLLogo.imageset/UCVLLogo.png differ diff --git a/ios/Resources/Geo/README.md b/ios/Resources/Geo/README.md new file mode 100644 index 0000000..0531db0 --- /dev/null +++ b/ios/Resources/Geo/README.md @@ -0,0 +1 @@ +Geo 数据未打包。请按 ../../README.md 的资源说明取得并核验自己的合法数据;libXray 下载脚本不恢复 Geo 数据。 diff --git a/ios/Scripts/fetch-libxray.sh b/ios/Scripts/fetch-libxray.sh new file mode 100644 index 0000000..6a29bf0 --- /dev/null +++ b/ios/Scripts/fetch-libxray.sh @@ -0,0 +1,35 @@ +#!/bin/sh +set -eu + +root_dir=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +vendor_dir="$root_dir/Vendor" +destination="$vendor_dir/LibXray.xcframework" +archive_url="https://github.com/XTLS/libXray/releases/download/v26.7.28/libxray-apple-cgo.zip" +expected_sha256="07f7ed7697277930e1c517755855950f594f41435b0dfc5917a66eea6278aeb9" + +if [ -d "$destination" ]; then + echo "LibXray.xcframework 已存在。" + exit 0 +fi + +work_dir=$(mktemp -d "${TMPDIR:-/tmp}/ucvl-libxray.XXXXXX") +trap 'rm -rf "$work_dir"' EXIT INT TERM +archive_path="$work_dir/libxray-apple-cgo.zip" + +curl --fail --location --retry 3 --output "$archive_path" "$archive_url" +actual_sha256=$(shasum -a 256 "$archive_path" | awk '{print tolower($1)}') +if [ "$actual_sha256" != "$expected_sha256" ]; then + echo "libXray SHA256 校验失败。" >&2 + exit 1 +fi + +unzip -q "$archive_path" -d "$work_dir/unpacked" +framework_path=$(find "$work_dir/unpacked" -type d -name LibXray.xcframework -print -quit) +if [ -z "$framework_path" ]; then + echo "官方压缩包中没有 LibXray.xcframework。" >&2 + exit 1 +fi + +mkdir -p "$vendor_dir" +mv "$framework_path" "$destination" +echo "已安装并校验 libXray v26.7.28。" diff --git a/ios/Scripts/generate-project.sh b/ios/Scripts/generate-project.sh new file mode 100644 index 0000000..8fbf04e --- /dev/null +++ b/ios/Scripts/generate-project.sh @@ -0,0 +1,8 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +command -v xcodegen >/dev/null 2>&1 || { + echo "请先安装 XcodeGen:brew install xcodegen" >&2 + exit 1 +} +xcodegen generate diff --git a/ios/Scripts/source-audit.py b/ios/Scripts/source-audit.py new file mode 100644 index 0000000..8c7dc1f --- /dev/null +++ b/ios/Scripts/source-audit.py @@ -0,0 +1,122 @@ +from __future__ import annotations + +import hashlib +import json +import plistlib +import re +import sys +from pathlib import Path + + +ROOT = Path(__file__).resolve().parent.parent +EXPECTED = [ + "project.yml", + "App/AppState.swift", + "App/ContentView.swift", + "App/PlatformAPI.swift", + "App/VPNController.swift", + "PacketTunnel/PacketTunnelProvider.swift", + "PacketTunnel/XrayBridge.swift", + "Shared/Models.swift", + "Shared/TunnelConfigurationBuilder.swift", + "Shared/NetworkAddress.swift", + "Tests/TunnelConfigurationBuilderTests.swift", + "Tests/ClientConfigResponseTests.swift", + "Shared/ConnectionAttemptPolicy.swift", + "Tests/ConnectionAttemptPolicyTests.swift", +] + + +def require(condition: bool, message: str) -> None: + if not condition: + raise RuntimeError(message) + + +def main() -> int: + for relative in EXPECTED: + require((ROOT / relative).is_file(), f"缺少文件:{relative}") + + for relative in ("App/Info.plist", "PacketTunnel/Info.plist", "App/UCVLZonghengjia.entitlements", "PacketTunnel/PacketTunnel.entitlements"): + with (ROOT / relative).open("rb") as stream: + value = plistlib.load(stream) + if relative.endswith("entitlements"): + require( + "packet-tunnel-provider" in value.get("com.apple.developer.networking.networkextension", []), + f"Network Extension 权限缺失:{relative}", + ) + + project = (ROOT / "project.yml").read_text(encoding="utf-8") + version_match = re.search(r'MARKETING_VERSION:\s*"(\d+\.\d+\.\d+)"', project) + require(version_match is not None, "缺少规范的源码版本号") + source_version = version_match.group(1) + readme = (ROOT / "README.md").read_text(encoding="utf-8") + require(f"{source_version} 源码候选版" in readme.splitlines()[0] + and f"版本 `{source_version}`" in readme, "README 与工程版本不一致") + require("cn.toplc.zonghengjia.PacketTunnel" in project, "Packet Tunnel Bundle ID 缺失") + require('iOS: "15.0"' in project, "iOS 最低版本与验收基线不一致") + + app_state = (ROOT / "App/AppState.swift").read_text(encoding="utf-8") + api = (ROOT / "App/PlatformAPI.swift").read_text(encoding="utf-8") + tunnel = (ROOT / "PacketTunnel/PacketTunnelProvider.swift").read_text(encoding="utf-8") + require("selectedNodeID" not in app_state, "客户端仍暴露节点选择") + require('URLQueryItem(name: "node", value: "auto")' in api, "未启用后台自动选节点") + require("verifyProxyEgress" in api and "verifyProxyEgress" in app_state, "缺少出口验证") + require("resolveIPv4Address" in tunnel and "excludedRoutes" in tunnel, "缺少节点域名防回环处理") + require("dns.alidns.com/resolve" in api and "doh.pub/resolve" in api, "缺少国内 DoH 真实地址解析") + require("NetworkAddress.isPublicIPv4" in api and "NetworkAddress.isPublicIPv4" in tunnel, "未拒绝 Fake-IP/内网地址") + require("response.gateway" in app_state and "configContract" in (ROOT / "Shared/Models.swift").read_text(encoding="utf-8"), "未兼容后台网关契约") + require("vpn.status == .connected" in app_state, "出口验证后未复核系统 VPN 状态") + require("ConnectionAttemptPolicy.decide" in app_state and "attemptedNode" in app_state, + "未区分控制面、本地授权与节点出口故障") + + secret_pattern = re.compile( + r"(?i)(password|passwd|private[_-]?key)['\"]?\s*[:=]\s*['\"][^'\"]{4,}['\"]" + ) + findings: list[str] = [] + for path in ROOT.rglob("*"): + if not path.is_file() or any(part in {".git", "Vendor", "BuildArtifacts"} for part in path.parts): + continue + if path.suffix.lower() not in {".swift", ".yml", ".yaml", ".json", ".md", ".sh", ".py", ".plist"}: + continue + text = path.read_text(encoding="utf-8", errors="ignore") + if secret_pattern.search(text): + findings.append(str(path.relative_to(ROOT))) + require(not findings, "疑似明文凭据:" + ", ".join(findings)) + + vendor_archive = ROOT / "Vendor/libxray-apple-cgo-v26.7.28.zip" + vendor_result = "not-present" + if vendor_archive.is_file(): + digest = hashlib.sha256(vendor_archive.read_bytes()).hexdigest() + require(digest == "07f7ed7697277930e1c517755855950f594f41435b0dfc5917a66eea6278aeb9", "libXray 本地归档 SHA256 不匹配") + vendor_result = digest + + geo_files = [ROOT / "Resources/Geo/geoip.dat", ROOT / "Resources/Geo/geosite.dat"] + geo_present = [path.is_file() for path in geo_files] + require(all(geo_present) or not any(geo_present), "Geo data must be supplied as a complete pair") + geo_status = "present-not-verified-by-source-audit" if all(geo_present) else "not-packaged" + + report = { + "result": "PASS", + "source_version": source_version, + "geo_data_status": geo_status, + "geo_data_required_before_build_and_tunnel": True, + "documentation_version_matches": True, + "scope": "Source audit only; no Xcode compile, signing, IPA export, or iPhone tunnel acceptance", + "automatic_node_selection": True, + "egress_verification": ["api.openai.com", "chatgpt.com"], + "domain_loop_prevention": True, + "gateway_contract": 2, + "legacy_backend_compatible": True, + "network_extension_entitlement": True, + "libxray_archive_sha256": vendor_result, + } + print(json.dumps(report, ensure_ascii=False, indent=2)) + return 0 + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except Exception as exc: + print(json.dumps({"result": "FAIL", "error": str(exc)}, ensure_ascii=False, indent=2), file=sys.stderr) + raise SystemExit(1) diff --git a/ios/Scripts/verify-and-archive.sh b/ios/Scripts/verify-and-archive.sh new file mode 100644 index 0000000..6787d24 --- /dev/null +++ b/ios/Scripts/verify-and-archive.sh @@ -0,0 +1,35 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +test -n "${DEVELOPMENT_TEAM:-}" || { + echo "请设置 DEVELOPMENT_TEAM(Apple Developer Team ID)。" >&2 + exit 1 +} +./Scripts/fetch-libxray.sh +./Scripts/generate-project.sh +xcodebuild \ + -project UCVLZonghengjia.xcodeproj \ + -scheme UCVLZonghengjia \ + -destination 'platform=iOS Simulator,name=iPhone 16 Pro' \ + DEVELOPMENT_TEAM="$DEVELOPMENT_TEAM" \ + test +xcodebuild \ + -project UCVLZonghengjia.xcodeproj \ + -scheme UCVLZonghengjia \ + -configuration Release \ + -destination 'generic/platform=iOS' \ + -archivePath build/UCVL-Zonghengjia-1.0.0.xcarchive \ + DEVELOPMENT_TEAM="$DEVELOPMENT_TEAM" \ + archive + +if [ -n "${EXPORT_OPTIONS_PLIST:-}" ]; then + test -f "$EXPORT_OPTIONS_PLIST" || { + echo "EXPORT_OPTIONS_PLIST 指定的文件不存在。" >&2 + exit 1 + } + xcodebuild \ + -exportArchive \ + -archivePath build/UCVL-Zonghengjia-1.0.0.xcarchive \ + -exportPath build/export \ + -exportOptionsPlist "$EXPORT_OPTIONS_PLIST" +fi diff --git a/ios/Shared/ConnectionAttemptPolicy.swift b/ios/Shared/ConnectionAttemptPolicy.swift new file mode 100644 index 0000000..1bd8912 --- /dev/null +++ b/ios/Shared/ConnectionAttemptPolicy.swift @@ -0,0 +1,26 @@ +import Foundation + +enum ConnectionAttemptDecision: Equatable { + case retryNode + case stop + case revokeAuthorization +} + +enum ConnectionAttemptPolicy { + static func decide(error: Error, hasAssignedNode: Bool) -> ConnectionAttemptDecision { + if error is CancellationError { return .stop } + if let failure = error as? UCVLError { + switch failure { + case .api(let status, _): + return status == 401 || status == 403 ? .revokeAuthorization : .stop + case .vpnPermission, .invalidConfiguration, .invalidResponse: + // Permission, malformed local configuration and control-plane + // failures must not mark every otherwise healthy node as failed. + return .stop + case .connection: + break + } + } + return hasAssignedNode ? .retryNode : .stop + } +} diff --git a/ios/Shared/Models.swift b/ios/Shared/Models.swift new file mode 100644 index 0000000..815ba58 --- /dev/null +++ b/ios/Shared/Models.swift @@ -0,0 +1,162 @@ +import Foundation + +enum JSONValue: Codable, Sendable, Equatable { + case string(String) + case integer(Int64) + case number(Double) + case object([String: JSONValue]) + case array([JSONValue]) + case bool(Bool) + case null + + init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + if container.decodeNil() { + self = .null + } else if let value = try? container.decode(Bool.self) { + self = .bool(value) + } else if let value = try? container.decode(Int64.self) { + self = .integer(value) + } else if let value = try? container.decode(Double.self) { + self = .number(value) + } else if let value = try? container.decode(String.self) { + self = .string(value) + } else if let value = try? container.decode([String: JSONValue].self) { + self = .object(value) + } else if let value = try? container.decode([JSONValue].self) { + self = .array(value) + } else { + throw DecodingError.dataCorruptedError(in: container, debugDescription: "Unsupported JSON value") + } + } + + func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .string(let value): try container.encode(value) + case .integer(let value): try container.encode(value) + case .number(let value): try container.encode(value) + case .object(let value): try container.encode(value) + case .array(let value): try container.encode(value) + case .bool(let value): try container.encode(value) + case .null: try container.encodeNil() + } + } +} + +struct LoginResponse: Decodable, Sendable { + let accessToken: String + let expiresAt: String + let profile: ClientProfile + + enum CodingKeys: String, CodingKey { + case accessToken = "access_token" + case expiresAt = "expires_at" + case profile + } +} + +struct ProfileEnvelope: Decodable, Sendable { + let profile: ClientProfile +} + +struct ClientProfile: Decodable, Sendable { + let username: String + let displayName: String + let email: String + let identityType: String + let subscription: SubscriptionProfile + let nodes: [VPNNode] + let routeModes: [RouteMode] + + enum CodingKeys: String, CodingKey { + case username + case displayName = "display_name" + case email + case identityType = "identity_type" + case subscription + case nodes + case routeModes = "route_modes" + } +} + +struct SubscriptionProfile: Decodable, Sendable { + let status: String + let plan: String + let usedBytes: Int64 + let trafficLimitBytes: Int64 + let expiresAt: String? + let deviceLimit: Int + + enum CodingKeys: String, CodingKey { + case status + case plan + case usedBytes = "used_bytes" + case trafficLimitBytes = "traffic_limit_bytes" + case expiresAt = "expires_at" + case deviceLimit = "device_limit" + } +} + +struct VPNNode: Decodable, Identifiable, Hashable, Sendable { + let slug: String + let name: String + let region: String + let status: String + + var id: String { slug } + var displayName: String { region.isEmpty ? name : "\(name) · \(region)" } +} + +struct RouteMode: Decodable, Identifiable, Hashable, Sendable { + let id: String + let name: String +} + +struct ClientConfigResponse: Decodable, Sendable { + struct Gateway: Decodable, Sendable { + let host: String + let ipv4: String? + } + + let configContract: Int? + let gateway: Gateway? + let node: VPNNode + let routeMode: String + let config: [String: JSONValue] + + enum CodingKeys: String, CodingKey { + case configContract = "config_contract" + case gateway + case node + case routeMode = "route_mode" + case config + } + + func configJSONString() throws -> String { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] + return String(decoding: try encoder.encode(config), as: UTF8.self) + } +} + +struct APIErrorEnvelope: Decodable { + let error: String? +} + +enum UCVLError: LocalizedError { + case api(status: Int, message: String) + case invalidResponse + case invalidConfiguration(String) + case vpnPermission(String) + case connection(String) + + var errorDescription: String? { + switch self { + case .api(_, let message), .invalidConfiguration(let message), .vpnPermission(let message), .connection(let message): + return message + case .invalidResponse: + return "平台返回了无法识别的数据。" + } + } +} diff --git a/ios/Shared/NetworkAddress.swift b/ios/Shared/NetworkAddress.swift new file mode 100644 index 0000000..d9129b9 --- /dev/null +++ b/ios/Shared/NetworkAddress.swift @@ -0,0 +1,24 @@ +import Foundation + +enum NetworkAddress { + static func isPublicIPv4(_ value: String) -> Bool { + let parts = value.split(separator: ".", omittingEmptySubsequences: false) + guard parts.count == 4, + let a = UInt8(parts[0]), + let b = UInt8(parts[1]), + let c = UInt8(parts[2]), + UInt8(parts[3]) != nil + else { return false } + + if a == 0 || a == 10 || a == 127 || a >= 224 { return false } + if a == 100 && (64...127).contains(b) { return false } + if a == 169 && b == 254 { return false } + if a == 172 && (16...31).contains(b) { return false } + if a == 192 && b == 168 { return false } + if a == 192 && b == 0 && (c == 0 || c == 2) { return false } + if a == 198 && (b == 18 || b == 19) { return false } + if a == 198 && b == 51 && c == 100 { return false } + if a == 203 && b == 0 && c == 113 { return false } + return true + } +} diff --git a/ios/Shared/TunnelConfigurationBuilder.swift b/ios/Shared/TunnelConfigurationBuilder.swift new file mode 100644 index 0000000..877d968 --- /dev/null +++ b/ios/Shared/TunnelConfigurationBuilder.swift @@ -0,0 +1,74 @@ +import Foundation + +enum TunnelConfigurationBuilder { + static func makeConfiguration( + rawJSON: String, + tunnelFileDescriptor: Int32, + assetDirectory: String, + resolvedRemoteAddress: String? = nil + ) throws -> String { + guard let data = rawJSON.data(using: .utf8), + var root = try JSONSerialization.jsonObject(with: data) as? [String: Any] + else { + throw UCVLError.invalidConfiguration("线路配置不是有效的 Xray JSON。") + } + + var environment = root["env"] as? [String: Any] ?? [:] + environment["xray.tun.fd"] = String(tunnelFileDescriptor) + environment["xray.location.asset"] = assetDirectory + root["env"] = environment + root["metrics"] = NSNull() + if let resolvedRemoteAddress { + try replaceProxyRemoteAddress(in: &root, with: resolvedRemoteAddress) + } + root["inbounds"] = [[ + "tag": "tun-in", + "port": 0, + "protocol": "tun", + "settings": [ + "name": "ucvl-tun", + "mtu": 1500, + "userLevel": 0, + ], + "sniffing": [ + "enabled": true, + "destOverride": ["http", "tls", "quic"], + "routeOnly": true, + ], + ]] + + guard JSONSerialization.isValidJSONObject(root) else { + throw UCVLError.invalidConfiguration("无法生成 Apple Packet Tunnel 配置。") + } + let output = try JSONSerialization.data(withJSONObject: root, options: [.sortedKeys]) + return String(decoding: output, as: UTF8.self) + } + + static func remoteAddress(from rawJSON: String) -> String? { + guard let data = rawJSON.data(using: .utf8), + let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + let outbounds = root["outbounds"] as? [[String: Any]], + let proxy = outbounds.first(where: { ($0["tag"] as? String) == "proxy" }), + let settings = proxy["settings"] as? [String: Any], + let vnext = settings["vnext"] as? [[String: Any]], + let address = vnext.first?["address"] as? String, + !address.isEmpty + else { return nil } + return address + } + + private static func replaceProxyRemoteAddress(in root: inout [String: Any], with address: String) throws { + guard var outbounds = root["outbounds"] as? [[String: Any]], + let proxyIndex = outbounds.firstIndex(where: { ($0["tag"] as? String) == "proxy" }), + var settings = outbounds[proxyIndex]["settings"] as? [String: Any], + var vnext = settings["vnext"] as? [[String: Any]], + !vnext.isEmpty + else { + throw UCVLError.invalidConfiguration("线路配置缺少代理服务器地址。") + } + vnext[0]["address"] = address + settings["vnext"] = vnext + outbounds[proxyIndex]["settings"] = settings + root["outbounds"] = outbounds + } +} diff --git a/ios/THIRD_PARTY_NOTICES.md b/ios/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..e32c41a --- /dev/null +++ b/ios/THIRD_PARTY_NOTICES.md @@ -0,0 +1,25 @@ +# 第三方软件声明 + +## XTLS/libXray + +- 版本:`v26.7.28` +- 项目:https://github.com/XTLS/libXray +- 许可证:MIT +- 修改状态:未修改官方 libXray 源码;客户端链接官方 Apple cgo XCFramework。 +- 官方发布包 SHA-256:`07F7ED7697277930E1C517755855950F594F41435B0DFC5917A66EEA6278AEB9` + +完整许可证见 `ThirdParty/libXray-MIT.txt`。 + +## XTLS/Xray-core + +- 项目:https://github.com/XTLS/Xray-core +- 对应源码:https://github.com/XTLS/Xray-core/tree/5ca6f4b7d4dc +- 许可证:Mozilla Public License 2.0 +- 用途:由 libXray 静态链接,作为 Packet Tunnel 内的网络核心。 +- 修改状态:未修改 Xray-core 源码。 + +完整许可证见 `ThirdParty/Xray-core-MPL-2.0.txt`。 + +## Geo 路由数据 + +`geoip.dat` 与 `geosite.dat` 仅用于实现平台下发的中国大陆直连、广告分流和私有地址规则。发布时应继续保留其数据源项目的许可声明。 diff --git a/ios/Tests/ClientConfigResponseTests.swift b/ios/Tests/ClientConfigResponseTests.swift new file mode 100644 index 0000000..e98b761 --- /dev/null +++ b/ios/Tests/ClientConfigResponseTests.swift @@ -0,0 +1,21 @@ +import XCTest +@testable import UCVLZonghengjia + +final class ClientConfigResponseTests: XCTestCase { + func testDecodesVersionedGatewayContract() throws { + let data = Data(#"{"config_contract":2,"gateway":{"host":"vpn.toplc.cn","ipv4":"192.0.2.1"},"node":{"slug":"n1","name":"VPN001","region":"东京","status":"online"},"route_mode":"smart","config":{}}"#.utf8) + let response = try JSONDecoder().decode(ClientConfigResponse.self, from: data) + + XCTAssertEqual(response.configContract, 2) + XCTAssertEqual(response.gateway?.host, "vpn.toplc.cn") + XCTAssertEqual(response.gateway?.ipv4, "192.0.2.1") + } + + func testOldBackendPayloadRemainsCompatible() throws { + let data = Data(#"{"node":{"slug":"n1","name":"VPN001","region":"东京","status":"online"},"route_mode":"smart","config":{}}"#.utf8) + let response = try JSONDecoder().decode(ClientConfigResponse.self, from: data) + + XCTAssertNil(response.configContract) + XCTAssertNil(response.gateway) + } +} diff --git a/ios/Tests/ConnectionAttemptPolicyTests.swift b/ios/Tests/ConnectionAttemptPolicyTests.swift new file mode 100644 index 0000000..f5c586f --- /dev/null +++ b/ios/Tests/ConnectionAttemptPolicyTests.swift @@ -0,0 +1,27 @@ +import XCTest +@testable import UCVLZonghengjia + +final class ConnectionAttemptPolicyTests: XCTestCase { + func testControlPlaneTimeoutDoesNotBlacklistUnassignedNode() { + XCTAssertEqual(ConnectionAttemptPolicy.decide(error: URLError(.timedOut), hasAssignedNode: false), .stop) + } + + func testAuthorizationFailureDoesNotCycleNodes() { + for status in [401, 403] { + XCTAssertEqual(ConnectionAttemptPolicy.decide( + error: UCVLError.api(status: status, message: "fixture"), hasAssignedNode: true), .revokeAuthorization) + } + XCTAssertEqual(ConnectionAttemptPolicy.decide( + error: UCVLError.api(status: 503, message: "fixture"), hasAssignedNode: false), .stop) + } + + func testPermissionAndConfigurationFailuresAreLocal() { + XCTAssertEqual(ConnectionAttemptPolicy.decide(error: UCVLError.vpnPermission("fixture"), hasAssignedNode: true), .stop) + XCTAssertEqual(ConnectionAttemptPolicy.decide(error: UCVLError.invalidConfiguration("fixture"), hasAssignedNode: true), .stop) + XCTAssertEqual(ConnectionAttemptPolicy.decide(error: CancellationError(), hasAssignedNode: true), .stop) + } + + func testAssignedNodeTransportFailureCanFailOver() { + XCTAssertEqual(ConnectionAttemptPolicy.decide(error: UCVLError.connection("fixture"), hasAssignedNode: true), .retryNode) + } +} diff --git a/ios/Tests/NetworkAddressTests.swift b/ios/Tests/NetworkAddressTests.swift new file mode 100644 index 0000000..de10a41 --- /dev/null +++ b/ios/Tests/NetworkAddressTests.swift @@ -0,0 +1,17 @@ +import XCTest +@testable import UCVLZonghengjia + +final class NetworkAddressTests: XCTestCase { + func testAcceptsPublicIPv4() { + XCTAssertTrue(NetworkAddress.isPublicIPv4("192.0.2.1")) + XCTAssertTrue(NetworkAddress.isPublicIPv4("8.216.53.107")) + } + + func testRejectsPrivateTailscaleAndFakeIPv4() { + XCTAssertFalse(NetworkAddress.isPublicIPv4("127.0.0.1")) + XCTAssertFalse(NetworkAddress.isPublicIPv4("192.168.50.1")) + XCTAssertFalse(NetworkAddress.isPublicIPv4("100.64.0.2")) + XCTAssertFalse(NetworkAddress.isPublicIPv4("198.18.0.119")) + XCTAssertFalse(NetworkAddress.isPublicIPv4("001.vpn.toplc.cn")) + } +} diff --git a/ios/Tests/TunnelConfigurationBuilderTests.swift b/ios/Tests/TunnelConfigurationBuilderTests.swift new file mode 100644 index 0000000..10228dc --- /dev/null +++ b/ios/Tests/TunnelConfigurationBuilderTests.swift @@ -0,0 +1,44 @@ +import XCTest +@testable import UCVLZonghengjia + +final class TunnelConfigurationBuilderTests: XCTestCase { + func testReplacesDesktopInboundsWithAppleTunnelAndPreservesRealityOutbound() throws { + let raw = #""" + { + "log":{"loglevel":"warning"}, + "inbounds":[{"tag":"socks-in","protocol":"socks","port":10808}], + "outbounds":[ + {"tag":"proxy","protocol":"vless","settings":{"vnext":[{"address":"001.vpn.toplc.cn","port":11081,"users":[{"id":"11111111-2222-3333-4444-555555555555"}]}]},"streamSettings":{"security":"reality","realitySettings":{"serverName":"www.microsoft.com"}}}, + {"tag":"direct","protocol":"freedom"} + ], + "routing":{"rules":[]} + } + """# + + let output = try TunnelConfigurationBuilder.makeConfiguration( + rawJSON: raw, + tunnelFileDescriptor: 42, + assetDirectory: "/app/assets", + resolvedRemoteAddress: "192.0.2.1" + ) + let data = try XCTUnwrap(output.data(using: .utf8)) + let root = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any]) + let environment = try XCTUnwrap(root["env"] as? [String: String]) + XCTAssertEqual(environment["xray.tun.fd"], "42") + XCTAssertEqual(environment["xray.location.asset"], "/app/assets") + + let inbounds = try XCTUnwrap(root["inbounds"] as? [[String: Any]]) + XCTAssertEqual(inbounds.count, 1) + XCTAssertEqual(inbounds[0]["protocol"] as? String, "tun") + + let outbounds = try XCTUnwrap(root["outbounds"] as? [[String: Any]]) + XCTAssertEqual(outbounds.first?["protocol"] as? String, "vless") + let settings = try XCTUnwrap(outbounds.first?["settings"] as? [String: Any]) + let vnext = try XCTUnwrap(settings["vnext"] as? [[String: Any]]) + XCTAssertEqual(vnext.first?["address"] as? String, "192.0.2.1") + let stream = try XCTUnwrap(outbounds.first?["streamSettings"] as? [String: Any]) + let reality = try XCTUnwrap(stream["realitySettings"] as? [String: Any]) + XCTAssertEqual(reality["serverName"] as? String, "www.microsoft.com") + XCTAssertEqual(TunnelConfigurationBuilder.remoteAddress(from: raw), "001.vpn.toplc.cn") + } +} diff --git a/ios/ThirdParty/Xray-core-MPL-2.0.txt b/ios/ThirdParty/Xray-core-MPL-2.0.txt new file mode 100644 index 0000000..76a17d7 --- /dev/null +++ b/ios/ThirdParty/Xray-core-MPL-2.0.txt @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/ios/ThirdParty/libXray-MIT.txt b/ios/ThirdParty/libXray-MIT.txt new file mode 100644 index 0000000..70a4648 --- /dev/null +++ b/ios/ThirdParty/libXray-MIT.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023-2025 XTLS + +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. diff --git a/ios/project.yml b/ios/project.yml new file mode 100644 index 0000000..fc5e580 --- /dev/null +++ b/ios/project.yml @@ -0,0 +1,118 @@ +name: UCVLZonghengjia +options: + bundleIdPrefix: cn.toplc + deploymentTarget: + iOS: "15.0" + createIntermediateGroups: true + groupSortPosition: top +settings: + base: + SWIFT_VERSION: "5.10" + MARKETING_VERSION: "1.0.2" + CURRENT_PROJECT_VERSION: "10002" + CODE_SIGN_STYLE: Automatic + DEVELOPMENT_TEAM: "" + CLANG_ENABLE_MODULES: YES + ENABLE_USER_SCRIPT_SANDBOXING: YES +configs: + Debug: debug + Release: release +targets: + UCVLZonghengjia: + type: application + platform: iOS + sources: + - path: App + - path: Shared + resources: + - path: Resources/Assets.xcassets + entitlements: + path: App/UCVLZonghengjia.entitlements + info: + path: App/Info.plist + properties: + CFBundleDisplayName: 优创⁺纵横家 + CFBundleShortVersionString: $(MARKETING_VERSION) + CFBundleVersion: $(CURRENT_PROJECT_VERSION) + UILaunchScreen: + UIColorName: UCVLLaunchBackground + UIImageName: UCVLLogo + UISupportedInterfaceOrientations: + - UIInterfaceOrientationPortrait + - UIInterfaceOrientationLandscapeLeft + - UIInterfaceOrientationLandscapeRight + UISupportedInterfaceOrientations~ipad: + - UIInterfaceOrientationPortrait + - UIInterfaceOrientationPortraitUpsideDown + - UIInterfaceOrientationLandscapeLeft + - UIInterfaceOrientationLandscapeRight + dependencies: + - target: PacketTunnel + embed: true + settings: + base: + PRODUCT_BUNDLE_IDENTIFIER: cn.toplc.zonghengjia + PRODUCT_NAME: UCVLZonghengjia + TARGETED_DEVICE_FAMILY: "1,2" + ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon + INFOPLIST_KEY_LSApplicationCategoryType: public.app-category.utilities + + PacketTunnel: + type: app-extension + platform: iOS + sources: + - path: PacketTunnel + - path: Shared/TunnelConfigurationBuilder.swift + - path: Shared/Models.swift + - path: Shared/NetworkAddress.swift + resources: + - path: Resources/Geo + entitlements: + path: PacketTunnel/PacketTunnel.entitlements + info: + path: PacketTunnel/Info.plist + properties: + CFBundleDisplayName: 优创⁺纵横家网络扩展 + CFBundleShortVersionString: $(MARKETING_VERSION) + CFBundleVersion: $(CURRENT_PROJECT_VERSION) + NSExtension: + NSExtensionPointIdentifier: com.apple.networkextension.packet-tunnel + NSExtensionPrincipalClass: $(PRODUCT_MODULE_NAME).PacketTunnelProvider + dependencies: + - framework: Vendor/LibXray.xcframework + embed: false + settings: + base: + PRODUCT_BUNDLE_IDENTIFIER: cn.toplc.zonghengjia.PacketTunnel + PRODUCT_NAME: PacketTunnel + TARGETED_DEVICE_FAMILY: "1,2" + APPLICATION_EXTENSION_API_ONLY: YES + SKIP_INSTALL: YES + OTHER_LDFLAGS: + - $(inherited) + - -ObjC + + UCVLZonghengjiaTests: + type: bundle.unit-test + platform: iOS + sources: + - path: Tests + dependencies: + - target: UCVLZonghengjia + settings: + base: + PRODUCT_BUNDLE_IDENTIFIER: cn.toplc.zonghengjia.tests + GENERATE_INFOPLIST_FILE: YES + +schemes: + UCVLZonghengjia: + build: + targets: + UCVLZonghengjia: all + PacketTunnel: all + UCVLZonghengjiaTests: [test] + test: + targets: + - UCVLZonghengjiaTests + archive: + config: Release diff --git a/windows/ApiModels.cs b/windows/ApiModels.cs new file mode 100644 index 0000000..7d5dce9 --- /dev/null +++ b/windows/ApiModels.cs @@ -0,0 +1,207 @@ +using System.Net; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace UCVL.VPNPlus; + +internal sealed class LoginRequest +{ + [JsonPropertyName("login")] public string Login { get; init; } = ""; + [JsonPropertyName("password")] public string Password { get; init; } = ""; + [JsonPropertyName("device_id")] public string DeviceId { get; init; } = ""; + [JsonPropertyName("device_name")] public string DeviceName { get; init; } = ""; + [JsonPropertyName("app_version")] public string AppVersion { get; init; } = ""; +} + +internal sealed class LoginResponse +{ + [JsonPropertyName("access_token")] public string AccessToken { get; init; } = ""; + [JsonPropertyName("expires_at")] public DateTimeOffset ExpiresAt { get; init; } + [JsonPropertyName("profile")] public Profile Profile { get; init; } = new(); +} + +internal sealed class ProfileEnvelope +{ + [JsonPropertyName("profile")] public Profile Profile { get; init; } = new(); +} + +internal sealed class Profile +{ + [JsonPropertyName("usage_history_ranges")] public Dictionary? UsageHistoryRanges { get; init; } + [JsonPropertyName("usage_history")] public List UsageHistory { get; init; } = []; + [JsonPropertyName("username")] public string Username { get; init; } = ""; + [JsonPropertyName("display_name")] public string DisplayName { get; init; } = ""; + [JsonPropertyName("email")] public string Email { get; init; } = ""; + [JsonPropertyName("identity_type")] public string IdentityType { get; init; } = ""; + [JsonPropertyName("subscription")] public SubscriptionInfo Subscription { get; init; } = new(); + [JsonPropertyName("nodes")] public List Nodes { get; init; } = []; + // A separate, authenticated grant list; never merge these into public AI dispatch. + // Older servers omit the field, which leaves the released public path unchanged. + [JsonPropertyName("private_auxiliary_nodes")] public List PrivateAuxiliaryNodes { get; init; } = []; + [JsonPropertyName("route_modes")] public List RouteModes { get; init; } = []; +} + +internal sealed class DailyUsage +{ + [JsonPropertyName("day")] public string Day { get; init; } = ""; + [JsonPropertyName("upload_bytes")] public long UploadBytes { get; init; } + [JsonPropertyName("download_bytes")] public long DownloadBytes { get; init; } +} + +internal sealed class SubscriptionInfo +{ + [JsonPropertyName("status")] public string Status { get; init; } = ""; + [JsonPropertyName("plan")] public string Plan { get; init; } = ""; + [JsonPropertyName("used_bytes")] public long UsedBytes { get; init; } + [JsonPropertyName("traffic_limit_bytes")] public long TrafficLimitBytes { get; init; } + [JsonPropertyName("expires_at")] public DateTimeOffset? ExpiresAt { get; init; } + [JsonPropertyName("device_limit")] public int DeviceLimit { get; init; } +} + +internal class NodeInfo +{ + [JsonPropertyName("slug")] public string Slug { get; init; } = ""; + [JsonPropertyName("name")] public string Name { get; init; } = ""; + [JsonPropertyName("region")] public string Region { get; init; } = ""; + [JsonPropertyName("status")] public string Status { get; init; } = ""; + public override string ToString() => $"{Name} · {Region}"; +} + +internal sealed class PrivateAuxiliaryNode : NodeInfo +{ + [JsonPropertyName("probe_ipv4")] public string ProbeIpv4 { get; init; } = ""; + [JsonPropertyName("probe_port")] public int ProbePort { get; init; } = 18081; + [JsonPropertyName("connect_address")] public string ConnectAddress { get; init; } = ""; + [JsonPropertyName("connection_endpoints")] public List ConnectionEndpoints { get; init; } = []; + internal string EndpointHost => string.IsNullOrEmpty(ConnectAddress) ? ProbeIpv4 : ConnectAddress; + internal PrivateAuxiliaryNode WithEndpoint(PrivateConnectionEndpoint endpoint) => new() { + Slug = Slug, Name = Name, Region = Region, Status = Status, Contract = Contract, + ExpiresAt = ExpiresAt, TlsLeafSha256 = TlsLeafSha256, + ProbeIpv4 = endpoint.ProbeIpv4, ProbePort = endpoint.Port, ConnectAddress = endpoint.Address + }; + [JsonPropertyName("tls_leaf_sha256")] public string TlsLeafSha256 { get; init; } = ""; + [JsonPropertyName("contract")] public int Contract { get; init; } + [JsonPropertyName("expires_at")] public DateTimeOffset ExpiresAt { get; init; } + public override string ToString() => $"{Name} · 私有辅助"; +} + +internal sealed class PrivateConnectionEndpoint +{ + [JsonPropertyName("address")] public string Address { get; init; } = ""; + [JsonPropertyName("probe_ipv4")] public string ProbeIpv4 { get; init; } = ""; + [JsonPropertyName("port")] public int Port { get; init; } +} + +internal sealed class RouteModeInfo +{ + [JsonPropertyName("id")] public string Id { get; init; } = ""; + [JsonPropertyName("name")] public string Name { get; init; } = ""; + public override string ToString() => Name; +} + +internal sealed class ConfigResponse +{ + private TailnetEndpoint? _tailscaleEndpoint; + [JsonIgnore] internal bool HasTailscaleEndpoint { get; private set; } + // Missing means an older backend; explicit null is an administrator opt-out. + [JsonPropertyName("tailscale_endpoint")] public TailnetEndpoint? TailscaleEndpoint + { + get => _tailscaleEndpoint; + init { _tailscaleEndpoint = value; HasTailscaleEndpoint = true; } + } + [JsonPropertyName("config_expires_at")] public DateTimeOffset? ConfigExpiresAt { get; init; } + [JsonPropertyName("connection_scope")] public string ConnectionScope { get; init; } = ""; + [JsonPropertyName("config_contract")] public int? ConfigContract { get; init; } + [JsonPropertyName("gateway")] public GatewayInfo? Gateway { get; init; } + [JsonPropertyName("node")] public NodeInfo Node { get; init; } = new(); + [JsonPropertyName("route_mode")] public string RouteMode { get; init; } = ""; + [JsonPropertyName("config")] public JsonElement Config { get; init; } + + internal string GetRuntimeConfigJson() => + ConnectionScope == PrivateAuxiliaryRouting.Scope ? PrivateAuxiliaryRuntime.Prepare(this) + : TunConfigBuilder.OverrideProxyServerAddress(Config.GetRawText(), Gateway?.PreferredAddress()); +} + +internal sealed class TailnetEndpoint +{ + [JsonPropertyName("contract")] public int Contract { get; init; } + [JsonPropertyName("node_slug")] public string NodeSlug { get; init; } = ""; + [JsonPropertyName("address")] public string Address { get; init; } = ""; + [JsonPropertyName("port")] public int Port { get; init; } +} + +internal sealed class GatewayInfo +{ + [JsonPropertyName("host")] public string Host { get; init; } = ""; + [JsonPropertyName("ipv4")] public string? Ipv4 { get; init; } + + internal string? PreferredAddress() + { + if (IPAddress.TryParse(Ipv4, out var address) + && address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork + && !IPAddress.IsLoopback(address) + && IsPublicIpv4(address)) + { + return address.ToString(); + } + return string.IsNullOrWhiteSpace(Host) ? null : Host.Trim(); + } + + private static bool IsPublicIpv4(IPAddress address) + { + var bytes = address.GetAddressBytes(); + var first = bytes[0]; + var second = bytes[1]; + if (first == 0 || first == 10 || first == 127 || first >= 224) return false; + if (first == 100 && second >= 64 && second <= 127) return false; + if (first == 169 && second == 254) return false; + if (first == 172 && second >= 16 && second <= 31) return false; + if (first == 192 && second == 168) return false; + if (first == 198 && (second == 18 || second == 19)) return false; + return true; + } +} + +internal sealed class ErrorResponse +{ + [JsonPropertyName("error")] public string Error { get; init; } = ""; +} + +internal sealed class ClientUpdateInfo +{ + [JsonPropertyName("available")] public bool Available { get; init; } + [JsonPropertyName("version")] public string Version { get; init; } = ""; + [JsonPropertyName("download_url")] public string DownloadUrl { get; init; } = ""; + [JsonPropertyName("sha256")] public string Sha256 { get; init; } = ""; + [JsonPropertyName("size")] public long Size { get; init; } + [JsonPropertyName("notes")] public string Notes { get; init; } = ""; + [JsonPropertyName("mandatory")] public bool Mandatory { get; init; } +} + +internal sealed class LearningObservation +{ + [JsonPropertyName("report_id")] public string ReportId { get; init; } = Guid.NewGuid().ToString("D"); + [JsonPropertyName("target_type")] public string TargetType { get; init; } = "domain"; + [JsonPropertyName("target")] public string Target { get; init; } = ""; + [JsonPropertyName("port")] public int Port { get; init; } + [JsonPropertyName("access_kind")] public string AccessKind { get; init; } = "socket"; + [JsonPropertyName("network")] public string Network { get; init; } = "tcp"; + [JsonPropertyName("outcome")] public string Outcome { get; init; } = "direct_failed"; + [JsonPropertyName("failure_kind")] public string FailureKind { get; init; } = "other"; + [JsonPropertyName("scope")] public string Scope { get; init; } = "public"; + [JsonPropertyName("evidence_kind")] public string EvidenceKind { get; init; } = ""; + [JsonPropertyName("related_report_id")] public string? RelatedReportId { get; init; } + [JsonPropertyName("node")] public string Node { get; init; } = ""; + [JsonPropertyName("client_version")] public string ClientVersion { get; init; } = Application.ProductVersion; +} + +internal sealed class ObservationEnvelope +{ + [JsonPropertyName("observations")] public List Observations { get; init; } = []; +} + +internal sealed class ApiException : Exception +{ + internal int StatusCode { get; } + internal ApiException(int statusCode, string message) : base(message) => StatusCode = statusCode; +} diff --git a/windows/AppPaths.cs b/windows/AppPaths.cs new file mode 100644 index 0000000..564c1c2 --- /dev/null +++ b/windows/AppPaths.cs @@ -0,0 +1,55 @@ +using System.Text; + +namespace UCVL.VPNPlus; + +internal static class AppPaths +{ + internal static readonly string DataDirectory = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), + "UCVL", + "VPNPlus"); + + internal static string DeviceIdFile => Path.Combine(DataDirectory, "device-id.txt"); + internal static string TokenFile => Path.Combine(DataDirectory, "session.bin"); + internal static string ProxyStateFile => Path.Combine(DataDirectory, "proxy-state.json"); + internal static string TunStateFile => Path.Combine(DataDirectory, "tun-state.json"); + internal static string LearnedRoutesFile => Path.Combine(DataDirectory, "learned-routes.json"); + internal static string ConfigFile => Path.Combine(DataDirectory, "xray-config.json"); + internal static string PidFile => Path.Combine(DataDirectory, "xray.pid"); + internal static string LogFile => Path.Combine(DataDirectory, "vpnplus.log"); + internal static string XrayLogFile => Path.Combine(DataDirectory, "xray.log"); + internal static string ConnectionSelfTestFile => Path.Combine(DataDirectory, "connection-self-test.json"); + + internal static void EnsureDirectory() => Directory.CreateDirectory(DataDirectory); + + internal static string GetOrCreateDeviceId() + { + EnsureDirectory(); + if (File.Exists(DeviceIdFile)) + { + var existing = File.ReadAllText(DeviceIdFile, Encoding.UTF8).Trim(); + if (Guid.TryParse(existing, out _)) + { + return existing; + } + } + var deviceId = Guid.NewGuid().ToString("D"); + File.WriteAllText(DeviceIdFile, deviceId, new UTF8Encoding(false)); + return deviceId; + } + + internal static void WriteLog(string message) + { + try + { + EnsureDirectory(); + File.AppendAllText(LogFile, $"{DateTimeOffset.Now:O} {message}{Environment.NewLine}", Encoding.UTF8); + } + catch + { + // Logging must never prevent connecting or restoring the system proxy. + } + } + + internal static void WriteError(Exception exception) => WriteLog($"ERROR {exception}"); +} diff --git a/windows/Brand.cs b/windows/Brand.cs new file mode 100644 index 0000000..e3e899d --- /dev/null +++ b/windows/Brand.cs @@ -0,0 +1,18 @@ +namespace UCVL.VPNPlus; + +internal static class Brand +{ + internal static readonly Color Navy = Color.FromArgb(10, 34, 91); + internal static readonly Color DeepBlue = Color.FromArgb(12, 56, 132); + internal static readonly Color RoyalBlue = Color.FromArgb(0, 80, 221); + internal static readonly Color Cyan = Color.FromArgb(0, 145, 155); + internal static readonly Color PaleBlue = Color.FromArgb(219, 239, 255); + internal static readonly Color Surface = Color.FromArgb(237, 248, 255); + internal static readonly Color Text = Color.FromArgb(12, 43, 90); + internal static readonly Color Muted = Color.FromArgb(68, 100, 143); + internal static readonly Color Success = Color.FromArgb(0, 113, 110); + internal static readonly Color Danger = Color.FromArgb(205, 65, 76); + + internal static Font Font(float size, FontStyle style = FontStyle.Regular) => + new("Microsoft YaHei UI", size, style, GraphicsUnit.Point); +} diff --git a/windows/ClientShutdownScope.cs b/windows/ClientShutdownScope.cs new file mode 100644 index 0000000..f91664a --- /dev/null +++ b/windows/ClientShutdownScope.cs @@ -0,0 +1,20 @@ +namespace UCVL.VPNPlus; + +internal static class ClientShutdownScope +{ + internal record Instance(int Id, int SessionId, string? Executable); + // Legacy events are shared within the logon session. Refuse an ambiguous + // same-name process rather than signaling or closing an unrelated instance. + internal static bool IsUnambiguous(string expected, int session, IEnumerable processes) + => processes.Where(p => p.SessionId == session).All(p => !string.IsNullOrWhiteSpace(p.Executable) + && string.Equals(Path.GetFullPath(p.Executable), Path.GetFullPath(expected), StringComparison.OrdinalIgnoreCase)); + internal static bool SelfTest() + { + const string expected = @"C:\fixture\installed\VPNPlus.exe"; + return IsUnambiguous(expected, 1, [new(10,1,expected)]) + && IsUnambiguous(expected, 1, [new(10,2,@"D:\another-user\VPNPlus.exe")]) + && IsUnambiguous(expected, 1, [new(10,1,expected.ToLowerInvariant())]) + && !IsUnambiguous(expected, 1, [new(10,1,expected),new(11,1,@"D:\another-app\VPNPlus.exe")]) + && !IsUnambiguous(expected, 1, [new(10,1,null)]); + } +} diff --git a/windows/ClientUpdater.cs b/windows/ClientUpdater.cs new file mode 100644 index 0000000..2198a22 --- /dev/null +++ b/windows/ClientUpdater.cs @@ -0,0 +1,172 @@ +using System.Diagnostics; +using System.Security.Cryptography; + +namespace UCVL.VPNPlus; + +internal static class ClientUpdater +{ + private const long MaximumInstallerBytes = 200L * 1024 * 1024; + + internal static bool IsNewerVersion(string candidate, string? current = null) + { + var currentText = current ?? Application.ProductVersion; + return GitReleaseUpdater.IsStableVersion(candidate) + && TryParseComparableVersion(candidate, out var candidateVersion) + && TryParseComparableVersion(currentText, out var currentVersion) + && (candidateVersion > currentVersion + || candidateVersion == currentVersion && currentText.Split('+')[0].Contains('-')); + } + + internal static bool ShouldOffer(ClientUpdateInfo update, string? current = null) + => update.Available && IsNewerVersion(update.Version, current); + + private static bool TryParseComparableVersion(string? value, out Version version) + { + version = new Version(0, 0); + if (string.IsNullOrWhiteSpace(value)) return false; + + // Older development builds displayed versions such as 0.2.4+d. Build + // metadata and prerelease labels must not prevent those clients from + // recognizing a newer stable release. + var normalized = value.Trim(); + var suffixIndex = normalized.IndexOfAny(['+', '-']); + if (suffixIndex >= 0) normalized = normalized[..suffixIndex]; + return Version.TryParse(normalized, out version!); + } + + internal static bool SelfTest() + { + return TryParseComparableVersion("0.2.4+d", out var development) + && development == new Version(0, 2, 4) + && TryParseComparableVersion("0.2.7-beta.1", out var prerelease) + && prerelease == new Version(0, 2, 7) + && !TryParseComparableVersion("not-a-version", out _) + && IsNewerVersion("99.0.0") + && !IsNewerVersion("0.0.1"); + } + + internal static Task DownloadAsync(ClientUpdateInfo update, CancellationToken cancellationToken, IProgress? progress = null) + => DownloadCoreAsync(update, cancellationToken, progress, AppPaths.DataDirectory); + + // The fixture uses a disposable temp directory and in-memory HTTP transport. + // It exercises the same downloader without publishing or installing a release. + internal static Task DownloadForTestAsync(ClientUpdateInfo update, CancellationToken cancellationToken, + IProgress progress, string directory, HttpMessageHandler transport, + TimeSpan? totalTimeout = null, TimeSpan? idleTimeout = null) + => DownloadCoreAsync(update, cancellationToken, progress, directory, transport, totalTimeout, idleTimeout); + + private static async Task DownloadCoreAsync(ClientUpdateInfo update, CancellationToken cancellationToken, + IProgress? progress, string dataDirectory, HttpMessageHandler? transport = null, + TimeSpan? totalTimeout = null, TimeSpan? idleTimeout = null) + { + if (!GitReleaseUpdater.IsStableVersion(update.Version)) throw new InvalidOperationException("更新版本号无效。"); + var expectedPath = $"/admin/ucvl-software-downloads/releases/download/windows-v{update.Version}/UCVL-Zonghengjia-{update.Version}-win-x64-setup.exe"; + if (!Uri.TryCreate(update.DownloadUrl, UriKind.Absolute, out var uri) + || uri.Scheme != Uri.UriSchemeHttps + || !string.Equals(uri.Host, "pro.ucvl.cn", StringComparison.OrdinalIgnoreCase) + || uri.Port != 443 || uri.UserInfo.Length != 0 || uri.Query.Length != 0 || uri.Fragment.Length != 0 + || uri.AbsolutePath != expectedPath) + { + throw new InvalidOperationException("更新下载地址未通过安全校验。"); + } + if (update.Size <= 0 || update.Size > MaximumInstallerBytes) + { + throw new InvalidOperationException("更新包大小异常。"); + } + if (update.Sha256.Length != 64 || update.Sha256.Any(character => !Uri.IsHexDigit(character))) + { + throw new InvalidOperationException("更新包校验值无效。"); + } + + var updateDirectory = Path.Combine(dataDirectory, "updates"); + Directory.CreateDirectory(updateDirectory); + var finalPath = Path.Combine(updateDirectory, $"UCVL-Zonghengjia-{update.Version}-win-x64-setup.exe"); + var partialPath = finalPath + ".part"; + if (File.Exists(partialPath)) File.Delete(partialPath); + + // ResponseHeadersRead ends HttpClient.Timeout at the response headers. + // 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)); + var idleLimit = idleTimeout ?? TimeSpan.FromSeconds(30); + try + { + using var client = new HttpClient(transport ?? new SocketsHttpHandler { UseProxy = false, ConnectTimeout = TimeSpan.FromSeconds(10), AllowAutoRedirect = false }) { Timeout = TimeSpan.FromSeconds(30) }; + client.DefaultRequestHeaders.UserAgent.ParseAdd($"UCVL-VPNPlus/{Application.ProductVersion} Windows-x64 Updater"); + using var response = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, deadline.Token); + response.EnsureSuccessStatusCode(); + if (response.Content.Headers.ContentLength is long contentLength + && (contentLength != update.Size || contentLength > MaximumInstallerBytes)) + { + throw new InvalidOperationException("更新包长度与发布信息不一致。"); + } + + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + var buffer = new byte[128 * 1024]; + long total = 0; + await using (var source = await response.Content.ReadAsStreamAsync(deadline.Token)) + await using (var destination = new FileStream( + partialPath, + FileMode.CreateNew, + FileAccess.Write, + FileShare.None, + 128 * 1024, + FileOptions.Asynchronous | FileOptions.SequentialScan)) + { + while (true) + { + using var readDeadline = CancellationTokenSource.CreateLinkedTokenSource(deadline.Token); + readDeadline.CancelAfter(idleLimit); + var read = await source.ReadAsync(buffer, readDeadline.Token); + if (read == 0) break; + total += read; + if (total > MaximumInstallerBytes || total > update.Size) + { + throw new InvalidOperationException("更新包超出允许大小。"); + } + hash.AppendData(buffer, 0, read); + await destination.WriteAsync(buffer.AsMemory(0, read), deadline.Token); + progress?.Report((int)(total * 100 / update.Size)); + } + await destination.FlushAsync(deadline.Token); + } + if (total != update.Size) + { + throw new InvalidOperationException("更新包下载不完整。"); + } + var actualHash = Convert.ToHexString(hash.GetHashAndReset()).ToLowerInvariant(); + if (!CryptographicOperations.FixedTimeEquals( + Convert.FromHexString(actualHash), + Convert.FromHexString(update.Sha256))) + { + throw new InvalidOperationException("更新包 SHA-256 校验失败。"); + } + File.Move(partialPath, finalPath, overwrite: true); + return finalPath; + } + catch (Exception error) + { + try + { + if (File.Exists(partialPath)) File.Delete(partialPath); + } + catch { } + if (error is OperationCanceledException && !cancellationToken.IsCancellationRequested) + throw new TimeoutException("更新下载超时或长时间未收到数据,未启动安装;当前版本和连接保持不变,请稍后重试。", error); + throw; + } + } + + internal static Process LaunchInstaller(string installerPath) + { + return Process.Start(new ProcessStartInfo + { + FileName = installerPath, + Arguments = $"/UPDATE /D={Path.TrimEndingDirectorySeparator(AppContext.BaseDirectory)}", + UseShellExecute = true, + Verb = "runas", + WorkingDirectory = Path.GetDirectoryName(installerPath) ?? AppPaths.DataDirectory, + }) ?? throw new IOException("安装器未能启动,当前程序保持运行。"); + } +} diff --git a/windows/ConnectionAcceptanceTrace.cs b/windows/ConnectionAcceptanceTrace.cs new file mode 100644 index 0000000..860857c --- /dev/null +++ b/windows/ConnectionAcceptanceTrace.cs @@ -0,0 +1,20 @@ +using System.Text.Json; + +namespace UCVL.VPNPlus; + +// Opt-in CLI acceptance telemetry from the actual WinForms connection/timer +// path. Contains only lifecycle, node, health and process ID, never account data. +internal static class ConnectionAcceptanceTrace +{ + internal static bool Enabled { get; set; } + internal static void Record(string phase, string? node, bool connected, int? coreId, int failures = 0) + { + if (!Enabled) return; + try + { + File.AppendAllText(Path.Combine(AppContext.BaseDirectory, "ui-connection-self-test.jsonl"), + JsonSerializer.Serialize(new { time = DateTimeOffset.Now, phase, node, connected, coreId, failures }) + Environment.NewLine); + } + catch { /* Acceptance reporting cannot interrupt network recovery. */ } + } +} diff --git a/windows/ConnectionHealthPolicy.cs b/windows/ConnectionHealthPolicy.cs new file mode 100644 index 0000000..6afd9b7 --- /dev/null +++ b/windows/ConnectionHealthPolicy.cs @@ -0,0 +1,43 @@ +namespace UCVL.VPNPlus; + +// Advisory after connection only; never an Internet-site gate in StartAsync. +// A delayed probe must not undo a user's disconnect or judge a different core. +internal sealed class ConnectionHealthPolicy +{ + internal enum Decision { Ignore, Keep, Repair, Switch } + internal long Revision { get; private set; } + internal int Failures { get; private set; } + internal bool HasBeenHealthy { get; private set; } + private long _nextProbe; + internal void Invalidate() => Revision++; + internal void BeginCore(long now) + { + Invalidate(); Failures = 0; HasBeenHealthy = false; + _nextProbe = now + 5_000; + } + internal void ResetFailures() => Failures = 0; + internal bool IsDue(long now, bool running) => !running || now >= _nextProbe; + internal Decision Observe(long revision, int? testedCore, int? currentCore, + bool wanted, bool busy, bool transitioning, bool exiting, bool healthy, long now, bool proxyHealthy = false) + { + if (revision != Revision || testedCore != currentCore || !wanted || busy || transitioning || exiting) + return Decision.Ignore; + if (healthy && currentCore is not null) { + HasBeenHealthy = true; Failures = 0; _nextProbe = now + 20_000; + return Decision.Keep; + } + if (proxyHealthy && currentCore is not null) { + // Do not punish/restart a working node for a local smart-rule fault. + // The UI must show degraded routing, not declare the business path healthy. + Failures = 0; _nextProbe = now + 20_000; + return Decision.Repair; + } + Failures++; + _nextProbe = now + (HasBeenHealthy ? 20_000 : 5_000); + // Established connections retain tolerance for two transient rounds. + // An unverified newly selected node gets one retry, not a minute of + // false connected state; a dead core does not wait for HTTP timeouts. + return currentCore is null || Failures >= (HasBeenHealthy ? 3 : 2) + ? Decision.Switch : Decision.Keep; + } +} diff --git a/windows/ConnectionHealthSelfTest.cs b/windows/ConnectionHealthSelfTest.cs new file mode 100644 index 0000000..02c4d8f --- /dev/null +++ b/windows/ConnectionHealthSelfTest.cs @@ -0,0 +1,61 @@ +using System.Text.Json; + +namespace UCVL.VPNPlus; + +internal static class ConnectionHealthSelfTest +{ + internal static int Run() + { + var checks = new Dictionary(); + var policy = new ConnectionHealthPolicy(); + policy.BeginCore(1_000); + checks["new_core_has_short_background_grace"] = !policy.IsDue(5_999, true) && policy.IsDue(6_000, true); + checks["dead_core_does_not_wait_for_probe_due"] = policy.IsDue(1_001, false); + var revision = policy.Revision; + ConnectionHealthPolicy.Decision Observe(bool healthy, long now, int? core = 10) + => policy.Observe(policy.Revision, core, core, true, false, false, false, healthy, now); + checks["first_unverified_failure_is_tolerated"] = Observe(false,6_000) == ConnectionHealthPolicy.Decision.Keep && policy.Failures == 1; + checks["unverified_retry_is_bounded"] = !policy.IsDue(10_999,true) && policy.IsDue(11_000,true); + checks["second_unverified_failure_requests_switch"] = Observe(false,11_000) == ConnectionHealthPolicy.Decision.Switch; + policy.BeginCore(20_000); + checks["new_core_clears_previous_failure_history"] = !policy.HasBeenHealthy && policy.Failures == 0; + checks["healthy_transport_resets_failures"] = Observe(true,25_000) == ConnectionHealthPolicy.Decision.Keep && policy.HasBeenHealthy; + checks["established_probe_cadence_remains_twenty_seconds"] = !policy.IsDue(44_999,true) && policy.IsDue(45_000,true); + checks["established_first_failure_tolerated"] = Observe(false,45_000) == ConnectionHealthPolicy.Decision.Keep; + checks["established_second_failure_tolerated"] = Observe(false,65_000) == ConnectionHealthPolicy.Decision.Keep; + checks["established_third_failure_switches"] = Observe(false,85_000) == ConnectionHealthPolicy.Decision.Switch; + checks["success_clears_consecutive_failures"] = Observe(true,90_000) == ConnectionHealthPolicy.Decision.Keep && policy.Failures == 0; + checks["old_revision_cannot_apply"] = policy.Observe(revision,10,10,true,false,false,false,false,91_000) == ConnectionHealthPolicy.Decision.Ignore; + checks["different_core_result_cannot_apply"] = policy.Observe(policy.Revision,10,11,true,false,false,false,false,91_000) == ConnectionHealthPolicy.Decision.Ignore; + checks["core_exited_during_probe_result_is_ignored"] = policy.Observe(policy.Revision,10,null,true,false,false,false,false,91_000) == ConnectionHealthPolicy.Decision.Ignore; + checks["user_disconnect_cannot_be_undone_by_late_failure"] = policy.Observe(policy.Revision,10,10,false,false,false,false,false,91_000) == ConnectionHealthPolicy.Decision.Ignore; + checks["busy_result_is_ignored"] = policy.Observe(policy.Revision,10,10,true,true,false,false,false,91_000) == ConnectionHealthPolicy.Decision.Ignore; + checks["learning_transition_result_is_ignored"] = policy.Observe(policy.Revision,10,10,true,false,true,false,false,91_000) == ConnectionHealthPolicy.Decision.Ignore; + checks["exit_result_is_ignored"] = policy.Observe(policy.Revision,10,10,true,false,false,true,false,91_000) == ConnectionHealthPolicy.Decision.Ignore; + checks["ignored_results_do_not_modify_failures"] = policy.Failures == 0; + checks["dead_core_requests_switch"] = Observe(false,91_000,null) == ConnectionHealthPolicy.Decision.Switch; + policy.ResetFailures(); + checks["control_plane_deferral_retains_established_status"] = policy.HasBeenHealthy && policy.Failures == 0; + revision = policy.Revision; + policy.Invalidate(); + checks["new_attempt_invalidates_inflight_probe"] = policy.Observe(revision,10,10,true,false,false,false,true,92_000) == ConnectionHealthPolicy.Decision.Ignore; + policy.BeginCore(100_000); + checks["healthy_proxy_is_not_false_business_success"] = policy.Observe(policy.Revision,10,10,true,false,false,false,false,105_000,true) + == ConnectionHealthPolicy.Decision.Repair && !policy.HasBeenHealthy; + checks["local_fault_never_accumulates_node_penalty"] = Enumerable.Range(0,12).All(i => + policy.Observe(policy.Revision,10,10,true,false,false,false,false,125_000 + i*20_000,true) == ConnectionHealthPolicy.Decision.Repair) + && policy.Failures == 0; + checks["repaired_business_path_restores_health"] = Observe(true,400_000) == ConnectionHealthPolicy.Decision.Keep && policy.HasBeenHealthy; + checks["proxy_failure_still_switches_after_threshold"] = Observe(false,420_000) == ConnectionHealthPolicy.Decision.Keep + && Observe(false,440_000) == ConnectionHealthPolicy.Decision.Keep && Observe(false,460_000) == ConnectionHealthPolicy.Decision.Switch; + checks["late_proxy_success_does_not_revive_dead_core"] = policy.Observe(policy.Revision,null,null,true,false,false,false,false,480_000,true) + == ConnectionHealthPolicy.Decision.Switch; + checks["stale_proxy_proof_cannot_affect_new_core"] = policy.Observe(policy.Revision,10,11,true,false,false,false,false,500_000,true) + == ConnectionHealthPolicy.Decision.Ignore; + var passed = checks.Values.All(v => v); + File.WriteAllText(Path.Combine(AppContext.BaseDirectory,"connection-health-self-test.json"), + JsonSerializer.Serialize(new { kind="advisory_connection_health_policy", network_modified=false, + authenticated_codex_tested=false, checks, passed },new JsonSerializerOptions{WriteIndented=true})); + return passed ? 0 : 17; + } +} diff --git a/windows/ConnectionRecoveryPolicy.cs b/windows/ConnectionRecoveryPolicy.cs new file mode 100644 index 0000000..e42faf0 --- /dev/null +++ b/windows/ConnectionRecoveryPolicy.cs @@ -0,0 +1,22 @@ +namespace UCVL.VPNPlus; + +internal static class ConnectionRecoveryPolicy +{ + // A control-plane timeout is not evidence that the existing data-plane + // process needs to be destroyed. Revoked authorization still stops service. + internal static bool KeepExisting(bool reconnect, bool replacementStarted, bool coreRunning, Exception failure) + => reconnect && !replacementStarted && coreRunning + && failure is not ApiException { StatusCode: 401 or 403 }; + + internal static bool SelfTest() + { + var timeout = new TimeoutException(); + return KeepExisting(true, false, true, timeout) + && KeepExisting(true, false, true, new TaskCanceledException()) + && !KeepExisting(false, false, true, timeout) + && !KeepExisting(true, true, true, timeout) + && !KeepExisting(true, false, false, timeout) + && !KeepExisting(true, false, true, new ApiException(401, "test revoked")) + && !KeepExisting(true, false, true, new ApiException(403, "test forbidden")); + } +} diff --git a/windows/ConnectionSelection.cs b/windows/ConnectionSelection.cs new file mode 100644 index 0000000..a53641f --- /dev/null +++ b/windows/ConnectionSelection.cs @@ -0,0 +1,23 @@ +namespace UCVL.VPNPlus; + +// A manual selection is never allowed to fall back to automatic dispatch. +internal sealed record ConnectionSelection(string NodeSlug, bool Manual) +{ + internal static ConnectionSelection Create(bool manual, string? selectedSlug, IEnumerable authorizedSlugs) + { + if (!manual) return new("auto", false); + if (string.IsNullOrWhiteSpace(selectedSlug) || selectedSlug == "auto" + || !authorizedSlugs.Contains(selectedSlug, StringComparer.Ordinal)) + throw new InvalidOperationException("请选择当前账号有权使用的节点;节点可能已下线或授权已变更。"); + return new(selectedSlug, true); + } + + internal int Attempts(int availableCount) => Manual ? 1 : Math.Min(availableCount, 8); + + internal void ValidateResponse(string actualSlug) + { + if (string.IsNullOrWhiteSpace(actualSlug) || actualSlug == "auto" + || (Manual && !string.Equals(NodeSlug, actualSlug, StringComparison.Ordinal))) + throw new InvalidOperationException("服务器返回的节点与连接选择不一致,已拒绝连接。"); + } +} diff --git a/windows/ConnectionSelectionSelfTest.cs b/windows/ConnectionSelectionSelfTest.cs new file mode 100644 index 0000000..ddcc401 --- /dev/null +++ b/windows/ConnectionSelectionSelfTest.cs @@ -0,0 +1,120 @@ +using System.Text.Json; + +namespace UCVL.VPNPlus; + +internal static class ConnectionSelectionSelfTest +{ + internal static int Run() + { + var checks = new Dictionary(); + bool Rejected(Action action) + { + try { action(); return false; } + catch (InvalidOperationException) { return true; } + } + string[] authorized = ["office-test", "remote-test"]; + var auto = ConnectionSelection.Create(false, "office-test", authorized); + checks["default_auto_ignores_previous_manual_choice"] = auto.NodeSlug == "auto" && !auto.Manual; + checks["auto_attempts_are_bounded"] = auto.Attempts(12) == 8 && auto.Attempts(2) == 2; + var manual = ConnectionSelection.Create(true, "office-test", authorized); + checks["manual_uses_exact_authorized_node"] = manual.Manual && manual.NodeSlug == "office-test"; + checks["manual_has_no_fallback_attempt"] = manual.Attempts(12) == 1; + checks["missing_choice_rejected"] = Rejected(() => ConnectionSelection.Create(true, null, authorized)); + checks["removed_permission_rejected"] = Rejected(() => ConnectionSelection.Create(true, "removed", authorized)); + checks["manual_auto_slug_rejected"] = Rejected(() => ConnectionSelection.Create(true, "auto", ["auto"])); + checks["different_server_node_rejected"] = Rejected(() => manual.ValidateResponse("remote-test")); + checks["empty_server_node_rejected"] = Rejected(() => auto.ValidateResponse("")); + checks["manual_exact_response_accepted"] = !Rejected(() => manual.ValidateResponse("office-test")); + checks["auto_concrete_response_accepted"] = !Rejected(() => auto.ValidateResponse("remote-test")); + var siteName = NodePresentation.Name(NodePresentation.JinanSlug, "济南(博翠明湖)", true); + checks["private_connected_name_follows_registered_site"] = siteName == "济南(博翠明湖)"; + checks["legacy_private_empty_name_keeps_zero3_fallback"] = NodePresentation.Name(NodePresentation.JinanSlug, "", true) == NodePresentation.JinanName; + checks["public_node_not_relabelled_as_zero3"] = NodePresentation.Name(NodePresentation.JinanSlug, "VPN002", false) == "VPN002"; + checks["fallback_shows_actual_public_node"] = NodePresentation.Name("aliyun-tokyo-002", "VPN002", false) == "VPN002"; + checks["learning_keeps_connected_node_name"] = NodePresentation.LearningDetail(true, siteName, "规则已更新") == siteName + " · 规则已更新"; + checks["learning_after_fallback_names_public_node"] = NodePresentation.LearningDetail(true, "VPN002", "规则已更新") == "VPN002 · 规则已更新"; + checks["unconnected_selection_does_not_claim_actual_node"] = NodePresentation.LearningDetail(false, siteName, "正在验证") == "正在验证"; + checks["public_transport_has_no_suffix"] = NodePresentation.WithTransport("VPN002", false) == "VPN002"; + checks["tailnet_transport_has_explicit_suffix"] = NodePresentation.WithTransport("VPN002", true) == "VPN002 + Tailscale"; + checks["second_node_uses_same_transport_format"] = NodePresentation.WithTransport("VPN003", true) == "VPN003 + Tailscale"; + using (var form = new MainForm(preview: true, uiOnly: true)) + foreach (var check in form.CheckSelectionUi()) checks.Add(check.Key, check.Value); + var passed = checks.Values.All(v => v); + File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "connection-selection-self-test.json"), + JsonSerializer.Serialize(new { passed, network_modified = false, local_office_gateway_tested = false, checks }, + new JsonSerializerOptions { WriteIndented = true })); + return passed ? 0 : 18; + } +} + +internal sealed partial class MainForm +{ + internal Dictionary CheckSelectionUi() + { + var result = new Dictionary(); + var profile = new Profile { Nodes = [new() { Slug = "office-test", Name = "优创未来·济南办" }, new() { Slug = "remote-test", Name = "远程测试" }] }; + _availableNodeCount = 2; + UpdateSelectionNodes(profile, false); + result["ui_defaults_to_auto"] = !ManualSelection; + _connectionModeCombo.SelectedIndex = 1; + _manualNodeCombo.SelectedIndex = 0; + result["ui_manual_has_authorized_choices"] = ManualSelection && _manualNodeCombo.Items.Count == 2; + SetBusy(true); + result["ui_locked_during_connect"] = !_connectionModeCombo.Enabled && !_manualNodeCombo.Enabled; + SetBusy(false); + _wantConnected = true; + RefreshSelectionControls(); + result["ui_locked_during_connection_or_recovery"] = !_connectionModeCombo.Enabled && !_manualNodeCombo.Enabled; + _wantConnected = false; + RefreshSelectionControls(); + result["ui_editable_after_disconnect"] = _connectionModeCombo.Enabled && _manualNodeCombo.Enabled; + UpdateSelectionNodes(profile, true); + result["profile_refresh_keeps_exact_manual_choice"] = (_manualNodeCombo.SelectedItem as NodeInfo)?.Slug == "office-test"; + UpdateSelectionNodes(new Profile { Nodes = [profile.Nodes[1]] }, true); + result["removed_node_not_silently_replaced"] = ManualSelection && _manualNodeCombo.SelectedItem is null; + UpdateSelectionNodes(profile, false); + result["new_login_resets_to_auto"] = !ManualSelection && _manualNodeCombo.SelectedItem is null; + var nodeCount = _manualNodeCombo.Items.Count; + _currentNodeSlug = "office-test"; + _currentNodeBaseName = "VPN002"; + _currentNodeIsPrivateAuxiliary = false; + UpdateConnectedTransportPresentation(false); + result["connected_public_name_is_plain_node"] = _currentNodeName == "VPN002" && !_currentNodeUsesTailnet; + UpdateConnectedTransportPresentation(true); + result["connected_tailnet_name_marks_actual_transport"] = _currentNodeName == "VPN002 + Tailscale" && _currentNodeUsesTailnet; + UpdateConnectedTransportPresentation(true); + result["tailnet_refresh_does_not_duplicate_suffix"] = _currentNodeName == "VPN002 + Tailscale"; + UpdateConnectedTransportPresentation(false); + result["tailnet_fallback_removes_suffix_keeps_node"] = _currentNodeName == "VPN002" && _currentNodeSlug == "office-test" && !_currentNodeUsesTailnet; + result["transport_does_not_duplicate_node_choices"] = _manualNodeCombo.Items.Count == nodeCount && nodeCount == 2; + _currentNodeIsPrivateAuxiliary = true; + _currentNodeBaseName = NodePresentation.JinanName; + UpdateConnectedTransportPresentation(true); + result["private_tailnet_connection_shows_actual_transport"] = _currentNodeName == NodePresentation.JinanName + " + Tailscale" && _currentNodeUsesTailnet; + _currentNodeBaseName = null; + UpdateConnectedTransportPresentation(false); + result["cleared_connection_does_not_claim_tailnet"] = _currentNodeName is null && !_currentNodeUsesTailnet; + // Exercise real dashboard layout, not the hidden login page's stale bounds. + Opacity = 0; + ShowInTaskbar = false; + Show(); + ShowDashboard(profile); + _refreshTimer.Stop(); + PerformLayout(); + Application.DoEvents(); + _currentNodeName = NodePresentation.JinanName; + _currentNodeLabel.Text = _currentNodeName; + SetConnectionState(true, "已安全连接", _currentNodeName); + LayoutDashboard(); + result["connected_node_gets_full_width"] = _currentNodeLabel.Right == _nodeCard.Width - ScaleLogical(14); + result["connected_mode_badge_does_not_cover_name"] = !_scheduleBadge.Visible; + result["zero3_name_fits_connected_row"] = TextRenderer.MeasureText(_currentNodeName, _currentNodeLabel.Font).Width <= _currentNodeLabel.Width; + Size = MinimumSize; + PerformLayout(); + LayoutDashboard(); + Application.DoEvents(); + result["zero3_name_fits_compact_connected_row"] = TextRenderer.MeasureText(_currentNodeName, _currentNodeLabel.Font).Width <= _currentNodeLabel.Width; + RequestExit(); + return result; + } +} diff --git a/windows/ConnectionSelfTest.cs b/windows/ConnectionSelfTest.cs new file mode 100644 index 0000000..ef6244a --- /dev/null +++ b/windows/ConnectionSelfTest.cs @@ -0,0 +1,207 @@ +using System.Net; +using System.Text.Json; + +namespace UCVL.VPNPlus; + +internal static class ConnectionSelfTest +{ + private sealed class ProbeResult + { + public string Name { get; init; } = ""; + public string Url { get; init; } = ""; + public int? StatusCode { get; init; } + public long ElapsedMilliseconds { get; init; } + public string Error { get; init; } = ""; + } + + private sealed class TestResult + { + public DateTimeOffset StartedAt { get; init; } + public DateTimeOffset FinishedAt { get; set; } + public string Node { get; set; } = ""; + public string RouteMode { get; set; } = "smart"; + public bool Connected { get; set; } + public bool Passed { get; set; } + public bool AuthenticatedCodexConversationTested { get; set; } + public string Error { get; set; } = ""; + public List Probes { get; } = []; + public Dictionary HandoverChecks { get; } = []; + public bool PhysicalAdapterSwitchTested { get; set; } + } + + internal static async Task RunAsync(int stabilizationMilliseconds = 1500, string? accessToken = null, string routeMode = "smart", bool exerciseHandover = false) + { + AppPaths.EnsureDirectory(); + var result = new TestResult { StartedAt = DateTimeOffset.Now, RouteMode = routeMode }; + try + { + var token = string.IsNullOrWhiteSpace(accessToken) ? TokenStore.Load() : accessToken; + if (string.IsNullOrWhiteSpace(token)) + { + throw new InvalidOperationException("本机没有可用的登录会话。"); + } + using var api = new VpnApiClient(); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(150)); + var profile = await api.GetProfileAsync(token, timeout.Token); + var nodes = profile.Nodes + .Where(item => string.Equals(item.Status, "online", StringComparison.OrdinalIgnoreCase)) + .Concat(profile.Nodes.Where(item => !string.Equals(item.Status, "online", StringComparison.OrdinalIgnoreCase))) + .DistinctBy(item => item.Slug, StringComparer.OrdinalIgnoreCase) + .ToList(); + if (nodes.Count == 0) throw new InvalidOperationException("当前账号没有可测试的线路。"); + await using var xray = new XrayManager(); + var failures = new List(); + var excluded = new HashSet(StringComparer.OrdinalIgnoreCase); + for (var attempt = 0; attempt < Math.Min(nodes.Count, 8); attempt++) + { + NodeInfo? candidate = null; + try + { + // Exercise the same server-side automatic assignment as the + // UI, not a private test-only choice from the profile list. + var config = await api.GetConfigAsync(token, "auto", routeMode, timeout.Token, excluded); + candidate = config.Node; + result.Node = candidate.Name; + await xray.StartAsync(config.GetRuntimeConfigJson(), routeMode, candidate.Slug, timeout.Token); + break; + } + catch (LocalNetworkException) { throw; } + catch (ApiException exception) when (exception.StatusCode is 401 or 403) { throw; } + catch (Exception exception) when (exception is not OperationCanceledException) + { + failures.Add($"{candidate?.Name ?? "AI assignment"}: {exception.Message}"); + await xray.StopAsync(); + if (candidate is null) break; + excluded.Add(candidate.Slug); + } + } + if (!xray.IsRunning) + { + throw new InvalidOperationException( + "所有线路均未通过出口验证。" + string.Join(";", failures)); + } + result.Connected = true; + await Task.Delay(stabilizationMilliseconds, timeout.Token); + + using var handler = new SocketsHttpHandler + { + UseProxy = true, + Proxy = new WebProxy("http://127.0.0.1:10809"), + ConnectTimeout = TimeSpan.FromSeconds(10), + AutomaticDecompression = DecompressionMethods.All, + }; + using var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(15) }; + client.DefaultRequestHeaders.UserAgent.ParseAdd("UCVL-VPNPlus-ConnectionTest/0.2.2"); + result.Probes.Add(await ProbeAsync(client, "Google", "https://www.google.com/generate_204", timeout.Token)); + result.Probes.Add(await ProbeAsync(client, "OpenAI API", "https://api.openai.com/v1/models", timeout.Token)); + result.Probes.Add(await ProbeAsync(client, "Codex endpoint (unauthenticated)", "https://chatgpt.com/backend-api/codex/models", timeout.Token)); + result.Probes.Add(await ProbeAsync(client, "ChatGPT", "https://chatgpt.com/", timeout.Token)); + result.Probes.Add(await ProbeAsync(client, "管理平台", "https://vpn.toplc.cn/health/", timeout.Token)); + + // A browser following an explicit HTTP proxy is not evidence that + // native clients use the global TUN. Exercise both paths separately. + using var nativeHandler = new SocketsHttpHandler { UseProxy = false, ConnectTimeout = TimeSpan.FromSeconds(10) }; + using var native = new HttpClient(nativeHandler) { Timeout = TimeSpan.FromSeconds(15) }; + result.Probes.Add(await ProbeAsync(native, "Google via TUN (no HTTP proxy)", "https://www.google.com/generate_204", timeout.Token)); + result.Probes.Add(await ProbeAsync(native, "Codex via TUN (unauthenticated)", "https://chatgpt.com/backend-api/codex/models", timeout.Token)); + + var google = result.Probes.First(item => item.Name == "Google"); + var openAi = result.Probes.First(item => item.Name == "OpenAI API"); + var platform = result.Probes.First(item => item.Name == "管理平台"); + result.Passed = google.StatusCode is 200 or 204 + && openAi.StatusCode is 200 or 401 + && platform.StatusCode == 200; + var codex = result.Probes.First(item => item.Name == "Codex endpoint (unauthenticated)"); + result.Passed = result.Passed && codex.StatusCode is 200 or 401; + result.Passed = result.Passed + && result.Probes.First(item => item.Name == "Google via TUN (no HTTP proxy)").StatusCode is 200 or 204 + && result.Probes.First(item => item.Name == "Codex via TUN (unauthenticated)").StatusCode is 200 or 401; + // Probe results establish transport reachability, not an actual + // authenticated Codex conversation. Keep this distinction explicit. + if (result.Passed && exerciseHandover) + { + // Inject only the observed outage. The real Xray/route/DNS lifecycle + // executes; physical Wi-Fi/Ethernet adapters are never disabled. + var initialCore=xray.CoreId; + var initialNetwork=xray.BoundNetworkFingerprint; + var handover=new NetworkHandover(xray); + var now=Environment.TickCount64; + await handover.ObserveAsync(new(true,null),now,timeout.Token); + await Task.Delay(3100,timeout.Token); + var offline=await handover.ObserveAsync(new(true,null),Environment.TickCount64,timeout.Token); + result.HandoverChecks["outage_stops_real_core_preserves_config"]=offline==NetworkHandover.Result.Offline && !xray.IsRunning && xray.CanRebindNetwork; + var reading=PhysicalUplink.Read(); + if (!reading.Success || reading.Network is null) throw new IOException("Physical uplink unavailable during protected test"); + await handover.ObserveAsync(reading,Environment.TickCount64,timeout.Token); + await Task.Delay(3100,timeout.Token); + var restored=await handover.ObserveAsync(PhysicalUplink.Read(),Environment.TickCount64,timeout.Token); + result.HandoverChecks["real_core_recreated"]=restored==NetworkHandover.Result.Recovered && xray.IsRunning && xray.CoreId!=initialCore; + result.HandoverChecks["same_uplink_recovery"]=xray.BoundNetworkFingerprint==initialNetwork; + api.ResetTransport(); + var fresh=await api.GetProfileAsync(token,timeout.Token); + result.HandoverChecks["platform_authorization_after_transport_reset"]=fresh.Nodes.Count>0; + using var freshHandler=new SocketsHttpHandler { UseProxy=false, ConnectTimeout=TimeSpan.FromSeconds(10) }; + using var freshHttp=new HttpClient(freshHandler) { Timeout=TimeSpan.FromSeconds(15) }; + var afterGoogle=await ProbeAsync(freshHttp,"Google after handover via TUN","https://www.google.com/generate_204",timeout.Token); + var afterCodex=await ProbeAsync(freshHttp,"Codex after handover via TUN","https://chatgpt.com/backend-api/codex/models",timeout.Token); + result.Probes.Add(afterGoogle); result.Probes.Add(afterCodex); + result.HandoverChecks["tun_transport_after_rebind"]=afterGoogle.StatusCode is 200 or 204 && afterCodex.StatusCode is 200 or 401; + var stableCore=xray.CoreId; + result.HandoverChecks["steady_network_does_not_loop"]=await handover.ObserveAsync(PhysicalUplink.Read(),Environment.TickCount64,timeout.Token)==NetworkHandover.Result.Unchanged && xray.CoreId==stableCore; + result.Passed &= result.HandoverChecks.Values.All(v=>v); + } + if (result.Passed && !exerciseHandover && int.TryParse(Environment.GetEnvironmentVariable("UCVL_VPN_TEST_HOLD_SECONDS"), out var seconds)) + { + File.WriteAllText(AppPaths.ConnectionSelfTestFile, + JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true })); + await Task.Delay(TimeSpan.FromSeconds(Math.Clamp(seconds, 0, 75)), timeout.Token); + } + await xray.StopAsync(); + return result.Passed ? 0 : 2; + } + catch (Exception exception) + { + result.Passed = false; + result.Error = exception.Message; + AppPaths.WriteError(exception); + return 3; + } + finally + { + result.FinishedAt = DateTimeOffset.Now; + File.WriteAllText( + AppPaths.ConnectionSelfTestFile, + JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true })); + } + } + + private static async Task ProbeAsync( + HttpClient client, + string name, + string url, + CancellationToken cancellationToken) + { + var started = System.Diagnostics.Stopwatch.StartNew(); + try + { + using var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken); + return new ProbeResult + { + Name = name, + Url = url, + StatusCode = (int)response.StatusCode, + ElapsedMilliseconds = started.ElapsedMilliseconds, + }; + } + catch (Exception exception) + { + return new ProbeResult + { + Name = name, + Url = url, + ElapsedMilliseconds = started.ElapsedMilliseconds, + Error = exception.GetBaseException().Message, + }; + } + } +} diff --git a/windows/DailyTrafficChart.cs b/windows/DailyTrafficChart.cs new file mode 100644 index 0000000..e3f59da --- /dev/null +++ b/windows/DailyTrafficChart.cs @@ -0,0 +1,70 @@ +namespace UCVL.VPNPlus; + +internal sealed class DailyTrafficChart : Control +{ + private List _legacy = []; + private Dictionary? _ranges; + private UsageHistoryPeriod _period = UsageHistoryPeriod.All[2]; + private UsageHistorySeries? _series; + private readonly ToolTip _tip = new(); + private RectangleF _plot; + internal event Action? HistoryChanged; + internal string StatusText => _series is null ? "后台暂未提供此范围的明细" : + _series.Points.Any(p => p.UploadBytes is null || p.DownloadBytes is null) ? "按小时入账 · 缺口为无明细" : + _series.Bucket == "hour" ? "按小时入账 · 含当前小时" : "套餐全部设备 · 按天统计"; + internal string DetailText => _series is null ? "后台未提供此范围的可用明细;需要配套后台升级。" : + $"套餐全部设备 · {_series.Timezone}\n{_series.Note}\n本期总量不随筛选改变;本次流量仅指本机当前连接。"; + internal string SelectedRange => _period.Key; + internal int PointCount => _series?.Points.Count ?? 0; + internal DailyTrafficChart() { DoubleBuffered = true; BackColor = Color.White; Font = Brand.Font(7.3f); } + internal void SetHistory(List history, Dictionary? ranges = null) + { _legacy = history; _ranges = ranges; RefreshSeries(); } + internal void SetPeriod(UsageHistoryPeriod period) { _period = period; RefreshSeries(); } + private void RefreshSeries() + { + _series = UsageHistorySeries.Select(_period, _legacy, _ranges); + _tip.SetToolTip(this, DetailText); + Invalidate(); HistoryChanged?.Invoke(); + } + protected override void OnMouseMove(MouseEventArgs e) + { + base.OnMouseMove(e); + if (_series is null || _series.Points.Count == 0 || _plot.Width <= 0 || !_plot.Contains(e.Location)) return; + var index = Math.Clamp((int)Math.Round((e.X - _plot.Left) * (_series.Points.Count - 1d) / _plot.Width), 0, _series.Points.Count - 1); + var p = _series.Points[index]; + string Bytes(long? n) => n.HasValue ? $"{n.Value / 1024d / 1024:0.00} MB" : "无小时明细"; + _tip.SetToolTip(this, $"{p.Time} ({_series.Timezone})\n代理上传 {Bytes(p.UploadBytes)} · 代理下载 {Bytes(p.DownloadBytes)}\n{_series.Note}"); + } + protected override void Dispose(bool disposing) { if (disposing) _tip.Dispose(); base.Dispose(disposing); } + protected override void OnPaint(PaintEventArgs e) + { + base.OnPaint(e); + var points = _series?.Points ?? []; + var peak = points.Count == 0 ? 1024 * 1024d : Math.Max(1024 * 1024d, points.Max(p => Math.Max(p.UploadBytes ?? 0, p.DownloadBytes ?? 0))); + var chart = ChartAxis.Draw(e.Graphics, ClientRectangle, Font, DeviceDpi, peak, speed: false); + _plot = chart.Plot; + if (points.Count == 0 || points.All(p => p.UploadBytes is null && p.DownloadBytes is null)) + { + var message = _series is null ? "此范围需后台提供明细" : "暂无此范围代理流量明细"; + TextRenderer.DrawText(e.Graphics, message, Font, Rectangle.Round(_plot), Brand.Muted, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter); + } + void Line(bool up) + { + var segment = new List(); + void Flush() { ChartAxis.Curve(e.Graphics, segment.ToArray(), up ? Brand.RoyalBlue : Brand.Cyan, DeviceDpi, dots: true); segment.Clear(); } + for (var i = 0; i < points.Count; i++) + { + var n = up ? points[i].UploadBytes : points[i].DownloadBytes; + if (n is null) { Flush(); continue; } // Never bridge a missing-data interval. + segment.Add(new(_plot.Left + i * _plot.Width / Math.Max(1, points.Count - 1), + _plot.Bottom - (float)(n.Value / chart.Maximum) * _plot.Height)); + } + Flush(); + } + Line(true); Line(false); + // At most four axis labels; all points remain available in the plot/tooltips. + var labels = points.Select((p, i) => i == 0 || i == points.Count - 1 || i == (points.Count-1)/3 || i == (points.Count-1)*2/3 + ? p.Timestamp?.ToString(_period.Bucket == "hour" ? "HH:mm" : "MM/dd") ?? "" : "").ToArray(); + ChartAxis.TimeLabels(e.Graphics, _plot, Font, labels); + } +} diff --git a/windows/DashboardControls.cs b/windows/DashboardControls.cs new file mode 100644 index 0000000..413e2b9 --- /dev/null +++ b/windows/DashboardControls.cs @@ -0,0 +1,172 @@ +using System.Drawing.Drawing2D; + +namespace UCVL.VPNPlus; + +internal enum DashboardIcon { Server, Settings, Database, Upload, Download, Document, Chart, History, Shield } + +// Code-drawn icons keep the existing brand assets and remain crisp at high DPI. +internal static class DashboardDrawing +{ + internal static void Icon(Graphics g, DashboardIcon icon, Rectangle bounds, Color color) + { + var state = g.Save(); + g.SmoothingMode = SmoothingMode.AntiAlias; + g.TranslateTransform(bounds.Left, bounds.Top); + g.ScaleTransform(bounds.Width / 24f, bounds.Height / 24f); + using var pen = new Pen(color, 1.8f) { StartCap = LineCap.Round, EndCap = LineCap.Round, LineJoin = LineJoin.Round }; + switch (icon) + { + case DashboardIcon.Server: + g.DrawRectangle(pen, 2, 3, 20, 7); g.DrawRectangle(pen, 2, 14, 20, 7); + g.DrawLine(pen, 6, 6, 6, 7); g.DrawLine(pen, 6, 17, 6, 18); + g.DrawLine(pen, 15, 6.5f, 18, 6.5f); g.DrawLine(pen, 15, 17.5f, 18, 17.5f); break; + case DashboardIcon.Settings: + g.DrawEllipse(pen, 5, 5, 14, 14); g.DrawEllipse(pen, 9, 9, 6, 6); + for (var i = 0; i < 8; i++) { var a = i * Math.PI / 4; g.DrawLine(pen, 12 + (float)Math.Cos(a) * 8, 12 + (float)Math.Sin(a) * 8, 12 + (float)Math.Cos(a) * 10, 12 + (float)Math.Sin(a) * 10); } break; + case DashboardIcon.Database: + g.DrawEllipse(pen, 3, 3, 18, 6); g.DrawLine(pen, 3, 6, 3, 18); g.DrawLine(pen, 21, 6, 21, 18); + g.DrawArc(pen, 3, 9, 18, 6, 0, 180); g.DrawArc(pen, 3, 15, 18, 6, 0, 180); break; + case DashboardIcon.Upload: + case DashboardIcon.Download: + var up = icon == DashboardIcon.Upload; + g.DrawLine(pen, 12, 3, 12, 16); + g.DrawLines(pen, up ? [new PointF(7, 8), new(12, 3), new(17, 8)] : [new PointF(7, 11), new(12, 16), new(17, 11)]); + g.DrawLines(pen, [new PointF(3, 16), new(3, 21), new(21, 21), new(21, 16)]); break; + case DashboardIcon.Document: + g.DrawLines(pen, [new PointF(5, 2), new(15, 2), new(20, 7), new(20, 22), new(5, 22), new(5, 2)]); + g.DrawLines(pen, [new PointF(15, 2), new(15, 7), new(20, 7)]); + g.DrawLine(pen, 9, 12, 16, 12); g.DrawLine(pen, 9, 16, 16, 16); break; + case DashboardIcon.Chart: + for (var i = 0; i < 4; i++) g.DrawLine(pen, 4 + i * 5, 21, 4 + i * 5, 16 - i * 4); break; + case DashboardIcon.History: + g.DrawArc(pen, 2, 2, 20, 20, -85, 350); g.DrawLine(pen, 12, 2, 12, 12); g.DrawLine(pen, 12, 12, 22, 12); break; + case DashboardIcon.Shield: + using (var shield = new GraphicsPath()) + { + shield.AddLines([new PointF(12, 1), new(22, 5), new(22, 12)]); + shield.AddBezier(22, 12, 22, 18, 15, 22, 12, 24); + shield.AddBezier(12, 24, 9, 22, 2, 18, 2, 12); + shield.AddLine(2, 12, 2, 5); shield.CloseFigure(); + using var fill = new LinearGradientBrush(new Point(2, 2), new Point(22, 24), Color.FromArgb(100, color), color); + g.FillPath(fill, shield); + } + using (var check = new Pen(Color.White, 2.4f) { StartCap = LineCap.Round, EndCap = LineCap.Round, LineJoin = LineJoin.Round }) + g.DrawLines(check, [new PointF(7, 12), new(10.5f, 15.5f), new(17, 9)]); + break; + } + g.Restore(state); + } +} + +internal sealed class DashboardGlyph : Control +{ + internal DashboardIcon Glyph { get; set; } + internal DashboardGlyph(DashboardIcon glyph) { Glyph = glyph; DoubleBuffered = true; SetStyle(ControlStyles.SupportsTransparentBackColor, true); BackColor = Color.Transparent; ForeColor = Brand.RoyalBlue; } + protected override void OnPaint(PaintEventArgs e) + { + base.OnPaint(e); + var side = Math.Min(Width, Height) - 4; + if (side > 0) DashboardDrawing.Icon(e.Graphics, Glyph, new((Width - side) / 2, (Height - side) / 2, side, side), ForeColor); + } +} + +internal sealed class BrandHeaderPanel : Panel +{ + internal BrandHeaderPanel() { DoubleBuffered = true; ResizeRedraw = true; } + protected override void OnPaintBackground(PaintEventArgs e) + { + ScenicTheme.Backdrop(e.Graphics, ClientSize, DeviceDpi, header: true); + } +} + +internal sealed class MetricCard : CardPanel +{ + internal DashboardIcon Glyph { get; } + internal string Heading { get; } + internal string ValueText { get; private set; } = "—"; + internal string UnitText { get; private set; } = ""; + internal string Hint { get; private set; } = "仅代理流量"; + internal MetricCard(string heading, DashboardIcon glyph) { Heading = heading; Glyph = glyph; AccessibleName = heading; } + internal void SetBytes(double? bytes, bool speed = false, string? hint = null) + { + string[] units = ["B", "KB", "MB", "GB", "TB"]; + var value = bytes.HasValue && double.IsFinite(bytes.Value) ? Math.Max(0, bytes.Value) : (double?)null; + var unit = 0; + while (value >= 1024 && unit < units.Length - 1) { value /= 1024; unit++; } + ValueText = value.HasValue ? (value == 0 ? "0" : value.Value.ToString("0.##")) : "—"; + UnitText = value.HasValue ? units[unit] + (speed ? "/s" : "") : ""; + Hint = hint ?? "仅代理流量"; + AccessibleDescription = $"{Heading} {ValueText} {UnitText},{Hint}"; + Invalidate(); + } + protected override void OnPaint(PaintEventArgs e) + { + base.OnPaint(e); + var s = DeviceDpi / 96f; + int S(int n) => (int)Math.Round(n * s); + var g = e.Graphics; + DashboardDrawing.Icon(g, Glyph, new(S(10), S(18), S(22), S(22)), Glyph == DashboardIcon.Download ? Brand.Cyan : Brand.RoyalBlue); + var x = S(49); var right = Width - S(12); var available = right - x; + using var headingFont = Brand.Font(9); + using var unitFont = Brand.Font(9); + using var hintFont = Brand.Font(7.8f); + TextRenderer.DrawText(g, Heading, headingFont, new Rectangle(x, S(10), available, S(23)), Brand.Text, TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis); + var flags = TextFormatFlags.NoPadding | TextFormatFlags.SingleLine; + var unitWidth = TextRenderer.MeasureText(g, UnitText, unitFont, Size.Empty, flags).Width; + var size = 22f; + Font valueFont; + while (true) + { + valueFont = Brand.Font(size, FontStyle.Bold); + if (TextRenderer.MeasureText(g, ValueText, valueFont, Size.Empty, flags).Width + unitWidth + S(5) <= available || size <= 13) break; + valueFont.Dispose(); size--; + } + using (valueFont) + { + var valueWidth = TextRenderer.MeasureText(g, ValueText, valueFont, Size.Empty, flags).Width; + TextRenderer.DrawText(g, ValueText, valueFont, new Rectangle(x, S(31), available - unitWidth - S(4), S(32)), Brand.Navy, flags | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis); + TextRenderer.DrawText(g, UnitText, unitFont, new Rectangle(x + valueWidth + S(4), S(40), unitWidth, S(23)), Brand.Muted, flags | TextFormatFlags.VerticalCenter); + } + TextRenderer.DrawText(g, Hint, hintFont, new Rectangle(x, S(64), available, S(17)), Brand.Muted, TextFormatFlags.EndEllipsis); + } +} + +internal sealed class BadgeLabel : Label +{ + internal BadgeLabel() { DoubleBuffered = true; ResizeRedraw = true; } + protected override void OnPaint(PaintEventArgs e) + { + if (Width < 4 || Height < 4) return; + if (Parent is { } parent) + { + var state = e.Graphics.Save(); + e.Graphics.TranslateTransform(-Left, -Top); + InvokePaintBackground(parent, new PaintEventArgs(e.Graphics, parent.ClientRectangle)); + e.Graphics.Restore(state); + } + else e.Graphics.Clear(Brand.Surface); + e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; + using var path = UiGeometry.RoundedRectangle(new(0, 0, Width - 1, Height - 1), (Height - 1) / 2); + using var fill = new SolidBrush(BackColor); + e.Graphics.FillPath(fill, path); + TextRenderer.DrawText(e.Graphics, Text, Font, ClientRectangle, ForeColor, + TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis); + } +} + +internal sealed class ReadOnlyModeLabel : Control +{ + internal ReadOnlyModeLabel() { DoubleBuffered = true; ResizeRedraw = true; BackColor = Color.White; Font = Brand.Font(9.5f); AccessibleName = "当前代理模式(连接中不可修改)"; } + protected override void OnTextChanged(EventArgs e) { base.OnTextChanged(e); Invalidate(); } + protected override void OnPaint(PaintEventArgs e) + { + if (Width < 10 || Height < 10) return; + e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; + using var path = UiGeometry.RoundedRectangle(new(1, 1, Width - 3, Height - 3), Math.Max(3, DeviceDpi / 24)); + using var border = new Pen(Color.FromArgb(204, 219, 237)); + e.Graphics.DrawPath(border, path); + var pad = DeviceDpi / 12; + TextRenderer.DrawText(e.Graphics, Text, Font, new Rectangle(pad, 0, Width - pad * 2, Height), Brand.Text, + TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis); + } +} diff --git a/windows/DashboardLayout.cs b/windows/DashboardLayout.cs new file mode 100644 index 0000000..5672edb --- /dev/null +++ b/windows/DashboardLayout.cs @@ -0,0 +1,61 @@ +namespace UCVL.VPNPlus; + +internal readonly record struct DashboardGeometry( + Rectangle WelcomeLabel, Rectangle AccountLabel, Rectangle IdentityBadge, + Rectangle LogoutButton, Rectangle StatusCard, Rectangle NodeCard, Rectangle ModeCard, + Rectangle[] Metrics, Rectangle TrafficCard, Rectangle DailyCard, Rectangle Footer, + int ContentHeight, bool Compact); + +// Logical pixels converted once, independent of WinForms autoscaling. +internal static class DashboardLayout +{ + internal static DashboardGeometry Calculate(Size viewport, int dpi) + { + var scale = Math.Max(1f, dpi / 96f); + int S(int n) => (int)Math.Round(n * scale); + var margin = S(20); + var gap = S(10); + var width = Math.Max(S(540), viewport.Width - margin * 2); + var compact = width < S(720); + var half = (width - gap) / 2; + var welcome = new Rectangle(margin, S(8), width - S(132), S(30)); + var account = new Rectangle(margin, S(38), Math.Min(S(275), width - S(230)), S(24)); + var identity = new Rectangle(account.Right + S(10), S(38), S(92), S(23)); + var logout = new Rectangle(margin + width - S(104), S(16), S(104), S(34)); + var status = new Rectangle(margin, S(72), width, S(76)); + var node = new Rectangle(margin, status.Bottom + gap, compact ? width : half, S(72)); + var mode = compact + ? new Rectangle(margin, node.Bottom + gap, width, node.Height) + : new Rectangle(node.Right + gap, node.Top, width - half - gap, node.Height); + var traffic = new Rectangle(margin, mode.Bottom + gap, compact ? width : half, S(276)); + var daily = compact + ? new Rectangle(margin, traffic.Bottom + gap, width, traffic.Height) + : new Rectangle(traffic.Right + gap, traffic.Top, width - half - gap, traffic.Height); + Rectangle Metric(Rectangle parent, int column) => new(S(14) + column * ((parent.Width - S(28)) / 2), S(43), (parent.Width - S(28)) / 2 - S(2), S(82)); + // Relative to their matching chart card: totals together; speeds together. + Rectangle[] metrics = [Metric(daily, 0), Metric(traffic, 0), Metric(traffic, 1), Metric(daily, 1)]; + var footer = new Rectangle(margin, daily.Bottom + gap, width, S(76)); + return new(welcome, account, identity, logout, status, node, mode, metrics, traffic, + daily, footer, footer.Bottom + S(12), compact); + } + + internal static bool SelfTest() + { + foreach (var dpi in new[] { 96, 120, 144, 168, 192, 240, 288 }) + foreach (var width in new[] { 600, 620, 739, 760, 780, 900, 1100, 1600 }) + { + var viewport = new Size(width * dpi / 96, 560 * dpi / 96); + var p = Calculate(viewport, dpi); + Rectangle[] cards = [p.StatusCard, p.NodeCard, p.ModeCard, p.TrafficCard, p.DailyCard, p.Footer]; + if (cards.Any(c => c.Left < 0 || c.Right > viewport.Width || c.Bottom > p.ContentHeight || c.Width <= 0)) return false; + for (var i = 0; i < cards.Length; i++) + for (var j = i + 1; j < cards.Length; j++) + if (cards[i].IntersectsWith(cards[j])) return false; + if (p.WelcomeLabel.IntersectsWith(p.LogoutButton) || p.AccountLabel.IntersectsWith(p.IdentityBadge)) return false; + if (p.Metrics[0].IntersectsWith(p.Metrics[3]) || p.Metrics[1].IntersectsWith(p.Metrics[2])) return false; + for (var i = 0; i < p.Metrics.Length; i++) + if (p.Metrics[i].Right > (i == 0 || i == 3 ? p.DailyCard.Width : p.TrafficCard.Width)) return false; + } + return true; + } +} diff --git a/windows/GitReleasePolicySelfTest.cs b/windows/GitReleasePolicySelfTest.cs new file mode 100644 index 0000000..c3029c9 --- /dev/null +++ b/windows/GitReleasePolicySelfTest.cs @@ -0,0 +1,91 @@ +using System.Net; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace UCVL.VPNPlus; + +// In-memory adversarial responses. No real metadata is published or downloaded. +internal static class GitReleasePolicySelfTest +{ + private const string Name = "UCVL-Zonghengjia-0.2.16-win-x64-setup.exe"; + private const string Url = "https://pro.ucvl.cn/admin/ucvl-software-downloads/releases/download/windows-v0.2.16/" + Name; + private sealed class Handler(string mutation) : HttpMessageHandler + { + internal bool OnlyPublicUnauthenticated { get; private set; } = true; + protected override Task SendAsync(HttpRequestMessage request, CancellationToken token) + { + token.ThrowIfCancellationRequested(); + OnlyPublicUnauthenticated &= request.RequestUri?.Host == "pro.ucvl.cn" + && request.RequestUri.Scheme == "https" && request.Headers.Authorization is null; + var api = request.RequestUri!.AbsolutePath.EndsWith("/releases", StringComparison.Ordinal); + var release = JsonNode.Parse(JsonSerializer.Serialize(new { + tag_name="windows-v0.2.16", draft=false, prerelease=false, body="fixture", + assets=new[] { + new { name=Name, size=300000, browser_download_url="http://172.16.0.21:3000/untrusted.exe" }, + new { name=Name+".sha256", size=120, browser_download_url="https://untrusted.invalid/sha" }, + }, + }))!; + var assets = release["assets"]!.AsArray(); + if (mutation == "duplicate_installer") assets.Add(assets[0]!.DeepClone()); + if (mutation == "duplicate_checksum") assets.Add(assets[1]!.DeepClone()); + if (mutation == "missing_installer") assets.RemoveAt(0); + if (mutation == "oversized_installer") assets[0]!["size"] = 200L * 1024 * 1024 + 1; + if (mutation == "four_part_version") release["tag_name"] = "windows-v9.0.0.1"; + if (mutation == "missing_newest_no_fallback") { + release["tag_name"] = "windows-v0.2.17"; + assets.Clear(); + } + var text = api ? new JsonArray(release).ToJsonString() : new string('a',64) + " " + Name; + if (api && mutation == "missing_newest_no_fallback") { + var list=JsonNode.Parse(text)!.AsArray(); + var old=release.DeepClone(); old["tag_name"]="windows-v0.2.15"; + old["assets"]=new JsonArray( + new JsonObject { ["name"]="UCVL-Zonghengjia-0.2.15-win-x64-setup.exe", ["size"]=300000 }, + new JsonObject { ["name"]="UCVL-Zonghengjia-0.2.15-win-x64-setup.exe.sha256", ["size"]=120 }); + list.Add(old); text=list.ToJsonString(); + } + if (!api && mutation == "wrong_checksum_filename") text=new string('a',64)+" other.exe"; + if (!api && mutation == "missing_newest_no_fallback") text=new string('a',64)+" UCVL-Zonghengjia-0.2.15-win-x64-setup.exe"; + if (!api && mutation == "checksum_extra_line") text+="\n"+text; + if (!api && mutation == "oversized_checksum") text=new string('a',4097); + if (api && mutation.StartsWith("oversized_metadata", StringComparison.Ordinal)) text=new string(' ',2*1024*1024+1); + var response=new HttpResponseMessage(mutation == "redirect" ? HttpStatusCode.Found : HttpStatusCode.OK) { + Content=new ByteArrayContent(Encoding.UTF8.GetBytes(text)), + }; + if (mutation == "oversized_metadata_stream") response.Content.Headers.ContentLength = 1; + if (mutation == "redirect") response.Headers.Location=new Uri("https://untrusted.invalid/redirect"); + return Task.FromResult(response); + } + } + + internal static async Task RunAsync(Dictionary report, string directory, IProgress progress) + { + foreach (var mutation in new[] { "duplicate_installer", "duplicate_checksum", "missing_installer", + "oversized_installer", "four_part_version", "wrong_checksum_filename", "checksum_extra_line", + "oversized_checksum", "oversized_metadata", "oversized_metadata_stream", "redirect", + "missing_newest_no_fallback" }) + { + var rejected=false; + try { await GitReleaseUpdater.GetLatestAsync(CancellationToken.None,new Handler(mutation),"0.2.15"); } + catch (Exception error) when (error is InvalidOperationException or HttpRequestException) { rejected=true; } + report["git_rejects_"+mutation]=rejected; + } + var validHandler=new Handler("normal"); + var info=await GitReleaseUpdater.GetLatestAsync(CancellationToken.None,validHandler,"0.2.15"); + report["git_ignores_attachment_urls_uses_public_unauthenticated_origin"]=info.DownloadUrl==Url && validHandler.OnlyPublicUnauthenticated; + foreach (var invalid in new[] { Url.Replace("https:","http:"), Url.Replace("pro.ucvl.cn","pro.ucvl.cn:444"), + Url.Replace("pro.ucvl.cn","user@pro.ucvl.cn"), Url+"?token=test", Url+"#fragment", + "https://pro.ucvl.cn/attachments/fixture.exe", Url.Replace("0.2.16/","0.2.15/") }) + { + var rejected=false; + try { + await ClientUpdater.DownloadForTestAsync(new ClientUpdateInfo { + Version="0.2.16",Available=true,DownloadUrl=invalid,Size=300000,Sha256=new string('a',64), + },CancellationToken.None,progress,directory,new Handler("must_not_be_called")); + } catch (InvalidOperationException) { rejected=true; } + if (!rejected) throw new InvalidOperationException("Unexpected installer address accepted: "+invalid); + } + report["downloader_rejects_noncanonical_origins_and_paths"]=true; + } +} diff --git a/windows/GitReleaseUpdater.cs b/windows/GitReleaseUpdater.cs new file mode 100644 index 0000000..f8c577f --- /dev/null +++ b/windows/GitReleaseUpdater.cs @@ -0,0 +1,137 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text; + +namespace UCVL.VPNPlus; + +internal static class GitReleaseUpdater +{ + internal const string ReleaseApi = + "https://pro.ucvl.cn/api/v1/repos/admin/ucvl-software-downloads/releases?limit=50"; + private const string DownloadRoot = + "https://pro.ucvl.cn/admin/ucvl-software-downloads/releases/download/"; + private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNameCaseInsensitive = true }; + + internal static async Task GetLatestAsync( + CancellationToken cancellationToken, + HttpMessageHandler? transport = null, + string? currentVersion = null, + TimeSpan? totalTimeout = null) + { + // Include both streamed bodies (metadata and checksum) in one deadline. + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + deadline.CancelAfter(totalTimeout ?? TimeSpan.FromSeconds(20)); + var token = deadline.Token; + using var client = new HttpClient(transport ?? new SocketsHttpHandler + { + UseProxy = false, + ConnectTimeout = TimeSpan.FromSeconds(10), + AutomaticDecompression = DecompressionMethods.All, + AllowAutoRedirect = false, + }) { Timeout = TimeSpan.FromSeconds(20) }; + client.DefaultRequestHeaders.UserAgent.ParseAdd($"UCVL-VPNPlus/{Application.ProductVersion} Windows-x64 Updater"); + client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + using var response = await client.GetAsync(ReleaseApi, HttpCompletionOption.ResponseHeadersRead, token); + response.EnsureSuccessStatusCode(); + var payload = await ReadBoundedAsync(response.Content, 2 * 1024 * 1024, token); + var releases = JsonSerializer.Deserialize>(payload, JsonOptions) + ?? throw new InvalidOperationException("公司 Git 没有返回版本列表。"); + if (releases.Count > 50) throw new InvalidOperationException("公司 Git 版本列表超出限制。"); + var selected = releases + .Where(item => !item.Draft && !item.Prerelease) + .Select(item => (Release: item, Version: ParseWindowsVersion(item.TagName))) + .Where(item => item.Version is not null) + .OrderByDescending(item => item.Version) + .FirstOrDefault(); + if (selected.Version is null) + { + throw new InvalidOperationException("公司 Git 暂无 Windows 正式版本。"); + } + + var versionText = selected.Version.ToString(3); + var installerName = $"UCVL-Zonghengjia-{versionText}-win-x64-setup.exe"; + var checksumName = installerName + ".sha256"; + var installer = selected.Release.Assets.SingleOrDefault(item => item.Name == installerName) + ?? throw new InvalidOperationException("公司 Git 版本缺少 Windows 安装包。"); + if (installer.Size <= 0 || installer.Size > 200L * 1024 * 1024) + { + throw new InvalidOperationException("公司 Git 安装包大小异常。"); + } + if (selected.Release.Assets.Count(item => item.Name == checksumName) != 1) + { + throw new InvalidOperationException("公司 Git 版本缺少 SHA256 文件。"); + } + + var tag = Uri.EscapeDataString(selected.Release.TagName); + var checksumUrl = $"{DownloadRoot}{tag}/{Uri.EscapeDataString(checksumName)}"; + using var checksumResponse = await client.GetAsync(checksumUrl, HttpCompletionOption.ResponseHeadersRead, token); + checksumResponse.EnsureSuccessStatusCode(); + var checksum = (await ReadBoundedAsync(checksumResponse.Content, 4096, token)).Trim(); + var fields = checksum.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); + var digest = fields.FirstOrDefault()?.ToLowerInvariant() ?? ""; + if (fields.Length != 2 || fields[1].TrimStart('*') != installerName + || digest.Length != 64 || digest.Any(character => !Uri.IsHexDigit(character))) + { + throw new InvalidOperationException("公司 Git SHA256 文件无效。"); + } + + var current = currentVersion ?? Application.ProductVersion; + return new ClientUpdateInfo + { + Available = ClientUpdater.IsNewerVersion(versionText, current), + Version = versionText, + DownloadUrl = $"{DownloadRoot}{tag}/{Uri.EscapeDataString(installerName)}", + Sha256 = digest, + Size = installer.Size, + Notes = (selected.Release.Body ?? "").Trim(), + Mandatory = false, + }; + } + + private static async Task ReadBoundedAsync(HttpContent content, int maximum, CancellationToken token) + { + if (content.Headers.ContentLength is long length && length > maximum) + throw new InvalidOperationException("公司 Git 更新元数据过大。"); + using var result = new MemoryStream(); + await using var source = await content.ReadAsStreamAsync(token); + var buffer = new byte[8192]; + while (true) + { + var read = await source.ReadAsync(buffer, token); + if (read == 0) break; + if (result.Length + read > maximum) throw new InvalidOperationException("公司 Git 更新元数据过大。"); + result.Write(buffer, 0, read); + } + return new UTF8Encoding(false, true).GetString(result.ToArray()).TrimStart('\uFEFF'); + } + + internal static bool IsStableVersion(string? text) + => Version.TryParse(text, out var version) && version.Build >= 0 && version.Revision == -1 + && version.ToString(3) == text; + + private static Version? ParseWindowsVersion(string? tag) + { + const string prefix = "windows-v"; + if (tag is null || !tag.StartsWith(prefix, StringComparison.Ordinal)) return null; + var text = tag[prefix.Length..]; + return IsStableVersion(text) ? Version.Parse(text) : null; + } + + private sealed class GiteaRelease + { + [JsonPropertyName("tag_name")] public string TagName { get; init; } = ""; + [JsonPropertyName("body")] public string? Body { get; init; } + [JsonPropertyName("draft")] public bool Draft { get; init; } + [JsonPropertyName("prerelease")] public bool Prerelease { get; init; } + [JsonPropertyName("assets")] public List Assets { get; init; } = []; + } + + private sealed class GiteaAsset + { + [JsonPropertyName("name")] public string Name { get; init; } = ""; + [JsonPropertyName("size")] public long Size { get; init; } + } +} diff --git a/windows/InstallationIntegration.cs b/windows/InstallationIntegration.cs new file mode 100644 index 0000000..e432d3e --- /dev/null +++ b/windows/InstallationIntegration.cs @@ -0,0 +1,199 @@ +using Microsoft.Win32; +using System.Text.Json; + +namespace UCVL.VPNPlus; + +// Uninstaller, two shortcuts and ten owned registry values participate in the +// SAME durable journal as the program payload. No recursive registry/file removal. +internal static class InstallationIntegration +{ + internal record Value(RegistryValueKind Kind, string Data); + internal record Component(int Id, string Sha256, string? PreviousSha256); + internal record Registration(int Id, Value Next, Value? Previous); + internal record Snapshot(bool Isolated, List Components, + List Values, bool[] KeysExisted); + private static readonly string[] Names = ["", "Path", "DisplayName", "DisplayIcon", "DisplayVersion", + "Publisher", "URLInfoAbout", "UninstallString", "NoModify", "NoRepair"]; + private static readonly string[] StagedNames = ["Uninstall.exe", "Desktop.lnk", "StartMenu.lnk"]; + private static int KeyIndex(int id) => id < 2 ? 0 : 1; + private static RegistryKey Hive() => RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry32); + internal static string Key(string target, bool isolated, int index) + { + if (index is < 0 or > 1) throw new IOException("无效安装登记位置。"); + if (isolated) + { + target = InstallationTransaction.IsolatedTarget(target); + var id = Path.GetFileName(Path.GetDirectoryName(target))!["ucvl-nsis-acceptance-".Length..]; + return $"Software\\UCVL\\InstallerAcceptance\\{id}\\" + (index == 0 ? "app" : "uninstall"); + } + return index == 0 ? @"Software\Microsoft\Windows\CurrentVersion\App Paths\VPNPlus.exe" + : @"Software\Microsoft\Windows\CurrentVersion\Uninstall\UCVL.VPNPlus"; + } + internal static string Destination(string target, bool isolated, int id) + { + if (isolated) target = InstallationTransaction.IsolatedTarget(target); + var job = Path.GetDirectoryName(target)!; + var path = id switch { + 0 => Path.Combine(target, "Uninstall.exe"), + 1 => isolated ? Path.Combine(job, "shell", "Desktop.lnk") : Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "优创⁺纵横家.lnk"), + 2 => isolated ? Path.Combine(job, "shell", "StartMenu.lnk") : Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Programs), "优创未来", "优创⁺纵横家.lnk"), + _ => throw new IOException("无效安装组件。"), + }; + InstallationTransaction.NoLinks(path); + return path; + } + private static string Backup(string backup, int id) + { + if (id is < 0 or > 2) throw new IOException("无效备份组件。"); + var path = Path.Combine(backup, "components", StagedNames[id]); + InstallationTransaction.NoLinks(path); + return path; + } + private static Value Encode(object value, RegistryValueKind kind) => new(kind, kind switch { + RegistryValueKind.String or RegistryValueKind.ExpandString => JsonSerializer.Serialize((string)value), + RegistryValueKind.DWord => JsonSerializer.Serialize((int)value), + RegistryValueKind.QWord => JsonSerializer.Serialize((long)value), + RegistryValueKind.MultiString => JsonSerializer.Serialize((string[])value), + RegistryValueKind.Binary or RegistryValueKind.None => JsonSerializer.Serialize((byte[])value), + _ => throw new IOException("不支持的原安装登记类型,未覆盖。"), + }); + private static object Decode(Value value) => value.Kind switch { + RegistryValueKind.String or RegistryValueKind.ExpandString => JsonSerializer.Deserialize(value.Data)!, + RegistryValueKind.DWord => JsonSerializer.Deserialize(value.Data), + RegistryValueKind.QWord => JsonSerializer.Deserialize(value.Data), + RegistryValueKind.MultiString => JsonSerializer.Deserialize(value.Data)!, + RegistryValueKind.Binary or RegistryValueKind.None => JsonSerializer.Deserialize(value.Data)!, + _ => throw new IOException("无效原登记类型。"), + }; + private static Value? Read(RegistryKey hive, string keyName, string name) + { + using var key = hive.OpenSubKey(keyName); + if (key is null || !key.GetValueNames().Contains(name, StringComparer.OrdinalIgnoreCase)) return null; + var value = key.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames) + ?? throw new IOException("无法读取原安装登记。"); + return Encode(value, key.GetValueKind(name)); + } + internal static Snapshot Prepare(string stage, string target, string backup, bool isolated, string version) + { + stage = InstallationTransaction.Root(stage); + if (isolated) target = InstallationTransaction.IsolatedTarget(target); + var components = new List(); + for (var i = 0; i < 3; i++) + { + var source = Path.Combine(stage, StagedNames[i]); + InstallationTransaction.NoLinks(source); + if (!File.Exists(source) || new FileInfo(source).Length == 0) throw new IOException("缺少已准备的安装组件。"); + var destination = Destination(target, isolated, i); + var previous = File.Exists(destination) ? InstallationTransaction.Digest(destination) : null; + if (previous is not null) + { + var saved = Backup(backup, i); + Directory.CreateDirectory(Path.GetDirectoryName(saved)!); + File.Copy(destination, saved); + if (!InstallationTransaction.Matches(saved, previous)) throw new IOException("安装组件备份校验失败。"); + } + components.Add(new(i, InstallationTransaction.Digest(source), previous)); + } + using var hive = Hive(); + var existed = new bool[2]; + for (var i = 0; i < 2; i++) { using var key = hive.OpenSubKey(Key(target, isolated, i)); existed[i] = key is not null; } + // Never redirect another registered installation by trusting /D alone. + var registered = Read(hive, Key(target, isolated, 0), "Path"); + if (registered is not null && (registered.Kind != RegistryValueKind.String || + !string.Equals(InstallationTransaction.Root((string)Decode(registered)), target, StringComparison.OrdinalIgnoreCase))) + throw new IOException("安装目录与当前登记不一致,未覆盖其它安装。"); + object[] next = [Path.Combine(target, "VPNPlus.exe"), target, "优创⁺纵横家", Path.Combine(target, "VPNPlus.exe"), + version, "优创未来(UCVL)", "https://vpn.toplc.cn/", "\"" + Path.Combine(target, "Uninstall.exe") + "\"", 1, 1]; + var values = Names.Select((name, i) => new Registration(i, + Encode(next[i], i < 8 ? RegistryValueKind.String : RegistryValueKind.DWord), + Read(hive, Key(target, isolated, KeyIndex(i)), name))).ToList(); + return new(isolated, components, values, existed); + } + private static void Shape(string target, Snapshot snapshot) + { + if (snapshot.Isolated) _ = InstallationTransaction.IsolatedTarget(target); + if (snapshot.Components.Count != 3 || !snapshot.Components.Select(c => c.Id).Order().SequenceEqual(new[] { 0, 1, 2 }) + || snapshot.Values.Count != 10 || !snapshot.Values.Select(v => v.Id).Order().SequenceEqual(Enumerable.Range(0, 10)) + || snapshot.KeysExisted.Length != 2) + throw new IOException("安装组件恢复记录不完整。"); + foreach (var c in snapshot.Components) + if (c.Sha256.Length != 64 || c.Sha256.Any(x => !Uri.IsHexDigit(x)) || + c.PreviousSha256 is not null && (c.PreviousSha256.Length != 64 || c.PreviousSha256.Any(x => !Uri.IsHexDigit(x)))) + throw new IOException("组件恢复校验值无效。"); + foreach (var r in snapshot.Values) { _ = Decode(r.Next); if (r.Previous is not null) _ = Decode(r.Previous); } + } + internal static void ValidateRecovery(string target, string backup, Snapshot snapshot) + { + Shape(target, snapshot); + foreach (var file in snapshot.Components) + { + var destination = Destination(target, snapshot.Isolated, file.Id); + if (!InstallationTransaction.Matches(destination, file.PreviousSha256) && !InstallationTransaction.Matches(destination, file.Sha256)) + throw new IOException("安装组件被其它程序修改,保留备份,不覆盖外部改动。"); + if (file.PreviousSha256 is not null && !InstallationTransaction.Matches(Backup(backup, file.Id), file.PreviousSha256)) + throw new IOException("安装组件恢复备份损坏。"); + } + using var hive = Hive(); + foreach (var value in snapshot.Values) + { + var current = Read(hive, Key(target, snapshot.Isolated, KeyIndex(value.Id)), Names[value.Id]); + if (current != value.Previous && current != value.Next) throw new IOException("安装登记被其它程序修改,未覆盖。"); + } + } + internal static void Apply(string stage, string target, Snapshot snapshot, Action? afterWrite = null) + { + Shape(target, snapshot); + foreach (var file in snapshot.Components) + { + var destination = Destination(target, snapshot.Isolated, file.Id); + var source = Path.Combine(stage, StagedNames[file.Id]); + InstallationTransaction.NoLinks(source); + if (!InstallationTransaction.Matches(destination, file.PreviousSha256) || !InstallationTransaction.Matches(source, file.Sha256)) + throw new IOException("安装组件在准备后发生改变。"); + InstallationTransaction.Replace(source, destination); + if (!InstallationTransaction.Matches(destination, file.Sha256)) throw new IOException("组件安装后校验失败。"); + afterWrite?.Invoke(file.Id); + } + using var hive = Hive(); + foreach (var value in snapshot.Values) + { + var name = Names[value.Id]; var path = Key(target, snapshot.Isolated, KeyIndex(value.Id)); + if (Read(hive, path, name) != value.Previous) throw new IOException("登记在备份后发生改变。"); + using var key = hive.CreateSubKey(path, true) ?? throw new IOException("无法写入安装登记。"); + key.SetValue(name, Decode(value.Next), value.Next.Kind); key.Flush(); + if (Read(hive, path, name) != value.Next) throw new IOException("安装登记写入后校验失败。"); + afterWrite?.Invoke(3 + value.Id); + } + } + internal static void Recover(string target, string backup, Snapshot snapshot) + { + ValidateRecovery(target, backup, snapshot); + using var hive = Hive(); + foreach (var value in snapshot.Values.AsEnumerable().Reverse()) + { + var path = Key(target, snapshot.Isolated, KeyIndex(value.Id)); var name = Names[value.Id]; + if (Read(hive, path, name) == value.Previous) continue; + using var key = hive.OpenSubKey(path, true) ?? throw new IOException("恢复安装登记失败。"); + if (value.Previous is null) key.DeleteValue(name, false); + else key.SetValue(name, Decode(value.Previous), value.Previous.Kind); + key.Flush(); + } + foreach (var file in snapshot.Components.AsEnumerable().Reverse()) + { + var destination = Destination(target, snapshot.Isolated, file.Id); + if (InstallationTransaction.Matches(destination, file.PreviousSha256)) continue; + if (file.PreviousSha256 is null) File.Delete(destination); + else InstallationTransaction.Replace(Backup(backup, file.Id), destination); + } + for (var i = 0; i < 2; i++) + { + if (snapshot.KeysExisted[i]) continue; + var path = Key(target, snapshot.Isolated, i); + bool empty; + using (var key = hive.OpenSubKey(path)) empty = key is not null && key.ValueCount == 0 && key.SubKeyCount == 0; + if (empty) hive.DeleteSubKey(path, false); // Exact empty owned key; never a tree. + } + } +} diff --git a/windows/InstallationIntegrationSelfTest.cs b/windows/InstallationIntegrationSelfTest.cs new file mode 100644 index 0000000..fcffd44 --- /dev/null +++ b/windows/InstallationIntegrationSelfTest.cs @@ -0,0 +1,153 @@ +using Microsoft.Win32; +using System.Text.Json; + +namespace UCVL.VPNPlus; + +internal static class InstallationIntegrationSelfTest +{ + private static readonly string[] Files = ["VPNPlus.exe", "xray/xray.exe", "xray/wintun.dll"]; + internal static void Run(Dictionary checks) + { + using var hive = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry32); + var fixtures = new List(); + (string Source, string Target) Fixture(bool existing = true) + { + var job = Path.Combine(Path.GetTempPath(), "ucvl-nsis-acceptance-" + Guid.NewGuid().ToString("N")); + var source = Path.Combine(job, "payload"); var target = Path.Combine(job, "installed"); + Directory.CreateDirectory(Path.Combine(source, "xray")); Directory.CreateDirectory(Path.Combine(target, "xray")); + Directory.CreateDirectory(Path.Combine(job, "integration")); fixtures.Add(target); + foreach (var file in Files) + { + File.WriteAllText(Path.Combine(source, file), "new " + file); + if (existing) File.WriteAllText(Path.Combine(target, file), "old " + file); + } + File.WriteAllText(Path.Combine(target, "synthetic-settings.txt"), "preserve"); + File.WriteAllText(Path.Combine(source, "install-manifest.json"), JsonSerializer.Serialize(Files.Select(f => + new InstallationTransaction.PayloadFile(f, InstallationTransaction.Digest(Path.Combine(source, f)))))); + var names = new[] { "Uninstall.exe", "Desktop.lnk", "StartMenu.lnk" }; + for (var i = 0; i < 3; i++) + { + File.WriteAllText(Path.Combine(job, "integration", names[i]), "new component " + i); + if (!existing) continue; + var dest = InstallationIntegration.Destination(target, true, i); + Directory.CreateDirectory(Path.GetDirectoryName(dest)!); File.WriteAllText(dest, "old component " + i); + } + if (existing) + { + using var app = hive.CreateSubKey(InstallationIntegration.Key(target, true, 0)); + app.SetValue("Path", target); app.SetValue("", Path.Combine(target, "VPNPlus.exe")); + app.SetValue("fixture-sentinel", "keep"); + using var uninstall = hive.CreateSubKey(InstallationIntegration.Key(target, true, 1)); + uninstall.SetValue("DisplayVersion", "old version"); + uninstall.SetValue("Publisher", "%fixture%", RegistryValueKind.ExpandString); + uninstall.SetValue("NoModify", new byte[] { 1, 2, 3 }, RegistryValueKind.Binary); + uninstall.SetValue("NoRepair", 4294967297L, RegistryValueKind.QWord); + } + return (source, target); + } + void Assert(string name, bool passed) { checks[name] = passed; if (!passed) throw new IOException("Integration fixture failed: " + name); } + bool Fails(Action work) { try { work(); return false; } catch (IOException) { return true; } } + string Snapshot(string target) + { + var snapshot = new SortedDictionary(); + foreach (var file in Files.Append("synthetic-settings.txt")) snapshot[file] = File.Exists(Path.Combine(target, file)) + ? InstallationTransaction.Digest(Path.Combine(target, file)) : null; + for (var i = 0; i < 3; i++) + { + var file = InstallationIntegration.Destination(target, true, i); + snapshot["component-" + i] = File.Exists(file) ? InstallationTransaction.Digest(file) : null; + } + for (var i = 0; i < 2; i++) + { + using var key = hive.OpenSubKey(InstallationIntegration.Key(target, true, i)); + snapshot["key-" + i] = key is null ? null : "exists"; + if (key is not null) foreach (var name in key.GetValueNames().Order(StringComparer.Ordinal)) + snapshot[$"key-{i}-{name}"] = key.GetValueKind(name) + ":" + JsonSerializer.Serialize(key.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames)); + } + return JsonSerializer.Serialize(snapshot); + } + try + { + for (var index = 0; index < 13; index++) + { + var fixture = Fixture(); var before = Snapshot(fixture.Target); + Assert("integration_rollback_after_component_or_registry_write_" + index, + Fails(() => InstallationTransaction.Apply(fixture.Source, fixture.Target, integrated: true, isolated: true, + afterIntegrationWrite: i => { if (i == index) throw new IOException("synthetic integration failure"); })) + && Snapshot(fixture.Target) == before); + } + var interrupted = Fixture(); var interruptedBefore = Snapshot(interrupted.Target); + Assert("integration_interruption_before_commit_injected", Fails(() => InstallationTransaction.Apply(interrupted.Source, + interrupted.Target, integrated: true, isolated: true, recoverOnFailure: false, + afterIntegrationWrite: i => { if (i == 12) throw new IOException("synthetic process interruption"); }))); + Assert("integration_pending_install_refuses_client_network_start", Fails(() => InstallationTransaction.ValidateClientLaunch(interrupted.Target))); + InstallationTransaction.Recover(interrupted.Target, isolated: true); + Assert("integration_restart_recovery_restores_files_shortcuts_and_typed_registry", Snapshot(interrupted.Target) == interruptedBefore); + InstallationTransaction.Recover(interrupted.Target, isolated: true); + Assert("integration_recovery_idempotent", Snapshot(interrupted.Target) == interruptedBefore); + InstallationTransaction.ValidateClientLaunch(interrupted.Target); + Assert("integration_rolled_back_install_allows_client_start", true); + var fresh = Fixture(existing: false); var freshBefore = Snapshot(fresh.Target); + Assert("integration_failed_first_install_removes_only_its_new_entries", Fails(() => InstallationTransaction.Apply(fresh.Source, + fresh.Target, integrated: true, isolated: true, afterIntegrationWrite: i => { if (i == 12) throw new IOException("failure"); })) + && Snapshot(fresh.Target) == freshBefore); + var locked = Fixture(); var lockedBefore = Snapshot(locked.Target); + using (var handle = File.Open(InstallationIntegration.Destination(locked.Target, true, 0), FileMode.Open, FileAccess.Read, FileShare.Read)) + Assert("integration_locked_uninstaller_rolls_back_entire_payload", Fails(() => InstallationTransaction.Apply(locked.Source, + locked.Target, integrated: true, isolated: true)) && Snapshot(locked.Target) == lockedBefore); + var missing = Fixture(); var missingBefore = Snapshot(missing.Target); + File.Delete(Path.Combine(Path.GetDirectoryName(missing.Source)!, "integration", "Desktop.lnk")); + Assert("integration_missing_staged_component_rejected_before_payload", Fails(() => InstallationTransaction.Apply(missing.Source, + missing.Target, integrated: true, isolated: true)) && Snapshot(missing.Target) == missingBefore); + var success = Fixture(); + InstallationTransaction.Apply(success.Source, success.Target, integrated: true, isolated: true); + var committed = Snapshot(success.Target); InstallationTransaction.Recover(success.Target, isolated: true); + InstallationTransaction.ValidateClientLaunch(success.Target); + Assert("integration_committed_install_allows_client_start", true); + Assert("integration_success_commits_payload_and_all_metadata", Files.All(f => File.ReadAllText(Path.Combine(success.Target, f)) == "new " + f) + && Enumerable.Range(0, 3).All(i => File.ReadAllText(InstallationIntegration.Destination(success.Target, true, i)) == "new component " + i) + && Snapshot(success.Target) == committed); + using (var key = hive.OpenSubKey(InstallationIntegration.Key(success.Target, true, 0))) + Assert("integration_preserves_unowned_registry_values", (string?)key!.GetValue("fixture-sentinel") == "keep"); + var changed = Fixture(); + Fails(() => InstallationTransaction.Apply(changed.Source, changed.Target, integrated: true, isolated: true, + recoverOnFailure: false, afterIntegrationWrite: i => { if (i == 12) throw new IOException("interrupted"); })); + using (var key = hive.OpenSubKey(InstallationIntegration.Key(changed.Target, true, 1), true)) key!.SetValue("Publisher", "external change"); + var external = Snapshot(changed.Target); + Assert("integration_recovery_refuses_external_metadata_changes", Fails(() => InstallationTransaction.Recover(changed.Target, isolated: true)) + && Snapshot(changed.Target) == external); + var conflict = Fixture(); + using (var key = hive.OpenSubKey(InstallationIntegration.Key(conflict.Target, true, 0), true)) key!.SetValue("Path", Path.GetTempPath()); + var conflictBefore = Snapshot(conflict.Target); + Assert("integration_refuses_other_registered_directory", Fails(() => InstallationTransaction.Apply(conflict.Source, + conflict.Target, integrated: true, isolated: true)) && Snapshot(conflict.Target) == conflictBefore); + var scope = Fixture(); + Fails(() => InstallationTransaction.Apply(scope.Source, scope.Target, integrated: true, isolated: true, + recoverOnFailure: false, afterIntegrationWrite: i => { if (i == 0) throw new IOException("interrupted"); })); + var scopeBefore = Snapshot(scope.Target); + Assert("integration_production_recovery_refuses_isolated_journal", Fails(() => InstallationTransaction.Recover(scope.Target)) + && Snapshot(scope.Target) == scopeBefore); + var journalPath = Path.Combine(scope.Target, ".ucvl-installer", "journal.json"); + var journal = JsonSerializer.Deserialize(File.ReadAllText(journalPath))!; + File.WriteAllText(journalPath, JsonSerializer.Serialize(journal with { Integration = journal.Integration! with { Isolated = false } })); + Assert("integration_isolated_recovery_refuses_production_scope_tampering", InstallationTransaction.RecoverIsolated(scope.Target) == 22 + && Snapshot(scope.Target) == scopeBefore); + } + finally + { + // These exact generated GUID leaves belong solely to this run. Never + // delete the shared test namespace or any production registration. + foreach (var target in fixtures) + { + for (var i = 0; i < 2; i++) + { + var path = InstallationIntegration.Key(target, true, i); + using (var key = hive.OpenSubKey(path, true)) + if (key is not null) foreach (var name in key.GetValueNames()) key.DeleteValue(name); + hive.DeleteSubKey(path, false); + } + hive.DeleteSubKey(Path.GetDirectoryName(InstallationIntegration.Key(target, true, 0))!, false); + } + } + } +} diff --git a/windows/InstallationPackageSelfTest.cs b/windows/InstallationPackageSelfTest.cs new file mode 100644 index 0000000..e7f13ac --- /dev/null +++ b/windows/InstallationPackageSelfTest.cs @@ -0,0 +1,98 @@ +using System.Diagnostics; +using System.Security.Cryptography; +using System.Text.Json; + +namespace UCVL.VPNPlus; + +// Integration with real release files, but exclusively fresh temporary targets. +// Does not run NSIS, stop the live app, alter registry/shortcuts or use AppPaths. +internal static class InstallationPackageSelfTest +{ + internal static int Run(string oldPayload) + { + var source = AppContext.BaseDirectory; + var folder = Path.Combine(Path.GetTempPath(), "ucvl-real-payload-test-" + Guid.NewGuid().ToString("N")); + var checks = new Dictionary(); + var report = new Dictionary { + ["time"] = DateTimeOffset.Now, ["temporary_directory"] = folder, + ["live_installation_modified"] = false, ["network_modified"] = false, + ["nsis_ui_tested"] = false, ["checks"] = checks, + }; + try + { + var files = JsonSerializer.Deserialize>( + File.ReadAllText(Path.Combine(source, "install-manifest.json")))!; + if (files.Count == 0 || !File.Exists(Path.Combine(oldPayload, "VPNPlus.exe"))) + throw new IOException("Missing complete old release fixture."); + // Validate before any use of manifest paths. This only reads the candidate. + if (InstallationTransaction.Run("", verifyOnly: true) != 0) throw new IOException("Candidate verification failed."); + Directory.CreateDirectory(folder); + string Seed(string name) + { + var target = Path.Combine(folder, name); + Directory.CreateDirectory(target); + foreach (var item in files) + { + var previous = Path.Combine(oldPayload, item.Path); + if (!File.Exists(previous)) continue; + var destination = Path.Combine(target, item.Path); + Directory.CreateDirectory(Path.GetDirectoryName(destination)!); + File.Copy(previous, destination); + } + File.WriteAllText(Path.Combine(target, "user-settings.fixture"), "unchanged synthetic settings"); + return target; + } + void Assert(string name, bool value) + { + checks[name] = value; + if (!value) throw new IOException("Real payload check failed: " + name); + } + string Hash(string file) => Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(file))); + bool Original(string target) => files.All(item => { + var previous = Path.Combine(oldPayload, item.Path); + var destination = Path.Combine(target, item.Path); + return File.Exists(previous) ? File.Exists(destination) && Hash(previous) == Hash(destination) : !File.Exists(destination); + }); + bool Rejected(Action operation) + { + try { operation(); return false; } + catch (IOException) { return true; } + } + + var success = Seed("upgrade"); + InstallationTransaction.Apply(source, success, _ => + Assert("exe_path_always_present", File.Exists(Path.Combine(success, "VPNPlus.exe")))); + Assert("all_candidate_hashes_match", files.All(item => Hash(Path.Combine(success, item.Path)) == item.Sha256)); + Assert("synthetic_configuration_preserved", File.ReadAllText(Path.Combine(success, "user-settings.fixture")) == "unchanged synthetic settings"); + using (var child = Process.Start(new ProcessStartInfo { + FileName = Path.Combine(success, "VPNPlus.exe"), Arguments = "--startup-self-test", + WorkingDirectory = success, UseShellExecute = false, CreateNoWindow = true, + }) ?? throw new IOException("Installed fixture could not start.")) + { + if (!child.WaitForExit(30_000)) { child.Kill(); throw new IOException("Startup check timed out."); } + Assert("copied_application_startup_self_test", child.ExitCode == 0); + } + + var locked = Seed("locked-dependency"); + using (var handle = new FileStream(Path.Combine(locked, "xray", "xray.exe"), FileMode.Open, FileAccess.Read, FileShare.Read)) + Assert("locked_real_dependency_rolls_back_all_files", Rejected(() => InstallationTransaction.Apply(source, locked)) && Original(locked)); + + var interrupted = Seed("interrupted-after-main"); + Assert("interruption_after_final_replacement_recorded", Rejected(() => InstallationTransaction.Apply(source, interrupted, + index => { if (index == files.Count - 1) throw new IOException("Synthetic interruption after final replacement"); }, + recoverOnFailure: false))); + InstallationTransaction.Recover(interrupted); + Assert("full_old_payload_restored_after_interruption", Original(interrupted)); + InstallationTransaction.Recover(interrupted); + Assert("full_payload_recovery_is_idempotent", Original(interrupted)); + report["passed"] = true; + return 0; + } + catch (Exception error) { report["passed"] = false; report["error"] = error.ToString(); return 23; } + finally + { + File.WriteAllText(Path.Combine(source, "installation-package-self-test.json"), + JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true })); + } + } +} diff --git a/windows/InstallationRemoval.cs b/windows/InstallationRemoval.cs new file mode 100644 index 0000000..ccef92c --- /dev/null +++ b/windows/InstallationRemoval.cs @@ -0,0 +1,161 @@ +using System.Text.Json; + +namespace UCVL.VPNPlus; + +// Explicit uninstall only. Program files are backed up, never a recursive tree +// deletion. Both installation-directory extras and separate AppData are kept. +internal static class InstallationRemoval +{ + internal record RemovalJournal(string InstallId, string BackupId, string State, + List Files); + private const string JournalName = "uninstall-journal.json"; + private static readonly HashSet KnownFiles = new(StringComparer.Ordinal) { + "VPNPlus.exe", "README.md", "THIRD_PARTY_NOTICES.md", + "assets/company-logo-original.png", "assets/zonghengjia-app-logo-v1.png", "assets/zonghengjia-app-v1.ico", + "xray/xray.exe", "xray/wintun.dll", "xray/geoip.dat", "xray/geosite.dat", + "licenses/NSIS-COPYING.txt", "licenses/Wintun-License.txt", "licenses/Xray-MPL-2.0.txt", + }; + private static string Metadata(string target) => Path.Combine(target, ".ucvl-installer"); + private static T Read(string path) + { + InstallationTransaction.NoLinks(path); + if (new FileInfo(path).Length > 2 * 1024 * 1024) throw new IOException("安装所有权记录过大。"); + return JsonSerializer.Deserialize(File.ReadAllText(path)) ?? throw new IOException("安装所有权记录无效。"); + } + private static void Save(string metadata, RemovalJournal journal) + { + var temporary = Path.Combine(metadata, "uninstall-" + Guid.NewGuid().ToString("N") + ".tmp"); + try { + File.WriteAllText(temporary, JsonSerializer.Serialize(journal)); + InstallationTransaction.Replace(temporary, Path.Combine(metadata, JournalName)); + } finally { if (File.Exists(temporary)) File.Delete(temporary); } + } + private static void ValidateFiles(List files) + { + if (files.Count is 0 or > 13 || files.Select(f => f.Path).Distinct(StringComparer.OrdinalIgnoreCase).Count() != files.Count + || !files.Any(f => f.Path == "VPNPlus.exe") || !files.Any(f => f.Path == "xray/xray.exe") + || !files.Any(f => f.Path == "xray/wintun.dll") + || files.Any(f => !KnownFiles.Contains(f.Path) || f.Sha256 is null || f.Sha256.Length != 64 || f.Sha256.Any(c => !Uri.IsHexDigit(c)))) + throw new IOException("卸载记录包含未知文件或无效校验值,未删除文件。"); + } + private static InstallationTransaction.Journal Ownership(string target, string? helperDigest = null) + { + target = InstallationTransaction.Root(target); + var metadata = Metadata(target); + var installed = Read(Path.Combine(metadata, "journal.json")); + if (installed.State != "committed" || !Guid.TryParseExact(installed.BackupId,"N",out _)) + throw new IOException("安装事务尚未完成,先修复安装,不执行卸载。"); + var files=installed.Files.Select(f => new InstallationTransaction.PayloadFile(f.Path,f.Sha256)).ToList(); + ValidateFiles(files); + foreach (var file in files) _ = InstallationTransaction.Resolve(target,file.Path); + if (helperDigest is not null && !string.Equals(files.Single(f => f.Path == "VPNPlus.exe").Sha256,helperDigest,StringComparison.OrdinalIgnoreCase)) + throw new IOException("卸载器版本与当前安装不一致,请使用当前版本卸载器。"); + return installed; + } + private static RemovalJournal? Existing(string target, string installId) + { + var path=Path.Combine(Metadata(target),JournalName); + if (!File.Exists(path)) return null; + var journal=Read(path); + if (!Guid.TryParseExact(journal.InstallId,"N",out _) || !Guid.TryParseExact(journal.BackupId,"N",out _) + || journal.State is not ("pending" or "removed" or "rolled-back")) throw new IOException("卸载恢复记录无效。"); + ValidateFiles(journal.Files); + if (journal.InstallId != installId) { + if (journal.State == "pending") throw new IOException("另一个安装的卸载恢复未完成。"); + return null; // A completed old removal does not apply to a later reinstall. + } + var expected=Ownership(target).Files.ToDictionary(f=>f.Path,f=>f.Sha256,StringComparer.Ordinal); + if (journal.Files.Count != expected.Count || journal.Files.Any(f=>!expected.TryGetValue(f.Path,out var digest) + || !string.Equals(digest,f.Sha256,StringComparison.OrdinalIgnoreCase))) + throw new IOException("卸载恢复记录与安装所有权不一致,未修改文件。"); + return journal; + } + internal static void Check(string target, string? helperDigest = null) + { + target=InstallationTransaction.Root(target); + var installed=Ownership(target,helperDigest); + var journal=Existing(target,installed.BackupId); + if (journal?.State == "removed") { + if (installed.Files.Any(f=>File.Exists(InstallationTransaction.Resolve(target,f.Path)))) + throw new IOException("已卸载目录又出现程序文件,请先重新安装以更新所有权记录。"); + return; + } + foreach (var file in installed.Files) + if (!(journal?.State == "pending" && !File.Exists(InstallationTransaction.Resolve(target,file.Path))) + && !InstallationTransaction.Matches(InstallationTransaction.Resolve(target,file.Path),file.Sha256)) + throw new IOException("程序文件缺失或被修改,保留目录,请先修复安装:"+file.Path); + } + internal static void RecoverIfPending(string target) + { + var metadata=Metadata(InstallationTransaction.Root(target)); + if (!File.Exists(Path.Combine(metadata,JournalName))) return; + // An old completed removal must not prevent the installer's own pending + // transaction from recovering after a later interrupted reinstall. + var stored=Read(Path.Combine(metadata,JournalName)); + if (stored.State is "removed" or "rolled-back") return; + var installed=Ownership(target); + var journal=Existing(target,installed.BackupId); + if (journal?.State != "pending") return; + var backup=Path.Combine(metadata,"uninstall-"+journal.BackupId); + foreach (var file in journal.Files) { + var destination=InstallationTransaction.Resolve(target,file.Path); + if (File.Exists(destination) && !InstallationTransaction.Matches(destination,file.Sha256)) + throw new IOException("卸载期间文件被其它程序修改,备份保留:"+file.Path); + if (!InstallationTransaction.Matches(InstallationTransaction.Resolve(backup,file.Path),file.Sha256)) + throw new IOException("卸载恢复备份校验失败:"+file.Path); + } + foreach (var file in journal.Files) + if (!File.Exists(InstallationTransaction.Resolve(target,file.Path))) + InstallationTransaction.Replace(InstallationTransaction.Resolve(backup,file.Path),InstallationTransaction.Resolve(target,file.Path)); + Save(metadata,journal with {State="rolled-back"}); + } + internal static void Remove(string target, string? helperDigest = null, Action? afterDelete = null, bool recoverOnFailure = true) + { + target=InstallationTransaction.Root(target); + var installed=Ownership(target,helperDigest); + var metadata=Metadata(target); + using var transactionLock=new FileStream(Path.Combine(metadata,"install.lock"),FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.None); + RecoverIfPending(target); + if (Existing(target,installed.BackupId)?.State == "removed") return; + Check(target,helperDigest); // Validate all owned files before modifying any. + var files=installed.Files.Select(f=>new InstallationTransaction.PayloadFile(f.Path,f.Sha256)) + .OrderBy(f=>f.Path=="VPNPlus.exe"?1:0).ThenBy(f=>f.Path,StringComparer.Ordinal).ToList(); + var id=Guid.NewGuid().ToString("N"); + var backup=Path.Combine(metadata,"uninstall-"+id); + foreach(var file in files) { + var copy=InstallationTransaction.Resolve(backup,file.Path); + Directory.CreateDirectory(Path.GetDirectoryName(copy)!); + File.Copy(InstallationTransaction.Resolve(target,file.Path),copy); + if(!InstallationTransaction.Matches(copy,file.Sha256)) throw new IOException("卸载备份校验失败。"); + } + var journal=new RemovalJournal(installed.BackupId,id,"pending",files); + Save(metadata,journal); + try { + for(var i=0;i(); + var files=new[]{"VPNPlus.exe","xray/xray.exe","xray/wintun.dll","README.md"}; + var report=new Dictionary{["kind"]="isolated_recoverable_uninstall",["fixture_directory"]=root, + ["live_installation_changed"]=false,["network_changed"]=false,["checks"]=checks,["passed"]=false}; + (string Source,string Target) Fixture(string name) { + var source=Path.Combine(root,name,"payload"); var target=Path.Combine(root,name,"installed"); + Directory.CreateDirectory(Path.Combine(source,"xray")); + foreach(var file in files) File.WriteAllText(Path.Combine(source,file),"owned fixture "+file); + File.WriteAllText(Path.Combine(source,"install-manifest.json"),JsonSerializer.Serialize(files.Select(f=> + new InstallationTransaction.PayloadFile(f,Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(Path.Combine(source,f)))))))); + InstallationTransaction.Apply(source,target); + File.WriteAllText(Path.Combine(target,"session.bin"),"synthetic session"); + File.WriteAllText(Path.Combine(target,"xray","personal.txt"),"unrelated file"); + return(source,target); + } + bool Intact(string target)=>files.All(f=>File.Exists(Path.Combine(target,f)) && File.ReadAllText(Path.Combine(target,f))=="owned fixture "+f); + bool Extras(string target)=>File.ReadAllText(Path.Combine(target,"session.bin"))=="synthetic session" + && File.ReadAllText(Path.Combine(target,"xray","personal.txt"))=="unrelated file"; + bool Fails(Action action){try{action();return false;}catch(IOException){return true;}} + void Assert(string name,bool value){checks[name]=value;if(!value)throw new IOException("Removal fixture failed: "+name);} + try { + var success=Fixture("success"); + InstallationRemoval.Remove(success.Target); + Assert("only_recorded_program_files_removed",files.All(f=>!File.Exists(Path.Combine(success.Target,f))) && Extras(success.Target)); + var saved=JsonSerializer.Deserialize(File.ReadAllText(Path.Combine(success.Target,".ucvl-installer","uninstall-journal.json")))!; + Assert("complete_recovery_backup_retained",saved.State=="removed" && Intact(Path.Combine(success.Target,".ucvl-installer","uninstall-"+saved.BackupId))); + InstallationRemoval.Remove(success.Target); + Assert("removal_is_idempotent",Extras(success.Target)); + InstallationTransaction.Apply(success.Source,success.Target); + Assert("reinstall_after_removal",Intact(success.Target)&&Extras(success.Target)); + InstallationRemoval.Remove(success.Target); + Assert("old_removal_does_not_skip_new_install",files.All(f=>!File.Exists(Path.Combine(success.Target,f)))&&Extras(success.Target)); + Assert("interrupted_reinstall_injected",Fails(()=>InstallationTransaction.Apply(success.Source,success.Target, + i=>{if(i==1)throw new IOException("synthetic interrupted reinstall");},recoverOnFailure:false))); + InstallationTransaction.Apply(success.Source,success.Target); + Assert("completed_old_removal_does_not_block_install_recovery",Intact(success.Target)&&Extras(success.Target)); + for(var index=0;index<4;index++){ + var fault=Fixture("fault-"+index); + Assert("rollback_after_deletion_"+index,Fails(()=>InstallationRemoval.Remove(fault.Target,afterDelete:i=>{ + if(i==index)throw new IOException("synthetic failure");}))&&Intact(fault.Target)&&Extras(fault.Target)); + } + var locked=Fixture("locked-main"); + using(var handle=new FileStream(Path.Combine(locked.Target,"VPNPlus.exe"),FileMode.Open,FileAccess.Read,FileShare.Read)) + Assert("locked_main_restores_already_removed_dependencies",Fails(()=>InstallationRemoval.Remove(locked.Target))&&Intact(locked.Target)&&Extras(locked.Target)); + var interrupted=Fixture("interrupted"); + Assert("interruption_after_main_recorded",Fails(()=>InstallationRemoval.Remove(interrupted.Target,afterDelete:i=>{ + if(i==3)throw new IOException("synthetic process interruption");},recoverOnFailure:false))); + InstallationRemoval.RecoverIfPending(interrupted.Target); + Assert("interrupted_removal_recovers_all_files",Intact(interrupted.Target)&&Extras(interrupted.Target)); + InstallationRemoval.RecoverIfPending(interrupted.Target); + Assert("recovery_is_idempotent",Intact(interrupted.Target)); + var reinstall=Fixture("reinstall-during-interruption"); + Fails(()=>InstallationRemoval.Remove(reinstall.Target,afterDelete:i=>{if(i==0)throw new IOException("interrupted");},recoverOnFailure:false)); + InstallationTransaction.Apply(reinstall.Source,reinstall.Target); + Assert("installer_recovers_pending_removal_first",Intact(reinstall.Target)&&Extras(reinstall.Target)); + var changed=Fixture("modified-file"); + File.WriteAllText(Path.Combine(changed.Target,"README.md"),"user edited"); + Assert("modified_program_file_rejected_before_deletion",Fails(()=>InstallationRemoval.Remove(changed.Target)) + && File.ReadAllText(Path.Combine(changed.Target,"README.md"))=="user edited" && File.Exists(Path.Combine(changed.Target,"VPNPlus.exe"))&&Extras(changed.Target)); + var unknown=Fixture("unknown-file"); + var path=Path.Combine(unknown.Target,".ucvl-installer","journal.json"); + File.WriteAllText(path,File.ReadAllText(path).Replace("README.md","xray/personal.txt")); + Assert("unknown_owned_path_rejected",Fails(()=>InstallationRemoval.Remove(unknown.Target))&&Intact(unknown.Target)&&Extras(unknown.Target)); + var foreign=Fixture("foreign-helper"); + Assert("mismatched_uninstaller_version_rejected",Fails(()=>InstallationRemoval.Check(foreign.Target,new string('0',64)))&&Intact(foreign.Target)); + Assert("missing_ownership_rejected",Fails(()=>InstallationRemoval.Remove(root))); + Assert("volume_root_rejected",Fails(()=>InstallationRemoval.Remove(Path.GetPathRoot(root)!))); + var external=Fixture("external-change-during-recovery"); + Fails(()=>InstallationRemoval.Remove(external.Target,afterDelete:i=>{if(i==0)throw new IOException("interrupted");},recoverOnFailure:false)); + File.WriteAllText(Path.Combine(external.Target,"README.md"),"external change"); + Assert("recovery_preserves_external_changes",Fails(()=>InstallationRemoval.RecoverIfPending(external.Target)) + && File.ReadAllText(Path.Combine(external.Target,"README.md"))=="external change" && Extras(external.Target)); + var mismatch=Fixture("mismatched-removal-record"); + Fails(()=>InstallationRemoval.Remove(mismatch.Target,afterDelete:i=>{if(i==0)throw new IOException("interrupted");},recoverOnFailure:false)); + var journalPath=Path.Combine(mismatch.Target,".ucvl-installer","uninstall-journal.json"); + var tampered=JsonSerializer.Deserialize(File.ReadAllText(journalPath))!; + tampered.Files[0]=tampered.Files[0] with {Sha256=new string('0',64)}; + File.WriteAllText(journalPath,JsonSerializer.Serialize(tampered)); + Assert("mismatched_recovery_record_rejected",Fails(()=>InstallationRemoval.RecoverIfPending(mismatch.Target))&&Extras(mismatch.Target)); + var linkTarget=Fixture("link-destination"); + var link=Path.Combine(root,"installation-link"); + Directory.CreateSymbolicLink(link,linkTarget.Target); + Assert("linked_installation_rejected",Fails(()=>InstallationRemoval.Remove(link))&&Intact(linkTarget.Target)&&Extras(linkTarget.Target)); + report["passed"]=true; return 0; + } catch(Exception error){report["error"]=error.ToString();return 24;} + finally{File.WriteAllText(Path.Combine(AppContext.BaseDirectory,"uninstall-self-test.json"),JsonSerializer.Serialize(report,new JsonSerializerOptions{WriteIndented=true}));} + } +} diff --git a/windows/InstallationSelfTest.cs b/windows/InstallationSelfTest.cs new file mode 100644 index 0000000..80fe591 --- /dev/null +++ b/windows/InstallationSelfTest.cs @@ -0,0 +1,142 @@ +using System.Security.Cryptography; +using System.Text.Json; + +namespace UCVL.VPNPlus; + +internal static class InstallationSelfTest +{ + internal static int Run() + { + var root = Path.Combine(Path.GetTempPath(), "ucvl-install-fixture-" + Guid.NewGuid().ToString("N")); + var checks = new Dictionary(); + Directory.CreateDirectory(root); + (string Source, string Target) Fixture(string name) + { + var source = Path.Combine(root, name, "payload"); + var target = Path.Combine(root, name, "installed"); + Directory.CreateDirectory(Path.Combine(source, "xray")); + Directory.CreateDirectory(Path.Combine(target, "xray")); + foreach (var file in new[] { "VPNPlus.exe", "xray/xray.exe", "xray/wintun.dll", "README.md" }) + { + File.WriteAllText(Path.Combine(source, file), "new fixture " + file); + if (file != "README.md") File.WriteAllText(Path.Combine(target, file), "old fixture " + file); + } + // This is synthetic test data, not the user's actual saved login. + File.WriteAllText(Path.Combine(target, "session.bin"), "fixture session"); + File.WriteAllText(Path.Combine(target, "device-id.txt"), "fixture device"); + File.WriteAllText(Path.Combine(source, "install-manifest.json"), JsonSerializer.Serialize( + Directory.GetFiles(source, "*", SearchOption.AllDirectories).Select(f => + new InstallationTransaction.PayloadFile(Path.GetRelativePath(source, f).Replace('\\', '/'), + Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(f))))))); + return (source, target); + } + void Assert(string name, bool result) + { + checks[name] = result; + if (!result) throw new Exception("Fixture failed: " + name); + } + bool OldIntact(string target) => File.ReadAllText(Path.Combine(target, "VPNPlus.exe")) == "old fixture VPNPlus.exe" + && File.ReadAllText(Path.Combine(target, "xray", "xray.exe")) == "old fixture xray/xray.exe" + && File.ReadAllText(Path.Combine(target, "xray", "wintun.dll")) == "old fixture xray/wintun.dll" + && !File.Exists(Path.Combine(target, "README.md")); + bool Fails(Action action) + { + try { action(); return false; } + catch (IOException) { return true; } + } + var report = new Dictionary { + ["kind"] = "isolated_install_transaction_fault_injection", + ["real_installation_changed"] = false, ["network_changed"] = false, + ["fixture_directory"] = root, ["checks"] = checks, + }; + try + { + // Inspect the actual launch policy without starting PowerShell or changing DNS. + const string fixtureScript = "Write-Output 'synthetic launch fixture'"; + var powerShell = SystemPowerShell.CreateStartInfo(fixtureScript); + var systemDirectory = Environment.GetFolderPath(Environment.SpecialFolder.System); + Assert("powershell_uses_absolute_system_executable", Path.IsPathFullyQualified(powerShell.FileName) + && powerShell.FileName == Path.Combine(systemDirectory, "WindowsPowerShell", "v1.0", "powershell.exe")); + Assert("powershell_uses_existing_system_working_directory", powerShell.WorkingDirectory == systemDirectory + && Directory.Exists(powerShell.WorkingDirectory)); + var originalDirectory = Environment.CurrentDirectory; + try + { + Environment.CurrentDirectory = root; + Assert("powershell_does_not_inherit_current_directory", SystemPowerShell.CreateStartInfo(fixtureScript).WorkingDirectory == systemDirectory); + } + finally { Environment.CurrentDirectory = originalDirectory; } + const string prefix = "-NoProfile -NonInteractive -EncodedCommand "; + Assert("powershell_keeps_encoded_command_unchanged", powerShell.Arguments.StartsWith(prefix, StringComparison.Ordinal) + && System.Text.Encoding.Unicode.GetString(Convert.FromBase64String(powerShell.Arguments[prefix.Length..])) == fixtureScript); + Assert("powershell_has_no_shell_or_visible_window", !powerShell.UseShellExecute && powerShell.CreateNoWindow + && powerShell.WindowStyle == System.Diagnostics.ProcessWindowStyle.Hidden); + Assert("powershell_redirects_both_diagnostic_streams", powerShell.RedirectStandardOutput && powerShell.RedirectStandardError); + ReplacementContinuitySelfTest.Run(root, checks); + var isolated = Path.Combine(Path.GetTempPath(), "ucvl-nsis-acceptance-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(isolated); + var isolatedTarget = Path.Combine(isolated, "installed"); + Assert("isolated_nsis_target_allowed", InstallationTransaction.IsolatedTarget(isolatedTarget) == isolatedTarget.TrimEnd(Path.DirectorySeparatorChar)); + Assert("isolated_nsis_rejects_live_install", Fails(() => InstallationTransaction.IsolatedTarget( + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "UCVL", "VPNPlus")))); + Assert("isolated_nsis_rejects_temp_root", Fails(() => InstallationTransaction.IsolatedTarget(Path.GetTempPath()))); + Assert("isolated_nsis_rejects_nested_target", Fails(() => InstallationTransaction.IsolatedTarget(Path.Combine(isolatedTarget, "installed")))); + Assert("isolated_nsis_rejects_missing_job", Fails(() => InstallationTransaction.IsolatedTarget( + Path.Combine(Path.GetTempPath(), "ucvl-nsis-acceptance-" + Guid.NewGuid().ToString("N"), "installed")))); + Assert("isolated_nsis_rejects_invalid_identifier", Fails(() => InstallationTransaction.IsolatedTarget( + Path.Combine(Path.GetTempPath(), "ucvl-nsis-acceptance-not-a-guid", "installed")))); + var success = Fixture("success"); + InstallationTransaction.Apply(success.Source, success.Target, _ => + Assert("public_executable_never_missing", File.Exists(Path.Combine(success.Target, "VPNPlus.exe")))); + Assert("new_program_installed", File.ReadAllText(Path.Combine(success.Target, "VPNPlus.exe")) == "new fixture VPNPlus.exe"); + Assert("unlisted_configuration_preserved", File.ReadAllText(Path.Combine(success.Target, "session.bin")) == "fixture session" + && File.ReadAllText(Path.Combine(success.Target, "device-id.txt")) == "fixture device"); + + var bad = Fixture("bad-payload"); + File.AppendAllText(Path.Combine(bad.Source, "VPNPlus.exe"), "corrupted"); + Assert("corrupt_payload_rejected_before_write", Fails(() => InstallationTransaction.Apply(bad.Source, bad.Target)) && OldIntact(bad.Target)); + + for (var index = 0; index < 4; index++) + { + var fault = Fixture("fault-" + index); + Assert("rollback_after_write_" + index, Fails(() => InstallationTransaction.Apply(fault.Source, fault.Target, + i => { if (i == index) throw new IOException("simulated write failure"); })) && OldIntact(fault.Target)); + } + + var locked = Fixture("locked-main"); + using (var handle = new FileStream(Path.Combine(locked.Target, "VPNPlus.exe"), FileMode.Open, FileAccess.Read, FileShare.Read)) + Assert("locked_executable_rolls_back_dependencies", Fails(() => InstallationTransaction.Apply(locked.Source, locked.Target)) && OldIntact(locked.Target)); + + var interrupted = Fixture("interrupted"); + Assert("interruption_injected", Fails(() => InstallationTransaction.Apply(interrupted.Source, interrupted.Target, + i => { if (i == 1) throw new IOException("simulated interrupted installer"); }, recoverOnFailure: false))); + InstallationTransaction.Recover(interrupted.Target); + Assert("pending_journal_recovers", OldIntact(interrupted.Target)); + InstallationTransaction.Recover(interrupted.Target); + Assert("recovery_idempotent", OldIntact(interrupted.Target)); + InstallationTransaction.Apply(interrupted.Source, interrupted.Target); + Assert("upgrade_after_recovery", File.ReadAllText(Path.Combine(interrupted.Target, "VPNPlus.exe")) == "new fixture VPNPlus.exe"); + + var traversal = Fixture("traversal"); + var manifest = Path.Combine(traversal.Source, "install-manifest.json"); + File.WriteAllText(manifest, File.ReadAllText(manifest).Replace("README.md", "../README.md")); + Assert("traversal_rejected", Fails(() => InstallationTransaction.Apply(traversal.Source, traversal.Target)) && OldIntact(traversal.Target)); + + var modified = Fixture("external-change"); + Fails(() => InstallationTransaction.Apply(modified.Source, modified.Target, + i => { if (i == 0) throw new IOException("simulated interruption"); }, recoverOnFailure: false)); + File.WriteAllText(Path.Combine(modified.Target, "README.md"), "user changed this file after interruption"); + Assert("recovery_does_not_overwrite_external_change", Fails(() => InstallationTransaction.Recover(modified.Target)) + && File.ReadAllText(Path.Combine(modified.Target, "README.md")) == "user changed this file after interruption"); + InstallationIntegrationSelfTest.Run(checks); + report["passed"] = true; + return 0; + } + catch (Exception exception) { report["passed"] = false; report["error"] = exception.ToString(); return 21; } + finally + { + File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "installation-self-test.json"), + JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true })); + } + } +} diff --git a/windows/InstallationTransaction.cs b/windows/InstallationTransaction.cs new file mode 100644 index 0000000..4cb7a15 --- /dev/null +++ b/windows/InstallationTransaction.cs @@ -0,0 +1,320 @@ +using System.Security.Cryptography; +using System.Security.AccessControl; +using System.Runtime.InteropServices; +using System.Text.Json; + +namespace UCVL.VPNPlus; + +// Runs from the fully extracted installer payload, never from the live directory. +// Only manifest-listed program files are changed; AppPaths.DataDirectory is not used. +internal static class InstallationTransaction +{ + internal record PayloadFile(string Path, string Sha256); + internal record SavedFile(string Path, string Sha256, string? PreviousSha256); + internal record Journal(string BackupId, string State, List Files, + InstallationIntegration.Snapshot? Integration = null); + private const string Metadata = ".ucvl-installer"; + private const string Manifest = "install-manifest.json"; + + internal static void ValidateClientLaunch(string directory) + { + var metadata = System.IO.Path.Combine(Root(directory), Metadata); + foreach (var filename in new[] { "journal.json", "uninstall-journal.json" }) + { + var path = System.IO.Path.Combine(metadata, filename); + NoLinks(path); + if (!File.Exists(path)) continue; + if (new FileInfo(path).Length > 2 * 1024 * 1024) throw new IOException("安装恢复记录异常。"); + using var document = JsonDocument.Parse(File.ReadAllText(path)); + var state = document.RootElement.GetProperty("State").GetString(); + var complete = filename == "journal.json" ? state is "committed" or "rolled-back" + : state is "removed" or "rolled-back"; + if (!complete) + throw new IOException("上次安装或卸载尚未完成。请重新运行最新安装包恢复;不要卸载或删除程序目录。账号和配置仍保留。"); + } + } + + // The NSIS pipeline acceptance driver can only install inside one fresh + // temporary fixture. It never stops or takes the live client's mutex. + internal static string IsolatedTarget(string target) + { + var full = Root(target); + var job = System.IO.Path.GetDirectoryName(full)!; + var parent = System.IO.Path.GetDirectoryName(job); + const string prefix = "ucvl-nsis-acceptance-"; + var name = System.IO.Path.GetFileName(job); + if (!string.Equals(System.IO.Path.GetFileName(full), "installed", StringComparison.Ordinal) + || !string.Equals(parent, Root(System.IO.Path.GetTempPath()), StringComparison.OrdinalIgnoreCase) + || !name.StartsWith(prefix, StringComparison.Ordinal) + || !Guid.TryParseExact(name[prefix.Length..], "N", out _) + || !Directory.Exists(job)) + throw new IOException("隔离安装验收只允许已有临时任务的 installed 子目录。"); + return full; + } + + internal static int RunIsolated(string target, bool integrated = false, int? interruptAfter = null) + { + try { + if (interruptAfter is < 0 or > 12) throw new IOException("无效隔离故障注入位置。"); + Apply(AppContext.BaseDirectory, IsolatedTarget(target), integrated: integrated, isolated: true, + afterIntegrationWrite: interruptAfter is null ? null : i => { if (i == interruptAfter) Environment.Exit(42); }); + return 0; + } + catch (Exception error) + { + File.WriteAllText(System.IO.Path.Combine(AppContext.BaseDirectory, "install-error.txt"), error.ToString()); + return 20; + } + } + + internal static int RecoverIsolated(string target) + { + try { + target = IsolatedTarget(target); + using var guard = new FileStream(System.IO.Path.Combine(target, Metadata, "install.lock"), + FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); + Recover(target, isolated: true); ValidateClientLaunch(target); return 0; + } + catch { return 22; } + } + + internal static int Run(string target, bool verifyOnly, bool integrated = false) + { + try + { + if (verifyOnly) { ValidatePayload(AppContext.BaseDirectory); return 0; } + // Matches all supported old clients, so a running client blocks replacement. + using var client = new Mutex(false, "Local\\UCVL.VPNPlus.Client"); + bool acquired; + try { acquired = client.WaitOne(0); } + catch (AbandonedMutexException) { acquired = true; } + if (!acquired) throw new IOException("原程序仍在运行,未修改安装目录。"); + try { Apply(AppContext.BaseDirectory, target, integrated: integrated); } + finally { client.ReleaseMutex(); } + return 0; + } + catch (Exception exception) + { + // No session tokens, passwords, or network changes in this helper. + File.WriteAllText(System.IO.Path.Combine(AppContext.BaseDirectory, "install-error.txt"), + exception.ToString()); + // Do not relaunch a potentially mixed installation if rollback itself failed. + var pending = System.IO.Path.Combine(target, Metadata, "journal.json"); + try + { + if (!verifyOnly && File.Exists(pending) + && JsonSerializer.Deserialize(File.ReadAllText(pending))?.State == "pending") return 22; + } + catch { return 22; } + return 20; + } + } + + internal static string Root(string directory) + { + var root = System.IO.Path.TrimEndingDirectorySeparator(System.IO.Path.GetFullPath(directory)); + if (string.Equals(root, System.IO.Path.GetPathRoot(root), StringComparison.OrdinalIgnoreCase)) + throw new IOException("不能使用磁盘根目录作为安装目录。"); + NoLinks(root); + return root; + } + + internal static void NoLinks(string path) + { + for (var current = path; !string.IsNullOrEmpty(current); current = System.IO.Path.GetDirectoryName(current)) + if ((File.Exists(current) || Directory.Exists(current)) + && (File.GetAttributes(current) & FileAttributes.ReparsePoint) != 0) + throw new IOException("安装路径中不能包含链接或目录联接。"); + } + + internal static string Resolve(string root, string relative) + { + if (string.IsNullOrWhiteSpace(relative) || relative.Contains(':') || relative.Contains('\\') + || System.IO.Path.IsPathRooted(relative) + || relative.Split('/').Any(p => p is "" or "." or ".." || p.EndsWith(' ') || p.EndsWith('.'))) + throw new IOException("安装清单路径无效。"); + var allowed = relative is "VPNPlus.exe" or "README.md" or "THIRD_PARTY_NOTICES.md" + || relative.StartsWith("assets/", StringComparison.Ordinal) + || relative.StartsWith("xray/", StringComparison.Ordinal) + || relative.StartsWith("licenses/", StringComparison.Ordinal); + if (!allowed) throw new IOException("安装清单包含非程序文件。"); + var full = System.IO.Path.GetFullPath(System.IO.Path.Combine(root, relative)); + if (!full.StartsWith(root + System.IO.Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + throw new IOException("安装路径越界。"); + NoLinks(full); + return full; + } + + internal static string Digest(string path) + { + using var file = File.OpenRead(path); + return Convert.ToHexString(SHA256.HashData(file)); + } + + internal static bool Matches(string path, string? digest) => digest is null + ? !File.Exists(path) + : File.Exists(path) && string.Equals(Digest(path), digest, StringComparison.OrdinalIgnoreCase); + + private static List ValidatePayload(string source) + { + source = Root(source); + var files = JsonSerializer.Deserialize>(File.ReadAllText(System.IO.Path.Combine(source, Manifest))) + ?? throw new IOException("安装包缺少文件清单。"); + if (files.Count == 0 || files.Count > 10000 + || files.Select(f => f.Path).Distinct(StringComparer.OrdinalIgnoreCase).Count() != files.Count + || !files.Any(f => f.Path == "VPNPlus.exe") || !files.Any(f => f.Path == "xray/xray.exe") + || !files.Any(f => f.Path == "xray/wintun.dll")) + throw new IOException("安装清单不完整或存在重复文件。"); + foreach (var file in files) + if (file.Sha256 is null || file.Sha256.Length != 64 || !Matches(Resolve(source, file.Path), file.Sha256)) + throw new IOException("安装包文件校验失败:" + file.Path); + // Dependencies first. The public executable path is always present during an upgrade. + return files.OrderBy(f => f.Path == "VPNPlus.exe" ? 1 : 0).ThenBy(f => f.Path, StringComparer.Ordinal).ToList(); + } + + internal static void Replace(string source, string target) + { + NoLinks(target); + Directory.CreateDirectory(System.IO.Path.GetDirectoryName(target)!); + var temporary = target + ".update-" + Guid.NewGuid().ToString("N") + ".tmp"; + try + { + File.Copy(source, temporary); + // Preserve the installed file's owner/group/DACL before the rename. + // This is a program-file transaction, not a merge of old file data. + if (File.Exists(target)) + { + const AccessControlSections sections = AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group; + var security = new FileSecurity(); + security.SetSecurityDescriptorBinaryForm(new FileInfo(target).GetAccessControl(sections).GetSecurityDescriptorBinaryForm(), sections); + new FileInfo(temporary).SetAccessControl(security); + } + using (var flush = new FileStream(temporary, FileMode.Open, FileAccess.Write, FileShare.None)) flush.Flush(true); + // ReplaceFile can briefly remove the public name (and documents + // partial-failure states). Rename a flushed sibling instead, never + // deleting or moving the installed file out of the way first. + // https://learn.microsoft.com/windows/win32/api/winbase/nf-winbase-movefileexw + for (var attempt = 0; ; attempt++) + { + // No COPY_ALLOWED, DELAY_UNTIL_REBOOT or cross-volume fallback. + if (MoveFileExW(temporary, target, 0x1 | 0x8)) break; + var error = Marshal.GetLastWin32Error(); + if (attempt >= 24 || error is not (5 or 32 or 33) + || !File.Exists(temporary) || !File.Exists(target)) + throw new IOException("程序文件重命名失败,保留原安装并执行事务恢复。", + new System.ComponentModel.Win32Exception(error)); + Thread.Sleep(20); // Bounded antivirus/share contention; never retry by deleting the target. + } + } + finally { if (File.Exists(temporary)) File.Delete(temporary); } + } + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool MoveFileExW(string existing, string destination, uint flags); + + private static void Save(string metadata, Journal journal) + { + var temporary = System.IO.Path.Combine(metadata, "journal-" + Guid.NewGuid().ToString("N") + ".tmp"); + try + { + File.WriteAllText(temporary, JsonSerializer.Serialize(journal)); + Replace(temporary, System.IO.Path.Combine(metadata, "journal.json")); + } + finally { if (File.Exists(temporary)) File.Delete(temporary); } + } + + internal static void Recover(string target, bool isolated = false) + { + target = Root(target); + var metadata = System.IO.Path.Combine(target, Metadata); + NoLinks(metadata); + var path = System.IO.Path.Combine(metadata, "journal.json"); + if (!File.Exists(path)) return; + var journal = JsonSerializer.Deserialize(File.ReadAllText(path)) ?? throw new IOException("恢复记录无效。"); + if (journal.State is "committed" or "rolled-back") return; + if (journal.State != "pending" || !Guid.TryParseExact(journal.BackupId, "N", out _)) + throw new IOException("恢复记录状态无效。"); + if (journal.Integration is not null && journal.Integration.Isolated != isolated) + throw new IOException("安装恢复记录的生产/隔离作用域不匹配,未修改文件或登记。"); + var backup = System.IO.Path.Combine(metadata, journal.BackupId); + // Validate every backup and destination before changing any of them. + foreach (var file in journal.Files) + { + var destination = Resolve(target, file.Path); + if (!Matches(destination, file.PreviousSha256) && !Matches(destination, file.Sha256)) + throw new IOException("检测到安装文件被其它程序改变,备份已保留:" + file.Path); + if (file.PreviousSha256 is not null && !Matches(Resolve(backup, file.Path), file.PreviousSha256)) + throw new IOException("恢复备份校验失败:" + file.Path); + } + if (journal.Integration is not null) + InstallationIntegration.Recover(target, backup, journal.Integration); + foreach (var file in journal.Files.AsEnumerable().Reverse()) + { + var destination = Resolve(target, file.Path); + if (Matches(destination, file.PreviousSha256)) continue; + if (file.PreviousSha256 is null) File.Delete(destination); // Exact manifest file, never a directory. + else Replace(Resolve(backup, file.Path), destination); + } + Save(metadata, journal with { State = "rolled-back" }); + } + + internal static void Apply(string source, string target, Action? afterWrite = null, bool recoverOnFailure = true, + bool integrated = false, bool isolated = false, Action? afterIntegrationWrite = null) + { + source = Root(source); target = Root(target); + if (string.Equals(source, target, StringComparison.OrdinalIgnoreCase) + || source.StartsWith(target + "\\", StringComparison.OrdinalIgnoreCase) + || target.StartsWith(source + "\\", StringComparison.OrdinalIgnoreCase)) + throw new IOException("临时安装包与正式目录必须分开。"); + var files = ValidatePayload(source); // Fail before touching the installed files. + Directory.CreateDirectory(target); + var metadata = System.IO.Path.Combine(target, Metadata); + NoLinks(metadata); + Directory.CreateDirectory(metadata); + // Excludes installers in other Windows sessions too. + using var transactionLock = new FileStream(System.IO.Path.Combine(metadata, "install.lock"), + FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); + InstallationRemoval.RecoverIfPending(target); + Recover(target, isolated); + var id = Guid.NewGuid().ToString("N"); + var backup = System.IO.Path.Combine(metadata, id); + var saved = new List(); + foreach (var file in files) + { + var destination = Resolve(target, file.Path); + var digest = File.Exists(destination) ? Digest(destination) : null; + if (digest is not null) + { + var copy = Resolve(backup, file.Path); + Directory.CreateDirectory(System.IO.Path.GetDirectoryName(copy)!); + File.Copy(destination, copy); + if (!Matches(copy, digest)) throw new IOException("旧版本备份校验失败。"); + } + saved.Add(new SavedFile(file.Path, file.Sha256, digest)); + } + var stage = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(source)!, "integration"); + var integration = integrated ? InstallationIntegration.Prepare(stage, target, backup, isolated, Application.ProductVersion) : null; + var journal = new Journal(id, "pending", saved, integration); + Save(metadata, journal); + try + { + for (var i = 0; i < files.Count; i++) + { + var file = files[i]; + var destination = Resolve(target, file.Path); + if (!Matches(destination, saved[i].PreviousSha256)) throw new IOException("安装文件在备份后发生改变。"); + Replace(Resolve(source, file.Path), destination); + if (!Matches(destination, file.Sha256)) throw new IOException("安装后校验失败:" + file.Path); + afterWrite?.Invoke(i); // Isolated fault injection only; never provided by the installer. + } + if (integration is not null) InstallationIntegration.Apply(stage, target, integration, afterIntegrationWrite); + Save(metadata, journal with { State = "committed" }); + } + catch + { + if (recoverOnFailure) Recover(target, isolated); + throw; + } + } +} diff --git a/windows/InstallerGuardianGate.cs b/windows/InstallerGuardianGate.cs new file mode 100644 index 0000000..2992376 --- /dev/null +++ b/windows/InstallerGuardianGate.cs @@ -0,0 +1,289 @@ +using System.Diagnostics; +using System.IO.Pipes; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Security.Principal; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.RegularExpressions; +using Microsoft.Win32.SafeHandles; + +namespace UCVL.VPNPlus; + +// Opt-in NSIS handoff only. No network/shutdown/restart code belongs here. +// The independent guardian owns recovery, containment and the durable baseline. +internal static class InstallerGuardianGate +{ + internal const int Invalid = 70, TimedOut = 71, IdentityMismatch = 72, + EvidenceMismatch = 73, ReleaseRefused = 74, Replay = 75; + internal record Identity(int Pid, long StartTicks, string Path, int SessionId, string UserSid, string Sha256); + internal record Request(int Schema, string Nonce, string TargetDirectory, string BaselineJobDirectory, + DateTimeOffset CreatedAtUtc, DateTimeOffset DeadlineUtc, Identity Guardian, Identity Installer); + internal record Payload(string Path, string Sha256); + internal record Component(int Id, string Sha256); + internal record Ready(int Schema, string Nonce, string RequestSha256, string TargetDirectory, + string BaselineJobDirectory, string PayloadDirectory, string PayloadManifestPath, string PayloadManifestSha256, + string ComponentsDirectory, string ComponentsManifestPath, string ComponentsManifestSha256, + Payload[] Payload, Component[] Components, Identity Installer, Identity Guardian, DateTimeOffset DeadlineUtc); + internal record Release(int Schema, string Nonce, string Permit, string RequestSha256, string ReadySha256, + string BaselineSha256, Identity Installer, Identity Guardian, DateTimeOffset ExpiresAtUtc); + internal record Accepted(string RequestSha256, string ReadySha256, string ReleaseSha256); + internal record PipeApproval(string Nonce, string RequestSha256, string ReadySha256, string ReleaseSha256); + private static readonly string[] ComponentNames = ["Uninstall.exe", "Desktop.lnk", "StartMenu.lnk"]; + private static readonly JsonSerializerOptions Json = new() { UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow }; + private sealed class GateError(int code, string message) : IOException(message) { internal int Code => code; } + private static void Require(bool condition, int code, string message) { if (!condition) throw new GateError(code, message); } + + internal static int Run(string target, string control, string nonce, string installerPid, bool apply, Action? diagnostic = null) + { + try + { + Require(int.TryParse(installerPid, out var pid) && pid > 0, Invalid, "Invalid installer PID."); + using var scope = new Scope(AppContext.BaseDirectory, target, control, nonce, pid); + if (!apply) return scope.Wait(); + // Recheck and pin the exact same staged bytes through the existing + // transaction. No second WriteUninstaller/CreateShortcut occurs. + return scope.Apply(() => InstallationTransaction.Run(target, verifyOnly: false, integrated: true)); + } + catch (GateError error) { diagnostic?.Invoke(error); return error.Code; } + catch (Exception error) { diagnostic?.Invoke(error); return Invalid; } // No target error file or client launch on refusal. + } + + internal static string Plain(string path) + { + Require(!string.IsNullOrWhiteSpace(path) && Regex.IsMatch(path, @"^[A-Za-z]:\\") + && !path[2..].Contains(':') && !path.Contains('/') && !path.Contains('"') + && !path.Any(char.IsControl), Invalid, "A canonical local path is required."); + var full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(path)); + Require(string.Equals(full, path, StringComparison.Ordinal) && full.Length > 3 + && path[3..].Split('\\').All(p => p.Length > 0 && p is not "." and not ".." && !p.EndsWith('.') && !p.EndsWith(' ')), + Invalid, "Noncanonical gate path."); + InstallationTransaction.NoLinks(full); + return full; + } + private static bool Overlap(string a, string b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase) + || a.StartsWith(b + "\\", StringComparison.OrdinalIgnoreCase) || b.StartsWith(a + "\\", StringComparison.OrdinalIgnoreCase); + private static bool Hash(string? value) => value is not null && Regex.IsMatch(value, "^[A-F0-9]{64}$"); + private static string Digest(byte[] bytes) => Convert.ToHexString(SHA256.HashData(bytes)); + private static T Decode(byte[] bytes) => JsonSerializer.Deserialize(bytes, Json) ?? throw new GateError(Invalid, "Missing record."); + private static bool Same(T a, T b) => JsonSerializer.Serialize(a, Json) == JsonSerializer.Serialize(b, Json); + internal static void WriteNew(string path, T value) + { + Plain(path); + var temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp"; + try + { + using (var file = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { JsonSerializer.Serialize(file, value, Json); file.Flush(true); } + File.Move(temporary, path, overwrite: false); + } + finally { if (File.Exists(temporary)) File.Delete(temporary); } + } + + internal sealed class Scope : IDisposable + { + private readonly List held = []; + private readonly string source, target, control, requestHash; + private readonly Request request; + private readonly Process guardian, installer; + private readonly Stopwatch clock = Stopwatch.StartNew(); + private readonly TimeSpan remaining; + private readonly FileStream lease; + private string FileAt(string name) => Path.Combine(control, name); + + internal Scope(string source, string target, string control, string nonce, int installerPid) + { + // Constructor failures must also release all read locks. + try + { + // NSIS uses a short-name TEMP path. Canonicalize this trusted + // runtime location; caller-selected paths remain strict. + this.source = Plain(Path.GetFullPath(Path.TrimEndingDirectorySeparator(source))); this.target = Plain(target); this.control = Plain(control); + Require(Directory.Exists(control) && Regex.IsMatch(Path.GetFileName(control), "^ucvl-installer-control-[a-f0-9]{32}$"), Invalid, "Unknown control directory."); + Require(Regex.IsMatch(nonce, "^[a-f0-9]{64}$"), Invalid, "Invalid invocation nonce."); + var bytes = ReadPinned(FileAt("request.json")); requestHash = Digest(bytes); request = Decode(bytes); + Require(request.Schema == 1 && request.Nonce == nonce && request.TargetDirectory == this.target, Invalid, "Invocation does not match request."); + var baseline = Plain(request.BaselineJobDirectory); + var stage = Plain(Path.GetDirectoryName(this.source)!); + var roots = new[] { this.target, this.control, baseline, stage }; + for (var i = 0; i < roots.Length; i++) for (var j = i + 1; j < roots.Length; j++) + Require(!Overlap(roots[i], roots[j]), Invalid, "Control, baseline, target and staging must be separate."); + var now = DateTimeOffset.UtcNow; + Require(request.CreatedAtUtc.Offset == TimeSpan.Zero && request.DeadlineUtc.Offset == TimeSpan.Zero + && request.CreatedAtUtc <= now.AddSeconds(2) && request.DeadlineUtc > request.CreatedAtUtc + && request.DeadlineUtc - request.CreatedAtUtc <= TimeSpan.FromMinutes(5), Invalid, "Invalid total gate deadline."); + Require(now < request.DeadlineUtc, TimedOut, "Gate deadline expired."); + Require(request.Installer.Pid == installerPid && request.Guardian.Pid != installerPid + && request.Guardian.Pid != Environment.ProcessId, IdentityMismatch, "Invalid process relationship."); + guardian = PinIdentity(request.Guardian); installer = PinIdentity(request.Installer); + Require(request.DeadlineUtc.UtcTicks <= request.Installer.StartTicks + TimeSpan.FromMinutes(5).Ticks, + Invalid, "Deadline exceeds installer lifetime budget."); + Require(ParentPid(Environment.ProcessId) == installerPid && ParentPid(installerPid) == request.Guardian.Pid, + IdentityMismatch, "Guardian must own this installer and its helper."); + remaining = request.DeadlineUtc - now; + lease = new FileStream(FileAt("gate.lock"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); + held.Add(lease); + } + catch { Dispose(); throw; } + } + private byte[] ReadPinned(string path, int maximum = 4 * 1024 * 1024) + { + Plain(path); + var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); + held.Add(file); + Require(file.Length is > 0 && file.Length <= maximum, EvidenceMismatch, "Invalid evidence file size."); + using var memory = new MemoryStream(); file.CopyTo(memory); return memory.ToArray(); + } + private string PinHash(string path) + { + Plain(path); + var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); held.Add(file); + Require(file.Length > 0, EvidenceMismatch, "Empty staged file."); + return Convert.ToHexString(SHA256.HashData(file)); + } + private Process PinIdentity(Identity expected) + { + Require(expected.Pid > 0 && expected.StartTicks > 0 && expected.SessionId >= 0 && Hash(expected.Sha256), IdentityMismatch, "Incomplete process identity."); + Plain(expected.Path); + var process = Process.GetProcessById(expected.Pid); held.Add(process); + using var current = Process.GetCurrentProcess(); + using var identity = WindowsIdentity.GetCurrent(); + Require(!process.HasExited && process.StartTime.ToUniversalTime().Ticks == expected.StartTicks + && process.MainModule is not null && Path.GetFullPath(process.MainModule.FileName) == expected.Path && process.SessionId == expected.SessionId + && expected.SessionId == current.SessionId && expected.UserSid == identity.User?.Value + && OwnerSid(process) == expected.UserSid, IdentityMismatch, "Process identity or owner changed."); + Require(PinHash(expected.Path) == expected.Sha256, IdentityMismatch, "Process image hash changed."); + return process; + } + private void Alive() + { + Require(!guardian.HasExited && !installer.HasExited, IdentityMismatch, "Guardian or installer exited."); + Require(clock.Elapsed < remaining && DateTimeOffset.UtcNow < request.DeadlineUtc, TimedOut, "Gate deadline expired."); + } + private Ready Stage(bool createManifest) + { + Alive(); + var manifestPath = Path.Combine(source, "install-manifest.json"); + var bytes = ReadPinned(manifestPath); var rows = Decode(bytes); + Require(rows.Length is >= 3 and <= 10000 && rows.Select(r => r.Path).Distinct(StringComparer.OrdinalIgnoreCase).Count() == rows.Length + && new[] { "VPNPlus.exe", "xray/xray.exe", "xray/wintun.dll" }.All(n => rows.Any(r => r.Path == n)), EvidenceMismatch, "Incomplete payload manifest."); + foreach (var row in rows) + Require(Hash(row.Sha256) && PinHash(InstallationTransaction.Resolve(source, row.Path)) == row.Sha256, EvidenceMismatch, "Payload no longer matches its manifest."); + var integration = Plain(Path.Combine(Path.GetDirectoryName(source)!, "integration")); + var components = ComponentNames.Select((name, id) => new Component(id, PinHash(Path.Combine(integration, name)))).ToArray(); + var componentsManifest = Path.Combine(integration, "guardian-components.json"); + if (createManifest) WriteNew(componentsManifest, components); + var componentBytes = ReadPinned(componentsManifest); + Require(Same(Decode(componentBytes), components), EvidenceMismatch, "Staged component manifest changed."); + return new(1, request.Nonce, requestHash, target, request.BaselineJobDirectory, source, manifestPath, Digest(bytes), + integration, componentsManifest, Digest(componentBytes), rows, components, request.Installer, request.Guardian, request.DeadlineUtc); + } + internal int Wait() + { + Require(!File.Exists(FileAt("ready.json")) && !File.Exists(FileAt("release.json")) && !File.Exists(FileAt("accepted.json")) + && !File.Exists(FileAt("consumed.json")), Replay, "Control directory has already been used."); + Require(!Directory.Exists(request.BaselineJobDirectory) && !File.Exists(request.BaselineJobDirectory), Invalid, "Baseline job must be new and independent."); + var ready = Stage(createManifest: true); WriteNew(FileAt("ready.json"), ready); + var readyBytes = ReadPinned(FileAt("ready.json")); var readyHash = Digest(readyBytes); + while (!File.Exists(FileAt("release.json"))) { Alive(); Thread.Sleep(100); } + var releaseBytes = ReadPinned(FileAt("release.json")); ValidateRelease(ready, readyHash, releaseBytes); + Alive(); WriteNew(FileAt("accepted.json"), new Accepted(requestHash, readyHash, Digest(releaseBytes))); + return 0; + } + internal int Apply(Func apply) + { + Require(!File.Exists(FileAt("consumed.json")), Replay, "Release is single-use."); + var readyBytes = ReadPinned(FileAt("ready.json")); var ready = Decode(readyBytes); var readyHash = Digest(readyBytes); + Require(Same(Stage(createManifest: false), ready), EvidenceMismatch, "A different staged batch reached apply."); + var releaseBytes = ReadPinned(FileAt("release.json")); ValidateRelease(ready, readyHash, releaseBytes); + var accepted = Decode(ReadPinned(FileAt("accepted.json"))); + Require(Same(accepted, new Accepted(requestHash, readyHash, Digest(releaseBytes))), ReleaseRefused, "Gate acceptance changed."); + Alive(); WriteNew(FileAt("consumed.json"), accepted); + return apply(); + } + private void ValidateRelease(Ready ready, string readyHash, byte[] releaseBytes) + { + Alive(); var release = Decode(releaseBytes); + Require(release.Schema == 1 && release.Nonce == request.Nonce && release.Permit == "apply-integrated" + && release.RequestSha256 == requestHash && release.ReadySha256 == readyHash && Hash(release.BaselineSha256) + && Same(release.Guardian, request.Guardian) && Same(release.Installer, request.Installer) + && release.ExpiresAtUtc.Offset == TimeSpan.Zero && release.ExpiresAtUtc <= request.DeadlineUtc + && release.ExpiresAtUtc > DateTimeOffset.UtcNow, ReleaseRefused, "Release does not match this live gate."); + var bytes = ReadPinned(Path.Combine(request.BaselineJobDirectory, "baseline.json"), 16 * 1024 * 1024); + Require(Digest(bytes) == release.BaselineSha256, EvidenceMismatch, "Baseline hash changed."); + using var document = JsonDocument.Parse(bytes); var root = document.RootElement; + Require(root.GetProperty("Schema").GetInt32() == 2 && root.GetProperty("Mode").GetString() == "production-current-user" + && root.GetProperty("Target").GetString() == target, EvidenceMismatch, "Baseline scope mismatch."); + var payload = root.GetProperty("Candidate").Deserialize(Json)!; + var components = root.GetProperty("CandidateComponents").Deserialize(Json)!; + var manifests = root.GetProperty("ManifestHashes").Deserialize()!; + Require(Same(payload, ready.Payload) && Same(components, ready.Components) && manifests.Length == 3 + && manifests[1] == ready.PayloadManifestSha256 && manifests[2] == ready.ComponentsManifestSha256, + EvidenceMismatch, "Baseline does not bind this payload and all three generated components."); + ProveGuardianRelease(readyHash, Digest(releaseBytes)); + } + private void ProveGuardianRelease(string readyHash, string releaseHash) + { + Alive(); + var budget = request.DeadlineUtc - DateTimeOffset.UtcNow; + using var deadline = new CancellationTokenSource(budget < TimeSpan.FromSeconds(3) ? budget : TimeSpan.FromSeconds(3)); + using var pipe = new NamedPipeClientStream(".", "UCVL.InstallerGuardian." + request.Nonce, + PipeDirection.In, PipeOptions.Asynchronous, TokenImpersonationLevel.Identification); + try + { + pipe.ConnectAsync(deadline.Token).GetAwaiter().GetResult(); + Require(GetNamedPipeServerProcessId(pipe.SafePipeHandle, out var serverPid) && serverPid == request.Guardian.Pid, + IdentityMismatch, "Release pipe is not owned by the bound guardian."); + using var reader = new StreamReader(pipe); + var line = new System.Text.StringBuilder(); var character = new char[1]; + while (true) + { + var count = reader.ReadAsync(character.AsMemory(), deadline.Token).AsTask().GetAwaiter().GetResult(); + Require(count == 1 && line.Length < 2048, ReleaseRefused, "Missing or oversized guardian pipe approval."); + if (character[0] == '\n') break; + line.Append(character[0]); + } + var approval = JsonSerializer.Deserialize(line.ToString(), Json); + Require(Same(approval, new PipeApproval(request.Nonce, requestHash, readyHash, releaseHash)), + ReleaseRefused, "Guardian did not approve this exact release."); + } + catch (OperationCanceledException) { throw new GateError(TimedOut, "Guardian pipe deadline expired."); } + Alive(); + } + public void Dispose() { foreach (var item in held.AsEnumerable().Reverse()) item.Dispose(); held.Clear(); } + } + + [DllImport("advapi32.dll", SetLastError = true)] + private static extern bool OpenProcessToken(IntPtr process, uint access, out SafeAccessTokenHandle token); + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool GetNamedPipeServerProcessId(SafePipeHandle pipe, out int serverPid); + private static string OwnerSid(Process process) + { + Require(OpenProcessToken(process.Handle, 8, out var token), IdentityMismatch, "Cannot inspect process owner."); + using (token) using (var identity = new WindowsIdentity(token.DangerousGetHandle())) + return identity.User?.Value ?? throw new GateError(IdentityMismatch, "Process owner SID missing."); + } + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct Entry + { + public uint Size, Usage, Pid; public UIntPtr Heap; public uint Module, Threads, ParentPid; + public int Priority; public uint Flags; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string Exe; + } + [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr CreateToolhelp32Snapshot(uint flags, uint pid); + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] private static extern bool Process32First(IntPtr snapshot, ref Entry entry); + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] private static extern bool Process32Next(IntPtr snapshot, ref Entry entry); + [DllImport("kernel32.dll")] private static extern bool CloseHandle(IntPtr handle); + internal static int ParentPid(int pid) + { + var snapshot = CreateToolhelp32Snapshot(2, 0); + Require(snapshot != new IntPtr(-1), IdentityMismatch, "Cannot inspect process lineage."); + try + { + var entry = new Entry { Size = (uint)Marshal.SizeOf(), Exe = "" }; + if (Process32First(snapshot, ref entry)) do { if (entry.Pid == pid) return checked((int)entry.ParentPid); } while (Process32Next(snapshot, ref entry)); + throw new GateError(IdentityMismatch, "Parent process missing."); + } + finally { CloseHandle(snapshot); } + } +} diff --git a/windows/KnownTailnetEndpoints.cs b/windows/KnownTailnetEndpoints.cs new file mode 100644 index 0000000..e2b4408 --- /dev/null +++ b/windows/KnownTailnetEndpoints.cs @@ -0,0 +1,42 @@ +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. +// The authenticated API config remains the authority for credentials and identity. +internal static class KnownTailnetEndpoints +{ + internal static TailnetEndpoint? Resolve(ConfigResponse response, bool allowCompatibilityMapping) + { + // This switch permits legacy endpoint mapping, not an employee or + // tailnet-membership policy. The API still supplies node authorization. + // An explicit field (including null/invalid metadata) ALWAYS wins. Never + // turn server rejection or an unknown contract into a compiled fallback. + if (!allowCompatibilityMapping || response.HasTailscaleEndpoint || response.ConfigContract != 2 + || response.ConnectionScope is not ("" or "public") + || response.RouteMode is not ("smart" or "global")) return null; + var mapping = response.Node.Slug switch + { + "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), + _ => default + }; + if (mapping.Host is null) return null; + try + { + // Check the API's original node endpoint BEFORE the public-gateway + // rewrite. A reused slug/name must not send credentials to an old IP. + var root = JsonNode.Parse(response.Config.GetRawText())!.AsObject(); + if (root.ContainsKey(TailnetTransport.Marker) || PrivateAuxiliaryRuntime.IsPrivate(root)) return null; + var proxy = TailnetTransport.Proxy(root); + var server = proxy?["settings"]?["vnext"]?[0]; + if (server?["address"]?.GetValue() != mapping.Host + || server?["port"]?.GetValue() != mapping.PublicPort) return null; + return new TailnetEndpoint { Contract = 1, NodeSlug = response.Node.Slug, + Address = mapping.Address, Port = mapping.Port }; + } + catch (Exception e) when (e is System.Text.Json.JsonException or InvalidOperationException or FormatException) + { return null; } + } +} diff --git a/windows/LICENSE b/windows/LICENSE new file mode 100644 index 0000000..381a41b --- /dev/null +++ b/windows/LICENSE @@ -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. diff --git a/windows/LearningExpirySoakSelfTest.cs b/windows/LearningExpirySoakSelfTest.cs new file mode 100644 index 0000000..53bd6d1 --- /dev/null +++ b/windows/LearningExpirySoakSelfTest.cs @@ -0,0 +1,212 @@ +using System.Collections.Concurrent; +using System.Diagnostics; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace UCVL.VPNPlus; + +// An authorized node with private, loopback-only inbounds, plus a persistent +// local echo stream. Uses the production parser/lease book/routing updater. +// Injects direct-path failure ONLY into its own test core, to deterministically +// exercise leases even when the host's current direct path can work. +// No TUN, OS route/DNS/proxy writes, profile updates, telemetry submission, +// installed-client control, or authenticated Codex requests. +internal static class LearningExpirySoakSelfTest +{ + internal static async Task RunAsync(int minutes) + { + var reportPath = Path.Combine(AppContext.BaseDirectory, "learning-expiry-soak.json"); + var progressPath = Path.Combine(AppContext.BaseDirectory, "learning-expiry-soak-progress.json"); + var started = DateTimeOffset.Now; + var watch = Stopwatch.StartNew(); + var samples = new List(); + var comparisons = new List(); + var book = new NetworkLearningLeases(); + var hints = new ConcurrentDictionary(); + var hosts = new[] { "www.google.com", "api.openai.com", "chatgpt.com" }; + Process? core = null; + TcpClient? streamClient = null, streamServer = null; + var echo = new TcpListener(IPAddress.Loopback, 0); + var folder = Path.Combine(Path.GetTempPath(), "ucvl-expiry-soak-" + Guid.NewGuid().ToString("N")); + var configPath = Path.Combine(folder, "config.json"); + var coreId = 0; + var renewals = 0; + var taggedHints = 0; + var healthy = 0; + var failed = 0; + var streamChecks = 0; + var passed = false; + string? failure = null; + try + { + using var deadline = new CancellationTokenSource(TimeSpan.FromMinutes(minutes + 2)); + var token = deadline.Token; + using var api = new VpnApiClient(); + var access = TokenStore.Load() ?? throw new IOException("Existing session required."); + var profile = await api.GetProfileAsync(access, token); + var node = profile.Nodes.Single(n => n.Name == "VPN002"); + var response = await api.GetConfigAsync(access, node.Slug, "smart", token); + var config = LearningPolicy.DirectFirst(response.GetRuntimeConfigJson()); + var addresses = new List(); + foreach (var host in TunConfigBuilder.GetProxyServerHosts(config)) + addresses.AddRange(await Dns.GetHostAddressesAsync(host, token)); + var physical = TunRouting.GetPhysicalNetwork(addresses); + var reservations = Enumerable.Range(0, 4).Select(_ => new TcpListener(IPAddress.Loopback, 0)).ToArray(); + foreach (var reserve in reservations) reserve.Start(); + var ports = reservations.Select(l => ((IPEndPoint)l.LocalEndpoint).Port).ToArray(); + foreach (var reserve in reservations) reserve.Stop(); + echo.Start(); + var echoPort = ((IPEndPoint)echo.LocalEndpoint).Port; + var root = JsonNode.Parse(config)!.AsObject(); + root["inbounds"] = new JsonArray(new JsonObject { ["tag"] = "soak-business", ["listen"] = "127.0.0.1", + ["port"] = ports[0], ["protocol"] = "socks", ["settings"] = new JsonObject { ["auth"] = "noauth", ["udp"] = false } }); + config = root.ToJsonString(); + string Runtime(string source) + { + var runtime = JsonNode.Parse(TunConfigBuilder.Build(source, physical.InterfaceName, true, + includeTun: false, routingApiPort: ports[1], learningProbePort: ports[2], directProbePort: ports[3]))!; + var isolatedOutbounds = runtime["outbounds"]!.AsArray(); + for (var index = 0; index < isolatedOutbounds.Count; index++) { + var tag = isolatedOutbounds[index]!["tag"]!.GetValue(); + if (tag is "direct" or "ucvl-learning-direct") + isolatedOutbounds[index] = new JsonObject { ["tag"] = tag, ["protocol"] = "blackhole" }; + } + // Synthetic stream never leaves loopback and must not inherit a + // physical-interface binding intended for Internet direct traffic. + runtime["outbounds"]!.AsArray().Add(new JsonObject { ["tag"] = "soak-echo", ["protocol"] = "freedom" }); + runtime["routing"]!["rules"]!.AsArray().Insert(0, new JsonObject { ["type"] = "field", ["ip"] = new JsonArray("127.0.0.1"), + ["port"] = echoPort.ToString(), ["outboundTag"] = "soak-echo", ["ruleTag"] = "ucvl-soak-echo" }); + return runtime.ToJsonString(); + } + var xray = Path.Combine(AppContext.BaseDirectory, "xray", "xray.exe"); + Directory.CreateDirectory(folder); + await File.WriteAllTextAsync(configPath, Runtime(config), token); + var startInfo = new ProcessStartInfo(xray) { UseShellExecute = false, CreateNoWindow = true, + WorkingDirectory = Path.GetDirectoryName(xray)!, RedirectStandardOutput = true, RedirectStandardError = true }; + foreach (var argument in new[] { "run", "-c", configPath }) startInfo.ArgumentList.Add(argument); + core = new Process { StartInfo = startInfo }; + void ReadLine(object sender, DataReceivedEventArgs e) + { + if (e.Data is not { } line) return; + var hint = LearningPolicy.ParseAttempt(line, "fixture", "public"); + if (hint is null || !hosts.Contains(hint.Target)) return; + if (line.Contains("Hit route rule:")) Interlocked.Increment(ref taggedHints); + hints.TryAdd(hint.Target, 0); + } + core.OutputDataReceived += ReadLine; core.ErrorDataReceived += ReadLine; + core.Start(); core.BeginOutputReadLine(); core.BeginErrorReadLine(); + coreId = core.Id; + await Task.Delay(900, token); + File.Delete(configPath); // The launched core has consumed credentials; never keep them in evidence. + + async Task ApplyAsync() + { + if (!book.Dirty) return; + var merged = LearningPolicy.Merge(config, new() { Contract = 1, Revision = new string('0', 64), Rules = book.Targets.ToList() }); + var runtime = JsonNode.Parse(Runtime(merged))!; + await XrayRoutingUpdater.ApplyAsync(xray, ports[1], new JsonObject { ["routing"] = runtime["routing"]!.DeepClone() }.ToJsonString(), token); + book.Applied(); + } + async Task VerifyAsync(IEnumerable<(string Host, NetworkLearningLeases.Entry? Entry)> targets) + { + var proofs = await Task.WhenAll(targets.Select(async target => ( + target.Host, target.Entry, Proof: await ProxyProbe.CompareTlsAsync(new() { Target = target.Host, Port = 443 }, ports[3], ports[2], token)))); + foreach (var proof in proofs) { + book.Observe(new() { Target = proof.Host, TargetType = "domain", MatchMode = "exact" }, proof.Proof, Environment.TickCount64, proof.Entry); + if (proof.Entry is not null && proof.Proof.ShouldProxy) renewals++; + comparisons.Add(new { seconds = watch.Elapsed.TotalSeconds, target = proof.Host, direct = proof.Proof.DirectTls, + proxy = proof.Proof.ProxyTls, renewed = proof.Entry is not null && proof.Proof.ShouldProxy }); + } + await ApplyAsync(); + } + + // First observe the real tagged DIRECT log. This starts on a cold + // isolated rule bank; no fixed warmup can hide a broken parser. + await NodeHealthProbe.CheckAsync(token, ports[0]); + var observed = hosts.Where(h => hints.TryRemove(h, out _)).ToArray(); + if (observed.Length != 3 || taggedHints < 3) throw new IOException("Tagged direct attempts were not all observed."); + await VerifyAsync(observed.Select(h => (h, (NetworkLearningLeases.Entry?)null))); + if (book.Count == 0) throw new IOException("No proxy-needed rule available to exercise expiry."); + + streamClient = await ConnectEchoAsync(ports[0], echoPort, token); + streamServer = await echo.AcceptTcpClientAsync(token); + var initialRules = book.Count; + var exerciseStarted = Stopwatch.StartNew(); + var nextHealth = 0L; + while (exerciseStarted.Elapsed < TimeSpan.FromMinutes(minutes)) { + token.ThrowIfCancellationRequested(); + if (core.HasExited || core.Id != coreId) throw new IOException("Isolated core did not remain alive."); + var now = Environment.TickCount64; + var due = book.Due(now); + if (due.Length > 0) { + foreach (var entry in due) book.Scheduled(entry, now); + await VerifyAsync(due.Select(e => (e.Target.Target, (NetworkLearningLeases.Entry?)e))); + } + book.Expire(Environment.TickCount64); + await ApplyAsync(); + // No reconnect/retry hides an interrupted stream. + await EchoAsync(streamClient, streamServer, token); + streamChecks++; + if (exerciseStarted.ElapsedMilliseconds >= nextHealth) { + var ok = await NodeHealthProbe.CheckAsync(token, ports[0]); + if (ok) healthy++; else failed++; + samples.Add(new { seconds = exerciseStarted.Elapsed.TotalSeconds, ordinary_smart_healthy = ok, + same_core = !core.HasExited && core.Id == coreId, leases = book.Count, renewals, stream_checks = streamChecks }); + nextHealth = exerciseStarted.ElapsedMilliseconds + 15_000; + await File.WriteAllTextAsync(progressPath, JsonSerializer.Serialize(new { running = true, started, + requested_minutes = minutes, elapsed_seconds = exerciseStarted.Elapsed.TotalSeconds, core_id = coreId, + healthy, failed, renewals, streamChecks, taggedHints, initialRules }), token); + } + await Task.Delay(5_000, token); + } + passed = failed == 0 && healthy > 0 && !core.HasExited && (minutes < 11 || renewals >= initialRules) + && (minutes < 21 || renewals >= initialRules * 2) && (minutes < 30 || renewals >= initialRules * 3); + } + catch (Exception error) { failure = error.GetType().Name + ": " + error.Message; } + finally + { + streamClient?.Dispose(); streamServer?.Dispose(); echo.Stop(); + if (core is not null) { try { if (!core.HasExited) core.Kill(true); await core.WaitForExitAsync(); } catch { } core.Dispose(); } + if (File.Exists(configPath)) File.Delete(configPath); + if (Directory.Exists(folder)) Directory.Delete(folder); + await File.WriteAllTextAsync(reportPath, JsonSerializer.Serialize(new { scope = "isolated direct-path fault injection, real authorized VPN002 transport, loopback lifecycle soak and persistent local TCP stream; NOT installed TUN or authenticated Codex acceptance", + started, finished = DateTimeOffset.Now, requested_minutes = minutes, elapsed_seconds = watch.Elapsed.TotalSeconds, + passed, failure, network_modified = false, installed_client_modified = false, production_observations_submitted = false, + direct_path_fault_injected_in_isolated_core = true, + core_id = coreId, taggedHints, renewals, streamChecks, healthy, failed, comparisons, samples }, new JsonSerializerOptions { WriteIndented = true })); + await File.WriteAllTextAsync(progressPath, JsonSerializer.Serialize(new { running = false, passed, failure, report = Path.GetFileName(reportPath) })); + } + return passed ? 0 : 34; + } + + private static async Task ConnectEchoAsync(int port, int targetPort, CancellationToken token) + { + var client = new TcpClient(); + try { + await client.ConnectAsync(IPAddress.Loopback, port, token); + var stream = client.GetStream(); + await stream.WriteAsync(new byte[] { 5, 1, 0 }, token); + var hello = new byte[2]; await stream.ReadExactlyAsync(hello, token); + if (!hello.SequenceEqual(new byte[] { 5, 0 })) throw new IOException("SOCKS greeting rejected."); + await stream.WriteAsync(new byte[] { 5, 1, 0, 1, 127, 0, 0, 1, (byte)(targetPort >> 8), (byte)targetPort }, token); + var reply = new byte[10]; await stream.ReadExactlyAsync(reply, token); + if (reply[1] != 0) throw new IOException("SOCKS connect rejected."); + return client; + } catch { client.Dispose(); throw; } + } + private static async Task EchoAsync(TcpClient client, TcpClient server, CancellationToken token) + { + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token); + deadline.CancelAfter(TimeSpan.FromSeconds(5)); + var payload = Encoding.UTF8.GetBytes("ucvl-isolated-continuity-" + Guid.NewGuid()); + var buffer = new byte[payload.Length]; + await client.GetStream().WriteAsync(payload, deadline.Token); + await server.GetStream().ReadExactlyAsync(buffer, deadline.Token); + await server.GetStream().WriteAsync(buffer, deadline.Token); + await client.GetStream().ReadExactlyAsync(buffer, deadline.Token); + if (!buffer.SequenceEqual(payload)) throw new IOException("Persistent stream payload mismatch."); + } +} diff --git a/windows/LearningMatrixSelfTest.cs b/windows/LearningMatrixSelfTest.cs new file mode 100644 index 0000000..608219f --- /dev/null +++ b/windows/LearningMatrixSelfTest.cs @@ -0,0 +1,101 @@ +using System.Diagnostics; +using System.Net; +using System.Net.Sockets; +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace UCVL.VPNPlus; + +// Real core + authorized nodes, loopback-only inbounds. Never acquires the network +// owner, installs TUN, changes DNS/route/proxy or touches the running installation. +internal static class LearningMatrixSelfTest +{ + internal static async Task RunAsync() + { + var results = new List(); + var passed = false; + string? errorType = null; + try + { + using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(3)); + using var api = new VpnApiClient(); + var access = TokenStore.Load() ?? throw new IOException("No existing app session."); + var profile = await api.GetProfileAsync(access, timeout.Token); + var nodes = profile.Nodes.Where(n=>n.Name is "VPN002" or "VPN003").ToArray(); + if (nodes.Length != 2) throw new IOException("Expected authorized public nodes absent."); + var nodePasses = new List(); + foreach (var node in nodes) + { + var response = await api.GetConfigAsync(access,node.Slug,"smart",timeout.Token); + var config = LearningPolicy.DirectFirst(response.GetRuntimeConfigJson()); + var addresses = new List(); + foreach (var host in TunConfigBuilder.GetProxyServerHosts(config)) addresses.AddRange(await Dns.GetHostAddressesAsync(host,timeout.Token)); + var physical = TunRouting.GetPhysicalNetwork(addresses); + // Reserve simultaneously so port numbers cannot duplicate each other. + var listeners = Enumerable.Range(0,4).Select(_=>new TcpListener(IPAddress.Loopback,0)).ToArray(); + foreach(var l in listeners) l.Start(); + var ports = listeners.Select(l=>((IPEndPoint)l.LocalEndpoint).Port).ToArray(); + foreach(var l in listeners) l.Stop(); + var root=JsonNode.Parse(config)!.AsObject(); + root["inbounds"]=new JsonArray(new JsonObject { ["tag"]="matrix-business",["listen"]="127.0.0.1",["port"]=ports[0], + ["protocol"]="socks",["settings"]=new JsonObject { ["auth"]="noauth",["udp"]=false }, + ["sniffing"]=new JsonObject { ["enabled"]=true,["destOverride"]=new JsonArray("tls"),["routeOnly"]=false } }); + config=root.ToJsonString(); + string Runtime(string source) => TunConfigBuilder.Build(source,physical.InterfaceName,true,includeTun:false, + routingApiPort:ports[1],learningProbePort:ports[2],directProbePort:ports[3]); + var folder=Path.Combine(Path.GetTempPath(),"ucvl-learning-matrix-"+Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(folder); + var path=Path.Combine(folder,"config.json"); + var xray=Path.Combine(AppContext.BaseDirectory,"xray","xray.exe"); + Process? process=null; + try + { + await File.WriteAllTextAsync(path,Runtime(config),timeout.Token); + var start=new ProcessStartInfo(xray) { UseShellExecute=false,CreateNoWindow=true,RedirectStandardOutput=true,RedirectStandardError=true }; + foreach(var arg in new[]{"run","-c",path}) start.ArgumentList.Add(arg); + process=Process.Start(start)!; + _=process.StandardOutput.ReadToEndAsync(); _=process.StandardError.ReadToEndAsync(); + await Task.Delay(800,timeout.Token); + var originalPid=process.Id; + var comparisons=await Task.WhenAll(new[]{"www.google.com","chatgpt.com","www.baidu.com"}.Select(async host=> { + var watch=Stopwatch.StartNew(); + var observation=new LearningObservation { Target=host,Port=443,AccessKind="http" }; + var comparison=await ProxyProbe.CompareTlsAsync(observation,ports[3],ports[2],timeout.Token); + return (host,comparison,ms:watch.ElapsedMilliseconds); + })); + var learned=comparisons.Where(p=>p.comparison.ShouldProxy).Select(p=>new RoutingTarget {Target=p.host,TargetType="domain",MatchMode="exact"}).ToList(); + var updated=LearningPolicy.Merge(config,new() {Contract=1,Revision=new string('0',64),Rules=learned}); + var runtime=JsonNode.Parse(Runtime(updated))!; + await XrayRoutingUpdater.ApplyAsync(xray,ports[1],new JsonObject { ["routing"]=runtime["routing"]!.DeepClone() }.ToJsonString(),timeout.Token); + using var http=new HttpClient(new SocketsHttpHandler {UseProxy=true,Proxy=new WebProxy($"socks5://127.0.0.1:{ports[0]}"),AllowAutoRedirect=false}) { Timeout=TimeSpan.FromSeconds(12) }; + int google=0; + try { using var reply=await http.GetAsync("https://www.google.com/generate_204",timeout.Token); google=(int)reply.StatusCode; } catch(HttpRequestException) { } catch(TaskCanceledException) when(!timeout.IsCancellationRequested) { } + bool businessTls; + // Uses the ordinary smart-routed listener, NOT the forced proxy listener. + businessTls=await ProxyProbe.ProbeTlsAsync(new(){Target="chatgpt.com",Port=443},ports[0],timeout.Token,resolverProxyPort:ports[2])==true; + var sameCore=!process.HasExited && process.Id==originalPid; + var ok=sameCore && google==204 && businessTls && comparisons.All(p=>p.comparison.DirectTls==true || p.comparison.ShouldProxy) + && comparisons.Any(p=>p.comparison.DirectTls==true) && learned.Count>0; + results.Add(new {node=node.Name,passed=ok,comparisons=comparisons.Select(p=>new {target=p.host,direct_tls=p.comparison.DirectTls,proxy_tls=p.comparison.ProxyTls,promoted=p.comparison.ShouldProxy,elapsed_ms=p.ms}), + google_smart_http=google,chatgpt_smart_tls=businessTls,same_core_after_rule_update=sameCore}); + nodePasses.Add(ok); + } + finally + { + if(process is not null) {try {if(!process.HasExited) process.Kill(true); await process.WaitForExitAsync();} finally {process.Dispose();} } + if(File.Exists(path)) File.Delete(path); + Directory.Delete(folder); + } + } + passed=nodePasses.Count==2 && nodePasses.All(x=>x); + } + catch(Exception error) {errorType=error.GetType().Name;} + finally + { + File.WriteAllText(Path.Combine(AppContext.BaseDirectory,"learning-matrix-self-test.json"),JsonSerializer.Serialize(new { + scope="real physical-interface direct TLS vs authorized-node proxy TLS, then loopback smart routing; NOT installed TUN or authenticated Codex acceptance", + passed,error_type=errorType,os_network_modified=false,production_observations_submitted=false,results},new JsonSerializerOptions{WriteIndented=true})); + } + return passed?0:33; + } +} diff --git a/windows/LearningPolicy.cs b/windows/LearningPolicy.cs new file mode 100644 index 0000000..590f14c --- /dev/null +++ b/windows/LearningPolicy.cs @@ -0,0 +1,112 @@ +using System.Net; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.RegularExpressions; + +namespace UCVL.VPNPlus; + +// Minimal transport observations, not URL/history collection or an HTTP status classifier. +internal static class LearningPolicy +{ + private static readonly Regex Failure = new(@"proxy/freedom: failed to open connection to (?tcp|udp):(?\[[0-9a-fA-F:]+\]|[A-Za-z0-9._-]+):(?\d{1,5})", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private static readonly Regex DirectAttempt = new(@"app/dispatcher: (?:Hit route rule: \[[^\[\]\r\n]{1,200}\] so )?taking detour \[direct\] for \[tcp:(?[A-Za-z0-9._-]+):443\]", RegexOptions.Compiled); + + // An attempt is only a hint for a separate direct TLS check, never failure evidence. + // Probe outbounds have a different tag, preventing recursive self-observation. + internal static LearningObservation? ParseAttempt(string line, string node, string scope) + { + if (line.Length > 8192) return null; + var match = DirectAttempt.Match(line); + var target = match.Groups["target"].Value.TrimEnd('.').ToLowerInvariant(); + if (!match.Success || !Allowed("domain", target)) return null; + return new() { Target=target, TargetType="domain", Port=443, Network="tcp", AccessKind="http", Node=node, Scope=scope }; + } + internal static bool PublicIp(IPAddress ip) + { + if (ip.IsIPv4MappedToIPv6) return PublicIp(ip.MapToIPv4()); + var b = ip.GetAddressBytes(); + if (b.Length != 4) return false; // Do not automatically promote IPv6 without equivalent validation. + return b[0] is > 0 and < 224 && b[0] != 10 && b[0] != 127 + && !(b[0] == 100 && b[1] is >= 64 and <= 127) + && !(b[0] == 169 && b[1] == 254) && !(b[0] == 172 && b[1] is >= 16 and <= 31) + && !(b[0] == 192 && (b[1] == 168 || b[1] == 0 || b[1] == 2)) + && !(b[0] == 198 && (b[1] is 18 or 19 || b[1] == 51 && b[2] == 100)) + && !(b[0] == 203 && b[1] == 0 && b[2] == 113); + } + internal static bool Allowed(string kind, string target) + { + if (kind == "ip") return IPAddress.TryParse(target, out var ip) && PublicIp(ip); + if (kind != "domain" || IPAddress.TryParse(target, out _) || target.Length > 253 || !target.Contains('.')) return false; + if (target.Split('.').Any(label => !Regex.IsMatch(label, "^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$"))) return false; + return !new[] { "toplc.cn", "ucvl.cn", "ucvl.net", "local", "localhost", "lan", "internal", "home", "invalid", "test", "example", "arpa", "onion" } + .Any(suffix => target == suffix || target.EndsWith("." + suffix, StringComparison.Ordinal)); + } + internal static LearningObservation? Parse(string line, string node, string scope) + { + if (line.Length > 8192) return null; + var match = Failure.Match(line); + if (!match.Success || !int.TryParse(match.Groups["port"].Value, out var port) || port is < 1 or > 65535) return null; + var target = match.Groups["target"].Value.Trim('[', ']').TrimEnd('.').ToLowerInvariant(); + var type = IPAddress.TryParse(target, out _) ? "ip" : "domain"; + if (!Allowed(type, target)) return null; + var failure = line.Contains("timeout", StringComparison.OrdinalIgnoreCase) || line.Contains("timed out", StringComparison.OrdinalIgnoreCase) ? "timeout" + : line.Contains("reset", StringComparison.OrdinalIgnoreCase) ? "reset" + : line.Contains("lookup", StringComparison.OrdinalIgnoreCase) || line.Contains("dns", StringComparison.OrdinalIgnoreCase) ? "dns" + : line.Contains("unreachable", StringComparison.OrdinalIgnoreCase) ? "unreachable" : "other"; + return new LearningObservation { Target = target, TargetType = type, Port = port, + Network = match.Groups["network"].Value.ToLowerInvariant(), AccessKind = port is 80 or 443 ? "http" : "socket", + FailureKind = failure, Node = node, Scope = scope }; + } + internal static string Merge(string baseConfig, RoutingManifest manifest) + { + if (manifest.Contract != 1 || !Regex.IsMatch(manifest.Revision, "^[0-9a-f]{64}$") || manifest.Rules.Count > 2048) + throw new InvalidDataException("智能规则版本或容量无效。"); + var root = JsonNode.Parse(baseConfig)!.AsObject(); + var rules = root["routing"]?["rules"]?.AsArray() ?? throw new InvalidDataException("缺少原路由。"); + // Server tags only the replaceable learned bank; preserve LAN/company/DNS/default rules. + for (var i = rules.Count - 1; i >= 0; i--) + if (rules[i]?["ruleTag"]?.GetValue() == "ucvl-learned") rules.RemoveAt(i); + var domains = new JsonArray(); var ips = new JsonArray(); + foreach (var entry in manifest.Rules) + { + if (!Allowed(entry.TargetType, entry.Target) || entry.MatchMode is not ("exact" or "suffix") + || entry.TargetType == "ip" && entry.MatchMode != "exact") throw new InvalidDataException("不安全的智能目标。"); + if (entry.TargetType == "domain") domains.Add((entry.MatchMode == "suffix" ? "domain:" : "full:") + entry.Target); + else ips.Add(entry.Target + "/32"); + } + // After private-address DIRECT. Never insert ahead of this safety boundary. + var insertion = rules.Count > 0 ? 1 : 0; + if (ips.Count > 0) rules.Insert(insertion, new JsonObject { ["type"] = "field", ["ip"] = ips, ["network"] = "tcp", ["port"] = "443", ["outboundTag"] = "proxy", ["ruleTag"] = "ucvl-learned" }); + if (domains.Count > 0) rules.Insert(insertion, new JsonObject { ["type"] = "field", ["domain"] = domains, ["network"] = "tcp", ["port"] = "443", ["outboundTag"] = "proxy", ["ruleTag"] = "ucvl-learned" }); + return root.ToJsonString(); + } + + internal static string DirectFirst(string baseConfig) + { + var root = JsonNode.Parse(baseConfig)!.AsObject(); + if (root["routing"]?["rules"] is JsonArray rules) + for (var i = rules.Count - 1; i >= 0; i--) + { + var rule = rules[i]!.AsObject(); + if (rule["ruleTag"]?.GetValue() == "ucvl-learned" || rule["outboundTag"]?.GetValue() == "proxy" + && (rule["domain"] is not null || rule["ip"] is not null) + && rule.All(pair => pair.Key is "type" or "domain" or "ip" or "outboundTag" or "ruleTag")) + rules.RemoveAt(i); // Shared/manual destination lists are hints in direct-first smart mode. + } + return root.ToJsonString(); + } +} + +internal sealed class RoutingManifest +{ + [System.Text.Json.Serialization.JsonPropertyName("contract")] public int Contract { get; init; } + [System.Text.Json.Serialization.JsonPropertyName("mode")] public string Mode { get; init; } = ""; + [System.Text.Json.Serialization.JsonPropertyName("revision")] public string Revision { get; init; } = ""; + [System.Text.Json.Serialization.JsonPropertyName("rules")] public List Rules { get; init; } = []; +} +internal sealed class RoutingTarget +{ + [System.Text.Json.Serialization.JsonPropertyName("target_type")] public string TargetType { get; init; } = ""; + [System.Text.Json.Serialization.JsonPropertyName("target")] public string Target { get; init; } = ""; + [System.Text.Json.Serialization.JsonPropertyName("match_mode")] public string MatchMode { get; init; } = ""; +} diff --git a/windows/LearningProbeBudget.cs b/windows/LearningProbeBudget.cs new file mode 100644 index 0000000..26be0cf --- /dev/null +++ b/windows/LearningProbeBudget.cs @@ -0,0 +1,23 @@ +namespace UCVL.VPNPlus; + +// One budget per core/network epoch. No unbounded queues, browsing history or disk cache. +internal sealed class LearningProbeBudget +{ + private readonly Dictionary _recent = new(); + private long _window; + private int _count; + private int _active; + internal bool TryEnter(string target, long now) + { + lock (_recent) + { + if (_active >= 4) return false; + if (now - _window >= 60_000) { _count=0; _window=now; } + if (_count >= 60 || _recent.TryGetValue(target, out var previous) && now-previous < 30_000) return false; + foreach (var key in _recent.Where(p => now-p.Value >= 60_000).Select(p=>p.Key).ToArray()) _recent.Remove(key); + _recent[target]=now; _count++; _active++; + return true; + } + } + internal void Exit() { lock (_recent) { _active--; } } +} diff --git a/windows/LearningSelfTest.cs b/windows/LearningSelfTest.cs new file mode 100644 index 0000000..5de1ced --- /dev/null +++ b/windows/LearningSelfTest.cs @@ -0,0 +1,93 @@ +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace UCVL.VPNPlus; + +internal static class LearningSelfTest +{ + internal static int Run() + { + var checks = new Dictionary(); + const string baseConfig = """{"inbounds":[],"outbounds":[{"tag":"proxy","protocol":"socks","settings":{"servers":[{"address":"8.8.8.8","port":443}]}},{"tag":"direct","protocol":"freedom"},{"tag":"block","protocol":"blackhole"}],"routing":{"rules":[{"type":"field","ip":["geoip:private"],"outboundTag":"direct"},{"type":"field","domain":["domain:openai.com"],"outboundTag":"proxy","ruleTag":"ucvl-learned"},{"type":"field","domain":["geosite:category-ads-all"],"outboundTag":"block"},{"type":"field","network":"tcp,udp","outboundTag":"direct"}]}}"""; + bool Throws(Action action) { try { action(); return false; } catch (InvalidDataException) { return true; } } + LearningObservation? Parse(string text) => LearningPolicy.Parse(text, "fixture", "public"); + var line = "[Info] [123] app/proxyman/outbound: failed to process outbound traffic > proxy/freedom: failed to open connection to tcp:learn.example.com:443 > i/o timeout"; + var parsed = Parse(line); + checks["freedom_without_direct_detected"] = parsed is { Target: "learn.example.com", FailureKind: "timeout", Port: 443 }; + checks["acceptance_is_not_success"] = Parse("from tcp:127.0.0.1:777 accepted tcp:learn.example.com:443 [socks-in -> direct]") is null; + checks["http_auth_status_is_not_failure"] = Parse("HTTP 401 / 403 / 429 direct learn.example.com:443") is null; + checks["proxy_failures_not_direct"] = Parse(line.Replace("proxy/freedom", "proxy/vless/outbound")) is null; + checks["private_failures_not_collected"] = Parse(line.Replace("learn.example.com", "192.168.50.111")) is null; + checks["company_not_collected"] = Parse(line.Replace("learn.example.com", "vpn.toplc.cn")) is null; + checks["source_not_misidentified"] = Parse("tcp:127.0.0.1:777 " + line)?.Target == "learn.example.com"; + checks["oversized_line_rejected"] = Parse(new string('x', 8193) + line) is null; + const string attempt = "[Info] [1753901314] app/dispatcher: taking detour [direct] for [tcp:tls-gap.example.com:443]"; + checks["tls_attempt_detected_before_failure_log"] = LearningPolicy.ParseAttempt(attempt,"fixture","public")?.Target == "tls-gap.example.com"; + var tagged = attempt.Replace("app/dispatcher: ", "app/dispatcher: Hit route rule: [ucvl-fixture-0] so "); + checks["real_tagged_attempt_detected"] = LearningPolicy.ParseAttempt(tagged,"fixture","public")?.Target == "tls-gap.example.com"; + checks["tagged_proxy_not_collected"] = LearningPolicy.ParseAttempt(tagged.Replace("[direct]", "[proxy]"),"fixture","public") is null; + checks["tagged_probe_not_recursive"] = LearningPolicy.ParseAttempt(tagged.Replace("[direct]", "[ucvl-learning-direct]"),"fixture","public") is null; + checks["oversized_tag_rejected"] = LearningPolicy.ParseAttempt(tagged.Replace("ucvl-fixture-0", new string('x',201)),"fixture","public") is null; + checks["multiline_tag_rejected"] = LearningPolicy.ParseAttempt(tagged.Replace("ucvl-fixture-0", "ucvl-\n0"),"fixture","public") is null; + checks["attempt_is_not_failure_evidence"] = Parse(attempt) is null; + checks["probe_not_recursively_observed"] = LearningPolicy.ParseAttempt(attempt.Replace("[direct]","[ucvl-learning-direct]"),"fixture","public") is null; + checks["proxy_attempt_not_observed"] = LearningPolicy.ParseAttempt(attempt.Replace("[direct]","[proxy]"),"fixture","public") is null; + checks["private_attempt_not_observed"] = LearningPolicy.ParseAttempt(attempt.Replace("tls-gap.example.com","192.168.50.111"),"fixture","public") is null; + checks["non_tls_attempt_not_observed"] = LearningPolicy.ParseAttempt(attempt.Replace(":443]",":80]"),"fixture","public") is null; + checks["no_url_collection"] = LearningPolicy.ParseAttempt(attempt.Replace("tls-gap.example.com","example.com/path?token=x"),"fixture","public") is null; + foreach (bool? directTls in new bool?[] { true, false, null }) + foreach (bool? proxyTls in new bool?[] { true, false, null }) + checks[$"pair_{directTls}_{proxyTls}"] = new ProxyProbe.PathComparison(directTls,proxyTls).ShouldProxy == (directTls == false && proxyTls == true); + var budget = new LearningProbeBudget(); + checks["four_concurrent_probes"] = Enumerable.Range(0,4).All(i=>budget.TryEnter("target"+i,100_000)); + checks["fifth_probe_bounded"] = !budget.TryEnter("fifth",100_000); + budget.Exit(); + checks["duplicate_suppressed"] = !budget.TryEnter("target0",100_001); + checks["free_slot_available"] = budget.TryEnter("fifth",100_001); + for(var i=0;i<4;i++) budget.Exit(); + checks["target_rechecked_after_cooldown"] = budget.TryEnter("target0",130_001); + budget.Exit(); + NetworkLearningLeaseSelfTest.AddChecks(checks); + var rate = new LearningProbeBudget(); + checks["sixty_per_minute"] = Enumerable.Range(0,60).All(i=>{ var allowed=rate.TryEnter("r"+i,100_000); if(allowed) rate.Exit(); return allowed; }); + checks["rate_limit_enforced"] = !rate.TryEnter("overflow",100_001); + checks["rate_window_recovers"] = rate.TryEnter("new",160_001); + foreach (var host in new[] { "127.0.0.1", "100.100.1.1", "192.168.1.1", "169.254.169.254", "::1", "::ffff:127.0.0.1", "203.0.113.1" }) + checks["nonpublic_ip_" + host] = !LearningPolicy.Allowed("ip", host); + foreach (var host in new[] { "192.168.50.111", "a.local", "a.invalid", "x.toplc.cn", "a.com/path", "a.com?secret=1", "bad_.com", "-bad.com" }) + checks["unsafe_domain_" + host] = !LearningPolicy.Allowed("domain", host); + checks["public_ip_allowed"] = LearningPolicy.Allowed("ip", "8.8.8.8"); + var direct = LearningPolicy.DirectFirst(baseConfig); + checks["new_network_removes_shared_forcing"] = !direct.Contains("openai.com") && direct.Contains("category-ads-all"); + var root = JsonNode.Parse(direct)!; + checks["private_and_default_stay_direct"] = root["routing"]!["rules"]![0]!["outboundTag"]!.GetValue() == "direct" + && root["routing"]!["rules"]!.AsArray().Last()!["outboundTag"]!.GetValue() == "direct"; + RoutingManifest Rules(string target) => new() { Contract = 1, Mode = "direct_first_candidates", Revision = new string('a',64), + Rules = [new RoutingTarget { TargetType = "domain", Target = target, MatchMode = "exact" }] }; + var verified = LearningPolicy.Merge(direct, Rules("learn.example.com")); + checks["confirmed_exact_only"] = verified.Contains("full:learn.example.com") && !verified.Contains("domain:learn.example.com"); + checks["only_verified_tcp443_is_proxied"] = JsonNode.Parse(verified)!["routing"]!["rules"]![1]!["port"]!.GetValue() == "443" + && JsonNode.Parse(verified)!["routing"]!["rules"]![1]!["network"]!.GetValue() == "tcp"; + checks["private_precedes_learned"] = JsonNode.Parse(verified)!["routing"]!["rules"]![0]!["ip"]![0]!.GetValue() == "geoip:private"; + checks["expiry_restores_direct"] = !LearningPolicy.Merge(verified, new() { Contract=1, Revision=new string('b',64) }).Contains("learn.example.com"); + checks["network_change_restores_direct"] = !LearningPolicy.DirectFirst(verified).Contains("learn.example.com"); + checks["unsafe_manifest_rejected"] = Throws(() => LearningPolicy.Merge(direct, Rules("vpn.toplc.cn"))); + checks["invalid_manifest_contract_rejected"] = Throws(() => LearningPolicy.Merge(direct, new() { Contract=99, Revision=new string('a',64) })); + var runtime = JsonNode.Parse(TunConfigBuilder.Build(direct, "Ethernet", true, includeTun:false, routingApiPort:18090, learningProbePort:18091))!; + checks["info_in_memory_access_disabled"] = runtime["log"]!["loglevel"]!.GetValue() == "info" && runtime["log"]!["access"]!.GetValue() == "none"; + checks["probe_loopback_only"] = runtime["inbounds"]![0]!["listen"]!.GetValue() == "127.0.0.1"; + checks["probe_forced_proxy_after_private_guard"] = runtime["routing"]!["rules"]![0]!["outboundTag"]!.GetValue() == "block" + && runtime["routing"]!["rules"]![1]!["outboundTag"]!.GetValue() == "proxy"; + checks["no_tun_in_test"] = runtime["inbounds"]!.AsArray().All(x => x!["protocol"]!.GetValue() != "tun"); + var both = JsonNode.Parse(TunConfigBuilder.Build(direct,"Ethernet",true,includeTun:false,learningProbePort:18091,directProbePort:18092))!; + var directInbound = both["inbounds"]!.AsArray().Single(x=>x!["tag"]!.GetValue()=="ucvl-direct-probe")!; + checks["direct_probe_loopback_only"] = directInbound["listen"]!.GetValue() == "127.0.0.1"; + checks["direct_probe_no_sniff"] = directInbound["sniffing"] is null; + var directOutbound = both["outbounds"]!.AsArray().Single(x=>x!["tag"]!.GetValue()=="ucvl-learning-direct")!; + checks["direct_probe_binds_physical"] = directOutbound["streamSettings"]!["sockopt"]!["interface"]!.GetValue() == "Ethernet"; + checks["direct_probe_not_learned_route"] = both["routing"]!["rules"]![0]!["outboundTag"]!.GetValue() == "block" && both["routing"]!["rules"]![1]!["outboundTag"]!.GetValue() == "ucvl-learning-direct"; + var report = new { scope="isolated policy tests; no current core or OS networking changed", passed=checks.Values.All(x=>x), checks }; + File.WriteAllText(Path.Combine(AppContext.BaseDirectory,"learning-self-test.json"), JsonSerializer.Serialize(report,new JsonSerializerOptions{WriteIndented=true})); + return report.passed ? 0 : 31; + } +} diff --git a/windows/LearningStore.cs b/windows/LearningStore.cs new file mode 100644 index 0000000..0e8c537 --- /dev/null +++ b/windows/LearningStore.cs @@ -0,0 +1,125 @@ +using System.Net; +using System.Text.Json; + +namespace UCVL.VPNPlus; + +internal static class LearningStore +{ + private static readonly object Sync = new(); + private static readonly Dictionary> Failures = new(StringComparer.OrdinalIgnoreCase); + private static readonly TimeSpan FailureWindow = TimeSpan.FromMinutes(5); + private static readonly TimeSpan LocalRuleLifetime = TimeSpan.FromDays(7); + + private sealed class LearnedTarget + { + public string TargetType { get; init; } = "domain"; + public string Target { get; init; } = ""; + public DateTimeOffset CreatedAt { get; init; } + public DateTimeOffset ExpiresAt { get; init; } + } + + internal static bool RecordFailureAndLearn(LearningObservation observation) + { + if (!IsAllowed(observation.TargetType, observation.Target)) return false; + lock (Sync) + { + var targets = LoadUnsafe(); + var now = DateTimeOffset.UtcNow; + if (targets.Any(item => + item.ExpiresAt > now + && item.TargetType == observation.TargetType + && string.Equals(item.Target, observation.Target, StringComparison.OrdinalIgnoreCase))) + { + return false; + } + + var key = $"{observation.TargetType}:{observation.Target}"; + if (!Failures.TryGetValue(key, out var queue)) + { + queue = new Queue(); + Failures[key] = queue; + } + while (queue.Count > 0 && now - queue.Peek() > FailureWindow) queue.Dequeue(); + queue.Enqueue(now); + if (queue.Count < 3) return false; + + queue.Clear(); + targets.RemoveAll(item => item.ExpiresAt <= now); + targets.Add(new LearnedTarget + { + TargetType = observation.TargetType, + Target = observation.Target, + CreatedAt = now, + ExpiresAt = now + LocalRuleLifetime, + }); + SaveUnsafe(targets); + return true; + } + } + + internal static IReadOnlyList<(string TargetType, string Target)> GetActiveTargets() + { + lock (Sync) + { + var now = DateTimeOffset.UtcNow; + var targets = LoadUnsafe(); + var active = targets.Where(item => item.ExpiresAt > now && IsAllowed(item.TargetType, item.Target)).ToList(); + if (active.Count != targets.Count) SaveUnsafe(active); + return active.Select(item => (item.TargetType, item.Target)).ToList(); + } + } + + private static List LoadUnsafe() + { + try + { + if (!File.Exists(AppPaths.LearnedRoutesFile)) return []; + return JsonSerializer.Deserialize>(File.ReadAllText(AppPaths.LearnedRoutesFile)) ?? []; + } + catch (Exception exception) + { + AppPaths.WriteError(exception); + return []; + } + } + + private static void SaveUnsafe(List targets) + { + AppPaths.EnsureDirectory(); + File.WriteAllText(AppPaths.LearnedRoutesFile, JsonSerializer.Serialize(targets)); + } + + private static bool IsAllowed(string targetType, string target) + { + if (targetType == "ip") + { + return IPAddress.TryParse(target, out var address) + && !IPAddress.IsLoopback(address) + && !IsPrivate(address); + } + if (targetType != "domain") return false; + var domain = target.Trim().TrimEnd('.').ToLowerInvariant(); + if (!domain.Contains('.') || domain is "toplc.cn" or "ucvl.cn" or "ucvl.net" or "localhost") return false; + return !domain.EndsWith(".local", StringComparison.Ordinal) + && !domain.EndsWith(".toplc.cn", StringComparison.Ordinal) + && !domain.EndsWith(".ucvl.cn", StringComparison.Ordinal) + && !domain.EndsWith(".ucvl.net", StringComparison.Ordinal); + } + + private static bool IsPrivate(IPAddress address) + { + if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) + { + var bytes = address.GetAddressBytes(); + return bytes[0] == 10 + || bytes[0] == 127 + || bytes[0] == 0 + || (bytes[0] == 169 && bytes[1] == 254) + || (bytes[0] == 172 && bytes[1] is >= 16 and <= 31) + || (bytes[0] == 192 && bytes[1] == 168) + || bytes[0] >= 224; + } + return address.IsIPv6LinkLocal || address.IsIPv6Multicast || address.Equals(IPAddress.IPv6Loopback) + || (address.GetAddressBytes()[0] & 0xfe) == 0xfc; + } +} diff --git a/windows/LearningTransportSelfTest.cs b/windows/LearningTransportSelfTest.cs new file mode 100644 index 0000000..a8e64ef --- /dev/null +++ b/windows/LearningTransportSelfTest.cs @@ -0,0 +1,66 @@ +using System.Diagnostics; +using System.Net; +using System.Net.Sockets; +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace UCVL.VPNPlus; + +internal static class LearningTransportSelfTest +{ + internal static async Task RunAsync() + { + var folder = Path.Combine(Path.GetTempPath(), "ucvl-learning-transport-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(folder); + var configPath = Path.Combine(folder, "fixture.json"); + Process? process = null; + var report = new Dictionary { ["scope"] = "isolated real proxy DoH + destination TLS; not TUN, business login or automatic fallback acceptance", + ["os_network_modified"] = false, ["production_observations_submitted"] = false }; + try + { + using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(75)); + using var api = new VpnApiClient(); + var token = TokenStore.Load(); + if (string.IsNullOrWhiteSpace(token)) throw new IOException("No app session available for read-only configuration."); + var profile = await api.GetProfileAsync(token, deadline.Token); + var node = profile.Nodes.First(); + report["node"] = node.Name; + var response = await api.GetConfigAsync(token, node.Slug, "smart", deadline.Token); + var config = LearningPolicy.DirectFirst(response.GetRuntimeConfigJson()); + var addresses = new List(); + foreach (var host in TunConfigBuilder.GetProxyServerHosts(config)) addresses.AddRange(await Dns.GetHostAddressesAsync(host, deadline.Token)); + var physical = TunRouting.GetPhysicalNetwork(addresses); + using var reservation = new TcpListener(IPAddress.Loopback, 0); + reservation.Start(); + var port = ((IPEndPoint)reservation.LocalEndpoint).Port; + reservation.Stop(); + var root = JsonNode.Parse(config)!.AsObject(); + root["inbounds"] = new JsonArray(); + root = JsonNode.Parse(TunConfigBuilder.Build(root.ToJsonString(), physical.InterfaceName, + includeLocalLearning: false, includeTun: false, learningProbePort: port))!.AsObject(); + root["log"] = new JsonObject { ["loglevel"] = "none", ["access"] = "none" }; + File.WriteAllText(configPath, root.ToJsonString()); + var start = new ProcessStartInfo(Path.Combine(AppContext.BaseDirectory, "xray", "xray.exe")) { + UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true }; + foreach (var arg in new[] { "run", "-c", configPath }) start.ArgumentList.Add(arg); + process = Process.Start(start)!; + _ = process.StandardOutput.ReadToEndAsync(); _ = process.StandardError.ReadToEndAsync(); + await Task.Delay(900, deadline.Token); + var checks = new Dictionary(); + foreach (var target in new[] { "www.google.com", "chatgpt.com" }) + checks[target] = await ProxyProbe.ProbeTlsAsync(new() { TargetType="domain", Target=target, Port=443, Network="tcp" }, port, deadline.Token) == true; + checks["private_destination_rejected"] = await ProxyProbe.ProbeTlsAsync(new() { TargetType="ip", Target="192.168.50.111", Port=443, Network="tcp" }, port, deadline.Token) is null; + report["checks"] = checks; + report["passed"] = checks.Values.All(value => value); + return checks.Values.All(value => value) ? 0 : 32; + } + catch (Exception error) { report["error_type"] = error.GetType().Name; report["passed"] = false; return 32; } + finally + { + if (process is not null) { try { if (!process.HasExited) process.Kill(true); await process.WaitForExitAsync(); } finally { process.Dispose(); } } + if (File.Exists(configPath)) File.Delete(configPath); + Directory.Delete(folder); + File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "learning-transport-self-test.json"), JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented=true })); + } + } +} diff --git a/windows/MainForm.Chrome.cs b/windows/MainForm.Chrome.cs new file mode 100644 index 0000000..6659c33 --- /dev/null +++ b/windows/MainForm.Chrome.cs @@ -0,0 +1,51 @@ +namespace UCVL.VPNPlus; + +internal sealed partial class MainForm +{ + private WindowChrome? _windowChrome; + internal WindowChrome? WindowChromeForTest => _windowChrome; + + // Remove the native caption before HWND creation, not only after its first + // style/paint messages. This avoids a transient second caption at startup. + protected override CreateParams CreateParams + { + get + { + var parameters = base.CreateParams; + parameters.Style = unchecked((int)ChromeNative.ClientChromeStyle(parameters.Style)); + return parameters; + } + } + + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + LayoutBrandHeader(); + CenterCards(); + LayoutDashboard(); + } + + // Explicit title/tray Exit and installer IPC share the graceful exit path. + private void InitializeWindowChrome(Panel header) + { + if (_windowChrome is not null) return; + _windowChrome = new WindowChrome(this, header, RequestExit); + _windowChrome.SetLoginMode(true); + } + + private void LayoutWindowChrome() => _windowChrome?.LayoutButtons(); + + // Minimize is a normal taskbar state, never Hide() or a disconnect. Avoid + // presenting a second, tray-only entry while the taskbar owns restoration. + private void UpdateTaskbarPresentation() + { + if (_exitResourcesDisposed) return; + _notifyIcon.Visible = ShouldShowTrayIcon(WindowState, _preview || _uiOnly || _exiting); + } + + internal static bool ShouldShowTrayIcon(FormWindowState state, bool suppressed) => + !suppressed && state != FormWindowState.Minimized; + + internal bool MinimizedToTaskbarForTest => WindowState == FormWindowState.Minimized + && ShowInTaskbar && Visible && !_notifyIcon.Visible && !_exiting; +} diff --git a/windows/MainForm.Dashboard.cs b/windows/MainForm.Dashboard.cs new file mode 100644 index 0000000..58f7223 --- /dev/null +++ b/windows/MainForm.Dashboard.cs @@ -0,0 +1,373 @@ +using System.Text.Json; + +namespace UCVL.VPNPlus; + +internal sealed partial class MainForm +{ + private readonly BadgeLabel _identityBadge = new(); + private readonly BadgeLabel _scheduleBadge = new(); + private readonly Label _sampleLabel = new(); + private readonly Label _uploadLegend = new(); + private readonly Label _downloadLegend = new(); + private readonly Label _dailyUploadLegend = new(), _dailyDownloadLegend = new(); + private readonly Label _historyStatus = new(); + private readonly ReadOnlyModeLabel _routeReadOnly = new(); + private readonly ComboBox _historyRangeCombo = new(); + private readonly Label _footerHint = new(); + private readonly Label _footerPoem = new(); + private readonly PictureBox _footerCompanyLogo = new(); + private readonly Label _footerCompanySite = new(); + private readonly CardPanel _nodeCard = new(), _modeCard = new(), _trafficCard = new(), _dailyCard = new(); + private readonly ScenicPanel _footer = new() { FooterArtwork = true }; + private readonly ScenicPanel _dashboardBody = new(); + private readonly VScrollBar _dashboardScrollBar = new(); + private readonly MetricCard _usageMetric = new("本期代理流量", DashboardIcon.Database); + private readonly MetricCard _uploadMetric = new("上传速度", DashboardIcon.Upload); + private readonly MetricCard _downloadMetric = new("下载速度", DashboardIcon.Download); + private readonly MetricCard _sessionMetric = new("本次代理流量", DashboardIcon.Document); + private readonly DashboardGlyph _nodeIcon = new(DashboardIcon.Server), _modeIcon = new(DashboardIcon.Settings); + private readonly DashboardGlyph _trafficIcon = new(DashboardIcon.Chart), _dailyIcon = new(DashboardIcon.History); + private readonly Label _trafficHeading = new(), _dailyHeading = new(); + private bool _layingOutDashboard; + + private void BuildDashboardView() + { + _dashboardView.Dock = DockStyle.Fill; + _dashboardView.BackColor = Brand.Surface; + _dashboardView.AutoScroll = false; + _dashboardView.Visible = false; + _dashboardView.Resize += (_, _) => LayoutDashboard(); + _content.Controls.Add(_dashboardView); + _dashboardBody.BackColor = Brand.Surface; + _dashboardView.Controls.Add(_dashboardBody); + _dashboardView.Controls.Add(_dashboardScrollBar); + _dashboardScrollBar.AccessibleName = "主界面垂直滚动"; + _dashboardScrollBar.ValueChanged += (_, _) => _dashboardBody.Top = -_dashboardScrollBar.Value; + _dashboardView.MouseWheel += DashboardMouseWheel; + _dashboardBody.MouseWheel += DashboardMouseWheel; + ConfigureLabel(_welcomeLabel, "", Brand.Font(15, FontStyle.Bold), Brand.Navy); + ConfigureLabel(_accountLabel, "", Brand.Font(9.5f), Brand.Muted); + ConfigureLabel(_identityBadge, "", Brand.Font(8.5f), Brand.RoyalBlue); + ConfigureLabel(_scheduleBadge, "AI 自动调度", Brand.Font(8, FontStyle.Bold), Brand.RoyalBlue); + foreach (var badge in new[] { _identityBadge, _scheduleBadge }) + { + badge.BackColor = Color.FromArgb(226, 239, 255); + badge.TextAlign = ContentAlignment.MiddleCenter; + } + ConfigureSecondaryButton(_logoutButton, "退出账号", Point.Empty, new(104, 34)); + _logoutButton.ForeColor = Brand.RoyalBlue; + _logoutButton.Click += async (_, _) => await LogoutAsync(); + _dashboardBody.Controls.AddRange([_welcomeLabel, _accountLabel, _identityBadge, _logoutButton]); + + ConfigureLabel(_statusTitle, "未连接", Brand.Font(17, FontStyle.Bold), Brand.Text); + ConfigureLabel(_statusDetail, "点击连接,自动选择工作节点", Brand.Font(9.5f), Brand.Muted); + _statusDot.ForeColor = Brand.Muted; + _statusCard.ScenicStatus = true; + _nodeCard.AccentBar = _modeCard.AccentBar = true; + _trafficCard.MetricBand = _dailyCard.MetricBand = true; + ConfigurePrimaryButton(_connectButton, "连接", Point.Empty, new(130, 42)); + _connectButton.Click += async (_, _) => + { + if (!_busy && !_wantConnected && !_handoverOperating) + _tailnetPreference.ResetForUserConnect(); + await ToggleConnectionAsync(); + }; + _statusCard.Controls.AddRange([_statusDot, _statusTitle, _statusDetail, _connectButton]); + ConfigureLabel(_nodeHeading, "当前工作节点", Brand.Font(9), Brand.Text); + ConfigureLabel(_routeHeading, "代理模式", Brand.Font(9), Brand.Text); + ConfigureLabel(_currentNodeLabel, "连接后自动分配", Brand.Font(12, FontStyle.Bold), Brand.RoyalBlue); + _nodeCard.Controls.AddRange([_nodeIcon, _nodeHeading, _currentNodeLabel, _scheduleBadge]); + BuildConnectionSelection(); + ConfigureCombo(_routeCombo, Point.Empty, new(220, 30)); + _routeCombo.BackColor = Color.White; + _routeCombo.AccessibleName = "代理模式(连接时不可更改)"; + _routeReadOnly.Visible = false; + _modeCard.Controls.AddRange([_modeIcon, _routeHeading, _routeCombo, _routeReadOnly]); + + ConfigureLabel(_trafficHeading, "实时网速", Brand.Font(9.5f, FontStyle.Bold), Brand.Text); + ConfigureLabel(_dailyHeading, "代理流量", Brand.Font(9.5f, FontStyle.Bold), Brand.Text); + ConfigureLabel(_sampleLabel, "仅代理流量 · 近 5 分钟", Brand.Font(7.5f), Brand.Muted); + _sampleLabel.TextAlign = ContentAlignment.MiddleRight; + ConfigureLabel(_uploadLegend, "● 上传 —", Brand.Font(8), Brand.RoyalBlue); + ConfigureLabel(_downloadLegend, "● 下载 —", Brand.Font(8), Brand.Cyan); + ConfigureLabel(_dailyUploadLegend, "● 上传", Brand.Font(8), Brand.RoyalBlue); + ConfigureLabel(_dailyDownloadLegend, "● 下载", Brand.Font(8), Brand.Cyan); + ConfigureLabel(_historyStatus, "套餐全部设备 · 按天统计", Brand.Font(7), Brand.Muted); + _historyStatus.AutoEllipsis = true; + _historyStatus.TextAlign = ContentAlignment.MiddleRight; + _dailyChart.HistoryChanged += () => { _historyStatus.Text = _dailyChart.StatusText; _historyStatus.AccessibleDescription = _dailyChart.DetailText; }; + _trafficCard.Controls.AddRange([_trafficIcon, _trafficHeading, _sampleLabel, _trafficChart, _uploadLegend, _downloadLegend]); + _dailyCard.Controls.AddRange([_dailyIcon, _dailyHeading, _dailyChart, _dailyUploadLegend, _dailyDownloadLegend]); + ConfigureCombo(_historyRangeCombo, Point.Empty, new(120, 28)); + _historyRangeCombo.BackColor = Color.White; + _historyRangeCombo.Font = Brand.Font(8.5f); + _historyRangeCombo.DrawMode = DrawMode.OwnerDrawFixed; + _historyRangeCombo.DrawItem += (_, e) => + { + if (e.Index < 0) return; + var highlight = _historyRangeCombo.DroppedDown && (e.State & DrawItemState.Selected) != 0; + using var fill = new SolidBrush(highlight ? Brand.PaleBlue : Color.White); + e.Graphics.FillRectangle(fill, e.Bounds); + TextRenderer.DrawText(e.Graphics, _historyRangeCombo.Items[e.Index]?.ToString() ?? "", _historyRangeCombo.Font, + e.Bounds, Brand.Text, TextFormatFlags.VerticalCenter | TextFormatFlags.Left | TextFormatFlags.EndEllipsis); + e.DrawFocusRectangle(); + }; + _historyRangeCombo.AccessibleName = "代理流量历史时间范围"; + _historyRangeCombo.Items.AddRange(UsageHistoryPeriod.All); + _historyRangeCombo.SelectedItem = UsageHistoryPeriod.All[2]; + _historyRangeCombo.SelectedIndexChanged += (_, _) => + { + if (_historyRangeCombo.SelectedItem is UsageHistoryPeriod period) _dailyChart.SetPeriod(period); + }; + _dailyCard.Controls.AddRange([_historyRangeCombo, _historyStatus]); + ConfigureLabel(_planLabel, "", Brand.Font(8.5f), Brand.Muted); + ConfigureLabel(_expiryLabel, "", Brand.Font(8.5f), Brand.Muted); + ConfigureLabel(_footerHint, "仅限内部使用,不作商业使用。", Brand.Font(9, FontStyle.Bold), Brand.DeepBlue); + _footerHint.TextAlign = ContentAlignment.MiddleRight; + ConfigureLabel(_footerPoem, "— 科技守护连接 · 让世界更近 —", new Font("KaiTi", 11.5f), Brand.Muted); + _footerPoem.TextAlign = ContentAlignment.MiddleRight; + _footerCompanyLogo.Image = LoadCompanyLogo(); + _footerCompanyLogo.SizeMode = PictureBoxSizeMode.Zoom; + ConfigureLabel(_footerCompanySite, "vpn.toplc.cn", Brand.Font(8), Brand.Muted); + _footerCompanyLogo.BackColor = Color.Transparent; + _footer.Controls.AddRange([_planLabel, _expiryLabel, _footerHint, _footerPoem, _footerCompanyLogo, _footerCompanySite]); + foreach (var card in new CardPanel[] { _statusCard, _nodeCard, _modeCard, _trafficCard, _dailyCard }) + { + card.BackColor = Color.White; + _dashboardBody.Controls.Add(card); + } + foreach (var metric in new[] { _usageMetric, _sessionMetric, _uploadMetric, _downloadMetric }) metric.Embedded = true; + _trafficCard.Controls.AddRange([_uploadMetric, _downloadMetric]); + _dailyCard.Controls.AddRange([_usageMetric, _sessionMetric]); + _dashboardBody.Controls.Add(_footer); + foreach (var label in new[] { _welcomeLabel, _accountLabel, _statusTitle, _statusDetail, _currentNodeLabel, _planLabel, _expiryLabel }) + { + label.AutoEllipsis = true; + label.TextAlign = ContentAlignment.MiddleLeft; + } + _sessionMetric.SetBytes(0, hint: "本次连接累计"); + DisplayTraffic(null, null, "仅代理流量 · 近 5 分钟"); + LayoutDashboard(); + } + + private void DisplayTraffic(double? upload, double? download, string sampling) + { + _uploadMetric.SetBytes(upload, speed: true); + _downloadMetric.SetBytes(download, speed: true); + _sampleLabel.Text = sampling; + _uploadLegend.Text = upload.HasValue ? $"● 上传 {FormatBytes((long)upload.Value)}/s" : "● 上传 —"; + _downloadLegend.Text = download.HasValue ? $"● 下载 {FormatBytes((long)download.Value)}/s" : "● 下载 —"; + } + + private void DashboardMouseWheel(object? sender, MouseEventArgs e) + { + if (!_dashboardScrollBar.Visible || e is HandledMouseEventArgs { Handled: true }) return; + var limit = Math.Max(0, _dashboardScrollBar.Maximum - _dashboardScrollBar.LargeChange + 1); + _dashboardScrollBar.Value = Math.Clamp(_dashboardScrollBar.Value - Math.Sign(e.Delta) * ScaleLogical(54), 0, limit); + if (e is HandledMouseEventArgs handled) handled.Handled = true; + } + + private void LayoutDashboard() + { + if (_layingOutDashboard || _dashboardView.ClientSize.Width <= 0) return; + _layingOutDashboard = true; + Control[] layoutContainers = [_dashboardView, _dashboardBody, _statusCard, _nodeCard, _modeCard, _trafficCard, _dailyCard, _footer]; + foreach (var container in layoutContainers) container.SuspendLayout(); + try + { + var previousScroll = _dashboardScrollBar.Value; + // Explicit vertical canvas: card reflow must never retain a previous + // horizontal extent or reset the user's scroll offset on repaint. + var viewport = _dashboardView.ClientSize; + var layout = DashboardLayout.Calculate(viewport, DeviceDpi); + _dashboardScrollBar.Visible = layout.ContentHeight > viewport.Height; + _dashboardScrollBar.Bounds = new Rectangle(viewport.Width - ScaleLogical(17), 0, ScaleLogical(17), viewport.Height); + if (_dashboardScrollBar.Visible) + layout = DashboardLayout.Calculate(new Size(viewport.Width - ScaleLogical(17), viewport.Height), DeviceDpi); + void Place(Control c, Rectangle r) { c.Bounds = r; } + Rectangle R(int x, int y, int w, int h) => new(ScaleLogical(x), ScaleLogical(y), ScaleLogical(w), ScaleLogical(h)); + Place(_welcomeLabel, layout.WelcomeLabel); Place(_accountLabel, layout.AccountLabel); + Place(_identityBadge, layout.IdentityBadge); Place(_logoutButton, layout.LogoutButton); + Place(_statusCard, layout.StatusCard); Place(_nodeCard, layout.NodeCard); Place(_modeCard, layout.ModeCard); + var metrics = new[] { _usageMetric, _uploadMetric, _downloadMetric, _sessionMetric }; + for (var i = 0; i < 4; i++) Place(metrics[i], layout.Metrics[i]); + Place(_trafficCard, layout.TrafficCard); Place(_dailyCard, layout.DailyCard); Place(_footer, layout.Footer); + + _statusDot.Bounds = R(24, 15, 42, 46); + _connectButton.Bounds = new(_statusCard.Width - ScaleLogical(148), ScaleLogical(17), ScaleLogical(130), ScaleLogical(42)); + var textWidth = _connectButton.Left - ScaleLogical(100); + _statusTitle.Bounds = new(ScaleLogical(84), ScaleLogical(10), textWidth, ScaleLogical(33)); + _statusDetail.Bounds = new(ScaleLogical(85), ScaleLogical(43), textWidth, ScaleLogical(25)); + _nodeIcon.Bounds = R(26, 23, 24, 24); _modeIcon.Bounds = R(26, 23, 24, 24); + _nodeHeading.Bounds = new(ScaleLogical(54), ScaleLogical(9), Math.Max(0, _nodeCard.Width - ScaleLogical(205)), ScaleLogical(23)); + _connectionModeCombo.Bounds = new(_nodeCard.Width - ScaleLogical(144), ScaleLogical(6), ScaleLogical(130), ScaleLogical(28)); + _manualNodeCombo.Bounds = new(ScaleLogical(54), ScaleLogical(34), _nodeCard.Width - ScaleLogical(68), ScaleLogical(28)); + var badgeWidth = ScaleLogical(88); + var badgeX = _nodeCard.Width - badgeWidth - ScaleLogical(14); + _currentNodeLabel.Bounds = new(ScaleLogical(54), ScaleLogical(34), + _selectionUiConnected ? _nodeCard.Width - ScaleLogical(68) : badgeX - ScaleLogical(60), ScaleLogical(27)); + _scheduleBadge.Bounds = new(badgeX, ScaleLogical(35), badgeWidth, ScaleLogical(23)); + _routeHeading.Bounds = new(ScaleLogical(54), ScaleLogical(8), _modeCard.Width - ScaleLogical(70), ScaleLogical(22)); + _routeCombo.Bounds = new(ScaleLogical(54), ScaleLogical(33), _modeCard.Width - ScaleLogical(70), ScaleLogical(28)); + _routeReadOnly.Bounds = new(_routeCombo.Left, _routeCombo.Top, _routeCombo.Width, ScaleLogical(28)); + _trafficIcon.Bounds = R(15, 10, 20, 20); _dailyIcon.Bounds = R(15, 10, 20, 20); + _trafficHeading.Bounds = R(42, 8, 92, 26); + _sampleLabel.Bounds = new(ScaleLogical(132), ScaleLogical(10), _trafficCard.Width - ScaleLogical(146), ScaleLogical(22)); + _dailyHeading.Bounds = new(ScaleLogical(42), ScaleLogical(8), _dailyCard.Width - ScaleLogical(180), ScaleLogical(26)); + _historyRangeCombo.Bounds = new(_dailyCard.Width - ScaleLogical(140), ScaleLogical(10), ScaleLogical(124), ScaleLogical(26)); + _trafficChart.Bounds = new(ScaleLogical(13), ScaleLogical(132), _trafficCard.Width - ScaleLogical(26), ScaleLogical(106)); + _dailyChart.Bounds = new(ScaleLogical(13), ScaleLogical(132), _dailyCard.Width - ScaleLogical(26), ScaleLogical(106)); + var legendWidth = (_trafficCard.Width - ScaleLogical(40)) / 2; + _uploadLegend.Bounds = new(ScaleLogical(20), ScaleLogical(248), legendWidth, ScaleLogical(19)); + _downloadLegend.Bounds = new(ScaleLogical(20) + legendWidth, ScaleLogical(248), legendWidth, ScaleLogical(19)); + _dailyUploadLegend.Bounds = new(ScaleLogical(20), ScaleLogical(248), ScaleLogical(52), ScaleLogical(19)); + _dailyDownloadLegend.Bounds = new(ScaleLogical(76), ScaleLogical(248), ScaleLogical(52), ScaleLogical(19)); + _historyStatus.Bounds = new(ScaleLogical(134), ScaleLogical(248), _dailyCard.Width - ScaleLogical(148), ScaleLogical(19)); + _planLabel.Bounds = R(0, 4, 300, 26); + _expiryLabel.Bounds = R(306, 4, 132, 26); + _footerCompanyLogo.Bounds = R(0, 34, 32, 34); + _footerCompanySite.Bounds = R(0, 41, 220, 22); + _footerHint.Visible = true; + _footerHint.Bounds = new(ScaleLogical(232), ScaleLogical(39), Math.Max(1, _footer.Width - ScaleLogical(232)), ScaleLogical(28)); + _footerPoem.Visible = !layout.Compact && _footer.Width >= ScaleLogical(780); + _footerPoem.Bounds = new(_footer.Width - ScaleLogical(322), ScaleLogical(5), ScaleLogical(322), ScaleLogical(29)); + _dashboardBody.Size = new Size(layout.StatusCard.Right + ScaleLogical(20), layout.ContentHeight); + _dashboardScrollBar.Maximum = Math.Max(0, layout.ContentHeight - 1); + _dashboardScrollBar.LargeChange = Math.Max(1, viewport.Height); + _dashboardScrollBar.SmallChange = ScaleLogical(28); + _dashboardScrollBar.Value = Math.Clamp(previousScroll, 0, Math.Max(0, layout.ContentHeight - viewport.Height)); + _dashboardBody.Location = new Point(0, -_dashboardScrollBar.Value); + _dashboardScrollBar.BringToFront(); + } + finally + { + foreach (var container in layoutContainers.Reverse()) container.ResumeLayout(false); + _layingOutDashboard = false; + } + } + + // Isolated synthetic fixture: no stored account, core, system proxy, update query or installation. + internal static void RenderPreview() + { + using var form = new MainForm(preview: true) { Opacity = 0, ShowInTaskbar = false }; + form.Show(); + form.ShowDashboard(new Profile + { + DisplayName = "示例用户", Email = "demo@example.com", IdentityType = "employee", + Subscription = new SubscriptionInfo { Plan = "员工福利", UsedBytes = 17480516895, DeviceLimit = 3 }, + Nodes = [new NodeInfo { Name = "VPN003", Slug = "preview", Status = "online" }], + RouteModes = [new RouteModeInfo { Id = "smart", Name = "AI 智能代理" }], + UsageHistory = Enumerable.Range(0, 7).Select(i => new DailyUsage { Day = DateTime.Today.AddDays(i - 6).ToString("yyyy-MM-dd"), UploadBytes = new long[] { 14000000, 0, 0, 0, 3000000, 35000000, 196000000 }[i], DownloadBytes = new long[] { 28000000, 0, 0, 0, 26000000, 158000000, 126000000 }[i] }).ToList() + }); + form._refreshTimer.Stop(); + var fixtureRanges = UsageHistoryPeriod.All.ToDictionary(p => p.Key, p => new UsageHistorySeries + { + Bucket = p.Bucket, Note = p.Bucket == "hour" ? "演示数据 · 按上报入账小时;缺口为无明细" : "演示数据 · 月筛选为近30个自然日", + Points = Enumerable.Range(0, p.Count).Select(i => new UsageHistoryPoint + { + Time = p.Bucket == "hour" ? new DateTimeOffset(2026, 9, 9, 21, 0, 0, TimeSpan.FromHours(8)).AddHours(i - p.Count + 1).ToString("O") + : new DateOnly(2026, 9, 9).AddDays(i - p.Count + 1).ToString("yyyy-MM-dd"), + UploadBytes = p.Bucket == "hour" && i == 3 ? null : (long)((Math.Sin(i * .72) + 1.1) * 60_000_000), + DownloadBytes = p.Bucket == "hour" && i == 3 ? null : (long)((Math.Cos(i * .81) + 1.1) * 84_000_000) + }).ToList() + }); + form._currentNodeLabel.Text = "VPN003"; + form.SetConnectionState(true, "已安全连接", "VPN003 · AI 智能代理"); + form.DisplayTraffic(91975, 23357, "21:13:00 · 近 5 分钟"); + form._sessionMetric.SetBytes(130180710, hint: "本次连接累计"); + for (var i = 0; i < 60; i++) form._trafficChart.Add((i % 13 == 0 ? 72 : 8 + Math.Sin(i * 1.8) * 4) * 1024, + (i % 9 == 2 ? 130 : 10 + Math.Sin(i * 2.4) * 8) * 1024, DateTimeOffset.Now.AddSeconds((i - 59) * 5)); + form.LayoutBrandHeader(); form.LayoutDashboard(); + var checks = new Dictionary { ["geometry_56_viewport_dpi_cases"] = DashboardLayout.SelfTest() }; + foreach (var check in UsageHistorySeries.SelfTest()) checks[check.Key] = check.Value; + void Capture(string suffix) + { + form.PerformLayout(); form.LayoutDashboard(); Application.DoEvents(); + using var image = new Bitmap(form.Width, form.Height); + form.DrawToBitmap(image, new Rectangle(Point.Empty, image.Size)); + image.Save(Path.Combine(AppContext.BaseDirectory, $"preview-{GetDisplayVersion()}-{suffix}.png")); + } + Capture("dashboard"); + form._currentNodeName = NodePresentation.JinanName; + form._currentNodeLabel.Text = form._currentNodeName; + form.SetConnectionState(true, "已安全连接", form._currentNodeName + " · AI 智能代理"); + Capture("zero3-connected"); + checks["zero3_connected_name_fits"] = TextRenderer.MeasureText(form._currentNodeName, form._currentNodeLabel.Font).Width <= form._currentNodeLabel.Width; + checks["dashboard_controls_within_cards"] = form.DashboardControlsFit(); + checks["footer_slogan_displays_without_company_brand"] = !form._brandHeader.Controls.Contains(form._footerCompanyLogo) + && form._footerCompanyLogo.Parent == form._footer && !form._footerCompanyLogo.Visible; + checks["footer_slogan_text_has_no_url"] = form._footerCompanySite.Visible && form._footerCompanySite.Text == "智能连接 · 高效办公" + && !form._footerCompanySite.Text.Contains("vpn.", StringComparison.OrdinalIgnoreCase) + && !form._footerCompanySite.Text.Contains("://", StringComparison.OrdinalIgnoreCase); + checks["official_header_logo_preserved"] = form._brandHeader.Controls.OfType().Any(logo => logo.Visible && logo.Image is not null + && logo.SizeMode == PictureBoxSizeMode.Zoom && logo.Tag is Rectangle bounds && bounds == new Rectangle(20, 29, 62, 67) + && logo.Bounds == new Rectangle(form.ScaleLogical(20), form.ScaleLogical(29), form.ScaleLogical(62), form.ScaleLogical(67))); + checks["product_header_named_zonghengjia"] = form.Text == "纵横家" && form._brandHeader.Controls.OfType