-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
4328 lines (3709 loc) · 153 KB
/
main.py
File metadata and controls
4328 lines (3709 loc) · 153 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import asyncio
import base64
import hashlib
import hmac
import html
import json
import logging
import os
import re
import secrets
import shutil
import threading
import time
import uuid
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import Any, Literal
from urllib.parse import urlsplit, urlunsplit
import httpx
from fastapi import Depends, FastAPI, HTTPException, Request, Response
from fastapi.responses import FileResponse
from fastapi.responses import HTMLResponse
from fastapi.responses import JSONResponse
from fastapi.responses import StreamingResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field
APP_DIR = Path(__file__).resolve().parent
STATIC_DIR = (APP_DIR / "static").resolve()
_DATA_PATH_RAW = os.getenv("APP_DATA_PATH", "./data/chat.json").strip() or "./data/chat.json"
if Path(_DATA_PATH_RAW).is_absolute():
DATA_PATH = Path(_DATA_PATH_RAW).resolve()
else:
DATA_PATH = (APP_DIR / _DATA_PATH_RAW).resolve()
LEGACY_DATA_PATH = (APP_DIR / "data" / "store.json").resolve()
ATTACHMENT_FILE_DIR = (DATA_PATH.parent / "file").resolve()
ATTACHMENT_FILE_URL_PREFIX = "/data/file/"
ATTACHMENT_FILE_DIR.mkdir(parents=True, exist_ok=True)
AUDIT_LOG_PATH = (DATA_PATH.parent / "audit.log").resolve()
SESSION_COOKIE = "pychat_session"
SESSION_TTL_SECONDS = int(os.getenv("APP_SESSION_TTL_SECONDS", "604800"))
SESSION_COOKIE_SAMESITE = os.getenv("APP_SESSION_COOKIE_SAMESITE", "lax").lower()
SESSION_COOKIE_SECURE = os.getenv("APP_SESSION_COOKIE_SECURE", "false").lower() in {
"1",
"true",
"yes",
}
AUTH_FREE_API_PATHS = {
"/api/auth/status",
"/api/auth/login",
"/api/auth/logout",
"/api/setup/init",
}
DEFAULT_APP_TITLE = "My Chat"
DEFAULT_APP_SUBTITLE = "Build your own AI assistant"
DEFAULT_MODEL_NAME = os.getenv("DEFAULT_MODEL_NAME", "gpt-5.5").strip() or "gpt-5.5"
DEFAULT_BASE_URL = os.getenv("DEFAULT_BASE_URL", "").strip()
DEFAULT_API_KEY = os.getenv("DEFAULT_API_KEY", "").strip()
MAX_RETENTION_HOURS = 24 * 365 * 5
MAX_UPSTREAM_CONTEXT_MESSAGES_LIMIT = 500
MAX_UPSTREAM_CONTEXT_CHARS_LIMIT = 1_000_000
MAX_UPSTREAM_IMAGE_MESSAGES_LIMIT = 50
def _env_int(name: str, default: int, minimum: int) -> int:
try:
value = int(os.getenv(name, str(default)) or str(default))
except Exception:
value = default
return max(minimum, value)
DEFAULT_UPSTREAM_CONTEXT_MESSAGES = min(
MAX_UPSTREAM_CONTEXT_MESSAGES_LIMIT,
_env_int("APP_MAX_UPSTREAM_CONTEXT_MESSAGES", 40, 1),
)
DEFAULT_UPSTREAM_CONTEXT_CHARS = min(
MAX_UPSTREAM_CONTEXT_CHARS_LIMIT,
_env_int("APP_MAX_UPSTREAM_CONTEXT_CHARS", 120000, 1000),
)
DEFAULT_UPSTREAM_IMAGE_MESSAGES = min(
MAX_UPSTREAM_IMAGE_MESSAGES_LIMIT,
_env_int("APP_MAX_UPSTREAM_IMAGE_MESSAGES", 4, 0),
)
BUILTIN_OPS_AGENT_NAME = "运维专家"
BUILTIN_OPS_AGENT_PROMPT = """你是一名资深运维/运维开发工程师助手。
## 风格
- 默认中文。先给结论,再给最多3条要点。
- 除非用户要求,不提供背景扩展或免责声明。
- 能一句话说清就只说一句。
- 能用命令解决的不说废话,能用代码解决的不写文档
- 回答用散文+代码块,不滥用列表和标题
- 不说"好的""当然""希望对你有帮助"
## 能力范围
Linux 系统、Shell、Python、go、lua、容器、监控告警、公有/私有云平台、分布式/集中式块存储、文件存储、网络排障、数据库运维、中间件运维、k8s/docker
## 回答原则
- 给可以直接用的命令/脚本,附必要参数说明
- 有多种方案时,直接推荐最优的,其他的一句话带过
- 不确定的直接说,不编
- 排障类问题:定位命令 → 关键字段 → 结论,没有第四段
- 涉及危险操作主动提示风险,一句话够了
## 禁止
- 不开头重复用户的问题
- 不结尾加任何引导句,不说"把xxx贴出来""如有问题""可以继续问"
- 不把一句话能说清的东西拆成列表
- 同一个意思只说一次,不在结尾复述
- 列表项超过5条时,合并同类、删掉次要的
- 命令注释只写必要的,不写废话注释
## 回答前强制自检
1. 第一句是废话?→ 删
2. 能更短?→ 删多余的
3. 有用户没问的东西?→ 删
4. 列表能改一句话?→ 改
5. 结尾有引导句?→ 删。"""
BUILTIN_GENERAL_AGENT_NAME = "默认助手"
BUILTIN_GENERAL_AGENT_PROMPT = """你是一名通用中文助手。
## 风格
- 默认中文。先给结论,再给最多3条要点。
- 除非用户要求,不提供背景扩展或免责声明。
- 能一句话说清就只说一句。
- 不说"好的""当然""希望对你有帮助"
## 回答原则
- 有多种方案时,直接推荐最优的,其他的一句话带过
- 不确定的直接说,不编
## 禁止
- 不开头重复用户的问题
- 不结尾加任何引导句,不说"把xxx贴出来""如有问题""可以继续问"
- 不把一句话能说清的东西拆成列表
- 同一个意思只说一次,不在结尾复述
- 列表项超过5条时,合并同类、删掉次要的
## 回答前强制自检
1. 第一句是废话?→ 删
2. 能更短?→ 删多余的
3. 有用户没问的东西?→ 删
4. 列表能改一句话?→ 改
5. 结尾有引导句?→ 删。"""
# Fresh deployment default builtin agent.
# Supported keys are the `key` fields in BUILTIN_AGENTS below.
DEFAULT_BUILTIN_AGENT_KEY = "general"
BUILTIN_AGENTS = [
{
"key": "ops",
"name": BUILTIN_OPS_AGENT_NAME,
"prompt": BUILTIN_OPS_AGENT_PROMPT,
},
{
"key": "general",
"name": BUILTIN_GENERAL_AGENT_NAME,
"prompt": BUILTIN_GENERAL_AGENT_PROMPT,
},
]
BUILTIN_AGENT_BY_KEY = {item["key"]: item for item in BUILTIN_AGENTS}
BUILTIN_AGENT_BY_NAME = {item["name"]: item for item in BUILTIN_AGENTS}
BUILTIN_AGENT_NAME_SET = set(BUILTIN_AGENT_BY_NAME.keys())
UPSTREAM_RETRY_STATUS_CODES = {429, 500, 502, 503, 504}
UPSTREAM_RETRY_DELAYS_SECONDS = [0.8, 1.6]
STORAGE_LOCK = threading.Lock()
AUDIT_LOG_LOCK = threading.Lock()
LOGGER = logging.getLogger("py_lite_chat")
def now_ts() -> int:
return int(time.time())
def new_id() -> str:
return uuid.uuid4().hex
def sha256_hex(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def build_chat_title_from_message(message: str, max_len: int = 28) -> str:
text = " ".join((message or "").strip().splitlines()).strip()
if not text:
return "新对话"
if len(text) <= max_len:
return text
return f"{text[:max_len].rstrip()}..."
def _safe_int(value: Any, default: int = 0) -> int:
try:
return int(value)
except Exception:
return default
def _normalize_retention_hours(value: Any, default: int = 0) -> int:
ttl = _safe_int(value, default)
if ttl < 0:
ttl = 0
if ttl > MAX_RETENTION_HOURS:
ttl = MAX_RETENTION_HOURS
return ttl
def _normalize_range_int(value: Any, default: int, minimum: int, maximum: int) -> int:
result = _safe_int(value, default)
if result < minimum:
return minimum
if result > maximum:
return maximum
return result
def _normalize_upstream_context_settings(app_meta: dict[str, Any] | None) -> dict[str, int]:
meta = app_meta or {}
return {
"upstream_context_messages": _normalize_range_int(
meta.get("upstream_context_messages"),
DEFAULT_UPSTREAM_CONTEXT_MESSAGES,
1,
MAX_UPSTREAM_CONTEXT_MESSAGES_LIMIT,
),
"upstream_context_chars": _normalize_range_int(
meta.get("upstream_context_chars"),
DEFAULT_UPSTREAM_CONTEXT_CHARS,
1000,
MAX_UPSTREAM_CONTEXT_CHARS_LIMIT,
),
"upstream_image_messages": _normalize_range_int(
meta.get("upstream_image_messages"),
DEFAULT_UPSTREAM_IMAGE_MESSAGES,
0,
MAX_UPSTREAM_IMAGE_MESSAGES_LIMIT,
),
}
def _normalize_role(value: Any) -> str:
role = str(value or "user").strip().lower()
if role not in {"admin", "user"}:
return "user"
return role
def _normalize_username(value: Any) -> str:
return str(value or "").strip()
def _normalize_bool(value: Any, default: bool = False) -> bool:
if isinstance(value, bool):
return value
if isinstance(value, (int, float)):
return bool(value)
if isinstance(value, str):
return value.strip().lower() in {"1", "true", "yes", "on"}
return default
def _normalize_reasoning_effort(value: Any) -> str | None:
effort = str(value or "").strip().lower()
if effort in {"low", "medium", "high", "xhigh"}:
return effort
return None
def _get_builtin_agent_definition_by_name(name: Any) -> dict[str, Any] | None:
return BUILTIN_AGENT_BY_NAME.get(str(name or "").strip())
def _get_default_builtin_agent_definition() -> dict[str, Any]:
configured = BUILTIN_AGENT_BY_KEY.get(DEFAULT_BUILTIN_AGENT_KEY)
if configured:
return configured
return BUILTIN_AGENTS[0]
def _mask_secret_for_audit(value: Any) -> str:
raw = str(value or "")
n = len(raw)
if n <= 0:
return ""
if n <= 6:
return "*" * n
return f"{raw[:2]}{'*' * (n - 4)}{raw[-2:]}"
def _truncate_for_audit_text(value: Any, max_len: int = 240) -> str:
text = str(value or "")
if len(text) <= max_len:
return text
return f"{text[:max_len]}...(总{len(text)}字符)"
def _sanitize_audit_value(value: Any, key_name: str = "", depth: int = 0) -> Any:
if depth > 6:
return "[已省略嵌套对象]"
key = str(key_name or "").lower()
if key in {"message", "messages", "prompt", "input"} or key.endswith("_message") or key.endswith("_content"):
return "[已省略消息内容]"
if key in {"attachments", "files", "images"}:
if isinstance(value, list):
return f"[已省略附件,共{len(value)}项]"
return "[已省略附件]"
if any(token in key for token in ("password", "api_key", "authorization", "token", "cookie", "secret")):
return _mask_secret_for_audit(value)
if isinstance(value, dict):
sanitized: dict[str, Any] = {}
items = list(value.items())
for idx, (k, v) in enumerate(items):
if idx >= 80:
sanitized["__剩余字段__"] = f"已省略{len(items) - idx}个字段"
break
sanitized[str(k)] = _sanitize_audit_value(v, key_name=str(k), depth=depth + 1)
return sanitized
if isinstance(value, list):
sanitized_items = []
for idx, item in enumerate(value):
if idx >= 30:
sanitized_items.append(f"[已省略剩余{len(value) - idx}项]")
break
sanitized_items.append(_sanitize_audit_value(item, key_name=key_name, depth=depth + 1))
return sanitized_items
if isinstance(value, (bytes, bytearray)):
return f"[二进制{len(value)}字节]"
if isinstance(value, str):
return _truncate_for_audit_text(value)
if value is None or isinstance(value, (int, float, bool)):
return value
return _truncate_for_audit_text(repr(value))
async def _extract_request_params_for_audit(request: Request) -> dict[str, Any]:
params: dict[str, Any] = {}
query_map: dict[str, Any] = {}
for key in request.query_params.keys():
values = request.query_params.getlist(key)
query_map[key] = values[0] if len(values) == 1 else values
if query_map:
params["query"] = _sanitize_audit_value(query_map)
if request.method not in {"POST", "PUT", "PATCH", "DELETE"}:
return params
content_type = str(request.headers.get("content-type") or "").lower()
if "application/json" not in content_type:
if content_type:
params["body"] = f"[{content_type} 请求体未解析]"
return params
body_bytes = await request.body()
if not body_bytes:
return params
if request.url.path in {"/api/chat", "/api/chat/stream"}:
try:
payload = json.loads(body_bytes.decode("utf-8", errors="ignore"))
except Exception:
params["body"] = "[聊天请求参数解析失败]"
return params
if isinstance(payload, dict):
summary = {
"chat_id": payload.get("chat_id"),
"model_id": payload.get("model_id"),
"model_name": payload.get("model_name"),
"mask_id": payload.get("mask_id"),
"reasoning_effort": payload.get("reasoning_effort"),
"temperature": payload.get("temperature"),
"attachments_count": len(payload.get("attachments", []))
if isinstance(payload.get("attachments"), list)
else 0,
"message": "[已省略消息内容]",
"_has_model_id": "model_id" in payload,
"_has_mask_id": "mask_id" in payload,
"_has_reasoning_effort": "reasoning_effort" in payload,
}
params["body"] = summary
return params
params["body"] = "[聊天请求体格式异常]"
return params
try:
payload = json.loads(body_bytes.decode("utf-8", errors="ignore"))
params["body"] = _sanitize_audit_value(payload)
except Exception:
params["body"] = _truncate_for_audit_text(body_bytes.decode("utf-8", errors="ignore"), max_len=400)
return params
def _client_ip_for_audit(request: Request) -> str:
xff = str(request.headers.get("x-forwarded-for") or "").strip()
if xff:
return xff.split(",")[0].strip()
client = request.client
return client.host if client else ""
def _describe_api_action(method: str, path: str) -> str:
method_u = str(method or "").upper()
if path == "/api/auth/login":
return "用户登录"
if path == "/api/auth/logout":
return "用户登出"
if path == "/api/auth/status":
return "查询登录状态"
if path == "/api/setup/init":
return "初始化应用"
if path == "/api/state":
return "读取应用状态"
if path == "/api/models":
return "读取模型列表" if method_u == "GET" else "新增或更新模型"
if method_u == "POST" and path.endswith("/streaming") and path.startswith("/api/models/"):
return "修改模型流传输设置"
if method_u == "DELETE" and path.startswith("/api/models/"):
return "删除模型"
if path == "/api/masks":
return "读取Agent列表" if method_u == "GET" else "新增或编辑Agent"
if method_u == "POST" and path.endswith("/public") and path.startswith("/api/masks/"):
return "设置Agent公开状态"
if method_u == "DELETE" and path.startswith("/api/masks/"):
return "删除Agent"
if path == "/api/admin/app-settings":
return "修改应用设置"
if path == "/api/user/retention-settings":
return "修改个人消息保留策略"
if path == "/api/default-model":
return "设置默认模型"
if path == "/api/default-agent":
return "设置默认Agent"
if path == "/api/chats":
return "读取会话列表" if method_u == "GET" else "创建会话"
if path == "/api/chats/clear":
return "清空个人会话数据"
if method_u == "POST" and path.startswith("/api/chats/") and path.endswith("/config"):
return "修改会话参数"
if method_u == "DELETE" and path.startswith("/api/chats/"):
return "删除会话"
if path == "/api/chat":
return "发送消息"
if path == "/api/chat/stream":
return "流式发送消息"
if path == "/api/admin/users":
return "读取用户列表" if method_u == "GET" else "创建用户"
if method_u == "POST" and path.startswith("/api/admin/users/") and path.endswith("/password"):
return "重置用户密码"
if method_u == "DELETE" and path.startswith("/api/admin/users/"):
return "删除用户"
if path == "/api/admin/chats/clear":
return "清空所有用户会话数据"
return "API访问"
def _reasoning_effort_label_for_audit(value: Any) -> str:
effort = _normalize_reasoning_effort(value)
if effort == "low":
return "低"
if effort == "medium":
return "中"
if effort == "high":
return "高"
if effort == "xhigh":
return "超高"
return "无"
def _enrich_request_params_for_audit(
request: Request,
request_params: dict[str, Any] | None,
store: dict[str, Any] | None = None,
user: dict[str, Any] | None = None,
) -> dict[str, Any] | None:
if not isinstance(request_params, dict):
return request_params
if request.url.path not in {"/api/chat", "/api/chat/stream"}:
return request_params
body = request_params.get("body")
if not isinstance(body, dict):
return request_params
if not isinstance(store, dict):
return request_params
chat_id = str(body.get("chat_id") or "").strip()
user_id = str((user or {}).get("id") or "").strip()
chat = find_chat_for_user(store, chat_id, user_id) if chat_id and user_id else None
use_payload_model = bool(body.get("_has_model_id"))
use_payload_mask = bool(body.get("_has_mask_id"))
use_payload_reasoning = bool(body.get("_has_reasoning_effort"))
payload_model_id = str(body.get("model_id") or "").strip()
payload_model_name = str(body.get("model_name") or "").strip()
payload_mask_id_raw = body.get("mask_id")
payload_mask_id = str(payload_mask_id_raw or "").strip() if payload_mask_id_raw is not None else None
target_model_id = payload_model_id if use_payload_model else str((chat or {}).get("model_id") or "").strip()
if not target_model_id:
target_model_id = str((user or {}).get("default_model_id") or "").strip()
model = _resolve_visible_model(store, user or {}, target_model_id) if target_model_id else None
if not model and payload_model_name:
named_model = find_model(store, None, payload_model_name)
if named_model and ((user or {}).get("role") == "admin" or named_model.get("enabled", True)):
model = named_model
if not model:
model = _pick_first_enabled_model(store)
model_name = str((model or {}).get("name") or payload_model_name or "(未知模型)")
target_mask_id = payload_mask_id if use_payload_mask else (chat or {}).get("mask_id")
mask = _resolve_visible_mask(store, user or {}, target_mask_id) if target_mask_id else None
mask_name = str((mask or {}).get("name") or "不使用Agent")
reasoning_source = (
body.get("reasoning_effort")
if use_payload_reasoning
else (chat or {}).get("reasoning_effort")
)
enriched_body = {
"chat_id": chat_id or None,
"model": model_name,
"agent": mask_name,
"推理等级": _reasoning_effort_label_for_audit(reasoning_source),
"temperature": body.get("temperature"),
"attachments_count": body.get("attachments_count", 0),
"message": "[已省略消息内容]",
}
request_params["body"] = _sanitize_audit_value(enriched_body)
return request_params
def _write_audit_log(record: dict[str, Any]) -> None:
try:
AUDIT_LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
line = json.dumps(record, ensure_ascii=False, separators=(",", ":"))
with AUDIT_LOG_LOCK:
with AUDIT_LOG_PATH.open("a", encoding="utf-8") as f:
f.write(line + "\n")
except Exception as exc:
LOGGER.warning("write audit log failed: %s", exc)
def _audit_log_api_request(
request: Request,
status_code: int,
user: dict[str, Any] | None,
request_params: dict[str, Any] | None = None,
extra: dict[str, Any] | None = None,
) -> None:
user_name = ""
user_id = ""
role = ""
if isinstance(user, dict):
user_name = str(user.get("username") or "")
user_id = str(user.get("id") or "")
role = str(user.get("role") or "")
record: dict[str, Any] = {
"时间": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
"事件": _describe_api_action(request.method, request.url.path),
"方法": request.method,
"路径": request.url.path,
"状态码": int(status_code),
"用户": user_name,
"角色": role,
"用户ID": user_id,
"来源IP": _client_ip_for_audit(request),
}
if request_params:
record["请求参数"] = _sanitize_audit_value(request_params)
if extra:
record["附加信息"] = _sanitize_audit_value(extra)
record["结果"] = "成功" if int(status_code) < 400 else "失败"
_write_audit_log(record)
def _extract_error_detail_from_body(body_bytes: bytes | bytearray | None, content_type: str) -> str | None:
if not body_bytes or not isinstance(body_bytes, (bytes, bytearray)):
return None
content_type = str(content_type or "").lower()
if "application/json" in content_type:
try:
payload = json.loads(body_bytes.decode("utf-8", errors="ignore"))
except Exception:
payload = None
if isinstance(payload, dict):
detail = payload.get("detail")
if isinstance(detail, str) and detail.strip():
return detail.strip()[:500]
error = payload.get("error")
if isinstance(error, dict):
message = error.get("message")
if isinstance(message, str) and message.strip():
return message.strip()[:500]
message = payload.get("message")
if isinstance(message, str) and message.strip():
return message.strip()[:500]
return None
if "text/plain" in content_type:
text = body_bytes.decode("utf-8", errors="ignore").strip()
if text:
return text[:500]
return None
async def _extract_error_detail_from_response(response: Response) -> tuple[Response, str | None]:
try:
status_code = int(getattr(response, "status_code", 200))
except Exception:
status_code = 200
if status_code < 400:
return response, None
content_type = str(getattr(response, "headers", {}).get("content-type") or "").lower()
body_bytes = getattr(response, "body", None)
if isinstance(body_bytes, (bytes, bytearray)):
return response, _extract_error_detail_from_body(body_bytes, content_type)
if "text/event-stream" in content_type:
return response, None
body_iterator = getattr(response, "body_iterator", None)
if body_iterator is None:
return response, None
chunks: list[bytes] = []
async for chunk in body_iterator:
if isinstance(chunk, bytes):
chunks.append(chunk)
else:
chunks.append(str(chunk).encode("utf-8"))
body_bytes = b"".join(chunks)
cloned_response = Response(
content=body_bytes,
status_code=response.status_code,
headers=dict(response.headers),
media_type=getattr(response, "media_type", None),
background=getattr(response, "background", None),
)
return cloned_response, _extract_error_detail_from_body(body_bytes, content_type)
def _mask_api_key_for_display(api_key: Any) -> str:
raw = str(api_key or "").strip()
n = len(raw)
if n == 0:
return ""
if n <= 12:
return "*" * n
if n <= 17:
keep = 2
elif n <= 24:
keep = 4
else:
keep = 6
hidden = max(0, n - 2 * keep)
return f"{raw[:keep]}{'*' * hidden}{raw[n - keep:]}"
def _payload_has_field(payload: Any, field_name: str) -> bool:
fields_set = getattr(payload, "model_fields_set", None)
if fields_set is None:
fields_set = getattr(payload, "__fields_set__", set())
return field_name in fields_set
MAX_ATTACHMENTS_PER_MESSAGE = 8
MAX_ATTACHMENT_NAME_LEN = 255
MAX_ATTACHMENT_MIME_LEN = 128
MAX_ATTACHMENT_TEXT_CHARS = 20000
MAX_ATTACHMENT_DATA_URL_CHARS = 2_500_000
MAX_APP_ICON_DATA_URL_CHARS = 750_000
MAX_APP_ICON_BYTES = 512 * 1024
def _truncate_text(text: str, max_len: int) -> str:
if len(text) <= max_len:
return text
return text[:max_len]
def _decode_app_icon_data_url(value: Any) -> tuple[bytes, str] | None:
raw = "" if value is None else str(value).strip()
if not raw:
return None
if len(raw) > MAX_APP_ICON_DATA_URL_CHARS:
return None
lower = raw.lower()
mime_to_ext = {
"data:image/png;base64,": "png",
"data:image/jpeg;base64,": "jpg",
"data:image/jpg;base64,": "jpg",
"data:image/webp;base64,": "webp",
"data:image/gif;base64,": "gif",
"data:image/svg+xml;base64,": "svg",
"data:image/x-icon;base64,": "ico",
"data:image/vnd.microsoft.icon;base64,": "ico",
}
ext = ""
for prefix, candidate_ext in mime_to_ext.items():
if lower.startswith(prefix):
ext = candidate_ext
break
if not ext:
return None
try:
encoded = raw.split(",", 1)[1]
binary = base64.b64decode(_clean_base64_text(encoded) + "===", validate=False)
except Exception:
return None
if not binary or len(binary) > MAX_APP_ICON_BYTES:
return None
return binary, ext
def _normalize_app_icon_filename(value: Any) -> str:
raw = Path(str(value or "").strip()).name
if not raw:
return ""
if not re.fullmatch(r"app-icon\.(png|jpg|webp|gif|svg|ico)", raw, flags=re.I):
return ""
path = (STATIC_DIR / raw).resolve()
try:
path.relative_to(STATIC_DIR)
except ValueError:
return ""
return raw if path.exists() else ""
def _remove_app_icon_files(keep_filename: str = "") -> None:
STATIC_DIR.mkdir(parents=True, exist_ok=True)
keep = Path(str(keep_filename or "")).name
for path in STATIC_DIR.glob("app-icon.*"):
if path.name == keep:
continue
if not path.is_file():
continue
try:
path.unlink()
except Exception:
pass
def _store_app_icon_data_url(value: Any) -> str:
decoded = _decode_app_icon_data_url(value)
if decoded is None:
return ""
binary, ext = decoded
STATIC_DIR.mkdir(parents=True, exist_ok=True)
filename = f"app-icon.{ext}"
path = (STATIC_DIR / filename).resolve()
try:
path.relative_to(STATIC_DIR)
except ValueError:
return ""
try:
path.write_bytes(binary)
except Exception:
return ""
_remove_app_icon_files(filename)
return filename
def _app_icon_url_for_meta(app_meta: dict[str, Any] | None) -> str:
meta = app_meta or {}
filename = _normalize_app_icon_filename(meta.get("icon_filename"))
if not filename:
return ""
version = _safe_int(meta.get("updated_at"), 0)
if version <= 0:
try:
version = int((STATIC_DIR / filename).stat().st_mtime)
except Exception:
version = int(time.time())
return f"/static/{filename}?v={version}"
def _serialize_app_meta_for_client(app_meta: dict[str, Any] | None) -> dict[str, Any]:
meta = app_meta or {}
legacy_ttl_hours = _safe_int(meta.get("message_ttl_hours"), 0)
text_ttl_hours = _safe_int(meta.get("message_text_ttl_hours"), legacy_ttl_hours)
media_ttl_hours = _safe_int(meta.get("message_media_ttl_hours"), legacy_ttl_hours)
return {
"title": meta.get("title") or DEFAULT_APP_TITLE,
"subtitle": meta.get("subtitle") or DEFAULT_APP_SUBTITLE,
"icon_url": _app_icon_url_for_meta(meta),
"icon_data_url": "",
"message_ttl_hours": legacy_ttl_hours,
"message_text_ttl_hours": text_ttl_hours,
"message_media_ttl_hours": media_ttl_hours,
**_normalize_upstream_context_settings(meta),
}
def _safe_local_attachment_path_from_url(data_url: str) -> Path | None:
raw = str(data_url or "").strip()
if not raw.startswith(ATTACHMENT_FILE_URL_PREFIX):
return None
suffix = raw[len(ATTACHMENT_FILE_URL_PREFIX) :].lstrip("/")
if not suffix:
return None
candidate = (ATTACHMENT_FILE_DIR / suffix).resolve()
try:
candidate.relative_to(ATTACHMENT_FILE_DIR)
except ValueError:
return None
return candidate
def _store_data_image_to_local_file(data_url: str, mime_hint: str = "") -> tuple[str | None, int | None]:
raw = str(data_url or "").strip()
if not raw.startswith("data:image/") or ";base64," not in raw:
return None, None
_, encoded = raw.split(",", 1)
cleaned = _clean_base64_text(encoded)
if not cleaned:
return None, None
try:
binary = base64.b64decode(cleaned + "===", validate=False)
except Exception:
return None, None
if not binary:
return None, None
mime_type = _infer_image_mime_from_data_url(raw)
if not mime_type.startswith("image/"):
hint = str(mime_hint or "").strip().lower()
mime_type = hint if hint.startswith("image/") else "image/png"
digest = hashlib.sha256(binary).hexdigest()
ext = _image_extension_from_mime(mime_type)
filename = f"{digest}.{ext}"
ATTACHMENT_FILE_DIR.mkdir(parents=True, exist_ok=True)
file_path = ATTACHMENT_FILE_DIR / filename
if not file_path.exists():
try:
with file_path.open("wb") as f:
f.write(binary)
except Exception:
return None, None
return f"{ATTACHMENT_FILE_URL_PREFIX}{filename}", len(binary)
def _materialize_attachment_data_url(
kind: str,
mime_type: str,
raw_data_url: Any,
current_size: int,
) -> tuple[str | None, int]:
data_url = None if raw_data_url is None else str(raw_data_url).strip()
size = max(0, _safe_int(current_size, 0))
if not data_url:
return None, size
if kind == "image" and data_url.startswith("data:image/"):
local_url, local_size = _store_data_image_to_local_file(data_url, mime_type)
if local_url:
data_url = local_url
if local_size is not None and local_size > 0:
size = local_size
if len(data_url) > MAX_ATTACHMENT_DATA_URL_CHARS:
data_url = data_url[:MAX_ATTACHMENT_DATA_URL_CHARS]
if not (
data_url.startswith("data:")
or data_url.startswith("http://")
or data_url.startswith("https://")
or data_url.startswith(ATTACHMENT_FILE_URL_PREFIX)
):
return None, size
local_path = _safe_local_attachment_path_from_url(data_url)
if local_path is not None and size <= 0:
try:
size = max(0, local_path.stat().st_size)
except FileNotFoundError:
size = 0
except Exception:
pass
return data_url, size
def _normalize_attachment_kind(kind: str, mime_type: str) -> str:
raw = (kind or "").strip().lower()
if raw in {"image", "text", "file"}:
return raw
if mime_type.startswith("image/"):
return "image"
if mime_type.startswith("text/"):
return "text"
return "file"
def _normalize_attachment(att: Any) -> dict[str, Any] | None:
if not isinstance(att, dict):
return None
name = str(att.get("name") or "attachment").strip() or "attachment"
mime_type = str(att.get("mime_type") or "").strip().lower()
if not mime_type:
mime_type = "application/octet-stream"
kind = _normalize_attachment_kind(str(att.get("kind") or ""), mime_type)
size = _safe_int(att.get("size"), 0)
if size < 0:
size = 0
data_url, size = _materialize_attachment_data_url(kind, mime_type, att.get("data_url"), size)
text_content = att.get("text_content")
if text_content is not None:
text_content = _truncate_text(str(text_content), MAX_ATTACHMENT_TEXT_CHARS)
normalized = {
"name": _truncate_text(name, MAX_ATTACHMENT_NAME_LEN),
"mime_type": _truncate_text(mime_type, MAX_ATTACHMENT_MIME_LEN),
"size": size,
"kind": kind,
}
if data_url:
normalized["data_url"] = data_url
if text_content:
normalized["text_content"] = text_content
return normalized
def _normalize_attachments(attachments: Any) -> list[dict[str, Any]]:
if not isinstance(attachments, list):
return []
normalized: list[dict[str, Any]] = []
for item in attachments[:MAX_ATTACHMENTS_PER_MESSAGE]:
att = _normalize_attachment(item)
if att is not None:
normalized.append(att)
return normalized
def _clean_base64_text(value: str) -> str:
return "".join(ch for ch in str(value or "") if ch not in {"\n", "\r", "\t", " "})
def _is_probable_base64_blob(value: str) -> bool:
cleaned = _clean_base64_text(value)
if len(cleaned) < 128:
return False
allowed = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=")
return all(ch in allowed for ch in cleaned)
def _infer_image_mime_from_data_url(data_url: str) -> str:
raw = str(data_url or "")
if raw.startswith("data:image/"):
prefix = raw[5:].split(",", 1)[0]
mime = prefix.split(";", 1)[0]
if mime.startswith("image/"):
return mime
return "image/png"
def _infer_image_mime_from_url(url: str) -> str:
lower = str(url or "").lower()
if ".png" in lower:
return "image/png"
if ".jpg" in lower or ".jpeg" in lower:
return "image/jpeg"
if ".webp" in lower:
return "image/webp"
if ".gif" in lower:
return "image/gif"
return "image/png"
def _image_extension_from_mime(mime_type: str) -> str:
lower = str(mime_type or "").lower()