586 lines
17 KiB
TypeScript
586 lines
17 KiB
TypeScript
import { runtimeConfig } from '../../config/runtime.js'
|
||
import { createHttpError } from '../../utils/http.js'
|
||
import {
|
||
assertDevMockConnectorEnabled,
|
||
DEV_MOCK_CONNECTOR_API_KEY,
|
||
devMockConnectorBaseUrl,
|
||
} from '../dev-mock/connector-endpoint.js'
|
||
import { isDevMockEnabled } from '../dev-mock/dev-mock-enabled.js'
|
||
import {
|
||
exportMockSessionCredential,
|
||
loginMockHuyaSms,
|
||
sendMockHuyaSmsCode,
|
||
} from '../dev-mock/mock-semi-auto-connector.js'
|
||
import {
|
||
HUYA_NATIVE_TICKET_PREFIX,
|
||
huyaNativeConnector,
|
||
type HuyaStoredCredential,
|
||
} from './huya-native/huya-native-connector.js'
|
||
import { recordSemiAutoTrace, traceFingerprint } from './semi-auto-trace.js'
|
||
|
||
export type ConnectorLoginSession = {
|
||
sessionId: string
|
||
status:
|
||
| 'verification_pending'
|
||
| 'waiting_code'
|
||
| 'waiting_scan'
|
||
| 'scanned'
|
||
| 'authenticated'
|
||
| 'expired'
|
||
| 'failed'
|
||
qrContent: string
|
||
qrImage?: string
|
||
expiresAt: string
|
||
huyaUid: string
|
||
nickname: string
|
||
hasCredential: boolean
|
||
message: string
|
||
}
|
||
|
||
type HuyaSmsChallengeBase = {
|
||
image: string
|
||
width: number
|
||
height: number
|
||
}
|
||
|
||
export type HuyaSmsChallenge =
|
||
| (HuyaSmsChallengeBase & {
|
||
type: 'slider'
|
||
puzzleImage: string
|
||
puzzleWidth: number
|
||
puzzleY: number
|
||
})
|
||
| (HuyaSmsChallengeBase & {
|
||
type: 'rotate'
|
||
puzzleImage: string
|
||
puzzleWidth: number
|
||
puzzleHeight: number
|
||
puzzleX: number
|
||
puzzleY: number
|
||
})
|
||
| (HuyaSmsChallengeBase & {
|
||
type: 'click'
|
||
tipImage: string
|
||
question: string
|
||
wordSize: number
|
||
})
|
||
|
||
export type HuyaChallengeSolution = {
|
||
distance?: number
|
||
angle?: number
|
||
points?: Array<{ x: number; y: number }>
|
||
}
|
||
|
||
export type HuyaSmsChallengeInput = HuyaChallengeSolution & {
|
||
sessionId: string
|
||
}
|
||
|
||
export type HuyaSmsSendResult = {
|
||
session: ConnectorLoginSession
|
||
challenge: HuyaSmsChallenge | null
|
||
}
|
||
|
||
/*
|
||
* Connector 的登录会话由运行期实现返回,具体挑战结构见上方联合类型。
|
||
*/
|
||
|
||
export type ConnectorBindingSession = {
|
||
sessionId: string
|
||
status:
|
||
| 'not_started'
|
||
| 'qr_pending'
|
||
| 'scanned'
|
||
| 'role_ready'
|
||
| 'confirmed'
|
||
| 'expired'
|
||
| 'failed'
|
||
qrImage: string
|
||
qrExpiresAt: string
|
||
qrUrl: string
|
||
bindGameAccount: string
|
||
bindGameRole: string
|
||
bindGameRoleId: string
|
||
bindGameChannel: string
|
||
/** 平台返回的角色 ID 是否可核对(纯数字);false 时需引导客户联系客服人工核实。 */
|
||
roleIdVerified?: boolean
|
||
/** 已绑定角色但缺少可核对角色 ID:客户页应提示联系客服,禁止直接确认绑定。 */
|
||
requiresSupport?: boolean
|
||
hasExistingBinding?: boolean
|
||
rebindRequested?: boolean
|
||
rebindUnchanged?: boolean
|
||
rebindConfirmState?: 'idle' | 'submitting' | 'accepted' | 'rejected'
|
||
rebindConfirmMessage?: string
|
||
bindConfirmState?: 'idle' | 'submitting' | 'accepted' | 'rejected'
|
||
bindConfirmMessage?: string
|
||
rebindCooldownDays?: number
|
||
nextRebindAt?: string
|
||
platformChangeBindDay?: number
|
||
platformChangeBindTime?: number
|
||
message: string
|
||
}
|
||
|
||
export type ConnectorBrowserTicket = {
|
||
ticket: string
|
||
expiresAt: string
|
||
targetUrl: string
|
||
}
|
||
|
||
export type ConnectorInjectionPayload = {
|
||
platform: 'huya' | 'weibo'
|
||
targetUrl: string
|
||
expiresAt: string
|
||
cookies: Array<{
|
||
name: string
|
||
value: string
|
||
domain: string
|
||
path: string
|
||
secure: boolean
|
||
}>
|
||
}
|
||
|
||
type ConnectorRequestOptions = {
|
||
method?: 'GET' | 'POST' | 'DELETE'
|
||
body?: unknown
|
||
}
|
||
|
||
export type SemiAutoConnectorMode = 'embedded' | 'external' | 'mock'
|
||
|
||
type RemoteConnectorMode = Exclude<SemiAutoConnectorMode, 'embedded'>
|
||
|
||
type ConnectorEndpoint = {
|
||
baseUrl: string
|
||
apiKey: string
|
||
}
|
||
|
||
function externalConnectorBaseUrl() {
|
||
return String(runtimeConfig.semiAuto?.connectorBaseUrl || '')
|
||
.trim()
|
||
.replace(/\/+$/, '')
|
||
}
|
||
|
||
function externalConnectorApiKey() {
|
||
return String(runtimeConfig.semiAuto?.connectorApiKey || '').trim()
|
||
}
|
||
|
||
export function isExternalSemiAutoConnectorConfigured() {
|
||
return Boolean(externalConnectorBaseUrl() && externalConnectorApiKey())
|
||
}
|
||
|
||
export function getSemiAutoConnectorStatus() {
|
||
return {
|
||
defaultConnectorMode: runtimeConfig.semiAuto?.defaultConnectorMode || ('embedded' as const),
|
||
embeddedConnectorAvailable: true,
|
||
externalConnectorConfigured: isExternalSemiAutoConnectorConfigured(),
|
||
mockConnectorAvailable: isDevMockEnabled(),
|
||
}
|
||
}
|
||
|
||
export function defaultSemiAutoConnectorMode(): SemiAutoConnectorMode {
|
||
const mode = String(runtimeConfig.semiAuto?.defaultConnectorMode || 'embedded').trim()
|
||
return mode === 'external' || mode === 'mock' ? mode : 'embedded'
|
||
}
|
||
|
||
function resolveConnectorEndpoint(mode: RemoteConnectorMode): ConnectorEndpoint {
|
||
if (mode === 'mock') {
|
||
assertDevMockConnectorEnabled()
|
||
return {
|
||
baseUrl: devMockConnectorBaseUrl(),
|
||
apiKey: DEV_MOCK_CONNECTOR_API_KEY,
|
||
}
|
||
}
|
||
const baseUrl = externalConnectorBaseUrl()
|
||
const apiKey = externalConnectorApiKey()
|
||
if (!baseUrl || !apiKey) {
|
||
throw createHttpError('半自动履约 Connector 尚未配置', {
|
||
statusCode: 503,
|
||
errorCode: 'semi_auto_connector_not_configured',
|
||
})
|
||
}
|
||
return { baseUrl, apiKey }
|
||
}
|
||
|
||
async function callConnector<T>(
|
||
path: string,
|
||
options: ConnectorRequestOptions = {},
|
||
mode: RemoteConnectorMode = 'external',
|
||
): Promise<T> {
|
||
const endpoint = resolveConnectorEndpoint(mode)
|
||
|
||
const timeoutMs = Math.max(1000, Number(runtimeConfig.semiAuto?.connectorTimeoutMs || 15_000))
|
||
const controller = new AbortController()
|
||
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
||
const method = String(options.method || 'GET').toUpperCase()
|
||
const startedAt = Date.now()
|
||
try {
|
||
const requestInit: RequestInit = {
|
||
method,
|
||
headers: {
|
||
Accept: 'application/json',
|
||
'Content-Type': 'application/json',
|
||
'X-Semi-Auto-Key': endpoint.apiKey,
|
||
},
|
||
signal: controller.signal,
|
||
}
|
||
if (options.body !== undefined) requestInit.body = JSON.stringify(options.body)
|
||
const response = await fetch(`${endpoint.baseUrl}${path}`, requestInit)
|
||
const text = await response.text()
|
||
let payload: unknown = null
|
||
try {
|
||
payload = text ? JSON.parse(text) : null
|
||
} catch {
|
||
payload = null
|
||
}
|
||
recordSemiAutoTrace({
|
||
direction: 'outbound',
|
||
channel: 'external_connector',
|
||
action: `${method} ${path}`,
|
||
status: response.ok ? 'ok' : 'error',
|
||
httpStatus: response.status,
|
||
durationMs: Date.now() - startedAt,
|
||
requestSummary: { baseUrl: endpoint.baseUrl },
|
||
requestBody: options.body,
|
||
maskRequestCode: true,
|
||
responseSummary: { bodyBytes: text.length },
|
||
responseBody: payload ?? text,
|
||
always: method !== 'GET',
|
||
fingerprint: method === 'GET' ? traceFingerprint(payload) : undefined,
|
||
})
|
||
if (!response.ok) {
|
||
const detail =
|
||
payload && typeof payload === 'object'
|
||
? String((payload as Record<string, unknown>).detail || '')
|
||
: ''
|
||
throw createHttpError(detail || `半自动履约 Connector 请求失败(${response.status})`, {
|
||
statusCode: 502,
|
||
errorCode: 'semi_auto_connector_request_failed',
|
||
})
|
||
}
|
||
return payload as T
|
||
} catch (error) {
|
||
if (!(error && typeof error === 'object' && 'statusCode' in error)) {
|
||
recordSemiAutoTrace({
|
||
direction: 'outbound',
|
||
channel: 'external_connector',
|
||
action: `${method} ${path}`,
|
||
status: 'error',
|
||
durationMs: Date.now() - startedAt,
|
||
requestSummary: { baseUrl: endpoint.baseUrl },
|
||
requestBody: options.body,
|
||
maskRequestCode: true,
|
||
always: true,
|
||
errorMessage: error instanceof Error ? error.message : String(error),
|
||
})
|
||
}
|
||
if (error && typeof error === 'object' && 'statusCode' in error) throw error
|
||
if (error instanceof Error && error.name === 'AbortError') {
|
||
throw createHttpError('半自动履约 Connector 请求超时', {
|
||
statusCode: 504,
|
||
errorCode: 'semi_auto_connector_timeout',
|
||
})
|
||
}
|
||
throw createHttpError(
|
||
error instanceof Error ? error.message : '半自动履约 Connector 请求失败',
|
||
{
|
||
statusCode: 502,
|
||
errorCode: 'semi_auto_connector_request_failed',
|
||
},
|
||
)
|
||
} finally {
|
||
clearTimeout(timer)
|
||
}
|
||
}
|
||
|
||
export async function createHuyaLoginSession(
|
||
input: {
|
||
taskId: number
|
||
orderNo: string
|
||
},
|
||
mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(),
|
||
): Promise<ConnectorLoginSession> {
|
||
if (mode === 'embedded') {
|
||
return huyaNativeConnector.createLoginSession(input)
|
||
}
|
||
return callConnector<ConnectorLoginSession>(
|
||
'/api/internal/huya-semi-auto/sessions',
|
||
{
|
||
method: 'POST',
|
||
body: {
|
||
task_id: input.taskId,
|
||
order_no: input.orderNo,
|
||
},
|
||
},
|
||
mode,
|
||
)
|
||
}
|
||
|
||
export async function getHuyaLoginSession(
|
||
sessionId: string,
|
||
mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(),
|
||
): Promise<ConnectorLoginSession> {
|
||
if (mode === 'embedded') return huyaNativeConnector.getLoginSession(sessionId)
|
||
return callConnector<ConnectorLoginSession>(
|
||
`/api/internal/huya-semi-auto/sessions/${encodeURIComponent(sessionId)}`,
|
||
{},
|
||
mode,
|
||
)
|
||
}
|
||
|
||
export async function sendHuyaSmsCode(
|
||
input: {
|
||
taskId: number
|
||
orderNo: string
|
||
mobile: string
|
||
},
|
||
mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(),
|
||
): Promise<HuyaSmsSendResult> {
|
||
if (mode === 'embedded') return huyaNativeConnector.sendSmsCode(input)
|
||
if (mode === 'mock') {
|
||
return {
|
||
session: sendMockHuyaSmsCode({
|
||
taskId: input.taskId,
|
||
orderNo: input.orderNo,
|
||
mobile: input.mobile,
|
||
}),
|
||
challenge: null,
|
||
}
|
||
}
|
||
const payload = await callConnector<HuyaSmsSendResult | ConnectorLoginSession>(
|
||
'/api/internal/huya-semi-auto/sms/send',
|
||
{
|
||
method: 'POST',
|
||
body: {
|
||
task_id: input.taskId,
|
||
order_no: input.orderNo,
|
||
mobile: input.mobile,
|
||
},
|
||
},
|
||
mode,
|
||
)
|
||
return 'session' in payload ? payload : { session: payload, challenge: null }
|
||
}
|
||
|
||
export async function verifyHuyaSmsChallenge(
|
||
input: HuyaSmsChallengeInput,
|
||
mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(),
|
||
): Promise<HuyaSmsSendResult> {
|
||
if (mode === 'embedded') {
|
||
return huyaNativeConnector.verifySmsChallenge(input.sessionId, input)
|
||
}
|
||
if (mode === 'mock') {
|
||
throw createHttpError('Mock Connector 不使用虎牙安全验证', {
|
||
statusCode: 409,
|
||
errorCode: 'mock_huya_sms_challenge_unsupported',
|
||
})
|
||
}
|
||
return callConnector<HuyaSmsSendResult>(
|
||
'/api/internal/huya-semi-auto/sms/verify',
|
||
{
|
||
method: 'POST',
|
||
body: {
|
||
session_id: input.sessionId,
|
||
distance: input.distance,
|
||
angle: input.angle,
|
||
points: input.points,
|
||
},
|
||
},
|
||
mode,
|
||
)
|
||
}
|
||
|
||
export async function loginHuyaSms(
|
||
input: {
|
||
sessionId: string
|
||
taskId: number
|
||
orderNo: string
|
||
mobile: string
|
||
code: string
|
||
},
|
||
mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(),
|
||
): Promise<ConnectorLoginSession> {
|
||
if (mode === 'embedded') {
|
||
return huyaNativeConnector.loginWithSms({
|
||
sessionId: input.sessionId,
|
||
mobile: input.mobile,
|
||
code: input.code,
|
||
})
|
||
}
|
||
if (mode === 'mock') {
|
||
return loginMockHuyaSms({
|
||
sessionId: input.sessionId,
|
||
mobile: input.mobile,
|
||
code: input.code,
|
||
})
|
||
}
|
||
return callConnector<ConnectorLoginSession>(
|
||
'/api/internal/huya-semi-auto/sms/login',
|
||
{
|
||
method: 'POST',
|
||
body: {
|
||
session_id: input.sessionId,
|
||
task_id: input.taskId,
|
||
order_no: input.orderNo,
|
||
mobile: input.mobile,
|
||
code: input.code,
|
||
},
|
||
},
|
||
mode,
|
||
)
|
||
}
|
||
|
||
export async function startHuyaBinding(
|
||
sessionId: string,
|
||
mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(),
|
||
options: { forceRebind?: boolean } = {},
|
||
): Promise<ConnectorBindingSession> {
|
||
if (mode === 'embedded') {
|
||
return huyaNativeConnector.startBinding(
|
||
sessionId,
|
||
options.forceRebind ? { forceRebind: true } : {},
|
||
)
|
||
}
|
||
return callConnector<ConnectorBindingSession>(
|
||
`/api/internal/huya-semi-auto/sessions/${encodeURIComponent(sessionId)}/binding`,
|
||
{ method: 'POST', body: { force_rebind: Boolean(options.forceRebind) } },
|
||
mode,
|
||
)
|
||
}
|
||
|
||
export async function getHuyaBinding(
|
||
sessionId: string,
|
||
mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(),
|
||
): Promise<ConnectorBindingSession> {
|
||
if (mode === 'embedded') return huyaNativeConnector.pollBinding(sessionId)
|
||
return callConnector<ConnectorBindingSession>(
|
||
`/api/internal/huya-semi-auto/sessions/${encodeURIComponent(sessionId)}/binding`,
|
||
{},
|
||
mode,
|
||
)
|
||
}
|
||
|
||
/**
|
||
* 只读绑定快照:不触发虎牙查询,供「确认绑定」这类本地动作使用。
|
||
* 外部 Connector 没有独立快照端点,只能复用 GET(由 Connector 侧决定是否访问虎牙)。
|
||
*/
|
||
export async function getHuyaBindingSnapshot(
|
||
sessionId: string,
|
||
mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(),
|
||
): Promise<ConnectorBindingSession> {
|
||
if (mode === 'embedded') return huyaNativeConnector.bindingSnapshot(sessionId)
|
||
return callConnector<ConnectorBindingSession>(
|
||
`/api/internal/huya-semi-auto/sessions/${encodeURIComponent(sessionId)}/binding`,
|
||
{},
|
||
mode,
|
||
)
|
||
}
|
||
|
||
export async function confirmHuyaBinding(
|
||
sessionId: string,
|
||
mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(),
|
||
options: { acceptExistingRole?: boolean } = {},
|
||
): Promise<ConnectorBindingSession> {
|
||
if (mode === 'embedded') return huyaNativeConnector.confirmBinding(sessionId, options)
|
||
return callConnector<ConnectorBindingSession>(
|
||
`/api/internal/huya-semi-auto/sessions/${encodeURIComponent(sessionId)}/binding/confirm`,
|
||
{
|
||
method: 'POST',
|
||
body: options.acceptExistingRole ? { acceptExistingRole: true } : {},
|
||
},
|
||
mode,
|
||
)
|
||
}
|
||
|
||
/**
|
||
* 客户返回上一步修改资料:只重置绑定/换绑状态,不注销登录会话、不删除客户资料。
|
||
* 外部 Connector 通过独立 reset 端点实现;未提供时由调用方决定是否继续。
|
||
*/
|
||
export async function resetHuyaBinding(
|
||
sessionId: string,
|
||
mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(),
|
||
): Promise<ConnectorBindingSession> {
|
||
if (mode === 'embedded') return huyaNativeConnector.resetBinding(sessionId)
|
||
if (mode === 'mock') return startHuyaBinding(sessionId, mode, {})
|
||
return callConnector<ConnectorBindingSession>(
|
||
`/api/internal/huya-semi-auto/sessions/${encodeURIComponent(sessionId)}/binding/reset`,
|
||
{ method: 'POST', body: {} },
|
||
mode,
|
||
)
|
||
}
|
||
|
||
/**
|
||
* 扫码后由项目侧主动向虎牙提交换绑确认。
|
||
* 外部 Connector 暂未提供独立端点时复用 confirm 端点(语义一致,幂等)。
|
||
*/
|
||
export async function submitHuyaRebind(
|
||
sessionId: string,
|
||
mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(),
|
||
): Promise<ConnectorBindingSession> {
|
||
if (mode === 'embedded') return huyaNativeConnector.submitRebind(sessionId)
|
||
return callConnector<ConnectorBindingSession>(
|
||
`/api/internal/huya-semi-auto/sessions/${encodeURIComponent(sessionId)}/binding/confirm`,
|
||
{ method: 'POST', body: { rebind: true } },
|
||
mode,
|
||
)
|
||
}
|
||
|
||
export async function createHuyaBrowserTicket(
|
||
input: {
|
||
sessionId: string
|
||
targetUrl?: string
|
||
},
|
||
mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(),
|
||
): Promise<ConnectorBrowserTicket> {
|
||
if (mode === 'embedded') return huyaNativeConnector.createBrowserTicket(input)
|
||
return callConnector<ConnectorBrowserTicket>(
|
||
`/api/internal/huya-semi-auto/sessions/${encodeURIComponent(input.sessionId)}/browser-ticket`,
|
||
{ method: 'POST', body: { targetUrl: input.targetUrl || '' } },
|
||
mode,
|
||
)
|
||
}
|
||
|
||
export async function exportHuyaSessionCredential(
|
||
sessionId: string,
|
||
mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(),
|
||
): Promise<HuyaStoredCredential> {
|
||
if (mode === 'embedded') return huyaNativeConnector.exportSessionCredential(sessionId)
|
||
if (mode === 'mock') return exportMockSessionCredential(sessionId)
|
||
return callConnector<HuyaStoredCredential>(
|
||
`/api/internal/huya-semi-auto/sessions/${encodeURIComponent(sessionId)}/credential`,
|
||
{},
|
||
mode,
|
||
)
|
||
}
|
||
|
||
export function inferSemiAutoConnectorModeFromTicket(ticket: string): SemiAutoConnectorMode {
|
||
const normalized = ticket.trim()
|
||
if (normalized.startsWith('mock-ticket-')) return 'mock'
|
||
if (normalized.startsWith(HUYA_NATIVE_TICKET_PREFIX)) return 'embedded'
|
||
return 'external'
|
||
}
|
||
|
||
export async function consumeHuyaBrowserTicket(
|
||
ticket: string,
|
||
mode: SemiAutoConnectorMode = inferSemiAutoConnectorModeFromTicket(ticket),
|
||
): Promise<ConnectorInjectionPayload> {
|
||
if (mode === 'embedded') return huyaNativeConnector.consumeBrowserTicket(ticket)
|
||
return callConnector<ConnectorInjectionPayload>(
|
||
`/api/internal/huya-semi-auto/browser-tickets/${encodeURIComponent(ticket)}`,
|
||
{},
|
||
mode,
|
||
)
|
||
}
|
||
|
||
export async function revokeHuyaSession(
|
||
sessionId: string,
|
||
mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(),
|
||
): Promise<void> {
|
||
if (mode === 'embedded') {
|
||
await huyaNativeConnector.revokeSession(sessionId)
|
||
return
|
||
}
|
||
await callConnector<{ ok: boolean }>(
|
||
`/api/internal/huya-semi-auto/sessions/${encodeURIComponent(sessionId)}`,
|
||
{ method: 'DELETE' },
|
||
mode,
|
||
)
|
||
}
|