qwenproxy-cli 1.0.0

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 (109) hide show
  1. package/LICENSE +14 -0
  2. package/README.md +907 -0
  3. package/bin/qwenproxy.js +141 -0
  4. package/package.json +78 -0
  5. package/src/api/error-classifier.ts +159 -0
  6. package/src/api/error-helpers.ts +118 -0
  7. package/src/api/models.ts +261 -0
  8. package/src/api/server.ts +859 -0
  9. package/src/cache/memory-cache.ts +385 -0
  10. package/src/clean-cache.ts +204 -0
  11. package/src/core/account-concurrency.ts +671 -0
  12. package/src/core/account-manager.ts +297 -0
  13. package/src/core/account-priority.ts +163 -0
  14. package/src/core/accounts.ts +186 -0
  15. package/src/core/config.ts +383 -0
  16. package/src/core/crypto-utils.ts +79 -0
  17. package/src/core/database.ts +276 -0
  18. package/src/core/errors.ts +118 -0
  19. package/src/core/logger.ts +269 -0
  20. package/src/core/memory-usage.ts +84 -0
  21. package/src/core/metrics.ts +291 -0
  22. package/src/core/model-alias.ts +77 -0
  23. package/src/core/model-registry.ts +544 -0
  24. package/src/core/mutex.ts +119 -0
  25. package/src/core/paths.ts +199 -0
  26. package/src/core/prompt-limits.ts +214 -0
  27. package/src/core/reasoning-effort.ts +102 -0
  28. package/src/core/stream-registry.ts +96 -0
  29. package/src/core/waf-isolation.ts +117 -0
  30. package/src/core/watchdog.ts +195 -0
  31. package/src/delete-chats.ts +23 -0
  32. package/src/index.ts +64 -0
  33. package/src/login.ts +147 -0
  34. package/src/reset-cooldowns.ts +11 -0
  35. package/src/routes/anthropic/index.ts +355 -0
  36. package/src/routes/anthropic/translate.ts +522 -0
  37. package/src/routes/anthropic/types.ts +154 -0
  38. package/src/routes/anthropic/validation.ts +144 -0
  39. package/src/routes/chat/account.ts +1817 -0
  40. package/src/routes/chat/context.ts +241 -0
  41. package/src/routes/chat/errors.ts +85 -0
  42. package/src/routes/chat/helpers.ts +268 -0
  43. package/src/routes/chat/index.ts +618 -0
  44. package/src/routes/chat/media.ts +285 -0
  45. package/src/routes/chat/retry-policy.ts +754 -0
  46. package/src/routes/chat/stop.ts +98 -0
  47. package/src/routes/chat/streaming.ts +2710 -0
  48. package/src/routes/chat/validation.ts +526 -0
  49. package/src/routes/chat.ts +2 -0
  50. package/src/routes/completions.ts +290 -0
  51. package/src/routes/images.ts +139 -0
  52. package/src/routes/responses/adapter.ts +503 -0
  53. package/src/routes/responses/index.ts +405 -0
  54. package/src/routes/responses/state.ts +230 -0
  55. package/src/routes/responses/streaming.ts +528 -0
  56. package/src/routes/responses/types.ts +285 -0
  57. package/src/routes/responses/validation.ts +202 -0
  58. package/src/routes/upload.ts +731 -0
  59. package/src/routes/videos.ts +214 -0
  60. package/src/services/auth-playwright.ts +173 -0
  61. package/src/services/captcha-coordinator.ts +161 -0
  62. package/src/services/captcha-solver.ts +553 -0
  63. package/src/services/chat-cleanup.ts +80 -0
  64. package/src/services/context-meter.ts +317 -0
  65. package/src/services/fingerprint.ts +242 -0
  66. package/src/services/human-behavior.ts +173 -0
  67. package/src/services/media-generation.ts +1748 -0
  68. package/src/services/playwright.ts +2800 -0
  69. package/src/services/qwen-chat-pool.ts +345 -0
  70. package/src/services/qwen-errors.ts +133 -0
  71. package/src/services/qwen-headers.ts +79 -0
  72. package/src/services/qwen-thread-state.ts +393 -0
  73. package/src/services/qwen-url.ts +19 -0
  74. package/src/services/qwen.ts +3126 -0
  75. package/src/services/session-keeper.ts +88 -0
  76. package/src/services/token-estimation-metrics.ts +118 -0
  77. package/src/sync/claude-code.ts +75 -0
  78. package/src/sync/codex.ts +123 -0
  79. package/src/sync/index.ts +362 -0
  80. package/src/sync/omp.ts +105 -0
  81. package/src/sync/opencode.ts +214 -0
  82. package/src/sync/types.ts +53 -0
  83. package/src/sync/utils.ts +27 -0
  84. package/src/sync-clients.ts +189 -0
  85. package/src/tools/instructions.ts +137 -0
  86. package/src/tools/manifest.ts +81 -0
  87. package/src/tools/parser.ts +2989 -0
  88. package/src/tools/toolcall-tags.ts +142 -0
  89. package/src/tools/types.ts +53 -0
  90. package/src/tui/app.ts +264 -0
  91. package/src/tui/index.ts +61 -0
  92. package/src/tui/markdown.ts +258 -0
  93. package/src/tui/proxy-client.ts +326 -0
  94. package/src/tui/screen.ts +278 -0
  95. package/src/tui/server-manager.ts +270 -0
  96. package/src/tui/theme.ts +432 -0
  97. package/src/tui/types.ts +33 -0
  98. package/src/tui/views/accounts-view.ts +656 -0
  99. package/src/tui/views/chat-view.ts +823 -0
  100. package/src/tui/views/logs-view.ts +413 -0
  101. package/src/tui/views/status-view.ts +204 -0
  102. package/src/tui/views/storage-view.ts +291 -0
  103. package/src/tui/views/sync-view.ts +409 -0
  104. package/src/types/ali-oss.d.ts +32 -0
  105. package/src/utils/context-truncation.ts +84 -0
  106. package/src/utils/json.ts +380 -0
  107. package/src/utils/session-id.ts +37 -0
  108. package/src/utils/tool-call-guard.ts +85 -0
  109. package/src/utils/types.ts +109 -0
@@ -0,0 +1,317 @@
1
+ import { config } from "../core/config.ts";
2
+ import {
3
+ getModelCapabilities,
4
+ getModelContextWindow,
5
+ getModelContextWindowSource,
6
+ } from "../core/model-registry.ts";
7
+ import { estimateTokenCount } from "../utils/context-truncation.ts";
8
+ import type { PersonalizationEstimationInfo } from "./token-estimation-metrics.ts";
9
+ import type { Usage } from "../utils/types.ts";
10
+
11
+ export type ContextMeterMode = "full" | "delta" | "replay";
12
+
13
+ export interface ContextMeterOptions {
14
+ enabled: boolean;
15
+ windowTokens: number;
16
+ reportUsage: boolean;
17
+ }
18
+
19
+ export interface ContextMeterSnapshot {
20
+ enabled: true;
21
+ estimate: "heuristic";
22
+ model: string;
23
+ contextWindowTokens: number;
24
+ contextWindowSource: "configured" | "upstream" | "registry" | "default";
25
+ reservedOutputTokens: number;
26
+ usableInputTokens: number;
27
+ estimatedContextTokens: number;
28
+ estimatedRequestTokens: number;
29
+ estimatedContextPercent: number;
30
+ estimatedUsablePercent: number;
31
+ remainingContextTokens: number;
32
+ remainingUsableTokens: number;
33
+ fullPromptChars: number;
34
+ fullPromptBytes: number;
35
+ requestPromptChars: number;
36
+ requestPromptBytes: number;
37
+ qwenPayloadBytes: number | null;
38
+ qwenPayloadPromptChars: number | null;
39
+ qwenPayloadMessageCount: number | null;
40
+ messageCount: number | null;
41
+ fullMessageCount: number | null;
42
+ toolsCount: number;
43
+ filesCount: number;
44
+ personalizationBytes: number;
45
+ personalizationTokens: number;
46
+ mode: ContextMeterMode;
47
+ upstreamPromptTokens: number | null;
48
+ upstreamContextPercent: number | null;
49
+ upstreamRemainingContextTokens: number | null;
50
+ reportedPromptTokens: number | null;
51
+ measurementSource: "qwen" | "local_estimate" | "unavailable";
52
+ }
53
+
54
+ export interface BuildContextMeterInput {
55
+ modelId: string;
56
+ accountId?: string;
57
+ requestPrompt: string;
58
+ fullPrompt: string;
59
+ mode: ContextMeterMode;
60
+ qwenPayloadBytes?: number;
61
+ qwenPayloadPromptChars?: number;
62
+ qwenPayloadMessageCount?: number;
63
+ messageCount?: number;
64
+ fullMessageCount?: number;
65
+ toolsCount?: number;
66
+ filesCount?: number;
67
+ activePersonalization?: PersonalizationEstimationInfo | null;
68
+ }
69
+
70
+ export interface MeteredUsage extends Usage {
71
+ context_meter: ContextMeterSnapshot;
72
+ }
73
+
74
+ function roundPercent(value: number): number {
75
+ return Number(value.toFixed(2));
76
+ }
77
+
78
+ function getReservedOutputTokens(
79
+ modelId: string,
80
+ accountId?: string,
81
+ ): number {
82
+ const capabilities = getModelCapabilities(modelId, accountId);
83
+ return Math.max(
84
+ 4_096,
85
+ capabilities.maxOutputTokens,
86
+ capabilities.maxThinkingTokens,
87
+ );
88
+ }
89
+
90
+ export function getContextMeterOptions(): ContextMeterOptions {
91
+ return {
92
+ enabled: config.contextMeter.enabled,
93
+ windowTokens: config.contextMeter.windowTokens,
94
+ reportUsage: config.contextMeter.reportUsage,
95
+ };
96
+ }
97
+
98
+ /**
99
+ * Build a request-time context estimate without serializing or retaining the
100
+ * prompt. `fullPrompt` is the complete history reconstructed from the client;
101
+ * `requestPrompt` is the delta or replay actually sent to Qwen.
102
+ */
103
+ export function buildContextMeterSnapshot(
104
+ input: BuildContextMeterInput,
105
+ options: ContextMeterOptions = getContextMeterOptions(),
106
+ ): ContextMeterSnapshot | null {
107
+ if (!options.enabled) return null;
108
+
109
+ const contextWindowTokens =
110
+ options.windowTokens > 0
111
+ ? options.windowTokens
112
+ : getModelContextWindow(input.modelId, input.accountId);
113
+ const contextWindowSource =
114
+ options.windowTokens > 0
115
+ ? "configured"
116
+ : getModelContextWindowSource(input.modelId, input.accountId);
117
+ const reservedOutputTokens = getReservedOutputTokens(
118
+ input.modelId,
119
+ input.accountId,
120
+ );
121
+ const usableInputTokens = Math.max(
122
+ 1,
123
+ contextWindowTokens - reservedOutputTokens,
124
+ );
125
+ const estimatedContextTokens = estimateTokenCount(input.fullPrompt);
126
+ const estimatedRequestTokens = estimateTokenCount(input.requestPrompt);
127
+ const personalization = input.activePersonalization ?? null;
128
+
129
+ return {
130
+ enabled: true,
131
+ estimate: "heuristic",
132
+ model: input.modelId,
133
+ contextWindowTokens,
134
+ contextWindowSource,
135
+ reservedOutputTokens,
136
+ usableInputTokens,
137
+ estimatedContextTokens,
138
+ estimatedRequestTokens,
139
+ estimatedContextPercent: roundPercent(
140
+ (estimatedContextTokens / contextWindowTokens) * 100,
141
+ ),
142
+ estimatedUsablePercent: roundPercent(
143
+ (estimatedContextTokens / usableInputTokens) * 100,
144
+ ),
145
+ remainingContextTokens: Math.max(
146
+ 0,
147
+ contextWindowTokens - estimatedContextTokens,
148
+ ),
149
+ remainingUsableTokens: Math.max(
150
+ 0,
151
+ usableInputTokens - estimatedContextTokens,
152
+ ),
153
+ fullPromptChars: input.fullPrompt.length,
154
+ fullPromptBytes: Buffer.byteLength(input.fullPrompt, "utf8"),
155
+ requestPromptChars: input.requestPrompt.length,
156
+ requestPromptBytes: Buffer.byteLength(input.requestPrompt, "utf8"),
157
+ qwenPayloadBytes: input.qwenPayloadBytes ?? null,
158
+ qwenPayloadPromptChars: input.qwenPayloadPromptChars ?? null,
159
+ qwenPayloadMessageCount: input.qwenPayloadMessageCount ?? null,
160
+ messageCount: input.messageCount ?? null,
161
+ fullMessageCount: input.fullMessageCount ?? null,
162
+ toolsCount: input.toolsCount ?? 0,
163
+ filesCount: input.filesCount ?? 0,
164
+ personalizationBytes: personalization?.bytes ?? 0,
165
+ personalizationTokens: personalization?.estimatedTokens ?? 0,
166
+ mode: input.mode,
167
+ upstreamPromptTokens: null,
168
+ upstreamContextPercent: null,
169
+ upstreamRemainingContextTokens: null,
170
+ reportedPromptTokens: null,
171
+ measurementSource: "local_estimate",
172
+ };
173
+ }
174
+
175
+ /**
176
+ * Add the diagnostic extension without changing standard OpenAI usage by
177
+ * default. If reportUsage is enabled, prompt_tokens uses Qwen's measured
178
+ * input_tokens when available and falls back to the local estimate otherwise.
179
+ */
180
+ export function enrichUsageWithContextMeter(
181
+ usage: Usage,
182
+ snapshot: ContextMeterSnapshot | null | undefined,
183
+ options: ContextMeterOptions = getContextMeterOptions(),
184
+ ): Usage | MeteredUsage {
185
+ if (!snapshot || !options.enabled) return usage;
186
+
187
+ const upstreamPromptTokens =
188
+ Number.isFinite(usage.prompt_tokens) && usage.prompt_tokens > 0
189
+ ? usage.prompt_tokens
190
+ : null;
191
+ const reportedPromptTokens = options.reportUsage
192
+ ? (upstreamPromptTokens ?? snapshot.estimatedContextTokens)
193
+ : usage.prompt_tokens;
194
+ const contextMeter: ContextMeterSnapshot = {
195
+ ...snapshot,
196
+ upstreamPromptTokens,
197
+ upstreamContextPercent:
198
+ upstreamPromptTokens !== null
199
+ ? roundPercent((upstreamPromptTokens / snapshot.contextWindowTokens) * 100)
200
+ : null,
201
+ upstreamRemainingContextTokens:
202
+ upstreamPromptTokens !== null
203
+ ? Math.max(0, snapshot.contextWindowTokens - upstreamPromptTokens)
204
+ : null,
205
+ reportedPromptTokens,
206
+ measurementSource: upstreamPromptTokens !== null ? "qwen" : "local_estimate",
207
+ };
208
+
209
+ if (!options.reportUsage) {
210
+ return {
211
+ ...usage,
212
+ context_meter: contextMeter,
213
+ };
214
+ }
215
+
216
+ const completionTokens = Math.max(0, usage.completion_tokens || 0);
217
+ return {
218
+ ...usage,
219
+ prompt_tokens: reportedPromptTokens,
220
+ total_tokens: reportedPromptTokens + completionTokens,
221
+ prompt_tokens_details: {
222
+ ...(usage.prompt_tokens_details ?? { cached_tokens: 0 }),
223
+ text_tokens: reportedPromptTokens,
224
+ },
225
+ context_meter: contextMeter,
226
+ };
227
+ }
228
+
229
+ export function contextMeterLogData(
230
+ snapshot: ContextMeterSnapshot,
231
+ ): Record<string, unknown> {
232
+ return {
233
+ model: snapshot.model,
234
+ mode: snapshot.mode,
235
+ estimate: snapshot.estimate,
236
+ estimatedContextTokens: snapshot.estimatedContextTokens,
237
+ estimatedRequestTokens: snapshot.estimatedRequestTokens,
238
+ contextWindowTokens: snapshot.contextWindowTokens,
239
+ contextWindowSource: snapshot.contextWindowSource,
240
+ measurementSource: snapshot.measurementSource,
241
+ estimatedContextPercent: snapshot.estimatedContextPercent,
242
+ estimatedUsablePercent: snapshot.estimatedUsablePercent,
243
+ remainingContextTokens: snapshot.remainingContextTokens,
244
+ remainingUsableTokens: snapshot.remainingUsableTokens,
245
+ fullPromptChars: snapshot.fullPromptChars,
246
+ fullPromptBytes: snapshot.fullPromptBytes,
247
+ requestPromptChars: snapshot.requestPromptChars,
248
+ requestPromptBytes: snapshot.requestPromptBytes,
249
+ qwenPayloadBytes: snapshot.qwenPayloadBytes,
250
+ qwenPayloadPromptChars: snapshot.qwenPayloadPromptChars,
251
+ qwenPayloadMessageCount: snapshot.qwenPayloadMessageCount,
252
+ messageCount: snapshot.messageCount,
253
+ fullMessageCount: snapshot.fullMessageCount,
254
+ toolsCount: snapshot.toolsCount,
255
+ filesCount: snapshot.filesCount,
256
+ personalizationBytes: snapshot.personalizationBytes,
257
+ personalizationTokens: snapshot.personalizationTokens,
258
+ upstreamPromptTokens: snapshot.upstreamPromptTokens,
259
+ upstreamContextPercent: snapshot.upstreamContextPercent,
260
+ upstreamRemainingContextTokens: snapshot.upstreamRemainingContextTokens,
261
+ reportedPromptTokens: snapshot.reportedPromptTokens,
262
+ };
263
+ }
264
+
265
+ export function getContextMeterHeaders(
266
+ snapshot: ContextMeterSnapshot | null | undefined,
267
+ ): Record<string, string> {
268
+ if (!snapshot) return {};
269
+
270
+ const headers: Record<string, string> = {
271
+ "X-QwenProxy-Context-Meter": "enabled",
272
+ "X-QwenProxy-Context-Model": snapshot.model,
273
+ "X-QwenProxy-Context-Mode": snapshot.mode,
274
+ "X-QwenProxy-Context-Window-Tokens": String(snapshot.contextWindowTokens),
275
+ "X-QwenProxy-Context-Window-Source": snapshot.contextWindowSource,
276
+ "X-QwenProxy-Context-Measurement": snapshot.measurementSource,
277
+ "X-QwenProxy-Context-Estimated-Tokens": String(
278
+ snapshot.estimatedContextTokens,
279
+ ),
280
+ "X-QwenProxy-Context-Percent": String(snapshot.estimatedContextPercent),
281
+ "X-QwenProxy-Context-Remaining-Tokens": String(
282
+ snapshot.remainingContextTokens,
283
+ ),
284
+ "X-QwenProxy-Context-Full-Prompt-Bytes": String(
285
+ snapshot.fullPromptBytes,
286
+ ),
287
+ "X-QwenProxy-Context-Request-Prompt-Bytes": String(
288
+ snapshot.requestPromptBytes,
289
+ ),
290
+ "X-QwenProxy-Context-Qwen-Payload-Bytes": String(
291
+ snapshot.qwenPayloadBytes ?? 0,
292
+ ),
293
+ };
294
+
295
+ if (snapshot.upstreamPromptTokens !== null) {
296
+ headers["X-QwenProxy-Context-Upstream-Tokens"] = String(
297
+ snapshot.upstreamPromptTokens,
298
+ );
299
+ }
300
+ if (snapshot.upstreamContextPercent !== null) {
301
+ headers["X-QwenProxy-Context-Upstream-Percent"] = String(
302
+ snapshot.upstreamContextPercent,
303
+ );
304
+ }
305
+ if (snapshot.upstreamRemainingContextTokens !== null) {
306
+ headers["X-QwenProxy-Context-Upstream-Remaining-Tokens"] = String(
307
+ snapshot.upstreamRemainingContextTokens,
308
+ );
309
+ }
310
+ if (snapshot.reportedPromptTokens !== null) {
311
+ headers["X-QwenProxy-Context-Reported-Tokens"] = String(
312
+ snapshot.reportedPromptTokens,
313
+ );
314
+ }
315
+
316
+ return headers;
317
+ }
@@ -0,0 +1,242 @@
1
+ function mulberry32(seed: number): () => number {
2
+ return () => {
3
+ seed |= 0;
4
+ seed = (seed + 0x6d2b79f5) | 0;
5
+ let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
6
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
7
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
8
+ };
9
+ }
10
+
11
+ function seedFromString(value: string): number {
12
+ let hash = 0;
13
+ for (let i = 0; i < value.length; i++) {
14
+ hash = ((hash << 5) - hash + value.charCodeAt(i)) | 0;
15
+ }
16
+ return hash >>> 0;
17
+ }
18
+
19
+ function pick<T>(rng: () => number, values: readonly T[]): T {
20
+ return values[Math.floor(rng() * values.length)];
21
+ }
22
+
23
+ function randInt(rng: () => number, min: number, max: number): number {
24
+ return Math.floor(rng() * (max - min + 1)) + min;
25
+ }
26
+
27
+ const CHROME_MAJOR = 149;
28
+
29
+ const VIEWPORTS = [
30
+ { width: 1366, height: 768 },
31
+ { width: 1440, height: 900 },
32
+ { width: 1536, height: 864 },
33
+ { width: 1600, height: 900 },
34
+ { width: 1680, height: 1050 },
35
+ { width: 1920, height: 1080 },
36
+ { width: 1920, height: 1200 },
37
+ { width: 1280, height: 720 },
38
+ { width: 1280, height: 800 },
39
+ { width: 1536, height: 864 },
40
+ ] as const;
41
+
42
+ const WEBGL_PROFILES = [
43
+ {
44
+ vendor: "Google Inc. (Intel)",
45
+ renderer: "ANGLE (Intel, Intel(R) UHD Graphics 630 Direct3D11 vs_5_0 ps_5_0, D3D11)",
46
+ },
47
+ {
48
+ vendor: "Google Inc. (Intel)",
49
+ renderer: "ANGLE (Intel, Intel(R) Iris(R) Xe Graphics Direct3D11 vs_5_0 ps_5_0, D3D11)",
50
+ },
51
+ {
52
+ vendor: "Google Inc. (Intel)",
53
+ renderer: "ANGLE (Intel, Intel(R) UHD Graphics 770 Direct3D11 vs_5_0 ps_5_0, D3D11)",
54
+ },
55
+ {
56
+ vendor: "Google Inc. (NVIDIA)",
57
+ renderer: "ANGLE (NVIDIA, NVIDIA GeForce RTX 3060 Direct3D11 vs_5_0 ps_5_0, D3D11)",
58
+ },
59
+ {
60
+ vendor: "Google Inc. (NVIDIA)",
61
+ renderer: "ANGLE (NVIDIA, NVIDIA GeForce RTX 3070 Direct3D11 vs_5_0 ps_5_0, D3D11)",
62
+ },
63
+ {
64
+ vendor: "Google Inc. (NVIDIA)",
65
+ renderer: "ANGLE (NVIDIA, NVIDIA GeForce RTX 3080 Direct3D11 vs_5_0 ps_5_0, D3D11)",
66
+ },
67
+ {
68
+ vendor: "Google Inc. (NVIDIA)",
69
+ renderer: "ANGLE (NVIDIA, NVIDIA GeForce RTX 4060 Direct3D11 vs_5_0 ps_5_0, D3D11)",
70
+ },
71
+ {
72
+ vendor: "Google Inc. (NVIDIA)",
73
+ renderer: "ANGLE (NVIDIA, NVIDIA GeForce RTX 4070 Direct3D11 vs_5_0 ps_5_0, D3D11)",
74
+ },
75
+ {
76
+ vendor: "Google Inc. (NVIDIA)",
77
+ renderer: "ANGLE (NVIDIA, NVIDIA GeForce GTX 1660 SUPER Direct3D11 vs_5_0 ps_5_0, D3D11)",
78
+ },
79
+ {
80
+ vendor: "Google Inc. (AMD)",
81
+ renderer: "ANGLE (AMD, AMD Radeon RX 6600 Direct3D11 vs_5_0 ps_5_0, D3D11)",
82
+ },
83
+ {
84
+ vendor: "Google Inc. (AMD)",
85
+ renderer: "ANGLE (AMD, AMD Radeon RX 7600 Direct3D11 vs_5_0 ps_5_0, D3D11)",
86
+ },
87
+ {
88
+ vendor: "Google Inc. (AMD)",
89
+ renderer: "ANGLE (AMD, AMD Radeon RX 580 Direct3D11 vs_5_0 ps_5_0, D3D11)",
90
+ },
91
+ ] as const;
92
+
93
+ const LANGUAGE_PROFILES = [
94
+ ["pt-BR", "pt", "en-US", "en"],
95
+ ["pt-BR", "pt", "en-US", "en", "es"],
96
+ ["pt-BR", "en-US", "en", "pt"],
97
+ ["pt-BR", "pt", "en"],
98
+ ["pt-BR", "pt;q=0.9", "en-US;q=0.8", "en;q=0.7"],
99
+ ] as const;
100
+
101
+ const HARDWARE_CONCURRENCIES = [4, 6, 8, 8, 8, 12, 16, 16, 24, 32] as const;
102
+ const DEVICE_MEMORIES = [4, 8, 8, 8, 16, 16, 32] as const;
103
+
104
+ const PLATFORM_VERSIONS = [
105
+ { platform: "Windows", platformVersion: "14.0.0", major: "10" },
106
+ { platform: "Windows", platformVersion: "15.0.0", major: "11" },
107
+ { platform: "Windows", platformVersion: "14.0.0", major: "10" },
108
+ { platform: "Windows", platformVersion: "15.0.0", major: "11" },
109
+ ] as const;
110
+
111
+ const NOT_A_BRAND_VARIANTS = [
112
+ { brand: "Not/A)Brand", version: "99" },
113
+ { brand: "Not)A_Brand", version: "99" },
114
+ { brand: "Not/A)Brand", version: "8" },
115
+ { brand: "Not?A_Brand", version: "24" },
116
+ { brand: "Not/A)Brand", version: "99" },
117
+ ] as const;
118
+
119
+ export interface FingerprintProfile {
120
+ accountId: string;
121
+ seed: number;
122
+ userAgent: string;
123
+ appVersion: string;
124
+ chromeMajor: number;
125
+ chromeVersion: string;
126
+ brands: Array<{ brand: string; version: string }>;
127
+ fullVersionList: Array<{ brand: string; version: string }>;
128
+ secChUa: string;
129
+ platform: string;
130
+ platformVersion: string;
131
+ architecture: string;
132
+ bitness: string;
133
+ languages: string[];
134
+ locale: string;
135
+ timezoneId: string;
136
+ viewport: { width: number; height: number };
137
+ hardwareConcurrency: number;
138
+ deviceMemory: number;
139
+ webglVendor: string;
140
+ webglRenderer: string;
141
+ colorDepth: number;
142
+ pixelDepth: number;
143
+ canvasNoiseSeed: number;
144
+ audioNoiseSeed: number;
145
+ webglNoiseSeed: number;
146
+ outerWidthOffset: number;
147
+ outerHeightOffset: number;
148
+ }
149
+
150
+ const profileCache = new Map<string, FingerprintProfile>();
151
+
152
+ // Per-account rotation salt. The seed is normally derived ONLY from the
153
+ // accountId, so after a hard WAF block (captcha/TMD) the account would return
154
+ // from its cooldown on the SAME device identity the WAF already flagged — the
155
+ // flag re-propagates immediately. Bumping the salt (and closing the browser
156
+ // context) makes the next profile a fresh device identity.
157
+ const rotationSalts = new Map<string, number>();
158
+
159
+ export function rotateFingerprintSeed(accountId: string): number {
160
+ const next = (rotationSalts.get(accountId) ?? 0) + 1;
161
+ rotationSalts.set(accountId, next);
162
+ profileCache.delete(accountId);
163
+ return next;
164
+ }
165
+
166
+ export function getFingerprintRotation(accountId: string): number {
167
+ return rotationSalts.get(accountId) ?? 0;
168
+ }
169
+
170
+ export function getFingerprintProfile(accountId: string): FingerprintProfile {
171
+ const cached = profileCache.get(accountId);
172
+ if (cached) return cached;
173
+
174
+ const salt = rotationSalts.get(accountId) ?? 0;
175
+ const seed = seedFromString(salt === 0 ? accountId : `${accountId}#r${salt}`);
176
+ const rng = mulberry32(seed);
177
+ const viewport = pick(rng, VIEWPORTS);
178
+ const webgl = pick(rng, WEBGL_PROFILES);
179
+ const languages = [...pick(rng, LANGUAGE_PROFILES)];
180
+ const hardwareConcurrency = pick(rng, HARDWARE_CONCURRENCIES);
181
+ const deviceMemory = pick(rng, DEVICE_MEMORIES);
182
+ const platformInfo = pick(rng, PLATFORM_VERSIONS);
183
+ const notABrand = pick(rng, NOT_A_BRAND_VARIANTS);
184
+
185
+ const build = randInt(rng, 7300, 7600);
186
+ const patch = randInt(rng, 0, 160);
187
+ const chromeVersion = `${CHROME_MAJOR}.0.${build}.${patch}`;
188
+
189
+ const brands = [
190
+ { brand: notABrand.brand, version: notABrand.version },
191
+ { brand: "Google Chrome", version: String(CHROME_MAJOR) },
192
+ { brand: "Chromium", version: String(CHROME_MAJOR) },
193
+ ];
194
+ const fullVersionList = [
195
+ { brand: notABrand.brand, version: chromeVersion },
196
+ { brand: "Google Chrome", version: chromeVersion },
197
+ { brand: "Chromium", version: chromeVersion },
198
+ ];
199
+ const secChUa = brands
200
+ .map((brand) => `"${brand.brand}";v="${brand.version}"`)
201
+ .join(", ");
202
+ const userAgent = `Mozilla/5.0 (Windows NT ${platformInfo.major}.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${chromeVersion} Safari/537.36`;
203
+
204
+ const profile: FingerprintProfile = {
205
+ accountId,
206
+ seed,
207
+ userAgent,
208
+ appVersion: userAgent.replace("Mozilla/", ""),
209
+ chromeMajor: CHROME_MAJOR,
210
+ chromeVersion,
211
+ brands,
212
+ fullVersionList,
213
+ secChUa,
214
+ platform: "Win32",
215
+ platformVersion: platformInfo.platformVersion,
216
+ architecture: "x86",
217
+ bitness: "64",
218
+ languages,
219
+ locale: languages[0].split(";")[0],
220
+ timezoneId: "America/Sao_Paulo",
221
+ viewport,
222
+ hardwareConcurrency,
223
+ deviceMemory,
224
+ webglVendor: webgl.vendor,
225
+ webglRenderer: webgl.renderer,
226
+ colorDepth: 24,
227
+ pixelDepth: 24,
228
+ canvasNoiseSeed: randInt(rng, 1, 2147483647),
229
+ audioNoiseSeed: randInt(rng, 1, 2147483647),
230
+ webglNoiseSeed: randInt(rng, 1, 2147483647),
231
+ outerWidthOffset: randInt(rng, 0, 20),
232
+ outerHeightOffset: randInt(rng, 75, 95),
233
+ };
234
+
235
+ profileCache.set(accountId, profile);
236
+ return profile;
237
+ }
238
+
239
+ export function clearFingerprintCache(accountId?: string): void {
240
+ if (accountId) profileCache.delete(accountId);
241
+ else profileCache.clear();
242
+ }