WIP-CHECKPOINT[auth-refactor]: 固化工程师崩溃前部分成果 + 同树其他未提交WIP(仅源码,不含密钥/二进制)-- 待重激活工程师续作

This commit is contained in:
Simon
2026-07-07 21:52:11 +08:00
parent 242c1967ff
commit fab75760e0
203 changed files with 21504 additions and 3345 deletions
+7
View File
@@ -0,0 +1,7 @@
#!/usr/bin/env python3
# 添加 settings 行
with open("/app/app/config.py", "a") as f:
f.write("\n\n# 创建全局配置实例\n# 整个应用通过 from app.config import settings 使用同一个实例\nsettings = Settings()\n")
print("Done!")
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env python3
import sys
sys.path.insert(0, "/app")
from app.config import settings
print(f"settings.redis_url = {repr(settings.redis_url)}")
print(f"bool(settings.redis_url) = {bool(settings.redis_url)}")
# Parse URL manually
from urllib.parse import urlparse
parsed = urlparse(settings.redis_url)
print(f"parsed = {parsed}")
print(f"parsed.hostname = {parsed.hostname}")
print(f"parsed.port = {parsed.port}")
print(f"parsed.password = {parsed.password}")
print(f"parsed.path = {parsed.path}")
+2 -2
View File
@@ -66,8 +66,8 @@ services:
container_name: wecom_it_nginx_green
restart: unless-stopped
ports:
- "5080:80"
- "5443:443"
- "80:80"
- "443:443"
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
- ./nginx/ssl:/etc/nginx/ssl:ro
+2 -1
View File
@@ -138,8 +138,9 @@ services:
- ./nginx/ssl:/etc/nginx/ssl:ro
- ./html/itdesk:/usr/share/nginx/html/itdesk:ro
- ./html/itagent:/usr/share/nginx/html/itagent:ro
- ./html/itadmin:/usr/share/nginx/html/itadmin:ro
- ./html/itadmin:/usr/share/nginx/html/itadmin
- ./html/itportal:/usr/share/nginx/html/itportal:ro
- ./html/h5:/usr/share/nginx/html/h5:ro
depends_on:
- backend
networks:
+31
View File
@@ -0,0 +1,31 @@
import re
# 读取nginx.conf
with open('/etc/nginx/nginx.conf', 'r') as f:
content = f.read()
# 找到/itadmin/ location块并替换
old_block = '''location /itadmin/ {
# IP 白名单:仅允许内网网段
allow 10.0.0.0/8;
allow 172.16.0.0/12;
allow 192.168.0.0/16;
allow 10.212.0.0/16; # VPN 网段
deny all;'''
new_block = '''location /itadmin/ {
# IP 白名单:仅允许内网网段 + 临时公网IP
allow 10.0.0.0/8;
allow 172.16.0.0/12;
allow 192.168.0.0/16;
allow 10.212.0.0/16; # VPN 网段
allow 43.174.152.34; # 临时添加 (2026-07-06)
deny all;'''
content = content.replace(old_block, new_block)
# 写回
with open('/etc/nginx/nginx.conf', 'w') as f:
f.write(content)
print('Done')
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env python3
"""修复 Redis 连接问题的脚本 - 直接编辑文件"""
import sys
# 读取原始文件
config_path = "/app/app/config.py"
with open(config_path, "r", encoding="utf-8") as f:
lines = f.readlines()
# 找到 create_redis_client 方法的开始
start_idx = None
for i, line in enumerate(lines):
if "def create_redis_client(self)" in line:
start_idx = i
break
if start_idx is None:
print("ERROR: Could not find create_redis_client method")
sys.exit(1)
# 找到方法结束(下一个 def 或 class)
end_idx = None
for i in range(start_idx + 1, len(lines)):
if lines[i].strip().startswith("def ") or lines[i].strip().startswith("class "):
end_idx = i
break
if end_idx is None:
end_idx = len(lines)
print(f"Found method at lines {start_idx+1} to {end_idx}")
# 新的方法实现
new_method = ''' def create_redis_client(self) -> aioredis.Redis:
"""创建 Redis 异步客户端实例。
使用单独的 host/port/password 参数,避免 URL 解析问题
(特别是密码中包含特殊字符 ! @ # 时)。
自动附加 protocol=2 参数,强制使用 RESP2 协议。
原因:Windows 版 Redis 3.x 不支持 RESP3 协议(HELLO 命令),
而 redis-py 8.0+ 默认使用 RESP3,会导致连接失败。
全项目统一使用此方法创建 Redis 客户端,避免协议不匹配。
Returns:
aioredis.Redis: 配置好的 Redis 异步客户端
"""
# 如果 redis_url 为空,使用默认值
if not self.redis_url:
# 默认值:本地 Redis
return aioredis.Redis(
host="localhost",
port=6379,
protocol=2,
decode_responses=True
)
# 解析 REDIS_URL 提取连接参数
# 格式: redis://:password@host:port/db
from urllib.parse import urlparse
parsed = urlparse(self.redis_url)
# 提取密码(去掉用户名部分,如果存在的话)
password = parsed.password
if not password:
# 尝试从 netloc 中提取(格式 :password@host
netloc = parsed.netloc
if "@" in netloc:
password = netloc.split("@")[0].split(":")[-1]
return aioredis.Redis(
host=parsed.hostname or "localhost",
port=parsed.port or 6379,
password=password,
db=parsed.path and int(parsed.path.lstrip("/")) or 0,
protocol=2,
decode_responses=True
)
'''
# 替换方法
new_lines = lines[:start_idx] + [new_method] + lines[end_idx:]
# 写回文件
with open(config_path, "w", encoding="utf-8") as f:
f.writelines(new_lines)
print("Fixed!")
+138
View File
@@ -0,0 +1,138 @@
#!/usr/bin/env python3
"""修复 Redis URL 解析问题"""
config_path = "/app/app/config.py"
with open(config_path, "r", encoding="utf-8") as f:
content = f.read()
# 找到并替换 create_redis_client 方法
old = ''' def create_redis_client(self) -> aioredis.Redis:
"""创建 Redis 异步客户端实例。
使用单独的 host/port/password 参数,避免 URL 解析问题
(特别是密码中包含特殊字符 ! @ # 时)。
自动附加 protocol=2 参数,强制使用 RESP2 协议。
原因:Windows 版 Redis 3.x 不支持 RESP3 协议(HELLO 命令),
而 redis-py 8.0+ 默认使用 RESP3,会导致连接失败。
全项目统一使用此方法创建 Redis 客户端,避免协议不匹配。
Returns:
aioredis.Redis: 配置好的 Redis 异步客户端
"""
# 如果 redis_url 为空,使用默认值
if not self.redis_url:
# 默认值:本地 Redis
return aioredis.Redis(
host="localhost",
port=6379,
protocol=2,
decode_responses=True
)
# 解析 REDIS_URL 提取连接参数
# 格式: redis://:password@host:port/db
from urllib.parse import urlparse
parsed = urlparse(self.redis_url)
# 提取密码(去掉用户名部分,如果存在的话)
password = parsed.password
if not password:
# 尝试从 netloc 中提取(格式 :password@host
netloc = parsed.netloc
if "@" in netloc:
password = netloc.split("@")[0].split(":")[-1]
return aioredis.Redis(
host=parsed.hostname or "localhost",
port=parsed.port or 6379,
password=password,
db=parsed.path and int(parsed.path.lstrip("/")) or 0,
protocol=2,
decode_responses=True
)'''
new = ''' def create_redis_client(self) -> aioredis.Redis:
"""创建 Redis 异步客户端实例。
使用单独的 host/port/password 参数,避免 URL 解析问题
(特别是密码中包含特殊字符 ! @ # 时)。
自动附加 protocol=2 参数,强制使用 RESP2 协议。
原因:Windows 版 Redis 3.x 不支持 RESP3 协议(HELLO 命令),
而 redis-py 8.0+ 默认使用 RESP3,会导致连接失败。
全项目统一使用此方法创建 Redis 客户端,避免协议不匹配。
Returns:
aioredis.Redis: 配置好的 Redis 异步客户端
"""
# 如果 redis_url 为空,使用默认值
if not self.redis_url:
# 默认值:本地 Redis
return aioredis.Redis(
host="localhost",
port=6379,
protocol=2,
decode_responses=True
)
# 解析 REDIS_URL 提取连接参数
# 格式: redis://:password@host:port/db
# 注意:密码中可能包含 @ 字符,需要特殊处理
# 例如:redis://:R3d!s@2026#Secure@redis:6379/0
# 其中 :R3d!s@2026#Secure 是密码,redis 是主机名
url = self.redis_url
# 找到最后一个 @ 之前的所有内容作为密码
# 格式: redis://:password@host:port/db
scheme_prefix = "redis://:"
if url.startswith(scheme_prefix):
# 提取 @ 之后的部分(主机和端口)
rest = url[len(scheme_prefix):]
at_pos = rest.rfind("@")
if at_pos > 0:
password = rest[:at_pos]
host_part = rest[at_pos+1:]
# 解析主机部分
if "/" in host_part:
host_port, db = host_part.split("/", 1)
db = int(db) if db.isdigit() else 0
else:
host_port = host_part
db = 0
if ":" in host_port:
host, port = host_port.split(":", 1)
port = int(port)
else:
host = host_port
port = 6379
return aioredis.Redis(
host=host,
port=port,
password=password,
db=db,
protocol=2,
decode_responses=True
)
# 回退:使用 from_url
return aioredis.from_url(url, protocol=2)'''
if old not in content:
print("ERROR: Could not find old method")
print("Looking for method...")
import re
match = re.search(r'def create_redis_client.*?(?=\n def |\nclass |\Z)', content, re.DOTALL)
if match:
print(f"Found: {match.group(0)[:200]}")
sys.exit(1)
new_content = content.replace(old, new)
with open(config_path, "w", encoding="utf-8") as f:
f.write(new_content)
print("Fixed!")
+13
View File
@@ -0,0 +1,13 @@
# 管理后台 — /itadmin/(仅限内网/VPN + 临时公网IP)
location /itadmin/ {
# IP 白名单:仅允许内网网段
allow 10.0.0.0/8;
allow 172.16.0.0/12;
allow 192.168.0.0/16;
allow 10.212.0.0/16; # VPN 网段
allow 43.174.152.34; # 临时添加 (2026-07-06)
deny all;
alias /usr/share/nginx/html/itadmin/;
index index.html;
try_files $uri /itadmin/index.html;
}
@@ -0,0 +1,15 @@
# 临时IP白名单配置(2026-07-06
# 添加用户公网IP: 43.174.152.34
# 管理后台 /itadmin/ 临时允许访问
location /itadmin/ {
allow 10.0.0.0/8;
allow 172.16.0.0/12;
allow 192.168.0.0/16;
allow 10.212.0.0/16;
allow 43.174.152.34; # 临时添加
deny all;
alias /usr/share/nginx/html/itadmin/;
index index.html;
try_files $uri /itadmin/index.html;
}
+6 -2
View File
@@ -31,8 +31,12 @@ if [ -f "/tmp/agent-v3.tar.b64" ]; then
base64 -d /tmp/agent-v3.tar.b64 > agent-v3.tar.gz
tar -xzf agent-v3.tar.gz
# 移动文件
cp -r dist/* /opt/wecom-it-desk/html/itagent/
# 移动文件(使用 rsync 替代 cp,确保文件真正覆盖)
# --checksum: 基于 checksum 对比,不依赖 mtime
# -a: 归档模式,保留权限和时间戳
# -v: 显示详细输出
# --delete: 删除目标目录中源目录没有的文件
rsync -av --checksum --delete dist/ /opt/wecom-it-desk/html/itagent/
# 4. 重启 nginx
echo "[4/4] 重启 nginx..."
+212
View File
@@ -0,0 +1,212 @@
# =============================================================================
# 企微智能IT支持服务台 — Nginx 配置(公司内网服务器版)
# =============================================================================
# 适用场景:独立域名 itsupport.servyou.com.cn,公司内网 DNS 解析
# 与 NAS 版的区别:
# 1. 移除 Cloudflare 相关头(X-Forwarded-Proto https 等)
# 2. server_name 改为正式域名
# 3. 真实 IP 直接从 $remote_addr 获取(无 CF 代理层)
# 4. 预留 HTTPS 配置注释(如公司有统一 SSL 终端)
# =============================================================================
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# ------------------------------------------------------------------
# 日志格式
# ------------------------------------------------------------------
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent"';
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log warn;
# ------------------------------------------------------------------
# 真实 IP 还原(2026-06-15 v0.5.1 修复)
# ------------------------------------------------------------------
set_real_ip_from 10.0.0.0/8; # 内网 A 类(代理/WAF 出口)
set_real_ip_from 172.16.0.0/12; # 内网 B 类
set_real_ip_from 192.168.0.0/16; # 内网 C 类
set_real_ip_from 10.212.0.0/16; # VPN 网段
real_ip_header X-Forwarded-For; # 从 X-Forwarded-For 取最后一个非信任 IP
real_ip_recursive on; # 递归剥离已信任代理 IP
# ------------------------------------------------------------------
# 基础配置
# ------------------------------------------------------------------
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
client_max_body_size 50m;
# ------------------------------------------------------------------
# Gzip 压缩(前端静态资源)
# ------------------------------------------------------------------
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css text/xml text/javascript
application/javascript application/xml+rss
application/json application/ld+json;
# =================================================================
# 上游服务定义(Docker 内部网络)
# =================================================================
upstream backend_api {
server wecom_it_backend:8000;
}
# =================================================================
# HTTP 服务(监听 80 端口)
# =================================================================
server {
listen 80;
server_name itsupport.servyou.com.cn;
location /.well-known/acme-challenge/ {
root /usr/share/nginx/html;
}
# H5 静态文件服务
location /h5/ {
alias /usr/share/nginx/html/h5/;
index index.html;
try_files $uri $uri/ /h5/index.html;
}
# H5 API 反向代理
location /h5/api/ {
proxy_pass http://wecom_it_backend:8000/;
proxy_http_version 1.1;
proxy_redirect off;
proxy_set_header Host $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 Connection "";
proxy_connect_timeout 60s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
}
location / {
return 301 https://$host$request_uri;
}
}
# =================================================================
# HTTPS — 443 端口(主服务)
# =================================================================
server {
listen 443 ssl;
http2 on;
server_name itsupport.servyou.com.cn;
ssl_certificate /etc/nginx/ssl/itsupport.servyou.com.cn.crt;
ssl_certificate_key /etc/nginx/ssl/itsupport.servyou.com.cn.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-eval' https://res.wx.qq.com; style-src 'self' 'unsafe-inline' https://res.wx.qq.com; connect-src 'self' wss://itsupport.servyou.com.cn https://itsupport.servyou.com.cn https://qyapi.weixin.qq.com; img-src 'self' data: https://res.wx.qq.com; font-src 'self' data:;" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=()" always;
add_header Cross-Origin-Opener-Policy "same-origin" always;
add_header Cross-Origin-Embedder-Policy "require-corp" always;
add_header Cross-Origin-Resource-Policy "same-origin" always;
server_tokens off;
location = /health {
access_log off;
return 200 "healthy\n";
add_header Content-Type text/plain;
}
# 员工端:/itdesk/ -> 重定向到 /itagent/(保持前端路由 base 一致)
location /itdesk/ {
return 301 /itagent/;
}
location /itagent/ {
alias /usr/share/nginx/html/itagent/;
index index.html;
try_files $uri $uri/ /index.html;
}
location /itadmin/ {
allow 10.0.0.0/8;
allow 172.16.0.0/12;
allow 192.168.0.0/16;
allow 10.212.0.0/16;
allow 10.240.0.0/16;
allow 117.147.35.138;
allow 218.75.34.87;
allow 43.174.152.34;
#deny all;
alias /usr/share/nginx/html/itadmin/;
index index.html;
try_files $uri /itadmin/index.html;
}
location /itportal/ {
alias /usr/share/nginx/html/itportal/;
index index.html;
try_files $uri /itportal/index.html;
}
location /api/ {
location ~ ^/api/admin/ {
allow 10.0.0.0/8;
allow 172.16.0.0/12;
allow 192.168.0.0/16;
allow 10.212.0.0/16;
#deny all;
proxy_pass http://backend_api;
proxy_set_header Host $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 60s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
}
proxy_pass http://backend_api/;
proxy_http_version 1.1;
proxy_redirect off;
proxy_set_header Host $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 Connection "";
proxy_connect_timeout 60s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
}
location /ws/ {
access_log off;
proxy_pass http://backend_api;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_read_timeout 86400s;
}
# H5 静态文件服务
location /h5/ {
alias /usr/share/nginx/html/h5/;
index index.html;
try_files $uri $uri/ /h5/index.html;
}
# H5 API 反向代理
location /h5/api/ {
proxy_pass http://wecom_it_backend:8000/;
proxy_http_version 1.1;
proxy_redirect off;
proxy_set_header Host $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 Connection "";
proxy_connect_timeout 60s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
}
location = / {
return 302 /itportal/;
}
}
}
+1 -1
View File
@@ -38,7 +38,7 @@ http {
# Upstream — 切换到 Green 环境
# ------------------------------------------------------------------
upstream backend_api {
server wecom_it_backend_green:8000;
server wecom_it_backend:8000;
}
# ------------------------------------------------------------------
+8 -1
View File
@@ -18,8 +18,15 @@ server {
proxy_set_header X-Forwarded-Proto $scheme;
}
# H5 端点反向代理
# H5 静态文件服务
location /h5/ {
alias /usr/share/nginx/html/h5/;
index index.html;
try_files $uri $uri/ /h5/index.html;
}
# H5 API 反向代理(更具体的路径)
location /h5/api/ {
proxy_pass http://wecom_it_backend_green:8000/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env python3
"""Add IP 115.227.36.10 to nginx whitelist"""
with open('/opt/wecom-it-desk/nginx/nginx.conf', 'r') as f:
content = f.read()
# Add after existing office IPs
content = content.replace(
'allow 218.75.34.87;',
'allow 218.75.34.87;\n allow 115.227.36.10; # 新增办公网出口IP'
)
with open('/opt/wecom-it-desk/nginx/nginx.conf', 'w') as f:
f.write(content)
print('Done')
+2 -2
View File
@@ -112,8 +112,8 @@ http {
# API 路由分发(根据路径选择上游服务)
# ------------------------------------------------------------------
# Core 服务:认证、员工、角色
location ~ ^/api/(auth|employees|roles|mfa) {
# Core 服务:认证、员工、角色(包括 auth_qrcode 扫码登录)
location ~ ^/api/(auth|employees|roles|mfa|auth_qrcode) {
proxy_pass http://core_backend;
proxy_http_version 1.1;
proxy_set_header Host $host;
+58 -97
View File
@@ -8,40 +8,29 @@
# 3. 真实 IP 直接从 $remote_addr 获取(无 CF 代理层)
# 4. 预留 HTTPS 配置注释(如公司有统一 SSL 终端)
# =============================================================================
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# ------------------------------------------------------------------
# 日志格式
# ------------------------------------------------------------------
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent"';
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log warn;
# ------------------------------------------------------------------
# 真实 IP 还原(2026-06-15 v0.5.1 修复)
# ------------------------------------------------------------------
# 问题:公司有 WAF/堡垒机/反向代理,nginx 看到的 $remote_addr
# 是代理 IP(不在白名单),allow/deny 因此误判 403
# 修法:信任内网段代理透传的 X-Forwarded-For 头,用真实 IP 做白名单
# 注意:set_real_ip_from 是"我信任的代理",不是"我允许的客户端"
# 必须精确,否则攻击者可伪造 X-Forwarded-For 绕过白名单
set_real_ip_from 10.0.0.0/8; # 内网 A 类(代理/WAF 出口)
set_real_ip_from 172.16.0.0/12; # 内网 B 类
set_real_ip_from 192.168.0.0/16; # 内网 C 类
set_real_ip_from 192.168.0.0/16; # 内网 C 类
set_real_ip_from 10.212.0.0/16; # VPN 网段
real_ip_header X-Forwarded-For; # 从 X-Forwarded-For 取最后一个非信任 IP
real_ip_recursive on; # 递归剥离已信任代理 IP
# ------------------------------------------------------------------
# 基础配置
# ------------------------------------------------------------------
@@ -50,8 +39,7 @@ http {
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
client_max_body_size 50m; # 支持文件上传(企微媒体文件)
client_max_body_size 50m;
# ------------------------------------------------------------------
# Gzip 压缩(前端静态资源)
# ------------------------------------------------------------------
@@ -59,39 +47,47 @@ http {
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css text/xml text/javascript
application/javascript application/xml+rss
application/json application/ld+json;
application/javascript application/xml+rss
application/json application/ld+json;
# =================================================================
# 上游服务定义(Docker 内部网络)
# =================================================================
upstream backend_api {
server backend:8000;
}
# =================================================================
# HTTP 服务(监听 80 端口)
# =================================================================
# 如果公司有统一 SSL 终端(如 F5/Nginx 反代),此服务器只需监听 80
# 如果需要本机 HTTPS,取消下方 server 块注释,并配置证书路径
# =================================================================
# HTTP — 80 端口强制 301 跳 HTTPS
# =================================================================
server {
listen 80;
server_name itsupport.servyou.com.cn;
# ACME http-01 验证用(如果以后用 Let's Encrypt
location /.well-known/acme-challenge/ {
root /usr/share/nginx/html;
}
# 其他全部 301 跳 https
# H5 静态文件服务
location /h5/ {
root /usr/share/nginx/html;
index index.html;
try_files $uri /h5/index.html;
}
# H5 API 反向代理
location /h5/api/ {
proxy_pass http://backend:8000/;
proxy_http_version 1.1;
proxy_redirect off;
proxy_set_header Host $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 Connection "";
proxy_connect_timeout 60s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
}
location / {
return 301 https://$host$request_uri;
}
}
# =================================================================
# HTTPS — 443 端口(主服务)
# =================================================================
@@ -99,8 +95,6 @@ http {
listen 443 ssl;
http2 on;
server_name itsupport.servyou.com.cn;
# SSL 证书(通配符 *.servyou.com.cn,fullchain 含 leaf+intermediate+root)
ssl_certificate /etc/nginx/ssl/itsupport.servyou.com.cn.crt;
ssl_certificate_key /etc/nginx/ssl/itsupport.servyou.com.cn.key;
ssl_protocols TLSv1.2 TLSv1.3;
@@ -108,92 +102,57 @@ http {
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
# ------------------------------------------------------------------
# 安全头
# ------------------------------------------------------------------
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
# CSP 收紧: 去掉 unsafe-inline(生产不需要,只有 dev HMR 需要)
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-eval' https://res.wx.qq.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https: http:; connect-src 'self' https://qyapi.weixin.qq.com wss://*; font-src 'self' data:;" always;
# 隐私与跨域控制
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-eval' https://res.wx.qq.com; style-src 'self' 'unsafe-inline' https://res.wx.qq.com; connect-src 'self' wss://itsupport.servyou.com.cn https://itsupport.servyou.com.cn https://qyapi.weixin.qq.com; img-src 'self' data: https://res.wx.qq.com; font-src 'self' data:;" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=()" always;
add_header Cross-Origin-Opener-Policy "same-origin" always;
add_header Cross-Origin-Embedder-Policy "require-corp" always;
add_header Cross-Origin-Resource-Policy "same-origin" always;
# 隐藏服务器版本
server_tokens off;
# ------------------------------------------------------------------
# 健康检查端点
# ------------------------------------------------------------------
location = /health {
access_log off;
return 200 "healthy\n";
add_header Content-Type text/plain;
}
# ------------------------------------------------------------------
# H5 员工端 — /itdesk/
# ------------------------------------------------------------------
# 员工端:/itdesk/ -> 重定向到 /itagent/(保持前端路由 base 一致)
location /itdesk/ {
alias /usr/share/nginx/html/itdesk/;
index index.html;
try_files $uri /itdesk/index.html;
return 301 /itagent/;
}
# ------------------------------------------------------------------
# 坐席工作台 — /itagent/
# ------------------------------------------------------------------
location /itagent/ {
alias /usr/share/nginx/html/itagent/;
index index.html;
try_files $uri /itagent/index.html;
try_files $uri $uri/ /index.html;
}
# ------------------------------------------------------------------
# 管理后台 — /itadmin/(仅限内网/VPN 访问)
# ------------------------------------------------------------------
location /itadmin/ {
# IP 白名单:仅允许内网网段
allow 10.0.0.0/8;
allow 172.16.0.0/12;
allow 192.168.0.0/16;
allow 10.212.0.0/16; # VPN 网段
deny all;
allow 10.212.0.0/16;
allow 10.240.0.0/16;
allow 117.147.35.138;
allow 218.75.34.87;
allow 43.174.152.34;
#deny all;
alias /usr/share/nginx/html/itadmin/;
index index.html;
try_files $uri /itadmin/index.html;
}
# ------------------------------------------------------------------
# 统一入口 Portal — /itportal/
# ------------------------------------------------------------------
location /itportal/ {
alias /usr/share/nginx/html/itportal/;
index index.html;
try_files $uri /itportal/index.html;
}
# ------------------------------------------------------------------
# 后端 API — /api/(管理端 API 仅限内网/VPN
# ------------------------------------------------------------------
location /api/ {
# 管理端 API 路径需要 IP 白名单
location ~ ^/api/admin/ {
allow 10.0.0.0/8;
allow 172.16.0.0/12;
allow 192.168.0.0/16;
allow 10.212.0.0/16;
deny all;
#deny all;
proxy_pass http://backend_api;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
@@ -203,28 +162,20 @@ http {
proxy_send_timeout 300s;
proxy_read_timeout 300s;
}
# 其他 API 路径
proxy_pass http://backend_api/;
proxy_http_version 1.1;
proxy_redirect off; # 禁用重定向修改,让后端的 307/302 保持原始 location
proxy_redirect off;
proxy_set_header Host $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 Connection "";
# 超时设置(AI 回复可能较慢)
proxy_connect_timeout 60s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
}
# ------------------------------------------------------------------
# WebSocket — /ws/(坐席端实时通信)
# ------------------------------------------------------------------
location /ws/ {
access_log off; # P0-#4: 关闭 WS 路径日志,避免 token 泄露
access_log off;
proxy_pass http://backend_api;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
@@ -232,18 +183,28 @@ http {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_read_timeout 86400s; # WebSocket 长连接
proxy_read_timeout 86400s;
}
# H5 静态文件服务
location /h5/ {
root /usr/share/nginx/html;
index index.html;
try_files $uri /h5/index.html;
}
# H5 API 反向代理
location /h5/api/ {
proxy_pass http://backend:8000/;
proxy_http_version 1.1;
proxy_redirect off;
proxy_set_header Host $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 Connection "";
proxy_connect_timeout 60s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
}
# ------------------------------------------------------------------
# 企微回调 — /api/wecom/callback(接收企微消息推送)
# ------------------------------------------------------------------
# 企微验证回调 URL 时使用 GET,后续消息推送使用 POST
# 此路径已包含在 /api/ 的代理规则中,无需单独配置
# ------------------------------------------------------------------
# 默认路径 — 重定向到统一入口
# ------------------------------------------------------------------
location = / {
return 302 /itportal/;
}
+21
View File
@@ -0,0 +1,21 @@
#!/usr/bin/env python3
"""Update nginx.conf to add 10.240.0.0/16"""
import re
with open('/opt/wecom-it-desk/nginx/nginx.conf', 'r') as f:
content = f.read()
# Add 10.240.0.0/16 after 10.212.0.0/16 in both locations
content = content.replace(
'allow 10.212.0.0/16; # VPN 网段\n',
'allow 10.212.0.0/16; # VPN 网段\n allow 10.240.0.0/16; # 内网段 - 办公网(新增)\n'
)
content = content.replace(
'allow 10.212.0.0/16;\n',
'allow 10.212.0.0/16;\n allow 10.240.0.0/16; # 内网段 - 办公网(新增)\n'
)
with open('/opt/wecom-it-desk/nginx/nginx.conf', 'w') as f:
f.write(content)
print('Done')
+28
View File
@@ -0,0 +1,28 @@
#!/usr/bin/env python3
"""Upload nginx.conf to production server via JumpServer"""
import base64
import subprocess
import sys
import os
# Read and encode the nginx.conf file
nginx_conf_path = os.path.join(os.path.dirname(__file__), 'nginx.conf')
with open(nginx_conf_path, 'rb') as f:
b64_data = base64.b64encode(f.read()).decode()
print(f"Encoded {len(b64_data)} characters")
# Create the remote Python script
remote_script = 'python3 -c "'
remote_script += f"import base64; data = '''{b64_data}'''; "
remote_script += "with open('/opt/wecom-it-desk/nginx/nginx.conf', 'wb') as f: f.write(base64.b64decode(data)); print('OK')"
remote_script += '"'
# Execute via jms_ops
result = subprocess.run([
'python', r'C:\Users\simon\.workbuddy\skills\jumpserver-ops\scripts\jms_ops.py',
'exec', '-c', remote_script
], capture_output=True, text=True, encoding='utf-8', errors='replace', cwd=r'd:\资料\03-项目开发\wecom_it_smart_desk')
print(result.stdout)
print(result.stderr)
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env python3
import asyncio
import sys
sys.path.insert(0, "/app")
from app.config import settings
from app.dependencies import get_redis
async def test():
print("Testing Redis using the new config...")
try:
r = await get_redis()
result = await r.ping()
print(f"Ping result: {result}")
except Exception as e:
print(f"Error: {e}")
asyncio.run(test())
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env python3
import sys
sys.path.insert(0, "/app")
# Test config directly
from app.config import settings
print(f"REDIS_URL = {settings.redis_url}")
print("Creating Redis client...")
client = settings.create_redis_client()
print(f"Client created: {client}")
import asyncio
async def test():
result = await client.ping()
print(f"Ping result: {result}")
asyncio.run(test())