forked from qegj567-cloud/SullyOS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
2919 lines (2706 loc) · 132 KB
/
Copy pathindex.js
File metadata and controls
2919 lines (2706 loc) · 132 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const BRAVE_ENDPOINT = "https://api.search.brave.com/res/v1";
const FEISHU_BASE = "https://open.feishu.cn/open-apis";
const XHS_BASE = "https://edith.xiaohongshu.com";
const XHS_MEDIA_HOST_CANDIDATES = [
"https://edith.xiaohongshu.com",
"https://creator.xiaohongshu.com",
"https://www.xiaohongshu.com",
];
const XHS_PUBLISH_HOST_CANDIDATES = [
"https://edith.xiaohongshu.com",
"https://www.xiaohongshu.com",
];
function corsHeaders(origin) {
return {
"Access-Control-Allow-Origin": origin || "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization, Depth, X-Brave-API-Key, X-Notion-API-Key, X-Feishu-Token, X-Xhs-Cookie, X-Netease-Cookie, X-WebDAV-Method, X-WebDAV-Depth, X-WebDAV-Range, X-GitHub-Method, X-GitHub-Api-Version, Mcp-Session-Id, Accept, Range",
"Access-Control-Expose-Headers": "Mcp-Session-Id",
"Access-Control-Max-Age": "86400",
};
}
function jsonResponse(obj, { status = 200, origin } = {}) {
return new Response(JSON.stringify(obj), {
status,
headers: {
"Content-Type": "application/json; charset=utf-8",
...corsHeaders(origin),
},
});
}
// ---- /fetch-webpage 用: SSRF 防护 + body 大小上限 ----
// 网页分享代理只抓用户粘贴的公网网页, 拒绝 loopback / 私有网段 / link-local / 内网后缀。
function isUnsafeFetchTarget(parsed) {
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return true;
const host = parsed.hostname.toLowerCase().replace(/^\[|\]$/g, '');
if (host === 'localhost' || host.endsWith('.local') || host.endsWith('.internal')) return true;
if (host === '::1' || host === '0.0.0.0') return true;
const v4 = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
if (v4) {
const a = Number(v4[1]), b = Number(v4[2]);
if (a === 127 || a === 10 || a === 0) return true;
if (a === 192 && b === 168) return true;
if (a === 169 && b === 254) return true;
if (a === 172 && b >= 16 && b <= 31) return true;
}
// IPv6 唯一本地 (fc00::/7) / link-local (fe80::/10)
if (/^f[cd][0-9a-f]{2}:/i.test(host) || /^fe[89ab][0-9a-f]:/i.test(host)) return true;
return false;
}
// 读 Response body, 累加到 maxBytes 就停 (防超大页面打爆 worker)。
async function readBodyCapped(res, maxBytes) {
const reader = (res.body && res.body.getReader) ? res.body.getReader() : null;
if (!reader) return await res.text();
const chunks = [];
let total = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
if (value) {
total += value.length;
chunks.push(value);
if (total >= maxBytes) { try { await reader.cancel(); } catch (e) { /* ignore */ } break; }
}
}
const merged = new Uint8Array(total);
let offset = 0;
for (const c of chunks) { merged.set(c.subarray(0, total - offset), offset); offset += c.length; }
return new TextDecoder('utf-8', { fatal: false }).decode(merged);
}
function route(url) {
const p = url.pathname.replace(/\/+$/, "");
if (p === "" || p === "/") return { kind: "web" };
if (p === "/search") return { kind: "web" };
if (p === "/news") return { kind: "news" };
if (p === "/videos") return { kind: "videos" };
if (p === "/images") return { kind: "images" };
return null;
}
// ================================================================
// 小红书签名 — 基于 xhshow 逆向的真实算法
// 参考: https://github.com/Cloxl/xhshow
// ================================================================
// ---------- Pure-JS MD5 (RFC 1321) ----------
function md5(string) {
function md5cycle(x, k) {
let a = x[0], b = x[1], c = x[2], d = x[3];
a = ff(a, b, c, d, k[0], 7, -680876936); d = ff(d, a, b, c, k[1], 12, -389564586);
c = ff(c, d, a, b, k[2], 17, 606105819); b = ff(b, c, d, a, k[3], 22, -1044525330);
a = ff(a, b, c, d, k[4], 7, -176418897); d = ff(d, a, b, c, k[5], 12, 1200080426);
c = ff(c, d, a, b, k[6], 17, -1473231341); b = ff(b, c, d, a, k[7], 22, -45705983);
a = ff(a, b, c, d, k[8], 7, 1770035416); d = ff(d, a, b, c, k[9], 12, -1958414417);
c = ff(c, d, a, b, k[10], 17, -42063); b = ff(b, c, d, a, k[11], 22, -1990404162);
a = ff(a, b, c, d, k[12], 7, 1804603682); d = ff(d, a, b, c, k[13], 12, -40341101);
c = ff(c, d, a, b, k[14], 17, -1502002290); b = ff(b, c, d, a, k[15], 22, 1236535329);
a = gg(a, b, c, d, k[1], 5, -165796510); d = gg(d, a, b, c, k[6], 9, -1069501632);
c = gg(c, d, a, b, k[11], 14, 643717713); b = gg(b, c, d, a, k[0], 20, -373897302);
a = gg(a, b, c, d, k[5], 5, -701558691); d = gg(d, a, b, c, k[10], 9, 38016083);
c = gg(c, d, a, b, k[15], 14, -660478335); b = gg(b, c, d, a, k[4], 20, -405537848);
a = gg(a, b, c, d, k[9], 5, 568446438); d = gg(d, a, b, c, k[14], 9, -1019803690);
c = gg(c, d, a, b, k[3], 14, -187363961); b = gg(b, c, d, a, k[8], 20, 1163531501);
a = gg(a, b, c, d, k[13], 5, -1444681467); d = gg(d, a, b, c, k[2], 9, -51403784);
c = gg(c, d, a, b, k[7], 14, 1735328473); b = gg(b, c, d, a, k[12], 20, -1926607734);
a = hh(a, b, c, d, k[5], 4, -378558); d = hh(d, a, b, c, k[8], 11, -2022574463);
c = hh(c, d, a, b, k[11], 16, 1839030562); b = hh(b, c, d, a, k[14], 23, -35309556);
a = hh(a, b, c, d, k[1], 4, -1530992060); d = hh(d, a, b, c, k[4], 11, 1272893353);
c = hh(c, d, a, b, k[7], 16, -155497632); b = hh(b, c, d, a, k[10], 23, -1094730640);
a = hh(a, b, c, d, k[13], 4, 681279174); d = hh(d, a, b, c, k[0], 11, -358537222);
c = hh(c, d, a, b, k[3], 16, -722521979); b = hh(b, c, d, a, k[6], 23, 76029189);
a = hh(a, b, c, d, k[9], 4, -640364487); d = hh(d, a, b, c, k[12], 11, -421815835);
c = hh(c, d, a, b, k[15], 16, 530742520); b = hh(b, c, d, a, k[2], 23, -995338651);
a = ii(a, b, c, d, k[0], 6, -198630844); d = ii(d, a, b, c, k[7], 10, 1126891415);
c = ii(c, d, a, b, k[14], 15, -1416354905); b = ii(b, c, d, a, k[5], 21, -57434055);
a = ii(a, b, c, d, k[12], 6, 1700485571); d = ii(d, a, b, c, k[3], 10, -1894986606);
c = ii(c, d, a, b, k[10], 15, -1051523); b = ii(b, c, d, a, k[1], 21, -2054922799);
a = ii(a, b, c, d, k[8], 6, 1873313359); d = ii(d, a, b, c, k[15], 10, -30611744);
c = ii(c, d, a, b, k[6], 15, -1560198380); b = ii(b, c, d, a, k[13], 21, 1309151649);
a = ii(a, b, c, d, k[4], 6, -145523070); d = ii(d, a, b, c, k[11], 10, -1120210379);
c = ii(c, d, a, b, k[2], 15, 718787259); b = ii(b, c, d, a, k[9], 21, -343485551);
x[0] = add32(a, x[0]); x[1] = add32(b, x[1]); x[2] = add32(c, x[2]); x[3] = add32(d, x[3]);
}
function cmn(q, a, b, x, s, t) { a = add32(add32(a, q), add32(x, t)); return add32((a << s) | (a >>> (32 - s)), b); }
function ff(a, b, c, d, x, s, t) { return cmn((b & c) | ((~b) & d), a, b, x, s, t); }
function gg(a, b, c, d, x, s, t) { return cmn((b & d) | (c & (~d)), a, b, x, s, t); }
function hh(a, b, c, d, x, s, t) { return cmn(b ^ c ^ d, a, b, x, s, t); }
function ii(a, b, c, d, x, s, t) { return cmn(c ^ (b | (~d)), a, b, x, s, t); }
function add32(a, b) { return (a + b) & 0xFFFFFFFF; }
const encoder = new TextEncoder();
const bytes = encoder.encode(string);
let n = bytes.length;
let tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
let i;
for (i = 0; i < n; i++) tail[i >> 2] |= bytes[i] << ((i % 4) << 3);
// We need to handle longer strings properly
let state = [1732584193, -271733879, -1732584194, 271733878];
let nBlocks = ((n + 8) >> 6) + 1;
let totalLen = nBlocks * 64;
let buf = new Uint8Array(totalLen);
buf.set(bytes);
buf[n] = 0x80;
let dv = new DataView(buf.buffer);
dv.setUint32(totalLen - 8, (n * 8) & 0xFFFFFFFF, true);
dv.setUint32(totalLen - 4, Math.floor(n * 8 / 0x100000000), true);
for (let offset = 0; offset < totalLen; offset += 64) {
let k = [];
for (let j = 0; j < 16; j++) k[j] = dv.getUint32(offset + j * 4, true);
md5cycle(state, k);
}
const hex = [];
for (let si = 0; si < 4; si++) {
for (let bi = 0; bi < 4; bi++) {
hex.push(((state[si] >> (bi * 8)) & 0xFF).toString(16).padStart(2, '0'));
}
}
return hex.join('');
}
// ---------- Custom Base64 alphabets ----------
const STD_B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const CUSTOM_B64 = "ZmserbBoHQtNP+wOcza/LpngG8yJq42KWYj0DSfdikx3VT16IlUAFM97hECvuRX5";
const X3_B64 = "MfgqrsbcyzPQRStuvC7mn501HIJBo2DEFTKdeNOwxWXYZap89+/A4UVLhijkl63G";
function translateB64(input, fromAlpha, toAlpha) {
let out = "";
for (const ch of input) {
const idx = fromAlpha.indexOf(ch);
out += idx >= 0 ? toAlpha[idx] : ch;
}
return out;
}
function bytesToStdB64(bytes) {
return btoa(String.fromCharCode(...bytes));
}
function customB64Encode(bytes) {
return translateB64(bytesToStdB64(bytes), STD_B64, CUSTOM_B64);
}
function x3B64Encode(bytes) {
return translateB64(bytesToStdB64(bytes), STD_B64, X3_B64);
}
// ---------- 124-byte XOR key (from xhshow) ----------
const HEX_KEY = "71a302257793271ddd273bcee3e4b98d9d7935e1da33f5765e2ea8afb6dc77a51a499d23b67c20660025860cbf13d4540d92497f58686c574e508f46e1956344f39139bf4faf22a3eef120b79258145b2feb5193b6478669961298e79bedca646e1a693a926154a5a7a1bd1cf0dedb742f917a747a1e388b234f2277";
function hexToBytes(hex) {
const bytes = new Uint8Array(hex.length / 2);
for (let i = 0; i < hex.length; i += 2) bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
return bytes;
}
const XOR_KEY = hexToBytes(HEX_KEY);
// ---------- Constants ----------
const VERSION_BYTES = [119, 104, 96, 41];
const CHECKSUM_FIXED_TAIL = [249, 65, 103, 103, 201, 181, 131, 99, 94, 7, 68, 250, 132, 21];
function intToLE(val, len = 4) {
const arr = [];
for (let i = 0; i < len; i++) { arr.push(val & 0xFF); val = Math.floor(val / 256); }
return arr;
}
// Timestamp fingerprint with XOR key 41
function envFingerprintA(tsMs, xorKey) {
const buf = new ArrayBuffer(8);
const dv = new DataView(buf);
// Write as two 32-bit ints (little-endian) since BigInt may not be available everywhere
dv.setUint32(0, tsMs & 0xFFFFFFFF, true);
dv.setUint32(4, Math.floor(tsMs / 0x100000000) & 0xFFFFFFFF, true);
const data = new Uint8Array(buf);
const sum1 = (data[1] + data[2] + data[3] + data[4]) & 0xFF;
const sum2 = (data[5] + data[6] + data[7]) & 0xFF;
data[0] = (sum1 + sum2) & 0xFF;
for (let i = 0; i < data.length; i++) data[i] ^= xorKey;
return Array.from(data);
}
function envFingerprintB(tsMs) {
const buf = new ArrayBuffer(8);
const dv = new DataView(buf);
dv.setUint32(0, tsMs & 0xFFFFFFFF, true);
dv.setUint32(4, Math.floor(tsMs / 0x100000000) & 0xFFFFFFFF, true);
return Array.from(new Uint8Array(buf));
}
// ---------- Build the 124-byte payload ----------
function buildPayloadArray(md5Hex, a1Value, contentStr, timestampSec) {
const payload = [];
// [0-3] Version magic
payload.push(...VERSION_BYTES);
// [4-7] Random seed
const seed = new Uint8Array(4);
crypto.getRandomValues(seed);
payload.push(...seed);
const seedByte0 = seed[0];
// [8-15] Env fingerprint A
const tsMs = Math.floor(timestampSec * 1000);
payload.push(...envFingerprintA(tsMs, 41));
// [16-23] Env fingerprint B (offset timestamp)
const offset = Math.floor(Math.random() * 40) + 10;
payload.push(...envFingerprintB(Math.floor((timestampSec - offset) * 1000)));
// [24-27] sequence value
payload.push(...intToLE(Math.floor(Math.random() * 36) + 15));
// [28-31] window props length
payload.push(...intToLE(Math.floor(Math.random() * 301) + 900));
// [32-35] content string length
payload.push(...intToLE(contentStr.length));
// [36-43] First 8 bytes of MD5, XOR'd with seedByte0
const md5Bytes = hexToBytes(md5Hex);
for (let i = 0; i < 8; i++) payload.push(md5Bytes[i] ^ seedByte0);
// [44] a1 field length marker
payload.push(52);
// [45-96] a1 cookie value, padded/truncated to 52 bytes
const a1Bytes = new TextEncoder().encode(a1Value);
const a1Padded = new Uint8Array(52);
a1Padded.set(a1Bytes.slice(0, 52));
payload.push(...a1Padded);
// [97] app identifier length marker
payload.push(10);
// [98-107] "xhs-pc-web"
const appId = new TextEncoder().encode("xhs-pc-web");
const appPadded = new Uint8Array(10);
appPadded.set(appId.slice(0, 10));
payload.push(...appPadded);
// [108-109] fixed values
payload.push(1);
payload.push(1); // CHECKSUM_VERSION
// [110] seed XOR 115
payload.push(seedByte0 ^ 115);
// [111-124] fixed tail
payload.push(...CHECKSUM_FIXED_TAIL);
return new Uint8Array(payload);
}
// ---------- XOR transform ----------
function xorTransform(payload) {
const result = new Uint8Array(payload.length);
for (let i = 0; i < payload.length; i++) {
result[i] = i < XOR_KEY.length ? (payload[i] ^ XOR_KEY[i]) & 0xFF : payload[i] & 0xFF;
}
return result;
}
// ---------- CRC32 table for X-s-common ----------
const CRC32_TABLE = (() => {
const table = new Uint32Array(256);
for (let i = 0; i < 256; i++) {
let c = i;
for (let j = 0; j < 8; j++) {
c = (c & 1) ? ((0xEDB88320 ^ (c >>> 1)) >>> 0) : (c >>> 1);
}
table[i] = c >>> 0;
}
return table;
})();
// XHS variant of CRC32 — processes first 57 chars
function mrc(e) {
let o = 0xFFFFFFFF;
const len = Math.min(57, e.length);
for (let n = 0; n < len; n++) {
o = (CRC32_TABLE[(o & 255) ^ e.charCodeAt(n)] ^ (o >>> 8)) >>> 0;
}
return ((o ^ 0xFFFFFFFF) ^ 0xEDB88320) >>> 0;
}
// Generate X-s-common header value
function generateXsCommon(xs, xt, a1) {
const common = {
s0: 5, s1: "",
x0: "1", x1: "3.6.8", x2: "Windows",
x3: "xhs-pc-web", x4: "4.21.1",
x5: a1, x6: xt, x7: xs,
x8: "", x9: mrc(xt + xs), x10: 1
};
const jsonStr = JSON.stringify(common);
const encoded = encodeURIComponent(jsonStr);
const bytes = Array.from(encoded).map(c => c.charCodeAt(0));
return customB64Encode(bytes);
}
// ---------- Generate X-s and X-t ----------
function signXs(method, uri, a1Value, postBody = null) {
// Step 1: Build content string (POST 需要包含 body)
let content = uri;
if (method === "POST" && postBody) {
content = uri + JSON.stringify(postBody);
}
// Step 2: MD5
const md5Hex = md5(content);
// Step 3: Build 124-byte payload
const timestamp = Date.now() / 1000;
const payloadArray = buildPayloadArray(md5Hex, a1Value, content, timestamp);
// Step 4: XOR transform
const xorResult = xorTransform(payloadArray);
// Step 5: Custom Base64 → x3
const x3Sig = x3B64Encode(Array.from(xorResult.slice(0, 124)));
// Step 6: Signature data JSON
const sigData = {
x0: "4.2.6",
x1: "xhs-pc-web",
x2: "Windows",
x3: "mns0301_" + x3Sig,
x4: ""
};
// Step 7: Encode entire JSON with custom Base64
const jsonStr = JSON.stringify(sigData);
const jsonBytes = Array.from(new TextEncoder().encode(jsonStr));
// Step 8: Final x-s
const xs = "XYS_" + customB64Encode(jsonBytes);
const xt = String(Math.floor(timestamp * 1000));
return { xs, xt };
}
// ---------- Cookie parser ----------
function getCookieValue(cookieStr, key) {
const match = cookieStr.match(new RegExp(`(?:^|;\\s*)${key}=([^;]*)`));
return match ? match[1] : '';
}
// ---------- XHS API fetch ----------
// options: { baseUrl, origin, referer }
function xhsFetch(cookie, api, method = 'GET', body = null, options = {}) {
const a1 = getCookieValue(cookie, 'a1');
if (!a1) {
return Promise.resolve({ ok: false, status: 401, data: { success: false, message: 'Cookie 中缺少 a1' } });
}
const { xs, xt } = signXs(method, api, a1, body);
const xsCommon = generateXsCommon(xs, xt, a1);
const originHost = options.origin || 'https://www.xiaohongshu.com';
const refererUrl = options.referer || (originHost + '/');
const headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
'Accept': 'application/json, text/plain, */*',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'Cookie': cookie,
'Origin': originHost,
'Referer': refererUrl,
'X-s': xs,
'X-t': xt,
'X-s-common': xsCommon,
'X-b3-traceid': crypto.randomUUID().replace(/-/g, '').slice(0, 16),
};
const fetchOptions = { method, headers };
if (method === 'POST' || method === 'PUT') {
headers['Content-Type'] = 'application/json;charset=UTF-8';
if (body) fetchOptions.body = JSON.stringify(body);
}
const baseUrl = options.baseUrl || XHS_BASE;
const url = `${baseUrl}${api}`;
return fetch(url, fetchOptions).then(async (res) => {
const text = await res.text();
let data;
try { data = JSON.parse(text); } catch { data = { raw: text }; }
return { ok: res.ok, status: res.status, data };
});
}
// ---------- XHS 图片上传 ----------
// 生成一个最小的有效 PNG 图片 (1080x1080 纯色)
function generateMinimalPNG() {
// 生成一张 1x1 的深紫色 PNG,小红书会自动拉伸
// PNG signature + IHDR + IDAT + IEND
const signature = [137, 80, 78, 71, 13, 10, 26, 10];
// IHDR: 1x1, 8-bit RGB
const ihdr = [
0, 0, 0, 13, // chunk length
73, 72, 68, 82, // "IHDR"
0, 0, 0, 1, // width = 1
0, 0, 0, 1, // height = 1
8, 2, // 8-bit RGB
0, 0, 0, // compression, filter, interlace
// CRC32 of IHDR
0x1E, 0x93, 0x09, 0x36
];
// IDAT: deflated [filter_none(0), R, G, B] = [0, 88, 28, 120] (dark purple)
// Raw deflate of [0, 88, 28, 120]: use stored block
const rawData = new Uint8Array([0, 88, 28, 120]); // filter=0, R=88, G=28, B=120
// Zlib: CMF=0x78, FLG=0x01 (no dict, low compression)
// Stored block: BFINAL=1, BTYPE=00, LEN=4, NLEN=0xFFFB, data, Adler32
const adler = adler32(rawData);
const idat_data = new Uint8Array([
0x78, 0x01, // zlib header
0x01, // BFINAL=1, BTYPE=00 (stored)
0x04, 0x00, 0xFB, 0xFF, // LEN=4, NLEN=~4
...rawData,
(adler >> 24) & 0xFF, (adler >> 16) & 0xFF, (adler >> 8) & 0xFF, adler & 0xFF
]);
const idat_crc = crc32Bytes([73, 68, 65, 84, ...idat_data]);
const idat = [
(idat_data.length >> 24) & 0xFF, (idat_data.length >> 16) & 0xFF,
(idat_data.length >> 8) & 0xFF, idat_data.length & 0xFF,
73, 68, 65, 84, // "IDAT"
...idat_data,
(idat_crc >> 24) & 0xFF, (idat_crc >> 16) & 0xFF, (idat_crc >> 8) & 0xFF, idat_crc & 0xFF
];
// IEND
const iend = [0, 0, 0, 0, 73, 69, 78, 68, 0xAE, 0x42, 0x60, 0x82];
return new Uint8Array([...signature, ...ihdr, ...idat, ...iend]);
}
function adler32(data) {
let a = 1, b = 0;
for (let i = 0; i < data.length; i++) {
a = (a + data[i]) % 65521;
b = (b + a) % 65521;
}
return ((b << 16) | a) >>> 0;
}
function crc32Bytes(data) {
let crc = 0xFFFFFFFF;
for (let i = 0; i < data.length; i++) {
crc = (CRC32_TABLE[(crc & 0xFF) ^ data[i]] ^ (crc >>> 8)) >>> 0;
}
return (crc ^ 0xFFFFFFFF) >>> 0;
}
// 获取 XHS 上传凭证
// ReaJason/xhs 使用 GET edith.xiaohongshu.com/api/media/v1/upload/web/permit?...
// 真实浏览器发布时 Origin 为 creator.xiaohongshu.com
async function getUploadCredentials(cookie, count = 1) {
const params = { biz_name: 'spectrum', scene: 'image', file_count: count, version: '1', source: 'web' };
const qs = Object.entries(params).map(([k, v]) => `${k}=${v}`).join('&');
const getApi = `/api/media/v1/upload/web/permit?${qs}`;
const attempts = [];
// 组合: host × origin,优先匹配 ReaJason 库 (edith + 无特殊 origin)
const originCombos = [
{}, // 默认 www.xiaohongshu.com
{ origin: 'https://creator.xiaohongshu.com', referer: 'https://creator.xiaohongshu.com/' },
];
for (const baseUrl of XHS_MEDIA_HOST_CANDIDATES) {
for (const originOpt of originCombos) {
const result = await xhsFetch(cookie, getApi, 'GET', null, { baseUrl, ...originOpt });
attempts.push({
baseUrl,
origin: originOpt.origin || 'default',
method: 'GET',
status: result.status,
ok: result.ok,
raw: JSON.stringify(result.data).slice(0, 240),
});
if (result.ok && result.data?.data?.uploadTempPermits) {
return { ...result, debug: { baseUrl, method: 'GET', origin: originOpt.origin || 'default', attempts } };
}
}
}
return {
ok: false,
status: 502,
data: { message: '所有候选 host + origin 的上传凭证接口均失败' },
debug: { attempts }
};
}
// 上传图片字节到 XHS (ros-upload CDN)
async function uploadBytesToXhs(cookie, imgBytes, contentType = 'image/png') {
// Step 1: 获取上传凭证
const result = await getUploadCredentials(cookie);
// 响应格式: { data: { uploadTempPermits: [{ fileIds: [...], token: "..." }] } }
// 或者: { uploadTempPermits: [...] }
const permitRoot = result.data?.data || result.data;
const tempPermit = permitRoot?.uploadTempPermits?.[0];
if (!tempPermit?.fileIds?.[0] || !tempPermit?.token) {
return {
error: '获取上传凭证失败',
debug: {
raw: JSON.stringify(result.data).slice(0, 500),
attempts: result.debug?.attempts || []
}
};
}
const fileId = tempPermit.fileIds[0];
const token = tempPermit.token;
// Step 2: PUT 上传到 ros-upload CDN
const uploadUrl = `https://ros-upload.xiaohongshu.com/${fileId}`;
const uploadRes = await fetch(uploadUrl, {
method: 'PUT',
headers: {
'X-Cos-Security-Token': token,
'Content-Type': contentType,
},
body: imgBytes
});
if (uploadRes.ok) {
return { file_id: fileId };
}
const uploadText = await uploadRes.text().catch(() => '');
return {
error: `CDN上传失败: ${uploadRes.status}`,
debug: { fileId, response: uploadText.slice(0, 300) }
};
}
// 上传图片到 XHS (通过 image_url 下载后上传)
async function uploadImageToXhs(cookie, imageUrl) {
try {
const imgRes = await fetch(imageUrl);
if (!imgRes.ok) return { error: `下载图片失败: ${imgRes.status}`, debug: { url: imageUrl } };
const imgBytes = new Uint8Array(await imgRes.arrayBuffer());
const ct = imgRes.headers.get('content-type') || 'image/jpeg';
return await uploadBytesToXhs(cookie, imgBytes, ct);
} catch (e) {
return { error: `图片上传异常: ${e.message}` };
}
}
// 上传占位图到 XHS
async function uploadPlaceholderImage(cookie) {
try {
const pngData = generateMinimalPNG();
return await uploadBytesToXhs(cookie, pngData, 'image/png');
} catch (e) {
return { error: `占位图上传异常: ${e.message}` };
}
}
// ================================================================
// 网易云音乐代理 — 转发到用户自部署的 api-enhanced
// api-enhanced: https://github.com/NeteaseCloudMusicApiEnhanced/api-enhanced
// 一键部署到 Vercel, 得到一个类似 https://xxx.vercel.app 的地址后填到下面
// ================================================================
//
// ⚠️ 多上游 —— 可以填 N 个 api-enhanced 部署地址, Worker 会随机挑选 + 自动容灾。
// 推荐组合:
// 1) Vercel (主) — 你现有的这个
// 2) Deno Deploy (备) — 免费 100w req/天, 国外走这个最快
// 3) 另一个 Vercel 账号的二部署 — 双倍配额
// 见 notes/music-scaling.md 部署教程。
const NETEASE_UPSTREAMS = [
"https://api-enhanced-ochre-kappa.vercel.app",
// "https://sully-music.deno.dev", // ← 部署 Deno Deploy 后把 URL 粘贴到这里
// "https://api-enhanced-mirror.vercel.app", // ← 部署第二个 Vercel 后把 URL 粘贴到这里
];
// 国内 IP 伪装, 部分接口需要 realIP 参数才会返回内地版权数据
const NETEASE_REAL_IP = "116.25.146.177";
// ========== 边缘缓存 TTL 配置 ==========
// 单位: 秒。0 或未列出的 action 不缓存(登录/用户数据等)。
// 命中缓存 → 不打上游, 零成本。Cloudflare 免费 KV-like 缓存, 每 PoP 独立。
const NETEASE_CACHE_TTL = {
// 长期稳定 — 激进缓存
'lyric': 30 * 24 * 3600, // 30天 (歌词几乎不变)
'lyric/new': 30 * 24 * 3600,
'song/detail': 3600, // 1小时
'album': 1800, // 30分
'artists': 1800,
'artist/songs': 1800,
'mv/detail': 1800,
// 中期
'search': 600, // 10分
'search/hot': 1800,
'search/hot/detail': 1800,
'search/default': 600,
'toplist': 600,
'toplist/detail': 600,
'top/playlist': 600,
'playlist/detail': 600,
'playlist/track/all': 600,
'banner': 1800,
'personalized': 1800,
'personalized/newsong': 1800,
'comment/music': 300, // 5分
// 短期 — 签名链接有效期短
'song/url': 180, // 3分 (URL 5分钟过期, 留余量)
'mv/url': 180,
// 用户专属: 不出现在本表 = 不缓存
// login/*, captcha/*, user/*, likelist, like, logout,
// recommend/songs, personal_fm, daily_signin, check/music
};
// 已知 action → 真实上游路径的特例映射(大多数 api-enhanced 路径和 action 同名,
// 下面只处理名字不同 / 有特殊参数的那几个)。
const NETEASE_ACTION_REWRITE = {
"search": "/cloudsearch", // 用 cloudsearch 返回更完整的字段
"song/url": "/song/url/v1",
"user/detail": "/user/detail",
"user/playlist": "/user/playlist",
"user/record": "/user/record",
"user/cloud": "/user/cloud",
"user/subcount": "/user/subcount",
"likelist": "/likelist",
"like": "/like",
"playlist/detail": "/playlist/detail",
"playlist/track/all": "/playlist/track/all",
"personal_fm": "/personal_fm",
"recommend/songs": "/recommend/songs",
"recommend/resource": "/recommend/resource",
"daily_signin": "/daily_signin",
"toplist": "/toplist",
"toplist/detail": "/toplist/detail",
"top/playlist": "/top/playlist",
"personalized": "/personalized",
"personalized/newsong": "/personalized/newsong",
"banner": "/banner",
"login/status": "/login/status",
"login/cellphone": "/login/cellphone",
"login/qr/key": "/login/qr/key",
"login/qr/create": "/login/qr/create",
"login/qr/check": "/login/qr/check",
"captcha/sent": "/captcha/sent",
"captcha/verify": "/captcha/verify",
"logout": "/logout",
"song/detail": "/song/detail",
"lyric": "/lyric",
"lyric/new": "/lyric/new",
"comment/music": "/comment/music",
"album": "/album",
"artists": "/artists",
"artist/songs": "/artist/songs",
"mv/detail": "/mv/detail",
"mv/url": "/mv/url",
};
// action 白名单 — 只允许 api-enhanced 已知的安全接口(防止被当成开放代理)
const NETEASE_ACTION_ALLOWED = new Set([
...Object.keys(NETEASE_ACTION_REWRITE),
"song/url",
"search/suggest",
"search/hot",
"search/hot/detail",
"search/default",
"check/music",
]);
function buildNeteaseUpstream(action, body, cookie) {
if (!NETEASE_ACTION_ALLOWED.has(action)) return null;
const p = new URLSearchParams();
if (cookie && cookie.trim()) p.set("cookie", cookie.trim());
p.set("realIP", NETEASE_REAL_IP);
// cache-buster, 避免 Vercel 边缘缓存干扰登录态
p.set("timestamp", Date.now().toString());
// Special-case 几个需要重命名 / 默认值的字段
if (action === "search") {
p.set("keywords", body.keyword || body.keywords || "");
p.set("type", String(body.type || 1));
p.set("limit", String(body.limit || 30));
p.set("offset", String(body.offset || 0));
} else if (action === "song/url") {
const ids = Array.isArray(body.ids) ? body.ids : (body.id != null ? [body.id] : []);
if (ids.length) p.set("id", ids.join(","));
p.set("level", body.level || "exhigh");
} else if (action === "song/detail") {
const ids = Array.isArray(body.ids) ? body.ids : (body.id != null ? [body.id] : []);
if (ids.length) p.set("ids", ids.join(","));
} else if (action === "user/playlist") {
if (body.uid != null) p.set("uid", String(body.uid));
p.set("limit", String(body.limit || 30));
p.set("offset", String(body.offset || 0));
} else if (action === "user/record") {
if (body.uid != null) p.set("uid", String(body.uid));
p.set("type", String(body.type ?? 1)); // 0: 全部, 1: 最近一周
} else if (action === "user/cloud") {
p.set("limit", String(body.limit || 30));
p.set("offset", String(body.offset || 0));
} else {
// 通用:所有其余参数直接透传(字符串化)
for (const [k, v] of Object.entries(body || {})) {
if (v == null) continue;
if (Array.isArray(v)) p.set(k, v.join(","));
else p.set(k, String(v));
}
}
const upstream = NETEASE_ACTION_REWRITE[action] || `/${action}`;
return `${upstream}?${p}`;
}
// ========== 缓存 Key 构造 ==========
// 使用"虚拟" URL 作为 Cache API 的 key。只包含业务参数(action + 过滤后的 body),
// 故意剔除 cookie / realIP / timestamp / level(cookie 桶代替) 等不稳定参数。
// 这样同一个 action 的相同查询跨 PoP / 多上游 都能命中同一个缓存条目。
function buildCacheKey(action, body, cookieBucket) {
const p = new URLSearchParams();
const skip = new Set(['timestamp', 'realIP', 'cookie', '_']);
for (const [k, v] of Object.entries(body || {})) {
if (v == null || skip.has(k)) continue;
if (Array.isArray(v)) p.set(k, v.join(","));
else p.set(k, String(v));
}
// 排序保证确定性 (对象顺序 / 用户输入顺序不同也能命中同一 key)
const sorted = [...p.entries()].sort(([a], [b]) => a.localeCompare(b));
const qs = sorted.map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join('&');
return new Request(
`https://sully-netease-cache.internal/${action}/${cookieBucket}?${qs}`,
{ method: 'GET' }
);
}
// ========== 多上游 fetch 带失败转移 ==========
// 从 NETEASE_UPSTREAMS 随机打乱, 依次尝试, 任何一个成功(HTTP 2xx + code!=-460)就返回。
// 自动屏蔽被网易风控的上游 (HTTP 200 但 body 里 code=-460 / -7 = 被限流)。
function shuffleCopy(arr) {
const a = [...arr];
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
async function fetchFromAnyUpstream(upstreamPath, timeoutMs = 8000) {
const order = shuffleCopy(NETEASE_UPSTREAMS);
const errors = [];
for (const base of order) {
const upstreamUrl = base.replace(/\/+$/, '') + upstreamPath;
try {
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), timeoutMs);
const res = await fetch(upstreamUrl, {
method: "GET",
headers: { "Accept": "application/json" },
signal: ctrl.signal,
});
clearTimeout(t);
const text = await res.text();
// HTTP 层挂了直接换下一个
if (!res.ok) {
errors.push(`${new URL(base).host} HTTP ${res.status}`);
continue;
}
// 应用层风控: 尝试识别 -460/-7 等明显失败码, 这种情况下换个上游可能成功
let shouldFailover = false;
try {
const j = JSON.parse(text);
if (j?.code === -460 || j?.code === -7) shouldFailover = true;
} catch { /* 不是 JSON, 当成功处理 */ }
if (shouldFailover && order.length > 1) {
errors.push(`${new URL(base).host} risk-control (code=-460/-7)`);
continue;
}
return { text, status: res.status, upstream: new URL(base).host, error: null };
} catch (e) {
errors.push(`${new URL(base).host} ${e.name === 'AbortError' ? 'timeout' : e.message}`);
}
}
return { text: '', status: 502, upstream: '', error: errors.join(' | ') };
}
// ================================================================
// XHS Lite —— 验证过的纯算签名 + web API 封装(隔离在 IIFE 内,
// 不与上面旧的 /xhs/ 签名实现冲突)。对外暴露 /api/<command> 桥接契约,
// 与 scripts/xhs-bridge.mjs 完全兼容,前端 bridge 模式直接复用。
//
// 签名移植自 Cloxl/xhshow (MIT),已与 Python 原版逐字节比对验证
// (见 worker/xhs-lite/test/)。cookie 经 X-Xhs-Cookie 头按请求传入。
// ================================================================
const XHSLite = (() => {
const STANDARD_B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
const CUSTOM_B64 = 'ZmserbBoHQtNP+wOcza/LpngG8yJq42KWYj0DSfdikx3VT16IlUAFM97hECvuRX5';
const X3_B64 = 'MfgqrsbcyzPQRStuvC7mn501HIJBo2DEFTKdeNOwxWXYZap89+/A4UVLhijkl63G';
const HEX_KEY =
'71a302257793271ddd273bcee3e4b98d9d7935e1da33f5765e2ea8afb6dc77a5' +
'1a499d23b67c20660025860cbf13d4540d92497f58686c574e508f46e1956344' +
'f39139bf4faf22a3eef120b79258145b2feb5193b6478669961298e79bedca64' +
'6e1a693a926154a5a7a1bd1cf0dedb742f917a747a1e388b234f2277516db711' +
'6035439730fa61e9822a0eca7bff72d8';
const VERSION_BYTES = [121, 104, 96, 41];
const PAYLOAD_LENGTH = 144, A1_LENGTH = 52, APP_ID_LENGTH = 10;
const A3_PREFIX = [2, 97, 51, 16];
const ENV_TABLE = [115, 248, 83, 102, 103, 201, 181, 131, 99, 94, 4, 68, 250, 132, 21];
const ENV_CHECKS_DEFAULT = [0, 1, 18, 1, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0];
const HASH_IV = [1831565813, 461845907, 2246822507, 3266489909];
const X3_PREFIX = 'mns0301_', XYS_PREFIX = 'XYS_', B1_SECRET_KEY = 'xhswebmplfbt';
const SIGNATURE_DATA_TEMPLATE = { x0: '4.2.6', x1: 'xhs-pc-web', x2: 'Windows', x3: '', x4: '' };
const SIGNATURE_XSCOMMON_TEMPLATE = {
s0: 5, s1: '', x0: '1', x1: '4.2.6', x2: 'Windows', x3: 'xhs-pc-web', x4: '4.86.0',
x5: '', x6: '', x7: '', x8: '', x9: -596800761, x10: 0, x11: 'normal',
};
const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0';
const IMG_FORMATS = ['jpg', 'webp', 'avif'];
const EDITH = 'https://edith.xiaohongshu.com', CREATOR = 'https://creator.xiaohongshu.com', WWW = 'https://www.xiaohongshu.com';
const RNG = {
randint(a, b) { return a + Math.floor(Math.random() * (b - a + 1)); },
randbytes(n) { const o = new Uint8Array(n); crypto.getRandomValues(o); return o; },
};
const u32 = (v) => v >>> 0;
const rotl = (v, n) => u32((v << n) | (v >>> (32 - n)));
const utf8 = (s) => new TextEncoder().encode(s);
function intToLeBytes(val, length = 4) {
const arr = []; let v = val;
for (let i = 0; i < length; i++) { arr.push(v & 0xff); v = Math.floor(v / 256); }
return arr;
}
function hexToBytes(hex) {
const out = [];
for (let i = 0; i < hex.length; i += 2) out.push(parseInt(hex.slice(i, i + 2), 16));
return out;
}
function md5Hex(bytes) {
if (typeof bytes === 'string') bytes = utf8(bytes);
const s = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21];
const K = [];
for (let i = 0; i < 64; i++) K[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296) >>> 0;
const ml = bytes.length * 8;
const withOne = bytes.length + 1;
const padLen = ((withOne + 8 + 63) & ~63) - withOne - 8;
const total = bytes.length + 1 + padLen + 8;
const msg = new Uint8Array(total);
msg.set(bytes); msg[bytes.length] = 0x80;
const lenLo = ml >>> 0, lenHi = Math.floor(ml / 4294967296) >>> 0;
for (let i = 0; i < 4; i++) msg[total - 8 + i] = (lenLo >>> (8 * i)) & 0xff;
for (let i = 0; i < 4; i++) msg[total - 4 + i] = (lenHi >>> (8 * i)) & 0xff;
let a0 = 0x67452301, b0 = 0xefcdab89, c0 = 0x98badcfe, d0 = 0x10325476;
for (let off = 0; off < total; off += 64) {
const M = new Array(16);
for (let i = 0; i < 16; i++) {
M[i] = ((msg[off + i * 4]) | (msg[off + i * 4 + 1] << 8) | (msg[off + i * 4 + 2] << 16) | (msg[off + i * 4 + 3] << 24)) >>> 0;
}
let A = a0, B = b0, C = c0, D = d0;
for (let i = 0; i < 64; i++) {
let F, g;
if (i < 16) { F = (B & C) | (~B & D); g = i; }
else if (i < 32) { F = (D & B) | (~D & C); g = (5 * i + 1) % 16; }
else if (i < 48) { F = B ^ C ^ D; g = (3 * i + 5) % 16; }
else { F = C ^ (B | (~D >>> 0)); g = (7 * i) % 16; }
F = (F + A + K[i] + M[g]) >>> 0;
A = D; D = C; C = B; B = (B + rotl(F, s[i])) >>> 0;
}
a0 = (a0 + A) >>> 0; b0 = (b0 + B) >>> 0; c0 = (c0 + C) >>> 0; d0 = (d0 + D) >>> 0;
}
const toHex = (n) => { let h = ''; for (let i = 0; i < 4; i++) h += ((n >>> (8 * i)) & 0xff).toString(16).padStart(2, '0'); return h; };
return toHex(a0) + toHex(b0) + toHex(c0) + toHex(d0);
}
function bytesToStdB64(bytes) {
let out = ''; const n = bytes.length;
for (let i = 0; i < n; i += 3) {
const b0 = bytes[i], b1 = i + 1 < n ? bytes[i + 1] : 0, b2 = i + 2 < n ? bytes[i + 2] : 0;
out += STANDARD_B64[b0 >> 2];
out += STANDARD_B64[((b0 & 3) << 4) | (b1 >> 4)];
out += i + 1 < n ? STANDARD_B64[((b1 & 15) << 2) | (b2 >> 6)] : '=';
out += i + 2 < n ? STANDARD_B64[b2 & 63] : '=';
}
return out;
}
function translateAlphabet(str, to) {
let out = '';
for (const ch of str) { const idx = STANDARD_B64.indexOf(ch); out += idx === -1 ? ch : to[idx]; }
return out;
}
const encodeCustom = (bytes) => translateAlphabet(bytesToStdB64(bytes), CUSTOM_B64);
const encodeX3 = (bytes) => translateAlphabet(bytesToStdB64(bytes), X3_B64);
const encodeCustomStr = (str) => encodeCustom(utf8(str));
const CRC_POLY = 0xedb88320;
let CRC_TABLE = null;
function crcTable() {
if (CRC_TABLE) return CRC_TABLE;
CRC_TABLE = new Uint32Array(256);
for (let d = 0; d < 256; d++) { let r = d; for (let k = 0; k < 8; k++) r = (r & 1) ? ((r >>> 1) ^ CRC_POLY) : (r >>> 1); CRC_TABLE[d] = r >>> 0; }
return CRC_TABLE;
}
function crc32JsInt(str) {
const tbl = crcTable(); let c = 0xffffffff;
for (let i = 0; i < str.length; i++) { const b = str.charCodeAt(i) & 0xff; c = (tbl[(c ^ b) & 0xff] ^ (c >>> 8)) >>> 0; }
const v = ((0xffffffff ^ c) ^ CRC_POLY) >>> 0;
return v & 0x80000000 ? v - 0x100000000 : v;
}
function rc4(keyBytes, dataBytes) {
const S = new Uint8Array(256);
for (let i = 0; i < 256; i++) S[i] = i;
let j = 0;
for (let i = 0; i < 256; i++) { j = (j + S[i] + keyBytes[i % keyBytes.length]) & 0xff; const t = S[i]; S[i] = S[j]; S[j] = t; }
const out = new Uint8Array(dataBytes.length);
let a = 0, b = 0;
for (let k = 0; k < dataBytes.length; k++) {
a = (a + 1) & 0xff; b = (b + S[a]) & 0xff;
const t = S[a]; S[a] = S[b]; S[b] = t;
out[k] = dataBytes[k] ^ S[(S[a] + S[b]) & 0xff];
}
return out;
}
function customHashV2(inputBytes) {
let [s0, s1, s2, s3] = HASH_IV;
const length = inputBytes.length;
s0 = u32(s0 ^ length); s1 = u32(s1 ^ u32(length << 8)); s2 = u32(s2 ^ u32(length << 16)); s3 = u32(s3 ^ u32(length << 24));
const dv = new DataView(new Uint8Array(inputBytes).buffer);
for (let i = 0; i < Math.floor(length / 8); i++) {
const v0 = dv.getUint32(i * 8, true), v1 = dv.getUint32(i * 8 + 4, true);
s0 = rotl(u32(u32(s0 + v0) ^ s2), 7);
s1 = rotl(u32(u32(v0 ^ s1) + s3), 11);
s2 = rotl(u32(u32(s2 + v1) ^ s0), 13);
s3 = rotl(u32(u32(s3 ^ v1) + s1), 17);
}
const t0 = u32(s0 ^ length), t1 = u32(s1 ^ t0), t2 = u32(s2 + t1), t3 = u32(s3 ^ t2);
const r0 = rotl(t0, 9), r1 = rotl(t1, 13), r2 = rotl(t2, 17), r3 = rotl(t3, 19);
s0 = u32(r0 + r2); s1 = u32(r1 ^ r3); s2 = u32(r2 + s0); s3 = u32(r3 ^ s1);
const result = [];
for (const s of [s0, s1, s2, s3]) result.push(...intToLeBytes(s, 4));
return result;
}
function pyQuote(value, safeExtra) {
const keep = new Set();
const always = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.-~';
for (const c of always) keep.add(c);
for (const c of safeExtra) keep.add(c);
let out = '';
for (const byte of utf8(value)) {
const ch = String.fromCharCode(byte);