import ky, { HTTPError, KyInstance } from "ky"; import { CorpConfig, HoseSealSource } from "../config/types.js"; import { createSealClientForUrl } from "../http/factory.js"; import { resolveSealCustomHeaders } from "../http/request-headers.js"; import { getHoseAuthCache, setHoseAuthCache } from "./token-store.js"; import { SealEnterpriseConfig, SealSession, TokenEntry } from "./types.js"; type HoseLoginResponse = { value?: { accessToken?: string; refreshToken?: string; corporation?: { id?: string; name?: string; }; staff?: { id?: string; name?: string; }; }; accessToken?: string; token?: string; data?: unknown; }; type HoseProvisionalResponse = { value?: { message?: string; }; }; type SealTokenResponse = { token?: string; accessToken?: string; expiresIn?: number; expires_in?: number; data?: { token?: string; accessToken?: string; expiresIn?: number; expires_in?: number; }; }; export type HoseAssistLink = { corpId: string; accessToken: string; baseUrl?: string; }; export type HoseAssistSealSession = { corpId: string; sealUrl: string; token: string; expiresIn: number; }; export const HOSE_STANDARD_DOMAINS = [ "https://app.ekuaibao.com", "https://dd2.hosecloud.com", "https://wx2.ekuaibao.com", "https://kdcloud2.ekuaibao.com", "https://ddenterprise.ekuaibao.com", "https://feishu.ekuaibao.com" ] as const; const HOSE_ASSIST_HOST_SUFFIXES = [".ekuaibao.com", ".hosecloud.com"] as const; const HOSE_ASSIST_PATH = "/web/thirdparty.html"; const CORP_ID_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/; export type HoseRoleDef = { id: string; name: string; enName?: string | null; sourceType?: string; sourceTypeValue?: string | null; groupId?: string; groupName?: string; }; export type HoseRoleDefGroup = { id: string; name: string; enName?: string | null; roleDefs: HoseRoleDef[]; }; export type HoseStaffDetail = { id: string; name: string; nickName?: string | null; code?: string; departments?: string[]; defaultDepartment?: string; cellphone?: string; active: boolean; userId?: string; email?: string | null; showEmail?: string | null; external?: boolean; authState?: boolean; roles?: Array<{ roleDefId: string; properties?: Record; }>; }; export type HoseProbeResult = { domain: string; corpId: string; corpName?: string; openapiToken: string; expireTime?: number; }; const openapiTokenRequests = new Map>(); const closeApiTokenRequests = new Map>(); export function normalizeBaseUrl(url: string): string { return url.replace(/\/+$/, ""); } export function parseHoseAssistLink(value: string): HoseAssistLink { let url: URL; try { url = new URL(value.trim()); } catch { throw new Error("Invalid Hose assistance link: expected a valid HTTPS URL"); } if ( url.protocol !== "https:" || url.port || !isHoseAssistHost(url.hostname) || url.pathname.replace(/\/+$/, "") !== HOSE_ASSIST_PATH ) { throw new Error( "Invalid Hose assistance link: expected an HTTPS */web/thirdparty.html URL from ekuaibao.com or hosecloud.com" ); } const accessTokens = url.searchParams.getAll("accessToken").filter(Boolean); const corpIds = url.searchParams.getAll("ekbCorpId").filter(Boolean); if (accessTokens.length !== 1 || corpIds.length !== 1) { throw new Error("Invalid Hose assistance link: accessToken and ekbCorpId are required exactly once"); } const corpId = corpIds[0]!.trim().toLowerCase(); if (!CORP_ID_PATTERN.test(corpId)) { throw new Error("Invalid Hose assistance link: ekbCorpId is not a valid tenant slug"); } return { corpId, accessToken: accessTokens[0]!, baseUrl: url.origin }; } export async function exchangeHoseAssistLink( value: string | HoseAssistLink, options?: { customHeaders?: Record } ): Promise { const link = typeof value === "string" ? parseHoseAssistLink(value) : normalizeHoseAssistLink(value); const sealUrl = `https://${link.corpId}.sealai.cc`; const sealClient = createSealClientForUrl(sealUrl, undefined, options?.customHeaders); const sealResponse = await sealClient .get("api/auth/oauth2/session/oem-hosecloud", { searchParams: { token: link.accessToken, returnToken: "1" } }) .json(); const token = sealResponse.token ?? sealResponse.accessToken ?? sealResponse.data?.token ?? sealResponse.data?.accessToken; if (!token) { throw new Error("Seal SSO did not return a bearer token"); } const expiresIn = sealResponse.expiresIn ?? sealResponse.expires_in ?? sealResponse.data?.expiresIn ?? sealResponse.data?.expires_in ?? 3600; return { corpId: link.corpId, sealUrl, token, expiresIn: Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : 3600 }; } export function assertHoseAssistTenantMatches(corpId: string, tenant: Record): void { const hoseCorpConfig = tenant.hoseCorpConfig && typeof tenant.hoseCorpConfig === "object" ? tenant.hoseCorpConfig as Record : undefined; const candidates = [tenant.tenantSlug, hoseCorpConfig?.corporationId] .filter((value): value is string => typeof value === "string" && Boolean(value)); const expectedCorpId = corpId.trim().toLowerCase(); const normalizedCandidates = candidates .map((value) => value.trim().toLowerCase()) .filter(Boolean); if ( normalizedCandidates.length === 0 || normalizedCandidates.some((value) => value !== expectedCorpId) ) { throw new Error("Hose assistance link tenant mismatch: the Seal tenant does not match ekbCorpId"); } } function isHoseAssistHost(hostname: string): boolean { const normalized = hostname.toLowerCase(); return HOSE_ASSIST_HOST_SUFFIXES.some((suffix) => normalized.endsWith(suffix)); } function normalizeHoseAssistLink(value: HoseAssistLink): HoseAssistLink { const corpId = typeof value?.corpId === "string" ? value.corpId.trim().toLowerCase() : ""; const accessToken = typeof value?.accessToken === "string" ? value.accessToken.trim() : ""; const baseUrl = typeof value?.baseUrl === "string" && value.baseUrl.trim() ? value.baseUrl.trim() : undefined; if (!CORP_ID_PATTERN.test(corpId) || !accessToken) { throw new Error("Invalid Hose assistance link: accessToken and ekbCorpId are required"); } return { corpId, accessToken, ...(baseUrl ? { baseUrl } : {}) }; } function isFresh(entry: TokenEntry | undefined, refreshTtl = 60): entry is TokenEntry { return Boolean(entry && Date.now() < entry.expiresAt - refreshTtl * 1000); } export function defaultSealUrl(corp: CorpConfig, source: HoseSealSource): string { if (corp.seal.url) return corp.seal.url; if (source.sealUrl) return source.sealUrl; return `https://${source.corpId.toLowerCase()}.sealai.cc`; } function hoseUid(source: HoseSealSource): string { return source.staffId.includes(":") ? source.staffId : `${source.corpId}:${source.staffId}`; } function hoseClient(source: HoseSealSource): KyInstance { return ky.create({ prefix: normalizeBaseUrl(source.domain), timeout: 30000, hooks: { beforeError: [ async ({ error }) => { const body = error instanceof HTTPError ? await error.response.text().catch(() => "") : ""; error.message = `${error.message}${body ? `: ${body}` : ""}`; return error; } ] } }); } async function fetchHoseOpenapiToken(source: HoseSealSource): Promise { const client = hoseClient(source); const appKey = source.appKey ?? source.key; const appSecurity = source.appSecurity ?? source.password; if (!appKey || !appSecurity) { throw new Error("Hose source requires appKey/key and appSecurity/password"); } const response = await client .post("api/openapi/v1/auth/getAccessToken", { json: { appKey, appSecurity } }) .json(); const token = response.value?.accessToken ?? response.accessToken ?? response.token; if (!token) { throw new Error("Hose login did not return an access token"); } return { token, expiresAt: Date.now() + 3600 * 1000 }; } export async function ensureHoseOpenapiToken(corp: CorpConfig): Promise { if (corp.source.type !== "hose") { throw new Error(`Unsupported Seal source: ${corp.source.type}`); } const cache = getHoseAuthCache(corp.id); if (isFresh(cache.openapi)) { return cache.openapi.token; } const pending = openapiTokenRequests.get(corp.id); if (pending) return pending; const request = fetchHoseOpenapiToken(corp.source) .then((openapi) => { setHoseAuthCache(corp.id, { ...getHoseAuthCache(corp.id), openapi }); return openapi.token; }) .finally(() => openapiTokenRequests.delete(corp.id)); openapiTokenRequests.set(corp.id, request); return request; } export async function fetchHoseCloseApiToken( source: HoseSealSource, openapiToken: string, expiresIn = 7200 ): Promise { const client = hoseClient(source); const uid = hoseUid(source); const response = await client .post("api/openapi/v1.1/provisional/getProvisionalAuth", { searchParams: { accessToken: openapiToken }, json: { uid, pageType: "home", expireDate: expiresIn } }) .json(); const url = response.value?.message; if (!url) { throw new Error("Hose CloseAPI did not return a provisional auth URL"); } const closeapiToken = new URL(url).searchParams.get("accessToken"); if (!closeapiToken) { throw new Error("Hose provisional auth URL did not include accessToken"); } return { token: closeapiToken, url, expiresAt: Date.now() + expiresIn * 1000 }; } export async function ensureHoseCloseApiToken(corp: CorpConfig): Promise { if (corp.source.type !== "hose") { throw new Error(`Unsupported Seal source: ${corp.source.type}`); } const source = corp.source; const cache = getHoseAuthCache(corp.id); if (isFresh(cache.closeapi) && cache.closeapi.url) { return cache.closeapi; } const pending = closeApiTokenRequests.get(corp.id); if (pending) return pending; const request = ensureHoseOpenapiToken(corp) .then((openapiToken) => fetchHoseCloseApiToken(source, openapiToken)) .then((closeapi) => { setHoseAuthCache(corp.id, { ...getHoseAuthCache(corp.id), closeapi }); return closeapi; }) .finally(() => closeApiTokenRequests.delete(corp.id)); closeApiTokenRequests.set(corp.id, request); return request; } export async function getHoseEnterpriseUrl(corp: CorpConfig): Promise { if (corp.source.type !== "hose") { throw new Error(`Unsupported Seal source: ${corp.source.type}`); } const url = (await ensureHoseCloseApiToken(corp)).url; if (!url) { throw new Error("Hose provisional auth URL was not available"); } return url; } export async function getHoseProvisionalAuthLink( corp: CorpConfig, expiresIn = 7200, _options?: { force?: boolean } ): Promise<{ corpId: string; staffId: string; url: string; token?: string; expiresIn: number; }> { if (corp.source.type !== "hose") { throw new Error(`Unsupported Seal source: ${corp.source.type}`); } if (!Number.isFinite(expiresIn) || expiresIn <= 0) { throw new Error(`Invalid expire seconds: ${expiresIn}. Must be a positive integer.`); } const openapiToken = await ensureHoseOpenapiToken(corp); const provisional = await fetchHoseCloseApiToken(corp.source, openapiToken, expiresIn); if (!provisional.url) { throw new Error("Hose provisional auth URL was not available"); } return { corpId: corp.source.corpId, staffId: corp.source.staffId, url: provisional.url, token: provisional.token, expiresIn }; } export async function getHoseSealSession(corp: CorpConfig): Promise { if (corp.source.type !== "hose") { throw new Error(`Unsupported Seal source: ${corp.source.type}`); } const hoseAccess = await ensureHoseCloseApiToken(corp); const sealUrl = defaultSealUrl(corp, corp.source); const customHeaders = resolveSealCustomHeaders(corp.seal); const sealClient = createSealClientForUrl(sealUrl, undefined, customHeaders); const sealResponse = await sealClient .get("api/auth/oauth2/session/oem-hosecloud", { searchParams: { token: hoseAccess.token, returnToken: "1" } }) .json(); const token = sealResponse.token ?? sealResponse.accessToken ?? sealResponse.data?.token ?? sealResponse.data?.accessToken; if (!token) { throw new Error("Seal SSO did not return a bearer token"); } const expiresIn = sealResponse.expiresIn ?? sealResponse.expires_in ?? sealResponse.data?.expiresIn ?? sealResponse.data?.expires_in ?? 3600; const enterprise: SealEnterpriseConfig = { provider: "hose", corpId: corp.source.corpId, staffId: corp.source.staffId, sealUrl: normalizeBaseUrl(sealUrl), tenantSlug: corp.seal.tenantSlug, raw: { sourceType: "hose", hoseDomain: normalizeBaseUrl(corp.source.domain) } }; return { token, expiresAt: Date.now() + expiresIn * 1000, enterprise }; } export async function probeHoseDomain( appKey: string, appSecurity: string, explicitDomain?: string ): Promise { if (explicitDomain) { const normalized = normalizeBaseUrl(explicitDomain); const result = await testSingleHoseDomain(normalized, appKey, appSecurity); if (!result) { throw new Error( `Failed to authenticate on specified domain: ${normalized}. Please verify appKey/appSecurity and domain connectivity.` ); } return result; } const candidatePromises = HOSE_STANDARD_DOMAINS.map(async (domain) => { try { return await testSingleHoseDomain(domain, appKey, appSecurity); } catch { return undefined; } }); const results = await Promise.all(candidatePromises); const matched = results.filter((item): item is HoseProbeResult => Boolean(item)); if (matched.length > 0 && matched[0]) { return matched[0]; } throw new Error( "Failed to authenticate with appKey/appSecurity on all 6 standard Hose domains " + "(app.ekuaibao.com, dd2.hosecloud.com, wx2.ekuaibao.com, kdcloud2.ekuaibao.com, ddenterprise.ekuaibao.com, feishu.ekuaibao.com). " + "If your enterprise uses a private cloud or custom domain (such as 美年大健康), please specify the \"domain\" parameter explicitly." ); } async function testSingleHoseDomain( domain: string, appKey: string, appSecurity: string ): Promise { try { const response = await fetch(`${domain}/api/openapi/v1/auth/getAccessToken`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ appKey, appSecurity }), signal: AbortSignal.timeout(8000) }); if (!response.ok) return undefined; const data = (await response.json()) as { value?: { accessToken?: string; corporationId?: string; corporation?: { id?: string; name?: string; }; expireTime?: number; errorCode?: number; }; accessToken?: string; }; if (data.value?.errorCode) return undefined; const openapiToken = data.value?.accessToken ?? data.accessToken; const corpId = data.value?.corporationId ?? data.value?.corporation?.id; if (!openapiToken || !corpId) return undefined; return { domain, corpId, corpName: data.value?.corporation?.name, openapiToken, expireTime: data.value?.expireTime }; } catch { return undefined; } } export async function fetchHoseRoleDefGroups( domain: string, openapiToken: string ): Promise { const url = `${normalizeBaseUrl(domain)}/api/openapi/v1/roleDefGroups?accessToken=${encodeURIComponent(openapiToken)}`; const response = await fetch(url, { headers: { "content-type": "application/json", Accept: "application/json" }, signal: AbortSignal.timeout(10000) }); if (!response.ok) { const text = await response.text().catch(() => ""); throw new Error(`Failed to fetch Hose role definition groups: ${response.status} ${text}`); } const json = (await response.json()) as { items?: Array<{ id: string; name: string; enName?: string | null; roleDefs?: Array<{ id: string; name: string; enName?: string | null; sourceType?: string; sourceTypeValue?: string | null; }>; }>; }; const groups = json.items ?? []; return groups.map((g) => ({ id: g.id, name: g.name, enName: g.enName, roleDefs: (g.roleDefs ?? []).map((r) => ({ id: r.id, name: r.name, enName: r.enName, sourceType: r.sourceType, sourceTypeValue: r.sourceTypeValue, groupId: g.id, groupName: g.name })) })); } export async function fetchHoseRoleStaffs( domain: string, openapiToken: string, roledefId: string, staffBy = "id" ): Promise<{ id: string; name: string; count: number; staffs: string[] }> { const cleanId = roledefId.startsWith("$") ? roledefId.slice(1) : roledefId; const url = `${normalizeBaseUrl(domain)}/api/openapi/v1/roledefs/$${cleanId}?accessToken=${encodeURIComponent(openapiToken)}&staffBy=${encodeURIComponent(staffBy)}&pathType=name`; const response = await fetch(url, { headers: { "content-type": "application/json", Accept: "application/json" }, signal: AbortSignal.timeout(10000) }); if (!response.ok) { const text = await response.text().catch(() => ""); throw new Error(`Failed to fetch Hose role staffs for ${cleanId}: ${response.status} ${text}`); } const json = (await response.json()) as { value?: { id: string; name: string; count?: number; contents?: Array<{ pathType?: string; path?: string[]; staffs?: string[]; }>; }; }; const val = json.value; if (!val) { throw new Error(`Hose role staff query returned empty result for ${cleanId}`); } const allStaffs: string[] = []; for (const c of val.contents ?? []) { for (const s of c.staffs ?? []) { if (s && !allStaffs.includes(s)) { allStaffs.push(s); } } } return { id: val.id ?? cleanId, name: val.name ?? "", count: val.count ?? allStaffs.length, staffs: allStaffs }; } export async function fetchHoseStaffDetails( domain: string, openapiToken: string, staffIds: string[] ): Promise { if (staffIds.length === 0) return []; const url = `${normalizeBaseUrl(domain)}/api/openapi/v1/staffs/getStaffIds?accessToken=${encodeURIComponent(openapiToken)}`; const response = await fetch(url, { method: "POST", headers: { "content-type": "application/json", Accept: "application/json" }, body: JSON.stringify({ type: "STAFFID", conditionIds: staffIds.slice(0, 100) }), signal: AbortSignal.timeout(10000) }); if (!response.ok) { const text = await response.text().catch(() => ""); throw new Error(`Failed to fetch Hose staff details: ${response.status} ${text}`); } const json = (await response.json()) as { items?: HoseStaffDetail[]; }; return json.items ?? []; } // ── OpenAPI Key Extraction from Assistance Link ────────────────────────────── export type HoseOpenApiKey = { id: string; name?: string; appKey: string; appSecurity: string; active: boolean; corporationId?: string; createTime?: number; updateTime?: number; }; export type HoseAssistLinkDetails = { corpId: string; baseUrl: string; accessToken: string; staffId: string; corpName?: string; staffName?: string; isAdmin?: boolean; cellphone?: string; }; export type HoseLinkKeysResult = { corpId: string; corpName?: string; baseUrl: string; staffId: string; keys: HoseOpenApiKey[]; }; export function maskHoseSecurity(secret: string): string { if (!secret) return "-"; if (secret.length <= 12) return "******"; return `${secret.slice(0, 8)}...${secret.slice(-4)}`; } export async function resolveHoseAssistLinkDetails( value: string | HoseAssistLink ): Promise { const link = typeof value === "string" ? parseHoseAssistLink(value) : normalizeHoseAssistLink(value); const baseUrl = link.baseUrl || "https://app.ekuaibao.com"; let staffId: string | undefined; let corpName: string | undefined; let staffName: string | undefined; let isAdmin: boolean | undefined; let cellphone: string | undefined; const headers: Record = { accesstoken: link.accessToken, corpid: link.corpId }; // 1. Try resolving staffId, corporationName, and staffName via $UNITY JWT try { const jwtRes = await ky .get(`${baseUrl}/api/engine/realm/$UNITY/actions/jwt`, { searchParams: { corpId: link.corpId }, headers, timeout: 10000 }) .json<{ id?: string; value?: string }>(); const token = jwtRes.id || jwtRes.value; if (token) { const parts = token.split("."); if (parts.length >= 2) { const base64 = parts[1]!.replace(/-/g, "+").replace(/_/g, "/"); const payload = JSON.parse(Buffer.from(base64, "base64").toString("utf-8")) as Record; if (typeof payload.staffId === "string") staffId = payload.staffId; if (typeof payload.corporationName === "string") corpName = payload.corporationName; if (typeof payload.staffName === "string") staffName = payload.staffName; if (typeof payload.cellphone === "string") cellphone = payload.cellphone; if (payload.isAdmin !== undefined) { isAdmin = payload.isAdmin === true || payload.isAdmin === "true"; } } } } catch { // Ignore and fallback } // 2. If staffId or corpName is still missing, fallback to /api/account/v2/session if (!staffId || !corpName) { try { const sessionRes = await ky .get(`${baseUrl}/api/account/v2/session`, { headers: { ...headers, ...(staffId ? { staffid: staffId } : {}) }, timeout: 10000 }) .json<{ value?: { id?: string; userId?: string; loginStaffId?: string; corporationId?: string; corporationName?: string; privilege?: string; }; }>(); const s = sessionRes?.value; if (s) { if (!staffId && s.loginStaffId) staffId = s.loginStaffId; if (!corpName && s.corporationName) corpName = s.corporationName; if (!staffName && s.privilege) staffName = s.privilege; } } catch { // Ignore } } // Default staffId if still unresolved if (!staffId) { staffId = `${link.corpId}:admin`; } return { corpId: link.corpId, baseUrl, accessToken: link.accessToken, staffId, corpName, staffName, isAdmin, cellphone }; } export async function fetchHoseOpenApiKeysFromLink( value: string | HoseAssistLink ): Promise { const details = await resolveHoseAssistLinkDetails(value); const headers: Record = { accesstoken: details.accessToken, corpid: details.corpId, staffid: details.staffId }; let json: { items?: unknown[]; count?: number }; try { const response = await ky.get(`${details.baseUrl}/api/innerapi/v1/key`, { searchParams: { corpId: details.corpId }, headers, timeout: 15000 }); json = (await response.json()) as { items?: unknown[]; count?: number }; } catch (error) { const msg = error instanceof Error ? error.message : String(error); throw new Error(`Failed to query Hose OpenAPI keys from assistance link: ${msg}`); } const rawItems = json.items ?? []; const keys: HoseOpenApiKey[] = []; for (const raw of rawItems) { if (typeof raw === "object" && raw !== null) { const item = raw as Record; if (typeof item.appKey === "string" && typeof item.appSecurity === "string") { keys.push({ id: String(item.id ?? item.appKey), name: typeof item.name === "string" ? item.name : undefined, appKey: item.appKey, appSecurity: item.appSecurity, active: typeof item.active === "boolean" ? item.active : true, corporationId: typeof item.corporationId === "string" ? item.corporationId : details.corpId, createTime: typeof item.createTime === "number" ? item.createTime : undefined, updateTime: typeof item.updateTime === "number" ? item.updateTime : undefined }); } } } return { corpId: details.corpId, corpName: details.corpName, baseUrl: details.baseUrl, staffId: details.staffId, keys }; }