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
@@ -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}`);
|
||||
}
|
||||
Reference in new issue
Block a user