325 lines
9.4 KiB
TypeScript
325 lines
9.4 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 {
|
||
HUYA_NATIVE_TICKET_PREFIX,
|
||
huyaNativeConnector,
|
||
type HuyaStoredCredential,
|
||
} from './huya-native/huya-native-connector.js'
|
||
|
||
export type ConnectorLoginSession = {
|
||
sessionId: string
|
||
status: 'waiting_scan' | 'scanned' | 'authenticated' | 'expired' | 'failed'
|
||
qrContent: string
|
||
qrImage?: string
|
||
expiresAt: string
|
||
huyaUid: string
|
||
nickname: string
|
||
hasCredential: boolean
|
||
message: string
|
||
}
|
||
|
||
export type ConnectorBindingSession = {
|
||
sessionId: string
|
||
status:
|
||
| 'not_started'
|
||
| 'qr_pending'
|
||
| 'scanned'
|
||
| 'role_ready'
|
||
| 'confirmed'
|
||
| 'expired'
|
||
| 'failed'
|
||
qrImage: string
|
||
qrExpiresAt: string
|
||
bindGameAccount: string
|
||
bindGameRole: string
|
||
bindGameChannel: string
|
||
hasExistingBinding?: boolean
|
||
rebindRequested?: boolean
|
||
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)
|
||
try {
|
||
const requestInit: RequestInit = {
|
||
method: options.method || 'GET',
|
||
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
|
||
}
|
||
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) 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 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,
|
||
)
|
||
}
|
||
|
||
export async function confirmHuyaBinding(
|
||
sessionId: string,
|
||
mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(),
|
||
): Promise<ConnectorBindingSession> {
|
||
if (mode === 'embedded') return huyaNativeConnector.confirmBinding(sessionId)
|
||
return callConnector<ConnectorBindingSession>(
|
||
`/api/internal/huya-semi-auto/sessions/${encodeURIComponent(sessionId)}/binding/confirm`,
|
||
{ method: 'POST', body: {} },
|
||
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 function exportHuyaSessionCredential(
|
||
sessionId: string,
|
||
mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(),
|
||
): HuyaStoredCredential {
|
||
if (mode !== 'embedded') {
|
||
throw createHttpError('当前虎牙 Connector 模式不支持直接导出 CK', {
|
||
statusCode: 409,
|
||
errorCode: 'semi_auto_credential_export_unsupported',
|
||
})
|
||
}
|
||
return huyaNativeConnector.exportSessionCredential(sessionId)
|
||
}
|
||
|
||
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,
|
||
)
|
||
}
|