geng
@@ -12,6 +12,8 @@ RUN pip install --disable-pip-version-check -r /tmp/requirements.txt \
|
||||
|
||||
COPY --chown=app:app wechat_rpa/*.py /app/wechat_rpa/
|
||||
COPY --chown=app:app admin-web/apps/web-antd/dist/ /app/admin-web/apps/web-antd/dist/
|
||||
# 手机远程控制台(admin-web/apps/mobile-h5,独立项目),由 admin_api.py 托管在 /m/
|
||||
COPY --chown=app:app admin-web/apps/mobile-h5/dist/ /app/admin-web/apps/mobile-h5/dist/
|
||||
|
||||
USER app
|
||||
WORKDIR /app/wechat_rpa
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
# 手机远程控制台(/m/)的 HTTPS 入口。
|
||||
#
|
||||
# 自 2026-09-28(mobile-http-20260928)起按用户要求,内外网都允许明文 HTTP 登录手机端
|
||||
# (MOBILE_REQUIRE_HTTPS 默认 never)。HTTP 下 ZYT 密码和手机会话令牌在公网上可被截获;
|
||||
# 配好本 HTTPS 入口后,建议给 api 服务加环境变量 MOBILE_REQUIRE_HTTPS=auto(公网必须 HTTPS,内网仍可 HTTP)。
|
||||
#
|
||||
# 启用步骤(宝塔面板或手工均可):
|
||||
# 1. 证书:宝塔「网站 → im.zhenyangtang.cn → SSL」申请 Let's Encrypt,或 acme.sh。
|
||||
# 公网 443 没有转发到本机时,HTTP-01 验证会失败,改用 DNS-01(DNS API)签发。
|
||||
# 2. 端口:路由器把公网 TCP 443(或选定的 HTTPS 端口,例如 8443)转发到 192.168.110.111。
|
||||
# 用非 443 端口时把下面的 listen 改成对应端口,手机访问 https://im.zhenyangtang.cn:8443/m/。
|
||||
# 3. 把本文件复制成 im.zhenyangtang.cn.https.conf 放到与现有 conf 相同的目录,修改证书路径,
|
||||
# `nginx -t` 通过后 `nginx -s reload`。现有的 80 端口配置保持不动,桌面端继续可用。
|
||||
# 4. 验证:curl -I https://im.zhenyangtang.cn/m/ 返回 200;手机浏览器打开后登录页不再提示明文连接。
|
||||
#
|
||||
# 注意 X-Real-IP 必须由 Nginx 用 $remote_addr 覆盖写入:后台用它做登录限流和"是否内网"的判断。
|
||||
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
server_name im.zhenyangtang.cn;
|
||||
|
||||
ssl_certificate /www/server/panel/vhost/cert/im.zhenyangtang.cn/fullchain.pem;
|
||||
ssl_certificate_key /www/server/panel/vhost/cert/im.zhenyangtang.cn/privkey.pem;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_prefer_server_ciphers off;
|
||||
ssl_session_cache shared:SSL_IM:10m;
|
||||
ssl_session_timeout 1d;
|
||||
add_header Strict-Transport-Security "max-age=31536000" always;
|
||||
|
||||
client_max_body_size 100m;
|
||||
|
||||
location ^~ /api/v2/ {
|
||||
proxy_pass http://127.0.0.1:18766;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_connect_timeout 15s;
|
||||
proxy_send_timeout 300s;
|
||||
# 桌面端命令通道长轮询最长挂起 25 秒,远小于这里的读超时。
|
||||
proxy_read_timeout 300s;
|
||||
}
|
||||
|
||||
location ^~ /api/ {
|
||||
proxy_pass http://127.0.0.1:18766/api/v2/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_connect_timeout 15s;
|
||||
proxy_send_timeout 300s;
|
||||
proxy_read_timeout 300s;
|
||||
}
|
||||
|
||||
location ^~ /gateway/ {
|
||||
proxy_pass http://127.0.0.1:18770/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_connect_timeout 15s;
|
||||
proxy_send_timeout 300s;
|
||||
proxy_read_timeout 300s;
|
||||
}
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:18766;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection $connection_upgrade;
|
||||
proxy_connect_timeout 15s;
|
||||
proxy_send_timeout 300s;
|
||||
proxy_read_timeout 300s;
|
||||
}
|
||||
|
||||
access_log /www/wwwlogs/im.zhenyangtang.cn.https.log;
|
||||
error_log /www/wwwlogs/im.zhenyangtang.cn.https.error.log;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env bash
|
||||
# 基线核对、备份将被替换的源文件和 /m/ 目录、给当前镜像打回滚标签。只读线上 + 写本目录。
|
||||
set -euo pipefail
|
||||
test "${REMOTE_RELEASE_APPROVED:-}" = mobile-http-20260928
|
||||
release=/home/ps/mobile-http-20260928
|
||||
cd "$release"
|
||||
test ! -e baseline-check.json
|
||||
python3 remote_server_guard.py baseline > baseline-check.json.tmp
|
||||
mv baseline-check.json.tmp baseline-check.json
|
||||
cat baseline-check.json
|
||||
test ! -e source-before
|
||||
test ! -e preflight-complete
|
||||
if docker image inspect zyt/wecom-admin:before-mobile-http-20260928 >/dev/null 2>&1; then
|
||||
echo 'Refuse to replace existing rollback tag' >&2; exit 1
|
||||
fi
|
||||
mkdir -m 700 source-before
|
||||
python3 - <<'PY'
|
||||
from pathlib import Path
|
||||
import json, shutil
|
||||
r = Path('/home/ps/mobile-http-20260928'); project = Path('/opt/im-admin')
|
||||
plan = json.loads((r / 'release-plan.json').read_text())
|
||||
for name in plan['backendFiles'] + plan['deployFiles']:
|
||||
target = r / 'source-before' / name
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(project / name, target)
|
||||
shutil.copytree(project / plan['frontendDir'], r / 'source-before' / plan['frontendDir'])
|
||||
PY
|
||||
docker tag zyt/wecom-admin:current zyt/wecom-admin:before-mobile-http-20260928
|
||||
docker image inspect zyt/wecom-admin:current --format '{{.Id}}' > image-before.txt
|
||||
printf '%s\n' ready > preflight-complete
|
||||
echo "preflight complete; rollback image tagged before-mobile-http-20260928 ($(cat image-before.txt))"
|
||||
@@ -0,0 +1,22 @@
|
||||
#!/usr/bin/env bash
|
||||
# 构建候选镜像 + 离线跑测试 + 核对候选镜像文件。线上服务不受影响。
|
||||
# 本次不改数据库(只改登录的 HTTPS 默认策略和 /m/ 静态文件),不做整库备份;回滚靠旧镜像和 source-before。
|
||||
set -euo pipefail
|
||||
test "${REMOTE_RELEASE_APPROVED:-}" = mobile-http-20260928
|
||||
release=/home/ps/mobile-http-20260928
|
||||
cd "$release"
|
||||
test -f preflight-complete
|
||||
test ! -e candidate-passed
|
||||
python3 remote_server_guard.py baseline
|
||||
test "$(docker image inspect zyt/wecom-admin:before-mobile-http-20260928 --format '{{.Id}}')" = "$(cat image-before.txt)"
|
||||
docker build --network=none --pull=false -f Dockerfile.overlay -t zyt/wecom-admin:mobile-http-20260928 . > candidate-build.log 2>&1
|
||||
# serverTestModules 随包放在 tests/;imageTestModules 用镜像自带的测试文件(PYTHONPATH 后一项)。
|
||||
# -P:不把工作目录 /app/wechat_rpa 放到 sys.path 最前面,否则镜像里同名的旧测试会盖住随包的新测试。
|
||||
mapfile -t modules < <(python3 -c 'import json;p=json.load(open("release-plan.json"));print("\n".join(p["serverTestModules"]+p.get("imageTestModules",[])))')
|
||||
test "${#modules[@]}" -gt 0
|
||||
docker run --rm --network=none --read-only --tmpfs /tmp:size=512m,mode=1777 --tmpfs /data:size=256m,mode=1777 \
|
||||
-v "$release/tests:/release-tests:ro" -e PYTHONPATH=/release-tests:/app/wechat_rpa \
|
||||
zyt/wecom-admin:mobile-http-20260928 python -X utf8 -B -P -m unittest "${modules[@]}" -q > candidate-tests.log 2>&1
|
||||
tail -n 3 candidate-tests.log
|
||||
python3 remote_server_guard.py candidate
|
||||
printf '%s\n' passed > candidate-passed
|
||||
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env bash
|
||||
# 替换 remote_api.py 和整个 /m/ 目录;切换镜像,只重建 api 容器。任何一步失败自动调用 rollback.sh。
|
||||
set -euo pipefail
|
||||
test "${REMOTE_RELEASE_APPROVED:-}" = mobile-http-20260928
|
||||
release=/home/ps/mobile-http-20260928
|
||||
cd "$release"
|
||||
test -f candidate-passed
|
||||
python3 remote_server_guard.py baseline
|
||||
cd /opt/im-admin/deploy/im-admin
|
||||
docker compose config --quiet
|
||||
rollback_on_error() { rc=$?; trap - ERR; bash "$release/rollback.sh"; exit "$rc"; }
|
||||
trap rollback_on_error ERR
|
||||
python3 - <<'PY'
|
||||
from pathlib import Path
|
||||
import json, hashlib, os, shutil
|
||||
r = Path('/home/ps/mobile-http-20260928'); target = Path('/opt/im-admin')
|
||||
plan = json.loads((r / 'release-plan.json').read_text())
|
||||
rows = [row for row in json.loads((r / 'manifest.json').read_text()) if row['path'].startswith('payload/')]
|
||||
frontend = plan['frontendDir']
|
||||
# 容器从镜像里读 /m/,宿主上的目录只给以后整包重建用;仍然整体换名,避免留下半套文件。
|
||||
staging = target / (frontend + '.mobile-http.tmp'); assert not staging.exists()
|
||||
old = target / (frontend + '.mobile-http.old'); assert not old.exists()
|
||||
for row in rows:
|
||||
rel = row['path'][len('payload/'):]
|
||||
data = (r / row['path']).read_bytes(); assert hashlib.sha256(data).hexdigest() == row['sha256'], rel
|
||||
if rel.startswith(frontend + '/'):
|
||||
dest = staging / rel[len(frontend) + 1:]
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
dest.write_bytes(data); os.chmod(dest, 0o644)
|
||||
continue
|
||||
dest = (target / rel).resolve(); assert dest.is_relative_to(target) and dest.exists()
|
||||
tmp = dest.with_name(dest.name + '.mobile-http.tmp'); assert not tmp.exists()
|
||||
with tmp.open('xb') as f:
|
||||
f.write(data)
|
||||
os.chmod(tmp, dest.stat().st_mode & 0o777); os.replace(tmp, dest)
|
||||
for directory in [staging] + [p for p in staging.rglob('*') if p.is_dir()]:
|
||||
os.chmod(directory, 0o755)
|
||||
final = target / frontend
|
||||
os.replace(final, old)
|
||||
os.replace(staging, final)
|
||||
shutil.rmtree(old) # 原目录已在 source-before 里
|
||||
PY
|
||||
docker tag zyt/wecom-admin:mobile-http-20260928 zyt/wecom-admin:current
|
||||
docker compose up -d --no-deps --no-build --wait --wait-timeout 180 api
|
||||
bash "$release/04-verify.sh"
|
||||
trap - ERR
|
||||
printf '%s\n' 'Plain-HTTP phone login enabled, deployed and verified.'
|
||||
@@ -0,0 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
test "${REMOTE_RELEASE_APPROVED:-}" = mobile-http-20260928
|
||||
release=/home/ps/mobile-http-20260928
|
||||
cd "$release"
|
||||
python3 remote_server_guard.py deployed | tee deployed-verification.json
|
||||
@@ -0,0 +1,9 @@
|
||||
ARG BASE_IMAGE=zyt/wecom-admin:before-mobile-http-20260928
|
||||
FROM ${BASE_IMAGE}
|
||||
# 先删掉旧版 /m/ 目录再放新版,镜像里不残留旧的(带内网横幅的)页面文件。
|
||||
USER root
|
||||
RUN rm -rf /app/admin-web/apps/mobile-h5/dist
|
||||
USER app
|
||||
COPY --chown=app:app payload/wechat_rpa/remote_api.py /app/wechat_rpa/remote_api.py
|
||||
COPY --chown=app:app payload/admin-web/apps/mobile-h5/dist/ /app/admin-web/apps/mobile-h5/dist/
|
||||
WORKDIR /app/wechat_rpa
|
||||
@@ -0,0 +1,162 @@
|
||||
[
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/_plugin-vue_export-helper-4o9rbdkf.js",
|
||||
"sha256": "8d6186020c3d8562f581ea579742dd497649203a880b9c13cc904462b134bc60",
|
||||
"bytes": 2308
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/AccountSwitcher-BZXg15MH.css",
|
||||
"sha256": "b61f1f1af65c2c3438066ffe41683af7e38062eb9389cda3f8fdad8ee77498ff",
|
||||
"bytes": 359
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/AccountSwitcher-DHX0QDeT.js",
|
||||
"sha256": "226d4cde03c5434f20aa96c84cfb33538af084d79805348a089e343c5056281f",
|
||||
"bytes": 14528
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/brand-mark-CPUQS9Am.png",
|
||||
"sha256": "1caa8c492da279e8d01f676fe9232ccad016321699d519b3834692052cc5f5ee",
|
||||
"bytes": 16743
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/cell-group-CEKvg8Wf.js",
|
||||
"sha256": "b0d4b420bc5197a5df6d918e740e2b90b108c6e06ba930c3fd8e97fabe010556",
|
||||
"bytes": 4490
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/ConversationsView-BMjeHKhk.js",
|
||||
"sha256": "75cd3809eb0d7db6c994302dd296674eadd366a53a4feb97a759173d70546e80",
|
||||
"bytes": 28526
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/ConversationsView-CytDMSuM.css",
|
||||
"sha256": "1f646a0178eb9e3f837ac62b5521ec60c0e7d5b4b086b9076c4bf2a7448f98ae",
|
||||
"bytes": 4220
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/DevicesView-CHTvxQxK.css",
|
||||
"sha256": "40fd5adaea4d4aed376a57c75ebec4544d50f424863704b00ce80b98f7881ddd",
|
||||
"bytes": 3983
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/DevicesView-DVXAQfpT.js",
|
||||
"sha256": "237de4f76004cbf16e5928060cf009fbbb3beec826006a876ddbede0ee9512f7",
|
||||
"bytes": 10460
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/field-Bs9V8Rb1.js",
|
||||
"sha256": "da55fbacb606cdb51f6eb09fb8bf4963fe249e869d653f0fb71d3c0da9ed7b4c",
|
||||
"bytes": 8422
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/format-2xch3ZbY.js",
|
||||
"sha256": "a98c816d31f9a937c5418dd48d25bc5b7b96fb3084d58571565d0810f420ced9",
|
||||
"bytes": 14363
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/index-C_mEe-tZ.js",
|
||||
"sha256": "6c6620136850dbdfa6ea22a9fa6c320f3f5d33150b83f1d1b9597e0894f5d0de",
|
||||
"bytes": 117757
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/index-D80qzV0-.css",
|
||||
"sha256": "c0c7a7706d3d4a4ca2baa88f31aa2fd5c6080b4f2e539b4812a99d51f2de9fd0",
|
||||
"bytes": 97051
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/LoginView-Br8nsdQM.js",
|
||||
"sha256": "29bdcbe8030ef2e169b2ea453cef160f2b3c86b9a83718971023a9862e10bd45",
|
||||
"bytes": 6336
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/LoginView-J4b4q6ai.css",
|
||||
"sha256": "15ecdd5cb294bb51eef05e4843ac3a65f6e1718cbf16206547a876c52c5e8a2d",
|
||||
"bytes": 1107
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/MeView-B-MK2tgf.css",
|
||||
"sha256": "a3bd246d2658ee50d4cac9afa1d051c33e8676be3155260256e7106a9c5dd136",
|
||||
"bytes": 927
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/MeView-BOWGunAt.js",
|
||||
"sha256": "9e5ff0c332dfae54d9f8e1c70b0a896e48aef80e8b45101092c08a59dfddf521",
|
||||
"bytes": 3465
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/ShellView-D354hIv5.css",
|
||||
"sha256": "513a381d7ecfe8c24ca22166d658c8604df9d9478a8765ffcef7beb031917dcd",
|
||||
"bytes": 130
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/ShellView-DcQ5QK1V.js",
|
||||
"sha256": "13f70e99d3eccfa014f14dc313a195b4f24200929bf60142f6fd190ef33f2f3d",
|
||||
"bytes": 2939
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/use-placeholder-D9ZemjXL.js",
|
||||
"sha256": "530e97b69f045bf3c2798b79c1f49bd3ee69f53a657bad39825cb69d68552c9c",
|
||||
"bytes": 607
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/icons/apple-touch-icon.png",
|
||||
"sha256": "3167d1d07f22a44ea393b377e5181918ae4890c137de37fe91e2f3780b6ce70e",
|
||||
"bytes": 24681
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/icons/favicon-64.png",
|
||||
"sha256": "7c9d031dcd296a45a79d960481c34eb150dd33e4a2bace6f28385be01c1a675e",
|
||||
"bytes": 5439
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/icons/icon-192.png",
|
||||
"sha256": "9637a4d3e4cbb385ed0b35069d6bb3522b90d1b8aaec439cfdf5ec1264040b5a",
|
||||
"bytes": 26433
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/icons/icon-512.png",
|
||||
"sha256": "803ed98fb41fc724cb5319f45409d5e9725465f6f37cb6312e6b79170f852974",
|
||||
"bytes": 144310
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/icons/icon-maskable-512.png",
|
||||
"sha256": "88b6cecdb691f9e2f4179fd00eae937a5f6863cd61d34aadda1e6ac45e6217a2",
|
||||
"bytes": 95961
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/index.html",
|
||||
"sha256": "6f335e7804fe9a1ce7bb5df388d2af81c7d919ddebb3beaee9533553a36adf04",
|
||||
"bytes": 1357
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/manifest.webmanifest",
|
||||
"sha256": "ac64783b6865e3f68fdc735d5d66cad0c13ffc8b6be6ae5fbebc0e2eac5a61fd",
|
||||
"bytes": 684
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/sw.js",
|
||||
"sha256": "d908e9a6ec5c75ffcca8f9f6d97ec683b005fa211975f89beee372849df44a69",
|
||||
"bytes": 339
|
||||
},
|
||||
{
|
||||
"path": "payload/wechat_rpa/remote_api.py",
|
||||
"sha256": "e8a51c1701a05d54713f45325e03481ad22609bc721455aa5ddef0d3ed5ae29a",
|
||||
"bytes": 37707
|
||||
},
|
||||
{
|
||||
"path": "tests/test_backend.py",
|
||||
"sha256": "7473ec5583c97941e132ade7a1f66abcf54fa6108ec6bb2a182f0152964fff61",
|
||||
"bytes": 66279
|
||||
},
|
||||
{
|
||||
"path": "tests/test_remote_api.py",
|
||||
"sha256": "479cb9b042dc14707af718734c33688013203d4154f36199b7b0ced656653c39",
|
||||
"bytes": 38523
|
||||
},
|
||||
{
|
||||
"path": "tests/test_zyt_auth.py",
|
||||
"sha256": "40ab2d37f51780af26497e22948ef665c92b7f3707f6ba30a6d711bf5b15dfa6",
|
||||
"bytes": 4907
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,27 @@
|
||||
--- production/wechat_rpa/remote_api.py
|
||||
+++ release/wechat_rpa/remote_api.py
|
||||
@@ -79,15 +79,17 @@
|
||||
|
||||
|
||||
def https_required(request: Request) -> bool:
|
||||
- """手机端要在公网上提交 ZYT 密码,明文 HTTP 只允许在内网试用。
|
||||
-
|
||||
- MOBILE_REQUIRE_HTTPS:auto(默认,公网地址必须 HTTPS)/ always / never。
|
||||
-
|
||||
- 没有 X-Real-IP 时按"来源不明"处理:生产环境里直连 API 的对端是 Docker 网桥
|
||||
- (172.x,看起来像内网),代理漏配头就会把公网请求误当内网放行。只有本机回环
|
||||
+ """手机端登录是否必须走 HTTPS。
|
||||
+
|
||||
+ MOBILE_REQUIRE_HTTPS:never(默认,内外网都允许明文 HTTP 登录,按用户要求)/
|
||||
+ auto(公网地址必须 HTTPS,内网可用 HTTP)/ always。配好 HTTPS 入口后建议改成
|
||||
+ auto:明文 HTTP 下 ZYT 密码和手机会话令牌在公网上可被截获。
|
||||
+
|
||||
+ auto 模式下没有 X-Real-IP 时按"来源不明"处理:生产环境里直连 API 的对端是 Docker
|
||||
+ 网桥(172.x,看起来像内网),代理漏配头就会把公网请求误当内网放行。只有本机回环
|
||||
(开发时直接访问 127.0.0.1)才在没有这个头时被信任。
|
||||
"""
|
||||
- policy = os.environ.get("MOBILE_REQUIRE_HTTPS", "auto").strip().lower()
|
||||
+ policy = os.environ.get("MOBILE_REQUIRE_HTTPS", "never").strip().lower()
|
||||
if policy == "never" or request_scheme(request) == "https":
|
||||
return False
|
||||
if policy == "always":
|
||||
@@ -0,0 +1 @@
|
||||
.switcher[data-v-91cf283c]{max-height:80vh}.switcher-body[data-v-91cf283c]{padding:16px 0 12px}.switcher-body h3[data-v-91cf283c]{margin:0 16px 8px;font-size:17px}.switcher-state[data-v-91cf283c]{place-items:center;padding:32px 0;display:grid}.switcher-list[data-v-91cf283c]{margin-top:12px}.current[data-v-91cf283c]{color:var(--app-primary);margin-left:6px}
|
||||
@@ -0,0 +1 @@
|
||||
.detail[data-v-70465908]{padding-bottom:16px}.detail-head[data-v-70465908]{align-items:center;gap:12px;padding:16px;display:flex}.avatar[data-v-70465908]{width:52px;height:52px;color:var(--app-primary);background:var(--app-primary-soft);border-radius:14px;flex:none;place-items:center;font-size:22px;font-weight:600;display:grid}.detail-title[data-v-70465908]{flex:1;min-width:0}.detail-title h2[data-v-70465908]{text-overflow:ellipsis;white-space:nowrap;margin:0 0 4px;font-size:18px;overflow:hidden}.detail-title p[data-v-70465908]{margin:0;font-size:13px}.badge[data-v-70465908]{color:var(--app-danger);background:var(--app-danger-soft);border-radius:999px;flex:none;align-items:center;gap:4px;padding:4px 10px;font-size:12px;font-weight:600;display:inline-flex}.group[data-v-70465908]{margin-bottom:12px}.state[data-v-70465908]{background:var(--app-surface);border:1px solid var(--app-border);border-radius:14px;margin:0 16px;padding:16px}.state--blocked[data-v-70465908]{border-color:var(--app-danger-soft);background:linear-gradient(0deg, var(--app-danger-soft), var(--app-danger-soft)), var(--app-surface)}.state h3[data-v-70465908]{align-items:center;gap:6px;margin:0 0 6px;font-size:15px;display:flex}.state--blocked h3[data-v-70465908]{color:var(--app-danger)}.state>p[data-v-70465908]{color:var(--app-text-2);margin:0 0 12px;font-size:13px;line-height:1.6}.state dl[data-v-70465908]{grid-template-columns:repeat(2,minmax(0,1fr));gap:8px 12px;margin:0 0 14px;display:grid}.state dt[data-v-70465908]{color:var(--app-muted);font-size:12px}.state dd[data-v-70465908]{word-break:break-all;margin:2px 0 0;font-size:14px}.reason[data-v-70465908]{margin:0 0 12px}.reason[data-v-70465908] .van-cell-group--inset{margin:0}.state[data-v-70465908] .van-cell-group--inset{margin:0 0 12px}.note[data-v-70465908]{color:var(--app-muted);margin:0;font-size:13px;line-height:1.6}.row[data-v-645c253b]{border:0;border-bottom:1px solid var(--app-border);background:var(--app-surface);width:100%;min-height:64px;color:inherit;text-align:left;cursor:pointer;align-items:center;gap:12px;padding:10px 16px;display:flex}.row[data-v-645c253b]:active,.row.active[data-v-645c253b]{background:var(--app-primary-soft)}.avatar[data-v-645c253b]{border-radius:12px;flex:none;place-items:center;width:42px;height:42px;font-size:17px;font-weight:600;display:grid}.avatar--wecom[data-v-645c253b]{color:#2f6fff;background:#2f6fff1f}.avatar--wechat[data-v-645c253b]{color:#0f9e69;background:#13b77a24}.avatar--group[data-v-645c253b]{color:#7a5cff;background:#8a6bff24}.body[data-v-645c253b]{flex:1;gap:4px;min-width:0;display:grid}.line[data-v-645c253b]{justify-content:space-between;align-items:center;gap:8px;min-width:0;display:flex}.name[data-v-645c253b]{text-overflow:ellipsis;white-space:nowrap;font-size:15px;font-weight:600;overflow:hidden}.time[data-v-645c253b]{color:var(--app-muted);flex:none;font-size:12px}.sub[data-v-645c253b]{color:var(--app-muted);font-size:12px}.meta[data-v-645c253b]{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.blocked[data-v-645c253b]{color:var(--app-danger);background:var(--app-danger-soft);border-radius:999px;flex:none;padding:1px 8px;font-weight:600}.page[data-v-cc7f80e6]{min-height:100%}.nav-action[data-v-cc7f80e6]{color:var(--app-primary);background:0 0;border:0;align-items:center;gap:4px;padding:6px 0;font-size:14px;display:inline-flex}.toolbar[data-v-cc7f80e6]{top:calc(46px + env(safe-area-inset-top));z-index:2;background:var(--app-bg);position:-webkit-sticky;position:sticky}.toolbar[data-v-cc7f80e6] .van-search{background:0 0;padding-bottom:4px}.tabs[data-v-cc7f80e6]{--van-tabs-nav-background:transparent;padding:0 4px}.list-body[data-v-cc7f80e6]{min-height:60vh}.single .list-pane[data-v-cc7f80e6]{max-width:720px;margin:0 auto}.split[data-v-cc7f80e6]{grid-template-columns:minmax(300px,380px) minmax(0,1fr);align-items:start;gap:16px;max-width:1180px;margin:0 auto;padding:0 24px 24px;display:grid}.split .list-body[data-v-cc7f80e6]{border-radius:16px;overflow:clip}.detail-pane[data-v-cc7f80e6]{top:calc(46px + env(safe-area-inset-top) + 12px);min-height:320px;margin-top:12px;position:-webkit-sticky;position:sticky}.sheet[data-v-cc7f80e6]{max-height:88vh;padding-top:8px}
|
||||
@@ -0,0 +1 @@
|
||||
.panel[data-v-bcd7f731]{padding:16px}.panel-head[data-v-bcd7f731]{align-items:flex-start;gap:12px;display:flex}.panel-icon[data-v-bcd7f731]{width:44px;height:44px;color:var(--app-primary);background:var(--app-primary-soft);border-radius:12px;flex:none;place-items:center;font-size:22px;display:grid}.panel-title[data-v-bcd7f731]{flex:1;min-width:0}.panel-title h2[data-v-bcd7f731]{text-overflow:ellipsis;white-space:nowrap;margin:2px 0 4px;font-size:17px;font-weight:600;overflow:hidden}.panel-title p[data-v-bcd7f731]{margin:0;font-size:13px;line-height:1.45}.pill[data-v-bcd7f731]{white-space:nowrap;border-radius:999px;flex:none;align-items:center;gap:6px;padding:4px 10px;font-size:12px;font-weight:600;display:inline-flex}.pill .dot[data-v-bcd7f731]{background:currentColor;border-radius:50%;width:7px;height:7px}.pill--success[data-v-bcd7f731]{color:var(--app-success);background:var(--app-success-soft)}.pill--success .dot[data-v-bcd7f731]{box-shadow:0 0 0 3px var(--app-success-soft);animation:2.2s ease-in-out infinite breathe-bcd7f731}.pill--warning[data-v-bcd7f731]{color:var(--app-warning);background:var(--app-warning-soft)}.pill--danger[data-v-bcd7f731]{color:var(--app-danger);background:var(--app-danger-soft)}.pill--muted[data-v-bcd7f731],.pill--primary[data-v-bcd7f731]{color:var(--app-muted);background:var(--app-muted-soft)}@keyframes breathe-bcd7f731{50%{opacity:.45}}.stats[data-v-bcd7f731]{grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;margin:16px 0 0;display:grid}.stat[data-v-bcd7f731]{background:var(--app-surface-2);border:1px solid var(--app-border);border-radius:12px;padding:10px 12px}.stat dt[data-v-bcd7f731]{color:var(--app-muted);font-size:12px}.stat dd[data-v-bcd7f731]{margin:4px 0 0;font-size:15px;font-weight:600}.meta[data-v-bcd7f731]{margin:12px 0 0;font-size:12px}.progress[data-v-bcd7f731]{border-radius:12px;align-items:center;gap:8px;margin-top:12px;padding:10px 12px;font-size:13px;line-height:1.45;display:flex}.progress--primary[data-v-bcd7f731]{color:var(--app-primary);background:var(--app-primary-soft)}.progress--success[data-v-bcd7f731]{color:var(--app-success);background:var(--app-success-soft)}.progress--danger[data-v-bcd7f731]{color:var(--app-danger);background:var(--app-danger-soft)}.progress--warning[data-v-bcd7f731]{color:var(--app-warning);background:var(--app-warning-soft)}.progress--muted[data-v-bcd7f731]{color:var(--app-muted);background:var(--app-muted-soft)}.actions[data-v-bcd7f731]{margin-top:16px}.blocked[data-v-bcd7f731]{margin:10px 4px 0;font-size:13px;line-height:1.5}.page[data-v-8ead1f63]{min-height:100%}.page-body[data-v-8ead1f63]{min-height:calc(100vh - 96px);min-height:calc(100dvh - 96px)}.content[data-v-8ead1f63]{max-width:720px;margin:0 auto;padding:12px 16px 24px}.stack[data-v-8ead1f63]{gap:12px;display:grid}.skeleton-card[data-v-8ead1f63]{padding:16px 0}.empty-hint[data-v-8ead1f63]{max-width:280px;color:var(--app-muted);text-align:center;margin:0 auto;font-size:13px;line-height:1.6}.nav-action[data-v-8ead1f63]{color:var(--app-primary);background:0 0;border:0;align-items:center;gap:4px;padding:6px 0;font-size:14px;display:inline-flex}.stale[data-v-8ead1f63]{margin:0 4px;font-size:12px}.split[data-v-8ead1f63]{grid-template-columns:minmax(240px,320px) minmax(0,1fr);align-items:start;gap:16px;max-width:1080px;margin:0 auto;padding:16px 24px 24px;display:grid}.split-list[data-v-8ead1f63]{gap:10px;display:grid}.device-row[data-v-8ead1f63]{text-align:left;width:100%;color:inherit;cursor:pointer;align-items:center;gap:12px;padding:12px 14px;display:flex}.device-row.active[data-v-8ead1f63]{border-color:var(--app-primary);box-shadow:0 0 0 2px var(--app-primary-soft)}.device-row-icon[data-v-8ead1f63]{color:var(--app-primary);font-size:20px}.device-row-text[data-v-8ead1f63]{gap:2px;min-width:0;display:grid}.device-row-text strong[data-v-8ead1f63]{text-overflow:ellipsis;white-space:nowrap;font-size:15px;overflow:hidden}.device-row-text small[data-v-8ead1f63]{font-size:12px}
|
||||
@@ -0,0 +1 @@
|
||||
.login[data-v-004201f6]{min-height:100vh;min-height:100dvh;padding:calc(env(safe-area-inset-top) + 24px) 16px calc(env(safe-area-inset-bottom) + 24px);background:radial-gradient(120% 60% at 50% 0%, var(--app-primary-soft), transparent 70%), var(--app-bg);justify-content:center;align-items:center;display:flex}.login-card[data-v-004201f6]{width:100%;max-width:420px}.login-head[data-v-004201f6]{text-align:center;margin-bottom:24px}.login-mark[data-v-004201f6]{box-shadow:var(--app-shadow);border-radius:20px}.login-head h1[data-v-004201f6]{letter-spacing:.5px;margin:16px 0 6px;font-size:24px;font-weight:700}.login-head p[data-v-004201f6]{color:var(--app-muted);margin:0;font-size:14px}.login-notice[data-v-004201f6]{border-radius:12px;margin:0 16px 12px}.login-form[data-v-004201f6] .van-cell-group--inset,.login-form[data-v-004201f6]{margin:0}.login-error[data-v-004201f6]{color:var(--app-danger);margin:12px 16px 0;font-size:14px;line-height:1.5}.login-actions[data-v-004201f6]{margin:20px 16px 0}.login-foot[data-v-004201f6]{text-align:center;color:var(--app-muted);margin:16px 16px 0;font-size:12px}
|
||||
@@ -0,0 +1 @@
|
||||
.content[data-v-1710faf3]{max-width:720px;margin:0 auto;padding:12px 0 32px}.profile[data-v-1710faf3]{align-items:center;gap:14px;margin:0 16px;padding:16px;display:flex}.avatar[data-v-1710faf3]{color:#fff;background:linear-gradient(135deg,#2f6fff,#5a65ff);border-radius:50%;flex:none;place-items:center;width:54px;height:54px;font-size:22px;font-weight:700;display:grid}.profile-text[data-v-1710faf3]{flex:1;min-width:0}.profile-text h2[data-v-1710faf3]{margin:0 0 4px;font-size:18px}.profile-text p[data-v-1710faf3]{margin:0;font-size:13px}.root[data-v-1710faf3]{color:var(--app-warning);background:var(--app-warning-soft);border-radius:999px;flex:none;padding:4px 10px;font-size:12px;font-weight:600}.section-title[data-v-1710faf3]{color:var(--app-muted);margin:24px 32px 8px;font-size:13px;font-weight:600}.hint[data-v-1710faf3]{margin:8px 32px 0;font-size:12px;line-height:1.6}.logout[data-v-1710faf3]{margin:32px 16px 0}
|
||||
@@ -0,0 +1 @@
|
||||
import{n as e,t}from"./_plugin-vue_export-helper-4o9rbdkf.js";import{a as n,i as r,o as i,s as a}from"./format-2xch3ZbY.js";import{a as o,n as s,t as c}from"./cell-group-CEKvg8Wf.js";import{Ct as l,Ft as u,Jt as d,Kt as f,Lt as p,St as m,Ut as h,Yt as g,_t as _,d as v,ft as y,gt as b,ht as x,i as S,n as C,qt as w,vt as T,xt as E,yt as D}from"./index-C_mEe-tZ.js";var O={class:`page`},k={key:0,class:`content`},A={class:`profile app-card`},j={class:`avatar`,"aria-hidden":`true`},M={class:`profile-text`},N={class:`app-muted`},P={key:0,class:`root`},F={class:`hint app-muted`},I={class:`logout`},L=t(l({__name:`MeView`,setup(t){let l=v(),L=f(!1),R=x(()=>C.me),z=x(()=>{let e=R.value;if(!e)return[];let{permissions:t,permission_codes:n}=e;return[{title:`查看本人电脑与会话`,code:`登录即可`,granted:!0},{title:`远程启停本人电脑`,code:n.control,granted:t.control},{title:`查看并控制所有客服电脑`,code:n.control_all,granted:t.control_all},{title:`会话加入黑名单`,code:n.blacklist_add,granted:t.blacklist_add},{title:`会话移出黑名单`,code:n.blacklist_remove,granted:t.blacklist_remove}]}),B=x(()=>{var e;let t=(e=R.value)==null?void 0:e.session.expires_at;return t?new Date(t*1e3).toISOString():``}),V=/iPhone|iPad|iPod/.test(navigator.userAgent);async function H(){try{await a({title:`退出登录?`,message:`退出后需要重新输入 ZYT 账号密码。`,confirmButtonText:`退出`})}catch{return}L.value=!0,await S(),await l.replace({name:`login`})}return(t,a)=>(u(),D(`div`,O,[m(w(i),{title:`我的`,"safe-area-inset-top":``,fixed:``,placeholder:``,border:!1}),R.value?(u(),D(`div`,k,[b(`section`,A,[b(`span`,j,g(w(r)(R.value.account.nickname||R.value.account.sn)),1),b(`div`,M,[b(`h2`,null,g(R.value.account.nickname||R.value.account.sn),1),b(`p`,N,`ZYT 账号 `+g(R.value.account.sn||`—`),1)]),R.value.permissions.root?(u(),D(`span`,P,`超级管理员`)):T(``,!0)]),a[1]||(a[1]=b(`h3`,{class:`section-title`},`手机端权限`,-1)),m(w(c),{inset:``},{default:h(()=>[(u(!0),D(y,null,p(z.value,t=>(u(),_(w(s),{key:t.title,title:t.title,label:t.code,center:``},{value:h(()=>[b(`span`,{class:d(t.granted?`tone-success`:`tone-muted`)},[m(w(e),{name:t.granted?`passed`:`close`},null,8,[`name`]),E(` `+g(t.granted?`已开通`:`未开通`),1)],2)]),_:2},1032,[`title`,`label`]))),128))]),_:1}),a[2]||(a[2]=b(`p`,{class:`hint app-muted`},` 权限在 ZYT「权限管理 → 角色管理」里勾选「企微客服助手」下的项目,调整后 10 分钟内自动生效,或退出重新登录。 `,-1)),a[3]||(a[3]=b(`h3`,{class:`section-title`},`登录信息`,-1)),m(w(c),{inset:``},{default:h(()=>[m(w(s),{title:`登录时间`,value:w(n)(R.value.session.created_at)},null,8,[`value`]),m(w(s),{title:`最长有效至`,value:B.value?w(n)(B.value):`—`,label:`ZYT 登录失效后会提前退出`},null,8,[`value`])]),_:1}),a[4]||(a[4]=b(`h3`,{class:`section-title`},`添加到主屏幕`,-1)),b(`p`,F,[w(V)?(u(),D(y,{key:0},[E(`在 Safari 中点底部「分享」按钮,选择「添加到主屏幕」,之后像 App 一样打开。`)],64)):(u(),D(y,{key:1},[E(`在浏览器菜单中选择「添加到主屏幕」或「安装应用」,之后像 App 一样打开。`)],64))]),b(`div`,I,[m(w(o),{block:``,round:``,type:`danger`,plain:``,loading:L.value,onClick:H},{default:h(()=>[...a[0]||(a[0]=[E(`退出登录`,-1)])]),_:1},8,[`loading`])])])):T(``,!0)]))}}),[[`__scopeId`,`data-v-1710faf3`]]);export{L as default};
|
||||
@@ -0,0 +1 @@
|
||||
.shell[data-v-5972669c]{min-height:100vh;min-height:100dvh}.shell-tabbar[data-v-5972669c]{border-top:1px solid var(--app-border)}
|
||||
@@ -0,0 +1 @@
|
||||
import{a as e,n as t,o as n,p as r,r as i,t as a}from"./_plugin-vue_export-helper-4o9rbdkf.js";import{n as o,t as s}from"./use-placeholder-D9ZemjXL.js";import{B as c,Ct as l,Et as u,Ft as d,Kt as f,Q as p,Rt as m,S as h,St as g,U as _,Ut as v,X as y,Z as b,_ as x,_t as S,g as C,ht as w,pt as T,q as E,qt as D,rt as O,wt as k,xt as A,yt as j,zt as M}from"./index-C_mEe-tZ.js";var[N,P]=x(`tabbar`),F={route:Boolean,fixed:b,border:b,zIndex:y,placeholder:Boolean,activeColor:String,beforeChange:Function,inactiveColor:String,modelValue:E(0),safeAreaInsetBottom:{type:Boolean,default:null}},I=Symbol(N),L=l({name:N,props:F,emits:[`change`,`update:modelValue`],setup(e,{emit:t,slots:n}){let i=f(),{linkChildren:a}=c(I),l=s(i,P),u=()=>{var t;return(t=e.safeAreaInsetBottom)==null?e.fixed:t},d=()=>{var t;let{fixed:a,zIndex:o,border:s}=e;return g(`div`,{ref:i,role:`tablist`,style:h(o),class:[P({fixed:a}),{[r]:s,"van-safe-area-bottom":u()}]},[(t=n.default)==null?void 0:t.call(n)])};return a({props:e,setActive:(n,r)=>{o(e.beforeChange,{args:[n],done(){t(`update:modelValue`,n),t(`change`,n),r()}})}}),()=>e.fixed&&e.placeholder?l(d):d()}}),R=C(L),[z,B]=x(`tabbar-item`),V=p({},e,{dot:Boolean,icon:String,name:y,badge:y,badgeProps:Object,iconPrefix:String}),H=l({name:z,props:V,emits:[`click`],setup(e,{emit:r,slots:a}){let o=n(),s=k().proxy,{parent:c,index:l}=_(I);if(!c)return;let d=w(()=>{var t;let{route:n,modelValue:r}=c.props;if(n&&`$route`in s){let{$route:t}=s,{to:n}=e,r=O(n)?n:{path:n};return t.matched.some(e=>{let t=`path`in r&&r.path===e.path,n=`name`in r&&r.name===e.name;return t||n})}return((t=e.name)==null?l.value:t)===r}),f=t=>{var n;d.value||c.setActive((n=e.name)==null?l.value:n,o),r(`click`,t)},p=()=>{if(a.icon)return a.icon({active:d.value});if(e.icon)return g(t,{name:e.icon,classPrefix:e.iconPrefix},null)};return()=>{var t;let{dot:n,badge:r}=e,{activeColor:o,inactiveColor:s}=c.props,l=d.value?o:s;return g(`div`,{role:`tab`,class:B({active:d.value}),style:{color:l},tabindex:0,"aria-selected":d.value,onClick:f},[g(i,u({dot:n,class:B(`icon`),content:r},e.badgeProps),{default:p}),g(`div`,{class:B(`text`)},[(t=a.default)==null?void 0:t.call(a,{active:d.value})])])}}}),U=C(H),W={class:`shell`},G=a(l({__name:`ShellView`,setup(e){return(e,t)=>{let n=m(`RouterView`);return d(),j(`div`,W,[g(n,null,{default:v(({Component:e})=>[(d(),S(T,{include:[`DevicesView`,`ConversationsView`]},[(d(),S(M(e)))],1024))]),_:1}),g(D(R),{route:``,placeholder:``,"safe-area-inset-bottom":``,class:`shell-tabbar`},{default:v(()=>[g(D(U),{replace:``,to:{name:`desktops`},icon:`desktop-o`},{default:v(()=>[...t[0]||(t[0]=[A(`电脑`,-1)])]),_:1}),g(D(U),{replace:``,to:{name:`conversations`},icon:`chat-o`},{default:v(()=>[...t[1]||(t[1]=[A(`会话`,-1)])]),_:1}),g(D(U),{replace:``,to:{name:`me`},icon:`user-o`},{default:v(()=>[...t[2]||(t[2]=[A(`我的`,-1)])]),_:1})]),_:1})])}}}),[[`__scopeId`,`data-v-5972669c`]]);export{G as default};
|
||||
@@ -0,0 +1 @@
|
||||
import{Ct as e,Et as t,St as n,Tt as r,Vt as i,X as a,Y as o,Z as s,_ as c,et as l,g as u,ht as d,m as f,nt as p,v as m,wt as h}from"./index-C_mEe-tZ.js";var g=`van-hairline`,_=`${g}--top`,v=`${g}--left`;`${g}`;var y=`${g}--bottom`,b=`${g}--surround`,x=`${g}--top-bottom`;`${g}`;var S=`van-haptics-feedback`,C=Symbol(`van-form`),w=Symbol();function T(e){let t=r(w,null);t&&i(t,t=>{t&&e()})}var E={to:[String,Object],url:String,replace:Boolean};function D({to:e,url:t,replace:n,$router:r}){e&&r?r[n?`replace`:`push`](e):t&&(n?location.replace(t):location.href=t)}function O(){let e=h().proxy;return()=>D(e)}var[k,A]=c(`badge`),j={dot:Boolean,max:a,tag:o(`div`),color:String,offset:Array,content:a,showZero:s,position:o(`top-right`)},M=e({name:k,props:j,setup(e,{slots:t}){let r=()=>{if(t.content)return!0;let{content:n,showZero:r}=e;return l(n)&&n!==``&&(r||n!==0&&n!==`0`)},i=()=>{let{dot:n,max:i,content:a}=e;if(!n&&r())return t.content?t.content():l(i)&&p(a)&&+a>+i?`${i}+`:a},a=e=>e.startsWith(`-`)?e.replace(`-`,``):`-${e}`,o=d(()=>{let n={background:e.color};if(e.offset){let[r,i]=e.offset,{position:o}=e,[s,c]=o.split(`-`);t.default?(n[s]=typeof i==`number`?m(s===`top`?i:-i):s===`top`?m(i):a(i),n[c]=typeof r==`number`?m(c===`left`?r:-r):c===`left`?m(r):a(r)):(n.marginTop=m(i),n.marginLeft=m(r))}return n}),s=()=>{if(r()||e.dot)return n(`div`,{class:A([e.position,{dot:e.dot,fixed:!!t.default}]),style:o.value},[i()])};return()=>{if(t.default){let{tag:r}=e;return n(r,{class:A(`wrapper`)},{default:()=>[t.default(),s()]})}return s()}}}),N=u(M),[P,F]=c(`icon`),I=e=>e==null?void 0:e.includes(`/`),L={dot:Boolean,tag:o(`i`),name:String,size:a,badge:a,color:String,badgeProps:Object,classPrefix:String},R=e({name:P,props:L,setup(e,{slots:i}){let a=r(f,null),o=d(()=>e.classPrefix||(a==null?void 0:a.iconPrefix)||F());return()=>{let{tag:r,dot:a,name:s,size:c,badge:l,color:u}=e,d=I(s);return n(N,t({dot:a,tag:r,class:[o.value,d?``:`${o.value}-${s}`],style:{color:u,fontSize:m(c)},content:l},e.badgeProps),{default:()=>{var e;return[(e=i.default)==null?void 0:e.call(i),d&&n(`img`,{class:F(`image`),src:s},null)]}})}}}),z=u(R),B=(e,t)=>{let n=e.__vccOpts||e;for(let[e,r]of t)n[e]=r;return n};export{E as a,T as c,b as d,_ as f,S as h,D as i,y as l,C as m,z as n,O as o,x as p,N as r,w as s,B as t,v as u};
|
||||
|
After Width: | Height: | Size: 16 KiB |
@@ -0,0 +1 @@
|
||||
import{a as e,d as t,n,o as r,p as i}from"./_plugin-vue_export-helper-4o9rbdkf.js";import{Ct as a,Et as o,O as s,Q as c,St as l,X as u,Y as d,Z as f,_ as p,et as m,ft as h,g,ht as _,v,wt as y,x as b}from"./index-C_mEe-tZ.js";function x(e){let t=y();t&&c(t.proxy,e)}var[S,C]=p(`loading`),w=Array(12).fill(null).map((e,t)=>l(`i`,{class:C(`line`,String(t+1))},null)),T=l(`svg`,{class:C(`circular`),viewBox:`25 25 50 50`},[l(`circle`,{cx:`50`,cy:`50`,r:`20`,fill:`none`},null)]),E={size:u,type:d(`circular`),color:String,vertical:Boolean,textSize:u,textColor:String},D=a({name:S,props:E,setup(e,{slots:t}){let n=_(()=>c({color:e.color},b(e.size))),r=()=>{let r=e.type===`spinner`?w:T;return l(`span`,{class:C(`spinner`,e.type),style:n.value},[t.icon?t.icon():r])},i=()=>{var n;if(t.default)return l(`span`,{class:C(`text`),style:{fontSize:v(e.textSize),color:(n=e.textColor)==null?e.color:n}},[t.default()])};return()=>{let{type:t,vertical:n}=e;return l(`div`,{class:C([t,{vertical:n}]),"aria-live":`polite`,"aria-busy":!0},[r(),i()])}}}),O=g(D),[k,A]=p(`button`),j=c({},e,{tag:d(`button`),text:String,icon:String,type:d(`default`),size:d(`normal`),color:String,block:Boolean,plain:Boolean,round:Boolean,square:Boolean,loading:Boolean,hairline:Boolean,disabled:Boolean,iconPrefix:String,nativeType:d(`button`),loadingSize:u,loadingText:String,loadingType:String,iconPosition:d(`left`)}),M=a({name:k,props:j,emits:[`click`],setup(e,{emit:i,slots:a}){let o=r(),c=()=>a.loading?a.loading():l(O,{size:e.loadingSize,type:e.loadingType,class:A(`loading`)},null),u=()=>{if(e.loading)return c();if(a.icon)return l(`div`,{class:A(`icon`)},[a.icon()]);if(e.icon)return l(n,{name:e.icon,class:A(`icon`),classPrefix:e.iconPrefix},null)},d=()=>{let t;if(t=e.loading?e.loadingText:a.default?a.default():e.text,t)return l(`span`,{class:A(`text`)},[t])},f=()=>{let{color:t,plain:n}=e;if(t){let e={color:n?t:`white`};return n||(e.background=t),t.includes(`gradient`)?e.border=0:e.borderColor=t,e}},p=t=>{e.loading?s(t):e.disabled||(i(`click`,t),o())};return()=>{let{tag:n,type:r,size:i,block:a,round:o,plain:s,square:c,loading:m,disabled:h,hairline:g,nativeType:_,iconPosition:v}=e,y=[A([r,i,{plain:s,block:a,round:o,square:c,loading:m,disabled:h,hairline:g}]),{[t]:g}];return l(n,{type:_,class:y,style:f(),disabled:h,onClick:p},{default:()=>[l(`div`,{class:A(`content`)},[v===`left`&&u(),d(),v===`right`&&u()])]})}}}),N=g(M),P=()=>{var e;let{scopeId:t}=((e=y())==null?void 0:e.vnode)||{};return t?{[t]:``}:null},[F,I]=p(`cell`),L={tag:d(`div`),icon:String,size:String,title:u,value:u,label:u,center:Boolean,isLink:Boolean,border:f,iconPrefix:String,valueClass:null,labelClass:null,titleClass:null,titleStyle:null,arrowDirection:String,required:{type:[Boolean,String],default:null},clickable:{type:Boolean,default:null}},R=c({},L,e),z=a({name:F,props:R,setup(e,{slots:t}){let i=r(),a=()=>{if(t.label||m(e.label))return l(`div`,{class:[I(`label`),e.labelClass]},[t.label?t.label():e.label])},o=()=>{var n;if(t.title||m(e.title)){let r=(n=t.title)==null?void 0:n.call(t);return Array.isArray(r)&&r.length===0?void 0:l(`div`,{class:[I(`title`),e.titleClass],style:e.titleStyle},[r||l(`span`,null,[e.title]),a()])}},s=()=>{let n=t.value||t.default;if(n||m(e.value))return l(`div`,{class:[I(`value`),e.valueClass]},[n?n():l(`span`,null,[e.value])])},c=()=>{if(t.icon)return t.icon();if(e.icon)return l(n,{name:e.icon,class:I(`left-icon`),classPrefix:e.iconPrefix},null)},u=()=>{if(t[`right-icon`])return t[`right-icon`]();if(e.isLink){let t=e.arrowDirection&&e.arrowDirection!==`right`?`arrow-${e.arrowDirection}`:`arrow`;return l(n,{name:t,class:I(`right-icon`)},null)}};return()=>{var n,r,a;let{tag:d,size:f,center:p,border:m,isLink:h,required:g}=e,_=!!((a=(r=(n=e.clickable)==null?e.to:n)==null?e.url:r)==null?h:a),v={center:p,required:!!g,clickable:_,borderless:!m};return f&&(v[f]=!!f),l(d,{class:I(v),role:_?`button`:void 0,tabindex:_?0:void 0,onClick:_?i:void 0},{default:()=>{var e;return[c(),o(),s(),u(),(e=t.extra)==null?void 0:e.call(t)]}})}}}),B=g(z),[V,H]=p(`cell-group`),U=a({name:V,inheritAttrs:!1,props:{title:String,inset:Boolean,border:f},setup(e,{slots:t,attrs:n}){let r=()=>{var r;return l(`div`,o({class:[H({inset:e.inset}),{[i]:e.border&&!e.inset}]},n,P()),[(r=t.default)==null?void 0:r.call(t)])},a=()=>l(`div`,{class:H(`title`,{inset:e.inset})},[t.title?t.title():e.title]);return()=>e.title||t.title?l(h,null,[a(),r()]):r()}}),W=g(U);export{N as a,P as i,B as n,O as o,L as r,x as s,W as t};
|
||||
@@ -0,0 +1 @@
|
||||
import{c as e}from"./_plugin-vue_export-helper-4o9rbdkf.js";import{Dt as t,Kt as n,M as r,Mt as i,N as a,St as o,Vt as s,W as c,at as l,it as u}from"./index-C_mEe-tZ.js";function d(e,{args:t=[],done:n,canceled:r,error:i}){if(e){let a=e.apply(null,t);u(a)?a.then(e=>{e?n():r&&r()}).catch(i||l):a?n():r&&r()}else n()}var f=(o,l)=>{let u=n(),d=()=>{u.value=c(o).height};return i(()=>{if(t(d),l)for(let e=1;e<=3;e++)setTimeout(d,100*e)}),e(()=>t(d)),s([a,r],d),u};function p(e,t){let n=f(e,!0);return e=>o(`div`,{class:t(`placeholder`),style:{height:n.value?`${n.value}px`:void 0}},[e()])}export{d as n,p as t};
|
||||
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 5.3 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 141 KiB |
|
After Width: | Height: | Size: 94 KiB |
@@ -0,0 +1,26 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<meta name="color-scheme" content="light dark" />
|
||||
<meta name="theme-color" content="#f4f7fd" media="(prefers-color-scheme: light)" />
|
||||
<meta name="theme-color" content="#0b1222" media="(prefers-color-scheme: dark)" />
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
|
||||
<meta name="apple-mobile-web-app-title" content="客服控制台" />
|
||||
<meta name="format-detection" content="telephone=no" />
|
||||
<meta name="referrer" content="no-referrer" />
|
||||
<link rel="manifest" href="/m/manifest.webmanifest" />
|
||||
<link rel="icon" type="image/png" href="/m/icons/favicon-64.png" />
|
||||
<link rel="apple-touch-icon" href="/m/icons/apple-touch-icon.png" />
|
||||
<title>企微客服助手 · 手机控制台</title>
|
||||
<script type="module" crossorigin src="/m/assets/index-C_mEe-tZ.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/m/assets/index-D80qzV0-.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<noscript>请在浏览器设置中开启 JavaScript 后再打开手机控制台。</noscript>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"name": "企微客服助手 · 手机控制台",
|
||||
"short_name": "客服控制台",
|
||||
"description": "远程查看和启停客服电脑的自动回复,管理会话黑名单。",
|
||||
"lang": "zh-CN",
|
||||
"start_url": "/m/",
|
||||
"scope": "/m/",
|
||||
"display": "standalone",
|
||||
"orientation": "any",
|
||||
"background_color": "#f4f7fd",
|
||||
"theme_color": "#2f6fff",
|
||||
"icons": [
|
||||
{ "src": "/m/icons/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any" },
|
||||
{ "src": "/m/icons/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any" },
|
||||
{ "src": "/m/icons/icon-maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
// 手机控制台的 Service Worker 只为"添加到主屏幕"存在,不缓存任何内容:
|
||||
// 远程控制看到的必须是实时状态,离线缓存只会展示过期的电脑状态。
|
||||
self.addEventListener('install', () => self.skipWaiting());
|
||||
self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim()));
|
||||
@@ -0,0 +1,804 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""手机远程控制台与桌面命令通道的 HTTP 接口。
|
||||
|
||||
/api/v2/mobile/* 手机 / 平板 H5 用,ZYT 账号密码登录(终端 9,由本服务代登)
|
||||
/api/v2/desktop/commands/* 桌面端长轮询领取指令、回执结果、顺带上报状态
|
||||
/api/v2/desktop/blacklist* 桌面端同步服务端会话黑名单
|
||||
|
||||
手机令牌和桌面令牌分别由 ``mobile_sessions`` 和 ``desktop_sessions`` 签发,互相
|
||||
不能冒用:手机端拿不到归档上传之类的桌面接口,桌面端也调不了手机接口。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import ipaddress
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from collections import defaultdict, deque
|
||||
from typing import Any, Callable
|
||||
|
||||
from fastapi import Depends, FastAPI, HTTPException, Query, Request
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
import zyt_auth
|
||||
from remote_store import (
|
||||
COMMAND_TYPES,
|
||||
MOBILE_IDENTITY_RECHECK_SECONDS,
|
||||
PERM_BLACKLIST_ADD,
|
||||
PERM_BLACKLIST_REMOVE,
|
||||
PERM_REMOTE_ALL,
|
||||
PERM_REMOTE_CONTROL,
|
||||
RemoteStore,
|
||||
account_label,
|
||||
account_permissions,
|
||||
valid_device_id,
|
||||
)
|
||||
|
||||
# 桌面端长轮询最长挂起时间。uvicorn 停机时会等在途请求结束,这里必须明显短于
|
||||
# compose 里 20 秒的 stop_grace_period,否则每次发版都会被强杀;指令本身靠进程内
|
||||
# 通知即时送达,挂起时长只影响"没事时多久回来报一次状态"。
|
||||
MAX_POLL_WAIT_SECONDS = 15
|
||||
# 挂起期间多久回库复查一次;进程内通知失效(多进程部署)时的兜底。
|
||||
POLL_RECHECK_SECONDS = 5
|
||||
|
||||
|
||||
def _error(status_code: int, code: str, message: str, **extra: Any) -> HTTPException:
|
||||
return HTTPException(status_code=status_code, detail={"code": code, "message": message, **extra})
|
||||
|
||||
|
||||
def _bearer(request: Request) -> str:
|
||||
raw = request.headers.get("authorization", "")
|
||||
return raw[7:].strip() if raw.lower().startswith("bearer ") else ""
|
||||
|
||||
|
||||
def trusted_client_ip(request: Request) -> str:
|
||||
"""做安全判断用的客户端地址。
|
||||
|
||||
X-Forwarded-For 的第一段是客户端自己填的,可以伪造;X-Real-IP 由 Nginx 按
|
||||
$remote_addr 覆盖写入,API 端口又只监听本机回环,只有 Nginx 能连进来。
|
||||
"""
|
||||
real_ip = request.headers.get("x-real-ip", "").strip()
|
||||
if real_ip:
|
||||
return real_ip
|
||||
return request.client.host if request.client else ""
|
||||
|
||||
|
||||
def _is_private_address(value: str) -> bool:
|
||||
try:
|
||||
address = ipaddress.ip_address(str(value or "").strip())
|
||||
except ValueError:
|
||||
return False
|
||||
return address.is_private or address.is_loopback or address.is_link_local
|
||||
|
||||
|
||||
def request_scheme(request: Request) -> str:
|
||||
forwarded = request.headers.get("x-forwarded-proto", "").split(",")[0].strip().lower()
|
||||
return forwarded or request.url.scheme.lower()
|
||||
|
||||
|
||||
def https_required(request: Request) -> bool:
|
||||
"""手机端登录是否必须走 HTTPS。
|
||||
|
||||
MOBILE_REQUIRE_HTTPS:never(默认,内外网都允许明文 HTTP 登录,按用户要求)/
|
||||
auto(公网地址必须 HTTPS,内网可用 HTTP)/ always。配好 HTTPS 入口后建议改成
|
||||
auto:明文 HTTP 下 ZYT 密码和手机会话令牌在公网上可被截获。
|
||||
|
||||
auto 模式下没有 X-Real-IP 时按"来源不明"处理:生产环境里直连 API 的对端是 Docker
|
||||
网桥(172.x,看起来像内网),代理漏配头就会把公网请求误当内网放行。只有本机回环
|
||||
(开发时直接访问 127.0.0.1)才在没有这个头时被信任。
|
||||
"""
|
||||
policy = os.environ.get("MOBILE_REQUIRE_HTTPS", "never").strip().lower()
|
||||
if policy == "never" or request_scheme(request) == "https":
|
||||
return False
|
||||
if policy == "always":
|
||||
return True
|
||||
real_ip = request.headers.get("x-real-ip", "").strip()
|
||||
if real_ip:
|
||||
return not _is_private_address(real_ip)
|
||||
peer = request.client.host if request.client else ""
|
||||
try:
|
||||
return not ipaddress.ip_address(peer).is_loopback
|
||||
except ValueError:
|
||||
return True
|
||||
|
||||
|
||||
class LoginAttempt:
|
||||
__slots__ = ("ip", "account", "finished")
|
||||
|
||||
def __init__(self, ip: str, account: str):
|
||||
self.ip, self.account, self.finished = ip, account, False
|
||||
|
||||
|
||||
class MobileLoginGuard:
|
||||
"""手机登录限流。
|
||||
|
||||
ZYT 按请求来源 IP 计数锁定(默认 30 分钟内错 5 次锁 30 分钟),而手机端的
|
||||
登录全部由本服务代发,在 ZYT 看来都来自服务器出口 IP——如果公司电脑也走同一
|
||||
个出口,锁住的就是全公司的 ZYT 登录。所以这里除了按账号、按客户端 IP 限流,
|
||||
还给"真正发到 ZYT 的密码错误"设了一个全局预算,并在 ZYT 已锁定时直接短路。
|
||||
|
||||
限流必须把"正在进行"的尝试也算进去:先检查、等 ZYT 回来再记账的话,一次并发
|
||||
发来十几个请求会全部通过检查,一起打到 ZYT 上。`begin()` 在锁里占位,
|
||||
`finish()` 按结果转成失败记录或释放。
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, *, account_limit: int = 5, account_window: int = 600,
|
||||
ip_limit: int = 10, ip_window: int = 600,
|
||||
upstream_budget: int | None = None, upstream_window: int = 1800,
|
||||
):
|
||||
if upstream_budget is None:
|
||||
try:
|
||||
upstream_budget = int(os.environ.get("MOBILE_LOGIN_UPSTREAM_FAILURE_BUDGET", "4"))
|
||||
except ValueError:
|
||||
upstream_budget = 4
|
||||
self.account_limit, self.account_window = account_limit, account_window
|
||||
self.ip_limit, self.ip_window = ip_limit, ip_window
|
||||
self.upstream_budget, self.upstream_window = max(0, upstream_budget), upstream_window
|
||||
self._accounts: dict[str, deque[float]] = {}
|
||||
self._ips: dict[str, deque[float]] = {}
|
||||
self._upstream: deque[float] = deque()
|
||||
self._pending_accounts: dict[str, int] = defaultdict(int)
|
||||
self._pending_ips: dict[str, int] = defaultdict(int)
|
||||
self._pending_upstream = 0
|
||||
self._locked_until = 0.0
|
||||
self._lock = threading.Lock()
|
||||
|
||||
@staticmethod
|
||||
def _recent(book: dict[str, deque[float]], key: str, window: int, now: float) -> deque[float]:
|
||||
"""剪掉过期记录;空了就把这个键删掉,随机账号名刷不大内存。"""
|
||||
items = book.get(key)
|
||||
if items is None:
|
||||
return deque()
|
||||
while items and items[0] <= now - window:
|
||||
items.popleft()
|
||||
if not items:
|
||||
del book[key]
|
||||
return items
|
||||
|
||||
@staticmethod
|
||||
def _minutes(seconds: float) -> int:
|
||||
return max(1, int((seconds + 59) // 60))
|
||||
|
||||
def begin(self, ip: str, account: str) -> LoginAttempt:
|
||||
now = time.time()
|
||||
with self._lock:
|
||||
if self._locked_until > now:
|
||||
wait = self._locked_until - now
|
||||
raise _error(
|
||||
429, "zyt_locked",
|
||||
f"ZYT 已暂时锁定登录,请 {self._minutes(wait)} 分钟后再试",
|
||||
retry_after=int(wait),
|
||||
)
|
||||
failures = self._recent(self._accounts, account, self.account_window, now)
|
||||
if len(failures) >= self.account_limit:
|
||||
wait = failures[0] + self.account_window - now
|
||||
raise _error(
|
||||
429, "rate_limited",
|
||||
f"该账号登录失败次数过多,请 {self._minutes(wait)} 分钟后再试",
|
||||
retry_after=int(wait),
|
||||
)
|
||||
if len(failures) + self._pending_accounts.get(account, 0) >= self.account_limit:
|
||||
raise _error(429, "rate_limited", "该账号正在登录,请稍候几秒再试", retry_after=5)
|
||||
failures = self._recent(self._ips, ip, self.ip_window, now)
|
||||
if len(failures) + self._pending_ips.get(ip, 0) >= self.ip_limit:
|
||||
wait = (failures[0] + self.ip_window - now) if failures else 5
|
||||
raise _error(
|
||||
429, "rate_limited",
|
||||
f"登录尝试过于频繁,请 {self._minutes(wait)} 分钟后再试",
|
||||
retry_after=int(wait),
|
||||
)
|
||||
while self._upstream and self._upstream[0] <= now - self.upstream_window:
|
||||
self._upstream.popleft()
|
||||
if self.upstream_budget:
|
||||
if len(self._upstream) >= self.upstream_budget:
|
||||
wait = self._upstream[0] + self.upstream_window - now
|
||||
raise _error(
|
||||
429, "upstream_budget",
|
||||
"近期手机端密码错误次数较多,为避免 ZYT 锁定服务器出口 IP,"
|
||||
f"已暂停手机登录,请 {self._minutes(wait)} 分钟后再试",
|
||||
retry_after=int(wait),
|
||||
)
|
||||
if len(self._upstream) + self._pending_upstream >= self.upstream_budget:
|
||||
raise _error(429, "rate_limited", "同时登录的人较多,请几秒后再试", retry_after=5)
|
||||
self._pending_accounts[account] += 1
|
||||
self._pending_ips[ip] += 1
|
||||
self._pending_upstream += 1
|
||||
return LoginAttempt(ip, account)
|
||||
|
||||
def finish(self, attempt: LoginAttempt, outcome: str) -> None:
|
||||
"""outcome:credentials(密码错)、unknown_account(账号不存在)、success(ZYT 认可了密码)、
|
||||
other(网络、终端未开通等,不记账)。"""
|
||||
if attempt.finished:
|
||||
return
|
||||
attempt.finished = True
|
||||
now = time.time()
|
||||
with self._lock:
|
||||
for book, key in ((self._pending_accounts, attempt.account), (self._pending_ips, attempt.ip)):
|
||||
book[key] -= 1
|
||||
if book[key] <= 0:
|
||||
del book[key]
|
||||
self._pending_upstream = max(0, self._pending_upstream - 1)
|
||||
if outcome in ("credentials", "unknown_account"):
|
||||
self._accounts.setdefault(attempt.account, deque()).append(now)
|
||||
self._ips.setdefault(attempt.ip, deque()).append(now)
|
||||
# ZYT 只给"账号存在、密码不对"累计出口 IP 的失败次数。
|
||||
if outcome == "credentials":
|
||||
self._upstream.append(now)
|
||||
elif outcome == "success":
|
||||
self._accounts.pop(attempt.account, None)
|
||||
# 密码校验通过时 ZYT 会清零该出口 IP 的失败计数(AdminAccountSafeCache::relieve)。
|
||||
self._upstream.clear()
|
||||
|
||||
def locked(self, seconds: int) -> None:
|
||||
with self._lock:
|
||||
self._locked_until = max(self._locked_until, time.time() + max(60, int(seconds)))
|
||||
|
||||
|
||||
class ZytMobileAuth:
|
||||
"""默认实现:真的去调 ZYT。测试里换成假的。"""
|
||||
|
||||
def __init__(self, api_url: Callable[[], str]):
|
||||
self._api_url = api_url
|
||||
|
||||
def login(self, account: str, password: str) -> str:
|
||||
return zyt_auth.login_admin(
|
||||
account, password, terminal=zyt_auth.WECOM_RPA_MOBILE_TERMINAL, api_url=self._api_url()
|
||||
)
|
||||
|
||||
def identity(self, token: str) -> dict[str, Any]:
|
||||
return zyt_auth.verify_admin_session(
|
||||
token, terminal=zyt_auth.WECOM_RPA_MOBILE_TERMINAL, api_url=self._api_url()
|
||||
)
|
||||
|
||||
def logout(self, token: str) -> None:
|
||||
zyt_auth.logout_admin(token, api_url=self._api_url())
|
||||
|
||||
|
||||
class _Waiter:
|
||||
__slots__ = ("key", "loop", "event")
|
||||
|
||||
def __init__(self, key: tuple[int, str]):
|
||||
self.key = key
|
||||
self.loop = asyncio.get_running_loop()
|
||||
self.event = asyncio.Event()
|
||||
|
||||
async def wait(self, timeout: float) -> None:
|
||||
try:
|
||||
await asyncio.wait_for(self.event.wait(), timeout=max(0.0, timeout))
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
|
||||
|
||||
class CommandNotifier:
|
||||
"""进程内唤醒:有新指令或黑名单变化时,立刻结束对应电脑挂着的长轮询。
|
||||
|
||||
先登记再查库:登记和查库之间落库的指令也能把它叫醒,不会白等一个复查周期。
|
||||
唤醒走 ``call_soon_threadsafe``,发通知的请求和挂起的长轮询不在同一个事件
|
||||
循环(线程)里也不会漏掉。
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._waiters: dict[tuple[int, str], set[_Waiter]] = {}
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def register(self, account_id: int, device_id: str) -> _Waiter:
|
||||
waiter = _Waiter((int(account_id), str(device_id)))
|
||||
with self._lock:
|
||||
self._waiters.setdefault(waiter.key, set()).add(waiter)
|
||||
return waiter
|
||||
|
||||
def unregister(self, waiter: _Waiter) -> None:
|
||||
with self._lock:
|
||||
waiters = self._waiters.get(waiter.key)
|
||||
if waiters is not None:
|
||||
waiters.discard(waiter)
|
||||
if not waiters:
|
||||
self._waiters.pop(waiter.key, None)
|
||||
|
||||
def notify(self, account_id: int, device_id: str | None = None) -> None:
|
||||
with self._lock:
|
||||
targets = [
|
||||
waiter
|
||||
for key, waiters in self._waiters.items()
|
||||
if key[0] == int(account_id) and (device_id is None or key[1] == device_id)
|
||||
for waiter in waiters
|
||||
]
|
||||
for waiter in targets:
|
||||
try:
|
||||
waiter.loop.call_soon_threadsafe(waiter.event.set)
|
||||
except RuntimeError:
|
||||
# 事件循环已经关闭(请求刚好结束),没有人需要被叫醒。
|
||||
continue
|
||||
|
||||
|
||||
class MobilePrincipal:
|
||||
def __init__(self, row: dict[str, Any], token: str):
|
||||
self.row = row
|
||||
self.token = token
|
||||
self.permissions = account_permissions(row)
|
||||
|
||||
@property
|
||||
def account_id(self) -> int:
|
||||
return int(self.row["id"])
|
||||
|
||||
@property
|
||||
def session_id(self) -> int:
|
||||
return int(self.row["session_id"])
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
return f"{account_label(self.row)}(手机)"
|
||||
|
||||
def me(self) -> dict[str, Any]:
|
||||
return {
|
||||
"account": {
|
||||
"id": self.account_id,
|
||||
"nickname": str(self.row.get("nickname") or ""),
|
||||
"sn": str(self.row.get("zyt_sn") or ""),
|
||||
"avatar": str(self.row.get("avatar") or ""),
|
||||
},
|
||||
"permissions": {
|
||||
"control": self.permissions["control"],
|
||||
"control_all": self.permissions["control_all"],
|
||||
"blacklist_add": self.permissions["blacklist_add"],
|
||||
"blacklist_remove": self.permissions["blacklist_remove"],
|
||||
"root": self.permissions["root"],
|
||||
"known": self.permissions["known"],
|
||||
},
|
||||
"permission_codes": {
|
||||
"control": PERM_REMOTE_CONTROL,
|
||||
"control_all": PERM_REMOTE_ALL,
|
||||
"blacklist_add": PERM_BLACKLIST_ADD,
|
||||
"blacklist_remove": PERM_BLACKLIST_REMOVE,
|
||||
},
|
||||
"session": {
|
||||
"created_at": str(self.row.get("session_created_at") or ""),
|
||||
"expires_at": int(self.row.get("session_expires_at") or 0),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
# ── 请求体 ───────────────────────────────────────────────────────────────────
|
||||
class MobileLoginBody(BaseModel):
|
||||
account: str = Field(min_length=1, max_length=64)
|
||||
password: str = Field(min_length=1, max_length=128, repr=False)
|
||||
client_name: str = Field(default="", max_length=120)
|
||||
|
||||
|
||||
class CommandBody(BaseModel):
|
||||
type: str = Field(min_length=1, max_length=32)
|
||||
|
||||
|
||||
class BlacklistBody(BaseModel):
|
||||
name: str = Field(default="", max_length=191)
|
||||
account_name: str = Field(default="", max_length=191)
|
||||
reason: str = Field(default="", max_length=200)
|
||||
|
||||
|
||||
class StatusBody(BaseModel):
|
||||
listening: bool = False
|
||||
state: str = Field(default="", max_length=32)
|
||||
transport: str = Field(default="", max_length=16)
|
||||
wecom_connected: bool = False
|
||||
pending_count: int = Field(default=0, ge=0, le=1_000_000)
|
||||
app_version: str = Field(default="", max_length=64)
|
||||
capabilities: list[str] = Field(default_factory=list, max_length=16)
|
||||
|
||||
|
||||
class DesktopPollBody(BaseModel):
|
||||
wait: int = Field(default=15, ge=0, le=60)
|
||||
status: StatusBody | None = None
|
||||
# 桌面端当前持有的黑名单版本;与服务端不一致时立即返回,让它去同步。
|
||||
blacklist_version: int | None = Field(default=None, ge=0)
|
||||
|
||||
|
||||
class AckBody(BaseModel):
|
||||
ok: bool
|
||||
result: dict[str, Any] = Field(default_factory=dict)
|
||||
error: str = Field(default="", max_length=500)
|
||||
status: StatusBody | None = None
|
||||
|
||||
|
||||
class DesktopBlacklistSyncBody(BaseModel):
|
||||
add: list[dict[str, Any]] = Field(default_factory=list, max_length=500)
|
||||
|
||||
|
||||
def register_remote_routes(
|
||||
app: FastAPI,
|
||||
database: Any,
|
||||
*,
|
||||
current_desktop: Callable[..., Any],
|
||||
zyt_api_url: Callable[[], str],
|
||||
zyt_mobile_auth: Any = None,
|
||||
login_guard: MobileLoginGuard | None = None,
|
||||
) -> RemoteStore:
|
||||
store = RemoteStore(database)
|
||||
store.initialize()
|
||||
app.state.remote_store = store
|
||||
notifier = CommandNotifier()
|
||||
app.state.remote_notifier = notifier
|
||||
guard = login_guard or MobileLoginGuard()
|
||||
auth = zyt_mobile_auth or ZytMobileAuth(zyt_api_url)
|
||||
identity_locks: dict[int, asyncio.Lock] = {}
|
||||
|
||||
# ── 手机端鉴权 ───────────────────────────────────────────────────────
|
||||
async def _recheck_identity(row: dict[str, Any], request: Request) -> dict[str, Any] | None:
|
||||
# 同一会话并发的几个请求只复核一次;用完即删,锁表不随会话数增长。
|
||||
session_id = int(row["session_id"])
|
||||
lock = identity_locks.setdefault(session_id, asyncio.Lock())
|
||||
try:
|
||||
async with lock:
|
||||
return await _recheck_identity_locked(session_id, request)
|
||||
finally:
|
||||
if not lock.locked() and identity_locks.get(session_id) is lock:
|
||||
identity_locks.pop(session_id, None)
|
||||
|
||||
async def _recheck_identity_locked(session_id: int, request: Request) -> dict[str, Any] | None:
|
||||
fresh = await asyncio.to_thread(store.mobile_session, _bearer(request))
|
||||
if fresh is None:
|
||||
return None
|
||||
if time.time() - int(fresh["identity_checked_at"] or 0) < MOBILE_IDENTITY_RECHECK_SECONDS:
|
||||
return fresh
|
||||
zyt_token = await asyncio.to_thread(store.mobile_zyt_token, session_id)
|
||||
try:
|
||||
if not zyt_token:
|
||||
raise zyt_auth.ZytLoginError("ZYT 会话缺失", kind="rejected")
|
||||
identity = await asyncio.to_thread(auth.identity, zyt_token)
|
||||
if str(identity.get("user_id") or "") != str(fresh["zyt_user_id"]):
|
||||
raise zyt_auth.ZytLoginError("ZYT 身份与手机会话不一致", kind="rejected")
|
||||
except zyt_auth.ZytAuthError as exc:
|
||||
if getattr(exc, "kind", "") == "unavailable":
|
||||
# ZYT 暂时连不上不算下线:沿用上次同步的权限,一分钟后再试。
|
||||
await asyncio.to_thread(store.mark_identity_checked, session_id, retry_in=60)
|
||||
return fresh
|
||||
await asyncio.to_thread(
|
||||
store.revoke_mobile_session, session_id=session_id,
|
||||
reason="zyt_invalid", ip=trusted_client_ip(request),
|
||||
)
|
||||
return None
|
||||
try:
|
||||
await asyncio.to_thread(store.refresh_identity, session_id, identity)
|
||||
except PermissionError:
|
||||
await asyncio.to_thread(
|
||||
store.revoke_mobile_session, session_id=session_id,
|
||||
reason="account_disabled", ip=trusted_client_ip(request),
|
||||
)
|
||||
return None
|
||||
return await asyncio.to_thread(store.mobile_session, _bearer(request))
|
||||
|
||||
async def current_mobile(request: Request) -> MobilePrincipal:
|
||||
token = _bearer(request)
|
||||
row = await asyncio.to_thread(store.mobile_session, token) if token else None
|
||||
if row is not None and time.time() - int(row["identity_checked_at"] or 0) >= MOBILE_IDENTITY_RECHECK_SECONDS:
|
||||
row = await _recheck_identity(row, request)
|
||||
if row is None:
|
||||
raise _error(401, "session_expired", "登录已失效,请重新登录")
|
||||
return MobilePrincipal(row, token)
|
||||
|
||||
def target_account(principal: MobilePrincipal, account_id: int | None) -> dict[str, Any]:
|
||||
if account_id is None or int(account_id) == principal.account_id:
|
||||
return principal.row
|
||||
if not principal.permissions["control_all"]:
|
||||
raise _error(403, "forbidden", "只能查看和控制自己的电脑")
|
||||
account = store.account(int(account_id))
|
||||
if account is None or str(account.get("status")) != "active":
|
||||
raise _error(404, "account_not_found", "客服账号不存在或已停用")
|
||||
return account
|
||||
|
||||
# ── 手机端:登录 ─────────────────────────────────────────────────────
|
||||
@app.post("/api/v2/mobile/auth/login")
|
||||
async def mobile_login(body: MobileLoginBody, request: Request) -> dict:
|
||||
ip = trusted_client_ip(request)
|
||||
if https_required(request):
|
||||
raise _error(403, "https_required", "请通过 HTTPS 地址访问手机控制台,明文连接不能提交密码")
|
||||
account_key = body.account.strip().lower()
|
||||
attempt = guard.begin(ip, account_key)
|
||||
outcome = "other"
|
||||
try:
|
||||
zyt_token = await asyncio.to_thread(auth.login, body.account.strip(), body.password)
|
||||
outcome = "success"
|
||||
except zyt_auth.ZytLoginError as exc:
|
||||
if exc.kind in ("credentials", "unknown_account"):
|
||||
outcome = exc.kind
|
||||
database.audit(None, "mobile.login.failed", f"account={account_key[:64]}", ip)
|
||||
raise _error(401, "invalid_credentials", "账号或密码错误") from exc
|
||||
if exc.kind == "password_change_required":
|
||||
outcome = "success"
|
||||
raise _error(403, "password_change_required", str(exc)) from exc
|
||||
if exc.kind == "locked":
|
||||
guard.locked(exc.retry_after or 1800)
|
||||
database.audit(None, "mobile.login.locked", f"account={account_key[:64]}", ip)
|
||||
raise _error(429, "zyt_locked", str(exc), retry_after=exc.retry_after) from exc
|
||||
if exc.kind == "disabled":
|
||||
raise _error(403, "account_disabled", str(exc)) from exc
|
||||
if exc.kind == "terminal_unsupported":
|
||||
raise _error(503, "terminal_unsupported", str(exc)) from exc
|
||||
if exc.kind == "unavailable":
|
||||
raise _error(502, "zyt_unavailable", "ZYT 登录服务暂不可用,请稍后重试") from exc
|
||||
raise _error(400, "login_rejected", str(exc)) from exc
|
||||
except zyt_auth.ZytAuthError as exc:
|
||||
raise _error(502, "zyt_unavailable", "ZYT 登录服务暂不可用,请稍后重试") from exc
|
||||
finally:
|
||||
guard.finish(attempt, outcome)
|
||||
try:
|
||||
identity = await asyncio.to_thread(auth.identity, zyt_token)
|
||||
account = await asyncio.to_thread(store.upsert_account, identity)
|
||||
except zyt_auth.ZytLoginError as exc:
|
||||
await asyncio.to_thread(auth.logout, zyt_token)
|
||||
status_code = {"terminal_unsupported": 503, "disabled": 403}.get(exc.kind, 502)
|
||||
code = {"terminal_unsupported": "terminal_unsupported",
|
||||
"disabled": "account_disabled"}.get(exc.kind, "zyt_unavailable")
|
||||
raise _error(status_code, code, str(exc)) from exc
|
||||
except zyt_auth.ZytAuthError as exc:
|
||||
await asyncio.to_thread(auth.logout, zyt_token)
|
||||
raise _error(502, "zyt_unavailable", str(exc)) from exc
|
||||
except PermissionError as exc:
|
||||
await asyncio.to_thread(auth.logout, zyt_token)
|
||||
raise _error(403, "account_disabled", str(exc)) from exc
|
||||
except ValueError as exc:
|
||||
await asyncio.to_thread(auth.logout, zyt_token)
|
||||
raise _error(502, "zyt_unavailable", str(exc)) from exc
|
||||
token, session = await asyncio.to_thread(
|
||||
store.create_mobile_session, int(account["id"]), zyt_token=zyt_token,
|
||||
client_name=body.client_name, user_agent=request.headers.get("user-agent", ""), ip=ip,
|
||||
)
|
||||
row = await asyncio.to_thread(store.mobile_session, token)
|
||||
principal = MobilePrincipal(row, token)
|
||||
return {"access_token": token, "expires_at": session["expires_at"], "me": principal.me()}
|
||||
|
||||
@app.post("/api/v2/mobile/auth/logout")
|
||||
async def mobile_logout(request: Request, principal: MobilePrincipal = Depends(current_mobile)) -> dict:
|
||||
zyt_token = await asyncio.to_thread(store.mobile_zyt_token, principal.session_id)
|
||||
await asyncio.to_thread(
|
||||
store.revoke_mobile_session, session_id=principal.session_id, reason="logout",
|
||||
ip=trusted_client_ip(request),
|
||||
)
|
||||
if zyt_token:
|
||||
await asyncio.to_thread(auth.logout, zyt_token)
|
||||
return {"ok": True}
|
||||
|
||||
@app.get("/api/v2/mobile/me")
|
||||
async def mobile_me(principal: MobilePrincipal = Depends(current_mobile)) -> dict:
|
||||
return principal.me()
|
||||
|
||||
# ── 手机端:电脑 ─────────────────────────────────────────────────────
|
||||
@app.get("/api/v2/mobile/accounts")
|
||||
async def mobile_accounts(
|
||||
q: str = Query(default="", max_length=64),
|
||||
principal: MobilePrincipal = Depends(current_mobile),
|
||||
) -> dict:
|
||||
if not principal.permissions["control_all"]:
|
||||
raise _error(403, "forbidden", f"查看全部客服电脑需要 ZYT 权限 {PERM_REMOTE_ALL}")
|
||||
return {"items": await asyncio.to_thread(store.accounts_overview, q)}
|
||||
|
||||
@app.get("/api/v2/mobile/desktops")
|
||||
async def mobile_desktops(
|
||||
account_id: int | None = Query(default=None, ge=1),
|
||||
principal: MobilePrincipal = Depends(current_mobile),
|
||||
) -> dict:
|
||||
account = target_account(principal, account_id)
|
||||
items = await asyncio.to_thread(store.devices, int(account["id"]))
|
||||
return {
|
||||
"account": {
|
||||
"id": int(account["id"]),
|
||||
"nickname": str(account.get("nickname") or ""),
|
||||
"sn": str(account.get("zyt_sn") or ""),
|
||||
},
|
||||
"items": items,
|
||||
"server_time": int(time.time()),
|
||||
}
|
||||
|
||||
@app.post("/api/v2/mobile/desktops/{device_id}/commands")
|
||||
async def mobile_create_command(
|
||||
device_id: str, body: CommandBody, request: Request,
|
||||
account_id: int | None = Query(default=None, ge=1),
|
||||
principal: MobilePrincipal = Depends(current_mobile),
|
||||
) -> dict:
|
||||
account = target_account(principal, account_id)
|
||||
if not principal.permissions["control"]:
|
||||
raise _error(403, "forbidden", f"远程启停需要 ZYT 权限 {PERM_REMOTE_CONTROL}")
|
||||
if body.type not in COMMAND_TYPES:
|
||||
raise _error(400, "invalid_command", "不支持的指令")
|
||||
try:
|
||||
device_id = valid_device_id(device_id)
|
||||
except ValueError as exc:
|
||||
raise _error(404, "device_not_found", "电脑不存在") from exc
|
||||
device = await asyncio.to_thread(store.device, int(account["id"]), device_id)
|
||||
if device is None:
|
||||
raise _error(404, "device_not_found", "电脑不存在或已被管理端下线")
|
||||
if not device["online"]:
|
||||
raise _error(409, "device_offline", "电脑离线:客服软件没有运行,无法远程拉起")
|
||||
if not device["remote_capable"]:
|
||||
raise _error(409, "client_outdated", "该电脑上的客服软件版本过低,请升级后再远程控制")
|
||||
try:
|
||||
command = await asyncio.to_thread(
|
||||
store.create_command, account_id=int(account["id"]), device_id=device_id,
|
||||
command_type=body.type, actor_account_id=principal.account_id,
|
||||
actor_label=principal.label, ip=trusted_client_ip(request),
|
||||
)
|
||||
except LookupError as exc:
|
||||
raise _error(404, "device_not_found", str(exc)) from exc
|
||||
notifier.notify(int(account["id"]), device_id)
|
||||
return {"command": command}
|
||||
|
||||
@app.get("/api/v2/mobile/commands/{command_id}")
|
||||
async def mobile_command(
|
||||
command_id: str, principal: MobilePrincipal = Depends(current_mobile),
|
||||
) -> dict:
|
||||
command = await asyncio.to_thread(store.command, command_id)
|
||||
if command is None:
|
||||
raise _error(404, "command_not_found", "指令不存在")
|
||||
if command["account_id"] != principal.account_id and not principal.permissions["control_all"]:
|
||||
raise _error(404, "command_not_found", "指令不存在")
|
||||
command.pop("account_id", None)
|
||||
return {"command": command}
|
||||
|
||||
# ── 手机端:会话与黑名单 ─────────────────────────────────────────────
|
||||
@app.get("/api/v2/mobile/conversations")
|
||||
async def mobile_conversations(
|
||||
account_id: int | None = Query(default=None, ge=1),
|
||||
q: str = Query(default="", max_length=100),
|
||||
scope: str = Query(default="all", pattern="^(all|blocked)$"),
|
||||
cursor: str = Query(default="", max_length=200),
|
||||
limit: int = Query(default=30, ge=1, le=100),
|
||||
principal: MobilePrincipal = Depends(current_mobile),
|
||||
) -> dict:
|
||||
account = target_account(principal, account_id)
|
||||
try:
|
||||
return await asyncio.to_thread(
|
||||
store.conversations, str(account["tenant_id"]), query=q, scope=scope,
|
||||
cursor=cursor, limit=limit,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise _error(400, "invalid_cursor", str(exc)) from exc
|
||||
|
||||
@app.put("/api/v2/mobile/blacklist/{account}/{conversation:path}")
|
||||
async def mobile_blacklist_add(
|
||||
account: str, conversation: str, body: BlacklistBody, request: Request,
|
||||
account_id: int | None = Query(default=None, ge=1),
|
||||
principal: MobilePrincipal = Depends(current_mobile),
|
||||
) -> dict:
|
||||
target = target_account(principal, account_id)
|
||||
if not principal.permissions["blacklist_add"]:
|
||||
raise _error(403, "forbidden", f"加入黑名单需要 ZYT 权限 {PERM_BLACKLIST_ADD}")
|
||||
try:
|
||||
entry, version = await asyncio.to_thread(
|
||||
store.add_blacklist, str(target["tenant_id"]),
|
||||
{"account": account, "conversation": conversation, **body.model_dump()},
|
||||
source="mobile", actor_label=principal.label,
|
||||
actor_account_id=principal.account_id, ip=trusted_client_ip(request),
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise _error(400, "invalid_conversation", str(exc)) from exc
|
||||
notifier.notify(int(target["id"]))
|
||||
return {"entry": entry, "version": version}
|
||||
|
||||
@app.delete("/api/v2/mobile/blacklist/{account}/{conversation:path}")
|
||||
async def mobile_blacklist_remove(
|
||||
account: str, conversation: str, request: Request,
|
||||
account_id: int | None = Query(default=None, ge=1),
|
||||
principal: MobilePrincipal = Depends(current_mobile),
|
||||
) -> dict:
|
||||
target = target_account(principal, account_id)
|
||||
if not principal.permissions["blacklist_remove"]:
|
||||
raise _error(403, "forbidden", f"移出黑名单需要 ZYT 权限 {PERM_BLACKLIST_REMOVE},请联系主管")
|
||||
try:
|
||||
version = await asyncio.to_thread(
|
||||
store.remove_blacklist, str(target["tenant_id"]), account, conversation,
|
||||
source="mobile", actor_label=principal.label, ip=trusted_client_ip(request),
|
||||
)
|
||||
except LookupError as exc:
|
||||
raise _error(404, "not_blocked", str(exc)) from exc
|
||||
except ValueError as exc:
|
||||
raise _error(400, "invalid_conversation", str(exc)) from exc
|
||||
notifier.notify(int(target["id"]))
|
||||
return {"ok": True, "version": version}
|
||||
|
||||
# ── 桌面端:命令通道 ─────────────────────────────────────────────────
|
||||
def _desktop_label(account: Any) -> str:
|
||||
return f"{account_label(account)}(电脑 {str(account['device_name'] or '')[:40]})"
|
||||
|
||||
async def _report(account: Any, status: StatusBody | None) -> None:
|
||||
if status is None:
|
||||
return
|
||||
await asyncio.to_thread(
|
||||
store.report_status, int(account["id"]), str(account["device_id"]),
|
||||
status.model_dump(), app_version=str(account["app_version"] or ""),
|
||||
)
|
||||
|
||||
@app.post("/api/v2/desktop/commands/poll")
|
||||
async def desktop_poll(
|
||||
body: DesktopPollBody, request: Request, account: Any = Depends(current_desktop),
|
||||
) -> dict:
|
||||
account_id = int(account["id"])
|
||||
device_id = str(account["device_id"])
|
||||
tenant = str(account["tenant_id"])
|
||||
await _report(account, body.status)
|
||||
wait = float(min(body.wait, MAX_POLL_WAIT_SECONDS))
|
||||
deadline = time.monotonic() + wait
|
||||
while True:
|
||||
waiter = notifier.register(account_id, device_id)
|
||||
try:
|
||||
commands = await asyncio.to_thread(store.take_commands, account_id, device_id)
|
||||
version = await asyncio.to_thread(store.blacklist_version, tenant)
|
||||
remaining = deadline - time.monotonic()
|
||||
if (
|
||||
commands
|
||||
or (body.blacklist_version is not None and version != body.blacklist_version)
|
||||
or remaining <= 0
|
||||
or await request.is_disconnected()
|
||||
):
|
||||
break
|
||||
await waiter.wait(min(remaining, POLL_RECHECK_SECONDS))
|
||||
finally:
|
||||
notifier.unregister(waiter)
|
||||
return {"commands": commands, "blacklist_version": version, "server_time": int(time.time())}
|
||||
|
||||
@app.post("/api/v2/desktop/commands/{command_id}/ack")
|
||||
async def desktop_ack(
|
||||
command_id: str, body: AckBody, request: Request, account: Any = Depends(current_desktop),
|
||||
) -> dict:
|
||||
await _report(account, body.status)
|
||||
try:
|
||||
command = await asyncio.to_thread(
|
||||
store.ack_command, account_id=int(account["id"]),
|
||||
device_id=str(account["device_id"]), command_id=command_id, ok=body.ok,
|
||||
result=body.result, error=body.error, ip=trusted_client_ip(request),
|
||||
)
|
||||
except LookupError as exc:
|
||||
raise _error(404, "command_not_found", str(exc)) from exc
|
||||
return {"ok": True, "command": command}
|
||||
|
||||
@app.post("/api/v2/desktop/status")
|
||||
async def desktop_status(body: StatusBody, account: Any = Depends(current_desktop)) -> dict:
|
||||
await _report(account, body)
|
||||
return {"ok": True}
|
||||
|
||||
# ── 桌面端:黑名单 ───────────────────────────────────────────────────
|
||||
@app.get("/api/v2/desktop/blacklist")
|
||||
async def desktop_blacklist(account: Any = Depends(current_desktop)) -> dict:
|
||||
version, items = await asyncio.to_thread(store.blacklist, str(account["tenant_id"]))
|
||||
return {"version": version, "items": items}
|
||||
|
||||
@app.post("/api/v2/desktop/blacklist/sync")
|
||||
async def desktop_blacklist_sync(
|
||||
body: DesktopBlacklistSyncBody, request: Request, account: Any = Depends(current_desktop),
|
||||
) -> dict:
|
||||
# 电脑前的人加黑名单不要求 ZYT 权限:拉黑只会让系统少发消息,是安全方向;
|
||||
# 离线时加的、升级前本地就有的条目也都从这里补传。
|
||||
before = await asyncio.to_thread(store.blacklist_version, str(account["tenant_id"]))
|
||||
version, items, rejected = await asyncio.to_thread(
|
||||
store.sync_desktop_blacklist, str(account["tenant_id"]), body.add,
|
||||
actor_label=_desktop_label(account), actor_account_id=int(account["id"]),
|
||||
ip=trusted_client_ip(request),
|
||||
)
|
||||
if version != before:
|
||||
notifier.notify(int(account["id"]))
|
||||
return {"version": version, "items": items, "rejected": rejected}
|
||||
|
||||
@app.delete("/api/v2/desktop/blacklist/{account_key}/{conversation:path}")
|
||||
async def desktop_blacklist_remove(
|
||||
account_key: str, conversation: str, request: Request,
|
||||
account: Any = Depends(current_desktop),
|
||||
) -> dict:
|
||||
if not account_permissions(account)["blacklist_remove"]:
|
||||
raise _error(
|
||||
403, "forbidden",
|
||||
f"移出黑名单需要 ZYT 权限 {PERM_BLACKLIST_REMOVE},请联系主管在手机控制台操作",
|
||||
)
|
||||
try:
|
||||
version = await asyncio.to_thread(
|
||||
store.remove_blacklist, str(account["tenant_id"]), account_key, conversation,
|
||||
source="desktop", actor_label=_desktop_label(account), ip=trusted_client_ip(request),
|
||||
)
|
||||
except LookupError as exc:
|
||||
raise _error(404, "not_blocked", str(exc)) from exc
|
||||
except ValueError as exc:
|
||||
raise _error(400, "invalid_conversation", str(exc)) from exc
|
||||
notifier.notify(int(account["id"]))
|
||||
return {"ok": True, "version": version}
|
||||
|
||||
return store
|
||||
@@ -0,0 +1,97 @@
|
||||
"""Assemble the server bundle locally: payload + manifest + tar.gz. No upload, no deployment.
|
||||
|
||||
python prepare_bundle.py
|
||||
|
||||
Sources: C:/kefu/wechat_rpa/remote_api.py and the rebuilt C:/kefu/admin-web/apps/mobile-h5/dist.
|
||||
Production for these files is exactly the mobile-remote-20260928 payload, so the replaced file is
|
||||
diffed against that payload and the diff is written to payload-diff.txt for review.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import difflib, hashlib, json, shutil, tarfile
|
||||
|
||||
folder = Path(__file__).resolve().parent
|
||||
kefu = folder.parent.parent
|
||||
previous = folder.parent / 'mobile-remote-20260928' / 'payload'
|
||||
plan = json.loads((folder / 'release-plan.json').read_text(encoding='utf-8'))
|
||||
base = json.loads((folder / 'server-baseline.json').read_text(encoding='utf-8'))
|
||||
sha = lambda data: hashlib.sha256(data).hexdigest()
|
||||
lf = lambda data: data.replace(b'\r\n', b'\n')
|
||||
frontend = plan['frontendDir']
|
||||
BANNER = '只能在公司内网登录'.encode()
|
||||
|
||||
# 1. The recorded baseline is what the previous release put on the server.
|
||||
for name, wanted in base['expected'].items():
|
||||
assert sha((previous / name).read_bytes()) == wanted, 'Baseline differs from the deployed payload: ' + name
|
||||
|
||||
# 2. Fresh payload from the working trees; record the backend diff.
|
||||
payload = folder / 'payload'
|
||||
if payload.exists():
|
||||
shutil.rmtree(payload)
|
||||
diff_lines = []
|
||||
for name in plan['backendFiles'] + plan['newBackendFiles'] + plan['deployFiles']:
|
||||
data = lf((kefu / name).read_bytes())
|
||||
assert b'\r' not in data, 'Stray carriage return: ' + name
|
||||
if name.endswith('.py'):
|
||||
compile(data, name, 'exec')
|
||||
before = previous / name
|
||||
if before.exists():
|
||||
diff_lines += difflib.unified_diff(before.read_text(encoding='utf-8').splitlines(),
|
||||
data.decode('utf-8').splitlines(),
|
||||
'production/' + name, 'release/' + name, lineterm='')
|
||||
target = payload / name
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(data)
|
||||
(folder / 'payload-diff.txt').write_text('\n'.join(diff_lines) + '\n', encoding='utf-8')
|
||||
dist = kefu / frontend
|
||||
assert (dist / 'index.html').is_file(), 'Build the phone console first: cd admin-web/apps/mobile-h5 && pnpm build'
|
||||
for text in dist.rglob('*'):
|
||||
if text.is_file():
|
||||
data = text.read_bytes()
|
||||
if text.suffix in {'.html', '.js', '.css', '.json', '.webmanifest'}:
|
||||
assert b'\r\n' not in data, 'CRLF in build output: ' + str(text)
|
||||
assert BANNER not in data, 'Old intranet-only banner still in build: ' + str(text)
|
||||
shutil.copytree(dist, payload / frontend)
|
||||
|
||||
tests = folder / 'tests'
|
||||
if tests.exists():
|
||||
shutil.rmtree(tests)
|
||||
tests.mkdir()
|
||||
for module in plan['serverTestModules']:
|
||||
data = lf((kefu / 'wechat_rpa' / f'{module}.py').read_bytes())
|
||||
compile(data, module, 'exec')
|
||||
(tests / f'{module}.py').write_bytes(data)
|
||||
|
||||
scripts = ['release-plan.json', 'server-baseline.json', 'Dockerfile.overlay', 'remote_server_guard.py',
|
||||
'01-preflight.sh', '02-build.sh', '03-deploy.sh', '04-verify.sh', 'rollback.sh']
|
||||
|
||||
# 3. Manifest over everything the server will verify.
|
||||
manifest = []
|
||||
for path in sorted(p for p in list(payload.rglob('*')) + list(tests.rglob('*')) if p.is_file()):
|
||||
data = path.read_bytes()
|
||||
manifest.append({'path': path.relative_to(folder).as_posix(), 'sha256': sha(data), 'bytes': len(data)})
|
||||
(folder / 'manifest.json').write_text(json.dumps(manifest, indent=2), encoding='utf-8')
|
||||
|
||||
# 4. Server bundle (LF line endings for shell scripts) and archive.
|
||||
bundle = folder / 'server-bundle'
|
||||
if bundle.exists():
|
||||
shutil.rmtree(bundle)
|
||||
bundle.mkdir()
|
||||
shutil.copytree(payload, bundle / 'payload')
|
||||
shutil.copytree(tests, bundle / 'tests')
|
||||
for name in scripts + ['manifest.json']:
|
||||
(bundle / name).write_bytes(lf((folder / name).read_bytes()))
|
||||
archive = folder / 'mobile-http-server-bundle.tar.gz'
|
||||
if archive.exists():
|
||||
archive.unlink()
|
||||
with tarfile.open(archive, 'x:gz') as tf:
|
||||
for p in sorted(bundle.rglob('*')):
|
||||
if p.is_file():
|
||||
arc = p.relative_to(bundle).as_posix(); assert not arc.startswith(('/', '..'))
|
||||
info = tf.gettarinfo(str(p), arcname=arc)
|
||||
info.mode = 0o755 if arc.endswith('.sh') else 0o644
|
||||
info.uid = info.gid = 0
|
||||
info.uname = info.gname = ''
|
||||
with p.open('rb') as handle:
|
||||
tf.addfile(info, handle)
|
||||
print(json.dumps({'archive': str(archive), 'bytes': archive.stat().st_size, 'sha256': sha(archive.read_bytes()),
|
||||
'files': len(manifest), 'diff_lines': len(diff_lines), 'uploaded': False}, ensure_ascii=False, indent=1))
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"release": "mobile-http-20260928",
|
||||
"candidateRoot": "C:/kefu",
|
||||
"backendFiles": [
|
||||
"wechat_rpa/remote_api.py"
|
||||
],
|
||||
"newBackendFiles": [],
|
||||
"deployFiles": [],
|
||||
"frontendDir": "admin-web/apps/mobile-h5/dist",
|
||||
"serverTestModules": [
|
||||
"test_remote_api",
|
||||
"test_zyt_auth",
|
||||
"test_backend"
|
||||
],
|
||||
"imageTestModules": [
|
||||
"test_archive_api"
|
||||
],
|
||||
"schemaMigration": "none",
|
||||
"restartServices": [
|
||||
"api"
|
||||
],
|
||||
"notes": "User request 2026-09-28: the phone console must also work over plain HTTP from outside the office. MOBILE_REQUIRE_HTTPS now defaults to never (auto/always still available once HTTPS exists); the /m/ login page no longer shows the intranet-only banner. No database change."
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
"""Read-only checks for mobile-http-20260928: baseline / candidate / deployed.
|
||||
|
||||
Prints hashes and status only; never reads chat content, patients or credentials.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import argparse, hashlib, json, subprocess, urllib.error, urllib.request
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('mode', choices=['baseline', 'candidate', 'deployed'])
|
||||
args = parser.parse_args()
|
||||
RELEASE = 'mobile-http-20260928'
|
||||
BANNER = '只能在公司内网登录'
|
||||
folder = Path(__file__).resolve().parent
|
||||
project = Path('/opt/im-admin')
|
||||
base = json.loads((folder / 'server-baseline.json').read_text())
|
||||
plan = json.loads((folder / 'release-plan.json').read_text())
|
||||
manifest = json.loads((folder / 'manifest.json').read_text())
|
||||
payload_rows = [row for row in manifest if row['path'].startswith('payload/')]
|
||||
frontend = plan['frontendDir']
|
||||
sha = lambda data: hashlib.sha256(data).hexdigest()
|
||||
image = lambda ref: subprocess.check_output(['docker', 'image', 'inspect', ref, '--format', '{{.Id}}'], text=True).strip()
|
||||
|
||||
# The unpacked bundle itself must be intact.
|
||||
for row in manifest:
|
||||
path = (folder / row['path']).resolve()
|
||||
assert path.is_relative_to(folder), row['path']
|
||||
assert path.stat().st_size == row['bytes'] and sha(path.read_bytes()) == row['sha256'], row['path']
|
||||
|
||||
# project-relative path -> expected sha256 on the host
|
||||
if args.mode == 'baseline':
|
||||
expected_host = dict(base['expected'])
|
||||
else:
|
||||
expected_host = {row['path'][len('payload/'):]: row['sha256'] for row in payload_rows}
|
||||
container_code = {k: v for k, v in expected_host.items() if k.startswith(('wechat_rpa/', 'admin-web/'))}
|
||||
frontend_files = sorted(k[len(frontend) + 1:] for k in expected_host if k.startswith(frontend + '/'))
|
||||
|
||||
|
||||
def in_container(code, target, ref=None):
|
||||
command = (['docker', 'run', '--rm', '-i', '--network=none', '--entrypoint', 'python', ref, '-c', code]
|
||||
if ref else ['docker', 'exec', '-i', 'im-admin-api-1', 'python', '-c', code])
|
||||
return json.loads(subprocess.check_output(command, input=json.dumps(target).encode()))
|
||||
|
||||
|
||||
HASHES = ('from pathlib import Path;import hashlib,json,sys;names=json.load(sys.stdin);'
|
||||
'print(json.dumps({n:(hashlib.sha256((Path("/app")/n).read_bytes()).hexdigest() '
|
||||
'if (Path("/app")/n).is_file() else None) for n in names}))')
|
||||
# /m/ 目录里的完整文件清单(不能残留旧版带横幅的页面文件)和横幅文字检查。
|
||||
FRONTEND = ('from pathlib import Path;import json,sys;q=json.load(sys.stdin);root=Path("/app")/q["root"];'
|
||||
'files=sorted(p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file());'
|
||||
'print(json.dumps({"files":files,"banner":[f for f in files if q["banner"] in '
|
||||
'(root/f).read_bytes().decode("utf-8","ignore")]}))')
|
||||
FRONTEND_QUERY = {'root': frontend, 'banner': BANNER}
|
||||
|
||||
current = image('zyt/wecom-admin:current')
|
||||
result = {'mode': args.mode, 'release': RELEASE, 'image': current}
|
||||
# 只重建 api:网关和知识库 worker 继续跑它们自己的镜像,部署后核对它们没有被动过。
|
||||
OTHERS = ['im-admin-gateway-1', 'im-admin-knowledge-worker-1']
|
||||
|
||||
|
||||
def inspect(container):
|
||||
raw = json.loads(subprocess.check_output(['docker', 'inspect', container]))[0]
|
||||
return {'id': raw['Id'], 'image': raw['Image'], 'running': raw['State']['Running'],
|
||||
'health': raw['State'].get('Health', {}).get('Status', 'not_configured')}
|
||||
|
||||
|
||||
if args.mode == 'baseline':
|
||||
api = inspect('im-admin-api-1')
|
||||
assert api['image'] == current, 'API container is not on zyt/wecom-admin:current'
|
||||
assert api['running'] and api['health'] == 'healthy', 'API container is not healthy'
|
||||
others = {name: inspect(name) for name in OTHERS}
|
||||
for name, state in others.items():
|
||||
assert state['running'], 'Not running: ' + name
|
||||
result['others'] = others
|
||||
|
||||
if args.mode in ('baseline', 'deployed'):
|
||||
for name, wanted in expected_host.items():
|
||||
assert sha((project / name).read_bytes()) == wanted, 'Host drift: ' + name
|
||||
actual = in_container(HASHES, sorted(container_code))
|
||||
assert actual == container_code, 'Running api container differs from expected code'
|
||||
result['files'] = len(expected_host)
|
||||
|
||||
if args.mode == 'candidate':
|
||||
candidate = 'zyt/wecom-admin:' + RELEASE
|
||||
actual = in_container(HASHES, sorted(container_code), candidate)
|
||||
assert actual == container_code, 'Candidate image differs from manifest'
|
||||
listing = in_container(FRONTEND, FRONTEND_QUERY, candidate)
|
||||
assert listing['files'] == frontend_files, 'Candidate /m/ has extra or missing files'
|
||||
assert not listing['banner'], listing['banner']
|
||||
result['candidate'] = image(candidate)
|
||||
result['files'] = len(container_code)
|
||||
|
||||
if args.mode == 'deployed':
|
||||
wanted = image('zyt/wecom-admin:' + RELEASE)
|
||||
assert current == wanted, 'current tag does not point at the release image'
|
||||
raw = json.loads(subprocess.check_output(['docker', 'inspect', 'im-admin-api-1']))[0]
|
||||
assert raw['Image'] == wanted and raw['State']['Running'] and raw['RestartCount'] == 0
|
||||
assert raw['State'].get('Health', {}).get('Status') == 'healthy'
|
||||
recorded = folder / 'baseline-check.json'
|
||||
if recorded.exists():
|
||||
before = json.loads(recorded.read_text())['others']
|
||||
for name in OTHERS:
|
||||
now = inspect(name)
|
||||
assert now['id'] == before[name]['id'] and now['running'], 'Unrelated container changed: ' + name
|
||||
result['others_unchanged'] = OTHERS
|
||||
host_files = sorted(p.relative_to(project / frontend).as_posix() for p in (project / frontend).rglob('*') if p.is_file())
|
||||
assert host_files == frontend_files, 'Host /m/ has extra or missing files'
|
||||
listing = in_container(FRONTEND, FRONTEND_QUERY)
|
||||
assert listing['files'] == frontend_files and not listing['banner'], listing
|
||||
for url in ['http://127.0.0.1:18766/api/v2/health', 'http://127.0.0.1:18770/health']:
|
||||
with urllib.request.urlopen(url, timeout=15) as response:
|
||||
assert response.status == 200, url
|
||||
# New routes still refuse anonymous callers. No login is attempted.
|
||||
for method, path in [('GET', '/api/v2/mobile/me'), ('GET', '/api/v2/mobile/desktops'),
|
||||
('POST', '/api/v2/desktop/commands/poll'), ('GET', '/api/v2/desktop/blacklist')]:
|
||||
request = urllib.request.Request('http://127.0.0.1:18766' + path, method=method,
|
||||
data=b'{}' if method == 'POST' else None,
|
||||
headers={'Content-Type': 'application/json'})
|
||||
try:
|
||||
urllib.request.urlopen(request, timeout=15)
|
||||
except urllib.error.HTTPError as exc:
|
||||
assert exc.code == 401, (path, exc.code)
|
||||
else:
|
||||
raise AssertionError('Accessible without authentication: ' + path)
|
||||
with urllib.request.urlopen('http://127.0.0.1:18766/m/', timeout=15) as response:
|
||||
body = response.read()
|
||||
assert response.status == 200 and '企微客服助手'.encode() in body, 'mobile console entry missing'
|
||||
# 本次目的:公网来源的明文 HTTP 登录不再被拒绝(在运行中的容器里、用它的真实环境变量判断)。
|
||||
code = ("import remote_api,json;from starlette.requests import Request;"
|
||||
"r=Request({'type':'http','method':'POST','path':'/api/v2/mobile/auth/login','root_path':'',"
|
||||
"'headers':[(b'x-real-ip',b'114.114.114.114')],'scheme':'http','query_string':b'',"
|
||||
"'client':('172.18.0.1',40000),'server':('127.0.0.1',8766)});"
|
||||
"print(json.dumps({'public_http_login_refused':remote_api.https_required(r)}))")
|
||||
policy = json.loads(subprocess.check_output(['docker', 'exec', '-i', 'im-admin-api-1', 'python', '-c', code]))
|
||||
assert policy == {'public_http_login_refused': False}, policy
|
||||
result['policy'] = policy
|
||||
|
||||
result['status'] = 'passed'
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env bash
|
||||
# 恢复 remote_api.py 和原 /m/ 目录,切回旧镜像(mobile-remote-20260928),只重建 api。不涉及数据库。
|
||||
set -euo pipefail
|
||||
test "${REMOTE_RELEASE_APPROVED:-}" = mobile-http-20260928
|
||||
release=/home/ps/mobile-http-20260928
|
||||
cd /opt/im-admin/deploy/im-admin
|
||||
test -d "$release/source-before"
|
||||
test "$(docker image inspect zyt/wecom-admin:before-mobile-http-20260928 --format '{{.Id}}')" = "$(cat "$release/image-before.txt")"
|
||||
python3 - <<'PY'
|
||||
from pathlib import Path
|
||||
import hashlib, json, os, shutil
|
||||
r = Path('/home/ps/mobile-http-20260928'); project = Path('/opt/im-admin')
|
||||
base = json.loads((r / 'server-baseline.json').read_text())
|
||||
plan = json.loads((r / 'release-plan.json').read_text())
|
||||
sha = lambda data: hashlib.sha256(data).hexdigest()
|
||||
for name in plan['backendFiles'] + plan['deployFiles']:
|
||||
data = (r / 'source-before' / name).read_bytes(); assert sha(data) == base['expected'][name]
|
||||
target = project / name; tmp = target.with_name(target.name + '.rollback-http.tmp')
|
||||
if tmp.exists():
|
||||
tmp.unlink()
|
||||
with tmp.open('xb') as f:
|
||||
f.write(data)
|
||||
os.chmod(tmp, target.stat().st_mode & 0o777); os.replace(tmp, target)
|
||||
frontend = plan['frontendDir']
|
||||
saved = r / 'source-before' / frontend
|
||||
for name, wanted in base['expected'].items():
|
||||
if name.startswith(frontend + '/'):
|
||||
assert sha((saved / name[len(frontend) + 1:]).read_bytes()) == wanted, name
|
||||
restore = project / (frontend + '.rollback-http.tmp')
|
||||
if restore.exists():
|
||||
shutil.rmtree(restore)
|
||||
shutil.copytree(saved, restore)
|
||||
for leftover in [project / frontend, project / (frontend + '.mobile-http.tmp')]:
|
||||
if leftover.exists():
|
||||
shutil.rmtree(leftover)
|
||||
old = project / (frontend + '.mobile-http.old')
|
||||
if old.exists():
|
||||
shutil.rmtree(old)
|
||||
os.replace(restore, project / frontend)
|
||||
PY
|
||||
docker tag zyt/wecom-admin:before-mobile-http-20260928 zyt/wecom-admin:current
|
||||
docker compose up -d --no-deps --no-build --wait --wait-timeout 180 api
|
||||
curl -fsS -o /dev/null http://127.0.0.1:18766/api/v2/health
|
||||
curl -fsS -o /dev/null http://127.0.0.1:18770/health
|
||||
printf '%s\n' 'Previous image, remote_api.py and /m/ restored.'
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"host": "192.168.110.111",
|
||||
"user": "ps",
|
||||
"project": "/opt/im-admin",
|
||||
"compose": "/opt/im-admin/deploy/im-admin",
|
||||
"checked_at": "2026-09-28",
|
||||
"source": "Production as deployed by mobile-remote-20260928 (15:21): remote_api.py and the 28 /m/ files from that release payload; remote_api.py hash re-read from the host before building this release.",
|
||||
"expected": {
|
||||
"admin-web/apps/mobile-h5/dist/assets/_plugin-vue_export-helper-CT0ZqwFS.js": "97abcbc7c960add5c448947dad40ea8ca6ca2ae18069a632b62b61723e43f24f",
|
||||
"admin-web/apps/mobile-h5/dist/assets/AccountSwitcher-5FuHazzf.js": "8c06092db48aca97b0d3fb35871315e4434b5ad5ccd9c5d44a7cfc3ba343db22",
|
||||
"admin-web/apps/mobile-h5/dist/assets/AccountSwitcher-BZXg15MH.css": "b61f1f1af65c2c3438066ffe41683af7e38062eb9389cda3f8fdad8ee77498ff",
|
||||
"admin-web/apps/mobile-h5/dist/assets/brand-mark-CPUQS9Am.png": "1caa8c492da279e8d01f676fe9232ccad016321699d519b3834692052cc5f5ee",
|
||||
"admin-web/apps/mobile-h5/dist/assets/cell-group-B1PakqJq.js": "7a648b566b9c00c1c8d1b6d2ca9737ca237e521f0e25065cedf86e82fa2471d8",
|
||||
"admin-web/apps/mobile-h5/dist/assets/ConversationsView-CLYafisP.js": "c145f55146ff5373b293e2922b021f55c6851fa34db65fdacb64139fb88c4fa8",
|
||||
"admin-web/apps/mobile-h5/dist/assets/ConversationsView-CytDMSuM.css": "1f646a0178eb9e3f837ac62b5521ec60c0e7d5b4b086b9076c4bf2a7448f98ae",
|
||||
"admin-web/apps/mobile-h5/dist/assets/DevicesView-Cgb9V9Z0.js": "ddb9c705e5cc4822e9166686a7eab319c772540981134f30a9f850fc85ac8692",
|
||||
"admin-web/apps/mobile-h5/dist/assets/DevicesView-CHTvxQxK.css": "40fd5adaea4d4aed376a57c75ebec4544d50f424863704b00ce80b98f7881ddd",
|
||||
"admin-web/apps/mobile-h5/dist/assets/field-CRX3eS7h.js": "393394f3545f3224264be9d1eb87c72b6ce474651b3794b3839f43bfbd69aa86",
|
||||
"admin-web/apps/mobile-h5/dist/assets/format-DEXJ_MrY.js": "d6a7fc2e067a2adcf92b498812422755d5ac8f00acfcf07fd935201eee35c056",
|
||||
"admin-web/apps/mobile-h5/dist/assets/index-D80qzV0-.css": "c0c7a7706d3d4a4ca2baa88f31aa2fd5c6080b4f2e539b4812a99d51f2de9fd0",
|
||||
"admin-web/apps/mobile-h5/dist/assets/index-Gkjcdjlo.js": "63a10401ab035b495ba24c55f9b1bd7ef54c76c6d6bc549f4b0eda62dbd915ac",
|
||||
"admin-web/apps/mobile-h5/dist/assets/LoginView-C25eERA6.css": "b561a20e6d76366db7634b028098ed9f848f665b95f0ffe538f02abce87e8991",
|
||||
"admin-web/apps/mobile-h5/dist/assets/LoginView-nW7aCAJ5.js": "ded80bbda052a9da5f7beaab6af536258b706f2bf0688331fa8bccd9e23355c6",
|
||||
"admin-web/apps/mobile-h5/dist/assets/MeView-B-MK2tgf.css": "a3bd246d2658ee50d4cac9afa1d051c33e8676be3155260256e7106a9c5dd136",
|
||||
"admin-web/apps/mobile-h5/dist/assets/MeView-uJ3uOzy0.js": "711a690039d1fe0d648c285da7bd1ef5b62afe8249d10ad7e76208318fc3094d",
|
||||
"admin-web/apps/mobile-h5/dist/assets/ShellView-CQXCC9xU.js": "8a2afb226d06ece5a929c2c85c4c73bbf68977b4ccde960aa7f6a5ae4614af62",
|
||||
"admin-web/apps/mobile-h5/dist/assets/ShellView-D354hIv5.css": "513a381d7ecfe8c24ca22166d658c8604df9d9478a8765ffcef7beb031917dcd",
|
||||
"admin-web/apps/mobile-h5/dist/assets/use-placeholder-CcVnlsb4.js": "168066192a95a203466245545388b756dfd035c466b007e65ccadc1c94f3fd80",
|
||||
"admin-web/apps/mobile-h5/dist/icons/apple-touch-icon.png": "3167d1d07f22a44ea393b377e5181918ae4890c137de37fe91e2f3780b6ce70e",
|
||||
"admin-web/apps/mobile-h5/dist/icons/favicon-64.png": "7c9d031dcd296a45a79d960481c34eb150dd33e4a2bace6f28385be01c1a675e",
|
||||
"admin-web/apps/mobile-h5/dist/icons/icon-192.png": "9637a4d3e4cbb385ed0b35069d6bb3522b90d1b8aaec439cfdf5ec1264040b5a",
|
||||
"admin-web/apps/mobile-h5/dist/icons/icon-512.png": "803ed98fb41fc724cb5319f45409d5e9725465f6f37cb6312e6b79170f852974",
|
||||
"admin-web/apps/mobile-h5/dist/icons/icon-maskable-512.png": "88b6cecdb691f9e2f4179fd00eae937a5f6863cd61d34aadda1e6ac45e6217a2",
|
||||
"admin-web/apps/mobile-h5/dist/index.html": "d11023af89db5c20bde0c4eaaa35fd9ad192a85353165c0a675e139ae5d94f13",
|
||||
"admin-web/apps/mobile-h5/dist/manifest.webmanifest": "ac64783b6865e3f68fdc735d5d66cad0c13ffc8b6be6ae5fbebc0e2eac5a61fd",
|
||||
"admin-web/apps/mobile-h5/dist/sw.js": "d908e9a6ec5c75ffcca8f9f6d97ec683b005fa211975f89beee372849df44a69",
|
||||
"wechat_rpa/remote_api.py": "843f0a814a0de4f8078f7f9f23a4ac92388d7556c9fe378987f67eda46c55c5b"
|
||||
},
|
||||
"must_not_exist": []
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env bash
|
||||
# 基线核对、备份将被替换的源文件和 /m/ 目录、给当前镜像打回滚标签。只读线上 + 写本目录。
|
||||
set -euo pipefail
|
||||
test "${REMOTE_RELEASE_APPROVED:-}" = mobile-http-20260928
|
||||
release=/home/ps/mobile-http-20260928
|
||||
cd "$release"
|
||||
test ! -e baseline-check.json
|
||||
python3 remote_server_guard.py baseline > baseline-check.json.tmp
|
||||
mv baseline-check.json.tmp baseline-check.json
|
||||
cat baseline-check.json
|
||||
test ! -e source-before
|
||||
test ! -e preflight-complete
|
||||
if docker image inspect zyt/wecom-admin:before-mobile-http-20260928 >/dev/null 2>&1; then
|
||||
echo 'Refuse to replace existing rollback tag' >&2; exit 1
|
||||
fi
|
||||
mkdir -m 700 source-before
|
||||
python3 - <<'PY'
|
||||
from pathlib import Path
|
||||
import json, shutil
|
||||
r = Path('/home/ps/mobile-http-20260928'); project = Path('/opt/im-admin')
|
||||
plan = json.loads((r / 'release-plan.json').read_text())
|
||||
for name in plan['backendFiles'] + plan['deployFiles']:
|
||||
target = r / 'source-before' / name
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(project / name, target)
|
||||
shutil.copytree(project / plan['frontendDir'], r / 'source-before' / plan['frontendDir'])
|
||||
PY
|
||||
docker tag zyt/wecom-admin:current zyt/wecom-admin:before-mobile-http-20260928
|
||||
docker image inspect zyt/wecom-admin:current --format '{{.Id}}' > image-before.txt
|
||||
printf '%s\n' ready > preflight-complete
|
||||
echo "preflight complete; rollback image tagged before-mobile-http-20260928 ($(cat image-before.txt))"
|
||||
@@ -0,0 +1,22 @@
|
||||
#!/usr/bin/env bash
|
||||
# 构建候选镜像 + 离线跑测试 + 核对候选镜像文件。线上服务不受影响。
|
||||
# 本次不改数据库(只改登录的 HTTPS 默认策略和 /m/ 静态文件),不做整库备份;回滚靠旧镜像和 source-before。
|
||||
set -euo pipefail
|
||||
test "${REMOTE_RELEASE_APPROVED:-}" = mobile-http-20260928
|
||||
release=/home/ps/mobile-http-20260928
|
||||
cd "$release"
|
||||
test -f preflight-complete
|
||||
test ! -e candidate-passed
|
||||
python3 remote_server_guard.py baseline
|
||||
test "$(docker image inspect zyt/wecom-admin:before-mobile-http-20260928 --format '{{.Id}}')" = "$(cat image-before.txt)"
|
||||
docker build --network=none --pull=false -f Dockerfile.overlay -t zyt/wecom-admin:mobile-http-20260928 . > candidate-build.log 2>&1
|
||||
# serverTestModules 随包放在 tests/;imageTestModules 用镜像自带的测试文件(PYTHONPATH 后一项)。
|
||||
# -P:不把工作目录 /app/wechat_rpa 放到 sys.path 最前面,否则镜像里同名的旧测试会盖住随包的新测试。
|
||||
mapfile -t modules < <(python3 -c 'import json;p=json.load(open("release-plan.json"));print("\n".join(p["serverTestModules"]+p.get("imageTestModules",[])))')
|
||||
test "${#modules[@]}" -gt 0
|
||||
docker run --rm --network=none --read-only --tmpfs /tmp:size=512m,mode=1777 --tmpfs /data:size=256m,mode=1777 \
|
||||
-v "$release/tests:/release-tests:ro" -e PYTHONPATH=/release-tests:/app/wechat_rpa \
|
||||
zyt/wecom-admin:mobile-http-20260928 python -X utf8 -B -P -m unittest "${modules[@]}" -q > candidate-tests.log 2>&1
|
||||
tail -n 3 candidate-tests.log
|
||||
python3 remote_server_guard.py candidate
|
||||
printf '%s\n' passed > candidate-passed
|
||||
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env bash
|
||||
# 替换 remote_api.py 和整个 /m/ 目录;切换镜像,只重建 api 容器。任何一步失败自动调用 rollback.sh。
|
||||
set -euo pipefail
|
||||
test "${REMOTE_RELEASE_APPROVED:-}" = mobile-http-20260928
|
||||
release=/home/ps/mobile-http-20260928
|
||||
cd "$release"
|
||||
test -f candidate-passed
|
||||
python3 remote_server_guard.py baseline
|
||||
cd /opt/im-admin/deploy/im-admin
|
||||
docker compose config --quiet
|
||||
rollback_on_error() { rc=$?; trap - ERR; bash "$release/rollback.sh"; exit "$rc"; }
|
||||
trap rollback_on_error ERR
|
||||
python3 - <<'PY'
|
||||
from pathlib import Path
|
||||
import json, hashlib, os, shutil
|
||||
r = Path('/home/ps/mobile-http-20260928'); target = Path('/opt/im-admin')
|
||||
plan = json.loads((r / 'release-plan.json').read_text())
|
||||
rows = [row for row in json.loads((r / 'manifest.json').read_text()) if row['path'].startswith('payload/')]
|
||||
frontend = plan['frontendDir']
|
||||
# 容器从镜像里读 /m/,宿主上的目录只给以后整包重建用;仍然整体换名,避免留下半套文件。
|
||||
staging = target / (frontend + '.mobile-http.tmp'); assert not staging.exists()
|
||||
old = target / (frontend + '.mobile-http.old'); assert not old.exists()
|
||||
for row in rows:
|
||||
rel = row['path'][len('payload/'):]
|
||||
data = (r / row['path']).read_bytes(); assert hashlib.sha256(data).hexdigest() == row['sha256'], rel
|
||||
if rel.startswith(frontend + '/'):
|
||||
dest = staging / rel[len(frontend) + 1:]
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
dest.write_bytes(data); os.chmod(dest, 0o644)
|
||||
continue
|
||||
dest = (target / rel).resolve(); assert dest.is_relative_to(target) and dest.exists()
|
||||
tmp = dest.with_name(dest.name + '.mobile-http.tmp'); assert not tmp.exists()
|
||||
with tmp.open('xb') as f:
|
||||
f.write(data)
|
||||
os.chmod(tmp, dest.stat().st_mode & 0o777); os.replace(tmp, dest)
|
||||
for directory in [staging] + [p for p in staging.rglob('*') if p.is_dir()]:
|
||||
os.chmod(directory, 0o755)
|
||||
final = target / frontend
|
||||
os.replace(final, old)
|
||||
os.replace(staging, final)
|
||||
shutil.rmtree(old) # 原目录已在 source-before 里
|
||||
PY
|
||||
docker tag zyt/wecom-admin:mobile-http-20260928 zyt/wecom-admin:current
|
||||
docker compose up -d --no-deps --no-build --wait --wait-timeout 180 api
|
||||
bash "$release/04-verify.sh"
|
||||
trap - ERR
|
||||
printf '%s\n' 'Plain-HTTP phone login enabled, deployed and verified.'
|
||||
@@ -0,0 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
test "${REMOTE_RELEASE_APPROVED:-}" = mobile-http-20260928
|
||||
release=/home/ps/mobile-http-20260928
|
||||
cd "$release"
|
||||
python3 remote_server_guard.py deployed | tee deployed-verification.json
|
||||
@@ -0,0 +1,9 @@
|
||||
ARG BASE_IMAGE=zyt/wecom-admin:before-mobile-http-20260928
|
||||
FROM ${BASE_IMAGE}
|
||||
# 先删掉旧版 /m/ 目录再放新版,镜像里不残留旧的(带内网横幅的)页面文件。
|
||||
USER root
|
||||
RUN rm -rf /app/admin-web/apps/mobile-h5/dist
|
||||
USER app
|
||||
COPY --chown=app:app payload/wechat_rpa/remote_api.py /app/wechat_rpa/remote_api.py
|
||||
COPY --chown=app:app payload/admin-web/apps/mobile-h5/dist/ /app/admin-web/apps/mobile-h5/dist/
|
||||
WORKDIR /app/wechat_rpa
|
||||
@@ -0,0 +1,162 @@
|
||||
[
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/_plugin-vue_export-helper-4o9rbdkf.js",
|
||||
"sha256": "8d6186020c3d8562f581ea579742dd497649203a880b9c13cc904462b134bc60",
|
||||
"bytes": 2308
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/AccountSwitcher-BZXg15MH.css",
|
||||
"sha256": "b61f1f1af65c2c3438066ffe41683af7e38062eb9389cda3f8fdad8ee77498ff",
|
||||
"bytes": 359
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/AccountSwitcher-DHX0QDeT.js",
|
||||
"sha256": "226d4cde03c5434f20aa96c84cfb33538af084d79805348a089e343c5056281f",
|
||||
"bytes": 14528
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/brand-mark-CPUQS9Am.png",
|
||||
"sha256": "1caa8c492da279e8d01f676fe9232ccad016321699d519b3834692052cc5f5ee",
|
||||
"bytes": 16743
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/cell-group-CEKvg8Wf.js",
|
||||
"sha256": "b0d4b420bc5197a5df6d918e740e2b90b108c6e06ba930c3fd8e97fabe010556",
|
||||
"bytes": 4490
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/ConversationsView-BMjeHKhk.js",
|
||||
"sha256": "75cd3809eb0d7db6c994302dd296674eadd366a53a4feb97a759173d70546e80",
|
||||
"bytes": 28526
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/ConversationsView-CytDMSuM.css",
|
||||
"sha256": "1f646a0178eb9e3f837ac62b5521ec60c0e7d5b4b086b9076c4bf2a7448f98ae",
|
||||
"bytes": 4220
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/DevicesView-CHTvxQxK.css",
|
||||
"sha256": "40fd5adaea4d4aed376a57c75ebec4544d50f424863704b00ce80b98f7881ddd",
|
||||
"bytes": 3983
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/DevicesView-DVXAQfpT.js",
|
||||
"sha256": "237de4f76004cbf16e5928060cf009fbbb3beec826006a876ddbede0ee9512f7",
|
||||
"bytes": 10460
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/field-Bs9V8Rb1.js",
|
||||
"sha256": "da55fbacb606cdb51f6eb09fb8bf4963fe249e869d653f0fb71d3c0da9ed7b4c",
|
||||
"bytes": 8422
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/format-2xch3ZbY.js",
|
||||
"sha256": "a98c816d31f9a937c5418dd48d25bc5b7b96fb3084d58571565d0810f420ced9",
|
||||
"bytes": 14363
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/index-C_mEe-tZ.js",
|
||||
"sha256": "6c6620136850dbdfa6ea22a9fa6c320f3f5d33150b83f1d1b9597e0894f5d0de",
|
||||
"bytes": 117757
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/index-D80qzV0-.css",
|
||||
"sha256": "c0c7a7706d3d4a4ca2baa88f31aa2fd5c6080b4f2e539b4812a99d51f2de9fd0",
|
||||
"bytes": 97051
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/LoginView-Br8nsdQM.js",
|
||||
"sha256": "29bdcbe8030ef2e169b2ea453cef160f2b3c86b9a83718971023a9862e10bd45",
|
||||
"bytes": 6336
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/LoginView-J4b4q6ai.css",
|
||||
"sha256": "15ecdd5cb294bb51eef05e4843ac3a65f6e1718cbf16206547a876c52c5e8a2d",
|
||||
"bytes": 1107
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/MeView-B-MK2tgf.css",
|
||||
"sha256": "a3bd246d2658ee50d4cac9afa1d051c33e8676be3155260256e7106a9c5dd136",
|
||||
"bytes": 927
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/MeView-BOWGunAt.js",
|
||||
"sha256": "9e5ff0c332dfae54d9f8e1c70b0a896e48aef80e8b45101092c08a59dfddf521",
|
||||
"bytes": 3465
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/ShellView-D354hIv5.css",
|
||||
"sha256": "513a381d7ecfe8c24ca22166d658c8604df9d9478a8765ffcef7beb031917dcd",
|
||||
"bytes": 130
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/ShellView-DcQ5QK1V.js",
|
||||
"sha256": "13f70e99d3eccfa014f14dc313a195b4f24200929bf60142f6fd190ef33f2f3d",
|
||||
"bytes": 2939
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/use-placeholder-D9ZemjXL.js",
|
||||
"sha256": "530e97b69f045bf3c2798b79c1f49bd3ee69f53a657bad39825cb69d68552c9c",
|
||||
"bytes": 607
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/icons/apple-touch-icon.png",
|
||||
"sha256": "3167d1d07f22a44ea393b377e5181918ae4890c137de37fe91e2f3780b6ce70e",
|
||||
"bytes": 24681
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/icons/favicon-64.png",
|
||||
"sha256": "7c9d031dcd296a45a79d960481c34eb150dd33e4a2bace6f28385be01c1a675e",
|
||||
"bytes": 5439
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/icons/icon-192.png",
|
||||
"sha256": "9637a4d3e4cbb385ed0b35069d6bb3522b90d1b8aaec439cfdf5ec1264040b5a",
|
||||
"bytes": 26433
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/icons/icon-512.png",
|
||||
"sha256": "803ed98fb41fc724cb5319f45409d5e9725465f6f37cb6312e6b79170f852974",
|
||||
"bytes": 144310
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/icons/icon-maskable-512.png",
|
||||
"sha256": "88b6cecdb691f9e2f4179fd00eae937a5f6863cd61d34aadda1e6ac45e6217a2",
|
||||
"bytes": 95961
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/index.html",
|
||||
"sha256": "6f335e7804fe9a1ce7bb5df388d2af81c7d919ddebb3beaee9533553a36adf04",
|
||||
"bytes": 1357
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/manifest.webmanifest",
|
||||
"sha256": "ac64783b6865e3f68fdc735d5d66cad0c13ffc8b6be6ae5fbebc0e2eac5a61fd",
|
||||
"bytes": 684
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/sw.js",
|
||||
"sha256": "d908e9a6ec5c75ffcca8f9f6d97ec683b005fa211975f89beee372849df44a69",
|
||||
"bytes": 339
|
||||
},
|
||||
{
|
||||
"path": "payload/wechat_rpa/remote_api.py",
|
||||
"sha256": "e8a51c1701a05d54713f45325e03481ad22609bc721455aa5ddef0d3ed5ae29a",
|
||||
"bytes": 37707
|
||||
},
|
||||
{
|
||||
"path": "tests/test_backend.py",
|
||||
"sha256": "7473ec5583c97941e132ade7a1f66abcf54fa6108ec6bb2a182f0152964fff61",
|
||||
"bytes": 66279
|
||||
},
|
||||
{
|
||||
"path": "tests/test_remote_api.py",
|
||||
"sha256": "479cb9b042dc14707af718734c33688013203d4154f36199b7b0ced656653c39",
|
||||
"bytes": 38523
|
||||
},
|
||||
{
|
||||
"path": "tests/test_zyt_auth.py",
|
||||
"sha256": "40ab2d37f51780af26497e22948ef665c92b7f3707f6ba30a6d711bf5b15dfa6",
|
||||
"bytes": 4907
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1 @@
|
||||
.switcher[data-v-91cf283c]{max-height:80vh}.switcher-body[data-v-91cf283c]{padding:16px 0 12px}.switcher-body h3[data-v-91cf283c]{margin:0 16px 8px;font-size:17px}.switcher-state[data-v-91cf283c]{place-items:center;padding:32px 0;display:grid}.switcher-list[data-v-91cf283c]{margin-top:12px}.current[data-v-91cf283c]{color:var(--app-primary);margin-left:6px}
|
||||
@@ -0,0 +1 @@
|
||||
.detail[data-v-70465908]{padding-bottom:16px}.detail-head[data-v-70465908]{align-items:center;gap:12px;padding:16px;display:flex}.avatar[data-v-70465908]{width:52px;height:52px;color:var(--app-primary);background:var(--app-primary-soft);border-radius:14px;flex:none;place-items:center;font-size:22px;font-weight:600;display:grid}.detail-title[data-v-70465908]{flex:1;min-width:0}.detail-title h2[data-v-70465908]{text-overflow:ellipsis;white-space:nowrap;margin:0 0 4px;font-size:18px;overflow:hidden}.detail-title p[data-v-70465908]{margin:0;font-size:13px}.badge[data-v-70465908]{color:var(--app-danger);background:var(--app-danger-soft);border-radius:999px;flex:none;align-items:center;gap:4px;padding:4px 10px;font-size:12px;font-weight:600;display:inline-flex}.group[data-v-70465908]{margin-bottom:12px}.state[data-v-70465908]{background:var(--app-surface);border:1px solid var(--app-border);border-radius:14px;margin:0 16px;padding:16px}.state--blocked[data-v-70465908]{border-color:var(--app-danger-soft);background:linear-gradient(0deg, var(--app-danger-soft), var(--app-danger-soft)), var(--app-surface)}.state h3[data-v-70465908]{align-items:center;gap:6px;margin:0 0 6px;font-size:15px;display:flex}.state--blocked h3[data-v-70465908]{color:var(--app-danger)}.state>p[data-v-70465908]{color:var(--app-text-2);margin:0 0 12px;font-size:13px;line-height:1.6}.state dl[data-v-70465908]{grid-template-columns:repeat(2,minmax(0,1fr));gap:8px 12px;margin:0 0 14px;display:grid}.state dt[data-v-70465908]{color:var(--app-muted);font-size:12px}.state dd[data-v-70465908]{word-break:break-all;margin:2px 0 0;font-size:14px}.reason[data-v-70465908]{margin:0 0 12px}.reason[data-v-70465908] .van-cell-group--inset{margin:0}.state[data-v-70465908] .van-cell-group--inset{margin:0 0 12px}.note[data-v-70465908]{color:var(--app-muted);margin:0;font-size:13px;line-height:1.6}.row[data-v-645c253b]{border:0;border-bottom:1px solid var(--app-border);background:var(--app-surface);width:100%;min-height:64px;color:inherit;text-align:left;cursor:pointer;align-items:center;gap:12px;padding:10px 16px;display:flex}.row[data-v-645c253b]:active,.row.active[data-v-645c253b]{background:var(--app-primary-soft)}.avatar[data-v-645c253b]{border-radius:12px;flex:none;place-items:center;width:42px;height:42px;font-size:17px;font-weight:600;display:grid}.avatar--wecom[data-v-645c253b]{color:#2f6fff;background:#2f6fff1f}.avatar--wechat[data-v-645c253b]{color:#0f9e69;background:#13b77a24}.avatar--group[data-v-645c253b]{color:#7a5cff;background:#8a6bff24}.body[data-v-645c253b]{flex:1;gap:4px;min-width:0;display:grid}.line[data-v-645c253b]{justify-content:space-between;align-items:center;gap:8px;min-width:0;display:flex}.name[data-v-645c253b]{text-overflow:ellipsis;white-space:nowrap;font-size:15px;font-weight:600;overflow:hidden}.time[data-v-645c253b]{color:var(--app-muted);flex:none;font-size:12px}.sub[data-v-645c253b]{color:var(--app-muted);font-size:12px}.meta[data-v-645c253b]{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.blocked[data-v-645c253b]{color:var(--app-danger);background:var(--app-danger-soft);border-radius:999px;flex:none;padding:1px 8px;font-weight:600}.page[data-v-cc7f80e6]{min-height:100%}.nav-action[data-v-cc7f80e6]{color:var(--app-primary);background:0 0;border:0;align-items:center;gap:4px;padding:6px 0;font-size:14px;display:inline-flex}.toolbar[data-v-cc7f80e6]{top:calc(46px + env(safe-area-inset-top));z-index:2;background:var(--app-bg);position:-webkit-sticky;position:sticky}.toolbar[data-v-cc7f80e6] .van-search{background:0 0;padding-bottom:4px}.tabs[data-v-cc7f80e6]{--van-tabs-nav-background:transparent;padding:0 4px}.list-body[data-v-cc7f80e6]{min-height:60vh}.single .list-pane[data-v-cc7f80e6]{max-width:720px;margin:0 auto}.split[data-v-cc7f80e6]{grid-template-columns:minmax(300px,380px) minmax(0,1fr);align-items:start;gap:16px;max-width:1180px;margin:0 auto;padding:0 24px 24px;display:grid}.split .list-body[data-v-cc7f80e6]{border-radius:16px;overflow:clip}.detail-pane[data-v-cc7f80e6]{top:calc(46px + env(safe-area-inset-top) + 12px);min-height:320px;margin-top:12px;position:-webkit-sticky;position:sticky}.sheet[data-v-cc7f80e6]{max-height:88vh;padding-top:8px}
|
||||
@@ -0,0 +1 @@
|
||||
.panel[data-v-bcd7f731]{padding:16px}.panel-head[data-v-bcd7f731]{align-items:flex-start;gap:12px;display:flex}.panel-icon[data-v-bcd7f731]{width:44px;height:44px;color:var(--app-primary);background:var(--app-primary-soft);border-radius:12px;flex:none;place-items:center;font-size:22px;display:grid}.panel-title[data-v-bcd7f731]{flex:1;min-width:0}.panel-title h2[data-v-bcd7f731]{text-overflow:ellipsis;white-space:nowrap;margin:2px 0 4px;font-size:17px;font-weight:600;overflow:hidden}.panel-title p[data-v-bcd7f731]{margin:0;font-size:13px;line-height:1.45}.pill[data-v-bcd7f731]{white-space:nowrap;border-radius:999px;flex:none;align-items:center;gap:6px;padding:4px 10px;font-size:12px;font-weight:600;display:inline-flex}.pill .dot[data-v-bcd7f731]{background:currentColor;border-radius:50%;width:7px;height:7px}.pill--success[data-v-bcd7f731]{color:var(--app-success);background:var(--app-success-soft)}.pill--success .dot[data-v-bcd7f731]{box-shadow:0 0 0 3px var(--app-success-soft);animation:2.2s ease-in-out infinite breathe-bcd7f731}.pill--warning[data-v-bcd7f731]{color:var(--app-warning);background:var(--app-warning-soft)}.pill--danger[data-v-bcd7f731]{color:var(--app-danger);background:var(--app-danger-soft)}.pill--muted[data-v-bcd7f731],.pill--primary[data-v-bcd7f731]{color:var(--app-muted);background:var(--app-muted-soft)}@keyframes breathe-bcd7f731{50%{opacity:.45}}.stats[data-v-bcd7f731]{grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;margin:16px 0 0;display:grid}.stat[data-v-bcd7f731]{background:var(--app-surface-2);border:1px solid var(--app-border);border-radius:12px;padding:10px 12px}.stat dt[data-v-bcd7f731]{color:var(--app-muted);font-size:12px}.stat dd[data-v-bcd7f731]{margin:4px 0 0;font-size:15px;font-weight:600}.meta[data-v-bcd7f731]{margin:12px 0 0;font-size:12px}.progress[data-v-bcd7f731]{border-radius:12px;align-items:center;gap:8px;margin-top:12px;padding:10px 12px;font-size:13px;line-height:1.45;display:flex}.progress--primary[data-v-bcd7f731]{color:var(--app-primary);background:var(--app-primary-soft)}.progress--success[data-v-bcd7f731]{color:var(--app-success);background:var(--app-success-soft)}.progress--danger[data-v-bcd7f731]{color:var(--app-danger);background:var(--app-danger-soft)}.progress--warning[data-v-bcd7f731]{color:var(--app-warning);background:var(--app-warning-soft)}.progress--muted[data-v-bcd7f731]{color:var(--app-muted);background:var(--app-muted-soft)}.actions[data-v-bcd7f731]{margin-top:16px}.blocked[data-v-bcd7f731]{margin:10px 4px 0;font-size:13px;line-height:1.5}.page[data-v-8ead1f63]{min-height:100%}.page-body[data-v-8ead1f63]{min-height:calc(100vh - 96px);min-height:calc(100dvh - 96px)}.content[data-v-8ead1f63]{max-width:720px;margin:0 auto;padding:12px 16px 24px}.stack[data-v-8ead1f63]{gap:12px;display:grid}.skeleton-card[data-v-8ead1f63]{padding:16px 0}.empty-hint[data-v-8ead1f63]{max-width:280px;color:var(--app-muted);text-align:center;margin:0 auto;font-size:13px;line-height:1.6}.nav-action[data-v-8ead1f63]{color:var(--app-primary);background:0 0;border:0;align-items:center;gap:4px;padding:6px 0;font-size:14px;display:inline-flex}.stale[data-v-8ead1f63]{margin:0 4px;font-size:12px}.split[data-v-8ead1f63]{grid-template-columns:minmax(240px,320px) minmax(0,1fr);align-items:start;gap:16px;max-width:1080px;margin:0 auto;padding:16px 24px 24px;display:grid}.split-list[data-v-8ead1f63]{gap:10px;display:grid}.device-row[data-v-8ead1f63]{text-align:left;width:100%;color:inherit;cursor:pointer;align-items:center;gap:12px;padding:12px 14px;display:flex}.device-row.active[data-v-8ead1f63]{border-color:var(--app-primary);box-shadow:0 0 0 2px var(--app-primary-soft)}.device-row-icon[data-v-8ead1f63]{color:var(--app-primary);font-size:20px}.device-row-text[data-v-8ead1f63]{gap:2px;min-width:0;display:grid}.device-row-text strong[data-v-8ead1f63]{text-overflow:ellipsis;white-space:nowrap;font-size:15px;overflow:hidden}.device-row-text small[data-v-8ead1f63]{font-size:12px}
|
||||
@@ -0,0 +1 @@
|
||||
.login[data-v-004201f6]{min-height:100vh;min-height:100dvh;padding:calc(env(safe-area-inset-top) + 24px) 16px calc(env(safe-area-inset-bottom) + 24px);background:radial-gradient(120% 60% at 50% 0%, var(--app-primary-soft), transparent 70%), var(--app-bg);justify-content:center;align-items:center;display:flex}.login-card[data-v-004201f6]{width:100%;max-width:420px}.login-head[data-v-004201f6]{text-align:center;margin-bottom:24px}.login-mark[data-v-004201f6]{box-shadow:var(--app-shadow);border-radius:20px}.login-head h1[data-v-004201f6]{letter-spacing:.5px;margin:16px 0 6px;font-size:24px;font-weight:700}.login-head p[data-v-004201f6]{color:var(--app-muted);margin:0;font-size:14px}.login-notice[data-v-004201f6]{border-radius:12px;margin:0 16px 12px}.login-form[data-v-004201f6] .van-cell-group--inset,.login-form[data-v-004201f6]{margin:0}.login-error[data-v-004201f6]{color:var(--app-danger);margin:12px 16px 0;font-size:14px;line-height:1.5}.login-actions[data-v-004201f6]{margin:20px 16px 0}.login-foot[data-v-004201f6]{text-align:center;color:var(--app-muted);margin:16px 16px 0;font-size:12px}
|
||||
@@ -0,0 +1 @@
|
||||
.content[data-v-1710faf3]{max-width:720px;margin:0 auto;padding:12px 0 32px}.profile[data-v-1710faf3]{align-items:center;gap:14px;margin:0 16px;padding:16px;display:flex}.avatar[data-v-1710faf3]{color:#fff;background:linear-gradient(135deg,#2f6fff,#5a65ff);border-radius:50%;flex:none;place-items:center;width:54px;height:54px;font-size:22px;font-weight:700;display:grid}.profile-text[data-v-1710faf3]{flex:1;min-width:0}.profile-text h2[data-v-1710faf3]{margin:0 0 4px;font-size:18px}.profile-text p[data-v-1710faf3]{margin:0;font-size:13px}.root[data-v-1710faf3]{color:var(--app-warning);background:var(--app-warning-soft);border-radius:999px;flex:none;padding:4px 10px;font-size:12px;font-weight:600}.section-title[data-v-1710faf3]{color:var(--app-muted);margin:24px 32px 8px;font-size:13px;font-weight:600}.hint[data-v-1710faf3]{margin:8px 32px 0;font-size:12px;line-height:1.6}.logout[data-v-1710faf3]{margin:32px 16px 0}
|
||||
@@ -0,0 +1 @@
|
||||
import{n as e,t}from"./_plugin-vue_export-helper-4o9rbdkf.js";import{a as n,i as r,o as i,s as a}from"./format-2xch3ZbY.js";import{a as o,n as s,t as c}from"./cell-group-CEKvg8Wf.js";import{Ct as l,Ft as u,Jt as d,Kt as f,Lt as p,St as m,Ut as h,Yt as g,_t as _,d as v,ft as y,gt as b,ht as x,i as S,n as C,qt as w,vt as T,xt as E,yt as D}from"./index-C_mEe-tZ.js";var O={class:`page`},k={key:0,class:`content`},A={class:`profile app-card`},j={class:`avatar`,"aria-hidden":`true`},M={class:`profile-text`},N={class:`app-muted`},P={key:0,class:`root`},F={class:`hint app-muted`},I={class:`logout`},L=t(l({__name:`MeView`,setup(t){let l=v(),L=f(!1),R=x(()=>C.me),z=x(()=>{let e=R.value;if(!e)return[];let{permissions:t,permission_codes:n}=e;return[{title:`查看本人电脑与会话`,code:`登录即可`,granted:!0},{title:`远程启停本人电脑`,code:n.control,granted:t.control},{title:`查看并控制所有客服电脑`,code:n.control_all,granted:t.control_all},{title:`会话加入黑名单`,code:n.blacklist_add,granted:t.blacklist_add},{title:`会话移出黑名单`,code:n.blacklist_remove,granted:t.blacklist_remove}]}),B=x(()=>{var e;let t=(e=R.value)==null?void 0:e.session.expires_at;return t?new Date(t*1e3).toISOString():``}),V=/iPhone|iPad|iPod/.test(navigator.userAgent);async function H(){try{await a({title:`退出登录?`,message:`退出后需要重新输入 ZYT 账号密码。`,confirmButtonText:`退出`})}catch{return}L.value=!0,await S(),await l.replace({name:`login`})}return(t,a)=>(u(),D(`div`,O,[m(w(i),{title:`我的`,"safe-area-inset-top":``,fixed:``,placeholder:``,border:!1}),R.value?(u(),D(`div`,k,[b(`section`,A,[b(`span`,j,g(w(r)(R.value.account.nickname||R.value.account.sn)),1),b(`div`,M,[b(`h2`,null,g(R.value.account.nickname||R.value.account.sn),1),b(`p`,N,`ZYT 账号 `+g(R.value.account.sn||`—`),1)]),R.value.permissions.root?(u(),D(`span`,P,`超级管理员`)):T(``,!0)]),a[1]||(a[1]=b(`h3`,{class:`section-title`},`手机端权限`,-1)),m(w(c),{inset:``},{default:h(()=>[(u(!0),D(y,null,p(z.value,t=>(u(),_(w(s),{key:t.title,title:t.title,label:t.code,center:``},{value:h(()=>[b(`span`,{class:d(t.granted?`tone-success`:`tone-muted`)},[m(w(e),{name:t.granted?`passed`:`close`},null,8,[`name`]),E(` `+g(t.granted?`已开通`:`未开通`),1)],2)]),_:2},1032,[`title`,`label`]))),128))]),_:1}),a[2]||(a[2]=b(`p`,{class:`hint app-muted`},` 权限在 ZYT「权限管理 → 角色管理」里勾选「企微客服助手」下的项目,调整后 10 分钟内自动生效,或退出重新登录。 `,-1)),a[3]||(a[3]=b(`h3`,{class:`section-title`},`登录信息`,-1)),m(w(c),{inset:``},{default:h(()=>[m(w(s),{title:`登录时间`,value:w(n)(R.value.session.created_at)},null,8,[`value`]),m(w(s),{title:`最长有效至`,value:B.value?w(n)(B.value):`—`,label:`ZYT 登录失效后会提前退出`},null,8,[`value`])]),_:1}),a[4]||(a[4]=b(`h3`,{class:`section-title`},`添加到主屏幕`,-1)),b(`p`,F,[w(V)?(u(),D(y,{key:0},[E(`在 Safari 中点底部「分享」按钮,选择「添加到主屏幕」,之后像 App 一样打开。`)],64)):(u(),D(y,{key:1},[E(`在浏览器菜单中选择「添加到主屏幕」或「安装应用」,之后像 App 一样打开。`)],64))]),b(`div`,I,[m(w(o),{block:``,round:``,type:`danger`,plain:``,loading:L.value,onClick:H},{default:h(()=>[...a[0]||(a[0]=[E(`退出登录`,-1)])]),_:1},8,[`loading`])])])):T(``,!0)]))}}),[[`__scopeId`,`data-v-1710faf3`]]);export{L as default};
|
||||
@@ -0,0 +1 @@
|
||||
.shell[data-v-5972669c]{min-height:100vh;min-height:100dvh}.shell-tabbar[data-v-5972669c]{border-top:1px solid var(--app-border)}
|
||||
@@ -0,0 +1 @@
|
||||
import{a as e,n as t,o as n,p as r,r as i,t as a}from"./_plugin-vue_export-helper-4o9rbdkf.js";import{n as o,t as s}from"./use-placeholder-D9ZemjXL.js";import{B as c,Ct as l,Et as u,Ft as d,Kt as f,Q as p,Rt as m,S as h,St as g,U as _,Ut as v,X as y,Z as b,_ as x,_t as S,g as C,ht as w,pt as T,q as E,qt as D,rt as O,wt as k,xt as A,yt as j,zt as M}from"./index-C_mEe-tZ.js";var[N,P]=x(`tabbar`),F={route:Boolean,fixed:b,border:b,zIndex:y,placeholder:Boolean,activeColor:String,beforeChange:Function,inactiveColor:String,modelValue:E(0),safeAreaInsetBottom:{type:Boolean,default:null}},I=Symbol(N),L=l({name:N,props:F,emits:[`change`,`update:modelValue`],setup(e,{emit:t,slots:n}){let i=f(),{linkChildren:a}=c(I),l=s(i,P),u=()=>{var t;return(t=e.safeAreaInsetBottom)==null?e.fixed:t},d=()=>{var t;let{fixed:a,zIndex:o,border:s}=e;return g(`div`,{ref:i,role:`tablist`,style:h(o),class:[P({fixed:a}),{[r]:s,"van-safe-area-bottom":u()}]},[(t=n.default)==null?void 0:t.call(n)])};return a({props:e,setActive:(n,r)=>{o(e.beforeChange,{args:[n],done(){t(`update:modelValue`,n),t(`change`,n),r()}})}}),()=>e.fixed&&e.placeholder?l(d):d()}}),R=C(L),[z,B]=x(`tabbar-item`),V=p({},e,{dot:Boolean,icon:String,name:y,badge:y,badgeProps:Object,iconPrefix:String}),H=l({name:z,props:V,emits:[`click`],setup(e,{emit:r,slots:a}){let o=n(),s=k().proxy,{parent:c,index:l}=_(I);if(!c)return;let d=w(()=>{var t;let{route:n,modelValue:r}=c.props;if(n&&`$route`in s){let{$route:t}=s,{to:n}=e,r=O(n)?n:{path:n};return t.matched.some(e=>{let t=`path`in r&&r.path===e.path,n=`name`in r&&r.name===e.name;return t||n})}return((t=e.name)==null?l.value:t)===r}),f=t=>{var n;d.value||c.setActive((n=e.name)==null?l.value:n,o),r(`click`,t)},p=()=>{if(a.icon)return a.icon({active:d.value});if(e.icon)return g(t,{name:e.icon,classPrefix:e.iconPrefix},null)};return()=>{var t;let{dot:n,badge:r}=e,{activeColor:o,inactiveColor:s}=c.props,l=d.value?o:s;return g(`div`,{role:`tab`,class:B({active:d.value}),style:{color:l},tabindex:0,"aria-selected":d.value,onClick:f},[g(i,u({dot:n,class:B(`icon`),content:r},e.badgeProps),{default:p}),g(`div`,{class:B(`text`)},[(t=a.default)==null?void 0:t.call(a,{active:d.value})])])}}}),U=C(H),W={class:`shell`},G=a(l({__name:`ShellView`,setup(e){return(e,t)=>{let n=m(`RouterView`);return d(),j(`div`,W,[g(n,null,{default:v(({Component:e})=>[(d(),S(T,{include:[`DevicesView`,`ConversationsView`]},[(d(),S(M(e)))],1024))]),_:1}),g(D(R),{route:``,placeholder:``,"safe-area-inset-bottom":``,class:`shell-tabbar`},{default:v(()=>[g(D(U),{replace:``,to:{name:`desktops`},icon:`desktop-o`},{default:v(()=>[...t[0]||(t[0]=[A(`电脑`,-1)])]),_:1}),g(D(U),{replace:``,to:{name:`conversations`},icon:`chat-o`},{default:v(()=>[...t[1]||(t[1]=[A(`会话`,-1)])]),_:1}),g(D(U),{replace:``,to:{name:`me`},icon:`user-o`},{default:v(()=>[...t[2]||(t[2]=[A(`我的`,-1)])]),_:1})]),_:1})])}}}),[[`__scopeId`,`data-v-5972669c`]]);export{G as default};
|
||||
@@ -0,0 +1 @@
|
||||
import{Ct as e,Et as t,St as n,Tt as r,Vt as i,X as a,Y as o,Z as s,_ as c,et as l,g as u,ht as d,m as f,nt as p,v as m,wt as h}from"./index-C_mEe-tZ.js";var g=`van-hairline`,_=`${g}--top`,v=`${g}--left`;`${g}`;var y=`${g}--bottom`,b=`${g}--surround`,x=`${g}--top-bottom`;`${g}`;var S=`van-haptics-feedback`,C=Symbol(`van-form`),w=Symbol();function T(e){let t=r(w,null);t&&i(t,t=>{t&&e()})}var E={to:[String,Object],url:String,replace:Boolean};function D({to:e,url:t,replace:n,$router:r}){e&&r?r[n?`replace`:`push`](e):t&&(n?location.replace(t):location.href=t)}function O(){let e=h().proxy;return()=>D(e)}var[k,A]=c(`badge`),j={dot:Boolean,max:a,tag:o(`div`),color:String,offset:Array,content:a,showZero:s,position:o(`top-right`)},M=e({name:k,props:j,setup(e,{slots:t}){let r=()=>{if(t.content)return!0;let{content:n,showZero:r}=e;return l(n)&&n!==``&&(r||n!==0&&n!==`0`)},i=()=>{let{dot:n,max:i,content:a}=e;if(!n&&r())return t.content?t.content():l(i)&&p(a)&&+a>+i?`${i}+`:a},a=e=>e.startsWith(`-`)?e.replace(`-`,``):`-${e}`,o=d(()=>{let n={background:e.color};if(e.offset){let[r,i]=e.offset,{position:o}=e,[s,c]=o.split(`-`);t.default?(n[s]=typeof i==`number`?m(s===`top`?i:-i):s===`top`?m(i):a(i),n[c]=typeof r==`number`?m(c===`left`?r:-r):c===`left`?m(r):a(r)):(n.marginTop=m(i),n.marginLeft=m(r))}return n}),s=()=>{if(r()||e.dot)return n(`div`,{class:A([e.position,{dot:e.dot,fixed:!!t.default}]),style:o.value},[i()])};return()=>{if(t.default){let{tag:r}=e;return n(r,{class:A(`wrapper`)},{default:()=>[t.default(),s()]})}return s()}}}),N=u(M),[P,F]=c(`icon`),I=e=>e==null?void 0:e.includes(`/`),L={dot:Boolean,tag:o(`i`),name:String,size:a,badge:a,color:String,badgeProps:Object,classPrefix:String},R=e({name:P,props:L,setup(e,{slots:i}){let a=r(f,null),o=d(()=>e.classPrefix||(a==null?void 0:a.iconPrefix)||F());return()=>{let{tag:r,dot:a,name:s,size:c,badge:l,color:u}=e,d=I(s);return n(N,t({dot:a,tag:r,class:[o.value,d?``:`${o.value}-${s}`],style:{color:u,fontSize:m(c)},content:l},e.badgeProps),{default:()=>{var e;return[(e=i.default)==null?void 0:e.call(i),d&&n(`img`,{class:F(`image`),src:s},null)]}})}}}),z=u(R),B=(e,t)=>{let n=e.__vccOpts||e;for(let[e,r]of t)n[e]=r;return n};export{E as a,T as c,b as d,_ as f,S as h,D as i,y as l,C as m,z as n,O as o,x as p,N as r,w as s,B as t,v as u};
|
||||
|
After Width: | Height: | Size: 16 KiB |
@@ -0,0 +1 @@
|
||||
import{a as e,d as t,n,o as r,p as i}from"./_plugin-vue_export-helper-4o9rbdkf.js";import{Ct as a,Et as o,O as s,Q as c,St as l,X as u,Y as d,Z as f,_ as p,et as m,ft as h,g,ht as _,v,wt as y,x as b}from"./index-C_mEe-tZ.js";function x(e){let t=y();t&&c(t.proxy,e)}var[S,C]=p(`loading`),w=Array(12).fill(null).map((e,t)=>l(`i`,{class:C(`line`,String(t+1))},null)),T=l(`svg`,{class:C(`circular`),viewBox:`25 25 50 50`},[l(`circle`,{cx:`50`,cy:`50`,r:`20`,fill:`none`},null)]),E={size:u,type:d(`circular`),color:String,vertical:Boolean,textSize:u,textColor:String},D=a({name:S,props:E,setup(e,{slots:t}){let n=_(()=>c({color:e.color},b(e.size))),r=()=>{let r=e.type===`spinner`?w:T;return l(`span`,{class:C(`spinner`,e.type),style:n.value},[t.icon?t.icon():r])},i=()=>{var n;if(t.default)return l(`span`,{class:C(`text`),style:{fontSize:v(e.textSize),color:(n=e.textColor)==null?e.color:n}},[t.default()])};return()=>{let{type:t,vertical:n}=e;return l(`div`,{class:C([t,{vertical:n}]),"aria-live":`polite`,"aria-busy":!0},[r(),i()])}}}),O=g(D),[k,A]=p(`button`),j=c({},e,{tag:d(`button`),text:String,icon:String,type:d(`default`),size:d(`normal`),color:String,block:Boolean,plain:Boolean,round:Boolean,square:Boolean,loading:Boolean,hairline:Boolean,disabled:Boolean,iconPrefix:String,nativeType:d(`button`),loadingSize:u,loadingText:String,loadingType:String,iconPosition:d(`left`)}),M=a({name:k,props:j,emits:[`click`],setup(e,{emit:i,slots:a}){let o=r(),c=()=>a.loading?a.loading():l(O,{size:e.loadingSize,type:e.loadingType,class:A(`loading`)},null),u=()=>{if(e.loading)return c();if(a.icon)return l(`div`,{class:A(`icon`)},[a.icon()]);if(e.icon)return l(n,{name:e.icon,class:A(`icon`),classPrefix:e.iconPrefix},null)},d=()=>{let t;if(t=e.loading?e.loadingText:a.default?a.default():e.text,t)return l(`span`,{class:A(`text`)},[t])},f=()=>{let{color:t,plain:n}=e;if(t){let e={color:n?t:`white`};return n||(e.background=t),t.includes(`gradient`)?e.border=0:e.borderColor=t,e}},p=t=>{e.loading?s(t):e.disabled||(i(`click`,t),o())};return()=>{let{tag:n,type:r,size:i,block:a,round:o,plain:s,square:c,loading:m,disabled:h,hairline:g,nativeType:_,iconPosition:v}=e,y=[A([r,i,{plain:s,block:a,round:o,square:c,loading:m,disabled:h,hairline:g}]),{[t]:g}];return l(n,{type:_,class:y,style:f(),disabled:h,onClick:p},{default:()=>[l(`div`,{class:A(`content`)},[v===`left`&&u(),d(),v===`right`&&u()])]})}}}),N=g(M),P=()=>{var e;let{scopeId:t}=((e=y())==null?void 0:e.vnode)||{};return t?{[t]:``}:null},[F,I]=p(`cell`),L={tag:d(`div`),icon:String,size:String,title:u,value:u,label:u,center:Boolean,isLink:Boolean,border:f,iconPrefix:String,valueClass:null,labelClass:null,titleClass:null,titleStyle:null,arrowDirection:String,required:{type:[Boolean,String],default:null},clickable:{type:Boolean,default:null}},R=c({},L,e),z=a({name:F,props:R,setup(e,{slots:t}){let i=r(),a=()=>{if(t.label||m(e.label))return l(`div`,{class:[I(`label`),e.labelClass]},[t.label?t.label():e.label])},o=()=>{var n;if(t.title||m(e.title)){let r=(n=t.title)==null?void 0:n.call(t);return Array.isArray(r)&&r.length===0?void 0:l(`div`,{class:[I(`title`),e.titleClass],style:e.titleStyle},[r||l(`span`,null,[e.title]),a()])}},s=()=>{let n=t.value||t.default;if(n||m(e.value))return l(`div`,{class:[I(`value`),e.valueClass]},[n?n():l(`span`,null,[e.value])])},c=()=>{if(t.icon)return t.icon();if(e.icon)return l(n,{name:e.icon,class:I(`left-icon`),classPrefix:e.iconPrefix},null)},u=()=>{if(t[`right-icon`])return t[`right-icon`]();if(e.isLink){let t=e.arrowDirection&&e.arrowDirection!==`right`?`arrow-${e.arrowDirection}`:`arrow`;return l(n,{name:t,class:I(`right-icon`)},null)}};return()=>{var n,r,a;let{tag:d,size:f,center:p,border:m,isLink:h,required:g}=e,_=!!((a=(r=(n=e.clickable)==null?e.to:n)==null?e.url:r)==null?h:a),v={center:p,required:!!g,clickable:_,borderless:!m};return f&&(v[f]=!!f),l(d,{class:I(v),role:_?`button`:void 0,tabindex:_?0:void 0,onClick:_?i:void 0},{default:()=>{var e;return[c(),o(),s(),u(),(e=t.extra)==null?void 0:e.call(t)]}})}}}),B=g(z),[V,H]=p(`cell-group`),U=a({name:V,inheritAttrs:!1,props:{title:String,inset:Boolean,border:f},setup(e,{slots:t,attrs:n}){let r=()=>{var r;return l(`div`,o({class:[H({inset:e.inset}),{[i]:e.border&&!e.inset}]},n,P()),[(r=t.default)==null?void 0:r.call(t)])},a=()=>l(`div`,{class:H(`title`,{inset:e.inset})},[t.title?t.title():e.title]);return()=>e.title||t.title?l(h,null,[a(),r()]):r()}}),W=g(U);export{N as a,P as i,B as n,O as o,L as r,x as s,W as t};
|
||||
@@ -0,0 +1 @@
|
||||
import{c as e}from"./_plugin-vue_export-helper-4o9rbdkf.js";import{Dt as t,Kt as n,M as r,Mt as i,N as a,St as o,Vt as s,W as c,at as l,it as u}from"./index-C_mEe-tZ.js";function d(e,{args:t=[],done:n,canceled:r,error:i}){if(e){let a=e.apply(null,t);u(a)?a.then(e=>{e?n():r&&r()}).catch(i||l):a?n():r&&r()}else n()}var f=(o,l)=>{let u=n(),d=()=>{u.value=c(o).height};return i(()=>{if(t(d),l)for(let e=1;e<=3;e++)setTimeout(d,100*e)}),e(()=>t(d)),s([a,r],d),u};function p(e,t){let n=f(e,!0);return e=>o(`div`,{class:t(`placeholder`),style:{height:n.value?`${n.value}px`:void 0}},[e()])}export{d as n,p as t};
|
||||
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 5.3 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 141 KiB |
|
After Width: | Height: | Size: 94 KiB |
@@ -0,0 +1,26 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<meta name="color-scheme" content="light dark" />
|
||||
<meta name="theme-color" content="#f4f7fd" media="(prefers-color-scheme: light)" />
|
||||
<meta name="theme-color" content="#0b1222" media="(prefers-color-scheme: dark)" />
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
|
||||
<meta name="apple-mobile-web-app-title" content="客服控制台" />
|
||||
<meta name="format-detection" content="telephone=no" />
|
||||
<meta name="referrer" content="no-referrer" />
|
||||
<link rel="manifest" href="/m/manifest.webmanifest" />
|
||||
<link rel="icon" type="image/png" href="/m/icons/favicon-64.png" />
|
||||
<link rel="apple-touch-icon" href="/m/icons/apple-touch-icon.png" />
|
||||
<title>企微客服助手 · 手机控制台</title>
|
||||
<script type="module" crossorigin src="/m/assets/index-C_mEe-tZ.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/m/assets/index-D80qzV0-.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<noscript>请在浏览器设置中开启 JavaScript 后再打开手机控制台。</noscript>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"name": "企微客服助手 · 手机控制台",
|
||||
"short_name": "客服控制台",
|
||||
"description": "远程查看和启停客服电脑的自动回复,管理会话黑名单。",
|
||||
"lang": "zh-CN",
|
||||
"start_url": "/m/",
|
||||
"scope": "/m/",
|
||||
"display": "standalone",
|
||||
"orientation": "any",
|
||||
"background_color": "#f4f7fd",
|
||||
"theme_color": "#2f6fff",
|
||||
"icons": [
|
||||
{ "src": "/m/icons/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any" },
|
||||
{ "src": "/m/icons/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any" },
|
||||
{ "src": "/m/icons/icon-maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
// 手机控制台的 Service Worker 只为"添加到主屏幕"存在,不缓存任何内容:
|
||||
// 远程控制看到的必须是实时状态,离线缓存只会展示过期的电脑状态。
|
||||
self.addEventListener('install', () => self.skipWaiting());
|
||||
self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim()));
|
||||
@@ -0,0 +1,804 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""手机远程控制台与桌面命令通道的 HTTP 接口。
|
||||
|
||||
/api/v2/mobile/* 手机 / 平板 H5 用,ZYT 账号密码登录(终端 9,由本服务代登)
|
||||
/api/v2/desktop/commands/* 桌面端长轮询领取指令、回执结果、顺带上报状态
|
||||
/api/v2/desktop/blacklist* 桌面端同步服务端会话黑名单
|
||||
|
||||
手机令牌和桌面令牌分别由 ``mobile_sessions`` 和 ``desktop_sessions`` 签发,互相
|
||||
不能冒用:手机端拿不到归档上传之类的桌面接口,桌面端也调不了手机接口。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import ipaddress
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from collections import defaultdict, deque
|
||||
from typing import Any, Callable
|
||||
|
||||
from fastapi import Depends, FastAPI, HTTPException, Query, Request
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
import zyt_auth
|
||||
from remote_store import (
|
||||
COMMAND_TYPES,
|
||||
MOBILE_IDENTITY_RECHECK_SECONDS,
|
||||
PERM_BLACKLIST_ADD,
|
||||
PERM_BLACKLIST_REMOVE,
|
||||
PERM_REMOTE_ALL,
|
||||
PERM_REMOTE_CONTROL,
|
||||
RemoteStore,
|
||||
account_label,
|
||||
account_permissions,
|
||||
valid_device_id,
|
||||
)
|
||||
|
||||
# 桌面端长轮询最长挂起时间。uvicorn 停机时会等在途请求结束,这里必须明显短于
|
||||
# compose 里 20 秒的 stop_grace_period,否则每次发版都会被强杀;指令本身靠进程内
|
||||
# 通知即时送达,挂起时长只影响"没事时多久回来报一次状态"。
|
||||
MAX_POLL_WAIT_SECONDS = 15
|
||||
# 挂起期间多久回库复查一次;进程内通知失效(多进程部署)时的兜底。
|
||||
POLL_RECHECK_SECONDS = 5
|
||||
|
||||
|
||||
def _error(status_code: int, code: str, message: str, **extra: Any) -> HTTPException:
|
||||
return HTTPException(status_code=status_code, detail={"code": code, "message": message, **extra})
|
||||
|
||||
|
||||
def _bearer(request: Request) -> str:
|
||||
raw = request.headers.get("authorization", "")
|
||||
return raw[7:].strip() if raw.lower().startswith("bearer ") else ""
|
||||
|
||||
|
||||
def trusted_client_ip(request: Request) -> str:
|
||||
"""做安全判断用的客户端地址。
|
||||
|
||||
X-Forwarded-For 的第一段是客户端自己填的,可以伪造;X-Real-IP 由 Nginx 按
|
||||
$remote_addr 覆盖写入,API 端口又只监听本机回环,只有 Nginx 能连进来。
|
||||
"""
|
||||
real_ip = request.headers.get("x-real-ip", "").strip()
|
||||
if real_ip:
|
||||
return real_ip
|
||||
return request.client.host if request.client else ""
|
||||
|
||||
|
||||
def _is_private_address(value: str) -> bool:
|
||||
try:
|
||||
address = ipaddress.ip_address(str(value or "").strip())
|
||||
except ValueError:
|
||||
return False
|
||||
return address.is_private or address.is_loopback or address.is_link_local
|
||||
|
||||
|
||||
def request_scheme(request: Request) -> str:
|
||||
forwarded = request.headers.get("x-forwarded-proto", "").split(",")[0].strip().lower()
|
||||
return forwarded or request.url.scheme.lower()
|
||||
|
||||
|
||||
def https_required(request: Request) -> bool:
|
||||
"""手机端登录是否必须走 HTTPS。
|
||||
|
||||
MOBILE_REQUIRE_HTTPS:never(默认,内外网都允许明文 HTTP 登录,按用户要求)/
|
||||
auto(公网地址必须 HTTPS,内网可用 HTTP)/ always。配好 HTTPS 入口后建议改成
|
||||
auto:明文 HTTP 下 ZYT 密码和手机会话令牌在公网上可被截获。
|
||||
|
||||
auto 模式下没有 X-Real-IP 时按"来源不明"处理:生产环境里直连 API 的对端是 Docker
|
||||
网桥(172.x,看起来像内网),代理漏配头就会把公网请求误当内网放行。只有本机回环
|
||||
(开发时直接访问 127.0.0.1)才在没有这个头时被信任。
|
||||
"""
|
||||
policy = os.environ.get("MOBILE_REQUIRE_HTTPS", "never").strip().lower()
|
||||
if policy == "never" or request_scheme(request) == "https":
|
||||
return False
|
||||
if policy == "always":
|
||||
return True
|
||||
real_ip = request.headers.get("x-real-ip", "").strip()
|
||||
if real_ip:
|
||||
return not _is_private_address(real_ip)
|
||||
peer = request.client.host if request.client else ""
|
||||
try:
|
||||
return not ipaddress.ip_address(peer).is_loopback
|
||||
except ValueError:
|
||||
return True
|
||||
|
||||
|
||||
class LoginAttempt:
|
||||
__slots__ = ("ip", "account", "finished")
|
||||
|
||||
def __init__(self, ip: str, account: str):
|
||||
self.ip, self.account, self.finished = ip, account, False
|
||||
|
||||
|
||||
class MobileLoginGuard:
|
||||
"""手机登录限流。
|
||||
|
||||
ZYT 按请求来源 IP 计数锁定(默认 30 分钟内错 5 次锁 30 分钟),而手机端的
|
||||
登录全部由本服务代发,在 ZYT 看来都来自服务器出口 IP——如果公司电脑也走同一
|
||||
个出口,锁住的就是全公司的 ZYT 登录。所以这里除了按账号、按客户端 IP 限流,
|
||||
还给"真正发到 ZYT 的密码错误"设了一个全局预算,并在 ZYT 已锁定时直接短路。
|
||||
|
||||
限流必须把"正在进行"的尝试也算进去:先检查、等 ZYT 回来再记账的话,一次并发
|
||||
发来十几个请求会全部通过检查,一起打到 ZYT 上。`begin()` 在锁里占位,
|
||||
`finish()` 按结果转成失败记录或释放。
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, *, account_limit: int = 5, account_window: int = 600,
|
||||
ip_limit: int = 10, ip_window: int = 600,
|
||||
upstream_budget: int | None = None, upstream_window: int = 1800,
|
||||
):
|
||||
if upstream_budget is None:
|
||||
try:
|
||||
upstream_budget = int(os.environ.get("MOBILE_LOGIN_UPSTREAM_FAILURE_BUDGET", "4"))
|
||||
except ValueError:
|
||||
upstream_budget = 4
|
||||
self.account_limit, self.account_window = account_limit, account_window
|
||||
self.ip_limit, self.ip_window = ip_limit, ip_window
|
||||
self.upstream_budget, self.upstream_window = max(0, upstream_budget), upstream_window
|
||||
self._accounts: dict[str, deque[float]] = {}
|
||||
self._ips: dict[str, deque[float]] = {}
|
||||
self._upstream: deque[float] = deque()
|
||||
self._pending_accounts: dict[str, int] = defaultdict(int)
|
||||
self._pending_ips: dict[str, int] = defaultdict(int)
|
||||
self._pending_upstream = 0
|
||||
self._locked_until = 0.0
|
||||
self._lock = threading.Lock()
|
||||
|
||||
@staticmethod
|
||||
def _recent(book: dict[str, deque[float]], key: str, window: int, now: float) -> deque[float]:
|
||||
"""剪掉过期记录;空了就把这个键删掉,随机账号名刷不大内存。"""
|
||||
items = book.get(key)
|
||||
if items is None:
|
||||
return deque()
|
||||
while items and items[0] <= now - window:
|
||||
items.popleft()
|
||||
if not items:
|
||||
del book[key]
|
||||
return items
|
||||
|
||||
@staticmethod
|
||||
def _minutes(seconds: float) -> int:
|
||||
return max(1, int((seconds + 59) // 60))
|
||||
|
||||
def begin(self, ip: str, account: str) -> LoginAttempt:
|
||||
now = time.time()
|
||||
with self._lock:
|
||||
if self._locked_until > now:
|
||||
wait = self._locked_until - now
|
||||
raise _error(
|
||||
429, "zyt_locked",
|
||||
f"ZYT 已暂时锁定登录,请 {self._minutes(wait)} 分钟后再试",
|
||||
retry_after=int(wait),
|
||||
)
|
||||
failures = self._recent(self._accounts, account, self.account_window, now)
|
||||
if len(failures) >= self.account_limit:
|
||||
wait = failures[0] + self.account_window - now
|
||||
raise _error(
|
||||
429, "rate_limited",
|
||||
f"该账号登录失败次数过多,请 {self._minutes(wait)} 分钟后再试",
|
||||
retry_after=int(wait),
|
||||
)
|
||||
if len(failures) + self._pending_accounts.get(account, 0) >= self.account_limit:
|
||||
raise _error(429, "rate_limited", "该账号正在登录,请稍候几秒再试", retry_after=5)
|
||||
failures = self._recent(self._ips, ip, self.ip_window, now)
|
||||
if len(failures) + self._pending_ips.get(ip, 0) >= self.ip_limit:
|
||||
wait = (failures[0] + self.ip_window - now) if failures else 5
|
||||
raise _error(
|
||||
429, "rate_limited",
|
||||
f"登录尝试过于频繁,请 {self._minutes(wait)} 分钟后再试",
|
||||
retry_after=int(wait),
|
||||
)
|
||||
while self._upstream and self._upstream[0] <= now - self.upstream_window:
|
||||
self._upstream.popleft()
|
||||
if self.upstream_budget:
|
||||
if len(self._upstream) >= self.upstream_budget:
|
||||
wait = self._upstream[0] + self.upstream_window - now
|
||||
raise _error(
|
||||
429, "upstream_budget",
|
||||
"近期手机端密码错误次数较多,为避免 ZYT 锁定服务器出口 IP,"
|
||||
f"已暂停手机登录,请 {self._minutes(wait)} 分钟后再试",
|
||||
retry_after=int(wait),
|
||||
)
|
||||
if len(self._upstream) + self._pending_upstream >= self.upstream_budget:
|
||||
raise _error(429, "rate_limited", "同时登录的人较多,请几秒后再试", retry_after=5)
|
||||
self._pending_accounts[account] += 1
|
||||
self._pending_ips[ip] += 1
|
||||
self._pending_upstream += 1
|
||||
return LoginAttempt(ip, account)
|
||||
|
||||
def finish(self, attempt: LoginAttempt, outcome: str) -> None:
|
||||
"""outcome:credentials(密码错)、unknown_account(账号不存在)、success(ZYT 认可了密码)、
|
||||
other(网络、终端未开通等,不记账)。"""
|
||||
if attempt.finished:
|
||||
return
|
||||
attempt.finished = True
|
||||
now = time.time()
|
||||
with self._lock:
|
||||
for book, key in ((self._pending_accounts, attempt.account), (self._pending_ips, attempt.ip)):
|
||||
book[key] -= 1
|
||||
if book[key] <= 0:
|
||||
del book[key]
|
||||
self._pending_upstream = max(0, self._pending_upstream - 1)
|
||||
if outcome in ("credentials", "unknown_account"):
|
||||
self._accounts.setdefault(attempt.account, deque()).append(now)
|
||||
self._ips.setdefault(attempt.ip, deque()).append(now)
|
||||
# ZYT 只给"账号存在、密码不对"累计出口 IP 的失败次数。
|
||||
if outcome == "credentials":
|
||||
self._upstream.append(now)
|
||||
elif outcome == "success":
|
||||
self._accounts.pop(attempt.account, None)
|
||||
# 密码校验通过时 ZYT 会清零该出口 IP 的失败计数(AdminAccountSafeCache::relieve)。
|
||||
self._upstream.clear()
|
||||
|
||||
def locked(self, seconds: int) -> None:
|
||||
with self._lock:
|
||||
self._locked_until = max(self._locked_until, time.time() + max(60, int(seconds)))
|
||||
|
||||
|
||||
class ZytMobileAuth:
|
||||
"""默认实现:真的去调 ZYT。测试里换成假的。"""
|
||||
|
||||
def __init__(self, api_url: Callable[[], str]):
|
||||
self._api_url = api_url
|
||||
|
||||
def login(self, account: str, password: str) -> str:
|
||||
return zyt_auth.login_admin(
|
||||
account, password, terminal=zyt_auth.WECOM_RPA_MOBILE_TERMINAL, api_url=self._api_url()
|
||||
)
|
||||
|
||||
def identity(self, token: str) -> dict[str, Any]:
|
||||
return zyt_auth.verify_admin_session(
|
||||
token, terminal=zyt_auth.WECOM_RPA_MOBILE_TERMINAL, api_url=self._api_url()
|
||||
)
|
||||
|
||||
def logout(self, token: str) -> None:
|
||||
zyt_auth.logout_admin(token, api_url=self._api_url())
|
||||
|
||||
|
||||
class _Waiter:
|
||||
__slots__ = ("key", "loop", "event")
|
||||
|
||||
def __init__(self, key: tuple[int, str]):
|
||||
self.key = key
|
||||
self.loop = asyncio.get_running_loop()
|
||||
self.event = asyncio.Event()
|
||||
|
||||
async def wait(self, timeout: float) -> None:
|
||||
try:
|
||||
await asyncio.wait_for(self.event.wait(), timeout=max(0.0, timeout))
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
|
||||
|
||||
class CommandNotifier:
|
||||
"""进程内唤醒:有新指令或黑名单变化时,立刻结束对应电脑挂着的长轮询。
|
||||
|
||||
先登记再查库:登记和查库之间落库的指令也能把它叫醒,不会白等一个复查周期。
|
||||
唤醒走 ``call_soon_threadsafe``,发通知的请求和挂起的长轮询不在同一个事件
|
||||
循环(线程)里也不会漏掉。
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._waiters: dict[tuple[int, str], set[_Waiter]] = {}
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def register(self, account_id: int, device_id: str) -> _Waiter:
|
||||
waiter = _Waiter((int(account_id), str(device_id)))
|
||||
with self._lock:
|
||||
self._waiters.setdefault(waiter.key, set()).add(waiter)
|
||||
return waiter
|
||||
|
||||
def unregister(self, waiter: _Waiter) -> None:
|
||||
with self._lock:
|
||||
waiters = self._waiters.get(waiter.key)
|
||||
if waiters is not None:
|
||||
waiters.discard(waiter)
|
||||
if not waiters:
|
||||
self._waiters.pop(waiter.key, None)
|
||||
|
||||
def notify(self, account_id: int, device_id: str | None = None) -> None:
|
||||
with self._lock:
|
||||
targets = [
|
||||
waiter
|
||||
for key, waiters in self._waiters.items()
|
||||
if key[0] == int(account_id) and (device_id is None or key[1] == device_id)
|
||||
for waiter in waiters
|
||||
]
|
||||
for waiter in targets:
|
||||
try:
|
||||
waiter.loop.call_soon_threadsafe(waiter.event.set)
|
||||
except RuntimeError:
|
||||
# 事件循环已经关闭(请求刚好结束),没有人需要被叫醒。
|
||||
continue
|
||||
|
||||
|
||||
class MobilePrincipal:
|
||||
def __init__(self, row: dict[str, Any], token: str):
|
||||
self.row = row
|
||||
self.token = token
|
||||
self.permissions = account_permissions(row)
|
||||
|
||||
@property
|
||||
def account_id(self) -> int:
|
||||
return int(self.row["id"])
|
||||
|
||||
@property
|
||||
def session_id(self) -> int:
|
||||
return int(self.row["session_id"])
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
return f"{account_label(self.row)}(手机)"
|
||||
|
||||
def me(self) -> dict[str, Any]:
|
||||
return {
|
||||
"account": {
|
||||
"id": self.account_id,
|
||||
"nickname": str(self.row.get("nickname") or ""),
|
||||
"sn": str(self.row.get("zyt_sn") or ""),
|
||||
"avatar": str(self.row.get("avatar") or ""),
|
||||
},
|
||||
"permissions": {
|
||||
"control": self.permissions["control"],
|
||||
"control_all": self.permissions["control_all"],
|
||||
"blacklist_add": self.permissions["blacklist_add"],
|
||||
"blacklist_remove": self.permissions["blacklist_remove"],
|
||||
"root": self.permissions["root"],
|
||||
"known": self.permissions["known"],
|
||||
},
|
||||
"permission_codes": {
|
||||
"control": PERM_REMOTE_CONTROL,
|
||||
"control_all": PERM_REMOTE_ALL,
|
||||
"blacklist_add": PERM_BLACKLIST_ADD,
|
||||
"blacklist_remove": PERM_BLACKLIST_REMOVE,
|
||||
},
|
||||
"session": {
|
||||
"created_at": str(self.row.get("session_created_at") or ""),
|
||||
"expires_at": int(self.row.get("session_expires_at") or 0),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
# ── 请求体 ───────────────────────────────────────────────────────────────────
|
||||
class MobileLoginBody(BaseModel):
|
||||
account: str = Field(min_length=1, max_length=64)
|
||||
password: str = Field(min_length=1, max_length=128, repr=False)
|
||||
client_name: str = Field(default="", max_length=120)
|
||||
|
||||
|
||||
class CommandBody(BaseModel):
|
||||
type: str = Field(min_length=1, max_length=32)
|
||||
|
||||
|
||||
class BlacklistBody(BaseModel):
|
||||
name: str = Field(default="", max_length=191)
|
||||
account_name: str = Field(default="", max_length=191)
|
||||
reason: str = Field(default="", max_length=200)
|
||||
|
||||
|
||||
class StatusBody(BaseModel):
|
||||
listening: bool = False
|
||||
state: str = Field(default="", max_length=32)
|
||||
transport: str = Field(default="", max_length=16)
|
||||
wecom_connected: bool = False
|
||||
pending_count: int = Field(default=0, ge=0, le=1_000_000)
|
||||
app_version: str = Field(default="", max_length=64)
|
||||
capabilities: list[str] = Field(default_factory=list, max_length=16)
|
||||
|
||||
|
||||
class DesktopPollBody(BaseModel):
|
||||
wait: int = Field(default=15, ge=0, le=60)
|
||||
status: StatusBody | None = None
|
||||
# 桌面端当前持有的黑名单版本;与服务端不一致时立即返回,让它去同步。
|
||||
blacklist_version: int | None = Field(default=None, ge=0)
|
||||
|
||||
|
||||
class AckBody(BaseModel):
|
||||
ok: bool
|
||||
result: dict[str, Any] = Field(default_factory=dict)
|
||||
error: str = Field(default="", max_length=500)
|
||||
status: StatusBody | None = None
|
||||
|
||||
|
||||
class DesktopBlacklistSyncBody(BaseModel):
|
||||
add: list[dict[str, Any]] = Field(default_factory=list, max_length=500)
|
||||
|
||||
|
||||
def register_remote_routes(
|
||||
app: FastAPI,
|
||||
database: Any,
|
||||
*,
|
||||
current_desktop: Callable[..., Any],
|
||||
zyt_api_url: Callable[[], str],
|
||||
zyt_mobile_auth: Any = None,
|
||||
login_guard: MobileLoginGuard | None = None,
|
||||
) -> RemoteStore:
|
||||
store = RemoteStore(database)
|
||||
store.initialize()
|
||||
app.state.remote_store = store
|
||||
notifier = CommandNotifier()
|
||||
app.state.remote_notifier = notifier
|
||||
guard = login_guard or MobileLoginGuard()
|
||||
auth = zyt_mobile_auth or ZytMobileAuth(zyt_api_url)
|
||||
identity_locks: dict[int, asyncio.Lock] = {}
|
||||
|
||||
# ── 手机端鉴权 ───────────────────────────────────────────────────────
|
||||
async def _recheck_identity(row: dict[str, Any], request: Request) -> dict[str, Any] | None:
|
||||
# 同一会话并发的几个请求只复核一次;用完即删,锁表不随会话数增长。
|
||||
session_id = int(row["session_id"])
|
||||
lock = identity_locks.setdefault(session_id, asyncio.Lock())
|
||||
try:
|
||||
async with lock:
|
||||
return await _recheck_identity_locked(session_id, request)
|
||||
finally:
|
||||
if not lock.locked() and identity_locks.get(session_id) is lock:
|
||||
identity_locks.pop(session_id, None)
|
||||
|
||||
async def _recheck_identity_locked(session_id: int, request: Request) -> dict[str, Any] | None:
|
||||
fresh = await asyncio.to_thread(store.mobile_session, _bearer(request))
|
||||
if fresh is None:
|
||||
return None
|
||||
if time.time() - int(fresh["identity_checked_at"] or 0) < MOBILE_IDENTITY_RECHECK_SECONDS:
|
||||
return fresh
|
||||
zyt_token = await asyncio.to_thread(store.mobile_zyt_token, session_id)
|
||||
try:
|
||||
if not zyt_token:
|
||||
raise zyt_auth.ZytLoginError("ZYT 会话缺失", kind="rejected")
|
||||
identity = await asyncio.to_thread(auth.identity, zyt_token)
|
||||
if str(identity.get("user_id") or "") != str(fresh["zyt_user_id"]):
|
||||
raise zyt_auth.ZytLoginError("ZYT 身份与手机会话不一致", kind="rejected")
|
||||
except zyt_auth.ZytAuthError as exc:
|
||||
if getattr(exc, "kind", "") == "unavailable":
|
||||
# ZYT 暂时连不上不算下线:沿用上次同步的权限,一分钟后再试。
|
||||
await asyncio.to_thread(store.mark_identity_checked, session_id, retry_in=60)
|
||||
return fresh
|
||||
await asyncio.to_thread(
|
||||
store.revoke_mobile_session, session_id=session_id,
|
||||
reason="zyt_invalid", ip=trusted_client_ip(request),
|
||||
)
|
||||
return None
|
||||
try:
|
||||
await asyncio.to_thread(store.refresh_identity, session_id, identity)
|
||||
except PermissionError:
|
||||
await asyncio.to_thread(
|
||||
store.revoke_mobile_session, session_id=session_id,
|
||||
reason="account_disabled", ip=trusted_client_ip(request),
|
||||
)
|
||||
return None
|
||||
return await asyncio.to_thread(store.mobile_session, _bearer(request))
|
||||
|
||||
async def current_mobile(request: Request) -> MobilePrincipal:
|
||||
token = _bearer(request)
|
||||
row = await asyncio.to_thread(store.mobile_session, token) if token else None
|
||||
if row is not None and time.time() - int(row["identity_checked_at"] or 0) >= MOBILE_IDENTITY_RECHECK_SECONDS:
|
||||
row = await _recheck_identity(row, request)
|
||||
if row is None:
|
||||
raise _error(401, "session_expired", "登录已失效,请重新登录")
|
||||
return MobilePrincipal(row, token)
|
||||
|
||||
def target_account(principal: MobilePrincipal, account_id: int | None) -> dict[str, Any]:
|
||||
if account_id is None or int(account_id) == principal.account_id:
|
||||
return principal.row
|
||||
if not principal.permissions["control_all"]:
|
||||
raise _error(403, "forbidden", "只能查看和控制自己的电脑")
|
||||
account = store.account(int(account_id))
|
||||
if account is None or str(account.get("status")) != "active":
|
||||
raise _error(404, "account_not_found", "客服账号不存在或已停用")
|
||||
return account
|
||||
|
||||
# ── 手机端:登录 ─────────────────────────────────────────────────────
|
||||
@app.post("/api/v2/mobile/auth/login")
|
||||
async def mobile_login(body: MobileLoginBody, request: Request) -> dict:
|
||||
ip = trusted_client_ip(request)
|
||||
if https_required(request):
|
||||
raise _error(403, "https_required", "请通过 HTTPS 地址访问手机控制台,明文连接不能提交密码")
|
||||
account_key = body.account.strip().lower()
|
||||
attempt = guard.begin(ip, account_key)
|
||||
outcome = "other"
|
||||
try:
|
||||
zyt_token = await asyncio.to_thread(auth.login, body.account.strip(), body.password)
|
||||
outcome = "success"
|
||||
except zyt_auth.ZytLoginError as exc:
|
||||
if exc.kind in ("credentials", "unknown_account"):
|
||||
outcome = exc.kind
|
||||
database.audit(None, "mobile.login.failed", f"account={account_key[:64]}", ip)
|
||||
raise _error(401, "invalid_credentials", "账号或密码错误") from exc
|
||||
if exc.kind == "password_change_required":
|
||||
outcome = "success"
|
||||
raise _error(403, "password_change_required", str(exc)) from exc
|
||||
if exc.kind == "locked":
|
||||
guard.locked(exc.retry_after or 1800)
|
||||
database.audit(None, "mobile.login.locked", f"account={account_key[:64]}", ip)
|
||||
raise _error(429, "zyt_locked", str(exc), retry_after=exc.retry_after) from exc
|
||||
if exc.kind == "disabled":
|
||||
raise _error(403, "account_disabled", str(exc)) from exc
|
||||
if exc.kind == "terminal_unsupported":
|
||||
raise _error(503, "terminal_unsupported", str(exc)) from exc
|
||||
if exc.kind == "unavailable":
|
||||
raise _error(502, "zyt_unavailable", "ZYT 登录服务暂不可用,请稍后重试") from exc
|
||||
raise _error(400, "login_rejected", str(exc)) from exc
|
||||
except zyt_auth.ZytAuthError as exc:
|
||||
raise _error(502, "zyt_unavailable", "ZYT 登录服务暂不可用,请稍后重试") from exc
|
||||
finally:
|
||||
guard.finish(attempt, outcome)
|
||||
try:
|
||||
identity = await asyncio.to_thread(auth.identity, zyt_token)
|
||||
account = await asyncio.to_thread(store.upsert_account, identity)
|
||||
except zyt_auth.ZytLoginError as exc:
|
||||
await asyncio.to_thread(auth.logout, zyt_token)
|
||||
status_code = {"terminal_unsupported": 503, "disabled": 403}.get(exc.kind, 502)
|
||||
code = {"terminal_unsupported": "terminal_unsupported",
|
||||
"disabled": "account_disabled"}.get(exc.kind, "zyt_unavailable")
|
||||
raise _error(status_code, code, str(exc)) from exc
|
||||
except zyt_auth.ZytAuthError as exc:
|
||||
await asyncio.to_thread(auth.logout, zyt_token)
|
||||
raise _error(502, "zyt_unavailable", str(exc)) from exc
|
||||
except PermissionError as exc:
|
||||
await asyncio.to_thread(auth.logout, zyt_token)
|
||||
raise _error(403, "account_disabled", str(exc)) from exc
|
||||
except ValueError as exc:
|
||||
await asyncio.to_thread(auth.logout, zyt_token)
|
||||
raise _error(502, "zyt_unavailable", str(exc)) from exc
|
||||
token, session = await asyncio.to_thread(
|
||||
store.create_mobile_session, int(account["id"]), zyt_token=zyt_token,
|
||||
client_name=body.client_name, user_agent=request.headers.get("user-agent", ""), ip=ip,
|
||||
)
|
||||
row = await asyncio.to_thread(store.mobile_session, token)
|
||||
principal = MobilePrincipal(row, token)
|
||||
return {"access_token": token, "expires_at": session["expires_at"], "me": principal.me()}
|
||||
|
||||
@app.post("/api/v2/mobile/auth/logout")
|
||||
async def mobile_logout(request: Request, principal: MobilePrincipal = Depends(current_mobile)) -> dict:
|
||||
zyt_token = await asyncio.to_thread(store.mobile_zyt_token, principal.session_id)
|
||||
await asyncio.to_thread(
|
||||
store.revoke_mobile_session, session_id=principal.session_id, reason="logout",
|
||||
ip=trusted_client_ip(request),
|
||||
)
|
||||
if zyt_token:
|
||||
await asyncio.to_thread(auth.logout, zyt_token)
|
||||
return {"ok": True}
|
||||
|
||||
@app.get("/api/v2/mobile/me")
|
||||
async def mobile_me(principal: MobilePrincipal = Depends(current_mobile)) -> dict:
|
||||
return principal.me()
|
||||
|
||||
# ── 手机端:电脑 ─────────────────────────────────────────────────────
|
||||
@app.get("/api/v2/mobile/accounts")
|
||||
async def mobile_accounts(
|
||||
q: str = Query(default="", max_length=64),
|
||||
principal: MobilePrincipal = Depends(current_mobile),
|
||||
) -> dict:
|
||||
if not principal.permissions["control_all"]:
|
||||
raise _error(403, "forbidden", f"查看全部客服电脑需要 ZYT 权限 {PERM_REMOTE_ALL}")
|
||||
return {"items": await asyncio.to_thread(store.accounts_overview, q)}
|
||||
|
||||
@app.get("/api/v2/mobile/desktops")
|
||||
async def mobile_desktops(
|
||||
account_id: int | None = Query(default=None, ge=1),
|
||||
principal: MobilePrincipal = Depends(current_mobile),
|
||||
) -> dict:
|
||||
account = target_account(principal, account_id)
|
||||
items = await asyncio.to_thread(store.devices, int(account["id"]))
|
||||
return {
|
||||
"account": {
|
||||
"id": int(account["id"]),
|
||||
"nickname": str(account.get("nickname") or ""),
|
||||
"sn": str(account.get("zyt_sn") or ""),
|
||||
},
|
||||
"items": items,
|
||||
"server_time": int(time.time()),
|
||||
}
|
||||
|
||||
@app.post("/api/v2/mobile/desktops/{device_id}/commands")
|
||||
async def mobile_create_command(
|
||||
device_id: str, body: CommandBody, request: Request,
|
||||
account_id: int | None = Query(default=None, ge=1),
|
||||
principal: MobilePrincipal = Depends(current_mobile),
|
||||
) -> dict:
|
||||
account = target_account(principal, account_id)
|
||||
if not principal.permissions["control"]:
|
||||
raise _error(403, "forbidden", f"远程启停需要 ZYT 权限 {PERM_REMOTE_CONTROL}")
|
||||
if body.type not in COMMAND_TYPES:
|
||||
raise _error(400, "invalid_command", "不支持的指令")
|
||||
try:
|
||||
device_id = valid_device_id(device_id)
|
||||
except ValueError as exc:
|
||||
raise _error(404, "device_not_found", "电脑不存在") from exc
|
||||
device = await asyncio.to_thread(store.device, int(account["id"]), device_id)
|
||||
if device is None:
|
||||
raise _error(404, "device_not_found", "电脑不存在或已被管理端下线")
|
||||
if not device["online"]:
|
||||
raise _error(409, "device_offline", "电脑离线:客服软件没有运行,无法远程拉起")
|
||||
if not device["remote_capable"]:
|
||||
raise _error(409, "client_outdated", "该电脑上的客服软件版本过低,请升级后再远程控制")
|
||||
try:
|
||||
command = await asyncio.to_thread(
|
||||
store.create_command, account_id=int(account["id"]), device_id=device_id,
|
||||
command_type=body.type, actor_account_id=principal.account_id,
|
||||
actor_label=principal.label, ip=trusted_client_ip(request),
|
||||
)
|
||||
except LookupError as exc:
|
||||
raise _error(404, "device_not_found", str(exc)) from exc
|
||||
notifier.notify(int(account["id"]), device_id)
|
||||
return {"command": command}
|
||||
|
||||
@app.get("/api/v2/mobile/commands/{command_id}")
|
||||
async def mobile_command(
|
||||
command_id: str, principal: MobilePrincipal = Depends(current_mobile),
|
||||
) -> dict:
|
||||
command = await asyncio.to_thread(store.command, command_id)
|
||||
if command is None:
|
||||
raise _error(404, "command_not_found", "指令不存在")
|
||||
if command["account_id"] != principal.account_id and not principal.permissions["control_all"]:
|
||||
raise _error(404, "command_not_found", "指令不存在")
|
||||
command.pop("account_id", None)
|
||||
return {"command": command}
|
||||
|
||||
# ── 手机端:会话与黑名单 ─────────────────────────────────────────────
|
||||
@app.get("/api/v2/mobile/conversations")
|
||||
async def mobile_conversations(
|
||||
account_id: int | None = Query(default=None, ge=1),
|
||||
q: str = Query(default="", max_length=100),
|
||||
scope: str = Query(default="all", pattern="^(all|blocked)$"),
|
||||
cursor: str = Query(default="", max_length=200),
|
||||
limit: int = Query(default=30, ge=1, le=100),
|
||||
principal: MobilePrincipal = Depends(current_mobile),
|
||||
) -> dict:
|
||||
account = target_account(principal, account_id)
|
||||
try:
|
||||
return await asyncio.to_thread(
|
||||
store.conversations, str(account["tenant_id"]), query=q, scope=scope,
|
||||
cursor=cursor, limit=limit,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise _error(400, "invalid_cursor", str(exc)) from exc
|
||||
|
||||
@app.put("/api/v2/mobile/blacklist/{account}/{conversation:path}")
|
||||
async def mobile_blacklist_add(
|
||||
account: str, conversation: str, body: BlacklistBody, request: Request,
|
||||
account_id: int | None = Query(default=None, ge=1),
|
||||
principal: MobilePrincipal = Depends(current_mobile),
|
||||
) -> dict:
|
||||
target = target_account(principal, account_id)
|
||||
if not principal.permissions["blacklist_add"]:
|
||||
raise _error(403, "forbidden", f"加入黑名单需要 ZYT 权限 {PERM_BLACKLIST_ADD}")
|
||||
try:
|
||||
entry, version = await asyncio.to_thread(
|
||||
store.add_blacklist, str(target["tenant_id"]),
|
||||
{"account": account, "conversation": conversation, **body.model_dump()},
|
||||
source="mobile", actor_label=principal.label,
|
||||
actor_account_id=principal.account_id, ip=trusted_client_ip(request),
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise _error(400, "invalid_conversation", str(exc)) from exc
|
||||
notifier.notify(int(target["id"]))
|
||||
return {"entry": entry, "version": version}
|
||||
|
||||
@app.delete("/api/v2/mobile/blacklist/{account}/{conversation:path}")
|
||||
async def mobile_blacklist_remove(
|
||||
account: str, conversation: str, request: Request,
|
||||
account_id: int | None = Query(default=None, ge=1),
|
||||
principal: MobilePrincipal = Depends(current_mobile),
|
||||
) -> dict:
|
||||
target = target_account(principal, account_id)
|
||||
if not principal.permissions["blacklist_remove"]:
|
||||
raise _error(403, "forbidden", f"移出黑名单需要 ZYT 权限 {PERM_BLACKLIST_REMOVE},请联系主管")
|
||||
try:
|
||||
version = await asyncio.to_thread(
|
||||
store.remove_blacklist, str(target["tenant_id"]), account, conversation,
|
||||
source="mobile", actor_label=principal.label, ip=trusted_client_ip(request),
|
||||
)
|
||||
except LookupError as exc:
|
||||
raise _error(404, "not_blocked", str(exc)) from exc
|
||||
except ValueError as exc:
|
||||
raise _error(400, "invalid_conversation", str(exc)) from exc
|
||||
notifier.notify(int(target["id"]))
|
||||
return {"ok": True, "version": version}
|
||||
|
||||
# ── 桌面端:命令通道 ─────────────────────────────────────────────────
|
||||
def _desktop_label(account: Any) -> str:
|
||||
return f"{account_label(account)}(电脑 {str(account['device_name'] or '')[:40]})"
|
||||
|
||||
async def _report(account: Any, status: StatusBody | None) -> None:
|
||||
if status is None:
|
||||
return
|
||||
await asyncio.to_thread(
|
||||
store.report_status, int(account["id"]), str(account["device_id"]),
|
||||
status.model_dump(), app_version=str(account["app_version"] or ""),
|
||||
)
|
||||
|
||||
@app.post("/api/v2/desktop/commands/poll")
|
||||
async def desktop_poll(
|
||||
body: DesktopPollBody, request: Request, account: Any = Depends(current_desktop),
|
||||
) -> dict:
|
||||
account_id = int(account["id"])
|
||||
device_id = str(account["device_id"])
|
||||
tenant = str(account["tenant_id"])
|
||||
await _report(account, body.status)
|
||||
wait = float(min(body.wait, MAX_POLL_WAIT_SECONDS))
|
||||
deadline = time.monotonic() + wait
|
||||
while True:
|
||||
waiter = notifier.register(account_id, device_id)
|
||||
try:
|
||||
commands = await asyncio.to_thread(store.take_commands, account_id, device_id)
|
||||
version = await asyncio.to_thread(store.blacklist_version, tenant)
|
||||
remaining = deadline - time.monotonic()
|
||||
if (
|
||||
commands
|
||||
or (body.blacklist_version is not None and version != body.blacklist_version)
|
||||
or remaining <= 0
|
||||
or await request.is_disconnected()
|
||||
):
|
||||
break
|
||||
await waiter.wait(min(remaining, POLL_RECHECK_SECONDS))
|
||||
finally:
|
||||
notifier.unregister(waiter)
|
||||
return {"commands": commands, "blacklist_version": version, "server_time": int(time.time())}
|
||||
|
||||
@app.post("/api/v2/desktop/commands/{command_id}/ack")
|
||||
async def desktop_ack(
|
||||
command_id: str, body: AckBody, request: Request, account: Any = Depends(current_desktop),
|
||||
) -> dict:
|
||||
await _report(account, body.status)
|
||||
try:
|
||||
command = await asyncio.to_thread(
|
||||
store.ack_command, account_id=int(account["id"]),
|
||||
device_id=str(account["device_id"]), command_id=command_id, ok=body.ok,
|
||||
result=body.result, error=body.error, ip=trusted_client_ip(request),
|
||||
)
|
||||
except LookupError as exc:
|
||||
raise _error(404, "command_not_found", str(exc)) from exc
|
||||
return {"ok": True, "command": command}
|
||||
|
||||
@app.post("/api/v2/desktop/status")
|
||||
async def desktop_status(body: StatusBody, account: Any = Depends(current_desktop)) -> dict:
|
||||
await _report(account, body)
|
||||
return {"ok": True}
|
||||
|
||||
# ── 桌面端:黑名单 ───────────────────────────────────────────────────
|
||||
@app.get("/api/v2/desktop/blacklist")
|
||||
async def desktop_blacklist(account: Any = Depends(current_desktop)) -> dict:
|
||||
version, items = await asyncio.to_thread(store.blacklist, str(account["tenant_id"]))
|
||||
return {"version": version, "items": items}
|
||||
|
||||
@app.post("/api/v2/desktop/blacklist/sync")
|
||||
async def desktop_blacklist_sync(
|
||||
body: DesktopBlacklistSyncBody, request: Request, account: Any = Depends(current_desktop),
|
||||
) -> dict:
|
||||
# 电脑前的人加黑名单不要求 ZYT 权限:拉黑只会让系统少发消息,是安全方向;
|
||||
# 离线时加的、升级前本地就有的条目也都从这里补传。
|
||||
before = await asyncio.to_thread(store.blacklist_version, str(account["tenant_id"]))
|
||||
version, items, rejected = await asyncio.to_thread(
|
||||
store.sync_desktop_blacklist, str(account["tenant_id"]), body.add,
|
||||
actor_label=_desktop_label(account), actor_account_id=int(account["id"]),
|
||||
ip=trusted_client_ip(request),
|
||||
)
|
||||
if version != before:
|
||||
notifier.notify(int(account["id"]))
|
||||
return {"version": version, "items": items, "rejected": rejected}
|
||||
|
||||
@app.delete("/api/v2/desktop/blacklist/{account_key}/{conversation:path}")
|
||||
async def desktop_blacklist_remove(
|
||||
account_key: str, conversation: str, request: Request,
|
||||
account: Any = Depends(current_desktop),
|
||||
) -> dict:
|
||||
if not account_permissions(account)["blacklist_remove"]:
|
||||
raise _error(
|
||||
403, "forbidden",
|
||||
f"移出黑名单需要 ZYT 权限 {PERM_BLACKLIST_REMOVE},请联系主管在手机控制台操作",
|
||||
)
|
||||
try:
|
||||
version = await asyncio.to_thread(
|
||||
store.remove_blacklist, str(account["tenant_id"]), account_key, conversation,
|
||||
source="desktop", actor_label=_desktop_label(account), ip=trusted_client_ip(request),
|
||||
)
|
||||
except LookupError as exc:
|
||||
raise _error(404, "not_blocked", str(exc)) from exc
|
||||
except ValueError as exc:
|
||||
raise _error(400, "invalid_conversation", str(exc)) from exc
|
||||
notifier.notify(int(account["id"]))
|
||||
return {"ok": True, "version": version}
|
||||
|
||||
return store
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"release": "mobile-http-20260928",
|
||||
"candidateRoot": "C:/kefu",
|
||||
"backendFiles": [
|
||||
"wechat_rpa/remote_api.py"
|
||||
],
|
||||
"newBackendFiles": [],
|
||||
"deployFiles": [],
|
||||
"frontendDir": "admin-web/apps/mobile-h5/dist",
|
||||
"serverTestModules": [
|
||||
"test_remote_api",
|
||||
"test_zyt_auth",
|
||||
"test_backend"
|
||||
],
|
||||
"imageTestModules": [
|
||||
"test_archive_api"
|
||||
],
|
||||
"schemaMigration": "none",
|
||||
"restartServices": [
|
||||
"api"
|
||||
],
|
||||
"notes": "User request 2026-09-28: the phone console must also work over plain HTTP from outside the office. MOBILE_REQUIRE_HTTPS now defaults to never (auto/always still available once HTTPS exists); the /m/ login page no longer shows the intranet-only banner. No database change."
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
"""Read-only checks for mobile-http-20260928: baseline / candidate / deployed.
|
||||
|
||||
Prints hashes and status only; never reads chat content, patients or credentials.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import argparse, hashlib, json, subprocess, urllib.error, urllib.request
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('mode', choices=['baseline', 'candidate', 'deployed'])
|
||||
args = parser.parse_args()
|
||||
RELEASE = 'mobile-http-20260928'
|
||||
BANNER = '只能在公司内网登录'
|
||||
folder = Path(__file__).resolve().parent
|
||||
project = Path('/opt/im-admin')
|
||||
base = json.loads((folder / 'server-baseline.json').read_text())
|
||||
plan = json.loads((folder / 'release-plan.json').read_text())
|
||||
manifest = json.loads((folder / 'manifest.json').read_text())
|
||||
payload_rows = [row for row in manifest if row['path'].startswith('payload/')]
|
||||
frontend = plan['frontendDir']
|
||||
sha = lambda data: hashlib.sha256(data).hexdigest()
|
||||
image = lambda ref: subprocess.check_output(['docker', 'image', 'inspect', ref, '--format', '{{.Id}}'], text=True).strip()
|
||||
|
||||
# The unpacked bundle itself must be intact.
|
||||
for row in manifest:
|
||||
path = (folder / row['path']).resolve()
|
||||
assert path.is_relative_to(folder), row['path']
|
||||
assert path.stat().st_size == row['bytes'] and sha(path.read_bytes()) == row['sha256'], row['path']
|
||||
|
||||
# project-relative path -> expected sha256 on the host
|
||||
if args.mode == 'baseline':
|
||||
expected_host = dict(base['expected'])
|
||||
else:
|
||||
expected_host = {row['path'][len('payload/'):]: row['sha256'] for row in payload_rows}
|
||||
container_code = {k: v for k, v in expected_host.items() if k.startswith(('wechat_rpa/', 'admin-web/'))}
|
||||
frontend_files = sorted(k[len(frontend) + 1:] for k in expected_host if k.startswith(frontend + '/'))
|
||||
|
||||
|
||||
def in_container(code, target, ref=None):
|
||||
command = (['docker', 'run', '--rm', '-i', '--network=none', '--entrypoint', 'python', ref, '-c', code]
|
||||
if ref else ['docker', 'exec', '-i', 'im-admin-api-1', 'python', '-c', code])
|
||||
return json.loads(subprocess.check_output(command, input=json.dumps(target).encode()))
|
||||
|
||||
|
||||
HASHES = ('from pathlib import Path;import hashlib,json,sys;names=json.load(sys.stdin);'
|
||||
'print(json.dumps({n:(hashlib.sha256((Path("/app")/n).read_bytes()).hexdigest() '
|
||||
'if (Path("/app")/n).is_file() else None) for n in names}))')
|
||||
# /m/ 目录里的完整文件清单(不能残留旧版带横幅的页面文件)和横幅文字检查。
|
||||
FRONTEND = ('from pathlib import Path;import json,sys;q=json.load(sys.stdin);root=Path("/app")/q["root"];'
|
||||
'files=sorted(p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file());'
|
||||
'print(json.dumps({"files":files,"banner":[f for f in files if q["banner"] in '
|
||||
'(root/f).read_bytes().decode("utf-8","ignore")]}))')
|
||||
FRONTEND_QUERY = {'root': frontend, 'banner': BANNER}
|
||||
|
||||
current = image('zyt/wecom-admin:current')
|
||||
result = {'mode': args.mode, 'release': RELEASE, 'image': current}
|
||||
# 只重建 api:网关和知识库 worker 继续跑它们自己的镜像,部署后核对它们没有被动过。
|
||||
OTHERS = ['im-admin-gateway-1', 'im-admin-knowledge-worker-1']
|
||||
|
||||
|
||||
def inspect(container):
|
||||
raw = json.loads(subprocess.check_output(['docker', 'inspect', container]))[0]
|
||||
return {'id': raw['Id'], 'image': raw['Image'], 'running': raw['State']['Running'],
|
||||
'health': raw['State'].get('Health', {}).get('Status', 'not_configured')}
|
||||
|
||||
|
||||
if args.mode == 'baseline':
|
||||
api = inspect('im-admin-api-1')
|
||||
assert api['image'] == current, 'API container is not on zyt/wecom-admin:current'
|
||||
assert api['running'] and api['health'] == 'healthy', 'API container is not healthy'
|
||||
others = {name: inspect(name) for name in OTHERS}
|
||||
for name, state in others.items():
|
||||
assert state['running'], 'Not running: ' + name
|
||||
result['others'] = others
|
||||
|
||||
if args.mode in ('baseline', 'deployed'):
|
||||
for name, wanted in expected_host.items():
|
||||
assert sha((project / name).read_bytes()) == wanted, 'Host drift: ' + name
|
||||
actual = in_container(HASHES, sorted(container_code))
|
||||
assert actual == container_code, 'Running api container differs from expected code'
|
||||
result['files'] = len(expected_host)
|
||||
|
||||
if args.mode == 'candidate':
|
||||
candidate = 'zyt/wecom-admin:' + RELEASE
|
||||
actual = in_container(HASHES, sorted(container_code), candidate)
|
||||
assert actual == container_code, 'Candidate image differs from manifest'
|
||||
listing = in_container(FRONTEND, FRONTEND_QUERY, candidate)
|
||||
assert listing['files'] == frontend_files, 'Candidate /m/ has extra or missing files'
|
||||
assert not listing['banner'], listing['banner']
|
||||
result['candidate'] = image(candidate)
|
||||
result['files'] = len(container_code)
|
||||
|
||||
if args.mode == 'deployed':
|
||||
wanted = image('zyt/wecom-admin:' + RELEASE)
|
||||
assert current == wanted, 'current tag does not point at the release image'
|
||||
raw = json.loads(subprocess.check_output(['docker', 'inspect', 'im-admin-api-1']))[0]
|
||||
assert raw['Image'] == wanted and raw['State']['Running'] and raw['RestartCount'] == 0
|
||||
assert raw['State'].get('Health', {}).get('Status') == 'healthy'
|
||||
recorded = folder / 'baseline-check.json'
|
||||
if recorded.exists():
|
||||
before = json.loads(recorded.read_text())['others']
|
||||
for name in OTHERS:
|
||||
now = inspect(name)
|
||||
assert now['id'] == before[name]['id'] and now['running'], 'Unrelated container changed: ' + name
|
||||
result['others_unchanged'] = OTHERS
|
||||
host_files = sorted(p.relative_to(project / frontend).as_posix() for p in (project / frontend).rglob('*') if p.is_file())
|
||||
assert host_files == frontend_files, 'Host /m/ has extra or missing files'
|
||||
listing = in_container(FRONTEND, FRONTEND_QUERY)
|
||||
assert listing['files'] == frontend_files and not listing['banner'], listing
|
||||
for url in ['http://127.0.0.1:18766/api/v2/health', 'http://127.0.0.1:18770/health']:
|
||||
with urllib.request.urlopen(url, timeout=15) as response:
|
||||
assert response.status == 200, url
|
||||
# New routes still refuse anonymous callers. No login is attempted.
|
||||
for method, path in [('GET', '/api/v2/mobile/me'), ('GET', '/api/v2/mobile/desktops'),
|
||||
('POST', '/api/v2/desktop/commands/poll'), ('GET', '/api/v2/desktop/blacklist')]:
|
||||
request = urllib.request.Request('http://127.0.0.1:18766' + path, method=method,
|
||||
data=b'{}' if method == 'POST' else None,
|
||||
headers={'Content-Type': 'application/json'})
|
||||
try:
|
||||
urllib.request.urlopen(request, timeout=15)
|
||||
except urllib.error.HTTPError as exc:
|
||||
assert exc.code == 401, (path, exc.code)
|
||||
else:
|
||||
raise AssertionError('Accessible without authentication: ' + path)
|
||||
with urllib.request.urlopen('http://127.0.0.1:18766/m/', timeout=15) as response:
|
||||
body = response.read()
|
||||
assert response.status == 200 and '企微客服助手'.encode() in body, 'mobile console entry missing'
|
||||
# 本次目的:公网来源的明文 HTTP 登录不再被拒绝(在运行中的容器里、用它的真实环境变量判断)。
|
||||
code = ("import remote_api,json;from starlette.requests import Request;"
|
||||
"r=Request({'type':'http','method':'POST','path':'/api/v2/mobile/auth/login','root_path':'',"
|
||||
"'headers':[(b'x-real-ip',b'114.114.114.114')],'scheme':'http','query_string':b'',"
|
||||
"'client':('172.18.0.1',40000),'server':('127.0.0.1',8766)});"
|
||||
"print(json.dumps({'public_http_login_refused':remote_api.https_required(r)}))")
|
||||
policy = json.loads(subprocess.check_output(['docker', 'exec', '-i', 'im-admin-api-1', 'python', '-c', code]))
|
||||
assert policy == {'public_http_login_refused': False}, policy
|
||||
result['policy'] = policy
|
||||
|
||||
result['status'] = 'passed'
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env bash
|
||||
# 恢复 remote_api.py 和原 /m/ 目录,切回旧镜像(mobile-remote-20260928),只重建 api。不涉及数据库。
|
||||
set -euo pipefail
|
||||
test "${REMOTE_RELEASE_APPROVED:-}" = mobile-http-20260928
|
||||
release=/home/ps/mobile-http-20260928
|
||||
cd /opt/im-admin/deploy/im-admin
|
||||
test -d "$release/source-before"
|
||||
test "$(docker image inspect zyt/wecom-admin:before-mobile-http-20260928 --format '{{.Id}}')" = "$(cat "$release/image-before.txt")"
|
||||
python3 - <<'PY'
|
||||
from pathlib import Path
|
||||
import hashlib, json, os, shutil
|
||||
r = Path('/home/ps/mobile-http-20260928'); project = Path('/opt/im-admin')
|
||||
base = json.loads((r / 'server-baseline.json').read_text())
|
||||
plan = json.loads((r / 'release-plan.json').read_text())
|
||||
sha = lambda data: hashlib.sha256(data).hexdigest()
|
||||
for name in plan['backendFiles'] + plan['deployFiles']:
|
||||
data = (r / 'source-before' / name).read_bytes(); assert sha(data) == base['expected'][name]
|
||||
target = project / name; tmp = target.with_name(target.name + '.rollback-http.tmp')
|
||||
if tmp.exists():
|
||||
tmp.unlink()
|
||||
with tmp.open('xb') as f:
|
||||
f.write(data)
|
||||
os.chmod(tmp, target.stat().st_mode & 0o777); os.replace(tmp, target)
|
||||
frontend = plan['frontendDir']
|
||||
saved = r / 'source-before' / frontend
|
||||
for name, wanted in base['expected'].items():
|
||||
if name.startswith(frontend + '/'):
|
||||
assert sha((saved / name[len(frontend) + 1:]).read_bytes()) == wanted, name
|
||||
restore = project / (frontend + '.rollback-http.tmp')
|
||||
if restore.exists():
|
||||
shutil.rmtree(restore)
|
||||
shutil.copytree(saved, restore)
|
||||
for leftover in [project / frontend, project / (frontend + '.mobile-http.tmp')]:
|
||||
if leftover.exists():
|
||||
shutil.rmtree(leftover)
|
||||
old = project / (frontend + '.mobile-http.old')
|
||||
if old.exists():
|
||||
shutil.rmtree(old)
|
||||
os.replace(restore, project / frontend)
|
||||
PY
|
||||
docker tag zyt/wecom-admin:before-mobile-http-20260928 zyt/wecom-admin:current
|
||||
docker compose up -d --no-deps --no-build --wait --wait-timeout 180 api
|
||||
curl -fsS -o /dev/null http://127.0.0.1:18766/api/v2/health
|
||||
curl -fsS -o /dev/null http://127.0.0.1:18770/health
|
||||
printf '%s\n' 'Previous image, remote_api.py and /m/ restored.'
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"host": "192.168.110.111",
|
||||
"user": "ps",
|
||||
"project": "/opt/im-admin",
|
||||
"compose": "/opt/im-admin/deploy/im-admin",
|
||||
"checked_at": "2026-09-28",
|
||||
"source": "Production as deployed by mobile-remote-20260928 (15:21): remote_api.py and the 28 /m/ files from that release payload; remote_api.py hash re-read from the host before building this release.",
|
||||
"expected": {
|
||||
"admin-web/apps/mobile-h5/dist/assets/_plugin-vue_export-helper-CT0ZqwFS.js": "97abcbc7c960add5c448947dad40ea8ca6ca2ae18069a632b62b61723e43f24f",
|
||||
"admin-web/apps/mobile-h5/dist/assets/AccountSwitcher-5FuHazzf.js": "8c06092db48aca97b0d3fb35871315e4434b5ad5ccd9c5d44a7cfc3ba343db22",
|
||||
"admin-web/apps/mobile-h5/dist/assets/AccountSwitcher-BZXg15MH.css": "b61f1f1af65c2c3438066ffe41683af7e38062eb9389cda3f8fdad8ee77498ff",
|
||||
"admin-web/apps/mobile-h5/dist/assets/brand-mark-CPUQS9Am.png": "1caa8c492da279e8d01f676fe9232ccad016321699d519b3834692052cc5f5ee",
|
||||
"admin-web/apps/mobile-h5/dist/assets/cell-group-B1PakqJq.js": "7a648b566b9c00c1c8d1b6d2ca9737ca237e521f0e25065cedf86e82fa2471d8",
|
||||
"admin-web/apps/mobile-h5/dist/assets/ConversationsView-CLYafisP.js": "c145f55146ff5373b293e2922b021f55c6851fa34db65fdacb64139fb88c4fa8",
|
||||
"admin-web/apps/mobile-h5/dist/assets/ConversationsView-CytDMSuM.css": "1f646a0178eb9e3f837ac62b5521ec60c0e7d5b4b086b9076c4bf2a7448f98ae",
|
||||
"admin-web/apps/mobile-h5/dist/assets/DevicesView-Cgb9V9Z0.js": "ddb9c705e5cc4822e9166686a7eab319c772540981134f30a9f850fc85ac8692",
|
||||
"admin-web/apps/mobile-h5/dist/assets/DevicesView-CHTvxQxK.css": "40fd5adaea4d4aed376a57c75ebec4544d50f424863704b00ce80b98f7881ddd",
|
||||
"admin-web/apps/mobile-h5/dist/assets/field-CRX3eS7h.js": "393394f3545f3224264be9d1eb87c72b6ce474651b3794b3839f43bfbd69aa86",
|
||||
"admin-web/apps/mobile-h5/dist/assets/format-DEXJ_MrY.js": "d6a7fc2e067a2adcf92b498812422755d5ac8f00acfcf07fd935201eee35c056",
|
||||
"admin-web/apps/mobile-h5/dist/assets/index-D80qzV0-.css": "c0c7a7706d3d4a4ca2baa88f31aa2fd5c6080b4f2e539b4812a99d51f2de9fd0",
|
||||
"admin-web/apps/mobile-h5/dist/assets/index-Gkjcdjlo.js": "63a10401ab035b495ba24c55f9b1bd7ef54c76c6d6bc549f4b0eda62dbd915ac",
|
||||
"admin-web/apps/mobile-h5/dist/assets/LoginView-C25eERA6.css": "b561a20e6d76366db7634b028098ed9f848f665b95f0ffe538f02abce87e8991",
|
||||
"admin-web/apps/mobile-h5/dist/assets/LoginView-nW7aCAJ5.js": "ded80bbda052a9da5f7beaab6af536258b706f2bf0688331fa8bccd9e23355c6",
|
||||
"admin-web/apps/mobile-h5/dist/assets/MeView-B-MK2tgf.css": "a3bd246d2658ee50d4cac9afa1d051c33e8676be3155260256e7106a9c5dd136",
|
||||
"admin-web/apps/mobile-h5/dist/assets/MeView-uJ3uOzy0.js": "711a690039d1fe0d648c285da7bd1ef5b62afe8249d10ad7e76208318fc3094d",
|
||||
"admin-web/apps/mobile-h5/dist/assets/ShellView-CQXCC9xU.js": "8a2afb226d06ece5a929c2c85c4c73bbf68977b4ccde960aa7f6a5ae4614af62",
|
||||
"admin-web/apps/mobile-h5/dist/assets/ShellView-D354hIv5.css": "513a381d7ecfe8c24ca22166d658c8604df9d9478a8765ffcef7beb031917dcd",
|
||||
"admin-web/apps/mobile-h5/dist/assets/use-placeholder-CcVnlsb4.js": "168066192a95a203466245545388b756dfd035c466b007e65ccadc1c94f3fd80",
|
||||
"admin-web/apps/mobile-h5/dist/icons/apple-touch-icon.png": "3167d1d07f22a44ea393b377e5181918ae4890c137de37fe91e2f3780b6ce70e",
|
||||
"admin-web/apps/mobile-h5/dist/icons/favicon-64.png": "7c9d031dcd296a45a79d960481c34eb150dd33e4a2bace6f28385be01c1a675e",
|
||||
"admin-web/apps/mobile-h5/dist/icons/icon-192.png": "9637a4d3e4cbb385ed0b35069d6bb3522b90d1b8aaec439cfdf5ec1264040b5a",
|
||||
"admin-web/apps/mobile-h5/dist/icons/icon-512.png": "803ed98fb41fc724cb5319f45409d5e9725465f6f37cb6312e6b79170f852974",
|
||||
"admin-web/apps/mobile-h5/dist/icons/icon-maskable-512.png": "88b6cecdb691f9e2f4179fd00eae937a5f6863cd61d34aadda1e6ac45e6217a2",
|
||||
"admin-web/apps/mobile-h5/dist/index.html": "d11023af89db5c20bde0c4eaaa35fd9ad192a85353165c0a675e139ae5d94f13",
|
||||
"admin-web/apps/mobile-h5/dist/manifest.webmanifest": "ac64783b6865e3f68fdc735d5d66cad0c13ffc8b6be6ae5fbebc0e2eac5a61fd",
|
||||
"admin-web/apps/mobile-h5/dist/sw.js": "d908e9a6ec5c75ffcca8f9f6d97ec683b005fa211975f89beee372849df44a69",
|
||||
"wechat_rpa/remote_api.py": "843f0a814a0de4f8078f7f9f23a4ac92388d7556c9fe378987f67eda46c55c5b"
|
||||
},
|
||||
"must_not_exist": []
|
||||
}
|
||||
@@ -0,0 +1,723 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""手机远程控制台、桌面命令通道与服务端黑名单。
|
||||
|
||||
重点是边界:手机令牌和桌面令牌互不通用,没有 ZYT 权限的人拦得住,只能动自己
|
||||
名下的电脑,命令只会被目标电脑领走,手机登录不会把值班电脑顶下线。
|
||||
"""
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
from pathlib import Path
|
||||
from unittest import TestCase, main, mock
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
import admin_api
|
||||
import admin_backend as ab
|
||||
import remote_store
|
||||
import zyt_auth
|
||||
|
||||
STRONG = "Zhen@2026Ops"
|
||||
LAN = {"X-Real-IP": "192.168.1.20"}
|
||||
CONTROL = remote_store.PERM_REMOTE_CONTROL
|
||||
ALL = remote_store.PERM_REMOTE_ALL
|
||||
ADD = remote_store.PERM_BLACKLIST_ADD
|
||||
REMOVE = remote_store.PERM_BLACKLIST_REMOVE
|
||||
|
||||
|
||||
class FakeZyt:
|
||||
"""ZYT 的替身:账号密码、终端 9 令牌、/adminapi/desktop/session。"""
|
||||
|
||||
def __init__(self):
|
||||
self.users = {
|
||||
"kefu1": {"id": 101, "password": "pw-kefu1", "name": "客服一", "root": False,
|
||||
"permissions": [CONTROL, ADD]},
|
||||
"kefu2": {"id": 202, "password": "pw-kefu2", "name": "客服二", "root": False,
|
||||
"permissions": []},
|
||||
"boss": {"id": 303, "password": "pw-boss", "name": "主管", "root": False,
|
||||
"permissions": [ALL, ADD, REMOVE]},
|
||||
}
|
||||
self.tokens: dict[str, str] = {}
|
||||
self.login_calls = 0
|
||||
self.login_delay = 0.0
|
||||
self.login_error: Exception | None = None
|
||||
self.identity_error: Exception | None = None
|
||||
self.logged_out: list[str] = []
|
||||
self._count_lock = threading.Lock()
|
||||
|
||||
def login(self, account, password):
|
||||
with self._count_lock:
|
||||
self.login_calls += 1
|
||||
number = self.login_calls
|
||||
if self.login_delay:
|
||||
time.sleep(self.login_delay)
|
||||
if self.login_error is not None:
|
||||
raise self.login_error
|
||||
user = self.users.get(account)
|
||||
if user is None:
|
||||
raise zyt_auth.ZytLoginError("账号或密码错误", kind="unknown_account")
|
||||
if user["password"] != password:
|
||||
raise zyt_auth.ZytLoginError("账号或密码错误", kind="credentials")
|
||||
if user.get("is_paw") == 0:
|
||||
raise zyt_auth.ZytLoginError("该账号仍在使用初始密码", kind="password_change_required")
|
||||
token = f"zyt-mobile-{account}-{number}"
|
||||
self.tokens[token] = account
|
||||
return token
|
||||
|
||||
def identity_for(self, account, terminal):
|
||||
user = self.users[account]
|
||||
return {
|
||||
"user_id": f"admin:{user['id']}", "sn": account, "nickname": user["name"],
|
||||
"mobile": "", "avatar": "", "terminal": terminal, "status": "active",
|
||||
"root": user["root"], "role_ids": [2], "permissions": list(user["permissions"]),
|
||||
"permissions_known": True,
|
||||
}
|
||||
|
||||
def identity(self, token):
|
||||
if self.identity_error is not None:
|
||||
raise self.identity_error
|
||||
account = self.tokens.get(token)
|
||||
if account is None:
|
||||
raise zyt_auth.ZytLoginError("登录已失效,请重新登录", kind="rejected")
|
||||
return self.identity_for(account, 9)
|
||||
|
||||
def logout(self, token):
|
||||
self.logged_out.append(token)
|
||||
self.tokens.pop(token, None)
|
||||
|
||||
|
||||
class _Base(TestCase):
|
||||
budget = "0"
|
||||
|
||||
def setUp(self):
|
||||
self.root = Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.root, True)
|
||||
self.db = ab.Database(self.root / "t.db")
|
||||
self.db.initialize("Admin@123456")
|
||||
uid = self.db.authenticate("admin", "Admin@123456")["id"]
|
||||
self.db.change_password(uid, "Admin@123456", STRONG, "1.1.1.1")
|
||||
self.zyt = FakeZyt()
|
||||
env = mock.patch.dict(os.environ, {
|
||||
"MOBILE_LOGIN_UPSTREAM_FAILURE_BUDGET": self.budget, "MOBILE_REQUIRE_HTTPS": "auto",
|
||||
})
|
||||
env.start()
|
||||
self.addCleanup(env.stop)
|
||||
self.client = TestClient(admin_api.create_app(
|
||||
self.root / "t.db", zyt_token_verifier=self._verify_desktop, zyt_mobile_auth=self.zyt,
|
||||
))
|
||||
self.addCleanup(self.client.close)
|
||||
|
||||
def _verify_desktop(self, token):
|
||||
account = token.removeprefix("zyt-desktop-")
|
||||
if account not in self.zyt.users:
|
||||
raise zyt_auth.ZytAuthError("登录已失效")
|
||||
return self.zyt.identity_for(account, 7)
|
||||
|
||||
# ── 登录助手 ──
|
||||
def desktop_login(self, account="kefu1", device_id="dev-0000000000000001"):
|
||||
response = self.client.post(
|
||||
"/api/v2/desktop/auth/exchange",
|
||||
headers={"Authorization": f"Bearer zyt-desktop-{account}"},
|
||||
json={"device_id": device_id, "device_name": f"PC-{account}", "app_version": "1.5.0",
|
||||
"interactive_login": True},
|
||||
)
|
||||
self.assertEqual(response.status_code, 200, response.text)
|
||||
return {"Authorization": f"Bearer {response.json()['access_token']}"}, response.json()["account"]
|
||||
|
||||
def mobile_login(self, account="kefu1", password=None, headers=None, expect=200):
|
||||
response = self.client.post(
|
||||
"/api/v2/mobile/auth/login",
|
||||
headers=headers if headers is not None else LAN,
|
||||
json={"account": account, "password": password or self.zyt.users[account]["password"]},
|
||||
)
|
||||
self.assertEqual(response.status_code, expect, response.text)
|
||||
if expect != 200:
|
||||
return response
|
||||
return {"Authorization": f"Bearer {response.json()['access_token']}"}
|
||||
|
||||
def admin_login(self):
|
||||
response = self.client.post("/api/v2/auth/login", json={"username": "admin", "password": STRONG})
|
||||
self.assertEqual(response.status_code, 200, response.text)
|
||||
return {"Authorization": f"Bearer {response.json()['access_token']}"}
|
||||
|
||||
def poll(self, desktop, *, status=None, wait=0, blacklist_version=None):
|
||||
body = {"wait": wait, "status": status if status is not None else {
|
||||
"listening": False, "state": "stopped", "transport": "visual", "wecom_connected": True,
|
||||
"pending_count": 2, "app_version": "1.5.0", "capabilities": ["commands_v1", "blacklist_sync_v1"],
|
||||
}}
|
||||
if blacklist_version is not None:
|
||||
body["blacklist_version"] = blacklist_version
|
||||
response = self.client.post("/api/v2/desktop/commands/poll", headers=desktop, json=body)
|
||||
self.assertEqual(response.status_code, 200, response.text)
|
||||
return response.json()
|
||||
|
||||
def detail(self, response):
|
||||
return response.json()["detail"]
|
||||
|
||||
|
||||
class MobileAuthTest(_Base):
|
||||
def test_mobile_login_does_not_kick_the_desktop_and_tokens_are_not_interchangeable(self):
|
||||
desktop, _account = self.desktop_login()
|
||||
mobile = self.mobile_login()
|
||||
self.assertEqual(self.client.get("/api/v2/desktop/me", headers=desktop).status_code, 200)
|
||||
me = self.client.get("/api/v2/mobile/me", headers=mobile)
|
||||
self.assertEqual(me.status_code, 200, me.text)
|
||||
self.assertEqual(me.json()["account"]["nickname"], "客服一")
|
||||
self.assertTrue(me.json()["permissions"]["control"])
|
||||
self.assertFalse(me.json()["permissions"]["blacklist_remove"])
|
||||
self.assertEqual(self.client.get("/api/v2/desktop/me", headers=mobile).status_code, 401)
|
||||
self.assertEqual(self.client.get("/api/v2/mobile/me", headers=desktop).status_code, 401)
|
||||
self.assertEqual(
|
||||
self.client.post("/api/v2/desktop/commands/poll", headers=mobile, json={"wait": 0}).status_code,
|
||||
401,
|
||||
)
|
||||
|
||||
def test_mobile_and_desktop_land_on_the_same_account(self):
|
||||
_desktop, desktop_account = self.desktop_login()
|
||||
mobile = self.mobile_login()
|
||||
self.assertEqual(
|
||||
self.client.get("/api/v2/mobile/me", headers=mobile).json()["account"]["id"],
|
||||
desktop_account["id"],
|
||||
)
|
||||
|
||||
def test_wrong_password_is_generic_and_limited_per_account(self):
|
||||
for _ in range(5):
|
||||
response = self.mobile_login(password="wrong", expect=401)
|
||||
self.assertEqual(self.detail(response)["code"], "invalid_credentials")
|
||||
self.assertEqual(self.detail(response)["message"], "账号或密码错误")
|
||||
calls = self.zyt.login_calls
|
||||
blocked = self.mobile_login(expect=429)
|
||||
self.assertEqual(self.detail(blocked)["code"], "rate_limited")
|
||||
self.assertEqual(self.zyt.login_calls, calls, "被限流的尝试不能再发到 ZYT")
|
||||
# 其他账号不受影响
|
||||
self.mobile_login("kefu2")
|
||||
|
||||
def test_public_plain_http_login_is_refused(self):
|
||||
public = {"X-Real-IP": "114.114.114.114"}
|
||||
response = self.mobile_login(headers=public, expect=403)
|
||||
self.assertEqual(self.detail(response)["code"], "https_required")
|
||||
self.assertEqual(self.zyt.login_calls, 0)
|
||||
self.mobile_login(headers={**public, "X-Forwarded-Proto": "https"})
|
||||
# 伪造 X-Forwarded-For 不能冒充内网
|
||||
spoofed = {"X-Real-IP": "114.114.114.114", "X-Forwarded-For": "10.0.0.8"}
|
||||
self.assertEqual(self.detail(self.mobile_login(headers=spoofed, expect=403))["code"], "https_required")
|
||||
# 代理漏配 X-Real-IP 时不放行明文登录(对端不是本机回环)
|
||||
self.assertEqual(self.detail(self.mobile_login(headers={}, expect=403))["code"], "https_required")
|
||||
|
||||
def test_plain_http_login_is_allowed_by_default(self):
|
||||
with mock.patch.dict(os.environ):
|
||||
os.environ.pop("MOBILE_REQUIRE_HTTPS")
|
||||
self.mobile_login(headers={"X-Real-IP": "114.114.114.114"})
|
||||
self.mobile_login("kefu2", headers={})
|
||||
self.assertEqual(self.zyt.login_calls, 2)
|
||||
|
||||
def test_zyt_lockout_is_remembered_and_not_retried(self):
|
||||
self.zyt.login_error = zyt_auth.ZytLoginError(
|
||||
"密码连续5次输入错误,请30分钟后重试", kind="locked", retry_after=1800)
|
||||
response = self.mobile_login(expect=429)
|
||||
self.assertEqual(self.detail(response)["code"], "zyt_locked")
|
||||
self.zyt.login_error = None
|
||||
calls = self.zyt.login_calls
|
||||
again = self.mobile_login("kefu2", expect=429)
|
||||
self.assertEqual(self.detail(again)["code"], "zyt_locked")
|
||||
self.assertEqual(self.zyt.login_calls, calls)
|
||||
|
||||
def test_unsupported_terminal_and_outage_are_reported_clearly(self):
|
||||
self.zyt.login_error = zyt_auth.ZytLoginError("升级", kind="terminal_unsupported")
|
||||
self.assertEqual(self.detail(self.mobile_login(expect=503))["code"], "terminal_unsupported")
|
||||
self.zyt.login_error = zyt_auth.ZytLoginError("超时", kind="unavailable")
|
||||
self.assertEqual(self.detail(self.mobile_login(expect=502))["code"], "zyt_unavailable")
|
||||
|
||||
def test_logout_revokes_the_session_and_the_zyt_token(self):
|
||||
mobile = self.mobile_login()
|
||||
self.assertEqual(self.client.post("/api/v2/mobile/auth/logout", headers=mobile).status_code, 200)
|
||||
self.assertEqual(self.client.get("/api/v2/mobile/me", headers=mobile).status_code, 401)
|
||||
self.assertEqual(len(self.zyt.logged_out), 1)
|
||||
|
||||
def test_disabled_account_and_admin_revoke_end_mobile_sessions(self):
|
||||
_desktop, account = self.desktop_login()
|
||||
mobile = self.mobile_login()
|
||||
admin = self.admin_login()
|
||||
listing = self.client.get("/api/v2/desktop-accounts", headers=admin).json()["accounts"]
|
||||
self.assertEqual(listing[0]["mobile_session_count"], 1)
|
||||
revoke = self.client.post(f"/api/v2/desktop-accounts/{account['id']}/revoke-devices", headers=admin)
|
||||
self.assertEqual(revoke.status_code, 200, revoke.text)
|
||||
self.assertEqual(self.client.get("/api/v2/mobile/me", headers=mobile).status_code, 401)
|
||||
|
||||
mobile = self.mobile_login()
|
||||
disabled = self.client.put(
|
||||
f"/api/v2/desktop-accounts/{account['id']}", headers=admin, json={"status": "disabled"})
|
||||
self.assertEqual(disabled.status_code, 200, disabled.text)
|
||||
self.assertEqual(self.client.get("/api/v2/mobile/me", headers=mobile).status_code, 401)
|
||||
self.assertEqual(self.detail(self.mobile_login(expect=403))["code"], "account_disabled")
|
||||
|
||||
def test_identity_is_rechecked_and_follows_zyt(self):
|
||||
mobile = self.mobile_login()
|
||||
self.zyt.users["kefu1"]["permissions"] = [CONTROL, ADD, REMOVE]
|
||||
with self.db.connect() as db:
|
||||
db.execute("UPDATE mobile_sessions SET identity_checked_at=0")
|
||||
db.commit()
|
||||
me = self.client.get("/api/v2/mobile/me", headers=mobile).json()
|
||||
self.assertTrue(me["permissions"]["blacklist_remove"])
|
||||
|
||||
# ZYT 暂时不可用:不下线,沿用上次的权限
|
||||
self.zyt.identity_error = zyt_auth.ZytLoginError("超时", kind="unavailable")
|
||||
with self.db.connect() as db:
|
||||
db.execute("UPDATE mobile_sessions SET identity_checked_at=0")
|
||||
db.commit()
|
||||
self.assertEqual(self.client.get("/api/v2/mobile/me", headers=mobile).status_code, 200)
|
||||
|
||||
# ZYT 会话真的失效:手机端下线
|
||||
self.zyt.identity_error = None
|
||||
self.zyt.tokens.clear()
|
||||
with self.db.connect() as db:
|
||||
db.execute("UPDATE mobile_sessions SET identity_checked_at=0")
|
||||
db.commit()
|
||||
self.assertEqual(self.client.get("/api/v2/mobile/me", headers=mobile).status_code, 401)
|
||||
|
||||
|
||||
class UpstreamBudgetTest(_Base):
|
||||
budget = "2"
|
||||
|
||||
def test_password_failures_across_accounts_pause_mobile_login(self):
|
||||
self.mobile_login("kefu1", password="bad", expect=401)
|
||||
self.mobile_login("kefu2", password="bad", expect=401)
|
||||
response = self.mobile_login("boss", expect=429)
|
||||
self.assertEqual(self.detail(response)["code"], "upstream_budget")
|
||||
self.assertEqual(self.zyt.login_calls, 2)
|
||||
|
||||
def test_unknown_accounts_do_not_spend_the_zyt_budget(self):
|
||||
# ZYT 不给"账号不存在"计数,随手乱填的账号名不应该把全体手机登录停掉。
|
||||
for name in ("nobody-1", "nobody-2", "nobody-3"):
|
||||
response = self.mobile_login(name, password="x", expect=401)
|
||||
self.assertEqual(self.detail(response)["message"], "账号或密码错误")
|
||||
self.mobile_login("kefu1")
|
||||
|
||||
def test_a_successful_login_resets_the_budget_like_zyt_does(self):
|
||||
self.mobile_login("kefu1", password="bad", expect=401)
|
||||
self.mobile_login("kefu1")
|
||||
self.mobile_login("kefu2", password="bad", expect=401)
|
||||
self.mobile_login("boss")
|
||||
self.mobile_login("kefu2", password="bad", expect=401)
|
||||
self.mobile_login("kefu2", password="bad", expect=401)
|
||||
self.assertEqual(self.detail(self.mobile_login("boss", expect=429))["code"], "upstream_budget")
|
||||
|
||||
|
||||
class ConcurrentLoginTest(_Base):
|
||||
budget = "4"
|
||||
|
||||
def test_a_parallel_burst_cannot_outrun_the_limits(self):
|
||||
"""并发的错误密码不能一起穿过限流打到 ZYT(ZYT 按出口 IP 5 次就锁)。"""
|
||||
self.zyt.login_delay = 0.4
|
||||
results = []
|
||||
|
||||
def attempt(index):
|
||||
response = self.client.post(
|
||||
"/api/v2/mobile/auth/login", headers={"X-Real-IP": f"192.168.1.{index + 10}"},
|
||||
json={"account": "kefu1" if index % 2 else "kefu2", "password": "wrong"})
|
||||
results.append(response.status_code)
|
||||
|
||||
workers = [threading.Thread(target=attempt, args=(index,)) for index in range(12)]
|
||||
for worker in workers:
|
||||
worker.start()
|
||||
for worker in workers:
|
||||
worker.join(30)
|
||||
self.assertLessEqual(self.zyt.login_calls, 4)
|
||||
self.assertEqual(results.count(401), self.zyt.login_calls)
|
||||
self.assertEqual(results.count(429), 12 - self.zyt.login_calls)
|
||||
|
||||
def test_initial_password_accounts_are_refused_without_counting_as_failures(self):
|
||||
self.zyt.users["kefu1"]["is_paw"] = 0
|
||||
for _ in range(6):
|
||||
response = self.mobile_login("kefu1", expect=403)
|
||||
self.assertEqual(self.detail(response)["code"], "password_change_required")
|
||||
self.assertEqual(self.zyt.login_calls, 6)
|
||||
|
||||
|
||||
class RemoteControlTest(_Base):
|
||||
def test_device_list_shows_live_status_from_the_command_channel(self):
|
||||
desktop, _account = self.desktop_login()
|
||||
mobile = self.mobile_login()
|
||||
self.poll(desktop, status={
|
||||
"listening": True, "state": "running", "transport": "protocol", "wecom_connected": True,
|
||||
"pending_count": 3, "app_version": "1.5.0", "capabilities": ["commands_v1", "blacklist_sync_v1"],
|
||||
})
|
||||
items = self.client.get("/api/v2/mobile/desktops", headers=mobile).json()["items"]
|
||||
self.assertEqual(len(items), 1)
|
||||
device = items[0]
|
||||
self.assertTrue(device["online"])
|
||||
self.assertTrue(device["remote_capable"])
|
||||
self.assertTrue(device["status"]["listening"])
|
||||
self.assertEqual(device["status"]["state_label"], "监听中")
|
||||
self.assertEqual(device["status"]["transport_label"], "协议通道")
|
||||
self.assertEqual(device["status"]["pending_count"], 3)
|
||||
|
||||
def test_command_round_trip(self):
|
||||
desktop, _account = self.desktop_login()
|
||||
mobile = self.mobile_login()
|
||||
self.poll(desktop)
|
||||
created = self.client.post(
|
||||
"/api/v2/mobile/desktops/dev-0000000000000001/commands", headers=mobile,
|
||||
json={"type": "start_listening"})
|
||||
self.assertEqual(created.status_code, 200, created.text)
|
||||
command = created.json()["command"]
|
||||
self.assertEqual(command["status"], "pending")
|
||||
|
||||
delivered = self.poll(desktop)["commands"]
|
||||
self.assertEqual([item["id"] for item in delivered], [command["id"]])
|
||||
self.assertEqual(delivered[0]["type"], "start_listening")
|
||||
state = self.client.get(f"/api/v2/mobile/commands/{command['id']}", headers=mobile).json()["command"]
|
||||
self.assertEqual(state["status"], "delivered")
|
||||
|
||||
ack = self.client.post(
|
||||
f"/api/v2/desktop/commands/{command['id']}/ack", headers=desktop,
|
||||
json={"ok": True, "result": {"listening": True}, "status": {
|
||||
"listening": True, "state": "running", "transport": "visual", "wecom_connected": True,
|
||||
"pending_count": 0, "app_version": "1.5.0", "capabilities": ["commands_v1"]}})
|
||||
self.assertEqual(ack.status_code, 200, ack.text)
|
||||
state = self.client.get(f"/api/v2/mobile/commands/{command['id']}", headers=mobile).json()["command"]
|
||||
self.assertEqual(state["status"], "succeeded")
|
||||
self.assertTrue(state["result"]["listening"])
|
||||
# 回执里带的状态立刻反映到手机端,不用等下一次长轮询
|
||||
device = self.client.get("/api/v2/mobile/desktops", headers=mobile).json()["items"][0]
|
||||
self.assertTrue(device["status"]["listening"])
|
||||
self.assertEqual(device["last_command"]["status"], "succeeded")
|
||||
self.assertEqual(self.poll(desktop)["commands"], [])
|
||||
actions = [row["action"] for row in self.db.audit_entries(50)]
|
||||
self.assertIn("remote.command.create", actions)
|
||||
self.assertIn("remote.command.ack", actions)
|
||||
|
||||
def test_unacknowledged_commands_are_redelivered_and_stale_ones_superseded(self):
|
||||
desktop, _account = self.desktop_login()
|
||||
mobile = self.mobile_login()
|
||||
self.poll(desktop)
|
||||
url = "/api/v2/mobile/desktops/dev-0000000000000001/commands"
|
||||
first = self.client.post(url, headers=mobile, json={"type": "stop_listening"}).json()["command"]
|
||||
second = self.client.post(url, headers=mobile, json={"type": "start_listening"}).json()["command"]
|
||||
state = self.client.get(f"/api/v2/mobile/commands/{first['id']}", headers=mobile).json()["command"]
|
||||
self.assertEqual(state["status"], "superseded")
|
||||
self.assertEqual([item["id"] for item in self.poll(desktop)["commands"]], [second["id"]])
|
||||
# 没回执就再给一次,由电脑按 id 去重
|
||||
self.assertEqual([item["id"] for item in self.poll(desktop)["commands"]], [second["id"]])
|
||||
|
||||
def test_commands_expire_after_ten_minutes(self):
|
||||
desktop, _account = self.desktop_login()
|
||||
mobile = self.mobile_login()
|
||||
self.poll(desktop)
|
||||
command = self.client.post(
|
||||
"/api/v2/mobile/desktops/dev-0000000000000001/commands", headers=mobile,
|
||||
json={"type": "stop_listening"}).json()["command"]
|
||||
self.assertGreaterEqual(command["expires_at"] - time.time(), 590)
|
||||
with self.db.connect() as db:
|
||||
db.execute("UPDATE desktop_commands SET expires_at=?", (int(time.time()) - 1,))
|
||||
db.commit()
|
||||
self.assertEqual(self.poll(desktop)["commands"], [])
|
||||
state = self.client.get(f"/api/v2/mobile/commands/{command['id']}", headers=mobile).json()["command"]
|
||||
self.assertEqual(state["status"], "expired")
|
||||
late = self.client.post(f"/api/v2/desktop/commands/{command['id']}/ack", headers=desktop,
|
||||
json={"ok": True})
|
||||
self.assertEqual(late.json()["command"]["status"], "expired")
|
||||
|
||||
def test_long_poll_wakes_up_as_soon_as_a_command_arrives(self):
|
||||
desktop, _account = self.desktop_login()
|
||||
mobile = self.mobile_login()
|
||||
self.poll(desktop)
|
||||
result = {}
|
||||
|
||||
def wait_for_command():
|
||||
started = time.monotonic()
|
||||
result["body"] = self.poll(desktop, wait=20)
|
||||
result["elapsed"] = time.monotonic() - started
|
||||
|
||||
worker = threading.Thread(target=wait_for_command)
|
||||
worker.start()
|
||||
time.sleep(0.6)
|
||||
created = self.client.post(
|
||||
"/api/v2/mobile/desktops/dev-0000000000000001/commands", headers=mobile,
|
||||
json={"type": "stop_listening"})
|
||||
self.assertEqual(created.status_code, 200, created.text)
|
||||
worker.join(15)
|
||||
self.assertFalse(worker.is_alive())
|
||||
self.assertEqual(len(result["body"]["commands"]), 1)
|
||||
self.assertLess(result["elapsed"], 5)
|
||||
|
||||
def test_offline_and_outdated_clients_cannot_be_commanded(self):
|
||||
desktop, _account = self.desktop_login()
|
||||
mobile = self.mobile_login()
|
||||
url = "/api/v2/mobile/desktops/dev-0000000000000001/commands"
|
||||
# 旧版客户端:有心跳,没有命令通道
|
||||
self.client.get("/api/v2/desktop/me", headers=desktop)
|
||||
device = self.client.get("/api/v2/mobile/desktops", headers=mobile).json()["items"][0]
|
||||
self.assertTrue(device["online"])
|
||||
self.assertFalse(device["remote_capable"])
|
||||
response = self.client.post(url, headers=mobile, json={"type": "start_listening"})
|
||||
self.assertEqual(response.status_code, 409)
|
||||
self.assertEqual(self.detail(response)["code"], "client_outdated")
|
||||
# 程序没开:心跳停了
|
||||
self.poll(desktop)
|
||||
with self.db.connect() as db:
|
||||
db.execute("UPDATE desktop_devices SET last_seen_at='2020-01-01T00:00:00+08:00'")
|
||||
db.commit()
|
||||
response = self.client.post(url, headers=mobile, json={"type": "start_listening"})
|
||||
self.assertEqual(response.status_code, 409)
|
||||
self.assertEqual(self.detail(response)["code"], "device_offline")
|
||||
self.assertEqual(
|
||||
self.client.post(url.replace("0001", "9999"), headers=mobile,
|
||||
json={"type": "start_listening"}).status_code, 404)
|
||||
|
||||
def test_permissions_and_account_scope(self):
|
||||
desktop1, account1 = self.desktop_login("kefu1", "dev-0000000000000001")
|
||||
self.poll(desktop1)
|
||||
_desktop2, account2 = self.desktop_login("kefu2", "dev-0000000000000002")
|
||||
kefu2 = self.mobile_login("kefu2")
|
||||
# 没有 remote/control:能看不能控
|
||||
self.assertEqual(self.client.get("/api/v2/mobile/desktops", headers=kefu2).status_code, 200)
|
||||
response = self.client.post(
|
||||
"/api/v2/mobile/desktops/dev-0000000000000002/commands", headers=kefu2,
|
||||
json={"type": "start_listening"})
|
||||
self.assertEqual(response.status_code, 403)
|
||||
# 不能看别人的电脑,也不能冒用别人的设备 id
|
||||
self.assertEqual(self.client.get(
|
||||
f"/api/v2/mobile/desktops?account_id={account1['id']}", headers=kefu2).status_code, 403)
|
||||
kefu1 = self.mobile_login("kefu1")
|
||||
self.assertEqual(self.client.post(
|
||||
"/api/v2/mobile/desktops/dev-0000000000000002/commands", headers=kefu1,
|
||||
json={"type": "start_listening"}).status_code, 404)
|
||||
self.assertEqual(self.client.get("/api/v2/mobile/accounts", headers=kefu1).status_code, 403)
|
||||
# 主管(remote/all):能看全部、能控别人
|
||||
boss = self.mobile_login("boss")
|
||||
accounts = self.client.get("/api/v2/mobile/accounts", headers=boss).json()["items"]
|
||||
self.assertEqual({item["id"] for item in accounts} >= {account1["id"], account2["id"]}, True)
|
||||
created = self.client.post(
|
||||
f"/api/v2/mobile/desktops/dev-0000000000000001/commands?account_id={account1['id']}",
|
||||
headers=boss, json={"type": "stop_listening"})
|
||||
self.assertEqual(created.status_code, 200, created.text)
|
||||
self.assertEqual(self.poll(desktop1)["commands"][0]["created_by"], "主管(手机)")
|
||||
# 未知指令
|
||||
self.assertEqual(self.client.post(
|
||||
"/api/v2/mobile/desktops/dev-0000000000000001/commands", headers=kefu1,
|
||||
json={"type": "shutdown"}).status_code, 400)
|
||||
|
||||
|
||||
class BlacklistTest(_Base):
|
||||
def seed_archive(self, desktop):
|
||||
payload = {
|
||||
"source_account": {"external_account_id": "1688850000000001", "display_name": "客服一企微"},
|
||||
"source_table": "message_table",
|
||||
"checkpoint": {"rowid": 3},
|
||||
"messages": [
|
||||
{
|
||||
"source_message_id": f"m-{index}", "server_id": f"s-{index}",
|
||||
"conversation": {"external_id": external_id, "name": name},
|
||||
"sender": {"external_id": "7881000000000001", "display_name": name,
|
||||
"identity_type": "wecom_local_uid", "scope_id": "1688850000000001"},
|
||||
"sent_at": 1_758_000_000_000 + index * 1000,
|
||||
"message_type": "text", "direction": "inbound", "content": "正文不应出现在手机端",
|
||||
}
|
||||
for index, (external_id, name) in enumerate(
|
||||
(("S:1688850000000001_7881000000000001", "客户张三"),
|
||||
("R:10696052955016166", "售后群"),
|
||||
("S:1688850000000001_7881000000000002", "客户李四")), start=1)
|
||||
],
|
||||
}
|
||||
response = self.client.post("/api/v2/archive/desktop/imports/messages", headers=desktop, json=payload)
|
||||
self.assertEqual(response.status_code, 200, response.text)
|
||||
|
||||
def test_conversations_carry_blacklist_state_and_never_message_bodies(self):
|
||||
desktop, _account = self.desktop_login()
|
||||
self.seed_archive(desktop)
|
||||
mobile = self.mobile_login()
|
||||
listing = self.client.get("/api/v2/mobile/conversations", headers=mobile)
|
||||
self.assertEqual(listing.status_code, 200, listing.text)
|
||||
items = listing.json()["items"]
|
||||
self.assertEqual([item["name"] for item in items], ["客户李四", "售后群", "客户张三"])
|
||||
self.assertNotIn("正文不应出现在手机端", listing.text)
|
||||
self.assertEqual(items[1]["type_label"], "群聊")
|
||||
|
||||
target = items[0]
|
||||
added = self.client.put(
|
||||
f"/api/v2/mobile/blacklist/{target['account']}/{target['conversation']}",
|
||||
headers=mobile, json={"reason": "客户投诉"})
|
||||
self.assertEqual(added.status_code, 200, added.text)
|
||||
self.assertEqual(added.json()["entry"]["name"], "客户李四")
|
||||
self.assertEqual(added.json()["entry"]["account_name"], "客服一企微")
|
||||
self.assertEqual(added.json()["entry"]["created_by"], "客服一(手机)")
|
||||
|
||||
searched = self.client.get("/api/v2/mobile/conversations?q=李四", headers=mobile).json()
|
||||
self.assertEqual(len(searched["items"]), 1)
|
||||
self.assertTrue(searched["items"][0]["blocked"])
|
||||
self.assertEqual(searched["items"][0]["blacklist"]["reason"], "客户投诉")
|
||||
blocked = self.client.get("/api/v2/mobile/conversations?scope=blocked", headers=mobile).json()
|
||||
self.assertEqual(blocked["blocked_total"], 1)
|
||||
self.assertEqual(blocked["items"][0]["conversation"], target["conversation"])
|
||||
|
||||
# 其他客服看不到这个租户的会话
|
||||
other = self.mobile_login("kefu2")
|
||||
self.assertEqual(self.client.get("/api/v2/mobile/conversations", headers=other).json()["items"], [])
|
||||
|
||||
def test_blacklist_permissions(self):
|
||||
_desktop, account = self.desktop_login()
|
||||
kefu2 = self.mobile_login("kefu2")
|
||||
path = "/api/v2/mobile/blacklist/1688850000000001/S:1688850000000001_7881000000000009"
|
||||
self.assertEqual(self.client.put(path, headers=kefu2, json={}).status_code, 403)
|
||||
kefu1 = self.mobile_login("kefu1")
|
||||
first = self.client.put(path, headers=kefu1, json={"name": "客户王五"})
|
||||
self.assertEqual(first.status_code, 200, first.text)
|
||||
removed = self.client.delete(path, headers=kefu1)
|
||||
self.assertEqual(removed.status_code, 403)
|
||||
self.assertIn(REMOVE, self.detail(removed)["message"])
|
||||
boss = self.mobile_login("boss")
|
||||
by_boss = self.client.delete(f"{path}?account_id={account['id']}", headers=boss)
|
||||
self.assertEqual(by_boss.status_code, 200, by_boss.text)
|
||||
self.assertGreater(by_boss.json()["version"], first.json()["version"])
|
||||
self.assertEqual(self.client.delete(f"{path}?account_id={account['id']}", headers=boss).status_code, 404)
|
||||
actions = [row["action"] for row in self.db.audit_entries(50)]
|
||||
self.assertIn("blacklist.add", actions)
|
||||
self.assertIn("blacklist.remove", actions)
|
||||
|
||||
def test_desktop_sync_is_the_write_through_path_and_polls_see_the_version(self):
|
||||
desktop, _account = self.desktop_login()
|
||||
mobile = self.mobile_login()
|
||||
start = self.poll(desktop)["blacklist_version"]
|
||||
synced = self.client.post("/api/v2/desktop/blacklist/sync", headers=desktop, json={"add": [
|
||||
{"account": "1688850000000001", "conversation": "S:legacy-1", "name": "老客户", "account_name": "企微"},
|
||||
{"account": "1688850000000001", "conversation": "S:legacy-1", "name": "老客户"},
|
||||
{"account": "", "conversation": "S:bad"},
|
||||
]})
|
||||
self.assertEqual(synced.status_code, 200, synced.text)
|
||||
body = synced.json()
|
||||
self.assertEqual([item["conversation"] for item in body["items"]], ["S:legacy-1"])
|
||||
self.assertEqual(len(body["rejected"]), 1)
|
||||
self.assertGreater(body["version"], start)
|
||||
# 版本不一致的长轮询立即返回,让电脑去同步
|
||||
began = time.monotonic()
|
||||
self.assertEqual(self.poll(desktop, wait=10, blacklist_version=start)["blacklist_version"], body["version"])
|
||||
self.assertLess(time.monotonic() - began, 3)
|
||||
pulled = self.client.get("/api/v2/desktop/blacklist", headers=desktop).json()
|
||||
self.assertEqual(pulled["version"], body["version"])
|
||||
# 桌面端没有 remove 权限:移出被拒;主管有
|
||||
denied = self.client.delete("/api/v2/desktop/blacklist/1688850000000001/S:legacy-1", headers=desktop)
|
||||
self.assertEqual(denied.status_code, 403)
|
||||
self.zyt.users["kefu1"]["permissions"].append(REMOVE)
|
||||
desktop, _account = self.desktop_login()
|
||||
allowed = self.client.delete("/api/v2/desktop/blacklist/1688850000000001/S:legacy-1", headers=desktop)
|
||||
self.assertEqual(allowed.status_code, 200, allowed.text)
|
||||
self.assertEqual(self.client.get("/api/v2/desktop/blacklist", headers=desktop).json()["items"], [])
|
||||
# 手机加的黑名单,电脑下一次长轮询就能看到版本变化
|
||||
version = self.poll(desktop)["blacklist_version"]
|
||||
self.client.put("/api/v2/mobile/blacklist/1688850000000001/S:from-phone", headers=mobile, json={})
|
||||
self.assertGreater(self.poll(desktop, blacklist_version=version)["blacklist_version"], version)
|
||||
|
||||
def test_re_adding_a_removed_entry_reactivates_it(self):
|
||||
desktop, account = self.desktop_login()
|
||||
boss = self.mobile_login("boss")
|
||||
path = f"/api/v2/mobile/blacklist/1688850000000001/S:again?account_id={account['id']}"
|
||||
self.assertEqual(self.client.put(path, headers=boss, json={"reason": "一"}).status_code, 200)
|
||||
self.assertEqual(self.client.delete(path, headers=boss).status_code, 200)
|
||||
again = self.client.put(path, headers=boss, json={"reason": "二"})
|
||||
self.assertEqual(again.status_code, 200)
|
||||
items = self.client.get("/api/v2/desktop/blacklist", headers=desktop).json()["items"]
|
||||
self.assertEqual([(item["conversation"], item["reason"]) for item in items], [("S:again", "二")])
|
||||
|
||||
|
||||
class MobileHostingTest(_Base):
|
||||
def test_mobile_bundle_is_served_under_m_with_safe_fallback(self):
|
||||
dist = self.root / "mobile-dist"
|
||||
(dist / "assets").mkdir(parents=True)
|
||||
(dist / "index.html").write_text("<html>mobile</html>", encoding="utf-8")
|
||||
(dist / "assets" / "app-abc123.js").write_text("console.log(1)", encoding="utf-8")
|
||||
(self.root / "secret.txt").write_text("secret", encoding="utf-8")
|
||||
with mock.patch.object(admin_api, "_mobile_dist", return_value=dist):
|
||||
client = TestClient(admin_api.create_app(self.root / "t.db", zyt_mobile_auth=self.zyt))
|
||||
with client:
|
||||
entry = client.get("/m/")
|
||||
self.assertIn("mobile", entry.text)
|
||||
self.assertEqual(entry.headers["cache-control"], "no-cache")
|
||||
self.assertEqual(entry.headers["x-frame-options"], "DENY")
|
||||
self.assertIn("frame-ancestors 'none'", entry.headers["content-security-policy"])
|
||||
asset = client.get("/m/assets/app-abc123.js")
|
||||
self.assertEqual(asset.status_code, 200)
|
||||
self.assertIn("immutable", asset.headers["cache-control"])
|
||||
# 发版后旧页面请求旧 chunk:必须是 404,不能回 index.html
|
||||
self.assertEqual(client.get("/m/assets/app-old999.js").status_code, 404)
|
||||
self.assertIn("mobile", client.get("/m/devices/abc").text)
|
||||
self.assertNotIn("secret", client.get("/m/..%2Fsecret.txt").text)
|
||||
self.assertEqual(client.get("/m", follow_redirects=False).status_code, 308)
|
||||
self.assertEqual(client.get("/api/v2/health").status_code, 200)
|
||||
|
||||
|
||||
class ZytMobileClientTest(TestCase):
|
||||
def response(self, payload):
|
||||
return io.BytesIO(json.dumps(payload).encode("utf-8"))
|
||||
|
||||
def login(self, payload):
|
||||
with mock.patch.object(zyt_auth.urllib.request, "urlopen", return_value=self.response(payload)) as opened:
|
||||
token = zyt_auth.login_admin("kefu1", "secret", api_url="https://zyt.example.test")
|
||||
request = opened.call_args.args[0]
|
||||
self.assertEqual(json.loads(request.data)["terminal"], 9)
|
||||
return token
|
||||
|
||||
def failure(self, message):
|
||||
with self.assertRaises(zyt_auth.ZytLoginError) as caught:
|
||||
self.login({"code": 0, "msg": message, "data": []})
|
||||
return caught.exception
|
||||
|
||||
def test_login_returns_the_terminal_9_token(self):
|
||||
self.assertEqual(self.login({"code": 1, "data": {"token": "abc"}}), "abc")
|
||||
|
||||
def test_initial_password_accounts_are_refused_and_logged_out(self):
|
||||
with mock.patch.object(zyt_auth.urllib.request, "urlopen", side_effect=[
|
||||
self.response({"code": 1, "data": {"token": "fresh", "is_paw": 0}}),
|
||||
self.response({"code": 1, "msg": ""}),
|
||||
]) as opened:
|
||||
with self.assertRaises(zyt_auth.ZytLoginError) as caught:
|
||||
zyt_auth.login_admin("kefu1", "secret", api_url="https://zyt.example.test")
|
||||
self.assertEqual(caught.exception.kind, "password_change_required")
|
||||
logout = opened.call_args_list[1].args[0]
|
||||
self.assertTrue(logout.full_url.endswith("/adminapi/login/logout"))
|
||||
self.assertEqual(logout.headers.get("Token"), "fresh")
|
||||
|
||||
def test_login_failures_are_classified(self):
|
||||
self.assertEqual(self.failure("密码错误").kind, "credentials")
|
||||
self.assertEqual(self.failure("账号不存在").kind, "unknown_account")
|
||||
self.assertEqual(str(self.failure("账号不存在")), "账号或密码错误")
|
||||
locked = self.failure("密码连续5次输入错误,请30分钟后重试")
|
||||
self.assertEqual((locked.kind, locked.retry_after), ("locked", 1800))
|
||||
self.assertEqual(self.failure("terminal必须在 1,2,7 范围内").kind, "terminal_unsupported")
|
||||
self.assertEqual(self.failure("账号已禁用").kind, "disabled")
|
||||
|
||||
def test_transport_errors_are_unavailable(self):
|
||||
with mock.patch.object(zyt_auth.urllib.request, "urlopen",
|
||||
side_effect=urllib.error.URLError("timed out")):
|
||||
with self.assertRaises(zyt_auth.ZytLoginError) as caught:
|
||||
zyt_auth.login_admin("kefu1", "secret", api_url="https://zyt.example.test")
|
||||
self.assertEqual(caught.exception.kind, "unavailable")
|
||||
|
||||
def test_session_must_be_the_mobile_terminal(self):
|
||||
def verify(data):
|
||||
with mock.patch.object(zyt_auth.urllib.request, "urlopen", return_value=self.response(data)):
|
||||
return zyt_auth.verify_admin_session("tok", api_url="https://zyt.example.test")
|
||||
|
||||
identity = verify({"code": 1, "data": {"user_id": "admin:9", "terminal": 9, "status": "active",
|
||||
"root": 0, "permissions": [CONTROL]}})
|
||||
self.assertEqual(identity["permissions"], [CONTROL])
|
||||
for other in (7, 8): # 桌面端令牌、ZYT 的 AI 浏览器令牌都不能当手机令牌用
|
||||
with self.assertRaises(zyt_auth.ZytLoginError) as caught:
|
||||
verify({"code": 1, "data": {"user_id": "admin:9", "terminal": other, "status": "active"}})
|
||||
self.assertEqual(caught.exception.kind, "terminal_unsupported")
|
||||
with self.assertRaises(zyt_auth.ZytLoginError) as caught:
|
||||
verify({"code": 0, "msg": "当前登录令牌不属于企业微信客服桌面端"})
|
||||
self.assertEqual(caught.exception.kind, "terminal_unsupported")
|
||||
with self.assertRaises(zyt_auth.ZytLoginError) as caught:
|
||||
verify({"code": 0, "msg": "登录已失效,请重新登录"})
|
||||
self.assertEqual(caught.exception.kind, "rejected")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,100 @@
|
||||
"""跨服务器桌面认证:只在路由缺失时兼容,拒绝结果不能降级。"""
|
||||
import io
|
||||
import json
|
||||
import unittest
|
||||
import urllib.error
|
||||
from unittest import mock
|
||||
|
||||
import zyt_auth
|
||||
|
||||
|
||||
class DesktopVerificationRegressionTest(unittest.TestCase):
|
||||
def response(self, payload):
|
||||
return io.BytesIO(json.dumps(payload).encode("utf-8"))
|
||||
|
||||
def session(self, **updates):
|
||||
data = {"user_id": "admin:9", "terminal": 7, "status": "active",
|
||||
"root": False, "role_ids": [2], "permissions": ["tcm.diagnosis/lists"]}
|
||||
data.update(updates)
|
||||
return {"code": 1, "data": data}
|
||||
|
||||
def verify(self):
|
||||
return zyt_auth.verify_desktop_token("test-token", api_url="https://identity.example.test")
|
||||
|
||||
def missing(self, status=404):
|
||||
return urllib.error.HTTPError("https://identity.example.test", status, "test", None, None)
|
||||
|
||||
def test_success_never_requests_ip_bound_web_profile(self):
|
||||
with mock.patch.object(zyt_auth.urllib.request, "urlopen", side_effect=[
|
||||
self.response(self.session(root=True, permissions=["*"])),
|
||||
self.response({"code": -1, "msg": "ip地址发生变化,请重新登录"}),
|
||||
]) as opened:
|
||||
identity = self.verify()
|
||||
self.assertEqual(opened.call_count, 1)
|
||||
self.assertTrue(identity["root"])
|
||||
self.assertEqual(identity["role_ids"], [2])
|
||||
self.assertEqual(identity["permissions"], ["*"])
|
||||
self.assertTrue(identity["permissions_known"])
|
||||
|
||||
def test_missing_permissions_do_not_trigger_profile_request(self):
|
||||
payload = self.session()
|
||||
del payload["data"]["permissions"]
|
||||
with mock.patch.object(zyt_auth.urllib.request, "urlopen", return_value=self.response(payload)) as opened:
|
||||
identity = self.verify()
|
||||
self.assertEqual(opened.call_count, 1)
|
||||
self.assertEqual(identity["permissions"], [])
|
||||
self.assertFalse(identity["permissions_known"])
|
||||
|
||||
def test_empty_permissions_are_known(self):
|
||||
with mock.patch.object(zyt_auth.urllib.request, "urlopen", return_value=self.response(self.session(permissions=[]))):
|
||||
identity = self.verify()
|
||||
self.assertTrue(identity["permissions_known"])
|
||||
self.assertEqual(identity["permissions"], [])
|
||||
|
||||
def test_only_missing_routes_allow_legacy_verification(self):
|
||||
for status in (404, 405):
|
||||
with self.subTest(status=status), mock.patch.object(zyt_auth.urllib.request, "urlopen", side_effect=[
|
||||
self.missing(status), self.response({"code": 1, "data": {
|
||||
"user": {"id": 9, "disable": 0, "role_ids": [2]}, "permissions": []}}),
|
||||
]) as opened:
|
||||
identity = self.verify()
|
||||
self.assertEqual(identity["user_id"], "admin:9")
|
||||
self.assertEqual(opened.call_count, 2)
|
||||
|
||||
def test_http_rejections_do_not_fall_back(self):
|
||||
for status in (401, 403, 500, 502):
|
||||
with self.subTest(status=status), mock.patch.object(zyt_auth.urllib.request, "urlopen", side_effect=self.missing(status)) as opened:
|
||||
with self.assertRaises(zyt_auth.ZytAuthError):
|
||||
self.verify()
|
||||
self.assertEqual(opened.call_count, 1)
|
||||
|
||||
def test_invalid_identity_cannot_be_accepted_through_web_fallback(self):
|
||||
failures = [{"code": -1, "msg": "登录已失效"}, {"code": "bad"}, [],
|
||||
{"code": 1, "data": []}, self.session(user_id=""),
|
||||
self.session(terminal=1), self.session(terminal="bad"),
|
||||
self.session(status="disabled")]
|
||||
for payload in failures:
|
||||
with self.subTest(payload=payload), mock.patch.object(zyt_auth.urllib.request, "urlopen", side_effect=[
|
||||
self.response(payload), self.response({"code": 1, "data": {"user": {"id": 9}}}),
|
||||
]) as opened:
|
||||
with self.assertRaises(zyt_auth.ZytAuthError):
|
||||
self.verify()
|
||||
self.assertEqual(opened.call_count, 1)
|
||||
|
||||
def test_bad_json_and_network_failure_do_not_fall_back(self):
|
||||
for result in (io.BytesIO(b"<html>error</html>"), urllib.error.URLError("offline")):
|
||||
with self.subTest(result=result), mock.patch.object(zyt_auth.urllib.request, "urlopen", side_effect=[result]) as opened:
|
||||
with self.assertRaises(zyt_auth.ZytAuthError):
|
||||
self.verify()
|
||||
self.assertEqual(opened.call_count, 1)
|
||||
|
||||
def test_legacy_ip_error_identifies_missing_server_deployment(self):
|
||||
with mock.patch.object(zyt_auth.urllib.request, "urlopen", side_effect=[
|
||||
self.missing(), self.response({"code": -1, "msg": "ip地址发生变化,请重新登录"}),
|
||||
]):
|
||||
with self.assertRaisesRegex(zyt_auth.ZytAuthError, "/adminapi/desktop/session"):
|
||||
self.verify()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,723 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""手机远程控制台、桌面命令通道与服务端黑名单。
|
||||
|
||||
重点是边界:手机令牌和桌面令牌互不通用,没有 ZYT 权限的人拦得住,只能动自己
|
||||
名下的电脑,命令只会被目标电脑领走,手机登录不会把值班电脑顶下线。
|
||||
"""
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
from pathlib import Path
|
||||
from unittest import TestCase, main, mock
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
import admin_api
|
||||
import admin_backend as ab
|
||||
import remote_store
|
||||
import zyt_auth
|
||||
|
||||
STRONG = "Zhen@2026Ops"
|
||||
LAN = {"X-Real-IP": "192.168.1.20"}
|
||||
CONTROL = remote_store.PERM_REMOTE_CONTROL
|
||||
ALL = remote_store.PERM_REMOTE_ALL
|
||||
ADD = remote_store.PERM_BLACKLIST_ADD
|
||||
REMOVE = remote_store.PERM_BLACKLIST_REMOVE
|
||||
|
||||
|
||||
class FakeZyt:
|
||||
"""ZYT 的替身:账号密码、终端 9 令牌、/adminapi/desktop/session。"""
|
||||
|
||||
def __init__(self):
|
||||
self.users = {
|
||||
"kefu1": {"id": 101, "password": "pw-kefu1", "name": "客服一", "root": False,
|
||||
"permissions": [CONTROL, ADD]},
|
||||
"kefu2": {"id": 202, "password": "pw-kefu2", "name": "客服二", "root": False,
|
||||
"permissions": []},
|
||||
"boss": {"id": 303, "password": "pw-boss", "name": "主管", "root": False,
|
||||
"permissions": [ALL, ADD, REMOVE]},
|
||||
}
|
||||
self.tokens: dict[str, str] = {}
|
||||
self.login_calls = 0
|
||||
self.login_delay = 0.0
|
||||
self.login_error: Exception | None = None
|
||||
self.identity_error: Exception | None = None
|
||||
self.logged_out: list[str] = []
|
||||
self._count_lock = threading.Lock()
|
||||
|
||||
def login(self, account, password):
|
||||
with self._count_lock:
|
||||
self.login_calls += 1
|
||||
number = self.login_calls
|
||||
if self.login_delay:
|
||||
time.sleep(self.login_delay)
|
||||
if self.login_error is not None:
|
||||
raise self.login_error
|
||||
user = self.users.get(account)
|
||||
if user is None:
|
||||
raise zyt_auth.ZytLoginError("账号或密码错误", kind="unknown_account")
|
||||
if user["password"] != password:
|
||||
raise zyt_auth.ZytLoginError("账号或密码错误", kind="credentials")
|
||||
if user.get("is_paw") == 0:
|
||||
raise zyt_auth.ZytLoginError("该账号仍在使用初始密码", kind="password_change_required")
|
||||
token = f"zyt-mobile-{account}-{number}"
|
||||
self.tokens[token] = account
|
||||
return token
|
||||
|
||||
def identity_for(self, account, terminal):
|
||||
user = self.users[account]
|
||||
return {
|
||||
"user_id": f"admin:{user['id']}", "sn": account, "nickname": user["name"],
|
||||
"mobile": "", "avatar": "", "terminal": terminal, "status": "active",
|
||||
"root": user["root"], "role_ids": [2], "permissions": list(user["permissions"]),
|
||||
"permissions_known": True,
|
||||
}
|
||||
|
||||
def identity(self, token):
|
||||
if self.identity_error is not None:
|
||||
raise self.identity_error
|
||||
account = self.tokens.get(token)
|
||||
if account is None:
|
||||
raise zyt_auth.ZytLoginError("登录已失效,请重新登录", kind="rejected")
|
||||
return self.identity_for(account, 9)
|
||||
|
||||
def logout(self, token):
|
||||
self.logged_out.append(token)
|
||||
self.tokens.pop(token, None)
|
||||
|
||||
|
||||
class _Base(TestCase):
|
||||
budget = "0"
|
||||
|
||||
def setUp(self):
|
||||
self.root = Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.root, True)
|
||||
self.db = ab.Database(self.root / "t.db")
|
||||
self.db.initialize("Admin@123456")
|
||||
uid = self.db.authenticate("admin", "Admin@123456")["id"]
|
||||
self.db.change_password(uid, "Admin@123456", STRONG, "1.1.1.1")
|
||||
self.zyt = FakeZyt()
|
||||
env = mock.patch.dict(os.environ, {
|
||||
"MOBILE_LOGIN_UPSTREAM_FAILURE_BUDGET": self.budget, "MOBILE_REQUIRE_HTTPS": "auto",
|
||||
})
|
||||
env.start()
|
||||
self.addCleanup(env.stop)
|
||||
self.client = TestClient(admin_api.create_app(
|
||||
self.root / "t.db", zyt_token_verifier=self._verify_desktop, zyt_mobile_auth=self.zyt,
|
||||
))
|
||||
self.addCleanup(self.client.close)
|
||||
|
||||
def _verify_desktop(self, token):
|
||||
account = token.removeprefix("zyt-desktop-")
|
||||
if account not in self.zyt.users:
|
||||
raise zyt_auth.ZytAuthError("登录已失效")
|
||||
return self.zyt.identity_for(account, 7)
|
||||
|
||||
# ── 登录助手 ──
|
||||
def desktop_login(self, account="kefu1", device_id="dev-0000000000000001"):
|
||||
response = self.client.post(
|
||||
"/api/v2/desktop/auth/exchange",
|
||||
headers={"Authorization": f"Bearer zyt-desktop-{account}"},
|
||||
json={"device_id": device_id, "device_name": f"PC-{account}", "app_version": "1.5.0",
|
||||
"interactive_login": True},
|
||||
)
|
||||
self.assertEqual(response.status_code, 200, response.text)
|
||||
return {"Authorization": f"Bearer {response.json()['access_token']}"}, response.json()["account"]
|
||||
|
||||
def mobile_login(self, account="kefu1", password=None, headers=None, expect=200):
|
||||
response = self.client.post(
|
||||
"/api/v2/mobile/auth/login",
|
||||
headers=headers if headers is not None else LAN,
|
||||
json={"account": account, "password": password or self.zyt.users[account]["password"]},
|
||||
)
|
||||
self.assertEqual(response.status_code, expect, response.text)
|
||||
if expect != 200:
|
||||
return response
|
||||
return {"Authorization": f"Bearer {response.json()['access_token']}"}
|
||||
|
||||
def admin_login(self):
|
||||
response = self.client.post("/api/v2/auth/login", json={"username": "admin", "password": STRONG})
|
||||
self.assertEqual(response.status_code, 200, response.text)
|
||||
return {"Authorization": f"Bearer {response.json()['access_token']}"}
|
||||
|
||||
def poll(self, desktop, *, status=None, wait=0, blacklist_version=None):
|
||||
body = {"wait": wait, "status": status if status is not None else {
|
||||
"listening": False, "state": "stopped", "transport": "visual", "wecom_connected": True,
|
||||
"pending_count": 2, "app_version": "1.5.0", "capabilities": ["commands_v1", "blacklist_sync_v1"],
|
||||
}}
|
||||
if blacklist_version is not None:
|
||||
body["blacklist_version"] = blacklist_version
|
||||
response = self.client.post("/api/v2/desktop/commands/poll", headers=desktop, json=body)
|
||||
self.assertEqual(response.status_code, 200, response.text)
|
||||
return response.json()
|
||||
|
||||
def detail(self, response):
|
||||
return response.json()["detail"]
|
||||
|
||||
|
||||
class MobileAuthTest(_Base):
|
||||
def test_mobile_login_does_not_kick_the_desktop_and_tokens_are_not_interchangeable(self):
|
||||
desktop, _account = self.desktop_login()
|
||||
mobile = self.mobile_login()
|
||||
self.assertEqual(self.client.get("/api/v2/desktop/me", headers=desktop).status_code, 200)
|
||||
me = self.client.get("/api/v2/mobile/me", headers=mobile)
|
||||
self.assertEqual(me.status_code, 200, me.text)
|
||||
self.assertEqual(me.json()["account"]["nickname"], "客服一")
|
||||
self.assertTrue(me.json()["permissions"]["control"])
|
||||
self.assertFalse(me.json()["permissions"]["blacklist_remove"])
|
||||
self.assertEqual(self.client.get("/api/v2/desktop/me", headers=mobile).status_code, 401)
|
||||
self.assertEqual(self.client.get("/api/v2/mobile/me", headers=desktop).status_code, 401)
|
||||
self.assertEqual(
|
||||
self.client.post("/api/v2/desktop/commands/poll", headers=mobile, json={"wait": 0}).status_code,
|
||||
401,
|
||||
)
|
||||
|
||||
def test_mobile_and_desktop_land_on_the_same_account(self):
|
||||
_desktop, desktop_account = self.desktop_login()
|
||||
mobile = self.mobile_login()
|
||||
self.assertEqual(
|
||||
self.client.get("/api/v2/mobile/me", headers=mobile).json()["account"]["id"],
|
||||
desktop_account["id"],
|
||||
)
|
||||
|
||||
def test_wrong_password_is_generic_and_limited_per_account(self):
|
||||
for _ in range(5):
|
||||
response = self.mobile_login(password="wrong", expect=401)
|
||||
self.assertEqual(self.detail(response)["code"], "invalid_credentials")
|
||||
self.assertEqual(self.detail(response)["message"], "账号或密码错误")
|
||||
calls = self.zyt.login_calls
|
||||
blocked = self.mobile_login(expect=429)
|
||||
self.assertEqual(self.detail(blocked)["code"], "rate_limited")
|
||||
self.assertEqual(self.zyt.login_calls, calls, "被限流的尝试不能再发到 ZYT")
|
||||
# 其他账号不受影响
|
||||
self.mobile_login("kefu2")
|
||||
|
||||
def test_public_plain_http_login_is_refused(self):
|
||||
public = {"X-Real-IP": "114.114.114.114"}
|
||||
response = self.mobile_login(headers=public, expect=403)
|
||||
self.assertEqual(self.detail(response)["code"], "https_required")
|
||||
self.assertEqual(self.zyt.login_calls, 0)
|
||||
self.mobile_login(headers={**public, "X-Forwarded-Proto": "https"})
|
||||
# 伪造 X-Forwarded-For 不能冒充内网
|
||||
spoofed = {"X-Real-IP": "114.114.114.114", "X-Forwarded-For": "10.0.0.8"}
|
||||
self.assertEqual(self.detail(self.mobile_login(headers=spoofed, expect=403))["code"], "https_required")
|
||||
# 代理漏配 X-Real-IP 时不放行明文登录(对端不是本机回环)
|
||||
self.assertEqual(self.detail(self.mobile_login(headers={}, expect=403))["code"], "https_required")
|
||||
|
||||
def test_plain_http_login_is_allowed_by_default(self):
|
||||
with mock.patch.dict(os.environ):
|
||||
os.environ.pop("MOBILE_REQUIRE_HTTPS")
|
||||
self.mobile_login(headers={"X-Real-IP": "114.114.114.114"})
|
||||
self.mobile_login("kefu2", headers={})
|
||||
self.assertEqual(self.zyt.login_calls, 2)
|
||||
|
||||
def test_zyt_lockout_is_remembered_and_not_retried(self):
|
||||
self.zyt.login_error = zyt_auth.ZytLoginError(
|
||||
"密码连续5次输入错误,请30分钟后重试", kind="locked", retry_after=1800)
|
||||
response = self.mobile_login(expect=429)
|
||||
self.assertEqual(self.detail(response)["code"], "zyt_locked")
|
||||
self.zyt.login_error = None
|
||||
calls = self.zyt.login_calls
|
||||
again = self.mobile_login("kefu2", expect=429)
|
||||
self.assertEqual(self.detail(again)["code"], "zyt_locked")
|
||||
self.assertEqual(self.zyt.login_calls, calls)
|
||||
|
||||
def test_unsupported_terminal_and_outage_are_reported_clearly(self):
|
||||
self.zyt.login_error = zyt_auth.ZytLoginError("升级", kind="terminal_unsupported")
|
||||
self.assertEqual(self.detail(self.mobile_login(expect=503))["code"], "terminal_unsupported")
|
||||
self.zyt.login_error = zyt_auth.ZytLoginError("超时", kind="unavailable")
|
||||
self.assertEqual(self.detail(self.mobile_login(expect=502))["code"], "zyt_unavailable")
|
||||
|
||||
def test_logout_revokes_the_session_and_the_zyt_token(self):
|
||||
mobile = self.mobile_login()
|
||||
self.assertEqual(self.client.post("/api/v2/mobile/auth/logout", headers=mobile).status_code, 200)
|
||||
self.assertEqual(self.client.get("/api/v2/mobile/me", headers=mobile).status_code, 401)
|
||||
self.assertEqual(len(self.zyt.logged_out), 1)
|
||||
|
||||
def test_disabled_account_and_admin_revoke_end_mobile_sessions(self):
|
||||
_desktop, account = self.desktop_login()
|
||||
mobile = self.mobile_login()
|
||||
admin = self.admin_login()
|
||||
listing = self.client.get("/api/v2/desktop-accounts", headers=admin).json()["accounts"]
|
||||
self.assertEqual(listing[0]["mobile_session_count"], 1)
|
||||
revoke = self.client.post(f"/api/v2/desktop-accounts/{account['id']}/revoke-devices", headers=admin)
|
||||
self.assertEqual(revoke.status_code, 200, revoke.text)
|
||||
self.assertEqual(self.client.get("/api/v2/mobile/me", headers=mobile).status_code, 401)
|
||||
|
||||
mobile = self.mobile_login()
|
||||
disabled = self.client.put(
|
||||
f"/api/v2/desktop-accounts/{account['id']}", headers=admin, json={"status": "disabled"})
|
||||
self.assertEqual(disabled.status_code, 200, disabled.text)
|
||||
self.assertEqual(self.client.get("/api/v2/mobile/me", headers=mobile).status_code, 401)
|
||||
self.assertEqual(self.detail(self.mobile_login(expect=403))["code"], "account_disabled")
|
||||
|
||||
def test_identity_is_rechecked_and_follows_zyt(self):
|
||||
mobile = self.mobile_login()
|
||||
self.zyt.users["kefu1"]["permissions"] = [CONTROL, ADD, REMOVE]
|
||||
with self.db.connect() as db:
|
||||
db.execute("UPDATE mobile_sessions SET identity_checked_at=0")
|
||||
db.commit()
|
||||
me = self.client.get("/api/v2/mobile/me", headers=mobile).json()
|
||||
self.assertTrue(me["permissions"]["blacklist_remove"])
|
||||
|
||||
# ZYT 暂时不可用:不下线,沿用上次的权限
|
||||
self.zyt.identity_error = zyt_auth.ZytLoginError("超时", kind="unavailable")
|
||||
with self.db.connect() as db:
|
||||
db.execute("UPDATE mobile_sessions SET identity_checked_at=0")
|
||||
db.commit()
|
||||
self.assertEqual(self.client.get("/api/v2/mobile/me", headers=mobile).status_code, 200)
|
||||
|
||||
# ZYT 会话真的失效:手机端下线
|
||||
self.zyt.identity_error = None
|
||||
self.zyt.tokens.clear()
|
||||
with self.db.connect() as db:
|
||||
db.execute("UPDATE mobile_sessions SET identity_checked_at=0")
|
||||
db.commit()
|
||||
self.assertEqual(self.client.get("/api/v2/mobile/me", headers=mobile).status_code, 401)
|
||||
|
||||
|
||||
class UpstreamBudgetTest(_Base):
|
||||
budget = "2"
|
||||
|
||||
def test_password_failures_across_accounts_pause_mobile_login(self):
|
||||
self.mobile_login("kefu1", password="bad", expect=401)
|
||||
self.mobile_login("kefu2", password="bad", expect=401)
|
||||
response = self.mobile_login("boss", expect=429)
|
||||
self.assertEqual(self.detail(response)["code"], "upstream_budget")
|
||||
self.assertEqual(self.zyt.login_calls, 2)
|
||||
|
||||
def test_unknown_accounts_do_not_spend_the_zyt_budget(self):
|
||||
# ZYT 不给"账号不存在"计数,随手乱填的账号名不应该把全体手机登录停掉。
|
||||
for name in ("nobody-1", "nobody-2", "nobody-3"):
|
||||
response = self.mobile_login(name, password="x", expect=401)
|
||||
self.assertEqual(self.detail(response)["message"], "账号或密码错误")
|
||||
self.mobile_login("kefu1")
|
||||
|
||||
def test_a_successful_login_resets_the_budget_like_zyt_does(self):
|
||||
self.mobile_login("kefu1", password="bad", expect=401)
|
||||
self.mobile_login("kefu1")
|
||||
self.mobile_login("kefu2", password="bad", expect=401)
|
||||
self.mobile_login("boss")
|
||||
self.mobile_login("kefu2", password="bad", expect=401)
|
||||
self.mobile_login("kefu2", password="bad", expect=401)
|
||||
self.assertEqual(self.detail(self.mobile_login("boss", expect=429))["code"], "upstream_budget")
|
||||
|
||||
|
||||
class ConcurrentLoginTest(_Base):
|
||||
budget = "4"
|
||||
|
||||
def test_a_parallel_burst_cannot_outrun_the_limits(self):
|
||||
"""并发的错误密码不能一起穿过限流打到 ZYT(ZYT 按出口 IP 5 次就锁)。"""
|
||||
self.zyt.login_delay = 0.4
|
||||
results = []
|
||||
|
||||
def attempt(index):
|
||||
response = self.client.post(
|
||||
"/api/v2/mobile/auth/login", headers={"X-Real-IP": f"192.168.1.{index + 10}"},
|
||||
json={"account": "kefu1" if index % 2 else "kefu2", "password": "wrong"})
|
||||
results.append(response.status_code)
|
||||
|
||||
workers = [threading.Thread(target=attempt, args=(index,)) for index in range(12)]
|
||||
for worker in workers:
|
||||
worker.start()
|
||||
for worker in workers:
|
||||
worker.join(30)
|
||||
self.assertLessEqual(self.zyt.login_calls, 4)
|
||||
self.assertEqual(results.count(401), self.zyt.login_calls)
|
||||
self.assertEqual(results.count(429), 12 - self.zyt.login_calls)
|
||||
|
||||
def test_initial_password_accounts_are_refused_without_counting_as_failures(self):
|
||||
self.zyt.users["kefu1"]["is_paw"] = 0
|
||||
for _ in range(6):
|
||||
response = self.mobile_login("kefu1", expect=403)
|
||||
self.assertEqual(self.detail(response)["code"], "password_change_required")
|
||||
self.assertEqual(self.zyt.login_calls, 6)
|
||||
|
||||
|
||||
class RemoteControlTest(_Base):
|
||||
def test_device_list_shows_live_status_from_the_command_channel(self):
|
||||
desktop, _account = self.desktop_login()
|
||||
mobile = self.mobile_login()
|
||||
self.poll(desktop, status={
|
||||
"listening": True, "state": "running", "transport": "protocol", "wecom_connected": True,
|
||||
"pending_count": 3, "app_version": "1.5.0", "capabilities": ["commands_v1", "blacklist_sync_v1"],
|
||||
})
|
||||
items = self.client.get("/api/v2/mobile/desktops", headers=mobile).json()["items"]
|
||||
self.assertEqual(len(items), 1)
|
||||
device = items[0]
|
||||
self.assertTrue(device["online"])
|
||||
self.assertTrue(device["remote_capable"])
|
||||
self.assertTrue(device["status"]["listening"])
|
||||
self.assertEqual(device["status"]["state_label"], "监听中")
|
||||
self.assertEqual(device["status"]["transport_label"], "协议通道")
|
||||
self.assertEqual(device["status"]["pending_count"], 3)
|
||||
|
||||
def test_command_round_trip(self):
|
||||
desktop, _account = self.desktop_login()
|
||||
mobile = self.mobile_login()
|
||||
self.poll(desktop)
|
||||
created = self.client.post(
|
||||
"/api/v2/mobile/desktops/dev-0000000000000001/commands", headers=mobile,
|
||||
json={"type": "start_listening"})
|
||||
self.assertEqual(created.status_code, 200, created.text)
|
||||
command = created.json()["command"]
|
||||
self.assertEqual(command["status"], "pending")
|
||||
|
||||
delivered = self.poll(desktop)["commands"]
|
||||
self.assertEqual([item["id"] for item in delivered], [command["id"]])
|
||||
self.assertEqual(delivered[0]["type"], "start_listening")
|
||||
state = self.client.get(f"/api/v2/mobile/commands/{command['id']}", headers=mobile).json()["command"]
|
||||
self.assertEqual(state["status"], "delivered")
|
||||
|
||||
ack = self.client.post(
|
||||
f"/api/v2/desktop/commands/{command['id']}/ack", headers=desktop,
|
||||
json={"ok": True, "result": {"listening": True}, "status": {
|
||||
"listening": True, "state": "running", "transport": "visual", "wecom_connected": True,
|
||||
"pending_count": 0, "app_version": "1.5.0", "capabilities": ["commands_v1"]}})
|
||||
self.assertEqual(ack.status_code, 200, ack.text)
|
||||
state = self.client.get(f"/api/v2/mobile/commands/{command['id']}", headers=mobile).json()["command"]
|
||||
self.assertEqual(state["status"], "succeeded")
|
||||
self.assertTrue(state["result"]["listening"])
|
||||
# 回执里带的状态立刻反映到手机端,不用等下一次长轮询
|
||||
device = self.client.get("/api/v2/mobile/desktops", headers=mobile).json()["items"][0]
|
||||
self.assertTrue(device["status"]["listening"])
|
||||
self.assertEqual(device["last_command"]["status"], "succeeded")
|
||||
self.assertEqual(self.poll(desktop)["commands"], [])
|
||||
actions = [row["action"] for row in self.db.audit_entries(50)]
|
||||
self.assertIn("remote.command.create", actions)
|
||||
self.assertIn("remote.command.ack", actions)
|
||||
|
||||
def test_unacknowledged_commands_are_redelivered_and_stale_ones_superseded(self):
|
||||
desktop, _account = self.desktop_login()
|
||||
mobile = self.mobile_login()
|
||||
self.poll(desktop)
|
||||
url = "/api/v2/mobile/desktops/dev-0000000000000001/commands"
|
||||
first = self.client.post(url, headers=mobile, json={"type": "stop_listening"}).json()["command"]
|
||||
second = self.client.post(url, headers=mobile, json={"type": "start_listening"}).json()["command"]
|
||||
state = self.client.get(f"/api/v2/mobile/commands/{first['id']}", headers=mobile).json()["command"]
|
||||
self.assertEqual(state["status"], "superseded")
|
||||
self.assertEqual([item["id"] for item in self.poll(desktop)["commands"]], [second["id"]])
|
||||
# 没回执就再给一次,由电脑按 id 去重
|
||||
self.assertEqual([item["id"] for item in self.poll(desktop)["commands"]], [second["id"]])
|
||||
|
||||
def test_commands_expire_after_ten_minutes(self):
|
||||
desktop, _account = self.desktop_login()
|
||||
mobile = self.mobile_login()
|
||||
self.poll(desktop)
|
||||
command = self.client.post(
|
||||
"/api/v2/mobile/desktops/dev-0000000000000001/commands", headers=mobile,
|
||||
json={"type": "stop_listening"}).json()["command"]
|
||||
self.assertGreaterEqual(command["expires_at"] - time.time(), 590)
|
||||
with self.db.connect() as db:
|
||||
db.execute("UPDATE desktop_commands SET expires_at=?", (int(time.time()) - 1,))
|
||||
db.commit()
|
||||
self.assertEqual(self.poll(desktop)["commands"], [])
|
||||
state = self.client.get(f"/api/v2/mobile/commands/{command['id']}", headers=mobile).json()["command"]
|
||||
self.assertEqual(state["status"], "expired")
|
||||
late = self.client.post(f"/api/v2/desktop/commands/{command['id']}/ack", headers=desktop,
|
||||
json={"ok": True})
|
||||
self.assertEqual(late.json()["command"]["status"], "expired")
|
||||
|
||||
def test_long_poll_wakes_up_as_soon_as_a_command_arrives(self):
|
||||
desktop, _account = self.desktop_login()
|
||||
mobile = self.mobile_login()
|
||||
self.poll(desktop)
|
||||
result = {}
|
||||
|
||||
def wait_for_command():
|
||||
started = time.monotonic()
|
||||
result["body"] = self.poll(desktop, wait=20)
|
||||
result["elapsed"] = time.monotonic() - started
|
||||
|
||||
worker = threading.Thread(target=wait_for_command)
|
||||
worker.start()
|
||||
time.sleep(0.6)
|
||||
created = self.client.post(
|
||||
"/api/v2/mobile/desktops/dev-0000000000000001/commands", headers=mobile,
|
||||
json={"type": "stop_listening"})
|
||||
self.assertEqual(created.status_code, 200, created.text)
|
||||
worker.join(15)
|
||||
self.assertFalse(worker.is_alive())
|
||||
self.assertEqual(len(result["body"]["commands"]), 1)
|
||||
self.assertLess(result["elapsed"], 5)
|
||||
|
||||
def test_offline_and_outdated_clients_cannot_be_commanded(self):
|
||||
desktop, _account = self.desktop_login()
|
||||
mobile = self.mobile_login()
|
||||
url = "/api/v2/mobile/desktops/dev-0000000000000001/commands"
|
||||
# 旧版客户端:有心跳,没有命令通道
|
||||
self.client.get("/api/v2/desktop/me", headers=desktop)
|
||||
device = self.client.get("/api/v2/mobile/desktops", headers=mobile).json()["items"][0]
|
||||
self.assertTrue(device["online"])
|
||||
self.assertFalse(device["remote_capable"])
|
||||
response = self.client.post(url, headers=mobile, json={"type": "start_listening"})
|
||||
self.assertEqual(response.status_code, 409)
|
||||
self.assertEqual(self.detail(response)["code"], "client_outdated")
|
||||
# 程序没开:心跳停了
|
||||
self.poll(desktop)
|
||||
with self.db.connect() as db:
|
||||
db.execute("UPDATE desktop_devices SET last_seen_at='2020-01-01T00:00:00+08:00'")
|
||||
db.commit()
|
||||
response = self.client.post(url, headers=mobile, json={"type": "start_listening"})
|
||||
self.assertEqual(response.status_code, 409)
|
||||
self.assertEqual(self.detail(response)["code"], "device_offline")
|
||||
self.assertEqual(
|
||||
self.client.post(url.replace("0001", "9999"), headers=mobile,
|
||||
json={"type": "start_listening"}).status_code, 404)
|
||||
|
||||
def test_permissions_and_account_scope(self):
|
||||
desktop1, account1 = self.desktop_login("kefu1", "dev-0000000000000001")
|
||||
self.poll(desktop1)
|
||||
_desktop2, account2 = self.desktop_login("kefu2", "dev-0000000000000002")
|
||||
kefu2 = self.mobile_login("kefu2")
|
||||
# 没有 remote/control:能看不能控
|
||||
self.assertEqual(self.client.get("/api/v2/mobile/desktops", headers=kefu2).status_code, 200)
|
||||
response = self.client.post(
|
||||
"/api/v2/mobile/desktops/dev-0000000000000002/commands", headers=kefu2,
|
||||
json={"type": "start_listening"})
|
||||
self.assertEqual(response.status_code, 403)
|
||||
# 不能看别人的电脑,也不能冒用别人的设备 id
|
||||
self.assertEqual(self.client.get(
|
||||
f"/api/v2/mobile/desktops?account_id={account1['id']}", headers=kefu2).status_code, 403)
|
||||
kefu1 = self.mobile_login("kefu1")
|
||||
self.assertEqual(self.client.post(
|
||||
"/api/v2/mobile/desktops/dev-0000000000000002/commands", headers=kefu1,
|
||||
json={"type": "start_listening"}).status_code, 404)
|
||||
self.assertEqual(self.client.get("/api/v2/mobile/accounts", headers=kefu1).status_code, 403)
|
||||
# 主管(remote/all):能看全部、能控别人
|
||||
boss = self.mobile_login("boss")
|
||||
accounts = self.client.get("/api/v2/mobile/accounts", headers=boss).json()["items"]
|
||||
self.assertEqual({item["id"] for item in accounts} >= {account1["id"], account2["id"]}, True)
|
||||
created = self.client.post(
|
||||
f"/api/v2/mobile/desktops/dev-0000000000000001/commands?account_id={account1['id']}",
|
||||
headers=boss, json={"type": "stop_listening"})
|
||||
self.assertEqual(created.status_code, 200, created.text)
|
||||
self.assertEqual(self.poll(desktop1)["commands"][0]["created_by"], "主管(手机)")
|
||||
# 未知指令
|
||||
self.assertEqual(self.client.post(
|
||||
"/api/v2/mobile/desktops/dev-0000000000000001/commands", headers=kefu1,
|
||||
json={"type": "shutdown"}).status_code, 400)
|
||||
|
||||
|
||||
class BlacklistTest(_Base):
|
||||
def seed_archive(self, desktop):
|
||||
payload = {
|
||||
"source_account": {"external_account_id": "1688850000000001", "display_name": "客服一企微"},
|
||||
"source_table": "message_table",
|
||||
"checkpoint": {"rowid": 3},
|
||||
"messages": [
|
||||
{
|
||||
"source_message_id": f"m-{index}", "server_id": f"s-{index}",
|
||||
"conversation": {"external_id": external_id, "name": name},
|
||||
"sender": {"external_id": "7881000000000001", "display_name": name,
|
||||
"identity_type": "wecom_local_uid", "scope_id": "1688850000000001"},
|
||||
"sent_at": 1_758_000_000_000 + index * 1000,
|
||||
"message_type": "text", "direction": "inbound", "content": "正文不应出现在手机端",
|
||||
}
|
||||
for index, (external_id, name) in enumerate(
|
||||
(("S:1688850000000001_7881000000000001", "客户张三"),
|
||||
("R:10696052955016166", "售后群"),
|
||||
("S:1688850000000001_7881000000000002", "客户李四")), start=1)
|
||||
],
|
||||
}
|
||||
response = self.client.post("/api/v2/archive/desktop/imports/messages", headers=desktop, json=payload)
|
||||
self.assertEqual(response.status_code, 200, response.text)
|
||||
|
||||
def test_conversations_carry_blacklist_state_and_never_message_bodies(self):
|
||||
desktop, _account = self.desktop_login()
|
||||
self.seed_archive(desktop)
|
||||
mobile = self.mobile_login()
|
||||
listing = self.client.get("/api/v2/mobile/conversations", headers=mobile)
|
||||
self.assertEqual(listing.status_code, 200, listing.text)
|
||||
items = listing.json()["items"]
|
||||
self.assertEqual([item["name"] for item in items], ["客户李四", "售后群", "客户张三"])
|
||||
self.assertNotIn("正文不应出现在手机端", listing.text)
|
||||
self.assertEqual(items[1]["type_label"], "群聊")
|
||||
|
||||
target = items[0]
|
||||
added = self.client.put(
|
||||
f"/api/v2/mobile/blacklist/{target['account']}/{target['conversation']}",
|
||||
headers=mobile, json={"reason": "客户投诉"})
|
||||
self.assertEqual(added.status_code, 200, added.text)
|
||||
self.assertEqual(added.json()["entry"]["name"], "客户李四")
|
||||
self.assertEqual(added.json()["entry"]["account_name"], "客服一企微")
|
||||
self.assertEqual(added.json()["entry"]["created_by"], "客服一(手机)")
|
||||
|
||||
searched = self.client.get("/api/v2/mobile/conversations?q=李四", headers=mobile).json()
|
||||
self.assertEqual(len(searched["items"]), 1)
|
||||
self.assertTrue(searched["items"][0]["blocked"])
|
||||
self.assertEqual(searched["items"][0]["blacklist"]["reason"], "客户投诉")
|
||||
blocked = self.client.get("/api/v2/mobile/conversations?scope=blocked", headers=mobile).json()
|
||||
self.assertEqual(blocked["blocked_total"], 1)
|
||||
self.assertEqual(blocked["items"][0]["conversation"], target["conversation"])
|
||||
|
||||
# 其他客服看不到这个租户的会话
|
||||
other = self.mobile_login("kefu2")
|
||||
self.assertEqual(self.client.get("/api/v2/mobile/conversations", headers=other).json()["items"], [])
|
||||
|
||||
def test_blacklist_permissions(self):
|
||||
_desktop, account = self.desktop_login()
|
||||
kefu2 = self.mobile_login("kefu2")
|
||||
path = "/api/v2/mobile/blacklist/1688850000000001/S:1688850000000001_7881000000000009"
|
||||
self.assertEqual(self.client.put(path, headers=kefu2, json={}).status_code, 403)
|
||||
kefu1 = self.mobile_login("kefu1")
|
||||
first = self.client.put(path, headers=kefu1, json={"name": "客户王五"})
|
||||
self.assertEqual(first.status_code, 200, first.text)
|
||||
removed = self.client.delete(path, headers=kefu1)
|
||||
self.assertEqual(removed.status_code, 403)
|
||||
self.assertIn(REMOVE, self.detail(removed)["message"])
|
||||
boss = self.mobile_login("boss")
|
||||
by_boss = self.client.delete(f"{path}?account_id={account['id']}", headers=boss)
|
||||
self.assertEqual(by_boss.status_code, 200, by_boss.text)
|
||||
self.assertGreater(by_boss.json()["version"], first.json()["version"])
|
||||
self.assertEqual(self.client.delete(f"{path}?account_id={account['id']}", headers=boss).status_code, 404)
|
||||
actions = [row["action"] for row in self.db.audit_entries(50)]
|
||||
self.assertIn("blacklist.add", actions)
|
||||
self.assertIn("blacklist.remove", actions)
|
||||
|
||||
def test_desktop_sync_is_the_write_through_path_and_polls_see_the_version(self):
|
||||
desktop, _account = self.desktop_login()
|
||||
mobile = self.mobile_login()
|
||||
start = self.poll(desktop)["blacklist_version"]
|
||||
synced = self.client.post("/api/v2/desktop/blacklist/sync", headers=desktop, json={"add": [
|
||||
{"account": "1688850000000001", "conversation": "S:legacy-1", "name": "老客户", "account_name": "企微"},
|
||||
{"account": "1688850000000001", "conversation": "S:legacy-1", "name": "老客户"},
|
||||
{"account": "", "conversation": "S:bad"},
|
||||
]})
|
||||
self.assertEqual(synced.status_code, 200, synced.text)
|
||||
body = synced.json()
|
||||
self.assertEqual([item["conversation"] for item in body["items"]], ["S:legacy-1"])
|
||||
self.assertEqual(len(body["rejected"]), 1)
|
||||
self.assertGreater(body["version"], start)
|
||||
# 版本不一致的长轮询立即返回,让电脑去同步
|
||||
began = time.monotonic()
|
||||
self.assertEqual(self.poll(desktop, wait=10, blacklist_version=start)["blacklist_version"], body["version"])
|
||||
self.assertLess(time.monotonic() - began, 3)
|
||||
pulled = self.client.get("/api/v2/desktop/blacklist", headers=desktop).json()
|
||||
self.assertEqual(pulled["version"], body["version"])
|
||||
# 桌面端没有 remove 权限:移出被拒;主管有
|
||||
denied = self.client.delete("/api/v2/desktop/blacklist/1688850000000001/S:legacy-1", headers=desktop)
|
||||
self.assertEqual(denied.status_code, 403)
|
||||
self.zyt.users["kefu1"]["permissions"].append(REMOVE)
|
||||
desktop, _account = self.desktop_login()
|
||||
allowed = self.client.delete("/api/v2/desktop/blacklist/1688850000000001/S:legacy-1", headers=desktop)
|
||||
self.assertEqual(allowed.status_code, 200, allowed.text)
|
||||
self.assertEqual(self.client.get("/api/v2/desktop/blacklist", headers=desktop).json()["items"], [])
|
||||
# 手机加的黑名单,电脑下一次长轮询就能看到版本变化
|
||||
version = self.poll(desktop)["blacklist_version"]
|
||||
self.client.put("/api/v2/mobile/blacklist/1688850000000001/S:from-phone", headers=mobile, json={})
|
||||
self.assertGreater(self.poll(desktop, blacklist_version=version)["blacklist_version"], version)
|
||||
|
||||
def test_re_adding_a_removed_entry_reactivates_it(self):
|
||||
desktop, account = self.desktop_login()
|
||||
boss = self.mobile_login("boss")
|
||||
path = f"/api/v2/mobile/blacklist/1688850000000001/S:again?account_id={account['id']}"
|
||||
self.assertEqual(self.client.put(path, headers=boss, json={"reason": "一"}).status_code, 200)
|
||||
self.assertEqual(self.client.delete(path, headers=boss).status_code, 200)
|
||||
again = self.client.put(path, headers=boss, json={"reason": "二"})
|
||||
self.assertEqual(again.status_code, 200)
|
||||
items = self.client.get("/api/v2/desktop/blacklist", headers=desktop).json()["items"]
|
||||
self.assertEqual([(item["conversation"], item["reason"]) for item in items], [("S:again", "二")])
|
||||
|
||||
|
||||
class MobileHostingTest(_Base):
|
||||
def test_mobile_bundle_is_served_under_m_with_safe_fallback(self):
|
||||
dist = self.root / "mobile-dist"
|
||||
(dist / "assets").mkdir(parents=True)
|
||||
(dist / "index.html").write_text("<html>mobile</html>", encoding="utf-8")
|
||||
(dist / "assets" / "app-abc123.js").write_text("console.log(1)", encoding="utf-8")
|
||||
(self.root / "secret.txt").write_text("secret", encoding="utf-8")
|
||||
with mock.patch.object(admin_api, "_mobile_dist", return_value=dist):
|
||||
client = TestClient(admin_api.create_app(self.root / "t.db", zyt_mobile_auth=self.zyt))
|
||||
with client:
|
||||
entry = client.get("/m/")
|
||||
self.assertIn("mobile", entry.text)
|
||||
self.assertEqual(entry.headers["cache-control"], "no-cache")
|
||||
self.assertEqual(entry.headers["x-frame-options"], "DENY")
|
||||
self.assertIn("frame-ancestors 'none'", entry.headers["content-security-policy"])
|
||||
asset = client.get("/m/assets/app-abc123.js")
|
||||
self.assertEqual(asset.status_code, 200)
|
||||
self.assertIn("immutable", asset.headers["cache-control"])
|
||||
# 发版后旧页面请求旧 chunk:必须是 404,不能回 index.html
|
||||
self.assertEqual(client.get("/m/assets/app-old999.js").status_code, 404)
|
||||
self.assertIn("mobile", client.get("/m/devices/abc").text)
|
||||
self.assertNotIn("secret", client.get("/m/..%2Fsecret.txt").text)
|
||||
self.assertEqual(client.get("/m", follow_redirects=False).status_code, 308)
|
||||
self.assertEqual(client.get("/api/v2/health").status_code, 200)
|
||||
|
||||
|
||||
class ZytMobileClientTest(TestCase):
|
||||
def response(self, payload):
|
||||
return io.BytesIO(json.dumps(payload).encode("utf-8"))
|
||||
|
||||
def login(self, payload):
|
||||
with mock.patch.object(zyt_auth.urllib.request, "urlopen", return_value=self.response(payload)) as opened:
|
||||
token = zyt_auth.login_admin("kefu1", "secret", api_url="https://zyt.example.test")
|
||||
request = opened.call_args.args[0]
|
||||
self.assertEqual(json.loads(request.data)["terminal"], 9)
|
||||
return token
|
||||
|
||||
def failure(self, message):
|
||||
with self.assertRaises(zyt_auth.ZytLoginError) as caught:
|
||||
self.login({"code": 0, "msg": message, "data": []})
|
||||
return caught.exception
|
||||
|
||||
def test_login_returns_the_terminal_9_token(self):
|
||||
self.assertEqual(self.login({"code": 1, "data": {"token": "abc"}}), "abc")
|
||||
|
||||
def test_initial_password_accounts_are_refused_and_logged_out(self):
|
||||
with mock.patch.object(zyt_auth.urllib.request, "urlopen", side_effect=[
|
||||
self.response({"code": 1, "data": {"token": "fresh", "is_paw": 0}}),
|
||||
self.response({"code": 1, "msg": ""}),
|
||||
]) as opened:
|
||||
with self.assertRaises(zyt_auth.ZytLoginError) as caught:
|
||||
zyt_auth.login_admin("kefu1", "secret", api_url="https://zyt.example.test")
|
||||
self.assertEqual(caught.exception.kind, "password_change_required")
|
||||
logout = opened.call_args_list[1].args[0]
|
||||
self.assertTrue(logout.full_url.endswith("/adminapi/login/logout"))
|
||||
self.assertEqual(logout.headers.get("Token"), "fresh")
|
||||
|
||||
def test_login_failures_are_classified(self):
|
||||
self.assertEqual(self.failure("密码错误").kind, "credentials")
|
||||
self.assertEqual(self.failure("账号不存在").kind, "unknown_account")
|
||||
self.assertEqual(str(self.failure("账号不存在")), "账号或密码错误")
|
||||
locked = self.failure("密码连续5次输入错误,请30分钟后重试")
|
||||
self.assertEqual((locked.kind, locked.retry_after), ("locked", 1800))
|
||||
self.assertEqual(self.failure("terminal必须在 1,2,7 范围内").kind, "terminal_unsupported")
|
||||
self.assertEqual(self.failure("账号已禁用").kind, "disabled")
|
||||
|
||||
def test_transport_errors_are_unavailable(self):
|
||||
with mock.patch.object(zyt_auth.urllib.request, "urlopen",
|
||||
side_effect=urllib.error.URLError("timed out")):
|
||||
with self.assertRaises(zyt_auth.ZytLoginError) as caught:
|
||||
zyt_auth.login_admin("kefu1", "secret", api_url="https://zyt.example.test")
|
||||
self.assertEqual(caught.exception.kind, "unavailable")
|
||||
|
||||
def test_session_must_be_the_mobile_terminal(self):
|
||||
def verify(data):
|
||||
with mock.patch.object(zyt_auth.urllib.request, "urlopen", return_value=self.response(data)):
|
||||
return zyt_auth.verify_admin_session("tok", api_url="https://zyt.example.test")
|
||||
|
||||
identity = verify({"code": 1, "data": {"user_id": "admin:9", "terminal": 9, "status": "active",
|
||||
"root": 0, "permissions": [CONTROL]}})
|
||||
self.assertEqual(identity["permissions"], [CONTROL])
|
||||
for other in (7, 8): # 桌面端令牌、ZYT 的 AI 浏览器令牌都不能当手机令牌用
|
||||
with self.assertRaises(zyt_auth.ZytLoginError) as caught:
|
||||
verify({"code": 1, "data": {"user_id": "admin:9", "terminal": other, "status": "active"}})
|
||||
self.assertEqual(caught.exception.kind, "terminal_unsupported")
|
||||
with self.assertRaises(zyt_auth.ZytLoginError) as caught:
|
||||
verify({"code": 0, "msg": "当前登录令牌不属于企业微信客服桌面端"})
|
||||
self.assertEqual(caught.exception.kind, "terminal_unsupported")
|
||||
with self.assertRaises(zyt_auth.ZytLoginError) as caught:
|
||||
verify({"code": 0, "msg": "登录已失效,请重新登录"})
|
||||
self.assertEqual(caught.exception.kind, "rejected")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,100 @@
|
||||
"""跨服务器桌面认证:只在路由缺失时兼容,拒绝结果不能降级。"""
|
||||
import io
|
||||
import json
|
||||
import unittest
|
||||
import urllib.error
|
||||
from unittest import mock
|
||||
|
||||
import zyt_auth
|
||||
|
||||
|
||||
class DesktopVerificationRegressionTest(unittest.TestCase):
|
||||
def response(self, payload):
|
||||
return io.BytesIO(json.dumps(payload).encode("utf-8"))
|
||||
|
||||
def session(self, **updates):
|
||||
data = {"user_id": "admin:9", "terminal": 7, "status": "active",
|
||||
"root": False, "role_ids": [2], "permissions": ["tcm.diagnosis/lists"]}
|
||||
data.update(updates)
|
||||
return {"code": 1, "data": data}
|
||||
|
||||
def verify(self):
|
||||
return zyt_auth.verify_desktop_token("test-token", api_url="https://identity.example.test")
|
||||
|
||||
def missing(self, status=404):
|
||||
return urllib.error.HTTPError("https://identity.example.test", status, "test", None, None)
|
||||
|
||||
def test_success_never_requests_ip_bound_web_profile(self):
|
||||
with mock.patch.object(zyt_auth.urllib.request, "urlopen", side_effect=[
|
||||
self.response(self.session(root=True, permissions=["*"])),
|
||||
self.response({"code": -1, "msg": "ip地址发生变化,请重新登录"}),
|
||||
]) as opened:
|
||||
identity = self.verify()
|
||||
self.assertEqual(opened.call_count, 1)
|
||||
self.assertTrue(identity["root"])
|
||||
self.assertEqual(identity["role_ids"], [2])
|
||||
self.assertEqual(identity["permissions"], ["*"])
|
||||
self.assertTrue(identity["permissions_known"])
|
||||
|
||||
def test_missing_permissions_do_not_trigger_profile_request(self):
|
||||
payload = self.session()
|
||||
del payload["data"]["permissions"]
|
||||
with mock.patch.object(zyt_auth.urllib.request, "urlopen", return_value=self.response(payload)) as opened:
|
||||
identity = self.verify()
|
||||
self.assertEqual(opened.call_count, 1)
|
||||
self.assertEqual(identity["permissions"], [])
|
||||
self.assertFalse(identity["permissions_known"])
|
||||
|
||||
def test_empty_permissions_are_known(self):
|
||||
with mock.patch.object(zyt_auth.urllib.request, "urlopen", return_value=self.response(self.session(permissions=[]))):
|
||||
identity = self.verify()
|
||||
self.assertTrue(identity["permissions_known"])
|
||||
self.assertEqual(identity["permissions"], [])
|
||||
|
||||
def test_only_missing_routes_allow_legacy_verification(self):
|
||||
for status in (404, 405):
|
||||
with self.subTest(status=status), mock.patch.object(zyt_auth.urllib.request, "urlopen", side_effect=[
|
||||
self.missing(status), self.response({"code": 1, "data": {
|
||||
"user": {"id": 9, "disable": 0, "role_ids": [2]}, "permissions": []}}),
|
||||
]) as opened:
|
||||
identity = self.verify()
|
||||
self.assertEqual(identity["user_id"], "admin:9")
|
||||
self.assertEqual(opened.call_count, 2)
|
||||
|
||||
def test_http_rejections_do_not_fall_back(self):
|
||||
for status in (401, 403, 500, 502):
|
||||
with self.subTest(status=status), mock.patch.object(zyt_auth.urllib.request, "urlopen", side_effect=self.missing(status)) as opened:
|
||||
with self.assertRaises(zyt_auth.ZytAuthError):
|
||||
self.verify()
|
||||
self.assertEqual(opened.call_count, 1)
|
||||
|
||||
def test_invalid_identity_cannot_be_accepted_through_web_fallback(self):
|
||||
failures = [{"code": -1, "msg": "登录已失效"}, {"code": "bad"}, [],
|
||||
{"code": 1, "data": []}, self.session(user_id=""),
|
||||
self.session(terminal=1), self.session(terminal="bad"),
|
||||
self.session(status="disabled")]
|
||||
for payload in failures:
|
||||
with self.subTest(payload=payload), mock.patch.object(zyt_auth.urllib.request, "urlopen", side_effect=[
|
||||
self.response(payload), self.response({"code": 1, "data": {"user": {"id": 9}}}),
|
||||
]) as opened:
|
||||
with self.assertRaises(zyt_auth.ZytAuthError):
|
||||
self.verify()
|
||||
self.assertEqual(opened.call_count, 1)
|
||||
|
||||
def test_bad_json_and_network_failure_do_not_fall_back(self):
|
||||
for result in (io.BytesIO(b"<html>error</html>"), urllib.error.URLError("offline")):
|
||||
with self.subTest(result=result), mock.patch.object(zyt_auth.urllib.request, "urlopen", side_effect=[result]) as opened:
|
||||
with self.assertRaises(zyt_auth.ZytAuthError):
|
||||
self.verify()
|
||||
self.assertEqual(opened.call_count, 1)
|
||||
|
||||
def test_legacy_ip_error_identifies_missing_server_deployment(self):
|
||||
with mock.patch.object(zyt_auth.urllib.request, "urlopen", side_effect=[
|
||||
self.missing(), self.response({"code": -1, "msg": "ip地址发生变化,请重新登录"}),
|
||||
]):
|
||||
with self.assertRaisesRegex(zyt_auth.ZytAuthError, "/adminapi/desktop/session"):
|
||||
self.verify()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env bash
|
||||
# 基线核对、备份将被替换的源文件和 /m/ 目录、给当前镜像打回滚标签。只读线上 + 写本目录。
|
||||
set -euo pipefail
|
||||
test "${REMOTE_RELEASE_APPROVED:-}" = mobile-ignore-20260929
|
||||
release=/home/ps/mobile-ignore-20260929
|
||||
cd "$release"
|
||||
test ! -e baseline-check.json
|
||||
python3 remote_server_guard.py baseline > baseline-check.json.tmp
|
||||
mv baseline-check.json.tmp baseline-check.json
|
||||
cat baseline-check.json
|
||||
test ! -e source-before
|
||||
test ! -e preflight-complete
|
||||
if docker image inspect zyt/wecom-admin:before-mobile-ignore-20260929 >/dev/null 2>&1; then
|
||||
echo 'Refuse to replace existing rollback tag' >&2; exit 1
|
||||
fi
|
||||
mkdir -m 700 source-before
|
||||
python3 - <<'PY'
|
||||
from pathlib import Path
|
||||
import json, shutil
|
||||
r = Path('/home/ps/mobile-ignore-20260929'); project = Path('/opt/im-admin')
|
||||
plan = json.loads((r / 'release-plan.json').read_text())
|
||||
for name in plan['backendFiles'] + plan['deployFiles']:
|
||||
target = r / 'source-before' / name
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(project / name, target)
|
||||
shutil.copytree(project / plan['frontendDir'], r / 'source-before' / plan['frontendDir'])
|
||||
PY
|
||||
docker tag zyt/wecom-admin:current zyt/wecom-admin:before-mobile-ignore-20260929
|
||||
docker image inspect zyt/wecom-admin:current --format '{{.Id}}' > image-before.txt
|
||||
printf '%s\n' ready > preflight-complete
|
||||
echo "preflight complete; rollback image tagged before-mobile-ignore-20260929 ($(cat image-before.txt))"
|
||||
@@ -0,0 +1,22 @@
|
||||
#!/usr/bin/env bash
|
||||
# 构建候选镜像 + 离线跑测试 + 核对候选镜像文件。线上服务不受影响。
|
||||
# 本次不改数据库(只改 /m/ 静态文件里的文字),不做整库备份;回滚靠旧镜像和 source-before。
|
||||
set -euo pipefail
|
||||
test "${REMOTE_RELEASE_APPROVED:-}" = mobile-ignore-20260929
|
||||
release=/home/ps/mobile-ignore-20260929
|
||||
cd "$release"
|
||||
test -f preflight-complete
|
||||
test ! -e candidate-passed
|
||||
python3 remote_server_guard.py baseline
|
||||
test "$(docker image inspect zyt/wecom-admin:before-mobile-ignore-20260929 --format '{{.Id}}')" = "$(cat image-before.txt)"
|
||||
docker build --network=none --pull=false -f Dockerfile.overlay -t zyt/wecom-admin:mobile-ignore-20260929 . > candidate-build.log 2>&1
|
||||
# serverTestModules 随包放在 tests/;imageTestModules 用镜像自带的测试文件(PYTHONPATH 后一项)。
|
||||
# -P:不把工作目录 /app/wechat_rpa 放到 sys.path 最前面,否则镜像里同名的旧测试会盖住随包的新测试。
|
||||
mapfile -t modules < <(python3 -c 'import json;p=json.load(open("release-plan.json"));print("\n".join(p["serverTestModules"]+p.get("imageTestModules",[])))')
|
||||
test "${#modules[@]}" -gt 0
|
||||
docker run --rm --network=none --read-only --tmpfs /tmp:size=512m,mode=1777 --tmpfs /data:size=256m,mode=1777 \
|
||||
-v "$release/tests:/release-tests:ro" -e PYTHONPATH=/release-tests:/app/wechat_rpa \
|
||||
zyt/wecom-admin:mobile-ignore-20260929 python -X utf8 -B -P -m unittest "${modules[@]}" -q > candidate-tests.log 2>&1
|
||||
tail -n 3 candidate-tests.log
|
||||
python3 remote_server_guard.py candidate
|
||||
printf '%s\n' passed > candidate-passed
|
||||
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env bash
|
||||
# 只替换整个 /m/ 目录(后端代码不变);切换镜像,只重建 api 容器。任何一步失败自动调用 rollback.sh。
|
||||
set -euo pipefail
|
||||
test "${REMOTE_RELEASE_APPROVED:-}" = mobile-ignore-20260929
|
||||
release=/home/ps/mobile-ignore-20260929
|
||||
cd "$release"
|
||||
test -f candidate-passed
|
||||
python3 remote_server_guard.py baseline
|
||||
cd /opt/im-admin/deploy/im-admin
|
||||
docker compose config --quiet
|
||||
rollback_on_error() { rc=$?; trap - ERR; bash "$release/rollback.sh"; exit "$rc"; }
|
||||
trap rollback_on_error ERR
|
||||
python3 - <<'PY'
|
||||
from pathlib import Path
|
||||
import json, hashlib, os, shutil
|
||||
r = Path('/home/ps/mobile-ignore-20260929'); target = Path('/opt/im-admin')
|
||||
plan = json.loads((r / 'release-plan.json').read_text())
|
||||
rows = [row for row in json.loads((r / 'manifest.json').read_text()) if row['path'].startswith('payload/')]
|
||||
frontend = plan['frontendDir']
|
||||
# 容器从镜像里读 /m/,宿主上的目录只给以后整包重建用;仍然整体换名,避免留下半套文件。
|
||||
staging = target / (frontend + '.mobile-ignore.tmp'); assert not staging.exists()
|
||||
old = target / (frontend + '.mobile-ignore.old'); assert not old.exists()
|
||||
for row in rows:
|
||||
rel = row['path'][len('payload/'):]
|
||||
data = (r / row['path']).read_bytes(); assert hashlib.sha256(data).hexdigest() == row['sha256'], rel
|
||||
if rel.startswith(frontend + '/'):
|
||||
dest = staging / rel[len(frontend) + 1:]
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
dest.write_bytes(data); os.chmod(dest, 0o644)
|
||||
continue
|
||||
dest = (target / rel).resolve(); assert dest.is_relative_to(target) and dest.exists()
|
||||
tmp = dest.with_name(dest.name + '.mobile-ignore.tmp'); assert not tmp.exists()
|
||||
with tmp.open('xb') as f:
|
||||
f.write(data)
|
||||
os.chmod(tmp, dest.stat().st_mode & 0o777); os.replace(tmp, dest)
|
||||
for directory in [staging] + [p for p in staging.rglob('*') if p.is_dir()]:
|
||||
os.chmod(directory, 0o755)
|
||||
final = target / frontend
|
||||
os.replace(final, old)
|
||||
os.replace(staging, final)
|
||||
shutil.rmtree(old) # 原目录已在 source-before 里
|
||||
PY
|
||||
docker tag zyt/wecom-admin:mobile-ignore-20260929 zyt/wecom-admin:current
|
||||
docker compose up -d --no-deps --no-build --wait --wait-timeout 180 api
|
||||
bash "$release/04-verify.sh"
|
||||
trap - ERR
|
||||
printf '%s\n' 'Phone console wording 黑名单 -> 忽略 deployed and verified.'
|
||||
@@ -0,0 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
test "${REMOTE_RELEASE_APPROVED:-}" = mobile-ignore-20260929
|
||||
release=/home/ps/mobile-ignore-20260929
|
||||
cd "$release"
|
||||
python3 remote_server_guard.py deployed | tee deployed-verification.json
|
||||
@@ -0,0 +1,8 @@
|
||||
ARG BASE_IMAGE=zyt/wecom-admin:before-mobile-ignore-20260929
|
||||
FROM ${BASE_IMAGE}
|
||||
# 先删掉旧版 /m/ 目录再放新版,镜像里不残留旧的(带“黑名单”文字的)页面文件。
|
||||
USER root
|
||||
RUN rm -rf /app/admin-web/apps/mobile-h5/dist
|
||||
USER app
|
||||
COPY --chown=app:app payload/admin-web/apps/mobile-h5/dist/ /app/admin-web/apps/mobile-h5/dist/
|
||||
WORKDIR /app/wechat_rpa
|
||||
@@ -0,0 +1,157 @@
|
||||
[
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/_plugin-vue_export-helper-D4BeZ2vp.js",
|
||||
"sha256": "2903b693612f3c118ad2142aadbd72b7df39f7e9264c2699d3a184118edf79e9",
|
||||
"bytes": 2308
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/AccountSwitcher-BZXg15MH.css",
|
||||
"sha256": "b61f1f1af65c2c3438066ffe41683af7e38062eb9389cda3f8fdad8ee77498ff",
|
||||
"bytes": 359
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/AccountSwitcher-DmKdvr8J.js",
|
||||
"sha256": "ef16f6b813d27b9dd615960fdef1e6e9a371483c611957b727f3eef766729db4",
|
||||
"bytes": 14528
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/brand-mark-CPUQS9Am.png",
|
||||
"sha256": "1caa8c492da279e8d01f676fe9232ccad016321699d519b3834692052cc5f5ee",
|
||||
"bytes": 16743
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/cell-group-B1mihubH.js",
|
||||
"sha256": "889a5877c28e5d0cd1d3abec0e86ad6ca6615140a2270e977f58d6398de13fec",
|
||||
"bytes": 4490
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/ConversationsView-BeEp2NbK.js",
|
||||
"sha256": "ecb3f12c2b4c6a2e11cf0300824237c237e5e08e3479445c942382fd9c5f5d96",
|
||||
"bytes": 28481
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/ConversationsView-BJrOxtrJ.css",
|
||||
"sha256": "b30e00c1e3c5d454be03e7a36622130f5dd14fe81f196cd6e226dd083d040617",
|
||||
"bytes": 4220
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/DevicesView-CHTvxQxK.css",
|
||||
"sha256": "40fd5adaea4d4aed376a57c75ebec4544d50f424863704b00ce80b98f7881ddd",
|
||||
"bytes": 3983
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/DevicesView-HbIaJI1u.js",
|
||||
"sha256": "46136ea68c275d388a61345624b3511a7d3857d3b6591247602e89d99f5cecc8",
|
||||
"bytes": 10460
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/field-BLYigdmn.js",
|
||||
"sha256": "67e7a6e35dd7abcaa8f61a02b448e24abe94362151fcd042b8706e4aebf7248c",
|
||||
"bytes": 8422
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/format-Dt9-L1ne.js",
|
||||
"sha256": "5718f9373cb4af20835d41ecf49df053e85f29e835ec7857f806d453f2be7227",
|
||||
"bytes": 14363
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/index-C_M75pH8.js",
|
||||
"sha256": "fbedf701fea8bb30607032576c6afaa4de6a02308be22346010e43c8fa7b6ccb",
|
||||
"bytes": 117757
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/index-D80qzV0-.css",
|
||||
"sha256": "c0c7a7706d3d4a4ca2baa88f31aa2fd5c6080b4f2e539b4812a99d51f2de9fd0",
|
||||
"bytes": 97051
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/LoginView-CLW1WjQp.js",
|
||||
"sha256": "07735a478c62e626d73cb49b675182ef12683917b8d9ab6c18ad604a5ed051f6",
|
||||
"bytes": 6336
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/LoginView-J4b4q6ai.css",
|
||||
"sha256": "15ecdd5cb294bb51eef05e4843ac3a65f6e1718cbf16206547a876c52c5e8a2d",
|
||||
"bytes": 1107
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/MeView-CpoVHD8m.css",
|
||||
"sha256": "08a41cb29e760c2040c22007c7fc5dd5669d84e7515f3c671072bf2241dae2bb",
|
||||
"bytes": 927
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/MeView-DTU4-bV-.js",
|
||||
"sha256": "3e2a4ec3c8ac8fc804c1c08dd3a913ec2fd298006f03643488dec37f08f74d0f",
|
||||
"bytes": 3459
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/ShellView-D354hIv5.css",
|
||||
"sha256": "513a381d7ecfe8c24ca22166d658c8604df9d9478a8765ffcef7beb031917dcd",
|
||||
"bytes": 130
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/ShellView-DMPqnSgh.js",
|
||||
"sha256": "256c84cc64e04be449d156d1704efb4575d4e5d137af99f9a83397b2e768317c",
|
||||
"bytes": 2939
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/assets/use-placeholder-BHVOzwXa.js",
|
||||
"sha256": "0ed96441a0fb80d8e585d63838b200ea6435f8deb2641f1effee136f96ef2e76",
|
||||
"bytes": 607
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/icons/apple-touch-icon.png",
|
||||
"sha256": "3167d1d07f22a44ea393b377e5181918ae4890c137de37fe91e2f3780b6ce70e",
|
||||
"bytes": 24681
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/icons/favicon-64.png",
|
||||
"sha256": "7c9d031dcd296a45a79d960481c34eb150dd33e4a2bace6f28385be01c1a675e",
|
||||
"bytes": 5439
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/icons/icon-192.png",
|
||||
"sha256": "9637a4d3e4cbb385ed0b35069d6bb3522b90d1b8aaec439cfdf5ec1264040b5a",
|
||||
"bytes": 26433
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/icons/icon-512.png",
|
||||
"sha256": "803ed98fb41fc724cb5319f45409d5e9725465f6f37cb6312e6b79170f852974",
|
||||
"bytes": 144310
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/icons/icon-maskable-512.png",
|
||||
"sha256": "88b6cecdb691f9e2f4179fd00eae937a5f6863cd61d34aadda1e6ac45e6217a2",
|
||||
"bytes": 95961
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/index.html",
|
||||
"sha256": "d69ec239352bbbfcd48f6243ab704424ed9708c2dd332581a974fe3b4a3855fe",
|
||||
"bytes": 1357
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/manifest.webmanifest",
|
||||
"sha256": "36885be5f98b3bba7e79780a32ab0bbbbe06ed1fc26a14950abc1bb6ffe6a697",
|
||||
"bytes": 681
|
||||
},
|
||||
{
|
||||
"path": "payload/admin-web/apps/mobile-h5/dist/sw.js",
|
||||
"sha256": "d908e9a6ec5c75ffcca8f9f6d97ec683b005fa211975f89beee372849df44a69",
|
||||
"bytes": 339
|
||||
},
|
||||
{
|
||||
"path": "tests/test_backend.py",
|
||||
"sha256": "7473ec5583c97941e132ade7a1f66abcf54fa6108ec6bb2a182f0152964fff61",
|
||||
"bytes": 66279
|
||||
},
|
||||
{
|
||||
"path": "tests/test_remote_api.py",
|
||||
"sha256": "479cb9b042dc14707af718734c33688013203d4154f36199b7b0ced656653c39",
|
||||
"bytes": 38523
|
||||
},
|
||||
{
|
||||
"path": "tests/test_zyt_auth.py",
|
||||
"sha256": "40ab2d37f51780af26497e22948ef665c92b7f3707f6ba30a6d711bf5b15dfa6",
|
||||
"bytes": 4907
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
.switcher[data-v-91cf283c]{max-height:80vh}.switcher-body[data-v-91cf283c]{padding:16px 0 12px}.switcher-body h3[data-v-91cf283c]{margin:0 16px 8px;font-size:17px}.switcher-state[data-v-91cf283c]{place-items:center;padding:32px 0;display:grid}.switcher-list[data-v-91cf283c]{margin-top:12px}.current[data-v-91cf283c]{color:var(--app-primary);margin-left:6px}
|
||||
@@ -0,0 +1 @@
|
||||
.detail[data-v-bdbcc19d]{padding-bottom:16px}.detail-head[data-v-bdbcc19d]{align-items:center;gap:12px;padding:16px;display:flex}.avatar[data-v-bdbcc19d]{width:52px;height:52px;color:var(--app-primary);background:var(--app-primary-soft);border-radius:14px;flex:none;place-items:center;font-size:22px;font-weight:600;display:grid}.detail-title[data-v-bdbcc19d]{flex:1;min-width:0}.detail-title h2[data-v-bdbcc19d]{text-overflow:ellipsis;white-space:nowrap;margin:0 0 4px;font-size:18px;overflow:hidden}.detail-title p[data-v-bdbcc19d]{margin:0;font-size:13px}.badge[data-v-bdbcc19d]{color:var(--app-danger);background:var(--app-danger-soft);border-radius:999px;flex:none;align-items:center;gap:4px;padding:4px 10px;font-size:12px;font-weight:600;display:inline-flex}.group[data-v-bdbcc19d]{margin-bottom:12px}.state[data-v-bdbcc19d]{background:var(--app-surface);border:1px solid var(--app-border);border-radius:14px;margin:0 16px;padding:16px}.state--blocked[data-v-bdbcc19d]{border-color:var(--app-danger-soft);background:linear-gradient(0deg, var(--app-danger-soft), var(--app-danger-soft)), var(--app-surface)}.state h3[data-v-bdbcc19d]{align-items:center;gap:6px;margin:0 0 6px;font-size:15px;display:flex}.state--blocked h3[data-v-bdbcc19d]{color:var(--app-danger)}.state>p[data-v-bdbcc19d]{color:var(--app-text-2);margin:0 0 12px;font-size:13px;line-height:1.6}.state dl[data-v-bdbcc19d]{grid-template-columns:repeat(2,minmax(0,1fr));gap:8px 12px;margin:0 0 14px;display:grid}.state dt[data-v-bdbcc19d]{color:var(--app-muted);font-size:12px}.state dd[data-v-bdbcc19d]{word-break:break-all;margin:2px 0 0;font-size:14px}.reason[data-v-bdbcc19d]{margin:0 0 12px}.reason[data-v-bdbcc19d] .van-cell-group--inset{margin:0}.state[data-v-bdbcc19d] .van-cell-group--inset{margin:0 0 12px}.note[data-v-bdbcc19d]{color:var(--app-muted);margin:0;font-size:13px;line-height:1.6}.row[data-v-645c253b]{border:0;border-bottom:1px solid var(--app-border);background:var(--app-surface);width:100%;min-height:64px;color:inherit;text-align:left;cursor:pointer;align-items:center;gap:12px;padding:10px 16px;display:flex}.row[data-v-645c253b]:active,.row.active[data-v-645c253b]{background:var(--app-primary-soft)}.avatar[data-v-645c253b]{border-radius:12px;flex:none;place-items:center;width:42px;height:42px;font-size:17px;font-weight:600;display:grid}.avatar--wecom[data-v-645c253b]{color:#2f6fff;background:#2f6fff1f}.avatar--wechat[data-v-645c253b]{color:#0f9e69;background:#13b77a24}.avatar--group[data-v-645c253b]{color:#7a5cff;background:#8a6bff24}.body[data-v-645c253b]{flex:1;gap:4px;min-width:0;display:grid}.line[data-v-645c253b]{justify-content:space-between;align-items:center;gap:8px;min-width:0;display:flex}.name[data-v-645c253b]{text-overflow:ellipsis;white-space:nowrap;font-size:15px;font-weight:600;overflow:hidden}.time[data-v-645c253b]{color:var(--app-muted);flex:none;font-size:12px}.sub[data-v-645c253b]{color:var(--app-muted);font-size:12px}.meta[data-v-645c253b]{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.blocked[data-v-645c253b]{color:var(--app-danger);background:var(--app-danger-soft);border-radius:999px;flex:none;padding:1px 8px;font-weight:600}.page[data-v-4433756d]{min-height:100%}.nav-action[data-v-4433756d]{color:var(--app-primary);background:0 0;border:0;align-items:center;gap:4px;padding:6px 0;font-size:14px;display:inline-flex}.toolbar[data-v-4433756d]{top:calc(46px + env(safe-area-inset-top));z-index:2;background:var(--app-bg);position:-webkit-sticky;position:sticky}.toolbar[data-v-4433756d] .van-search{background:0 0;padding-bottom:4px}.tabs[data-v-4433756d]{--van-tabs-nav-background:transparent;padding:0 4px}.list-body[data-v-4433756d]{min-height:60vh}.single .list-pane[data-v-4433756d]{max-width:720px;margin:0 auto}.split[data-v-4433756d]{grid-template-columns:minmax(300px,380px) minmax(0,1fr);align-items:start;gap:16px;max-width:1180px;margin:0 auto;padding:0 24px 24px;display:grid}.split .list-body[data-v-4433756d]{border-radius:16px;overflow:clip}.detail-pane[data-v-4433756d]{top:calc(46px + env(safe-area-inset-top) + 12px);min-height:320px;margin-top:12px;position:-webkit-sticky;position:sticky}.sheet[data-v-4433756d]{max-height:88vh;padding-top:8px}
|
||||