@vicyangorg/dsh-music 0.6.0 → 0.8.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.
@@ -0,0 +1,521 @@
1
+ /**
2
+ * QQ 扫码登录(QQ 音乐网页版同款链路,只读、不写账号):
3
+ * xlogin 页面 cookie → ssl/ptqrshow(二维码图 + qrsig)→ ssl/ptqrlogin 轮询(66 未扫 / 67 已扫待确认 / 65 失效 / 0 成功)
4
+ * → 成功后沿 check_sig → graph login_jump → authorize 跳转到 y.qq.com/portal/wx_redirect.html 拿到 OAuth code
5
+ * → musicu.fcg QQConnectLogin.LoginServer.QQLogin { code } 换登录态(qm_keyst / qqmusic_key + uin)。
6
+ * 与 y.qq.com/portal/wx_redirect.html 内联脚本(login_type=1 分支)一致;零外部依赖,仅 node: 内置模块。
7
+ * 中间产物(qrsig、p_skey 等 QQ 登录 cookie)只留在内存会话里,换到音乐登录态后即丢弃,不落盘、不进日志。
8
+ */
9
+ import { inflateSync } from 'node:zlib'
10
+ import { QQ_UA } from './qqmusic.js'
11
+
12
+ const PT_HOST = 'https://xui.ptlogin2.qq.com'
13
+ const PT_APPID = '716027609' // QQ 音乐网页版在 QQ 互联里使用的 ptlogin appid
14
+ const PT_DAID = '383'
15
+ const QQ_CLIENT_ID = '100497308' // QQ 音乐的 QQ 互联 client_id(pt_3rd_aid)
16
+ const S_URL = 'https://graph.qq.com/oauth2.0/login_jump'
17
+ const PTUI_VERSION = '26111016' // xlogin 页面下发的 ptui_version(2026-11)
18
+ const WX_REDIRECT = 'https://y.qq.com/portal/wx_redirect.html?login_type=1&surl=https%3A%2F%2Fy.qq.com%2F'
19
+ const AUTHORIZE_URL = 'https://graph.qq.com/oauth2.0/authorize'
20
+ /* QQ 音乐登录页(y.qq.com)用的授权页参数:authorize?which=Login&display=pc&response_type=code&redirect_uri=…&client_id=…&state=state(无 scope) */
21
+ const AUTHORIZE_PAGE = `https://graph.qq.com/oauth2.0/show?which=Login&display=pc&response_type=code&redirect_uri=${encodeURIComponent(WX_REDIRECT)}&client_id=${QQ_CLIENT_ID}&state=state`
22
+ /* 授权页表单里的 redirect_uri = 页面参数 decodeURIComponent 后的值(抓包:surl 是完全解码的 https://y.qq.com/),不能多编一层 */
23
+ const REDIRECT_URI_PLAIN = 'https://y.qq.com/portal/wx_redirect.html?login_type=1&surl=https://y.qq.com/'
24
+ /* 授权表单是浏览器顶层导航提交的:带上导航类请求头,和真实流量一致 */
25
+ const NAV_HEADERS = {
26
+ Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
27
+ 'Sec-Fetch-Site': 'same-origin', 'Sec-Fetch-Mode': 'navigate', 'Sec-Fetch-Dest': 'document', 'Sec-Fetch-User': '?1',
28
+ 'Upgrade-Insecure-Requests': '1',
29
+ }
30
+ const XLOGIN = `${PT_HOST}/cgi-bin/xlogin?appid=${PT_APPID}&daid=${PT_DAID}&style=33&login_text=%E7%99%BB%E5%BD%95&hide_title_bar=1&hide_border=1&target=self&s_url=${encodeURIComponent(S_URL)}&pt_3rd_aid=${QQ_CLIENT_ID}&theme=2&hide_close_icon=1&hide_title_bar=1`
31
+ const COOKIE_FIELDS = ['uin', 'qqmusic_uin', 'wxuin', 'wxrefresh_token', 'psrf_qqaccess_token', 'psrf_qqunionid', 'psrf_musickey_createtime', 'psrf_qqopenid', 'qqmusic_nick']
32
+
33
+ function httpError(message, status = 502, extra) {
34
+ const err = new Error(message)
35
+ err.status = status
36
+ if (extra) Object.assign(err, extra)
37
+ return err
38
+ }
39
+
40
+ /** ptlogin 的 ptqrtoken:qrsig 的 hash33 */
41
+ export function hash33(text) {
42
+ let hash = 0
43
+ for (let i = 0; i < text.length; i++) hash += (hash << 5) + text.charCodeAt(i)
44
+ return hash & 0x7fffffff
45
+ }
46
+
47
+ /** 解析 `ptuiCB('0','0','https://…','0','登录成功!', 'nick')` → 参数数组(非 ptuiCB 返回 null) */
48
+ export function parsePtuiCb(text) {
49
+ const s = String(text || '').trim()
50
+ if (!/^ptuiCB\s*\(/.test(s)) return null
51
+ const args = []
52
+ const re = /'((?:\\.|[^'\\])*)'/g
53
+ let m
54
+ while ((m = re.exec(s))) args.push(m[1].replace(/\\'/g, "'").replace(/\\\\/g, '\\'))
55
+ return args
56
+ }
57
+
58
+ /**
59
+ * 1-bit 灰度 PNG(QQ 二维码图:111×111 = 37 模块 × 3px,无静区)→ `{ size, modules }`(1 = 黑块),
60
+ * 供前端按模块画成清晰 SVG。其它格式返回 null,调用方退回直接显示 PNG。
61
+ */
62
+ export function pngToMatrix(input) {
63
+ try {
64
+ const b = Buffer.isBuffer(input) ? input : Buffer.from(input)
65
+ if (b.length < 57 || b.readUInt32BE(0) !== 0x89504e47 || b.readUInt32BE(4) !== 0x0d0a1a0a) return null
66
+ let off = 8
67
+ let width = 0
68
+ let height = 0
69
+ const idat = []
70
+ while (off + 12 <= b.length) {
71
+ const len = b.readUInt32BE(off)
72
+ const type = b.toString('latin1', off + 4, off + 8)
73
+ const data = b.subarray(off + 8, off + 8 + len)
74
+ if (type === 'IHDR') {
75
+ width = data.readUInt32BE(0)
76
+ height = data.readUInt32BE(4)
77
+ if (data[8] !== 1 || data[9] !== 0 || data[12] !== 0) return null // 只支持非隔行 1-bit 灰度
78
+ } else if (type === 'IDAT') idat.push(data)
79
+ else if (type === 'IEND') break
80
+ off += 12 + len
81
+ }
82
+ if (!(width > 0 && height > 0 && width === height) || !idat.length) return null
83
+ const raw = inflateSync(Buffer.concat(idat))
84
+ const stride = Math.ceil(width / 8)
85
+ if (raw.length < height * (stride + 1)) return null
86
+ const lines = []
87
+ let prev = Buffer.alloc(stride)
88
+ for (let y = 0; y < height; y++) {
89
+ const filter = raw[y * (stride + 1)]
90
+ const line = Buffer.from(raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1)))
91
+ for (let i = 0; i < stride; i++) {
92
+ const a = i >= 1 ? line[i - 1] : 0
93
+ const up = prev[i]
94
+ const c = i >= 1 ? prev[i - 1] : 0
95
+ let v = line[i]
96
+ if (filter === 1) v = (v + a) & 255
97
+ else if (filter === 2) v = (v + up) & 255
98
+ else if (filter === 3) v = (v + ((a + up) >> 1)) & 255
99
+ else if (filter === 4) {
100
+ const p = a + up - c
101
+ const pa = Math.abs(p - a)
102
+ const pb = Math.abs(p - up)
103
+ const pc = Math.abs(p - c)
104
+ v = (v + (pa <= pb && pa <= pc ? a : pb <= pc ? up : c)) & 255
105
+ }
106
+ line[i] = v
107
+ }
108
+ lines.push(line)
109
+ prev = line
110
+ }
111
+ const dark = (x, y) => ((lines[y][x >> 3] >> (7 - (x & 7))) & 1) === 0
112
+ // 模块边长:每个模块内像素必须同色(整图是方阵,边长能整除像素宽)
113
+ for (const m of [3, 4, 2, 5, 6, 7, 8, 1]) {
114
+ if (width % m !== 0) continue
115
+ const size = width / m
116
+ if (size < 21 || size > 177) continue
117
+ let blocky = true
118
+ const modules = new Uint8Array(size * size)
119
+ for (let y = 0; y < size && blocky; y++) {
120
+ for (let x = 0; x < size; x++) {
121
+ const v = dark(x * m, y * m)
122
+ for (let dy = 0; dy < m && blocky; dy++) for (let dx = 0; dx < m; dx++) if (dark(x * m + dx, y * m + dy) !== v) { blocky = false; break }
123
+ modules[y * size + x] = v ? 1 : 0
124
+ }
125
+ }
126
+ if (!blocky) continue
127
+ // 去掉图片自带的白边(QQ 的图四周有 2 模块留白),交给前端按标准 4 模块静区绘制
128
+ const trimmed = trimLightBorder(size, modules)
129
+ return trimmed || { size, modules: Array.from(modules) }
130
+ }
131
+ return null
132
+ } catch {
133
+ return null
134
+ }
135
+ }
136
+
137
+ /** 去掉四边全亮的行列;剩余边长必须是合法 QR 尺寸(21 + 4k),否则返回 null(保留原图) */
138
+ function trimLightBorder(size, modules) {
139
+ let top = 0
140
+ let bottom = size - 1
141
+ let left = 0
142
+ let right = size - 1
143
+ const rowDark = (y) => { for (let x = left; x <= right; x++) if (modules[y * size + x]) return true; return false }
144
+ const colDark = (x) => { for (let y = top; y <= bottom; y++) if (modules[y * size + x]) return true; return false }
145
+ while (top < bottom && !rowDark(top)) top++
146
+ while (bottom > top && !rowDark(bottom)) bottom--
147
+ while (left < right && !colDark(left)) left++
148
+ while (right > left && !colDark(right)) right--
149
+ const n = bottom - top + 1
150
+ if (n !== right - left + 1 || n < 21 || n > 177 || (n - 21) % 4 !== 0) return null
151
+ const out = new Uint8Array(n * n)
152
+ for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) out[y * n + x] = modules[(top + y) * size + left + x]
153
+ return { size: n, modules: Array.from(out) }
154
+ }
155
+
156
+ /** 简易 cookie 罐:按名字记值(域名/路径属性按 qq.com 全量回传,仅用于这条固定跳转链) */
157
+ /** 会话 cookie 罐(内存)。按浏览器的规则做事:带 Domain 属性的按域匹配,没带的是 host-only;
158
+ * Max-Age=0 / Expires 已过期 / 空值带过期属性 = 删除。真实抓包对照:check_sig 会用删除语义清掉
159
+ * p_skey_forbid,如果把它当成普通 cookie 带到 authorize,服务端直接判成未登录(踢回 show 页)。 */
160
+ function createJar() {
161
+ const map = new Map() /* name → { value, domain, hostOnly };domain '' = 来路不明(seed 进来的),所有主机都带 */
162
+ const hostnameOf = (url) => { try { return new URL(String(url)).hostname } catch { return '' } }
163
+ const matches = (c, host) => {
164
+ if (!c.domain) return true /* seed 进来的(来路不明)cookie:所有主机都带 */
165
+ if (!host) return false
166
+ return c.hostOnly ? host === c.domain : host === c.domain || host.endsWith('.' + c.domain)
167
+ }
168
+ return {
169
+ absorb(res, requestUrl) {
170
+ const host = hostnameOf(requestUrl || (res && res.url) || '')
171
+ const list = typeof res.headers.getSetCookie === 'function' ? res.headers.getSetCookie() : []
172
+ for (const line of list) {
173
+ const parts = String(line).split(';')
174
+ const pair = parts[0]
175
+ const i = pair.indexOf('=')
176
+ if (i <= 0) continue
177
+ const name = pair.slice(0, i).trim()
178
+ const value = pair.slice(i + 1).trim()
179
+ const attrs = {}
180
+ for (const a of parts.slice(1)) {
181
+ const j = a.indexOf('=')
182
+ if (j > 0) attrs[a.slice(0, j).trim().toLowerCase()] = a.slice(j + 1).trim()
183
+ }
184
+ let expired = attrs['max-age'] != null && Number(attrs['max-age']) <= 0
185
+ if (attrs.expires) {
186
+ const t = Date.parse(attrs.expires)
187
+ if (Number.isFinite(t) && t <= Date.now()) expired = true
188
+ }
189
+ if (value === '' && (attrs.expires != null || attrs['max-age'] != null)) expired = true
190
+ if (expired) { map.delete(name); continue }
191
+ const domain = String(attrs.domain || '').replace(/^\./, '').toLowerCase() || host
192
+ if (!domain) continue
193
+ map.set(name, { value, domain, hostOnly: !attrs.domain })
194
+ }
195
+ },
196
+ /** 某个 URL(或主机名)会带上的 cookie;不传 = 全部 */
197
+ header(url) {
198
+ const host = url ? (hostnameOf(url) || String(url)) : ''
199
+ return [...map.entries()]
200
+ .filter(([, c]) => !host || matches(c, host))
201
+ .map(([k, c]) => `${k}=${c.value}`).join('; ')
202
+ },
203
+ /** 某个 URL 会带上的 cookie 名(诊断用) */
204
+ namesFor: (url) => [...map.entries()].filter(([, c]) => matches(c, hostnameOf(url) || String(url || ''))).map(([k]) => k),
205
+ get: (name) => (map.get(name) || {}).value || '',
206
+ names: () => [...map.keys()],
207
+ set(name, value, domain = '') { if (name && value != null && value !== '') map.set(name, { value: String(value), domain, hostOnly: false }) },
208
+ drop: (name) => { map.delete(name) },
209
+ seed(header, domain = '') {
210
+ for (const pair of String(header || '').split(';')) {
211
+ const i = pair.indexOf('=')
212
+ if (i > 0) map.set(pair.slice(0, i).trim(), { value: pair.slice(i + 1).trim(), domain, hostOnly: false })
213
+ }
214
+ },
215
+ copyFrom(other) {
216
+ for (const [name, c] of other.entries()) map.set(name, { ...c })
217
+ },
218
+ entries: () => [...map.entries()],
219
+ }
220
+ }
221
+
222
+ export function createQQLogin({ fetchImpl, timeoutMs = 15000 } = {}) {
223
+ const fetch = fetchImpl || globalThis.fetch
224
+ if (typeof fetch !== 'function') throw new Error('QQ 扫码登录需要 fetch')
225
+
226
+ async function request(url, init) {
227
+ const ac = AbortSignal.timeout(timeoutMs)
228
+ const signal = init.signal ? AbortSignal.any([init.signal, ac]) : ac
229
+ let res
230
+ try {
231
+ res = await fetch(url, { ...init, signal, redirect: 'manual' })
232
+ } catch (err) {
233
+ if (err && (err.name === 'TimeoutError' || err.name === 'AbortError')) throw httpError('连接超时', 504)
234
+ throw httpError(`网络请求失败:${(err && err.message) || err}`, 502)
235
+ }
236
+ if (!res || typeof res.status !== 'number') throw httpError('接口无响应', 502)
237
+ return res
238
+ }
239
+
240
+ /** 创建扫码会话:拿二维码图(同时得到 qrsig) */
241
+ async function qrCreate() {
242
+ const jar = createJar()
243
+ const page = await request(XLOGIN, { headers: { 'User-Agent': QQ_UA, Accept: 'text/html,*/*' } })
244
+ jar.absorb(page, XLOGIN)
245
+ const pageText = await page.text().catch(() => '')
246
+ /* 官方轮询 URL 末尾的 pt_js_version = 登录页里 monorepo 版本号(c_login_2.js 的 CDN 路径) */
247
+ const jsVer = (pageText.match(/monorepo\/([0-9a-f]+)\/ptlogin\/js/) || [])[1] || ''
248
+ const t = Math.random()
249
+ const show = `${PT_HOST}/ssl/ptqrshow?appid=${PT_APPID}&e=2&l=M&s=3&d=72&v=4&t=${t}&daid=${PT_DAID}&pt_3rd_aid=${QQ_CLIENT_ID}&u1=${encodeURIComponent(S_URL)}`
250
+ const res = await request(show, { headers: { 'User-Agent': QQ_UA, Referer: XLOGIN, Accept: 'image/*,**' } })
251
+ jar.absorb(res, show)
252
+ const bytes = Buffer.from(await res.arrayBuffer())
253
+ if (res.status !== 200 || bytes.length < 100 || !jar.get('qrsig')) {
254
+ throw httpError(`获取 QQ 登录二维码失败(HTTP ${res.status},${bytes.length} 字节)`, 502)
255
+ }
256
+ const matrix = pngToMatrix(bytes)
257
+ return {
258
+ qrsig: jar.get('qrsig'),
259
+ /* 官方登录页轮询时带 login_sig = xlogin 下发的 pt_login_sig(缺了它,手机确认后服务端会判成二维码已失效) */
260
+ loginSig: jar.get('pt_login_sig') || '',
261
+ jsVer,
262
+ cookies: jar.header(),
263
+ /* 会话 cookie 罐(内存对象):轮询/换票沿用同一个罐,服务端在扫码成功那一跳下发的
264
+ ETK / superkey / RK / ptcz 等必须带到 check_sig → authorize,否则授权会被踢回登录页 */
265
+ jar,
266
+ matrix: matrix ? { size: matrix.size, modules: matrix.modules } : null,
267
+ png: `data:image/png;base64,${bytes.toString('base64')}`,
268
+ }
269
+ }
270
+
271
+ /** 轮询一次。返回 `{ code, message }`:801 未扫 / 802 已扫待确认 / 800 已失效 / 803 成功(附 cookie)/ 804 其它(风控等,需重开) */
272
+ async function qrPoll(session) {
273
+ const poll = `${PT_HOST}/ssl/ptqrlogin?u1=${encodeURIComponent(S_URL)}&ptqrtoken=${hash33(session.qrsig)}&ptredirect=0&h=1&t=1&g=1&from_ui=1&ptlang=2052&action=0-0-${Date.now()}&js_ver=${PTUI_VERSION}&js_type=1&login_sig=${encodeURIComponent(session.loginSig || '')}&pt_uistyle=40&aid=${PT_APPID}&daid=${PT_DAID}&pt_3rd_aid=${QQ_CLIENT_ID}${session.jsVer ? `&pt_js_version=${session.jsVer}` : ''}`
274
+ const res = await request(poll, { headers: { 'User-Agent': QQ_UA, Referer: XLOGIN, Accept: '*/*', Cookie: session.jar ? session.jar.header(poll) : session.cookies } })
275
+ if (session.jar) session.jar.absorb(res, poll)
276
+ const text = await res.text()
277
+ const args = parsePtuiCb(text)
278
+ if (!args) throw httpError(`QQ 扫码状态返回异常(HTTP ${res.status})`, 502)
279
+ const code = String(args[0])
280
+ if (code === '66') return { code: 801, message: '二维码未失效' }
281
+ if (code === '67') return { code: 802, message: '手机QQ扫码成功,等待确认' }
282
+ if (code === '65') return { code: 800, message: '二维码已失效' }
283
+ if (code !== '0') return { code: 804, message: args[4] || `返回码 ${code}` }
284
+ const cookie = await exchange(args[2], session)
285
+ return { code: 803, message: '登录成功', cookie }
286
+ }
287
+
288
+ /** 页面级跳转:优先最终落点 wx_redirect.html?…code=…,其次 location.href= / location.replace( / meta refresh 里的 qq.com 地址 */
289
+ function safeUrl(raw, base) {
290
+ try {
291
+ const u = new URL(String(raw).replace(/&amp;/g, '&'), base)
292
+ return /^https?:$/.test(u.protocol) && /(^|\.)qq\.com$/.test(u.hostname) ? u.href : ''
293
+ } catch { return '' }
294
+ }
295
+
296
+ /** 从 HTML 里找下一个跳转:落点 URL / meta refresh / location 跳转 / 自动提交的表单(授权确认页) */
297
+ function nextFromHtml(text, base, seen = []) {
298
+ const t = String(text || '').slice(0, 262144)
299
+ .replace(/\\\//g, '/').replace(/\\u0026/g, '&').replace(/&#0*38;/gi, '&').replace(/&#x0*26;/gi, '&')
300
+ const final = t.match(/https?:\/\/y\.qq\.com\/portal\/wx_redirect\.html[^"'\s<>)]*/)
301
+ if (final) return { url: final[0].replace(/&amp;/g, '&') }
302
+ const m = t.match(/(?:location(?:\.href|\.replace|\.assign)?\s*[=(]\s*|http-equiv=["']?refresh["']?[^>]*?url=)["']?(https?:\/\/[^"'\s<>)]+)/i)
303
+ if (m) {
304
+ const url = safeUrl(m[1], base)
305
+ if (url) return { url }
306
+ }
307
+ /* 授权确认页 / 中转页:<form action=…> + 隐藏字段 + 自动 submit —— 照着表单提交一次 */
308
+ const form = t.match(/<form\b([^>]*)>([\s\S]*?)<\/form>/i)
309
+ if (form) {
310
+ const action = (form[1].match(/action=["']?([^"'\s>]+)/i) || [])[1] || ''
311
+ const url = safeUrl(action, base)
312
+ if (url && /graph\.qq\.com/.test(new URL(url).hostname)) {
313
+ const method = /method=["']?post/i.test(form[1]) ? 'POST' : 'GET'
314
+ const fields = new URLSearchParams()
315
+ const re = /<input\b([^>]*)>/gi
316
+ let input
317
+ let count = 0
318
+ while ((input = re.exec(form[2]))) {
319
+ if (!/type=["']?hidden/i.test(input[1])) continue
320
+ const name = (input[1].match(/name=["']?([^"'\s>]+)/i) || [])[1] || ''
321
+ if (!name) continue
322
+ const value = ((input[1].match(/value=("([^"]*)"|'([^']*)'|[^\s>]+)/i) || [])[1] || '')
323
+ fields.append(name, value.replace(/^["']|["']$/g, ''))
324
+ count++
325
+ }
326
+ if (count > 0) {
327
+ if (method === 'GET') return { url: url + (url.includes('?') ? '&' : '?') + fields.toString() }
328
+ return { url, method: 'POST', body: fields.toString() }
329
+ }
330
+ }
331
+ }
332
+ /* 兜底:页面里(例如内嵌 JSON 配置)出现的 qq.com 链接 —— 优先 OAuth 路径,排除静态资源 */
333
+ const re2 = /https?:\/\/[^"'\s<>)\\]{8,400}/g
334
+ const prefer = []
335
+ const rest = []
336
+ let m2
337
+ while ((m2 = re2.exec(t))) {
338
+ const u = safeUrl(m2[0], base)
339
+ if (!u || seen.includes(u)) continue
340
+ if (/\.(js|css|png|gif|jpe?g|webp|ico|svg|woff2?)(\?|$)/i.test(u) || /^https?:\/\/imgcache\.qq\.com\//.test(u)) continue
341
+ if (/\/oauth2\.0\/|login_jump|wx_redirect/.test(u)) prefer.push(u)
342
+ else rest.push(u)
343
+ }
344
+ const pick = prefer[0] || rest[0] || ''
345
+ return pick ? { url: pick } : null
346
+ }
347
+
348
+ /** g_tk:QQ 互联的防 CSRF 值 = hash33 变体(种子 5381)作用于 p_skey cookie */
349
+ function gtkOf(jar) {
350
+ const str = jar.get('p_skey') || ''
351
+ let hash = 5381
352
+ for (let i = 0; i < str.length; i++) hash += (hash << 5) + str.charCodeAt(i)
353
+ return hash & 0x7fffffff
354
+ }
355
+
356
+ function uuid() {
357
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
358
+ const r = Math.floor(Math.random() * 16)
359
+ const v = c === 'x' ? r : (r & 0x3) | 0x8
360
+ return v.toString(16).toUpperCase()
361
+ })
362
+ }
363
+
364
+ /**
365
+ * login_jump 只是 iframe 里的一个 postMessage 页面(告诉父页 qclogin_success);
366
+ * 父页(authorize/show)收到后用表单 POST authorize 完成授权:openapi=1010(头像昵称)、from_ptlogin=1、update_auth=1、g_tk=hash33(p_skey)
367
+ */
368
+ function authorizeStep(jar) {
369
+ const f = new URLSearchParams()
370
+ f.set('response_type', 'code')
371
+ f.set('client_id', QQ_CLIENT_ID)
372
+ f.set('redirect_uri', REDIRECT_URI_PLAIN)
373
+ f.set('scope', '')
374
+ f.set('state', 'state')
375
+ f.set('switch', '')
376
+ f.set('from_ptlogin', '1')
377
+ f.set('src', '1')
378
+ f.set('update_auth', '1')
379
+ f.set('openapi', '1010')
380
+ f.set('g_tk', String(gtkOf(jar)))
381
+ f.set('auth_time', String(Date.now()))
382
+ /* 官方页 getUuid():有 ui cookie 用它,否则生成一个并写回 cookie —— 表单里的 ui 和 cookie 必须一致 */
383
+ const ui = jar.get('ui') || uuid()
384
+ jar.set('ui', ui, 'graph.qq.com')
385
+ f.set('ui', ui)
386
+ return { url: AUTHORIZE_URL, method: 'POST', body: f.toString(), headers: { ...NAV_HEADERS, Referer: AUTHORIZE_PAGE, Origin: 'https://graph.qq.com' } }
387
+ }
388
+
389
+ /** 诊断信息(给用户看的错误文案用):去掉标签、遮住长 token,只留前 200 字 */
390
+ function describeBody(text) {
391
+ const t = String(text || '')
392
+ const urls = []
393
+ const re = /https?:\/\/[^"'\s<>)\\]{8,200}/g
394
+ let m
395
+ while ((m = re.exec(t)) && urls.length < 4) urls.push(m[0].replace(/[A-Za-z0-9_\-]{17,}/g, '…'))
396
+ const plain = t.replace(/<script[\s\S]*?<\/script>/gi, ' ').replace(/<style[\s\S]*?<\/style>/gi, ' ')
397
+ .replace(/<[^>]{0,300}>/g, ' ').replace(/[A-Za-z0-9_\-]{17,}/g, '…').replace(/\s+/g, ' ').trim().slice(0, 200)
398
+ return { len: t.length, plain, urls }
399
+ }
400
+
401
+ /** check_sig → login_jump → authorize → wx_redirect.html?code=… → musicu QQLogin 换音乐登录态 */
402
+ async function exchange(jumpUrl, session) {
403
+ /* 跳转地址由服务端下发(check_sig…),主机只认 qq.com 下的 http(s) 地址;错误文案带上 host/path 方便定位 */
404
+ let parsed = null
405
+ try { parsed = new URL(String(jumpUrl)) } catch { parsed = null }
406
+ const hostOk = !!parsed && /^https?:$/.test(parsed.protocol) && /(^|\.)qq\.com$/.test(parsed.hostname)
407
+ if (!hostOk) {
408
+ const shown = parsed ? `${parsed.hostname}${parsed.pathname}`.slice(0, 80) : String(jumpUrl || '').slice(0, 60)
409
+ throw httpError(`QQ 登录跳转地址异常(${shown})`, 502)
410
+ }
411
+ // ptlogin2 的会话 cookie(qrsig / pt_login_sig 等)只在内存里跟着这条跳转链走
412
+ const jar = createJar()
413
+ if (session.jar) jar.copyFrom(session.jar)
414
+ else jar.seed(session.cookies)
415
+ let url = parsed.href
416
+ let referer = XLOGIN
417
+ let code = ''
418
+ let lastStatus = 0
419
+ let lastText = ''
420
+ let post = null /* 下一跳是表单 POST 时:{ body } */
421
+ const hops = []
422
+ const seen = []
423
+ for (let hop = 0; hop < 10 && url; hop++) {
424
+ if (seen.includes(url)) {
425
+ lastText = text || lastText
426
+ break
427
+ }
428
+ seen.push(url)
429
+ const init = { headers: { 'User-Agent': QQ_UA, Accept: 'text/html,application/json,*/*', Referer: referer, Cookie: jar.header(url) } }
430
+ if (post) {
431
+ init.method = 'POST'
432
+ init.headers['Content-Type'] = 'application/x-www-form-urlencoded'
433
+ init.body = post.body
434
+ if (post.headers) Object.assign(init.headers, post.headers)
435
+ }
436
+ post = null
437
+ const res = await request(url, init)
438
+ jar.absorb(res, url)
439
+ lastStatus = res.status
440
+ const text = await res.text().catch(() => '')
441
+ const u = new URL(url)
442
+ hops.push(`${u.hostname}${u.pathname}→${res.status}`)
443
+ /* 授权表单这一跳最关键:被踢回 show = 服务端没认登录态。记下它带了哪些 cookie(只记名字)和跳去了哪 */
444
+ if (/\/oauth2\.0\/authorize/.test(u.pathname)) {
445
+ const to = res.headers.get('location')
446
+ let toShown = '无跳转'
447
+ if (to) { try { const t = new URL(to, url); toShown = t.hostname + t.pathname } catch { toShown = '?' } }
448
+ hops[hops.length - 1] += `→${toShown}(cookie 名:${jar.namesFor(url).join(',') || '无'})`
449
+ }
450
+ /* 到达落点(wx_redirect.html?…code=…):授权码就在 URL 里,页面本身不用再解析 */
451
+ if (url.includes('/portal/wx_redirect.html')) {
452
+ code = u.searchParams.get('code') || ''
453
+ break
454
+ }
455
+ /* 302 Location 优先;没有的话(graph 的页面有用 JS / meta / 表单跳的)从正文里找下一个 qq.com 落点 */
456
+ let step = null
457
+ const location = res.headers.get('location')
458
+ if (location) step = { url: safeUrl(location, url) }
459
+ /* login_jump 的 200 页只是 iframe 里的 postMessage(qclogin_success)→ 按官方授权页的逻辑提交 authorize 表单 */
460
+ if (!step && /\/oauth2\.0\/login_jump/.test(u.pathname) && /qclogin_success/.test(text)) {
461
+ /* 浏览器在 check_sig 之后就没有 p_skey_forbid 这个 cookie(服务端用删除语义清掉的);保险起见授权前再丢一次 */
462
+ jar.drop('p_skey_forbid')
463
+ step = authorizeStep(jar)
464
+ }
465
+ if (!step) {
466
+ const cb = text.match(/"callback"\s*:\s*"(https?:\/\/[^"\s]+)"/)
467
+ if (cb) step = { url: safeUrl(cb[1].replace(/\\\//g, '/'), url) }
468
+ }
469
+ if (!step) step = nextFromHtml(text, url, seen)
470
+ if (!step || !step.url) {
471
+ lastText = text
472
+ break
473
+ }
474
+ referer = url
475
+ url = step.url
476
+ if (step.method === 'POST') post = { body: step.body, headers: step.headers || null }
477
+ if (url.includes('/portal/wx_redirect.html')) {
478
+ code = new URL(url).searchParams.get('code') || ''
479
+ break
480
+ }
481
+ }
482
+ if (!code) {
483
+ const d = describeBody(lastText)
484
+ const detail = `跳转链 ${hops.join(' › ') || '(空)'};末页 ${d.len} 字节${d.plain ? `「${d.plain}」` : ''}${d.urls.length ? `;页面链接 ${d.urls.join(' | ')}` : ''}`
485
+ throw httpError(`QQ 登录成功但没拿到授权码(${detail.slice(0, 800)})`, 502)
486
+ }
487
+ const body = JSON.stringify({
488
+ comm: { g_tk: 5381, platform: 'yqq', ct: 24, cv: 0 },
489
+ req: { module: 'QQConnectLogin.LoginServer', method: 'QQLogin', param: { code } },
490
+ })
491
+ const res = await request('https://u.y.qq.com/cgi-bin/musicu.fcg', {
492
+ method: 'POST',
493
+ headers: { 'User-Agent': QQ_UA, Referer: WX_REDIRECT, Origin: 'https://y.qq.com', Accept: 'application/json, text/plain, */*', Cookie: jar.header('https://u.y.qq.com/') },
494
+ body,
495
+ })
496
+ jar.absorb(res, 'https://u.y.qq.com/cgi-bin/musicu.fcg')
497
+ let json = null
498
+ try { json = JSON.parse(await res.text()) } catch { json = null }
499
+ const ok = json && Number(json.code) === 0 && json.req && Number(json.req.code) === 0
500
+ if (!ok) {
501
+ const desc = json ? `code ${json.code}/${json.req && json.req.code}${json.req && json.req.msg ? ' ' + json.req.msg : ''}` : `HTTP ${res.status}`
502
+ throw httpError(`QQ 音乐登录换票失败(${desc})`, 502)
503
+ }
504
+ const data = (json.req.data && typeof json.req.data === 'object') ? json.req.data : {}
505
+ const keyst = jar.get('qm_keyst') || jar.get('qqmusic_key') || data.musickey || data.qm_keyst || data.qqmusic_key || ''
506
+ const uin = jar.get('uin') || jar.get('qqmusic_uin') || jar.get('wxuin') || data.musicid || data.uin || data.wxuin || ''
507
+ if (!keyst || !uin) {
508
+ const seen = [...jar.names(), ...Object.keys(data)].filter((k) => !/skey|token|sig/i.test(k)).join(',')
509
+ throw httpError(`QQ 登录成功但未返回音乐登录态(字段:${seen || '无'})`, 502)
510
+ }
511
+ const parts = [`qqmusic_key=${keyst}`, `qm_keyst=${keyst}`, `uin=${uin}`, `qqmusic_uin=${uin}`]
512
+ for (const key of COOKIE_FIELDS) {
513
+ if (key === 'uin' || key === 'qqmusic_uin') continue
514
+ const v = jar.get(key) || (data[key] != null ? String(data[key]) : '')
515
+ if (v) parts.push(`${key}=${v}`)
516
+ }
517
+ return parts.join('; ')
518
+ }
519
+
520
+ return { qrCreate, qrPoll }
521
+ }