feat(semi-auto): 支持微博半自动履约与手机号国家码登录
新增微博内置 Connector:扫码/短信登录、Cookie 获取与一次性浏览器票据;客户页支持国家码选择、短信/扫码登录及登录即授权;dev-mock 与后台任务页适配微博 Mock 单。
This commit is contained in:
@@ -0,0 +1,750 @@
|
||||
/**
|
||||
* order_site 内置微博半自动 Connector(Mock 闭环用)。
|
||||
*
|
||||
* 支持:
|
||||
* - 微博扫码登录(passport /sso/v2/qrcode/*)
|
||||
* - 手机号短信验证码登录(passport /sso/v2/sms/send + /sso/v2/login)
|
||||
* - 登录后账号信息
|
||||
* - 一次性浏览器注入票据
|
||||
*
|
||||
* 手机号、验证码、Cookie 都只保存在内存会话中,不落库、不写日志。
|
||||
*/
|
||||
|
||||
import crypto from 'node:crypto'
|
||||
|
||||
import { createHttpError } from '../../../utils/http.js'
|
||||
import type {
|
||||
ConnectorBindingSession,
|
||||
ConnectorBrowserTicket,
|
||||
ConnectorInjectionPayload,
|
||||
ConnectorLoginSession,
|
||||
} from '../huya-connector-client.js'
|
||||
|
||||
const PASSPORT_BASE = 'https://passport.weibo.com'
|
||||
const WEIBO_BASE = 'https://weibo.com'
|
||||
const WEIBO_LOGIN_URL =
|
||||
'https://weibo.com/newlogin?tabtype=weibo&gid=102803&openLoginLayer=0&url=https%3A%2F%2Fweibo.com%2F'
|
||||
const WEIBO_LOGIN_VER = '20250520'
|
||||
const SIGNIN_REFERER =
|
||||
`${PASSPORT_BASE}/sso/signin?entry=miniblog&source=miniblog&disp=popup` +
|
||||
`&url=${encodeURIComponent(WEIBO_LOGIN_URL)}&from=weibopro`
|
||||
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 LOGIN_QR_TTL_MS = 5 * 60 * 1000
|
||||
const CREDENTIAL_TTL_MS = 24 * 60 * 60 * 1000
|
||||
const BROWSER_TICKET_TTL_MS = 2 * 60 * 1000
|
||||
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-'
|
||||
|
||||
export type WeiboCountryCode = {
|
||||
code: string
|
||||
name: string
|
||||
}
|
||||
|
||||
const FALLBACK_COUNTRY_CODES: WeiboCountryCode[] = [
|
||||
{ code: '86', name: '中国' },
|
||||
{ code: '852', name: '中国香港' },
|
||||
{ code: '886', name: '中国台湾' },
|
||||
{ code: '853', name: '中国澳门' },
|
||||
{ code: '81', name: '日本' },
|
||||
]
|
||||
|
||||
// 微博网页登录 JS 会对手机号/验证码做一层 XOR + base64url + 字母替换编码。
|
||||
const SSO_ENCODE_KEY = 'x9Lp2WnQ'
|
||||
const SSO_BASE_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
|
||||
const SSO_MAP_ALPHABET = 'iaAehJvQ7RIDBX5L31T0kcf9ElVbpMdPZSmzoN_uxGO-2rFUtyY6sHCwKj4Wqgn8'
|
||||
|
||||
function encodeSsoField(value: string): string {
|
||||
const bytes = Buffer.from(String(value || ''), 'utf8')
|
||||
const key = Buffer.from(SSO_ENCODE_KEY, 'utf8')
|
||||
const xored = Buffer.allocUnsafe(bytes.length)
|
||||
for (let index = 0; index < bytes.length; index += 1) {
|
||||
const byte = bytes[index] ?? 0
|
||||
const keyByte = key[index % key.length] ?? 0
|
||||
xored[index] = byte ^ keyByte
|
||||
}
|
||||
const encoded = xored
|
||||
.toString('base64')
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=+$/, '')
|
||||
let result = ''
|
||||
for (const char of encoded) {
|
||||
const alphabetIndex = SSO_BASE_ALPHABET.indexOf(char)
|
||||
result += alphabetIndex >= 0 ? SSO_MAP_ALPHABET[alphabetIndex] : char
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
type FetchLike = typeof fetch
|
||||
|
||||
type WeiboAccount = {
|
||||
uid: string
|
||||
nickname: string
|
||||
avatar: string
|
||||
}
|
||||
|
||||
type WeiboTicket = {
|
||||
ticket: string
|
||||
targetUrl: string
|
||||
cookie: string
|
||||
expiresAtMs: number
|
||||
}
|
||||
|
||||
type WeiboSession = {
|
||||
sessionId: string
|
||||
taskId: number
|
||||
orderNo: string
|
||||
createdAtMs: number
|
||||
expiresAtMs: number
|
||||
status: ConnectorLoginSession['status']
|
||||
qrid: string
|
||||
qrImage: string
|
||||
message: string
|
||||
cookie: string
|
||||
account: WeiboAccount | null
|
||||
tickets: Map<string, WeiboTicket>
|
||||
}
|
||||
|
||||
export type WeiboNativeConnectorOptions = {
|
||||
fetchImpl?: FetchLike
|
||||
now?: () => number
|
||||
timeoutMs?: number
|
||||
stateRoot?: string
|
||||
}
|
||||
|
||||
function iso(value: number): string {
|
||||
return new Date(value).toISOString()
|
||||
}
|
||||
|
||||
function normalizeCookiePairs(cookie: string): Array<[string, string]> {
|
||||
const pairs: Array<[string, string]> = []
|
||||
for (const part of String(cookie || '').split(';')) {
|
||||
const index = part.indexOf('=')
|
||||
if (index <= 0) continue
|
||||
const key = part.slice(0, index).trim()
|
||||
const value = part.slice(index + 1).trim()
|
||||
if (key) pairs.push([key, value])
|
||||
}
|
||||
return pairs
|
||||
}
|
||||
|
||||
function cookieValue(cookie: string, key: string): string {
|
||||
for (const [itemKey, itemValue] of normalizeCookiePairs(cookie)) {
|
||||
if (itemKey === key) return itemValue
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
function buildCookieHeader(pairs: Map<string, string>): string {
|
||||
return Array.from(pairs.entries())
|
||||
.map(([key, value]) => `${key}=${value}`)
|
||||
.join('; ')
|
||||
}
|
||||
|
||||
function readSetCookie(headers: Headers): string[] {
|
||||
const withGetSetCookie = headers as Headers & { getSetCookie?: () => string[] }
|
||||
if (typeof withGetSetCookie.getSetCookie === 'function') {
|
||||
return withGetSetCookie.getSetCookie()
|
||||
}
|
||||
return (headers.get('set-cookie') || '').split(/,(?=\s*[^;,=\s]+=)/g).filter(Boolean)
|
||||
}
|
||||
|
||||
export class WeiboNativeConnector {
|
||||
private readonly sessions = new Map<string, WeiboSession>()
|
||||
private readonly smsCookies = new Map<string, { cookie: string; expiresAtMs: number }>()
|
||||
private countryCodeCache: { items: WeiboCountryCode[]; expiresAtMs: number } | null = null
|
||||
private readonly fetchImpl: FetchLike
|
||||
private readonly now: () => number
|
||||
private readonly timeoutMs: number
|
||||
|
||||
constructor(options: WeiboNativeConnectorOptions = {}) {
|
||||
this.fetchImpl = options.fetchImpl || fetch
|
||||
this.now = options.now || (() => Date.now())
|
||||
this.timeoutMs = Math.max(1000, options.timeoutMs || 15_000)
|
||||
}
|
||||
|
||||
async createQrLoginSession(input: {
|
||||
taskId: number
|
||||
orderNo: string
|
||||
}): Promise<ConnectorLoginSession> {
|
||||
this.prune()
|
||||
const sessionId = crypto.randomBytes(18).toString('base64url')
|
||||
const response = await this.fetchImpl(
|
||||
`${PASSPORT_BASE}/sso/v2/qrcode/image?entry=miniblog&size=180`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers: this.jsonHeaders(),
|
||||
signal: AbortSignal.timeout(this.timeoutMs),
|
||||
},
|
||||
)
|
||||
if (!response.ok) {
|
||||
throw createHttpError(`获取微博登录二维码失败:HTTP ${response.status}`, {
|
||||
statusCode: 502,
|
||||
errorCode: 'weibo_qrcode_failed',
|
||||
})
|
||||
}
|
||||
const payload = (await response.json().catch(() => null)) as {
|
||||
retcode?: number
|
||||
msg?: string
|
||||
data?: { qrid?: string; image?: string }
|
||||
} | null
|
||||
if (!payload || Number(payload.retcode) !== 20000000 || !payload.data?.qrid) {
|
||||
throw createHttpError(payload?.msg || '获取微博登录二维码失败', {
|
||||
statusCode: 502,
|
||||
errorCode: 'weibo_qrcode_failed',
|
||||
})
|
||||
}
|
||||
const qrImage = await this.downloadQrImage(String(payload.data.image || ''))
|
||||
const nowMs = this.now()
|
||||
const session: WeiboSession = {
|
||||
sessionId,
|
||||
taskId: Number(input.taskId) || 0,
|
||||
orderNo: String(input.orderNo || ''),
|
||||
createdAtMs: nowMs,
|
||||
expiresAtMs: nowMs + CREDENTIAL_TTL_MS,
|
||||
status: 'waiting_scan',
|
||||
qrid: String(payload.data.qrid),
|
||||
qrImage,
|
||||
message: '请使用微博 App 扫码登录',
|
||||
cookie: '',
|
||||
account: null,
|
||||
tickets: new Map(),
|
||||
}
|
||||
this.sessions.set(sessionId, session)
|
||||
return this.loginView(session)
|
||||
}
|
||||
|
||||
async getQrLoginSession(sessionId: string): Promise<ConnectorLoginSession> {
|
||||
const session = this.requireSession(sessionId)
|
||||
if (session.status === 'authenticated') return this.loginView(session)
|
||||
if (session.status === 'expired' || session.status === 'failed') return this.loginView(session)
|
||||
const checkUrl =
|
||||
`${PASSPORT_BASE}/sso/v2/qrcode/check?entry=miniblog&source=miniblog` +
|
||||
`&url=${encodeURIComponent(WEIBO_LOGIN_URL)}&qrid=${encodeURIComponent(session.qrid)}` +
|
||||
`&disp=popup&rid=norid&ver=${WEIBO_LOGIN_VER}`
|
||||
const response = await this.fetchImpl(checkUrl, {
|
||||
method: 'GET',
|
||||
headers: this.jsonHeaders(),
|
||||
signal: AbortSignal.timeout(this.timeoutMs),
|
||||
})
|
||||
if (!response.ok) {
|
||||
session.status = 'failed'
|
||||
session.message = `微博扫码状态查询失败:HTTP ${response.status}`
|
||||
return this.loginView(session)
|
||||
}
|
||||
const payload = (await response.json().catch(() => null)) as {
|
||||
retcode?: number
|
||||
msg?: string
|
||||
data?: { url?: string }
|
||||
} | null
|
||||
const retcode = Number(payload?.retcode || 0)
|
||||
if (retcode === 20000000) {
|
||||
const loginUrl = String(payload?.data?.url || '').trim()
|
||||
if (!loginUrl) {
|
||||
session.status = 'failed'
|
||||
session.message = '微博登录成功但缺少跳转地址'
|
||||
return this.loginView(session)
|
||||
}
|
||||
await this.finishLogin(
|
||||
session,
|
||||
loginUrl,
|
||||
buildCookieHeader(this.collectCookiePairs(response.headers)),
|
||||
)
|
||||
return this.loginView(session)
|
||||
}
|
||||
if ([50114000, 50114001].includes(retcode)) {
|
||||
session.status = 'waiting_scan'
|
||||
session.message = '请使用微博 App 扫码登录'
|
||||
return this.loginView(session)
|
||||
}
|
||||
if (retcode === 50114002) {
|
||||
session.status = 'scanned'
|
||||
session.message = '已扫码,请在微博客户端确认登录'
|
||||
return this.loginView(session)
|
||||
}
|
||||
if ([50114003, 50114004, 50114015].includes(retcode)) {
|
||||
session.status = 'expired'
|
||||
session.message = '登录二维码已过期,请刷新'
|
||||
return this.loginView(session)
|
||||
}
|
||||
session.status = 'failed'
|
||||
session.message = String(payload?.msg || '微博扫码登录失败')
|
||||
return this.loginView(session)
|
||||
}
|
||||
|
||||
async getCountryCodes(): Promise<WeiboCountryCode[]> {
|
||||
const nowMs = this.now()
|
||||
if (this.countryCodeCache && this.countryCodeCache.expiresAtMs > nowMs) {
|
||||
return this.countryCodeCache.items
|
||||
}
|
||||
try {
|
||||
const body = new URLSearchParams({ entry: 'miniblog', source: 'miniblog' })
|
||||
const response = await this.fetchImpl(`${PASSPORT_BASE}/sso/v2/web/config`, {
|
||||
method: 'POST',
|
||||
headers: this.formHeaders(),
|
||||
body,
|
||||
signal: AbortSignal.timeout(this.timeoutMs),
|
||||
})
|
||||
if (response.ok) {
|
||||
const payload = (await response.json().catch(() => null)) as {
|
||||
retcode?: number
|
||||
data?: {
|
||||
country_code?: Array<{
|
||||
country_code?: string | number
|
||||
local?: { zh_CN?: string }
|
||||
}>
|
||||
}
|
||||
} | null
|
||||
if (Number(payload?.retcode) === 20000000) {
|
||||
const items = (payload?.data?.country_code || [])
|
||||
.map((item) => ({
|
||||
code: String(item.country_code || '').trim(),
|
||||
name: String(item.local?.zh_CN || '').trim(),
|
||||
}))
|
||||
.filter((item) => item.code && item.name)
|
||||
if (items.length > 0) {
|
||||
this.countryCodeCache = { items, expiresAtMs: nowMs + COUNTRY_CODE_TTL_MS }
|
||||
return items
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 国家码只影响输入体验,拉取失败时使用内置兜底列表。
|
||||
}
|
||||
return FALLBACK_COUNTRY_CODES
|
||||
}
|
||||
|
||||
async sendSmsCode(mobileInput: string, countryCodeInput: unknown = '86'): Promise<void> {
|
||||
this.prune()
|
||||
const mobile = this.normalizeMobile(mobileInput, countryCodeInput)
|
||||
const body = new URLSearchParams({
|
||||
entry: 'miniblog',
|
||||
mobile: encodeSsoField(mobile),
|
||||
el: '2',
|
||||
})
|
||||
const response = await this.fetchImpl(`${PASSPORT_BASE}/sso/v2/sms/send`, {
|
||||
method: 'POST',
|
||||
headers: this.formHeaders(),
|
||||
body,
|
||||
signal: AbortSignal.timeout(this.timeoutMs),
|
||||
})
|
||||
const payload = (await response.json().catch(() => null)) as {
|
||||
retcode?: number
|
||||
msg?: string
|
||||
data?: { act?: string; mfa_id?: string }
|
||||
} | null
|
||||
if (Number(payload?.retcode) === 0 && String(payload?.data?.act || '') === 'mfa_1') {
|
||||
throw createHttpError('微博要求二次验证,请改用扫码登录', {
|
||||
statusCode: 409,
|
||||
errorCode: 'weibo_sms_mfa_required',
|
||||
})
|
||||
}
|
||||
if (!response.ok || !payload || Number(payload.retcode) !== 20000000) {
|
||||
throw createHttpError(payload?.msg || `发送微博短信验证码失败:HTTP ${response.status}`, {
|
||||
statusCode: 409,
|
||||
errorCode: 'weibo_sms_send_failed',
|
||||
})
|
||||
}
|
||||
const sendCookie = buildCookieHeader(this.collectCookiePairs(response.headers))
|
||||
if (sendCookie) {
|
||||
this.smsCookies.set(mobile, {
|
||||
cookie: sendCookie,
|
||||
expiresAtMs: this.now() + SMS_COOKIE_TTL_MS,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async loginWithSms(input: {
|
||||
taskId: number
|
||||
orderNo: string
|
||||
mobile: string
|
||||
code: string
|
||||
countryCode?: unknown
|
||||
}): Promise<{ sessionId: string; session: ConnectorLoginSession }> {
|
||||
this.prune()
|
||||
const mobile = this.normalizeMobile(input.mobile, input.countryCode)
|
||||
const code = String(input.code || '').trim()
|
||||
if (!code) {
|
||||
throw createHttpError('请输入微博短信验证码', {
|
||||
statusCode: 400,
|
||||
errorCode: 'weibo_sms_code_required',
|
||||
})
|
||||
}
|
||||
const body = new URLSearchParams({
|
||||
entry: 'miniblog',
|
||||
source: 'miniblog',
|
||||
type: '2',
|
||||
url: WEIBO_LOGIN_URL,
|
||||
ver: WEIBO_LOGIN_VER,
|
||||
username: encodeSsoField(mobile),
|
||||
scode: encodeSsoField(code),
|
||||
el: '2',
|
||||
disp: 'popup',
|
||||
rid: 'norid',
|
||||
})
|
||||
const response = await this.fetchImpl(`${PASSPORT_BASE}/sso/v2/login`, {
|
||||
method: 'POST',
|
||||
headers: this.formHeaders(),
|
||||
body,
|
||||
signal: AbortSignal.timeout(this.timeoutMs),
|
||||
})
|
||||
const payload = (await response.json().catch(() => null)) as {
|
||||
retcode?: number
|
||||
msg?: string
|
||||
data?: { data?: { act?: string; location?: string; mfa_id?: string } }
|
||||
} | null
|
||||
if (!response.ok || !payload) {
|
||||
throw createHttpError(`微博短信登录失败:HTTP ${response.status}`, {
|
||||
statusCode: 502,
|
||||
errorCode: 'weibo_sms_login_failed',
|
||||
})
|
||||
}
|
||||
const act = String(payload.data?.data?.act || '')
|
||||
if (act === 'mfa_1' || act === 'mfa_2') {
|
||||
throw createHttpError('微博要求二次验证,请在微博 App 完成验证后重试', {
|
||||
statusCode: 409,
|
||||
errorCode: 'weibo_sms_mfa_required',
|
||||
})
|
||||
}
|
||||
if (act !== 'goto') {
|
||||
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'),
|
||||
taskId: Number(input.taskId) || 0,
|
||||
orderNo: String(input.orderNo || ''),
|
||||
createdAtMs: nowMs,
|
||||
expiresAtMs: nowMs + CREDENTIAL_TTL_MS,
|
||||
status: 'authenticated',
|
||||
qrid: '',
|
||||
qrImage: '',
|
||||
message: '微博登录成功',
|
||||
cookie: '',
|
||||
account: null,
|
||||
tickets: new Map(),
|
||||
}
|
||||
const pendingSmsCookie = this.smsCookies.get(mobile)
|
||||
this.smsCookies.delete(mobile)
|
||||
const responseCookie = buildCookieHeader(this.collectCookiePairs(response.headers))
|
||||
const seedCookie = [pendingSmsCookie?.cookie || '', responseCookie].filter(Boolean).join('; ')
|
||||
await this.finishLogin(session, location, seedCookie)
|
||||
this.sessions.set(session.sessionId, session)
|
||||
return { sessionId: session.sessionId, session: this.loginView(session) }
|
||||
}
|
||||
|
||||
async getBinding(sessionId: string): Promise<ConnectorBindingSession> {
|
||||
const session = this.requireSession(sessionId)
|
||||
if (session.status !== 'authenticated' || !session.account) {
|
||||
throw createHttpError('微博账号尚未登录', {
|
||||
statusCode: 409,
|
||||
errorCode: 'weibo_login_required',
|
||||
})
|
||||
}
|
||||
return this.bindingView(session)
|
||||
}
|
||||
|
||||
async createBrowserTicket(input: {
|
||||
sessionId: string
|
||||
targetUrl?: string
|
||||
}): Promise<ConnectorBrowserTicket> {
|
||||
const session = this.requireSession(input.sessionId)
|
||||
if (!session.cookie) {
|
||||
throw createHttpError('微博登录态不存在或已过期', {
|
||||
statusCode: 404,
|
||||
errorCode: 'weibo_credential_not_found',
|
||||
})
|
||||
}
|
||||
const ticket = `${TICKET_PREFIX}${crypto.randomBytes(32).toString('base64url')}`
|
||||
const targetUrl = String(input.targetUrl || '').trim() || 'https://weibo.com/'
|
||||
const expiresAtMs = this.now() + BROWSER_TICKET_TTL_MS
|
||||
session.tickets.set(ticket, {
|
||||
ticket,
|
||||
targetUrl,
|
||||
cookie: session.cookie,
|
||||
expiresAtMs,
|
||||
})
|
||||
return { ticket, expiresAt: iso(expiresAtMs), targetUrl }
|
||||
}
|
||||
|
||||
async consumeBrowserTicket(ticketInput: string): Promise<ConnectorInjectionPayload> {
|
||||
this.prune()
|
||||
const ticket = String(ticketInput || '').trim()
|
||||
if (!ticket) {
|
||||
throw createHttpError('注入票据无效', {
|
||||
statusCode: 400,
|
||||
errorCode: 'weibo_ticket_invalid',
|
||||
})
|
||||
}
|
||||
for (const session of this.sessions.values()) {
|
||||
const item = session.tickets.get(ticket)
|
||||
if (!item) continue
|
||||
session.tickets.delete(ticket)
|
||||
if (item.expiresAtMs <= this.now()) {
|
||||
throw createHttpError('浏览器注入票据不存在或已过期', {
|
||||
statusCode: 404,
|
||||
errorCode: 'weibo_ticket_expired',
|
||||
})
|
||||
}
|
||||
return {
|
||||
platform: 'weibo',
|
||||
targetUrl: item.targetUrl,
|
||||
expiresAt: iso(item.expiresAtMs),
|
||||
cookies: normalizeCookiePairs(item.cookie)
|
||||
.filter(([name, value]) => name && value)
|
||||
.map(([name, value]) => ({
|
||||
name,
|
||||
value,
|
||||
domain: '.weibo.com',
|
||||
path: '/',
|
||||
secure: true,
|
||||
})),
|
||||
}
|
||||
}
|
||||
throw createHttpError('浏览器注入票据不存在或已过期', {
|
||||
statusCode: 404,
|
||||
errorCode: 'weibo_ticket_not_found',
|
||||
})
|
||||
}
|
||||
|
||||
async revokeSession(sessionIdInput: string): Promise<void> {
|
||||
const sessionId = String(sessionIdInput || '').trim()
|
||||
const session = this.sessions.get(sessionId)
|
||||
if (!session) return
|
||||
session.cookie = ''
|
||||
session.tickets.clear()
|
||||
this.sessions.delete(sessionId)
|
||||
}
|
||||
|
||||
private async finishLogin(
|
||||
session: WeiboSession,
|
||||
loginUrl: string,
|
||||
seedCookie = '',
|
||||
): Promise<void> {
|
||||
const { cookie } = await this.followWithCookies(loginUrl, seedCookie)
|
||||
if (!cookie || !cookieValue(cookie, 'SUB')) {
|
||||
session.status = 'failed'
|
||||
session.message = '微博登录成功但未获取到登录 Cookie'
|
||||
return
|
||||
}
|
||||
session.cookie = cookie
|
||||
session.account = await this.fetchAccount(cookie)
|
||||
session.status = 'authenticated'
|
||||
session.message = '微博登录成功'
|
||||
}
|
||||
|
||||
private collectCookiePairs(headers: Headers): Map<string, string> {
|
||||
const pairs = new Map<string, string>()
|
||||
for (const raw of readSetCookie(headers)) {
|
||||
const first = String(raw || '').split(';', 1)[0] || ''
|
||||
const separator = first.indexOf('=')
|
||||
if (separator <= 0) continue
|
||||
const key = first.slice(0, separator).trim()
|
||||
const value = first.slice(separator + 1).trim()
|
||||
if (key) pairs.set(key, value)
|
||||
}
|
||||
return pairs
|
||||
}
|
||||
|
||||
private async followWithCookies(
|
||||
url: string,
|
||||
seedCookie = '',
|
||||
): Promise<{ cookie: string; finalUrl: string }> {
|
||||
const pairs = new Map<string, string>(normalizeCookiePairs(seedCookie))
|
||||
let currentUrl = url
|
||||
for (let index = 0; index < 8; index += 1) {
|
||||
const response = await this.fetchImpl(currentUrl, {
|
||||
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',
|
||||
...(pairs.size > 0 ? { cookie: buildCookieHeader(pairs) } : {}),
|
||||
},
|
||||
redirect: 'manual',
|
||||
signal: AbortSignal.timeout(this.timeoutMs),
|
||||
})
|
||||
for (const [key, value] of this.collectCookiePairs(response.headers)) {
|
||||
pairs.set(key, value)
|
||||
}
|
||||
const location = response.headers.get('location')
|
||||
if (response.status >= 300 && response.status < 400 && location) {
|
||||
currentUrl = new URL(location, currentUrl).toString()
|
||||
continue
|
||||
}
|
||||
await response.arrayBuffer().catch(() => undefined)
|
||||
break
|
||||
}
|
||||
return { cookie: buildCookieHeader(pairs), finalUrl: currentUrl }
|
||||
}
|
||||
|
||||
private async fetchAccount(cookie: string): Promise<WeiboAccount> {
|
||||
try {
|
||||
const response = await this.fetchImpl(`${WEIBO_BASE}/ajax/side/info`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'user-agent': PC_UA,
|
||||
referer: 'https://weibo.com/',
|
||||
'x-requested-with': 'XMLHttpRequest',
|
||||
accept: 'application/json, text/plain, */*',
|
||||
cookie,
|
||||
},
|
||||
signal: AbortSignal.timeout(this.timeoutMs),
|
||||
})
|
||||
const payload = (await response.json().catch(() => null)) as {
|
||||
data?: {
|
||||
user?: {
|
||||
id?: number | string
|
||||
screen_name?: string
|
||||
avatar_large?: string
|
||||
}
|
||||
}
|
||||
} | null
|
||||
const user = payload?.data?.user
|
||||
return {
|
||||
uid: String(user?.id || ''),
|
||||
nickname: String(user?.screen_name || ''),
|
||||
avatar: String(user?.avatar_large || ''),
|
||||
}
|
||||
} catch {
|
||||
return { uid: '', nickname: '', avatar: '' }
|
||||
}
|
||||
}
|
||||
|
||||
private async downloadQrImage(imageUrl: string): Promise<string> {
|
||||
const url = String(imageUrl || '').trim()
|
||||
if (!url) return ''
|
||||
const response = await this.fetchImpl(url, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'user-agent': PC_UA,
|
||||
referer: 'https://passport.weibo.com/',
|
||||
accept: 'image/avif,image/webp,image/apng,image/*,*/*;q=0.8',
|
||||
},
|
||||
signal: AbortSignal.timeout(this.timeoutMs),
|
||||
})
|
||||
if (!response.ok) return ''
|
||||
const contentType = String(response.headers.get('content-type') || 'image/png').split(';', 1)[0]
|
||||
const buffer = Buffer.from(await response.arrayBuffer())
|
||||
if (buffer.length === 0) return ''
|
||||
return `data:${contentType || 'image/png'};base64,${buffer.toString('base64')}`
|
||||
}
|
||||
|
||||
private loginView(session: WeiboSession): ConnectorLoginSession {
|
||||
return {
|
||||
sessionId: session.sessionId,
|
||||
status: session.status,
|
||||
qrContent: '',
|
||||
qrImage: session.qrImage,
|
||||
expiresAt: iso(session.createdAtMs + LOGIN_QR_TTL_MS),
|
||||
huyaUid: session.account?.uid || '',
|
||||
nickname: session.account?.nickname || '',
|
||||
hasCredential: Boolean(session.cookie),
|
||||
message: session.message,
|
||||
}
|
||||
}
|
||||
|
||||
private bindingView(session: WeiboSession): ConnectorBindingSession {
|
||||
const account = session.account
|
||||
return {
|
||||
sessionId: session.sessionId,
|
||||
status: 'confirmed',
|
||||
qrImage: '',
|
||||
qrExpiresAt: '',
|
||||
bindGameAccount: account?.nickname || '',
|
||||
bindGameRole: account?.uid || '',
|
||||
bindGameChannel: '微博',
|
||||
hasExistingBinding: true,
|
||||
rebindRequested: false,
|
||||
message: '微博账号已授权',
|
||||
}
|
||||
}
|
||||
|
||||
private requireSession(sessionIdInput: string): WeiboSession {
|
||||
this.prune()
|
||||
const sessionId = String(sessionIdInput || '').trim()
|
||||
const session = this.sessions.get(sessionId)
|
||||
if (!session) {
|
||||
throw createHttpError('微博登录会话不存在或已过期', {
|
||||
statusCode: 404,
|
||||
errorCode: 'weibo_session_not_found',
|
||||
})
|
||||
}
|
||||
return session
|
||||
}
|
||||
|
||||
private normalizeMobile(value: string, countryCodeInput: unknown = '86'): string {
|
||||
const digits = String(value || '').replace(/\D/g, '')
|
||||
if (!digits) {
|
||||
throw createHttpError('请输入手机号', {
|
||||
statusCode: 400,
|
||||
errorCode: 'weibo_mobile_required',
|
||||
})
|
||||
}
|
||||
const countryCode = String(countryCodeInput ?? '').replace(/\D/g, '') || '86'
|
||||
// 微博网页端:大陆手机号直接使用 11 位号码;其他地区使用 00 + 国家码 + 号码。
|
||||
if (countryCode === '86') {
|
||||
if (digits.startsWith('86') && digits.length > 11) return digits.slice(2)
|
||||
return digits
|
||||
}
|
||||
if (digits.startsWith('00')) return digits
|
||||
return `00${countryCode}${digits}`
|
||||
}
|
||||
|
||||
private jsonHeaders(): Record<string, string> {
|
||||
return {
|
||||
'user-agent': PC_UA,
|
||||
origin: PASSPORT_BASE,
|
||||
referer: SIGNIN_REFERER,
|
||||
accept: 'application/json, text/plain, */*',
|
||||
'accept-language': 'zh-CN,zh;q=0.9',
|
||||
'x-requested-with': 'XMLHttpRequest',
|
||||
}
|
||||
}
|
||||
|
||||
private formHeaders(): Record<string, string> {
|
||||
return {
|
||||
...this.jsonHeaders(),
|
||||
'content-type': 'application/x-www-form-urlencoded',
|
||||
}
|
||||
}
|
||||
|
||||
private prune(): void {
|
||||
const nowMs = this.now()
|
||||
for (const [mobile, item] of Array.from(this.smsCookies.entries())) {
|
||||
if (item.expiresAtMs <= nowMs) this.smsCookies.delete(mobile)
|
||||
}
|
||||
for (const [sessionId, session] of Array.from(this.sessions.entries())) {
|
||||
if (session.expiresAtMs <= nowMs) {
|
||||
session.cookie = ''
|
||||
session.tickets.clear()
|
||||
this.sessions.delete(sessionId)
|
||||
}
|
||||
}
|
||||
if (this.sessions.size <= MAX_SESSIONS) return
|
||||
const overflow = this.sessions.size - MAX_SESSIONS
|
||||
for (const [sessionId, session] of Array.from(this.sessions.entries()).slice(0, overflow)) {
|
||||
session.cookie = ''
|
||||
session.tickets.clear()
|
||||
this.sessions.delete(sessionId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const weiboNativeConnector = new WeiboNativeConnector()
|
||||
export const WEIBO_TICKET_PREFIX = TICKET_PREFIX
|
||||
@@ -0,0 +1,224 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { WEIBO_TICKET_PREFIX, WeiboNativeConnector } from './weibo-native-connector.js'
|
||||
|
||||
type CapturedCall = { url: string; init: RequestInit }
|
||||
|
||||
function jsonResponse(payload: unknown): Response {
|
||||
return new Response(JSON.stringify(payload), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
function createFetchMock(
|
||||
handler: (url: string, init: RequestInit) => Response | Promise<Response>,
|
||||
) {
|
||||
const calls: CapturedCall[] = []
|
||||
const fetchImpl = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url =
|
||||
typeof input === 'string'
|
||||
? input
|
||||
: input instanceof URL
|
||||
? input.toString()
|
||||
: String(input.url)
|
||||
const requestInit = init || {}
|
||||
calls.push({ url, init: requestInit })
|
||||
return handler(url, requestInit)
|
||||
}) as typeof fetch
|
||||
return { fetchImpl, calls }
|
||||
}
|
||||
|
||||
function defaultHandler(url: string): Response {
|
||||
if (url.includes('/sso/v2/web/config')) {
|
||||
return jsonResponse({
|
||||
retcode: 20000000,
|
||||
data: {
|
||||
country_code: [
|
||||
{ country_code: '86', local: { zh_CN: '中国' } },
|
||||
{ country_code: '852', local: { zh_CN: '中国香港' } },
|
||||
{ country_code: '886', local: { zh_CN: '中国台湾' } },
|
||||
],
|
||||
},
|
||||
})
|
||||
}
|
||||
if (url.includes('/sso/v2/qrcode/image')) {
|
||||
return jsonResponse({
|
||||
retcode: 20000000,
|
||||
data: { qrid: 'qr-1', image: 'https://v2.qr.weibo.cn/qr-demo.png' },
|
||||
})
|
||||
}
|
||||
if (url.includes('/sso/v2/qrcode/check')) {
|
||||
return jsonResponse({ retcode: 50114001, msg: '未使用', data: null })
|
||||
}
|
||||
if (url.startsWith('https://v2.qr.weibo.cn/')) {
|
||||
return new Response(Buffer.from('fake-png'), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'image/png' },
|
||||
})
|
||||
}
|
||||
if (url.includes('/sso/v2/sms/send')) {
|
||||
return jsonResponse({ retcode: 20000000 })
|
||||
}
|
||||
if (url.includes('/sso/v2/login')) {
|
||||
return jsonResponse({
|
||||
retcode: 20000000,
|
||||
data: {
|
||||
data: {
|
||||
act: 'goto',
|
||||
location: 'https://passport.weibo.com/sso/v2/goto?ticket=demo',
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
if (url.includes('/sso/v2/goto')) {
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
headers: {
|
||||
location: 'https://weibo.com/',
|
||||
'set-cookie': 'SUB=demo-sub; Path=/; Domain=.weibo.com',
|
||||
},
|
||||
})
|
||||
}
|
||||
if (url === 'https://weibo.com/') {
|
||||
return new Response('<html></html>', {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'text/html' },
|
||||
})
|
||||
}
|
||||
if (url.includes('/ajax/side/info')) {
|
||||
return jsonResponse({
|
||||
data: {
|
||||
user: {
|
||||
id: 123456,
|
||||
screen_name: '微博测试账号',
|
||||
avatar_large: 'https://tvax1.sinaimg.cn/demo.jpg',
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
return new Response('not found', { status: 404 })
|
||||
}
|
||||
|
||||
test('微博二维码会话解析 qrid 并把图片转成 base64', async () => {
|
||||
const { fetchImpl, calls } = createFetchMock(defaultHandler)
|
||||
const connector = new WeiboNativeConnector({ fetchImpl })
|
||||
const session = await connector.createQrLoginSession({ taskId: 1, orderNo: 'MOCKWB1' })
|
||||
|
||||
assert.equal(session.status, 'waiting_scan')
|
||||
assert.match(session.qrImage || '', /^data:image\/png;base64,/)
|
||||
assert.ok(calls.some((call) => call.url.includes('qrcode/image?entry=miniblog&size=180')))
|
||||
})
|
||||
|
||||
test('微博二维码未扫码时保持等待扫码状态', async () => {
|
||||
const { fetchImpl } = createFetchMock(defaultHandler)
|
||||
const connector = new WeiboNativeConnector({ fetchImpl })
|
||||
const session = await connector.createQrLoginSession({ taskId: 1, orderNo: 'MOCKWB1' })
|
||||
const polled = await connector.getQrLoginSession(session.sessionId)
|
||||
assert.equal(polled.status, 'waiting_scan')
|
||||
})
|
||||
|
||||
test('微博发送短信验证码使用大陆 11 位手机号', async () => {
|
||||
const { fetchImpl, calls } = createFetchMock(defaultHandler)
|
||||
const connector = new WeiboNativeConnector({ fetchImpl })
|
||||
await connector.sendSmsCode('18900762182')
|
||||
|
||||
const call = calls.find((item) => item.url.includes('/sso/v2/sms/send'))
|
||||
assert.ok(call)
|
||||
const form = new URLSearchParams(String(call.init.body))
|
||||
assert.equal(form.get('entry'), 'miniblog')
|
||||
assert.equal(form.get('mobile'), 'T3JH3iRZfvXRi9K')
|
||||
assert.equal(form.get('mfa_id'), null)
|
||||
assert.equal(form.get('el'), '2')
|
||||
})
|
||||
|
||||
test('微博短信发送支持其他国家码并按 00 前缀编码', async () => {
|
||||
const { fetchImpl, calls } = createFetchMock(defaultHandler)
|
||||
const connector = new WeiboNativeConnector({ fetchImpl })
|
||||
await connector.sendSmsCode('61234567', '852')
|
||||
|
||||
const call = calls.find((item) => item.url.includes('/sso/v2/sms/send'))
|
||||
assert.ok(call)
|
||||
const form = new URLSearchParams(String(call.init.body))
|
||||
assert.equal(form.get('mobile'), 'TiNs13aS9CXDe9Nva3')
|
||||
})
|
||||
|
||||
test('微博国家码列表来自 web config 并缓存', async () => {
|
||||
const { fetchImpl, calls } = createFetchMock(defaultHandler)
|
||||
const connector = new WeiboNativeConnector({ fetchImpl })
|
||||
const first = await connector.getCountryCodes()
|
||||
const second = await connector.getCountryCodes()
|
||||
|
||||
assert.deepEqual(first, [
|
||||
{ code: '86', name: '中国' },
|
||||
{ code: '852', name: '中国香港' },
|
||||
{ code: '886', name: '中国台湾' },
|
||||
])
|
||||
assert.deepEqual(second, first)
|
||||
assert.equal(calls.filter((call) => call.url.includes('/sso/v2/web/config')).length, 1)
|
||||
})
|
||||
|
||||
test('微博短信登录会带上发码响应下发的 Cookie', async () => {
|
||||
const { fetchImpl, calls } = createFetchMock((url) => {
|
||||
if (url.includes('/sso/v2/sms/send')) {
|
||||
return new Response(JSON.stringify({ retcode: 20000000 }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
'set-cookie': 'SCF=send-cookie; Path=/',
|
||||
},
|
||||
})
|
||||
}
|
||||
return defaultHandler(url)
|
||||
})
|
||||
const connector = new WeiboNativeConnector({ fetchImpl })
|
||||
await connector.sendSmsCode('13800138000')
|
||||
const { session } = await connector.loginWithSms({
|
||||
taskId: 1,
|
||||
orderNo: 'MOCKWB1',
|
||||
mobile: '13800138000',
|
||||
code: '123456',
|
||||
})
|
||||
|
||||
assert.equal(session.status, 'authenticated')
|
||||
const redirectCall = calls.find((item) => item.url.includes('/sso/v2/goto'))
|
||||
assert.ok(redirectCall)
|
||||
const headers = redirectCall.init.headers as Record<string, string>
|
||||
assert.match(headers.cookie || '', /SCF=send-cookie/)
|
||||
})
|
||||
|
||||
test('微博短信登录建立会话并可生成一次性注入票据', async () => {
|
||||
const { fetchImpl, calls } = createFetchMock(defaultHandler)
|
||||
const connector = new WeiboNativeConnector({ fetchImpl })
|
||||
const { sessionId, session } = await connector.loginWithSms({
|
||||
taskId: 1,
|
||||
orderNo: 'MOCKWB1',
|
||||
mobile: '138 0013 8000',
|
||||
code: '123456',
|
||||
})
|
||||
|
||||
assert.equal(session.status, 'authenticated')
|
||||
assert.equal(session.huyaUid, '123456')
|
||||
assert.equal(session.nickname, '微博测试账号')
|
||||
|
||||
const loginCall = calls.find((item) => item.url.includes('/sso/v2/login'))
|
||||
assert.ok(loginCall)
|
||||
const form = new URLSearchParams(String(loginCall.init.body))
|
||||
assert.equal(form.get('type'), '2')
|
||||
assert.equal(form.get('username'), 'T3Gs3iR_9fN7A9t')
|
||||
assert.equal(form.get('scode'), 'T3r81iMS')
|
||||
|
||||
const ticket = await connector.createBrowserTicket({
|
||||
sessionId,
|
||||
targetUrl: 'https://weibo.com/',
|
||||
})
|
||||
assert.ok(ticket.ticket.startsWith(WEIBO_TICKET_PREFIX))
|
||||
|
||||
const payload = await connector.consumeBrowserTicket(ticket.ticket)
|
||||
assert.equal(payload.platform, 'weibo')
|
||||
assert.equal(payload.targetUrl, 'https://weibo.com/')
|
||||
assert.ok(payload.cookies.some((cookie) => cookie.name === 'SUB' && cookie.value === 'demo-sub'))
|
||||
|
||||
await assert.rejects(() => connector.consumeBrowserTicket(ticket.ticket), /票据不存在或已过期/)
|
||||
})
|
||||
Reference in New Issue
Block a user