From 97315a3c924b5cc50bec7c1593af07940241c9b9 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Tue, 9 Jun 2026 14:31:06 +0800 Subject: [PATCH] Improve Hose enterprise add workflow --- src/cli.ts | 100 +++++++++++++++++++++++++++++---- src/core/config/loader.test.ts | 37 ++++++++++++ src/core/config/loader.ts | 42 ++++++++++---- 3 files changed, 155 insertions(+), 24 deletions(-) diff --git a/src/cli.ts b/src/cli.ts index 1089de1..c8d054d 100755 --- a/src/cli.ts +++ b/src/cli.ts @@ -5,11 +5,12 @@ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node import { homedir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; -import { getEnterprisesDirCandidates, loadCorpConfigs, USER_ENTERPRISES_DIR } from "./core/config/loader.js"; +import { getEnterprisesDirCandidates, loadCorpConfigs, resolveWritableEnterprisesDir } from "./core/config/loader.js"; import { createSealClient } from "./core/http/factory.js"; import { resolveLiveSealEnterpriseConfig } from "./domains/seal/source.js"; import { sealTools, type SealTool } from "./domains/seal/tools.js"; import { CorpConfig } from "./core/config/types.js"; +import { clearCorpTokenCache } from "./core/auth/token-store.js"; const VERSION = "0.3.0"; const APP_ROOT = dirname(dirname(fileURLToPath(import.meta.url))); @@ -101,7 +102,7 @@ async function main() { } if (area === "corps" && action === "add-hose") { - addHoseCorp(jsonObject(args.json)); + await addHoseCorp(jsonObject(args.json)); return; } @@ -407,15 +408,28 @@ function readCurrentCorpId(): string | undefined { return value || undefined; } -function addHoseCorp(input: Record) { - const id = requiredString(input, "id"); - const name = requiredString(input, "name"); +async function addHoseCorp(input: Record) { + const nameInput = optionalString(input, "name"); const appKey = requiredString(input, "appKey"); const appSecurity = requiredString(input, "appSecurity"); - const corpId = requiredString(input, "corpId"); - const staffId = requiredString(input, "staffId"); + const staffId = requiredStringAlias(input, ["staffId", "proxyStaffBizId"]); + const corpIdInput = + optionalString(input, "corpId") ?? + optionalString(input, "corporationId"); const domain = optionalString(input, "domain") ?? "https://app.ekuaibao.com"; - const sealUrl = optionalString(input, "sealUrl") ?? `https://${id.toLowerCase()}.sealai.cc`; + const verify = input.force === true || input.verify === false ? false : true; + const remote = corpIdInput && !verify + ? undefined + : await resolveHoseCorporation(domain, appKey, appSecurity); + const corpId = corpIdInput ?? remote?.id ?? (!verify ? inferCorpIdFromStaffId(staffId) : undefined); + if (!corpId) { + throw new Error( + "Missing required JSON field: corpId. Hose login did not return corporationId. Pass force:true to infer it from proxyStaffBizId." + ); + } + const id = optionalString(input, "id") ?? corpId; + const name = nameInput ?? remote?.name ?? corpId; + const sealUrl = optionalString(input, "sealUrl") ?? `https://${corpId.toLowerCase()}.sealai.cc`; const config: CorpConfig = { id, @@ -439,8 +453,14 @@ function addHoseCorp(input: Record) { } }; - mkdirSync(USER_ENTERPRISES_DIR, { recursive: true, mode: 0o700 }); - const file = join(USER_ENTERPRISES_DIR, `${safeFileName(id)}.json`); + if (verify) { + clearCorpTokenCache(id); + await resolveLiveSealEnterpriseConfig(config); + } + + const enterprisesDir = resolveWritableEnterprisesDir(); + mkdirSync(enterprisesDir, { recursive: true, mode: 0o700 }); + const file = join(enterprisesDir, `${safeFileName(id)}.json`); if (existsSync(file) && input.overwrite !== true) { throw new Error(`Enterprise config already exists: ${file}. Pass "overwrite": true to replace it.`); } @@ -449,6 +469,8 @@ function addHoseCorp(input: Record) { printJson({ id, name, + corpId, + verified: verify, path: file }); } @@ -459,11 +481,59 @@ function requiredString(input: Record, key: string): string { return value; } +function requiredStringAlias(input: Record, keys: string[]): string { + for (const key of keys) { + const value = optionalString(input, key); + if (value) return value; + } + throw new Error(`Missing required JSON field: ${keys.join(" or ")}`); +} + function optionalString(input: Record, key: string): string | undefined { const value = input[key]; return typeof value === "string" && value.trim() ? value.trim() : undefined; } +function inferCorpIdFromStaffId(staffId: string): string | undefined { + const [corpId] = staffId.split(":", 1); + return corpId || undefined; +} + +async function resolveHoseCorporation(domain: string, appKey: string, appSecurity: string) { + const response = await fetch(`${domain.replace(/\/+$/, "")}/api/openapi/v1/auth/getAccessToken`, { + method: "POST", + headers: { + "content-type": "application/json" + }, + body: JSON.stringify({ + appKey, + appSecurity + }) + }); + + if (!response.ok) { + const body = await response.text().catch(() => ""); + throw new Error(`Hose login failed: ${response.status}${body ? ` ${body}` : ""}`); + } + + const data = await response.json() as { + value?: { + corporationId?: string; + corporation?: { + id?: string; + name?: string; + }; + }; + }; + const corporationId = data.value?.corporationId ?? data.value?.corporation?.id; + return corporationId + ? { + id: corporationId, + name: data.value?.corporation?.name + } + : undefined; +} + function safeFileName(value: string): string { return value.replace(/[^a-zA-Z0-9._-]/g, "_"); } @@ -612,7 +682,7 @@ Usage: seal-home corps list [--corp ] seal-home corps current seal-home corps switch - seal-home corps add-hose --json '{"id":"corp-id","name":"企业名称","appKey":"...","appSecurity":"...","corpId":"...","staffId":"..."}' + seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}' seal-home source config [--corp ] seal-home tool [--corp ] [--json '{"key":"value"}'] seal-home rules versions [--corp ] @@ -629,6 +699,12 @@ Usage: } main().catch((error) => { - console.error(error instanceof Error ? error.message : String(error)); + console.error(redactSensitiveText(error instanceof Error ? error.message : String(error))); process.exit(1); }); + +function redactSensitiveText(value: string): string { + return value + .replace(/([?&](?:accessToken|token|returnToken)=)[^&\s]+/gi, "$1") + .replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, "$1"); +} diff --git a/src/core/config/loader.test.ts b/src/core/config/loader.test.ts index cf23bb6..b6c841b 100644 --- a/src/core/config/loader.test.ts +++ b/src/core/config/loader.test.ts @@ -5,14 +5,22 @@ import { join } from "node:path"; import { loadCorpConfigs, resolveEnterprisesDir } from "./loader.js"; const ORIGINAL_ENV = process.env.SEAL_HOME_ENTERPRISES_DIR; +const ORIGINAL_USER_DIR_ENV = process.env.SEAL_HOME_USER_ENTERPRISES_DIR; +const ORIGINAL_CWD = process.cwd(); const tempDirs: string[] = []; afterEach(() => { + process.chdir(ORIGINAL_CWD); if (ORIGINAL_ENV === undefined) { delete process.env.SEAL_HOME_ENTERPRISES_DIR; } else { process.env.SEAL_HOME_ENTERPRISES_DIR = ORIGINAL_ENV; } + if (ORIGINAL_USER_DIR_ENV === undefined) { + delete process.env.SEAL_HOME_USER_ENTERPRISES_DIR; + } else { + process.env.SEAL_HOME_USER_ENTERPRISES_DIR = ORIGINAL_USER_DIR_ENV; + } for (const dir of tempDirs.splice(0)) { rmSync(dir, { recursive: true, force: true }); @@ -44,6 +52,23 @@ describe("loadCorpConfigs", () => { expect(resolveEnterprisesDir()).toBeUndefined(); expect(loadCorpConfigs()).toEqual([]); }); + + test("merges local and user enterprise directories with user configs taking precedence", () => { + const workspace = makeTempDir(); + const workspaceEnterprises = join(workspace, "enterprises"); + const userDir = makeTempDir(); + mkdirSync(workspaceEnterprises, { recursive: true }); + writeCorpConfig(join(workspaceEnterprises, "shared.json"), "shared", "Workspace"); + writeCorpConfig(join(userDir, "shared.json"), "shared", "User"); + writeCorpConfig(join(userDir, "user-only.json"), "user-only", "User Only"); + process.chdir(workspace); + process.env.SEAL_HOME_USER_ENTERPRISES_DIR = userDir; + + expect(loadCorpConfigs().map((corp) => [corp.id, corp.name])).toEqual([ + ["shared", "User"], + ["user-only", "User Only"] + ]); + }); }); function makeTempDir(): string { @@ -52,3 +77,15 @@ function makeTempDir(): string { tempDirs.push(dir); return dir; } + +function writeCorpConfig(path: string, id: string, name: string) { + writeFileSync(path, JSON.stringify({ + id, + name, + source: { + type: "direct", + token: "seal-token", + sealUrl: `https://${id}.sealai.cc` + } + })); +} diff --git a/src/core/config/loader.ts b/src/core/config/loader.ts index e98a4d3..8565f8d 100644 --- a/src/core/config/loader.ts +++ b/src/core/config/loader.ts @@ -5,30 +5,48 @@ import { CorpConfig, CorpConfigSchema } from "./types.js"; const ENTERPRISES_DIR = "enterprises"; const CONFIG_ENV = "SEAL_HOME_ENTERPRISES_DIR"; +const USER_DIR_ENV = "SEAL_HOME_USER_ENTERPRISES_DIR"; export const USER_ENTERPRISES_DIR = join(homedir(), ".config", "seal-home", "enterprises"); export function loadCorpConfigs(): CorpConfig[] { - const dir = resolveEnterprisesDir(); - if (!dir) { - return []; + const dirs = resolveEnterprisesDirs(); + const byId = new Map(); + + for (const dir of dirs) { + for (const file of readdirSync(dir) + .filter((item) => item.endsWith(".json")) + .filter((item) => !item.startsWith("example."))) { + const content = readFileSync(join(dir, file), "utf-8"); + const corp = CorpConfigSchema.parse(JSON.parse(content)); + byId.set(corp.id, corp); + } } - return readdirSync(dir) - .filter((file) => file.endsWith(".json")) - .filter((file) => !file.startsWith("example.")) - .map((file) => { - const content = readFileSync(join(dir, file), "utf-8"); - return CorpConfigSchema.parse(JSON.parse(content)); - }); + return Array.from(byId.values()); } export function resolveEnterprisesDir(): string | undefined { + return resolveEnterprisesDirs()[0]; +} + +export function resolveEnterprisesDirs(): string[] { + const configured = process.env[CONFIG_ENV]?.trim(); + if (configured) return existsSync(configured) ? [configured] : []; + + const userDir = process.env[USER_DIR_ENV]?.trim() || USER_ENTERPRISES_DIR; + return [ENTERPRISES_DIR, userDir].filter((dir) => existsSync(dir)); +} + +export function resolvePrimaryEnterprisesDir(): string | undefined { const configured = process.env[CONFIG_ENV]?.trim(); if (configured) return existsSync(configured) ? configured : undefined; - if (existsSync(ENTERPRISES_DIR)) return ENTERPRISES_DIR; + const userDir = process.env[USER_DIR_ENV]?.trim() || USER_ENTERPRISES_DIR; + return existsSync(userDir) ? userDir : undefined; +} - return existsSync(USER_ENTERPRISES_DIR) ? USER_ENTERPRISES_DIR : undefined; +export function resolveWritableEnterprisesDir(): string { + return process.env[CONFIG_ENV]?.trim() || USER_ENTERPRISES_DIR; } export function getEnterprisesDirCandidates(): string[] {