431 lines
15 KiB
TypeScript
431 lines
15 KiB
TypeScript
import { assertHoseAssistTenantMatches, exchangeHoseAssistLink, getHoseProvisionalAuthLink } from "../../core/auth/hose.js";
|
|
import { clearCorpTokenCache } from "../../core/auth/token-store.js";
|
|
import { formatBeijingIso } from "../../core/config/timestamps.js";
|
|
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 { createDelegation, getMe } from "../../domains/seal/api.js";
|
|
import {
|
|
booleanOption,
|
|
parseDelegationExpireHours,
|
|
parseHoseExpireSeconds,
|
|
stringOption
|
|
} from "../parser.js";
|
|
import { outputOptions, printJson, redactSensitiveText } from "../printer.js";
|
|
import type { ParsedArgs } from "../types.js";
|
|
import { runCapability, runCapabilityResult } from "../helpers.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 hose-extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--name <customName>] [--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 | null, args: ParsedArgs) {
|
|
const subAction = args.command[2]?.toLowerCase();
|
|
const fromLink = stringOption(args.options["from-link"]) ?? (subAction === "from-link" ? args.command[3] : undefined);
|
|
|
|
if ((action === "seal-link" || action === "link" || (action === "hose-link" && corp?.source?.type === "seal")) && fromLink) {
|
|
const note = stringOption(args.options.note);
|
|
const expireOption = args.options.expire ?? args.options["expires-in"] ?? args.options.expiresIn;
|
|
const expiresInHours = parseDelegationExpireHours(expireOption, 24);
|
|
const session = await exchangeHoseAssistLink(fromLink);
|
|
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, expiresInHours });
|
|
|
|
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,
|
|
expiresAt: formatBeijingIso(Date.now() + expiresInHours * 3600 * 1000)
|
|
});
|
|
return;
|
|
}
|
|
|
|
if (!corp) {
|
|
throw new Error(`auth ${action ?? ""} requires an enterprise. Provide --corp <id> or select one.`);
|
|
}
|
|
|
|
if (action === "check" || action === "diagnose" || action === "status" || action === "test" || action === "doctor") {
|
|
printJson(await diagnoseAuth(corp));
|
|
return;
|
|
}
|
|
|
|
if (action === "seal-link" || action === "link" || (action === "hose-link" && corp.source?.type === "seal")) {
|
|
const client = await createSealClient(corp);
|
|
|
|
if (subAction === "list") {
|
|
await runCapability("sealDelegationList", client, corp, {}, outputOptions(args.options));
|
|
return;
|
|
}
|
|
|
|
if (subAction === "revoke") {
|
|
const tokenId = args.command[3] ?? stringOption(args.options.tokenId) ?? stringOption(args.options.id);
|
|
if (!tokenId) throw new Error("Usage: seal-use auth link revoke <tokenId>");
|
|
await runCapability("sealDelegationRevoke", client, corp, { tokenId }, outputOptions(args.options));
|
|
return;
|
|
}
|
|
|
|
const note = stringOption(args.options.note) ?? "CLI generated provisional access link";
|
|
const expireOption = args.options.expire ?? args.options["expires-in"] ?? args.options.expiresIn;
|
|
const expiresInHours = parseDelegationExpireHours(expireOption, 24);
|
|
const delegation = await runCapabilityResult(
|
|
"sealDelegationCreate",
|
|
client,
|
|
corp,
|
|
{ note, expiresInHours }
|
|
);
|
|
if (action === "hose-link") {
|
|
console.error(`👉 提示: 企业「${corp.name}」源类型为 Seal 原生测试环境,已自动为您生成委托免登直达链接。`);
|
|
}
|
|
const delegationRecord = delegation as Record<string, unknown>;
|
|
const staffName = "staffName" in corp.source && typeof corp.source.staffName === "string" ? corp.source.staffName : undefined;
|
|
const expiresAt = formatBeijingIso(Date.now() + expiresInHours * 3600 * 1000);
|
|
printJson({
|
|
id: delegationRecord.id,
|
|
corpId: corp.source.corpId ?? corp.id,
|
|
corpName: corp.name,
|
|
staffId: corp.source.staffId,
|
|
...(staffName ? { staffName } : {}),
|
|
link: delegationRecord.link,
|
|
expiresAt,
|
|
token: delegationRecord.token
|
|
});
|
|
return;
|
|
}
|
|
|
|
if (action === "hose-link") {
|
|
const rawExpire = args.options.expire ?? args.options["expires-in"] ?? args.options.expiresIn;
|
|
const expiresIn = parseHoseExpireSeconds(rawExpire, 7200);
|
|
const force =
|
|
booleanOption(args.options.force) === true ||
|
|
booleanOption(args.options.refresh) === true ||
|
|
booleanOption(args.options.f) === true;
|
|
const provisional = await getHoseProvisionalAuthLink(corp, expiresIn, { force });
|
|
const staffName = "staffName" in corp.source && typeof corp.source.staffName === "string" ? corp.source.staffName : undefined;
|
|
const expiresAt = formatBeijingIso(Date.now() + expiresIn * 1000);
|
|
printJson({
|
|
corpId: corp.source.corpId ?? corp.id,
|
|
corpName: corp.name,
|
|
staffId: corp.source.staffId,
|
|
...(staffName ? { staffName } : {}),
|
|
link: provisional.url,
|
|
expiresAt,
|
|
token: provisional.token
|
|
});
|
|
return;
|
|
}
|
|
|
|
if (action === "keys" || action === "hose-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.`);
|
|
}
|
|
|
|
async function diagnoseAuth(corp: CorpConfig) {
|
|
if (corp.source.type !== "hose") {
|
|
const client = await createSealClient(corp);
|
|
const me = await getMe(client);
|
|
return {
|
|
corp: {
|
|
id: corp.id,
|
|
name: corp.name,
|
|
sourceType: corp.source.type
|
|
},
|
|
ok: true,
|
|
stages: [
|
|
{
|
|
name: "seal.whoami",
|
|
ok: true,
|
|
user: me.user,
|
|
tenant: me.tenant
|
|
}
|
|
]
|
|
};
|
|
}
|
|
|
|
clearCorpTokenCache(corp.id);
|
|
const source = corp.source;
|
|
const appKey = source.appKey ?? source.key;
|
|
const appSecurity = source.appSecurity ?? source.password;
|
|
const sealUrl = (corp.seal.url ?? source.sealUrl ?? `https://${source.corpId.toLowerCase()}.sealai.cc`).replace(/\/+$/, "");
|
|
const uid = source.staffId.includes(":") ? source.staffId : `${source.corpId}:${source.staffId}`;
|
|
const stages: Array<Record<string, unknown>> = [];
|
|
|
|
if ((!appKey || !appSecurity) && !source.closeToken) {
|
|
return {
|
|
corp: {
|
|
id: corp.id,
|
|
name: corp.name,
|
|
sourceType: corp.source.type
|
|
},
|
|
ok: false,
|
|
stages: [
|
|
{
|
|
name: "hose.openapi",
|
|
ok: false,
|
|
error: "Hose source requires appKey/key and appSecurity/password"
|
|
}
|
|
]
|
|
};
|
|
}
|
|
|
|
const openapi = appKey && appSecurity
|
|
? await runDiagnoseStage("hose.openapi", async () => {
|
|
const json = await postJson(`${source.domain.replace(/\/+$/, "")}/api/openapi/v1/auth/getAccessToken`, {
|
|
appKey,
|
|
appSecurity
|
|
});
|
|
const value = objectValue(json.value);
|
|
const token = stringValue(value.accessToken) ?? stringValue(json.accessToken) ?? stringValue(json.token);
|
|
if (!token) throw new Error("Hose login did not return an access token");
|
|
return {
|
|
token,
|
|
public: {
|
|
corporationId: stringValue(value.corporationId) ?? stringValue(objectValue(value.corporation).id),
|
|
expireTime: numberValue(value.expireTime)
|
|
}
|
|
};
|
|
})
|
|
: undefined;
|
|
if (openapi) stages.push(openapi.public);
|
|
|
|
const openapiToken = openapi?.private?.token;
|
|
const provisional = source.closeToken
|
|
? {
|
|
public: {
|
|
name: "hose.closeapi",
|
|
ok: true,
|
|
corpId: source.corpId,
|
|
staffId: source.staffId,
|
|
configured: true,
|
|
expiresAt: source.expiresAt
|
|
},
|
|
private: { token: source.closeToken }
|
|
}
|
|
: openapiToken
|
|
? await runDiagnoseStage("hose.provisional", async () => {
|
|
const json = await postJson(
|
|
`${source.domain.replace(/\/+$/, "")}/api/openapi/v1.1/provisional/getProvisionalAuth?accessToken=${encodeURIComponent(openapiToken)}`,
|
|
{
|
|
uid,
|
|
pageType: "home",
|
|
expireDate: 7200
|
|
}
|
|
);
|
|
const url = stringValue(objectValue(json.value).message);
|
|
if (!url) throw new Error("Hose CloseAPI did not return a provisional auth URL");
|
|
const token = new URL(url).searchParams.get("accessToken");
|
|
if (!token) throw new Error("Hose provisional auth URL did not include accessToken");
|
|
return {
|
|
token,
|
|
public: {
|
|
uid,
|
|
enterpriseUrl: redactSensitiveText(url)
|
|
}
|
|
};
|
|
})
|
|
: skippedStage("hose.provisional");
|
|
stages.push(provisional.public);
|
|
|
|
const sealCustomHeaders = resolveSealCustomHeaders(corp.seal);
|
|
const provisionalToken = provisional.private?.token;
|
|
const sealSession = provisionalToken
|
|
? await runDiagnoseStage("seal.sso", async () => {
|
|
const client = createSealClientForUrl(sealUrl, undefined, sealCustomHeaders);
|
|
const json = await client
|
|
.get(
|
|
`api/auth/oauth2/session/oem-hosecloud?token=${encodeURIComponent(provisionalToken)}&returnToken=1`
|
|
)
|
|
.json<Record<string, unknown>>();
|
|
const data = objectValue(json.data);
|
|
const token =
|
|
stringValue(json.token) ??
|
|
stringValue(json.accessToken) ??
|
|
stringValue(data.token) ??
|
|
stringValue(data.accessToken);
|
|
if (!token) throw new Error("Seal SSO did not return a bearer token");
|
|
return {
|
|
token,
|
|
public: {
|
|
sealUrl,
|
|
expiresIn: numberValue(json.expiresIn) ?? numberValue(json.expires_in) ?? numberValue(data.expiresIn) ?? numberValue(data.expires_in)
|
|
}
|
|
};
|
|
})
|
|
: skippedStage("seal.sso");
|
|
stages.push(sealSession.public);
|
|
|
|
const sealToken = sealSession.private?.token;
|
|
const whoami = sealToken
|
|
? await runDiagnoseStage("seal.whoami", async () => {
|
|
const client = createSealClientForUrl(sealUrl, sealToken, sealCustomHeaders);
|
|
const json = await client.get("api/v1/auth/me").json<Record<string, unknown>>();
|
|
const data = objectValue(json.data);
|
|
const user = objectValue(data.user ?? json.user);
|
|
const tenant = objectValue(data.tenant ?? json.tenant);
|
|
return {
|
|
public: {
|
|
user: {
|
|
id: stringValue(user.id),
|
|
name: stringValue(user.name),
|
|
isAdmin: booleanValue(user.isAdmin),
|
|
providerUserId: stringValue(user.providerUserId)
|
|
},
|
|
tenant: {
|
|
id: stringValue(tenant.id),
|
|
name: stringValue(tenant.name),
|
|
tenantSlug: stringValue(tenant.tenantSlug),
|
|
hoseCorpConfig: summarizeHoseCorpConfig(tenant.hoseCorpConfig)
|
|
}
|
|
}
|
|
};
|
|
})
|
|
: skippedStage("seal.whoami");
|
|
stages.push(whoami.public);
|
|
|
|
return {
|
|
corp: {
|
|
id: corp.id,
|
|
name: corp.name,
|
|
sourceType: corp.source.type
|
|
},
|
|
ok: stages.every((stage) => stage.ok === true),
|
|
stages
|
|
};
|
|
}
|
|
|
|
type DiagnoseStageResult = {
|
|
public: Record<string, unknown>;
|
|
private?: {
|
|
token?: string;
|
|
};
|
|
};
|
|
|
|
async function runDiagnoseStage(
|
|
name: string,
|
|
action: () => Promise<{ public: Record<string, unknown>; token?: string }>
|
|
): Promise<DiagnoseStageResult> {
|
|
try {
|
|
const result = await action();
|
|
return {
|
|
public: {
|
|
name,
|
|
ok: true,
|
|
...compactObject(result.public)
|
|
},
|
|
private: result.token ? { token: result.token } : undefined
|
|
};
|
|
} catch (error) {
|
|
return {
|
|
public: {
|
|
name,
|
|
ok: false,
|
|
error: redactSensitiveText(error instanceof Error ? error.message : String(error))
|
|
}
|
|
};
|
|
}
|
|
}
|
|
|
|
function skippedStage(name: string): DiagnoseStageResult {
|
|
return {
|
|
public: {
|
|
name,
|
|
ok: false,
|
|
skipped: true
|
|
}
|
|
};
|
|
}
|
|
|
|
async function postJson(url: string, body: Record<string, unknown>): Promise<Record<string, unknown>> {
|
|
const response = await fetch(url, {
|
|
method: "POST",
|
|
headers: {
|
|
"content-type": "application/json"
|
|
},
|
|
body: JSON.stringify(body)
|
|
});
|
|
return parseJsonResponse(response);
|
|
}
|
|
|
|
async function parseJsonResponse(response: Response): Promise<Record<string, unknown>> {
|
|
const body = await response.text();
|
|
if (!response.ok) {
|
|
throw new Error(`${response.status} ${body}`);
|
|
}
|
|
const json = JSON.parse(body) as unknown;
|
|
return objectValue(json);
|
|
}
|
|
|
|
function objectValue(value: unknown): Record<string, unknown> {
|
|
return value && typeof value === "object" && !Array.isArray(value)
|
|
? (value as Record<string, unknown>)
|
|
: {};
|
|
}
|
|
|
|
function stringValue(value: unknown): string | undefined {
|
|
return typeof value === "string" && value ? value : undefined;
|
|
}
|
|
|
|
function numberValue(value: unknown): number | undefined {
|
|
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
}
|
|
|
|
function booleanValue(value: unknown): boolean | undefined {
|
|
return typeof value === "boolean" ? value : undefined;
|
|
}
|
|
|
|
function summarizeHoseCorpConfig(value: unknown) {
|
|
const config = objectValue(value);
|
|
return compactObject({
|
|
corporationId: stringValue(config.corporationId),
|
|
corporationName: stringValue(config.corporationName)
|
|
});
|
|
}
|
|
|
|
function compactObject<T extends Record<string, unknown>>(value: T): T {
|
|
return Object.fromEntries(
|
|
Object.entries(value).filter(([, item]) => item !== undefined)
|
|
) as T;
|
|
}
|
|
|
|
export { formatBeijingIso } from "../../core/config/timestamps.js";
|
|
|