完善半自动履约凭证与客户重新授权流程
统一虎牙和微博账号级 CK 保存与导出;CK 失效后回到客户重新登录,后台支持重发授权;客户授权页改为统一深色布局并收敛开发迁移配置。
This commit is contained in:
@@ -8,12 +8,13 @@
|
||||
* - 一次性浏览器注入票据
|
||||
*
|
||||
* 手机号和验证码只保存在短期内存会话中;登录成功后的账号 Cookie 由任务服务
|
||||
* 导出为账号级凭证,经 AES-256-GCM 加密后落库,不写日志。
|
||||
* 导出为账号级凭证写入内部凭证表,不写日志。
|
||||
*/
|
||||
|
||||
import crypto from 'node:crypto'
|
||||
|
||||
import { createHttpError } from '../../../utils/http.js'
|
||||
import { logWarn } from '../../../utils/logger.js'
|
||||
import type {
|
||||
ConnectorBindingSession,
|
||||
ConnectorBrowserTicket,
|
||||
@@ -23,8 +24,10 @@ import type {
|
||||
|
||||
const PASSPORT_BASE = 'https://passport.weibo.com'
|
||||
const WEIBO_BASE = 'https://weibo.com'
|
||||
const WEIBO_RETURN_URL = 'https://weibo.com/'
|
||||
const WEIBO_LOGIN_URL =
|
||||
'https://weibo.com/newlogin?tabtype=weibo&gid=102803&openLoginLayer=0&url=https%3A%2F%2Fweibo.com%2F'
|
||||
`https://weibo.com/newlogin?tabtype=weibo&gid=102803&openLoginLayer=0` +
|
||||
`&url=${WEIBO_RETURN_URL}`
|
||||
const WEIBO_LOGIN_VER = '20250520'
|
||||
const SIGNIN_REFERER =
|
||||
`${PASSPORT_BASE}/sso/signin?entry=miniblog&source=miniblog&disp=popup` +
|
||||
@@ -312,6 +315,7 @@ type SmsLoginState = {
|
||||
mobile: string
|
||||
cookies: WeiboCookieJar
|
||||
mfaId: string
|
||||
rid: string
|
||||
createdAtMs: number
|
||||
expiresAtMs: number
|
||||
}
|
||||
@@ -536,6 +540,7 @@ export class WeiboNativeConnector {
|
||||
mobile,
|
||||
cookies: await this.createBootstrapSession(),
|
||||
mfaId: '',
|
||||
rid: crypto.randomBytes(22).toString('base64url'),
|
||||
createdAtMs: this.now(),
|
||||
expiresAtMs: this.now() + SMS_COOKIE_TTL_MS,
|
||||
}
|
||||
@@ -629,7 +634,7 @@ export class WeiboNativeConnector {
|
||||
scode: encodeSsoField(code),
|
||||
el: '2',
|
||||
disp: 'popup',
|
||||
rid: String(input.rid || '').trim() || 'norid',
|
||||
rid: String(input.rid || '').trim() || state.rid,
|
||||
})
|
||||
const loginUrl = `${PASSPORT_BASE}/sso/v2/login`
|
||||
const response = await this.fetchImpl(`${PASSPORT_BASE}/sso/v2/login`, {
|
||||
@@ -642,34 +647,49 @@ export class WeiboNativeConnector {
|
||||
const payload = (await response.json().catch(() => null)) as {
|
||||
retcode?: number
|
||||
msg?: string
|
||||
data?: { data?: { act?: string; location?: string; mfa_id?: string } }
|
||||
data?: {
|
||||
act?: string
|
||||
location?: string
|
||||
mfa_id?: string
|
||||
data?: { act?: string; location?: string; mfa_id?: string }
|
||||
}
|
||||
} | null
|
||||
if (!response.ok || !payload) {
|
||||
logWarn('[weibo/sms-login]', '微博短信登录请求失败', {
|
||||
taskId: Number(input.taskId) || 0,
|
||||
status: response.status,
|
||||
hasPayload: Boolean(payload),
|
||||
})
|
||||
throw createHttpError(`微博短信登录失败:HTTP ${response.status}`, {
|
||||
statusCode: 502,
|
||||
errorCode: 'weibo_sms_login_failed',
|
||||
})
|
||||
}
|
||||
const act = String(payload.data?.data?.act || '')
|
||||
const act = String(payload.data?.data?.act || payload.data?.act || '')
|
||||
if (act === 'mfa_1' || act === 'mfa_2') {
|
||||
throw createHttpError('微博要求二次验证,请在微博 App 完成验证后重试', {
|
||||
statusCode: 409,
|
||||
errorCode: 'weibo_sms_mfa_required',
|
||||
})
|
||||
}
|
||||
if (act !== 'goto') {
|
||||
const location = String(payload.data?.data?.location || payload.data?.location || '').trim()
|
||||
if (!location) {
|
||||
logWarn('[weibo/sms-login]', '微博短信登录未通过', {
|
||||
taskId: Number(input.taskId) || 0,
|
||||
status: response.status,
|
||||
retcode: Number(payload.retcode) || 0,
|
||||
act,
|
||||
message: String(payload.msg || '')
|
||||
.trim()
|
||||
.slice(0, 200),
|
||||
dataKeys: payload.data ? Object.keys(payload.data) : [],
|
||||
nestedDataKeys: payload.data?.data ? Object.keys(payload.data.data) : [],
|
||||
})
|
||||
throw createHttpError(payload.msg || '微博短信登录失败,请检查验证码', {
|
||||
statusCode: 409,
|
||||
errorCode: 'weibo_sms_login_failed',
|
||||
})
|
||||
}
|
||||
const location = String(payload.data?.data?.location || '').trim()
|
||||
if (!location) {
|
||||
throw createHttpError('微博登录成功但缺少跳转地址', {
|
||||
statusCode: 502,
|
||||
errorCode: 'weibo_sms_login_failed',
|
||||
})
|
||||
}
|
||||
const nowMs = this.now()
|
||||
const session: WeiboSession = {
|
||||
sessionId: crypto.randomBytes(18).toString('base64url'),
|
||||
@@ -832,14 +852,33 @@ export class WeiboNativeConnector {
|
||||
}
|
||||
|
||||
private async finishLogin(session: WeiboSession, loginUrl: string): Promise<void> {
|
||||
await this.followWithCookies(loginUrl, session.cookies)
|
||||
const { finalUrl, body } = await this.followWithCookies(loginUrl, session.cookies)
|
||||
if (!session.cookies.has(WEIBO_BASE, 'SUB')) {
|
||||
session.status = 'failed'
|
||||
session.message = '微博登录成功但未获取到登录 Cookie'
|
||||
return
|
||||
}
|
||||
session.account = await this.fetchAccount(session.cookies.headerFor(WEIBO_BASE))
|
||||
let homeStatus = 0
|
||||
let homeBody = ''
|
||||
session.account = this.parseAccountFromHome(body)
|
||||
if (!session.account) {
|
||||
const home = await this.fetchHomePage(session.cookies)
|
||||
homeStatus = home.status
|
||||
homeBody = home.body
|
||||
session.account = this.parseAccountFromHome(homeBody)
|
||||
}
|
||||
if (!session.account) {
|
||||
session.account = await this.fetchAccount(session.cookies.headerFor(WEIBO_BASE))
|
||||
}
|
||||
if (!session.account.uid) {
|
||||
logWarn('[weibo/account]', '微博账号信息读取失败', {
|
||||
finalUrl,
|
||||
followedBodyLength: body.length,
|
||||
followedHasConfig: body.includes('window.$CONFIG'),
|
||||
homeStatus,
|
||||
homeBodyLength: homeBody.length,
|
||||
homeHasConfig: homeBody.includes('window.$CONFIG'),
|
||||
})
|
||||
session.status = 'failed'
|
||||
session.message = '微博登录成功但账号信息读取失败'
|
||||
return
|
||||
@@ -851,9 +890,10 @@ export class WeiboNativeConnector {
|
||||
private async followWithCookies(
|
||||
url: string,
|
||||
cookies: WeiboCookieJar,
|
||||
): Promise<{ finalUrl: string }> {
|
||||
): Promise<{ finalUrl: string; body: string }> {
|
||||
let currentUrl = url
|
||||
for (let index = 0; index < 8; index += 1) {
|
||||
let body = ''
|
||||
for (let index = 0; index < 12; index += 1) {
|
||||
const response = await this.fetchImpl(currentUrl, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
@@ -871,10 +911,96 @@ export class WeiboNativeConnector {
|
||||
currentUrl = new URL(location, currentUrl).toString()
|
||||
continue
|
||||
}
|
||||
await response.arrayBuffer().catch(() => undefined)
|
||||
body = await response.text().catch(() => '')
|
||||
break
|
||||
}
|
||||
return { finalUrl: currentUrl }
|
||||
return { finalUrl: currentUrl, body }
|
||||
}
|
||||
|
||||
private async fetchHomePage(cookies: WeiboCookieJar): Promise<{ status: number; body: string }> {
|
||||
try {
|
||||
const response = await this.fetchImpl(`${WEIBO_BASE}/`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'user-agent': PC_UA,
|
||||
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
|
||||
'accept-language': 'zh-CN,zh;q=0.9',
|
||||
referer: WEIBO_BASE,
|
||||
cookie: cookies.headerFor(WEIBO_BASE),
|
||||
},
|
||||
redirect: 'follow',
|
||||
signal: AbortSignal.timeout(this.timeoutMs),
|
||||
})
|
||||
cookies.addFromResponse(response.headers, response.url || `${WEIBO_BASE}/`)
|
||||
return {
|
||||
status: response.status,
|
||||
body: await response.text().catch(() => ''),
|
||||
}
|
||||
} catch {
|
||||
return { status: 0, body: '' }
|
||||
}
|
||||
}
|
||||
|
||||
private parseAccountFromHome(htmlInput: string): WeiboAccount | null {
|
||||
const html = String(htmlInput || '')
|
||||
const markerIndex = html.indexOf('window.$CONFIG')
|
||||
if (markerIndex < 0) return null
|
||||
const start = html.indexOf('{', markerIndex)
|
||||
if (start < 0) return null
|
||||
|
||||
let depth = 0
|
||||
let inString = false
|
||||
let escaped = false
|
||||
let end = -1
|
||||
for (let index = start; index < html.length; index += 1) {
|
||||
const char = html[index]
|
||||
if (inString) {
|
||||
if (escaped) {
|
||||
escaped = false
|
||||
} else if (char === '\\') {
|
||||
escaped = true
|
||||
} else if (char === '"') {
|
||||
inString = false
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (char === '"') {
|
||||
inString = true
|
||||
continue
|
||||
}
|
||||
if (char === '{') depth += 1
|
||||
if (char === '}') {
|
||||
depth -= 1
|
||||
if (depth === 0) {
|
||||
end = index + 1
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if (end <= start) return null
|
||||
|
||||
try {
|
||||
const config = JSON.parse(html.slice(start, end)) as {
|
||||
uid?: number | string
|
||||
user?: {
|
||||
id?: number | string
|
||||
idstr?: number | string
|
||||
screen_name?: string
|
||||
avatar_large?: string
|
||||
avatar_hd?: string
|
||||
}
|
||||
}
|
||||
const user = config.user
|
||||
const uid = String(user?.idstr || user?.id || config.uid || '')
|
||||
if (!uid) return null
|
||||
return {
|
||||
uid,
|
||||
nickname: String(user?.screen_name || ''),
|
||||
avatar: String(user?.avatar_large || user?.avatar_hd || ''),
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
private async fetchAccount(cookie: string): Promise<WeiboAccount> {
|
||||
|
||||
@@ -102,10 +102,21 @@ function defaultHandler(url: string): Response {
|
||||
})
|
||||
}
|
||||
if (url === 'https://weibo.com/') {
|
||||
return new Response('<html></html>', {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'text/html' },
|
||||
})
|
||||
return new Response(
|
||||
`<html><script>window.$CONFIG = ${JSON.stringify({
|
||||
uid: 123456,
|
||||
user: {
|
||||
id: 123456,
|
||||
idstr: '123456',
|
||||
screen_name: '微博测试账号',
|
||||
avatar_large: 'https://tvax1.sinaimg.cn/demo.jpg',
|
||||
},
|
||||
})};</script></html>`,
|
||||
{
|
||||
status: 200,
|
||||
headers: { 'content-type': 'text/html' },
|
||||
},
|
||||
)
|
||||
}
|
||||
if (url.includes('/ajax/side/info')) {
|
||||
return jsonResponse({
|
||||
@@ -226,6 +237,10 @@ test('微博短信登录建立会话并可生成一次性注入票据', async ()
|
||||
assert.equal(session.status, 'authenticated')
|
||||
assert.equal(session.huyaUid, '123456')
|
||||
assert.equal(session.nickname, '微博测试账号')
|
||||
assert.equal(
|
||||
calls.some((call) => call.url.includes('/ajax/side/info')),
|
||||
false,
|
||||
)
|
||||
|
||||
const loginCall = calls.find((item) => item.url.includes('/sso/v2/login'))
|
||||
assert.ok(loginCall)
|
||||
@@ -233,6 +248,19 @@ test('微博短信登录建立会话并可生成一次性注入票据', async ()
|
||||
assert.equal(form.get('type'), '2')
|
||||
assert.equal(form.get('username'), 'T3Gs3iR_9fN7A9t')
|
||||
assert.equal(form.get('scode'), 'T3r81iMS')
|
||||
assert.equal(
|
||||
form.get('url'),
|
||||
'https://weibo.com/newlogin?tabtype=weibo&gid=102803&openLoginLayer=0&url=https://weibo.com/',
|
||||
)
|
||||
assert.equal(form.get('rid')?.length, 30)
|
||||
assert.notEqual(form.get('rid'), 'norid')
|
||||
const loginHeaders = loginCall.init.headers as Record<string, string>
|
||||
assert.equal(
|
||||
loginHeaders.referer,
|
||||
'https://passport.weibo.com/sso/signin?entry=miniblog&source=miniblog&disp=popup' +
|
||||
'&url=https%3A%2F%2Fweibo.com%2Fnewlogin%3Ftabtype%3Dweibo%26gid%3D102803' +
|
||||
'%26openLoginLayer%3D0%26url%3Dhttps%3A%2F%2Fweibo.com%2F&from=weibopro',
|
||||
)
|
||||
|
||||
const ticket = await connector.createBrowserTicket({
|
||||
sessionId,
|
||||
@@ -248,6 +276,63 @@ test('微博短信登录建立会话并可生成一次性注入票据', async ()
|
||||
await assert.rejects(() => connector.consumeBrowserTicket(ticket.ticket), /票据不存在或已过期/)
|
||||
})
|
||||
|
||||
test('微博短信登录兼容成功响应省略 act、直接返回 data.location', async () => {
|
||||
const { fetchImpl } = createFetchMock((url) => {
|
||||
if (url.includes('/sso/v2/login')) {
|
||||
return jsonResponse({
|
||||
retcode: 20000000,
|
||||
msg: '',
|
||||
data: {
|
||||
location: 'https://passport.weibo.com/sso/v2/goto?ticket=demo-flat',
|
||||
},
|
||||
})
|
||||
}
|
||||
return defaultHandler(url)
|
||||
})
|
||||
const connector = new WeiboNativeConnector({ fetchImpl })
|
||||
await connector.sendSmsCode({ taskId: 1, mobile: '13800138000' })
|
||||
const { session } = await connector.loginWithSms({
|
||||
taskId: 1,
|
||||
orderNo: 'MOCKWB-FLAT',
|
||||
mobile: '13800138000',
|
||||
code: '123456',
|
||||
})
|
||||
|
||||
assert.equal(session.status, 'authenticated')
|
||||
assert.equal(session.hasCredential, true)
|
||||
})
|
||||
|
||||
test('微博登录落地页无账号配置时会显式请求首页读取账号', async () => {
|
||||
const { fetchImpl, calls } = createFetchMock((url) => {
|
||||
if (url.includes('/sso/v2/goto')) {
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
headers: { location: 'https://weibo.com/intermediate' },
|
||||
})
|
||||
}
|
||||
if (url === 'https://weibo.com/intermediate') {
|
||||
return new Response('<html>intermediate</html>', {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'text/html' },
|
||||
})
|
||||
}
|
||||
return defaultHandler(url)
|
||||
})
|
||||
const connector = new WeiboNativeConnector({ fetchImpl })
|
||||
await connector.sendSmsCode({ taskId: 1, mobile: '13800138000' })
|
||||
const { session } = await connector.loginWithSms({
|
||||
taskId: 1,
|
||||
orderNo: 'MOCKWB-HOME',
|
||||
mobile: '13800138000',
|
||||
code: '123456',
|
||||
})
|
||||
|
||||
assert.equal(session.status, 'authenticated')
|
||||
assert.equal(session.huyaUid, '123456')
|
||||
assert.ok(calls.some((call) => call.url === 'https://weibo.com/intermediate'))
|
||||
assert.ok(calls.some((call) => call.url === 'https://weibo.com/'))
|
||||
})
|
||||
|
||||
test('微博短信发送遇到 mfa_1 时返回易盾挑战,完成挑战后可用 mfa_id 重发', async () => {
|
||||
let sendCount = 0
|
||||
const { fetchImpl, calls } = createFetchMock((url, init) => {
|
||||
|
||||
Reference in New Issue
Block a user