import { canRefreshCorpAccessToken, fullPasswordLogin, fullSmsLogin, fullBrowserSyncLogin, hasOpenApiPersistentCredentials, sendSmsVerificationCode, importCredentials, importF12Credentials, importFromLink, parseHeadersOrCurl, refreshAccountCorporations, refreshSingleCorpAccessToken, } from "../../core/auth/login.js"; import { listAccounts, getActiveAccount, setActiveAccount, } from "../../core/auth/account-store.js"; import { createSessionClient } from "../../core/http/session-client.js"; import { stringOption, booleanOption } from "../parser.js"; import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js"; import { prompt } from "../helpers.js"; import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js"; import { handleAddPersistent, handleElevateCorp, handleExtractKeys, handleGenerateCorpLink, handleSyncFromSeal, resolveTargetCorpByArgOrContext, } from "./corps/index.js"; import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js"; function isHttpUrl(val?: string): boolean { return Boolean(val && /^https?:\/\//i.test(val.trim())); } export async function handleAuthCommand( parsed: CliParsedArgs, runtime: CliRuntime ): Promise { const action = parsed.action || "status"; switch (action) { case "login": return handleLogin(parsed, runtime); case "status": case "whoami": case "current": return handleStatus(parsed, runtime); case "refresh": case "renew": return handleRefresh(parsed, runtime); case "import": case "add": return handleImport(parsed, runtime); case "add-link": case "import-link": return handleAddLink(parsed, runtime); case "link": { const maybeUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]); if (isHttpUrl(maybeUrl)) { return handleAddLink(parsed, runtime); } return handleGenerateCorpLink(parsed, runtime); } case "hose-link": case "auth-link": case "login-link": return handleGenerateCorpLink(parsed, runtime); case "add-persistent": case "add-hose-persistent": case "add-openapi": case "add-hose": return handleAddPersistent(parsed, runtime); case "extract-keys": case "extract-key": case "hose-extract-keys": case "extract-hose-keys": return handleExtractKeys(parsed, runtime); case "elevate": case "elevate-hose": return handleElevateCorp(parsed, runtime); case "sync-seal": case "sync-from-seal": case "import-seal": return handleSyncFromSeal(parsed, runtime); case "accounts": case "list": case "account": case "accs": return handleAccounts(parsed, runtime); case "switch-account": case "switch": case "use-account": return handleSwitchAccount(parsed, runtime); default: return { stdout: "", stderr: `未知 auth 子命令: ${action}。支持: login, status, refresh, import, link, add-link, add-persistent, extract-keys, elevate, sync-seal, accounts, switch-account\n`, exitCode: 1, }; } } async function handleLogin(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const phone = stringOption(parsed.options, ["phone", "p"]); const password = stringOption(parsed.options, ["password", "pwd"]); const isSms = booleanOption(parsed.options, ["sms"]); const isSync = booleanOption(parsed.options, ["sync"]); const isInteractive = booleanOption(parsed.options, ["interactive", "i"]) || (!phone && !password && !isSms && !isSync); if (isDryRun(parsed, runtime)) { return mutationPreview(parsed, runtime, "登录并保存企业凭证", phone || (isSync ? "浏览器会话" : "交互式登录"), { mode: isSync ? "browser-sync" : isSms ? "sms" : "password", saveAll: true, }); } requireMutationConfirmation(parsed, runtime, "登录并保存企业凭证", `hose-use auth login${phone ? ` --phone=${phone}` : ""} --yes`); // 1. 浏览器同步 if (isSync) { const res = await fullBrowserSyncLogin({ saveAll: true }); if (runtime.jsonMode) { return { stdout: printJson(res), stderr: "", exitCode: 0 }; } return { stdout: `[SUCCESS] 成功从浏览器会话同步企业凭证!\n默认企业: ${res.selectedCorp.name} (${res.selectedCorp.id})\n共保存企业: ${res.allCorps.length} 家\n`, stderr: "", exitCode: 0, }; } // 2. 短信验证码登录 if (isSms) { const inputPhone = phone || (await prompt("请输入手机号: ")); if (!inputPhone) return { stdout: "", stderr: "手机号不能为空\n", exitCode: 1 }; let codeId: string | undefined; try { const sendRes = await sendSmsVerificationCode({ phone: inputPhone }); codeId = sendRes.codeId; console.log("短信验证码已发送!"); } catch (e) { console.log("若触发了人机验证,请在浏览器中获取验证码后直接在下方输入。"); } const code = await prompt("请输入收到的 6 位短信验证码: "); if (!code) return { stdout: "", stderr: "验证码不能为空\n", exitCode: 1 }; const res = await fullSmsLogin({ phone: inputPhone, code, codeId, saveAll: true, }); if (runtime.jsonMode) { return { stdout: printJson(res), stderr: "", exitCode: 0 }; } return { stdout: `[SUCCESS] 短信验证码登录成功!\n账号: ${res.accountId}\n默认企业: ${res.selectedCorp.name} (${res.selectedCorp.id})\n共保存企业: ${res.allCorps.length} 家\n`, stderr: "", exitCode: 0, }; } // 3. 账号密码登录 const inputPhone = phone || (isInteractive ? await prompt("请输入手机号: ") : ""); const inputPassword = password || (isInteractive ? await prompt("请输入密码: ") : ""); if (!inputPhone || !inputPassword) { return { stdout: "", stderr: "手机号和密码不能为空\n", exitCode: 1 }; } const res = await fullPasswordLogin({ phone: inputPhone, password: inputPassword, saveAll: true, }); if (runtime.jsonMode) { return { stdout: printJson(res), stderr: "", exitCode: 0 }; } const rows = res.allCorps.map((c, i) => [ i + 1, c.id, c.name, c.credentials.staffId, ]); const table = printTable(["#", "企业 ID", "企业名称", "员工工号"], rows); return { stdout: `[SUCCESS] 账密登录成功!\n账号: ${res.accountId}\n默认企业: ${res.selectedCorp.name} (${res.selectedCorp.id})\n共保存企业配置: ${res.allCorps.length} 家\n\n${table}\n`, stderr: "", exitCode: 0, }; } async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const currentCorp = runtime.selectedCorp; const activeAccount = getActiveAccount(); let sessionValid = false; let sessionData: unknown = null; if (currentCorp) { try { const client = await createSessionClient(currentCorp); const res = await client.get("api/account/v2/session").json<{ value?: unknown }>(); sessionValid = !!res.value; sessionData = res.value; } catch { sessionValid = false; } } const hasOpenApi = hasOpenApiPersistentCredentials(currentCorp); const isPersistent = canRefreshCorpAccessToken(currentCorp); const statusObj = { activeAccount: activeAccount?.accountId || null, currentCorp: currentCorp ? { id: currentCorp.id, name: currentCorp.name, staffId: currentCorp.credentials.staffId, source: currentCorp.source, accountId: currentCorp.accountId, persistent: isPersistent, hasOpenApiKey: hasOpenApi, tokenValid: sessionValid, } : null, session: sessionData, }; if (runtime.jsonMode) { return { stdout: printJson(statusObj), stderr: "", exitCode: 0 }; } const pairs: Record = { "当前活跃账号": activeAccount?.accountId || "未登录", "当前激活企业": currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "未配置", "当前员工工号": currentCorp?.credentials.staffId || "-", "员工真实姓名": currentCorp?.staffName || currentCorp?.session?.staffName || "-", "凭证来源类型": formatSourceLabel(currentCorp?.source, hasOpenApi), "持久化状态": isPersistent ? hasOpenApi ? `✅ OpenAPI 持久化密钥 (${currentCorp?.credentials.appKey})` : "✅ 统一认证主账号自动换票" : "⚪ 短期会话", "Token 有效性": sessionValid ? "✅ 有效 (已通过 Session 验证)" : "❌ 无效或未连接", "Token 过期时间": formatExpiresAt(currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime, isPersistent), }; if (currentCorp?.session) { if (currentCorp.session.loginTime) { pairs["会话创建时间"] = new Date(currentCorp.session.loginTime).toLocaleString("zh-CN", { hour12: false }); } if (currentCorp.session.platform) { pairs["官方平台类型"] = currentCorp.session.platform; } if (currentCorp.session.isAssistPlatform) { pairs["协助调试模式"] = "是 (Assist Platform)"; if (currentCorp.session.operationUserName || currentCorp.session.operationUserId) { pairs["协助操作人员"] = `${currentCorp.session.operationUserName || ""} (${currentCorp.session.operationUserId || ""})`.trim(); } if (currentCorp.session.assistId) { pairs["协助会话 ID"] = currentCorp.session.assistId; } } if (currentCorp.session.cellphone) { pairs["绑定手机号码"] = currentCorp.session.cellphone; } if (currentCorp.session.isAdmin !== undefined) { pairs["是否企业管理"] = currentCorp.session.isAdmin ? "是" : "否"; } } const summary = printKeyValue(pairs); return { stdout: `====== 当前登录与企业状态 ======\n${summary}\n`, stderr: "", exitCode: 0, }; } async function handleRefresh(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const accountId = stringOption(parsed.options, ["account", "a"]); const explicitCorp = parsed.args[0] || stringOption(parsed.options, ["corp"]); const targetCorp = explicitCorp ? resolveTargetCorpByArgOrContext(explicitCorp, runtime) : !accountId && !getActiveAccount() && runtime.selectedCorp && canRefreshCorpAccessToken(runtime.selectedCorp) ? runtime.selectedCorp : null; if (targetCorp && !accountId) { if (isDryRun(parsed, runtime)) { return mutationPreview(parsed, runtime, "刷新单企业凭证", `${targetCorp.name} (${targetCorp.id})`, { corpId: targetCorp.id, hasOpenApiKey: hasOpenApiPersistentCredentials(targetCorp), }); } requireMutationConfirmation( parsed, runtime, "刷新单企业凭证", `hose-use auth refresh ${targetCorp.id} --yes` ); const newToken = await refreshSingleCorpAccessToken(targetCorp); if (!newToken) { return { stdout: "", stderr: `刷新企业 [${targetCorp.name} (${targetCorp.id})] AccessToken 失败:缺少可用的账号凭证或 OpenAPI 持久化密钥\n`, exitCode: 1, }; } if (runtime.jsonMode) { return { stdout: printJson({ corpId: targetCorp.id, corpName: targetCorp.name, refreshed: true, expiresAt: targetCorp.auth?.expiresAt, }), stderr: "", exitCode: 0, }; } return { stdout: `[SUCCESS] 成功刷新企业 [${targetCorp.name} (${targetCorp.id})] 的 AccessToken!\n`, stderr: "", exitCode: 0, }; } if (isDryRun(parsed, runtime)) { return mutationPreview(parsed, runtime, "刷新账号下企业凭证", accountId || "当前账号", { saveAll: true }); } requireMutationConfirmation(parsed, runtime, "刷新账号下企业凭证", `hose-use auth refresh${accountId ? ` --account=${accountId}` : ""} --yes`); const res = await refreshAccountCorporations(accountId, { saveAll: true }); if (runtime.jsonMode) { return { stdout: printJson(res), stderr: "", exitCode: 0 }; } return { stdout: `[SUCCESS] 成功批量刷新账号 ${res.accountId} 下的所有企业 AccessToken!\n共刷新企业: ${res.allCorps.length} 家\n`, stderr: "", exitCode: 0, }; } async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise { let raw = parsed.args[0] || stringOption(parsed.options, ["raw", "headers", "curl", "url", "link"]); let accessToken = stringOption(parsed.options, ["token", "accessToken"]); let corpId = stringOption(parsed.options, ["corp", "corpId"]); let staffId = stringOption(parsed.options, ["staff", "staffId"]); let name = stringOption(parsed.options, ["name"]); const overwrite = booleanOption(parsed.options, ["overwrite", "force", "f"], false); const ttl = stringOption(parsed.options, ["ttl"]); const expires = stringOption(parsed.options, ["expires", "days"]); const elevate = booleanOption(parsed.options, ["elevate", "elevate-hose", "as-hose"], false); const noElevate = booleanOption(parsed.options, ["no-elevate"], false); const appKey = stringOption(parsed.options, ["app-key", "appKey"]); const keyId = stringOption(parsed.options, ["key-id", "keyId"]); const force = booleanOption(parsed.options, ["force", "f"], false); if (isDryRun(parsed, runtime)) { return mutationPreview(parsed, runtime, "导入并保存企业凭证", corpId || "待解析企业", { source: raw ? "captured-input" : "manual-input", elevate: elevate ? "required" : noElevate ? "disabled" : "auto-best-effort", overwrite, ttl: ttl || null, expires: expires || null, }); } requireMutationConfirmation(parsed, runtime, "导入并保存企业凭证", `hose-use auth ${parsed.action || "import"} --yes`); if (!raw && !accessToken && process.stdin.isTTY) { raw = await prompt("请粘贴抓包文本 / cURL 命令行 / 协助免密 URL (直接回车则手动逐项输入): "); } let baseUrl: string | undefined; if (raw) { const parsedObj = parseHeadersOrCurl(raw); if (parsedObj.accessToken) accessToken = parsedObj.accessToken; if (parsedObj.corpId) corpId = parsedObj.corpId; if (parsedObj.staffId) staffId = parsedObj.staffId; if (parsedObj.baseUrl) baseUrl = parsedObj.baseUrl; } if (!accessToken && process.stdin.isTTY) accessToken = await prompt("请输入 accessToken: "); if (!corpId && process.stdin.isTTY) corpId = await prompt("请输入 corpId: "); if (!accessToken || !corpId) { return { stdout: "", stderr: "accessToken 与 corpId 均为必填!\n", exitCode: 1 }; } try { const imported = await importCredentials({ accessToken, corpId, staffId, name, baseUrl, overwrite, ttl, expires, appKey, keyId, elevate: elevate ? true : noElevate ? false : undefined, autoElevate: !noElevate, force, source: raw && (raw.startsWith("http://") || raw.startsWith("https://")) ? "link" : undefined, }); if (runtime.jsonMode) { return { stdout: printJson(imported, runtime.outputOptions), stderr: "", exitCode: 0 }; } const hasOpenApi = hasOpenApiPersistentCredentials(imported); const summaryPairs: Record = { "企业名称": imported.name, "企业 ID": imported.id, "集群环境": imported.cluster || "app", "员工工号": imported.credentials.staffId, "员工姓名": imported.staffName || imported.session?.staffName || "-", "手机号码": imported.session?.cellphone || "-", "是否管理": imported.session?.isAdmin ? "是" : "否", "凭证来源": formatSourceLabel(imported.source, hasOpenApi), "持久化密钥": hasOpenApi ? `✅ 已自动提权持久化 (appKey: ${imported.credentials.appKey})` : "⚪ 未提取到 OpenAPI 密钥 (短期会话)", "服务节点": imported.baseUrl, "过期时间": formatExpiresAt(imported.auth?.expiresAt || imported.session?.expTime, hasOpenApi), "保存路径": `enterprises/${imported.id}.json`, }; if (imported.session?.isAssistPlatform) { summaryPairs["协助平台"] = "是 (Assist Platform 调试授权)"; if (imported.session.operationUserName || imported.session.operationUserId) { summaryPairs["协助操作人"] = `${imported.session.operationUserName || ""} (${imported.session.operationUserId || ""})`.trim(); } if (imported.session.assistId) { summaryPairs["协助会话 ID"] = imported.session.assistId; } } const summaryText = printKeyValue(summaryPairs); return { stdout: `[SUCCESS] 成功导入并保存企业凭证!\n${summaryText}\n`, stderr: "", exitCode: 0, }; } catch (error) { return { stdout: "", stderr: `[ERROR] 导入凭证失败: ${error instanceof Error ? error.message : String(error)}\n`, exitCode: 1, }; } } async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const linkUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]); return handleImport({ ...parsed, args: linkUrl ? [linkUrl] : [] }, runtime); } async function handleAccounts(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const accounts = listAccounts(); const active = getActiveAccount(); if (runtime.jsonMode) { return { stdout: printJson({ activeAccountId: active?.accountId, accounts }), stderr: "", exitCode: 0, }; } if (accounts.length === 0) { return { stdout: "暂无保存的账号,请使用 hose-use auth login 登录\n", stderr: "", exitCode: 0 }; } const rows = accounts.map((acc, i) => [ acc.accountId === active?.accountId ? `* ${i + 1}` : ` ${i + 1}`, acc.accountId, acc.userId || "-", acc.corporations.length, new Date(acc.updatedAt).toLocaleString(), ]); const table = printTable(["#", "账号标识", "用户 ID", "关联企业数", "最近更新时间"], rows); return { stdout: `====== 本地已保存账号列表 ======\n${table}\n`, stderr: "", exitCode: 0 }; } async function handleSwitchAccount(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const target = parsed.args[0] || stringOption(parsed.options, ["account", "a"]); if (!target) { return { stdout: "", stderr: "用法: hose-use auth switch-account \n", exitCode: 1 }; } if (isDryRun(parsed, runtime)) { return mutationPreview(parsed, runtime, "切换当前活跃账号", target, { activeAccountId: target }); } requireMutationConfirmation(parsed, runtime, "切换当前活跃账号", `hose-use auth switch-account ${target} --yes`); const success = setActiveAccount(target); if (!success) { return { stdout: "", stderr: `未找到账号: ${target}\n`, exitCode: 1 }; } return { stdout: `[SUCCESS] 当前活跃主账号已切换至: ${target}\n`, stderr: "", exitCode: 0, }; }