From fcbc87e997ca927af49300e114d9b3f9079c300b Mon Sep 17 00:00:00 2001 From: yunyingk Date: Tue, 15 Sep 2026 11:14:16 +0800 Subject: [PATCH] Add Hose OpenAPI key extraction from assist links --- skills/seal-use/SKILL.md | 4 +- skills/seal-use/references/cli.md | 11 +- .../references/enterprise-onboarding.md | 37 +- src/cli/commands/auth.ts | 35 +- src/cli/commands/corps.test.ts | 354 +++++++++++++++++- src/cli/commands/corps.ts | 259 ++++++++++++- src/cli/help.ts | 63 +++- src/cli/runner.ts | 7 +- src/core/auth/hose.test.ts | 72 +++- src/core/auth/hose.ts | 191 +++++++++- 10 files changed, 1011 insertions(+), 22 deletions(-) diff --git a/skills/seal-use/SKILL.md b/skills/seal-use/SKILL.md index c26e16b..4993b20 100644 --- a/skills/seal-use/SKILL.md +++ b/skills/seal-use/SKILL.md @@ -43,8 +43,8 @@ seal-use corps list - Treat CLI/MCP as the Agent's execution channel, not the user's interface. Translate natural-language intent into commands yourself; never ask the user to compose CLI syntax, JSON payloads, placeholder values, or internal IDs. - Before asking for enterprise parameters, resolve the target enterprise: when an enterprise is named, hinted, or keyword-identifiable, ALWAYS run `seal-use corps search ` (or `seal-use corps get ` if an exact ID is known) — DO NOT dump the entire enterprise catalog with `seal-use corps list` when the target is already known. Only run `seal-use corps list` (or `corps list --env `) for initial discovery when zero enterprise context is known. Resolve its human name to the returned `id` and pass that value as `--corp`; do not ask the user to know `corpId`. Use `seal-use corps get ` to inspect rich enterprise attributes (URLs, tenant slugs, staff IDs, environment relations, and config file locations) with sensitive secrets safely redacted. - If no enterprise is configured, the user is installing for the first time, or the user provides credentials, an assistance link, or a browser-copied cURL, read `references/enterprise-onboarding.md` before asking questions or running setup commands. -- When the user provides a Hose/合思 `thirdparty.html` assistance link, use `seal-use corps add-link [--name ...]`; the command verifies the tenant and records the temporary Seal session without echoing the link token. -- Keep enterprise identity origin separate from credential acquisition. A Hose/合思-sourced Seal tenant can be accessed with standard Hose app credentials, an assistance link, or a captured web session; receiving a Seal Bearer token does not by itself prove the tenant is Seal-native. +- When the user provides a Hose/合思 `thirdparty.html` assistance link, use `seal-use corps add-link [--name ...]` for temporary session access, or elevate privileges to permanent developer credentials using `seal-use corps extract-keys --save` (or `seal-use corps add-link --as-hose`). This Hose-exclusive capability extracts `appKey`/`appSecurity`. If the enterprise has multiple keys, specify `--app-key ` or `--key-id `. +- Keep enterprise identity origin separate from credential acquisition. A Hose/合思-sourced Seal tenant can be accessed with standard Hose app credentials, an assistance link, or a captured web session; receiving a Seal Bearer token does not by itself prove the tenant is Seal-native. Calling key extraction or `keys` on native Seal enterprises is strictly blocked. - Never ask a normal user for `corpId`, `staffId`, `proxyStaffBizId`, `tenantId`, or another discoverable internal ID. Discover it first. If discovery fails, explain what the field means, why it could not be discovered, and exactly where the user can find it. - Prefer compact commands first: `pick`, `--summary`, `--fields`, `attachments --summary`, `rules count`, and `rules list --summary`. - Parse JSON stdout. Do not scrape human text. diff --git a/skills/seal-use/references/cli.md b/skills/seal-use/references/cli.md index 23a754b..c95b569 100644 --- a/skills/seal-use/references/cli.md +++ b/skills/seal-use/references/cli.md @@ -88,7 +88,11 @@ seal-use corps replay-test [] [--record-id ] [--sn ] [--limi seal-use corps regression [--corp ] [--samples ] [--dry-run] [--fail-on-flips] seal-use corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}' seal-use corps add-seal --json '{"sealUrl":"https://tenant.sealai.cc","token":"seal-bearer-token"}' -seal-use corps add-link [--name ] [--overwrite] +seal-use corps add-link [--name ] [--as-hose] [--app-key ] [--key-id ] [--overwrite] +seal-use corps extract-keys [--reveal] [--save] [--name ] [--app-key ] [--key-id ] [--overwrite] +seal-use corps keys [ | ] [--reveal] [--save] [--app-key ] [--key-id ] +seal-use auth extract-keys [--reveal] [--save] [--name ] [--app-key ] [--key-id ] [--overwrite] +seal-use auth keys [--corp ] [--reveal] seal-use auth diagnose [--corp ] seal-use auth hose-link [--corp ] [--expire 7200] seal-use delegation list [--corp ] @@ -206,7 +210,10 @@ Enterprise and tenant management: - `seal-use corps get ` (rich enterprise attributes with sensitive secrets safely redacted) - `seal-use corps current [--corp ]` - `seal-use corps switch ` -- `seal-use auth diagnose --corp ` +- `seal-use corps extract-keys [--reveal] [--save] [--name ] [--app-key ] [--key-id ] [--overwrite]` extracts OpenAPI keys (`appKey` and `appSecurity`) from a Hose assistance link (`thirdparty.html`). **Hose Subdomain Privilege Elevation**: elevates a short-lived session token to permanent Hose OpenAPI developer credentials. If `--save` is specified, registers the enterprise as a durable Hose tenant. If the enterprise has multiple keys, execution halts and candidates are listed unless `--app-key` or `--key-id` is passed. +- `seal-use corps add-link [--name ] [--as-hose] [--app-key ] [--key-id ] [--overwrite]` imports a Hose assistance link. Without `--as-hose`, creates a temporary Seal Bearer session. With `--as-hose`, elevates permissions by extracting Hose OpenAPI developer keys and saving a durable Hose enterprise configuration. +- `seal-use corps keys [ | ] [--reveal] [--save]` reads/displays OpenAPI keys for a Hose assistance link or configured Hose enterprise (masked by default, `--reveal` displays plaintext). Rejects non-Hose/native-Seal tenants with exit code 2. +- `seal-use auth extract-keys ` and `seal-use auth keys [--corp ]` provide auth-domain aliases for key extraction and inspection. Read-only discovery: diff --git a/skills/seal-use/references/enterprise-onboarding.md b/skills/seal-use/references/enterprise-onboarding.md index 1641531..e633d67 100644 --- a/skills/seal-use/references/enterprise-onboarding.md +++ b/skills/seal-use/references/enterprise-onboarding.md @@ -73,21 +73,42 @@ seal-use auth diagnose --corp Do not ask for `domain`, `corpId`, or `proxyStaffBizId` up front. For a dedicated/private Hose deployment, add `domain` only after standard probing reports that it cannot find the enterprise. -## Route 2: Incoming Assistance Link +## Route 2: Incoming Assistance Link & Hose Subdomain Privilege Elevation -First distinguish the link by its host and purpose: +First distinguish the link by its host, purpose, and identity origin: -- A Hose authorization/provisional link opens a Hose session and may continue through Seal SSO. It is not a Seal delegation link. -- A Seal assistance/delegation link grants temporary delegated access on a Seal tenant. It is not a Hose OpenAPI credential. -- `seal-use auth hose-link` and `seal-use delegation create` generate links for an enterprise that is already configured. `seal-use corps add-link ` imports a received Hose/合思 `thirdparty.html` assistance link and verifies the resulting Seal tenant. +- A **Hose/合思 authorization/assistance link** (`https:///web/thirdparty.html?...`) opens an upstream Hose session and may continue through Seal SSO. It is not a Seal delegation link. +- A **Seal-native assistance/delegation link** grants temporary delegated access on a Seal tenant. It is not a Hose credential and cannot be elevated to Hose OpenAPI credentials. +- **Hose Subdomain Boundary (合思子域专属提权)**: `seal-use` primarily manages Seal tenants. Tenants sourced from the Hose ecosystem have an upstream Hose enterprise backing them. A received Hose assistance link contains only a temporary session `accessToken`. If you run standard `corps add-link`, it exchanges that temporary token for a short-lived Seal Bearer token—sufficient for basic Seal inspection, but it will expire and cannot call any Hose OpenAPI. +- **Privilege Elevation (权限等级提升)**: To elevate from a short-lived session token to permanent, durable Hose OpenAPI developer credentials, use `corps extract-keys --save` or `corps add-link --as-hose`. This leverages Hose's internal key interface (`GET /api/innerapi/v1/key`) using the session token to retrieve the enterprise's OpenAPI `appKey` and `appSecurity`. Once saved, the enterprise is upgraded to a standard Hose configuration with full OpenAPI support (e.g. `corps sync-hosecloud`). +- **Multi-Key Disambiguation (多套密钥明确抉择)**: If the enterprise owns multiple application keys, the CLI **will not** guess or silently pick the first key. Instead, it terminates with an informative candidate list and requires the user to specify `--app-key ` or `--key-id `. If only one key exists, it is selected automatically. +- **Non-Hose Tenants Blocked**: Calling `keys` on native Seal enterprises (`corp.source.type !== "hose"`) is strictly rejected with exit code 2, explaining that this capability belongs exclusively to the Hose ecosystem. -Use the direct import route when the incoming link is an HTTPS `thirdparty.html` URL from a supported `ekuaibao.com` or `hosecloud.com` domain: +### Command Usage ```bash -seal-use corps add-link "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=&ekbCorpId=&pageType=home" [--name "企业名称"] +# 1. 提取密钥并脱敏查看(合思子域能力): +seal-use corps extract-keys "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=...&ekbCorpId=..." + +# 2. 显式完整查看密钥明文(--reveal / -r): +seal-use corps extract-keys "" --reveal + +# 3. 提权保存为标准持久化合思企业配置: +seal-use corps extract-keys "" --save [--name "企业名称"] [--overwrite] +# 或简写为: +seal-use corps add-link "" --as-hose [--name "企业名称"] + +# 4. 多套密钥存在时,显式指定具体应用密钥: +seal-use corps extract-keys "" --save --app-key "ekb_app_..." +# 或按 key ID 选取: +seal-use corps extract-keys "" --save --key-id "key_id_..." + +# 5. 查看已配置合思企业当前使用的应用密钥: +seal-use corps keys [--reveal] +seal-use auth keys --corp [--reveal] ``` -The command parses `accessToken` and `ekbCorpId`, exchanges the temporary Hose token at the target Seal tenant, verifies `/api/v1/auth/me`, and stores only the normalized short-lived Seal session. It never prints or persists the original URL. Use `--overwrite` only when intentionally replacing an existing enterprise config. To create a Seal delegation link without persisting the session, use `seal-use delegation create --from-link [--note ...]`. +When using standard `add-link` (without `--as-hose`), it exchanges the temporary Hose token at the target Seal tenant, verifies `/api/v1/auth/me`, and stores only the normalized short-lived Seal session. When `--as-hose` or `extract-keys --save` is used, the CLI executes Hose subdomain privilege elevation to register a durable standard Hose configuration. Assistance links are credentials. Do not follow a link merely to inspect it when the user's request was only explanatory, and never publish, log, or commit it. diff --git a/src/cli/commands/auth.ts b/src/cli/commands/auth.ts index 03e03ea..97db3aa 100644 --- a/src/cli/commands/auth.ts +++ b/src/cli/commands/auth.ts @@ -4,9 +4,33 @@ import type { CorpConfig } from "../../core/config/types.js"; import { createSealClient, createSealClientForUrl } from "../../core/http/factory.js"; import { resolveSealCustomHeaders } from "../../core/http/request-headers.js"; import { getMe } from "../../domains/seal/api.js"; -import { numberOption } from "../parser.js"; +import { booleanOption, numberOption, stringOption } from "../parser.js"; import { printJson, redactSensitiveText } from "../printer.js"; import type { ParsedArgs } from "../types.js"; +import { extractKeysFromLinkAction, showCorpKeysAction } from "./corps.js"; + +export async function handleAuthExtractKeysCommand(maybeName: string | undefined, args: ParsedArgs) { + const link = maybeName ?? stringOption(args.options.link) ?? stringOption(args.options.url); + if (!link) { + throw new Error( + "Usage: seal-use auth extract-keys [--reveal] [--save] [--name ] [--overwrite]" + ); + } + const reveal = + booleanOption(args.options.reveal) === true || + booleanOption(args.options.r) === true || + booleanOption(args.options.plain) === true; + const save = booleanOption(args.options.save) === true || booleanOption(args.options.add) === true; + await extractKeysFromLinkAction(link, { + reveal, + save, + name: stringOption(args.options.name), + overwrite: booleanOption(args.options.overwrite) === true, + force: booleanOption(args.options.force) === true, + appKey: stringOption(args.options["app-key"]) ?? stringOption(args.options.appKey), + keyId: stringOption(args.options["key-id"]) ?? stringOption(args.options.keyId) + }); +} export async function handleAuthCommand(action: string | undefined, corp: CorpConfig, args: ParsedArgs) { if (action === "diagnose") { @@ -20,6 +44,15 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo return; } + if (action === "keys") { + const reveal = + booleanOption(args.options.reveal) === true || + booleanOption(args.options.r) === true || + booleanOption(args.options.plain) === true; + await showCorpKeysAction(corp.id, { reveal }); + return; + } + throw new Error(`Unknown auth command: ${action ?? ""}. Run 'seal-use help' for available commands.`); } diff --git a/src/cli/commands/corps.test.ts b/src/cli/commands/corps.test.ts index 9a92d97..1da573a 100644 --- a/src/cli/commands/corps.test.ts +++ b/src/cli/commands/corps.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, test } from "bun:test"; -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { runCli } from "../runner.js"; @@ -490,3 +490,355 @@ describe("corps list sorting and limit", () => { expect(limitedItems.map((c: any) => c.id)).toEqual(["corp-05", "corp-02", "corp-11"]); }); }); + +describe("Hose OpenAPI key extraction from assistance link", () => { + function mockHoseKeysRequests(options: { + staffId?: string; + corpName?: string; + keys?: Array<{ + id: string; + name?: string; + appKey: string; + appSecurity: string; + active?: boolean; + corporationId?: string; + createTime?: number; + }>; + } = {}) { + const staffId = options.staffId ?? "acme-01:admin01"; + const corpName = options.corpName ?? "Acme Corporation"; + const keys = options.keys ?? [ + { + id: "key-1", + name: "生产系统接入", + appKey: "ak_acme_production_123", + appSecurity: "sec_secret_password_456789", + active: true, + corporationId: "acme-01", + createTime: 1700000000000 + } + ]; + + const jwtPayload = Buffer.from( + JSON.stringify({ + staffId, + corporationName: corpName, + staffName: "Alice Admin" + }) + ).toString("base64url"); + const fakeJwt = `header.${jwtPayload}.signature`; + + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const urlStr = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + const url = new URL(urlStr); + + if (url.pathname === "/api/engine/realm/$UNITY/actions/jwt") { + return jsonResponse({ value: fakeJwt }); + } + + if (url.pathname === "/api/innerapi/v1/key") { + return jsonResponse({ items: keys, count: keys.length }); + } + + if (url.pathname === "/api/openapi/v1/auth/getAccessToken") { + return jsonResponse({ + value: { + accessToken: "openapi-token-xyz", + corporation: { id: "acme-01", name: corpName }, + staff: { id: staffId, name: "Alice Admin" } + } + }); + } + + if (url.pathname === "/api/auth/oauth2/session/oem-hosecloud") { + return jsonResponse({ accessToken: "seal-bearer-token", expiresIn: 1800 }); + } + + if (url.pathname === "/api/v1/auth/me") { + return jsonResponse({ + data: { + user: { id: "u-1", providerUserId: staffId, name: "Alice Admin" }, + tenant: { id: "t-1", tenantSlug: "acme-01", name: corpName } + } + }); + } + + return jsonResponse({ error: `Unexpected request: ${url.pathname}` }, 404); + }) as typeof fetch; + } + + test("corps extract-keys masks appSecurity by default", async () => { + setupConfigEnv(); + mockHoseKeysRequests(); + + const link = hoseLink(); + const result = await runCli(["corps", "extract-keys", link]); + + expect(result.isError).toBe(false); + expect(result.exitCode).toBe(0); + const parsed = JSON.parse(result.stdout); + expect(parsed.corpId).toBe("acme-01"); + expect(parsed.keys.length).toBe(1); + expect(parsed.keys[0].appKey).toBe("ak_acme_production_123"); + expect(parsed.keys[0].appSecurity).toBe("sec_secr...6789"); + expect(result.stdout).not.toContain("sec_secret_password_456789"); + expect(result.stderr).toContain("附加 --reveal (或 -r) 可查看完整 appSecurity 明文"); + }); + + test("corps extract-keys --reveal outputs plain text appSecurity", async () => { + setupConfigEnv(); + mockHoseKeysRequests(); + + const link = hoseLink(); + const result = await runCli(["corps", "extract-keys", link, "--reveal"]); + + expect(result.isError).toBe(false); + expect(result.exitCode).toBe(0); + const parsed = JSON.parse(result.stdout); + expect(parsed.keys[0].appSecurity).toBe("sec_secret_password_456789"); + expect(result.stdout).toContain("sec_secret_password_456789"); + }); + + test("corps extract-keys --save saves durable Hose enterprise configuration", async () => { + const enterprises = setupConfigEnv(); + mockHoseKeysRequests(); + + const link = hoseLink(); + const result = await runCli(["corps", "extract-keys", link, "--save", "--name", "Acme Hose", "--force"]); + + expect(result.isError).toBe(false); + expect(result.exitCode).toBe(0); + + const savedFile = join(enterprises, "acme-01.json"); + expect(existsSync(savedFile)).toBe(true); + const config = JSON.parse(readFileSync(savedFile, "utf-8")); + expect(config.id).toBe("acme-01"); + expect(config.name).toBe("Acme Hose"); + expect(config.source.type).toBe("hose"); + expect(config.source.appKey).toBe("ak_acme_production_123"); + expect(config.source.appSecurity).toBe("sec_secret_password_456789"); + expect(config.source.domain).toBe("https://wx2.ekuaibao.com"); + expect(config.source.staffId).toBe("acme-01:admin01"); + }); + + test("corps add-link --as-hose automatically registers as Hose OpenAPI configuration", async () => { + const enterprises = setupConfigEnv(); + mockHoseKeysRequests(); + + const link = hoseLink(); + const result = await runCli(["corps", "add-link", link, "--as-hose", "--name", "Acme Auto Hose", "--force"]); + + expect(result.isError).toBe(false); + expect(result.exitCode).toBe(0); + + const savedFile = join(enterprises, "acme-01.json"); + expect(existsSync(savedFile)).toBe(true); + const config = JSON.parse(readFileSync(savedFile, "utf-8")); + expect(config.id).toBe("acme-01"); + expect(config.source.type).toBe("hose"); + expect(config.source.appKey).toBe("ak_acme_production_123"); + expect(config.source.appSecurity).toBe("sec_secret_password_456789"); + }); + + test("auth extract-keys alias works before any enterprise is configured", async () => { + setupConfigEnv(); + mockHoseKeysRequests(); + + const link = hoseLink(); + const result = await runCli(["auth", "extract-keys", link]); + + expect(result.isError).toBe(false); + expect(result.exitCode).toBe(0); + const parsed = JSON.parse(result.stdout); + expect(parsed.corpId).toBe("acme-01"); + expect(parsed.keys[0].appKey).toBe("ak_acme_production_123"); + }); + + test("auth keys displays configured Hose keys and supports --reveal", async () => { + const enterprises = setupConfigEnv(); + mkdirSync(enterprises, { recursive: true }); + writeFileSync( + join(enterprises, "demo-hose.json"), + JSON.stringify({ + id: "demo-hose", + name: "Demo Hose Corp", + environment: "production", + seal: { url: "https://demo.sealai.cc", endpoints: { approvalStylePreferences: "" } }, + source: { + type: "hose", + domain: "https://app.ekuaibao.com", + appKey: "my-app-key-111", + appSecurity: "my-super-secret-password-222", + corpId: "demo-hose", + staffId: "demo:admin" + }, + auth: { refreshTtl: 300 } + }) + ); + + // 1. Default masked + const resMasked = await runCli(["auth", "keys", "--corp", "demo-hose"]); + expect(resMasked.isError).toBe(false); + const parsedMasked = JSON.parse(resMasked.stdout); + expect(parsedMasked.appKey).toBe("my-app-key-111"); + expect(parsedMasked.appSecurity).toBe("my-super...-222"); + expect(resMasked.stdout).not.toContain("my-super-secret-password-222"); + + // 2. Revealed + const resRevealed = await runCli(["auth", "keys", "--corp", "demo-hose", "--reveal"]); + expect(resRevealed.isError).toBe(false); + const parsedRevealed = JSON.parse(resRevealed.stdout); + expect(parsedRevealed.appSecurity).toBe("my-super-secret-password-222"); + }); + + test("corps extract-keys --save errors when multiple keys exist and no selector given", async () => { + setupConfigEnv(); + mockHoseKeysRequests({ + keys: [ + { + id: "key-prod", + name: "生产系统", + appKey: "ak_prod_111", + appSecurity: "sec_prod_111", + active: true, + corporationId: "acme-01" + }, + { + id: "key-dev", + name: "测试系统", + appKey: "ak_dev_222", + appSecurity: "sec_dev_222", + active: true, + corporationId: "acme-01" + } + ] + }); + + const link = hoseLink(); + const result = await runCli(["corps", "extract-keys", link, "--save"]); + + expect(result.exitCode).toBe(2); + expect(result.stderr).toContain("存在多套 (2 套) OpenAPI 应用密钥凭据"); + expect(result.stderr).toContain("ak_prod_111"); + expect(result.stderr).toContain("ak_dev_222"); + expect(result.stderr).toContain("--app-key"); + }); + + test("corps extract-keys --save succeeds with multiple keys when --app-key specified", async () => { + const enterprises = setupConfigEnv(); + mockHoseKeysRequests({ + keys: [ + { + id: "key-prod", + name: "生产系统", + appKey: "ak_prod_111", + appSecurity: "sec_prod_111", + active: true, + corporationId: "acme-01" + }, + { + id: "key-dev", + name: "测试系统", + appKey: "ak_dev_222", + appSecurity: "sec_dev_222", + active: true, + corporationId: "acme-01" + } + ] + }); + + const link = hoseLink(); + const result = await runCli([ + "corps", + "extract-keys", + link, + "--save", + "--app-key", + "ak_dev_222", + "--force" + ]); + + expect(result.isError).toBe(false); + expect(result.exitCode).toBe(0); + + const savedFile = join(enterprises, "acme-01.json"); + expect(existsSync(savedFile)).toBe(true); + const config = JSON.parse(readFileSync(savedFile, "utf-8")); + expect(config.source.appKey).toBe("ak_dev_222"); + expect(config.source.appSecurity).toBe("sec_dev_222"); + }); + + test("corps extract-keys --save succeeds with multiple keys when --key-id specified", async () => { + const enterprises = setupConfigEnv(); + mockHoseKeysRequests({ + keys: [ + { + id: "key-prod", + name: "生产系统", + appKey: "ak_prod_111", + appSecurity: "sec_prod_111", + active: true, + corporationId: "acme-01" + }, + { + id: "key-dev", + name: "测试系统", + appKey: "ak_dev_222", + appSecurity: "sec_dev_222", + active: true, + corporationId: "acme-01" + } + ] + }); + + const link = hoseLink(); + const result = await runCli([ + "corps", + "extract-keys", + link, + "--save", + "--key-id", + "key-prod", + "--force" + ]); + + expect(result.isError).toBe(false); + expect(result.exitCode).toBe(0); + + const savedFile = join(enterprises, "acme-01.json"); + expect(existsSync(savedFile)).toBe(true); + const config = JSON.parse(readFileSync(savedFile, "utf-8")); + expect(config.source.appKey).toBe("ak_prod_111"); + expect(config.source.appSecurity).toBe("sec_prod_111"); + }); + + test("corps keys and auth keys reject native Seal enterprise with exit code 2", async () => { + const enterprises = setupConfigEnv(); + mkdirSync(enterprises, { recursive: true }); + writeFileSync( + join(enterprises, "native-seal.json"), + JSON.stringify({ + id: "native-seal", + name: "原生 Seal 企业", + environment: "production", + seal: { url: "https://seal.example.com" }, + source: { + type: "seal", + sealUrl: "https://seal.example.com", + token: "token-123" + } + }) + ); + + // 1. corps keys + const corpsResult = await runCli(["corps", "keys", "native-seal"]); + expect(corpsResult.exitCode).toBe(2); + expect(corpsResult.stderr).toContain("合思子域专享能力"); + expect(corpsResult.stderr).toContain("原生 Seal (seal) 租户"); + + // 2. auth keys + const authResult = await runCli(["auth", "keys", "--corp", "native-seal"]); + expect(authResult.exitCode).toBe(2); + expect(authResult.stderr).toContain("合思子域专享能力"); + }); +}); diff --git a/src/cli/commands/corps.ts b/src/cli/commands/corps.ts index 69a05fa..8e2d00e 100644 --- a/src/cli/commands/corps.ts +++ b/src/cli/commands/corps.ts @@ -5,10 +5,13 @@ import { assertHoseAssistTenantMatches, defaultSealUrl, exchangeHoseAssistLink, + fetchHoseOpenApiKeysFromLink, fetchHoseRoleDefGroups, fetchHoseRoleStaffs, fetchHoseStaffDetails, - probeHoseDomain + maskHoseSecurity, + probeHoseDomain, + type HoseOpenApiKey } from "../../core/auth/hose.js"; import { clearCorpTokenCache } from "../../core/auth/token-store.js"; import { createSealClient, createSealClientForUrl } from "../../core/http/factory.js"; @@ -35,7 +38,7 @@ import { import { executeApprovalRunsReplay, type ReplayRecordsQuery } from "../../domains/seal/webhook-replay.js"; import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/source.js"; import { selectCorp } from "../helpers.js"; -import { confirmationRequired, usageError } from "../errors.js"; +import { CliError, confirmationRequired, usageError } from "../errors.js"; import { inferCorpIdFromStaffId, booleanOption, @@ -964,13 +967,74 @@ export async function handleCorpsCommand(action: string | undefined, maybeName: const link = maybeName ?? stringOption(args.options.link) ?? stringOption(args.options.url); if (!link) { throw new Error( - "Usage: seal-use corps add-link [--name ] [--overwrite]" + "Usage: seal-use corps add-link [--name ] [--as-hose] [--overwrite]" ); } + const asHose = booleanOption(args.options["as-hose"]) === true || booleanOption(args.options.hose) === true; + if (asHose) { + await addLinkAsHoseCorp( + link, + stringOption(args.options.name), + booleanOption(args.options.overwrite) === true, + booleanOption(args.options.force) === true, + { + appKey: stringOption(args.options["app-key"]) ?? stringOption(args.options.appKey), + keyId: stringOption(args.options["key-id"]) ?? stringOption(args.options.keyId) + } + ); + return; + } await addLinkCorp(link, stringOption(args.options.name), booleanOption(args.options.overwrite) === true); return; } + if (action === "extract-keys" || action === "extract-key") { + const link = maybeName ?? stringOption(args.options.link) ?? stringOption(args.options.url); + if (!link) { + throw new Error( + "Usage: seal-use corps extract-keys [--reveal] [--save] [--app-key ] [--key-id ] [--name ] [--overwrite]" + ); + } + const reveal = + booleanOption(args.options.reveal) === true || + booleanOption(args.options.r) === true || + booleanOption(args.options.plain) === true; + const save = booleanOption(args.options.save) === true || booleanOption(args.options.add) === true; + await extractKeysFromLinkAction(link, { + reveal, + save, + name: stringOption(args.options.name), + overwrite: booleanOption(args.options.overwrite) === true, + force: booleanOption(args.options.force) === true, + appKey: stringOption(args.options["app-key"]) ?? stringOption(args.options.appKey), + keyId: stringOption(args.options["key-id"]) ?? stringOption(args.options.keyId) + }); + return; + } + + if (action === "keys") { + const target = maybeName ?? stringOption(args.options.link) ?? stringOption(args.options.url) ?? stringOption(args.options.corp); + const reveal = + booleanOption(args.options.reveal) === true || + booleanOption(args.options.r) === true || + booleanOption(args.options.plain) === true; + if (target && (target.startsWith("http://") || target.startsWith("https://"))) { + const save = booleanOption(args.options.save) === true || booleanOption(args.options.add) === true; + await extractKeysFromLinkAction(target, { + reveal, + save, + name: stringOption(args.options.name), + overwrite: booleanOption(args.options.overwrite) === true, + force: booleanOption(args.options.force) === true, + appKey: stringOption(args.options["app-key"]) ?? stringOption(args.options.appKey), + keyId: stringOption(args.options["key-id"]) ?? stringOption(args.options.keyId) + }); + return; + } + await showCorpKeysAction(target, { reveal }); + return; + } + throw new Error(`Unknown corps command: ${action ?? ""}. Run 'seal-use help' for available commands.`); } @@ -1385,6 +1449,195 @@ async function addLinkCorp(link: string, name: string | undefined, overwrite: bo ); } +function selectHoseOpenApiKey( + keys: HoseOpenApiKey[], + corpId: string, + selection: { appKey?: string; keyId?: string }, + contextCmd: string +): HoseOpenApiKey { + if (keys.length === 0) { + throw new Error( + `[合思子域提权] 未能从协助链接中提取到合思企业 [${corpId}] 的 OpenAPI 密钥凭据。\n` + + `💡 说明:此能力专属于合思 (Hose) 子域,用于将临时会话提权为标准 OpenAPI 开发者接入。需要企业管理员已在合思开放平台创建应用并生成 appKey/appSecurity。` + ); + } + + if (selection.keyId || selection.appKey) { + const matched = keys.find( + (k) => + (selection.keyId && k.id === selection.keyId) || + (selection.appKey && k.appKey === selection.appKey) + ); + if (!matched) { + console.error(`\n❌ 未找到指定的合思 OpenAPI 密钥 (${selection.appKey ?? selection.keyId})。`); + console.error(`ℹ️ 该合思企业当前存在以下 ${keys.length} 套候选密钥:`); + for (const k of keys) { + const status = k.active ? "🟢 启用" : "⚪ 停用"; + console.error(` • "${k.name || "未命名应用"}" (appKey: ${k.appKey}, keyId: ${k.id}, 状态: ${status})`); + } + throw new CliError( + `指定的合思密钥不存在,请从上述候选列表中选择正确的 appKey 或 keyId。`, + 2, + `${contextCmd} --app-key ${keys[0]!.appKey}` + ); + } + return matched; + } + + if (keys.length === 1) { + return keys[0]!; + } + + // Multiple keys exist and user did not specify which one + console.error(`\nℹ️ [合思子域提权] 合思企业 [${corpId}] 存在多套 (${keys.length} 套) OpenAPI 应用密钥凭据:`); + for (let i = 0; i < keys.length; i++) { + const k = keys[i]!; + const status = k.active ? "🟢 启用" : "⚪ 停用"; + const name = k.name || "未命名应用"; + console.error(` [${i + 1}] "${name}" (appKey: ${k.appKey}, keyId: ${k.id}, 状态: ${status})`); + } + console.error(`\n👉 为确保权限提权绑定正确的业务应用,请显式指定要使用的密钥套件:`); + console.error(` 在命令后追加 --app-key 或 --key-id 参数。\n`); + + throw new CliError( + `合思企业 [${corpId}] 存在多套 OpenAPI 密钥,必须指定 --app-key 或 --key-id 明确选择要绑定的密钥。`, + 2, + `${contextCmd} --app-key ${keys[0]!.appKey}` + ); +} + +async function addLinkAsHoseCorp( + link: string, + name: string | undefined, + overwrite: boolean, + force = false, + selection?: { appKey?: string; keyId?: string } +) { + console.error("ℹ️ [合思子域提权] 正在通过合思协助链接提取 OpenAPI 开发者密钥并提升企业权限等级..."); + const result = await fetchHoseOpenApiKeysFromLink(link); + const selectedKey = selectHoseOpenApiKey( + result.keys, + result.corpId, + selection ?? {}, + `seal-use corps add-link "" --as-hose` + ); + console.error( + `ℹ️ [合思子域提权] 已选定合思 OpenAPI 凭据 (appKey: ${selectedKey.appKey}, 应用: "${selectedKey.name || "未命名应用"}"),正在初始化为长期合思标准配置...` + ); + await addHoseCorp({ + domain: result.baseUrl, + appKey: selectedKey.appKey, + appSecurity: selectedKey.appSecurity, + corpId: result.corpId, + name: name ?? result.corpName ?? result.corpId, + staffId: result.staffId, + overwrite, + force + }); +} + +export async function extractKeysFromLinkAction( + link: string, + options: { + reveal?: boolean; + save?: boolean; + name?: string; + overwrite?: boolean; + force?: boolean; + appKey?: string; + keyId?: string; + } +) { + const result = await fetchHoseOpenApiKeysFromLink(link); + const reveal = options.reveal === true; + + if (options.save) { + const selectedKey = selectHoseOpenApiKey( + result.keys, + result.corpId, + { appKey: options.appKey, keyId: options.keyId }, + `seal-use corps extract-keys "" --save` + ); + console.error( + `ℹ️ [合思子域提权] 正在将选定的合思 OpenAPI 密钥 (appKey: ${selectedKey.appKey}, 应用: "${selectedKey.name || "未命名应用"}") 保存为标准合思企业配置...` + ); + await addHoseCorp({ + domain: result.baseUrl, + appKey: selectedKey.appKey, + appSecurity: selectedKey.appSecurity, + corpId: result.corpId, + name: options.name ?? result.corpName ?? result.corpId, + staffId: result.staffId, + overwrite: options.overwrite, + force: options.force + }); + return; + } + + if (!reveal) { + console.error( + "ℹ️ [合思子域提权] 成功提取合思 (Hose) OpenAPI 密钥。接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整 appSecurity 明文;附加 --save 可将临时会话提权并持久化为标准合思企业。\n" + ); + } else { + console.error( + "⚠️ [合思子域提权] 正在以明文展示合思 (Hose) appSecurity 接入密码,请妥善保管敏感凭据。\n" + ); + } + + printJson({ + provider: "hose", + capability: "privilege-elevation", + corpId: result.corpId, + corpName: result.corpName ?? result.corpId, + baseUrl: result.baseUrl, + staffId: result.staffId, + keyCount: result.keys.length, + keys: result.keys.map((k) => ({ + id: k.id, + name: k.name || "-", + appKey: k.appKey, + appSecurity: reveal ? k.appSecurity : maskHoseSecurity(k.appSecurity), + active: k.active, + createTime: k.createTime, + updateTime: k.updateTime + })) + }); +} + +export async function showCorpKeysAction(targetCorpId: string | undefined, options: { reveal?: boolean }) { + const corp = selectCorp(targetCorpId); + const reveal = options.reveal === true; + + if (corp.source.type !== "hose") { + throw new CliError( + `【合思子域专享能力】当前企业「${corp.name}」(id: ${corp.id}) 为原生 Seal (${corp.source.type}) 租户,非合思 (Hose/合思云/易快报) 渠道企业。\n` + + `OpenAPI 密钥查询与提权能力专属于合思生态租户(用于从合思协助链接或合思凭据中提取开发者密钥提升权限等级),非合思渠道企业不支持此能力。`, + 2 + ); + } + + const appKey = corp.source.appKey ?? (corp.source as any).key; + const appSecurity = corp.source.appSecurity ?? (corp.source as any).password; + + if (!reveal) { + console.error("💡 [合思子域] 接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整 appSecurity 明文。\n"); + } else { + console.error("⚠️ [合思子域] 正在以明文展示合思 appSecurity 接入密码,请妥善保管敏感凭据。\n"); + } + + printJson({ + provider: "hose", + capability: "privilege-elevation", + corpId: corp.id, + corpName: corp.name, + domain: corp.source.domain, + staffId: corp.source.staffId, + appKey: appKey ?? "-", + appSecurity: appSecurity ? (reveal ? appSecurity : maskHoseSecurity(appSecurity)) : "-", + active: true + }); +} + type RemoteSealIdentity = { user: Record; tenant: Record; diff --git a/src/cli/help.ts b/src/cli/help.ts index 855e559..6d60792 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -144,7 +144,45 @@ export const HELP_REGISTRY: AreaHelp[] = [ { name: "add-link", summary: "Import enterprise configuration from a Hose assistance link", - usage: ["seal-use corps add-link [--name ] [--overwrite]"] + usage: [ + "seal-use corps add-link [--name ] [--as-hose] [--app-key ] [--key-id ] [--overwrite]" + ], + options: [ + { flag: "--name ", description: "Optional custom name for the enterprise" }, + { flag: "--as-hose", description: "【合思子域提权】从协助链接提取 OpenAPI 密钥并将临时会话升级为长期合思标准配置" }, + { flag: "--app-key ", description: "企业存在多套密钥时,指定使用的 appKey" }, + { flag: "--key-id ", description: "企业存在多套密钥时,指定使用的 keyId" }, + { flag: "--overwrite", description: "Overwrite existing enterprise config" } + ] + }, + { + name: "extract-keys", + aliases: ["extract-key"], + summary: "【合思子域提权】从合思协助链接提取 OpenAPI 开发者密钥 (appKey/appSecurity)", + usage: [ + "seal-use corps extract-keys [--reveal] [--save] [--app-key ] [--key-id ] [--name ] [--overwrite]" + ], + options: [ + { flag: "--reveal, -r", description: "显式揭示完整 appSecurity 明文(默认脱敏保护)" }, + { flag: "--save", description: "【提权升级】将提取到的合思 OpenAPI 密钥保存为长期标准配置" }, + { flag: "--app-key ", description: "存在多套密钥时指定使用的 appKey" }, + { flag: "--key-id ", description: "存在多套密钥时指定使用的 keyId" }, + { flag: "--name ", description: "Custom enterprise name when saving" }, + { flag: "--overwrite", description: "Overwrite existing enterprise config" } + ], + description: "专属于合思 (Hose/合思云/易快报) 子域的能力。利用协助链接中的内部权限读取 OpenAPI 密钥,将临时会话提权为标准开发者凭据。非合思渠道企业不支持。" + }, + { + name: "keys", + summary: "【合思子域】查看企业已配置的合思 OpenAPI 密钥,或从协助链接中提取", + usage: [ + "seal-use corps keys [ | ] [--reveal] [--save] [--app-key ]" + ], + options: [ + { flag: "--reveal, -r", description: "显式揭示完整 appSecurity 明文(默认脱敏保护)" }, + { flag: "--save", description: "从协助链接提取并保存为标准配置" }, + { flag: "--app-key ", description: "多套密钥时指定目标 appKey" } + ] }, { name: "regression", @@ -640,6 +678,29 @@ export const HELP_REGISTRY: AreaHelp[] = [ name: "hose-link", summary: "Generate Hose third-party assistance link", usage: ["seal-use auth hose-link [--corp ] [--expire 7200]"] + }, + { + name: "extract-keys", + summary: "【合思子域提权】从合思协助链接提取 OpenAPI 开发者密钥并可选升级配置", + usage: [ + "seal-use auth extract-keys [--reveal] [--save] [--app-key ] [--key-id ] [--name ] [--overwrite]" + ], + options: [ + { flag: "--reveal, -r", description: "显式揭示完整 appSecurity 明文(默认脱敏保护)" }, + { flag: "--save", description: "【提权升级】直接将提取到的合思 OpenAPI 密钥持久化为标准企业配置" }, + { flag: "--app-key ", description: "存在多套密钥时指定使用的 appKey" }, + { flag: "--key-id ", description: "存在多套密钥时指定使用的 keyId" } + ], + description: "专属于合思 (Hose/合思云/易快报) 子域的能力。非合思渠道企业不支持。" + }, + { + name: "keys", + summary: "【合思子域】查看当前企业已配置的合思 OpenAPI 开发者密钥", + usage: ["seal-use auth keys [--corp ] [--reveal]"], + options: [ + { flag: "--reveal, -r", description: "显式揭示完整 appSecurity 明文(默认脱敏保护)" } + ], + description: "专属于合思 (Hose) 来源企业。原生 Seal 企业不包含 OpenAPI 密钥,不支持此命令。" } ] }, diff --git a/src/cli/runner.ts b/src/cli/runner.ts index 178468c..75dc26c 100755 --- a/src/cli/runner.ts +++ b/src/cli/runner.ts @@ -7,7 +7,7 @@ import type { CorpConfig } from "../core/config/types.js"; import { VERSION, VERSION_INFO } from "../version.js"; import { handleApprovalRunsCommand } from "./commands/approval-runs.js"; import { handleAnalyticsCommand } from "./commands/analytics.js"; -import { handleAuthCommand } from "./commands/auth.js"; +import { handleAuthCommand, handleAuthExtractKeysCommand } from "./commands/auth.js"; import { handleBillingCommand } from "./commands/billing.js"; import { handleConfigCommand } from "./commands/config.js"; import { handleContactsCommand } from "./commands/contacts.js"; @@ -328,6 +328,11 @@ async function dispatch(argv: string[], runtime: CliRuntime) { return; } + if (area === "auth" && (action === "extract-keys" || action === "extract-key")) { + await handleAuthExtractKeysCommand(maybeName, args); + return; + } + const corp = selectCorp(stringOption(args.options.corp)); if (area === "source") { diff --git a/src/core/auth/hose.test.ts b/src/core/auth/hose.test.ts index 7bce8e7..9dfa02b 100644 --- a/src/core/auth/hose.test.ts +++ b/src/core/auth/hose.test.ts @@ -132,7 +132,8 @@ describe("hose auth helpers", () => { expect(result).toEqual({ corpId: "acme-01", - accessToken: "temporary-token" + accessToken: "temporary-token", + baseUrl: "https://wx2.ekuaibao.com" }); }); @@ -197,4 +198,73 @@ describe("hose auth helpers", () => { hoseCorpConfig: { corporationId: " ACME-01 " } })).not.toThrow(); }); + + test("fetchHoseOpenApiKeysFromLink extracts keys with discovered metadata", async () => { + const { fetchHoseOpenApiKeysFromLink, maskHoseSecurity } = await import("./hose.js"); + + expect(maskHoseSecurity("1234567890abcdef")).toBe("12345678...cdef"); + expect(maskHoseSecurity("short")).toBe("******"); + expect(maskHoseSecurity("")).toBe("-"); + + const jwtPayload = Buffer.from( + JSON.stringify({ + staffId: "acme-01:admin01", + corporationName: "Acme Corp Ltd", + staffName: "Alice Admin" + }) + ).toString("base64url"); + const fakeJwt = `header.${jwtPayload}.signature`; + + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const urlStr = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + const url = new URL(urlStr); + + if (url.pathname === "/api/engine/realm/$UNITY/actions/jwt") { + return new Response(JSON.stringify({ value: fakeJwt }), { + status: 200, + headers: { "content-type": "application/json" } + }); + } + + if (url.pathname === "/api/innerapi/v1/key") { + const reqHeaders = input instanceof Request ? input.headers : new Headers(init?.headers); + expect(reqHeaders.get("accesstoken")).toBe("test-token"); + expect(reqHeaders.get("corpid")).toBe("acme-01"); + expect(reqHeaders.get("staffid")).toBe("acme-01:admin01"); + + return new Response( + JSON.stringify({ + items: [ + { + id: "key-001", + name: "生产系统接入", + appKey: "ak_acme_production_123", + appSecurity: "sec_secret_password_456789", + active: true, + corporationId: "acme-01", + createTime: 1700000000000 + } + ], + count: 1 + }), + { status: 200, headers: { "content-type": "application/json" } } + ); + } + + return new Response("not found", { status: 404 }); + }) as typeof fetch; + + const res = await fetchHoseOpenApiKeysFromLink( + "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=test-token&ekbCorpId=Acme-01" + ); + + expect(res.corpId).toBe("acme-01"); + expect(res.corpName).toBe("Acme Corp Ltd"); + expect(res.staffId).toBe("acme-01:admin01"); + expect(res.baseUrl).toBe("https://wx2.ekuaibao.com"); + expect(res.keys.length).toBe(1); + expect(res.keys[0]!.appKey).toBe("ak_acme_production_123"); + expect(res.keys[0]!.appSecurity).toBe("sec_secret_password_456789"); + expect(res.keys[0]!.active).toBe(true); + }); }); diff --git a/src/core/auth/hose.ts b/src/core/auth/hose.ts index 5fb6148..6461763 100644 --- a/src/core/auth/hose.ts +++ b/src/core/auth/hose.ts @@ -45,6 +45,7 @@ type SealTokenResponse = { export type HoseAssistLink = { corpId: string; accessToken: string; + baseUrl?: string; }; export type HoseAssistSealSession = { @@ -151,7 +152,8 @@ export function parseHoseAssistLink(value: string): HoseAssistLink { return { corpId, - accessToken: accessTokens[0]! + accessToken: accessTokens[0]!, + baseUrl: url.origin }; } @@ -221,12 +223,14 @@ function isHoseAssistHost(hostname: string): boolean { function normalizeHoseAssistLink(value: HoseAssistLink): HoseAssistLink { const corpId = typeof value?.corpId === "string" ? value.corpId.trim().toLowerCase() : ""; const accessToken = typeof value?.accessToken === "string" ? value.accessToken.trim() : ""; + const baseUrl = typeof value?.baseUrl === "string" && value.baseUrl.trim() ? value.baseUrl.trim() : undefined; if (!CORP_ID_PATTERN.test(corpId) || !accessToken) { throw new Error("Invalid Hose assistance link: accessToken and ekbCorpId are required"); } return { corpId, - accessToken + accessToken, + ...(baseUrl ? { baseUrl } : {}) }; } @@ -721,3 +725,186 @@ export async function fetchHoseStaffDetails( return json.items ?? []; } + +// ── OpenAPI Key Extraction from Assistance Link ────────────────────────────── + +export type HoseOpenApiKey = { + id: string; + name?: string; + appKey: string; + appSecurity: string; + active: boolean; + corporationId?: string; + createTime?: number; + updateTime?: number; +}; + +export type HoseAssistLinkDetails = { + corpId: string; + baseUrl: string; + accessToken: string; + staffId: string; + corpName?: string; + staffName?: string; + isAdmin?: boolean; + cellphone?: string; +}; + +export type HoseLinkKeysResult = { + corpId: string; + corpName?: string; + baseUrl: string; + staffId: string; + keys: HoseOpenApiKey[]; +}; + +export function maskHoseSecurity(secret: string): string { + if (!secret) return "-"; + if (secret.length <= 12) return "******"; + return `${secret.slice(0, 8)}...${secret.slice(-4)}`; +} + +export async function resolveHoseAssistLinkDetails( + value: string | HoseAssistLink +): Promise { + const link = typeof value === "string" ? parseHoseAssistLink(value) : normalizeHoseAssistLink(value); + const baseUrl = link.baseUrl || "https://app.ekuaibao.com"; + let staffId: string | undefined; + let corpName: string | undefined; + let staffName: string | undefined; + let isAdmin: boolean | undefined; + let cellphone: string | undefined; + + const headers: Record = { + accesstoken: link.accessToken, + corpid: link.corpId + }; + + // 1. Try resolving staffId, corporationName, and staffName via $UNITY JWT + try { + const jwtRes = await ky + .get(`${baseUrl}/api/engine/realm/$UNITY/actions/jwt`, { + searchParams: { corpId: link.corpId }, + headers, + timeout: 10000 + }) + .json<{ id?: string; value?: string }>(); + const token = jwtRes.id || jwtRes.value; + if (token) { + const parts = token.split("."); + if (parts.length >= 2) { + const base64 = parts[1]!.replace(/-/g, "+").replace(/_/g, "/"); + const payload = JSON.parse(Buffer.from(base64, "base64").toString("utf-8")) as Record; + if (typeof payload.staffId === "string") staffId = payload.staffId; + if (typeof payload.corporationName === "string") corpName = payload.corporationName; + if (typeof payload.staffName === "string") staffName = payload.staffName; + if (typeof payload.cellphone === "string") cellphone = payload.cellphone; + if (payload.isAdmin !== undefined) { + isAdmin = payload.isAdmin === true || payload.isAdmin === "true"; + } + } + } + } catch { + // Ignore and fallback + } + + // 2. If staffId or corpName is still missing, fallback to /api/account/v2/session + if (!staffId || !corpName) { + try { + const sessionRes = await ky + .get(`${baseUrl}/api/account/v2/session`, { + headers: { + ...headers, + ...(staffId ? { staffid: staffId } : {}) + }, + timeout: 10000 + }) + .json<{ + value?: { + id?: string; + userId?: string; + loginStaffId?: string; + corporationId?: string; + corporationName?: string; + privilege?: string; + }; + }>(); + const s = sessionRes?.value; + if (s) { + if (!staffId && s.loginStaffId) staffId = s.loginStaffId; + if (!corpName && s.corporationName) corpName = s.corporationName; + if (!staffName && s.privilege) staffName = s.privilege; + } + } catch { + // Ignore + } + } + + // Default staffId if still unresolved + if (!staffId) { + staffId = `${link.corpId}:admin`; + } + + return { + corpId: link.corpId, + baseUrl, + accessToken: link.accessToken, + staffId, + corpName, + staffName, + isAdmin, + cellphone + }; +} + +export async function fetchHoseOpenApiKeysFromLink( + value: string | HoseAssistLink +): Promise { + const details = await resolveHoseAssistLinkDetails(value); + const headers: Record = { + accesstoken: details.accessToken, + corpid: details.corpId, + staffid: details.staffId + }; + + let json: { items?: unknown[]; count?: number }; + try { + const response = await ky.get(`${details.baseUrl}/api/innerapi/v1/key`, { + searchParams: { corpId: details.corpId }, + headers, + timeout: 15000 + }); + json = (await response.json()) as { items?: unknown[]; count?: number }; + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + throw new Error(`Failed to query Hose OpenAPI keys from assistance link: ${msg}`); + } + + const rawItems = json.items ?? []; + const keys: HoseOpenApiKey[] = []; + for (const raw of rawItems) { + if (typeof raw === "object" && raw !== null) { + const item = raw as Record; + if (typeof item.appKey === "string" && typeof item.appSecurity === "string") { + keys.push({ + id: String(item.id ?? item.appKey), + name: typeof item.name === "string" ? item.name : undefined, + appKey: item.appKey, + appSecurity: item.appSecurity, + active: typeof item.active === "boolean" ? item.active : true, + corporationId: typeof item.corporationId === "string" ? item.corporationId : details.corpId, + createTime: typeof item.createTime === "number" ? item.createTime : undefined, + updateTime: typeof item.updateTime === "number" ? item.updateTime : undefined + }); + } + } + } + + return { + corpId: details.corpId, + corpName: details.corpName, + baseUrl: details.baseUrl, + staffId: details.staffId, + keys + }; +}