1334 lines
42 KiB
TypeScript
1334 lines
42 KiB
TypeScript
import { randomBytes } from "node:crypto";
|
|
import ky, { HTTPError, KyInstance } from "ky";
|
|
import { z } from "zod";
|
|
import {
|
|
mergeMaterialPackFilePolicy,
|
|
normalizeMaterialPackFilePolicy,
|
|
type MaterialPackFilePolicyPatch
|
|
} from "./material-pack/policy.js";
|
|
import { CorpConfig } from "../../core/config/types.js";
|
|
import { ensureHoseOpenapiToken, fetchHoseCloseApiToken, defaultSealUrl, normalizeBaseUrl } from "../../core/auth/hose.js";
|
|
import { createSealClientForUrl } from "../../core/http/factory.js";
|
|
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
|
|
import {
|
|
ApprovalDocumentListData,
|
|
ApprovalDocumentListDataSchema,
|
|
ApprovalDocumentSchema,
|
|
ApprovalRun,
|
|
ApprovalRunListData,
|
|
ApprovalRunListDataSchema,
|
|
ApprovalRunSchema,
|
|
ApprovalRulesData,
|
|
ApprovalRulesDataSchema,
|
|
ApprovalRule,
|
|
ApprovalRuleSchema,
|
|
ApprovalStylePreferences,
|
|
ApprovalStylePreferencesSchema,
|
|
MeData,
|
|
MeDataSchema,
|
|
PublishVersionDataSchema,
|
|
SealSessionData,
|
|
SealSessionDataSchema,
|
|
RuleSetVersion,
|
|
RuleSetVersionSchema,
|
|
SealDelegationItem,
|
|
SealDelegationItemSchema,
|
|
SealDelegationCreateResult,
|
|
SealDelegationCreateResultSchema,
|
|
SealUserCreateResult,
|
|
SealUserCreateResultSchema,
|
|
SealUserResetPasswordResult,
|
|
SealUserResetPasswordResultSchema,
|
|
SealUserDetail,
|
|
SealUserDetailSchema,
|
|
SealContactSearchResult,
|
|
SealContactSearchResultSchema,
|
|
SealDepartment,
|
|
SealDepartmentSchema,
|
|
SealDepartmentListData,
|
|
SealDepartmentListDataSchema,
|
|
SealDepartmentUsersData,
|
|
SealDepartmentUsersDataSchema,
|
|
SealContactsLastSyncTime,
|
|
SealContactsLastSyncTimeSchema,
|
|
InsightStats,
|
|
InsightStatsSchema,
|
|
InsightRisksByTag,
|
|
InsightRisksByTagSchema,
|
|
InsightPerformance,
|
|
InsightPerformanceSchema,
|
|
ExpenseListData,
|
|
ExpenseListDataSchema,
|
|
InvoiceListData,
|
|
InvoiceListDataSchema,
|
|
SimulationApprovalDefinition,
|
|
SimulationApprovalDefinitionSchema,
|
|
LlmConfig,
|
|
LlmConfigSchema,
|
|
LlmProvider,
|
|
LlmProviderSchema,
|
|
AvailablePermissionsData,
|
|
AvailablePermissionsDataSchema,
|
|
PermissionConfigsData,
|
|
PermissionConfigsDataSchema,
|
|
BillingStatusData,
|
|
BillingStatusDataSchema,
|
|
WebhookIntegration,
|
|
WebhookIntegrationSchema,
|
|
WebhookMode,
|
|
SimulationBatch,
|
|
SimulationBatchSchema,
|
|
SimulationCreateResult,
|
|
SimulationCreateResultSchema,
|
|
SimulationTemplate,
|
|
SimulationTemplateSchema,
|
|
SimulationIntegrationStatus,
|
|
SimulationIntegrationStatusSchema,
|
|
SimulationHosecloudIntegration,
|
|
SimulationHosecloudIntegrationSchema,
|
|
MaterialPackage,
|
|
MaterialPackageSchema,
|
|
SimulationSpecification,
|
|
SimulationSpecificationSchema,
|
|
ThinkingPolicy,
|
|
ThinkingDepthPreference,
|
|
HosecloudConfigInput,
|
|
ApprovalRunsStats
|
|
} from "./types.js";
|
|
|
|
const SuccessResponseSchema = z.object({ success: z.boolean().optional() }).passthrough();
|
|
const RootDepartmentResponseSchema = z.object({
|
|
items: z.array(z.object({ _id: z.string() })).optional()
|
|
}).passthrough();
|
|
const PasswordLoginResponseSchema = z.object({
|
|
user: z.unknown().optional(),
|
|
session: z.object({ token: z.string().optional() }).optional()
|
|
}).passthrough();
|
|
const JsonResponseSchema = z.json();
|
|
|
|
async function unwrap<T>(response: Response, schema: z.ZodType<T>): Promise<T> {
|
|
const json = (await response.json()) as { data?: unknown };
|
|
return schema.parse(json.data ?? json);
|
|
}
|
|
|
|
export async function getMe(client: KyInstance): Promise<MeData> {
|
|
return unwrap(await client.get("api/v1/auth/me"), MeDataSchema);
|
|
}
|
|
|
|
export async function getSession(client: KyInstance): Promise<SealSessionData> {
|
|
return unwrap(await client.get("api/auth/get-session"), SealSessionDataSchema);
|
|
}
|
|
|
|
export async function listApprovalRules(client: KyInstance): Promise<ApprovalRulesData> {
|
|
return unwrap(await client.get("api/v1/rules"), ApprovalRulesDataSchema);
|
|
}
|
|
|
|
export async function createApprovalRule(
|
|
client: KyInstance,
|
|
params: { description: string; scope: string; strictness: string }
|
|
): Promise<ApprovalRule> {
|
|
return unwrap(await client.post("api/v1/rules", { json: params }), ApprovalRuleSchema);
|
|
}
|
|
|
|
export async function updateApprovalRule(
|
|
client: KyInstance,
|
|
ruleId: string,
|
|
params: { description?: string; scope?: string; strictness?: string }
|
|
): Promise<ApprovalRule> {
|
|
return unwrap(await client.put(`api/v1/rules/${ruleId}`, { json: params }), ApprovalRuleSchema);
|
|
}
|
|
|
|
export async function deleteApprovalRule(client: KyInstance, ruleId: string): Promise<void> {
|
|
await client.delete(`api/v1/rules/${ruleId}`);
|
|
}
|
|
|
|
export async function recodeApprovalRules(client: KyInstance): Promise<unknown> {
|
|
const response = await client.post("api/v1/rules/batch-recode", { throwHttpErrors: false });
|
|
const body = await response.json().catch(() => ({}));
|
|
return z.object({
|
|
ok: z.boolean(),
|
|
status: z.number(),
|
|
body: z.unknown()
|
|
}).parse({
|
|
ok: response.ok,
|
|
status: response.status,
|
|
body
|
|
});
|
|
}
|
|
|
|
export async function listApprovalRuleVersions(client: KyInstance): Promise<RuleSetVersion[]> {
|
|
return unwrap(await client.get("api/v1/rule-set-versions"), z.array(RuleSetVersionSchema));
|
|
}
|
|
|
|
export async function getApprovalRuleVersion(
|
|
client: KyInstance,
|
|
versionId: string
|
|
): Promise<RuleSetVersion> {
|
|
return unwrap(
|
|
await client.get(`api/v1/rule-set-versions/${versionId}`),
|
|
RuleSetVersionSchema
|
|
);
|
|
}
|
|
|
|
export async function publishApprovalRuleVersion(
|
|
client: KyInstance,
|
|
versionName: string
|
|
): Promise<z.infer<typeof PublishVersionDataSchema>> {
|
|
return unwrap(
|
|
await client.post("api/v1/rule-set-versions/publish", { json: { versionName } }),
|
|
PublishVersionDataSchema
|
|
);
|
|
}
|
|
|
|
export async function listApprovalDocuments(
|
|
client: KyInstance,
|
|
params: {
|
|
scenarios?: string[];
|
|
offset?: number;
|
|
limit?: number;
|
|
sortBy?: string;
|
|
sortOrder?: string;
|
|
} = {}
|
|
): Promise<ApprovalDocumentListData> {
|
|
const searchParams = new URLSearchParams();
|
|
searchParams.set("offset", String(params.offset ?? 0));
|
|
searchParams.set("limit", String(params.limit ?? 20));
|
|
searchParams.set("sortBy", params.sortBy ?? "createdAt");
|
|
searchParams.set("sortOrder", params.sortOrder ?? "desc");
|
|
|
|
params.scenarios?.forEach((scenario, index) => {
|
|
searchParams.set(`filter[scenarios][${index}]`, scenario);
|
|
});
|
|
|
|
return unwrap(
|
|
await client.get("api/v1/knowledge/articles", { searchParams }),
|
|
ApprovalDocumentListDataSchema
|
|
);
|
|
}
|
|
|
|
export async function getApprovalDocument(client: KyInstance, documentId: string) {
|
|
return unwrap(
|
|
await client.get(`api/v1/knowledge/articles/${documentId}`),
|
|
ApprovalDocumentSchema
|
|
);
|
|
}
|
|
|
|
export async function createApprovalDocument(
|
|
client: KyInstance,
|
|
params: {
|
|
title: string;
|
|
purpose: string;
|
|
content: string;
|
|
contentType?: string;
|
|
status?: string;
|
|
enabled?: boolean;
|
|
scenarios?: string[];
|
|
tags?: string[];
|
|
}
|
|
) {
|
|
return unwrap(
|
|
await client.post("api/v1/knowledge/articles", {
|
|
json: {
|
|
...params,
|
|
contentType: params.contentType ?? "policy",
|
|
status: params.status ?? "published",
|
|
enabled: params.enabled ?? true,
|
|
scenarios: params.scenarios && params.scenarios.length > 0 ? params.scenarios : ["audit"],
|
|
tags: params.tags ?? []
|
|
}
|
|
}),
|
|
ApprovalDocumentSchema
|
|
);
|
|
}
|
|
|
|
export async function updateApprovalDocument(
|
|
client: KyInstance,
|
|
documentId: string,
|
|
params: {
|
|
title?: string;
|
|
purpose?: string;
|
|
content?: string;
|
|
contentType?: string;
|
|
status?: string;
|
|
enabled?: boolean;
|
|
scenarios?: string[];
|
|
tags?: string[];
|
|
}
|
|
) {
|
|
const attributes = Object.fromEntries(
|
|
Object.entries(params).filter(([, value]) => value !== undefined)
|
|
);
|
|
|
|
return unwrap(
|
|
await client.patch(`api/v1/knowledge/articles/${documentId}`, {
|
|
json: { attributes }
|
|
}),
|
|
ApprovalDocumentSchema
|
|
);
|
|
}
|
|
|
|
export async function deleteApprovalDocument(
|
|
client: KyInstance,
|
|
documentId: string
|
|
): Promise<{ success: boolean; id: string }> {
|
|
await client.delete(`api/v1/knowledge/articles/${documentId}`);
|
|
return { success: true, id: documentId };
|
|
}
|
|
|
|
export async function getApprovalStylePreferences(
|
|
client: KyInstance,
|
|
endpoint = "api/v1/agent/ai-approval/config"
|
|
): Promise<ApprovalStylePreferences> {
|
|
return unwrap(
|
|
await client.get(endpoint),
|
|
ApprovalStylePreferencesSchema
|
|
);
|
|
}
|
|
|
|
export async function updateApprovalStylePreferences(
|
|
client: KyInstance,
|
|
params: Record<string, unknown>,
|
|
endpoint = "api/v1/agent/ai-approval/config"
|
|
): Promise<ApprovalStylePreferences> {
|
|
await client.post(endpoint, { json: params });
|
|
return getApprovalStylePreferences(client, endpoint);
|
|
}
|
|
|
|
export type WebhookMutationPreview = {
|
|
before: ApprovalStylePreferences;
|
|
after: ApprovalStylePreferences;
|
|
integration?: WebhookIntegration;
|
|
};
|
|
|
|
export async function saveApprovalStylePreferences(
|
|
client: KyInstance,
|
|
params: Record<string, unknown>,
|
|
endpoint = "api/v1/agent/ai-approval/config"
|
|
): Promise<boolean> {
|
|
const response = await client.post(endpoint, { json: params });
|
|
const json = await response.json().catch(() => ({}));
|
|
const data = SuccessResponseSchema.safeParse(
|
|
(json as { data?: unknown }).data ?? json
|
|
);
|
|
return data.success ? data.data.success ?? response.ok : response.ok;
|
|
}
|
|
|
|
export async function listWebhookIntegrations(
|
|
client: KyInstance,
|
|
endpoint = "api/v1/agent/ai-approval/config"
|
|
): Promise<WebhookIntegration[]> {
|
|
const preferences = await getApprovalStylePreferences(client, endpoint);
|
|
return parseWebhookIntegrations(preferences.integrations);
|
|
}
|
|
|
|
export async function addWebhookIntegration(
|
|
client: KyInstance,
|
|
baseUrl: string,
|
|
params: {
|
|
name: string;
|
|
mode?: WebhookMode;
|
|
outgoingResultWebhook: string;
|
|
autoApprovalRate?: number;
|
|
secret?: string;
|
|
materialPackFilePolicy?: MaterialPackFilePolicyPatch;
|
|
},
|
|
endpoint = "api/v1/agent/ai-approval/config"
|
|
): Promise<WebhookIntegration> {
|
|
const preferences = await getApprovalStylePreferences(client, endpoint);
|
|
const existing = parseWebhookIntegrations(preferences.integrations);
|
|
const integration = createWebhookIntegration(baseUrl, existing, params);
|
|
const saved = await saveApprovalStylePreferences(client, {
|
|
...preferences,
|
|
integrations: [...preferences.integrations, integration]
|
|
}, endpoint);
|
|
|
|
if (!saved) {
|
|
throw new Error("Seal did not confirm saving the Webhook integration");
|
|
}
|
|
|
|
return integration;
|
|
}
|
|
|
|
export async function previewAddWebhookIntegration(
|
|
client: KyInstance,
|
|
baseUrl: string,
|
|
params: {
|
|
name: string;
|
|
mode?: WebhookMode;
|
|
outgoingResultWebhook: string;
|
|
autoApprovalRate?: number;
|
|
secret?: string;
|
|
materialPackFilePolicy?: MaterialPackFilePolicyPatch;
|
|
},
|
|
endpoint = "api/v1/agent/ai-approval/config"
|
|
): Promise<WebhookMutationPreview> {
|
|
const before = await getApprovalStylePreferences(client, endpoint);
|
|
const existing = parseWebhookIntegrations(before.integrations);
|
|
const integration = createWebhookIntegration(baseUrl, existing, params);
|
|
return {
|
|
before,
|
|
after: { ...before, integrations: [...before.integrations, integration] },
|
|
integration
|
|
};
|
|
}
|
|
|
|
export async function updateWebhookIntegration(
|
|
client: KyInstance,
|
|
selector: string,
|
|
params: {
|
|
name?: string;
|
|
mode?: WebhookMode;
|
|
outgoingResultWebhook?: string;
|
|
autoApprovalRate?: number;
|
|
secret?: string;
|
|
rotateSecret?: boolean;
|
|
materialPackFilePolicy?: MaterialPackFilePolicyPatch;
|
|
},
|
|
endpoint = "api/v1/agent/ai-approval/config"
|
|
): Promise<WebhookIntegration> {
|
|
const preferences = await getApprovalStylePreferences(client, endpoint);
|
|
const entries = getWebhookEntries(preferences.integrations);
|
|
const entry = findWebhookEntry(entries, selector);
|
|
const updated = buildUpdatedWebhookIntegration(entry.integration, params);
|
|
|
|
const saved = await saveApprovalStylePreferences(client, {
|
|
...preferences,
|
|
integrations: preferences.integrations.map((integration, index) =>
|
|
index === entry.index ? updated : integration
|
|
)
|
|
}, endpoint);
|
|
|
|
if (!saved) {
|
|
throw new Error("Seal did not confirm saving the Webhook integration");
|
|
}
|
|
|
|
return updated;
|
|
}
|
|
|
|
export async function previewUpdateWebhookIntegration(
|
|
client: KyInstance,
|
|
selector: string,
|
|
params: {
|
|
name?: string;
|
|
mode?: WebhookMode;
|
|
outgoingResultWebhook?: string;
|
|
autoApprovalRate?: number;
|
|
secret?: string;
|
|
rotateSecret?: boolean;
|
|
materialPackFilePolicy?: MaterialPackFilePolicyPatch;
|
|
},
|
|
endpoint = "api/v1/agent/ai-approval/config"
|
|
): Promise<WebhookMutationPreview> {
|
|
const before = await getApprovalStylePreferences(client, endpoint);
|
|
const entries = getWebhookEntries(before.integrations);
|
|
const entry = findWebhookEntry(entries, selector);
|
|
const integration = buildUpdatedWebhookIntegration(entry.integration, params);
|
|
return {
|
|
before,
|
|
after: {
|
|
...before,
|
|
integrations: before.integrations.map((item, index) => index === entry.index ? integration : item)
|
|
},
|
|
integration
|
|
};
|
|
}
|
|
|
|
export async function deleteWebhookIntegration(
|
|
client: KyInstance,
|
|
selector: string,
|
|
endpoint = "api/v1/agent/ai-approval/config"
|
|
): Promise<WebhookIntegration> {
|
|
const preferences = await getApprovalStylePreferences(client, endpoint);
|
|
const entries = getWebhookEntries(preferences.integrations);
|
|
const entry = findWebhookEntry(entries, selector);
|
|
const saved = await saveApprovalStylePreferences(client, {
|
|
...preferences,
|
|
integrations: preferences.integrations.filter((_, index) => index !== entry.index)
|
|
}, endpoint);
|
|
|
|
if (!saved) {
|
|
throw new Error("Seal did not confirm deleting the Webhook integration");
|
|
}
|
|
|
|
return entry.integration;
|
|
}
|
|
|
|
export async function previewDeleteWebhookIntegration(
|
|
client: KyInstance,
|
|
selector: string,
|
|
endpoint = "api/v1/agent/ai-approval/config"
|
|
): Promise<WebhookMutationPreview> {
|
|
const before = await getApprovalStylePreferences(client, endpoint);
|
|
const entries = getWebhookEntries(before.integrations);
|
|
const entry = findWebhookEntry(entries, selector);
|
|
return {
|
|
before,
|
|
after: {
|
|
...before,
|
|
integrations: before.integrations.filter((_, index) => index !== entry.index)
|
|
},
|
|
integration: entry.integration
|
|
};
|
|
}
|
|
|
|
export function findWebhookIntegration(
|
|
integrations: WebhookIntegration[],
|
|
selector: string
|
|
): WebhookIntegration {
|
|
const normalized = selector.trim();
|
|
if (!normalized) throw new Error("Webhook selector must not be empty");
|
|
|
|
const exactId = integrations.find((integration) => integration.id === normalized);
|
|
if (exactId) return exactId;
|
|
|
|
const byName = integrations.filter((integration) => integration.name === normalized);
|
|
if (byName.length === 1) return byName[0]!;
|
|
if (byName.length > 1) {
|
|
throw new Error(`Multiple Webhook integrations match name: ${normalized}. Use the integration ID.`);
|
|
}
|
|
|
|
throw new Error(`Webhook integration not found: ${normalized}`);
|
|
}
|
|
|
|
export function filterWebhookIntegrations(
|
|
integrations: WebhookIntegration[],
|
|
query?: string
|
|
): WebhookIntegration[] {
|
|
const needle = query?.trim().toLowerCase();
|
|
if (!needle) return integrations;
|
|
|
|
return integrations.filter((integration) => [
|
|
integration.id,
|
|
integration.name,
|
|
integration.mode,
|
|
integration.outgoingResultWebhook,
|
|
integration.incomingDocumentWebhook.url,
|
|
integration.incomingManualResultWebhook.url
|
|
].some((value) => value.toLowerCase().includes(needle)));
|
|
}
|
|
|
|
function parseWebhookIntegrations(
|
|
integrations: Array<{ type: string } & Record<string, unknown>>
|
|
): WebhookIntegration[] {
|
|
return integrations
|
|
.filter((integration) => integration.type === "webhook")
|
|
.map((integration) => WebhookIntegrationSchema.parse(integration));
|
|
}
|
|
|
|
function getWebhookEntries(
|
|
integrations: Array<{ type: string } & Record<string, unknown>>
|
|
): Array<{ index: number; integration: WebhookIntegration }> {
|
|
return integrations.flatMap((integration, index) => {
|
|
if (integration.type !== "webhook") return [];
|
|
return [{ index, integration: WebhookIntegrationSchema.parse(integration) }];
|
|
});
|
|
}
|
|
|
|
function findWebhookEntry(
|
|
entries: Array<{ index: number; integration: WebhookIntegration }>,
|
|
selector: string
|
|
) {
|
|
const integration = findWebhookIntegration(
|
|
entries.map((entry) => entry.integration),
|
|
selector
|
|
);
|
|
return entries.find((entry) => entry.integration.id === integration.id)!;
|
|
}
|
|
|
|
function createWebhookIntegration(
|
|
baseUrl: string,
|
|
existing: WebhookIntegration[],
|
|
params: {
|
|
name: string;
|
|
mode?: WebhookMode;
|
|
outgoingResultWebhook: string;
|
|
autoApprovalRate?: number;
|
|
secret?: string;
|
|
materialPackFilePolicy?: MaterialPackFilePolicyPatch;
|
|
}
|
|
): WebhookIntegration {
|
|
const name = requiredText(params.name, "name");
|
|
const mode = params.mode ?? "assisted";
|
|
const outgoingResultWebhook = validUrl(params.outgoingResultWebhook, "outgoingResultWebhook");
|
|
const autoApprovalRate = validApprovalRate(params.autoApprovalRate ?? 60);
|
|
const stamp = nextWebhookTimestamp(existing);
|
|
const webhookId = `wh_${stamp}_${randomBytes(8).toString("hex").slice(0, 7)}`;
|
|
const root = normalizeBaseUrl(baseUrl);
|
|
|
|
return WebhookIntegrationSchema.parse({
|
|
type: "webhook",
|
|
id: `integration-${stamp}`,
|
|
name,
|
|
mode,
|
|
incomingDocumentWebhook: {
|
|
id: webhookId,
|
|
url: `${root}/api/v1/integrations/webhook/${webhookId}/document`
|
|
},
|
|
outgoingResultWebhook,
|
|
incomingManualResultWebhook: {
|
|
id: webhookId,
|
|
url: `${root}/api/v1/integrations/webhook/${webhookId}/manual-result`
|
|
},
|
|
secret: params.secret ? requiredText(params.secret, "secret") : generateWebhookSecret(),
|
|
autoApprovalRate,
|
|
materialPackFilePolicy: normalizeMaterialPackFilePolicy(params.materialPackFilePolicy)
|
|
});
|
|
}
|
|
|
|
function buildUpdatedWebhookIntegration(
|
|
integration: WebhookIntegration,
|
|
params: {
|
|
name?: string;
|
|
mode?: WebhookMode;
|
|
outgoingResultWebhook?: string;
|
|
autoApprovalRate?: number;
|
|
secret?: string;
|
|
rotateSecret?: boolean;
|
|
materialPackFilePolicy?: MaterialPackFilePolicyPatch;
|
|
}
|
|
): WebhookIntegration {
|
|
return WebhookIntegrationSchema.parse({
|
|
...integration,
|
|
...(params.name === undefined ? {} : { name: requiredText(params.name, "name") }),
|
|
...(params.mode === undefined ? {} : { mode: params.mode }),
|
|
...(params.outgoingResultWebhook === undefined
|
|
? {}
|
|
: { outgoingResultWebhook: validUrl(params.outgoingResultWebhook, "outgoingResultWebhook") }),
|
|
...(params.autoApprovalRate === undefined
|
|
? {}
|
|
: { autoApprovalRate: validApprovalRate(params.autoApprovalRate) }),
|
|
...(params.rotateSecret || params.secret !== undefined
|
|
? { secret: params.rotateSecret ? generateWebhookSecret() : requiredText(params.secret ?? "", "secret") }
|
|
: {}),
|
|
...(params.materialPackFilePolicy === undefined
|
|
? {}
|
|
: {
|
|
materialPackFilePolicy: mergeMaterialPackFilePolicy(
|
|
integration.materialPackFilePolicy,
|
|
params.materialPackFilePolicy
|
|
)
|
|
})
|
|
});
|
|
}
|
|
|
|
function nextWebhookTimestamp(existing: WebhookIntegration[]): number {
|
|
const usedIds = new Set(existing.map((integration) => integration.id));
|
|
let stamp = Date.now();
|
|
while (usedIds.has(`integration-${stamp}`)) stamp += 1;
|
|
return stamp;
|
|
}
|
|
|
|
function generateWebhookSecret(): string {
|
|
return randomBytes(16).toString("hex");
|
|
}
|
|
|
|
function requiredText(value: string, field: string): string {
|
|
const normalized = value.trim();
|
|
if (!normalized) throw new Error(`Webhook ${field} must not be empty`);
|
|
return normalized;
|
|
}
|
|
|
|
function validUrl(value: string, field: string): string {
|
|
const normalized = requiredText(value, field);
|
|
try {
|
|
return new URL(normalized).toString();
|
|
} catch {
|
|
throw new Error(`Webhook ${field} must be a valid URL`);
|
|
}
|
|
}
|
|
|
|
function validApprovalRate(value: number): number {
|
|
if (!Number.isInteger(value) || value < 0 || value > 100) {
|
|
throw new Error("Webhook autoApprovalRate must be an integer between 0 and 100");
|
|
}
|
|
return value;
|
|
}
|
|
|
|
export async function getApprovalContext(
|
|
client: KyInstance,
|
|
params: {
|
|
documentLimit?: number;
|
|
stylePreferencesEndpoint?: string;
|
|
} = {}
|
|
) {
|
|
const [rules, documents, stylePreferences] = await Promise.all([
|
|
listApprovalRules(client),
|
|
listApprovalDocuments(client, { limit: params.documentLimit ?? 50 }),
|
|
getApprovalStylePreferences(
|
|
client,
|
|
params.stylePreferencesEndpoint
|
|
).then(
|
|
(data) => ({ ok: true as const, data }),
|
|
(error) => ({
|
|
ok: false as const,
|
|
error: error instanceof Error ? error.message : String(error)
|
|
})
|
|
)
|
|
]);
|
|
|
|
return {
|
|
rules,
|
|
documents,
|
|
stylePreferences
|
|
};
|
|
}
|
|
|
|
export async function listApprovalRuns(
|
|
client: KyInstance,
|
|
params: {
|
|
offset?: number;
|
|
limit?: number;
|
|
fromTimestamp?: string;
|
|
toTimestamp?: string;
|
|
startDate?: string;
|
|
endDate?: string;
|
|
status?: string | string[];
|
|
sourceSystem?: string;
|
|
taskMode?: string;
|
|
manualApprovalStatus?: string | string[];
|
|
search?: string;
|
|
sourceDocumentSN?: string;
|
|
sourceDocumentId?: string;
|
|
} = {}
|
|
): Promise<ApprovalRunListData> {
|
|
const searchParams = new URLSearchParams();
|
|
searchParams.set("offset", String(params.offset ?? 0));
|
|
searchParams.set("limit", String(params.limit ?? 50));
|
|
|
|
setOptional(searchParams, "fromTimestamp", params.fromTimestamp);
|
|
setOptional(searchParams, "toTimestamp", params.toTimestamp);
|
|
setOptional(searchParams, "startDate", params.startDate);
|
|
setOptional(searchParams, "endDate", params.endDate);
|
|
setArrayOptional(searchParams, "status", params.status);
|
|
setOptional(searchParams, "sourceSystem", params.sourceSystem);
|
|
setOptional(searchParams, "taskMode", params.taskMode);
|
|
setOptional(searchParams, "search", params.search);
|
|
setOptional(searchParams, "sourceDocumentSN", params.sourceDocumentSN);
|
|
setOptional(searchParams, "sourceDocumentId", params.sourceDocumentId);
|
|
setArrayOptional(searchParams, "manualApprovalStatus", params.manualApprovalStatus);
|
|
|
|
return unwrap(
|
|
await client.get("api/v1/approvals", { searchParams }),
|
|
ApprovalRunListDataSchema
|
|
);
|
|
}
|
|
|
|
export async function getApprovalRun(client: KyInstance, runId: string): Promise<ApprovalRun> {
|
|
return unwrap(await client.get(`api/v1/approvals/${runId}`), ApprovalRunSchema);
|
|
}
|
|
|
|
export async function listSimulationBatchRecords(
|
|
client: KyInstance,
|
|
batchId: string
|
|
): Promise<ApprovalRun[]> {
|
|
const json = (await client
|
|
.get(`api/v1/simulation/batch/${batchId}/records`)
|
|
.json()) as { data?: unknown };
|
|
const data = json.data ?? json;
|
|
|
|
if (Array.isArray(data)) {
|
|
return z.array(ApprovalRunSchema).parse(data);
|
|
}
|
|
|
|
const parsed = ApprovalRunListDataSchema.parse(data);
|
|
return parsed.records;
|
|
}
|
|
|
|
export async function createSimulationBatch(
|
|
client: KyInstance,
|
|
params: Record<string, unknown>
|
|
): Promise<SimulationCreateResult> {
|
|
return unwrap(
|
|
await client.post("api/v1/simulation/create-batch", { json: params }),
|
|
SimulationCreateResultSchema
|
|
);
|
|
}
|
|
|
|
export async function createMaterialPackBatch(
|
|
client: KyInstance,
|
|
params: Record<string, unknown>
|
|
): Promise<SimulationCreateResult> {
|
|
return unwrap(
|
|
await client.post("api/v1/simulation/create-material-pack-batch", { json: params }),
|
|
SimulationCreateResultSchema
|
|
);
|
|
}
|
|
|
|
export async function listSimulationBatches(
|
|
client: KyInstance,
|
|
opts: { limit?: number } = {}
|
|
): Promise<SimulationBatch[]> {
|
|
const json = (await client
|
|
.get("api/v1/simulation/batches", {
|
|
searchParams: { limit: String(opts.limit ?? 50) }
|
|
})
|
|
.json()) as { data?: unknown };
|
|
const data = json.data ?? json;
|
|
return z.array(SimulationBatchSchema).parse(data);
|
|
}
|
|
|
|
export async function getSimulationBatch(
|
|
client: KyInstance,
|
|
batchId: string
|
|
): Promise<SimulationBatch> {
|
|
return unwrap(await client.get(`api/v1/simulation/batch/${batchId}`), SimulationBatchSchema);
|
|
}
|
|
|
|
export async function listSimulationTemplates(client: KyInstance): Promise<SimulationTemplate[]> {
|
|
const json = (await client.get("api/v1/simulation/templates").json()) as { data?: unknown };
|
|
const data = json.data ?? json;
|
|
return z.array(SimulationTemplateSchema).parse(data);
|
|
}
|
|
|
|
export async function getSimulationIntegrationStatus(
|
|
client: KyInstance
|
|
): Promise<SimulationIntegrationStatus> {
|
|
return unwrap(await client.get("api/v1/simulation/integration-status"), SimulationIntegrationStatusSchema);
|
|
}
|
|
|
|
export async function listSimulationHosecloudIntegrations(
|
|
client: KyInstance
|
|
): Promise<SimulationHosecloudIntegration[]> {
|
|
const json = (await client.get("api/v1/simulation/hosecloud-integrations").json()) as { data?: unknown };
|
|
const data = json.data ?? json;
|
|
return z.array(SimulationHosecloudIntegrationSchema).parse(data);
|
|
}
|
|
|
|
export async function cleanSimulationBatch(
|
|
client: KyInstance,
|
|
batchId: string
|
|
): Promise<unknown> {
|
|
const response = await client.delete(`api/v1/simulation/batch/${encodeURIComponent(batchId)}/data`);
|
|
const json = (await response.json().catch(() => ({}))) as { data?: unknown };
|
|
return json.data ?? json;
|
|
}
|
|
|
|
export async function listSimulationSpecifications(
|
|
client: KyInstance,
|
|
signKey?: string
|
|
): Promise<SimulationSpecification[]> {
|
|
const path = signKey
|
|
? "api/v1/simulation/hosecloud-specifications-by-sign-key"
|
|
: "api/v1/simulation/hosecloud-specifications";
|
|
const searchParams = signKey ? new URLSearchParams({ signKey }) : undefined;
|
|
const json = (await client.get(path, { searchParams }).json()) as { data?: unknown };
|
|
const data = json.data ?? json;
|
|
return z.array(SimulationSpecificationSchema).parse(data);
|
|
}
|
|
|
|
export async function getHosecloudCorporation(
|
|
client: KyInstance,
|
|
params: {
|
|
apiKey: string;
|
|
apiSecret: string;
|
|
apiOrigin?: string;
|
|
customApiUrl?: string;
|
|
}
|
|
): Promise<{ corporationId: string }> {
|
|
const json = (await client.post("api/hosecloud/corporation", { json: params }).json()) as { data?: unknown };
|
|
const data = json.data ?? json;
|
|
return z.object({ corporationId: z.string() }).parse(data);
|
|
}
|
|
|
|
export async function syncHosecloudOutbound(
|
|
client: KyInstance,
|
|
params: {
|
|
signKey: string;
|
|
webhookUrl: string;
|
|
completionWebhookUrl: string;
|
|
messageName: string;
|
|
mode: string;
|
|
}
|
|
): Promise<unknown> {
|
|
const response = await client.post("api/hosecloud/outbound-config/sync", { json: params });
|
|
const json = (await response.json().catch(() => ({}))) as { data?: unknown };
|
|
return json.data ?? json;
|
|
}
|
|
|
|
export async function uploadMaterialPackage(
|
|
client: KyInstance,
|
|
params: { fileName: string; fileBuffer: Uint8Array }
|
|
): Promise<MaterialPackage> {
|
|
const form = new FormData();
|
|
form.append("file", new Blob([new Uint8Array(params.fileBuffer)]), params.fileName);
|
|
return unwrap(
|
|
await client.post("api/v1/material-packages/upload", { body: form }),
|
|
MaterialPackageSchema
|
|
);
|
|
}
|
|
|
|
function setOptional(searchParams: URLSearchParams, key: string, value?: string) {
|
|
if (value) {
|
|
searchParams.set(key, value);
|
|
}
|
|
}
|
|
|
|
function setArrayOptional(
|
|
searchParams: URLSearchParams,
|
|
key: string,
|
|
value?: string | string[]
|
|
) {
|
|
if (!value) return;
|
|
|
|
const values = Array.isArray(value) ? value : [value];
|
|
values
|
|
.map((item) => item.trim())
|
|
.filter(Boolean)
|
|
.forEach((item, index) => {
|
|
searchParams.set(`${key}[${index}]`, item);
|
|
});
|
|
}
|
|
|
|
export async function listDelegations(client: KyInstance): Promise<SealDelegationItem[]> {
|
|
return unwrap(await client.get("api/v1/delegation/list"), z.array(SealDelegationItemSchema));
|
|
}
|
|
|
|
export async function createDelegation(
|
|
client: KyInstance,
|
|
params?: { note?: string }
|
|
): Promise<SealDelegationCreateResult> {
|
|
return unwrap(
|
|
await client.post("api/v1/delegation/create", { json: params ?? {} }),
|
|
SealDelegationCreateResultSchema
|
|
);
|
|
}
|
|
|
|
export async function revokeDelegation(client: KyInstance, tokenId: string): Promise<boolean> {
|
|
const response = await client.post("api/v1/delegation/revoke", { json: { tokenId } });
|
|
const json = (await response.json()) as { data?: unknown };
|
|
const data = SuccessResponseSchema.safeParse(json.data ?? json);
|
|
return data.success ? data.data.success ?? response.ok : response.ok;
|
|
}
|
|
|
|
export async function createLocalUser(
|
|
client: KyInstance,
|
|
params: { name: string; phone: string; permissions?: string[]; departmentIds?: string[] }
|
|
): Promise<SealUserCreateResult> {
|
|
let departmentIds = params.departmentIds && params.departmentIds.length > 0 ? params.departmentIds : undefined;
|
|
if (!departmentIds) {
|
|
const rootDepts = (await client.get("api/v1/contacts/departments/root/children").json()) as { data?: unknown };
|
|
const rootData = RootDepartmentResponseSchema.safeParse(rootDepts.data ?? rootDepts);
|
|
const firstId = rootData.success ? rootData.data.items?.[0]?._id : undefined;
|
|
if (firstId) {
|
|
departmentIds = [firstId];
|
|
}
|
|
}
|
|
return unwrap(
|
|
await client.post("api/v1/contacts/local/users", {
|
|
json: {
|
|
name: params.name,
|
|
phone: params.phone,
|
|
permissions: params.permissions ?? [],
|
|
departmentIds: departmentIds ?? []
|
|
}
|
|
}),
|
|
SealUserCreateResultSchema
|
|
);
|
|
}
|
|
|
|
export async function resetUserPassword(
|
|
client: KyInstance,
|
|
userId: string
|
|
): Promise<SealUserResetPasswordResult> {
|
|
return unwrap(
|
|
await client.post(`api/v1/contacts/local/users/${userId}/reset-password`, { json: {} }),
|
|
SealUserResetPasswordResultSchema
|
|
);
|
|
}
|
|
|
|
export async function getUserDetail(
|
|
client: KyInstance,
|
|
userId: string
|
|
): Promise<SealUserDetail> {
|
|
return unwrap(
|
|
await client.get(`api/v1/contacts/users/${userId}`),
|
|
SealUserDetailSchema
|
|
);
|
|
}
|
|
|
|
export async function searchUsers(
|
|
client: KyInstance,
|
|
keyword = ""
|
|
): Promise<SealContactSearchResult> {
|
|
return unwrap(
|
|
await client.get("api/v1/contacts/search", { searchParams: { query: keyword } }),
|
|
SealContactSearchResultSchema
|
|
);
|
|
}
|
|
|
|
export async function listRootDepartments(client: KyInstance): Promise<SealDepartmentListData> {
|
|
return unwrap(
|
|
await client.get("api/v1/contacts/departments/root/children"),
|
|
SealDepartmentListDataSchema
|
|
);
|
|
}
|
|
|
|
export async function getDepartment(
|
|
client: KyInstance,
|
|
departmentId: string
|
|
): Promise<SealDepartment> {
|
|
return unwrap(
|
|
await client.get(`api/v1/contacts/departments/${encodeURIComponent(departmentId)}`),
|
|
SealDepartmentSchema
|
|
);
|
|
}
|
|
|
|
export async function listDepartmentChildren(
|
|
client: KyInstance,
|
|
departmentId: string
|
|
): Promise<SealDepartmentListData> {
|
|
return unwrap(
|
|
await client.get(`api/v1/contacts/departments/${encodeURIComponent(departmentId)}/children`),
|
|
SealDepartmentListDataSchema
|
|
);
|
|
}
|
|
|
|
export async function listDepartmentUsers(
|
|
client: KyInstance,
|
|
departmentId: string
|
|
): Promise<SealDepartmentUsersData> {
|
|
return unwrap(
|
|
await client.get(`api/v1/contacts/departments/${encodeURIComponent(departmentId)}/users`),
|
|
SealDepartmentUsersDataSchema
|
|
);
|
|
}
|
|
|
|
export async function getContactsLastSyncTime(client: KyInstance): Promise<SealContactsLastSyncTime> {
|
|
return unwrap(await client.get("api/v1/contacts/last-sync-time"), SealContactsLastSyncTimeSchema);
|
|
}
|
|
|
|
export async function getInsightStats(
|
|
client: KyInstance,
|
|
params: { startDate?: string; endDate?: string; limit?: number } = {}
|
|
): Promise<InsightStats> {
|
|
const defaultRange = currentMonthDateRange();
|
|
const searchParams = new URLSearchParams();
|
|
setOptional(searchParams, "startDate", params.startDate ?? defaultRange.startDate);
|
|
setOptional(searchParams, "endDate", params.endDate ?? defaultRange.endDate);
|
|
if (params.limit !== undefined) searchParams.set("limit", String(params.limit));
|
|
|
|
return unwrap(
|
|
await client.get("api/v1/insight/stats", { searchParams }),
|
|
InsightStatsSchema
|
|
);
|
|
}
|
|
|
|
export async function getInsightRisksByTag(
|
|
client: KyInstance,
|
|
params: { tagId: string; startDate?: string; endDate?: string }
|
|
): Promise<InsightRisksByTag> {
|
|
const defaultRange = currentMonthDateRange();
|
|
const searchParams = new URLSearchParams();
|
|
searchParams.set("tagId", params.tagId);
|
|
searchParams.set("startDate", params.startDate ?? defaultRange.startDate);
|
|
searchParams.set("endDate", params.endDate ?? defaultRange.endDate);
|
|
|
|
return unwrap(
|
|
await client.get("api/v1/insight/risks-by-tag", { searchParams }),
|
|
InsightRisksByTagSchema
|
|
);
|
|
}
|
|
|
|
export async function getInsightPerformance(
|
|
client: KyInstance,
|
|
params: { startDate?: string | number; endDate?: string | number } = {}
|
|
): Promise<InsightPerformance> {
|
|
const defaultRange = currentMonthDateRange();
|
|
const startTs = normalizeToTimestamp(params.startDate ?? defaultRange.startDate);
|
|
const endTs = normalizeToTimestamp(params.endDate ?? defaultRange.endDate);
|
|
|
|
const searchParams = new URLSearchParams();
|
|
searchParams.set("startDate", String(startTs));
|
|
searchParams.set("endDate", String(endTs));
|
|
|
|
return unwrap(
|
|
await client.get("api/v1/insight/performance", { searchParams }),
|
|
InsightPerformanceSchema
|
|
);
|
|
}
|
|
|
|
export async function analyzeInsightRecord(
|
|
client: KyInstance,
|
|
recordId: string
|
|
): Promise<{ success: boolean; recordId: string }> {
|
|
await client.post(`api/v1/insight/analyze/${encodeURIComponent(recordId)}`);
|
|
return { success: true, recordId };
|
|
}
|
|
|
|
function normalizeToTimestamp(value: string | number): number {
|
|
if (typeof value === "number") {
|
|
return value < 1e11 ? value * 1000 : value;
|
|
}
|
|
const parsed = Number(value);
|
|
if (!isNaN(parsed) && value.trim() !== "") {
|
|
return parsed < 1e11 ? parsed * 1000 : parsed;
|
|
}
|
|
const date = new Date(value);
|
|
if (isNaN(date.getTime())) {
|
|
throw new Error(`Invalid date format: ${value}`);
|
|
}
|
|
return date.getTime();
|
|
}
|
|
|
|
function currentMonthDateRange(): { startDate: string; endDate: string } {
|
|
const now = new Date();
|
|
const start = new Date(now.getFullYear(), now.getMonth(), 1);
|
|
const end = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59, 999);
|
|
return {
|
|
startDate: start.toISOString(),
|
|
endDate: end.toISOString()
|
|
};
|
|
}
|
|
|
|
export type DataListParams = {
|
|
offset?: number;
|
|
limit?: number;
|
|
startDate?: string;
|
|
endDate?: string;
|
|
search?: string;
|
|
};
|
|
|
|
function dataListSearchParams(params: DataListParams): URLSearchParams {
|
|
const searchParams = new URLSearchParams();
|
|
setOptional(searchParams, "filter[startDate]", params.startDate);
|
|
setOptional(searchParams, "filter[endDate]", params.endDate);
|
|
setOptional(searchParams, "filter[search]", params.search);
|
|
searchParams.set("offset", String(params.offset ?? 0));
|
|
searchParams.set("limit", String(params.limit ?? 50));
|
|
return searchParams;
|
|
}
|
|
|
|
export async function listExpenses(
|
|
client: KyInstance,
|
|
params: DataListParams = {}
|
|
): Promise<ExpenseListData> {
|
|
return unwrap(
|
|
await client.get("api/v1/expenses/list", { searchParams: dataListSearchParams(params) }),
|
|
ExpenseListDataSchema
|
|
);
|
|
}
|
|
|
|
export async function listInvoices(
|
|
client: KyInstance,
|
|
params: DataListParams = {}
|
|
): Promise<InvoiceListData> {
|
|
return unwrap(
|
|
await client.get("api/v1/invoice/list", { searchParams: dataListSearchParams(params) }),
|
|
InvoiceListDataSchema
|
|
);
|
|
}
|
|
|
|
export async function listFeishuSimulationApprovalDefinitions(
|
|
client: KyInstance
|
|
): Promise<SimulationApprovalDefinition[]> {
|
|
return unwrap(
|
|
await client.get("api/v1/integrations/feishu/simulation/approval-definitions"),
|
|
z.array(SimulationApprovalDefinitionSchema)
|
|
);
|
|
}
|
|
|
|
export async function deleteLocalUser(
|
|
client: KyInstance,
|
|
userId: string
|
|
): Promise<boolean> {
|
|
const response = await client.delete(`api/v1/contacts/local/users/${userId}`);
|
|
const json = (await response.json()) as { data?: unknown };
|
|
const data = SuccessResponseSchema.safeParse(json.data ?? json);
|
|
return data.success ? data.data.success ?? response.ok : response.ok;
|
|
}
|
|
|
|
export async function activateLocalUser(
|
|
client: KyInstance,
|
|
userId: string
|
|
): Promise<boolean> {
|
|
const response = await client.post(`api/v1/contacts/local/users/${userId}/activate`, { json: {} });
|
|
const json = (await response.json()) as { data?: unknown };
|
|
const data = SuccessResponseSchema.safeParse(json.data ?? json);
|
|
return data.success ? data.data.success ?? response.ok : response.ok;
|
|
}
|
|
|
|
export async function loginWithPhonePassword(
|
|
client: KyInstance,
|
|
params: { phone: string; password: string }
|
|
): Promise<{ token: string; user: unknown }> {
|
|
const response = await client.post("api/auth/sms-otp/sign-in-password", {
|
|
json: params
|
|
});
|
|
const setAuthToken = response.headers.get("set-auth-token");
|
|
const json = PasswordLoginResponseSchema.parse(await response.json());
|
|
const token = setAuthToken ?? json.session?.token;
|
|
if (!token) {
|
|
throw new Error("Failed to retrieve authentication token from login response");
|
|
}
|
|
return { token, user: json.user };
|
|
}
|
|
|
|
export async function createDelegationForUser(
|
|
client: KyInstance,
|
|
params: { userIdOrPhone: string; note?: string },
|
|
createClientForToken: (token: string) => Promise<KyInstance>,
|
|
corp?: CorpConfig
|
|
): Promise<{
|
|
targetUser: SealUserDetail;
|
|
delegation: SealDelegationCreateResult;
|
|
temporaryPassword: string;
|
|
}> {
|
|
let user: SealUserDetail;
|
|
if (params.userIdOrPhone.startsWith("+") || /^\d{11}$/.test(params.userIdOrPhone)) {
|
|
const search = await searchUsers(client, params.userIdOrPhone);
|
|
const found = search.users.find(
|
|
(u) => u.mobile?.includes(params.userIdOrPhone) || u._id === params.userIdOrPhone
|
|
) ?? search.users[0];
|
|
if (!found) {
|
|
throw new Error(`User not found with phone/ID: ${params.userIdOrPhone}`);
|
|
}
|
|
user = found;
|
|
} else {
|
|
user = await getUserDetail(client, params.userIdOrPhone).catch(async () => {
|
|
const search = await searchUsers(client, params.userIdOrPhone);
|
|
// 优先精确匹配姓名,避免返回错误用户
|
|
const found =
|
|
search.users.find((u) => u.name === params.userIdOrPhone) ?? search.users[0];
|
|
if (!found) throw new Error(`User not found: ${params.userIdOrPhone}`);
|
|
return found;
|
|
});
|
|
}
|
|
|
|
if (user.status === "resigned") {
|
|
await activateLocalUser(client, user._id);
|
|
user = await getUserDetail(client, user._id);
|
|
}
|
|
|
|
const userAny = user as any;
|
|
const isSynced =
|
|
(Array.isArray(userAny.identities) &&
|
|
(userAny.identities as Array<{ provider?: string }>).some(
|
|
(i) => i.provider && i.provider !== "local"
|
|
)) ||
|
|
!!userAny.apps?.hosecloud;
|
|
|
|
if (isSynced && corp && corp.source.type === "hose") {
|
|
const rawPhone =
|
|
user.mobile ||
|
|
(userAny.identities as Array<{ providerId?: string }>)?.[0]?.providerId ||
|
|
"";
|
|
const cleanPhone = rawPhone.replace(/^\+86/, "");
|
|
const hoseIdentity = (userAny.identities as Array<{ provider?: string; providerId?: string }>)?.find(
|
|
(i) => i.provider === "hosecloud"
|
|
)?.providerId;
|
|
const staffId =
|
|
(userAny.apps?.hosecloud as { boundId?: string })?.boundId ||
|
|
hoseIdentity ||
|
|
(cleanPhone ? `${corp.source.corpId}:${cleanPhone}` : undefined);
|
|
|
|
if (staffId) {
|
|
const openapiToken = await ensureHoseOpenapiToken(corp);
|
|
const provisional = await fetchHoseCloseApiToken({ ...corp.source, staffId }, openapiToken);
|
|
const closeapiToken = provisional.token;
|
|
|
|
const sealUrl = defaultSealUrl(corp, corp.source);
|
|
const customHeaders = resolveSealCustomHeaders(corp.seal);
|
|
const sealClient = createSealClientForUrl(sealUrl, undefined, customHeaders);
|
|
let sealResponse: { token?: string; accessToken?: string; data?: { token?: string } };
|
|
try {
|
|
sealResponse = await sealClient
|
|
.get("api/auth/oauth2/session/oem-hosecloud", {
|
|
searchParams: {
|
|
token: closeapiToken,
|
|
returnToken: "1"
|
|
}
|
|
})
|
|
.json<{ token?: string; accessToken?: string; data?: { token?: string } }>();
|
|
} catch (error: unknown) {
|
|
if (error instanceof HTTPError && error.response.status === 400) {
|
|
throw new Error(`Seal AI 用户“${user.name}”未绑定合思账号,无法生成个人协助链接。`);
|
|
}
|
|
throw error;
|
|
}
|
|
|
|
const targetUserSealToken =
|
|
sealResponse.token ?? sealResponse.accessToken ?? sealResponse.data?.token;
|
|
|
|
if (targetUserSealToken) {
|
|
const userClient = await createClientForToken(targetUserSealToken);
|
|
const delegation = await createDelegation(userClient, {
|
|
note: params.note ?? `Delegation generated by admin for ${user.name}`
|
|
});
|
|
|
|
return {
|
|
targetUser: user,
|
|
delegation,
|
|
temporaryPassword: "N/A (Hose SSO)"
|
|
};
|
|
}
|
|
}
|
|
}
|
|
|
|
let resetRes: SealUserResetPasswordResult;
|
|
try {
|
|
resetRes = await resetUserPassword(client, user._id);
|
|
} catch (err: any) {
|
|
if (isSynced) {
|
|
throw new Error(
|
|
`用户 "${user.name}" (${user.mobile || user._id}) 为合思同步账号 (provider: hosecloud),无 Seal 本地密码。` +
|
|
`Seal 系统暂不支持对同步账号直接重置本地密码。`
|
|
);
|
|
}
|
|
throw err;
|
|
}
|
|
|
|
const rawPhone = user.mobile || (user as unknown as { identities?: Array<{ providerId?: string }> }).identities?.[0]?.providerId || "";
|
|
const cleanPhone = rawPhone.replace(/^\+86/, "");
|
|
if (!cleanPhone) {
|
|
throw new Error(`User ${user.name} has no associated phone number for password login`);
|
|
}
|
|
|
|
const { token } = await loginWithPhonePassword(client, {
|
|
phone: cleanPhone,
|
|
password: resetRes.password
|
|
});
|
|
|
|
const userClient = await createClientForToken(token);
|
|
const delegation = await createDelegation(userClient, {
|
|
note: params.note ?? `Delegation generated by admin for ${user.name}`
|
|
});
|
|
|
|
return {
|
|
targetUser: user,
|
|
delegation,
|
|
temporaryPassword: resetRes.password
|
|
};
|
|
}
|
|
|
|
export async function getLlmConfig(client: KyInstance): Promise<LlmConfig> {
|
|
return unwrap(await client.get("api/v1/llm/config"), LlmConfigSchema);
|
|
}
|
|
|
|
export async function listLlmProviders(client: KyInstance): Promise<LlmProvider[]> {
|
|
return unwrap(await client.get("api/v1/llm/providers"), z.array(LlmProviderSchema));
|
|
}
|
|
|
|
export async function listAvailablePermissions(client: KyInstance): Promise<AvailablePermissionsData> {
|
|
return unwrap(await client.get("api/v1/permissions/available"), AvailablePermissionsDataSchema);
|
|
}
|
|
|
|
export async function listPermissionConfigs(client: KyInstance): Promise<PermissionConfigsData> {
|
|
return unwrap(await client.get("api/v1/permissions/configs"), PermissionConfigsDataSchema);
|
|
}
|
|
|
|
export async function getBillingStatus(client: KyInstance): Promise<BillingStatusData> {
|
|
return unwrap(await client.get("api/v1/billing/status"), BillingStatusDataSchema);
|
|
}
|
|
|
|
export async function listBillingPlans(client: KyInstance): Promise<unknown> {
|
|
const response = await client.get("api/v1/billing/plans");
|
|
const json = (await response.json()) as { data?: unknown };
|
|
return JsonResponseSchema.parse(json.data ?? json);
|
|
}
|
|
|
|
export async function listBillingFeatures(client: KyInstance): Promise<unknown> {
|
|
const response = await client.get("api/v1/billing/features");
|
|
const json = (await response.json()) as { data?: unknown };
|
|
return JsonResponseSchema.parse(json.data ?? json);
|
|
}
|