Add Hose assistance link onboarding (#13)
This commit is contained in:
1 parent
9f3975a6a5
commit
4ce206a2ce
13 files changed
+527
-17
No files matched your search
@@ -50,6 +50,8 @@ describe("CLI version & help handling", () => {
|
||||
expect(result.stdout).toContain("seal-home users delegation <userIdOrPhone|name>");
|
||||
expect(result.stdout).toContain("seal-home webhook get|find <idOrName>");
|
||||
expect(result.stdout).toContain("seal-home webhook add --name <name> --result-url <url>");
|
||||
expect(result.stdout).toContain("seal-home corps add-link <https://.../web/thirdparty.html?...>");
|
||||
expect(result.stdout).toContain("seal-home delegation create [--note <note>] [--from-link <url>]");
|
||||
expect(result.stdout).toContain("[--secret <secret>|--rotate-secret]");
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { runCli } from "../runner.js";
|
||||
|
||||
const ORIGINAL_ENV = {
|
||||
enterprises: process.env.SEAL_HOME_ENTERPRISES_DIR,
|
||||
config: process.env.SEAL_HOME_CONFIG_FILE,
|
||||
tokenStore: process.env.SEAL_HOME_TOKEN_STORE
|
||||
};
|
||||
const ORIGINAL_FETCH = globalThis.fetch;
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
restoreEnv("SEAL_HOME_ENTERPRISES_DIR", ORIGINAL_ENV.enterprises);
|
||||
restoreEnv("SEAL_HOME_CONFIG_FILE", ORIGINAL_ENV.config);
|
||||
restoreEnv("SEAL_HOME_TOKEN_STORE", ORIGINAL_ENV.tokenStore);
|
||||
globalThis.fetch = ORIGINAL_FETCH;
|
||||
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe("corps link onboarding", () => {
|
||||
test("imports a Hose assistance link and writes a verified Seal config", async () => {
|
||||
const enterprises = setupConfigEnv();
|
||||
mockSealLinkRequests();
|
||||
|
||||
const link = hoseLink();
|
||||
const result = await runCli(["corps", "add-link", link, "--name", "Acme Corporation"]);
|
||||
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.stdout).not.toContain("hose-token");
|
||||
expect(result.stdout).not.toContain(link);
|
||||
|
||||
const config = JSON.parse(readFileSync(join(enterprises, "acme-01.json"), "utf-8")) as {
|
||||
id: string;
|
||||
name: string;
|
||||
seal: { url?: string; tenantSlug?: string };
|
||||
source: {
|
||||
type: string;
|
||||
token: string;
|
||||
expiresIn: number;
|
||||
provider?: string;
|
||||
corpId?: string;
|
||||
};
|
||||
};
|
||||
expect(config).toMatchObject({
|
||||
id: "acme-01",
|
||||
name: "Acme Corporation",
|
||||
seal: {
|
||||
url: "https://acme-01.sealai.cc",
|
||||
tenantSlug: "acme-01"
|
||||
},
|
||||
source: {
|
||||
type: "seal",
|
||||
token: "seal-bearer-token",
|
||||
expiresIn: 1800,
|
||||
provider: "hosecloud",
|
||||
corpId: "acme-01"
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test("creates a delegation directly from a Hose assistance link", async () => {
|
||||
mockSealLinkRequests({ delegation: true });
|
||||
|
||||
const result = await runCli([
|
||||
"delegation",
|
||||
"create",
|
||||
"--from-link",
|
||||
hoseLink(),
|
||||
"--note",
|
||||
"Customer support"
|
||||
]);
|
||||
|
||||
expect(result.isError).toBe(false);
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({
|
||||
tenant: {
|
||||
corpId: "acme-01",
|
||||
tenantSlug: "acme-01"
|
||||
},
|
||||
user: {
|
||||
id: "user-1",
|
||||
providerUserId: "staff-1"
|
||||
},
|
||||
delegation: {
|
||||
id: "delegation-1",
|
||||
token: "delegation-token",
|
||||
link: "https://acme-01.sealai.cc/delegation?token=delegation-token"
|
||||
},
|
||||
expiresIn: 1800
|
||||
});
|
||||
});
|
||||
|
||||
test("rejects a link when Seal identity does not match ekbCorpId", async () => {
|
||||
mockSealLinkRequests({ tenantSlug: "other-tenant", corporationId: "other-corp" });
|
||||
const enterprises = setupConfigEnv();
|
||||
|
||||
const result = await runCli(["corps", "add-link", hoseLink()]);
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.stderr).toContain("tenant mismatch");
|
||||
expect(result.stderr).not.toContain("hose-token");
|
||||
expect(readDirectory(enterprises)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
function setupConfigEnv() {
|
||||
const root = mkdtempSync(join(tmpdir(), "seal-home-link-cli-"));
|
||||
const enterprises = join(root, "enterprises");
|
||||
tempDirs.push(root);
|
||||
process.env.SEAL_HOME_ENTERPRISES_DIR = enterprises;
|
||||
process.env.SEAL_HOME_CONFIG_FILE = join(root, "config.json");
|
||||
process.env.SEAL_HOME_TOKEN_STORE = join(root, "tokens.json");
|
||||
return enterprises;
|
||||
}
|
||||
|
||||
function hoseLink() {
|
||||
return "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=hose-token&ekbCorpId=Acme-01&pageType=home";
|
||||
}
|
||||
|
||||
function mockSealLinkRequests(options: {
|
||||
delegation?: boolean;
|
||||
tenantSlug?: string;
|
||||
corporationId?: string;
|
||||
} = {}) {
|
||||
globalThis.fetch = (async (input: RequestInfo | URL) => {
|
||||
const requestUrl = typeof input === "string"
|
||||
? input
|
||||
: input instanceof URL
|
||||
? input.toString()
|
||||
: input.url;
|
||||
const url = new URL(requestUrl);
|
||||
|
||||
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: "user-1",
|
||||
tenantId: "tenant-1",
|
||||
name: "Support User",
|
||||
providerUserId: "staff-1",
|
||||
isAdmin: true
|
||||
},
|
||||
tenant: {
|
||||
id: "tenant-1",
|
||||
name: "Acme Tenant",
|
||||
tenantSlug: options.tenantSlug ?? "acme-01",
|
||||
hoseCorpConfig: {
|
||||
corporationId: options.corporationId ?? "acme-01",
|
||||
corporationName: "Acme Corporation"
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (options.delegation && url.pathname === "/api/v1/delegation/create") {
|
||||
return jsonResponse({
|
||||
data: {
|
||||
id: "delegation-1",
|
||||
token: "delegation-token",
|
||||
link: "https://acme-01.sealai.cc/delegation?token=delegation-token"
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return jsonResponse({ error: `Unexpected request: ${url.pathname}` }, 404);
|
||||
}) as typeof fetch;
|
||||
}
|
||||
|
||||
function jsonResponse(value: unknown, status = 200) {
|
||||
return new Response(JSON.stringify(value), {
|
||||
status,
|
||||
headers: { "content-type": "application/json" }
|
||||
});
|
||||
}
|
||||
|
||||
function readDirectory(path: string) {
|
||||
try {
|
||||
return Array.from(new Bun.Glob("*.json").scanSync({ cwd: path })).sort();
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function restoreEnv(name: string, value: string | undefined) {
|
||||
if (value === undefined) delete process.env[name];
|
||||
else process.env[name] = value;
|
||||
}
|
||||
@@ -1,12 +1,15 @@
|
||||
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
assertHoseAssistTenantMatches,
|
||||
exchangeHoseAssistLink,
|
||||
fetchHoseRoleDefGroups,
|
||||
fetchHoseRoleStaffs,
|
||||
fetchHoseStaffDetails,
|
||||
probeHoseDomain
|
||||
} from "../../core/auth/hose.js";
|
||||
import { clearCorpTokenCache } from "../../core/auth/token-store.js";
|
||||
import { createSealClientForUrl } from "../../core/http/factory.js";
|
||||
import {
|
||||
loadCorpConfigs,
|
||||
loadGlobalConfig,
|
||||
@@ -14,10 +17,12 @@ import {
|
||||
saveGlobalConfig
|
||||
} from "../../core/config/loader.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import { getMe } from "../../domains/seal/api.js";
|
||||
import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/source.js";
|
||||
import { selectCorp } from "../helpers.js";
|
||||
import {
|
||||
inferCorpIdFromStaffId,
|
||||
booleanOption,
|
||||
jsonObject,
|
||||
optionalNumber,
|
||||
optionalString,
|
||||
@@ -103,6 +108,17 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "add-link") {
|
||||
const link = maybeName ?? stringOption(args.options.link) ?? stringOption(args.options.url);
|
||||
if (!link) {
|
||||
throw new Error(
|
||||
"Usage: seal-home corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]"
|
||||
);
|
||||
}
|
||||
await addLinkCorp(link, stringOption(args.options.name), booleanOption(args.options.overwrite) === true);
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error(`Unknown corps command: ${action ?? ""}. Run 'seal-home help' for available commands.`);
|
||||
}
|
||||
|
||||
@@ -359,13 +375,58 @@ async function addSealCorp(input: Record<string, unknown>) {
|
||||
const expiresIn = optionalNumber(input, "expiresIn") ?? 30 * 24 * 60 * 60;
|
||||
const verify = input.force === true || input.verify === false ? false : true;
|
||||
const remote = verify ? await resolveSealWhoami(sealUrl, token) : undefined;
|
||||
writeSealCorpConfig(input, { token, sealUrl, expiresIn, verify, remote });
|
||||
}
|
||||
|
||||
async function addLinkCorp(link: string, name: string | undefined, overwrite: boolean) {
|
||||
const session = await exchangeHoseAssistLink(link);
|
||||
const client = createSealClientForUrl(session.sealUrl, session.token);
|
||||
const me = await getMe(client);
|
||||
const identity = {
|
||||
user: me.user as unknown as Record<string, unknown>,
|
||||
tenant: me.tenant as unknown as Record<string, unknown>
|
||||
};
|
||||
|
||||
assertHoseAssistTenantMatches(session.corpId, identity.tenant);
|
||||
writeSealCorpConfig(
|
||||
{
|
||||
id: session.corpId,
|
||||
corpId: session.corpId,
|
||||
name,
|
||||
provider: "hosecloud",
|
||||
overwrite
|
||||
},
|
||||
{
|
||||
token: session.token,
|
||||
sealUrl: session.sealUrl,
|
||||
expiresIn: session.expiresIn,
|
||||
verify: true,
|
||||
remote: identity
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
type RemoteSealIdentity = {
|
||||
user: Record<string, unknown>;
|
||||
tenant: Record<string, unknown>;
|
||||
};
|
||||
|
||||
function writeSealCorpConfig(
|
||||
input: Record<string, unknown>,
|
||||
auth: {
|
||||
token: string;
|
||||
sealUrl: string;
|
||||
expiresIn: number;
|
||||
verify: boolean;
|
||||
remote?: RemoteSealIdentity;
|
||||
}
|
||||
) {
|
||||
const { token, sealUrl, expiresIn, verify, remote } = auth;
|
||||
const remoteUser = remote?.user;
|
||||
const remoteTenant = remote?.tenant;
|
||||
const tenantSlug = optionalString(input, "tenantSlug") ?? stringValue(remoteTenant?.tenantSlug);
|
||||
const tenantId = optionalString(input, "tenantId") ?? stringValue(remoteTenant?.id);
|
||||
const tenantName = optionalString(input, "tenantName") ??
|
||||
optionalString(input, "name") ??
|
||||
stringValue(remoteTenant?.name);
|
||||
const tenantName = optionalString(input, "tenantName") ?? stringValue(remoteTenant?.name);
|
||||
const id = optionalString(input, "id") ?? tenantSlug ?? tenantId;
|
||||
if (!id) {
|
||||
throw new Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");
|
||||
@@ -378,10 +439,11 @@ async function addSealCorp(input: Record<string, unknown>) {
|
||||
const provider = optionalString(input, "provider") ??
|
||||
stringValue(remoteUser?.provider) ??
|
||||
stringValue((remoteTenant as any)?.providerConfig?.provider);
|
||||
const corpId = optionalString(input, "corpId") ?? tenantSlug ?? tenantId ?? id;
|
||||
|
||||
const config: CorpConfig = {
|
||||
id,
|
||||
name: tenantName ?? id,
|
||||
name: optionalString(input, "name") ?? tenantName ?? id,
|
||||
seal: {
|
||||
url: sealUrl,
|
||||
tenantSlug,
|
||||
@@ -395,7 +457,7 @@ async function addSealCorp(input: Record<string, unknown>) {
|
||||
sealUrl,
|
||||
expiresIn,
|
||||
staffId,
|
||||
corpId: tenantSlug ?? tenantId ?? id,
|
||||
corpId,
|
||||
tenantId,
|
||||
tenantSlug,
|
||||
tenantName,
|
||||
|
||||
@@ -1,9 +1,37 @@
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { assertHoseAssistTenantMatches, exchangeHoseAssistLink } from "../../core/auth/hose.js";
|
||||
import { createSealClientForUrl } from "../../core/http/factory.js";
|
||||
import { createDelegation, getMe } from "../../domains/seal/api.js";
|
||||
import { runTool } from "../helpers.js";
|
||||
import { stringOption } from "../parser.js";
|
||||
import { outputOptions } from "../printer.js";
|
||||
import { outputOptions, printJson } from "../printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
|
||||
export async function handleDelegationFromHoseLink(link: string, note?: string) {
|
||||
const session = await exchangeHoseAssistLink(link);
|
||||
const client = createSealClientForUrl(session.sealUrl, session.token);
|
||||
const me = await getMe(client);
|
||||
assertHoseAssistTenantMatches(session.corpId, me.tenant as unknown as Record<string, unknown>);
|
||||
const delegation = await createDelegation(client, { note });
|
||||
|
||||
printJson({
|
||||
tenant: {
|
||||
id: me.tenant.id,
|
||||
name: me.tenant.name,
|
||||
tenantSlug: me.tenant.tenantSlug,
|
||||
corpId: session.corpId
|
||||
},
|
||||
user: {
|
||||
id: me.user.id,
|
||||
name: me.user.name,
|
||||
providerUserId: me.user.providerUserId,
|
||||
isAdmin: me.user.isAdmin
|
||||
},
|
||||
delegation,
|
||||
expiresIn: session.expiresIn
|
||||
});
|
||||
}
|
||||
|
||||
export async function handleDelegationCommand(
|
||||
action: string | undefined,
|
||||
|
||||
+2
-1
@@ -97,10 +97,11 @@ Usage:
|
||||
seal-home corps switch <corpId>
|
||||
seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
|
||||
seal-home corps add-seal --json '{"sealUrl":"https://tenant.sealai.cc","token":"seal-bearer-token"}'
|
||||
seal-home corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]
|
||||
seal-home auth diagnose [--corp <corpId>]
|
||||
seal-home auth hose-link [--corp <corpId>] [--expire 7200]
|
||||
seal-home delegation list [--corp <corpId>]
|
||||
seal-home delegation create [--note <note>] [--corp <corpId>]
|
||||
seal-home delegation create [--note <note>] [--from-link <url>] [--corp <corpId>]
|
||||
seal-home delegation revoke <tokenId> [--corp <corpId>]
|
||||
seal-home users create --name <name> --phone <phone> [--dept <deptId>] [--corp <corpId>]
|
||||
seal-home users search <keyword> [--corp <corpId>]
|
||||
|
||||
+8
-1
@@ -10,7 +10,7 @@ import { handleBillingCommand } from "./commands/billing.js";
|
||||
import { handleConfigCommand } from "./commands/config.js";
|
||||
import { handleContextCommand } from "./commands/context.js";
|
||||
import { handleCorpsCommand } from "./commands/corps.js";
|
||||
import { handleDelegationCommand } from "./commands/delegation.js";
|
||||
import { handleDelegationCommand, handleDelegationFromHoseLink } from "./commands/delegation.js";
|
||||
import { handleDeployCommand } from "./commands/deploy.js";
|
||||
import { handleHttpCommand } from "./commands/http.js";
|
||||
import { handleLlmCommand } from "./commands/llm.js";
|
||||
@@ -234,6 +234,13 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (area === "delegation" && action === "create" && ("from-link" in args.options || "link" in args.options)) {
|
||||
const link = stringOption(args.options["from-link"]) ?? stringOption(args.options.link);
|
||||
if (!link) throw new Error("Usage: seal-home delegation create --from-link <url> [--note <note>]");
|
||||
await handleDelegationFromHoseLink(link, stringOption(args.options.note));
|
||||
return;
|
||||
}
|
||||
|
||||
const corp = selectCorp(stringOption(args.options.corp));
|
||||
|
||||
if (area === "source") {
|
||||
|
||||
@@ -6,12 +6,15 @@ import { CorpConfig, HoseSealSource } from "../config/types.js";
|
||||
import {
|
||||
HOSE_STANDARD_DOMAINS,
|
||||
defaultSealUrl,
|
||||
exchangeHoseAssistLink,
|
||||
fetchHoseStaffDetails,
|
||||
getHoseEnterpriseUrl,
|
||||
normalizeBaseUrl
|
||||
normalizeBaseUrl,
|
||||
parseHoseAssistLink
|
||||
} from "./hose.js";
|
||||
|
||||
const ORIGINAL_ENV = process.env.SEAL_HOME_TOKEN_STORE;
|
||||
const ORIGINAL_FETCH = globalThis.fetch;
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function setupTokenStore(data: Record<string, unknown>): string {
|
||||
@@ -29,6 +32,7 @@ afterEach(() => {
|
||||
} else {
|
||||
process.env.SEAL_HOME_TOKEN_STORE = ORIGINAL_ENV;
|
||||
}
|
||||
globalThis.fetch = ORIGINAL_FETCH;
|
||||
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
@@ -116,5 +120,66 @@ describe("hose auth helpers", () => {
|
||||
const details = await fetchHoseStaffDetails("https://app.ekuaibao.com", "fake-token", []);
|
||||
expect(details).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
test("parses a Hose third-party assistance link without exposing its token", () => {
|
||||
const result = parseHoseAssistLink(
|
||||
"https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=temporary-token&ekbCorpId=Acme-01&pageType=home"
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
corpId: "acme-01",
|
||||
accessToken: "temporary-token"
|
||||
});
|
||||
});
|
||||
|
||||
test("rejects unsupported Hose assistance link shapes", () => {
|
||||
expect(() => parseHoseAssistLink("http://wx2.ekuaibao.com/web/thirdparty.html?accessToken=t&ekbCorpId=acme")).toThrow(
|
||||
"expected an HTTPS"
|
||||
);
|
||||
expect(() => parseHoseAssistLink("https://example.com/web/thirdparty.html?accessToken=t&ekbCorpId=acme")).toThrow(
|
||||
"expected an HTTPS"
|
||||
);
|
||||
expect(() => parseHoseAssistLink("https://wx2.ekuaibao.com/web/home.html?accessToken=t&ekbCorpId=acme")).toThrow(
|
||||
"expected an HTTPS"
|
||||
);
|
||||
expect(() => parseHoseAssistLink("https://wx2.ekuaibao.com/web/thirdparty.html?ekbCorpId=acme")).toThrow(
|
||||
"required exactly once"
|
||||
);
|
||||
});
|
||||
|
||||
test("exchanges a Hose assistance link for a Seal session", async () => {
|
||||
let requestedUrl = "";
|
||||
globalThis.fetch = (async (input: RequestInfo | URL) => {
|
||||
requestedUrl = typeof input === "string"
|
||||
? input
|
||||
: input instanceof URL
|
||||
? input.toString()
|
||||
: input.url;
|
||||
return new Response(JSON.stringify({
|
||||
data: {
|
||||
accessToken: "seal-bearer-token",
|
||||
expiresIn: 1800
|
||||
}
|
||||
}), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" }
|
||||
});
|
||||
}) as typeof fetch;
|
||||
|
||||
const result = await exchangeHoseAssistLink(
|
||||
"https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=hose-token&ekbCorpId=Acme-01"
|
||||
);
|
||||
|
||||
const url = new URL(requestedUrl);
|
||||
expect(url.origin).toBe("https://acme-01.sealai.cc");
|
||||
expect(url.pathname).toBe("/api/auth/oauth2/session/oem-hosecloud");
|
||||
expect(url.searchParams.get("token")).toBe("hose-token");
|
||||
expect(url.searchParams.get("returnToken")).toBe("1");
|
||||
expect(result).toEqual({
|
||||
corpId: "acme-01",
|
||||
sealUrl: "https://acme-01.sealai.cc",
|
||||
token: "seal-bearer-token",
|
||||
expiresIn: 1800
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -40,6 +40,18 @@ type SealTokenResponse = {
|
||||
};
|
||||
};
|
||||
|
||||
export type HoseAssistLink = {
|
||||
corpId: string;
|
||||
accessToken: string;
|
||||
};
|
||||
|
||||
export type HoseAssistSealSession = {
|
||||
corpId: string;
|
||||
sealUrl: string;
|
||||
token: string;
|
||||
expiresIn: number;
|
||||
};
|
||||
|
||||
export const HOSE_STANDARD_DOMAINS = [
|
||||
"https://app.ekuaibao.com",
|
||||
"https://dd2.hosecloud.com",
|
||||
@@ -49,6 +61,10 @@ export const HOSE_STANDARD_DOMAINS = [
|
||||
"https://feishu.ekuaibao.com"
|
||||
] as const;
|
||||
|
||||
const HOSE_ASSIST_HOST_SUFFIXES = [".ekuaibao.com", ".hosecloud.com"] as const;
|
||||
const HOSE_ASSIST_PATH = "/web/thirdparty.html";
|
||||
const CORP_ID_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
||||
|
||||
export type HoseRoleDef = {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -101,6 +117,109 @@ export function normalizeBaseUrl(url: string): string {
|
||||
return url.replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
export function parseHoseAssistLink(value: string): HoseAssistLink {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(value.trim());
|
||||
} catch {
|
||||
throw new Error("Invalid Hose assistance link: expected a valid HTTPS URL");
|
||||
}
|
||||
|
||||
if (
|
||||
url.protocol !== "https:" ||
|
||||
url.port ||
|
||||
!isHoseAssistHost(url.hostname) ||
|
||||
url.pathname.replace(/\/+$/, "") !== HOSE_ASSIST_PATH
|
||||
) {
|
||||
throw new Error(
|
||||
"Invalid Hose assistance link: expected an HTTPS */web/thirdparty.html URL from ekuaibao.com or hosecloud.com"
|
||||
);
|
||||
}
|
||||
|
||||
const accessTokens = url.searchParams.getAll("accessToken").filter(Boolean);
|
||||
const corpIds = url.searchParams.getAll("ekbCorpId").filter(Boolean);
|
||||
if (accessTokens.length !== 1 || corpIds.length !== 1) {
|
||||
throw new Error("Invalid Hose assistance link: accessToken and ekbCorpId are required exactly once");
|
||||
}
|
||||
|
||||
const corpId = corpIds[0]!.trim().toLowerCase();
|
||||
if (!CORP_ID_PATTERN.test(corpId)) {
|
||||
throw new Error("Invalid Hose assistance link: ekbCorpId is not a valid tenant slug");
|
||||
}
|
||||
|
||||
return {
|
||||
corpId,
|
||||
accessToken: accessTokens[0]!
|
||||
};
|
||||
}
|
||||
|
||||
export async function exchangeHoseAssistLink(
|
||||
value: string | HoseAssistLink
|
||||
): Promise<HoseAssistSealSession> {
|
||||
const link = typeof value === "string" ? parseHoseAssistLink(value) : normalizeHoseAssistLink(value);
|
||||
const sealUrl = `https://${link.corpId}.sealai.cc`;
|
||||
const sealResponse = await ky
|
||||
.get(`${sealUrl}/api/auth/oauth2/session/oem-hosecloud`, {
|
||||
searchParams: {
|
||||
token: link.accessToken,
|
||||
returnToken: "1"
|
||||
},
|
||||
timeout: 30000
|
||||
})
|
||||
.json<SealTokenResponse>();
|
||||
|
||||
const token =
|
||||
sealResponse.token ??
|
||||
sealResponse.accessToken ??
|
||||
sealResponse.data?.token ??
|
||||
sealResponse.data?.accessToken;
|
||||
if (!token) {
|
||||
throw new Error("Seal SSO did not return a bearer token");
|
||||
}
|
||||
|
||||
const expiresIn =
|
||||
sealResponse.expiresIn ??
|
||||
sealResponse.expires_in ??
|
||||
sealResponse.data?.expiresIn ??
|
||||
sealResponse.data?.expires_in ??
|
||||
3600;
|
||||
|
||||
return {
|
||||
corpId: link.corpId,
|
||||
sealUrl,
|
||||
token,
|
||||
expiresIn: Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : 3600
|
||||
};
|
||||
}
|
||||
|
||||
export function assertHoseAssistTenantMatches(corpId: string, tenant: Record<string, unknown>): void {
|
||||
const hoseCorpConfig = tenant.hoseCorpConfig && typeof tenant.hoseCorpConfig === "object"
|
||||
? tenant.hoseCorpConfig as Record<string, unknown>
|
||||
: undefined;
|
||||
const candidates = [tenant.tenantSlug, hoseCorpConfig?.corporationId]
|
||||
.filter((value): value is string => typeof value === "string" && Boolean(value));
|
||||
if (candidates.length > 0 && !candidates.some((value) => value.toLowerCase() === corpId)) {
|
||||
throw new Error("Hose assistance link tenant mismatch: the Seal tenant does not match ekbCorpId");
|
||||
}
|
||||
}
|
||||
|
||||
function isHoseAssistHost(hostname: string): boolean {
|
||||
const normalized = hostname.toLowerCase();
|
||||
return HOSE_ASSIST_HOST_SUFFIXES.some((suffix) => normalized.endsWith(suffix));
|
||||
}
|
||||
|
||||
function normalizeHoseAssistLink(value: HoseAssistLink): HoseAssistLink {
|
||||
const corpId = typeof value?.corpId === "string" ? value.corpId.trim().toLowerCase() : "";
|
||||
const accessToken = typeof value?.accessToken === "string" ? value.accessToken.trim() : "";
|
||||
if (!CORP_ID_PATTERN.test(corpId) || !accessToken) {
|
||||
throw new Error("Invalid Hose assistance link: accessToken and ekbCorpId are required");
|
||||
}
|
||||
return {
|
||||
corpId,
|
||||
accessToken
|
||||
};
|
||||
}
|
||||
|
||||
function isFresh(entry: TokenEntry | undefined, refreshTtl = 60): entry is TokenEntry {
|
||||
return Boolean(entry && Date.now() < entry.expiresAt - refreshTtl * 1000);
|
||||
}
|
||||
|
||||
@@ -32,8 +32,12 @@ export async function createSealClient(corp: CorpConfig): Promise<KyInstance> {
|
||||
export async function createSealClientForToken(corp: CorpConfig, token: string): Promise<KyInstance> {
|
||||
const session = await getSealSessionForCorp(corp);
|
||||
|
||||
return createSealClientForUrl(session.enterprise.sealUrl, token);
|
||||
}
|
||||
|
||||
export function createSealClientForUrl(sealUrl: string, token: string): KyInstance {
|
||||
return ky.create({
|
||||
prefix: session.enterprise.sealUrl,
|
||||
prefix: sealUrl.replace(/\/+$/, ""),
|
||||
timeout: 30000,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`
|
||||
|
||||
Reference in new issue
Block a user