diff --git a/.zcode-plugin/plugin.json b/.zcode-plugin/plugin.json index 4d73505..bbaaf0c 100644 --- a/.zcode-plugin/plugin.json +++ b/.zcode-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "seal-home", - "version": "0.9.2", + "version": "0.9.3", "description": "Seal Home tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.", "author": { "name": "yingqing" diff --git a/CHANGELOG.md b/CHANGELOG.md index 773fd5c..a1579e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 --- +## [0.9.3] - 2026-08-26 + +### Added +- **Automated Hose Enterprise Initialization & Probing**: Added `seal-home corps probe-hose` to probe enterprise metadata and discover available role definition groups via OpenAPI. +- **Multi-Domain Concurrent Probing**: Intelligently probes candidate public SaaS domains (`app.ekuaibao.com`, `dd2.hosecloud.com`, `wx2.ekuaibao.com`, `kdcloud2.ekuaibao.com`, `ddenterprise.ekuaibao.com`, `feishu.ekuaibao.com`) when `domain` is omitted, while supporting explicit custom domains for private cloud / dedicated tenants (e.g. 美年大健康). +- **OpenAPI Role & Staff Discovery**: Added `seal-home corps hose-staffs` to query members under any role (defaults to `admin`, or business roles like `财务主管`, `采购申请权限`) and batch resolve member details (name, cellphone, activation status, third-party user ID) via `POST /api/openapi/v1/staffs/getStaffIds`. +- **Strict Staff Selection Guard (Anti-Silent Activation)**: Guarded `seal-home corps add-hose` against silent administrator activation. When multiple candidate administrators exist, the system requires explicit selection (`staffId`, `staffName`, or `staffPhone`) or structured candidate confirmation. +- **Dedicated Skill Reference**: Added `skills/seal-home/references/hose-enterprise-init.md` covering domain decision tiering, OpenAPI contracts, and non-TUI Agent autonomous workflows. + +--- + ## [0.9.2] - 2026-08-25 ### Fixed & Enhanced diff --git a/dist/mcp/server.js b/dist/mcp/server.js index 211dfd3..6f05aae 100644 --- a/dist/mcp/server.js +++ b/dist/mcp/server.js @@ -24673,6 +24673,14 @@ function clearCorpTokenCache(corpId) { } // src/core/auth/hose.ts +var 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" +]; var openapiTokenRequests = new Map; var closeApiTokenRequests = new Map; function normalizeBaseUrl(url2) { @@ -24859,6 +24867,149 @@ async function getHoseSealSession(corp) { enterprise }; } +async function probeHoseDomain(appKey, appSecurity, explicitDomain) { + 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 (domain2) => { + try { + return await testSingleHoseDomain(domain2, appKey, appSecurity); + } catch { + return; + } + }); + const results = await Promise.all(candidatePromises); + const matched = results.filter((item) => 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(domain2, appKey, appSecurity) { + try { + const response = await fetch(`${domain2}/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; + const data = await response.json(); + if (data.value?.errorCode) + return; + const openapiToken = data.value?.accessToken ?? data.accessToken; + const corpId = data.value?.corporationId ?? data.value?.corporation?.id; + if (!openapiToken || !corpId) + return; + return { + domain: domain2, + corpId, + corpName: data.value?.corporation?.name, + openapiToken, + expireTime: data.value?.expireTime + }; + } catch { + return; + } +} +async function fetchHoseRoleDefGroups(domain2, openapiToken) { + const url2 = `${normalizeBaseUrl(domain2)}/api/openapi/v1/roleDefGroups?accessToken=${encodeURIComponent(openapiToken)}`; + const response = await fetch(url2, { + headers: { + "content-type": "application/json", + Accept: "application/json" + }, + signal: AbortSignal.timeout(1e4) + }); + if (!response.ok) { + const text = await response.text().catch(() => ""); + throw new Error(`Failed to fetch Hose role definition groups: ${response.status} ${text}`); + } + const json2 = await response.json(); + const groups = json2.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 + })) + })); +} +async function fetchHoseRoleStaffs(domain2, openapiToken, roledefId, staffBy = "id") { + const cleanId = roledefId.startsWith("$") ? roledefId.slice(1) : roledefId; + const url2 = `${normalizeBaseUrl(domain2)}/api/openapi/v1/roledefs/$${cleanId}?accessToken=${encodeURIComponent(openapiToken)}&staffBy=${encodeURIComponent(staffBy)}&pathType=name`; + const response = await fetch(url2, { + headers: { + "content-type": "application/json", + Accept: "application/json" + }, + signal: AbortSignal.timeout(1e4) + }); + if (!response.ok) { + const text = await response.text().catch(() => ""); + throw new Error(`Failed to fetch Hose role staffs for ${cleanId}: ${response.status} ${text}`); + } + const json2 = await response.json(); + const val = json2.value; + if (!val) { + throw new Error(`Hose role staff query returned empty result for ${cleanId}`); + } + const allStaffs = []; + 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 + }; +} +async function fetchHoseStaffDetails(domain2, openapiToken, staffIds) { + if (staffIds.length === 0) + return []; + const url2 = `${normalizeBaseUrl(domain2)}/api/openapi/v1/staffs/getStaffIds?accessToken=${encodeURIComponent(openapiToken)}`; + const response = await fetch(url2, { + method: "POST", + headers: { + "content-type": "application/json", + Accept: "application/json" + }, + body: JSON.stringify({ + type: "STAFFID", + conditionIds: staffIds.slice(0, 100) + }), + signal: AbortSignal.timeout(1e4) + }); + if (!response.ok) { + const text = await response.text().catch(() => ""); + throw new Error(`Failed to fetch Hose staff details: ${response.status} ${text}`); + } + const json2 = await response.json(); + return json2.items ?? []; +} // src/core/auth/seal.ts var memoryCache = new Map; @@ -24943,7 +25094,7 @@ async function createSealClientForToken(corp, token) { // package.json var package_default = { name: "seal-home", - version: "0.9.2", + version: "0.9.3", type: "module", module: "src/server.ts", bin: { @@ -24959,6 +25110,7 @@ var package_default = { "build:plugin": "node scripts/build-plugin.mjs", bump: "bun run scripts/bump-version.ts", "openapi:bundle": "bun run scripts/bundle-openapi.ts", + "openapi:raw": "bun run scripts/generate-raw-openapi.ts", test: "bun test" }, dependencies: { @@ -29132,14 +29284,6 @@ function requiredString(input, key) { throw new Error(`Missing required JSON field: ${key}`); return value; } -function requiredStringAlias(input, keys) { - 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, key) { const value = input[key]; return typeof value === "string" && value.trim() ? value.trim() : undefined; @@ -29148,10 +29292,6 @@ function optionalNumber(input, key) { const value = input[key]; return typeof value === "number" && Number.isFinite(value) ? value : undefined; } -function inferCorpIdFromStaffId(staffId) { - const [corpId] = staffId.split(":", 1); - return corpId || undefined; -} function safeFileName(value) { return value.replace(/[^a-zA-Z0-9._-]/g, "_"); } @@ -29935,6 +30075,14 @@ async function handleCorpsCommand(action, maybeName, args) { }); return; } + if (action === "probe-hose") { + await probeHoseCorp(jsonObject(args.json)); + return; + } + if (action === "hose-staffs") { + await queryHoseStaffs(jsonObject(args.json)); + return; + } if (action === "add-hose") { await addHoseCorp(jsonObject(args.json)); return; @@ -29945,21 +30093,173 @@ async function handleCorpsCommand(action, maybeName, args) { } throw new Error(`Unknown corps command: ${action ?? ""}. Run 'seal-home help' for available commands.`); } +async function probeHoseCorp(input) { + const appKey = requiredString(input, "appKey"); + const appSecurity = requiredString(input, "appSecurity"); + const explicitDomain = optionalString(input, "domain"); + const probe = await probeHoseDomain(appKey, appSecurity, explicitDomain); + const roleGroups = await fetchHoseRoleDefGroups(probe.domain, probe.openapiToken).catch(() => []); + const totalRoles = roleGroups.reduce((acc, g) => acc + g.roleDefs.length, 0); + printJson({ + domain: probe.domain, + corpId: probe.corpId, + name: probe.corpName ?? probe.corpId, + roleCount: totalRoles, + roleGroups: roleGroups.map((g) => ({ + id: g.id, + name: g.name, + roleDefs: g.roleDefs.map((r) => ({ + id: r.id, + name: r.name, + sourceType: r.sourceType + })) + })) + }); +} +async function queryHoseStaffs(input) { + const appKey = requiredString(input, "appKey"); + const appSecurity = requiredString(input, "appSecurity"); + const explicitDomain = optionalString(input, "domain"); + const roleQuery = optionalString(input, "role") ?? optionalString(input, "roleDefId") ?? "admin"; + const probe = await probeHoseDomain(appKey, appSecurity, explicitDomain); + const roleGroups = await fetchHoseRoleDefGroups(probe.domain, probe.openapiToken); + let targetRoleDefId; + let targetRoleName; + for (const g of roleGroups) { + for (const r of g.roleDefs) { + if (r.id === roleQuery || r.id === `${probe.corpId}:${roleQuery}`) { + targetRoleDefId = r.id; + targetRoleName = r.name; + break; + } + } + if (targetRoleDefId) + break; + } + if (!targetRoleDefId && (roleQuery === "admin" || roleQuery === "主管理员")) { + for (const g of roleGroups) { + for (const r of g.roleDefs) { + if (r.id.endsWith(":admin") || r.name === "主管理员") { + targetRoleDefId = r.id; + targetRoleName = r.name; + break; + } + } + if (targetRoleDefId) + break; + } + } + if (!targetRoleDefId) { + for (const g of roleGroups) { + for (const r of g.roleDefs) { + if (r.name.toLowerCase().includes(roleQuery.toLowerCase())) { + targetRoleDefId = r.id; + targetRoleName = r.name; + break; + } + } + if (targetRoleDefId) + break; + } + } + if (!targetRoleDefId) { + throw new Error(`Role not found matching query: '${roleQuery}'. Run 'seal-home corps probe-hose' to view all available roles.`); + } + const roleStaffs = await fetchHoseRoleStaffs(probe.domain, probe.openapiToken, targetRoleDefId); + const staffDetails = await fetchHoseStaffDetails(probe.domain, probe.openapiToken, roleStaffs.staffs); + printJson({ + domain: probe.domain, + corpId: probe.corpId, + corpName: probe.corpName ?? probe.corpId, + roleId: targetRoleDefId, + roleName: targetRoleName, + count: staffDetails.length, + staffs: staffDetails.map((s) => ({ + id: s.id, + name: s.name, + cellphone: s.cellphone, + active: s.active, + authState: s.authState, + userId: s.userId, + email: s.email + })) + }); +} async function addHoseCorp(input) { const nameInput = optionalString(input, "name"); const appKey = requiredString(input, "appKey"); const appSecurity = requiredString(input, "appSecurity"); - const staffId = requiredStringAlias(input, ["staffId", "proxyStaffBizId"]); - const corpIdInput = optionalString(input, "corpId") ?? optionalString(input, "corporationId"); - const domain2 = optionalString(input, "domain") ?? "https://app.ekuaibao.com"; - const verify = input.force === true || input.verify === false ? false : true; - const remote = corpIdInput && !verify ? undefined : await resolveHoseCorporation(domain2, 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 explicitDomain = optionalString(input, "domain"); + const explicitStaffId = optionalString(input, "staffId") ?? optionalString(input, "proxyStaffBizId"); + const staffName = optionalString(input, "staffName"); + const staffPhone = optionalString(input, "staffPhone"); + const roleQuery = optionalString(input, "role") ?? "admin"; + const force = input.force === true; + const verify = force || input.verify === false ? false : true; + let domain2 = explicitDomain; + let corpId = optionalString(input, "corpId") ?? optionalString(input, "corporationId"); + let corpName = nameInput; + let openapiToken; + if (!domain2 || !corpId || !explicitStaffId) { + const probe = await probeHoseDomain(appKey, appSecurity, explicitDomain); + domain2 = probe.domain; + corpId = corpId ?? probe.corpId; + corpName = corpName ?? probe.corpName; + openapiToken = probe.openapiToken; + } + let finalStaffId = explicitStaffId; + if (!finalStaffId && openapiToken && domain2) { + const roleGroups = await fetchHoseRoleDefGroups(domain2, openapiToken).catch(() => []); + let targetRoleId; + for (const g of roleGroups) { + for (const r of g.roleDefs) { + if (r.id.endsWith(`:${roleQuery}`) || r.name === roleQuery || r.id === roleQuery) { + targetRoleId = r.id; + break; + } + } + if (targetRoleId) + break; + } + if (!targetRoleId) { + targetRoleId = roleGroups.find((g) => g.roleDefs.some((r) => r.id.endsWith(":admin")))?.roleDefs.find((r) => r.id.endsWith(":admin"))?.id; + } + if (targetRoleId) { + const roleStaffs = await fetchHoseRoleStaffs(domain2, openapiToken, targetRoleId).catch(() => ({ staffs: [] })); + const staffDetails = await fetchHoseStaffDetails(domain2, openapiToken, roleStaffs.staffs).catch(() => []); + if (staffName || staffPhone) { + const matches = staffDetails.filter((s) => { + if (staffName && s.name !== staffName && !s.name.includes(staffName)) + return false; + if (staffPhone && (!s.cellphone || !s.cellphone.includes(staffPhone))) + return false; + return true; + }); + if (matches.length === 1 && matches[0]) { + finalStaffId = matches[0].id; + } else if (matches.length > 1) { + throw new Error(`Multiple staff members matched '${staffName ?? staffPhone}': ${matches.map((m) => `${m.name}(${m.id})`).join(", ")}. Please specify exact staffId.`); + } else { + throw new Error(`No staff member found matching '${staffName ?? staffPhone}' under role ${targetRoleId}. Run 'seal-home corps hose-staffs' to view candidates.`); + } + } else if (!force) { + const candidates = staffDetails.map((s) => `${s.name} (${s.cellphone || "no-phone"}, id: ${s.id}, active: ${s.active})`).join(` + - `); + throw new Error(`Missing required parameter: staffId. Found ${staffDetails.length} candidate administrators: + - ${candidates} +` + `Please specify 'staffId', 'staffName', or 'staffPhone' to explicitly select an account (or pass force:true to bypass).`); + } + } + } + if (!finalStaffId) { + if (!verify && explicitStaffId) { + finalStaffId = explicitStaffId; + } else { + throw new Error("Missing required parameter: staffId (or proxyStaffBizId). Run 'seal-home corps hose-staffs' to discover available administrators."); + } } const id = optionalString(input, "id") ?? corpId; - const name = nameInput ?? remote?.name ?? corpId; + const name = corpName ?? corpId; const sealUrl = optionalString(input, "sealUrl") ?? `https://${corpId.toLowerCase()}.sealai.cc`; const config2 = { id, @@ -29976,7 +30276,7 @@ async function addHoseCorp(input) { appKey, appSecurity, corpId, - staffId + staffId: finalStaffId }, auth: { refreshTtl: 300 @@ -29998,6 +30298,8 @@ async function addHoseCorp(input) { id, name, corpId, + domain: domain2, + staffId: finalStaffId, verified: verify, path: file2 }); @@ -30065,28 +30367,6 @@ async function addSealCorp(input) { path: file2 }); } -async function resolveHoseCorporation(domain2, appKey, appSecurity) { - const response = await fetch(`${domain2.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(); - const corporationId = data.value?.corporationId ?? data.value?.corporation?.id; - return corporationId ? { - id: corporationId, - name: data.value?.corporation?.name - } : undefined; -} async function resolveSealWhoami(sealUrl, token) { const json2 = await getJson2(`${sealUrl}/api/v1/auth/me`, { authorization: `Bearer ${token}` @@ -30193,7 +30473,7 @@ var openapi_default = { openapi: "3.1.0", info: { title: "seal-home Wrapped API", - version: "0.9.2", + version: "0.9.3", description: `Planned HTTP contract for the seal-home wrapped backend API. These endpoints describe the intended stable API for frontend developers and agents once @@ -34495,13 +34775,13 @@ import { dirname as dirname3, join as join6 } from "node:path"; // skills/seal-home/SKILL.md var SKILL_default = `--- name: seal-home -description: "v0.9.2: Use when working with Seal Home tenant operations: packaged customer feedback from WeChat or screenshots, target-enterprise discovery, approval-run and Langfuse diagnosis, simulation test batch creation and publishing, minimal approval-rule remediation and publishing, delegation links, Hose/合思 authorization, LLM config, permissions, billing, users, rules, documents, and search." +description: "v0.9.3: Use when working with Seal Home tenant operations: packaged customer feedback from WeChat or screenshots, target-enterprise discovery, approval-run and Langfuse diagnosis, simulation test batch creation and publishing, minimal approval-rule remediation and publishing, delegation links, Hose/合思 authorization, LLM config, permissions, billing, users, rules, documents, and search." metadata: - version: 0.9.2 - short-description: Seal tenant and Hose approval automation (v0.9.2) + version: 0.9.3 + short-description: Seal tenant and Hose approval automation (v0.9.3) --- -# Seal Home (v0.9.2) +# Seal Home (v0.9.3) Use the \`seal_cli\` MCP tool when it is available; pass the command string as its \`command\` argument. If MCP is unavailable, fall back to the global \`seal-home\` CLI. This skill is a routing layer for agents: keep this file short, choose the right command, and read a focused reference only when the task needs detail. @@ -34588,6 +34868,7 @@ seal-home tool seal_approval_search --corp --json '{"keywords":["差旅 - \`references/approval-run-lightweight.md\`: 单号定位、字段裁剪、摘要、引用规则、单据摘要、附件摘要。 - \`references/rule-lightweight.md\`: 规则 count/list summary、按版本/编号取单条规则、规则搜索裁剪。 - \`references/customer-feedback-rule-remediation.md\`: 微信/截图反馈包到企业定位、审批追踪、根因分类、最小规则 diff、确认、发布与验收的固定闭环。 +- \`references/hose-enterprise-init.md\`: Hose 企业自动化初始化、多域名并发探测、OpenAPI 角色与人员发现、安全选人。 - \`references/hose-enterprise-auth.md\`: Hose 企业配置、认证诊断、授权链接。 - \`references/approval-attachment-trace.md\`: 附件/发票/OCR/图片争议的 Langfuse 追踪工作流。 - \`references/cli.md\`: 完整 CLI 命令清单。 @@ -34807,7 +35088,9 @@ seal-home tools list seal-home corps list [--corp ] seal-home corps current [--corp ] seal-home corps switch -seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}' +seal-home corps probe-hose --json '{"appKey":"...","appSecurity":"..."}' +seal-home corps hose-staffs --json '{"appKey":"...","appSecurity":"...","role":"admin"}' +seal-home corps add-hose --json '{"appKey":"...","appSecurity":"...","staffId":"corpId:staffId"}' seal-home corps add-seal --json '{"sealUrl":"https://tenant.sealai.cc","token":"seal-bearer-token"}' seal-home auth diagnose [--corp ] seal-home auth hose-link [--corp ] [--expire 7200] @@ -35532,10 +35815,15 @@ Use this reference for Hose/合思 enterprise configuration and user-facing Hose ## Add or switch an enterprise -Use the CLI for normal enterprise setup. Do not inspect source code or hand-edit \`~/.config/seal-home/enterprises/*.json\` unless the CLI fails or the user explicitly asks for low-level config debugging. +Use the CLI for normal enterprise setup. Do not inspect source code or hand-edit \`~/.config/seal-home/enterprises/*.json\` unless the CLI fails or the user explicitly asks for low-level config debugging. For full automated multi-domain probing and role/staff discovery, read \`references/hose-enterprise-init.md\`. \`\`\`bash -seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}' +# 1. Probing & discovery (auto-detects domain and roles) +seal-home corps probe-hose --json '{"appKey":"...","appSecurity":"..."}' +seal-home corps hose-staffs --json '{"appKey":"...","appSecurity":"...","role":"admin"}' + +# 2. Add enterprise (supports domain auto-probing and staffName/staffPhone matching) +seal-home corps add-hose --json '{"appKey":"...","appSecurity":"...","staffId":"corpId:staffId"}' seal-home corps list seal-home corps current --corp seal-home corps switch diff --git a/dist/openapi.json b/dist/openapi.json index 3e06e22..d688b4b 100644 --- a/dist/openapi.json +++ b/dist/openapi.json @@ -2,7 +2,7 @@ "openapi": "3.1.0", "info": { "title": "seal-home Wrapped API", - "version": "0.9.2", + "version": "0.9.3", "description": "Planned HTTP contract for the seal-home wrapped backend API.\n\nThese endpoints describe the intended stable API for frontend developers and agents once\nthe HTTP adapter is implemented.\nThey are not the raw downstream Seal endpoints. seal-home is responsible for enterprise\nselection, source authentication, response compaction, and diagnostics-friendly fields.\n" }, "servers": [ diff --git a/openapi/openapi.yaml b/openapi/openapi.yaml index 23f56f0..f20a509 100644 --- a/openapi/openapi.yaml +++ b/openapi/openapi.yaml @@ -1,7 +1,7 @@ openapi: 3.1.0 info: title: seal-home Wrapped API - version: 0.9.2 + version: 0.9.3 description: | Planned HTTP contract for the seal-home wrapped backend API. diff --git a/package.json b/package.json index 4f1a36f..b0d4194 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "seal-home", - "version": "0.9.2", + "version": "0.9.3", "type": "module", "module": "src/server.ts", "bin": { diff --git a/skills/seal-home/SKILL.md b/skills/seal-home/SKILL.md index b19d482..a86a313 100644 --- a/skills/seal-home/SKILL.md +++ b/skills/seal-home/SKILL.md @@ -1,12 +1,12 @@ --- name: seal-home -description: "v0.9.2: Use when working with Seal Home tenant operations: packaged customer feedback from WeChat or screenshots, target-enterprise discovery, approval-run and Langfuse diagnosis, simulation test batch creation and publishing, minimal approval-rule remediation and publishing, delegation links, Hose/合思 authorization, LLM config, permissions, billing, users, rules, documents, and search." +description: "v0.9.3: Use when working with Seal Home tenant operations: packaged customer feedback from WeChat or screenshots, target-enterprise discovery, approval-run and Langfuse diagnosis, simulation test batch creation and publishing, minimal approval-rule remediation and publishing, delegation links, Hose/合思 authorization, LLM config, permissions, billing, users, rules, documents, and search." metadata: - version: 0.9.2 - short-description: Seal tenant and Hose approval automation (v0.9.2) + version: 0.9.3 + short-description: Seal tenant and Hose approval automation (v0.9.3) --- -# Seal Home (v0.9.2) +# Seal Home (v0.9.3) Use the `seal_cli` MCP tool when it is available; pass the command string as its `command` argument. If MCP is unavailable, fall back to the global `seal-home` CLI. This skill is a routing layer for agents: keep this file short, choose the right command, and read a focused reference only when the task needs detail. @@ -93,6 +93,7 @@ seal-home tool seal_approval_search --corp --json '{"keywords":["差旅 - `references/approval-run-lightweight.md`: 单号定位、字段裁剪、摘要、引用规则、单据摘要、附件摘要。 - `references/rule-lightweight.md`: 规则 count/list summary、按版本/编号取单条规则、规则搜索裁剪。 - `references/customer-feedback-rule-remediation.md`: 微信/截图反馈包到企业定位、审批追踪、根因分类、最小规则 diff、确认、发布与验收的固定闭环。 +- `references/hose-enterprise-init.md`: Hose 企业自动化初始化、多域名并发探测、OpenAPI 角色与人员发现、安全选人。 - `references/hose-enterprise-auth.md`: Hose 企业配置、认证诊断、授权链接。 - `references/approval-attachment-trace.md`: 附件/发票/OCR/图片争议的 Langfuse 追踪工作流。 - `references/cli.md`: 完整 CLI 命令清单。 diff --git a/skills/seal-home/references/cli.md b/skills/seal-home/references/cli.md index 739ec66..907bbfa 100644 --- a/skills/seal-home/references/cli.md +++ b/skills/seal-home/references/cli.md @@ -39,7 +39,9 @@ seal-home tools list seal-home corps list [--corp ] seal-home corps current [--corp ] seal-home corps switch -seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}' +seal-home corps probe-hose --json '{"appKey":"...","appSecurity":"..."}' +seal-home corps hose-staffs --json '{"appKey":"...","appSecurity":"...","role":"admin"}' +seal-home corps add-hose --json '{"appKey":"...","appSecurity":"...","staffId":"corpId:staffId"}' seal-home corps add-seal --json '{"sealUrl":"https://tenant.sealai.cc","token":"seal-bearer-token"}' seal-home auth diagnose [--corp ] seal-home auth hose-link [--corp ] [--expire 7200] diff --git a/skills/seal-home/references/hose-enterprise-auth.md b/skills/seal-home/references/hose-enterprise-auth.md index 95e8498..9ed7aab 100644 --- a/skills/seal-home/references/hose-enterprise-auth.md +++ b/skills/seal-home/references/hose-enterprise-auth.md @@ -4,10 +4,15 @@ Use this reference for Hose/合思 enterprise configuration and user-facing Hose ## Add or switch an enterprise -Use the CLI for normal enterprise setup. Do not inspect source code or hand-edit `~/.config/seal-home/enterprises/*.json` unless the CLI fails or the user explicitly asks for low-level config debugging. +Use the CLI for normal enterprise setup. Do not inspect source code or hand-edit `~/.config/seal-home/enterprises/*.json` unless the CLI fails or the user explicitly asks for low-level config debugging. For full automated multi-domain probing and role/staff discovery, read `references/hose-enterprise-init.md`. ```bash -seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}' +# 1. Probing & discovery (auto-detects domain and roles) +seal-home corps probe-hose --json '{"appKey":"...","appSecurity":"..."}' +seal-home corps hose-staffs --json '{"appKey":"...","appSecurity":"...","role":"admin"}' + +# 2. Add enterprise (supports domain auto-probing and staffName/staffPhone matching) +seal-home corps add-hose --json '{"appKey":"...","appSecurity":"...","staffId":"corpId:staffId"}' seal-home corps list seal-home corps current --corp seal-home corps switch diff --git a/skills/seal-home/references/hose-enterprise-init.md b/skills/seal-home/references/hose-enterprise-init.md new file mode 100644 index 0000000..ba5e497 --- /dev/null +++ b/skills/seal-home/references/hose-enterprise-init.md @@ -0,0 +1,106 @@ +# Hose Enterprise Initialization & Automated Discovery + +Use this reference for automated Hose/合思 enterprise onboarding, multi-domain probing (including dedicated private cloud domains like 美年大健康), OpenAPI role and staff discovery, and non-TUI safe administrator selection. + +--- + +## 1. Domain Tiering & Probing Strategy + +合思在不同公有云和专有云平台部署了不同的服务端域名。系统采用 **三级域名决策模型**: + +```mermaid +flowchart TD + A["输入参数: appKey, appSecurity, [domain]"] --> B{"是否显式提供了 domain?
(如美年大健康等专有云/独立部署域名)"} + B -->|是 (专属域名优先)| C["直接针对该 domain 验证"] + B -->|否 (未指定)| D["并发探测 6 大标准公共 SaaS 域名"] + D --> E{"是否有且仅有 1 个域名验证成功?"} + E -->|是| F["自动锁定该域名为目标 domain"] + E -->|否 (全部返回 403 / 失败)| G["❌ 友好降级提示:
'在标准合思 SaaS 环境中未检测到有效凭证。
若是专属域名或私有化部署环境(如美年大健康),请显式提供企业专属 domain。'"] +``` + +### 预置 6 大标准公共 SaaS 域名池(仅作缺省探测使用): +1. `https://app.ekuaibao.com` (合思独立版 / 标准版) +2. `https://dd2.hosecloud.com` (钉钉版) +3. `https://wx2.ekuaibao.com` (企业微信版) +4. `https://kdcloud2.ekuaibao.com` (云之家版) +5. `https://ddenterprise.ekuaibao.com` (钉钉企业自建应用) +6. `https://feishu.ekuaibao.com` (飞书版) + +--- + +## 2. 核心 OpenAPI 接口契约 + +| 阶段 | 接口用途 | Method & URL 规范 | 关键参数 | 注意事项 | +| :---: | :--- | :--- | :--- | :--- | +| **1** | 获取开放凭证 | `POST {domain}/api/openapi/v1/auth/getAccessToken` | `appKey`, `appSecurity` | 确定有效 `domain`、`corpId` 与 `accessToken` | +| **2** | 查询角色组与角色 | `GET {domain}/api/openapi/v1/roleDefGroups?accessToken=...` | `accessToken` | 获取企业全部角色分组及 RoleDefId | +| **3** | 查询角色成员 ID 列表 | `GET {domain}/api/openapi/v1/roledefs/${roledefId}?accessToken=...&staffBy=id` | `accessToken`, `roledefId` | **URL 中必须带有字面量 `$` 字符**(如 `/roledefs/$ID01...:admin`) | +| **4** | 批量查询人员详情 | `POST {domain}/api/openapi/v1/staffs/getStaffIds?accessToken=...` | `{"type": "STAFFID", "conditionIds": [...]}` | 批量单次上限 100,返回姓名、手机号、是否激活(`authState`)、第三方 ID | +| **5** | 生成临时免密凭据 | `POST {domain}/api/openapi/v1.1/provisional/getProvisionalAuth?accessToken=...` | `{"uid": "{corpId}:{staffId}", "pageType": "home", "expireDate": 7200}` | 用于 Seal SSO 换取 Session 会话 | + +--- + +## 3. CLI 探测与人员发现命令 + +### 1) 企业探测与角色发现 (`corps probe-hose`) +```bash +seal-home corps probe-hose --json '{ + "appKey": "...", + "appSecurity": "...", + "domain": "https://custom.ekuaibao.com" # 可选,未传时自动探测 6 域名 +}' +``` +* **输出**:自动探测匹配的 `domain`、企业 ID `corpId`、企业名称 `name`、角色总数以及完整的角色分组列表。 + +### 2) 按角色查询候选员工 (`corps hose-staffs`) +```bash +# 默认查询主管理员角色 (admin) +seal-home corps hose-staffs --json '{ + "appKey": "...", + "appSecurity": "...", + "role": "admin" +}' + +# 查询指定业务角色 (如 "财务主管"、"采购申请权限" 或具体 roleDefId) +seal-home corps hose-staffs --json '{ + "appKey": "...", + "appSecurity": "...", + "role": "财务主管" +}' +``` +* **输出**:返回匹配角色下所有人员的详情列表,包含 `id` (`corpId:staffId`)、`name`、`cellphone`、`active`(是否在职)、`authState`(是否激活)。 + +--- + +## 4. 安全选人与防静默绑定规范 (Anti-Silent Guard) + +为了防止越权及未授权账号绑定,系统实施**严格的人员选定与安全确认机制**: + +1. **若用户在初始指令中已指名(姓名或手机号)**: + ```bash + seal-home corps add-hose --json '{ + "appKey": "...", + "appSecurity": "...", + "staffName": "于光泽" + }' + ``` + * 系统通过角色人员列表匹配:若**唯一匹配且 `active == true`**,直接绑定该 `staffId` 完成接入。 +2. **若用户未指定且存在多位候选管理员**: + ```bash + seal-home corps add-hose --json '{ + "appKey": "...", + "appSecurity": "..." + }' + ``` + * 系统**严禁静默默认挑选第一个管理员**; + * 命令会以错误形式退出,并列出所有候选管理员详情(姓名、手机号、ID、激活状态); + * Agent 应将候选人列表以结构化形式呈现给用户确认,待用户选定后,传入 `staffId` 或 `staffName` 再次执行。 +3. **若已知目标人员 ID**: + ```bash + seal-home corps add-hose --json '{ + "appKey": "...", + "appSecurity": "...", + "staffId": "ID01OZVhtzekb5:ID01K9vHULqNj1" + }' + ``` + * 直接使用指定 ID 完成接入并进行连通性验证。 diff --git a/src/cli/commands/corps.ts b/src/cli/commands/corps.ts index f57dfa7..e79476e 100644 --- a/src/cli/commands/corps.ts +++ b/src/cli/commands/corps.ts @@ -1,5 +1,11 @@ import { existsSync, mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; +import { + fetchHoseRoleDefGroups, + fetchHoseRoleStaffs, + fetchHoseStaffDetails, + probeHoseDomain +} from "../../core/auth/hose.js"; import { clearCorpTokenCache } from "../../core/auth/token-store.js"; import { loadCorpConfigs, @@ -77,6 +83,16 @@ export async function handleCorpsCommand(action: string | undefined, maybeName: return; } + if (action === "probe-hose") { + await probeHoseCorp(jsonObject(args.json)); + return; + } + + if (action === "hose-staffs") { + await queryHoseStaffs(jsonObject(args.json)); + return; + } + if (action === "add-hose") { await addHoseCorp(jsonObject(args.json)); return; @@ -90,27 +106,203 @@ export async function handleCorpsCommand(action: string | undefined, maybeName: throw new Error(`Unknown corps command: ${action ?? ""}. Run 'seal-home help' for available commands.`); } +async function probeHoseCorp(input: Record) { + const appKey = requiredString(input, "appKey"); + const appSecurity = requiredString(input, "appSecurity"); + const explicitDomain = optionalString(input, "domain"); + + const probe = await probeHoseDomain(appKey, appSecurity, explicitDomain); + const roleGroups = await fetchHoseRoleDefGroups(probe.domain, probe.openapiToken).catch(() => []); + + const totalRoles = roleGroups.reduce((acc, g) => acc + g.roleDefs.length, 0); + + printJson({ + domain: probe.domain, + corpId: probe.corpId, + name: probe.corpName ?? probe.corpId, + roleCount: totalRoles, + roleGroups: roleGroups.map((g) => ({ + id: g.id, + name: g.name, + roleDefs: g.roleDefs.map((r) => ({ + id: r.id, + name: r.name, + sourceType: r.sourceType + })) + })) + }); +} + +async function queryHoseStaffs(input: Record) { + const appKey = requiredString(input, "appKey"); + const appSecurity = requiredString(input, "appSecurity"); + const explicitDomain = optionalString(input, "domain"); + const roleQuery = optionalString(input, "role") ?? optionalString(input, "roleDefId") ?? "admin"; + + const probe = await probeHoseDomain(appKey, appSecurity, explicitDomain); + const roleGroups = await fetchHoseRoleDefGroups(probe.domain, probe.openapiToken); + + let targetRoleDefId: string | undefined; + let targetRoleName: string | undefined; + + // 1. Direct match by id + for (const g of roleGroups) { + for (const r of g.roleDefs) { + if (r.id === roleQuery || r.id === `${probe.corpId}:${roleQuery}`) { + targetRoleDefId = r.id; + targetRoleName = r.name; + break; + } + } + if (targetRoleDefId) break; + } + + // 2. Admin match default + if (!targetRoleDefId && (roleQuery === "admin" || roleQuery === "主管理员")) { + for (const g of roleGroups) { + for (const r of g.roleDefs) { + if (r.id.endsWith(":admin") || r.name === "主管理员") { + targetRoleDefId = r.id; + targetRoleName = r.name; + break; + } + } + if (targetRoleDefId) break; + } + } + + // 3. Match by role name substring + if (!targetRoleDefId) { + for (const g of roleGroups) { + for (const r of g.roleDefs) { + if (r.name.toLowerCase().includes(roleQuery.toLowerCase())) { + targetRoleDefId = r.id; + targetRoleName = r.name; + break; + } + } + if (targetRoleDefId) break; + } + } + + if (!targetRoleDefId) { + throw new Error( + `Role not found matching query: '${roleQuery}'. Run 'seal-home corps probe-hose' to view all available roles.` + ); + } + + const roleStaffs = await fetchHoseRoleStaffs(probe.domain, probe.openapiToken, targetRoleDefId); + const staffDetails = await fetchHoseStaffDetails(probe.domain, probe.openapiToken, roleStaffs.staffs); + + printJson({ + domain: probe.domain, + corpId: probe.corpId, + corpName: probe.corpName ?? probe.corpId, + roleId: targetRoleDefId, + roleName: targetRoleName, + count: staffDetails.length, + staffs: staffDetails.map((s) => ({ + id: s.id, + name: s.name, + cellphone: s.cellphone, + active: s.active, + authState: s.authState, + userId: s.userId, + email: s.email + })) + }); +} + async function addHoseCorp(input: Record) { const nameInput = optionalString(input, "name"); const appKey = requiredString(input, "appKey"); const appSecurity = requiredString(input, "appSecurity"); - const staffId = requiredStringAlias(input, ["staffId", "proxyStaffBizId"]); - const corpIdInput = - optionalString(input, "corpId") ?? - optionalString(input, "corporationId"); - const domain = optionalString(input, "domain") ?? "https://app.ekuaibao.com"; - 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 explicitDomain = optionalString(input, "domain"); + const explicitStaffId = optionalString(input, "staffId") ?? optionalString(input, "proxyStaffBizId"); + const staffName = optionalString(input, "staffName"); + const staffPhone = optionalString(input, "staffPhone"); + const roleQuery = optionalString(input, "role") ?? "admin"; + const force = input.force === true; + const verify = force || input.verify === false ? false : true; + + let domain = explicitDomain; + let corpId = optionalString(input, "corpId") ?? optionalString(input, "corporationId"); + let corpName = nameInput; + let openapiToken: string | undefined; + + if (!domain || !corpId || !explicitStaffId) { + const probe = await probeHoseDomain(appKey, appSecurity, explicitDomain); + domain = probe.domain; + corpId = corpId ?? probe.corpId; + corpName = corpName ?? probe.corpName; + openapiToken = probe.openapiToken; } + + let finalStaffId = explicitStaffId; + + if (!finalStaffId && openapiToken && domain) { + const roleGroups = await fetchHoseRoleDefGroups(domain, openapiToken).catch(() => []); + let targetRoleId: string | undefined; + for (const g of roleGroups) { + for (const r of g.roleDefs) { + if (r.id.endsWith(`:${roleQuery}`) || r.name === roleQuery || r.id === roleQuery) { + targetRoleId = r.id; + break; + } + } + if (targetRoleId) break; + } + if (!targetRoleId) { + targetRoleId = roleGroups + .find((g) => g.roleDefs.some((r) => r.id.endsWith(":admin"))) + ?.roleDefs.find((r) => r.id.endsWith(":admin"))?.id; + } + + if (targetRoleId) { + const roleStaffs = await fetchHoseRoleStaffs(domain, openapiToken, targetRoleId).catch(() => ({ staffs: [] })); + const staffDetails = await fetchHoseStaffDetails(domain, openapiToken, roleStaffs.staffs).catch(() => []); + + if (staffName || staffPhone) { + const matches = staffDetails.filter((s) => { + if (staffName && s.name !== staffName && !s.name.includes(staffName)) return false; + if (staffPhone && (!s.cellphone || !s.cellphone.includes(staffPhone))) return false; + return true; + }); + if (matches.length === 1 && matches[0]) { + finalStaffId = matches[0].id; + } else if (matches.length > 1) { + throw new Error( + `Multiple staff members matched '${staffName ?? staffPhone}': ${matches.map((m) => `${m.name}(${m.id})`).join(", ")}. Please specify exact staffId.` + ); + } else { + throw new Error( + `No staff member found matching '${staffName ?? staffPhone}' under role ${targetRoleId}. Run 'seal-home corps hose-staffs' to view candidates.` + ); + } + } else if (!force) { + const candidates = staffDetails + .map((s) => `${s.name} (${s.cellphone || "no-phone"}, id: ${s.id}, active: ${s.active})`) + .join("\n - "); + throw new Error( + `Missing required parameter: staffId. Found ${staffDetails.length} candidate administrators:\n - ${candidates}\n` + + `Please specify 'staffId', 'staffName', or 'staffPhone' to explicitly select an account (or pass force:true to bypass).` + ); + } + } + } + + if (!finalStaffId) { + if (!verify && explicitStaffId) { + finalStaffId = explicitStaffId; + } else { + throw new Error( + "Missing required parameter: staffId (or proxyStaffBizId). Run 'seal-home corps hose-staffs' to discover available administrators." + ); + } + } + const id = optionalString(input, "id") ?? corpId; - const name = nameInput ?? remote?.name ?? corpId; + const name = corpName ?? corpId; const sealUrl = optionalString(input, "sealUrl") ?? `https://${corpId.toLowerCase()}.sealai.cc`; const config: CorpConfig = { @@ -124,11 +316,11 @@ async function addHoseCorp(input: Record) { }, source: { type: "hose", - domain, + domain: domain!, appKey, appSecurity, - corpId, - staffId + corpId: corpId!, + staffId: finalStaffId }, auth: { refreshTtl: 300 @@ -152,6 +344,8 @@ async function addHoseCorp(input: Record) { id, name, corpId, + domain, + staffId: finalStaffId, verified: verify, path: file }); diff --git a/src/core/auth/hose.test.ts b/src/core/auth/hose.test.ts index 2345728..730ae31 100644 --- a/src/core/auth/hose.test.ts +++ b/src/core/auth/hose.test.ts @@ -3,7 +3,13 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { CorpConfig, HoseSealSource } from "../config/types.js"; -import { defaultSealUrl, getHoseEnterpriseUrl, normalizeBaseUrl } from "./hose.js"; +import { + HOSE_STANDARD_DOMAINS, + defaultSealUrl, + fetchHoseStaffDetails, + getHoseEnterpriseUrl, + normalizeBaseUrl +} from "./hose.js"; const ORIGINAL_ENV = process.env.SEAL_HOME_TOKEN_STORE; const tempDirs: string[] = []; @@ -95,4 +101,20 @@ describe("hose auth helpers", () => { const url = await getHoseEnterpriseUrl(corp); expect(url).toBe("https://app.ekuaibao.com/web/home.html?accessToken=close-token"); }); + + test("HOSE_STANDARD_DOMAINS contains 6 expected public platform domains", () => { + expect(HOSE_STANDARD_DOMAINS.length).toBe(6); + expect(HOSE_STANDARD_DOMAINS).toContain("https://app.ekuaibao.com"); + expect(HOSE_STANDARD_DOMAINS).toContain("https://dd2.hosecloud.com"); + expect(HOSE_STANDARD_DOMAINS).toContain("https://wx2.ekuaibao.com"); + expect(HOSE_STANDARD_DOMAINS).toContain("https://kdcloud2.ekuaibao.com"); + expect(HOSE_STANDARD_DOMAINS).toContain("https://ddenterprise.ekuaibao.com"); + expect(HOSE_STANDARD_DOMAINS).toContain("https://feishu.ekuaibao.com"); + }); + + test("fetchHoseStaffDetails returns empty array for empty staffIds", async () => { + const details = await fetchHoseStaffDetails("https://app.ekuaibao.com", "fake-token", []); + expect(details).toEqual([]); + }); }); + diff --git a/src/core/auth/hose.ts b/src/core/auth/hose.ts index ef04c0c..750f563 100644 --- a/src/core/auth/hose.ts +++ b/src/core/auth/hose.ts @@ -40,6 +40,60 @@ type SealTokenResponse = { }; }; +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; + +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>(); @@ -293,3 +347,233 @@ export async function getHoseSealSession(corp: CorpConfig): Promise 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 ?? []; +}