feat: add server managed auto updates
This commit is contained in:
1 parent
ba2e159cad
commit
5c7d341d9b
6 files changed
+466
-6
No files matched your search
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
@@ -13,8 +14,12 @@ from typing import Any, Callable
|
||||
from urllib.parse import urljoin, urlparse
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from cryptography.exceptions import InvalidSignature
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
|
||||
from douyin.core import path_config
|
||||
from douyin.core.version import VERSION
|
||||
from douyin.license.public_key import PUBLIC_KEY_PEM
|
||||
|
||||
|
||||
DEFAULT_INSTALLER_ARGS = (
|
||||
@@ -23,6 +28,7 @@ DEFAULT_INSTALLER_ARGS = (
|
||||
"/NORESTART",
|
||||
"/CURRENTUSER",
|
||||
)
|
||||
DEFAULT_UPDATE_MANIFEST_URL = "http://103.236.55.219:18100/api/v1/update/manifest"
|
||||
|
||||
|
||||
class UpdateError(RuntimeError):
|
||||
@@ -40,6 +46,7 @@ class UpdateSettings:
|
||||
require_sha256: bool = True
|
||||
require_https: bool = True
|
||||
allow_cross_origin: bool = False
|
||||
require_signed_manifest: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -121,6 +128,33 @@ def _as_installer_args(value: Any) -> tuple[str, ...]:
|
||||
return DEFAULT_INSTALLER_ARGS
|
||||
|
||||
|
||||
def _canonical_payload_bytes(payload: dict[str, Any]) -> bytes:
|
||||
return json.dumps(
|
||||
payload,
|
||||
ensure_ascii=False,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
).encode("utf-8")
|
||||
|
||||
|
||||
def _verify_manifest_signature(manifest: dict[str, Any]) -> None:
|
||||
signature_raw = manifest.get("signature")
|
||||
if not isinstance(signature_raw, str) or not signature_raw.strip():
|
||||
raise UpdateError("manifest 缺少签名")
|
||||
payload = dict(manifest)
|
||||
payload.pop("signature", None)
|
||||
try:
|
||||
signature = base64.b64decode(signature_raw.encode("ascii"), validate=True)
|
||||
public_key = serialization.load_pem_public_key(PUBLIC_KEY_PEM)
|
||||
public_key.verify(signature, _canonical_payload_bytes(payload))
|
||||
except InvalidSignature as exc:
|
||||
raise UpdateError("manifest 签名校验失败") from exc
|
||||
except UpdateError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise UpdateError(f"manifest 签名校验异常:{exc}") from exc
|
||||
|
||||
|
||||
def load_update_settings() -> UpdateSettings:
|
||||
cfg = _read_config()
|
||||
section = cfg.get("auto_update") if isinstance(cfg.get("auto_update"), dict) else {}
|
||||
@@ -129,8 +163,13 @@ def load_update_settings() -> UpdateSettings:
|
||||
or str(section.get("manifest_url", "") or "")
|
||||
or str(cfg.get("update_manifest_url", "") or "")
|
||||
).strip()
|
||||
using_default_manifest = False
|
||||
if not manifest_url and getattr(sys, "frozen", False):
|
||||
manifest_url = DEFAULT_UPDATE_MANIFEST_URL
|
||||
using_default_manifest = True
|
||||
env_enabled = os.environ.get("DOUYIN_AUTO_UPDATE_ENABLED")
|
||||
enabled = _to_bool(env_enabled, default=_to_bool(section.get("enabled"), False))
|
||||
enabled_default = True if using_default_manifest else _to_bool(section.get("enabled"), False)
|
||||
enabled = _to_bool(env_enabled, default=enabled_default)
|
||||
if os.environ.get("DOUYIN_DISABLE_AUTO_UPDATE", "").strip() == "1":
|
||||
enabled = False
|
||||
if not manifest_url:
|
||||
@@ -151,8 +190,9 @@ def load_update_settings() -> UpdateSettings:
|
||||
timeout_seconds=timeout_seconds,
|
||||
fail_closed=_to_bool(section.get("fail_closed"), True),
|
||||
require_sha256=_to_bool(section.get("require_sha256"), True),
|
||||
require_https=_to_bool(section.get("require_https"), True),
|
||||
require_https=_to_bool(section.get("require_https"), not using_default_manifest),
|
||||
allow_cross_origin=_to_bool(section.get("allow_cross_origin"), False),
|
||||
require_signed_manifest=_to_bool(section.get("require_signed_manifest"), using_default_manifest),
|
||||
)
|
||||
|
||||
|
||||
@@ -306,6 +346,8 @@ def perform_forced_update(
|
||||
|
||||
_validate_manifest_url(settings)
|
||||
manifest = fetch_manifest(settings.manifest_url, settings.timeout_seconds)
|
||||
if settings.require_signed_manifest:
|
||||
_verify_manifest_signature(manifest)
|
||||
latest_version = str(manifest.get("version", "") or "").strip()
|
||||
if not latest_version:
|
||||
raise UpdateError("manifest 缺少 version")
|
||||
|
||||
@@ -15,6 +15,9 @@ python -m license_server.manage --db data/app.db unbind DG-XXXX-XXXX-XXXX-XXXX-X
|
||||
GET /api/v1/health
|
||||
POST /api/v1/activate
|
||||
POST /api/v1/verify
|
||||
POST /api/v1/verify_license
|
||||
GET /api/v1/update/manifest
|
||||
GET /api/v1/update/download/{filename}
|
||||
GET /admin
|
||||
```
|
||||
|
||||
@@ -78,3 +81,26 @@ export DYGJ_LICENSE_ADMIN_TOKEN="$(cat secrets/admin_token.txt)"
|
||||
```
|
||||
|
||||
不要把管理员 token 放到 URL 里,避免进入浏览器历史、访问日志或截图。
|
||||
|
||||
## 自动更新
|
||||
|
||||
卡密后台同一个网站也负责发布客户端更新,不需要额外端口:
|
||||
|
||||
```text
|
||||
http://服务器IP:18100/admin
|
||||
```
|
||||
|
||||
登录后在“在线更新”区域上传新版安装包 `.exe`,填写版本号(例如 `3.3.4`)后点击“上传并发布”。服务端会:
|
||||
|
||||
- 保存安装包到 `data/updates/`
|
||||
- 自动计算安装包 SHA256
|
||||
- 生成 `/api/v1/update/manifest`
|
||||
- 使用服务端私钥给 manifest 签名
|
||||
|
||||
打包后的客户端默认读取:
|
||||
|
||||
```text
|
||||
http://103.236.55.219:18100/api/v1/update/manifest
|
||||
```
|
||||
|
||||
如果后台未发布更新,manifest 返回 `version=0.0.0`,客户端不会下载。发布高于客户端当前版本的安装包后,客户端启动时会下载、校验签名和 SHA256,然后启动安装器并退出旧进程。
|
||||
+138
-4
@@ -9,12 +9,13 @@ import time
|
||||
from html import escape
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import urljoin
|
||||
|
||||
from fastapi import FastAPI, Form, Request
|
||||
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response
|
||||
from fastapi import FastAPI, File, Form, Request, UploadFile
|
||||
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse, Response
|
||||
from pydantic import BaseModel
|
||||
|
||||
from license_server.core import LicenseActionResult, LicenseService
|
||||
from license_server.core import LicenseActionResult, LicenseService, UpdateManifest
|
||||
|
||||
|
||||
RATE_LIMIT_WINDOW_SECONDS = 60
|
||||
@@ -198,6 +199,56 @@ def _rate_limited(request: Request, scope: str, *, max_requests: int | None = No
|
||||
return False
|
||||
|
||||
|
||||
def _public_base_url(request: Request) -> str:
|
||||
configured = str(os.environ.get("DYGJ_LICENSE_PUBLIC_BASE_URL") or "").strip()
|
||||
if configured:
|
||||
return configured.rstrip("/")
|
||||
return str(request.base_url).rstrip("/")
|
||||
|
||||
|
||||
def _signed_update_manifest(service: LicenseService, request: Request) -> dict[str, Any]:
|
||||
manifest = service.load_update_manifest()
|
||||
if not manifest.enabled:
|
||||
payload: dict[str, Any] = {
|
||||
"enabled": False,
|
||||
"version": "0.0.0",
|
||||
"force": False,
|
||||
"message": "no update published",
|
||||
}
|
||||
payload["signature"] = service.sign_payload(payload)
|
||||
return payload
|
||||
|
||||
download_path = f"/api/v1/update/download/{manifest.filename}"
|
||||
payload = {
|
||||
"enabled": True,
|
||||
"version": manifest.version,
|
||||
"url": urljoin(_public_base_url(request) + "/", download_path.lstrip("/")),
|
||||
"filename": manifest.filename,
|
||||
"sha256": manifest.sha256,
|
||||
"force": manifest.force,
|
||||
"notes": manifest.notes,
|
||||
"published_at": manifest.published_at,
|
||||
}
|
||||
payload["signature"] = service.sign_payload(payload)
|
||||
return payload
|
||||
|
||||
|
||||
def _update_summary_html(manifest: UpdateManifest) -> str:
|
||||
status = "已开启" if manifest.enabled else "未发布/已关闭"
|
||||
sha = manifest.sha256[:12] + "..." if manifest.sha256 else "-"
|
||||
file_name = manifest.filename or "-"
|
||||
published = manifest.published_at or "-"
|
||||
return (
|
||||
"<div class='update-state'>"
|
||||
f"<b>{escape(status)}</b>"
|
||||
f"<span>版本:<code>{escape(manifest.version or '0.0.0')}</code></span>"
|
||||
f"<span>文件:<code>{escape(file_name)}</code></span>"
|
||||
f"<span>SHA256:<code>{escape(sha)}</code></span>"
|
||||
f"<span>发布时间:{escape(published)}</span>"
|
||||
"</div>"
|
||||
)
|
||||
|
||||
|
||||
def _admin_page(
|
||||
service: LicenseService,
|
||||
csrf_token: str,
|
||||
@@ -208,6 +259,8 @@ def _admin_page(
|
||||
stats = service.stats()
|
||||
card_rows = service.list_cards(limit=50)
|
||||
audit_rows = service.audit_logs(limit=30)
|
||||
update_manifest = service.load_update_manifest()
|
||||
update_html = _update_summary_html(update_manifest)
|
||||
created_rows = "".join(
|
||||
f"<li><code>{escape(card)}</code></li>" for card in (cards or [])
|
||||
)
|
||||
@@ -252,6 +305,7 @@ def _admin_page(
|
||||
.stat b {{ display: block; font-size: 28px; margin-top: 8px; }}
|
||||
section {{ background: #fff; border: 1px solid #e5e7eb; border-radius: 16px; padding: 18px; margin: 14px 0; box-shadow: 0 12px 30px rgba(15, 23, 42, .06); }}
|
||||
form.inline {{ display: grid; grid-template-columns: repeat(5, minmax(120px, 1fr)); gap: 10px; align-items: end; }}
|
||||
form.update {{ display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 10px; align-items: end; }}
|
||||
label {{ display: block; color: #475569; font-size: 13px; }}
|
||||
input {{ width: 100%; box-sizing: border-box; padding: 10px 12px; border: 1px solid #cbd5e1; border-radius: 10px; margin-top: 5px; }}
|
||||
button {{ padding: 10px 16px; cursor: pointer; border: 0; border-radius: 10px; background: #2563eb; color: white; font-weight: 700; }}
|
||||
@@ -266,7 +320,9 @@ def _admin_page(
|
||||
.status.revoked {{ background: #fee2e2; color: #991b1b; }}
|
||||
.msg {{ padding: 10px 12px; background: #ecfdf5; border: 1px solid #a7f3d0; border-radius: 8px; }}
|
||||
.cards {{ display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }}
|
||||
@media (max-width: 860px) {{ .grid, .cards, form.inline {{ grid-template-columns: 1fr; }} }}
|
||||
.update-state {{ display: flex; flex-wrap: wrap; gap: 10px 16px; padding: 12px; border-radius: 12px; background: #f8fafc; border: 1px solid #e2e8f0; margin-bottom: 12px; }}
|
||||
.help {{ margin-top: 8px; color: #64748b; font-size: 13px; }}
|
||||
@media (max-width: 860px) {{ .grid, .cards, form.inline, form.update {{ grid-template-columns: 1fr; }} }}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -315,6 +371,23 @@ def _admin_page(
|
||||
</form>
|
||||
</section>
|
||||
</div>
|
||||
<section>
|
||||
<h2>在线更新</h2>
|
||||
{update_html}
|
||||
<form class="update" method="post" action="/admin/update/publish" enctype="multipart/form-data">
|
||||
<input type="hidden" name="csrf_token" value="{csrf_attr}" />
|
||||
<label>新版本号 <input name="version" placeholder="例如 3.3.4" /></label>
|
||||
<label>说明 <input name="notes" placeholder="更新内容,可留空" /></label>
|
||||
<label>安装包 exe <input name="installer" type="file" accept=".exe" /></label>
|
||||
<label>强制更新 <input name="force" value="1" /></label>
|
||||
<button type="submit">上传并发布</button>
|
||||
</form>
|
||||
<form method="post" action="/admin/update/disable" style="margin-top:10px">
|
||||
<input type="hidden" name="csrf_token" value="{csrf_attr}" />
|
||||
<button class="secondary" type="submit">关闭更新</button>
|
||||
</form>
|
||||
<div class="help">客户端读取 <code>/api/v1/update/manifest</code>,manifest 会用服务端私钥签名,安装包下载后再做 SHA256 校验。</div>
|
||||
</section>
|
||||
<section>
|
||||
<h2>最近卡密</h2>
|
||||
<table>
|
||||
@@ -383,6 +456,26 @@ def create_app(
|
||||
return result_response(LicenseActionResult(False, "rate_limited", "请求过于频繁,请稍后再试"))
|
||||
return result_response(get_service().verify_license_doc(req.license))
|
||||
|
||||
@app.get("/api/v1/update/manifest")
|
||||
def update_manifest(request: Request) -> JSONResponse:
|
||||
return JSONResponse(_signed_update_manifest(get_service(), request))
|
||||
|
||||
@app.get("/api/v1/update/download/{filename}")
|
||||
def update_download(filename: str) -> Response:
|
||||
service = get_service()
|
||||
manifest = service.load_update_manifest()
|
||||
safe_name = Path(str(filename or "")).name
|
||||
if not manifest.enabled or safe_name != manifest.filename:
|
||||
return JSONResponse({"ok": False, "reason": "not_found"}, status_code=404)
|
||||
target = service.update_dir / manifest.filename
|
||||
if not target.exists():
|
||||
return JSONResponse({"ok": False, "reason": "file_missing"}, status_code=404)
|
||||
return FileResponse(
|
||||
target,
|
||||
media_type="application/octet-stream",
|
||||
filename=manifest.filename,
|
||||
)
|
||||
|
||||
@app.get("/admin")
|
||||
def admin(request: Request) -> Response:
|
||||
if not _admin_allowed(request, app.state.admin_token):
|
||||
@@ -490,6 +583,47 @@ def create_app(
|
||||
message=f"已解绑 {count} 台设备",
|
||||
)
|
||||
|
||||
@app.post("/admin/update/publish")
|
||||
async def admin_update_publish(
|
||||
request: Request,
|
||||
csrf_token: str = Form(""),
|
||||
version: str = Form(""),
|
||||
notes: str = Form(""),
|
||||
force: str = Form("1"),
|
||||
installer: UploadFile = File(...),
|
||||
) -> HTMLResponse:
|
||||
if not _admin_allowed(request, app.state.admin_token):
|
||||
return _admin_forbidden()
|
||||
csrf = _csrf_token(request)
|
||||
if not _csrf_allowed(request, csrf_token):
|
||||
return _admin_page(get_service(), csrf, message="CSRF 校验失败,请刷新后台页面后重试")
|
||||
try:
|
||||
content = await installer.read()
|
||||
manifest = get_service().publish_update(
|
||||
version=version,
|
||||
filename=installer.filename or "",
|
||||
content=content,
|
||||
force=str(force).strip() not in {"0", "false", "False", "否"},
|
||||
notes=notes,
|
||||
)
|
||||
msg = f"已发布更新 V{manifest.version},文件={manifest.filename}"
|
||||
except Exception as exc:
|
||||
msg = f"发布更新失败:{exc}"
|
||||
return _admin_page(get_service(), csrf, message=msg)
|
||||
|
||||
@app.post("/admin/update/disable")
|
||||
def admin_update_disable(
|
||||
request: Request,
|
||||
csrf_token: str = Form(""),
|
||||
) -> HTMLResponse:
|
||||
if not _admin_allowed(request, app.state.admin_token):
|
||||
return _admin_forbidden()
|
||||
csrf = _csrf_token(request)
|
||||
if not _csrf_allowed(request, csrf_token):
|
||||
return _admin_page(get_service(), csrf, message="CSRF 校验失败,请刷新后台页面后重试")
|
||||
get_service().disable_update()
|
||||
return _admin_page(get_service(), csrf, message="已关闭自动更新发布")
|
||||
|
||||
return app
|
||||
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ from __future__ import annotations
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
import sqlite3
|
||||
from dataclasses import dataclass
|
||||
@@ -71,6 +72,17 @@ class AuditLogEntry:
|
||||
created_at: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class UpdateManifest:
|
||||
enabled: bool
|
||||
version: str
|
||||
filename: str
|
||||
sha256: str
|
||||
force: bool
|
||||
notes: str
|
||||
published_at: str
|
||||
|
||||
|
||||
def utcnow() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
@@ -118,6 +130,19 @@ def generate_card_code() -> str:
|
||||
return f"DG-{groups}"
|
||||
|
||||
|
||||
def sanitize_update_filename(filename: str, *, version: str = "") -> str:
|
||||
raw = Path(str(filename or "")).name.strip()
|
||||
if not raw.lower().endswith(".exe"):
|
||||
safe_version = re.sub(r"[^0-9A-Za-z_.-]+", "_", str(version or "latest"))
|
||||
raw = f"DouyinGuaji-{safe_version}-Setup.exe"
|
||||
cleaned = re.sub(r'[<>:"/\\|?*\x00-\x1f]+', "_", raw).strip(" .")
|
||||
return cleaned or "DouyinGuaji-Setup.exe"
|
||||
|
||||
|
||||
def sha256_bytes(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def _bounded_int(value: int, *, name: str, minimum: int, maximum: int) -> int:
|
||||
parsed = int(value)
|
||||
if parsed < minimum or parsed > maximum:
|
||||
@@ -139,6 +164,16 @@ class LicenseService:
|
||||
self.db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self._init_db()
|
||||
|
||||
@property
|
||||
def update_dir(self) -> Path:
|
||||
path = self.db_path.parent / "updates"
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
@property
|
||||
def update_manifest_path(self) -> Path:
|
||||
return self.db_path.parent / "update_manifest.json"
|
||||
|
||||
def _connect(self) -> sqlite3.Connection:
|
||||
conn = sqlite3.connect(self.db_path, timeout=10)
|
||||
conn.row_factory = sqlite3.Row
|
||||
@@ -335,6 +370,81 @@ class LicenseService:
|
||||
for row in rows
|
||||
]
|
||||
|
||||
def load_update_manifest(self) -> UpdateManifest:
|
||||
try:
|
||||
raw = json.loads(self.update_manifest_path.read_text(encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
return UpdateManifest(False, "0.0.0", "", "", False, "", "")
|
||||
except Exception:
|
||||
return UpdateManifest(False, "0.0.0", "", "", False, "manifest 读取失败", "")
|
||||
if not isinstance(raw, dict):
|
||||
return UpdateManifest(False, "0.0.0", "", "", False, "manifest 格式错误", "")
|
||||
raw_filename = str(raw.get("filename") or "").strip()
|
||||
return UpdateManifest(
|
||||
enabled=bool(raw.get("enabled")),
|
||||
version=str(raw.get("version") or "0.0.0").strip() or "0.0.0",
|
||||
filename=sanitize_update_filename(raw_filename, version=str(raw.get("version") or "")) if raw_filename else "",
|
||||
sha256=str(raw.get("sha256") or "").strip().lower(),
|
||||
force=bool(raw.get("force")),
|
||||
notes=str(raw.get("notes") or ""),
|
||||
published_at=str(raw.get("published_at") or ""),
|
||||
)
|
||||
|
||||
def publish_update(
|
||||
self,
|
||||
*,
|
||||
version: str,
|
||||
filename: str,
|
||||
content: bytes,
|
||||
force: bool = True,
|
||||
notes: str = "",
|
||||
) -> UpdateManifest:
|
||||
version = str(version or "").strip().lstrip("Vv")
|
||||
if not re.fullmatch(r"\d+(?:\.\d+){0,3}", version):
|
||||
raise ValueError("version must look like 3.3.4")
|
||||
if not content:
|
||||
raise ValueError("installer file is empty")
|
||||
safe_filename = sanitize_update_filename(filename, version=version)
|
||||
if not safe_filename.lower().endswith(".exe"):
|
||||
raise ValueError("installer must be an .exe file")
|
||||
target = self.update_dir / safe_filename
|
||||
target.write_bytes(content)
|
||||
manifest = UpdateManifest(
|
||||
enabled=True,
|
||||
version=version,
|
||||
filename=safe_filename,
|
||||
sha256=sha256_bytes(content),
|
||||
force=bool(force),
|
||||
notes=str(notes or "").strip()[:500],
|
||||
published_at=iso_utc(utcnow()),
|
||||
)
|
||||
self.update_manifest_path.write_text(
|
||||
json.dumps(manifest.__dict__, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return manifest
|
||||
|
||||
def disable_update(self) -> UpdateManifest:
|
||||
existing = self.load_update_manifest()
|
||||
manifest = UpdateManifest(
|
||||
enabled=False,
|
||||
version=existing.version or "0.0.0",
|
||||
filename=existing.filename,
|
||||
sha256=existing.sha256,
|
||||
force=False,
|
||||
notes=existing.notes,
|
||||
published_at=existing.published_at,
|
||||
)
|
||||
self.update_manifest_path.write_text(
|
||||
json.dumps(manifest.__dict__, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return manifest
|
||||
|
||||
def sign_payload(self, payload: dict[str, Any]) -> str:
|
||||
signature = self.private_key.sign(canonical_payload_bytes(payload))
|
||||
return base64.b64encode(signature).decode("ascii")
|
||||
|
||||
def activate(self, code: str, *, machine_fingerprint: str) -> LicenseActionResult:
|
||||
raw_machine = str(machine_fingerprint or "").strip()
|
||||
if not raw_machine:
|
||||
|
||||
@@ -5,6 +5,9 @@ import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
|
||||
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM, TEST_PUBLIC_KEY_PEM
|
||||
|
||||
|
||||
def test_compare_versions_handles_v_prefix_and_patch_order():
|
||||
@@ -30,6 +33,26 @@ def test_load_settings_is_disabled_without_manifest_url(tmp_path, monkeypatch):
|
||||
assert settings.manifest_url == ""
|
||||
|
||||
|
||||
def test_load_settings_uses_default_server_for_frozen_exe(tmp_path, monkeypatch):
|
||||
from douyin.core import path_config
|
||||
from douyin.updater import force_update
|
||||
from douyin.updater.force_update import load_update_settings
|
||||
|
||||
cfg = tmp_path / "config.json"
|
||||
cfg.write_text(json.dumps({}), encoding="utf-8")
|
||||
monkeypatch.setattr(path_config, "get_config_path", lambda: str(cfg))
|
||||
monkeypatch.setattr(force_update.sys, "frozen", True, raising=False)
|
||||
monkeypatch.delenv("DOUYIN_UPDATE_MANIFEST_URL", raising=False)
|
||||
monkeypatch.delenv("DOUYIN_AUTO_UPDATE_ENABLED", raising=False)
|
||||
|
||||
settings = load_update_settings()
|
||||
|
||||
assert settings.enabled is True
|
||||
assert settings.manifest_url == force_update.DEFAULT_UPDATE_MANIFEST_URL
|
||||
assert settings.require_https is False
|
||||
assert settings.require_signed_manifest is True
|
||||
|
||||
|
||||
def test_forced_update_downloads_verifies_and_launches_installer(tmp_path):
|
||||
from douyin.updater.force_update import UpdateSettings, perform_forced_update
|
||||
|
||||
@@ -81,6 +104,73 @@ def test_forced_update_downloads_verifies_and_launches_installer(tmp_path):
|
||||
assert any(arg.startswith("/LOG=") for arg in launched[0])
|
||||
|
||||
|
||||
def test_forced_update_accepts_signed_manifest(tmp_path, monkeypatch):
|
||||
from douyin.updater import force_update
|
||||
from douyin.updater.force_update import UpdateSettings, perform_forced_update
|
||||
|
||||
private_key = serialization.load_pem_private_key(TEST_PRIVATE_KEY_PEM, password=None)
|
||||
monkeypatch.setattr(force_update, "PUBLIC_KEY_PEM", TEST_PUBLIC_KEY_PEM)
|
||||
payload = b"signed installer"
|
||||
expected_sha = hashlib.sha256(payload).hexdigest()
|
||||
manifest = {
|
||||
"enabled": True,
|
||||
"version": "3.3.4",
|
||||
"url": "http://103.236.55.219:18100/api/v1/update/download/DouyinGuaji-3.3.4-Setup.exe",
|
||||
"filename": "DouyinGuaji-3.3.4-Setup.exe",
|
||||
"sha256": expected_sha,
|
||||
"force": True,
|
||||
}
|
||||
manifest["signature"] = force_update.base64.b64encode(
|
||||
private_key.sign(force_update._canonical_payload_bytes(dict(manifest)))
|
||||
).decode("ascii")
|
||||
launched: list[list[str]] = []
|
||||
|
||||
result = perform_forced_update(
|
||||
UpdateSettings(
|
||||
enabled=True,
|
||||
manifest_url="http://103.236.55.219:18100/api/v1/update/manifest",
|
||||
download_dir=tmp_path,
|
||||
require_https=False,
|
||||
require_signed_manifest=True,
|
||||
),
|
||||
current_version="3.3.3",
|
||||
fetch_manifest=lambda url, timeout: manifest,
|
||||
download_file=lambda url, dest, timeout: dest.write_bytes(payload),
|
||||
launch_installer=lambda cmd: launched.append(cmd),
|
||||
)
|
||||
|
||||
assert result.status == "update_started"
|
||||
assert launched
|
||||
|
||||
|
||||
def test_forced_update_rejects_bad_signed_manifest(tmp_path, monkeypatch):
|
||||
from douyin.updater import force_update
|
||||
from douyin.updater.force_update import UpdateError, UpdateSettings, perform_forced_update
|
||||
|
||||
monkeypatch.setattr(force_update, "PUBLIC_KEY_PEM", TEST_PUBLIC_KEY_PEM)
|
||||
manifest = {
|
||||
"version": "3.3.4",
|
||||
"url": "http://103.236.55.219:18100/api/v1/update/download/app.exe",
|
||||
"sha256": "0" * 64,
|
||||
"signature": "bad",
|
||||
}
|
||||
|
||||
with pytest.raises(UpdateError, match="签名"):
|
||||
perform_forced_update(
|
||||
UpdateSettings(
|
||||
enabled=True,
|
||||
manifest_url="http://103.236.55.219:18100/api/v1/update/manifest",
|
||||
download_dir=tmp_path,
|
||||
require_https=False,
|
||||
require_signed_manifest=True,
|
||||
),
|
||||
current_version="3.3.3",
|
||||
fetch_manifest=lambda url, timeout: manifest,
|
||||
download_file=lambda url, dest, timeout: None,
|
||||
launch_installer=lambda cmd: None,
|
||||
)
|
||||
|
||||
|
||||
def test_launch_installer_on_windows_waits_for_parent_before_setup(monkeypatch, tmp_path):
|
||||
from douyin.updater import force_update
|
||||
|
||||
|
||||
@@ -121,6 +121,64 @@ def test_admin_page_can_create_and_revoke_card(tmp_path):
|
||||
assert service.activate(card, machine_fingerprint="machine-a").reason == "revoked"
|
||||
|
||||
|
||||
def test_update_manifest_defaults_to_no_update_with_signature(tmp_path):
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from license_server import api
|
||||
from license_server.core import LicenseService
|
||||
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
|
||||
|
||||
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
|
||||
client = TestClient(api.create_app(service=service, admin_token="secret"))
|
||||
|
||||
resp = client.get("/api/v1/update/manifest")
|
||||
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert body["enabled"] is False
|
||||
assert body["version"] == "0.0.0"
|
||||
assert isinstance(body["signature"], str)
|
||||
|
||||
|
||||
def test_admin_can_publish_update_and_download_installer(tmp_path):
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from license_server import api
|
||||
from license_server.core import LicenseService
|
||||
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
|
||||
|
||||
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
|
||||
client = TestClient(api.create_app(service=service, admin_token="secret"))
|
||||
client.post("/admin/login", data={"admin_token": "secret"}, follow_redirects=False)
|
||||
payload = b"installer bytes"
|
||||
|
||||
published = client.post(
|
||||
"/admin/update/publish",
|
||||
cookies={api.ADMIN_CSRF_COOKIE: "csrf-token"},
|
||||
data={
|
||||
"csrf_token": "csrf-token",
|
||||
"version": "3.3.4",
|
||||
"notes": "smoke",
|
||||
"force": "1",
|
||||
},
|
||||
files={"installer": ("DouyinGuaji-3.3.4-Setup.exe", payload, "application/octet-stream")},
|
||||
)
|
||||
manifest = client.get("/api/v1/update/manifest")
|
||||
body = manifest.json()
|
||||
download = client.get("/api/v1/update/download/DouyinGuaji-3.3.4-Setup.exe")
|
||||
|
||||
assert published.status_code == 200
|
||||
assert "已发布更新 V3.3.4" in published.text
|
||||
assert manifest.status_code == 200
|
||||
assert body["enabled"] is True
|
||||
assert body["version"] == "3.3.4"
|
||||
assert body["sha256"]
|
||||
assert body["url"].endswith("/api/v1/update/download/DouyinGuaji-3.3.4-Setup.exe")
|
||||
assert isinstance(body["signature"], str)
|
||||
assert download.status_code == 200
|
||||
assert download.content == payload
|
||||
|
||||
|
||||
def test_admin_page_shows_stats_cards_and_audit_logs(tmp_path):
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
|
||||
Reference in new issue
Block a user