-
Notifications
You must be signed in to change notification settings - Fork 67
/
_bili.ts
366 lines (351 loc) · 10.2 KB
/
_bili.ts
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
//Next Type Begin
/**
* Make all properties in T optional
*/
type Partial<T> = {
[P in keyof T]?: T[P];
};
/**
* Object of `cookies` from header
*/
type cookies = Partial<{
[key: string]: string;
}>;
//Next Type End
import qs from "qs";
// 此项目无大数据hash需求,故不用wasm,还可保持edge-runtime兼容性
// import { md5 } from "hash-wasm";
import { md5 } from "js-md5";
import * as env from "../_config";
const loggerc = env.logger.child({ action: "调用组件(_bili)" });
const sorted = (params: { [x: string]: any }) => {
const map = new Map();
for (let k in params) {
map.set(k, params[k]);
}
const arr = Array.from(map).sort();
let obj = {};
for (let i in arr) {
let k = arr[i][0];
let value = arr[i][1];
obj[k] = value;
}
return obj;
};
/**
* Bilibili APP API 签名
* @param params JSON 原请求数据
* @param appkey 可不填
* @param appsec 可不填
*/
export const appsign = async (
params: any,
appkey = "1d8b6e7d45233436",
appsec = "560c52ccd288fed045859ed18bffd973"
/**
* 常用key:
* 783bbb7264451d82 / 2653583c8873dea268ab9386918b1d65 (Android)
* 1d8b6e7d45233436 / 560c52ccd288fed045859ed18bffd973 (IOS)
*/
) => {
params.appkey = appkey;
params = sorted(params);
const query = qs.stringify(params);
const sign = md5(query + appsec);
params.sign = sign;
const to_return = qs.stringify(params);
const log = loggerc.child({
module: "Bilibili APP API 签名",
});
log.info({});
log.debug({ context: to_return });
return to_return;
};
/**
* 生成CorrespondPath算法
*/
export const CorrespondPath = async () => {
const publicKey = await crypto.subtle.importKey(
"jwk",
{
kty: "RSA",
n: "y4HdjgJHBlbaBN04VERG4qNBIFHP6a3GozCl75AihQloSWCXC5HDNgyinEnhaQ_4-gaMud_GF50elYXLlCToR9se9Z8z433U3KjM-3Yx7ptKkmQNAMggQwAVKgq3zYAoidNEWuxpkY_mAitTSRLnsJW-NCTa0bqBFF6Wm1MxgfE",
e: "AQAB",
},
{ name: "RSA-OAEP", hash: "SHA-256" },
true,
["encrypt"]
);
async function getCorrespondPath(timestamp: number) {
const data = new TextEncoder().encode(`refresh_${timestamp}`);
const encrypted = new Uint8Array(
await crypto.subtle.encrypt({ name: "RSA-OAEP" }, publicKey, data)
);
return encrypted.reduce(
(str, c) => str + c.toString(16).padStart(2, "0"),
""
);
}
const ts = Date.now();
const to_return = await getCorrespondPath(ts);
const log = loggerc.child({
module: "Bilibili 生成CorrespondPath",
});
log.info({});
log.debug({ context: to_return });
return to_return;
};
/**
* 通过WEB端Cookies获取APP端access_key(IOS APPKEY)
* @param cookies WEB端Cookies
*/
export const cookies2access_key = async (cookies: {
SESSDATA: string;
DedeUserID: string;
bili_jct: string; //即`csrf token`
}) => {
const log = loggerc.child({
module: "通过WEB端Cookies获取APP端access_key(IOS APPKEY)",
});
if (!cookies.SESSDATA || !cookies.DedeUserID || !cookies.bili_jct) {
log.info({ status: "Failed: No cookies" });
return;
}
const auth_code = await fetch(
// 第三方登陆法失效,现使用TV登陆法(会产生登陆信息)
env.api.main.web.third_login + "/x/passport-tv-login/qrcode/auth_code",
{
method: "POST",
body: await appsign(
{ appkey: "783bbb7264451d82", local_id: 0, ts: Date.now() },
"783bbb7264451d82",
"2653583c8873dea268ab9386918b1d65"
),
headers: {
"User-Agent": env.UA,
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
// cookie: `DedeUserID=${cookies.DedeUserID}; SESSDATA=${cookies.SESSDATA}`,
},
}
)
.then((res) => res.json())
.then(
(res: {
code: number;
message: string;
ttl: number;
data?: {
url: string;
auth_code: string;
};
}) => {
if (res.code !== 0 || !res?.data?.auth_code) {
log.info({ status: "Failed: No auth_code" });
return;
}
return res.data.auth_code;
}
);
if (!auth_code) {
log.info({ status: "Failed: No auth_code" });
return;
}
return await fetch(
env.api.main.web.third_login + "/x/passport-tv-login/h5/qrcode/confirm",
{
method: "POST",
body: qs.stringify({ auth_code, build: 7082000, csrf: cookies.bili_jct }),
headers: {
"User-Agent": env.UA,
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
cookie: `DedeUserID=${cookies.DedeUserID}; SESSDATA=${cookies.SESSDATA}`,
},
}
).then(
async () =>
await fetch(
env.api.main.web.third_login + "/x/passport-tv-login/qrcode/poll",
{
method: "POST",
body: await appsign(
{
appkey: "783bbb7264451d82",
local_id: 0,
auth_code,
ts: Date.now(),
},
"783bbb7264451d82",
"2653583c8873dea268ab9386918b1d65"
),
headers: {
"User-Agent": env.UA,
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
},
}
)
.then((res) => res.json())
.then(
(res: {
code: number;
message: string;
ttl: number;
data?: {
access_token: string;
refresh_token: string;
expires_in: number;
};
}) => {
if (res.code !== 0 || !res?.data?.access_token) {
log.info({ status: "Failed: No access_token" });
return;
}
const to_return = res.data.access_token;
log.info({ status: "Success" });
log.debug({ context: to_return });
return to_return;
}
)
);
};
/**
* 通过access_key查询个人信息
* @param access_key Bilibili access key \
* 查询不到,返回为 无会员(0,0)
*/
export const access_key2info = async (access_key: string) => {
const log = loggerc.child({
module: "通过access_key查询个人信息",
});
return await fetch(
env.api.main.app.user_info +
"/x/v2/account/myinfo?" +
(await appsign({ access_key: access_key, ts: Date.now() })),
env.fetch_config_UA
)
.then((res) => res.json())
.then((res: { data?: any; code: number }) => {
let to_return = {
uid: 0,
vip_type: 0 as 0 | 1 | 2,
};
if (res.code === 0) {
const data = res.data;
to_return = {
uid: Number(data.mid),
vip_type: Number(data.vip.type) as 0 | 1 | 2, //TODO 没有加类型判断校验
};
}
log.info({});
log.debug({ context: to_return });
return to_return;
});
};
/**
* 通过含access_key及sign的Params查询个人信息
* @param params 字符串的params,如 ?access_key=xxx&sign=xxx \
* 查询不到,返回为 无会员(0,0)
*/
export const access_keyParams2info = async (params: string) => {
const log = loggerc.child({
module: "通过含access_key及sign的Params查询个人信息",
});
return await fetch(
env.api.main.app.user_info + "/x/v2/account/myinfo" + params,
env.fetch_config_UA
)
.then((res) => res.json())
.then((res: { data?: any; code: number }) => {
let to_return = {
uid: 0,
vip_type: 0 as 0 | 1 | 2,
};
if (res.code === 0) {
const data = res.data;
to_return = {
uid: Number(data.mid),
vip_type: Number(data.vip.type) as 0 | 1 | 2, //TODO 没有加类型判断校验
};
}
log.info({});
log.debug({ context: to_return });
return to_return;
});
};
/**
* 通过cookie查询mid/vip
* @param cookies Bilibili cookies \
* 查询不到,返回为 无会员(0,0)
*/
export const cookies2info = async (cookies: { SESSDATA: string }) => {
const log = loggerc.child({
module: "通过cookie查询mid/vip",
});
if (!cookies.SESSDATA) {
log.info({ status: "Failed" });
return;
}
return await fetch(env.api.main.web.user_info + "/x/vip/web/user/info?", {
headers: { "User-Agent": env.UA, cookie: "SESSDATA=" + cookies.SESSDATA },
})
.then((res) => res.json())
.then(
(res: { data?: { mid: number; vip_type: 0 | 1 | 2 }; code: number }) => {
let to_return = {
uid: 0,
vip_type: 0 as 0 | 1 | 2,
};
if (res.code === 0) {
const data = res.data;
to_return = {
uid: Number(data.mid),
vip_type: Number(data.vip_type) as 0 | 1 | 2, //TODO 没有加类型判断校验
};
}
log.info({});
log.debug({ context: to_return });
return to_return;
}
);
};
/**
* 获取Bilibili网页版Cookies \
* 默认:游客Cookies \
* @param link 欲获取Cookies之链接
*/
export const getCookies = async (uri = "https://www.bilibili.com/") => {
const log = loggerc.child({
module: "获取Bilibili网页版Cookies(游客)",
});
return await fetch(uri, env.fetch_config_UA)
.then((res) => {
//代码来源
/*本文作者: cylee'贝尔塔猫
本文链接: https://www.cnblogs.com/CyLee/p/16170228.html
关于博主: 评论和私信会在第一时间回复。或者直接私信我。
版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!*/
// 获取 cookie
const cookie = res.headers.get("set-cookie") || "";
// 清理一下 cookie 的格式,移除过期时间,只保留基础的键值对才能正常使用
const real_cookie = cookie
.replace(/(;?)( ?)expires=(.+?);\s/gi, "")
.replace(/(;?)( ?)path=\/(,?)(\s?)/gi, "")
.replace(
/(;?)( ?)domain=(.?)([a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?)/gi,
""
)
.replace(/,/gi, ";")
.trim();
const to_return = real_cookie;
log.info({});
log.debug({ context: to_return });
return to_return;
})
.catch((err) => console.error(err));
};
export const cookies2usable = (cookies: cookies) => {
let usable_cookies = "";
for (const [key, val] of Object.entries(cookies)) {
usable_cookies += key + "=" + val + ";";
}
return usable_cookies;
};