-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathserver.js
More file actions
669 lines (576 loc) · 17.9 KB
/
Copy pathserver.js
File metadata and controls
669 lines (576 loc) · 17.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
const crypto = require('crypto');
const jpeg = require('jpeg-js');
const JPRX_BASE_URL = 'https://jprx.m.qq.com';
const WX_BASE_URL = 'https://open.weixin.qq.com';
const WX_LONGPOLL_BASE_URL = 'https://long.open.weixin.qq.com';
const APP_VERSION = '1.4.0';
const APP_ENV = 'release';
const OPENCLAW_CLIENT_VERSION = '2026.3.13';
const POLL_INTERVAL_MS = 2000;
const WX_LOGIN_INFO = {
appid: 'wx9d11056dd75b7240',
redirectUri: 'https://security.guanjia.qq.com/login',
};
function timestamp() {
return new Date().toLocaleTimeString('zh-CN', { hour12: false });
}
function log(message) {
process.stdout.write(`[${timestamp()}] ${message}\n`);
}
function flattenCandidates(input, out = []) {
if (input == null) {
return out;
}
out.push(input);
if (Array.isArray(input)) {
for (const item of input) {
flattenCandidates(item, out);
}
return out;
}
if (typeof input === 'object') {
for (const value of Object.values(input)) {
flattenCandidates(value, out);
}
}
return out;
}
function firstString(...candidates) {
for (const candidate of flattenCandidates(candidates)) {
if (typeof candidate === 'string' && candidate.trim()) {
return candidate.trim();
}
}
return '';
}
function firstObject(...candidates) {
for (const candidate of flattenCandidates(candidates)) {
if (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) {
return candidate;
}
}
return null;
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function createTraceId() {
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 16)}`;
}
function gcd(a, b) {
let x = Math.abs(a);
let y = Math.abs(b);
while (y) {
const t = x % y;
x = y;
y = t;
}
return x || 1;
}
function normalizeJprxResponse(raw, response) {
const nestedCode =
raw?.data?.resp?.common?.code ??
raw?.data?.common?.code ??
raw?.resp?.common?.code ??
raw?.common?.code;
const nestedMessage =
raw?.data?.resp?.common?.message ??
raw?.data?.common?.message ??
raw?.resp?.common?.message ??
raw?.common?.message ??
raw?.message ??
response.statusText;
if (!response.ok) {
return {
success: false,
code: response.status,
message: nestedMessage || `HTTP ${response.status}`,
data: raw,
raw,
};
}
const ret = raw?.ret;
const data =
raw?.data?.resp?.data ??
raw?.data?.data ??
raw?.resp?.data ??
raw?.data ??
raw;
if (ret === 0 && (nestedCode == null || nestedCode === 0)) {
return {
success: true,
code: 0,
message: 'Success',
data,
raw,
};
}
return {
success: false,
code: nestedCode ?? ret ?? response.status,
message: nestedMessage || '业务请求失败',
data,
raw,
};
}
async function postJprx(endpoint, payload, session) {
const accountId = session.userId || '1';
const headers = {
'Content-Type': 'application/json',
'X-Version': '1',
'X-Token': session.loginKey || '',
'X-Guid': session.guid || '1',
'X-Account': accountId,
'X-Account-Id': accountId,
'X-Session': '',
'X-Trace-Id': createTraceId(),
};
if (session.jwtToken) {
headers['X-OpenClaw-Token'] = session.jwtToken;
}
if (OPENCLAW_CLIENT_VERSION) {
headers['X-OpenClaw-ClientVersion'] = OPENCLAW_CLIENT_VERSION;
}
const requestBody = {
...payload,
web_version: APP_VERSION,
web_env: APP_ENV,
};
const response = await fetch(`${JPRX_BASE_URL}${endpoint}`, {
method: 'POST',
headers,
body: JSON.stringify(requestBody),
});
const headerJwt = response.headers.get('x-new-token') || response.headers.get('X-New-Token') || '';
if (headerJwt) {
session.jwtToken = headerJwt;
}
let raw = null;
try {
raw = await response.json();
} catch {
raw = null;
}
return normalizeJprxResponse(raw, response);
}
function mapUserInfo(rawUserInfo, fallbackGuid) {
const source = rawUserInfo && typeof rawUserInfo === 'object' ? rawUserInfo : {};
return {
nickname: firstString(source.nickname, source.nick_name),
avatar: firstString(source.avatar, source.avatar_url, source.head_img_url, source.head_img),
guid: firstString(source.guid, fallbackGuid),
userId: firstString(source.userId, source.user_id, source.uid, source.uin),
...source,
};
}
function applyLoginContext(session, result) {
const bodyToken = firstString(
result.data?.token,
result.raw?.data?.resp?.data?.token,
result.raw?.data?.data?.token,
result.raw?.resp?.data?.token
);
const rawUserInfo =
firstObject(
result.data?.userInfo,
result.data?.user_info,
result.raw?.data?.userInfo,
result.raw?.data?.user_info,
result.raw?.data?.resp?.data?.userInfo,
result.raw?.data?.resp?.data?.user_info,
result.raw?.data?.data?.userInfo,
result.raw?.data?.data?.user_info,
result.raw?.resp?.data?.userInfo,
result.raw?.resp?.data?.user_info,
result.data,
result.raw?.data?.resp?.data,
result.raw?.data?.data,
result.raw?.resp?.data
) || {};
const userInfo = mapUserInfo(rawUserInfo, session.guid);
const userId = firstString(
userInfo.userId,
userInfo.user_id,
userInfo.uid,
userInfo.uin,
result.data?.userId,
result.data?.user_id,
result.data?.uid,
result.data?.uin,
result.raw?.data?.userId,
result.raw?.data?.user_id,
result.raw?.data?.resp?.data?.userId,
result.raw?.data?.resp?.data?.user_id,
result.raw?.data?.data?.userId,
result.raw?.data?.data?.user_id
);
const guid = firstString(
userInfo.guid,
result.data?.guid,
result.data?.user_guid,
session.guid
);
const loginKey = firstString(
userInfo.loginKey,
userInfo.login_key,
result.data?.loginKey,
result.data?.login_key,
result.raw?.data?.loginKey,
result.raw?.data?.login_key,
result.raw?.data?.resp?.data?.loginKey,
result.raw?.data?.resp?.data?.login_key
);
const openclawChannelToken = firstString(
result.data?.openclawChannelToken,
result.data?.openclaw_channel_token,
result.raw?.data?.resp?.data?.openclawChannelToken,
result.raw?.data?.resp?.data?.openclaw_channel_token,
result.raw?.data?.data?.openclawChannelToken,
result.raw?.data?.data?.openclaw_channel_token
);
session.userInfo = userInfo;
session.userId = userId || session.userId || '';
session.guid = guid || session.guid || '';
session.loginKey = loginKey || session.loginKey || '';
session.jwtToken = bodyToken || session.jwtToken || '';
session.openclawChannelToken = openclawChannelToken || session.openclawChannelToken || '';
}
function buildQrConnectUrl(state) {
const redirectUri = encodeURIComponent(WX_LOGIN_INFO.redirectUri);
return `${WX_BASE_URL}/connect/qrconnect?appid=${WX_LOGIN_INFO.appid}&scope=snsapi_login&redirect_uri=${redirectUri}&state=${state}&login_type=jssdk&self_redirect=true&style=white`;
}
async function fetchQrChallenge(session) {
session.guid = crypto.randomUUID();
session.state = '';
session.uuid = '';
session.loginKey = '';
session.userId = '';
session.userInfo = null;
session.jwtToken = '';
session.openclawChannelToken = '';
session.apiKey = '';
log('正在请求登录 state...');
const stateResult = await postJprx('/data/4050/forward', { guid: session.guid }, session);
if (!stateResult.success) {
throw new Error(`获取登录 state 失败: ${stateResult.message}`);
}
const state = firstString(stateResult.data?.state);
if (!state) {
throw new Error('获取登录 state 失败: 响应里没有 state');
}
session.state = state;
const qrPageUrl = buildQrConnectUrl(state);
log('正在获取微信二维码页面...');
const html = await fetch(qrPageUrl).then((response) => response.text());
const uuid =
html.match(/\/connect\/qrcode\/([A-Za-z0-9]+)/)?.[1] ||
html.match(/var G="([A-Za-z0-9]+)"/)?.[1] ||
'';
if (!uuid) {
throw new Error('解析二维码 uuid 失败');
}
session.uuid = uuid;
return {
state,
uuid,
qrPageUrl,
qrImageUrl: `${WX_BASE_URL}/connect/qrcode/${uuid}`,
};
}
function decodeJpegToBinaryMatrix(buffer) {
const image = jpeg.decode(buffer, { useTArray: true });
const { width, height, data } = image;
const rowBits = [];
const y = Math.floor(height / 2);
for (let x = 0; x < width; x += 1) {
const index = (y * width + x) * 4;
const gray = data[index];
rowBits.push(gray < 128 ? 1 : 0);
}
const runs = [];
let current = rowBits[0];
let count = 1;
for (let i = 1; i < rowBits.length; i += 1) {
if (rowBits[i] === current) {
count += 1;
} else {
runs.push(count);
current = rowBits[i];
count = 1;
}
}
runs.push(count);
let moduleSize = runs[0] || 1;
for (const run of runs.slice(1)) {
moduleSize = gcd(moduleSize, run);
}
if (moduleSize < 2 || width % moduleSize !== 0 || height % moduleSize !== 0) {
throw new Error(`二维码模块尺寸识别失败: moduleSize=${moduleSize}, width=${width}, height=${height}`);
}
const moduleCountX = width / moduleSize;
const moduleCountY = height / moduleSize;
const matrix = [];
for (let my = 0; my < moduleCountY; my += 1) {
const row = [];
for (let mx = 0; mx < moduleCountX; mx += 1) {
const sampleX = Math.min(width - 1, mx * moduleSize + Math.floor(moduleSize / 2));
const sampleY = Math.min(height - 1, my * moduleSize + Math.floor(moduleSize / 2));
const index = (sampleY * width + sampleX) * 4;
const gray = data[index];
row.push(gray < 128);
}
matrix.push(row);
}
return matrix;
}
function trimQrMatrix(matrix, padding = 1) {
let top = 0;
let bottom = matrix.length - 1;
let left = 0;
let right = matrix[0]?.length - 1 || 0;
while (top <= bottom && matrix[top].every((cell) => !cell)) {
top += 1;
}
while (bottom >= top && matrix[bottom].every((cell) => !cell)) {
bottom -= 1;
}
while (left <= right && matrix.every((row) => !row[left])) {
left += 1;
}
while (right >= left && matrix.every((row) => !row[right])) {
right -= 1;
}
const cropped = matrix
.slice(top, bottom + 1)
.map((row) => row.slice(left, right + 1));
const width = cropped[0]?.length || 0;
const emptyRow = new Array(width + padding * 2).fill(false);
const padded = cropped.map((row) => [
...new Array(padding).fill(false),
...row,
...new Array(padding).fill(false),
]);
return [
...new Array(padding).fill(null).map(() => emptyRow.slice()),
...padded,
...new Array(padding).fill(null).map(() => emptyRow.slice()),
];
}
function renderCompactQrMatrix(matrix) {
const compactMatrix = trimQrMatrix(matrix, 1);
const lines = [];
for (let y = 0; y < compactMatrix.length; y += 2) {
const topRow = compactMatrix[y];
const bottomRow = compactMatrix[y + 1] || new Array(topRow.length).fill(false);
let line = '';
for (let x = 0; x < topRow.length; x += 1) {
const top = topRow[x];
const bottom = bottomRow[x];
if (top && bottom) {
line += '█';
} else if (top) {
line += '▀';
} else if (bottom) {
line += '▄';
} else {
line += ' ';
}
}
lines.push(line);
}
return `\n${lines.join('\n')}\n`;
}
function renderAsciiQrMatrix(matrix) {
const compactMatrix = trimQrMatrix(matrix, 1);
const lines = compactMatrix.map((row) =>
row.map((cell) => (cell ? '##' : ' ')).join('')
);
return `\n${lines.join('\n')}\n`;
}
function renderQrMatrix(matrix) {
if (process.platform === 'win32') {
return renderAsciiQrMatrix(matrix);
}
return renderCompactQrMatrix(matrix);
}
async function printQrCode(uuid) {
log(`正在下载二维码图片,uuid=${uuid}`);
const imageBuffer = Buffer.from(await fetch(`${WX_BASE_URL}/connect/qrcode/${uuid}`).then((response) => response.arrayBuffer()));
const matrix = decodeJpegToBinaryMatrix(imageBuffer);
process.stdout.write(renderQrMatrix(matrix));
}
function parseLongPollScript(script) {
const errcode = Number(script.match(/window\.wx_errcode=(\d+)/)?.[1] || NaN);
const code = script.match(/window\.wx_code='([^']*)'/)?.[1] || '';
return { errcode, code };
}
async function waitForWxCode(uuid) {
log('开始轮询扫码状态...');
let last = '';
while (true) {
const script = await fetch(`${WX_LONGPOLL_BASE_URL}/connect/l/qrconnect?uuid=${uuid}${last ? `&last=${last}` : ''}`).then((response) => response.text());
const { errcode, code } = parseLongPollScript(script);
if (errcode === 404) {
log('二维码已扫描,等待微信里点击允许...');
last = String(errcode);
await sleep(100);
continue;
}
if (errcode === 403) {
log('用户取消了本次登录,继续等待下一次扫描...');
last = String(errcode);
await sleep(POLL_INTERVAL_MS);
continue;
}
if (errcode === 408) {
await sleep(POLL_INTERVAL_MS);
continue;
}
if (errcode === 402) {
throw new Error('二维码已过期');
}
if (errcode === 405 && code) {
log('微信确认完成,已拿到登录 code。');
return code;
}
if (!Number.isNaN(errcode)) {
log(`收到未处理的微信状态码: ${errcode}`);
await sleep(POLL_INTERVAL_MS);
continue;
}
throw new Error(`解析微信轮询响应失败: ${script.slice(0, 120)}`);
}
}
async function completeLogin(session, code) {
log('正在调用 4026 换取登录态...');
const callbackResult = await postJprx('/data/4026/forward', {
guid: session.guid,
state: session.state,
code,
}, session);
if (!callbackResult.success) {
throw new Error(`登录回调失败: ${callbackResult.message}`);
}
applyLoginContext(session, callbackResult);
if ((!session.userInfo || !session.userInfo.userId) && session.guid) {
log('4026 未返回完整 user_info,补调 4027...');
const userInfoResult = await postJprx('/data/4027/forward', { guid: session.guid }, session);
if (userInfoResult.success) {
applyLoginContext(session, userInfoResult);
}
}
if (!session.openclawChannelToken) {
log('当前没有 openclaw_channel_token,补调 4058...');
const channelTokenResult = await postJprx('/data/4058/forward', {}, session);
if (channelTokenResult.success) {
applyLoginContext(session, channelTokenResult);
}
}
log(
`登录成功,loginKey=${session.loginKey ? 'yes' : 'no'},jwt=${session.jwtToken ? 'yes' : 'no'},channelToken=${session.openclawChannelToken ? 'yes' : 'no'}。`
);
}
async function fetchApiKey(session) {
log('正在调用 4055 获取 apiKey...');
const apiKeyResult = await postJprx('/data/4055/forward', {}, session);
if (!apiKeyResult.success) {
throw new Error(`获取 apiKey 失败: ${apiKeyResult.message}`);
}
const apiKey = firstString(
apiKeyResult.data?.key,
apiKeyResult.raw?.data?.key,
apiKeyResult.raw?.data?.resp?.data?.key,
apiKeyResult.raw?.resp?.data?.key
);
if (!apiKey) {
throw new Error('4055 返回成功,但响应里没有 key');
}
session.apiKey = apiKey;
return apiKey;
}
function buildRiskAssessPayload(session) {
const now = new Date();
const offsetMinutes = -now.getTimezoneOffset();
const sign = offsetMinutes >= 0 ? '+' : '-';
const absoluteMinutes = Math.abs(offsetMinutes);
const pad = (value, size = 2) => String(value).padStart(size, '0');
const payload = {
scene: 'login',
userId: session.userId || '',
deviceToken: session.guid || '',
extra: {
client_end: 'QClaw',
macOS_id: session.guid || '',
},
eventTime:
`${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}` +
`T${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}.` +
`${pad(now.getMilliseconds(), 3)}${sign}${pad(Math.floor(absoluteMinutes / 60))}:${pad(absoluteMinutes % 60)}`,
};
return payload;
}
async function performRiskAssess(session) {
if (!session.guid) {
log('当前没有 guid,跳过 4155。');
return;
}
log('正在调用 4155 上报首次登录风控事件... deviceToken=guid');
const riskResult = await postJprx('/data/4155/forward', buildRiskAssessPayload(session), session);
if (!riskResult.success) {
log(`4155 调用失败: ${riskResult.message} (deviceToken=guid)`);
return;
}
log('4155 调用成功。deviceToken=guid');
}
function printApiKey(apiKey) {
process.stdout.write('\n');
log('apiKey 获取成功。');
process.stdout.write(`${apiKey}\n\n`);
process.stdout.write(
`curl 'https://mmgrcalltoken.3g.qq.com/aizone/v1/chat/completions' \\\n` +
` -H 'Authorization: Bearer ${apiKey}' \\\n` +
` -H 'Content-Type: application/json' \\\n` +
` -d '{\n` +
` "model": "modelroute",\n` +
` "messages": [\n` +
` { "role": "user", "content": "hi" }\n` +
` ],\n` +
` "max_tokens": 10000\n` +
` }'\n`
);
}
async function run() {
const session = {};
process.on('SIGINT', () => {
process.stdout.write('\n');
log('已中断。');
process.exit(130);
});
while (true) {
try {
const { uuid, qrPageUrl } = await fetchQrChallenge(session);
log(`guid=${session.guid}`);
log(`state=${session.state}`);
log(`扫码地址:${qrPageUrl}`);
log('如果终端里的二维码显示异常,请复制上面的地址到浏览器打开后扫码。');
log('请使用微信扫描下面的二维码:');
await printQrCode(uuid);
const code = await waitForWxCode(uuid);
await completeLogin(session, code);
const apiKey = await fetchApiKey(session);
await performRiskAssess(session);
printApiKey(apiKey);
return;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
log(message);
if (message.includes('二维码已过期')) {
log('正在重新生成二维码...');
continue;
}
process.exitCode = 1;
return;
}
}
}
run();