feat: add seal auth providers
This commit is contained in:
1 parent
25e4dd7714
commit
d575683c8b
8 files changed
+510
No files matched your search
@@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { CorpConfig } from "../config/types.js";
|
||||||
|
import { SealSession } from "./types.js";
|
||||||
|
|
||||||
|
export async function getDirectSealSession(corp: CorpConfig): Promise<SealSession> {
|
||||||
|
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"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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<TokenEntry> {
|
||||||
|
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<HoseLoginResponse>();
|
||||||
|
|
||||||
|
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<string> {
|
||||||
|
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<TokenEntry> {
|
||||||
|
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<HoseProvisionalResponse>();
|
||||||
|
|
||||||
|
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<string> {
|
||||||
|
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<SealSession> {
|
||||||
|
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<SealTokenResponse>();
|
||||||
|
|
||||||
|
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
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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<string, SealSession>();
|
||||||
|
|
||||||
|
function isExpired(session: SealSession, refreshTtl: number): boolean {
|
||||||
|
return Date.now() >= session.expiresAt - refreshTtl * 1000;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshSealSession(corp: CorpConfig): Promise<SealSession> {
|
||||||
|
switch (corp.source.type) {
|
||||||
|
case "hose":
|
||||||
|
return getHoseSealSession(corp);
|
||||||
|
case "direct":
|
||||||
|
return getDirectSealSession(corp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getSealSessionForCorp(corp: CorpConfig): Promise<SealSession> {
|
||||||
|
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<string> {
|
||||||
|
return (await getSealSessionForCorp(corp)).token;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function resolveSealEnterpriseConfig(
|
||||||
|
corp: CorpConfig
|
||||||
|
): Promise<SealEnterpriseConfig> {
|
||||||
|
return (await getSealSessionForCorp(corp)).enterprise;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearSealToken(corpId: string): void {
|
||||||
|
memoryCache.delete(corpId);
|
||||||
|
clearSealSession(corpId);
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -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<typeof TokenEntrySchema>;
|
||||||
|
export type SealEnterpriseConfig = z.infer<typeof SealEnterpriseConfigSchema>;
|
||||||
|
export type SealSession = z.infer<typeof SealSessionSchema>;
|
||||||
|
export type HoseAuthCache = z.infer<typeof HoseAuthCacheSchema>;
|
||||||
|
export type CorpTokenCache = z.infer<typeof CorpTokenCacheSchema>;
|
||||||
|
export type TokenStore = z.infer<typeof TokenStoreSchema>;
|
||||||
@@ -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<KyInstance> {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
Reference in new issue
Block a user