feat(auth): support OpenAPI persistent credentials, auto-refresh, and Web login link generation (v0.8.10)

This commit is contained in:
gitea committed 2026-09-28 16:50:18 +08:00
1 parent 1d825269f4
commit 96c5a3f242
27 files changed
+2994 -583

No files matched your search

+115 -3
View File
@@ -1,5 +1,14 @@
import { describe, expect, it } from "bun:test";
import { canRefreshCorpAccessToken, resolveLinkExpiresAt } from "../auth/login.js";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
canRefreshCorpAccessToken,
getCorpProvisionalAuthLink,
hasOpenApiPersistentCredentials,
resolveLinkExpiresAt,
selectOpenApiKey,
} from "../auth/login.js";
import { createSessionClient } from "./session-client.js";
import type { CorpConfig } from "../config/types.js";
@@ -8,19 +17,32 @@ function corp(overrides: Partial<CorpConfig> = {}): CorpConfig {
id: "corp-1",
name: "测试企业",
source: "link",
credentials: { accessToken: "token", corpId: "corp-1", staffId: "staff-1" },
credentials: { accessToken: "token", corpId: "corp-1", staffId: "corp-1:staff-1" },
...overrides,
baseUrl: overrides.baseUrl ?? "https://app.ekuaibao.com",
};
}
describe("core/http/session-client refresh policy", () => {
it("only allows account credentials with an explicit account binding to refresh", () => {
it("allows refresh for account credentials or OpenAPI persistent credentials", () => {
expect(canRefreshCorpAccessToken(corp())).toBe(false);
expect(canRefreshCorpAccessToken(corp({ source: "browser", accountId: "86-1" }))).toBe(false);
expect(canRefreshCorpAccessToken(corp({ source: "account" }))).toBe(false);
expect(canRefreshCorpAccessToken(corp({ source: "account", accountId: "86-1" }))).toBe(true);
expect(canRefreshCorpAccessToken(corp({ source: "account", accountId: "86-1", session: { isShortTermToken: true } }))).toBe(false);
const openApiCorp = corp({
source: "link",
credentials: {
accessToken: "token",
corpId: "corp-1",
staffId: "corp-1:staff-1",
appKey: "key-123",
appSecurity: "sec-456",
},
});
expect(hasOpenApiPersistentCredentials(openApiCorp)).toBe(true);
expect(canRefreshCorpAccessToken(openApiCorp)).toBe(true);
});
it("fails expired temporary credentials without retrying or refreshing", async () => {
@@ -39,6 +61,96 @@ describe("core/http/session-client refresh policy", () => {
globalThis.fetch = originalFetch;
}
});
it("automatically refreshes expired token via OpenAPI getProvisionalAuth when appKey/appSecurity are present", async () => {
const originalFetch = globalThis.fetch;
const tempDir = mkdtempSync(join(tmpdir(), "hose-use-test-"));
const prevEnv = process.env.HOSE_ENTERPRISES_DIR;
process.env.HOSE_ENTERPRISES_DIR = tempDir;
const seenUrls: string[] = [];
globalThis.fetch = (async (input: string | URL | Request) => {
const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
seenUrls.push(url);
if (url.includes("/api/openapi/v1/auth/getAccessToken")) {
return new Response(
JSON.stringify({
value: {
accessToken: "openapi-token-xyz",
corporationId: "corp-1",
expireTime: Date.now() + 7200_000,
},
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
}
if (url.includes("/api/openapi/v1.1/provisional/getProvisionalAuth")) {
return new Response(
JSON.stringify({
value: {
message:
"https://app.ekuaibao.com/web/thirdparty.html?accessToken=fresh-session-token-999&ekbCorpId=corp-1",
},
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
}
return new Response(JSON.stringify({ value: { ok: true } }), {
status: 200,
headers: { "content-type": "application/json" },
});
}) as unknown as typeof fetch;
try {
const persistentCorp = corp({
source: "openapi",
credentials: {
accessToken: "",
corpId: "corp-1",
staffId: "corp-1:staff-1",
appKey: "test-app-key",
appSecurity: "test-app-security",
},
auth: {
refreshTtl: 300,
expiresAt: Date.now() - 10_000,
},
});
const client = await createSessionClient(persistentCorp);
expect(persistentCorp.credentials.accessToken).toBe("fresh-session-token-999");
const linkRes = await getCorpProvisionalAuthLink(persistentCorp, { enterprisesDir: tempDir });
expect(linkRes.method).toBe("provisional-openapi");
expect(linkRes.url).toContain("accessToken=fresh-session-token-999");
expect(client).toBeDefined();
expect(seenUrls.some((u) => u.includes("getProvisionalAuth"))).toBe(true);
} finally {
globalThis.fetch = originalFetch;
if (prevEnv === undefined) delete process.env.HOSE_ENTERPRISES_DIR;
else process.env.HOSE_ENTERPRISES_DIR = prevEnv;
rmSync(tempDir, { recursive: true, force: true });
}
});
});
describe("core/auth/login > selectOpenApiKey", () => {
const sampleKeys = [
{ id: "k1", name: "停用密钥", appKey: "ak-1", appSecurity: "sec-1", active: false },
{ id: "k2", name: "启用密钥A", appKey: "ak-2", appSecurity: "sec-2", active: true },
{ id: "k3", name: "启用密钥B", appKey: "ak-3", appSecurity: "sec-3", active: true },
];
it("auto-selects when only one active key exists", () => {
const picked = selectOpenApiKey([sampleKeys[0]!, sampleKeys[1]!], "corp-1");
expect(picked.appKey).toBe("ak-2");
});
it("requires explicit selection or --force when multiple active keys exist", () => {
expect(() => selectOpenApiKey(sampleKeys, "corp-1")).toThrow("存在多套");
expect(selectOpenApiKey(sampleKeys, "corp-1", { force: true }).appKey).toBe("ak-2");
expect(selectOpenApiKey(sampleKeys, "corp-1", { appKey: "ak-3" }).appKey).toBe("ak-3");
});
});
describe("core/auth/login link expiry", () => {