import ky, { type KyInstance } from "ky"; import { AuthenticationError } from "../errors.js"; export const DEFAULT_SSO_BASE_URL = "https://sso.hosecloud.com"; export interface SsoClientOptions { baseUrl?: string; timeout?: number; } export function createSsoClient(options: SsoClientOptions = {}): KyInstance { const baseUrl = options.baseUrl || DEFAULT_SSO_BASE_URL; return ky.create({ prefix: baseUrl, timeout: options.timeout ?? 15000, headers: { accept: "application/json, text/plain, */*", "user-agent": "hose-use/assist-platform-client", referer: `${baseUrl}/`, }, }); } export interface QrCodeStatusResponse { code: number; message: string; data?: { token?: string; ticket?: string; redirectUrl?: string; [key: string]: unknown; } | string; } export interface SsoQrCodeResult { dingUrl: string; ssoSessionId: string; appId: string; redirect: string; } /** * 请求 HoseCloudSSO 生成钉钉扫码登录链接与会话 Cookie */ export async function getSsoQrCode( client: KyInstance, options: { appId?: string; redirect?: string; } = {} ): Promise { const appId = options.appId || "12021"; const redirect = options.redirect || "https://unity.ekuaibao.com/platform-charge/"; try { const res = await client.post("api/v1/user/login/qrcode", { json: { type: "ding", appId, redirect, }, }); const cookieHeader = res.headers.get("set-cookie"); const matchCookie = cookieHeader ? cookieHeader.match(/SSO_SESSION_ID=([^;]+)/) : null; const ssoSessionId = matchCookie ? matchCookie[1] : ""; const json = (await res.json()) as { code?: number; message?: string; data?: { url?: string; appId?: string; redirect?: string }; }; if (json.code !== 0 || !json.data?.url) { throw new AuthenticationError( `获取钉钉登录二维码失败: ${json.message || "服务端未返回有效二维码链接"}` ); } return { dingUrl: json.data.url, ssoSessionId, appId: json.data.appId || appId, redirect: json.data.redirect || redirect, }; } catch (err) { if (err instanceof AuthenticationError) throw err; throw new AuthenticationError( `请求 SSO 钉钉二维码接口失败: ${err instanceof Error ? err.message : String(err)}` ); } } /** * 轮询 HoseCloudSSO 钉钉扫码登录确认状态 */ export async function pollSsoQrCodeStatus( client: KyInstance, options: { sessionId?: string; cookie?: string; signal?: AbortSignal; } = {} ): Promise { const headers: Record = {}; if (options.cookie) { headers.cookie = options.cookie; } else if (options.sessionId) { headers.cookie = `SSO_SESSION_ID=${options.sessionId}`; } try { return await client .get("api/v1/user/login/qrcode/status", { searchParams: { _t: Date.now() }, headers, signal: options.signal, }) .json(); } catch (error) { if (error instanceof Error && error.name === "AbortError") { throw error; } throw new AuthenticationError( `SSO 状态轮询异常: ${error instanceof Error ? error.message : String(error)}` ); } } /** * 将 SSO 返回的重定向地址或 Token 换取为 Unity 协助平台凭证会话 */ export async function verifySsoTokenOnUnity( tokenOrUrl: string, options: { unityBaseUrl?: string; } = {} ): Promise<{ sessionToken: string; userName: string }> { const unityBaseUrl = options.unityBaseUrl || "https://unity.ekuaibao.com"; // 提取候选 Token const candidates: string[] = []; if (tokenOrUrl.includes("://")) { try { const u = new URL(tokenOrUrl); const t = u.searchParams.get("token") || u.searchParams.get("ticket"); if (t) candidates.push(t); } catch {} } else { candidates.push(tokenOrUrl); } const firstCand = candidates[0] || tokenOrUrl; if (firstCand.includes(".")) { candidates.unshift(Buffer.from(firstCand).toString("base64")); } let lastError = "未能完成换票"; for (const cand of candidates) { try { const res = await ky .post(`${unityBaseUrl}/api/auth/verify`, { headers: { "content-type": "application/json", referer: `${unityBaseUrl}/platform-charge/index.html`, }, json: { token: cand }, timeout: 10000, }) .json<{ value?: { token: string; user?: { name?: string; userId?: string; [key: string]: unknown }; }; errorCode?: number; errorMessage?: string; }>(); if (res.value?.token) { return { sessionToken: res.value.token, userName: res.value.user?.name || "运营人员", }; } lastError = res.errorMessage || `errorCode: ${res.errorCode}`; } catch (e) { lastError = e instanceof Error ? e.message : String(e); } } throw new AuthenticationError(`换取合思协助平台会话失败: ${lastError}`); }