feat(半自动履约): 补齐微博游戏角色绑定流程
This commit is contained in:
@@ -24,6 +24,8 @@ import type {
|
||||
|
||||
const PASSPORT_BASE = 'https://passport.weibo.com'
|
||||
const WEIBO_BASE = 'https://weibo.com'
|
||||
const WEIBO_VIPCLUB_HOME = 'https://vipclub.e.weibo.com/aj/mall/home'
|
||||
const WEIBO_LIVELINK_QRCODE = 'https://livelinkbind.game.qq.com/api/qrcode/getMiniAppQrcode'
|
||||
const WEIBO_RETURN_URL = 'https://weibo.com/'
|
||||
const WEIBO_LOGIN_URL =
|
||||
`https://weibo.com/newlogin?tabtype=weibo&gid=102803&openLoginLayer=0` +
|
||||
@@ -35,6 +37,9 @@ const SIGNIN_REFERER =
|
||||
const PC_UA =
|
||||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' +
|
||||
'Chrome/155.0.0.0 Safari/537.36'
|
||||
const WEIBO_MOBILE_UA =
|
||||
'Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) ' +
|
||||
'AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Weibo'
|
||||
|
||||
const LOGIN_QR_TTL_MS = 5 * 60 * 1000
|
||||
const CREDENTIAL_TTL_MS = 24 * 60 * 60 * 1000
|
||||
@@ -43,6 +48,8 @@ const SMS_COOKIE_TTL_MS = 10 * 60 * 1000
|
||||
const COUNTRY_CODE_TTL_MS = 60 * 60 * 1000
|
||||
const MAX_SESSIONS = 200
|
||||
const TICKET_PREFIX = 'weibo-ticket-'
|
||||
const WEIBO_BINDING_QR_TTL_MS = 10 * 60 * 1000
|
||||
const WEIBO_AUTH_ERROR_CODES = new Set([100002, 100004, 400000, 400002])
|
||||
export const WEIBO_YIDUN_CAPTCHA_ID = '7cda0ba2785647ada4d6e946ddb2d465'
|
||||
|
||||
export type WeiboCountryCode = {
|
||||
@@ -93,6 +100,29 @@ type WeiboAccount = {
|
||||
avatar: string
|
||||
}
|
||||
|
||||
type WeiboGameRole = {
|
||||
isBound: boolean
|
||||
roleName: string
|
||||
canRebind: boolean
|
||||
rebindRemainDays: number
|
||||
bindUrl: string
|
||||
}
|
||||
|
||||
type WeiboGameRoleError = {
|
||||
code: string
|
||||
message: string
|
||||
}
|
||||
|
||||
type WeiboBindingQrState = {
|
||||
channel: 'wx' | 'qq'
|
||||
qrImage: string
|
||||
qrUrl: string
|
||||
token: string
|
||||
expiresAtMs: number
|
||||
rebindRequested: boolean
|
||||
baselineRoleName: string
|
||||
}
|
||||
|
||||
type WeiboTicket = {
|
||||
ticket: string
|
||||
targetUrl: string
|
||||
@@ -307,6 +337,10 @@ type WeiboSession = {
|
||||
message: string
|
||||
cookies: WeiboCookieJar
|
||||
account: WeiboAccount | null
|
||||
gameRole: WeiboGameRole | null
|
||||
gameRoleError: WeiboGameRoleError | null
|
||||
bindingQr: WeiboBindingQrState | null
|
||||
lastBindingChannel: 'wx' | 'qq' | ''
|
||||
tickets: Map<string, WeiboTicket>
|
||||
}
|
||||
|
||||
@@ -343,6 +377,55 @@ function iso(value: number): string {
|
||||
return new Date(value).toISOString()
|
||||
}
|
||||
|
||||
function weiboErrorCode(error: unknown): string {
|
||||
return error && typeof error === 'object'
|
||||
? String((error as { errorCode?: unknown }).errorCode || '').trim()
|
||||
: ''
|
||||
}
|
||||
|
||||
export function extractWeiboBindRawUrl(bindUrlInput: unknown): string {
|
||||
const bindUrl = String(bindUrlInput || '').trim()
|
||||
if (!bindUrl) {
|
||||
throw createHttpError('微博未返回角色绑定链接', {
|
||||
statusCode: 409,
|
||||
errorCode: 'weibo_bind_url_missing',
|
||||
})
|
||||
}
|
||||
let path = ''
|
||||
try {
|
||||
path = new URL(bindUrl).searchParams.get('path') || ''
|
||||
} catch {
|
||||
throw createHttpError('微博角色绑定链接格式错误', {
|
||||
statusCode: 502,
|
||||
errorCode: 'weibo_bind_url_invalid',
|
||||
})
|
||||
}
|
||||
const marker = '/pages/gameAccountBind/index?'
|
||||
const markerIndex = path.indexOf(marker)
|
||||
if (markerIndex < 0) {
|
||||
throw createHttpError('微博角色绑定链接缺少绑定页面参数', {
|
||||
statusCode: 502,
|
||||
errorCode: 'weibo_bind_url_invalid',
|
||||
})
|
||||
}
|
||||
const rawUrl = path.slice(markerIndex + marker.length)
|
||||
if (!rawUrl) {
|
||||
throw createHttpError('微博角色绑定链接参数为空', {
|
||||
statusCode: 502,
|
||||
errorCode: 'weibo_bind_url_invalid',
|
||||
})
|
||||
}
|
||||
return rawUrl
|
||||
}
|
||||
|
||||
function weiboBindQrImageSrc(value: unknown): string {
|
||||
const text = String(value || '').trim()
|
||||
if (!text) return ''
|
||||
if (/^(https?:\/\/|data:image\/)/i.test(text)) return text
|
||||
const mime = text.startsWith('iVBOR') ? 'image/png' : 'image/jpeg'
|
||||
return `data:${mime};base64,${text}`
|
||||
}
|
||||
|
||||
function readSetCookie(headers: Headers): string[] {
|
||||
const withGetSetCookie = headers as Headers & { getSetCookie?: () => string[] }
|
||||
if (typeof withGetSetCookie.getSetCookie === 'function') {
|
||||
@@ -412,6 +495,10 @@ export class WeiboNativeConnector {
|
||||
message: '请使用微博 App 扫码登录',
|
||||
cookies,
|
||||
account: null,
|
||||
gameRole: null,
|
||||
gameRoleError: null,
|
||||
bindingQr: null,
|
||||
lastBindingChannel: '',
|
||||
tickets: new Map(),
|
||||
}
|
||||
this.sessions.set(sessionId, session)
|
||||
@@ -703,6 +790,10 @@ export class WeiboNativeConnector {
|
||||
message: '微博登录成功',
|
||||
cookies: state.cookies,
|
||||
account: null,
|
||||
gameRole: null,
|
||||
gameRoleError: null,
|
||||
bindingQr: null,
|
||||
lastBindingChannel: '',
|
||||
tickets: new Map(),
|
||||
}
|
||||
this.smsSessions.delete(stateKey)
|
||||
@@ -719,6 +810,67 @@ export class WeiboNativeConnector {
|
||||
errorCode: 'weibo_login_required',
|
||||
})
|
||||
}
|
||||
try {
|
||||
await this.refreshGameRole(session)
|
||||
} catch (error) {
|
||||
if (weiboErrorCode(error) === 'weibo_credential_invalid') throw error
|
||||
return this.bindingView(session)
|
||||
}
|
||||
const role = session.gameRole
|
||||
const qr = session.bindingQr
|
||||
if (role?.isBound && qr && (!qr.rebindRequested || role.roleName !== qr.baselineRoleName)) {
|
||||
session.bindingQr = null
|
||||
}
|
||||
return this.bindingView(session)
|
||||
}
|
||||
|
||||
async startBinding(
|
||||
sessionId: string,
|
||||
options: { channel?: 'wx' | 'qq'; forceRebind?: boolean } = {},
|
||||
): Promise<ConnectorBindingSession> {
|
||||
const session = this.requireSession(sessionId)
|
||||
if (session.status !== 'authenticated' || !session.account) {
|
||||
throw createHttpError('微博账号尚未登录', {
|
||||
statusCode: 409,
|
||||
errorCode: 'weibo_login_required',
|
||||
})
|
||||
}
|
||||
const channel = options.channel === 'qq' ? 'qq' : 'wx'
|
||||
const role = await this.refreshGameRole(session)
|
||||
if (role.isBound && !role.canRebind) {
|
||||
session.bindingQr = null
|
||||
const wait = role.rebindRemainDays > 0 ? `,还需等待 ${role.rebindRemainDays} 天` : ''
|
||||
throw createHttpError(
|
||||
`微博账号已绑定角色${role.roleName ? `「${role.roleName}」` : ''},当前不可换绑${wait}`,
|
||||
{
|
||||
statusCode: 409,
|
||||
errorCode: 'weibo_rebind_cooldown',
|
||||
},
|
||||
)
|
||||
}
|
||||
if (role.isBound && options.forceRebind !== true) {
|
||||
session.bindingQr = null
|
||||
return this.bindingView(session)
|
||||
}
|
||||
if (!role.bindUrl) {
|
||||
throw createHttpError('微博没有返回当前账号的角色绑定链接', {
|
||||
statusCode: 409,
|
||||
errorCode: 'weibo_bind_url_missing',
|
||||
})
|
||||
}
|
||||
const qr = await this.generateBindQr(role.bindUrl, channel)
|
||||
const nowMs = this.now()
|
||||
session.bindingQr = {
|
||||
channel,
|
||||
qrImage: qr.image,
|
||||
qrUrl: '',
|
||||
token: qr.token,
|
||||
expiresAtMs: nowMs + WEIBO_BINDING_QR_TTL_MS,
|
||||
rebindRequested: role.isBound,
|
||||
baselineRoleName: role.roleName,
|
||||
}
|
||||
session.lastBindingChannel = channel
|
||||
session.message = '请使用微信或 QQ 扫码完成微博游戏角色绑定'
|
||||
return this.bindingView(session)
|
||||
}
|
||||
|
||||
@@ -845,6 +997,10 @@ export class WeiboNativeConnector {
|
||||
...account,
|
||||
nickname: account.nickname || String(input.nickname || ''),
|
||||
},
|
||||
gameRole: null,
|
||||
gameRoleError: null,
|
||||
bindingQr: null,
|
||||
lastBindingChannel: '',
|
||||
tickets: new Map(),
|
||||
}
|
||||
this.sessions.set(session.sessionId, session)
|
||||
@@ -885,6 +1041,15 @@ export class WeiboNativeConnector {
|
||||
}
|
||||
session.status = 'authenticated'
|
||||
session.message = '微博登录成功'
|
||||
await this.refreshGameRole(session).catch((error) => {
|
||||
session.gameRoleError = {
|
||||
code: weiboErrorCode(error) || 'weibo_game_role_query_failed',
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
}
|
||||
logWarn('[weibo/game-role]', '登录后读取微博角色绑定状态失败', {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
private async followWithCookies(
|
||||
@@ -917,6 +1082,134 @@ export class WeiboNativeConnector {
|
||||
return { finalUrl: currentUrl, body }
|
||||
}
|
||||
|
||||
private async refreshGameRole(session: WeiboSession): Promise<WeiboGameRole> {
|
||||
if (session.status !== 'authenticated' || !session.account?.uid) {
|
||||
throw createHttpError('微博账号尚未登录', {
|
||||
statusCode: 409,
|
||||
errorCode: 'weibo_login_required',
|
||||
})
|
||||
}
|
||||
try {
|
||||
const url = `${WEIBO_VIPCLUB_HOME}?F=&_t=${this.now()}`
|
||||
const response = await this.fetchImpl(url, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'user-agent': WEIBO_MOBILE_UA,
|
||||
accept: 'application/json, text/plain, */*',
|
||||
referer: 'https://vipclub.e.weibo.com/game/homepage',
|
||||
cookie: session.cookies.headerFor('https://vipclub.e.weibo.com/'),
|
||||
},
|
||||
signal: AbortSignal.timeout(this.timeoutMs),
|
||||
})
|
||||
session.cookies.addFromResponse(response.headers, response.url || url)
|
||||
const payload = (await response.json().catch(() => null)) as {
|
||||
code?: number
|
||||
msg?: string
|
||||
data?: {
|
||||
game_role?: {
|
||||
is_bound?: boolean
|
||||
role_name?: string
|
||||
can_rebind?: boolean
|
||||
rebind_remain_days?: number
|
||||
bind_url?: string
|
||||
}
|
||||
}
|
||||
} | null
|
||||
if (!response.ok) {
|
||||
throw createHttpError(`微博角色信息查询失败:HTTP ${response.status}`, {
|
||||
statusCode: 502,
|
||||
errorCode: 'weibo_game_role_query_failed',
|
||||
})
|
||||
}
|
||||
const code = Number(payload?.code)
|
||||
if (WEIBO_AUTH_ERROR_CODES.has(code)) {
|
||||
throw createHttpError(payload?.msg || '微博 CK 已失效,请重新登录', {
|
||||
statusCode: 409,
|
||||
errorCode: 'weibo_credential_invalid',
|
||||
})
|
||||
}
|
||||
if (!payload || code !== 100000) {
|
||||
throw createHttpError(payload?.msg || '微博角色信息查询失败', {
|
||||
statusCode: 502,
|
||||
errorCode: 'weibo_game_role_query_failed',
|
||||
})
|
||||
}
|
||||
const role = payload.data?.game_role || {}
|
||||
const gameRole: WeiboGameRole = {
|
||||
isBound: role.is_bound === true,
|
||||
roleName: String(role.role_name || '').trim(),
|
||||
canRebind: role.can_rebind === true,
|
||||
rebindRemainDays: Math.max(0, Math.trunc(Number(role.rebind_remain_days) || 0)),
|
||||
bindUrl: String(role.bind_url || '').trim(),
|
||||
}
|
||||
session.gameRole = gameRole
|
||||
session.gameRoleError = null
|
||||
return gameRole
|
||||
} catch (error) {
|
||||
session.gameRoleError = {
|
||||
code: weiboErrorCode(error) || 'weibo_game_role_query_failed',
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private async generateBindQr(
|
||||
bindUrl: string,
|
||||
channel: 'wx' | 'qq',
|
||||
): Promise<{ image: string; token: string }> {
|
||||
const rawUrl = extractWeiboBindRawUrl(bindUrl)
|
||||
const query = new URLSearchParams(rawUrl)
|
||||
const livePlatId = String(query.get('livePlatId') || '')
|
||||
const actId = String(query.get('actId') || '')
|
||||
const fromId = String(query.get('fromId') || '').slice(0, 32)
|
||||
if (!livePlatId || !actId) {
|
||||
throw createHttpError('微博绑定链接缺少活动参数', {
|
||||
statusCode: 502,
|
||||
errorCode: 'weibo_bind_url_invalid',
|
||||
})
|
||||
}
|
||||
const suffix = crypto.randomBytes(4).toString('hex')
|
||||
const response = await this.fetchImpl(WEIBO_LIVELINK_QRCODE, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'content-type': 'application/json;charset=UTF-8',
|
||||
accept: 'application/json, text/plain, */*',
|
||||
origin: 'https://livelink.qq.com',
|
||||
referer: 'https://livelink.qq.com/',
|
||||
'gap-plat-id': livePlatId,
|
||||
'gap-act-id': actId,
|
||||
'gap-user-from': 'pc',
|
||||
'gap-from-id': fromId,
|
||||
'vulcan-acctype': 'auth_in_h5',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
queryString: `${rawUrl}&sessionId=${Date.now()}_${suffix}`,
|
||||
accountType: channel,
|
||||
}),
|
||||
signal: AbortSignal.timeout(this.timeoutMs),
|
||||
})
|
||||
const payload = (await response.json().catch(() => null)) as {
|
||||
iRet?: number
|
||||
sMsg?: string
|
||||
jData?: { qrcode?: string; qrcodeToken?: string }
|
||||
} | null
|
||||
if (!response.ok || Number(payload?.iRet) !== 0) {
|
||||
throw createHttpError(payload?.sMsg || '微博绑定二维码生成失败', {
|
||||
statusCode: 502,
|
||||
errorCode: 'weibo_bind_qrcode_failed',
|
||||
})
|
||||
}
|
||||
const image = weiboBindQrImageSrc(payload?.jData?.qrcode)
|
||||
if (!image) {
|
||||
throw createHttpError('微博绑定接口没有返回二维码', {
|
||||
statusCode: 502,
|
||||
errorCode: 'weibo_bind_qrcode_failed',
|
||||
})
|
||||
}
|
||||
return { image, token: String(payload?.jData?.qrcodeToken || '') }
|
||||
}
|
||||
|
||||
private async fetchHomePage(cookies: WeiboCookieJar): Promise<{ status: number; body: string }> {
|
||||
try {
|
||||
const response = await this.fetchImpl(`${WEIBO_BASE}/`, {
|
||||
@@ -1071,19 +1364,48 @@ export class WeiboNativeConnector {
|
||||
|
||||
private bindingView(session: WeiboSession): ConnectorBindingSession {
|
||||
const account = session.account
|
||||
const role = session.gameRole
|
||||
const qr = session.bindingQr
|
||||
const qrActive = Boolean(qr && qr.expiresAtMs > this.now())
|
||||
const status: ConnectorBindingSession['status'] = session.gameRoleError
|
||||
? 'failed'
|
||||
: qrActive
|
||||
? 'qr_pending'
|
||||
: qr
|
||||
? 'expired'
|
||||
: role?.isBound
|
||||
? 'confirmed'
|
||||
: 'not_started'
|
||||
const cooldownDays = role?.isBound && !role.canRebind ? Math.max(0, role.rebindRemainDays) : 0
|
||||
const channel = qr?.channel || session.lastBindingChannel
|
||||
const channelLabel = channel === 'qq' ? 'QQ' : channel === 'wx' ? '微信' : '微博'
|
||||
return {
|
||||
sessionId: session.sessionId,
|
||||
status: 'confirmed',
|
||||
qrImage: '',
|
||||
qrExpiresAt: '',
|
||||
qrUrl: '',
|
||||
status,
|
||||
qrImage: qrActive ? qr?.qrImage || '' : '',
|
||||
qrExpiresAt: qrActive ? iso(Number(qr?.expiresAtMs || 0)) : '',
|
||||
qrUrl: qrActive ? qr?.qrUrl || '' : '',
|
||||
bindGameAccount: account?.nickname || '',
|
||||
bindGameRole: account?.uid || '',
|
||||
bindGameRoleId: account?.uid || '',
|
||||
bindGameChannel: '微博',
|
||||
hasExistingBinding: true,
|
||||
rebindRequested: false,
|
||||
message: '微博账号已授权',
|
||||
bindGameRole: role?.roleName || '',
|
||||
bindGameRoleId: '',
|
||||
bindGameChannel: channelLabel,
|
||||
hasExistingBinding: role?.isBound === true,
|
||||
rebindRequested: qr?.rebindRequested === true,
|
||||
rebindCooldownDays: cooldownDays,
|
||||
nextRebindAt: cooldownDays > 0 ? iso(this.now() + cooldownDays * 24 * 60 * 60 * 1000) : '',
|
||||
message: session.gameRoleError
|
||||
? session.gameRoleError.message
|
||||
: qrActive
|
||||
? qr?.rebindRequested
|
||||
? '请扫码选择新的微博游戏角色'
|
||||
: '请扫码完成微博游戏角色绑定'
|
||||
: status === 'expired'
|
||||
? '微博绑定二维码已过期,请重新获取'
|
||||
: status === 'confirmed'
|
||||
? `微博账号已绑定角色${role?.roleName ? `「${role.roleName}」` : ''}`
|
||||
: role
|
||||
? '微博账号尚未绑定游戏角色'
|
||||
: session.message || '微博角色绑定状态尚未就绪',
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,20 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { WEIBO_TICKET_PREFIX, WeiboNativeConnector } from './weibo-native-connector.js'
|
||||
import {
|
||||
extractWeiboBindRawUrl,
|
||||
WEIBO_TICKET_PREFIX,
|
||||
WeiboNativeConnector,
|
||||
} from './weibo-native-connector.js'
|
||||
|
||||
type CapturedCall = { url: string; init: RequestInit }
|
||||
|
||||
const BIND_URL =
|
||||
'sinaweibo://wbdiversion?username=gh_test&path=%2Fpages%2FgameAccountBind%2Findex' +
|
||||
'%3FactId%3D16722%26code%3Dabc%252Bdef%253D%26gameId%3Dcjm' +
|
||||
'%26livePlatId%3Dweiyouxi%26nonce%3Dabc123%26sig%3D0123456789abcdef' +
|
||||
'%26t%3D1794046086%26v%3D2.0'
|
||||
|
||||
function jsonResponse(payload: unknown): Response {
|
||||
return new Response(JSON.stringify(payload), {
|
||||
status: 200,
|
||||
@@ -129,9 +139,209 @@ function defaultHandler(url: string): Response {
|
||||
},
|
||||
})
|
||||
}
|
||||
if (url.startsWith('https://vipclub.e.weibo.com/aj/mall/home')) {
|
||||
return jsonResponse({
|
||||
code: 100000,
|
||||
msg: 'success',
|
||||
data: {
|
||||
game_role: {
|
||||
is_bound: false,
|
||||
role_name: '',
|
||||
can_rebind: true,
|
||||
rebind_remain_days: 0,
|
||||
bind_url: BIND_URL,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
if (url === 'https://livelinkbind.game.qq.com/api/qrcode/getMiniAppQrcode') {
|
||||
return jsonResponse({
|
||||
iRet: 0,
|
||||
sMsg: 'ok',
|
||||
jData: {
|
||||
qrcode: 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAAB',
|
||||
qrcodeToken: 'bind-token-1',
|
||||
},
|
||||
})
|
||||
}
|
||||
return new Response('not found', { status: 404 })
|
||||
}
|
||||
|
||||
async function loginWeiboSession(connector: WeiboNativeConnector) {
|
||||
await connector.sendSmsCode({ taskId: 1, mobile: '13800138000' })
|
||||
const { sessionId } = await connector.loginWithSms({
|
||||
taskId: 1,
|
||||
orderNo: 'MOCKWB1',
|
||||
mobile: '13800138000',
|
||||
code: '123456',
|
||||
})
|
||||
return sessionId
|
||||
}
|
||||
|
||||
test('微博 bind_url 提取保留内层编码并拒绝错误路径', () => {
|
||||
const raw = extractWeiboBindRawUrl(BIND_URL)
|
||||
assert.ok(raw.startsWith('actId=16722&code=abc%2Bdef%3D'))
|
||||
assert.equal(raw.includes('abc+def='), false)
|
||||
assert.throws(
|
||||
() => extractWeiboBindRawUrl('sinaweibo://wbdiversion?path=%2Fwrong'),
|
||||
(error: { errorCode?: string }) => error.errorCode === 'weibo_bind_url_invalid',
|
||||
)
|
||||
})
|
||||
|
||||
test('微博未绑定角色时可生成微信和 QQ 绑定二维码', async () => {
|
||||
const { fetchImpl, calls } = createFetchMock(defaultHandler)
|
||||
const connector = new WeiboNativeConnector({ fetchImpl })
|
||||
const sessionId = await loginWeiboSession(connector)
|
||||
|
||||
const wxBinding = await connector.startBinding(sessionId, { channel: 'wx' })
|
||||
assert.equal(wxBinding.status, 'qr_pending')
|
||||
assert.equal(wxBinding.bindGameChannel, '微信')
|
||||
assert.match(wxBinding.qrImage, /^data:image\/png;base64,/)
|
||||
|
||||
const qqBinding = await connector.startBinding(sessionId, { channel: 'qq' })
|
||||
assert.equal(qqBinding.status, 'qr_pending')
|
||||
assert.equal(qqBinding.bindGameChannel, 'QQ')
|
||||
|
||||
const qrCalls = calls.filter(
|
||||
(call) => call.url === 'https://livelinkbind.game.qq.com/api/qrcode/getMiniAppQrcode',
|
||||
)
|
||||
assert.equal(qrCalls.length, 2)
|
||||
const wxBody = JSON.parse(String(qrCalls[0]?.init.body)) as {
|
||||
accountType: string
|
||||
queryString: string
|
||||
}
|
||||
const qqHeaders = qrCalls[1]?.init.headers as Record<string, string>
|
||||
assert.equal(wxBody.accountType, 'wx')
|
||||
assert.ok(wxBody.queryString.startsWith(`${extractWeiboBindRawUrl(BIND_URL)}&sessionId=`))
|
||||
assert.equal(qqHeaders['gap-act-id'], '16722')
|
||||
assert.equal(qqHeaders['gap-plat-id'], 'weiyouxi')
|
||||
assert.equal(qqHeaders['vulcan-acctype'], 'auth_in_h5')
|
||||
})
|
||||
|
||||
test('微博已绑定且不可换绑时返回冷却期错误', async () => {
|
||||
const { fetchImpl } = createFetchMock((url) => {
|
||||
if (url.startsWith('https://vipclub.e.weibo.com/aj/mall/home')) {
|
||||
return jsonResponse({
|
||||
code: 100000,
|
||||
data: {
|
||||
game_role: {
|
||||
is_bound: true,
|
||||
role_name: '已有角色',
|
||||
can_rebind: false,
|
||||
rebind_remain_days: 7,
|
||||
bind_url: BIND_URL,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
return defaultHandler(url)
|
||||
})
|
||||
const connector = new WeiboNativeConnector({ fetchImpl })
|
||||
const sessionId = await loginWeiboSession(connector)
|
||||
|
||||
await assert.rejects(
|
||||
() => connector.startBinding(sessionId, { channel: 'wx', forceRebind: true }),
|
||||
(error: { errorCode?: string; message?: string }) => {
|
||||
assert.equal(error.errorCode, 'weibo_rebind_cooldown')
|
||||
assert.match(error.message || '', /还需等待 7 天/)
|
||||
return true
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
test('微博已有角色时默认直接确认,强制换绑后按新角色名确认', async () => {
|
||||
let roleName = '旧角色'
|
||||
const { fetchImpl } = createFetchMock((url) => {
|
||||
if (url.startsWith('https://vipclub.e.weibo.com/aj/mall/home')) {
|
||||
return jsonResponse({
|
||||
code: 100000,
|
||||
data: {
|
||||
game_role: {
|
||||
is_bound: true,
|
||||
role_name: roleName,
|
||||
can_rebind: true,
|
||||
rebind_remain_days: 0,
|
||||
bind_url: BIND_URL,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
return defaultHandler(url)
|
||||
})
|
||||
const connector = new WeiboNativeConnector({ fetchImpl })
|
||||
const sessionId = await loginWeiboSession(connector)
|
||||
|
||||
const existing = await connector.startBinding(sessionId, { channel: 'wx' })
|
||||
assert.equal(existing.status, 'confirmed')
|
||||
assert.equal(existing.bindGameRole, '旧角色')
|
||||
|
||||
const rebind = await connector.startBinding(sessionId, {
|
||||
channel: 'qq',
|
||||
forceRebind: true,
|
||||
})
|
||||
assert.equal(rebind.status, 'qr_pending')
|
||||
assert.equal(rebind.rebindRequested, true)
|
||||
|
||||
roleName = '新角色'
|
||||
const confirmed = await connector.getBinding(sessionId)
|
||||
assert.equal(confirmed.status, 'confirmed')
|
||||
assert.equal(confirmed.bindGameRole, '新角色')
|
||||
assert.equal(confirmed.qrImage, '')
|
||||
})
|
||||
|
||||
test('微博角色查询遇到 CK 失效时向服务层抛出凭证错误', async () => {
|
||||
let expired = false
|
||||
const { fetchImpl } = createFetchMock((url) => {
|
||||
if (url.startsWith('https://vipclub.e.weibo.com/aj/mall/home')) {
|
||||
return jsonResponse(
|
||||
expired
|
||||
? { code: 400002, msg: '未登陆' }
|
||||
: {
|
||||
code: 100000,
|
||||
data: {
|
||||
game_role: {
|
||||
is_bound: false,
|
||||
role_name: '',
|
||||
can_rebind: true,
|
||||
rebind_remain_days: 0,
|
||||
bind_url: BIND_URL,
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
return defaultHandler(url)
|
||||
})
|
||||
const connector = new WeiboNativeConnector({ fetchImpl })
|
||||
const sessionId = await loginWeiboSession(connector)
|
||||
expired = true
|
||||
|
||||
await assert.rejects(
|
||||
() => connector.getBinding(sessionId),
|
||||
(error: { errorCode?: string }) => error.errorCode === 'weibo_credential_invalid',
|
||||
)
|
||||
})
|
||||
|
||||
test('微博来联二维码失败时不生成虚假绑定状态', async () => {
|
||||
const { fetchImpl } = createFetchMock((url) => {
|
||||
if (url === 'https://livelinkbind.game.qq.com/api/qrcode/getMiniAppQrcode') {
|
||||
return jsonResponse({ iRet: -1, sMsg: '刷新二维码频率过快,请间隔5秒后重试' })
|
||||
}
|
||||
return defaultHandler(url)
|
||||
})
|
||||
const connector = new WeiboNativeConnector({ fetchImpl })
|
||||
const sessionId = await loginWeiboSession(connector)
|
||||
|
||||
await assert.rejects(
|
||||
() => connector.startBinding(sessionId, { channel: 'wx' }),
|
||||
(error: { errorCode?: string; message?: string }) => {
|
||||
assert.equal(error.errorCode, 'weibo_bind_qrcode_failed')
|
||||
assert.match(error.message || '', /间隔5秒/)
|
||||
return true
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
test('微博二维码会话解析 qrid 并把图片转成 base64', async () => {
|
||||
const { fetchImpl, calls } = createFetchMock(defaultHandler)
|
||||
const connector = new WeiboNativeConnector({ fetchImpl })
|
||||
|
||||
Reference in New Issue
Block a user