Open
[功能方案] 后台自动更新检查与通知 实现方案(v3.1.11) #15
凤城老人Add on  8 days ago
凤城老人
凤城老人Collaborators
8 days ago Create

ZhyCMS 后台自动更新检查与通知 实现方案(v3.1.11)

需求方:pollybird / ZhyCMS(main 分支)
目标版本:v3.1.11
编写日期:2026-11-09
方案性质:技术设计(含数据模型、接口、代码骨架、安全约束、测试与落地分期)
已实测依据:GitHub / GitCode Release API 均可用,字段映射已核实(见第 5 节)


一、需求与设计边界

1.1 需求

  1. 管理员登录后台后自动检查更新(不阻塞登录)。
  2. 同时支持 GitHub 与 GitCode 两个 Release 源。
  3. 按服务器出口 IP 归属地自动选择源:中国大陆 → 优先 GitCode;海外 → 优先 GitHub。
  4. 更新前告知用户更新内容(Release notes)。
  5. 更新完成后提示用户重启服务。

1.2 关键边界(务必先对齐)

决策 取舍 理由
是否应用内自动替换代码/镜像 不做(仅检查 + 告知 + 引导 + 重启提示) Docker 镜像不可变,容器内改文件在下次 up 即丢失;源码覆盖有签名缺失、依赖/迁移错配风险
更新动作执行者 部署者按引导执行(docker compose pull && up -d 或 git checkout tag) 符合容器化最佳实践;避免应用自我提权/自改代码
"提示重启"实现 引导文案固定"更新后请重启服务";重启后 CMS_VERSION 变化→横幅自动消失 Docker 下应用无法感知宿主新镜像,"运行时版本变更"是最可靠的生效信号
是否引入新依赖 不引入(复用 requests + version_cmp) release notes 采用转义渲染,无需 bleach;不触碰依赖基线

若后续确需"应用内一键更新",列为附录 B 的可选高风险模块(签名 + 备份 + 超管 + 二次确认),默认不开启。


二、总体架构

登录成功 / dashboard 加载
        │ (频率门限:update_check_interval_hours,默认 12h)
        ▼
 update_check.maybe_trigger()          ← 非阻塞,后台 daemon 线程
        │
        ├─ 站点级锁/门限(Setting.update_check_last_at + 可选 Redis 锁)
        ▼
 选择源:pick_channel()
   ├─ IP 地区缓存命中 → cn→gitcode / overseas→github
   └─ 未命中 → 多源探测出口 IP 地区(失败→连通性探测→默认 gitcode)
        ▼
 fetch_latest_release(source)          ← 首选失败自动切另一站(可用性兜底)
   ├─ GitHubProvider  (api.github.com)
   └─ GitCodeProvider (api.gitcode.com/api/v5)
        ▼
 归一化 ReleaseInfo → version_cmp(latest, current) → has_update?
        ▼
 写入 Setting 缓存(update_check_result / last_at / source / ip_region)
        ▼
 dashboard 横幅(有新版本)→ 弹窗(安全渲染 notes)→ 更新指引 + 重启提示

降级原则:任何环节失败都静默降级(仅记 warning 日志),绝不阻塞登录、不弹错误、不影响主流程。


三、数据结构设计(复用 Setting,不新建表)

在 app/models/setting.py 的 Setting.DEFAULTS(:38-178)新增:

键 默认值 说明 敏感
update_check_enable '1' 总开关(1/0) 否
update_check_channel 'auto' 首选源:auto/github/gitcode 否
update_check_interval_hours '12' 检查间隔(小时,1–168) 否
update_check_include_prerelease '0' 是否提示预发布版 否
update_check_ip_region '' 缓存的出口 IP 地区:cn/overseas 否
update_check_ip_region_at '' 地区检测时间(ISO,7 天有效) 否
update_check_last_at '' 上次检查时间(ISO,用于门限) 否
update_check_result '' 上次结果 JSON(ReleaseInfo + has_update) 否
update_check_dismissed '' 已忽略的版本 tag(用户关闭横幅后记录,避免反复提示) 否
update_check_github_token '' 可选 GitHub Token(提升匿名限流 60/h) 是(_secret? 不匹配后缀,需加入 SENSITIVE_KEYS_EXPLICIT 或改为 update_check_github_secret)

建议:GitHub Token 键命名为 update_check_github_secret,自动命中 _secret 后缀加密,无需改敏感键逻辑。

update_check_result 的 JSON 结构:

{
  "has_update": true,
  "current": "3.1.10",
  "latest": "3.1.11",
  "tag": "v3.1.11",
  "name": "v3.1.11 ...",
  "notes": "<原始 markdown 文本,展示前转义>",
  "published_at": "2026-11-11T10:00:00Z",
  "html_url": "https://github.com/pollybird/zhycms/releases/tag/v3.1.11",
  "download_url": "https://.../v3.1.11.zip",
  "source": "github",
  "prerelease": false,
  "checked_at": "2026-11-11T12:00:00+08:00"
}

无需 Alembic 迁移:Setting.get() 对未落库键回退 DEFAULTS(setting.py:228+)。如需物理落行,可仿 migrations/versions/0003_seed_settings.py 做幂等插入。


四、出口 IP 地区检测(需求核心)

4.1 策略(分层,逐级降级)

1) 读缓存 update_check_ip_region(7 天内有效)
2) 未命中 → 依次请求地区探测源(任一成功即用):
   a. https://myip.ipip.net            (国内友好,纯文本,含“中国”/城市)
   b. https://ip.useragentinfo.com/json (国内,country)
   c. https://ipinfo.io/json            (国际,country=CN)
   d. https://ip-api.com/json/?lang=zh-CN (国际,countryCode=CN)
   判定:country ∈ {CN, China, 中国} → 'cn',否则 'overseas'
3) 全部失败 → 连通性探测:并发 HEAD/GET 两站 API,选“可通且 RTT 低”者
4) 仍失败 → 默认 'gitcode'(企业站国内为主)
5) 写回缓存 update_check_ip_region / _at

实测(2026-11-09,部署环境):myip.ipip.net 200(返回"当前 IP:x.x.x.x 来自于:中国 贵州 贵阳 电信")、ipinfo.io/json 200(country: CN)、ip-api.com 可用;ip.useragentinfo.com/json 当前不可达(自动跳过,不影响降级)。据此实测出口 IP 归属中国大陆,首选应为 GitCode。

4.2 关键实现约束

  • 超时:单个探测源 3s,整体上限 8s(并发/顺序结合)。
  • SSRF 白名单:所有探测 URL 走 assert_safe_external_url(url, allowed_hosts={...}, allow_schemes=('https',));ip-api 为 http,单独放行其域名。
  • allow_redirects=False:防止 30x 跳转到内网。
  • 隐私提示:IP 探测会把服务器出口 IP 发给第三方;在设置页与 SECURITY.md 明确说明,并提供"仅连通性探测(不查 IP)"选项——对应 update_check_channel 设为具体站点时仍会探测连通性。

4.3 重要设计修正:IP 地区只作"首选",不锁死

即使用 IP 判为海外,也先试首选、失败自动切备选(见第 5.3)。原因:IP 库可能误判、GitHub 在国内可能间歇可用、GitCode 也可能临时故障。这样"地区选择"是优化项而非单点故障。

4.4 代码骨架(app/utils/update_check.py)

_REGION_PROBES = [
    ('https://myip.ipip.net', 'text'),
    ('https://ip.useragentinfo.com/json', 'json'),
    ('https://ipinfo.io/json', 'json'),
    ('https://ip-api.com/json/?lang=zh-CN', 'json'),
]

def get_exit_ip_region(force=False):
    """返回 'cn' | 'overseas' | ''(未知)。带 7 天缓存。"""
    if not force:
        region = Setting.get('update_check_ip_region')
        at = Setting.get('update_check_ip_region_at')
        if region and _within_days(at, 7):
            return region
    region = _probe_region() or _probe_connectivity() or 'cn'
    Setting.set('update_check_ip_region', region)
    Setting.set('update_check_ip_region_at', _now_iso())
    db.session.commit()
    return region

def pick_channel():
    """返回首选源 'github'|'gitcode'。"""
    cfg = Setting.get('update_check_channel', 'auto')
    if cfg in ('github', 'gitcode'):
        return cfg
    return 'gitcode' if get_exit_ip_region() == 'cn' else 'github'

五、Release Provider 适配(字段已实测)

5.1 端点

源 方法 端点 Header
GitHub GET https://api.github.com/repos/pollybird/zhycms/releases/latest Accept: application/vnd.github+json、User-Agent: ZhyCMS-UpdateCheck、可选 Authorization: Bearer <token>
GitCode GET https://api.gitcode.com/api/v5/repos/pollybird/ZhyCMS/releases/latest Accept: application/json、User-Agent

实测(2026-11-09):两站均返回 200,latest 均为 v3.1.7(见第 11 节发布配套提醒)。

5.2 字段映射(实测确认)

统一字段 GitHub GitCode
version tag_name 去前缀 v tag_name 去前缀 v
name name name
notes body body
published_at published_at(UTC) created_at(无 published_at)
html_url html_url 无,拼接 https://gitcode.com/pollybird/ZhyCMS/releases/tag/{tag}
download_url zipball_url 或 assets[0].browser_download_url assets[0].browser_download_url(实测 raw.gitcode.com/.../v3.1.7.zip)
prerelease prerelease prerelease

5.3 抓取与降级

def fetch_latest_release(source=None):
    source = source or pick_channel()
    primary, fallback = (source, 'gitcode' if source == 'github' else 'github')
    for s in (primary, fallback):          # 首选失败自动切备选
        try:
            info = _PROVIDERS[s].fetch()
            if info and not (info.prerelease and Setting.get('update_check_include_prerelease') != '1'):
                return info
        except Exception as e:
            logger.warning('更新源 %s 获取失败:%s', s, e)
    return None
  • 超时:单源 6s;allow_redirects=False。
  • SSRF:assert_safe_external_url(url, allowed_hosts={'api.github.com','api.gitcode.com'}, allow_schemes=('https',))。
  • 版本比较:复用 app/plugin_system.py:version_cmp(已支持缺位补 0)。
  • 归一化:ReleaseInfo 用 dataclasses.dataclass。

5.4 代码骨架

@dataclass
class ReleaseInfo:
    version: str; tag: str; name: str; notes: str
    published_at: str; html_url: str; download_url: str
    prerelease: bool; source: str

class _GitHubProvider:
    URL = 'https://api.github.com/repos/pollybird/zhycms/releases/latest'
    def fetch(self) -> ReleaseInfo: ...

class _GitCodeProvider:
    URL = 'https://api.gitcode.com/api/v5/repos/pollybird/ZhyCMS/releases/latest'
    def fetch(self) -> ReleaseInfo: ...

六、触发、频率与并发

6.1 触发点

场景 行为
管理员登录成功(admin/auth.py 成功分支,login_user 之后) update_check.maybe_trigger_async()
dashboard 渲染(admin/dashboard.py) 同上;同时读取缓存渲染横幅
设置页"立即检查"(AJAX) check_for_update(force=True) 同步返回结果
定时(可选) 不挂 APScheduler(4 worker 会重复);如启用则用 Redis 锁

6.2 频率门限

maybe_trigger_async():若 now - update_check_last_at < interval 直接返回;否则起 daemon 线程执行并写回 last_at。

6.3 多 worker 竞态

gunicorn 4 worker 下可能并发触发 → 最多重复 1–2 次外部请求(可接受)。可选优化:有 Redis 时用 SET NX EX 站点锁;无 Redis 依赖 Setting 门限,容忍少量重复。


七、UI 与交互

7.1 dashboard 横幅

仿现有"异地登录" warning 横幅(dashboard.py:47-52 的 session.pop('login_abnormal_alert') 模式):

  • 读取 update_check_result,若 has_update 且 tag != update_check_dismissed → 渲染横幅:
    发现新版本 v3.1.11(当前 v3.1.10)来源:GitCode  [查看更新内容] [×]
    
  • 点"查看更新内容"→ 弹窗(Bootstrap Modal,项目已用 AdminLTE/Bootstrap)。
  • 点 × → POST /settings/update/dismiss(CSRF)→ 写 update_check_dismissed=tag。

7.2 更新内容弹窗

  • 标题:v3.1.10 → v3.1.11
  • 元信息:发布时间、来源站、"查看 Release 页面"链接(html_url)
  • 正文:release notes 安全渲染(见第 8 节)
  • 底部:更新指引(Docker / 源码,见第 9 节)+ 重启提示

7.3 配置页 /settings/update(system:settings 权限)

  • 开关、首选源(auto/github/gitcode)、检查间隔、是否含预发布
  • "立即检查"按钮(AJAX,X-CSRF-Token,限流 10/minute)
  • 状态区:当前版本、最新版本、上次检查时间、出口 IP 地区、当前生效源
  • 更新指引(静态文案,按部署形态)
  • 菜单入口:base.html "系统设置"子菜单新增"版本更新"(current_user.has_permission('system:settings'))

八、更新内容的安全渲染(关键)

Release notes 是外部不可信内容,严禁直接 |safe。

默认方案(零新依赖,推荐):

from markupsafe import escape
def render_notes(notes: str) -> Markup:
    # 1) 转义全部 HTML;2) 保留换行;3) 不解析链接(防钓鱼)
    safe_text = str(escape(notes or ''))
    return Markup(safe_text.replace('\n', '<br>'))
  • 效果:内容原样可见(含 markdown 记号),不会执行任何 HTML/JS。
  • 若希望更可读:可仅对成对 **bold**、`code` 做最小化转换后再 Markup,但需严格白名单;或引入 bleach 白名单清洗(需新增依赖,本次不采用)。

明确写入 SECURITY.md:外部 Release 内容一律转义展示,不解析 HTML。


九、更新指引与"重启提示"

9.1 Docker 部署(README 主推)

# 1) 备份(后台「备份运维」或命令行)
# 2) 拉取并切换到新镜像 tag(或 latest)
docker compose pull
docker compose up -d
# 3) 新容器启动时 entrypoint 自动执行 Alembic 迁移(如有)
  • 文案提示:"更新完成后服务已由 up -d 重启;若使用外部反向代理/独立 gunicorn,请重启对应进程使新版本生效。"

9.2 源码部署

git fetch --tags
git checkout v3.1.11
pip install -r requirements.txt      # 如有新依赖
flask db upgrade                     # 如有数据库迁移(看 Release notes 的“升级注意”)
# 重启 gunicorn / systemd 服务
  • 文案提示:"更新完成后请重启服务(gunicorn / systemd)使新版本生效。"

9.3 "是否已生效"判定

  • 重启后 Setting.CMS_VERSION 变为新版本 → 横幅自动消失(has_update=false)。
  • 设置页展示"当前运行版本",便于用户确认。

十、安全考量清单

风险 措施
SSRF 所有外部请求域名白名单 + allow_redirects=False + 超时 3–6s
XSS(notes) 全量转义渲染,禁用 |safe
权限 配置/手动检查 system:settings;dismiss 需登录
CSRF POST 走现有 _csrf_token / X-CSRF-Token
限流 手动检查 @limiter.limit('10/minute')
隐私 IP 探测对外发送出口 IP,文档明示 + 可切换为连通性探测
可用性 全程后台线程 + 静默降级,绝不阻塞登录
供应链 仅读取元数据,不下载/不执行 release 内容
敏感配置 GitHub Token 用 _secret 后缀键,自动 Fernet 加密
审计 "立即检查""修改更新配置"写 audit_log

十一、发布流程配套(重要前置)

实测发现:GitHub 与 GitCode 的 latest Release 均停留在 v3.1.7,而代码已到 v3.1.10。若不补齐 Release,更新检查将永远显示"无更新"(version_cmp(latest=v3.1.7, current=v3.1.10) <= 0)。

配套要求:

  1. 每次发版在两站同步打 tag vX.Y.Z 并创建 Release(notes 与 CHANGELOG 对应版本一致)。
  2. 建议把"创建 GitHub/GitCode Release"纳入 RELEASE.md 发布清单或 CI 发布流程。
  3. Release notes 建议首行给一句"一句话摘要 + 是否含数据库迁移/新依赖",便于更新判断。

十二、文件改动清单

类型 文件 说明
新增 app/utils/update_check.py 核心逻辑(地区检测、Provider、检查、缓存)
新增 app/admin/system/update.py 路由:/settings/update、/settings/update/check、/settings/update/dismiss
新增 app/admin/templates/admin/setting/update.html 配置页
新增 app/admin/templates/admin/_update_modal.html(或并入 dashboard) 更新内容弹窗片段
修改 app/models/setting.py 新增 DEFAULTS 键
修改 app/admin/auth.py 登录成功后 maybe_trigger_async()
修改 app/admin/dashboard.py 触发 + 读取缓存传给模板
修改 app/admin/templates/admin/dashboard.html 横幅 + 弹窗挂载
修改 app/admin/templates/admin/base.html 菜单入口
修改 app/utils/helpers.py 审计标签(可选)
修改 app/admin/system/__init__.py 追加 from . import update # noqa: F401(沿用现有域子包注册方式,路由仍挂 admin_bp)
新增 tests/test_update_check.py 单元/集成测试
修改 CHANGELOG.md / SECURITY.md / README.md / UPGRADE.md 文档

十三、测试计划

类别 用例
Provider GitHub/GitCode JSON 归一化(mock 真实字段);缺字段容错
版本比较 v3.1.10 < v3.1.11、相等、预发布过滤
IP 地区 探测成功(cn/overseas)、全部失败→连通性→默认 gitcode;7 天缓存
降级 首选源 500/超时 → 自动切备选;两站都失败 → 静默无横幅
频率门限 interval 内不重复请求;force=True 必查
安全 notes 含 <script> → 输出被转义;SSRF 白名单拒绝非目标域名
权限 无 system:settings 访问 403;dismiss 需登录 + CSRF
UI 有更新显示横幅;dismiss 后不再显示;重启版本变化后横幅消失
门禁 全量测试、覆盖率、常量/异常吞噬门禁、版本一致性

十四、分阶段落地

阶段 内容 交付
一期(MVP) Setting 键 + update_check.py(地区检测/Provider/缓存)+ 登录触发 + dashboard 横幅 + 弹窗 + 重启提示 可用
二期 配置页 + 手动检查 + 首选失败切备选 + 限流 + 审计 + 测试 完整
三期(可选) source 部署"一键更新"(下载 zip + 备份 + 校验 + 超管二次确认) 默认关闭

附录 A:为何不做应用内自动更新(决策记录)

  • Docker:容器文件系统与镜像强绑定,docker cp/容器内改代码会在重建时丢失;正确做法是替换镜像并由编排重启。
  • 源码:无代码签名,应用自行下载并覆盖运行中代码,等于给远端一个"远程代码执行后门",一旦源站被攻破后果严重。
  • 迁移耦合:新版本可能含数据迁移/新依赖,应用内自行升级难以可靠处理。
  • 因此默认只做"检查 + 告知 + 引导 + 重启提示",把执行权与责任留在部署者。

附录 B(可选):源码部署"一键更新"约束(若将来要做)

  • 仅 is_super + 二次确认(YES_I_UNDERSTAND)
  • 先自动备份(复用 backup_utils.create_backup)
  • 下载 zip 后校验 SHA256(Release 附带校验文件)与签名
  • 禁止跨大版本自动升级;检测到 migrations/新依赖时拒绝并转人工
  • 失败自动回滚
  • 默认关闭,需显式开关

方案完毕。 建议先确认两个前置项:① 需同步补齐 GitHub/GitCode 的 Release(否则检测不到);② 是否需要把"应用内一键更新"纳入范围(默认不做)。

likedislike