Merge pull request #213 from yunyingk/mac15/support-delegation-expire-config

Add configurable expiration for Seal and Hose assistance links
This commit is contained in:
yunyingk authored and GitHub committed 2026-10-10 14:59:43 +08:00
commit c094980ae5
9 files changed
+323 -30

No files matched your search

+1 -1
View File
@@ -70,7 +70,7 @@ describe("CLI version & help handling", () => {
expect(result.stdout).toContain("seal-use webhook get|find <idOrName>");
expect(result.stdout).toContain("seal-use webhook add --name <name> --result-url <url>");
expect(result.stdout).toContain("seal-use corps add-link <url>");
expect(result.stdout).toContain("seal-use auth link [--note <note>] [--corp <corpId>]");
expect(result.stdout).toContain("seal-use auth link [--note <note>] [--expire <duration>] [--corp <corpId>]");
expect(result.stdout).toContain("[--secret <secret>|--rotate-secret]");
});
+138
View File
@@ -93,6 +93,75 @@ describe("auth links", () => {
expect(parsed.expiresAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+08:00$/);
});
test("supports --expire 7d for native Seal link and passes expiresInHours: 168", async () => {
const root = mkdtempSync(join(tmpdir(), "seal-use-auth-link-expire-"));
const enterprises = join(root, "enterprises");
tempDirs.push(root);
mkdirSync(enterprises, { recursive: true });
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
process.env.SEAL_USE_USAGE_FILE = join(root, "usage.json");
writeFileSync(
join(enterprises, "native-seal.json"),
JSON.stringify({
id: "native-seal",
name: "原生 Seal 企业",
environment: "production",
seal: { url: "https://native.seal.test", tenantSlug: "native-seal" },
source: {
type: "seal",
token: "seal-token",
sealUrl: "https://native.seal.test",
expiresIn: 3600,
corpId: "native-corp",
staffId: "native-staff"
},
auth: { refreshTtl: 300 }
})
);
let recordedPayload: any = null;
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const requestUrl = typeof input === "string"
? input
: input instanceof URL
? input.toString()
: input.url;
const url = new URL(requestUrl);
if (url.pathname === "/api/v1/delegation/create") {
if (input instanceof Request) {
recordedPayload = await input.clone().json();
} else if (init?.body) {
recordedPayload = JSON.parse(String(init.body));
}
return new Response(JSON.stringify({
data: {
id: "delegation-7d",
token: "delegation-token-7d",
link: "https://native.seal.test/delegation?token=delegation-token-7d"
}
}), { status: 200, headers: { "content-type": "application/json" } });
}
return new Response(JSON.stringify({ error: `Unexpected request: ${url.pathname}` }), {
status: 404,
headers: { "content-type": "application/json" }
});
}) as typeof fetch;
const result = await runCli(["auth", "link", "--corp", "native-seal", "--expire", "7d"]);
expect(result.isError).toBe(false);
expect(recordedPayload).toMatchObject({
expiresInHours: 168
});
// Test reject exceeding 7 days (168 hours)
const invalidResult = await runCli(["auth", "link", "--corp", "native-seal", "--expire", "8d"]);
expect(invalidResult.isError).toBe(true);
expect(invalidResult.exitCode).toBe(2);
});
test("formats hose-link with corp metadata, link, and Beijing ISO expiry without url field", async () => {
const root = mkdtempSync(join(tmpdir(), "seal-use-auth-hose-link-"));
const enterprises = join(root, "enterprises");
@@ -164,6 +233,75 @@ describe("auth links", () => {
expect(parsed.expiresAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+08:00$/);
});
test("supports --expire 7d for hose-link and converts to 604800 seconds", async () => {
const root = mkdtempSync(join(tmpdir(), "seal-use-auth-hose-link-7d-"));
const enterprises = join(root, "enterprises");
tempDirs.push(root);
mkdirSync(enterprises, { recursive: true });
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
process.env.SEAL_USE_USAGE_FILE = join(root, "usage.json");
writeFileSync(
join(enterprises, "hose-corp.json"),
JSON.stringify({
id: "hose-corp",
name: "合思测试企业",
environment: "production",
seal: { url: "https://hose-corp.sealai.cc" },
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
appKey: "key-1",
appSecurity: "sec-1",
corpId: "HOSE-CORP",
staffId: "HOSE-CORP:STAFF-1"
},
auth: { refreshTtl: 300 }
})
);
let recordedHoseBody: any = null;
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const requestUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
const url = new URL(requestUrl);
if (url.pathname === "/api/openapi/v1/auth/getAccessToken") {
return new Response(
JSON.stringify({
value: { accessToken: "test-openapi-token", expireTime: 7200 }
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
}
if (url.pathname === "/api/openapi/v1.1/provisional/getProvisionalAuth") {
if (input instanceof Request) {
recordedHoseBody = await input.clone().json();
} else if (init?.body) {
recordedHoseBody = JSON.parse(String(init.body));
}
return new Response(
JSON.stringify({
value: {
message: "https://app.ekuaibao.com/web/thirdparty.html?accessToken=provisional-token-7d"
}
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
}
return new Response(JSON.stringify({ error: `Unexpected request: ${url.pathname}` }), {
status: 404,
headers: { "content-type": "application/json" }
});
}) as typeof fetch;
const result = await runCli(["auth", "hose-link", "--corp", "hose-corp", "--expire", "7d"]);
expect(result.isError).toBe(false);
expect(recordedHoseBody).toMatchObject({
expireDate: 604800
});
});
test("runs auth check and hidden aliases (status, diagnose, test)", async () => {
const root = mkdtempSync(join(tmpdir(), "seal-use-auth-check-"));
const enterprises = join(root, "enterprises");
+17 -10
View File
@@ -5,7 +5,12 @@ 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, numberOption, stringOption } from "../parser.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";
@@ -40,11 +45,13 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
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 });
const delegation = await createDelegation(client, { note, expiresInHours });
printJson({
tenant: {
@@ -60,7 +67,8 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
isAdmin: me.user.isAdmin
},
delegation,
expiresIn: session.expiresIn
expiresIn: session.expiresIn,
expiresAt: formatBeijingIso(Date.now() + expiresInHours * 3600 * 1000)
});
return;
}
@@ -90,18 +98,20 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
}
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 }
{ 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() + 86400 * 1000);
const expiresAt = formatBeijingIso(Date.now() + expiresInHours * 3600 * 1000);
printJson({
id: delegationRecord.id,
corpId: corp.source.corpId ?? corp.id,
@@ -116,11 +126,8 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
}
if (action === "hose-link") {
const rawExpire = args.options.expire;
const expiresIn = rawExpire !== undefined ? numberOption(rawExpire) : 7200;
if (expiresIn === undefined || expiresIn <= 0) {
throw new Error(`Invalid --expire: ${String(rawExpire)}. Must be a positive number of seconds (e.g. --expire 7200 or --expire 86400).`);
}
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 ||
+11 -3
View File
@@ -2,7 +2,7 @@ import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { confirmationRequired } from "../errors.js";
import { runCapability } from "../helpers.js";
import { booleanOption, stringOption } from "../parser.js";
import { booleanOption, parseDelegationExpireHours, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
@@ -73,9 +73,17 @@ export async function handleUsersCommand(
if (action === "delegation" || action === "impersonate") {
const userIdOrPhone = maybeName ?? stringOption(args.options.userId) ?? stringOption(args.options.phone);
if (!userIdOrPhone) throw new Error("Usage: seal-use users delegation <userIdOrPhone> [--note <note>]");
if (!userIdOrPhone) throw new Error("Usage: seal-use users delegation <userIdOrPhone> [--note <note>] [--expire <duration>]");
const note = stringOption(args.options.note);
await runCapability("sealUserDelegationCreate", client, corp, { userIdOrPhone, note }, outputOptions(args.options));
const expireOption = args.options.expire ?? args.options["expires-in"] ?? args.options.expiresIn;
const expiresInHours = parseDelegationExpireHours(expireOption, 24);
await runCapability(
"sealUserDelegationCreate",
client,
corp,
{ userIdOrPhone, note, expiresInHours },
outputOptions(args.options)
);
return;
}
+10 -5
View File
@@ -835,11 +835,12 @@ export const HELP_REGISTRY: AreaHelp[] = [
name: "link",
summary: "【Seal 审核后台】生成免密登录/委托访问直达链接",
usage: [
"seal-use auth link [--note <note>] [--corp <corpId>]",
"seal-use auth link --from-link <url> [--note <note>]"
"seal-use auth link [--note <note>] [--expire <duration>] [--corp <corpId>]",
"seal-use auth link --from-link <url> [--note <note>] [--expire <duration>]"
],
options: [
{ flag: "--note <note>", description: "委托授权备注说明(如:演示测试、外部审计)" },
{ flag: "--expire, --expires-in <duration>", description: "委托授权有效期(1~168 小时,即最大 7 天),默认 24h,支持 7d、168h、24h 等" },
{ flag: "--from-link <url>", description: "直接由合思协助链接换取 Seal 委托直达链接" }
],
description:
@@ -859,9 +860,9 @@ export const HELP_REGISTRY: AreaHelp[] = [
{
name: "hose-link",
summary: "【合思外部主站】生成免密登录/第三方协助入口链接",
usage: ["seal-use auth hose-link [--corp <corpId>] [--expire 7200] [--force]"],
usage: ["seal-use auth hose-link [--corp <corpId>] [--expire <duration>] [--force]"],
options: [
{ flag: "--expire <seconds>", description: "链接有效时间(秒),默认 7200,支持如 86400(1天)" },
{ flag: "--expire, --expires-in <duration>", description: "链接有效时间,默认 7200 秒(2h),支持 7d、2h、86400 等" },
{ flag: "--force, --refresh, -f", description: "强制向合思 OpenAPI 申请全新临时凭证" }
],
description:
@@ -912,7 +913,11 @@ export const HELP_REGISTRY: AreaHelp[] = [
{
name: "delegation",
summary: "Create delegation token for a specific user",
usage: ["seal-use users delegation <userIdOrPhone|name> [--note <note>] [--corp <corpId>]"]
usage: ["seal-use users delegation <userIdOrPhone|name> [--note <note>] [--expire <duration>] [--corp <corpId>]"],
options: [
{ flag: "--note <note>", description: "委托授权备注说明" },
{ flag: "--expire, --expires-in <duration>", description: "委托授权有效期(1~168 小时,即最大 7 天),默认 24h,支持 7d、168h、24h 等" }
]
},
{
name: "reset-password",
+29
View File
@@ -7,6 +7,8 @@ import {
KNOWN_FLAGS,
numberOption,
parseArgs,
parseDelegationExpireHours,
parseHoseExpireSeconds,
splitOption,
stringOption,
VALUE_FLAGS
@@ -116,6 +118,33 @@ describe("option helpers", () => {
expect(splitOption("")).toBeUndefined();
expect(splitOption(true)).toBeUndefined();
});
test("parseDelegationExpireHours parses days, hours, and limits to 1..168", () => {
expect(parseDelegationExpireHours(undefined)).toBe(24);
expect(parseDelegationExpireHours("7d")).toBe(168);
expect(parseDelegationExpireHours("1d")).toBe(24);
expect(parseDelegationExpireHours("24h")).toBe(24);
expect(parseDelegationExpireHours("2h")).toBe(2);
expect(parseDelegationExpireHours("168")).toBe(168);
expect(parseDelegationExpireHours(168)).toBe(168);
expect(parseDelegationExpireHours("86400")).toBe(24);
expect(() => parseDelegationExpireHours("8d")).toThrow("1 到 168 小时(最大 7 天)");
expect(() => parseDelegationExpireHours("0h")).toThrow("1 到 168 小时(最大 7 天)");
expect(() => parseDelegationExpireHours("invalid")).toThrow("Must be a valid duration");
});
test("parseHoseExpireSeconds parses days, hours, minutes, and raw seconds", () => {
expect(parseHoseExpireSeconds(undefined)).toBe(7200);
expect(parseHoseExpireSeconds("7200")).toBe(7200);
expect(parseHoseExpireSeconds(7200)).toBe(7200);
expect(parseHoseExpireSeconds("2h")).toBe(7200);
expect(parseHoseExpireSeconds("7d")).toBe(604800);
expect(parseHoseExpireSeconds("30m")).toBe(1800);
expect(() => parseHoseExpireSeconds("0s")).toThrow("Must be a positive number of seconds");
expect(() => parseHoseExpireSeconds("invalid")).toThrow("Must be a valid duration");
});
});
describe("flag registry cross-check", () => {
+90 -2
View File
@@ -48,7 +48,7 @@ export const VALUE_FLAGS = new Set([
"docIdPrefix", "docIdSuffix", "document-id", "document-sn", "document-sns", "document-type",
"documentId", "documentLimit", "documentSn", "documentType", "domain", "enable",
"end", "end-date", "end-time", "endDate", "endTime", "env",
"environment", "expire", "expiresIn", "fields", "file", "file-id", "file-name", "flow-concurrency",
"environment", "expire", "expires-in", "expiresIn", "fields", "file", "file-id", "file-name", "flow-concurrency",
"flow-ids", "flow-status-list", "flowIds", "flowStatusList", "format", "from",
"from-link", "host", "humanResult", "id", "input", "integration",
"json", "json-path", "key-id", "keyId", "keyword", "level", "limit",
@@ -98,7 +98,7 @@ export const KNOWN_FLAGS = new Set([
"documentId", "documentLimit", "documentSn", "documentType", "domain", "download",
"downloads", "dry-run", "dryRun", "elevate-hose", "enable", "enabled",
"end", "end-date", "end-time", "endDate", "endTime", "env",
"environment", "exclude-deleted", "extract", "extract-expenses", "extractExpenses", "expire", "expiresIn", "f", "fail-on-flips",
"environment", "exclude-deleted", "extract", "extract-expenses", "extractExpenses", "expire", "expires-in", "expiresIn", "f", "fail-on-flips",
"fields", "file", "file-id", "file-name", "flow", "flow-concurrency", "flow-ids", "flow-status-list",
"flowIds", "flowStatusList", "force", "format", "from", "from-link",
"full", "h", "has-input", "has-output", "help", "hose", "hose-sso", "hoseSso",
@@ -436,3 +436,91 @@ export function materialPackFilePolicyOptions(
allowedExtensions
};
}
export function parseDelegationExpireHours(value: string | boolean | number | undefined, defaultHours = 24): number {
if (value === undefined || value === null || value === "") {
return defaultHours;
}
let hours: number;
if (typeof value === "number") {
if (!Number.isFinite(value) || value <= 0) {
throw usageError(`Invalid --expire: ${value}. Must be a positive duration (e.g. '7d', '24h', or 1..168).`);
}
if (value > 168 && value % 3600 === 0 && value / 3600 <= 168) {
hours = Math.round(value / 3600);
} else {
hours = Math.round(value);
}
} else if (typeof value === "string") {
const trimmed = value.trim();
const match = trimmed.match(/^(\d+(?:\.\d+)?)\s*(d|day|days|h|hr|hrs|hour|hours|m|min|mins|minute|minutes|s|sec|secs|second|seconds)?$/i);
if (!match || !match[1]) {
throw usageError(`Invalid --expire: '${value}'. Must be a valid duration (e.g. '7d', '24h', or 1..168).`);
}
const val = parseFloat(match[1]);
const unit = (match[2] ?? "").toLowerCase();
if (!unit) {
if (val > 168 && val % 3600 === 0 && val / 3600 <= 168) {
hours = Math.round(val / 3600);
} else {
hours = Math.round(val);
}
} else if (unit.startsWith("d")) {
hours = Math.round(val * 24);
} else if (unit.startsWith("h")) {
hours = Math.round(val);
} else if (unit.startsWith("m")) {
hours = Math.round(val / 60);
} else if (unit.startsWith("s")) {
hours = Math.round(val / 3600);
} else {
hours = Math.round(val);
}
} else {
throw usageError(`Invalid --expire: ${String(value)}.`);
}
if (hours < 1 || hours > 168) {
throw usageError(`Invalid --expire: computed ${hours} hours. Seal delegation 有效期必须在 1 到 168 小时(最大 7 天)之间。例如:--expire 7d 或 --expire 24h。`);
}
return hours;
}
export function parseHoseExpireSeconds(value: string | boolean | number | undefined, defaultSeconds = 7200): number {
if (value === undefined || value === null || value === "") {
return defaultSeconds;
}
let seconds: number;
if (typeof value === "number") {
if (!Number.isFinite(value) || value <= 0) {
throw usageError(`Invalid --expire: ${value}. Must be a positive duration.`);
}
seconds = Math.round(value);
} else if (typeof value === "string") {
const trimmed = value.trim();
const match = trimmed.match(/^(\d+(?:\.\d+)?)\s*(d|day|days|h|hr|hrs|hour|hours|m|min|mins|minute|minutes|s|sec|secs|second|seconds)?$/i);
if (!match || !match[1]) {
throw usageError(`Invalid --expire: '${value}'. Must be a valid duration (e.g. '7d', '2h', '7200').`);
}
const val = parseFloat(match[1]);
const unit = (match[2] ?? "").toLowerCase();
if (!unit || unit.startsWith("s")) {
seconds = Math.round(val);
} else if (unit.startsWith("d")) {
seconds = Math.round(val * 86400);
} else if (unit.startsWith("h")) {
seconds = Math.round(val * 3600);
} else if (unit.startsWith("m")) {
seconds = Math.round(val * 60);
} else {
seconds = Math.round(val);
}
} else {
throw usageError(`Invalid --expire: ${String(value)}.`);
}
if (seconds <= 0) {
throw usageError(`Invalid --expire: computed ${seconds} seconds. Must be a positive number of seconds.`);
}
return seconds;
}
+6 -4
View File
@@ -882,7 +882,7 @@ export async function listDelegations(client: KyInstance): Promise<SealDelegatio
export async function createDelegation(
client: KyInstance,
params?: { note?: string }
params?: { note?: string; expiresInHours?: number }
): Promise<SealDelegationCreateResult> {
return unwrap(
await client.post("api/v1/delegation/create", { json: params ?? {} }),
@@ -1162,7 +1162,7 @@ export async function loginWithPhonePassword(
export async function createDelegationForUser(
client: KyInstance,
params: { userIdOrPhone: string; note?: string },
params: { userIdOrPhone: string; note?: string; expiresInHours?: number },
createClientForToken: (token: string) => Promise<KyInstance>,
corp?: CorpConfig
): Promise<{
@@ -1249,7 +1249,8 @@ export async function createDelegationForUser(
if (targetUserSealToken) {
const userClient = await createClientForToken(targetUserSealToken);
const delegation = await createDelegation(userClient, {
note: params.note ?? `Delegation generated by admin for ${user.name}`
note: params.note ?? `Delegation generated by admin for ${user.name}`,
expiresInHours: params.expiresInHours
});
return {
@@ -1287,7 +1288,8 @@ export async function createDelegationForUser(
const userClient = await createClientForToken(token);
const delegation = await createDelegation(userClient, {
note: params.note ?? `Delegation generated by admin for ${user.name}`
note: params.note ?? `Delegation generated by admin for ${user.name}`,
expiresInHours: params.expiresInHours
});
return {
+21 -5
View File
@@ -29,10 +29,19 @@ export const identityCapabilities = [
name: "sealDelegationCreate",
description: "创建新的 Seal 授权链接 (Delegation)",
parameters: z.object({
note: z.string().optional().describe("授权链接的备注或说明信息")
note: z.string().optional().describe("授权链接的备注或说明信息"),
expiresInHours: z
.number()
.int()
.min(1)
.max(168)
.optional()
.describe("授权链接有效期小时数(1~168 小时,即最大 7 天,默认 24 小时)")
}),
handler: async (client: KyInstance, params: { note?: string }) =>
api.createDelegation(client, params)
handler: async (
client: KyInstance,
params: { note?: string; expiresInHours?: number }
) => api.createDelegation(client, params)
},
{
name: "sealDelegationRevoke",
@@ -107,11 +116,18 @@ export const identityCapabilities = [
description: "为指定 Seal 用户(按用户ID、手机号或姓名)重置密码登录并生成其专属授权链接 (Delegation)",
parameters: z.object({
userIdOrPhone: z.string().describe("目标用户 ID、手机号或姓名"),
note: z.string().optional().describe("授权链接备注信息")
note: z.string().optional().describe("授权链接备注信息"),
expiresInHours: z
.number()
.int()
.min(1)
.max(168)
.optional()
.describe("授权链接有效期小时数(1~168 小时,即最大 7 天,默认 24 小时)")
}),
handler: async (
client: KyInstance,
params: { userIdOrPhone: string; note?: string },
params: { userIdOrPhone: string; note?: string; expiresInHours?: number },
context: CapabilityContext
) =>
api.createDelegationForUser(