feat(assist-platform): 固化钉钉扫码登录闭环并优化多集群与网关错误解析
- 支持一行命令自动发起钉钉交互式扫码登录 (hose-use assist-platform login [--qr]) - 集成 qrcode-terminal 在终端直接输出紧凑 ANSI 文本二维码 - 严格对齐 HoseCloud SSO 钉钉时间戳的 60 秒安全防重放倒计时 - 自动从重定向参数或 Token 换取 Unity 运营中心会话凭证并安全落盘 - 在 core/http/assist-platform-client 增加响应体 errorCode: 403 拦截,杜绝凭证过期被吞成空数据的静默失败 - 修复 assist-platform enter 多集群租户 (wx2/shanghai 等) baseUrl 硬编码为 app 的验票失败问题 - 修复 workflow nodes grant 网关回包双层嵌套 saved/skipped 数据解析问题 - 补全 core/http/sso-client 单元测试并确保全部 957 项测试通过
This commit is contained in:
1 parent
eb9b979943
commit
95af2177e5
10 files changed
+555
-29
No files matched your search
@@ -9,6 +9,7 @@
|
||||
"@modelcontextprotocol/core": "^2.0.0",
|
||||
"@modelcontextprotocol/server": "^2.0.0",
|
||||
"ky": "^2.0.2",
|
||||
"qrcode-terminal": "^0.12.0",
|
||||
"quickjs-emscripten-core": "0.32.0",
|
||||
"yaml": "^2.9.0",
|
||||
"zod": "^4.4.3",
|
||||
@@ -16,6 +17,7 @@
|
||||
"devDependencies": {
|
||||
"@modelcontextprotocol/client": "^2.0.0",
|
||||
"@types/bun": "^1.3.14",
|
||||
"@types/qrcode-terminal": "^0.12.2",
|
||||
"typescript": "^5.9.3",
|
||||
},
|
||||
},
|
||||
@@ -35,6 +37,8 @@
|
||||
|
||||
"@types/node": ["@types/node@25.8.0", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-TCFSk8IZh+iLX1xtksoBVtdmgL+1IX0fC9BeU4QqFSuNdN/K+HUlhqOzEmSYYpZUVsLYcPqc9KX+60iDuninSQ=="],
|
||||
|
||||
"@types/qrcode-terminal": ["@types/qrcode-terminal@0.12.2", "", {}, "sha512-v+RcIEJ+Uhd6ygSQ0u5YYY7ZM+la7GgPbs0V/7l/kFs2uO4S8BcIUEMoP7za4DNIqNnUD5npf0A/7kBhrCKG5Q=="],
|
||||
|
||||
"bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
|
||||
|
||||
"cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
|
||||
@@ -53,6 +57,8 @@
|
||||
|
||||
"pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
|
||||
|
||||
"qrcode-terminal": ["qrcode-terminal@0.12.0", "", { "bin": { "qrcode-terminal": "./bin/qrcode-terminal.js" } }, "sha512-EXtzRZmC+YGmGlDFbXKxQiMZNwCLEO6BANKXG4iCtSIM0yqc/pappSx3RIKr4r0uh5JsBckOXeKrB3Iz7mdQpQ=="],
|
||||
|
||||
"quickjs-emscripten-core": ["quickjs-emscripten-core@0.32.0", "", { "dependencies": { "@jitl/quickjs-ffi-types": "0.32.0" } }, "sha512-QFnPfjFey8EqknSrSxe1hZrf1/8z7/6s1QzGOmKo6++02r7QRRX7ZoyNaZh7JuVjWsVW87KnQrbZqnHkOAzUyg=="],
|
||||
|
||||
"shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],
|
||||
|
||||
@@ -46,6 +46,7 @@
|
||||
"@modelcontextprotocol/core": "^2.0.0",
|
||||
"@modelcontextprotocol/server": "^2.0.0",
|
||||
"ky": "^2.0.2",
|
||||
"qrcode-terminal": "^0.12.0",
|
||||
"quickjs-emscripten-core": "0.32.0",
|
||||
"yaml": "^2.9.0",
|
||||
"zod": "^4.4.3"
|
||||
@@ -53,6 +54,7 @@
|
||||
"devDependencies": {
|
||||
"@modelcontextprotocol/client": "^2.0.0",
|
||||
"@types/bun": "^1.3.14",
|
||||
"@types/qrcode-terminal": "^0.12.2",
|
||||
"typescript": "^5.9.3"
|
||||
}
|
||||
}
|
||||
@@ -833,7 +833,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
},
|
||||
flags: {
|
||||
...flagList("token t user name u hose-token jwt ticket ticket-id auth-code staff staff-id staffId alias corp-name count limit n start offset state status corpid id keyword query q message msg reason matter hours hour duration days day to recipient target remarks comment corp", "value"),
|
||||
...flagList("all a logout admin save import persist switch current overwrite candidates list-candidates", "boolean")
|
||||
...flagList("all a logout admin save import persist switch current overwrite candidates list-candidates qr", "boolean")
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -4,7 +4,10 @@ import {
|
||||
clearAssistPlatformSession,
|
||||
} from "../../../core/auth/assist-platform-store.js";
|
||||
import { createAssistPlatformClient } from "../../../core/http/assist-platform-client.js";
|
||||
import { searchCorporations } from "../../../domains/assist-platform/services.js";
|
||||
import {
|
||||
searchCorporations,
|
||||
loginAssistPlatformByQrCode,
|
||||
} from "../../../domains/assist-platform/services.js";
|
||||
import { booleanOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
@@ -66,35 +69,150 @@ export async function handleLogin(
|
||||
};
|
||||
}
|
||||
|
||||
// 查看当前协助平台会话状态
|
||||
const checkStatusOnly = booleanOption(parsed.options, ["status"]);
|
||||
const forceQr = booleanOption(parsed.options, ["qr", "force"]);
|
||||
const isInteractive = Boolean(
|
||||
process.stdin.isTTY && !process.env.CI && process.env.NODE_ENV !== "test"
|
||||
);
|
||||
const existing = loadAssistPlatformSession();
|
||||
if (!existing || !existing.token) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未检测到协助平台登录凭证。\n用法:\n hose-use assist-platform login --token <TOKEN> [--user <姓名>]\n hose-use assist-platform login --logout (清理凭证)\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
// 如果仅检查状态 (--status)
|
||||
if (checkStatusOnly) {
|
||||
if (!existing || !existing.token) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[ERROR] 未检测到协助平台登录凭证。\n请运行: hose-use assist-platform login 进行扫码登录\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const testClient = createAssistPlatformClient({
|
||||
token: existing.token,
|
||||
baseUrl: existing.baseUrl,
|
||||
hoseAccessToken: existing.hoseAccessToken,
|
||||
});
|
||||
|
||||
try {
|
||||
await searchCorporations(testClient, { limit: { start: 0, count: 1 } });
|
||||
} catch {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[ERROR] 协助平台凭证已过期或无效。\n请运行: hose-use assist-platform login 进行扫码登录\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ valid: true, ...existing }),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const pairs: Record<string, string> = {
|
||||
协助平台状态: "🟢 凭证有效 (已登录)",
|
||||
操作员工姓名: existing.userName || "运营实施人员",
|
||||
基础服务地址: existing.baseUrl || "https://unity.ekuaibao.com/api",
|
||||
当前会话凭证: existing.token.replace(/(.{4}).*(.{4})/, "$1****$2"),
|
||||
最后更新时间: new Date(existing.updatedAt).toLocaleString("zh-CN", { hour12: false }),
|
||||
};
|
||||
|
||||
return {
|
||||
stdout: printJson(existing),
|
||||
stdout: `====== 合思协助平台当前会话 ======\n${printKeyValue(pairs)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const pairs: Record<string, string> = {
|
||||
协助平台状态: "🟢 已登录",
|
||||
操作员工姓名: existing.userName || "运营实施人员",
|
||||
基础服务地址: existing.baseUrl || "https://unity.ekuaibao.com/api",
|
||||
当前会话凭证: existing.token.replace(/(.{4}).*(.{4})/, "$1****$2"),
|
||||
最后更新时间: new Date(existing.updatedAt).toLocaleString("zh-CN", { hour12: false }),
|
||||
};
|
||||
// 如果已有凭证且未强制发起扫码,先探测有效性
|
||||
if (existing?.token && !forceQr) {
|
||||
let isValid = false;
|
||||
const testClient = createAssistPlatformClient({
|
||||
token: existing.token,
|
||||
baseUrl: existing.baseUrl,
|
||||
hoseAccessToken: existing.hoseAccessToken,
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: `====== 合思协助平台当前会话 ======\n${printKeyValue(pairs)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
try {
|
||||
await searchCorporations(testClient, { limit: { start: 0, count: 1 } });
|
||||
isValid = true;
|
||||
} catch {
|
||||
isValid = false;
|
||||
}
|
||||
|
||||
if (isValid) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(existing),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const pairs: Record<string, string> = {
|
||||
协助平台状态: "🟢 已登录 (凭证有效)",
|
||||
操作员工姓名: existing.userName || "运营实施人员",
|
||||
基础服务地址: existing.baseUrl || "https://unity.ekuaibao.com/api",
|
||||
当前会话凭证: existing.token.replace(/(.{4}).*(.{4})/, "$1****$2"),
|
||||
最后更新时间: new Date(existing.updatedAt).toLocaleString("zh-CN", { hour12: false }),
|
||||
};
|
||||
|
||||
return {
|
||||
stdout: `====== 合思协助平台当前会话 ======\n${printKeyValue(pairs)}\n\n💡 提示: 当前凭证处于有效状态。如需重新扫码登录,请运行: hose-use assist-platform login --qr\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 凭证不存在或已失效:非交互/测试模式下给出指引,交互模式或显式 --qr 下直接自动拉起扫码登录
|
||||
if (!isInteractive && !forceQr) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未检测到协助平台登录凭证。\n用法:\n hose-use assist-platform login [--qr]\n hose-use assist-platform login --token <TOKEN> [--user <姓名>]\n hose-use assist-platform login --logout (清理凭证)\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 自动发起钉钉交互式扫码登录流程 ──────────────────────────
|
||||
try {
|
||||
const loginRes = await loginAssistPlatformByQrCode({
|
||||
timeoutMs: 60000,
|
||||
onQrCode: (qrText, dingUrl) => {
|
||||
if (!runtime.jsonMode) {
|
||||
process.stdout.write(`\n====== 合思协助平台钉钉扫码登录 ======\n`);
|
||||
process.stdout.write(`请使用钉钉 App 扫描下方二维码确认登录(有效期 60 秒):\n\n`);
|
||||
process.stdout.write(`${qrText}\n\n`);
|
||||
process.stdout.write(`🔗 快捷授权链接: ${dingUrl}\n\n`);
|
||||
process.stdout.write(`等待钉钉扫码并确认中... (最长等待 60 秒)\n`);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
success: true,
|
||||
token: loginRes.token,
|
||||
userName: loginRes.userName,
|
||||
baseUrl: loginRes.baseUrl,
|
||||
}),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `\n[SUCCESS] 协助平台凭证已自动更新成功!\n操作人员: ${loginRes.userName}\n会话 Token: ${loginRes.token}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
} catch (err) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[ERROR] 协助平台扫码登录失败: ${err instanceof Error ? err.message : String(err)}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,23 @@ export function createAssistPlatformClient(options: AssistPlatformClientOptions)
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
throw new AuthenticationError("协助平台凭证已过期或无效,请重新登录协助平台");
|
||||
}
|
||||
const contentType = response.headers.get("content-type");
|
||||
if (contentType && contentType.includes("application/json")) {
|
||||
try {
|
||||
const clone = response.clone();
|
||||
const json = (await clone.json()) as any;
|
||||
if (
|
||||
json?.errorCode === 403 ||
|
||||
(typeof json?.errorMessage === "string" && json.errorMessage.includes("token过期"))
|
||||
) {
|
||||
throw new AuthenticationError(
|
||||
"协助平台凭证已过期或无效,请运行: hose-use assist-platform login 重新扫码登录"
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof AuthenticationError) throw err;
|
||||
}
|
||||
}
|
||||
return response;
|
||||
},
|
||||
],
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
getOpenApiHeaders,
|
||||
} from "./openapi-client.js";
|
||||
import { resolveCorpCluster, getEasoClient, getUnityClient, clearUnityClientCache } from "./unity-client.js";
|
||||
import { createAssistPlatformClient } from "./assist-platform-client.js";
|
||||
import { getScriptEngineClient } from "./script-engine-client.js";
|
||||
import { setCorpTokens, resetTokenStoreMemory } from "../auth/token-store.js";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
@@ -150,4 +151,23 @@ describe("core/http/unity-client & script-engine-client", () => {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("createAssistPlatformClient throws AuthenticationError when response body contains errorCode: 403", async () => {
|
||||
const client = createAssistPlatformClient({
|
||||
token: "fake-token",
|
||||
baseUrl: "https://mock-unity.invalid",
|
||||
});
|
||||
|
||||
const mockFetch = async () =>
|
||||
new Response(JSON.stringify({ errorCode: 403, errorMessage: "token过期请重新登录!" }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
|
||||
const testClient = client.extend({ fetch: mockFetch as any });
|
||||
|
||||
expect(async () => {
|
||||
await testClient.get("test").json();
|
||||
}).toThrow("协助平台凭证已过期或无效,请运行: hose-use assist-platform login 重新扫码登录");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import {
|
||||
createSsoClient,
|
||||
getSsoQrCode,
|
||||
pollSsoQrCodeStatus,
|
||||
verifySsoTokenOnUnity,
|
||||
} from "./sso-client.js";
|
||||
import { AuthenticationError } from "../errors.js";
|
||||
|
||||
describe("core/http/sso-client", () => {
|
||||
it("getSsoQrCode 能够正常解析二维码链接与 Session Cookie", async () => {
|
||||
const mockClient = {
|
||||
post: async () => ({
|
||||
headers: new Headers({
|
||||
"set-cookie": "SSO_SESSION_ID=mock-session-1234; Path=/; HttpOnly",
|
||||
}),
|
||||
json: async () => ({
|
||||
code: 0,
|
||||
message: "ok",
|
||||
data: {
|
||||
url: "https://login.dingtalk.com/oauth2/auth?mock=1",
|
||||
appId: "12021",
|
||||
redirect: "https://unity.ekuaibao.com/platform-charge/",
|
||||
},
|
||||
}),
|
||||
}),
|
||||
};
|
||||
|
||||
const res = await getSsoQrCode(mockClient as any);
|
||||
expect(res.dingUrl).toContain("login.dingtalk.com");
|
||||
expect(res.ssoSessionId).toBe("mock-session-1234");
|
||||
});
|
||||
|
||||
it("getSsoQrCode 遇到业务错误时抛出 AuthenticationError", async () => {
|
||||
const mockClient = {
|
||||
post: async () => ({
|
||||
headers: new Headers(),
|
||||
json: async () => ({
|
||||
code: 1,
|
||||
message: "类型不支持",
|
||||
}),
|
||||
}),
|
||||
};
|
||||
|
||||
expect(async () => {
|
||||
await getSsoQrCode(mockClient as any);
|
||||
}).toThrow("类型不支持");
|
||||
});
|
||||
|
||||
it("pollSsoQrCodeStatus 能够正确传递 Cookie 并解析确认状态", async () => {
|
||||
let capturedHeaders: any = null;
|
||||
const mockClient = {
|
||||
get: (url: string, opts: any) => {
|
||||
capturedHeaders = opts.headers;
|
||||
return {
|
||||
json: async () => ({
|
||||
code: 0,
|
||||
message: "ok",
|
||||
data: {
|
||||
token: "mock-jwt-token",
|
||||
redirect: "https://unity.ekuaibao.com/platform-charge/?token=mock-token",
|
||||
},
|
||||
}),
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
const res = await pollSsoQrCodeStatus(mockClient as any, {
|
||||
sessionId: "session-abc",
|
||||
});
|
||||
|
||||
expect(capturedHeaders.cookie).toBe("SSO_SESSION_ID=session-abc");
|
||||
expect(res.code).toBe(0);
|
||||
expect(typeof res.data).toBe("object");
|
||||
});
|
||||
|
||||
it("verifySsoTokenOnUnity 优先从 redirect 提取 token 并完成换票", async () => {
|
||||
// 拦截全局 fetch 测试 verifySsoTokenOnUnity
|
||||
const originalFetch = globalThis.fetch;
|
||||
try {
|
||||
globalThis.fetch = (async (url: any, opts: any) => {
|
||||
const req = new Request(url, opts);
|
||||
const body = (await req.json()) as any;
|
||||
if (body.token === "extracted-token") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
value: {
|
||||
token: "unity-session-uuid",
|
||||
user: { name: "张三", userId: "zhangsan" },
|
||||
},
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } }
|
||||
);
|
||||
}
|
||||
return new Response(JSON.stringify({ errorCode: 400 }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
}) as any;
|
||||
|
||||
const res = await verifySsoTokenOnUnity(
|
||||
"https://unity.ekuaibao.com/platform-charge/?token=extracted-token"
|
||||
);
|
||||
|
||||
expect(res.sessionToken).toBe("unity-session-uuid");
|
||||
expect(res.userName).toBe("张三");
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
it("verifySsoTokenOnUnity 当 token 包含点时自动 base64 处理", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
try {
|
||||
let passedToken = "";
|
||||
globalThis.fetch = (async (url: any, opts: any) => {
|
||||
const req = new Request(url, opts);
|
||||
const body = (await req.json()) as any;
|
||||
passedToken = body.token;
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
value: {
|
||||
token: "unity-session-uuid-2",
|
||||
user: { name: "李四" },
|
||||
},
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } }
|
||||
);
|
||||
}) as any;
|
||||
|
||||
const res = await verifySsoTokenOnUnity("jwt.with.dots");
|
||||
expect(passedToken).toBe(Buffer.from("jwt.with.dots").toString("base64"));
|
||||
expect(res.sessionToken).toBe("unity-session-uuid-2");
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -32,6 +32,65 @@ export interface QrCodeStatusResponse {
|
||||
} | string;
|
||||
}
|
||||
|
||||
export interface SsoQrCodeResult {
|
||||
dingUrl: string;
|
||||
ssoSessionId: string;
|
||||
appId: string;
|
||||
redirect: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求 HoseCloudSSO 生成钉钉扫码登录链接与会话 Cookie
|
||||
*/
|
||||
export async function getSsoQrCode(
|
||||
client: KyInstance,
|
||||
options: {
|
||||
appId?: string;
|
||||
redirect?: string;
|
||||
} = {}
|
||||
): Promise<SsoQrCodeResult> {
|
||||
const appId = options.appId || "12021";
|
||||
const redirect = options.redirect || "https://unity.ekuaibao.com/platform-charge/";
|
||||
|
||||
try {
|
||||
const res = await client.post("api/v1/user/login/qrcode", {
|
||||
json: {
|
||||
type: "ding",
|
||||
appId,
|
||||
redirect,
|
||||
},
|
||||
});
|
||||
|
||||
const cookieHeader = res.headers.get("set-cookie");
|
||||
const matchCookie = cookieHeader ? cookieHeader.match(/SSO_SESSION_ID=([^;]+)/) : null;
|
||||
const ssoSessionId = matchCookie ? matchCookie[1] : "";
|
||||
|
||||
const json = (await res.json()) as {
|
||||
code?: number;
|
||||
message?: string;
|
||||
data?: { url?: string; appId?: string; redirect?: string };
|
||||
};
|
||||
|
||||
if (json.code !== 0 || !json.data?.url) {
|
||||
throw new AuthenticationError(
|
||||
`获取钉钉登录二维码失败: ${json.message || "服务端未返回有效二维码链接"}`
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
dingUrl: json.data.url,
|
||||
ssoSessionId,
|
||||
appId: json.data.appId || appId,
|
||||
redirect: json.data.redirect || redirect,
|
||||
};
|
||||
} catch (err) {
|
||||
if (err instanceof AuthenticationError) throw err;
|
||||
throw new AuthenticationError(
|
||||
`请求 SSO 钉钉二维码接口失败: ${err instanceof Error ? err.message : String(err)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 轮询 HoseCloudSSO 钉钉扫码登录确认状态
|
||||
*/
|
||||
@@ -67,3 +126,67 @@ export async function pollSsoQrCodeStatus(
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 SSO 返回的重定向地址或 Token 换取为 Unity 协助平台凭证会话
|
||||
*/
|
||||
export async function verifySsoTokenOnUnity(
|
||||
tokenOrUrl: string,
|
||||
options: {
|
||||
unityBaseUrl?: string;
|
||||
} = {}
|
||||
): Promise<{ sessionToken: string; userName: string }> {
|
||||
const unityBaseUrl = options.unityBaseUrl || "https://unity.ekuaibao.com";
|
||||
|
||||
// 提取候选 Token
|
||||
const candidates: string[] = [];
|
||||
if (tokenOrUrl.includes("://")) {
|
||||
try {
|
||||
const u = new URL(tokenOrUrl);
|
||||
const t = u.searchParams.get("token") || u.searchParams.get("ticket");
|
||||
if (t) candidates.push(t);
|
||||
} catch {}
|
||||
} else {
|
||||
candidates.push(tokenOrUrl);
|
||||
}
|
||||
|
||||
const firstCand = candidates[0] || tokenOrUrl;
|
||||
if (firstCand.includes(".")) {
|
||||
candidates.unshift(Buffer.from(firstCand).toString("base64"));
|
||||
}
|
||||
|
||||
let lastError = "未能完成换票";
|
||||
for (const cand of candidates) {
|
||||
try {
|
||||
const res = await ky
|
||||
.post(`${unityBaseUrl}/api/auth/verify`, {
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
referer: `${unityBaseUrl}/platform-charge/index.html`,
|
||||
},
|
||||
json: { token: cand },
|
||||
timeout: 10000,
|
||||
})
|
||||
.json<{
|
||||
value?: {
|
||||
token: string;
|
||||
user?: { name?: string; userId?: string; [key: string]: unknown };
|
||||
};
|
||||
errorCode?: number;
|
||||
errorMessage?: string;
|
||||
}>();
|
||||
|
||||
if (res.value?.token) {
|
||||
return {
|
||||
sessionToken: res.value.token,
|
||||
userName: res.value.user?.name || "运营人员",
|
||||
};
|
||||
}
|
||||
lastError = res.errorMessage || `errorCode: ${res.errorCode}`;
|
||||
} catch (e) {
|
||||
lastError = e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
}
|
||||
|
||||
throw new AuthenticationError(`换取合思协助平台会话失败: ${lastError}`);
|
||||
}
|
||||
@@ -1,7 +1,15 @@
|
||||
import ky, { type KyInstance } from "ky";
|
||||
import qrcode from "qrcode-terminal";
|
||||
import { BusinessError, NotFoundError } from "../../core/errors.js";
|
||||
import { importFromLink, type ImportFromLinkOptions } from "../../core/auth/link-import.js";
|
||||
import { loadCorpConfigs, resolveWritableEnterprisesDir, saveCorpConfig } from "../../core/config/loader.js";
|
||||
import { saveAssistPlatformSession } from "../../core/auth/assist-platform-store.js";
|
||||
import {
|
||||
createSsoClient,
|
||||
getSsoQrCode,
|
||||
pollSsoQrCodeStatus,
|
||||
verifySsoTokenOnUnity,
|
||||
} from "../../core/http/sso-client.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import {
|
||||
approveAssistTicketApi,
|
||||
@@ -351,8 +359,10 @@ export async function importAssistSessionToLocal(
|
||||
}> {
|
||||
const sessionResult = await generateAssistSession(client, params);
|
||||
|
||||
const importBaseUrl = sessionResult.baseUrl || "https://app.ekuaibao.com";
|
||||
const importOptions: ImportFromLinkOptions = {
|
||||
name: params.saveName,
|
||||
baseUrl: importBaseUrl,
|
||||
overwrite: params.overwrite ?? true,
|
||||
enterprisesDir: params.enterprisesDir,
|
||||
ttl: params.ttl,
|
||||
@@ -361,7 +371,7 @@ export async function importAssistSessionToLocal(
|
||||
|
||||
const linkToImport = sessionResult.loginUrl.includes("accessToken=")
|
||||
? sessionResult.loginUrl
|
||||
: `https://app.ekuaibao.com/web/thirdparty.html?accessToken=${encodeURIComponent(sessionResult.token)}&ekbCorpId=${encodeURIComponent(sessionResult.corporationId)}${sessionResult.staffId ? `&staffId=${encodeURIComponent(sessionResult.staffId)}` : ""}`;
|
||||
: `${importBaseUrl}/web/thirdparty.html?accessToken=${encodeURIComponent(sessionResult.token)}&ekbCorpId=${encodeURIComponent(sessionResult.corporationId)}${sessionResult.staffId ? `&staffId=${encodeURIComponent(sessionResult.staffId)}` : ""}`;
|
||||
|
||||
const previousCorp = loadCorpConfigs(params.enterprisesDir ? [params.enterprisesDir] : undefined)
|
||||
.find((corp) => corp.id === sessionResult.corporationId);
|
||||
@@ -520,3 +530,95 @@ export async function transferAssistTicket(
|
||||
remarks: params.remarks,
|
||||
};
|
||||
}
|
||||
|
||||
export interface AssistQrLoginOptions {
|
||||
timeoutMs?: number;
|
||||
onQrCode?: (qrText: string, dingUrl: string) => void;
|
||||
onProgress?: (elapsedMs: number, remainingMs: number) => void;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export function generateTerminalQrCode(text: string): Promise<string> {
|
||||
return new Promise((resolve) => {
|
||||
try {
|
||||
qrcode.generate(text, { small: true }, (qr) => {
|
||||
resolve(qr);
|
||||
});
|
||||
} catch {
|
||||
resolve("");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 完整固化的钉钉交互式扫码登录合思协助平台闭环
|
||||
*/
|
||||
export async function loginAssistPlatformByQrCode(
|
||||
options: AssistQrLoginOptions = {}
|
||||
): Promise<{ token: string; userName: string; baseUrl: string }> {
|
||||
const timeoutMs = options.timeoutMs ?? 60000;
|
||||
const ssoClient = createSsoClient();
|
||||
const qrRes = await getSsoQrCode(ssoClient);
|
||||
|
||||
const terminalQr = await generateTerminalQrCode(qrRes.dingUrl);
|
||||
|
||||
if (options.onQrCode) {
|
||||
options.onQrCode(terminalQr, qrRes.dingUrl);
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
let pollData: any = null;
|
||||
|
||||
while (Date.now() - startTime < timeoutMs) {
|
||||
if (options.signal?.aborted) {
|
||||
throw new BusinessError("扫码登录已取消");
|
||||
}
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 1500));
|
||||
|
||||
const elapsed = Date.now() - startTime;
|
||||
const remaining = Math.max(0, timeoutMs - elapsed);
|
||||
if (options.onProgress) {
|
||||
options.onProgress(elapsed, remaining);
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await pollSsoQrCodeStatus(ssoClient, {
|
||||
cookie: `SSO_SESSION_ID=${qrRes.ssoSessionId}`,
|
||||
signal: options.signal,
|
||||
});
|
||||
|
||||
if (res.code === 0 && res.data && typeof res.data === "object") {
|
||||
pollData = res.data;
|
||||
break;
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof Error && err.name === "AbortError") throw err;
|
||||
// 容错继续轮询
|
||||
}
|
||||
}
|
||||
|
||||
if (!pollData) {
|
||||
throw new BusinessError("钉钉扫码登录超时(超过 60 秒时间窗口),请重新发起登录");
|
||||
}
|
||||
|
||||
const tokenCandidate = pollData.redirect || pollData.token;
|
||||
if (!tokenCandidate) {
|
||||
throw new BusinessError("SSO 认证响应中未包含有效 Token 或跳转链接");
|
||||
}
|
||||
|
||||
const { sessionToken, userName } = await verifySsoTokenOnUnity(tokenCandidate);
|
||||
|
||||
saveAssistPlatformSession({
|
||||
token: sessionToken,
|
||||
userName,
|
||||
baseUrl: "https://unity.ekuaibao.com/api",
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
|
||||
return {
|
||||
token: sessionToken,
|
||||
userName,
|
||||
baseUrl: "https://unity.ekuaibao.com/api",
|
||||
};
|
||||
}
|
||||
@@ -90,12 +90,12 @@ export async function grantWorkflowNodesApi(options: {
|
||||
timeout: 30000,
|
||||
});
|
||||
const json = (await response.json()) as any;
|
||||
const data = json?.data ?? {};
|
||||
const innerData = json?.data?.data ?? json?.data ?? {};
|
||||
return {
|
||||
success: Boolean(json?.success ?? true),
|
||||
saved: Array.isArray(data.saved) ? data.saved : [],
|
||||
skipped: Array.isArray(data.skipped) ? data.skipped : [],
|
||||
rawMessage: json?.msg || json?.message || "",
|
||||
saved: Array.isArray(innerData.saved) ? innerData.saved : [],
|
||||
skipped: Array.isArray(innerData.skipped) ? innerData.skipped : [],
|
||||
rawMessage: json?.data?.msg || json?.msg || json?.message || "",
|
||||
};
|
||||
} catch (err: any) {
|
||||
const message = err?.message || String(err);
|
||||
|
||||
Reference in new issue
Block a user