HouYunFei commited on
Commit
fb7592d
·
2 Parent(s): aad0199cb1d19f

Merge branch 'fork/STA1N156/codex/complete-account-export'

Browse files
api/accounts.py CHANGED
@@ -1,7 +1,15 @@
1
  from __future__ import annotations
2
 
 
 
 
 
 
 
 
3
  from fastapi import APIRouter, Header, HTTPException
4
  from fastapi.concurrency import run_in_threadpool
 
5
  from pydantic import BaseModel, Field
6
 
7
  from services.auth_service import auth_service
@@ -36,6 +44,7 @@ class UserKeyUpdateRequest(BaseModel):
36
 
37
  class AccountCreateRequest(BaseModel):
38
  tokens: list[str] = Field(default_factory=list)
 
39
 
40
 
41
  class AccountDeleteRequest(BaseModel):
@@ -46,6 +55,11 @@ class AccountRefreshRequest(BaseModel):
46
  access_tokens: list[str] = Field(default_factory=list)
47
 
48
 
 
 
 
 
 
49
  class AccountUpdateRequest(BaseModel):
50
  access_token: str = ""
51
  type: str | None = None
@@ -91,6 +105,43 @@ class Sub2APIImportRequest(BaseModel):
91
  account_ids: list[str] = Field(default_factory=list)
92
 
93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  def create_router() -> APIRouter:
95
  router = APIRouter()
96
 
@@ -149,10 +200,21 @@ def create_router() -> APIRouter:
149
  @router.post("/api/accounts")
150
  async def create_accounts(body: AccountCreateRequest, authorization: str | None = Header(default=None)):
151
  require_admin(authorization)
152
- tokens = [str(token or "").strip() for token in body.tokens if str(token or "").strip()]
 
 
153
  if not tokens:
154
  raise HTTPException(status_code=400, detail={"error": "tokens is required"})
155
- result = account_service.add_accounts(tokens)
 
 
 
 
 
 
 
 
 
156
  refresh_result = account_service.refresh_accounts(tokens)
157
  return {
158
  **result,
@@ -179,6 +241,33 @@ def create_router() -> APIRouter:
179
  raise HTTPException(status_code=400, detail={"error": "access_tokens is required"})
180
  return account_service.refresh_accounts(access_tokens)
181
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
  @router.post("/api/accounts/update")
183
  async def update_account(body: AccountUpdateRequest, authorization: str | None = Header(default=None)):
184
  require_admin(authorization)
 
1
  from __future__ import annotations
2
 
3
+ import io
4
+ import json
5
+ import re
6
+ import zipfile
7
+ from datetime import datetime
8
+ from typing import Any, Literal
9
+
10
  from fastapi import APIRouter, Header, HTTPException
11
  from fastapi.concurrency import run_in_threadpool
12
+ from fastapi.responses import Response
13
  from pydantic import BaseModel, Field
14
 
15
  from services.auth_service import auth_service
 
44
 
45
  class AccountCreateRequest(BaseModel):
46
  tokens: list[str] = Field(default_factory=list)
47
+ accounts: list[dict[str, Any]] = Field(default_factory=list)
48
 
49
 
50
  class AccountDeleteRequest(BaseModel):
 
55
  access_tokens: list[str] = Field(default_factory=list)
56
 
57
 
58
+ class AccountExportRequest(BaseModel):
59
+ access_tokens: list[str] = Field(default_factory=list)
60
+ format: Literal["json", "zip"] = "json"
61
+
62
+
63
  class AccountUpdateRequest(BaseModel):
64
  access_token: str = ""
65
  type: str | None = None
 
105
  account_ids: list[str] = Field(default_factory=list)
106
 
107
 
108
+ def _account_payload_token(item: dict[str, Any]) -> str:
109
+ return str(item.get("access_token") or item.get("accessToken") or "").strip()
110
+
111
+
112
+ def _unique_tokens(tokens: list[str]) -> list[str]:
113
+ return list(dict.fromkeys(str(token or "").strip() for token in tokens if str(token or "").strip()))
114
+
115
+
116
+ def _download_timestamp() -> str:
117
+ return datetime.now().strftime("%Y%m%d-%H%M%S")
118
+
119
+
120
+ def _safe_export_name(value: str, fallback: str) -> str:
121
+ clean = re.sub(r"[^A-Za-z0-9._-]+", "-", value.strip()).strip("-._")
122
+ return (clean or fallback)[:80]
123
+
124
+
125
+ def _account_zip_bytes(items: list[dict[str, str]]) -> bytes:
126
+ buf = io.BytesIO()
127
+ used_names: set[str] = set()
128
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as archive:
129
+ for index, item in enumerate(items, start=1):
130
+ raw_name = item.get("email") or item.get("account_id") or f"account-{index:03d}"
131
+ base_name = _safe_export_name(raw_name, f"account-{index:03d}")
132
+ name = base_name
133
+ suffix = 2
134
+ while name in used_names:
135
+ name = f"{base_name}-{suffix}"
136
+ suffix += 1
137
+ used_names.add(name)
138
+ archive.writestr(
139
+ f"{name}.json",
140
+ json.dumps(item, ensure_ascii=False, indent=2) + "\n",
141
+ )
142
+ return buf.getvalue()
143
+
144
+
145
  def create_router() -> APIRouter:
146
  router = APIRouter()
147
 
 
200
  @router.post("/api/accounts")
201
  async def create_accounts(body: AccountCreateRequest, authorization: str | None = Header(default=None)):
202
  require_admin(authorization)
203
+ account_payloads = [item for item in body.accounts if isinstance(item, dict)]
204
+ payload_tokens = [_account_payload_token(item) for item in account_payloads]
205
+ tokens = _unique_tokens([*body.tokens, *payload_tokens])
206
  if not tokens:
207
  raise HTTPException(status_code=400, detail={"error": "tokens is required"})
208
+ if account_payloads:
209
+ result = account_service.add_account_items(account_payloads)
210
+ payload_token_set = set(_unique_tokens(payload_tokens))
211
+ extra_tokens = [token for token in tokens if token not in payload_token_set]
212
+ if extra_tokens:
213
+ extra_result = account_service.add_accounts(extra_tokens)
214
+ result["added"] = int(result.get("added") or 0) + int(extra_result.get("added") or 0)
215
+ result["skipped"] = int(result.get("skipped") or 0) + int(extra_result.get("skipped") or 0)
216
+ else:
217
+ result = account_service.add_accounts(tokens)
218
  refresh_result = account_service.refresh_accounts(tokens)
219
  return {
220
  **result,
 
241
  raise HTTPException(status_code=400, detail={"error": "access_tokens is required"})
242
  return account_service.refresh_accounts(access_tokens)
243
 
244
+ @router.post("/api/accounts/export")
245
+ async def export_accounts(body: AccountExportRequest, authorization: str | None = Header(default=None)):
246
+ require_admin(authorization)
247
+ access_tokens = _unique_tokens(body.access_tokens)
248
+ items = account_service.build_export_items(access_tokens)
249
+ if not items:
250
+ raise HTTPException(
251
+ status_code=400,
252
+ detail={"error": "没有可导出的完整账号,需要同时有 access_token、refresh_token 和 id_token"},
253
+ )
254
+
255
+ timestamp = _download_timestamp()
256
+ if body.format == "zip":
257
+ content = _account_zip_bytes(items)
258
+ return Response(
259
+ content,
260
+ media_type="application/zip",
261
+ headers={"Content-Disposition": f'attachment; filename="codex-accounts-{timestamp}.zip"'},
262
+ )
263
+
264
+ payload: dict[str, str] | list[dict[str, str]] = items[0] if len(items) == 1 else items
265
+ return Response(
266
+ json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
267
+ media_type="application/json",
268
+ headers={"Content-Disposition": f'attachment; filename="codex-accounts-{timestamp}.json"'},
269
+ )
270
+
271
  @router.post("/api/accounts/update")
272
  async def update_account(body: AccountUpdateRequest, authorization: str | None = Header(default=None)):
273
  require_admin(authorization)
services/account_service.py CHANGED
@@ -1,9 +1,11 @@
1
  from __future__ import annotations
2
 
 
 
3
  from concurrent.futures import ThreadPoolExecutor, as_completed
 
4
  from threading import Condition, Lock
5
  from typing import Any
6
- from datetime import datetime
7
 
8
  from services.config import config
9
  from services.log_service import (
@@ -14,6 +16,40 @@ from services.storage.base import StorageBackend
14
  from utils.helper import anonymize_token
15
 
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  class AccountService:
18
  """账号池服务,使用 token -> account 的 dict 保存账号。"""
19
 
@@ -222,6 +258,48 @@ class AccountService:
222
  {"added": added, "skipped": skipped})
223
  return {"added": added, "skipped": skipped, "items": items}
224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225
  def delete_accounts(self, tokens: list[str]) -> dict:
226
  target_set = set(token for token in tokens if token)
227
  if not target_set:
@@ -338,5 +416,59 @@ class AccountService:
338
  "items": self.list_accounts(),
339
  }
340
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
341
 
342
  account_service = AccountService(config.get_storage_backend())
 
1
  from __future__ import annotations
2
 
3
+ import base64
4
+ import json
5
  from concurrent.futures import ThreadPoolExecutor, as_completed
6
+ from datetime import datetime, timedelta, timezone
7
  from threading import Condition, Lock
8
  from typing import Any
 
9
 
10
  from services.config import config
11
  from services.log_service import (
 
16
  from utils.helper import anonymize_token
17
 
18
 
19
+ EXPORT_TIMEZONE = timezone(timedelta(hours=8))
20
+
21
+
22
+ def _clean_string(value: Any) -> str:
23
+ if value is None:
24
+ return ""
25
+ return str(value).strip()
26
+
27
+
28
+ def _decode_jwt_payload(token: str) -> dict[str, Any]:
29
+ parts = str(token or "").split(".")
30
+ if len(parts) < 2:
31
+ return {}
32
+ try:
33
+ payload = parts[1] + "=" * (-len(parts[1]) % 4)
34
+ decoded = base64.urlsafe_b64decode(payload.encode("utf-8"))
35
+ data = json.loads(decoded.decode("utf-8"))
36
+ except Exception:
37
+ return {}
38
+ return data if isinstance(data, dict) else {}
39
+
40
+
41
+ def _format_timestamp(value: Any) -> str:
42
+ try:
43
+ timestamp = int(value)
44
+ except (TypeError, ValueError):
45
+ return ""
46
+ return datetime.fromtimestamp(timestamp, tz=timezone.utc).astimezone(EXPORT_TIMEZONE).isoformat(timespec="seconds")
47
+
48
+
49
+ def _nested_dict(value: Any) -> dict[str, Any]:
50
+ return value if isinstance(value, dict) else {}
51
+
52
+
53
  class AccountService:
54
  """账号池服务,使用 token -> account 的 dict 保存账号。"""
55
 
 
258
  {"added": added, "skipped": skipped})
259
  return {"added": added, "skipped": skipped, "items": items}
260
 
261
+ def add_account_items(self, items: list[dict[str, Any]]) -> dict:
262
+ payloads: list[dict[str, Any]] = []
263
+ seen_tokens: set[str] = set()
264
+ for item in items:
265
+ if not isinstance(item, dict):
266
+ continue
267
+ access_token = _clean_string(item.get("access_token") or item.get("accessToken"))
268
+ if not access_token or access_token in seen_tokens:
269
+ continue
270
+
271
+ payload = dict(item)
272
+ payload["access_token"] = access_token
273
+ payload.pop("accessToken", None)
274
+ if _clean_string(payload.get("type")).lower() == "codex":
275
+ payload.setdefault("export_type", "codex")
276
+ payload.pop("type", None)
277
+ payloads.append(payload)
278
+ seen_tokens.add(access_token)
279
+
280
+ if not payloads:
281
+ return {"added": 0, "skipped": 0, "items": self.list_accounts()}
282
+
283
+ with self._lock:
284
+ added = 0
285
+ skipped = 0
286
+ for payload in payloads:
287
+ access_token = payload["access_token"]
288
+ current = self._accounts.get(access_token)
289
+ if current is None:
290
+ added += 1
291
+ current = {}
292
+ else:
293
+ skipped += 1
294
+ account = self._normalize_account({**current, **payload})
295
+ if account is not None:
296
+ self._accounts[access_token] = account
297
+ self._save_accounts()
298
+ items = [dict(item) for item in self._accounts.values()]
299
+ log_service.add(LOG_TYPE_ACCOUNT, f"新增 {added} 个账号,跳过 {skipped} 个",
300
+ {"added": added, "skipped": skipped})
301
+ return {"added": added, "skipped": skipped, "items": items}
302
+
303
  def delete_accounts(self, tokens: list[str]) -> dict:
304
  target_set = set(token for token in tokens if token)
305
  if not target_set:
 
416
  "items": self.list_accounts(),
417
  }
418
 
419
+ def build_export_items(self, access_tokens: list[str] | None = None) -> list[dict[str, str]]:
420
+ requested_tokens = [token for token in dict.fromkeys(access_tokens or []) if token]
421
+ with self._lock:
422
+ if requested_tokens:
423
+ accounts = [dict(self._accounts[token]) for token in requested_tokens if token in self._accounts]
424
+ else:
425
+ accounts = [dict(item) for item in self._accounts.values()]
426
+
427
+ export_items: list[dict[str, str]] = []
428
+ for account in accounts:
429
+ access_token = _clean_string(account.get("access_token"))
430
+ id_token = _clean_string(account.get("id_token"))
431
+ refresh_token = _clean_string(account.get("refresh_token"))
432
+ if not access_token or not refresh_token or not id_token:
433
+ continue
434
+
435
+ access_claims = _decode_jwt_payload(access_token)
436
+ id_claims = _decode_jwt_payload(id_token)
437
+ access_auth = _nested_dict(access_claims.get("https://api.openai.com/auth"))
438
+ id_auth = _nested_dict(id_claims.get("https://api.openai.com/auth"))
439
+ profile = _nested_dict(access_claims.get("https://api.openai.com/profile"))
440
+
441
+ email = (
442
+ _clean_string(account.get("email"))
443
+ or _clean_string(profile.get("email"))
444
+ or _clean_string(id_claims.get("email"))
445
+ )
446
+ account_id = (
447
+ _clean_string(account.get("account_id"))
448
+ or _clean_string(access_auth.get("chatgpt_account_id"))
449
+ or _clean_string(id_auth.get("chatgpt_account_id"))
450
+ )
451
+ expired = _clean_string(account.get("expired")) or _format_timestamp(access_claims.get("exp"))
452
+ last_refresh = (
453
+ _clean_string(account.get("last_refresh"))
454
+ or _format_timestamp(access_claims.get("iat"))
455
+ or _format_timestamp(access_claims.get("nbf"))
456
+ )
457
+
458
+ export_items.append(
459
+ {
460
+ "type": _clean_string(account.get("export_type")) or "codex",
461
+ "email": email,
462
+ "expired": expired,
463
+ "id_token": id_token,
464
+ "account_id": account_id,
465
+ "access_token": access_token,
466
+ "last_refresh": last_refresh,
467
+ "refresh_token": refresh_token,
468
+ }
469
+ )
470
+
471
+ return export_items
472
+
473
 
474
  account_service = AccountService(config.get_storage_backend())
services/register/openai_register.py CHANGED
@@ -722,7 +722,7 @@ def worker(index: int) -> dict:
722
  result = registrar.register(index)
723
  cost = time.time() - start
724
  access_token = str(result["access_token"])
725
- account_service.add_accounts([access_token])
726
  account_service.refresh_accounts([access_token])
727
  with stats_lock:
728
  stats["done"] += 1
 
722
  result = registrar.register(index)
723
  cost = time.time() - start
724
  access_token = str(result["access_token"])
725
+ account_service.add_account_items([result])
726
  account_service.refresh_accounts([access_token])
727
  with stats_lock:
728
  stats["done"] += 1
test/test_account_export.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import json
3
+ import unittest
4
+ from typing import Any
5
+
6
+ from services.account_service import AccountService
7
+
8
+
9
+ class MemoryStorage:
10
+ def __init__(self, accounts: list[dict[str, Any]] | None = None) -> None:
11
+ self.accounts = list(accounts or [])
12
+
13
+ def load_accounts(self) -> list[dict[str, Any]]:
14
+ return list(self.accounts)
15
+
16
+ def save_accounts(self, accounts: list[dict[str, Any]]) -> None:
17
+ self.accounts = list(accounts)
18
+
19
+ def load_auth_keys(self) -> list[dict[str, Any]]:
20
+ return []
21
+
22
+ def save_auth_keys(self, auth_keys: list[dict[str, Any]]) -> None:
23
+ pass
24
+
25
+ def health_check(self) -> dict[str, Any]:
26
+ return {"ok": True}
27
+
28
+ def get_backend_info(self) -> dict[str, Any]:
29
+ return {"type": "memory"}
30
+
31
+
32
+ def make_jwt(payload: dict[str, Any]) -> str:
33
+ def encode(value: dict[str, Any]) -> str:
34
+ raw = json.dumps(value, separators=(",", ":")).encode("utf-8")
35
+ return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
36
+
37
+ return f'{encode({"alg": "none", "typ": "JWT"})}.{encode(payload)}.sig'
38
+
39
+
40
+ class AccountExportTests(unittest.TestCase):
41
+ def test_build_export_items_uses_codex_shape_and_jwt_claims(self) -> None:
42
+ access_token = make_jwt(
43
+ {
44
+ "exp": 0,
45
+ "iat": 3600,
46
+ "https://api.openai.com/auth": {"chatgpt_account_id": "acct_123"},
47
+ "https://api.openai.com/profile": {"email": "test@example.com"},
48
+ }
49
+ )
50
+ id_token = make_jwt({"email": "fallback@example.com"})
51
+ service = AccountService(
52
+ MemoryStorage(
53
+ [
54
+ {
55
+ "access_token": access_token,
56
+ "id_token": id_token,
57
+ "refresh_token": "rt_test",
58
+ }
59
+ ]
60
+ )
61
+ )
62
+
63
+ [item] = service.build_export_items([access_token])
64
+
65
+ self.assertEqual(item["type"], "codex")
66
+ self.assertEqual(item["email"], "test@example.com")
67
+ self.assertEqual(item["expired"], "1970-01-01T08:00:00+08:00")
68
+ self.assertEqual(item["account_id"], "acct_123")
69
+ self.assertEqual(item["access_token"], access_token)
70
+ self.assertEqual(item["last_refresh"], "1970-01-01T09:00:00+08:00")
71
+ self.assertEqual(item["id_token"], id_token)
72
+ self.assertEqual(item["refresh_token"], "rt_test")
73
+
74
+ def test_build_export_items_skips_accounts_missing_complete_tokens(self) -> None:
75
+ complete_access_token = make_jwt({"exp": 0})
76
+ complete_id_token = make_jwt({"email": "complete@example.com"})
77
+ service = AccountService(
78
+ MemoryStorage(
79
+ [
80
+ {"access_token": "only_access"},
81
+ {"access_token": "missing_id", "refresh_token": "rt_missing_id"},
82
+ {"access_token": complete_access_token, "id_token": complete_id_token, "refresh_token": "rt_complete"},
83
+ ]
84
+ )
85
+ )
86
+
87
+ items = service.build_export_items()
88
+
89
+ self.assertEqual(len(items), 1)
90
+ self.assertEqual(items[0]["access_token"], complete_access_token)
91
+ self.assertEqual(items[0]["id_token"], complete_id_token)
92
+ self.assertEqual(items[0]["refresh_token"], "rt_complete")
93
+
94
+ def test_add_account_items_preserves_export_fields_without_overwriting_plan_type(self) -> None:
95
+ service = AccountService(MemoryStorage())
96
+
97
+ result = service.add_account_items(
98
+ [
99
+ {
100
+ "type": "codex",
101
+ "access_token": "access_token_test",
102
+ "refresh_token": "rt_test",
103
+ "account_id": "acct_123",
104
+ }
105
+ ]
106
+ )
107
+
108
+ account = service.get_account("access_token_test")
109
+ self.assertEqual(result["added"], 1)
110
+ self.assertIsNotNone(account)
111
+ self.assertEqual(account["type"], "free")
112
+ self.assertEqual(account["export_type"], "codex")
113
+ self.assertEqual(account["refresh_token"], "rt_test")
114
+ self.assertEqual(account["account_id"], "acct_123")
115
+
116
+
117
+ if __name__ == "__main__":
118
+ unittest.main()
web/src/app/accounts/components/account-import-dialog.tsx CHANGED
@@ -26,7 +26,7 @@ import {
26
  DialogTitle,
27
  } from "@/components/ui/dialog";
28
  import { Textarea } from "@/components/ui/textarea";
29
- import { createAccounts, type Account } from "@/lib/api";
30
  import { cn } from "@/lib/utils";
31
 
32
  type ImportMethod = "menu" | "token" | "session" | "cpa";
@@ -38,6 +38,7 @@ type AccountImportDialogProps = {
38
 
39
  type PendingCpaImport = {
40
  tokens: string[];
 
41
  parsedFileCount: number;
42
  errorCount: number;
43
  };
@@ -56,9 +57,27 @@ function getSessionAccessToken(value: unknown) {
56
  return typeof token === "string" ? token.trim() : "";
57
  }
58
 
59
- function getCpaAccessToken(value: unknown) {
60
- const token = (value as { access_token?: unknown })?.access_token;
61
- return typeof token === "string" ? token.trim() : "";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  }
63
 
64
  function readFileAsText(file: File) {
@@ -130,7 +149,7 @@ export function AccountImportDialog({ disabled, onImported }: AccountImportDialo
130
  }
131
  };
132
 
133
- const submitTokens = async (tokens: string[], successText?: string) => {
134
  const normalizedTokens = tokens.map((item) => item.trim()).filter(Boolean);
135
 
136
  if (normalizedTokens.length === 0) {
@@ -140,7 +159,7 @@ export function AccountImportDialog({ disabled, onImported }: AccountImportDialo
140
 
141
  setIsSubmitting(true);
142
  try {
143
- const data = await createAccounts(normalizedTokens);
144
  onImported(data.items);
145
  setOpen(false);
146
  resetState();
@@ -230,15 +249,16 @@ export function AccountImportDialog({ disabled, onImported }: AccountImportDialo
230
  files.map(async (file) => {
231
  const raw = await readFileAsText(file);
232
  const parsed = JSON.parse(raw) as unknown;
233
- const token = getCpaAccessToken(parsed);
234
  return {
235
- token,
236
  };
237
  }),
238
  );
239
 
240
- const tokens = results.map((item) => item.token).filter((item): item is string => Boolean(item));
241
- const parsedFileCount = tokens.length;
 
242
  const errorCount = results.length - parsedFileCount;
243
 
244
  if (parsedFileCount === 0) {
@@ -248,6 +268,7 @@ export function AccountImportDialog({ disabled, onImported }: AccountImportDialo
248
 
249
  setPendingCpaImport({
250
  tokens,
 
251
  parsedFileCount,
252
  errorCount,
253
  });
@@ -553,7 +574,13 @@ export function AccountImportDialog({ disabled, onImported }: AccountImportDialo
553
  </Button>
554
  <Button
555
  className="h-10 rounded-xl bg-stone-950 px-5 text-white hover:bg-stone-800"
556
- onClick={() => void submitTokens(pendingCpaImport?.tokens ?? [], "CPA JSON 导入完成")}
 
 
 
 
 
 
557
  disabled={isSubmitting || !pendingCpaImport}
558
  >
559
  {isSubmitting ? <LoaderCircle className="size-4 animate-spin" /> : null}
 
26
  DialogTitle,
27
  } from "@/components/ui/dialog";
28
  import { Textarea } from "@/components/ui/textarea";
29
+ import { createAccounts, type Account, type AccountImportPayload } from "@/lib/api";
30
  import { cn } from "@/lib/utils";
31
 
32
  type ImportMethod = "menu" | "token" | "session" | "cpa";
 
38
 
39
  type PendingCpaImport = {
40
  tokens: string[];
41
+ accounts: AccountImportPayload[];
42
  parsedFileCount: number;
43
  errorCount: number;
44
  };
 
57
  return typeof token === "string" ? token.trim() : "";
58
  }
59
 
60
+ function getCpaAccount(value: unknown): AccountImportPayload | null {
61
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
62
+ return null;
63
+ }
64
+ const raw = value as Record<string, unknown>;
65
+ const tokenValue = raw.access_token ?? raw.accessToken;
66
+ const token = typeof tokenValue === "string" ? tokenValue.trim() : "";
67
+ if (!token) {
68
+ return null;
69
+ }
70
+
71
+ const payload: AccountImportPayload = {
72
+ ...raw,
73
+ access_token: token,
74
+ };
75
+ delete payload.accessToken;
76
+ if (payload.type === "codex") {
77
+ payload.export_type = "codex";
78
+ delete payload.type;
79
+ }
80
+ return payload;
81
  }
82
 
83
  function readFileAsText(file: File) {
 
149
  }
150
  };
151
 
152
+ const submitTokens = async (tokens: string[], successText?: string, accountPayloads: AccountImportPayload[] = []) => {
153
  const normalizedTokens = tokens.map((item) => item.trim()).filter(Boolean);
154
 
155
  if (normalizedTokens.length === 0) {
 
159
 
160
  setIsSubmitting(true);
161
  try {
162
+ const data = await createAccounts(normalizedTokens, accountPayloads);
163
  onImported(data.items);
164
  setOpen(false);
165
  resetState();
 
249
  files.map(async (file) => {
250
  const raw = await readFileAsText(file);
251
  const parsed = JSON.parse(raw) as unknown;
252
+ const account = getCpaAccount(parsed);
253
  return {
254
+ account,
255
  };
256
  }),
257
  );
258
 
259
+ const accounts = results.map((item) => item.account).filter((item): item is AccountImportPayload => Boolean(item));
260
+ const tokens = accounts.map((item) => item.access_token);
261
+ const parsedFileCount = accounts.length;
262
  const errorCount = results.length - parsedFileCount;
263
 
264
  if (parsedFileCount === 0) {
 
268
 
269
  setPendingCpaImport({
270
  tokens,
271
+ accounts,
272
  parsedFileCount,
273
  errorCount,
274
  });
 
574
  </Button>
575
  <Button
576
  className="h-10 rounded-xl bg-stone-950 px-5 text-white hover:bg-stone-800"
577
+ onClick={() =>
578
+ void submitTokens(
579
+ pendingCpaImport?.tokens ?? [],
580
+ "CPA JSON 导入完成",
581
+ pendingCpaImport?.accounts ?? [],
582
+ )
583
+ }
584
  disabled={isSubmitting || !pendingCpaImport}
585
  >
586
  {isSubmitting ? <LoaderCircle className="size-4 animate-spin" /> : null}
web/src/app/accounts/page.tsx CHANGED
@@ -42,10 +42,12 @@ import {
42
  } from "@/components/ui/select";
43
  import {
44
  deleteAccounts,
 
45
  fetchAccounts,
46
  refreshAccounts,
47
  updateAccount,
48
  type Account,
 
49
  type AccountStatus,
50
  } from "@/lib/api";
51
  import { useAuthGuard } from "@/lib/use-auth-guard";
@@ -149,13 +151,11 @@ function maskToken(token?: string) {
149
  return `${token.slice(0, 16)}...${token.slice(-8)}`;
150
  }
151
 
152
- function downloadTokens(accounts: Account[]) {
153
- const content = `${accounts.map((account) => account.access_token).join("\n")}\n`;
154
- const blob = new Blob([content], { type: "text/plain;charset=utf-8" });
155
  const url = URL.createObjectURL(blob);
156
  const link = document.createElement("a");
157
  link.href = url;
158
- link.download = `accounts-${Date.now()}.txt`;
159
  link.click();
160
  URL.revokeObjectURL(url);
161
  }
@@ -179,6 +179,7 @@ function AccountsPageContent() {
179
  const [isRefreshing, setIsRefreshing] = useState(false);
180
  const [isDeleting, setIsDeleting] = useState(false);
181
  const [isUpdating, setIsUpdating] = useState(false);
 
182
 
183
  const loadAccounts = async (silent = false) => {
184
  if (!silent) {
@@ -340,6 +341,25 @@ function AccountsPageContent() {
340
  }
341
  };
342
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
343
  const toggleSelectAll = (checked: boolean) => {
344
  if (checked) {
345
  setSelectedIds((prev) => Array.from(new Set([...prev, ...currentRows.map((item) => item.access_token)])));
@@ -388,11 +408,20 @@ function AccountsPageContent() {
388
  <Button
389
  variant="outline"
390
  className="h-10 rounded-xl border-stone-200 bg-white/80 px-4 text-stone-700 hover:bg-white"
391
- onClick={() => downloadTokens(accounts)}
392
- disabled={accounts.length === 0}
 
 
 
 
 
 
 
 
 
393
  >
394
- <Download className="size-4" />
395
- 导出全部 Token
396
  </Button>
397
  </div>
398
  </section>
@@ -580,6 +609,24 @@ function AccountsPageContent() {
580
  {isDeleting ? <LoaderCircle className="size-4 animate-spin" /> : <Trash2 className="size-4" />}
581
  删除所选
582
  </Button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
583
  {selectedIds.length > 0 ? (
584
  <span className="rounded-lg bg-stone-100 px-2.5 py-1 text-xs font-medium text-stone-600">
585
  已选择 {selectedIds.length} 项
 
42
  } from "@/components/ui/select";
43
  import {
44
  deleteAccounts,
45
+ exportAccounts,
46
  fetchAccounts,
47
  refreshAccounts,
48
  updateAccount,
49
  type Account,
50
+ type AccountExportFormat,
51
  type AccountStatus,
52
  } from "@/lib/api";
53
  import { useAuthGuard } from "@/lib/use-auth-guard";
 
151
  return `${token.slice(0, 16)}...${token.slice(-8)}`;
152
  }
153
 
154
+ function downloadBlob(blob: Blob, filename: string) {
 
 
155
  const url = URL.createObjectURL(blob);
156
  const link = document.createElement("a");
157
  link.href = url;
158
+ link.download = filename;
159
  link.click();
160
  URL.revokeObjectURL(url);
161
  }
 
179
  const [isRefreshing, setIsRefreshing] = useState(false);
180
  const [isDeleting, setIsDeleting] = useState(false);
181
  const [isUpdating, setIsUpdating] = useState(false);
182
+ const [isExporting, setIsExporting] = useState(false);
183
 
184
  const loadAccounts = async (silent = false) => {
185
  if (!silent) {
 
341
  }
342
  };
343
 
344
+ const handleExportAccounts = async (format: AccountExportFormat, tokens: string[]) => {
345
+ if (tokens.length === 0) {
346
+ toast.error("没有可导出的账户");
347
+ return;
348
+ }
349
+
350
+ setIsExporting(true);
351
+ try {
352
+ const data = await exportAccounts(format, tokens);
353
+ downloadBlob(data.blob, data.filename);
354
+ toast.success(format === "zip" ? "ZIP 压缩包已导出" : "JSON 文件已导出");
355
+ } catch (error) {
356
+ const message = error instanceof Error ? error.message : "导出账户失败";
357
+ toast.error(message);
358
+ } finally {
359
+ setIsExporting(false);
360
+ }
361
+ };
362
+
363
  const toggleSelectAll = (checked: boolean) => {
364
  if (checked) {
365
  setSelectedIds((prev) => Array.from(new Set([...prev, ...currentRows.map((item) => item.access_token)])));
 
408
  <Button
409
  variant="outline"
410
  className="h-10 rounded-xl border-stone-200 bg-white/80 px-4 text-stone-700 hover:bg-white"
411
+ onClick={() => void handleExportAccounts("json", accounts.map((item) => item.access_token))}
412
+ disabled={accounts.length === 0 || isExporting}
413
+ >
414
+ {isExporting ? <LoaderCircle className="size-4 animate-spin" /> : <Download className="size-4" />}
415
+ 导出全部 JSON
416
+ </Button>
417
+ <Button
418
+ variant="outline"
419
+ className="h-10 rounded-xl border-stone-200 bg-white/80 px-4 text-stone-700 hover:bg-white"
420
+ onClick={() => void handleExportAccounts("zip", accounts.map((item) => item.access_token))}
421
+ disabled={accounts.length === 0 || isExporting}
422
  >
423
+ {isExporting ? <LoaderCircle className="size-4 animate-spin" /> : <Download className="size-4" />}
424
+ 导出全部 ZIP
425
  </Button>
426
  </div>
427
  </section>
 
609
  {isDeleting ? <LoaderCircle className="size-4 animate-spin" /> : <Trash2 className="size-4" />}
610
  删除所选
611
  </Button>
612
+ <Button
613
+ variant="ghost"
614
+ className="h-8 rounded-lg px-3 text-stone-500 hover:bg-stone-100"
615
+ onClick={() => void handleExportAccounts("json", selectedTokens)}
616
+ disabled={selectedTokens.length === 0 || isExporting}
617
+ >
618
+ {isExporting ? <LoaderCircle className="size-4 animate-spin" /> : <Download className="size-4" />}
619
+ 导出所选 JSON
620
+ </Button>
621
+ <Button
622
+ variant="ghost"
623
+ className="h-8 rounded-lg px-3 text-stone-500 hover:bg-stone-100"
624
+ onClick={() => void handleExportAccounts("zip", selectedTokens)}
625
+ disabled={selectedTokens.length === 0 || isExporting}
626
+ >
627
+ {isExporting ? <LoaderCircle className="size-4 animate-spin" /> : <Download className="size-4" />}
628
+ 导出所选 ZIP
629
+ </Button>
630
  {selectedIds.length > 0 ? (
631
  <span className="rounded-lg bg-stone-100 px-2.5 py-1 text-xs font-medium text-stone-600">
632
  已选择 {selectedIds.length} 项
web/src/lib/api.ts CHANGED
@@ -8,10 +8,16 @@ export type AuthRole = "admin" | "user";
8
  export type Account = {
9
  access_token: string;
10
  type: AccountType;
 
11
  status: AccountStatus;
12
  quota: number;
13
  image_quota_unknown?: boolean;
14
  email?: string | null;
 
 
 
 
 
15
  user_id?: string | null;
16
  limits_progress?: Array<{
17
  feature_name?: string;
@@ -49,6 +55,22 @@ type AccountUpdateResponse = {
49
  items: Account[];
50
  };
51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  export type SettingsConfig = {
53
  proxy: string;
54
  base_url?: string;
@@ -270,10 +292,13 @@ export async function fetchAccounts() {
270
  return httpRequest<AccountListResponse>("/api/accounts");
271
  }
272
 
273
- export async function createAccounts(tokens: string[]) {
274
  return httpRequest<AccountMutationResponse>("/api/accounts", {
275
  method: "POST",
276
- body: { tokens },
 
 
 
277
  });
278
  }
279
 
@@ -291,6 +316,32 @@ export async function refreshAccounts(accessTokens: string[]) {
291
  });
292
  }
293
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
294
  export async function updateAccount(
295
  accessToken: string,
296
  updates: {
 
8
  export type Account = {
9
  access_token: string;
10
  type: AccountType;
11
+ export_type?: string | null;
12
  status: AccountStatus;
13
  quota: number;
14
  image_quota_unknown?: boolean;
15
  email?: string | null;
16
+ expired?: string | null;
17
+ id_token?: string | null;
18
+ account_id?: string | null;
19
+ last_refresh?: string | null;
20
+ refresh_token?: string | null;
21
  user_id?: string | null;
22
  limits_progress?: Array<{
23
  feature_name?: string;
 
55
  items: Account[];
56
  };
57
 
58
+ export type AccountImportPayload = {
59
+ access_token: string;
60
+ accessToken?: string;
61
+ type?: string;
62
+ export_type?: string;
63
+ email?: string;
64
+ expired?: string;
65
+ id_token?: string;
66
+ account_id?: string;
67
+ last_refresh?: string;
68
+ refresh_token?: string;
69
+ [key: string]: unknown;
70
+ };
71
+
72
+ export type AccountExportFormat = "json" | "zip";
73
+
74
  export type SettingsConfig = {
75
  proxy: string;
76
  base_url?: string;
 
292
  return httpRequest<AccountListResponse>("/api/accounts");
293
  }
294
 
295
+ export async function createAccounts(tokens: string[], accounts: AccountImportPayload[] = []) {
296
  return httpRequest<AccountMutationResponse>("/api/accounts", {
297
  method: "POST",
298
+ body: {
299
+ tokens,
300
+ ...(accounts.length > 0 ? { accounts } : {}),
301
+ },
302
  });
303
  }
304
 
 
316
  });
317
  }
318
 
319
+ function getFilenameFromDisposition(value: unknown, fallback: string) {
320
+ const disposition = typeof value === "string" ? value : "";
321
+ const utf8Match = disposition.match(/filename\*=UTF-8''([^;]+)/i);
322
+ if (utf8Match?.[1]) {
323
+ return decodeURIComponent(utf8Match[1].replace(/"/g, ""));
324
+ }
325
+ const match = disposition.match(/filename="?([^";]+)"?/i);
326
+ return match?.[1] || fallback;
327
+ }
328
+
329
+ export async function exportAccounts(format: AccountExportFormat, accessTokens: string[] = []) {
330
+ const response = await request.request<Blob>({
331
+ url: "/api/accounts/export",
332
+ method: "POST",
333
+ data: {
334
+ format,
335
+ access_tokens: accessTokens,
336
+ },
337
+ responseType: "blob",
338
+ });
339
+ return {
340
+ blob: response.data,
341
+ filename: getFilenameFromDisposition(response.headers["content-disposition"], `codex-accounts.${format}`),
342
+ };
343
+ }
344
+
345
  export async function updateAccount(
346
  accessToken: string,
347
  updates: {