211 lines
6.5 KiB
TypeScript
211 lines
6.5 KiB
TypeScript
import type { PoolClient } from 'pg'
|
|
|
|
import { query } from '../../db/client.js'
|
|
|
|
export type SemiAutoCredentialCookie = {
|
|
name: string
|
|
value: string
|
|
domain: string
|
|
path: string
|
|
secure: boolean
|
|
httpOnly: boolean
|
|
hostOnly?: boolean
|
|
expiresAt: string | null
|
|
}
|
|
|
|
export type SemiAutoCredentialPayload = {
|
|
platformUid: string
|
|
nickname: string
|
|
cookies: SemiAutoCredentialCookie[]
|
|
}
|
|
|
|
export type SemiAutoCredentialSource = 'qr' | 'sms' | 'web' | 'app' | 'import'
|
|
|
|
export type SemiAutoCredentialRecord = SemiAutoCredentialPayload & {
|
|
id: number
|
|
platform: 'huya' | 'weibo'
|
|
source: SemiAutoCredentialSource | ''
|
|
status: 'unknown' | 'valid' | 'invalid' | 'error'
|
|
updatedAt: string
|
|
}
|
|
|
|
type CredentialRow = {
|
|
id: number
|
|
platform: 'huya' | 'weibo'
|
|
platform_uid: string
|
|
platform_nickname: string
|
|
credential_payload_json: string
|
|
credential_source: SemiAutoCredentialSource | ''
|
|
credential_status: 'unknown' | 'valid' | 'invalid' | 'error'
|
|
credential_updated_at: string
|
|
}
|
|
|
|
function normalizeCookieList(value: unknown): SemiAutoCredentialCookie[] {
|
|
if (!Array.isArray(value)) return []
|
|
return value
|
|
.filter((item): item is Record<string, unknown> =>
|
|
Boolean(item && typeof item === 'object' && !Array.isArray(item)),
|
|
)
|
|
.map((item) => {
|
|
const domain = String(item.domain || '')
|
|
.trim()
|
|
.toLowerCase()
|
|
return {
|
|
name: String(item.name || '').trim(),
|
|
value: String(item.value || ''),
|
|
domain,
|
|
path: String(item.path || '/').trim() || '/',
|
|
secure: item.secure === true,
|
|
httpOnly: item.httpOnly === true,
|
|
hostOnly: typeof item.hostOnly === 'boolean' ? item.hostOnly : !domain.startsWith('.'),
|
|
expiresAt: item.expiresAt ? String(item.expiresAt) : null,
|
|
}
|
|
})
|
|
.filter((item) => item.name && item.domain)
|
|
}
|
|
|
|
export function buildSemiAutoCredentialCookieHeader(
|
|
cookies: SemiAutoCredentialCookie[],
|
|
requestUrlInput: unknown,
|
|
): string {
|
|
const requestUrl = new URL(String(requestUrlInput || '').trim())
|
|
const hostname = requestUrl.hostname.toLowerCase()
|
|
const requestPath = requestUrl.pathname || '/'
|
|
const nowMs = Date.now()
|
|
return cookies
|
|
.filter((cookie) => {
|
|
if (cookie.secure && requestUrl.protocol !== 'https:') return false
|
|
if (cookie.expiresAt) {
|
|
const expiresAtMs = Date.parse(cookie.expiresAt)
|
|
if (Number.isFinite(expiresAtMs) && expiresAtMs <= nowMs) return false
|
|
}
|
|
const cookieDomain = cookie.domain.trim().toLowerCase().replace(/^\./, '')
|
|
if (!cookieDomain) return false
|
|
const hostOnly = cookie.hostOnly ?? !cookie.domain.startsWith('.')
|
|
const domainMatches = hostOnly
|
|
? hostname === cookieDomain
|
|
: hostname === cookieDomain || hostname.endsWith(`.${cookieDomain}`)
|
|
if (!domainMatches) return false
|
|
const cookiePath = cookie.path || '/'
|
|
return (
|
|
requestPath === cookiePath ||
|
|
requestPath.startsWith(cookiePath.endsWith('/') ? cookiePath : `${cookiePath}/`)
|
|
)
|
|
})
|
|
.sort((left, right) => (right.path || '/').length - (left.path || '/').length)
|
|
.map((cookie) => `${cookie.name}=${cookie.value}`)
|
|
.join('; ')
|
|
}
|
|
|
|
function decodeCredential(row: CredentialRow): SemiAutoCredentialRecord {
|
|
const parsed = JSON.parse(row.credential_payload_json) as Record<string, unknown>
|
|
return {
|
|
id: Number(row.id),
|
|
platform: row.platform,
|
|
platformUid: row.platform_uid,
|
|
nickname: row.platform_nickname,
|
|
cookies: normalizeCookieList(parsed.cookies),
|
|
source: row.credential_source,
|
|
status: row.credential_status,
|
|
updatedAt: row.credential_updated_at,
|
|
}
|
|
}
|
|
|
|
export async function upsertSemiAutoCredentialWithClient(
|
|
client: Pick<PoolClient, 'query'>,
|
|
input: {
|
|
platform: 'huya' | 'weibo'
|
|
source: SemiAutoCredentialSource
|
|
payload: SemiAutoCredentialPayload
|
|
},
|
|
): Promise<number> {
|
|
const platformUid = String(input.payload.platformUid || '').trim()
|
|
if (!platformUid) {
|
|
throw new Error('平台账号 UID 为空,无法保存半自动履约凭证')
|
|
}
|
|
const cookies = normalizeCookieList(input.payload.cookies)
|
|
if (cookies.length === 0) {
|
|
throw new Error('平台 Cookie 为空,无法保存半自动履约凭证')
|
|
}
|
|
const payloadJson = JSON.stringify({ cookies })
|
|
const result = await client.query<{ id: number }>(
|
|
`
|
|
INSERT INTO semi_auto_credentials (
|
|
platform, platform_uid, platform_nickname, credential_payload_json,
|
|
credential_source, credential_status, credential_updated_at,
|
|
last_checked_at, last_check_error, created_at, updated_at
|
|
) VALUES (
|
|
$1, $2, $3, $4, $5, 'valid', NOW(), NOW(), '', NOW(), NOW()
|
|
)
|
|
ON CONFLICT (platform, platform_uid) DO UPDATE
|
|
SET platform_nickname = EXCLUDED.platform_nickname,
|
|
credential_payload_json = EXCLUDED.credential_payload_json,
|
|
credential_source = EXCLUDED.credential_source,
|
|
credential_status = 'valid',
|
|
credential_updated_at = NOW(),
|
|
last_checked_at = NOW(),
|
|
last_check_error = '',
|
|
updated_at = NOW()
|
|
RETURNING id
|
|
`,
|
|
[
|
|
input.platform,
|
|
platformUid,
|
|
String(input.payload.nickname || '')
|
|
.trim()
|
|
.slice(0, 120),
|
|
payloadJson,
|
|
input.source,
|
|
],
|
|
)
|
|
return Number(result.rows[0]?.id || 0)
|
|
}
|
|
|
|
export async function loadSemiAutoCredential(
|
|
credentialIdInput: unknown,
|
|
): Promise<SemiAutoCredentialRecord | null> {
|
|
const credentialId = Number(credentialIdInput || 0)
|
|
if (!Number.isInteger(credentialId) || credentialId <= 0) return null
|
|
const result = await query<CredentialRow>(
|
|
`
|
|
SELECT
|
|
id, platform, platform_uid, platform_nickname, credential_payload_json,
|
|
credential_source, credential_status, credential_updated_at
|
|
FROM semi_auto_credentials
|
|
WHERE id = $1
|
|
LIMIT 1
|
|
`,
|
|
[credentialId],
|
|
)
|
|
const row = result.rows[0]
|
|
return row ? decodeCredential(row) : null
|
|
}
|
|
|
|
export async function markSemiAutoCredentialCheck(
|
|
credentialIdInput: unknown,
|
|
input: {
|
|
status: 'valid' | 'invalid' | 'error'
|
|
error?: string
|
|
},
|
|
): Promise<void> {
|
|
const credentialId = Number(credentialIdInput || 0)
|
|
if (!Number.isInteger(credentialId) || credentialId <= 0) return
|
|
await query(
|
|
`
|
|
UPDATE semi_auto_credentials
|
|
SET credential_status = $2,
|
|
last_checked_at = NOW(),
|
|
last_check_error = $3,
|
|
updated_at = NOW()
|
|
WHERE id = $1
|
|
`,
|
|
[
|
|
credentialId,
|
|
input.status,
|
|
String(input.error || '')
|
|
.trim()
|
|
.slice(0, 1000),
|
|
],
|
|
)
|
|
}
|