diff --git a/enterprises/example.direct.json b/enterprises/example.direct.json new file mode 100644 index 0000000..98c7705 --- /dev/null +++ b/enterprises/example.direct.json @@ -0,0 +1,21 @@ +{ + "id": "direct-corp", + "name": "Direct Seal 企业", + "seal": { + "url": "https://corp-id.sealai.cc", + "endpoints": { + "approvalStylePreferences": "api/v1/approval/style-preferences" + } + }, + "source": { + "type": "direct", + "token": "seal-bearer-token", + "sealUrl": "https://corp-id.sealai.cc", + "expiresIn": 3600, + "corpId": "corp-id", + "staffId": "staff-id" + }, + "auth": { + "refreshTtl": 300 + } +} diff --git a/enterprises/example.hose.json b/enterprises/example.hose.json new file mode 100644 index 0000000..e3b1c83 --- /dev/null +++ b/enterprises/example.hose.json @@ -0,0 +1,21 @@ +{ + "id": "corp-id", + "name": "企业名称", + "seal": { + "url": "https://corp-id.sealai.cc", + "endpoints": { + "approvalStylePreferences": "api/v1/approval/style-preferences" + } + }, + "source": { + "type": "hose", + "domain": "https://app.ekuaibao.com", + "key": "hose-app-key", + "password": "hose-app-security", + "staffId": "hose-staff-id", + "corpId": "hose-corp-id" + }, + "auth": { + "refreshTtl": 300 + } +} diff --git a/src/core/auth/direct.ts b/src/core/auth/direct.ts new file mode 100644 index 0000000..3a9c4b4 --- /dev/null +++ b/src/core/auth/direct.ts @@ -0,0 +1,25 @@ +import { CorpConfig } from "../config/types.js"; +import { SealSession } from "./types.js"; + +export async function getDirectSealSession(corp: CorpConfig): Promise { + if (corp.source.type !== "direct") { + throw new Error(`Unsupported Seal source: ${corp.source.type}`); + } + + const sealUrl = corp.seal.url ?? corp.source.sealUrl; + + return { + token: corp.source.token, + expiresAt: Date.now() + corp.source.expiresIn * 1000, + enterprise: { + provider: "direct", + corpId: corp.source.corpId ?? corp.id, + staffId: corp.source.staffId, + sealUrl, + tenantSlug: corp.seal.tenantSlug, + raw: { + sourceType: "direct" + } + } + }; +} diff --git a/src/core/auth/hose.ts b/src/core/auth/hose.ts new file mode 100644 index 0000000..5fe440f --- /dev/null +++ b/src/core/auth/hose.ts @@ -0,0 +1,229 @@ +import ky, { HTTPError, KyInstance } from "ky"; +import { CorpConfig, HoseSealSource } from "../config/types.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; + }; +}; + +function normalizeBaseUrl(url: string): string { + return url.replace(/\/+$/, ""); +} + +function isFresh(entry: TokenEntry | undefined, refreshTtl = 60): entry is TokenEntry { + return Boolean(entry && Date.now() < entry.expiresAt - refreshTtl * 1000); +} + +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 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 + }; +} + +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 openapi = await fetchHoseOpenapiToken(corp.source); + setHoseAuthCache(corp.id, { + ...cache, + openapi + }); + return openapi.token; +} + +async function fetchHoseCloseApiToken( + source: HoseSealSource, + openapiToken: string +): Promise { + const client = hoseClient(source); + const uid = `${source.corpId}:${source.staffId}`; + + const response = await client + .post("api/openapi/v1.1/provisional/getProvisionalAuth", { + searchParams: { + accessToken: openapiToken + }, + json: { + uid, + pageType: "home", + expireDate: 7200 + } + }) + .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, + expiresAt: Date.now() + 7200 * 1000 + }; +} + +async function ensureHoseCloseApiToken(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.closeapi)) { + return cache.closeapi.token; + } + + const openapiToken = await ensureHoseOpenapiToken(corp); + const closeapi = await fetchHoseCloseApiToken(corp.source, openapiToken); + setHoseAuthCache(corp.id, { + ...getHoseAuthCache(corp.id), + closeapi + }); + return closeapi.token; +} + +export async function getHoseSealSession(corp: CorpConfig): Promise { + if (corp.source.type !== "hose") { + throw new Error(`Unsupported Seal source: ${corp.source.type}`); + } + + const hoseAccessToken = await ensureHoseCloseApiToken(corp); + const sealUrl = defaultSealUrl(corp, corp.source); + + const sealResponse = await ky + .get(`${normalizeBaseUrl(sealUrl)}/api/auth/oauth2/session/oem-hosecloud`, { + searchParams: { + token: hoseAccessToken, + returnToken: "1" + }, + timeout: 30000 + }) + .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 + }; +} diff --git a/src/core/auth/seal.ts b/src/core/auth/seal.ts new file mode 100644 index 0000000..1de2d7b --- /dev/null +++ b/src/core/auth/seal.ts @@ -0,0 +1,54 @@ +import { CorpConfig } from "../config/types.js"; +import { getDirectSealSession } from "./direct.js"; +import { getHoseSealSession } from "./hose.js"; +import { clearSealSession, getSealSession, setSealSession } from "./token-store.js"; +import { SealEnterpriseConfig, SealSession } from "./types.js"; + +const memoryCache = new Map(); + +function isExpired(session: SealSession, refreshTtl: number): boolean { + return Date.now() >= session.expiresAt - refreshTtl * 1000; +} + +async function refreshSealSession(corp: CorpConfig): Promise { + switch (corp.source.type) { + case "hose": + return getHoseSealSession(corp); + case "direct": + return getDirectSealSession(corp); + } +} + +export async function getSealSessionForCorp(corp: CorpConfig): Promise { + const refreshTtl = corp.auth.refreshTtl; + const cached = memoryCache.get(corp.id); + if (cached && !isExpired(cached, refreshTtl)) { + return cached; + } + + const stored = getSealSession(corp.id); + if (stored && !isExpired(stored, refreshTtl)) { + memoryCache.set(corp.id, stored); + return stored; + } + + const next = await refreshSealSession(corp); + memoryCache.set(corp.id, next); + setSealSession(corp.id, next); + return next; +} + +export async function getSealToken(corp: CorpConfig): Promise { + return (await getSealSessionForCorp(corp)).token; +} + +export async function resolveSealEnterpriseConfig( + corp: CorpConfig +): Promise { + return (await getSealSessionForCorp(corp)).enterprise; +} + +export function clearSealToken(corpId: string): void { + memoryCache.delete(corpId); + clearSealSession(corpId); +} diff --git a/src/core/auth/token-store.ts b/src/core/auth/token-store.ts new file mode 100644 index 0000000..4b65419 --- /dev/null +++ b/src/core/auth/token-store.ts @@ -0,0 +1,88 @@ +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { homedir } from "node:os"; +import { + CorpTokenCache, + HoseAuthCache, + SealSession, + TokenStore, + TokenStoreSchema +} from "./types.js"; + +function storePath(): string { + return process.env.SEAL_HOME_TOKEN_STORE + ?? join(homedir(), ".config", "seal-home", "seal_tokens.json"); +} + +function readStore(): TokenStore { + const path = storePath(); + if (!existsSync(path)) { + return {}; + } + + try { + return TokenStoreSchema.parse(JSON.parse(readFileSync(path, "utf-8"))); + } catch { + return {}; + } +} + +function writeStore(store: TokenStore): void { + const path = storePath(); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, JSON.stringify(store, null, 2)); +} + +export function getSealSession(corpId: string): SealSession | undefined { + return readStore()[corpId]?.seal; +} + +export function setSealSession(corpId: string, session: SealSession): void { + const store = readStore(); + writeStore({ + ...store, + [corpId]: { + ...store[corpId], + seal: session + } + }); +} + +export function clearSealSession(corpId: string): void { + const store = readStore(); + const current = store[corpId]; + if (!current) return; + + writeStore({ + ...store, + [corpId]: { + ...current, + seal: undefined + } + }); +} + +export function getCorpTokenCache(corpId: string): CorpTokenCache { + return readStore()[corpId] ?? {}; +} + +export function getHoseAuthCache(corpId: string): HoseAuthCache { + return readStore()[corpId]?.hose ?? {}; +} + +export function setHoseAuthCache(corpId: string, hose: HoseAuthCache): void { + const store = readStore(); + writeStore({ + ...store, + [corpId]: { + ...store[corpId], + hose + } + }); +} + +export function clearCorpTokenCache(corpId: string): void { + const store = readStore(); + delete store[corpId]; + writeStore(store); +} diff --git a/src/core/auth/types.ts b/src/core/auth/types.ts new file mode 100644 index 0000000..1b2c702 --- /dev/null +++ b/src/core/auth/types.ts @@ -0,0 +1,42 @@ +import { z } from "zod"; + +export const TokenEntrySchema = z.object({ + token: z.string(), + expiresAt: z.number() +}); + +export const SealEnterpriseConfigSchema = z.object({ + provider: z.string(), + corpId: z.string().optional(), + staffId: z.string(), + sealUrl: z.string().url(), + tenantId: z.string().optional(), + tenantSlug: z.string().optional(), + tenantName: z.string().optional(), + raw: z.unknown().optional() +}); + +export const SealSessionSchema = z.object({ + token: z.string(), + expiresAt: z.number(), + enterprise: SealEnterpriseConfigSchema +}); + +export const HoseAuthCacheSchema = z.object({ + openapi: TokenEntrySchema.optional(), + closeapi: TokenEntrySchema.optional() +}); + +export const CorpTokenCacheSchema = z.object({ + seal: SealSessionSchema.optional(), + hose: HoseAuthCacheSchema.optional() +}); + +export const TokenStoreSchema = z.record(z.string(), CorpTokenCacheSchema); + +export type TokenEntry = z.infer; +export type SealEnterpriseConfig = z.infer; +export type SealSession = z.infer; +export type HoseAuthCache = z.infer; +export type CorpTokenCache = z.infer; +export type TokenStore = z.infer; diff --git a/src/core/http/factory.ts b/src/core/http/factory.ts new file mode 100644 index 0000000..f7f1602 --- /dev/null +++ b/src/core/http/factory.ts @@ -0,0 +1,30 @@ +import ky, { HTTPError, KyInstance } from "ky"; +import { CorpConfig } from "../config/types.js"; +import { clearSealToken, getSealSessionForCorp } from "../auth/seal.js"; + +export async function createSealClient(corp: CorpConfig): Promise { + const session = await getSealSessionForCorp(corp); + + return ky.create({ + prefix: session.enterprise.sealUrl, + timeout: 30000, + headers: { + Authorization: `Bearer ${session.token}` + }, + hooks: { + beforeError: [ + async ({ error }) => { + if (error instanceof HTTPError && error.response.status === 401) { + clearSealToken(corp.id); + } + const body = + error instanceof HTTPError + ? await error.response.text().catch(() => "") + : ""; + error.message = `${error.message}${body ? `: ${body}` : ""}`; + return error; + } + ] + } + }); +}