dsh-plugin-image-workbench 1.1.5 → 1.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/LICENSE +21 -21
  2. package/README.en.md +5 -3
  3. package/README.md +7 -3
  4. package/client.js +241 -241
  5. package/cordis.patch.yml +14 -14
  6. package/host.js +51 -0
  7. package/install.mjs +333 -387
  8. package/package.json +3 -2
  9. package/scripts/fetch-style-images.mjs +104 -0
  10. package/scripts/vendor-snapshot.py +154 -154
  11. package/server/access.py +26 -26
  12. package/server/app.py +1329 -1329
  13. package/server/catalog.py +147 -147
  14. package/server/composer.py +391 -391
  15. package/server/drafts.py +158 -158
  16. package/server/history.py +575 -575
  17. package/server/imaging.py +172 -172
  18. package/server/pool.py +1335 -1335
  19. package/server/pool_admin.py +921 -921
  20. package/server/pool_service.py +1073 -1073
  21. package/server/requirements.txt +6 -6
  22. package/server/smoke_check.py +402 -402
  23. package/server/static/access.html +202 -202
  24. package/vendor/chatgpt2api/source/.env.example +82 -82
  25. package/vendor/chatgpt2api/source/.python-version +1 -1
  26. package/vendor/chatgpt2api/source/LICENSE +21 -21
  27. package/vendor/chatgpt2api/source/README.md +391 -391
  28. package/vendor/chatgpt2api/source/VERSION +1 -1
  29. package/vendor/chatgpt2api/source/api/__init__.py +2 -2
  30. package/vendor/chatgpt2api/source/api/accounts.py +537 -537
  31. package/vendor/chatgpt2api/source/api/ai.py +217 -217
  32. package/vendor/chatgpt2api/source/api/app.py +62 -62
  33. package/vendor/chatgpt2api/source/api/errors.py +46 -46
  34. package/vendor/chatgpt2api/source/api/image_inputs.py +309 -309
  35. package/vendor/chatgpt2api/source/api/image_tasks.py +120 -120
  36. package/vendor/chatgpt2api/source/api/support.py +134 -134
  37. package/vendor/chatgpt2api/source/api/system.py +365 -365
  38. package/vendor/chatgpt2api/source/assets/kunrouai.svg +50 -50
  39. package/vendor/chatgpt2api/source/config.default.json +108 -108
  40. package/vendor/chatgpt2api/source/main.py +9 -9
  41. package/vendor/chatgpt2api/source/pyproject.toml +27 -27
  42. package/vendor/chatgpt2api/source/scripts/init_proxy_config.py +186 -186
  43. package/vendor/chatgpt2api/source/scripts/migrate_storage.py +163 -163
  44. package/vendor/chatgpt2api/source/scripts/privoxy-warp.conf +13 -13
  45. package/vendor/chatgpt2api/source/scripts/test_outlook_token_mailbox.py +385 -385
  46. package/vendor/chatgpt2api/source/scripts/test_storage.py +129 -129
  47. package/vendor/chatgpt2api/source/scripts/verify_oauth_refresh.py +92 -92
  48. package/vendor/chatgpt2api/source/services/account_service.py +1757 -1757
  49. package/vendor/chatgpt2api/source/services/auth_service.py +253 -253
  50. package/vendor/chatgpt2api/source/services/backup_service.py +671 -671
  51. package/vendor/chatgpt2api/source/services/config.py +667 -667
  52. package/vendor/chatgpt2api/source/services/content_filter.py +242 -242
  53. package/vendor/chatgpt2api/source/services/cpa_service.py +315 -315
  54. package/vendor/chatgpt2api/source/services/editable_file_task_service.py +260 -260
  55. package/vendor/chatgpt2api/source/services/image_service.py +376 -376
  56. package/vendor/chatgpt2api/source/services/image_storage_service.py +405 -405
  57. package/vendor/chatgpt2api/source/services/image_tags_service.py +76 -76
  58. package/vendor/chatgpt2api/source/services/image_task_service.py +550 -550
  59. package/vendor/chatgpt2api/source/services/log_service.py +337 -337
  60. package/vendor/chatgpt2api/source/services/model_service.py +182 -182
  61. package/vendor/chatgpt2api/source/services/oauth_login_service.py +267 -267
  62. package/vendor/chatgpt2api/source/services/openai_backend_api.py +2763 -2763
  63. package/vendor/chatgpt2api/source/services/openai_oauth.py +32 -32
  64. package/vendor/chatgpt2api/source/services/protocol/__init__.py +2 -2
  65. package/vendor/chatgpt2api/source/services/protocol/anthropic_v1_messages.py +307 -307
  66. package/vendor/chatgpt2api/source/services/protocol/chat_completion_cache.py +238 -238
  67. package/vendor/chatgpt2api/source/services/protocol/conversation.py +1644 -1644
  68. package/vendor/chatgpt2api/source/services/protocol/error_response.py +124 -124
  69. package/vendor/chatgpt2api/source/services/protocol/openai_search.py +19 -19
  70. package/vendor/chatgpt2api/source/services/protocol/openai_v1_chat_complete.py +316 -316
  71. package/vendor/chatgpt2api/source/services/protocol/openai_v1_image_edit.py +86 -86
  72. package/vendor/chatgpt2api/source/services/protocol/openai_v1_image_generations.py +42 -42
  73. package/vendor/chatgpt2api/source/services/protocol/openai_v1_models.py +53 -53
  74. package/vendor/chatgpt2api/source/services/protocol/openai_v1_response.py +453 -453
  75. package/vendor/chatgpt2api/source/services/protocol/web_search_tool.py +160 -160
  76. package/vendor/chatgpt2api/source/services/proxy_service.py +648 -648
  77. package/vendor/chatgpt2api/source/services/storage/__init__.py +5 -5
  78. package/vendor/chatgpt2api/source/services/storage/base.py +38 -38
  79. package/vendor/chatgpt2api/source/services/storage/database_storage.py +194 -194
  80. package/vendor/chatgpt2api/source/services/storage/factory.py +104 -104
  81. package/vendor/chatgpt2api/source/services/storage/git_storage.py +183 -183
  82. package/vendor/chatgpt2api/source/services/storage/json_storage.py +95 -95
  83. package/vendor/chatgpt2api/source/services/sub2api_service.py +531 -531
  84. package/vendor/chatgpt2api/source/utils/helper.py +469 -469
  85. package/vendor/chatgpt2api/source/utils/image_tokens.py +346 -346
  86. package/vendor/chatgpt2api/source/utils/log.py +110 -110
  87. package/vendor/chatgpt2api/source/utils/pkce.py +19 -19
  88. package/vendor/chatgpt2api/source/utils/pow.py +207 -207
  89. package/vendor/chatgpt2api/source/utils/sentinel.py +159 -159
  90. package/vendor/chatgpt2api/source/utils/turnstile.py +184 -184
  91. package/vendor/chatgpt2api/source/uv.lock +904 -904
  92. package/vendor/chatgpt2api/source/web/bun.lock +1501 -1501
  93. package/vendor/chatgpt2api/source/web/components.json +24 -24
  94. package/vendor/chatgpt2api/source/web/eslint.config.mjs +17 -17
  95. package/vendor/chatgpt2api/source/web/next.config.ts +40 -40
  96. package/vendor/chatgpt2api/source/web/package.json +58 -58
  97. package/vendor/chatgpt2api/source/web/postcss.config.mjs +5 -5
  98. package/vendor/chatgpt2api/source/web/src/app/accounts/components/account-import-dialog.tsx +925 -925
  99. package/vendor/chatgpt2api/source/web/src/app/accounts/page.tsx +1307 -1307
  100. package/vendor/chatgpt2api/source/web/src/app/debug/components/chat-panel.tsx +224 -224
  101. package/vendor/chatgpt2api/source/web/src/app/debug/components/editable-file-panel.tsx +444 -444
  102. package/vendor/chatgpt2api/source/web/src/app/debug/components/ppt-panel.tsx +9 -9
  103. package/vendor/chatgpt2api/source/web/src/app/debug/components/psd-panel.tsx +9 -9
  104. package/vendor/chatgpt2api/source/web/src/app/debug/components/search-panel.tsx +172 -172
  105. package/vendor/chatgpt2api/source/web/src/app/debug/components/skill-panel.tsx +169 -169
  106. package/vendor/chatgpt2api/source/web/src/app/debug/components/types.ts +39 -39
  107. package/vendor/chatgpt2api/source/web/src/app/debug/page.tsx +59 -59
  108. package/vendor/chatgpt2api/source/web/src/app/globals.css +230 -230
  109. package/vendor/chatgpt2api/source/web/src/app/image/components/image-composer.tsx +542 -542
  110. package/vendor/chatgpt2api/source/web/src/app/image/components/image-results.tsx +554 -554
  111. package/vendor/chatgpt2api/source/web/src/app/image/components/image-sidebar.tsx +176 -176
  112. package/vendor/chatgpt2api/source/web/src/app/image/page.tsx +1799 -1799
  113. package/vendor/chatgpt2api/source/web/src/app/image-manager/page.tsx +732 -732
  114. package/vendor/chatgpt2api/source/web/src/app/layout.tsx +50 -50
  115. package/vendor/chatgpt2api/source/web/src/app/login/page.tsx +101 -101
  116. package/vendor/chatgpt2api/source/web/src/app/logs/page.tsx +356 -356
  117. package/vendor/chatgpt2api/source/web/src/app/page.tsx +30 -30
  118. package/vendor/chatgpt2api/source/web/src/app/settings/components/api-docs-card.tsx +341 -341
  119. package/vendor/chatgpt2api/source/web/src/app/settings/components/backup-settings-card.tsx +447 -447
  120. package/vendor/chatgpt2api/source/web/src/app/settings/components/base-url-card.tsx +71 -71
  121. package/vendor/chatgpt2api/source/web/src/app/settings/components/config-card.tsx +491 -491
  122. package/vendor/chatgpt2api/source/web/src/app/settings/components/cpa-pool-dialog.tsx +108 -108
  123. package/vendor/chatgpt2api/source/web/src/app/settings/components/cpa-pools-card.tsx +169 -169
  124. package/vendor/chatgpt2api/source/web/src/app/settings/components/import-browser-dialog.tsx +185 -185
  125. package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-runtime-card.tsx +379 -379
  126. package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-settings-card.tsx +127 -127
  127. package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-settings.tsx +200 -200
  128. package/vendor/chatgpt2api/source/web/src/app/settings/components/settings-header.tsx +12 -12
  129. package/vendor/chatgpt2api/source/web/src/app/settings/components/sub2api-connections.tsx +886 -886
  130. package/vendor/chatgpt2api/source/web/src/app/settings/components/third-party-apps-card.tsx +81 -81
  131. package/vendor/chatgpt2api/source/web/src/app/settings/components/user-keys-card.tsx +422 -422
  132. package/vendor/chatgpt2api/source/web/src/app/settings/page.tsx +135 -135
  133. package/vendor/chatgpt2api/source/web/src/app/settings/store.ts +1069 -1069
  134. package/vendor/chatgpt2api/source/web/src/components/date-range-filter.tsx +49 -49
  135. package/vendor/chatgpt2api/source/web/src/components/header-actions.tsx +24 -24
  136. package/vendor/chatgpt2api/source/web/src/components/image-lightbox.tsx +434 -434
  137. package/vendor/chatgpt2api/source/web/src/components/image-thumbnail.tsx +46 -46
  138. package/vendor/chatgpt2api/source/web/src/components/theme-script.tsx +18 -18
  139. package/vendor/chatgpt2api/source/web/src/components/theme-toggle.tsx +14 -14
  140. package/vendor/chatgpt2api/source/web/src/components/top-nav.tsx +263 -263
  141. package/vendor/chatgpt2api/source/web/src/components/ui/animated-theme-toggler.tsx +256 -256
  142. package/vendor/chatgpt2api/source/web/src/components/ui/badge.tsx +41 -41
  143. package/vendor/chatgpt2api/source/web/src/components/ui/button.tsx +59 -59
  144. package/vendor/chatgpt2api/source/web/src/components/ui/calendar.tsx +46 -46
  145. package/vendor/chatgpt2api/source/web/src/components/ui/card.tsx +61 -61
  146. package/vendor/chatgpt2api/source/web/src/components/ui/checkbox.tsx +27 -27
  147. package/vendor/chatgpt2api/source/web/src/components/ui/dia-text-reveal.tsx +267 -267
  148. package/vendor/chatgpt2api/source/web/src/components/ui/dialog.tsx +132 -132
  149. package/vendor/chatgpt2api/source/web/src/components/ui/field.tsx +13 -13
  150. package/vendor/chatgpt2api/source/web/src/components/ui/input.tsx +19 -19
  151. package/vendor/chatgpt2api/source/web/src/components/ui/label.tsx +24 -24
  152. package/vendor/chatgpt2api/source/web/src/components/ui/morphing-text.tsx +149 -149
  153. package/vendor/chatgpt2api/source/web/src/components/ui/popover.tsx +38 -38
  154. package/vendor/chatgpt2api/source/web/src/components/ui/select.tsx +175 -175
  155. package/vendor/chatgpt2api/source/web/src/components/ui/sheet.tsx +143 -143
  156. package/vendor/chatgpt2api/source/web/src/components/ui/table.tsx +29 -29
  157. package/vendor/chatgpt2api/source/web/src/components/ui/tabs.tsx +91 -91
  158. package/vendor/chatgpt2api/source/web/src/components/ui/text-3d-flip.tsx +269 -269
  159. package/vendor/chatgpt2api/source/web/src/components/ui/textarea.tsx +18 -18
  160. package/vendor/chatgpt2api/source/web/src/components/version-release-dialog.tsx +127 -127
  161. package/vendor/chatgpt2api/source/web/src/constants/common-env.ts +6 -6
  162. package/vendor/chatgpt2api/source/web/src/hooks/use-version-check.ts +85 -85
  163. package/vendor/chatgpt2api/source/web/src/lib/api.ts +926 -926
  164. package/vendor/chatgpt2api/source/web/src/lib/auth-session.ts +26 -26
  165. package/vendor/chatgpt2api/source/web/src/lib/release.ts +25 -25
  166. package/vendor/chatgpt2api/source/web/src/lib/request.ts +93 -93
  167. package/vendor/chatgpt2api/source/web/src/lib/use-auth-guard.ts +89 -89
  168. package/vendor/chatgpt2api/source/web/src/lib/utils.ts +6 -6
  169. package/vendor/chatgpt2api/source/web/src/store/auth.ts +112 -112
  170. package/vendor/chatgpt2api/source/web/src/store/editable-file-history.ts +33 -33
  171. package/vendor/chatgpt2api/source/web/src/store/image-conversations.ts +318 -318
  172. package/vendor/chatgpt2api/source/web/tsconfig.json +42 -42
@@ -1,253 +1,253 @@
1
- from __future__ import annotations
2
-
3
- import hashlib
4
- import hmac
5
- import secrets
6
- import uuid
7
- from datetime import datetime, timezone
8
- from threading import Lock
9
- from typing import Literal
10
-
11
- from services.config import config
12
- from services.storage.base import StorageBackend
13
-
14
- AuthRole = Literal["admin", "user"]
15
-
16
-
17
- def _now_iso() -> str:
18
- return datetime.now(timezone.utc).isoformat()
19
-
20
-
21
- def _hash_key(value: str) -> str:
22
- return hashlib.sha256(value.encode("utf-8")).hexdigest()
23
-
24
-
25
- class AuthService:
26
- def __init__(self, storage: StorageBackend):
27
- self.storage = storage
28
- self._lock = Lock()
29
- self._items = self._load()
30
- self._last_used_flush_at: dict[str, datetime] = {}
31
-
32
- @staticmethod
33
- def _clean(value: object) -> str:
34
- return str(value or "").strip()
35
-
36
- @staticmethod
37
- def _default_name(role: object) -> str:
38
- return "管理员密钥" if str(role or "").strip().lower() == "admin" else "普通用户"
39
-
40
- def _normalize_item(self, raw: object) -> dict[str, object] | None:
41
- if not isinstance(raw, dict):
42
- return None
43
- role = self._clean(raw.get("role")).lower()
44
- if role not in {"admin", "user"}:
45
- return None
46
- key_hash = self._clean(raw.get("key_hash"))
47
- if not key_hash:
48
- return None
49
- item_id = self._clean(raw.get("id")) or uuid.uuid4().hex[:12]
50
- name = self._clean(raw.get("name")) or self._default_name(role)
51
- created_at = self._clean(raw.get("created_at")) or _now_iso()
52
- last_used_at = self._clean(raw.get("last_used_at")) or None
53
- return {
54
- "id": item_id,
55
- "name": name,
56
- "role": role,
57
- "key_hash": key_hash,
58
- "enabled": bool(raw.get("enabled", True)),
59
- "created_at": created_at,
60
- "last_used_at": last_used_at,
61
- }
62
-
63
- def _load(self) -> list[dict[str, object]]:
64
- try:
65
- items = self.storage.load_auth_keys()
66
- except Exception:
67
- return []
68
- if not isinstance(items, list):
69
- return []
70
- return [normalized for item in items if (normalized := self._normalize_item(item)) is not None]
71
-
72
- def _save(self) -> None:
73
- self.storage.save_auth_keys(self._items)
74
-
75
- def _reload_locked(self) -> None:
76
- self._items = self._load()
77
-
78
- @staticmethod
79
- def _public_item(item: dict[str, object]) -> dict[str, object]:
80
- return {
81
- "id": item.get("id"),
82
- "name": item.get("name"),
83
- "role": item.get("role"),
84
- "enabled": bool(item.get("enabled", True)),
85
- "created_at": item.get("created_at"),
86
- "last_used_at": item.get("last_used_at"),
87
- }
88
-
89
- def list_keys(self, role: AuthRole | None = None) -> list[dict[str, object]]:
90
- with self._lock:
91
- self._reload_locked()
92
- items = [item for item in self._items if role is None or item.get("role") == role]
93
- return [self._public_item(item) for item in items]
94
-
95
- def _has_key_hash_locked(self, key_hash: str, *, exclude_id: str = "") -> bool:
96
- for item in self._items:
97
- item_id = self._clean(item.get("id"))
98
- if exclude_id and item_id == exclude_id:
99
- continue
100
- stored_hash = self._clean(item.get("key_hash"))
101
- if stored_hash and hmac.compare_digest(stored_hash, key_hash):
102
- return True
103
- return False
104
-
105
- def _build_key_hash_locked(self, raw_key: str, *, exclude_id: str = "") -> str:
106
- candidate = self._clean(raw_key)
107
- if not candidate:
108
- raise ValueError("请输入新的专用密钥")
109
- admin_key = self._clean(config.auth_key)
110
- if admin_key and hmac.compare_digest(candidate, admin_key):
111
- raise ValueError("这个密钥和管理员密钥冲突了,请换一个新的密钥")
112
- key_hash = _hash_key(candidate)
113
- if self._has_key_hash_locked(key_hash, exclude_id=exclude_id):
114
- raise ValueError("这个专用密钥已经存在,请换一个新的密钥")
115
- return key_hash
116
-
117
- def _has_name_locked(self, name: str, *, role: AuthRole | None = None, exclude_id: str = "") -> bool:
118
- candidate = self._clean(name)
119
- if not candidate:
120
- return False
121
- for item in self._items:
122
- item_id = self._clean(item.get("id"))
123
- if exclude_id and item_id == exclude_id:
124
- continue
125
- if role is not None and item.get("role") != role:
126
- continue
127
- if self._clean(item.get("name")) == candidate:
128
- return True
129
- return False
130
-
131
- def _build_default_name_locked(self, role: AuthRole, *, exclude_id: str = "") -> str:
132
- base_name = self._default_name(role)
133
- if not self._has_name_locked(base_name, role=role, exclude_id=exclude_id):
134
- return base_name
135
- suffix = 2
136
- while True:
137
- candidate = f"{base_name} {suffix}"
138
- if not self._has_name_locked(candidate, role=role, exclude_id=exclude_id):
139
- return candidate
140
- suffix += 1
141
-
142
- def _build_name_locked(self, name: str, *, role: AuthRole, exclude_id: str = "") -> str:
143
- candidate = self._clean(name)
144
- if not candidate:
145
- return self._build_default_name_locked(role, exclude_id=exclude_id)
146
- if self._has_name_locked(candidate, role=role, exclude_id=exclude_id):
147
- raise ValueError("这个名称已经在使用中了,换一个更容易区分的名称吧")
148
- return candidate
149
-
150
- def create_key(self, *, role: AuthRole, name: str = "") -> tuple[dict[str, object], str]:
151
- with self._lock:
152
- self._reload_locked()
153
- normalized_name = self._build_name_locked(name, role=role)
154
- while True:
155
- raw_key = f"sk-{secrets.token_urlsafe(24)}"
156
- try:
157
- key_hash = self._build_key_hash_locked(raw_key)
158
- break
159
- except ValueError:
160
- continue
161
- item = {
162
- "id": uuid.uuid4().hex[:12],
163
- "name": normalized_name,
164
- "role": role,
165
- "key_hash": key_hash,
166
- "enabled": True,
167
- "created_at": _now_iso(),
168
- "last_used_at": None,
169
- }
170
- self._items.append(item)
171
- self._save()
172
- return self._public_item(item), raw_key
173
-
174
- def update_key(
175
- self,
176
- key_id: str,
177
- updates: dict[str, object],
178
- *,
179
- role: AuthRole | None = None,
180
- ) -> dict[str, object] | None:
181
- normalized_id = self._clean(key_id)
182
- if not normalized_id:
183
- return None
184
- with self._lock:
185
- self._reload_locked()
186
- for index, item in enumerate(self._items):
187
- if item.get("id") != normalized_id:
188
- continue
189
- if role is not None and item.get("role") != role:
190
- return None
191
- next_item = dict(item)
192
- next_role = "admin" if str(next_item.get("role") or "").strip().lower() == "admin" else "user"
193
- if "name" in updates and updates.get("name") is not None:
194
- next_item["name"] = self._build_name_locked(
195
- str(updates.get("name") or ""),
196
- role=next_role,
197
- exclude_id=normalized_id,
198
- )
199
- if "enabled" in updates and updates.get("enabled") is not None:
200
- next_item["enabled"] = bool(updates.get("enabled"))
201
- if "key" in updates and updates.get("key") is not None:
202
- next_item["key_hash"] = self._build_key_hash_locked(str(updates.get("key") or ""), exclude_id=normalized_id)
203
- self._items[index] = next_item
204
- self._save()
205
- return self._public_item(next_item)
206
- return None
207
-
208
- def delete_key(self, key_id: str, *, role: AuthRole | None = None) -> bool:
209
- normalized_id = self._clean(key_id)
210
- if not normalized_id:
211
- return False
212
- with self._lock:
213
- self._reload_locked()
214
- before = len(self._items)
215
- self._items = [
216
- item
217
- for item in self._items
218
- if not (item.get("id") == normalized_id and (role is None or item.get("role") == role))
219
- ]
220
- if len(self._items) == before:
221
- return False
222
- self._save()
223
- return True
224
-
225
- def authenticate(self, raw_key: str) -> dict[str, object] | None:
226
- candidate = self._clean(raw_key)
227
- if not candidate:
228
- return None
229
- candidate_hash = _hash_key(candidate)
230
- with self._lock:
231
- for index, item in enumerate(self._items):
232
- if not bool(item.get("enabled", True)):
233
- continue
234
- stored_hash = self._clean(item.get("key_hash"))
235
- if not stored_hash or not hmac.compare_digest(stored_hash, candidate_hash):
236
- continue
237
- next_item = dict(item)
238
- now = datetime.now(timezone.utc)
239
- next_item["last_used_at"] = now.isoformat()
240
- self._items[index] = next_item
241
- item_id = self._clean(next_item.get("id"))
242
- last_flush_at = self._last_used_flush_at.get(item_id)
243
- if last_flush_at is None or (now - last_flush_at).total_seconds() >= 60:
244
- try:
245
- self._save()
246
- self._last_used_flush_at[item_id] = now
247
- except Exception:
248
- pass
249
- return self._public_item(next_item)
250
- return None
251
-
252
-
253
- auth_service = AuthService(config.get_storage_backend())
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import hmac
5
+ import secrets
6
+ import uuid
7
+ from datetime import datetime, timezone
8
+ from threading import Lock
9
+ from typing import Literal
10
+
11
+ from services.config import config
12
+ from services.storage.base import StorageBackend
13
+
14
+ AuthRole = Literal["admin", "user"]
15
+
16
+
17
+ def _now_iso() -> str:
18
+ return datetime.now(timezone.utc).isoformat()
19
+
20
+
21
+ def _hash_key(value: str) -> str:
22
+ return hashlib.sha256(value.encode("utf-8")).hexdigest()
23
+
24
+
25
+ class AuthService:
26
+ def __init__(self, storage: StorageBackend):
27
+ self.storage = storage
28
+ self._lock = Lock()
29
+ self._items = self._load()
30
+ self._last_used_flush_at: dict[str, datetime] = {}
31
+
32
+ @staticmethod
33
+ def _clean(value: object) -> str:
34
+ return str(value or "").strip()
35
+
36
+ @staticmethod
37
+ def _default_name(role: object) -> str:
38
+ return "管理员密钥" if str(role or "").strip().lower() == "admin" else "普通用户"
39
+
40
+ def _normalize_item(self, raw: object) -> dict[str, object] | None:
41
+ if not isinstance(raw, dict):
42
+ return None
43
+ role = self._clean(raw.get("role")).lower()
44
+ if role not in {"admin", "user"}:
45
+ return None
46
+ key_hash = self._clean(raw.get("key_hash"))
47
+ if not key_hash:
48
+ return None
49
+ item_id = self._clean(raw.get("id")) or uuid.uuid4().hex[:12]
50
+ name = self._clean(raw.get("name")) or self._default_name(role)
51
+ created_at = self._clean(raw.get("created_at")) or _now_iso()
52
+ last_used_at = self._clean(raw.get("last_used_at")) or None
53
+ return {
54
+ "id": item_id,
55
+ "name": name,
56
+ "role": role,
57
+ "key_hash": key_hash,
58
+ "enabled": bool(raw.get("enabled", True)),
59
+ "created_at": created_at,
60
+ "last_used_at": last_used_at,
61
+ }
62
+
63
+ def _load(self) -> list[dict[str, object]]:
64
+ try:
65
+ items = self.storage.load_auth_keys()
66
+ except Exception:
67
+ return []
68
+ if not isinstance(items, list):
69
+ return []
70
+ return [normalized for item in items if (normalized := self._normalize_item(item)) is not None]
71
+
72
+ def _save(self) -> None:
73
+ self.storage.save_auth_keys(self._items)
74
+
75
+ def _reload_locked(self) -> None:
76
+ self._items = self._load()
77
+
78
+ @staticmethod
79
+ def _public_item(item: dict[str, object]) -> dict[str, object]:
80
+ return {
81
+ "id": item.get("id"),
82
+ "name": item.get("name"),
83
+ "role": item.get("role"),
84
+ "enabled": bool(item.get("enabled", True)),
85
+ "created_at": item.get("created_at"),
86
+ "last_used_at": item.get("last_used_at"),
87
+ }
88
+
89
+ def list_keys(self, role: AuthRole | None = None) -> list[dict[str, object]]:
90
+ with self._lock:
91
+ self._reload_locked()
92
+ items = [item for item in self._items if role is None or item.get("role") == role]
93
+ return [self._public_item(item) for item in items]
94
+
95
+ def _has_key_hash_locked(self, key_hash: str, *, exclude_id: str = "") -> bool:
96
+ for item in self._items:
97
+ item_id = self._clean(item.get("id"))
98
+ if exclude_id and item_id == exclude_id:
99
+ continue
100
+ stored_hash = self._clean(item.get("key_hash"))
101
+ if stored_hash and hmac.compare_digest(stored_hash, key_hash):
102
+ return True
103
+ return False
104
+
105
+ def _build_key_hash_locked(self, raw_key: str, *, exclude_id: str = "") -> str:
106
+ candidate = self._clean(raw_key)
107
+ if not candidate:
108
+ raise ValueError("请输入新的专用密钥")
109
+ admin_key = self._clean(config.auth_key)
110
+ if admin_key and hmac.compare_digest(candidate, admin_key):
111
+ raise ValueError("这个密钥和管理员密钥冲突了,请换一个新的密钥")
112
+ key_hash = _hash_key(candidate)
113
+ if self._has_key_hash_locked(key_hash, exclude_id=exclude_id):
114
+ raise ValueError("这个专用密钥已经存在,请换一个新的密钥")
115
+ return key_hash
116
+
117
+ def _has_name_locked(self, name: str, *, role: AuthRole | None = None, exclude_id: str = "") -> bool:
118
+ candidate = self._clean(name)
119
+ if not candidate:
120
+ return False
121
+ for item in self._items:
122
+ item_id = self._clean(item.get("id"))
123
+ if exclude_id and item_id == exclude_id:
124
+ continue
125
+ if role is not None and item.get("role") != role:
126
+ continue
127
+ if self._clean(item.get("name")) == candidate:
128
+ return True
129
+ return False
130
+
131
+ def _build_default_name_locked(self, role: AuthRole, *, exclude_id: str = "") -> str:
132
+ base_name = self._default_name(role)
133
+ if not self._has_name_locked(base_name, role=role, exclude_id=exclude_id):
134
+ return base_name
135
+ suffix = 2
136
+ while True:
137
+ candidate = f"{base_name} {suffix}"
138
+ if not self._has_name_locked(candidate, role=role, exclude_id=exclude_id):
139
+ return candidate
140
+ suffix += 1
141
+
142
+ def _build_name_locked(self, name: str, *, role: AuthRole, exclude_id: str = "") -> str:
143
+ candidate = self._clean(name)
144
+ if not candidate:
145
+ return self._build_default_name_locked(role, exclude_id=exclude_id)
146
+ if self._has_name_locked(candidate, role=role, exclude_id=exclude_id):
147
+ raise ValueError("这个名称已经在使用中了,换一个更容易区分的名称吧")
148
+ return candidate
149
+
150
+ def create_key(self, *, role: AuthRole, name: str = "") -> tuple[dict[str, object], str]:
151
+ with self._lock:
152
+ self._reload_locked()
153
+ normalized_name = self._build_name_locked(name, role=role)
154
+ while True:
155
+ raw_key = f"sk-{secrets.token_urlsafe(24)}"
156
+ try:
157
+ key_hash = self._build_key_hash_locked(raw_key)
158
+ break
159
+ except ValueError:
160
+ continue
161
+ item = {
162
+ "id": uuid.uuid4().hex[:12],
163
+ "name": normalized_name,
164
+ "role": role,
165
+ "key_hash": key_hash,
166
+ "enabled": True,
167
+ "created_at": _now_iso(),
168
+ "last_used_at": None,
169
+ }
170
+ self._items.append(item)
171
+ self._save()
172
+ return self._public_item(item), raw_key
173
+
174
+ def update_key(
175
+ self,
176
+ key_id: str,
177
+ updates: dict[str, object],
178
+ *,
179
+ role: AuthRole | None = None,
180
+ ) -> dict[str, object] | None:
181
+ normalized_id = self._clean(key_id)
182
+ if not normalized_id:
183
+ return None
184
+ with self._lock:
185
+ self._reload_locked()
186
+ for index, item in enumerate(self._items):
187
+ if item.get("id") != normalized_id:
188
+ continue
189
+ if role is not None and item.get("role") != role:
190
+ return None
191
+ next_item = dict(item)
192
+ next_role = "admin" if str(next_item.get("role") or "").strip().lower() == "admin" else "user"
193
+ if "name" in updates and updates.get("name") is not None:
194
+ next_item["name"] = self._build_name_locked(
195
+ str(updates.get("name") or ""),
196
+ role=next_role,
197
+ exclude_id=normalized_id,
198
+ )
199
+ if "enabled" in updates and updates.get("enabled") is not None:
200
+ next_item["enabled"] = bool(updates.get("enabled"))
201
+ if "key" in updates and updates.get("key") is not None:
202
+ next_item["key_hash"] = self._build_key_hash_locked(str(updates.get("key") or ""), exclude_id=normalized_id)
203
+ self._items[index] = next_item
204
+ self._save()
205
+ return self._public_item(next_item)
206
+ return None
207
+
208
+ def delete_key(self, key_id: str, *, role: AuthRole | None = None) -> bool:
209
+ normalized_id = self._clean(key_id)
210
+ if not normalized_id:
211
+ return False
212
+ with self._lock:
213
+ self._reload_locked()
214
+ before = len(self._items)
215
+ self._items = [
216
+ item
217
+ for item in self._items
218
+ if not (item.get("id") == normalized_id and (role is None or item.get("role") == role))
219
+ ]
220
+ if len(self._items) == before:
221
+ return False
222
+ self._save()
223
+ return True
224
+
225
+ def authenticate(self, raw_key: str) -> dict[str, object] | None:
226
+ candidate = self._clean(raw_key)
227
+ if not candidate:
228
+ return None
229
+ candidate_hash = _hash_key(candidate)
230
+ with self._lock:
231
+ for index, item in enumerate(self._items):
232
+ if not bool(item.get("enabled", True)):
233
+ continue
234
+ stored_hash = self._clean(item.get("key_hash"))
235
+ if not stored_hash or not hmac.compare_digest(stored_hash, candidate_hash):
236
+ continue
237
+ next_item = dict(item)
238
+ now = datetime.now(timezone.utc)
239
+ next_item["last_used_at"] = now.isoformat()
240
+ self._items[index] = next_item
241
+ item_id = self._clean(next_item.get("id"))
242
+ last_flush_at = self._last_used_flush_at.get(item_id)
243
+ if last_flush_at is None or (now - last_flush_at).total_seconds() >= 60:
244
+ try:
245
+ self._save()
246
+ self._last_used_flush_at[item_id] = now
247
+ except Exception:
248
+ pass
249
+ return self._public_item(next_item)
250
+ return None
251
+
252
+
253
+ auth_service = AuthService(config.get_storage_backend())