-
Notifications
You must be signed in to change notification settings - Fork 278
Expand file tree
/
Copy pathsso_to_auth_json.py
More file actions
2616 lines (2392 loc) · 94.9 KB
/
Copy pathsso_to_auth_json.py
File metadata and controls
2616 lines (2392 loc) · 94.9 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
#!/usr/bin/env python3
"""
SSO cookie → CPA / Grok2API auth.json 格式(纯 HTTP)
主路径:RFC 8628 Device Flow(对齐 CLIProxyAPI internal/auth/xai + verify/approve)
回退:Authorization Code + PKCE(referrer=grok-build + plan=generic)
写出:
- CLIProxyAPI 扁平 xai-*.json(base_url=cli-chat-proxy.grok.com)
- Grok2API / ~/.grok 风格 issuer::client_id 嵌套 auth
用法:
# 单个 / 批量 SSO,写出多个独立 auth 文件(每个可直接 cp 到 ~/.grok/auth.json)
python3 sso_to_auth_json.py --sso sso_list.txt --out-dir ./auth_out
# 合并到一个 json(key 带 user_id 后缀,避免覆盖)
python3 sso_to_auth_json.py --sso sso_list.txt --out auth_merged.json --merge
# 单行 sso
python3 sso_to_auth_json.py --sso-cookie 'eyJ...' --out ~/.grok/auth.json
# 只出 CPA + Grok2API
python3 sso_to_auth_json.py --sso sso_list.txt --cpa-auth-dir /path/to/auths \\
--grok2api-auth-dir /path/to/g2a --proxy http://127.0.0.1:7890
# 仅批量检查 grok.com 账号风控状态(botFlagSource/risk/deny),不换 token 不入库
# --sso-state-export 导出被标记名单 jsonl;--sso-state-clean-export 导出干净 sso 原始行 txt
python3 sso_to_auth_json.py --check-sso-state sso_list.txt --from-config config.json \\
--sso-state-export log/sso_flagged.jsonl \\
--sso-state-clean-export log/sso_clean.txt \\
--report-json log/sso_state_report.json
"""
from __future__ import annotations
import argparse
import base64
import hashlib
import json
import os
import re
import secrets
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from curl_cffi import requests
from secure_files import (
append_private_text,
atomic_write_json,
atomic_write_text,
ensure_private_dir,
exclusive_file_lock,
)
CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828"
OIDC_ISSUER = "https://auth.x.ai"
AUTH_KEY = f"{OIDC_ISSUER}::{CLIENT_ID}"
# 与 CPA internal/auth/xai/types.go 的 Scope 严格一致。
# 不可加 conversations:read/write —— 该 client 未获授权,device/code 与 consent
# 均会通过,但 token 端点会以 invalid_grant "Access denied" 拒绝签发。
SCOPES = "openid profile email offline_access grok-cli:access api:access"
# --- Device Flow 常量(主路径,对齐 CPA internal/auth/xai) --------------------
DEVICE_CODE_URL = f"{OIDC_ISSUER}/oauth2/device/code"
DEVICE_VERIFY_URL = f"{OIDC_ISSUER}/oauth2/device/verify"
DEVICE_APPROVE_URL = f"{OIDC_ISSUER}/oauth2/device/approve"
DEVICE_CODE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code"
DEVICE_DEFAULT_INTERVAL = 2
DEVICE_DEFAULT_EXPIRES = 1800
DEVICE_POLL_CAP_SECONDS = 10
# 浏览器点完「允许」后,服务端落库可能有延迟;协议路径 approve 多半无效,快速回退
DEVICE_GRACE_BROWSER = 8
DEVICE_GRACE_PROTOCOL = 6
# --- Authorization Code Flow 常量(回退路径) --------------------------------
# authorize 必须注入 referrer=grok-build,否则 access_token 无该 claim,
# cli-chat-proxy 会 403。实测 referrer=cli-proxy-api 会得到 referrer=None。
# plan=generic 对齐 grok-build-auth;consent.referrer 仍置空。
REDIRECT_URI = "http://127.0.0.1:56121/callback"
GROK_REFERRER = "grok-build"
GROK_PLAN = "generic"
GROK_VERSION = "0.2.93"
GROK_TOKEN_UA = f"grok-pager/{GROK_VERSION} grok-shell/{GROK_VERSION} (linux; x86_64)"
DEFAULT_UA = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36"
)
# consent 提交用的 Next.js Server Action ID(bootstrap;失效时扫 JS / 读本地缓存)
# 2026-07 实测:401b73e22a5e... 已 404;成功 ID 会写入 .next_action_id.cache 供下次快速路径
NEXT_ACTION_ID = "401b73e22a5e68737d0037e1aa449fef82cd1b35fb"
_NEXT_ACTION_CACHE_PATH = Path(__file__).resolve().parent / ".next_action_id.cache"
_NEXT_ACTION_ID_RE = re.compile(r"^[0-9a-f]{40,44}$", re.I)
_working_next_action_id = "" # 启动时由 _load_working_next_action_id() 填充
_NEXT_ACTION_RE = re.compile(
r'(?:\$ACTION_ID_|next-action["\']?\s*[:=]\s*["\']|["\'])([0-9a-f]{40,44})["\']',
re.I,
)
_CREATE_SERVER_REF_RE = re.compile(
r'createServerReference\)?\(["\']([0-9a-f]{40,44})["\']',
re.I,
)
_CALL_SERVER_RE = re.compile(
r'["\']([0-9a-f]{40,44})["\']\s*,\s*(?:callServer|findSourceMapURL)',
re.I,
)
_SCRIPT_SRC_RE = re.compile(r'src=["\']([^"\']+)["\']', re.I)
# --- CLIProxyAPI (CPA) 扁平格式常量 ------------------------------------------
# CPA 的 internal/auth/xai/token.go TokenStorage 读的是扁平字段。
# Build/CLI token(scope 含 grok-cli:access)必须走 cli-chat-proxy.grok.com,
# 不能用默认 api.x.ai/v1(那是计费通道,会 402)。
# headers 对齐 @xai-official/grok CLI / grok-build-auth(无 x-authenticateresponse)
CPA_TOKEN_ENDPOINT = f"{OIDC_ISSUER}/oauth2/token"
CPA_GROK_BASE_URL = "https://cli-chat-proxy.grok.com/v1"
CPA_GROK_HEADERS = {
"User-Agent": GROK_TOKEN_UA,
"X-XAI-Token-Auth": "xai-grok-cli",
"x-authenticateresponse": "authenticate-response",
"x-grok-client-identifier": "grok-pager",
"x-grok-client-version": GROK_VERSION,
}
CPA_PROBE_MODEL = "grok-4.5"
CPA_PROBE_URL = f"{CPA_GROK_BASE_URL}/responses"
GROK_HOME_URL = "https://grok.com/"
def _normalize_next_action_id(value: str) -> str:
val = str(value or "").strip().lower()
if _NEXT_ACTION_ID_RE.fullmatch(val):
return val
return ""
def _load_working_next_action_id() -> str:
"""优先读磁盘缓存(上次成功的 consent Next-Action),否则回落内置 bootstrap。"""
try:
cached = _normalize_next_action_id(
_NEXT_ACTION_CACHE_PATH.read_text(encoding="utf-8")
)
if cached:
return cached
except Exception:
pass
return _normalize_next_action_id(NEXT_ACTION_ID) or NEXT_ACTION_ID.lower()
def _save_working_next_action_id(action_id: str) -> None:
"""把已验证可用的 Next-Action 持久化,避免进程重启后再次扫 JS chunks。"""
val = _normalize_next_action_id(action_id)
if not val:
return
try:
atomic_write_text(_NEXT_ACTION_CACHE_PATH, val + "\n")
except Exception:
pass
def _invalidate_working_next_action_id(action_id: str = "") -> None:
"""某 ID 返回 Server action not found 时剔除,避免反复 404。"""
global _working_next_action_id
bad = _normalize_next_action_id(action_id)
current = _normalize_next_action_id(_working_next_action_id)
if bad and current and bad != current:
return
_working_next_action_id = ""
try:
if _NEXT_ACTION_CACHE_PATH.is_file():
if not bad:
_NEXT_ACTION_CACHE_PATH.unlink(missing_ok=True)
else:
cached = _normalize_next_action_id(
_NEXT_ACTION_CACHE_PATH.read_text(encoding="utf-8")
)
if not cached or cached == bad:
_NEXT_ACTION_CACHE_PATH.unlink(missing_ok=True)
except Exception:
pass
def _remember_working_next_action_id(action_id: str) -> None:
global _working_next_action_id
val = _normalize_next_action_id(action_id)
if not val:
return
_working_next_action_id = val
_save_working_next_action_id(val)
# 模块导入时加载缓存,保证 GUI/CLI 冷启动也能走快速路径
_working_next_action_id = _load_working_next_action_id()
def b64url_decode(seg: str) -> bytes:
seg += "=" * (-len(seg) % 4)
return base64.urlsafe_b64decode(seg)
def _decode_jwt_payload_with_status(token: str) -> tuple[bool, dict]:
"""Decode a JWT payload and distinguish valid empty claims from failure."""
try:
parts = str(token or "").split(".")
if len(parts) < 2:
return False, {}
payload = json.loads(b64url_decode(parts[1]))
if not isinstance(payload, dict):
return False, {}
return True, payload
except Exception:
return False, {}
def decode_jwt_payload(token: str) -> dict:
"""Return object claims, or an empty dict for malformed/non-object payloads."""
_ok, payload = _decode_jwt_payload_with_status(token)
return payload
def inspect_jwt_bfs(token: str) -> dict:
"""Detect xAI JWT risk claim ``bfs`` by key presence (not truthiness).
Clean tokens simply omit the claim. Flagged tokens typically carry
``bfs: 2`` (value may vary; presence alone is the signal).
Distinct from grok.com ``botFlagSource`` / registration policy deny.
"""
raw = str(token or "").strip()
if raw.startswith("sso="):
raw = raw[4:].strip()
# Nested JSON blob (encrypted_primary decode, or full OAuth response)
if raw.startswith("{"):
try:
obj = json.loads(raw)
except Exception:
obj = None
if isinstance(obj, dict):
for key in ("access_token", "token", "sso", "id_token", "key"):
nested = str(obj.get(key) or "").strip()
if nested.count(".") >= 2:
raw = nested
break
ok, claims = _decode_jwt_payload_with_status(raw) if raw.count(".") >= 2 else (False, {})
has = ok and ("bfs" in claims)
return {
"ok": ok,
"has_bfs": has,
"bfs": claims.get("bfs") if has else None,
"tier": claims.get("tier"),
"sub": str(claims.get("sub") or claims.get("principal_id") or "")[:48],
"exp": claims.get("exp"),
"referrer": claims.get("referrer"),
"claim_keys": sorted(str(k) for k in claims.keys()) if claims else [],
}
def inspect_token_bundle_bfs(
*,
access_token: str = "",
sso: str = "",
id_token: str = "",
refresh_token: str = "",
) -> dict:
"""Check OAuth / SSO bundle; prefer access_token, fall back to sso/id/refresh."""
sources: list[tuple[str, str]] = [
("access_token", str(access_token or "").strip()),
("sso", str(sso or "").strip()),
("id_token", str(id_token or "").strip()),
("refresh_token", str(refresh_token or "").strip()),
]
result = {
"ok": False,
"has_bfs": False,
"bfs": None,
"source": "",
"tier": None,
"sub": "",
"exp": None,
"referrer": None,
"claim_keys": [],
"checked": [],
}
for name, value in sources:
if not value or value.count(".") < 2:
continue
info = inspect_jwt_bfs(value)
result["checked"].append(name)
if not info.get("ok"):
continue
if not result["ok"]:
result.update(
{
"ok": True,
"has_bfs": bool(info.get("has_bfs")),
"bfs": info.get("bfs"),
"source": name,
"tier": info.get("tier"),
"sub": info.get("sub") or "",
"exp": info.get("exp"),
"referrer": info.get("referrer"),
"claim_keys": list(info.get("claim_keys") or []),
}
)
# Any source with bfs marks the bundle flagged (prefer reporting that source)
if info.get("has_bfs"):
result.update(
{
"ok": True,
"has_bfs": True,
"bfs": info.get("bfs"),
"source": name,
"tier": info.get("tier"),
"sub": info.get("sub") or result.get("sub") or "",
"exp": info.get("exp") or result.get("exp"),
"referrer": info.get("referrer") or result.get("referrer"),
"claim_keys": list(info.get("claim_keys") or result.get("claim_keys") or []),
}
)
break
return result
def inspect_cpa_record_bfs(record: dict | None) -> dict:
"""Inspect a CPA xai-*.json (or similar) auth record for the bfs claim."""
if not isinstance(record, dict):
return {
"ok": False,
"has_bfs": False,
"bfs": None,
"source": "",
"email": "",
"error": "invalid record",
}
# Prefer the current token over cached metadata. CPA may refresh the token
# in place while leaving custom fields untouched.
has_token = any(
str(record.get(key) or "").strip()
for key in ("access_token", "key", "sso", "id_token", "refresh_token")
)
# A record without a token can still be classified from metadata written by
# the register flow.
if not has_token and "bfs" in record and record.get("bfs") is True:
return {
"ok": True,
"has_bfs": True,
"bfs": record.get("bfs_value", record.get("bfs")),
"source": "record.bfs",
"email": str(record.get("email") or "").strip(),
"tier": record.get("tier"),
"sub": str(record.get("sub") or "")[:48],
"exp": None,
"referrer": None,
"claim_keys": [],
"checked": ["record.bfs"],
}
if not has_token and record.get("bfs") is False and record.get("bfs_checked"):
return {
"ok": True,
"has_bfs": False,
"bfs": None,
"source": "record.bfs",
"email": str(record.get("email") or "").strip(),
"tier": record.get("tier"),
"sub": str(record.get("sub") or "")[:48],
"exp": None,
"referrer": None,
"claim_keys": [],
"checked": ["record.bfs"],
}
info = inspect_token_bundle_bfs(
access_token=str(record.get("access_token") or record.get("key") or ""),
sso=str(record.get("sso") or ""),
id_token=str(record.get("id_token") or ""),
refresh_token=str(record.get("refresh_token") or ""),
)
info["email"] = str(record.get("email") or "").strip()
return info
def _flatten_nested_auth_entry(entry: dict) -> dict:
"""Normalize one nested Grok2API auth entry for the common scanner."""
return {
"access_token": entry.get("access_token") or entry.get("key") or "",
"refresh_token": entry.get("refresh_token") or "",
"id_token": entry.get("id_token") or "",
"email": entry.get("email") or "",
"sub": entry.get("user_id") or entry.get("sub") or "",
"sso": entry.get("sso") or "",
"disabled": entry.get("disabled"),
"bfs": entry.get("bfs"),
"bfs_value": entry.get("bfs_value"),
"bfs_source": entry.get("bfs_source"),
"bfs_checked": entry.get("bfs_checked"),
"bfs_status": entry.get("bfs_status"),
}
def _auth_record_candidates(data: object) -> list[tuple[str, dict]]:
"""Return direct or nested auth records from one JSON file."""
if not isinstance(data, dict):
return []
auth_fields = {
"access_token",
"key",
"sso",
"id_token",
"refresh_token",
"bfs",
"bfs_checked",
}
if auth_fields.intersection(data):
return [("", data)]
candidates: list[tuple[str, dict]] = []
for key, entry in data.items():
if not isinstance(entry, dict) or not auth_fields.intersection(entry):
continue
candidates.append((str(key), _flatten_nested_auth_entry(entry)))
return candidates
def scan_cpa_auth_dir_bfs(
auth_dir: str | Path,
*,
limit: int = 0,
include_clean: bool = True,
) -> dict:
"""Batch-scan CPA auth directory for JWT bfs flags. Pure local JWT decode."""
root = Path(auth_dir)
summary = {
"ok": True,
"auth_dir": str(root),
"total": 0,
"bfs_count": 0,
"clean_count": 0,
"error_count": 0,
"bfs_rate": 0.0,
"bfs_value_dist": {},
"items": [],
"scanned_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
}
if not root.is_dir():
summary["ok"] = False
summary["error"] = f"auth_dir not found: {root}"
return summary
# Auth directories can contain generated xai-/g2a- files or a merged
# auth.json created by the CLI. Scan JSON files by content rather than
# relying on one filename convention.
paths = sorted(root.glob("*.json"))
# de-dup by path
seen: set[str] = set()
ordered: list[Path] = []
for path in paths:
key = str(path.resolve()) if path.exists() else str(path)
if key in seen:
continue
seen.add(key)
ordered.append(path)
if limit and limit > 0:
ordered = ordered[: int(limit)]
value_dist: dict[str, int] = {}
for path in ordered:
try:
data = json.loads(path.read_text(encoding="utf-8"))
except Exception as exc:
summary["total"] += 1
item = {
"file": path.name,
"email": "",
"has_bfs": False,
"bfs": None,
"source": "",
"disabled": None,
"error": str(exc)[:120],
}
summary["error_count"] += 1
summary["items"].append(item)
continue
candidates = _auth_record_candidates(data)
if not candidates:
summary["total"] += 1
summary["error_count"] += 1
summary["items"].append(
{
"file": path.name,
"email": "",
"has_bfs": False,
"bfs": None,
"source": "",
"disabled": None,
"error": "no auth record found",
}
)
continue
for entry_key, data_record in candidates:
summary["total"] += 1
item = {
"file": f"{path.name}#{entry_key}" if entry_key else path.name,
"email": "",
"has_bfs": False,
"bfs": None,
"source": "",
"disabled": None,
"error": "",
}
info = inspect_cpa_record_bfs(data_record)
item["email"] = str(info.get("email") or data_record.get("email") or "")
item["has_bfs"] = bool(info.get("has_bfs"))
item["bfs"] = info.get("bfs")
item["source"] = str(info.get("source") or "")
item["sub"] = str(info.get("sub") or "")
item["tier"] = info.get("tier")
if "disabled" in data_record:
item["disabled"] = bool(data_record.get("disabled"))
if not info.get("ok") and not info.get("has_bfs"):
summary["error_count"] += 1
item["error"] = "jwt decode failed or empty token"
summary["items"].append(item)
continue
if item["has_bfs"]:
summary["bfs_count"] += 1
key = str(item["bfs"])
value_dist[key] = value_dist.get(key, 0) + 1
summary["items"].append(item)
else:
summary["clean_count"] += 1
if include_clean:
summary["items"].append(item)
decoded = summary["bfs_count"] + summary["clean_count"]
summary["bfs_rate"] = round(100.0 * summary["bfs_count"] / decoded, 2) if decoded else 0.0
summary["bfs_value_dist"] = value_dist
return summary
def apply_bfs_to_cpa_record(record: dict, bfs_info: dict | None = None) -> dict:
"""Annotate CPA record with bfs metadata; optionally disable flagged accounts."""
if not isinstance(record, dict):
return record
info = bfs_info or inspect_cpa_record_bfs(record)
if info.get("ok") is not True:
record["bfs"] = None
record["bfs_checked"] = False
record["bfs_status"] = "unknown"
record.pop("bfs_value", None)
record.pop("bfs_source", None)
return record
has = bool(info.get("has_bfs"))
record["bfs"] = has
record["bfs_checked"] = True
record["bfs_status"] = "flagged" if has else "clean"
if has:
record["bfs_value"] = info.get("bfs")
record["bfs_source"] = str(info.get("source") or "")
else:
record.pop("bfs_value", None)
record.pop("bfs_source", None)
return record
def rfc3339_ns(ts: float | None = None) -> str:
"""2026-07-10T01:00:00.000000000Z"""
if ts is None:
ts = time.time()
dt = datetime.fromtimestamp(ts, tz=timezone.utc)
return dt.strftime("%Y-%m-%dT%H:%M:%S") + ".000000000Z"
def _urlopen(req, proxy: str = "", timeout: int = 15):
"""urllib 请求,proxy 非空时走代理。"""
if proxy:
opener = urllib.request.build_opener(
urllib.request.ProxyHandler({"http": proxy, "https": proxy})
)
return opener.open(req, timeout=timeout)
return urllib.request.urlopen(req, timeout=timeout)
def _gen_pkce() -> tuple[str, str, str, str]:
"""生成 (code_verifier, code_challenge, state, nonce)。"""
verifier = base64.urlsafe_b64encode(os.urandom(32)).rstrip(b"=").decode()
challenge = base64.urlsafe_b64encode(
hashlib.sha256(verifier.encode()).digest()
).rstrip(b"=").decode()
state = base64.urlsafe_b64encode(os.urandom(16)).rstrip(b"=").decode()
nonce = base64.urlsafe_b64encode(os.urandom(16)).rstrip(b"=").decode()
return verifier, challenge, state, nonce
def _parse_consent_result(body: str) -> tuple[str | None, str]:
"""解析 consent 的 text/x-component 响应,返回 (code, 服务端错误)。
服务端拒绝时回 {"success":false,"error":"Access denied"}——这是账号资质裁决,
与 Next-Action 是否正确无关。必须把 error 透出来,否则会被误判成
「这个 action id 不对」而去徒劳地换 ID、扫 JS chunk。
"""
error = ""
for line in body.split("\n"):
start = line.find("{")
if start < 0:
continue
try:
data = json.loads(line[start:])
except Exception:
continue
if not isinstance(data, dict):
continue
if data.get("code") and data.get("success") is not False:
return data.get("code"), ""
if data.get("error"):
error = str(data.get("error"))
elif data.get("success") is False and not error:
error = "success=false"
return None, error
def _parse_consent_code(body: str) -> str | None:
"""从 consent 提交的 text/x-component 响应里解析出 authorization code。"""
return _parse_consent_result(body)[0]
def _extract_next_action_ids(html: str) -> list[str]:
"""仅从 HTML 文本抽哈希(弱信号;真正 id 多在 JS chunk)。"""
found: list[str] = []
seen: set[str] = set()
text = html or ""
def _add(val: str):
v = (val or "").strip().lower()
if len(v) < 40 or v in seen:
return
seen.add(v)
found.append(v)
for m in _CREATE_SERVER_REF_RE.finditer(text):
_add(m.group(1))
for m in _CALL_SERVER_RE.finditer(text):
_add(m.group(1))
for m in _NEXT_ACTION_RE.finditer(text):
_add(m.group(1))
if NEXT_ACTION_ID and NEXT_ACTION_ID.lower() not in seen:
found.append(NEXT_ACTION_ID.lower())
return found
def _discover_action_ids_from_js(session, html: str, base_url: str = "https://accounts.x.ai", log=None) -> list[str]:
"""从 consent 页引用的 /_next/static/chunks/*.js 解析 createServerReference 的 action id。
HTML 内嵌的 40 位 hex 经常是错误候选(会 404);真实 allow consent 在 JS 里。
"""
found: list[str] = []
seen: set[str] = set()
priority: list[str] = [] # consent/oauth 相关 chunk 里的 id 优先
def _add(val: str, prefer: bool = False):
v = (val or "").strip().lower()
if len(v) < 40 or v in seen:
return
seen.add(v)
if prefer:
priority.append(v)
else:
found.append(v)
srcs = _SCRIPT_SRC_RE.findall(html or "")
# 优先扫可能含 consent 逻辑的 chunk;其余也扫但限数量
scored: list[tuple[int, str]] = []
for src in srcs:
low = src.lower()
score = 0
if "chunk" not in low and "/_next/" not in low:
continue
if any(k in low for k in ("consent", "oauth", "auth", "login", "sign")):
score += 5
scored.append((score, src))
scored.sort(key=lambda x: (-x[0], x[1]))
fetched = 0
max_fetch = 40
for score, src in scored:
if fetched >= max_fetch:
break
full = src if src.startswith("http") else urllib.parse.urljoin(base_url.rstrip("/") + "/", src.lstrip("/"))
try:
resp = session.get(full, impersonate="chrome", timeout=15)
text = str(resp.text or "")
except Exception:
continue
fetched += 1
prefer = score > 0 or ("consent" in text.lower() and "oauth" in text.lower())
# 含 allow + createServerReference 的 chunk 更优先
if "createServerReference" in text or "callServer" in text:
prefer = True
for m in _CREATE_SERVER_REF_RE.finditer(text):
_add(m.group(1), prefer=prefer)
for m in _CALL_SERVER_RE.finditer(text):
_add(m.group(1), prefer=prefer)
# HTML 弱信号放后
for aid in _extract_next_action_ids(html):
_add(aid, prefer=False)
ordered = priority + [x for x in found if x not in priority]
if log:
log(f" [*] 从 JS chunks 解析 Next-Action {len(ordered)} 个(扫 {fetched} 个脚本)")
return ordered
def _new_sso_session(sso_cookie: str, proxy: str = ""):
"""创建带 SSO cookie 的 curl_cffi Session。"""
proxies = {"http": proxy, "https": proxy} if proxy else None
s = requests.Session()
if proxies:
s.proxies = proxies
for domain in (".x.ai", "accounts.x.ai", "auth.x.ai", ".grok.com", "grok.com"):
s.cookies.set("sso", sso_cookie, domain=domain)
s.cookies.set("sso-rw", sso_cookie, domain=domain)
return s
def _parse_grok_account_state(page_html: str) -> dict:
"""从 grok.com 首页 RSC 数据解析账号注册风控状态。"""
raw = str(page_html or "")
# Next.js 会把对象嵌入字符串,字段名通常表现为 \"botFlagSource\"。
# 解开这一层即可按普通 JSON 片段稳定提取,不依赖具体 chunk 或组件名。
normalized = raw.replace('\\"', '"')
source_match = re.search(r'botFlagSource"\s*:\s*(null|-?\d+)', normalized)
details_match = re.search(
r'botFlagDetails"\s*:\s*(?:null|"([^"]*)")', normalized
)
source = None
if source_match and source_match.group(1) != "null":
try:
source = int(source_match.group(1))
except (TypeError, ValueError):
source = None
details = details_match.group(1) if details_match and details_match.group(1) else ""
detail_fields: dict[str, str] = {}
for item in details.split(","):
key, sep, value = item.partition("=")
if sep and key.strip():
detail_fields[key.strip().lower()] = value.strip()
risk = None
try:
if detail_fields.get("risk"):
risk = float(detail_fields["risk"])
except (TypeError, ValueError):
risk = None
policy = detail_fields.get("policy", "").lower()
event = detail_fields.get("event", "")
denied = policy == "deny"
return {
"found": bool(source_match or details_match),
"bot_flag_source": source,
"bot_flag_details": details,
"policy": policy,
"risk": risk,
"event": event,
"denied": denied,
}
def inspect_sso_account_state(
sso_cookie: str,
proxy: str = "",
log=print,
timeout: int = 20,
) -> dict:
"""读取 grok.com 当前账号状态;诊断失败时返回 unknown,不阻断 OAuth。"""
result = _parse_grok_account_state("")
result.update({"status_code": 0, "url": "", "error": ""})
token = str(sso_cookie or "").strip()
if not token:
result["error"] = "sso 为空"
return result
try:
session = _new_sso_session(token, proxy=proxy)
response = session.get(
GROK_HOME_URL,
headers={"User-Agent": DEFAULT_UA, "Accept": "text/html,application/xhtml+xml"},
impersonate="chrome",
timeout=timeout,
allow_redirects=True,
)
result["status_code"] = int(getattr(response, "status_code", 0) or 0)
result["url"] = str(getattr(response, "url", "") or "")
if result["status_code"] != 200:
suffix = "(可能是 Cloudflare/出口限制)" if result["status_code"] in (403, 429, 503) else ""
result["error"] = f"grok.com HTTP {result['status_code']}{suffix}"
return result
parsed = _parse_grok_account_state(getattr(response, "text", "") or "")
result.update(parsed)
if parsed["denied"]:
log(
" ❌ 注册风控状态: "
f"botFlagSource={parsed['bot_flag_source']} "
f"{parsed['bot_flag_details']}"
)
elif parsed["found"]:
log(
" ✅ 注册风控状态可用: "
f"botFlagSource={parsed['bot_flag_source']}"
)
else:
result["error"] = "grok.com 未发现 botFlag 字段"
return result
except Exception as exc:
result["error"] = str(exc)
return result
def classify_sso_account_state(state: dict) -> str:
"""Map inspect_sso_account_state() into flagged / clean / error / unknown.
Aligns with the live risk gate:
- botFlagSource in (1, 2)
- policy=deny (any event, including $registration / $login)
"""
if not isinstance(state, dict):
return "unknown"
bf = state.get("bot_flag_source")
policy = str(state.get("policy") or "").strip().lower()
if state.get("denied") or bf in (1, 2) or policy == "deny":
return "flagged"
if state.get("found"):
return "clean"
try:
status = int(state.get("status_code") or 0)
except (TypeError, ValueError):
status = 0
if status != 200 or str(state.get("error") or "").strip():
return "error"
return "unknown"
def run_check_sso_state(
records: list[SsoInput],
*,
proxy: str = "",
delay: float = 0,
export: str | Path | None = None,
clean_export: str | Path | None = None,
log=print,
on_item=None,
cancel_callback=None,
) -> dict:
"""批量读取 grok.com 账号风控状态,不换 token 不入库。
export / clean_export 边检查边逐行追加写(0600),中断不丢已检查结果;
clean_export 写出 verdict=clean 的原始行(raw_line,每行一条),仅用于本机后续 --sso 输入。
"""
summary: dict = {
"ok": True,
"scanned_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"total": 0,
"flagged_count": 0,
"clean_count": 0,
"unknown_count": 0,
"error_count": 0,
"denied_count": 0,
"bot_flag_dist": {},
"items": [],
"export_path": "",
"export_count": 0,
"clean_export_path": "",
"clean_export_count": 0,
"cancelled": False,
}
dist: dict[str, int] = {}
export_path = None
clean_path = None
if export:
export_path = Path(export)
export_path.unlink(missing_ok=True)
if clean_export:
clean_path = Path(clean_export)
clean_path.unlink(missing_ok=True)
total = len(records)
for i, record in enumerate(records, 1):
if cancel_callback and cancel_callback():
summary["cancelled"] = True
break
email = str(record.email or "").strip()
def _check_log(message, _i=i):
log(f" [{_i}] {str(message).strip()}")
state = inspect_sso_account_state(record.sso, proxy=proxy, log=_check_log)
verdict = classify_sso_account_state(state)
bf = state.get("bot_flag_source")
summary["total"] += 1
dist_key = str(bf) if bf is not None else "none"
dist[dist_key] = dist.get(dist_key, 0) + 1
row = {
"index": i,
"email": email,
"bot_flag_source": bf,
"bot_flag_details": state.get("bot_flag_details") or "",
"risk": state.get("risk"),
"policy": state.get("policy") or "",
"event": state.get("event") or "",
"denied": bool(state.get("denied")),
"found": bool(state.get("found")),
"status_code": state.get("status_code"),
"verdict": verdict,
"error": state.get("error") or "",
}
summary["items"].append(row)
if verdict == "flagged":
summary["flagged_count"] += 1
if row["denied"]:
summary["denied_count"] += 1
if export_path:
append_private_text(export_path, json.dumps(row, ensure_ascii=False) + "\n")
elif verdict == "clean":
summary["clean_count"] += 1
if clean_path:
append_private_text(clean_path, record.raw_line + "\n")
elif verdict == "unknown":
summary["unknown_count"] += 1
else:
summary["error_count"] += 1
tag = "❌" if verdict == "flagged" else ("✅" if verdict == "clean" else "⚠️")
log(
f"{tag} [{i}/{total}] {email or '(no email)'} "
f"botFlagSource={bf} details={row['bot_flag_details'] or '-'} "
f"status={state.get('status_code')} -> {verdict}"
)
if on_item:
on_item(row, record, summary)
if delay and i < total:
if cancel_callback and cancel_callback():
summary["cancelled"] = True
break
time.sleep(float(delay))
summary["export_path"] = str(export_path) if export_path else ""
summary["export_count"] = summary["flagged_count"]
summary["clean_export_path"] = str(clean_path) if clean_path else ""
summary["clean_export_count"] = summary["clean_count"]
summary["bot_flag_dist"] = dist
if (
summary["total"]
and summary["flagged_count"] + summary["clean_count"] + summary["unknown_count"] == 0
):
summary["ok"] = False
return summary
def _normalize_token_payload(token: dict) -> dict | None:
if not isinstance(token, dict) or not token.get("access_token"):
return None
if not token.get("expires_in"):
token["expires_in"] = 21600
if not token.get("token_type"):
token["token_type"] = "Bearer"
return token
def _is_trusted_xai_url(raw: str) -> bool:
try:
parsed = urllib.parse.urlparse(str(raw or "").strip())
except Exception:
return False
if parsed.scheme != "https" or not parsed.hostname:
return False
host = parsed.hostname.lower()
return host == "x.ai" or host.endswith(".x.ai")
def _sso_principal_id(sso_cookie: str) -> str:
claims = decode_jwt_payload(sso_cookie)
for key in ("sub", "principal_id", "user_id", "uid", "id"):
val = str(claims.get(key) or "").strip()
if val:
return val
return ""
def _device_authorized(url: str = "", body: str = "") -> bool:
u = str(url or "").lower()
b = str(body or "").lower()
if "/oauth2/device/done" in u or u.rstrip("/").endswith("/device/done"):
return True
markers = (
"device authorized",
"you have authorized",
"device is authorized",
"authorization complete",
"设备已授权",
"已授权此设备",