Repository navigation
Expand file tree
/
Copy pathBMP_HTTP_API.py
More file actions
1924 lines (1746 loc) · 80.6 KB
/
Copy pathBMP_HTTP_API.py
File metadata and controls
1924 lines (1746 loc) · 80.6 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
# -*- coding: utf-8 -*-
"""
=====================================================================
# BMPLogin 公网 HTTP API v1.0 (路线 C: 认证器 ↔ 服务器直连)
---------------------------------------------------------------------
作用: 玩家 Bridge.exe 直接通过公网 HTTP 调用, 不用进游戏聊天.
直接读写 bmp_login/accounts.json 和 bmp_login/guestmap.json
(与 BeamMP 服务器主插件共享数据文件).
API 列表 (全部 POST, JSON body; 返回 JSON {ok, msg, data?}):
POST /api/auth/register {username, password, hwid?}
POST /api/auth/login {username, password, hwid, ip?, player_name?}
POST /api/auth/logout {username, hwid?}
POST /api/auth/whoami {hwid, ip?, player_name?}
POST /api/hwid/bind {hwid, username?, ip?, player_name?}
POST /api/vehicle/limit {hwid, username?, ip?, player_name?}
GET /api/ping → ok=True, ver="..."
部署 (Windows BeamMP 服务器机器):
1) 已有 Python 3.10+
2) pip 不需要额外依赖 (只用标准库: http.server + json)
3) python BMP_HTTP_API.py --host 0.0.0.0 --port 12124
4) Windows 防火墙放行 12124 端口
5) Bridge.exe 顶部填入: http://<服务器公网IP>:12124
安全:
• 所有密码传输用 sha256(password) 发送, 与服务器存储的 hashPassword 兼容.
• hwid 与 player_name 均参与 session: /login 后生成 access_token,
后续 /whoami /vehiclelimit /logout 携带 Authorization: Bearer <token>.
• 支持白名单模式 (--allow-hwid 只允许特定 HWID 调用, 或 --allow-ips a.b.c.d/24).
=====================================================================
"""
import re, os, sys, json, hashlib, hmac, time, threading, secrets, argparse, ipaddress, uuid
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
# 共享路径 — 和 main.lua 一致
_HERE = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.environ.get("BMP_DATA_DIR") or os.path.join(_HERE, "bmp_login")
ACCOUNTS_FILE = GUESTMAP_FILE = BANLIST_FILE = CHAT_QUEUE_FILE = None
ONLINE_FILE = KICK_QUEUE_FILE = VOTE_QUEUE_FILE = ADMIN_AUDIT_FILE = None
BINDINGS_FILE = None
class DataFileError(RuntimeError):
"""数据文件存在但无法解析 (损坏 / 写到一半) —— 必须拒绝写入, 绝不当成空库"""
def _set_data_dir(path):
"""统一推导全部数据文件路径.
以前 --data-dir 只改了 6 个路径, 漏了 chat_queue.json / admin_audit.jsonl,
导致 Bridge 聊天写进旧目录, Lua 插件永远读不到 (聊天完全不广播)。"""
global DATA_DIR, ACCOUNTS_FILE, GUESTMAP_FILE, BANLIST_FILE, CHAT_QUEUE_FILE
global ONLINE_FILE, KICK_QUEUE_FILE, VOTE_QUEUE_FILE, ADMIN_AUDIT_FILE, BINDINGS_FILE
DATA_DIR = os.path.abspath(path)
os.makedirs(DATA_DIR, exist_ok=True)
ACCOUNTS_FILE = os.path.join(DATA_DIR, "accounts.json")
GUESTMAP_FILE = os.path.join(DATA_DIR, "guestmap.json")
BANLIST_FILE = os.path.join(DATA_DIR, "banlist.json")
CHAT_QUEUE_FILE = os.path.join(DATA_DIR, "chat_queue.json")
ONLINE_FILE = os.path.join(DATA_DIR, "online_players.json")
KICK_QUEUE_FILE = os.path.join(DATA_DIR, "kick_queue.json")
VOTE_QUEUE_FILE = os.path.join(DATA_DIR, "vote_queue.json")
ADMIN_AUDIT_FILE = os.path.join(DATA_DIR, "admin_audit.jsonl")
BINDINGS_FILE = os.path.join(DATA_DIR, "bindings.json")
_set_data_dir(DATA_DIR)
VEHICLE_LIMITS = {"admin": 999, "authenticated": 5, "unauthenticated": 1}
DEFAULT_API_PORT = 12124
VERSION = "BMP-HTTP/v1.6.0"
ACCESS_TTL = 7 * 24 * 3600 # 7 天
# 聊天速率限制: name -> [时间戳列表]
CHAT_RATE_LIMIT = {}
CHAT_RATE_WINDOW = 60 # 60 秒
CHAT_RATE_MAX = 6 # 最多 6 条/分钟
# ---- 登录速率限制 ----
LOGIN_RATE = {} # key: "ip:username" -> [timestamps]
LOGIN_RATE_WINDOW = 300 # 5 分钟窗口
LOGIN_RATE_MAX = 5 # 每 5 分钟最多 5 次登录尝试
LOGIN_LOCKOUT_SECONDS = 600 # 超限后锁定 10 分钟
# ---- 请求体限制 ----
MAX_BODY_SIZE = 65536 # 64 KB (JSON body)
# ---- 投票请求限速 (按客户端 IP) ----
VOTE_RATE = {}
VOTE_RATE_WINDOW = 60
VOTE_RATE_MAX = 6
def _vote_allowed(ip):
now = int(time.time())
hits = [t for t in VOTE_RATE.get(ip, []) if now - t < VOTE_RATE_WINDOW]
if len(hits) >= VOTE_RATE_MAX:
VOTE_RATE[ip] = hits
return False
hits.append(now)
VOTE_RATE[ip] = hits
if len(VOTE_RATE) > 5000:
for k in list(VOTE_RATE.keys())[:2500]:
VOTE_RATE.pop(k, None)
return True
# ---- 管理员审计日志 ----
# ADMIN_AUDIT_FILE 由 _set_data_dir() 统一赋值
def _audit_log(action, admin, target="", detail=""):
"""管理员操作审计 — 追加写入 JSONL (每行一条, 不截断)"""
try:
entry = {
"ts": int(time.time()),
"action": action,
"admin": admin,
"target": target,
"detail": detail,
"ip": "",
}
with FILE_LOCK:
with open(ADMIN_AUDIT_FILE, "a", encoding="utf-8") as f:
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
except Exception:
pass
def _check_login_rate(ip, username):
"""检查登录速率限制, 返回 (允许, 剩余秒数)"""
key = f"{ip}:{username}"
now = int(time.time())
# 清理过期记录
if key in LOGIN_RATE:
LOGIN_RATE[key] = [t for t in LOGIN_RATE[key] if now - t < LOGIN_RATE_WINDOW]
else:
LOGIN_RATE[key] = []
recent = LOGIN_RATE[key]
if len(recent) >= LOGIN_RATE_MAX:
oldest = recent[0]
wait = LOGIN_LOCKOUT_SECONDS - (now - oldest)
return False, max(0, wait)
return True, 0
def _record_login_attempt(ip, username):
key = f"{ip}:{username}"
LOGIN_RATE.setdefault(key, [])
LOGIN_RATE[key].append(int(time.time()))
# 防止字典无限增长
if len(LOGIN_RATE) > 10000:
for k in list(LOGIN_RATE.keys())[:5000]:
del LOGIN_RATE[k]
# ============================================================
# JSON 数组兼容 (与 main.lua Array metatable 一致: 空表是 [])
# ============================================================
def _ensure_list(v):
if isinstance(v, list): return v
if isinstance(v, dict) and not v: return []
return []
def _deduplicate_bids(bids):
"""精简 bind_beam_ids: GUEST 只保留最近一条 (减少 UI 噪音)"""
bids = _ensure_list(bids)
if len(bids) <= 3:
return bids
grouped = {}
order = []
for b in bids:
tag = b.split(":", 1)[0] if ":" in b else "OTHER"
if tag not in grouped:
grouped[tag] = []
order.append(tag)
grouped[tag].append(b)
result = []
for tag in order:
items = grouped[tag]
if tag == "GUEST" and len(items) > 1:
result.append(items[-1]) # 只保留最近一条
else:
result.extend(items)
return result
def readJsonFile(path, retries=4, delay=0.04):
"""读 JSON. 文件不存在 -> None; 文件损坏 -> 抛 DataFileError.
旧实现把所有异常都吞成 None, 于是"文件损坏"和"文件不存在"无法区分,
随后的注册/封禁会把整份 accounts.json / banlist.json 覆盖成只剩一条记录。
这里额外做几次重试: Lua 插件与 Python API 是两个进程, Lua 在 Windows 上
改名失败时会退回"截断后重写", 正好读到半个文件是可能的。重试能消掉这种
瞬时误判, 真正损坏的文件仍然会抛异常 (调用方拒绝写入)。"""
if not os.path.exists(path):
return None
last = None
for attempt in range(max(1, retries)):
for enc in ("utf-8-sig", "utf-8"):
try:
with open(path, "r", encoding=enc) as f:
return json.loads(f.read() or "null")
except (OSError, ValueError) as e:
last = e
if attempt + 1 < retries:
time.sleep(delay)
raise DataFileError(f"{os.path.basename(path)}: {last}")
def writeJsonFile(path, obj):
tmp = path + ".tmp"
try:
with open(tmp, "w", encoding="utf-8") as f:
json.dump(obj, f, ensure_ascii=False, indent=2)
os.replace(tmp, path)
return True, None
except Exception as e:
try: os.remove(tmp)
except Exception: pass
return False, str(e)
# ============================================================
# 密码 hash (与 main.lua 的 hashPassword / verifyPassword 完全一致)
# main.lua 格式: hashPassword -> salt_hex16 : 64 printable chars
# hash64[i] = (password[i%pwdLen] + saltBytes[i%8] + i) % 95 + 32
# (ASCII 32..126 可打印字符,含符号空格, 不是 hex sha256)
# ============================================================
def _lua_hash64(password, salt_hex):
# 必须按 UTF-8 字节计算, 与 main.lua 的 password:byte(i) / #password 一致;
# 旧实现按 Unicode 码点算, 中文密码在游戏内永远登录失败
if not isinstance(password, str) or password == "":
raise ValueError("empty password")
pwd = password.encode("utf-8")
salt_bytes = [int(salt_hex[i:i+1], 16) for i in range(16)]
pwd_len = max(1, len(pwd))
out = []
for i in range(1, 65):
ci = pwd[(i - 1) % pwd_len]
si = salt_bytes[(i - 1) % 8]
out.append(chr(((ci + si + i) % 95) + 32))
return "".join(out)
def hashPassword(password):
import secrets as _s
salt_hex = _s.token_hex(8) # 16 位 hex
return f"{salt_hex}:{_lua_hash64(password, salt_hex)}"
def verifyPassword(password, stored):
if not stored: return False
if not isinstance(password, str) or password == "": return False
# 格式 1: "salt_hex16:hash64" (main.lua / API 注册的新账号)
if ":" in stored:
# salt 在最左, hash 在最后一个冒号之后 (main.lua verify: 匹配^([^:]+): 和 :(.+)$)
idx = stored.find(":")
salt_hex = stored[:idx]
hash_part = stored[idx+1:]
if len(hash_part) > 64:
hash_part = hash_part[-64:]
if len(salt_hex) == 16:
computed = _lua_hash64(password, salt_hex)
if hmac.compare_digest(computed, hash_part):
return True
# 格式 2: "salt_hex:<64位小写hex sha256(salt::pwd)>"
_, got = _salted_hash_sha256(password, salt_hex)
if hmac.compare_digest(got, hash_part):
return True
return False
# 格式 3: 只有 64 位 sha256 (没有 salt, 纯 sha256(password))
got = hashlib.sha256(password.encode("utf-8")).hexdigest()
return hmac.compare_digest(got, stored)
def _salted_hash_sha256(password, salt_hex=None):
"""兼容老的 sha256(salt::password) 格式 (未来可能再用, 保留)"""
if salt_hex is None:
salt_hex = secrets.token_hex(8)
combined = f"{salt_hex}::{password}".encode("utf-8")
return salt_hex, hashlib.sha256(combined).hexdigest()
# ============================================================
# 共享数据: accounts / guestmap / banlist
# ============================================================
def loadAccounts():
data = readJsonFile(ACCOUNTS_FILE)
if data is None or (isinstance(data, list) and not data):
data = {}
if not isinstance(data, dict):
raise DataFileError("accounts.json: 顶层不是对象")
for k, v in data.items():
if isinstance(v, dict):
v["bind_beam_ids"] = _ensure_list(v.get("bind_beam_ids"))
v["login_records"] = _ensure_list(v.get("login_records"))
return data
def saveAccounts(data):
return writeJsonFile(ACCOUNTS_FILE, data)
def loadGuestMap():
data = readJsonFile(GUESTMAP_FILE)
return data if isinstance(data, dict) else {}
def saveGuestMap(gm):
return writeJsonFile(GUESTMAP_FILE, gm)
def loadBanlist():
data = readJsonFile(BANLIST_FILE)
if data is None or (isinstance(data, list) and not data):
data = {}
if not isinstance(data, dict):
raise DataFileError("banlist.json: 顶层不是对象")
data["devices"] = _ensure_list(data.get("devices"))
data["accounts"] = _ensure_list(data.get("accounts"))
return data
# ============================================================
# 业务逻辑
# ============================================================
FILE_LOCK = threading.RLock()
ADMINS = set(a.strip() for a in os.environ.get("BMP_ADMINS","").split(",") if a.strip())
def _is_admin(username):
if not username: return False
# 1) 检查 ADMINS 集合 (命令行 --admins)
if username in ADMINS:
return True
# 2) 检查 accounts.json 中的 is_admin 字段
try:
accounts = loadAccounts()
acc = accounts.get(username)
if acc and isinstance(acc, dict) and acc.get("is_admin"):
return True
except Exception:
pass
return False
def _normalize_beam_ids(hwid, ip, player_name, username_bound=None):
"""按 main.lua 的 3 个优先级返回候选 beam_id 列表"""
bids = []
if hwid and isinstance(hwid, str) and len(hwid) >= 8:
bids.append("HWID:settings.BMPLoginHWID(uuid):" + str(hwid).lower().strip())
if ip and isinstance(ip, str) and re.match(r"^\d+\.\d+\.\d+\.\d+$", ip):
bids.append("IP:" + ip)
if player_name and isinstance(player_name, str) and 2 <= len(player_name) <= 40:
gm = player_name
if gm.lower().startswith("guest"):
bids.append("GUEST:" + gm)
else:
bids.append("NAME:" + gm)
# 账号强制绑定 (如果存在 username, 把账号自己的绑定加进去, 方便查找)
if username_bound and isinstance(username_bound, str):
pass
return bids
def _find_account(accounts, bids):
"""在 accounts 的 bind_beam_ids 里找命中 bids 的账号"""
for username, acc in accounts.items():
bind_ids = _ensure_list(acc.get("bind_beam_ids"))
for b in bind_ids:
if b in bids:
return username
return None
def _account_is_admin(accounts, username):
"""ADMINS 集合 或 accounts.json 里持久化的 is_admin 都算管理员"""
if not username:
return False
if username in ADMINS:
return True
acc = accounts.get(username) if isinstance(accounts, dict) else None
return bool(isinstance(acc, dict) and acc.get("is_admin"))
def _revoke_user_tokens(username):
"""改密/删号/撤管理员时立刻作废该账号所有 token.
旧实现只校验过期时间, 密码被重置后攻击者手里的 token 还能用满 7 天。"""
if not username:
return 0
with TOKENS_LOCK:
to_pop = [t for t, info in TOKENS.items() if info.get("username") == username]
for t in to_pop:
TOKENS.pop(t, None)
return len(to_pop)
# Access tokens: token -> {username, issued_at, expires_at}
TOKENS = {}
TOKENS_LOCK = threading.Lock()
def _issue_token(username):
tok = secrets.token_urlsafe(32)
with TOKENS_LOCK:
TOKENS[tok] = {"username": username,
"issued_at": int(time.time()),
"expires_at": int(time.time()) + ACCESS_TTL}
return tok
def _validate_token(auth_header):
if not auth_header: return None
m = re.match(r"Bearer\s+(\S+)", str(auth_header), flags=re.I)
if not m: return None
tok = m.group(1)
with TOKENS_LOCK:
info = TOKENS.get(tok)
if not info: return None
if info["expires_at"] < int(time.time()):
TOKENS.pop(tok, None)
return None
username = info["username"]
# 账号已被删除时 token 立即失效 (读到损坏文件时不要阻断已登录用户)
try:
accounts = loadAccounts()
if username not in accounts:
with TOKENS_LOCK:
TOKENS.pop(tok, None)
return None
except DataFileError:
pass
return username
def _get_str(body, key, default=""):
"""安全取字符串字段: 任何非字符串类型 (数字 / None / list) 一律返回默认值"""
v = body.get(key) if isinstance(body, dict) else None
return v.strip() if isinstance(v, str) else default
class BodyTooLarge(Exception):
pass
# ============================================================
# HTTP Handler
# ============================================================
class APIHandler(BaseHTTPRequestHandler):
server_version = VERSION
protocol_version = "HTTP/1.1"
timeout = 15 # 慢连接不能无限占着 handler 线程
def log_message(self, fmt, *args):
return
def _client_allowed(self):
"""--allow-ips 白名单. 旧实现只在 do_POST 里判断, 所有 GET 全部绕过"""
subnets = getattr(self.server, "cfg", {}).get("allow_subnets")
if not subnets:
return True
try:
ip_obj = ipaddress.ip_address(self.client_address[0])
except ValueError:
return False
return any(ip_obj in n for n in subnets)
def _vote_allowed(self):
"""投票接口按客户端 IP 限速 (防刷队列)"""
return _vote_allowed(self.client_address[0])
def _json(self, status, body):
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(data)))
self.send_header("Connection", "close")
# 安全头
self.send_header("X-Content-Type-Options", "nosniff")
self.send_header("X-Frame-Options", "DENY")
self.send_header("X-XSS-Protection", "1; mode=block")
self.send_header("Cache-Control", "no-store")
# CORS — 管理员 API 内部调, 通配只限玩家 API
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Headers", "Authorization, Content-Type, X-HWID")
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
self.end_headers()
self.wfile.write(data)
def _read_body(self):
try:
length = int(self.headers.get("Content-Length") or "0")
except Exception:
length = 0
if length > MAX_BODY_SIZE:
# 抛异常交给 do_POST 统一发 413, 否则会先发 413 再发 400 (双响应)
raise BodyTooLarge()
try:
raw = self.rfile.read(length) if length > 0 else b""
except (OSError, TimeoutError):
self.close_connection = True
return None
if not raw: return {}
try:
return json.loads(raw.decode("utf-8"))
except Exception:
return None
def do_OPTIONS(self):
self._json(204, {})
def do_GET(self):
if not self._client_allowed():
self._json(403, {"ok": False, "error": "IP not allowed"})
return
path = urlparse(self.path).path.rstrip("/") or "/"
if path == "/api/ping":
self._json(200, {"ok": True, "ver": VERSION,
"now": int(time.time())})
return
# 网页面板: 浏览器直接打开 http://<服务器IP>:12124/
if path in ("/", "/index.html", "/panel"):
return self._serve_panel()
if path in ("/account", "/register"):
return self._serve_static("account.html")
if path == "/api/bng/verify":
return self._bng_verify()
if path == "/api/chat/log":
return self._chat_log()
if path in ("/api/players/live", "/api/players/online"):
return self._players_live(getattr(self, "_auth_cache", None))
if path == "/api/chat/queue":
return self._chat_queue(getattr(self, "_auth_cache", None))
if path == "/api/players/names":
return self._players_names()
if path == "/api/vote/status":
return self._vote_status()
self._json(404, {"ok": False, "error": "not found"})
def do_POST(self):
try:
return self._do_post_impl()
except BodyTooLarge:
return self._json(413, {"ok": False, "error": f"请求体过大 (最大 {MAX_BODY_SIZE} 字节)"})
except DataFileError as e:
return self._json(503, {"ok": False, "error": f"数据文件损坏, 已拒绝写入: {e}"})
except Exception as e:
try:
self._json(500, {"ok": False, "error": f"服务器内部错误: {e}"})
except Exception:
pass
def _do_post_impl(self):
path = urlparse(self.path).path.rstrip("/") or "/"
# 先检查 IP 白名单
if not self._client_allowed():
self._json(403, {"ok": False, "error": "IP not allowed"})
return
body = self._read_body()
if body is None:
self._json(400, {"ok": False, "error": "invalid JSON body"})
return
if not isinstance(body, dict):
self._json(400, {"ok": False, "error": "JSON body must be an object"})
return
auth = self.headers.get("Authorization", "")
# ---- /api/auth/register ----
if path == "/api/auth/register":
return self._register(body)
# ---- /api/auth/login ----
if path == "/api/auth/login":
return self._login(body)
# ---- /api/auth/logout ----
if path == "/api/auth/logout":
return self._logout(auth)
# ---- /api/auth/whoami ----
if path == "/api/auth/whoami":
return self._whoami(auth, body)
# ---- /api/hwid/bind ----
if path == "/api/hwid/bind":
return self._bind_hwid(auth, body)
# ---- /api/vehicle/limit ----
if path == "/api/vehicle/limit":
return self._vehicle_limit(auth, body)
# ---- /api/chat/send (Bridge 聊天框 → 公屏广播) ----
if path == "/api/chat/send":
return self._chat_send(auth, body)
# ---- /api/chat/queue (查看当前队列, 调试用) ----
if path == "/api/chat/queue":
return self._chat_queue(auth)
# ---- /api/vote/kick (Bridge 发起投票) ----
if path == "/api/vote/kick":
return self._vote_kick(auth, body)
# ---- /api/vote/cast (Bridge 投票) ----
if path == "/api/vote/cast":
return self._vote_cast(auth, body)
# ---- 网站账号: BNG 官方账号 + 机器码 ----
if path == "/api/account/register":
return self._account_register(body)
if path == "/api/account/login":
return self._account_login(body)
if path == "/api/account/login-hwid":
return self._account_login_hwid(body)
# ---- 管理员 API ----
if path.startswith("/api/admin/"):
return self._admin_route(auth, path, body)
self._json(404, {"ok": False, "error": "not found: " + path})
# ============= 业务实现 =============
def _register(self, body):
username = _get_str(body, "username")
password = body.get("password")
hwid = _get_str(body, "hwid")
# IP 一律取真实 socket 对端, 不能听客户端自报 (否则可抢占别人的 IP 绑定)
ip = self.client_address[0]
player_name = _get_str(body, "player_name")
if not re.match(r"^[A-Za-z0-9_]{3,20}$", username):
return self._json(200, {"ok": False, "msg": "账号名不合法 (3-20 字符, 字母/数字/下划线)"})
if not isinstance(password, str):
return self._json(200, {"ok": False, "msg": "密码不合法 (4-64 字符)"})
if len(password) < 4 or len(password) > 64:
return self._json(200, {"ok": False, "msg": "密码不合法 (4-64 字符)"})
# 管理员账号名是保留名: 否则任何人都能抢注 --admins 里的名字拿到管理员权限
if username in ADMINS:
return self._json(403, {"ok": False,
"msg": "该账号名为管理员保留名, 请先在服务器本机创建账号"})
with FILE_LOCK:
accounts = loadAccounts()
if accounts.get(username):
return self._json(200, {"ok": False, "msg": f"账号 {username} 已存在"})
bids = _normalize_beam_ids(hwid, ip, player_name)
account = {
"username": username,
"password_hash": hashPassword(password),
"register_time": int(time.time()),
"bind_beam_ids": bids,
"login_records": [],
}
accounts[username] = account
ok, err = saveAccounts(accounts)
if not ok:
return self._json(500, {"ok": False, "msg": "保存失败: " + str(err)})
token = _issue_token(username)
return self._json(200, {
"ok": True,
"msg": f"注册成功!账号 {username} 已创建, 已自动登录",
"data": {"username": username, "access_token": token,
"bound_ids": bids, "ttl": ACCESS_TTL},
})
def _login(self, body):
username = _get_str(body, "username")
password = body.get("password")
hwid = _get_str(body, "hwid")
# 同上: 用真实对端 IP
ip = self.client_address[0]
player_name = _get_str(body, "player_name")
client_ip = self.client_address[0]
# 空密码 / 非字符串密码: 直接当密码错误处理 (不能抛异常, 否则不记录限速)
if not isinstance(password, str) or password == "":
if username:
_record_login_attempt(client_ip, username)
return self._json(200, {"ok": False, "msg": "账号或密码不正确"})
# ---- 登录速率限制 (防暴力破解) ----
if username:
allowed, wait = _check_login_rate(client_ip, username)
if not allowed:
return self._json(429, {
"ok": False,
"msg": f"登录尝试过多, 请 {wait} 秒后再试",
"retry_after": wait,
})
with FILE_LOCK:
accounts = loadAccounts()
acc = accounts.get(username)
if not acc:
# 账号不存在也记录 (防止枚举, 但记录登录失败次数)
if username:
_record_login_attempt(client_ip, username)
return self._json(200, {"ok": False, "msg": "账号或密码不正确"})
stored_hash = acc.get("password_hash") or ""
ok_pwd = verifyPassword(password, stored_hash)
if not ok_pwd:
# 密码错误 — 记录尝试
_record_login_attempt(client_ip, username)
return self._json(200, {"ok": False, "msg": "账号或密码不正确"})
bids = _normalize_beam_ids(hwid, ip, player_name)
bound = acc.get("bind_beam_ids") or []
changed = False
for b in bids:
if b and b not in bound:
bound.append(b)
changed = True
if changed:
acc["bind_beam_ids"] = bound
saveAccounts(accounts)
# 写登录记录
records = acc.get("login_records") or []
records.append({
"time": int(time.time()),
"hwid": hwid,
"ip": ip,
"name": player_name,
"via": "HTTP-API",
})
acc["login_records"] = records[-100:]
saveAccounts(accounts)
# 更新 guestmap
if bids:
gm = loadGuestMap()
for b in bids:
gm[b] = {"account": username, "last_seen": int(time.time())}
saveGuestMap(gm)
# 登录成功 — 清空速率限制记录
# (旧代码 keys 是 "ip:username", 却用 `username in LOGIN_RATE` 判断,
# 条件永远为假 -> 失败次数跨成功登录持续累计, 正常用户也会被锁)
if username:
LOGIN_RATE.pop(f"{client_ip}:{username}", None)
token = _issue_token(username)
# 管理员登录审计
if _is_admin(username):
_audit_log("admin_login", username, detail=f"ip={client_ip} hwid={hwid}")
return self._json(200, {
"ok": True,
"msg": f"登录成功, 欢迎回来 {username}",
"data": {"username": username,
"is_admin": _is_admin(username),
"bound_count": len(acc.get("bind_beam_ids") or []),
"access_token": token,
"ttl": ACCESS_TTL},
})
def _logout(self, auth):
username = _validate_token(auth)
if not username:
return self._json(200, {"ok": False, "msg": "未登录"})
# 撤销当前 token
with TOKENS_LOCK:
# 线性搜索该用户的 token
to_pop = [t for t, info in TOKENS.items() if info["username"] == username]
for t in to_pop:
TOKENS.pop(t, None)
return self._json(200, {"ok": True, "msg": f"{username} 已退出登录"})
def _whoami(self, auth, body):
username = _validate_token(auth)
hwid = (body.get("hwid") or "").strip()
ip = (body.get("ip") or "").strip()
player_name = (body.get("player_name") or "").strip()
if not username:
# 未登录, 但如果有 hwid 可以帮他查当前绑定情况
with FILE_LOCK:
accounts = loadAccounts()
bids = _normalize_beam_ids(hwid, ip, player_name)
who = _find_account(accounts, bids)
return self._json(200, {
"ok": True,
"msg": "未登录",
"data": {"logged": False,
"hwid_bound_account": who,
"guest_ids": bids,
"vehicle_limit": VEHICLE_LIMITS["unauthenticated"],
"label": "未认证用户"},
})
with FILE_LOCK:
accounts = loadAccounts()
acc = accounts.get(username)
if not acc:
return self._json(200, {"ok": False, "msg": "账号不存在"})
bids = acc.get("bind_beam_ids") or []
records = acc.get("login_records") or []
last_login = records[-1] if records else None
reg_time = acc.get("register_time")
if _is_admin(username):
label, limit = "管理员", VEHICLE_LIMITS["admin"]
else:
if bids:
label, limit = "认证用户", VEHICLE_LIMITS["authenticated"]
else:
label, limit = "未认证用户", VEHICLE_LIMITS["unauthenticated"]
return self._json(200, {
"ok": True,
"msg": f"当前账号: {username} ({label})",
"data": {"logged": True,
"username": username,
"is_admin": _is_admin(username),
"label": label,
"vehicle_limit": limit,
"bound_ids": bids,
"register_time": reg_time,
"last_login": last_login},
})
def _bind_hwid(self, auth, body):
username = _validate_token(auth)
if not username:
# 未登录允许先绑定 (和 /bmpid 聊天命令一致), 等玩家登录时自动关联账号
username = None
hwid = (body.get("hwid") or "").strip()
if len(hwid) < 8:
return self._json(200, {"ok": False, "msg": "hwid 不合法"})
ip = (body.get("ip") or "").strip()
player_name = (body.get("player_name") or "").strip()
bids = _normalize_beam_ids(hwid, ip, player_name)
with FILE_LOCK:
accounts = loadAccounts()
if username:
acc = accounts.get(username)
if not acc:
return self._json(200, {"ok": False, "msg": "账号不存在"})
bound = acc.get("bind_beam_ids") or []
for b in bids:
if b and b not in bound:
bound.append(b)
acc["bind_beam_ids"] = bound
saveAccounts(accounts)
# guestmap 更新
gm = loadGuestMap()
for b in bids:
gm[b] = {"account": username, "last_seen": int(time.time())}
saveGuestMap(gm)
label, limit = "认证用户", VEHICLE_LIMITS["authenticated"]
else:
# 暂存 guestmap 空账号? 存 settings.BMPLoginHWID 标识进 guestmap 不存账号, 但 main.lua 下次 _tryBind 时会用到
gm = loadGuestMap()
for b in bids:
if b not in gm:
gm[b] = {"last_seen": int(time.time()), "via": "HTTP-hwid-only"}
saveGuestMap(gm)
label, limit = "未认证用户", VEHICLE_LIMITS["unauthenticated"]
return self._json(200, {
"ok": True,
"msg": f"HWID 已接收, 绑定稳定UUID: {hwid}",
"data": {"bound_ids": bids, "label": label, "vehicle_limit": limit},
})
def _vehicle_limit(self, auth, body):
username = _validate_token(auth)
hwid = (body.get("hwid") or "").strip()
ip = (body.get("ip") or "").strip()
player_name = (body.get("player_name") or "").strip()
bids = _normalize_beam_ids(hwid, ip, player_name)
with FILE_LOCK:
accounts = loadAccounts()
if not username:
username = _find_account(accounts, bids)
if username and _is_admin(username):
label, limit = "管理员", VEHICLE_LIMITS["admin"]
elif username and bids:
label, limit = "认证用户", VEHICLE_LIMITS["authenticated"]
elif bids and _find_account(accounts, bids):
label, limit = "认证用户", VEHICLE_LIMITS["authenticated"]
else:
label, limit = "未认证用户", VEHICLE_LIMITS["unauthenticated"]
return self._json(200, {
"ok": True,
"msg": f"您是[{label}], 车辆上限 {limit} 辆",
"data": {"label": label, "vehicle_limit": limit,
"logged": bool(username), "username": username},
})
# ============= 聊天 → 公屏广播 =============
def _chat_send(self, auth, body):
"""
接收 {player_name, message, hwid?} → 写入 chat_queue.json
Lua 主插件 onTick 会每秒 poll 这个文件, 读到未发送消息就
MP.SendChatMessage(-1, "[Bridge] name: text") 广播给所有在线玩家.
"""
# 1) 取身份: 已登录一律用账号名 (不允许自报名字冒充别人);
# 未登录只能是 "guest", 不能借用任意 player_name 在公屏上冒充某玩家。
username = _validate_token(auth)
claimed = (body.get("player_name") or body.get("name") or "").strip()
if username:
name = username
if claimed and claimed != username:
_audit_log("chat_name_ignored", username, detail=f"claimed={claimed}")
else:
name = "guest"
if len(name) > 16:
name = name[:16]
name = re.sub(r"[\x00-\x1f<>{}\[\]|\\^]+", "_", name).strip() or "guest"
# 2) 文本检查
text = (body.get("message") or body.get("text") or "").strip()
if not text:
return self._json(200, {"ok": False, "msg": "消息不能为空"})
if len(text) > 200:
return self._json(200, {"ok": False, "msg": f"消息太长 ({len(text)}/200)"})
# 过滤控制字符 + 严重 HTML/JS 注入 (Lua 端再过一次)
text = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f]", "", text)
# 3) 速率限制 (按 name + 客户端 IP 双维度)
client_ip = self.client_address[0]
rate_key = f"{name}|{client_ip}"
now = int(time.time())
recent = [t for t in CHAT_RATE_LIMIT.get(rate_key, [])
if now - t < CHAT_RATE_WINDOW]
if len(recent) >= CHAT_RATE_MAX:
wait = CHAT_RATE_WINDOW - (now - min(recent))
return self._json(200, {
"ok": False,
"msg": f"发言太快, 请等 {wait} 秒再试 (限 {CHAT_RATE_MAX}/{CHAT_RATE_WINDOW}s)",
})
recent.append(now)
CHAT_RATE_LIMIT[rate_key] = recent
# 4) 写入队列 (file lock 防止和 Lua 抢写)
item = {
"id": secrets.token_hex(8),
"ts": now,
"name": name,
"text": text,
"ip": client_ip,
"username": username,
"sent": False,
}
try:
with FILE_LOCK:
queue = readJsonFile(CHAT_QUEUE_FILE)
if not isinstance(queue, list):
queue = []
queue.append(item)
# 队列上限 100 (旧的丢掉)
if len(queue) > 100:
queue = queue[-100:]
ok_w, err_w = writeJsonFile(CHAT_QUEUE_FILE, queue)
if not ok_w:
return self._json(500, {"ok": False, "msg": f"队列写入失败: {err_w}"})
except Exception as e:
return self._json(500, {"ok": False, "msg": "队列写入异常: " + str(e)})
return self._json(200, {
"ok": True,
"msg": f"已加入发送队列, 服务器将在 ~1 秒内广播给所有在线玩家",
"data": {"id": item["id"], "ahead": len([x for x in queue if not x.get("sent")]) - 1},
})
def _chat_queue(self, auth):
"""调试用: 查看当前队列"""
try:
with FILE_LOCK:
queue = readJsonFile(CHAT_QUEUE_FILE) or []
except Exception:
queue = []
unsent = [x for x in queue if not x.get("sent")] if isinstance(queue, list) else []
return self._json(200, {
"ok": True,
"data": {
"total": len(queue) if isinstance(queue, list) else 0,
"unsent": len(unsent),
"items": queue[-20:] if isinstance(queue, list) else [],
},
})
# ============= 管理员 API =============
def _admin_route(self, auth, path, body):
"""管理员路由分发 — 所有 /api/admin/* 端点"""
username = _validate_token(auth)
if not username:
return self._json(401, {"ok": False, "error": "未登录或 token 已过期"})
if not _is_admin(username):
return self._json(403, {"ok": False, "error": "非管理员, 无权访问"})
client_ip = self.client_address[0]
# 路由表
if path == "/api/admin/accounts":
return self._admin_list_accounts()
if path == "/api/admin/accounts/delete":
_audit_log("admin_delete_account", username,
target=(body or {}).get("username", ""),
detail=f"ip={client_ip}")
return self._admin_delete_account(body)
if path == "/api/admin/accounts/reset-password":
_audit_log("admin_reset_password", username,
target=(body or {}).get("username", ""),
detail=f"ip={client_ip}")
return self._admin_reset_password(body)
if path == "/api/admin/accounts/toggle-admin":
is_admin = (body or {}).get("is_admin", False)
_audit_log("admin_toggle_admin", username,
target=(body or {}).get("username", ""),
detail=f"set={is_admin} ip={client_ip}")
return self._admin_toggle_admin(body)
if path == "/api/admin/accounts/unbind":
_audit_log("admin_unbind", username,
target=(body or {}).get("username", ""),
detail=f"beam_id={(body or {}).get('beam_id','')} ip={client_ip}")
return self._admin_unbind(body)
if path == "/api/admin/ban":
_audit_log("admin_ban", username,
target=f"{(body or {}).get('type','')}:{(body or {}).get('value','')}",
detail=f"reason={(body or {}).get('reason','')} ip={client_ip}")
return self._admin_ban(body)
if path == "/api/admin/unban":