Publish reviewed history-free open-source snapshot (2026-10-12)
This commit is contained in:
@@ -0,0 +1 @@
|
||||
|
||||
@@ -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("只读检查发现待人工复核项;未修改任何申请或订阅。")
|
||||
@@ -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}。"))
|
||||
|
||||
@@ -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 '已更新'}。"))
|
||||
@@ -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} 个订阅状态。")
|
||||
@@ -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}。内部员工免费,现有订阅不变。")
|
||||
@@ -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套餐及所有订阅不变。")
|
||||
@@ -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 已停止。")
|
||||
Reference in New Issue
Block a user