diff --git a/WECOM_SETUP_CHECKLIST.md b/WECOM_SETUP_CHECKLIST.md index 206a9311..5b551c9a 100644 --- a/WECOM_SETUP_CHECKLIST.md +++ b/WECOM_SETUP_CHECKLIST.md @@ -4,12 +4,18 @@ Set these on the backend runtime: +- Recommended start point: copy `backend/.env.production.example` to `backend/.env` and update values. + - `WECOM_ENABLED=true` - `WECOM_CORP_ID=` - `WECOM_AGENT_ID=` - `WECOM_SECRET=` - `WECOM_REDIRECT_URI=https:///workspace` - `WECOM_AUTO_CREATE_USER=true` (or `false` if you require manual admin binding) +- `WECOM_MATCH_RULES=employee_id,mobile` (supported: `employee_id,mobile,email`) +- `WECOM_MATCH_OPERATOR=AND` (`AND` / `OR`) +- `WECOM_EMPLOYEE_ID_SOURCE=userid` (or `extattr:`) +- `WECOM_MOBILE_NORMALIZE=true` ## 2) Database Migration @@ -56,4 +62,3 @@ Available admin APIs: 2. WeCom login success creates an audit record. 3. Invalid/expired state is rejected. 4. Disabled user cannot login via WeCom. - diff --git a/backend/.env.production.example b/backend/.env.production.example new file mode 100644 index 00000000..bcfcb3b0 --- /dev/null +++ b/backend/.env.production.example @@ -0,0 +1,72 @@ +# hxops backend production environment template +# Usage: +# 1) Copy this file to backend/.env +# 2) Replace placeholder values +# 3) Restart backend service + +# ----------------------------------------------------------------------------- +# Core +# ----------------------------------------------------------------------------- +SECRET_KEY=replace-with-strong-random-secret +DATABASE_URL=postgresql://:@:5432/ + +# ----------------------------------------------------------------------------- +# Dify +# ----------------------------------------------------------------------------- +DIFY_API_BASE=https://api.dify.ai/v1 +DIFY_API_KEY=replace-with-default-dify-api-key + +# ----------------------------------------------------------------------------- +# Redis +# ----------------------------------------------------------------------------- +REDIS_URL=redis://:@:6379/0 + +# ----------------------------------------------------------------------------- +# Feature switches +# ----------------------------------------------------------------------------- +FEEDBACK_ENABLED=true + +# ----------------------------------------------------------------------------- +# Optional integrations +# ----------------------------------------------------------------------------- +HR_WORKFLOW_IFRAME_URL=https:// +HR_WORKFLOW_API_BASE=https:// +HR_WORKFLOW_API_KEY= + +INTEGRATION_API_BASE=https:// +INTEGRATION_API_KEY= + +# ----------------------------------------------------------------------------- +# WeCom OAuth +# ----------------------------------------------------------------------------- +WECOM_ENABLED=true +WECOM_CORP_ID=wwxxxxxxxxxxxxxxxx +WECOM_AGENT_ID=1000001 +WECOM_SECRET=replace-with-wecom-app-secret +WECOM_REDIRECT_URI=https:///workspace +# Optional: public HTTPS origin for WeCom console URLs (admin copy helper). Overrides notify base and request host when set. +WECOM_PUBLIC_BASE_URL=https:// + +# Login strategy: +# - Match existing local account first. +# - If no match, block login and require admin provision/binding. +WECOM_AUTO_CREATE_USER=false +WECOM_MATCH_RULES=employee_id,mobile +WECOM_MATCH_OPERATOR=AND + +# Employee id source options: +# - userid (default) +# - extattr: (from WeCom custom attributes) +# - any direct field name returned by user/get +WECOM_EMPLOYEE_ID_SOURCE=userid +WECOM_MOBILE_NORMALIZE=true +WECOM_CALLBACK_TOKEN= +WECOM_ENCODING_AES_KEY= +WECOM_CALLBACK_URL=https:///api/user/wecom/callback +WECOM_HOMEPAGE_URL=https:///workspace +WECOM_TRUSTED_DOMAIN= + +# WeCom notify/deeplink +WECOM_NOTIFY_ENABLED=true +WECOM_NOTIFY_BASE_URL=https:// +WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 3244bc98..102dd846 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -3,6 +3,8 @@ backend/app/__init__.py 应用工厂 """ +import logging + from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate @@ -12,6 +14,27 @@ from app.config import config db = SQLAlchemy() migrate = Migrate() +logger = logging.getLogger(__name__) + + +def _apply_persisted_settings(app: Flask) -> None: + """Pull the latest runtime-editable settings into ``app.config``. + + Reads from the database first, then ``backend/.env``. Tolerates the + common case where the table does not yet exist (fresh deploy before + ``flask db upgrade`` runs). + """ + from app.env_persistence import apply_env_settings + + try: + applied = apply_env_settings() + except Exception as exc: # pragma: no cover - defensive + logger.warning('Failed to refresh persisted settings: %s', exc) + return + for key, value in applied.items(): + app.config[key] = value + + def create_app(config_name='default'): app = Flask(__name__) app.config.from_object(config[config_name]) @@ -35,4 +58,15 @@ def create_app(config_name='default'): # 当前用户相关接口(首页、常用问题等) app.register_blueprint(user_bp, url_prefix='/api/user') + # Eagerly load persisted runtime settings so the very first request after + # a worker boot already sees the admin-saved configuration (otherwise the + # window between worker boot and the first ``before_request`` would still + # serve the defaults baked into config.py / the image). + with app.app_context(): + _apply_persisted_settings(app) + + @app.before_request + def _sync_persisted_settings(): + _apply_persisted_settings(app) + return app diff --git a/backend/app/api/admin.py b/backend/app/api/admin.py index a4b88327..4df3ad51 100644 --- a/backend/app/api/admin.py +++ b/backend/app/api/admin.py @@ -4,19 +4,206 @@ backend/app/api/admin.py 引用文件:flask, models, decorators 逻辑关系:提供 Agent 配置管理、用户与权限管理接口,供前端 Admin 控制台使用 """ -from flask import Blueprint, request, jsonify -from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig, LoginAudit +from flask import Blueprint, request, jsonify, current_app +from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig, LoginAudit, WecomNotifyAudit from app.decorators import require_admin from app.config import Config from app import db +from app.env_persistence import persist_env_settings from sqlalchemy import func, desc, inspect -from datetime import datetime +from sqlalchemy.exc import IntegrityError +from datetime import datetime, timedelta import csv import io import requests +import uuid +from app.services.wecom_notify import send_wecom_event_message admin_bp = Blueprint('admin', __name__) + +def _serialize_wecom_notify_settings(): + return { + 'enabled': bool(current_app.config.get('WECOM_NOTIFY_ENABLED', True)), + 'base_url': current_app.config.get('WECOM_NOTIFY_BASE_URL') or '', + 'events': [x for x in str(current_app.config.get('WECOM_NOTIFY_EVENTS', '')).split(',') if x], + } + + +def _serialize_wecom_system_settings(): + return { + 'enabled': bool(current_app.config.get('WECOM_ENABLED', False)), + 'corp_id': current_app.config.get('WECOM_CORP_ID') or '', + 'agent_id': str(current_app.config.get('WECOM_AGENT_ID') or ''), + 'secret': current_app.config.get('WECOM_SECRET') or '', + 'redirect_uri': current_app.config.get('WECOM_REDIRECT_URI') or '', + 'auto_create_user': bool(current_app.config.get('WECOM_AUTO_CREATE_USER', True)), + 'match_rules': current_app.config.get('WECOM_MATCH_RULES') or 'employee_id,mobile', + 'match_operator': str(current_app.config.get('WECOM_MATCH_OPERATOR') or 'AND').upper(), + 'first_login_bind_mode': str(current_app.config.get('WECOM_FIRST_LOGIN_BIND_MODE') or 'match_rules').lower(), + 'first_login_input_fields': current_app.config.get('WECOM_FIRST_LOGIN_INPUT_FIELDS') or 'employee_id,mobile,email', + 'employee_id_source': current_app.config.get('WECOM_EMPLOYEE_ID_SOURCE') or 'userid', + 'mobile_normalize': bool(current_app.config.get('WECOM_MOBILE_NORMALIZE', True)), + 'callback_token': current_app.config.get('WECOM_CALLBACK_TOKEN') or '', + 'encoding_aes_key': current_app.config.get('WECOM_ENCODING_AES_KEY') or '', + 'callback_url': current_app.config.get('WECOM_CALLBACK_URL') or '', + 'homepage_url': current_app.config.get('WECOM_HOMEPAGE_URL') or '', + 'trusted_domain': current_app.config.get('WECOM_TRUSTED_DOMAIN') or '', + 'public_base_url': current_app.config.get('WECOM_PUBLIC_BASE_URL') or '', + } + + +def _default_public_base(): + for key in ('WECOM_PUBLIC_BASE_URL', 'WECOM_NOTIFY_BASE_URL'): + configured = current_app.config.get(key) or '' + if configured: + return configured.rstrip('/') + return request.host_url.rstrip('/') + + +def _serialize_wecom_integration_manifest(): + settings = _serialize_wecom_system_settings() + public_base = _default_public_base() + callback_url = settings.get('callback_url') or f'{public_base}/api/user/wecom/callback' + homepage_url = settings.get('homepage_url') or f'{public_base}/workspace' + trusted_domain = settings.get('trusted_domain') or request.host.split(':')[0] + + return { + 'public_base_url': public_base, + 'callback_url': callback_url, + 'callback_token': settings.get('callback_token') or '', + 'encoding_aes_key': settings.get('encoding_aes_key') or '', + 'oauth_redirect_uri': settings.get('redirect_uri') or homepage_url, + 'homepage_url': homepage_url, + 'trusted_domain': trusted_domain, + 'authorize_api': f'{public_base}/api/user/wecom/authorize-url', + 'login_api': f'{public_base}/api/user/wecom/login', + } + + +def _serialize_debug_match_user(user: User) -> dict: + return { + 'id': user.id, + 'username': user.username, + 'real_name': user.real_name, + 'employee_id': user.employee_id, + 'phone_number': user.phone_number, + 'email': user.email, + 'status': user.status, + 'wecom_userid': user.wecom_userid, + 'wecom_unionid': user.wecom_unionid, + } + + +def _build_wecom_match_preview(identity: dict, rules: list[str], operator: str) -> dict: + from app.api import user as user_api + + bind_mode = user_api._get_wecom_first_login_bind_mode() + preview = { + 'bind_mode': bind_mode, + 'rules': { + 'fields': rules, + 'operator': operator, + }, + 'auto_create_user': bool(current_app.config.get('WECOM_AUTO_CREATE_USER', True)), + } + + bound_user = None + if identity.get('wecom_userid'): + bound_user = db.session.query(User).filter_by(wecom_userid=identity['wecom_userid']).first() + if not bound_user and identity.get('wecom_unionid'): + bound_user = db.session.query(User).filter_by(wecom_unionid=identity['wecom_unionid']).first() + + if bound_user: + preview['decision'] = 'already_bound' + preview['bound_user'] = _serialize_debug_match_user(bound_user) + return preview + + if bind_mode == 'input_verify': + preview['decision'] = 'input_verification_required' + preview['allowed_fields'] = user_api._get_wecom_first_login_input_fields() + return preview + + matched_users, missing_fields = user_api._find_users_by_match_rules(identity, rules, operator) + preview['missing_fields'] = missing_fields + preview['matched_users'] = [_serialize_debug_match_user(user) for user in matched_users] + + if missing_fields: + preview['decision'] = 'missing_match_fields' + elif len(matched_users) == 1: + preview['decision'] = 'matched_existing_user' + elif len(matched_users) > 1: + preview['decision'] = 'ambiguous_match' + elif preview['auto_create_user']: + preview['decision'] = 'would_auto_create_user' + else: + preview['decision'] = 'bind_required' + return preview + + +@admin_bp.route('/wecom/debug-user-by-code', methods=['POST']) +@require_admin +def debug_wecom_user_by_code(): + from app.api import user as user_api + + if not user_api._is_wecom_configured(): + return jsonify({'error': 'WeCom login is not configured'}), 400 + + data = request.get_json() or {} + code = str(data.get('code') or '').strip() + if not code: + return jsonify({'error': 'code is required'}), 400 + + access_token = user_api._get_wecom_access_token() + info_resp = requests.get( + 'https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo', + params={'access_token': access_token, 'code': code}, + timeout=8, + ) + auth_info = info_resp.json() + userid = auth_info.get('userid') or auth_info.get('UserId') + openid = auth_info.get('openid') or auth_info.get('OpenId') + + payload = { + 'auth_info': auth_info, + } + + if auth_info.get('errcode') != 0: + payload.update({ + 'error': f"WeCom auth failed: {auth_info.get('errmsg', 'unknown error')}", + 'error_code': 'WECOM_AUTH_FAILED', + }) + return jsonify(payload), 401 + + if not userid: + payload.update({ + 'error': '当前 code 对应的账号不在应用可见范围内,或不是本企业成员。', + 'error_code': 'WECOM_NOT_IN_AGENT_SCOPE', + 'openid': openid, + }) + return jsonify(payload), 401 + + user_resp = requests.get( + 'https://qyapi.weixin.qq.com/cgi-bin/user/get', + params={'access_token': access_token, 'userid': userid}, + timeout=8, + ) + wecom_user = user_resp.json() + payload['wecom_user'] = wecom_user + + if wecom_user.get('errcode') != 0: + payload.update({ + 'error': f"WeCom user fetch failed: {wecom_user.get('errmsg', 'unknown error')}", + 'error_code': 'WECOM_USER_FETCH_FAILED', + }) + return jsonify(payload), 401 + + identity = user_api._extract_wecom_identity(wecom_user) + rules, operator = user_api._get_wecom_match_config() + payload['normalized_identity'] = identity + payload['match_preview'] = _build_wecom_match_preview(identity, rules, operator) + return jsonify(payload) + @admin_bp.route('/dashboard', methods=['GET']) @require_admin def dashboard_stats(): @@ -452,7 +639,17 @@ def batch_update_permissions(): for agent in agents: if agent in user.agents: user.agents.remove(agent) - + if user.wecom_userid: + action_label = {'add': '新增', 'remove': '移除', 'set': '重置为'}[action] + agent_names = '、'.join([a.name for a in agents]) if agents else '无' + send_wecom_event_message( + event_type='permission_batch_updated', + user=user, + title='应用权限已更新', + content=f'管理员已{action_label}你的应用权限:{agent_names}', + jump_path='/workspace', + ) + db.session.commit() return jsonify({'status': 'ok', 'updated_count': len(users)}) @@ -510,7 +707,15 @@ def approve_request(id): agent = db.session.get(Agent, req.agent_id) if user and agent and agent not in user.agents: user.agents.append(agent) - + if user and user.wecom_userid: + send_wecom_event_message( + event_type='permission_request_approved', + user=user, + title='权限申请已通过', + content=f'你申请的应用权限已通过:{agent.name if agent else req.agent_id}', + jump_path='/workspace', + ) + db.session.commit() return jsonify({'status': 'ok'}) @@ -521,6 +726,16 @@ def reject_request(id): if not req: return jsonify({'error': 'Not found'}), 404 req.status = 'rejected' req.reviewed_at = datetime.utcnow() + user = db.session.get(User, req.user_id) + agent = db.session.get(Agent, req.agent_id) + if user and user.wecom_userid: + send_wecom_event_message( + event_type='permission_request_rejected', + user=user, + title='权限申请未通过', + content=f'你申请的应用权限未通过:{agent.name if agent else req.agent_id}', + jump_path='/workspace', + ) db.session.commit() return jsonify({'status': 'ok'}) @@ -805,6 +1020,119 @@ def unbind_wecom_user(): return jsonify({'status': 'ok', 'message': 'WeCom account unbound'}) +@admin_bp.route('/wecom/provision', methods=['POST']) +@require_admin +def provision_wecom_user(): + """ + Atomic admin helper to create user (optional), bind WeCom identity and assign agent permissions. + """ + data = request.get_json() or {} + create_user = bool(data.get('create_user', True)) + user_data = data.get('user') or {} + bind_data = data.get('bind') or {} + user_id = data.get('user_id') + permission_updated = False + + wecom_userid = (bind_data.get('wecom_userid') or '').strip() + wecom_unionid = (bind_data.get('wecom_unionid') or '').strip() + if not wecom_userid: + return jsonify({'error': 'bind.wecom_userid is required'}), 400 + + if create_user: + username = (user_data.get('username') or '').strip() + if not username: + return jsonify({'error': 'user.username is required when create_user=true'}), 400 + if db.session.query(User).filter_by(username=username).first(): + return jsonify({'error': 'Username exists'}), 400 + + email = (user_data.get('email') or '').strip() or None + employee_id = (user_data.get('employee_id') or '').strip() or None + phone_number = (user_data.get('phone_number') or '').strip() or None + if email and db.session.query(User).filter_by(email=email).first(): + return jsonify({'error': 'Email already exists'}), 400 + if employee_id and db.session.query(User).filter_by(employee_id=employee_id).first(): + return jsonify({'error': 'Employee ID already exists'}), 400 + if phone_number and db.session.query(User).filter_by(phone_number=phone_number).first(): + return jsonify({'error': 'Phone number already exists'}), 400 + + user = User( + username=username, + email=email, + department=user_data.get('department'), + role=user_data.get('role', 'user'), + status=user_data.get('status', 'active'), + real_name=user_data.get('real_name'), + employee_id=employee_id, + phone_number=phone_number, + ) + password = user_data.get('password') + user.set_password(password or uuid.uuid4().hex) + db.session.add(user) + db.session.flush() + binding_status = 'created' + else: + if user_id is None: + user_id = user_data.get('id') + if user_id is None: + return jsonify({'error': 'user_id is required when create_user=false'}), 400 + try: + user_id = int(user_id) + except (TypeError, ValueError): + return jsonify({'error': 'user_id must be integer'}), 400 + user = db.session.get(User, user_id) + if not user: + return jsonify({'error': 'User not found'}), 404 + binding_status = 'updated' + + dup = db.session.query(User).filter(User.wecom_userid == wecom_userid, User.id != user.id).first() + if dup: + db.session.rollback() + return jsonify({'error': f'wecom_userid already bound to user {dup.username}'}), 400 + if wecom_unionid: + dup_union = db.session.query(User).filter(User.wecom_unionid == wecom_unionid, User.id != user.id).first() + if dup_union: + db.session.rollback() + return jsonify({'error': f'wecom_unionid already bound to user {dup_union.username}'}), 400 + + user.wecom_userid = wecom_userid + if wecom_unionid: + user.wecom_unionid = wecom_unionid + + has_agent_ids = 'agent_ids' in data + if has_agent_ids: + agent_ids = data.get('agent_ids', []) + if not isinstance(agent_ids, list): + db.session.rollback() + return jsonify({'error': 'agent_ids must be array'}), 400 + if agent_ids: + try: + unique_ids = sorted({int(i) for i in agent_ids}) + except (TypeError, ValueError): + db.session.rollback() + return jsonify({'error': 'agent_ids must be integer array'}), 400 + agents = db.session.query(Agent).filter(Agent.id.in_(unique_ids)).all() + if len(agents) != len(unique_ids): + db.session.rollback() + return jsonify({'error': 'Some agent_ids are invalid'}), 400 + user.agents = agents + else: + user.agents = [] + permission_updated = True + + try: + db.session.commit() + except IntegrityError: + db.session.rollback() + return jsonify({'error': 'Provision failed due to data uniqueness conflict'}), 400 + + return jsonify({ + 'status': 'ok', + 'user_id': user.id, + 'binding': binding_status, + 'permission_updated': permission_updated, + }), 201 if create_user else 200 + + @admin_bp.route('/wecom/login-audits', methods=['GET']) @require_admin def get_wecom_login_audits(): @@ -834,9 +1162,138 @@ def get_wecom_login_audits(): 'source': r.source, 'status': r.status, 'reason': r.reason, + 'error_code': r.error_code, + 'match_rules': r.match_rules, + 'match_operator': r.match_operator, + 'match_result': r.match_result, 'wecom_userid': r.wecom_userid, 'ip': r.ip, 'user_agent': r.user_agent, 'created_at': r.created_at.isoformat() if r.created_at else None, } for r in rows ]) + + +@admin_bp.route('/wecom/notify-settings', methods=['GET', 'PUT']) +@require_admin +def wecom_notify_settings(): + if request.method == 'GET': + return jsonify(_serialize_wecom_notify_settings()) + + data = request.get_json() or {} + updates = {} + if 'enabled' in data: + updates['WECOM_NOTIFY_ENABLED'] = bool(data.get('enabled')) + if 'base_url' in data: + updates['WECOM_NOTIFY_BASE_URL'] = str(data.get('base_url') or '').strip() + if 'events' in data: + events = data.get('events') or [] + if isinstance(events, list): + updates['WECOM_NOTIFY_EVENTS'] = ','.join([str(x).strip() for x in events if str(x).strip()]) + + for key, value in updates.items(): + current_app.config[key] = value + persist_env_settings(updates) + + return jsonify({'status': 'ok', 'settings': _serialize_wecom_notify_settings()}) + + +@admin_bp.route('/wecom/system-settings', methods=['GET', 'PUT']) +@require_admin +def wecom_system_settings(): + if request.method == 'GET': + return jsonify(_serialize_wecom_system_settings()) + + data = request.get_json() or {} + bool_keys = { + 'enabled': 'WECOM_ENABLED', + 'auto_create_user': 'WECOM_AUTO_CREATE_USER', + 'mobile_normalize': 'WECOM_MOBILE_NORMALIZE', + } + str_keys = { + 'corp_id': 'WECOM_CORP_ID', + 'agent_id': 'WECOM_AGENT_ID', + 'secret': 'WECOM_SECRET', + 'redirect_uri': 'WECOM_REDIRECT_URI', + 'match_rules': 'WECOM_MATCH_RULES', + 'match_operator': 'WECOM_MATCH_OPERATOR', + 'first_login_bind_mode': 'WECOM_FIRST_LOGIN_BIND_MODE', + 'first_login_input_fields': 'WECOM_FIRST_LOGIN_INPUT_FIELDS', + 'employee_id_source': 'WECOM_EMPLOYEE_ID_SOURCE', + 'callback_token': 'WECOM_CALLBACK_TOKEN', + 'encoding_aes_key': 'WECOM_ENCODING_AES_KEY', + 'callback_url': 'WECOM_CALLBACK_URL', + 'homepage_url': 'WECOM_HOMEPAGE_URL', + 'trusted_domain': 'WECOM_TRUSTED_DOMAIN', + 'public_base_url': 'WECOM_PUBLIC_BASE_URL', + } + + updates = {} + for req_key, cfg_key in bool_keys.items(): + if req_key in data: + updates[cfg_key] = bool(data.get(req_key)) + for req_key, cfg_key in str_keys.items(): + if req_key in data: + updates[cfg_key] = str(data.get(req_key) or '').strip() + + for key, value in updates.items(): + current_app.config[key] = value + + if current_app.config.get('WECOM_MATCH_OPERATOR') not in {'AND', 'OR'}: + current_app.config['WECOM_MATCH_OPERATOR'] = 'AND' + updates['WECOM_MATCH_OPERATOR'] = 'AND' + + if current_app.config.get('WECOM_FIRST_LOGIN_BIND_MODE') not in {'match_rules', 'input_verify'}: + current_app.config['WECOM_FIRST_LOGIN_BIND_MODE'] = 'match_rules' + updates['WECOM_FIRST_LOGIN_BIND_MODE'] = 'match_rules' + + persist_env_settings(updates) + + return jsonify({'status': 'ok', 'settings': _serialize_wecom_system_settings()}) + + +@admin_bp.route('/wecom/integration-manifest', methods=['GET']) +@require_admin +def wecom_integration_manifest(): + return jsonify(_serialize_wecom_integration_manifest()) + + +@admin_bp.route('/wecom/notify-metrics', methods=['GET']) +@require_admin +def wecom_notify_metrics(): + now = datetime.utcnow() + from_time = now - timedelta(days=30) + total = db.session.query(func.count(WecomNotifyAudit.id)).filter(WecomNotifyAudit.created_at >= from_time).scalar() or 0 + sent = db.session.query(func.count(WecomNotifyAudit.id)).filter( + WecomNotifyAudit.created_at >= from_time, + WecomNotifyAudit.status == 'sent' + ).scalar() or 0 + opened_24h = db.session.query(func.count(WecomNotifyAudit.id)).filter( + WecomNotifyAudit.created_at >= from_time, + WecomNotifyAudit.opened_at.isnot(None), + ).scalar() or 0 + + by_event_rows = db.session.query( + WecomNotifyAudit.event_type, + WecomNotifyAudit.status, + func.count(WecomNotifyAudit.id) + ).filter(WecomNotifyAudit.created_at >= from_time).group_by( + WecomNotifyAudit.event_type, + WecomNotifyAudit.status + ).all() + by_event = {} + for event_type, status, cnt in by_event_rows: + if event_type not in by_event: + by_event[event_type] = {'sent': 0, 'failed': 0} + by_event[event_type][status] = int(cnt) + + return jsonify({ + 'window_days': 30, + 'total': int(total), + 'sent': int(sent), + 'failed': int(total - sent), + 'send_success_rate': round((sent / total) * 100, 2) if total else 0, + 'opened_24h': int(opened_24h), + 'opened_24h_rate': round((opened_24h / sent) * 100, 2) if sent else 0, + 'by_event': by_event, + }) diff --git a/backend/app/api/user.py b/backend/app/api/user.py index cc2e5a99..d5db2f6f 100644 --- a/backend/app/api/user.py +++ b/backend/app/api/user.py @@ -1,11 +1,15 @@ -from flask import Blueprint, request, jsonify, current_app, url_for +from flask import Blueprint, request, jsonify, current_app from app import db -from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, Announcement, LoginAudit +from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, Announcement, LoginAudit, WecomCallbackAudit +from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message +from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field from sqlalchemy.exc import IntegrityError, OperationalError +from sqlalchemy import and_, or_, inspect, insert from datetime import datetime, timedelta import uuid import requests from urllib.parse import quote +import re user_bp = Blueprint('user', __name__) @@ -14,6 +18,34 @@ _WECOM_ACCESS_TOKEN_CACHE = { 'expires_at': None, } _WECOM_STATE_CACHE = {} +_WECOM_BIND_SESSION_CACHE = {} +_ALLOWED_WECOM_MATCH_FIELDS = {'employee_id', 'mobile', 'email'} +_LOGIN_AUDIT_COLUMNS_CACHE = None + + +def _is_users_pk_sequence_error(exc: Exception) -> bool: + message = str(exc) + return 'null value in column "id"' in message and 'relation "users"' in message + + +class WeComLoginError(Exception): + def __init__(self, error: str, error_code: str, status_code: int, reason: str = None, extra: dict = None): + super().__init__(error) + self.error = error + self.error_code = error_code + self.status_code = status_code + self.reason = reason + self.extra = extra or {} + + def to_response(self): + payload = { + 'error': self.error, + 'error_code': self.error_code, + } + if self.reason: + payload['reason'] = self.reason + payload.update(self.extra) + return payload, self.status_code def _write_login_audit( source: str, @@ -21,24 +53,74 @@ def _write_login_audit( user: User = None, username: str = None, reason: str = None, - wecom_userid: str = None + wecom_userid: str = None, + error_code: str = None, + match_rules: list = None, + match_operator: str = None, + match_result: str = None, ): + payload = { + 'user_id': user.id if user else None, + 'username': username or (user.username if user else None), + 'source': source, + 'status': status, + 'reason': reason, + 'error_code': error_code, + 'match_rules': ','.join(match_rules) if isinstance(match_rules, list) else match_rules, + 'match_operator': match_operator, + 'match_result': match_result, + 'wecom_userid': wecom_userid, + 'ip': request.headers.get('X-Forwarded-For', request.remote_addr), + 'user_agent': (request.user_agent.string or '')[:255], + 'created_at': datetime.utcnow(), + } + try: - audit = LoginAudit( - user_id=user.id if user else None, - username=username or (user.username if user else None), - source=source, - status=status, - reason=reason, - wecom_userid=wecom_userid, - ip=request.headers.get('X-Forwarded-For', request.remote_addr), - user_agent=(request.user_agent.string or '')[:255] - ) - db.session.add(audit) + supported_columns = _get_login_audit_supported_columns() + if not supported_columns: + return + + filtered_payload = { + key: value for key, value in payload.items() + if key in supported_columns + } + if not filtered_payload: + return + + _execute_login_audit_insert(filtered_payload) except Exception: # Do not break auth flow because of audit logging. pass + +def _get_login_audit_supported_columns(): + global _LOGIN_AUDIT_COLUMNS_CACHE + + if _LOGIN_AUDIT_COLUMNS_CACHE is not None: + return _LOGIN_AUDIT_COLUMNS_CACHE + + try: + columns = { + column['name'] + for column in inspect(db.engine).get_columns(LoginAudit.__tablename__) + } + except Exception: + columns = set() + + _LOGIN_AUDIT_COLUMNS_CACHE = columns + return columns + + +def _execute_login_audit_insert(payload: dict): + nested = db.session.begin_nested() + try: + db.session.execute(insert(LoginAudit.__table__).values(**payload)) + db.session.flush() + nested.commit() + except Exception: + nested.rollback() + raise + def _get_current_user(): """ Helper to get current user from headers @@ -75,6 +157,117 @@ def _consume_wecom_state(state: str): exp = _WECOM_STATE_CACHE.pop(state, None) return bool(exp and exp > datetime.utcnow()) + +def _cleanup_wecom_bind_session_cache(): + now = datetime.utcnow() + expired = [ + key for key, item in _WECOM_BIND_SESSION_CACHE.items() + if not isinstance(item, dict) or not item.get('expires_at') or item['expires_at'] < now + ] + for key in expired: + _WECOM_BIND_SESSION_CACHE.pop(key, None) + + +def _issue_wecom_bind_session(identity: dict): + _cleanup_wecom_bind_session_cache() + token = f"hxops_wecom_bind_{uuid.uuid4().hex}" + _WECOM_BIND_SESSION_CACHE[token] = { + 'expires_at': datetime.utcnow() + timedelta(minutes=10), + 'identity': dict(identity or {}), + } + return token + + +def _get_wecom_bind_session(token: str): + if not token: + return None + _cleanup_wecom_bind_session_cache() + item = _WECOM_BIND_SESSION_CACHE.get(token) + if not isinstance(item, dict): + return None + expires_at = item.get('expires_at') + if not expires_at or expires_at < datetime.utcnow(): + _WECOM_BIND_SESSION_CACHE.pop(token, None) + return None + identity = item.get('identity') + return identity if isinstance(identity, dict) else None + + +def _consume_wecom_bind_session(token: str): + identity = _get_wecom_bind_session(token) + if identity is None: + return None + _WECOM_BIND_SESSION_CACHE.pop(token, None) + return identity + + +def _parse_wecom_field_list(raw_value, default_fields: list[str]): + if isinstance(raw_value, str): + pieces = [item.strip().lower() for item in raw_value.split(',')] + elif isinstance(raw_value, (list, tuple)): + pieces = [str(item).strip().lower() for item in raw_value] + else: + pieces = [] + + result = [] + for piece in pieces: + if piece in _ALLOWED_WECOM_MATCH_FIELDS and piece not in result: + result.append(piece) + return result or list(default_fields) + + +def _verify_wecom_msg_signature(msg_signature: str, token: str, timestamp: str, nonce: str, encrypt: str) -> bool: + if not msg_signature or not token or not encrypt: + return False + expected = sha1_hex([token, str(timestamp or ''), str(nonce or ''), encrypt]) + return expected == msg_signature + + +def _extract_xml_field(xml_text: str, tag: str): + if not xml_text: + return None + m = re.search(rf'<{tag}>', xml_text, re.DOTALL) + if m: + return m.group(1).strip() + m2 = re.search(rf'<{tag}>(.*?)', xml_text, re.DOTALL) + if m2: + return m2.group(1).strip() + return None + + +def _persist_wecom_callback_audit( + *, + msg_signature, + timestamp, + nonce, + encrypt_raw, + decrypted_xml=None, + msg_type=None, + event=None, + from_user=None, + agent_id=None, + msg_id=None, + error_message=None, +): + try: + row = WecomCallbackAudit( + msg_signature=msg_signature, + timestamp=timestamp, + nonce=nonce, + encrypt_raw=encrypt_raw, + decrypted_xml=decrypted_xml, + msg_type=msg_type, + event=event, + from_user=from_user, + agent_id=agent_id, + msg_id=msg_id, + error_message=error_message, + ) + db.session.add(row) + db.session.commit() + except Exception: + db.session.rollback() + def _get_wecom_access_token(): now = datetime.utcnow() token = _WECOM_ACCESS_TOKEN_CACHE.get('token') @@ -96,73 +289,349 @@ def _get_wecom_access_token(): _WECOM_ACCESS_TOKEN_CACHE['expires_at'] = now + timedelta(seconds=max(int(data.get('expires_in', 7200)) - 120, 60)) return data['access_token'] -def _build_login_payload(user: User, source: str = 'password'): - return { +def _build_login_payload(user: User, source: str = 'password', bind_status: str = None): + payload = { 'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'source': source, } + if bind_status: + payload['bind_status'] = bind_status + return payload -def _sync_or_create_user_from_wecom(wecom_user: dict) -> User: - userid = wecom_user.get('userid') - email = wecom_user.get('email') - mobile = wecom_user.get('mobile') - unionid = wecom_user.get('unionid') - name = wecom_user.get('name') or userid or 'wecom_user' - user = None - if userid: - user = db.session.query(User).filter_by(wecom_userid=userid).first() - if not user and email: - user = db.session.query(User).filter_by(email=email).first() - if not user and mobile: - user = db.session.query(User).filter_by(phone_number=mobile).first() +def _clean_str(value): + if value is None: + return None + if isinstance(value, str): + value = value.strip() + return value or None + return str(value).strip() or None - if user: - if userid and not user.wecom_userid: - user.wecom_userid = userid - if unionid and not user.wecom_unionid: - user.wecom_unionid = unionid - if name and not user.real_name: - user.real_name = name - if email and not user.email: - user.email = email - if mobile and not user.phone_number: - user.phone_number = mobile - return user - if not current_app.config.get('WECOM_AUTO_CREATE_USER', True): - raise PermissionError('No linked account found. Contact admin to bind WeCom account.') +def _normalize_mobile(mobile: str): + mobile = _clean_str(mobile) + if not mobile: + return None + digits = re.sub(r'\D', '', mobile) + if not digits: + return mobile + if digits.startswith('0086'): + digits = digits[4:] + elif digits.startswith('86') and len(digits) > 11: + digits = digits[2:] + return digits - # Ensure unique username for auto-created user - base_username = (userid or email or mobile or f"wecom_{uuid.uuid4().hex[:8]}").replace('@', '_') + +def _extract_wecom_extattr_value(wecom_user: dict, key: str): + extattr = wecom_user.get('extattr') or {} + attrs = extattr.get('attrs') if isinstance(extattr, dict) else None + if not isinstance(attrs, list): + return None + for attr in attrs: + if not isinstance(attr, dict): + continue + if _clean_str(attr.get('name')) != key: + continue + raw = attr.get('value') + if isinstance(raw, dict): + # Some WeCom payloads wrap values in nested shape. + raw = raw.get('text') or raw.get('web') or raw.get('value') + return _clean_str(raw) + return None + + +def _get_wecom_match_config(): + raw_rules = current_app.config.get('WECOM_MATCH_RULES', 'employee_id,mobile') + rules = _parse_wecom_field_list(raw_rules, ['employee_id', 'mobile']) + + operator = str(current_app.config.get('WECOM_MATCH_OPERATOR', 'AND')).upper() + if operator not in {'AND', 'OR'}: + operator = 'AND' + return rules, operator + + +def _get_wecom_first_login_bind_mode(): + mode = _clean_str(current_app.config.get('WECOM_FIRST_LOGIN_BIND_MODE')) or 'match_rules' + mode = mode.lower() + if mode not in {'match_rules', 'input_verify'}: + mode = 'match_rules' + return mode + + +def _get_wecom_first_login_input_fields(): + raw_fields = current_app.config.get('WECOM_FIRST_LOGIN_INPUT_FIELDS', 'employee_id,mobile,email') + return _parse_wecom_field_list(raw_fields, ['employee_id', 'mobile', 'email']) + + +def _extract_wecom_identity(wecom_user: dict): + userid = _clean_str(wecom_user.get('userid')) + unionid = _clean_str(wecom_user.get('unionid')) + email = _clean_str(wecom_user.get('email')) + mobile_raw = _clean_str(wecom_user.get('mobile')) + normalize_mobile = bool(current_app.config.get('WECOM_MOBILE_NORMALIZE', True)) + mobile = _normalize_mobile(mobile_raw) if normalize_mobile else mobile_raw + + employee_id_source = _clean_str(current_app.config.get('WECOM_EMPLOYEE_ID_SOURCE')) or 'userid' + if employee_id_source == 'userid': + employee_id = userid + elif employee_id_source.startswith('extattr:'): + employee_id = _extract_wecom_extattr_value(wecom_user, employee_id_source.split(':', 1)[1]) + else: + employee_id = _clean_str(wecom_user.get(employee_id_source)) + + return { + 'wecom_userid': userid, + 'wecom_unionid': unionid, + 'name': _clean_str(wecom_user.get('name')) or userid or 'wecom_user', + 'email': email, + 'mobile': mobile, + 'mobile_raw': mobile_raw, + 'employee_id': employee_id, + } + + +def _mobile_candidates(identity: dict): + values = [] + for item in [identity.get('mobile'), identity.get('mobile_raw')]: + item = _clean_str(item) + if item and item not in values: + values.append(item) + return values + + +def _find_users_by_input_field(field: str, value): + field = _clean_str(field) + if field not in _ALLOWED_WECOM_MATCH_FIELDS: + return [], 'invalid_field' + + if field == 'employee_id': + needle = _clean_str(value) + if not needle: + return [], 'employee_id' + return db.session.query(User).filter(User.employee_id == needle).all(), None + + if field == 'email': + needle = _clean_str(value) + if not needle: + return [], 'email' + return db.session.query(User).filter(User.email == needle).all(), None + + if field == 'mobile': + raw_mobile = _clean_str(value) + normalized_mobile = _normalize_mobile(raw_mobile) + candidates = [] + for item in [normalized_mobile, raw_mobile]: + item = _clean_str(item) + if item and item not in candidates: + candidates.append(item) + if not candidates: + return [], 'mobile' + return db.session.query(User).filter(User.phone_number.in_(candidates)).all(), None + + return [], 'invalid_field' + + +def _find_users_by_match_rules(identity: dict, rules: list, operator: str): + filters = [] + missing = [] + for rule in rules: + if rule == 'employee_id': + employee_id = _clean_str(identity.get('employee_id')) + if not employee_id: + missing.append('employee_id') + else: + filters.append(User.employee_id == employee_id) + elif rule == 'mobile': + candidates = _mobile_candidates(identity) + if not candidates: + missing.append('mobile') + else: + filters.append(User.phone_number.in_(candidates)) + elif rule == 'email': + email = _clean_str(identity.get('email')) + if not email: + missing.append('email') + else: + filters.append(User.email == email) + + if missing: + return [], missing + if not filters: + return [], ['match_rules'] + + clause = and_(*filters) if operator == 'AND' else or_(*filters) + users = db.session.query(User).filter(clause).all() + return users, [] + + +def _assert_wecom_binding_not_occupied(user: User, identity: dict): + wecom_userid = identity.get('wecom_userid') + wecom_unionid = identity.get('wecom_unionid') + + if wecom_userid: + dup = db.session.query(User).filter(User.wecom_userid == wecom_userid, User.id != user.id).first() + if dup: + raise WeComLoginError( + error=f'Current WeCom account has been bound to user: {dup.username}', + error_code='WECOM_BIND_CONFLICT', + status_code=409, + reason='bind_conflict', + ) + if wecom_unionid: + dup_union = db.session.query(User).filter(User.wecom_unionid == wecom_unionid, User.id != user.id).first() + if dup_union: + raise WeComLoginError( + error=f'Current WeCom unionid has been bound to user: {dup_union.username}', + error_code='WECOM_BIND_CONFLICT', + status_code=409, + reason='bind_conflict', + ) + + +def _sync_user_from_wecom_identity(user: User, identity: dict): + _assert_wecom_binding_not_occupied(user, identity) + + if identity.get('wecom_userid'): + user.wecom_userid = identity['wecom_userid'] + if identity.get('wecom_unionid') and not user.wecom_unionid: + user.wecom_unionid = identity['wecom_unionid'] + if identity.get('name') and not user.real_name: + user.real_name = identity['name'] + if identity.get('email') and not user.email: + dup_email = db.session.query(User).filter(User.email == identity['email'], User.id != user.id).first() + if not dup_email: + user.email = identity['email'] + if identity.get('mobile') and not user.phone_number: + candidates = _mobile_candidates(identity) + dup_mobile = db.session.query(User).filter(User.phone_number.in_(candidates), User.id != user.id).first() + if not dup_mobile: + user.phone_number = identity['mobile'] + if identity.get('employee_id') and not user.employee_id: + dup_employee = db.session.query(User).filter(User.employee_id == identity['employee_id'], User.id != user.id).first() + if not dup_employee: + user.employee_id = identity['employee_id'] + + +def _create_user_from_wecom_identity(identity: dict) -> User: + base_username = (identity.get('wecom_userid') or identity.get('email') or identity.get('mobile') or f"wecom_{uuid.uuid4().hex[:8]}").replace('@', '_') candidate = base_username suffix = 1 while db.session.query(User).filter_by(username=candidate).first(): candidate = f"{base_username}_{suffix}" suffix += 1 - safe_email = email or f"{candidate}@wecom.local" + safe_email = identity.get('email') or f"{candidate}@wecom.local" if db.session.query(User).filter_by(email=safe_email).first(): safe_email = f"{candidate}_{uuid.uuid4().hex[:6]}@wecom.local" + employee_id = identity.get('employee_id') + if employee_id and db.session.query(User).filter_by(employee_id=employee_id).first(): + employee_id = None + + phone_number = identity.get('mobile') + if phone_number: + candidates = _mobile_candidates(identity) + dup_mobile = db.session.query(User).filter(User.phone_number.in_(candidates)).first() + if dup_mobile: + phone_number = None + user = User( username=candidate, email=safe_email, role='user', status='active', - real_name=name, - phone_number=mobile, - wecom_userid=userid, - wecom_unionid=unionid, + real_name=identity.get('name'), + employee_id=employee_id, + phone_number=phone_number, + wecom_userid=identity.get('wecom_userid'), + wecom_unionid=identity.get('wecom_unionid'), ) - # Set random password to make local password login explicit. user.set_password(uuid.uuid4().hex) db.session.add(user) return user + +def _issue_wecom_input_bind_prompt(identity: dict): + allowed_fields = _get_wecom_first_login_input_fields() + binding_token = _issue_wecom_bind_session(identity) + raise WeComLoginError( + error='First WeCom login requires verification input to bind a local account.', + error_code='WECOM_BIND_INPUT_REQUIRED', + status_code=409, + reason='input_bind_required', + extra={ + 'binding_token': binding_token, + 'allowed_fields': allowed_fields, + 'wecom_name': identity.get('name'), + 'wecom_userid': identity.get('wecom_userid'), + }, + ) + +def _sync_or_create_user_from_wecom(wecom_user: dict): + identity = _extract_wecom_identity(wecom_user) + rules, operator = _get_wecom_match_config() + rule_info = {'operator': operator, 'fields': rules} + bind_mode = _get_wecom_first_login_bind_mode() + + user = None + if identity.get('wecom_userid'): + user = db.session.query(User).filter_by(wecom_userid=identity['wecom_userid']).first() + if user: + _sync_user_from_wecom_identity(user, identity) + return user, 'already_bound', rule_info + + if bind_mode == 'input_verify': + _issue_wecom_input_bind_prompt(identity) + + matched_users, missing_fields = _find_users_by_match_rules(identity, rules, operator) + + if missing_fields: + missing_field = missing_fields[0] + raise WeComLoginError( + error=f"Required match attribute missing: {missing_field}", + error_code='WECOM_MATCH_ATTR_MISSING', + status_code=422, + reason=f'missing_attr:{missing_field}', + extra={ + 'missing_field': missing_field, + 'match_rules': rule_info, + }, + ) + + if len(matched_users) == 1: + user = matched_users[0] + _sync_user_from_wecom_identity(user, identity) + return user, 'matched_and_bound', rule_info + + if len(matched_users) > 1: + raise WeComLoginError( + error='Multiple local users matched', + error_code='WECOM_MATCH_AMBIGUOUS', + status_code=409, + reason='ambiguous_match', + extra={ + 'candidate_count': len(matched_users), + 'match_rules': rule_info, + }, + ) + + if not current_app.config.get('WECOM_AUTO_CREATE_USER', True): + raise WeComLoginError( + error='No linked account found. Contact admin to bind WeCom account.', + error_code='WECOM_BIND_REQUIRED', + status_code=403, + reason='bind_required', + extra={ + 'match_rules': rule_info, + }, + ) + + user = _create_user_from_wecom_identity(identity) + return user, 'auto_created', rule_info + @user_bp.route('/register', methods=['POST']) def register(): """ @@ -283,6 +752,7 @@ def wecom_login(): db.session.commit() return jsonify({'error': 'Invalid or expired WeCom state'}), 400 + wecom_userid_for_audit = None try: access_token = _get_wecom_access_token() info_resp = requests.get( @@ -291,41 +761,371 @@ def wecom_login(): timeout=8 ) info = info_resp.json() - if info.get('errcode') != 0 or not info.get('UserId'): + # /cgi-bin/auth/getuserinfo 新接口返回小写 userid;为兼容历史 mock / 旧接口同时 + # 兼容大写 UserId。企业成员返回 userid,外部联系人/非可见范围成员只返回 openid。 + wecom_userid_value = info.get('userid') or info.get('UserId') + wecom_openid_value = info.get('openid') or info.get('OpenId') + wecom_userid_for_audit = wecom_userid_value + if info.get('errcode') != 0: _write_login_audit('wecom', 'failed', reason=f"auth_failed:{info.get('errmsg')}") db.session.commit() return jsonify({'error': f"WeCom auth failed: {info.get('errmsg', 'unknown error')}"}), 401 + if not wecom_userid_value: + # errcode=0 但没有 userid:登录者不在该自建应用「可见范围」内, + # 或不是本企业成员(外部联系人 / openid)。给出明确的可执行提示。 + _write_login_audit( + 'wecom', + 'failed', + reason=f"not_in_agent_scope:openid={wecom_openid_value or ''}", + error_code='WECOM_NOT_IN_AGENT_SCOPE', + ) + db.session.commit() + return jsonify({ + 'error': '当前企业微信账号未授权登录该应用:账号不在自建应用的可见范围内,或不是本企业成员。请管理员到「企业微信后台 → 应用管理 → 该应用 → 可见范围」中加入该成员所在的部门或个人。', + 'error_code': 'WECOM_NOT_IN_AGENT_SCOPE', + }), 401 user_resp = requests.get( 'https://qyapi.weixin.qq.com/cgi-bin/user/get', - params={'access_token': access_token, 'userid': info['UserId']}, + params={'access_token': access_token, 'userid': wecom_userid_value}, timeout=8 ) wecom_user = user_resp.json() + wecom_userid_for_audit = wecom_user.get('userid') or wecom_userid_for_audit if wecom_user.get('errcode') != 0: - _write_login_audit('wecom', 'failed', reason=f"user_fetch_failed:{wecom_user.get('errmsg')}", wecom_userid=info.get('UserId')) + _write_login_audit('wecom', 'failed', reason=f"user_fetch_failed:{wecom_user.get('errmsg')}", wecom_userid=wecom_userid_value) db.session.commit() return jsonify({'error': f"WeCom user fetch failed: {wecom_user.get('errmsg', 'unknown error')}"}), 401 - user = _sync_or_create_user_from_wecom(wecom_user) + user, bind_status, rule_info = _sync_or_create_user_from_wecom(wecom_user) if user.status != 'active': _write_login_audit('wecom', 'failed', user=user, reason='account_disabled', wecom_userid=wecom_user.get('userid')) db.session.commit() return jsonify({'error': 'Account is disabled'}), 403 - _write_login_audit('wecom', 'success', user=user, wecom_userid=wecom_user.get('userid')) + _write_login_audit( + 'wecom', + 'success', + user=user, + wecom_userid=wecom_user.get('userid'), + match_rules=rule_info.get('fields'), + match_operator=rule_info.get('operator'), + match_result=bind_status, + ) db.session.commit() - return jsonify(_build_login_payload(user, 'wecom')) - except PermissionError as e: + return jsonify(_build_login_payload(user, 'wecom', bind_status=bind_status)) + except WeComLoginError as e: db.session.rollback() - _write_login_audit('wecom', 'failed', reason='bind_required') + _write_login_audit( + 'wecom', + 'failed', + reason=e.reason or 'wecom_login_error', + wecom_userid=wecom_userid_for_audit, + error_code=e.error_code, + ) db.session.commit() - return jsonify({'error': str(e)}), 403 + payload, status_code = e.to_response() + return jsonify(payload), status_code except Exception as e: db.session.rollback() + if _is_users_pk_sequence_error(e): + _write_login_audit( + 'wecom', + 'failed', + reason='db_sequence_misconfig', + wecom_userid=wecom_userid_for_audit, + error_code='DB_SEQUENCE_MISCONFIG', + ) + db.session.commit() + return jsonify({ + 'error': '数据库主键自增配置异常,当前环境缺少 users.id 的自动序列。请执行数据库迁移后重试。', + 'error_code': 'DB_SEQUENCE_MISCONFIG', + }), 500 _write_login_audit('wecom', 'failed', reason=f'exception:{str(e)[:160]}') db.session.commit() return jsonify({'error': f'WeCom login failed: {str(e)}'}), 500 + +@user_bp.route('/wecom/complete-bind', methods=['POST']) +def wecom_complete_bind(): + if not _is_wecom_configured(): + return jsonify({'error': 'WeCom login is not configured'}), 400 + + data = request.get_json() or {} + binding_token = _clean_str(data.get('binding_token')) + field = _clean_str(data.get('field')) + value = data.get('value') + + identity = _get_wecom_bind_session(binding_token) + if not identity: + return jsonify({ + 'error': 'WeCom binding session expired. Please restart WeCom login.', + 'error_code': 'WECOM_BIND_SESSION_EXPIRED', + }), 400 + + allowed_fields = _get_wecom_first_login_input_fields() + if field not in allowed_fields: + return jsonify({ + 'error': 'Selected bind field is not allowed', + 'error_code': 'WECOM_BIND_FIELD_NOT_ALLOWED', + 'allowed_fields': allowed_fields, + }), 400 + + matched_users, missing_field = _find_users_by_input_field(field, value) + if missing_field: + return jsonify({ + 'error': f'{field} is required', + 'error_code': 'WECOM_BIND_INPUT_VALUE_REQUIRED', + 'field': field, + }), 400 + + if len(matched_users) == 0: + _write_login_audit( + 'wecom', + 'failed', + reason=f'input_bind_not_found:{field}', + wecom_userid=identity.get('wecom_userid'), + error_code='WECOM_BIND_INPUT_NOT_FOUND', + match_rules=[field], + match_operator='AND', + ) + db.session.commit() + return jsonify({ + 'error': 'No local account matched the verification value.', + 'error_code': 'WECOM_BIND_INPUT_NOT_FOUND', + 'field': field, + }), 404 + + if len(matched_users) > 1: + _write_login_audit( + 'wecom', + 'failed', + reason=f'input_bind_ambiguous:{field}', + wecom_userid=identity.get('wecom_userid'), + error_code='WECOM_BIND_INPUT_AMBIGUOUS', + match_rules=[field], + match_operator='AND', + ) + db.session.commit() + return jsonify({ + 'error': 'Multiple local accounts matched the verification value.', + 'error_code': 'WECOM_BIND_INPUT_AMBIGUOUS', + 'field': field, + 'candidate_count': len(matched_users), + }), 409 + + user = matched_users[0] + if user.status != 'active': + _write_login_audit( + 'wecom', + 'failed', + user=user, + reason='account_disabled', + wecom_userid=identity.get('wecom_userid'), + error_code='WECOM_ACCOUNT_DISABLED', + match_rules=[field], + match_operator='AND', + ) + db.session.commit() + return jsonify({'error': 'Account is disabled'}), 403 + + try: + _sync_user_from_wecom_identity(user, identity) + _write_login_audit( + 'wecom', + 'success', + user=user, + wecom_userid=identity.get('wecom_userid'), + match_rules=[field], + match_operator='AND', + match_result='input_verified_and_bound', + ) + db.session.commit() + _WECOM_BIND_SESSION_CACHE.pop(binding_token, None) + return jsonify(_build_login_payload(user, 'wecom', bind_status='input_verified_and_bound')) + except WeComLoginError as e: + db.session.rollback() + _write_login_audit( + 'wecom', + 'failed', + user=user, + reason=e.reason or 'wecom_input_bind_error', + wecom_userid=identity.get('wecom_userid'), + error_code=e.error_code, + match_rules=[field], + match_operator='AND', + ) + db.session.commit() + payload, status_code = e.to_response() + return jsonify(payload), status_code + except Exception as e: + db.session.rollback() + _write_login_audit( + 'wecom', + 'failed', + user=user, + reason=f'exception:{str(e)[:160]}', + wecom_userid=identity.get('wecom_userid'), + error_code='WECOM_BIND_INPUT_EXCEPTION', + match_rules=[field], + match_operator='AND', + ) + db.session.commit() + return jsonify({'error': f'WeCom bind failed: {str(e)}'}), 500 + + +@user_bp.route('/wecom/deeplink-opened', methods=['POST']) +def mark_wecom_deeplink_opened(): + user = _get_current_user() + if not user: + return jsonify({'error': 'Unauthorized'}), 401 + + data = request.get_json() or {} + trace_id = _clean_str(data.get('trace_id')) + if not trace_id: + return jsonify({'error': 'trace_id is required'}), 400 + + ok = mark_wecom_message_opened(trace_id) + if not ok: + return jsonify({'error': 'trace_id not found'}), 404 + + db.session.commit() + return jsonify({'status': 'ok'}) + + +@user_bp.route('/wecom/task-complete', methods=['POST']) +def wecom_task_complete(): + """ + Lightweight endpoint for sending task completion WeCom message. + Can be called by frontend after long-running task is done. + """ + user = _get_current_user() + if not user: + return jsonify({'error': 'Unauthorized'}), 401 + + data = request.get_json() or {} + title = _clean_str(data.get('title')) or 'AI 任务已完成' + content = _clean_str(data.get('content')) or '你发起的 AI 任务已完成,点击查看详情。' + agent_id = data.get('agent_id') + + jump_path = '/workspace' + jump_params = {} + if agent_id: + jump_path = f'/chat/{int(agent_id)}' + + result = send_wecom_event_message( + event_type='task_completed', + user=user, + title=title, + content=content, + jump_path=jump_path, + jump_params=jump_params, + ) + db.session.commit() + return jsonify(result), 200 if result.get('ok') else 202 + + +@user_bp.route('/wecom/callback', methods=['GET', 'POST']) +def wecom_callback(): + """ + Enterprise WeCom callback endpoint. + Supports URL verification and basic signature check for incoming events. + """ + msg_signature = request.args.get('msg_signature') or request.args.get('signature') + timestamp = request.args.get('timestamp', '') + nonce = request.args.get('nonce', '') + token = current_app.config.get('WECOM_CALLBACK_TOKEN') or '' + aes_key = current_app.config.get('WECOM_ENCODING_AES_KEY') or '' + corp_id = current_app.config.get('WECOM_CORP_ID') or '' + + if request.method == 'GET': + echostr = request.args.get('echostr', '') or '' + if not token: + return jsonify({'error': 'callback token not configured'}), 500 + if aes_key: + if not _verify_wecom_msg_signature(msg_signature, token, timestamp, nonce, echostr): + return jsonify({'error': 'invalid callback signature'}), 403 + try: + plain = decrypt_wecom_aes(echostr, aes_key, corp_id) + except Exception as exc: + _persist_wecom_callback_audit( + msg_signature=msg_signature, + timestamp=timestamp, + nonce=nonce, + encrypt_raw=echostr, + error_message=f'decrypt_failed:{str(exc)[:200]}', + ) + return jsonify({'error': 'decrypt failed'}), 400 + _persist_wecom_callback_audit( + msg_signature=msg_signature, + timestamp=timestamp, + nonce=nonce, + encrypt_raw=echostr, + decrypted_xml=plain, + msg_type='url_verify', + ) + return plain, 200, {'Content-Type': 'text/plain; charset=utf-8'} + if not _verify_wecom_msg_signature(msg_signature, token, timestamp, nonce, echostr): + return jsonify({'error': 'invalid callback signature'}), 403 + _persist_wecom_callback_audit( + msg_signature=msg_signature, + timestamp=timestamp, + nonce=nonce, + encrypt_raw=echostr, + decrypted_xml=echostr, + msg_type='url_verify_plain', + ) + return echostr, 200, {'Content-Type': 'text/plain; charset=utf-8'} + + payload = request.get_data(as_text=True) or '' + encrypt_field = extract_encrypt_field(payload) or '' + if not token: + return jsonify({'error': 'callback token not configured'}), 500 + if not encrypt_field: + return jsonify({'error': 'missing Encrypt field'}), 400 + if not _verify_wecom_msg_signature(msg_signature, token, timestamp, nonce, encrypt_field): + _persist_wecom_callback_audit( + msg_signature=msg_signature, + timestamp=timestamp, + nonce=nonce, + encrypt_raw=encrypt_field, + error_message='invalid_msg_signature', + ) + return jsonify({'error': 'invalid callback signature'}), 403 + + decrypted = None + if aes_key: + try: + decrypted = decrypt_wecom_aes(encrypt_field, aes_key, corp_id) + except Exception as exc: + _persist_wecom_callback_audit( + msg_signature=msg_signature, + timestamp=timestamp, + nonce=nonce, + encrypt_raw=encrypt_field, + error_message=f'decrypt_failed:{str(exc)[:200]}', + ) + return jsonify({'error': 'decrypt failed'}), 400 + + msg_type = _extract_xml_field(decrypted, 'MsgType') if decrypted else None + event = _extract_xml_field(decrypted, 'Event') if decrypted else None + from_user = _extract_xml_field(decrypted, 'FromUserName') if decrypted else None + agent_id = _extract_xml_field(decrypted, 'AgentID') if decrypted else None + msg_id = _extract_xml_field(decrypted, 'MsgId') if decrypted else None + + _persist_wecom_callback_audit( + msg_signature=msg_signature, + timestamp=timestamp, + nonce=nonce, + encrypt_raw=encrypt_field, + decrypted_xml=decrypted, + msg_type=msg_type, + event=event, + from_user=from_user, + agent_id=agent_id, + msg_id=msg_id, + ) + return 'success', 200, {'Content-Type': 'text/plain; charset=utf-8'} + @user_bp.route('/wecom/binding', methods=['GET']) def get_wecom_binding(): user = _get_current_user() diff --git a/backend/app/config.py b/backend/app/config.py index 4cfcebc3..6aeb809b 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -47,6 +47,25 @@ class Config: WECOM_SECRET = os.getenv('WECOM_SECRET') WECOM_REDIRECT_URI = os.getenv('WECOM_REDIRECT_URI') WECOM_AUTO_CREATE_USER = os.getenv('WECOM_AUTO_CREATE_USER', 'true').lower() == 'true' + WECOM_MATCH_RULES = os.getenv('WECOM_MATCH_RULES', 'employee_id,mobile') + WECOM_MATCH_OPERATOR = os.getenv('WECOM_MATCH_OPERATOR', 'AND').upper() + WECOM_FIRST_LOGIN_BIND_MODE = os.getenv('WECOM_FIRST_LOGIN_BIND_MODE', 'match_rules') + WECOM_FIRST_LOGIN_INPUT_FIELDS = os.getenv('WECOM_FIRST_LOGIN_INPUT_FIELDS', 'employee_id,mobile,email') + WECOM_EMPLOYEE_ID_SOURCE = os.getenv('WECOM_EMPLOYEE_ID_SOURCE', 'userid') + WECOM_MOBILE_NORMALIZE = os.getenv('WECOM_MOBILE_NORMALIZE', 'true').lower() == 'true' + WECOM_CALLBACK_TOKEN = os.getenv('WECOM_CALLBACK_TOKEN', '') + WECOM_ENCODING_AES_KEY = os.getenv('WECOM_ENCODING_AES_KEY', '') + WECOM_CALLBACK_URL = os.getenv('WECOM_CALLBACK_URL', '') + WECOM_HOMEPAGE_URL = os.getenv('WECOM_HOMEPAGE_URL', '') + WECOM_TRUSTED_DOMAIN = os.getenv('WECOM_TRUSTED_DOMAIN', '') + # Public HTTPS origin for WeCom console URLs (takes priority over notify base + request host). + WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL', '') + WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true' + WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL', '') + WECOM_NOTIFY_EVENTS = os.getenv( + 'WECOM_NOTIFY_EVENTS', + 'permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed', + ) class DevelopmentConfig(Config): diff --git a/backend/app/env_persistence.py b/backend/app/env_persistence.py new file mode 100644 index 00000000..943723e8 --- /dev/null +++ b/backend/app/env_persistence.py @@ -0,0 +1,233 @@ +"""Persistent storage for runtime-editable application settings. + +Settings managed from the admin console (e.g. WeCom configuration) need to +survive process restarts AND container/image rebuilds in production. Writing +only to ``backend/.env`` is not enough on Docker deployments because the +container's writable layer is discarded on every ``docker compose up --build``. + +Storage strategy: + +1. Database (``app_settings`` table) - canonical, always authoritative. +2. ``backend/.env`` - best-effort secondary write so local/dev workflows that + read the env file directly (or restart without DB access) still see updates. +3. ``os.environ`` - mirrored on write so legacy ``os.getenv`` consumers stay + in sync within the running process. + +On read we merge .env (lowest priority) over DB (highest priority); the DB +value wins whenever it exists. +""" + +from __future__ import annotations + +import logging +import os +from pathlib import Path +from typing import Iterable + +from dotenv import dotenv_values, set_key + + +logger = logging.getLogger(__name__) + + +BACKEND_ENV_PATH = Path(__file__).resolve().parents[1] / '.env' +WECOM_BOOL_KEYS = { + 'WECOM_ENABLED', + 'WECOM_AUTO_CREATE_USER', + 'WECOM_MOBILE_NORMALIZE', + 'WECOM_NOTIFY_ENABLED', +} + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _ensure_env_file_exists() -> bool: + try: + BACKEND_ENV_PATH.parent.mkdir(parents=True, exist_ok=True) + if not BACKEND_ENV_PATH.exists(): + BACKEND_ENV_PATH.write_text('', encoding='utf-8') + return True + except OSError as exc: + logger.warning('Cannot create %s: %s', BACKEND_ENV_PATH, exc) + return False + + +def _to_env_string(value: object) -> str: + if isinstance(value, bool): + return 'true' if value else 'false' + if value is None: + return '' + return str(value) + + +def _parse_env_value(key: str, value: object) -> object: + if value is None: + return None + if key in WECOM_BOOL_KEYS: + return str(value).strip().lower() == 'true' + return str(value) + + +def _matches_prefixes(key: str, prefixes: Iterable[str]) -> bool: + return any(key.startswith(prefix) for prefix in prefixes) + + +# --------------------------------------------------------------------------- +# Database read/write (primary store) +# --------------------------------------------------------------------------- + + +def _persist_to_db(values: dict[str, str]) -> bool: + """Write key/value pairs into the ``app_settings`` table. + + Returns True if every value was committed, False otherwise. The function + is defensive: it must not raise, because settings persistence is also + written to ``.env`` and we don't want to fail the API request. + """ + if not values: + return True + try: + from app import db + from app.models import AppSetting + except Exception as exc: # pragma: no cover - import safety net + logger.warning('AppSetting model unavailable: %s', exc) + return False + + try: + for key, value in values.items(): + existing = db.session.get(AppSetting, key) + if existing is None: + db.session.add(AppSetting(key=key, value=value)) + else: + existing.value = value + db.session.commit() + return True + except Exception as exc: + logger.warning('Failed to persist settings to DB: %s', exc) + try: + db.session.rollback() + except Exception: # pragma: no cover + pass + return False + + +def _load_from_db(prefixes: tuple[str, ...]) -> dict[str, str]: + try: + from app import db + from app.models import AppSetting + except Exception as exc: # pragma: no cover + logger.debug('AppSetting model unavailable for read: %s', exc) + return {} + + try: + rows = db.session.query(AppSetting).all() + except Exception as exc: + # Most common case: the migration has not been applied yet on a + # freshly-built container. Degrade gracefully to .env-only mode. + logger.debug('app_settings table not readable yet: %s', exc) + try: + db.session.rollback() + except Exception: # pragma: no cover + pass + return {} + + result: dict[str, str] = {} + for row in rows: + if row.key and _matches_prefixes(row.key, prefixes): + result[row.key] = row.value if row.value is not None else '' + return result + + +# --------------------------------------------------------------------------- +# .env read/write (secondary store, best-effort) +# --------------------------------------------------------------------------- + + +def _persist_to_env_file(values: dict[str, str]) -> bool: + if not values: + return True + if not _ensure_env_file_exists(): + return False + ok = True + for key, value in values.items(): + try: + set_key(str(BACKEND_ENV_PATH), key, value, quote_mode='auto') + except OSError as exc: + logger.warning('Cannot write %s to %s: %s', key, BACKEND_ENV_PATH, exc) + ok = False + return ok + + +def _load_from_env_file(prefixes: tuple[str, ...]) -> dict[str, str]: + if not BACKEND_ENV_PATH.exists(): + return {} + try: + loaded = dotenv_values(BACKEND_ENV_PATH) + except OSError as exc: + logger.warning('Cannot read %s: %s', BACKEND_ENV_PATH, exc) + return {} + return { + key: (value if value is not None else '') + for key, value in loaded.items() + if key and _matches_prefixes(key, prefixes) + } + + +# --------------------------------------------------------------------------- +# Public API +# --------------------------------------------------------------------------- + + +def persist_env_settings(values: dict[str, object]) -> dict[str, str]: + """Persist settings to the canonical store and mirror to ``os.environ``. + + Order: + 1. Mirror to ``os.environ`` so the current process picks them up + immediately. + 2. Persist to the database (canonical, survives container rebuilds). + 3. Best-effort write to ``backend/.env`` so dev workflows that grep the + file or restart without DB access keep working. + """ + if not values: + return {} + + persisted: dict[str, str] = {} + for key, value in values.items(): + env_value = _to_env_string(value) + os.environ[key] = env_value + persisted[key] = env_value + + db_ok = _persist_to_db(persisted) + file_ok = _persist_to_env_file(persisted) + + if not db_ok and not file_ok: + logger.error( + 'Failed to persist settings %s to BOTH database and .env file. ' + 'Settings will be lost when the process restarts.', + list(persisted.keys()), + ) + + return persisted + + +def apply_env_settings(prefixes: tuple[str, ...] = ('WECOM_',)) -> dict[str, object]: + """Load settings from the canonical store and apply to ``os.environ``. + + DB values take priority over ``backend/.env`` values; both are merged so + keys that only live in the env file (e.g. fresh deploy before any admin + edit) are still honored. + """ + file_values = _load_from_env_file(prefixes) + db_values = _load_from_db(prefixes) + + merged: dict[str, str] = {**file_values, **db_values} + + applied: dict[str, object] = {} + for key, raw_value in merged.items(): + parsed = _parse_env_value(key, raw_value) + os.environ[key] = _to_env_string(parsed) + applied[key] = parsed + return applied diff --git a/backend/app/models.py b/backend/app/models.py index 43a13952..d0fc7e22 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -274,7 +274,71 @@ class LoginAudit(Base): source: Mapped[str] = mapped_column(String(20), default='password') # password / wecom status: Mapped[str] = mapped_column(String(20), default='success') # success / failed reason: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) + error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + match_rules: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + match_operator: Mapped[Optional[str]] = mapped_column(String(8), nullable=True) + match_result: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) wecom_userid: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) ip: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) user_agent: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) + + +class WecomNotifyAudit(Base): + """ + 企业微信触达审计表 + 用途:记录企微消息发送结果与回流点击数据 + """ + __tablename__ = 'wecom_notify_audits' + + id: Mapped[int] = mapped_column(primary_key=True) + event_type: Mapped[str] = mapped_column(String(64), index=True) + status: Mapped[str] = mapped_column(String(20), default='sent', index=True) # sent / failed + trace_id: Mapped[str] = mapped_column(String(64), unique=True, index=True) + user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True, index=True) + username: Mapped[Optional[str]] = mapped_column(String(50), nullable=True) + wecom_userid: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + title: Mapped[Optional[str]] = mapped_column(String(120), nullable=True) + content: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + jump_url: Mapped[Optional[str]] = mapped_column(String(512), nullable=True) + error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + error_message: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) + opened_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True) + + +class AppSetting(Base): + """ + 应用运行时配置表(Key/Value) + 用途:将企业微信等管理员可编辑的配置长效保存到数据库, + 避免容器/部署重建后写入 backend/.env 的修改丢失。 + """ + __tablename__ = 'app_settings' + + key: Mapped[str] = mapped_column(String(128), primary_key=True) + value: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + updated_at: Mapped[datetime] = mapped_column( + DateTime, default=datetime.utcnow, onupdate=datetime.utcnow + ) + + +class WecomCallbackAudit(Base): + """ + 企业微信回调审计表 + 用途:记录消息与事件回调(安全模式解密后的内容摘要) + """ + __tablename__ = 'wecom_callback_audits' + + id: Mapped[int] = mapped_column(primary_key=True) + msg_signature: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + timestamp: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + nonce: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + encrypt_raw: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + decrypted_xml: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + msg_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True) + event: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) + from_user: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True) + agent_id: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + msg_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) + error_message: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) diff --git a/backend/app/services/wecom_crypto.py b/backend/app/services/wecom_crypto.py new file mode 100644 index 00000000..a62b3241 --- /dev/null +++ b/backend/app/services/wecom_crypto.py @@ -0,0 +1,93 @@ +""" +WeCom (企业微信) callback crypto helpers — compatible with WXBizMsgCrypt layout. +""" +from __future__ import annotations + +import base64 +import hashlib +import random +import struct +from typing import Optional + +from Crypto.Cipher import AES + + +def sha1_hex(parts: list[str]) -> str: + merged = ''.join(sorted([str(p) for p in parts if p is not None])) + return hashlib.sha1(merged.encode('utf-8')).hexdigest() + + +def _pkcs7_pad(data: bytes, block_size: int = 32) -> bytes: + pad_len = block_size - (len(data) % block_size) + return data + bytes([pad_len] * pad_len) + + +def _pkcs7_unpad(data: bytes) -> bytes: + if not data: + return data + pad_len = data[-1] + if pad_len < 1 or pad_len > 32: + raise ValueError('invalid pkcs7 padding') + if data[-pad_len:] != bytes([pad_len] * pad_len): + raise ValueError('invalid pkcs7 padding tail') + return data[:-pad_len] + + +def _aes_key_from_encoding_key(encoding_aes_key_b64: str) -> bytes: + raw = (encoding_aes_key_b64 or '').strip() + key = base64.b64decode(raw + '=') + if len(key) != 32: + raise ValueError('EncodingAESKey must decode to 32 bytes') + return key + + +def encrypt_wecom_aes(plain_text: str, encoding_aes_key_b64: str, corp_id: str) -> str: + """ + Encrypt plain text to base64 ciphertext (for tests / optional outbound use). + """ + aes_key = _aes_key_from_encoding_key(encoding_aes_key_b64) + iv = aes_key[:16] + random_bytes = bytes(random.randint(0, 255) for _ in range(16)) + msg_bytes = plain_text.encode('utf-8') + pack = ( + random_bytes + + struct.pack('>I', len(msg_bytes)) + + msg_bytes + + corp_id.encode('utf-8') + ) + padded = _pkcs7_pad(pack, 32) + cipher = AES.new(aes_key, AES.MODE_CBC, iv) + encrypted = cipher.encrypt(padded) + return base64.b64encode(encrypted).decode('ascii') + + +def decrypt_wecom_aes(cipher_b64: str, encoding_aes_key_b64: str, corp_id: str) -> str: + aes_key = _aes_key_from_encoding_key(encoding_aes_key_b64) + iv = aes_key[:16] + cipher_bytes = base64.b64decode(cipher_b64) + cipher = AES.new(aes_key, AES.MODE_CBC, iv) + plain_padded = cipher.decrypt(cipher_bytes) + plain = _pkcs7_unpad(plain_padded) + content = plain[16:] + if len(content) < 4: + raise ValueError('decrypted payload too short') + xml_len = struct.unpack('>I', content[:4])[0] + xml_bytes = content[4:4 + xml_len] + tail = content[4 + xml_len:] + if tail.decode('utf-8', errors='strict') != corp_id: + raise ValueError('corp_id mismatch after decrypt') + return xml_bytes.decode('utf-8') + + +def extract_encrypt_field(xml_body: str) -> Optional[str]: + if not xml_body: + return None + import re + + m = re.search(r'', xml_body, re.DOTALL) + if m: + return m.group(1).strip() + m2 = re.search(r'(.*?)', xml_body, re.DOTALL) + if m2: + return m2.group(1).strip() + return None diff --git a/backend/app/services/wecom_notify.py b/backend/app/services/wecom_notify.py new file mode 100644 index 00000000..7f2cc924 --- /dev/null +++ b/backend/app/services/wecom_notify.py @@ -0,0 +1,146 @@ +from __future__ import annotations + +from datetime import datetime, timedelta +from urllib.parse import urlencode +import uuid + +import requests +from flask import current_app + +from app import db +from app.models import User, WecomNotifyAudit + + +_TOKEN_CACHE = { + 'token': None, + 'expires_at': None, +} + + +def _get_enabled_events() -> set[str]: + raw = current_app.config.get('WECOM_NOTIFY_EVENTS', '') + if isinstance(raw, str): + return {x.strip() for x in raw.split(',') if x.strip()} + if isinstance(raw, (list, tuple, set)): + return {str(x).strip() for x in raw if str(x).strip()} + return set() + + +def _build_jump_url(path: str, trace_id: str, params: dict | None = None) -> str: + base = current_app.config.get('WECOM_NOTIFY_BASE_URL') or '' + if not base: + return '' + base = base.rstrip('/') + if not path.startswith('/'): + path = f'/{path}' + merged = {'wecom_trace': trace_id} + if params: + merged.update({k: v for k, v in params.items() if v is not None}) + return f'{base}{path}?{urlencode(merged)}' + + +def _get_access_token() -> str: + now = datetime.utcnow() + token = _TOKEN_CACHE.get('token') + expires_at = _TOKEN_CACHE.get('expires_at') + if token and expires_at and now < expires_at: + return token + + corp_id = current_app.config.get('WECOM_CORP_ID') + secret = current_app.config.get('WECOM_SECRET') + resp = requests.get( + 'https://qyapi.weixin.qq.com/cgi-bin/gettoken', + params={'corpid': corp_id, 'corpsecret': secret}, + timeout=8, + ) + data = resp.json() + if data.get('errcode') != 0 or not data.get('access_token'): + raise RuntimeError(f"Failed to fetch WeCom token: {data}") + + _TOKEN_CACHE['token'] = data['access_token'] + _TOKEN_CACHE['expires_at'] = now + timedelta(seconds=max(int(data.get('expires_in', 7200)) - 120, 60)) + return data['access_token'] + + +def send_wecom_event_message( + *, + event_type: str, + user: User, + title: str, + content: str, + jump_path: str = '/workspace', + jump_params: dict | None = None, +) -> dict: + trace_id = uuid.uuid4().hex + audit = WecomNotifyAudit( + event_type=event_type, + status='failed', + trace_id=trace_id, + user_id=user.id if user else None, + username=user.username if user else None, + wecom_userid=user.wecom_userid if user else None, + title=title, + content=content, + ) + db.session.add(audit) + + if not current_app.config.get('WECOM_NOTIFY_ENABLED', True): + audit.error_code = 'NOTIFY_DISABLED' + audit.error_message = 'WECOM_NOTIFY_ENABLED=false' + return {'ok': False, 'trace_id': trace_id, 'reason': 'notify_disabled'} + + if event_type not in _get_enabled_events(): + audit.error_code = 'EVENT_DISABLED' + audit.error_message = f'event {event_type} disabled' + return {'ok': False, 'trace_id': trace_id, 'reason': 'event_disabled'} + + if not user or not user.wecom_userid: + audit.error_code = 'WECOM_USER_UNBOUND' + audit.error_message = 'user has no wecom_userid' + return {'ok': False, 'trace_id': trace_id, 'reason': 'user_unbound'} + + try: + token = _get_access_token() + jump_url = _build_jump_url(jump_path, trace_id, jump_params) + audit.jump_url = jump_url + payload = { + 'touser': user.wecom_userid, + 'msgtype': 'textcard', + 'agentid': int(current_app.config.get('WECOM_AGENT_ID')), + 'textcard': { + 'title': title[:120], + 'description': (content or '')[:1024], + 'url': jump_url or (current_app.config.get('WECOM_NOTIFY_BASE_URL') or 'https://work.weixin.qq.com'), + 'btntxt': '查看详情', + }, + 'safe': 0, + } + resp = requests.post( + 'https://qyapi.weixin.qq.com/cgi-bin/message/send', + params={'access_token': token}, + json=payload, + timeout=8, + ) + data = resp.json() + if data.get('errcode') == 0: + audit.status = 'sent' + return {'ok': True, 'trace_id': trace_id} + + audit.error_code = str(data.get('errcode')) + audit.error_message = str(data.get('errmsg', 'unknown error'))[:255] + return {'ok': False, 'trace_id': trace_id, 'reason': 'send_failed', 'raw': data} + except Exception as exc: + audit.error_code = 'EXCEPTION' + audit.error_message = str(exc)[:255] + return {'ok': False, 'trace_id': trace_id, 'reason': 'exception'} + + +def mark_wecom_message_opened(trace_id: str) -> bool: + if not trace_id: + return False + row = db.session.query(WecomNotifyAudit).filter_by(trace_id=trace_id).first() + if not row: + return False + if not row.opened_at: + row.opened_at = datetime.utcnow() + return True diff --git a/backend/migrations/versions/9a2d6b4e8c1f_repair_missing_postgres_id_sequences.py b/backend/migrations/versions/9a2d6b4e8c1f_repair_missing_postgres_id_sequences.py new file mode 100644 index 00000000..ec2db67f --- /dev/null +++ b/backend/migrations/versions/9a2d6b4e8c1f_repair_missing_postgres_id_sequences.py @@ -0,0 +1,95 @@ +"""repair missing postgres id sequences + +Revision ID: 9a2d6b4e8c1f +Revises: c7d2a4b9e1f0 +Create Date: 2026-04-19 22:40:00.000000 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '9a2d6b4e8c1f' +down_revision = 'c7d2a4b9e1f0' +branch_labels = None +depends_on = None + + +def _column_info(bind, table_name: str): + return bind.execute( + sa.text( + """ + select data_type, is_identity, column_default + from information_schema.columns + where table_schema = 'public' + and table_name = :table_name + and column_name = 'id' + """ + ), + {'table_name': table_name}, + ).mappings().first() + + +def _needs_sequence(bind, inspector, table_name: str) -> bool: + columns = {column['name'] for column in inspector.get_columns(table_name)} + if 'id' not in columns: + return False + + pk = inspector.get_pk_constraint(table_name) or {} + constrained = pk.get('constrained_columns') or [] + if 'id' not in constrained: + return False + + info = _column_info(bind, table_name) + if not info: + return False + if info['data_type'] not in {'integer', 'bigint'}: + return False + if info['is_identity'] == 'YES': + return False + + sequence_name = bind.execute( + sa.text("select pg_get_serial_sequence(:table_name, 'id')"), + {'table_name': f'public.{table_name}'}, + ).scalar() + return sequence_name is None + + +def _repair_sequence(table_name: str) -> None: + seq_name = f'{table_name}_id_seq' + op.execute(f'CREATE SEQUENCE IF NOT EXISTS public.{seq_name}') + op.execute(f'ALTER SEQUENCE public.{seq_name} OWNED BY public.{table_name}.id') + op.execute( + "ALTER TABLE public.{table} " + "ALTER COLUMN id SET DEFAULT nextval('public.{seq}'::regclass)".format( + table=table_name, + seq=seq_name, + ) + ) + op.execute( + """ + SELECT setval( + 'public.{seq}', + COALESCE((SELECT MAX(id) FROM public.{table}), 1), + COALESCE((SELECT MAX(id) FROM public.{table}), 0) > 0 + ) + """.format(table=table_name, seq=seq_name) + ) + + +def upgrade(): + bind = op.get_bind() + if bind.dialect.name != 'postgresql': + return + + inspector = sa.inspect(bind) + for table_name in inspector.get_table_names(): + if _needs_sequence(bind, inspector, table_name): + _repair_sequence(table_name) + + +def downgrade(): + # Legacy databases may already rely on these repaired defaults/sequences. + # Rolling them back would risk breaking inserts again, so keep downgrade noop. + pass diff --git a/backend/migrations/versions/c7d2a4b9e1f0_add_app_settings_table.py b/backend/migrations/versions/c7d2a4b9e1f0_add_app_settings_table.py new file mode 100644 index 00000000..ed8ad667 --- /dev/null +++ b/backend/migrations/versions/c7d2a4b9e1f0_add_app_settings_table.py @@ -0,0 +1,40 @@ +"""add app_settings table + +Revision ID: c7d2a4b9e1f0 +Revises: e6b0b1c2d3f4 +Create Date: 2026-04-19 20:10:00.000000 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'c7d2a4b9e1f0' +down_revision = 'e6b0b1c2d3f4' +branch_labels = None +depends_on = None + + +def _has_table(table_name: str) -> bool: + bind = op.get_bind() + inspector = sa.inspect(bind) + return table_name in inspector.get_table_names() + + +def upgrade(): + if _has_table('app_settings'): + return + op.create_table( + 'app_settings', + sa.Column('key', sa.String(length=128), nullable=False), + sa.Column('value', sa.Text(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('key'), + ) + + +def downgrade(): + if not _has_table('app_settings'): + return + op.drop_table('app_settings') diff --git a/backend/migrations/versions/e6b0b1c2d3f4_expand_login_audit_columns.py b/backend/migrations/versions/e6b0b1c2d3f4_expand_login_audit_columns.py new file mode 100644 index 00000000..9578d103 --- /dev/null +++ b/backend/migrations/versions/e6b0b1c2d3f4_expand_login_audit_columns.py @@ -0,0 +1,48 @@ +"""expand login audit columns + +Revision ID: e6b0b1c2d3f4 +Revises: f1a0b9c8d7e6 +Create Date: 2026-04-18 17:40:00.000000 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'e6b0b1c2d3f4' +down_revision = 'f1a0b9c8d7e6' +branch_labels = None +depends_on = None + + +def _get_columns(table_name: str) -> set[str]: + bind = op.get_bind() + inspector = sa.inspect(bind) + return {column['name'] for column in inspector.get_columns(table_name)} + + +def upgrade(): + existing = _get_columns('login_audits') + + if 'error_code' not in existing: + op.add_column('login_audits', sa.Column('error_code', sa.String(length=64), nullable=True)) + if 'match_rules' not in existing: + op.add_column('login_audits', sa.Column('match_rules', sa.String(length=128), nullable=True)) + if 'match_operator' not in existing: + op.add_column('login_audits', sa.Column('match_operator', sa.String(length=8), nullable=True)) + if 'match_result' not in existing: + op.add_column('login_audits', sa.Column('match_result', sa.String(length=64), nullable=True)) + + +def downgrade(): + existing = _get_columns('login_audits') + + if 'match_result' in existing: + op.drop_column('login_audits', 'match_result') + if 'match_operator' in existing: + op.drop_column('login_audits', 'match_operator') + if 'match_rules' in existing: + op.drop_column('login_audits', 'match_rules') + if 'error_code' in existing: + op.drop_column('login_audits', 'error_code') diff --git a/backend/migrations/versions/f1a0b9c8d7e6_add_wecom_callback_audits.py b/backend/migrations/versions/f1a0b9c8d7e6_add_wecom_callback_audits.py new file mode 100644 index 00000000..e083c331 --- /dev/null +++ b/backend/migrations/versions/f1a0b9c8d7e6_add_wecom_callback_audits.py @@ -0,0 +1,50 @@ +"""add wecom callback audits + +Revision ID: f1a0b9c8d7e6 +Revises: d1e8a7f4c2b9 +Create Date: 2026-04-18 12:00:00.000000 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'f1a0b9c8d7e6' +down_revision = 'd1e8a7f4c2b9' +branch_labels = None +depends_on = None + + +def upgrade(): + op.create_table( + 'wecom_callback_audits', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('msg_signature', sa.String(length=128), nullable=True), + sa.Column('timestamp', sa.String(length=32), nullable=True), + sa.Column('nonce', sa.String(length=64), nullable=True), + sa.Column('encrypt_raw', sa.Text(), nullable=True), + sa.Column('decrypted_xml', sa.Text(), nullable=True), + sa.Column('msg_type', sa.String(length=32), nullable=True), + sa.Column('event', sa.String(length=64), nullable=True), + sa.Column('from_user', sa.String(length=128), nullable=True), + sa.Column('agent_id', sa.String(length=32), nullable=True), + sa.Column('msg_id', sa.String(length=64), nullable=True), + sa.Column('error_message', sa.String(length=255), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + ) + op.create_index(op.f('ix_wecom_callback_audits_created_at'), 'wecom_callback_audits', ['created_at'], unique=False) + op.create_index(op.f('ix_wecom_callback_audits_msg_type'), 'wecom_callback_audits', ['msg_type'], unique=False) + op.create_index(op.f('ix_wecom_callback_audits_event'), 'wecom_callback_audits', ['event'], unique=False) + op.create_index(op.f('ix_wecom_callback_audits_from_user'), 'wecom_callback_audits', ['from_user'], unique=False) + op.create_index(op.f('ix_wecom_callback_audits_msg_id'), 'wecom_callback_audits', ['msg_id'], unique=False) + + +def downgrade(): + op.drop_index(op.f('ix_wecom_callback_audits_msg_id'), table_name='wecom_callback_audits') + op.drop_index(op.f('ix_wecom_callback_audits_from_user'), table_name='wecom_callback_audits') + op.drop_index(op.f('ix_wecom_callback_audits_event'), table_name='wecom_callback_audits') + op.drop_index(op.f('ix_wecom_callback_audits_msg_type'), table_name='wecom_callback_audits') + op.drop_index(op.f('ix_wecom_callback_audits_created_at'), table_name='wecom_callback_audits') + op.drop_table('wecom_callback_audits') diff --git a/backend/requirements.txt b/backend/requirements.txt index 9679e5d2..3b4922b6 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -11,3 +11,4 @@ gevent pydantic python-dotenv openpyxl +pycryptodome diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index d4df8b24..685433a4 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -1,9 +1,26 @@ import pytest -from app import create_app, db -from app.models import User + + +@pytest.fixture(autouse=True) +def _isolate_persisted_settings(monkeypatch, tmp_path): + """Prevent tests from inheriting the developer's local ``backend/.env``. + + ``apply_env_settings`` is called eagerly in ``create_app`` and on every + request via the ``before_request`` hook. If the dev's real ``backend/.env`` + contains ``WECOM_AUTO_CREATE_USER=true`` (or any other WECOM_* override), + those values would silently overwrite the explicit ``app.config.update(...)`` + calls inside test fixtures. Routing reads to a tmp path makes every test + start from a clean slate. + """ + from app import env_persistence + + monkeypatch.setattr(env_persistence, 'BACKEND_ENV_PATH', tmp_path / 'isolated.env') + @pytest.fixture def app(): + from app import create_app, db + app = create_app('testing') with app.app_context(): db.create_all() @@ -11,10 +28,12 @@ def app(): db.session.remove() db.drop_all() + @pytest.fixture def client(app): return app.test_client() + @pytest.fixture def admin_headers(): return { @@ -23,6 +42,7 @@ def admin_headers(): 'Content-Type': 'application/json' } + @pytest.fixture def user_headers(): return { diff --git a/backend/tests/test_login_audit_compat.py b/backend/tests/test_login_audit_compat.py new file mode 100644 index 00000000..150d5f02 --- /dev/null +++ b/backend/tests/test_login_audit_compat.py @@ -0,0 +1,32 @@ +from app import db +from app.models import User +from app.api import user as user_api + + +def test_login_succeeds_when_login_audit_insert_fails(app, client, monkeypatch): + with app.app_context(): + admin = User( + username='admin', + email='admin@example.com', + role='admin', + status='active', + employee_id='EMP-ADMIN', + ) + admin.set_password('admin123') + db.session.add(admin) + db.session.commit() + + def _raise_audit_error(payload): + raise RuntimeError('simulated audit insert failure') + + monkeypatch.setattr(user_api, '_execute_login_audit_insert', _raise_audit_error) + + response = client.post('/api/user/login', json={ + 'username': 'admin', + 'password': 'admin123', + }) + + assert response.status_code == 200 + data = response.get_json() + assert data['username'] == 'admin' + assert data['role'] == 'admin' diff --git a/backend/tests/test_wecom_crypto.py b/backend/tests/test_wecom_crypto.py new file mode 100644 index 00000000..d9758b70 --- /dev/null +++ b/backend/tests/test_wecom_crypto.py @@ -0,0 +1,21 @@ +import base64 + +from app.services.wecom_crypto import decrypt_wecom_aes, encrypt_wecom_aes, sha1_hex + + +def test_wecom_aes_roundtrip(): + corp_id = 'ww1234567890abcdef' + aes_key_b64 = base64.b64encode(b'0' * 32).decode('ascii').rstrip('=') + xml = '' + cipher = encrypt_wecom_aes(xml, aes_key_b64, corp_id) + plain = decrypt_wecom_aes(cipher, aes_key_b64, corp_id) + assert plain == xml + + +def test_wecom_msg_signature(): + token = 'hxops-token' + ts = '123' + nonce = 'abc' + encrypt = 'cipher-text' + sig = sha1_hex([token, ts, nonce, encrypt]) + assert sha1_hex([token, ts, nonce, encrypt]) == sig diff --git a/backend/tests/test_wecom_debug_api.py b/backend/tests/test_wecom_debug_api.py new file mode 100644 index 00000000..a2514af0 --- /dev/null +++ b/backend/tests/test_wecom_debug_api.py @@ -0,0 +1,96 @@ +from app import db +from app.models import User +from app.api import admin as admin_api +from app.api import user as user_api + + +class DummyResponse: + def __init__(self, payload): + self._payload = payload + + def json(self): + return self._payload + + +def test_wecom_debug_user_by_code_returns_raw_user_and_match_preview(client, app, admin_headers, monkeypatch): + app.config.update( + WECOM_ENABLED=True, + WECOM_CORP_ID='ww-test', + WECOM_AGENT_ID='100001', + WECOM_SECRET='secret-test', + WECOM_AUTO_CREATE_USER=False, + WECOM_MATCH_RULES='employee_id', + WECOM_MATCH_OPERATOR='AND', + WECOM_EMPLOYEE_ID_SOURCE='userid', + ) + + with app.app_context(): + user = User( + username='emp001', + email='emp001@example.com', + employee_id='EMP001', + phone_number='13800138000', + status='active', + role='user', + ) + user.set_password('pwd') + db.session.add(user) + db.session.commit() + + monkeypatch.setattr(user_api, '_get_wecom_access_token', lambda: 'token-1') + + def fake_get(url, params=None, timeout=8): + if 'cgi-bin/auth/getuserinfo' in url: + return DummyResponse({'errcode': 0, 'errmsg': 'ok', 'userid': 'EMP001'}) + if 'cgi-bin/user/get' in url: + return DummyResponse({ + 'errcode': 0, + 'userid': 'EMP001', + 'name': '王超', + 'mobile': '13800138000', + 'email': 'emp001@example.com', + }) + raise AssertionError(f'unexpected url: {url}') + + monkeypatch.setattr(admin_api.requests, 'get', fake_get) + + res = client.post( + '/api/admin/wecom/debug-user-by-code', + json={'code': 'real-code-from-wecom'}, + headers=admin_headers, + ) + assert res.status_code == 200 + data = res.get_json() + assert data['auth_info']['userid'] == 'EMP001' + assert data['wecom_user']['name'] == '王超' + assert data['normalized_identity']['employee_id'] == 'EMP001' + assert data['match_preview']['decision'] == 'matched_existing_user' + assert data['match_preview']['matched_users'][0]['username'] == 'emp001' + + +def test_wecom_debug_user_by_code_returns_scope_error_when_only_openid(client, app, admin_headers, monkeypatch): + app.config.update( + WECOM_ENABLED=True, + WECOM_CORP_ID='ww-test', + WECOM_AGENT_ID='100001', + WECOM_SECRET='secret-test', + ) + + monkeypatch.setattr(user_api, '_get_wecom_access_token', lambda: 'token-1') + + def fake_get(url, params=None, timeout=8): + if 'cgi-bin/auth/getuserinfo' in url: + return DummyResponse({'errcode': 0, 'errmsg': 'ok', 'openid': 'oExternal_xx'}) + raise AssertionError(f'unexpected url: {url}') + + monkeypatch.setattr(admin_api.requests, 'get', fake_get) + + res = client.post( + '/api/admin/wecom/debug-user-by-code', + json={'code': 'code-out-of-scope'}, + headers=admin_headers, + ) + assert res.status_code == 401 + data = res.get_json() + assert data['error_code'] == 'WECOM_NOT_IN_AGENT_SCOPE' + assert data['openid'] == 'oExternal_xx' diff --git a/backend/tests/test_wecom_input_verify_flow.py b/backend/tests/test_wecom_input_verify_flow.py new file mode 100644 index 00000000..42a528af --- /dev/null +++ b/backend/tests/test_wecom_input_verify_flow.py @@ -0,0 +1,247 @@ +import pytest + +from app import create_app, db +from app.models import User +from app.api import user as user_api + + +class DummyResponse: + def __init__(self, payload): + self._payload = payload + + def json(self): + return self._payload + + +@pytest.fixture +def wecom_input_verify_client(): + app = create_app('testing') + app.config.update( + TESTING=True, + SQLALCHEMY_DATABASE_URI='sqlite:///:memory:', + WECOM_ENABLED=True, + WECOM_CORP_ID='ww-test', + WECOM_AGENT_ID='100001', + WECOM_SECRET='secret-test', + WECOM_REDIRECT_URI='https://example.com/workspace', + WECOM_AUTO_CREATE_USER=False, + WECOM_MATCH_RULES='employee_id,mobile', + WECOM_MATCH_OPERATOR='AND', + WECOM_FIRST_LOGIN_BIND_MODE='input_verify', + WECOM_FIRST_LOGIN_INPUT_FIELDS='employee_id,mobile,email', + WECOM_EMPLOYEE_ID_SOURCE='userid', + WECOM_MOBILE_NORMALIZE=True, + ) + with app.test_client() as client: + with app.app_context(): + db.create_all() + user_api._WECOM_STATE_CACHE.clear() + user_api._WECOM_BIND_SESSION_CACHE.clear() + user_api._WECOM_ACCESS_TOKEN_CACHE['token'] = None + user_api._WECOM_ACCESS_TOKEN_CACHE['expires_at'] = None + yield client, app + db.session.remove() + db.drop_all() + user_api._WECOM_STATE_CACHE.clear() + user_api._WECOM_BIND_SESSION_CACHE.clear() + user_api._WECOM_ACCESS_TOKEN_CACHE['token'] = None + user_api._WECOM_ACCESS_TOKEN_CACHE['expires_at'] = None + + +def _issue_state(client): + res = client.get('/api/user/wecom/authorize-url', query_string={'redirect_uri': 'https://example.com/workspace'}) + assert res.status_code == 200 + return res.get_json()['state'] + + +def _mock_wecom_requests(monkeypatch, userid, *, name='Test User', mobile=None, email=None): + def fake_get(url, params=None, timeout=8): + if 'cgi-bin/gettoken' in url: + return DummyResponse({'errcode': 0, 'access_token': 'token-1', 'expires_in': 7200}) + if 'cgi-bin/auth/getuserinfo' in url: + return DummyResponse({'errcode': 0, 'errmsg': 'ok', 'userid': userid}) + if 'cgi-bin/user/get' in url: + payload = {'errcode': 0, 'userid': userid, 'name': name} + if mobile is not None: + payload['mobile'] = mobile + if email is not None: + payload['email'] = email + return DummyResponse(payload) + raise AssertionError(f'unexpected url: {url}') + + monkeypatch.setattr(user_api.requests, 'get', fake_get) + + +def _start_input_verify_login(client, monkeypatch, *, userid, name='Test User', mobile=None, email=None): + _mock_wecom_requests(monkeypatch, userid=userid, name=name, mobile=mobile, email=email) + state = _issue_state(client) + res = client.post('/api/user/wecom/login', json={'code': 'code-input-verify', 'state': state}) + assert res.status_code == 409 + data = res.get_json() + assert data['error_code'] == 'WECOM_BIND_INPUT_REQUIRED' + assert data['binding_token'] + return data + + +def test_wecom_login_returns_input_verify_prompt_on_first_login(wecom_input_verify_client, monkeypatch): + client, app = wecom_input_verify_client + + with app.app_context(): + user = User( + username='emp001', + email='emp001@example.com', + employee_id='EMP001', + phone_number='13800138000', + status='active', + role='user', + ) + user.set_password('pwd') + db.session.add(user) + db.session.commit() + + data = _start_input_verify_login( + client, + monkeypatch, + userid='EMP001', + name='王超', + mobile='13800138000', + email='emp001@example.com', + ) + + assert data['allowed_fields'] == ['employee_id', 'mobile', 'email'] + assert data['wecom_name'] == '王超' + assert data['wecom_userid'] == 'EMP001' + + with app.app_context(): + user = db.session.query(User).filter_by(username='emp001').first() + assert user.wecom_userid is None + + +def test_wecom_complete_bind_binds_user_by_selected_field(wecom_input_verify_client, monkeypatch): + client, app = wecom_input_verify_client + + with app.app_context(): + user = User( + username='emp001', + email='emp001@example.com', + employee_id='EMP001', + phone_number='13800138000', + status='active', + role='user', + ) + user.set_password('pwd') + db.session.add(user) + db.session.commit() + + login_data = _start_input_verify_login( + client, + monkeypatch, + userid='EMP001', + name='王超', + mobile='13800138000', + email='emp001@example.com', + ) + + bind_res = client.post('/api/user/wecom/complete-bind', json={ + 'binding_token': login_data['binding_token'], + 'field': 'employee_id', + 'value': 'EMP001', + }) + assert bind_res.status_code == 200 + bind_data = bind_res.get_json() + assert bind_data['username'] == 'emp001' + assert bind_data['source'] == 'wecom' + assert bind_data['bind_status'] == 'input_verified_and_bound' + + with app.app_context(): + user = db.session.query(User).filter_by(username='emp001').first() + assert user.wecom_userid == 'EMP001' + assert user.real_name == '王超' + + expired_res = client.post('/api/user/wecom/complete-bind', json={ + 'binding_token': login_data['binding_token'], + 'field': 'employee_id', + 'value': 'EMP001', + }) + assert expired_res.status_code == 400 + assert expired_res.get_json()['error_code'] == 'WECOM_BIND_SESSION_EXPIRED' + + +def test_wecom_complete_bind_returns_not_found_when_value_does_not_match(wecom_input_verify_client, monkeypatch): + client, app = wecom_input_verify_client + + with app.app_context(): + user = User( + username='emp001', + email='emp001@example.com', + employee_id='EMP001', + phone_number='13800138000', + status='active', + role='user', + ) + user.set_password('pwd') + db.session.add(user) + db.session.commit() + + login_data = _start_input_verify_login( + client, + monkeypatch, + userid='EMP001', + name='王超', + mobile='13800138000', + email='emp001@example.com', + ) + + bind_res = client.post('/api/user/wecom/complete-bind', json={ + 'binding_token': login_data['binding_token'], + 'field': 'email', + 'value': 'missing@example.com', + }) + assert bind_res.status_code == 404 + bind_data = bind_res.get_json() + assert bind_data['error_code'] == 'WECOM_BIND_INPUT_NOT_FOUND' + + +def test_wecom_complete_bind_returns_ambiguous_for_mobile_raw_and_normalized_duplicates(wecom_input_verify_client, monkeypatch): + client, app = wecom_input_verify_client + + with app.app_context(): + user1 = User( + username='emp001', + email='emp001@example.com', + employee_id='EMP001', + phone_number='13800138000', + status='active', + role='user', + ) + user1.set_password('pwd') + user2 = User( + username='emp002', + email='emp002@example.com', + employee_id='EMP002', + phone_number='+86 13800138000', + status='active', + role='user', + ) + user2.set_password('pwd') + db.session.add_all([user1, user2]) + db.session.commit() + + login_data = _start_input_verify_login( + client, + monkeypatch, + userid='EMP009', + name='李雷', + mobile='13800990000', + email='emp009@example.com', + ) + + bind_res = client.post('/api/user/wecom/complete-bind', json={ + 'binding_token': login_data['binding_token'], + 'field': 'mobile', + 'value': '+86 13800138000', + }) + assert bind_res.status_code == 409 + bind_data = bind_res.get_json() + assert bind_data['error_code'] == 'WECOM_BIND_INPUT_AMBIGUOUS' + assert bind_data['candidate_count'] == 2 diff --git a/backend/tests/test_wecom_login_matching.py b/backend/tests/test_wecom_login_matching.py new file mode 100644 index 00000000..a7192c3d --- /dev/null +++ b/backend/tests/test_wecom_login_matching.py @@ -0,0 +1,195 @@ +import pytest + +from app import create_app, db +from app.models import User +from app.api import user as user_api + + +class DummyResponse: + def __init__(self, payload): + self._payload = payload + + def json(self): + return self._payload + + +@pytest.fixture +def wecom_client(): + app = create_app('testing') + app.config.update( + TESTING=True, + SQLALCHEMY_DATABASE_URI='sqlite:///:memory:', + WECOM_ENABLED=True, + WECOM_CORP_ID='ww-test', + WECOM_AGENT_ID='100001', + WECOM_SECRET='secret-test', + WECOM_REDIRECT_URI='https://example.com/workspace', + WECOM_AUTO_CREATE_USER=False, + WECOM_MATCH_RULES='employee_id,mobile', + WECOM_MATCH_OPERATOR='AND', + WECOM_EMPLOYEE_ID_SOURCE='userid', + WECOM_MOBILE_NORMALIZE=True, + ) + with app.test_client() as client: + with app.app_context(): + db.create_all() + user_api._WECOM_STATE_CACHE.clear() + user_api._WECOM_ACCESS_TOKEN_CACHE['token'] = None + user_api._WECOM_ACCESS_TOKEN_CACHE['expires_at'] = None + yield client, app + db.session.remove() + db.drop_all() + user_api._WECOM_STATE_CACHE.clear() + user_api._WECOM_ACCESS_TOKEN_CACHE['token'] = None + user_api._WECOM_ACCESS_TOKEN_CACHE['expires_at'] = None + + +def _issue_state(client): + res = client.get('/api/user/wecom/authorize-url', query_string={'redirect_uri': 'https://example.com/workspace'}) + assert res.status_code == 200 + return res.get_json()['state'] + + +def _mock_wecom_requests(monkeypatch, userid, mobile=None, email=None): + def fake_get(url, params=None, timeout=8): + if 'cgi-bin/gettoken' in url: + return DummyResponse({'errcode': 0, 'access_token': 'token-1', 'expires_in': 7200}) + if 'cgi-bin/auth/getuserinfo' in url: + # 真实 WeCom /cgi-bin/auth/getuserinfo 返回的是小写 userid (企业成员), + # 外部联系人/不在可见范围则返回 openid 而无 userid。 + return DummyResponse({'errcode': 0, 'errmsg': 'ok', 'userid': userid}) + if 'cgi-bin/user/get' in url: + payload = {'errcode': 0, 'userid': userid, 'name': 'Test User'} + if mobile is not None: + payload['mobile'] = mobile + if email is not None: + payload['email'] = email + return DummyResponse(payload) + raise AssertionError(f'unexpected url: {url}') + + monkeypatch.setattr(user_api.requests, 'get', fake_get) + + +def test_wecom_login_match_existing_user_by_employee_and_mobile(wecom_client, monkeypatch): + client, app = wecom_client + with app.app_context(): + user = User( + username='emp001', + email='emp001@example.com', + employee_id='EMP001', + phone_number='13800138000', + status='active', + role='user', + ) + user.set_password('pwd') + db.session.add(user) + db.session.commit() + + _mock_wecom_requests(monkeypatch, userid='EMP001', mobile='13800138000', email='emp001@example.com') + state = _issue_state(client) + res = client.post('/api/user/wecom/login', json={'code': 'code-1', 'state': state}) + assert res.status_code == 200 + data = res.get_json() + assert data['bind_status'] == 'matched_and_bound' + assert data['username'] == 'emp001' + + with app.app_context(): + user = db.session.query(User).filter_by(username='emp001').first() + assert user.wecom_userid == 'EMP001' + + +def test_wecom_login_bind_required_when_no_match(wecom_client, monkeypatch): + client, app = wecom_client + _mock_wecom_requests(monkeypatch, userid='EMP404', mobile='13800999999', email='emp404@example.com') + state = _issue_state(client) + res = client.post('/api/user/wecom/login', json={'code': 'code-2', 'state': state}) + assert res.status_code == 403 + data = res.get_json() + assert data['error_code'] == 'WECOM_BIND_REQUIRED' + assert data['reason'] == 'bind_required' + + with app.app_context(): + assert db.session.query(User).count() == 0 + + +def test_wecom_login_ambiguous_match_returns_409(wecom_client, monkeypatch): + client, app = wecom_client + with app.app_context(): + app.config['WECOM_MATCH_OPERATOR'] = 'OR' + user1 = User( + username='u1', + email='u1@example.com', + employee_id='EMP777', + phone_number='13900000001', + status='active', + role='user', + ) + user1.set_password('pwd') + user2 = User( + username='u2', + email='u2@example.com', + employee_id='EMP888', + phone_number='13888888888', + status='active', + role='user', + ) + user2.set_password('pwd') + db.session.add_all([user1, user2]) + db.session.commit() + + _mock_wecom_requests(monkeypatch, userid='EMP777', mobile='13888888888') + state = _issue_state(client) + res = client.post('/api/user/wecom/login', json={'code': 'code-3', 'state': state}) + assert res.status_code == 409 + data = res.get_json() + assert data['error_code'] == 'WECOM_MATCH_AMBIGUOUS' + assert data['reason'] == 'ambiguous_match' + assert data['candidate_count'] == 2 + + +def test_wecom_login_missing_match_attr_returns_422(wecom_client, monkeypatch): + client, app = wecom_client + with app.app_context(): + user = User( + username='u3', + email='u3@example.com', + employee_id='EMP003', + phone_number='13800380000', + status='active', + role='user', + ) + user.set_password('pwd') + db.session.add(user) + db.session.commit() + + _mock_wecom_requests(monkeypatch, userid='EMP003', mobile=None, email='u3@example.com') + state = _issue_state(client) + res = client.post('/api/user/wecom/login', json={'code': 'code-4', 'state': state}) + assert res.status_code == 422 + data = res.get_json() + assert data['error_code'] == 'WECOM_MATCH_ATTR_MISSING' + assert data['missing_field'] == 'mobile' + + +def test_wecom_login_returns_clear_error_when_user_not_in_agent_scope(wecom_client, monkeypatch): + """当 /auth/getuserinfo 返回 errcode=0 但只有 openid(登录者不在自建应用的可见范围)时, + 必须给出明确的中文提示而不是 'WeCom auth failed: ok'。 + """ + client, app = wecom_client + + def fake_get(url, params=None, timeout=8): + if 'cgi-bin/gettoken' in url: + return DummyResponse({'errcode': 0, 'access_token': 'token-1', 'expires_in': 7200}) + if 'cgi-bin/auth/getuserinfo' in url: + return DummyResponse({'errcode': 0, 'errmsg': 'ok', 'openid': 'oExternal_xx'}) + raise AssertionError(f'unexpected url: {url}') + + monkeypatch.setattr(user_api.requests, 'get', fake_get) + + state = _issue_state(client) + res = client.post('/api/user/wecom/login', json={'code': 'code-out-of-scope', 'state': state}) + assert res.status_code == 401 + data = res.get_json() + assert data['error_code'] == 'WECOM_NOT_IN_AGENT_SCOPE' + assert '可见范围' in data['error'] + assert 'WeCom auth failed: ok' not in data['error'] diff --git a/backend/tests/test_wecom_provision_api.py b/backend/tests/test_wecom_provision_api.py new file mode 100644 index 00000000..b60e8293 --- /dev/null +++ b/backend/tests/test_wecom_provision_api.py @@ -0,0 +1,107 @@ +from app import db +from app.models import Agent, User + + +def test_wecom_provision_create_bind_and_set_permissions(client, app, admin_headers): + with app.app_context(): + a1 = Agent(name='A1', type='api', dify_app_id='app-a1', dify_api_key='k-a1', is_active=True) + a2 = Agent(name='A2', type='api', dify_app_id='app-a2', dify_api_key='k-a2', is_active=True) + db.session.add_all([a1, a2]) + db.session.commit() + a1_id, a2_id = a1.id, a2.id + + payload = { + 'create_user': True, + 'user': { + 'username': 'emp2001', + 'real_name': 'Emp 2001', + 'employee_id': 'EMP2001', + 'phone_number': '13800111222', + 'email': 'emp2001@example.com', + 'department': 'IT', + 'role': 'user', + 'status': 'active', + }, + 'bind': { + 'wecom_userid': 'EMP2001', + 'wecom_unionid': 'UNION-2001', + }, + 'agent_ids': [a1_id, a2_id], + } + res = client.post('/api/admin/wecom/provision', json=payload, headers=admin_headers) + assert res.status_code == 201 + body = res.get_json() + assert body['status'] == 'ok' + assert body['permission_updated'] is True + + with app.app_context(): + user = db.session.get(User, body['user_id']) + assert user is not None + assert user.wecom_userid == 'EMP2001' + assert user.wecom_unionid == 'UNION-2001' + assert sorted([a.id for a in user.agents]) == sorted([a1_id, a2_id]) + + +def test_wecom_provision_conflict_should_not_create_new_user(client, app, admin_headers): + with app.app_context(): + existing = User(username='bound_user', email='bound@example.com', role='user', status='active', wecom_userid='WX-DUP') + existing.set_password('pwd') + db.session.add(existing) + db.session.commit() + + payload = { + 'create_user': True, + 'user': { + 'username': 'new_to_rollback', + 'email': 'new_to_rollback@example.com', + }, + 'bind': { + 'wecom_userid': 'WX-DUP', + }, + 'agent_ids': [], + } + res = client.post('/api/admin/wecom/provision', json=payload, headers=admin_headers) + assert res.status_code == 400 + assert 'already bound to user' in res.get_json()['error'] + + with app.app_context(): + should_not_exist = db.session.query(User).filter_by(username='new_to_rollback').first() + assert should_not_exist is None + + +def test_wecom_provision_bind_existing_user(client, app, admin_headers): + with app.app_context(): + user = User( + username='existing_user', + email='existing@example.com', + employee_id='EMP3001', + phone_number='13800990011', + role='user', + status='active', + ) + user.set_password('pwd') + agent = Agent(name='A3', type='api', dify_app_id='app-a3', dify_api_key='k-a3', is_active=True) + db.session.add_all([user, agent]) + db.session.commit() + user_id = user.id + agent_id = agent.id + + payload = { + 'create_user': False, + 'user_id': user_id, + 'bind': { + 'wecom_userid': 'EMP3001', + }, + 'agent_ids': [agent_id], + } + res = client.post('/api/admin/wecom/provision', json=payload, headers=admin_headers) + assert res.status_code == 200 + body = res.get_json() + assert body['binding'] == 'updated' + assert body['permission_updated'] is True + + with app.app_context(): + user = db.session.get(User, user_id) + assert user.wecom_userid == 'EMP3001' + assert [a.id for a in user.agents] == [agent_id] + diff --git a/backend/tests/test_wecom_settings_env_persistence.py b/backend/tests/test_wecom_settings_env_persistence.py new file mode 100644 index 00000000..4f950528 --- /dev/null +++ b/backend/tests/test_wecom_settings_env_persistence.py @@ -0,0 +1,125 @@ +from dotenv import dotenv_values + +from app import db, env_persistence +from app.models import AppSetting + + +def test_wecom_system_settings_persist_to_env_and_reload(client, app, admin_headers, monkeypatch, tmp_path): + env_file = tmp_path / '.env' + monkeypatch.setattr(env_persistence, 'BACKEND_ENV_PATH', env_file) + + payload = { + 'enabled': True, + 'corp_id': 'ww-persisted', + 'agent_id': '1000999', + 'secret': 'persist-secret', + 'redirect_uri': 'https://example.com/workspace', + 'auto_create_user': False, + 'match_rules': 'employee_id,email', + 'match_operator': 'OR', + 'employee_id_source': 'extattr:job_no', + 'mobile_normalize': False, + 'callback_token': 'cb-token', + 'encoding_aes_key': 'enc-key', + 'callback_url': 'https://example.com/api/user/wecom/callback', + 'homepage_url': 'https://example.com/workspace', + 'trusted_domain': 'example.com', + 'public_base_url': 'https://example.com', + } + + res = client.put('/api/admin/wecom/system-settings', json=payload, headers=admin_headers) + assert res.status_code == 200 + + saved = dotenv_values(env_file) + assert saved['WECOM_ENABLED'] == 'true' + assert saved['WECOM_CORP_ID'] == 'ww-persisted' + assert saved['WECOM_MATCH_OPERATOR'] == 'OR' + assert saved['WECOM_PUBLIC_BASE_URL'] == 'https://example.com' + + with app.app_context(): + rows = {row.key: row.value for row in db.session.query(AppSetting).all()} + assert rows['WECOM_ENABLED'] == 'true' + assert rows['WECOM_CORP_ID'] == 'ww-persisted' + assert rows['WECOM_MATCH_OPERATOR'] == 'OR' + assert rows['WECOM_PUBLIC_BASE_URL'] == 'https://example.com' + + with app.app_context(): + app.config['WECOM_ENABLED'] = False + app.config['WECOM_CORP_ID'] = '' + app.config['WECOM_MATCH_OPERATOR'] = 'AND' + app.config['WECOM_PUBLIC_BASE_URL'] = '' + + res = client.get('/api/admin/wecom/system-settings', headers=admin_headers) + assert res.status_code == 200 + data = res.get_json() + assert data['enabled'] is True + assert data['corp_id'] == 'ww-persisted' + assert data['match_operator'] == 'OR' + assert data['public_base_url'] == 'https://example.com' + + +def test_wecom_notify_settings_persist_to_env_and_reload(client, app, admin_headers, monkeypatch, tmp_path): + env_file = tmp_path / '.env' + monkeypatch.setattr(env_persistence, 'BACKEND_ENV_PATH', env_file) + + payload = { + 'enabled': False, + 'base_url': 'https://notify.example.com', + 'events': ['task_completed', 'permission_batch_updated'], + } + + res = client.put('/api/admin/wecom/notify-settings', json=payload, headers=admin_headers) + assert res.status_code == 200 + + saved = dotenv_values(env_file) + assert saved['WECOM_NOTIFY_ENABLED'] == 'false' + assert saved['WECOM_NOTIFY_BASE_URL'] == 'https://notify.example.com' + assert saved['WECOM_NOTIFY_EVENTS'] == 'task_completed,permission_batch_updated' + + with app.app_context(): + rows = {row.key: row.value for row in db.session.query(AppSetting).all()} + assert rows['WECOM_NOTIFY_ENABLED'] == 'false' + assert rows['WECOM_NOTIFY_BASE_URL'] == 'https://notify.example.com' + assert rows['WECOM_NOTIFY_EVENTS'] == 'task_completed,permission_batch_updated' + + with app.app_context(): + app.config['WECOM_NOTIFY_ENABLED'] = True + app.config['WECOM_NOTIFY_BASE_URL'] = '' + app.config['WECOM_NOTIFY_EVENTS'] = '' + + res = client.get('/api/admin/wecom/notify-settings', headers=admin_headers) + assert res.status_code == 200 + data = res.get_json() + assert data['enabled'] is False + assert data['base_url'] == 'https://notify.example.com' + assert data['events'] == ['task_completed', 'permission_batch_updated'] + + +def test_wecom_system_settings_survive_when_env_file_is_wiped(client, app, admin_headers, monkeypatch, tmp_path): + """Simulate a container rebuild that wipes backend/.env. The DB row must + still drive the runtime configuration.""" + env_file = tmp_path / '.env' + monkeypatch.setattr(env_persistence, 'BACKEND_ENV_PATH', env_file) + + res = client.put( + '/api/admin/wecom/system-settings', + json={'corp_id': 'ww-from-db-only', 'enabled': True}, + headers=admin_headers, + ) + assert res.status_code == 200 + + # Wipe the env file the way a fresh container build would. + if env_file.exists(): + env_file.unlink() + + # Reset in-memory config to defaults to prove the next request reloads + # values from the database rather than the (now empty) env file. + with app.app_context(): + app.config['WECOM_CORP_ID'] = '' + app.config['WECOM_ENABLED'] = False + + res = client.get('/api/admin/wecom/system-settings', headers=admin_headers) + assert res.status_code == 200 + data = res.get_json() + assert data['corp_id'] == 'ww-from-db-only' + assert data['enabled'] is True diff --git a/docker-compose.yml b/docker-compose.yml index fb21f1ee..a6275b4f 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -20,6 +20,12 @@ services: # 如果需要在宿主机调试,可暴露端口;生产环境建议只在网络内暴露 ports: - "5002:5002" + # 持久化运行时可写文件: + # - backend/.env 用于保存管理员后台修改的企业微信等配置(与数据库双写, + # 防止容器重建后从镜像基线读取丢失修改)。文件不存在时 docker 会自动 + # 把它当作目录挂载,因此先确保宿主机上存在该文件再启动。 + volumes: + - ./backend/.env:/app/.env networks: - ai-platform diff --git a/frontend/WW_verify_46MjWA55y3PBRLid.txt b/frontend/WW_verify_46MjWA55y3PBRLid.txt new file mode 100644 index 00000000..c4768439 --- /dev/null +++ b/frontend/WW_verify_46MjWA55y3PBRLid.txt @@ -0,0 +1 @@ +46MjWA55y3PBRLid \ No newline at end of file diff --git a/frontend/dist/index.html b/frontend/dist/index.html index afffdd82..d45ce5c3 100644 --- a/frontend/dist/index.html +++ b/frontend/dist/index.html @@ -10,8 +10,8 @@ hxai - - + +
diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 4f919d0a..ea014452 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -559,6 +559,7 @@ "integrity": "sha512-oH72nZRfDv9lADUBSo104Aq7gPHpQZc4BTx38r9xf9pg5LfP6EzSyH2n7qFmmxRQXh7YlUXODcYsg6PuTDSxGg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "undici-types": "~7.16.0" } @@ -611,7 +612,7 @@ }, "node_modules/@vue-office/docx": { "version": "1.6.3", - "resolved": "https://registry.npmjs.org/@vue-office/docx/-/docx-1.6.3.tgz", + "resolved": "https://mirrors.tencent.com/npm/@vue-office/docx/-/docx-1.6.3.tgz", "integrity": "sha512-Cs+3CAaRBOWOiW4XAhTwwxJ0dy8cPIf6DqfNvYcD3YACiLwO4kuawLF2IAXxyijhbuOeoFsfvoVbOc16A/4bZA==", "hasInstallScript": true, "license": "MIT", @@ -628,7 +629,7 @@ }, "node_modules/@vue-office/excel": { "version": "1.7.14", - "resolved": "https://registry.npmjs.org/@vue-office/excel/-/excel-1.7.14.tgz", + "resolved": "https://mirrors.tencent.com/npm/@vue-office/excel/-/excel-1.7.14.tgz", "integrity": "sha512-pVUgt+emDQUnW7q22CfnQ+jl43mM/7IFwYzOg7lwOwPEbiVB4K4qEQf+y/bc4xGXz75w1/e3Kz3G6wAafmFBFg==", "hasInstallScript": true, "license": "MIT", @@ -645,7 +646,7 @@ }, "node_modules/@vue-office/pdf": { "version": "1.6.5", - "resolved": "https://registry.npmjs.org/@vue-office/pdf/-/pdf-1.6.5.tgz", + "resolved": "https://mirrors.tencent.com/npm/@vue-office/pdf/-/pdf-1.6.5.tgz", "integrity": "sha512-3BePzeA5wji2JoZGJhdlc3XEXs6gMcSnBXrBXlGGfhZHjNijxcHa9V5Ibm8dDKoEwPPsfg+kf4TGP9/2GBR8jQ==", "hasInstallScript": true, "license": "MIT", @@ -965,6 +966,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", @@ -2055,6 +2057,7 @@ "resolved": "https://mirrors.tencent.com/npm/picomatch/-/picomatch-4.0.3.tgz", "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "license": "MIT", + "peer": true, "engines": { "node": ">=12" }, @@ -2099,6 +2102,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", @@ -2440,6 +2444,7 @@ "resolved": "https://mirrors.tencent.com/npm/tailwindcss/-/tailwindcss-3.4.17.tgz", "integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==", "license": "MIT", + "peer": true, "dependencies": { "@alloc/quick-lru": "^5.2.0", "arg": "^5.0.2", @@ -2541,6 +2546,7 @@ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "devOptional": true, "license": "Apache-2.0", + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -2599,6 +2605,7 @@ "integrity": "sha512-RHX7IvsJlEfjyA1rS7MY0UsmF91etdLAamslHR5lfuO3W/BXRdXm2tRE64ztpSPZbKqB4wAAZ0AwtF6QzfKZLA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@oxc-project/runtime": "0.114.0", "lightningcss": "^1.31.1", @@ -2684,6 +2691,7 @@ "resolved": "https://mirrors.tencent.com/npm/vue/-/vue-3.5.28.tgz", "integrity": "sha512-BRdrNfeoccSoIZeIhyPBfvWSLFP4q8J3u8Ju8Ug5vu3LdD+yTM13Sg4sKtljxozbnuMu1NB1X5HBHRYUzFocKg==", "license": "MIT", + "peer": true, "dependencies": { "@vue/compiler-dom": "3.5.28", "@vue/compiler-sfc": "3.5.28", diff --git a/frontend/src/config.ts b/frontend/src/config.ts index e639083a..14ce2de4 100644 --- a/frontend/src/config.ts +++ b/frontend/src/config.ts @@ -5,7 +5,10 @@ export const config = { enabled: true, authorizeApi: '/api/user/wecom/authorize-url', loginApi: '/api/user/wecom/login', - callbackPath: '/workspace' + completeBindApi: '/api/user/wecom/complete-bind', + callbackPath: '/workspace', + deeplinkTraceApi: '/api/user/wecom/deeplink-opened', + taskCompleteApi: '/api/user/wecom/task-complete' } }, workspace: { diff --git a/frontend/src/i18n.ts b/frontend/src/i18n.ts index 34ed3309..228db12a 100644 --- a/frontend/src/i18n.ts +++ b/frontend/src/i18n.ts @@ -43,7 +43,71 @@ const messages = { wecomStateExpired: 'WeCom login session expired, please try again.', wecomBindRequired: 'Current WeCom account is not bound to a local user, please contact admin.', wecomAccountDisabled: 'Account is disabled, please contact admin.', - wecomLoginFailed: 'WeCom login failed' + wecomLoginFailed: 'WeCom login failed', + wecomMatchAmbiguous: 'Multiple local users matched this WeCom account. Please contact admin.', + wecomMatchAttrMissing: 'Required account attributes are missing in WeCom. Please contact admin.', + wecomRetry: 'Retry WeCom Login', + wecomTechnicalInfo: 'Technical info: {detail}', + wecomBindPromptTitle: 'Verify and bind your local account', + wecomBindPromptDesc: 'This is your first WeCom login for {name}. Enter one allowed field below to bind your local account.', + wecomBindField: 'Verification field', + wecomBindValue: 'Verification value', + wecomBindValuePlaceholder: 'Enter your {field}', + wecomBindPromptHint: 'The value must exactly match an existing local account. After success, this WeCom account will be bound automatically.', + wecomBindSubmit: 'Verify and sign in', + wecomBindInputNotFound: 'No local account matched the value you entered.', + wecomBindInputAmbiguous: 'The value you entered matched multiple local accounts. Please contact the administrator.', + wecomBindSessionExpired: 'This WeCom binding session expired. Please restart WeCom login.', + wecomBindConflict: 'This WeCom account is already bound to another local account.', + wecomBindFieldNotAllowed: 'The selected verification field is not allowed.', + wecomBindValueRequired: 'Please enter a verification value.', + wecomFieldLabels: { + employee_id: 'employee ID', + mobile: 'mobile number', + email: 'email', + match_rules: 'match rules' + }, + wecomRuleJoin: { + and: 'and', + or: 'or' + }, + wecomFieldGuides: { + employee_id: 'Ask the administrator to verify the employee ID source configuration and make sure this member can return an employee ID.', + mobile: 'Ask the administrator to fill in the mobile number in the WeCom directory, or adjust the matching rules to stop requiring mobile.', + email: 'Ask the administrator to maintain the email field in the WeCom directory, or adjust the matching rules.', + default: 'Ask the administrator to verify the WeCom directory fields and the current matching rules.' + }, + wecomDialogTitles: { + matchAttrMissing: 'WeCom profile is incomplete', + matchAmbiguous: 'Multiple local accounts matched', + bindRequired: 'No local account can be linked', + bindInputRequired: 'Verification is required before binding', + bindConflict: 'This WeCom account is already linked elsewhere', + notInScope: 'This member is not authorized for the app', + stateExpired: 'WeCom login expired', + accountDisabled: 'Local account is disabled', + loginFailed: 'WeCom login failed' + }, + wecomDialogSummaries: { + matchAttrMissing: 'WeCom did not return "{field}", so the system cannot match your local account automatically.', + matchAmbiguous: 'This WeCom account matched multiple local accounts, so the system cannot decide which one to sign in.', + matchAmbiguousWithCount: 'This WeCom account matched {count} local accounts, so the system cannot decide which one to sign in.', + bindRequired: 'WeCom authentication succeeded, but no local account matched the current rules.', + bindInputRequired: 'WeCom authentication succeeded. Please verify one local account field to complete the first binding.', + bindConflict: 'This WeCom account is already bound to another local account.', + notInScope: 'This member is outside the app visibility scope, or is not a member of this enterprise.' + }, + wecomDialogDetails: { + currentRules: 'Current matching rules: {rules}', + bindFallback: 'If you already have a local account, ask the administrator to bind this WeCom account manually.', + ambiguousAction: 'Ask the administrator to clean duplicated employee ID/mobile/email data, or tighten the matching rules.', + bindRequiredAction: 'Ask the administrator to create or bind the local account first, or enable auto-create users.', + bindInputRequiredAction: 'Enter your employee ID, mobile number, or email on the next step to bind this WeCom account to your existing local account.', + bindConflictAction: 'Ask the administrator to unbind the old account before binding this WeCom account again.', + notInScopeAction: 'Ask the administrator to add this member or the member’s department into the WeCom app visibility scope.', + retryLogin: 'Start a new WeCom login and try again.', + contactAdmin: 'Please contact the administrator for assistance.' + } }, landing: { hero: { @@ -142,7 +206,8 @@ const messages = { denied: 'You do not have permission, please request access.', reason: 'Reason for request', submit: 'Submit Request' - } + }, + wecomEntryNotice: 'Opened from WeCom message. Related context is ready.' }, admin: { title: 'Admin Console', @@ -381,6 +446,16 @@ const messages = { wecom: { title: 'WeCom Binding Management', subtitle: 'Manually bind/unbind WeCom accounts and review login audit records', + systemSettings: 'WeCom System Settings', + integrationCopyTitle: 'WeCom Console Copy Helper', + integrationCopyDesc: 'Copy these values directly into WeCom console fields.', + integrationCopySecretsNote: + 'Token and EncodingAESKey are empty until you set them above (or in env) and save. They must match the WeCom console; use Generate if you want random values, then paste the same values into WeCom.', + publicBasePlaceholder: 'https://your-public-domain.com', + generateAddresses: 'Generate URLs', + generateToken: 'Generate', + generateEncodingKey: 'Generate', + copy: 'Copy', refresh: 'Refresh', quickBind: 'Quick Bind', bind: 'Bind', @@ -389,13 +464,71 @@ const messages = { boundOnly: 'Bound only', noData: 'No data', auditTitle: 'Login Audit (latest 200)', + notifySettings: 'Notify Settings', + notifyEnabled: 'Enable WeCom event notifications', + notifyBaseUrl: 'Deep link base URL (e.g. https://ai.company.com)', + notifyEvents: 'Enabled events (comma separated)', + notifyMetrics: 'Delivery Metrics (30 days)', + metricTotal: 'Total', + metricSuccessRate: 'Send success', + metricOpenedRate: 'Opened rate', + metricWindowDays: 'Window(days)', exportAudit: 'Export Audit', noAuditData: 'No audit records', confirmUnbind: 'Confirm unbinding this user from WeCom?', fields: { userId: 'User ID (user_id)', wecomUserId: 'WeCom UserId', - wecomUnionId: 'UnionId (optional)' + wecomUnionId: 'UnionId (optional)', + enabled: 'Enable WeCom login', + autoCreateUser: 'Auto create local user', + corpId: 'Corp ID', + agentId: 'Agent ID', + secret: 'App Secret', + redirectUri: 'OAuth Redirect URI', + matchRules: 'Match Rules', + matchOperator: 'Match Operator', + firstLoginBindMode: 'First login bind mode', + firstLoginInputFields: 'First login input fields', + employeeIdSource: 'Employee ID Source', + mobileNormalize: 'Normalize mobile number', + publicBaseUrl: 'Public HTTPS base (extranet)' + }, + bindModes: { + match_rules: 'Match automatically', + input_verify: 'Ask user to verify' + }, + copyFields: { + publicBaseUrl: 'Public base URL', + callbackUrl: 'Callback URL', + callbackToken: 'Token', + encodingAesKey: 'EncodingAESKey', + oauthRedirectUri: 'OAuth Redirect URI', + homepageUrl: 'Application Homepage URL', + trustedDomain: 'Trusted Domain', + authorizeApi: 'Authorize API (GET)', + loginApi: 'Login API (POST)' + }, + tips: { + enabled: 'Master switch for WeCom OAuth login.', + autoCreateUser: 'If no local user matches, automatically create one.', + corpId: 'From WeCom app credentials.', + agentId: 'Self-built app AgentId in WeCom.', + secret: 'App secret used to get access token.', + redirectUri: 'Must match WeCom trusted callback URL.', + matchRules: 'Supported values: employee_id,mobile,email.', + matchOperator: 'AND = all fields required, OR = any field matched.', + firstLoginBindMode: 'match_rules = use WeCom profile to auto-match. input_verify = ask the user to enter one allowed field on first login.', + firstLoginInputFields: 'Allowed fields for first-login verification, comma separated. Supported: employee_id,mobile,email.', + employeeIdSource: 'userid or extattr:.', + mobileNormalize: 'Normalize 86/0086 and symbols before matching.', + callbackToken: 'Used to verify callback signatures.', + encodingAesKey: 'Used for encrypted callback mode.', + callbackUrl: 'WeCom callback receiver URL for messages/events.', + homepageUrl: 'Application homepage opened in WeCom.', + trustedDomain: 'OAuth trusted domain configured in WeCom.', + publicBaseUrl: + 'HTTPS origin reachable from the internet (WeCom servers). Used to build callback and OAuth URLs. Priority: this field → notify base URL → current request host.' }, headers: { user: 'User', @@ -424,12 +557,43 @@ const messages = { success: 'Success', failed: 'Failed' }, + auditMessages: { + loginSuccess: 'Login succeeded', + matchAttrMissing: 'Missing required match field: {field}', + matchAmbiguous: 'Matched multiple local accounts', + bindRequired: 'No local account can be linked', + bindInputRequired: 'Waiting for the user to verify a local account field', + bindInputNotFound: 'No local account matched the user-entered verification value', + bindInputAmbiguous: 'The user-entered verification value matched multiple local accounts', + bindConflict: 'This WeCom account is already linked to another local account', + notInScope: 'Member is outside the app visibility scope or not in this enterprise', + invalidState: 'Invalid or expired login state', + missingCode: 'Callback is missing code', + accountDisabled: 'Local account is disabled', + authFailed: 'WeCom authorization failed: {detail}', + userFetchFailed: 'Failed to fetch WeCom member profile: {detail}', + exception: 'Exception: {detail}' + }, + auditMeta: { + rules: 'Rules: {rules}', + result: 'Result: {result}', + errorCode: 'Code: {code}' + }, + auditResults: { + already_bound: 'Logged in through an already bound WeCom account', + matched_and_bound: 'Matched and bound the local account by rules', + auto_created: 'Auto-created and bound a new local account', + input_verified_and_bound: 'Verified one field on first login and bound the local account' + }, msg: { bindInputRequired: 'Please enter user_id and wecom_userid', bindFailed: 'Bind failed', bindSuccess: 'Bind succeeded', unbindFailed: 'Unbind failed', - boundConflict: 'This WeCom account is already bound: {detail}' + boundConflict: 'This WeCom account is already bound: {detail}', + copySuccess: 'Copied', + copyFailed: 'Copy failed', + publicBaseRequired: 'Enter a valid public HTTPS domain or host (e.g. https://ai.company.com).' } }, @@ -731,7 +895,71 @@ const messages = { wecomStateExpired: '企业微信登录会话已过期,请重试。', wecomBindRequired: '当前企业微信账号未绑定本地用户,请联系管理员。', wecomAccountDisabled: '账号已禁用,请联系管理员。', - wecomLoginFailed: '企业微信登录失败' + wecomLoginFailed: '企业微信登录失败', + wecomMatchAmbiguous: '该企业微信账号匹配到多个本地账号,请联系管理员处理。', + wecomMatchAttrMissing: '企业微信缺少必要匹配字段,请联系管理员。', + wecomRetry: '重新发起企业微信登录', + wecomTechnicalInfo: '技术信息:{detail}', + wecomBindPromptTitle: '首次登录请校验并绑定本站账号', + wecomBindPromptDesc: '当前企业微信身份为 {name}。请输入一个允许的字段,用来绑定你已有的本站账号。', + wecomBindField: '校验字段', + wecomBindValue: '校验值', + wecomBindValuePlaceholder: '请输入你的{field}', + wecomBindPromptHint: '输入值必须和本站已有账号完全匹配。绑定成功后,当前企业微信账号会自动写回该用户表。', + wecomBindSubmit: '校验并登录', + wecomBindInputNotFound: '没有找到与你输入内容匹配的本站账号。', + wecomBindInputAmbiguous: '你输入的内容匹配到了多个本站账号,请联系管理员处理。', + wecomBindSessionExpired: '本次企业微信绑定会话已过期,请重新发起企业微信登录。', + wecomBindConflict: '当前企业微信账号已绑定到其他本站账号。', + wecomBindFieldNotAllowed: '当前选择的校验字段不被允许。', + wecomBindValueRequired: '请输入校验值。', + wecomFieldLabels: { + employee_id: '工号', + mobile: '手机号', + email: '邮箱', + match_rules: '匹配规则' + }, + wecomRuleJoin: { + and: '且', + or: '或' + }, + wecomFieldGuides: { + employee_id: '请管理员检查“工号来源字段”配置,并确认该成员在企业微信里能返回工号。', + mobile: '请管理员在企业微信通讯录中补齐该成员手机号,或调整匹配规则,不再强依赖手机号。', + email: '请管理员在企业微信通讯录中维护该成员邮箱,或调整匹配规则。', + default: '请管理员检查企业微信通讯录字段是否齐全,以及当前匹配规则是否合理。' + }, + wecomDialogTitles: { + matchAttrMissing: '企业微信资料不完整', + matchAmbiguous: '匹配到了多个本站账号', + bindRequired: '未找到可绑定的本站账号', + bindInputRequired: '首次绑定前需要人工校验', + bindConflict: '该企业微信账号已绑定到别的账号', + notInScope: '当前成员未被该应用授权', + stateExpired: '企业微信登录已过期', + accountDisabled: '本地账号已被禁用', + loginFailed: '企业微信登录失败' + }, + wecomDialogSummaries: { + matchAttrMissing: '企业微信没有返回“{field}”,所以系统无法按当前规则自动匹配你的本站账号。', + matchAmbiguous: '当前企业微信账号匹配到了多个本站账号,系统无法自动判断该登录哪一个。', + matchAmbiguousWithCount: '当前企业微信账号匹配到了 {count} 个本站账号,系统无法自动判断该登录哪一个。', + bindRequired: '企业微信侧认证已经成功,但本站没有找到符合当前规则的账号。', + bindInputRequired: '企业微信侧认证已经成功,请先输入一个本站字段完成首次绑定。', + bindConflict: '当前企业微信账号已经绑定到其他本站账号。', + notInScope: '当前成员不在企业微信应用可见范围内,或不是本企业成员。' + }, + wecomDialogDetails: { + currentRules: '当前匹配规则:{rules}', + bindFallback: '如果你已经有本站账号,可以请管理员先手动绑定当前企业微信账号。', + ambiguousAction: '请管理员清理重复的工号、手机号或邮箱数据,或者收紧匹配规则。', + bindRequiredAction: '请管理员先创建或绑定本站账号,或者开启自动创建用户。', + bindInputRequiredAction: '下一步请输入你的工号、手机号或邮箱中的一个,校验成功后就会把当前企业微信账号绑定到已有本站账号。', + bindConflictAction: '请管理员先解除旧绑定,再重新绑定当前企业微信账号。', + notInScopeAction: '请管理员到企业微信后台,把该成员或其所在部门加入该应用的可见范围。', + retryLogin: '请重新发起一次企业微信登录。', + contactAdmin: '如需帮助,请联系管理员。' + } }, landing: { hero: { @@ -827,7 +1055,8 @@ const messages = { denied: '您没有该应用的访问权限,请提交申请。', reason: '申请理由', submit: '提交申请' - } + }, + wecomEntryNotice: '已从企业微信消息进入,已为你准备好相关上下文。' }, admin: { title: '管理控制台', @@ -1066,6 +1295,16 @@ const messages = { wecom: { title: '企业微信绑定管理', subtitle: '手动绑定/解绑企业微信账号,并查看登录审计记录', + systemSettings: '企业微信系统配置', + integrationCopyTitle: '企微后台复制助手', + integrationCopyDesc: '以下字段可直接复制到企业微信管理后台对应配置项。', + integrationCopySecretsNote: + 'Token 与 EncodingAESKey 在未填写并保存前会显示为空:需与企微后台完全一致。可在上方填写后保存,或使用「生成」随机生成,再将相同值填入企微后台。', + publicBasePlaceholder: 'https://你的外网域名', + generateAddresses: '生成地址', + generateToken: '生成', + generateEncodingKey: '生成', + copy: '复制', refresh: '刷新', quickBind: '快速绑定', bind: '绑定', @@ -1074,13 +1313,71 @@ const messages = { boundOnly: '只看已绑定', noData: '暂无数据', auditTitle: '登录审计(最近 200 条)', + notifySettings: '触达设置', + notifyEnabled: '启用企微事件通知', + notifyBaseUrl: '深链基地址(例如:https://ai.company.com)', + notifyEvents: '启用事件(英文逗号分隔)', + notifyMetrics: '触达指标(近30天)', + metricTotal: '总触达', + metricSuccessRate: '发送成功率', + metricOpenedRate: '回流打开率', + metricWindowDays: '统计窗口(天)', exportAudit: '导出审计', noAuditData: '暂无审计记录', confirmUnbind: '确认解绑该用户的企业微信账号?', fields: { userId: '用户ID (user_id)', wecomUserId: '企业微信 UserId', - wecomUnionId: 'UnionId (可选)' + wecomUnionId: 'UnionId (可选)', + enabled: '启用企业微信登录', + autoCreateUser: '无匹配用户时自动创建', + corpId: '企业ID (CorpID)', + agentId: '应用AgentID', + secret: '应用Secret', + redirectUri: 'OAuth 回调地址', + matchRules: '匹配规则', + matchOperator: '匹配运算符', + firstLoginBindMode: '首次登录绑定模式', + firstLoginInputFields: '首次登录可输入字段', + employeeIdSource: '工号来源字段', + mobileNormalize: '手机号归一化', + publicBaseUrl: '外网 HTTPS 基地址' + }, + bindModes: { + match_rules: '按规则自动匹配', + input_verify: '要求用户输入校验' + }, + copyFields: { + publicBaseUrl: '外网基地址', + callbackUrl: '回调URL', + callbackToken: 'Token', + encodingAesKey: 'EncodingAESKey', + oauthRedirectUri: 'OAuth 回调地址', + homepageUrl: '应用主页URL', + trustedDomain: '可信域名', + authorizeApi: '授权说明接口 (GET)', + loginApi: '登录接口 (POST)' + }, + tips: { + enabled: '企业微信登录总开关。', + autoCreateUser: '未匹配到本地账号时,是否自动创建账号。', + corpId: '来自企业微信应用凭据。', + agentId: '企业微信自建应用中的 AgentId。', + secret: '用于获取 access_token 的应用密钥。', + redirectUri: '必须与企业微信配置的可信回调地址一致。', + matchRules: '支持 employee_id,mobile,email,英文逗号分隔。', + matchOperator: 'AND 表示全部字段都匹配,OR 表示任一字段匹配。', + firstLoginBindMode: 'match_rules 表示继续用企微资料自动匹配;input_verify 表示首次登录时要求员工输入一个字段完成绑定。', + firstLoginInputFields: '首次绑定允许员工输入的字段,英文逗号分隔。支持 employee_id,mobile,email。', + employeeIdSource: '可填 userid 或 extattr:<名称>。', + mobileNormalize: '匹配前会清洗 86/0086 前缀和分隔符。', + callbackToken: '用于回调签名校验。', + encodingAesKey: '用于安全模式消息解密。', + callbackUrl: '企业微信消息/事件回调接收地址。', + homepageUrl: '员工在企微内打开应用时访问的地址。', + trustedDomain: '企业微信 OAuth 可信域名。', + publicBaseUrl: + '企微服务器可访问的 HTTPS 根地址,用于生成回调与 OAuth 相关地址。优先级:本字段 → 触达深链基地址 → 当前访问主机。' }, headers: { user: '用户', @@ -1109,12 +1406,43 @@ const messages = { success: '成功', failed: '失败' }, + auditMessages: { + loginSuccess: '登录成功', + matchAttrMissing: '缺少用于匹配的字段:{field}', + matchAmbiguous: '匹配到了多个本站账号', + bindRequired: '未找到可绑定的本站账号', + bindInputRequired: '等待员工输入一个本站字段完成首次绑定', + bindInputNotFound: '员工输入的校验值未匹配到本站账号', + bindInputAmbiguous: '员工输入的校验值匹配到了多个本站账号', + bindConflict: '该企业微信账号已绑定到其他本站账号', + notInScope: '成员不在应用可见范围内,或不是本企业成员', + invalidState: '登录 state 无效或已过期', + missingCode: '回调中缺少 code', + accountDisabled: '本地账号已被禁用', + authFailed: '企业微信授权失败:{detail}', + userFetchFailed: '获取企业微信成员资料失败:{detail}', + exception: '异常:{detail}' + }, + auditMeta: { + rules: '规则:{rules}', + result: '结果:{result}', + errorCode: '代码:{code}' + }, + auditResults: { + already_bound: '通过已绑定的企业微信账号直接登录', + matched_and_bound: '按规则匹配并完成账号绑定', + auto_created: '自动创建本站账号并完成绑定', + input_verified_and_bound: '首次登录时经员工输入字段校验后完成绑定' + }, msg: { bindInputRequired: '请输入 user_id 与 wecom_userid', bindFailed: '绑定失败', bindSuccess: '绑定成功', unbindFailed: '解绑失败', - boundConflict: '该企业微信账号已被绑定:{detail}' + boundConflict: '该企业微信账号已被绑定:{detail}', + copySuccess: '已复制', + copyFailed: '复制失败', + publicBaseRequired: '请填写有效的外网 HTTPS 地址或域名(例如 https://ai.company.com)。' } }, @@ -1399,7 +1727,77 @@ const messages = { forgotPasswordDesc: '輸入您的郵箱以重設密碼', findPassword: '找回密碼', wecomLogin: '企業微信登錄', - wecomConnecting: '正在連接企業微信...' + wecomConnecting: '正在連接企業微信...', + wecomStartFailed: '啟動企業微信登錄失敗', + wecomInvalidState: '企業微信登入狀態無效', + wecomStateExpired: '企業微信登入會話已過期,請重試。', + wecomBindRequired: '當前企業微信帳號未綁定本地用戶,請聯繫管理員。', + wecomAccountDisabled: '帳號已被禁用,請聯繫管理員。', + wecomMatchAmbiguous: '該企業微信帳號匹配到多個本地帳號,請聯繫管理員處理。', + wecomMatchAttrMissing: '企業微信缺少必要匹配字段,請聯繫管理員。', + wecomLoginFailed: '企業微信登錄失敗', + wecomRetry: '重新發起企業微信登入', + wecomTechnicalInfo: '技術資訊:{detail}', + wecomBindPromptTitle: '首次登入請校驗並綁定本站帳號', + wecomBindPromptDesc: '當前企業微信身份為 {name}。請輸入一個允許的字段,用來綁定你已有的本站帳號。', + wecomBindField: '校驗字段', + wecomBindValue: '校驗值', + wecomBindValuePlaceholder: '請輸入你的{field}', + wecomBindPromptHint: '輸入值必須和本站已有帳號完全匹配。綁定成功後,當前企業微信帳號會自動寫回該用戶表。', + wecomBindSubmit: '校驗並登入', + wecomBindInputNotFound: '沒有找到與你輸入內容匹配的本站帳號。', + wecomBindInputAmbiguous: '你輸入的內容匹配到了多個本站帳號,請聯繫管理員處理。', + wecomBindSessionExpired: '本次企業微信綁定會話已過期,請重新發起企業微信登入。', + wecomBindConflict: '當前企業微信帳號已綁定到其他本站帳號。', + wecomBindFieldNotAllowed: '當前選擇的校驗字段不被允許。', + wecomBindValueRequired: '請輸入校驗值。', + wecomFieldLabels: { + employee_id: '工號', + mobile: '手機號', + email: '郵箱', + match_rules: '匹配規則' + }, + wecomRuleJoin: { + and: '且', + or: '或' + }, + wecomFieldGuides: { + employee_id: '請管理員檢查「工號來源字段」配置,並確認該成員在企業微信中能返回工號。', + mobile: '請管理員在企業微信通訊錄中補齊該成員手機號,或調整匹配規則,不再強依賴手機號。', + email: '請管理員在企業微信通訊錄中維護該成員郵箱,或調整匹配規則。', + default: '請管理員檢查企業微信通訊錄字段是否齊全,以及當前匹配規則是否合理。' + }, + wecomDialogTitles: { + matchAttrMissing: '企業微信資料不完整', + matchAmbiguous: '匹配到了多個本站帳號', + bindRequired: '未找到可綁定的本站帳號', + bindInputRequired: '首次綁定前需要人工校驗', + bindConflict: '該企業微信帳號已綁定到其他帳號', + notInScope: '當前成員未被該應用授權', + stateExpired: '企業微信登入已過期', + accountDisabled: '本地帳號已被禁用', + loginFailed: '企業微信登入失敗' + }, + wecomDialogSummaries: { + matchAttrMissing: '企業微信沒有返回「{field}」,所以系統無法按當前規則自動匹配你的本站帳號。', + matchAmbiguous: '當前企業微信帳號匹配到了多個本站帳號,系統無法自動判斷該登入哪一個。', + matchAmbiguousWithCount: '當前企業微信帳號匹配到了 {count} 個本站帳號,系統無法自動判斷該登入哪一個。', + bindRequired: '企業微信側驗證已成功,但本站沒有找到符合當前規則的帳號。', + bindInputRequired: '企業微信側驗證已成功,請先輸入一個本站字段完成首次綁定。', + bindConflict: '當前企業微信帳號已經綁定到其他本站帳號。', + notInScope: '當前成員不在企業微信應用可見範圍內,或不是本企業成員。' + }, + wecomDialogDetails: { + currentRules: '當前匹配規則:{rules}', + bindFallback: '如果你已經有本站帳號,可以請管理員先手動綁定當前企業微信帳號。', + ambiguousAction: '請管理員清理重複的工號、手機號或郵箱資料,或者收緊匹配規則。', + bindRequiredAction: '請管理員先建立或綁定本站帳號,或者開啟自動建立使用者。', + bindInputRequiredAction: '下一步請輸入你的工號、手機號或郵箱中的一個,校驗成功後就會把當前企業微信帳號綁定到已有本站帳號。', + bindConflictAction: '請管理員先解除舊綁定,再重新綁定當前企業微信帳號。', + notInScopeAction: '請管理員到企業微信後台,把該成員或其所在部門加入該應用的可見範圍。', + retryLogin: '請重新發起一次企業微信登入。', + contactAdmin: '如需協助,請聯繫管理員。' + } }, landing: { hero: { @@ -1490,7 +1888,8 @@ const messages = { denied: '您沒有該應用的訪問權限,請提交申請。', reason: '申請理由', submit: '提交申請' - } + }, + wecomEntryNotice: '已從企業微信消息進入,已為你準備好相關上下文。' }, admin: { title: '管理控制台', @@ -1729,6 +2128,16 @@ const messages = { wecom: { title: '企業微信綁定管理', subtitle: '手動綁定/解綁企業微信帳號,並查看登入審計記錄', + systemSettings: '企業微信系統配置', + integrationCopyTitle: '企微後台複製助手', + integrationCopyDesc: '以下字段可直接複製到企業微信管理後台對應配置項。', + integrationCopySecretsNote: + 'Token 與 EncodingAESKey 在未填寫並保存前會顯示為空:需與企微後台完全一致。可在上方填寫後保存,或使用「生成」隨機生成,再將相同值填入企微後台。', + publicBasePlaceholder: 'https://你的外網域名', + generateAddresses: '生成地址', + generateToken: '生成', + generateEncodingKey: '生成', + copy: '複製', refresh: '刷新', quickBind: '快速綁定', bind: '綁定', @@ -1737,13 +2146,76 @@ const messages = { boundOnly: '僅看已綁定', noData: '暫無資料', auditTitle: '登入審計(最近 200 條)', + notifySettings: '觸達設置', + notifyEnabled: '啟用企微事件通知', + notifyBaseUrl: '深鏈基地址(例如:https://ai.company.com)', + notifyEvents: '啟用事件(英文逗號分隔)', + notifyMetrics: '觸達指標(近30天)', + metricTotal: '總觸達', + metricSuccessRate: '發送成功率', + metricOpenedRate: '回流打開率', + metricWindowDays: '統計窗口(天)', exportAudit: '導出審計', noAuditData: '暫無審計記錄', confirmUnbind: '確認解綁該用戶的企業微信帳號?', fields: { userId: '用戶ID (user_id)', wecomUserId: '企業微信 UserId', - wecomUnionId: 'UnionId (可選)' + wecomUnionId: 'UnionId (可選)', + enabled: '啟用企業微信登入', + autoCreateUser: '無匹配用戶時自動建立', + corpId: '企業ID (CorpID)', + agentId: '應用AgentID', + secret: '應用Secret', + redirectUri: 'OAuth 回調地址', + matchRules: '匹配規則', + matchOperator: '匹配運算符', + firstLoginBindMode: '首次登入綁定模式', + firstLoginInputFields: '首次登入可輸入字段', + employeeIdSource: '工號來源字段', + mobileNormalize: '手機號歸一化', + callbackToken: '回調 Token', + encodingAesKey: 'EncodingAESKey', + callbackUrl: '回調URL', + homepageUrl: '應用主頁URL', + trustedDomain: '可信域名', + publicBaseUrl: '外網 HTTPS 基地址' + }, + bindModes: { + match_rules: '按規則自動匹配', + input_verify: '要求用戶輸入校驗' + }, + copyFields: { + publicBaseUrl: '外網基地址', + callbackUrl: '回調URL', + callbackToken: 'Token', + encodingAesKey: 'EncodingAESKey', + oauthRedirectUri: 'OAuth 回調地址', + homepageUrl: '應用主頁URL', + trustedDomain: '可信域名', + authorizeApi: '授權說明接口 (GET)', + loginApi: '登入接口 (POST)' + }, + tips: { + enabled: '企業微信登入總開關。', + autoCreateUser: '未匹配到本地帳號時,是否自動建立帳號。', + corpId: '來自企業微信應用憑據。', + agentId: '企業微信自建應用中的 AgentId。', + secret: '用於取得 access_token 的應用密鑰。', + redirectUri: '必須與企業微信配置的可信回調地址一致。', + matchRules: '支援 employee_id,mobile,email,英文逗號分隔。', + matchOperator: 'AND 表示全部字段都匹配,OR 表示任一字段匹配。', + firstLoginBindMode: 'match_rules 表示繼續用企微資料自動匹配;input_verify 表示首次登入時要求員工輸入一個字段完成綁定。', + firstLoginInputFields: '首次綁定允許員工輸入的字段,英文逗號分隔。支援 employee_id,mobile,email。', + employeeIdSource: '可填 userid 或 extattr:<名稱>。', + mobileNormalize: '匹配前會清洗 86/0086 前綴和分隔符。', + callbackToken: '用於回調簽章校驗。', + encodingAesKey: '用於安全模式訊息解密。', + callbackUrl: '企業微信訊息/事件回調接收地址。', + homepageUrl: '員工在企微內打開應用時訪問的地址。', + trustedDomain: '企業微信 OAuth 可信域名。', + publicBaseUrl: + '企微伺服器可訪問的 HTTPS 根地址,用於生成回調與 OAuth 相關地址。優先級:本字段 → 觸達深鏈基地址 → 當前訪問主機。' }, headers: { user: '用戶', @@ -1772,12 +2244,43 @@ const messages = { success: '成功', failed: '失敗' }, + auditMessages: { + loginSuccess: '登入成功', + matchAttrMissing: '缺少用於匹配的字段:{field}', + matchAmbiguous: '匹配到了多個本站帳號', + bindRequired: '未找到可綁定的本站帳號', + bindInputRequired: '等待員工輸入一個本站字段完成首次綁定', + bindInputNotFound: '員工輸入的校驗值未匹配到本站帳號', + bindInputAmbiguous: '員工輸入的校驗值匹配到了多個本站帳號', + bindConflict: '該企業微信帳號已綁定到其他本站帳號', + notInScope: '成員不在應用可見範圍內,或不是本企業成員', + invalidState: '登入 state 無效或已過期', + missingCode: '回調中缺少 code', + accountDisabled: '本地帳號已被禁用', + authFailed: '企業微信授權失敗:{detail}', + userFetchFailed: '獲取企業微信成員資料失敗:{detail}', + exception: '異常:{detail}' + }, + auditMeta: { + rules: '規則:{rules}', + result: '結果:{result}', + errorCode: '代碼:{code}' + }, + auditResults: { + already_bound: '透過已綁定的企業微信帳號直接登入', + matched_and_bound: '按規則匹配並完成帳號綁定', + auto_created: '自動建立本站帳號並完成綁定', + input_verified_and_bound: '首次登入時經員工輸入字段校驗後完成綁定' + }, msg: { bindInputRequired: '請輸入 user_id 與 wecom_userid', bindFailed: '綁定失敗', bindSuccess: '綁定成功', unbindFailed: '解綁失敗', - boundConflict: '該企業微信帳號已被綁定:{detail}' + boundConflict: '該企業微信帳號已被綁定:{detail}', + copySuccess: '已複製', + copyFailed: '複製失敗', + publicBaseRequired: '請填寫有效的外網 HTTPS 地址或域名(例如 https://ai.company.com)。' } }, @@ -2062,7 +2565,77 @@ const messages = { forgotPasswordDesc: 'กรอกอีเมลเพื่อรีเซ็ตรหัสผ่าน', findPassword: 'ค้นหารหัสผ่าน', wecomLogin: 'เข้าสู่ระบบด้วย WeCom', - wecomConnecting: 'กำลังเชื่อมต่อ WeCom...' + wecomConnecting: 'กำลังเชื่อมต่อ WeCom...', + wecomStartFailed: 'เริ่มต้นการเข้าสู่ระบบด้วย WeCom ไม่สำเร็จ', + wecomInvalidState: 'สถานะการเข้าสู่ระบบ WeCom ไม่ถูกต้อง', + wecomStateExpired: 'เซสชันการเข้าสู่ระบบ WeCom หมดอายุแล้ว กรุณาลองใหม่', + wecomBindRequired: 'บัญชี WeCom นี้ยังไม่เชื่อมกับผู้ใช้ในระบบ กรุณาติดต่อผู้ดูแลระบบ', + wecomAccountDisabled: 'บัญชีนี้ถูกปิดใช้งาน กรุณาติดต่อผู้ดูแลระบบ', + wecomMatchAmbiguous: 'บัญชี WeCom นี้ตรงกับผู้ใช้หลายบัญชี กรุณาติดต่อผู้ดูแลระบบ', + wecomMatchAttrMissing: 'ข้อมูลที่จำเป็นจาก WeCom ไม่ครบ กรุณาติดต่อผู้ดูแลระบบ', + wecomLoginFailed: 'เข้าสู่ระบบด้วย WeCom ล้มเหลว', + wecomRetry: 'ลองเข้าสู่ระบบ WeCom ใหม่', + wecomTechnicalInfo: 'ข้อมูลทางเทคนิค: {detail}', + wecomBindPromptTitle: 'ยืนยันและผูกบัญชีของคุณในการเข้าสู่ระบบครั้งแรก', + wecomBindPromptDesc: 'บัญชี WeCom ปัจจุบันคือ {name} กรุณากรอกข้อมูลที่อนุญาต 1 รายการเพื่อผูกกับบัญชีเดิมของคุณในระบบ', + wecomBindField: 'ฟิลด์สำหรับยืนยัน', + wecomBindValue: 'ค่ายืนยัน', + wecomBindValuePlaceholder: 'กรอก{field}ของคุณ', + wecomBindPromptHint: 'ค่าที่กรอกต้องตรงกับบัญชีที่มีอยู่ในระบบทุกตัวอักษร หากสำเร็จ ระบบจะผูกบัญชี WeCom นี้ให้อัตโนมัติ', + wecomBindSubmit: 'ยืนยันและเข้าสู่ระบบ', + wecomBindInputNotFound: 'ไม่พบบัญชีในระบบที่ตรงกับค่าที่คุณกรอก', + wecomBindInputAmbiguous: 'ค่าที่คุณกรอกตรงกับหลายบัญชีในระบบ กรุณาติดต่อผู้ดูแลระบบ', + wecomBindSessionExpired: 'เซสชันการผูกบัญชี WeCom นี้หมดอายุแล้ว กรุณาเริ่มการเข้าสู่ระบบ WeCom ใหม่', + wecomBindConflict: 'บัญชี WeCom นี้ถูกผูกกับบัญชีในระบบอื่นอยู่แล้ว', + wecomBindFieldNotAllowed: 'ไม่อนุญาตให้ใช้ฟิลด์นี้ในการยืนยัน', + wecomBindValueRequired: 'กรุณากรอกค่ายืนยัน', + wecomFieldLabels: { + employee_id: 'รหัสพนักงาน', + mobile: 'หมายเลขโทรศัพท์', + email: 'อีเมล', + match_rules: 'กฎการจับคู่' + }, + wecomRuleJoin: { + and: 'และ', + or: 'หรือ' + }, + wecomFieldGuides: { + employee_id: 'ให้ผู้ดูแลตรวจสอบการตั้งค่าแหล่งที่มาของรหัสพนักงาน และยืนยันว่าระบบ WeCom ส่งค่ารหัสพนักงานของสมาชิกคนนี้กลับมาได้', + mobile: 'ให้ผู้ดูแลกรอกหมายเลขโทรศัพท์ของสมาชิกคนนี้ในสมุดรายชื่อ WeCom หรือปรับกฎการจับคู่ไม่ให้บังคับใช้หมายเลขโทรศัพท์', + email: 'ให้ผู้ดูแลเพิ่มอีเมลของสมาชิกคนนี้ในสมุดรายชื่อ WeCom หรือปรับกฎการจับคู่', + default: 'ให้ผู้ดูแลตรวจสอบข้อมูลในสมุดรายชื่อ WeCom และกฎการจับคู่ปัจจุบัน' + }, + wecomDialogTitles: { + matchAttrMissing: 'ข้อมูลโปรไฟล์ WeCom ไม่ครบ', + matchAmbiguous: 'ตรงกับหลายบัญชีในระบบ', + bindRequired: 'ไม่พบบัญชีในระบบที่เชื่อมได้', + bindInputRequired: 'ต้องยืนยันก่อนผูกบัญชีครั้งแรก', + bindConflict: 'บัญชี WeCom นี้เชื่อมกับบัญชีอื่นอยู่แล้ว', + notInScope: 'สมาชิกคนนี้ยังไม่ได้รับสิทธิ์ในแอป', + stateExpired: 'การเข้าสู่ระบบ WeCom หมดอายุแล้ว', + accountDisabled: 'บัญชีในระบบถูกปิดใช้งาน', + loginFailed: 'เข้าสู่ระบบด้วย WeCom ล้มเหลว' + }, + wecomDialogSummaries: { + matchAttrMissing: 'WeCom ไม่ได้ส่งค่า "{field}" กลับมา จึงไม่สามารถจับคู่กับบัญชีในระบบของคุณโดยอัตโนมัติได้', + matchAmbiguous: 'บัญชี WeCom นี้ตรงกับหลายบัญชีในระบบ จึงไม่สามารถเลือกบัญชีที่จะเข้าสู่ระบบได้อัตโนมัติ', + matchAmbiguousWithCount: 'บัญชี WeCom นี้ตรงกับ {count} บัญชีในระบบ จึงไม่สามารถเลือกบัญชีที่จะเข้าสู่ระบบได้อัตโนมัติ', + bindRequired: 'การยืนยันตัวตนผ่าน WeCom สำเร็จแล้ว แต่ไม่พบบัญชีในระบบที่ตรงกับกฎปัจจุบัน', + bindInputRequired: 'การยืนยันตัวตนผ่าน WeCom สำเร็จแล้ว กรุณากรอกข้อมูลของบัญชีในระบบ 1 รายการเพื่อทำการผูกครั้งแรกให้เสร็จ', + bindConflict: 'บัญชี WeCom นี้เชื่อมกับบัญชีในระบบอื่นอยู่แล้ว', + notInScope: 'สมาชิกคนนี้อยู่นอกขอบเขตการมองเห็นของแอป หรือไม่ใช่สมาชิกขององค์กรนี้' + }, + wecomDialogDetails: { + currentRules: 'กฎการจับคู่ปัจจุบัน: {rules}', + bindFallback: 'หากคุณมีบัญชีในระบบอยู่แล้ว ให้ผู้ดูแลช่วยผูกบัญชี WeCom นี้ด้วยตนเอง', + ambiguousAction: 'ให้ผู้ดูแลล้างข้อมูลรหัสพนักงาน หมายเลขโทรศัพท์ หรืออีเมลที่ซ้ำกัน หรือปรับกฎการจับคู่ให้เข้มขึ้น', + bindRequiredAction: 'ให้ผู้ดูแลสร้างหรือผูกบัญชีในระบบก่อน หรือเปิดการสร้างผู้ใช้อัตโนมัติ', + bindInputRequiredAction: 'ในขั้นตอนถัดไป ให้กรอกรหัสพนักงาน หมายเลขโทรศัพท์ หรืออีเมลอย่างใดอย่างหนึ่ง เพื่อผูกบัญชี WeCom นี้กับบัญชีเดิมในระบบ', + bindConflictAction: 'ให้ผู้ดูแลยกเลิกการผูกเดิมก่อน แล้วจึงผูกบัญชี WeCom นี้อีกครั้ง', + notInScopeAction: 'ให้ผู้ดูแลเพิ่มสมาชิกคนนี้หรือแผนกของสมาชิกเข้าไปในขอบเขตการมองเห็นของแอป WeCom', + retryLogin: 'เริ่มต้นการเข้าสู่ระบบ WeCom ใหม่อีกครั้ง', + contactAdmin: 'กรุณาติดต่อผู้ดูแลระบบเพื่อขอความช่วยเหลือ' + } }, landing: { hero: { @@ -2153,7 +2726,8 @@ const messages = { denied: 'คุณไม่มีสิทธิ์เข้าถึงตัวแทนนี้ โปรดส่งคำขอ', reason: 'เหตุผลในการขอ', submit: 'ส่งคำขอ' - } + }, + wecomEntryNotice: 'เปิดมาจากข้อความ WeCom และเตรียมบริบทที่เกี่ยวข้องไว้ให้แล้ว' }, admin: { title: 'คอนโซลผู้ดูแลระบบ', @@ -2392,6 +2966,16 @@ const messages = { wecom: { title: 'การจัดการการผูกบัญชี WeCom', subtitle: 'ผูก/ยกเลิกการผูกบัญชี WeCom แบบแมนนวล และตรวจสอบบันทึกการเข้าสู่ระบบ', + systemSettings: 'การตั้งค่าระบบ WeCom', + integrationCopyTitle: 'ตัวช่วยคัดลอกค่าไปยังคอนโซล WeCom', + integrationCopyDesc: 'คัดลอกค่าด้านล่างไปใส่ในช่องที่ตรงกันในคอนโซลผู้ดูแล WeCom ได้โดยตรง', + integrationCopySecretsNote: + 'Token และ EncodingAESKey จะแสดงค่าว่างจนกว่าจะตั้งค่าและบันทึกด้านบน ต้องใช้ค่าเดียวกับในคอนโซล WeCom หากต้องการสุ่มค่าใหม่ ให้กดสร้าง แล้วนำค่าเดียวกันไปใส่ใน WeCom', + publicBasePlaceholder: 'https://your-public-domain.com', + generateAddresses: 'สร้าง URL', + generateToken: 'สร้าง', + generateEncodingKey: 'สร้าง', + copy: 'คัดลอก', refresh: 'รีเฟรช', quickBind: 'ผูกแบบรวดเร็ว', bind: 'ผูก', @@ -2400,13 +2984,76 @@ const messages = { boundOnly: 'แสดงเฉพาะที่ผูกแล้ว', noData: 'ไม่มีข้อมูล', auditTitle: 'บันทึกการเข้าสู่ระบบ (ล่าสุด 200 รายการ)', + notifySettings: 'การตั้งค่าการแจ้งเตือน', + notifyEnabled: 'เปิดใช้การแจ้งเตือนเหตุการณ์ WeCom', + notifyBaseUrl: 'Base URL สำหรับ deep link (เช่น https://ai.company.com)', + notifyEvents: 'เหตุการณ์ที่เปิดใช้ (คั่นด้วยจุลภาค)', + notifyMetrics: 'สถิติการส่ง (30 วัน)', + metricTotal: 'ทั้งหมด', + metricSuccessRate: 'อัตราส่งสำเร็จ', + metricOpenedRate: 'อัตราการเปิด', + metricWindowDays: 'ช่วงเวลา(วัน)', exportAudit: 'ส่งออกบันทึก', noAuditData: 'ไม่มีบันทึกการตรวจสอบ', confirmUnbind: 'ยืนยันยกเลิกการผูกบัญชี WeCom ของผู้ใช้นี้หรือไม่?', fields: { userId: 'รหัสผู้ใช้ (user_id)', wecomUserId: 'WeCom UserId', - wecomUnionId: 'UnionId (ไม่บังคับ)' + wecomUnionId: 'UnionId (ไม่บังคับ)', + enabled: 'เปิดใช้การเข้าสู่ระบบ WeCom', + autoCreateUser: 'สร้างผู้ใช้ในระบบอัตโนมัติเมื่อไม่พบการจับคู่', + corpId: 'Corp ID', + agentId: 'Agent ID', + secret: 'App Secret', + redirectUri: 'OAuth Redirect URI', + matchRules: 'กฎการจับคู่', + matchOperator: 'ตัวดำเนินการจับคู่', + firstLoginBindMode: 'โหมดการผูกบัญชีครั้งแรก', + firstLoginInputFields: 'ฟิลด์ที่ใช้กรอกในครั้งแรก', + employeeIdSource: 'แหล่งที่มาของรหัสพนักงาน', + mobileNormalize: 'ปรับรูปแบบเบอร์โทรศัพท์', + callbackToken: 'Callback Token', + encodingAesKey: 'EncodingAESKey', + callbackUrl: 'Callback URL', + homepageUrl: 'Application Homepage URL', + trustedDomain: 'Trusted Domain', + publicBaseUrl: 'Public HTTPS base' + }, + bindModes: { + match_rules: 'จับคู่อัตโนมัติ', + input_verify: 'ให้ผู้ใช้ยืนยันเอง' + }, + copyFields: { + publicBaseUrl: 'Public base URL', + callbackUrl: 'Callback URL', + callbackToken: 'Token', + encodingAesKey: 'EncodingAESKey', + oauthRedirectUri: 'OAuth Redirect URI', + homepageUrl: 'Application Homepage URL', + trustedDomain: 'Trusted Domain', + authorizeApi: 'Authorize API (GET)', + loginApi: 'Login API (POST)' + }, + tips: { + enabled: 'สวิตช์หลักสำหรับการเข้าสู่ระบบ WeCom', + autoCreateUser: 'หากไม่พบผู้ใช้ในระบบ ให้สร้างใหม่อัตโนมัติ', + corpId: 'รับมาจากข้อมูลแอป WeCom', + agentId: 'AgentId ของแอปที่สร้างเองใน WeCom', + secret: 'ความลับของแอปสำหรับขอ access token', + redirectUri: 'ต้องตรงกับ trusted callback URL ที่ตั้งไว้ใน WeCom', + matchRules: 'รองรับ employee_id,mobile,email คั่นด้วยจุลภาค', + matchOperator: 'AND = ต้องตรงทุกฟิลด์, OR = ตรงอย่างน้อยหนึ่งฟิลด์', + firstLoginBindMode: 'match_rules = ใช้ข้อมูลจาก WeCom จับคู่อัตโนมัติ, input_verify = ให้ผู้ใช้กรอกหนึ่งฟิลด์ในครั้งแรกเพื่อผูกบัญชี', + firstLoginInputFields: 'ฟิลด์ที่อนุญาตให้กรอกในการผูกครั้งแรก คั่นด้วยจุลภาค รองรับ employee_id,mobile,email', + employeeIdSource: 'ใช้ userid หรือ extattr:', + mobileNormalize: 'ล้างคำนำหน้า 86/0086 และสัญลักษณ์ก่อนจับคู่', + callbackToken: 'ใช้สำหรับตรวจสอบลายเซ็น callback', + encodingAesKey: 'ใช้กับ callback แบบเข้ารหัส', + callbackUrl: 'URL สำหรับรับ callback ของข้อความ/เหตุการณ์จาก WeCom', + homepageUrl: 'หน้าแรกของแอปที่เปิดใน WeCom', + trustedDomain: 'โดเมนที่เชื่อถือได้สำหรับ OAuth ใน WeCom', + publicBaseUrl: + 'ต้นทาง HTTPS ที่เข้าถึงได้จากภายนอกสำหรับเซิร์ฟเวอร์ WeCom ใช้สร้าง URL callback และ OAuth ลำดับความสำคัญ: ช่องนี้ → notify base URL → host ปัจจุบัน' }, headers: { user: 'ผู้ใช้', @@ -2435,12 +3082,43 @@ const messages = { success: 'สำเร็จ', failed: 'ล้มเหลว' }, + auditMessages: { + loginSuccess: 'เข้าสู่ระบบสำเร็จ', + matchAttrMissing: 'ขาดฟิลด์ที่จำเป็นสำหรับการจับคู่: {field}', + matchAmbiguous: 'ตรงกับหลายบัญชีในระบบ', + bindRequired: 'ไม่พบบัญชีในระบบที่เชื่อมได้', + bindInputRequired: 'กำลังรอให้ผู้ใช้กรอกข้อมูลบัญชีในระบบเพื่อผูกครั้งแรก', + bindInputNotFound: 'ค่าที่ยืนยันโดยผู้ใช้ไม่ตรงกับบัญชีใดในระบบ', + bindInputAmbiguous: 'ค่าที่ยืนยันโดยผู้ใช้ตรงกับหลายบัญชีในระบบ', + bindConflict: 'บัญชี WeCom นี้เชื่อมกับบัญชีในระบบอื่นอยู่แล้ว', + notInScope: 'สมาชิกอยู่นอกขอบเขตการมองเห็นของแอป หรือไม่ใช่สมาชิกขององค์กรนี้', + invalidState: 'สถานะการเข้าสู่ระบบไม่ถูกต้องหรือหมดอายุ', + missingCode: 'callback ไม่มี code', + accountDisabled: 'บัญชีในระบบถูกปิดใช้งาน', + authFailed: 'การยืนยันตัวตนผ่าน WeCom ล้มเหลว: {detail}', + userFetchFailed: 'ดึงข้อมูลสมาชิกจาก WeCom ไม่สำเร็จ: {detail}', + exception: 'ข้อผิดพลาด: {detail}' + }, + auditMeta: { + rules: 'กฎ: {rules}', + result: 'ผลลัพธ์: {result}', + errorCode: 'โค้ด: {code}' + }, + auditResults: { + already_bound: 'เข้าสู่ระบบผ่านบัญชี WeCom ที่ผูกไว้แล้ว', + matched_and_bound: 'จับคู่ตามกฎและผูกบัญชีสำเร็จ', + auto_created: 'สร้างบัญชีในระบบอัตโนมัติและผูกสำเร็จ', + input_verified_and_bound: 'ยืนยันหนึ่งฟิลด์ในการเข้าสู่ระบบครั้งแรกและผูกบัญชีสำเร็จ' + }, msg: { bindInputRequired: 'กรุณากรอก user_id และ wecom_userid', bindFailed: 'ผูกบัญชีไม่สำเร็จ', bindSuccess: 'ผูกบัญชีสำเร็จ', unbindFailed: 'ยกเลิกการผูกไม่สำเร็จ', - boundConflict: 'บัญชี WeCom นี้ถูกผูกไว้แล้ว: {detail}' + boundConflict: 'บัญชี WeCom นี้ถูกผูกไว้แล้ว: {detail}', + copySuccess: 'คัดลอกแล้ว', + copyFailed: 'คัดลอกไม่สำเร็จ', + publicBaseRequired: 'กรอกโดเมนหรือที่อยู่ HTTPS ภายนอกที่ถูกต้อง เช่น https://ai.company.com' } }, diff --git a/frontend/src/utils/wecom.ts b/frontend/src/utils/wecom.ts new file mode 100644 index 00000000..5cb28a90 --- /dev/null +++ b/frontend/src/utils/wecom.ts @@ -0,0 +1,331 @@ +export type WecomMatchField = 'employee_id' | 'mobile' | 'email'; + +export interface WecomNormalizedMatchRules { + operator: 'AND' | 'OR'; + fields: WecomMatchField[]; +} + +export interface WecomLoginErrorPayload { + error?: string | null; + error_code?: string | null; + reason?: string | null; + missing_field?: string | null; + candidate_count?: number | null; + match_rules?: unknown; +} + +export interface WecomLoginDialogContent { + title: string; + summary: string; + details: string[]; + technical?: string; +} + +export interface WecomAuditRowLike { + status?: string | null; + reason?: string | null; + error_code?: string | null; + match_rules?: string | null; + match_operator?: string | null; + match_result?: string | null; +} + +type TranslateFn = (key: string, params?: Record) => string; + +const KNOWN_MATCH_FIELDS: WecomMatchField[] = ['employee_id', 'mobile', 'email']; + +function cleanText(value: unknown): string { + return typeof value === 'string' ? value.trim() : String(value ?? '').trim(); +} + +function normalizeMatchField(value: unknown): WecomMatchField | null { + const normalized = cleanText(value).toLowerCase(); + return KNOWN_MATCH_FIELDS.includes(normalized as WecomMatchField) + ? (normalized as WecomMatchField) + : null; +} + +function getFieldGuide(field: WecomMatchField | null, t: TranslateFn): string { + if (field === 'mobile') return t('login.wecomFieldGuides.mobile'); + if (field === 'email') return t('login.wecomFieldGuides.email'); + if (field === 'employee_id') return t('login.wecomFieldGuides.employee_id'); + return t('login.wecomFieldGuides.default'); +} + +function extractMissingField(reason: string): WecomMatchField | null { + if (!reason.startsWith('missing_attr:')) return null; + return normalizeMatchField(reason.split(':', 2)[1]); +} + +function formatRuleList(fields: WecomMatchField[], operator: 'AND' | 'OR', t: TranslateFn): string { + if (fields.length === 0) return t('login.wecomFieldLabels.match_rules'); + const labels = fields.map((field) => formatWecomFieldLabel(field, t)); + if (labels.length === 1) return labels[0] || t('login.wecomFieldLabels.match_rules'); + const joiner = operator === 'OR' ? ` ${t('login.wecomRuleJoin.or')} ` : ` ${t('login.wecomRuleJoin.and')} `; + return labels.join(joiner); +} + +function buildTechnicalInfo(errorCode: string, rawError: string): string | undefined { + const parts: string[] = []; + if (errorCode) parts.push(`code=${errorCode}`); + if (rawError) parts.push(rawError); + return parts.length ? parts.join(' | ') : undefined; +} + +export function normalizeWecomMatchRules( + input: unknown, + fallbackOperator: unknown = 'AND', +): WecomNormalizedMatchRules { + let fieldsSource: unknown[] = []; + let operator: 'AND' | 'OR' = cleanText(fallbackOperator).toUpperCase() === 'OR' ? 'OR' : 'AND'; + + if (Array.isArray(input)) { + fieldsSource = input; + } else if (typeof input === 'string') { + fieldsSource = input.split(','); + } else if (input && typeof input === 'object') { + const maybeRules = input as Record; + fieldsSource = Array.isArray(maybeRules.fields) ? maybeRules.fields : []; + operator = cleanText(maybeRules.operator).toUpperCase() === 'OR' ? 'OR' : operator; + } + + const fields = fieldsSource + .map((value) => normalizeMatchField(value)) + .filter((value): value is WecomMatchField => Boolean(value)); + + return { operator, fields }; +} + +export function formatWecomFieldLabel(field: unknown, t: TranslateFn): string { + const normalized = normalizeMatchField(field); + if (normalized === 'employee_id') return t('login.wecomFieldLabels.employee_id'); + if (normalized === 'mobile') return t('login.wecomFieldLabels.mobile'); + if (normalized === 'email') return t('login.wecomFieldLabels.email'); + return t('login.wecomFieldLabels.match_rules'); +} + +export function formatWecomRuleText( + input: unknown, + t: TranslateFn, + fallbackOperator: unknown = 'AND', +): string { + const rules = normalizeWecomMatchRules(input, fallbackOperator); + return formatRuleList(rules.fields, rules.operator, t); +} + +export function buildWecomLoginDialogContent( + payload: WecomLoginErrorPayload, + t: TranslateFn, +): WecomLoginDialogContent { + const rawError = cleanText(payload.error); + const errorCode = cleanText(payload.error_code); + const reason = cleanText(payload.reason); + const rulesText = formatWecomRuleText(payload.match_rules, t); + const technical = buildTechnicalInfo(errorCode, rawError); + + if (errorCode === 'WECOM_MATCH_ATTR_MISSING') { + const missingField = normalizeMatchField(payload.missing_field) || extractMissingField(reason); + return { + title: t('login.wecomDialogTitles.matchAttrMissing'), + summary: t('login.wecomDialogSummaries.matchAttrMissing', { + field: formatWecomFieldLabel(missingField, t), + }), + details: [ + t('login.wecomDialogDetails.currentRules', { rules: rulesText }), + getFieldGuide(missingField, t), + t('login.wecomDialogDetails.bindFallback'), + ], + technical, + }; + } + + if (errorCode === 'WECOM_MATCH_AMBIGUOUS') { + const candidateCount = Number(payload.candidate_count || 0); + return { + title: t('login.wecomDialogTitles.matchAmbiguous'), + summary: candidateCount > 1 + ? t('login.wecomDialogSummaries.matchAmbiguousWithCount', { count: candidateCount }) + : t('login.wecomDialogSummaries.matchAmbiguous'), + details: [ + t('login.wecomDialogDetails.currentRules', { rules: rulesText }), + t('login.wecomDialogDetails.ambiguousAction'), + ], + technical, + }; + } + + if (errorCode === 'WECOM_BIND_REQUIRED') { + return { + title: t('login.wecomDialogTitles.bindRequired'), + summary: t('login.wecomDialogSummaries.bindRequired'), + details: [ + t('login.wecomDialogDetails.currentRules', { rules: rulesText }), + t('login.wecomDialogDetails.bindRequiredAction'), + ], + technical, + }; + } + + if (errorCode === 'WECOM_BIND_INPUT_REQUIRED') { + return { + title: t('login.wecomDialogTitles.bindInputRequired'), + summary: t('login.wecomDialogSummaries.bindInputRequired'), + details: [ + t('login.wecomDialogDetails.bindInputRequiredAction'), + ], + technical, + }; + } + + if (errorCode === 'WECOM_BIND_CONFLICT') { + return { + title: t('login.wecomDialogTitles.bindConflict'), + summary: t('login.wecomDialogSummaries.bindConflict'), + details: [ + rawError || t('login.wecomDialogDetails.bindConflictAction'), + t('login.wecomDialogDetails.bindConflictAction'), + ], + technical, + }; + } + + if (errorCode === 'WECOM_NOT_IN_AGENT_SCOPE') { + return { + title: t('login.wecomDialogTitles.notInScope'), + summary: t('login.wecomDialogSummaries.notInScope'), + details: [ + rawError || t('login.wecomDialogDetails.notInScopeAction'), + ], + technical, + }; + } + + if (rawError.includes('Invalid or expired WeCom state')) { + return { + title: t('login.wecomDialogTitles.stateExpired'), + summary: t('login.wecomStateExpired'), + details: [t('login.wecomDialogDetails.retryLogin')], + technical, + }; + } + + if (rawError.includes('Account is disabled')) { + return { + title: t('login.wecomDialogTitles.accountDisabled'), + summary: t('login.wecomAccountDisabled'), + details: [t('login.wecomDialogDetails.contactAdmin')], + technical, + }; + } + + if (rawError.includes('bind WeCom account') || rawError.includes('No linked account found')) { + return { + title: t('login.wecomDialogTitles.bindRequired'), + summary: t('login.wecomDialogSummaries.bindRequired'), + details: [ + t('login.wecomDialogDetails.currentRules', { rules: rulesText }), + t('login.wecomDialogDetails.bindRequiredAction'), + ], + technical, + }; + } + + return { + title: t('login.wecomDialogTitles.loginFailed'), + summary: rawError || t('login.wecomLoginFailed'), + details: [t('login.wecomDialogDetails.retryLogin')], + technical, + }; +} + +function formatWecomMatchResult(result: string, t: TranslateFn): string { + if (result === 'already_bound') return t('admin.wecom.auditResults.already_bound'); + if (result === 'matched_and_bound') return t('admin.wecom.auditResults.matched_and_bound'); + if (result === 'auto_created') return t('admin.wecom.auditResults.auto_created'); + if (result === 'input_verified_and_bound') return t('admin.wecom.auditResults.input_verified_and_bound'); + return result || '-'; +} + +export function formatWecomAuditReason(row: WecomAuditRowLike, t: TranslateFn): string { + const reason = cleanText(row.reason); + const errorCode = cleanText(row.error_code); + + if (cleanText(row.status) === 'success') { + const result = cleanText(row.match_result); + return result ? formatWecomMatchResult(result, t) : t('admin.wecom.auditMessages.loginSuccess'); + } + + if (errorCode === 'WECOM_MATCH_ATTR_MISSING') { + const field = extractMissingField(reason); + return t('admin.wecom.auditMessages.matchAttrMissing', { + field: formatWecomFieldLabel(field, t), + }); + } + + if (errorCode === 'WECOM_MATCH_AMBIGUOUS') { + return t('admin.wecom.auditMessages.matchAmbiguous'); + } + + if (errorCode === 'WECOM_BIND_REQUIRED') { + return t('admin.wecom.auditMessages.bindRequired'); + } + + if (errorCode === 'WECOM_BIND_CONFLICT') { + return t('admin.wecom.auditMessages.bindConflict'); + } + + if (errorCode === 'WECOM_BIND_INPUT_REQUIRED') { + return t('admin.wecom.auditMessages.bindInputRequired'); + } + + if (errorCode === 'WECOM_BIND_INPUT_NOT_FOUND') { + return t('admin.wecom.auditMessages.bindInputNotFound'); + } + + if (errorCode === 'WECOM_BIND_INPUT_AMBIGUOUS') { + return t('admin.wecom.auditMessages.bindInputAmbiguous'); + } + + if (errorCode === 'WECOM_NOT_IN_AGENT_SCOPE') { + return t('admin.wecom.auditMessages.notInScope'); + } + + if (reason === 'invalid_state') return t('admin.wecom.auditMessages.invalidState'); + if (reason === 'missing_code') return t('admin.wecom.auditMessages.missingCode'); + if (reason === 'account_disabled') return t('admin.wecom.auditMessages.accountDisabled'); + if (reason.startsWith('auth_failed:')) { + return t('admin.wecom.auditMessages.authFailed', { + detail: reason.split(':', 2)[1] || '-', + }); + } + if (reason.startsWith('user_fetch_failed:')) { + return t('admin.wecom.auditMessages.userFetchFailed', { + detail: reason.split(':', 2)[1] || '-', + }); + } + if (reason.startsWith('not_in_agent_scope:')) return t('admin.wecom.auditMessages.notInScope'); + if (reason.startsWith('exception:')) { + return t('admin.wecom.auditMessages.exception', { + detail: reason.split(':', 2)[1] || '-', + }); + } + + return reason || '-'; +} + +export function buildWecomAuditMeta(row: WecomAuditRowLike, t: TranslateFn): string[] { + const items: string[] = []; + const rulesText = formatWecomRuleText(row.match_rules, t, row.match_operator); + if (cleanText(row.match_rules)) { + items.push(t('admin.wecom.auditMeta.rules', { rules: rulesText })); + } + if (cleanText(row.match_result)) { + items.push(t('admin.wecom.auditMeta.result', { + result: formatWecomMatchResult(cleanText(row.match_result), t), + })); + } + if (cleanText(row.error_code)) { + items.push(t('admin.wecom.auditMeta.errorCode', { code: cleanText(row.error_code) })); + } + return items; +} diff --git a/frontend/src/views/AdminView.vue b/frontend/src/views/AdminView.vue index 73c100a7..c8468ebc 100644 --- a/frontend/src/views/AdminView.vue +++ b/frontend/src/views/AdminView.vue @@ -15,6 +15,7 @@ import { useI18n } from 'vue-i18n'; import { config } from '../config'; import ThemeToggleButton from '../components/ThemeToggleButton.vue'; import { loadReportLayoutPref, saveReportLayoutPref } from '../composables/useReportLayoutStorage'; +import { buildWecomAuditMeta, formatWecomAuditReason } from '../utils/wecom'; import { ArrowLeft, // Save, @@ -38,7 +39,8 @@ import { Megaphone, Link2, Unlink2, - RefreshCw + RefreshCw, + CircleHelp } from 'lucide-vue-next'; import * as XLSX from 'xlsx'; @@ -157,6 +159,61 @@ interface LoginAuditRow { ip?: string | null; user_agent?: string | null; created_at?: string | null; + error_code?: string | null; + match_rules?: string | null; + match_operator?: string | null; + match_result?: string | null; +} + +interface WecomNotifySettings { + enabled: boolean; + base_url: string; + events: string[]; +} + +interface WecomNotifyMetrics { + window_days: number; + total: number; + sent: number; + failed: number; + send_success_rate: number; + opened_24h: number; + opened_24h_rate: number; + by_event: Record; +} + +interface WecomSystemSettings { + enabled: boolean; + corp_id: string; + agent_id: string; + secret: string; + redirect_uri: string; + auto_create_user: boolean; + match_rules: string; + match_operator: 'AND' | 'OR'; + first_login_bind_mode: 'match_rules' | 'input_verify'; + first_login_input_fields: string; + employee_id_source: string; + mobile_normalize: boolean; + callback_token: string; + encoding_aes_key: string; + callback_url: string; + homepage_url: string; + trusted_domain: string; + /** HTTPS origin shown to WeCom (e.g. https://ai.company.com) */ + public_base_url: string; +} + +interface WecomIntegrationManifest { + public_base_url: string; + callback_url: string; + callback_token: string; + encoding_aes_key: string; + oauth_redirect_uri: string; + homepage_url: string; + trusted_domain: string; + authorize_api: string; + login_api: string; } // 获取路由实例,用于页面跳转 @@ -316,6 +373,34 @@ const wecomBoundOnly = ref(false); const wecomAuditSourceFilter = ref<'all' | 'wecom' | 'password'>('all'); const wecomAuditStatusFilter = ref<'all' | 'success' | 'failed'>('all'); const filteredWecomLoginAudits = computed(() => wecomLoginAudits.value); +const wecomNotifySettings = ref({ + enabled: true, + base_url: '', + events: [], +}); +const wecomNotifyEventsText = ref(''); +const wecomNotifyMetrics = ref(null); +const wecomSystemSettings = ref({ + enabled: true, + corp_id: '', + agent_id: '', + secret: '', + redirect_uri: '', + auto_create_user: true, + match_rules: 'employee_id,mobile', + match_operator: 'AND', + first_login_bind_mode: 'match_rules', + first_login_input_fields: 'employee_id,mobile,email', + employee_id_source: 'userid', + mobile_normalize: true, + callback_token: '', + encoding_aes_key: '', + callback_url: '', + homepage_url: '', + trusted_domain: '', + public_base_url: '', +}); +const wecomIntegrationManifest = ref(null); // Batch Operation Refs const selectedUserIds = ref([]); @@ -750,8 +835,210 @@ const loadWecomAudits = async () => { } }; +const loadWecomSystemSettings = async () => { + try { + const res = await fetch('/api/admin/wecom/system-settings', { headers: getAuthHeaders() }); + if (res.ok) { + wecomSystemSettings.value = await res.json(); + } + } catch (e) { + console.error('Error loading WeCom system settings:', e); + } +}; + +const loadWecomIntegrationManifest = async () => { + try { + const res = await fetch('/api/admin/wecom/integration-manifest', { headers: getAuthHeaders() }); + if (res.ok) { + wecomIntegrationManifest.value = await res.json(); + } + } catch (e) { + console.error('Error loading WeCom integration manifest:', e); + } +}; + +const copyText = async (text: string) => { + if (!text) return; + try { + await navigator.clipboard.writeText(text); + alert(t('admin.wecom.msg.copySuccess')); + } catch (e) { + console.error(e); + alert(t('admin.wecom.msg.copyFailed')); + } +}; + +const getWecomAuditReasonText = (row: LoginAuditRow) => formatWecomAuditReason(row, t); + +const getWecomAuditMetaText = (row: LoginAuditRow) => buildWecomAuditMeta(row, t).join(' | '); + +function normalizeWecomPublicBase(input: string): string | null { + const raw = (input || '').trim(); + if (!raw) return null; + let url = raw; + if (!/^https?:\/\//i.test(url)) url = `https://${url}`; + url = url.replace(/\/+$/, ''); + try { + const u = new URL(url); + if (!u.hostname) return null; + return `${u.protocol}//${u.host}`; + } catch { + return null; + } +} + +function ensureWecomIntegrationManifest() { + if (!wecomIntegrationManifest.value) { + wecomIntegrationManifest.value = { + public_base_url: '', + callback_url: '', + callback_token: '', + encoding_aes_key: '', + oauth_redirect_uri: '', + homepage_url: '', + trusted_domain: '', + authorize_api: '', + login_api: '', + }; + } +} + +function patchWecomIntegrationManifestFromSettings() { + ensureWecomIntegrationManifest(); + const s = wecomSystemSettings.value; + const base = normalizeWecomPublicBase(s.public_base_url); + const prev = wecomIntegrationManifest.value!; + wecomIntegrationManifest.value = { + ...prev, + callback_token: s.callback_token || '', + encoding_aes_key: s.encoding_aes_key || '', + }; + if (!base) return; + wecomIntegrationManifest.value = { + ...wecomIntegrationManifest.value!, + public_base_url: base, + callback_url: s.callback_url || `${base}/api/user/wecom/callback`, + oauth_redirect_uri: s.redirect_uri || `${base}/workspace`, + homepage_url: s.homepage_url || `${base}/workspace`, + trusted_domain: s.trusted_domain || new URL(base).hostname, + authorize_api: `${base}/api/user/wecom/authorize-url`, + login_api: `${base}/api/user/wecom/login`, + }; +} + +function generateWecomAddressesFromPublicBase() { + const base = normalizeWecomPublicBase(wecomSystemSettings.value.public_base_url); + if (!base) { + alert(t('admin.wecom.msg.publicBaseRequired')); + return; + } + const host = new URL(base).hostname; + wecomSystemSettings.value.callback_url = `${base}/api/user/wecom/callback`; + wecomSystemSettings.value.homepage_url = `${base}/workspace`; + wecomSystemSettings.value.trusted_domain = host; + wecomSystemSettings.value.redirect_uri = `${base}/workspace`; + patchWecomIntegrationManifestFromSettings(); +} + +function generateWecomCallbackToken() { + const bytes = new Uint8Array(24); + crypto.getRandomValues(bytes); + const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join(''); + wecomSystemSettings.value.callback_token = hex; + patchWecomIntegrationManifestFromSettings(); +} + +function generateWecomEncodingAesKey() { + const bytes = new Uint8Array(32); + crypto.getRandomValues(bytes); + let bin = ''; + for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]!); + const b64 = btoa(bin); + const key43 = b64.replace(/=+$/, ''); + wecomSystemSettings.value.encoding_aes_key = key43; + patchWecomIntegrationManifestFromSettings(); +} + +const saveWecomSystemSettings = async () => { + isSaving.value = true; + try { + const payload = { + ...wecomSystemSettings.value, + match_operator: (wecomSystemSettings.value.match_operator || 'AND').toUpperCase(), + }; + const res = await fetch('/api/admin/wecom/system-settings', { + method: 'PUT', + headers: { 'Content-Type': 'application/json', ...getAuthHeaders() }, + body: JSON.stringify(payload), + }); + const data = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(data.error || t('admin.msg.failed')); + wecomSystemSettings.value = data.settings || wecomSystemSettings.value; + await loadWecomIntegrationManifest(); + } catch (e: any) { + console.error(e); + alert(e.message || t('admin.msg.requestFailed')); + } finally { + isSaving.value = false; + } +}; + +const loadWecomNotifySettings = async () => { + try { + const res = await fetch('/api/admin/wecom/notify-settings', { headers: getAuthHeaders() }); + if (res.ok) { + wecomNotifySettings.value = await res.json(); + wecomNotifyEventsText.value = (wecomNotifySettings.value.events || []).join(','); + } + } catch (e) { + console.error('Error loading WeCom notify settings:', e); + } +}; + +const saveWecomNotifySettings = async () => { + isSaving.value = true; + try { + wecomNotifySettings.value.events = wecomNotifyEventsText.value + .split(',') + .map((x) => x.trim()) + .filter(Boolean); + const res = await fetch('/api/admin/wecom/notify-settings', { + method: 'PUT', + headers: { 'Content-Type': 'application/json', ...getAuthHeaders() }, + body: JSON.stringify(wecomNotifySettings.value), + }); + const data = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(data.error || t('admin.msg.failed')); + wecomNotifySettings.value = data.settings || wecomNotifySettings.value; + await loadWecomNotifyMetrics(); + } catch (e: any) { + console.error(e); + alert(e.message || t('admin.msg.requestFailed')); + } finally { + isSaving.value = false; + } +}; + +const loadWecomNotifyMetrics = async () => { + try { + const res = await fetch('/api/admin/wecom/notify-metrics', { headers: getAuthHeaders() }); + if (res.ok) { + wecomNotifyMetrics.value = await res.json(); + } + } catch (e) { + console.error('Error loading WeCom notify metrics:', e); + } +}; + const refreshWecomData = async () => { - await Promise.all([loadWecomBindings(), loadWecomAudits()]); + await Promise.all([ + loadWecomBindings(), + loadWecomAudits(), + loadWecomSystemSettings(), + loadWecomIntegrationManifest(), + loadWecomNotifySettings(), + loadWecomNotifyMetrics(), + ]); }; const bindWecomUser = async () => { @@ -819,7 +1106,12 @@ const exportWecomAudits = () => { Source: row.source || '', Username: row.username || '', Status: row.status || '', - Reason: row.reason || '', + Reason: getWecomAuditReasonText(row), + Meta: getWecomAuditMetaText(row), + ErrorCode: row.error_code || '', + MatchRules: row.match_rules || '', + MatchOperator: row.match_operator || '', + MatchResult: row.match_result || '', IP: row.ip || '', WecomUserId: row.wecom_userid || '', UserAgent: row.user_agent || '', @@ -2864,6 +3156,227 @@ const handlePermissionImport = async (event: Event) => { +
+

{{ t('admin.wecom.systemSettings') }}

+
+ + +
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+ + +
+
+
+ +
+ + +
+
+
+ +
+ + +
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ +
+
+ +
+
+ +
+
+

{{ t('admin.wecom.notifySettings') }}

+ + + +
+ +
+
+
+

{{ t('admin.wecom.notifyMetrics') }}

+
+
+
{{ t('admin.wecom.metricTotal') }}
+
{{ wecomNotifyMetrics.total }}
+
+
+
{{ t('admin.wecom.metricSuccessRate') }}
+
{{ wecomNotifyMetrics.send_success_rate }}%
+
+
+
{{ t('admin.wecom.metricOpenedRate') }}
+
{{ wecomNotifyMetrics.opened_24h_rate }}%
+
+
+
{{ t('admin.wecom.metricWindowDays') }}
+
{{ wecomNotifyMetrics.window_days }}
+
+
+
+
+ +
+

{{ t('admin.wecom.integrationCopyTitle') }}

+

{{ t('admin.wecom.integrationCopyDesc') }}

+

{{ t('admin.wecom.integrationCopySecretsNote') }}

+
+
+ +
+ + +
+
+
+
+

{{ t('admin.wecom.bindingList') }}

@@ -2959,7 +3472,14 @@ const handlePermissionImport = async (event: Event) => { {{ t('admin.wecom.auditStatus.' + row.status) }} - {{ row.reason || '-' }} + +
+
{{ getWecomAuditReasonText(row) }}
+
+ {{ getWecomAuditMetaText(row) }} +
+
+ {{ row.ip || '-' }} @@ -3708,4 +4228,3 @@ const handlePermissionImport = async (event: Event) => {
- diff --git a/frontend/src/views/WorkspaceView.vue b/frontend/src/views/WorkspaceView.vue index 11315677..185af22a 100644 --- a/frontend/src/views/WorkspaceView.vue +++ b/frontend/src/views/WorkspaceView.vue @@ -9,6 +9,13 @@ import { useRouter } from 'vue-router'; import { useI18n } from 'vue-i18n'; import { config } from '../config'; import ThemeToggleButton from '../components/ThemeToggleButton.vue'; +import { + buildWecomLoginDialogContent, + formatWecomFieldLabel, + normalizeWecomMatchRules, + type WecomLoginDialogContent, + type WecomMatchField, +} from '../utils/wecom'; import { Settings, LayoutGrid, @@ -81,6 +88,16 @@ interface Announcement { created_at: string; } +interface WecomBindPromptState { + binding_token: string; + allowed_fields: WecomMatchField[]; + wecom_name?: string; + field: WecomMatchField; + value: string; + submitting: boolean; + error: string; +} + // State const isLoading = ref(true); const currentUser = ref<{ id: number; username: string; role: string; default_agent_id?: number | null } | null>(null); @@ -118,6 +135,14 @@ const registerForm = ref({ username: '', password: '', email: '', real_name: '', const forgotPasswordForm = ref({ email: '' }); const pendingAgentId = ref(null); const isWecomLoggingIn = ref(false); +const wecomEntryHint = ref(''); +const wecomLoginDialog = ref(null); +const wecomBindPrompt = ref(null); + +const clearWecomCallbackQuery = () => { + const nextUrl = `${window.location.pathname}${window.location.hash || ''}`; + window.history.replaceState({}, '', nextUrl); +}; const handleForgotPassword = async () => { if (!forgotPasswordForm.value.email) { @@ -452,6 +477,85 @@ const handleWecomLogin = async () => { } }; +const openWecomLoginDialog = (payload: Record) => { + wecomLoginDialog.value = buildWecomLoginDialogContent(payload, t); +}; + +const openWecomBindPrompt = (payload: Record) => { + const allowedFields = normalizeWecomMatchRules(payload.allowed_fields).fields; + const fallbackFields: WecomMatchField[] = ['employee_id', 'mobile', 'email']; + const fields: WecomMatchField[] = allowedFields.length ? allowedFields : fallbackFields; + wecomBindPrompt.value = { + binding_token: String(payload.binding_token || ''), + allowed_fields: fields, + wecom_name: String(payload.wecom_name || ''), + field: fields[0] || 'employee_id', + value: '', + submitting: false, + error: '', + }; +}; + +const formatWecomBindPromptError = (payload: Record) => { + const errorCode = String(payload.error_code || ''); + if (errorCode === 'WECOM_BIND_INPUT_NOT_FOUND') return t('login.wecomBindInputNotFound'); + if (errorCode === 'WECOM_BIND_INPUT_AMBIGUOUS') return t('login.wecomBindInputAmbiguous'); + if (errorCode === 'WECOM_BIND_SESSION_EXPIRED') return t('login.wecomBindSessionExpired'); + if (errorCode === 'WECOM_BIND_CONFLICT') return t('login.wecomBindConflict'); + if (errorCode === 'WECOM_BIND_FIELD_NOT_ALLOWED') return t('login.wecomBindFieldNotAllowed'); + if (errorCode === 'WECOM_BIND_INPUT_VALUE_REQUIRED') return t('login.wecomBindValueRequired'); + if (String(payload.error || '').includes('Account is disabled')) return t('login.wecomAccountDisabled'); + return String(payload.error || t('login.wecomLoginFailed')); +}; + +const submitWecomCompleteBind = async () => { + if (!wecomBindPrompt.value) return; + if (!wecomBindPrompt.value.value.trim()) { + wecomBindPrompt.value.error = t('login.wecomBindValueRequired'); + return; + } + + wecomBindPrompt.value.submitting = true; + wecomBindPrompt.value.error = ''; + try { + const api = config.auth.wecom.completeBindApi || '/api/user/wecom/complete-bind'; + const res = await fetch(api, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + binding_token: wecomBindPrompt.value.binding_token, + field: wecomBindPrompt.value.field, + value: wecomBindPrompt.value.value.trim(), + }), + }); + const data = await res.json(); + if (!res.ok) { + wecomBindPrompt.value.error = formatWecomBindPromptError(data); + if (String(data.error_code || '') === 'WECOM_BIND_SESSION_EXPIRED') { + openWecomLoginDialog(data); + wecomBindPrompt.value = null; + } + return; + } + + wecomLoginDialog.value = null; + persistLoginUser(data); + sessionStorage.removeItem('hxops_wecom_state'); + wecomBindPrompt.value = null; + window.history.replaceState({}, '', '/workspace'); + await fetchHome(); + } catch (e) { + console.error(e); + if (wecomBindPrompt.value) { + wecomBindPrompt.value.error = t('login.wecomLoginFailed'); + } + } finally { + if (wecomBindPrompt.value) { + wecomBindPrompt.value.submitting = false; + } + } +}; + const tryWecomCallbackLogin = async () => { if (!config.auth?.wecom?.enabled) return false; @@ -462,7 +566,8 @@ const tryWecomCallbackLogin = async () => { const expectedState = sessionStorage.getItem('hxops_wecom_state'); if (expectedState && state && state !== expectedState) { - alert(t('login.wecomInvalidState')); + openWecomLoginDialog({ error: 'Invalid or expired WeCom state' }); + clearWecomCallbackQuery(); return true; } @@ -476,19 +581,18 @@ const tryWecomCallbackLogin = async () => { }); const data = await res.json(); if (!res.ok) { - const rawError = String(data.error || ''); - let friendly = rawError || t('login.wecomLoginFailed'); - if (rawError.includes('Invalid or expired WeCom state')) { - friendly = t('login.wecomStateExpired'); - } else if (rawError.includes('bind WeCom account') || rawError.includes('No linked account found')) { - friendly = t('login.wecomBindRequired'); - } else if (rawError.includes('Account is disabled')) { - friendly = t('login.wecomAccountDisabled'); + sessionStorage.removeItem('hxops_wecom_state'); + if (String(data.error_code || '') === 'WECOM_BIND_INPUT_REQUIRED') { + openWecomBindPrompt(data); + clearWecomCallbackQuery(); + return true; } - alert(friendly); + openWecomLoginDialog(data); + clearWecomCallbackQuery(); return true; } + wecomLoginDialog.value = null; persistLoginUser(data); sessionStorage.removeItem('hxops_wecom_state'); window.history.replaceState({}, '', '/workspace'); @@ -496,7 +600,9 @@ const tryWecomCallbackLogin = async () => { return true; } catch (e) { console.error(e); - alert(t('login.wecomLoginFailed')); + sessionStorage.removeItem('hxops_wecom_state'); + openWecomLoginDialog({ error: t('login.wecomLoginFailed') }); + clearWecomCallbackQuery(); return true; } finally { isWecomLoggingIn.value = false; @@ -572,6 +678,45 @@ const navigateWithQuickQuestion = (agentId: number, question: string) => { window.open(url, '_blank'); }; +const handleWecomDeeplinkContext = async () => { + const params = new URLSearchParams(window.location.search); + const traceId = params.get('wecom_trace'); + const target = params.get('target'); + const agentIdRaw = params.get('agent_id'); + const preset = params.get('preset'); + + if (!traceId && !target) return; + wecomEntryHint.value = t('workspace.wecomEntryNotice'); + + if (traceId && isLoggedIn.value) { + try { + const api = config.auth?.wecom?.deeplinkTraceApi || '/api/user/wecom/deeplink-opened'; + await fetch(api, { + method: 'POST', + headers: { 'Content-Type': 'application/json', ...getAuthHeaders() }, + body: JSON.stringify({ trace_id: traceId }), + }); + } catch (e) { + console.warn('Failed to mark WeCom deeplink opened', e); + } + } + + if (target === 'chat' && agentIdRaw && isLoggedIn.value) { + const agentId = Number(agentIdRaw); + if (Number.isInteger(agentId) && agents.value.some((a) => a.id === agentId)) { + const url = router.resolve({ + path: `/chat/${agentId}`, + query: preset ? { preset } : {}, + }).href; + window.open(url, '_blank'); + } + } + + if (traceId || target) { + window.history.replaceState({}, '', '/workspace'); + } +}; + // Favorites const toggleFavorite = async (agentId: number) => { if (favoriteAgentIds.value.includes(agentId)) { @@ -697,6 +842,7 @@ onMounted(async () => { loadAuthUser(); if (currentUser.value && currentUser.value.role !== 'guest') { await fetchHome(); + await handleWecomDeeplinkContext(); } else { await fetchPublicAgents(); isLoading.value = false; @@ -922,6 +1068,9 @@ onMounted(async () => {
+
+ {{ wecomEntryHint }} +
{
+ +
+
+ +
+
+ +
+

{{ wecomLoginDialog.title }}

+

{{ wecomLoginDialog.summary }}

+
+
+

+ {{ detail }} +

+
+

+ {{ $t('login.wecomTechnicalInfo', { detail: wecomLoginDialog.technical }) }} +

+
+ + +
+
+
+ +
+
+ +
+
+ +
+

{{ $t('login.wecomBindPromptTitle') }}

+

+ {{ $t('login.wecomBindPromptDesc', { name: wecomBindPrompt.wecom_name || '-' }) }} +

+
+
+
+ + +
+
+ + +
+

{{ $t('login.wecomBindPromptHint') }}

+

{{ wecomBindPrompt.error }}

+
+
+ + +
+
+
diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index deaac836..cf692504 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -7,6 +7,7 @@ export default defineConfig({ plugins: [vue()], server: { port: 8881, // 前端开发端口,实际上我们会用 Nginx 反代,但本地开发先改这个方便 + allowedHosts: ['hx.benl.cn'], proxy: { '/api': { target: 'http://127.0.0.1:5002',