From 2ca45d935e2f2725ebfd0fa691573ff4bdf83113 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Thu, 30 Jul 2026 19:13:54 +0800 Subject: [PATCH] Refine CLI service and align project metadata --- .agents/skills/seal-home/SKILL.md | 17 ++-- AGENTS.md | 2 +- README.md | 6 +- dist/openapi.json | 6 +- openapi/openapi.yaml | 9 +- skills/seal-home | 1 - src/cli.ts | 143 ++------------------------ src/cli/service.test.ts | 31 ++++++ src/cli/service.ts | 160 ++++++++++++++++++++++++++++++ src/core/auth/hose.ts | 47 ++++++--- src/domains/seal/api.ts | 47 ++++++--- 11 files changed, 285 insertions(+), 184 deletions(-) delete mode 120000 skills/seal-home create mode 100644 src/cli/service.test.ts create mode 100644 src/cli/service.ts diff --git a/.agents/skills/seal-home/SKILL.md b/.agents/skills/seal-home/SKILL.md index 2b202fb..5de8283 100644 --- a/.agents/skills/seal-home/SKILL.md +++ b/.agents/skills/seal-home/SKILL.md @@ -1,13 +1,13 @@ --- name: seal-home -version: 0.4.1 -description: "v0.4.1: Use when working with Seal Home approval automation: 合思/易快报企业认证, Hose authorization links, approval run lookup, LLM config, permissions, billing status, user search, user activation, admin delegation link generation, delegation links, approval rules, documents, search, and Langfuse hints." +version: 0.4.2 +description: "v0.4.2: Use when working with Seal Home tenant operations: target-tenant Seal delegation links, Hose/合思 authorization links, approval runs, LLM config, permissions, billing, users, rules, documents, search, and Langfuse hints." metadata: - version: 0.4.1 - short-description: Seal approval automation tools (v0.4.1) + version: 0.4.2 + short-description: Seal tenant and Hose approval automation (v0.4.2) --- -# Seal Home (v0.4.1) +# Seal Home (v0.4.2) Use the global `seal-home` CLI. This skill is a routing layer for agents: keep this file short, choose the right command, and read a focused reference only when the task needs detail. @@ -27,11 +27,14 @@ seal-home tools list - If output may be large, use `--summary`, `--fields`, `--count`, or `--output-file`; use `--full` only when the user really needs full payloads. - When returning ANY authorization, login, or delegation links (e.g. 合思授权链接, Seal授权链接/委托链接), ALWAYS provide BOTH a code block (` ```text ... ``` `) for easy copying without accidental default browser redirection, AND a clickable hyperlink. - For delegation links, always prefer `seal-home delegation create` over `users delegation` for link generation to ensure persistent token tracking. +- Never treat “Seal 协助/Seal 授权/委托” as a 合思授权入口. They are different links and must use different commands. +- A delegation link belongs to the Seal tenant selected by `--corp`; omitting `--corp` uses the current tenant and is unsafe for an explicitly named enterprise. +- For an explicitly named enterprise, first resolve it with `seal-home corps list`, then pass its exact `corpId` to every command. After creation, verify the returned URL host matches that enterprise's Seal tenant; if the host is the current/default tenant or cannot be verified, do not present the link as the target enterprise's link. ## Route By Intent -- User-facing Seal authorization / delegation link (Seal 授权链接/委托链接): `seal-home delegation create [--note ...] [--corp ]`. Always provide BOTH a code block (` ```text ... ``` `) AND a hyperlink. -- User-facing 合思 authorization link (合思授权链接): `seal-home auth hose-link --corp --expire 7200`; read `references/hose-enterprise-auth.md`. Always provide BOTH a code block (` ```text ... ``` `) AND a hyperlink. +- User-facing Seal tenant assistance link (Seal 协助/Seal 授权/委托): resolve the named enterprise first, then run `seal-home delegation create --corp --note ''`; verify the returned hostname is that tenant's Seal hostname. Always provide BOTH a code block (` ```text ... ``` `) AND a hyperlink. +- User-facing 合思 authorization link (合思/易快报授权): `seal-home auth hose-link --corp --expire 7200`; read `references/hose-enterprise-auth.md`. Never use this route when the user says Seal 协助. Always provide BOTH a code block (` ```text ... ``` `) AND a hyperlink. - Delegation links management: `seal-home delegation list`, `create [--note ...]`, `revoke `. - User & Contacts Management (用户搜索、激活与一键代生成授权): `seal-home users search [keyword]`, `users delegation ` (仅适用于 Seal 本地创建的账号 `provider: local`;对合思同步账号系统拒绝重置密码,需改用 `auth hose-link`), `users activate `, `users create --name ... --phone ...`, `reset-password `, `get `, `delete `. - LLM Model Config & Providers: `seal-home llm config`, `seal-home llm providers`. diff --git a/AGENTS.md b/AGENTS.md index d55431e..5e417fe 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,7 +4,7 @@ This is a Bun + TypeScript toolkit for the `seal-home` CLI and optional MCP server. Entry points are `src/cli.ts`, `src/server.ts`, and `src/probe.ts`. Shared config, auth, token, and HTTP code is under `src/core/`. Seal-specific API and tool logic is under `src/domains/seal/`. -Tests are colocated as `*.test.ts` files in `src/`. OpenAPI source YAML lives in `openapi/`; bundled output is `dist/openapi.json`. Example enterprise configs are in `enterprises/example.*.json`; real configs must stay untracked. Project skills live under `skills/seal-home/`. +Tests are colocated as `*.test.ts` files in `src/`. OpenAPI source YAML lives in `openapi/`; bundled output is `dist/openapi.json`. Example enterprise configs are in `enterprises/example.*.json`; real configs must stay untracked. The project skill lives under `.agents/skills/seal-home/`. ## Build, Test, and Development Commands diff --git a/README.md b/README.md index a7c886c..4142666 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ enterprises/*.json !enterprises/example.*.json ``` -The standard Codex skill lives at `skills/seal-home`. Install or copy that folder into a Codex skills directory when you want Codex to invoke the workflow as `$seal-home`. +The standard Codex skill lives at `.agents/skills/seal-home`. Install or copy that folder into a Codex skills directory when you want Codex to invoke the workflow as `$seal-home`. ## CLI @@ -112,7 +112,7 @@ Use `seal-home auth diagnose [--corp ]` when login fails. It reports fou ## Wrapped API Documentation -The OpenAPI source under `openapi/` describes the seal-home wrapped API for frontend developers and agents. It is intentionally not the raw downstream Seal API: endpoints are named around seal-home concepts such as corps, auth diagnosis, approval context, run summaries, document URLs, and Langfuse bridge hints. +The OpenAPI source under `openapi/` describes the planned HTTP contract for a seal-home wrapped API. The current implementation exposes the MCP server over stdio and does not listen on the OpenAPI server URL. It is intentionally not the raw downstream Seal API: endpoints are named around seal-home concepts such as corps, auth diagnosis, approval context, run summaries, document URLs, and Langfuse bridge hints. Source files are split by domain: @@ -146,7 +146,7 @@ Service state is stored under `~/.config/seal-home/`: - `service.pid` - `service.log` -The service is intentionally local. It is useful as a stable process lifecycle for future warmed caches and update/restart workflows; normal CLI commands still work without it. +The service is intentionally local and currently acts as a lifecycle wrapper for a long-lived stdio/MCP process; it does not expose the HTTP/OpenAPI contract. It is useful as a stable process lifecycle for future warmed caches and update/restart workflows; normal CLI commands still work without it. ## Enterprise Config diff --git a/dist/openapi.json b/dist/openapi.json index ad4486e..eac97d4 100644 --- a/dist/openapi.json +++ b/dist/openapi.json @@ -2,13 +2,13 @@ "openapi": "3.1.0", "info": { "title": "seal-home Wrapped API", - "version": "0.3.3", - "description": "HTTP contract for the seal-home wrapped backend API.\n\nThese endpoints describe the stable API that frontend developers and agents should use.\nThey are not the raw downstream Seal endpoints. seal-home is responsible for enterprise\nselection, source authentication, response compaction, and diagnostics-friendly fields.\n" + "version": "0.4.2", + "description": "Planned HTTP contract for the seal-home wrapped backend API.\n\nThese endpoints describe the intended stable API for frontend developers and agents once\nthe HTTP adapter is implemented.\nThey are not the raw downstream Seal endpoints. seal-home is responsible for enterprise\nselection, source authentication, response compaction, and diagnostics-friendly fields.\n" }, "servers": [ { "url": "http://localhost:8787", - "description": "Local seal-home service" + "description": "Reserved for a future local HTTP adapter; the current service uses MCP stdio." } ], "security": [ diff --git a/openapi/openapi.yaml b/openapi/openapi.yaml index 2fcc7c6..9578623 100644 --- a/openapi/openapi.yaml +++ b/openapi/openapi.yaml @@ -1,16 +1,17 @@ openapi: 3.1.0 info: title: seal-home Wrapped API - version: 0.3.3 + version: 0.4.2 description: | - HTTP contract for the seal-home wrapped backend API. + Planned HTTP contract for the seal-home wrapped backend API. - These endpoints describe the stable API that frontend developers and agents should use. + These endpoints describe the intended stable API for frontend developers and agents once + the HTTP adapter is implemented. They are not the raw downstream Seal endpoints. seal-home is responsible for enterprise selection, source authentication, response compaction, and diagnostics-friendly fields. servers: - url: http://localhost:8787 - description: Local seal-home service + description: Reserved for a future local HTTP adapter; the current service uses MCP stdio. security: - localSession: [] tags: diff --git a/skills/seal-home b/skills/seal-home deleted file mode 120000 index 49326da..0000000 --- a/skills/seal-home +++ /dev/null @@ -1 +0,0 @@ -.agents/skills/seal-home \ No newline at end of file diff --git a/src/cli.ts b/src/cli.ts index 6c7b3a6..a09a9f1 100755 --- a/src/cli.ts +++ b/src/cli.ts @@ -1,7 +1,7 @@ #!/usr/bin/env bun -import { spawn, spawnSync } from "node:child_process"; -import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; @@ -14,11 +14,10 @@ import { CorpConfig } from "./core/config/types.js"; import { clearCorpTokenCache } from "./core/auth/token-store.js"; import { getHoseProvisionalAuthLink } from "./core/auth/hose.js"; import { VERSION } from "./version.js"; +import { runServiceCommand, serviceStatus } from "./cli/service.js"; const APP_ROOT = dirname(dirname(fileURLToPath(import.meta.url))); const STATE_DIR = join(homedir(), ".config", "seal-home"); -const SERVICE_PID_FILE = join(STATE_DIR, "service.pid"); -const SERVICE_LOG_FILE = join(STATE_DIR, "service.log"); const CURRENT_CORP_FILE = join(STATE_DIR, "current-corp"); const RULE_LIST_FULL_COUNT_LIMIT = 100; const RULE_LIST_FULL_BYTES_LIMIT = 120_000; @@ -67,7 +66,7 @@ async function main() { } if (area === "service") { - await runServiceCommand(action); + await runServiceCommand(action, { appRoot: APP_ROOT, entryFile: fileURLToPath(import.meta.url), stateDir: STATE_DIR, version: VERSION }); return; } @@ -484,121 +483,15 @@ async function main() { throw new Error(`Unknown command: ${args.command.join(" ")}. Run 'seal-home help' for available commands.`); } -async function runServiceCommand(action?: string) { - switch (action) { - case "run": - await runService(); - return; - case "start": - startService(); - return; - case "stop": - stopService(); - return; - case "restart": - stopService({ quiet: true }); - startService(); - return; - case "status": - case undefined: - printJson(serviceStatus()); - return; - default: - throw new Error("Usage: seal-home service "); - } -} - -async function runService() { - ensureStateDir(); - writeFileSync(SERVICE_PID_FILE, `${process.pid}\n`); - appendLog(`running pid=${process.pid}`); - - const cleanup = () => { - if (readServicePid() === process.pid) { - rmSync(SERVICE_PID_FILE, { force: true }); - } - appendLog(`stopped pid=${process.pid}`); - }; - - process.on("SIGTERM", () => { - cleanup(); - process.exit(0); - }); - process.on("SIGINT", () => { - cleanup(); - process.exit(0); - }); - - setInterval(() => { - // Keep the process alive for warmed auth/search caches in this runtime. - }, 60_000); - - await new Promise(() => {}); -} - -function startService() { - ensureStateDir(); - const current = serviceStatus(); - if (current.running) { - printJson(current); - return; - } - - const child = spawn(process.execPath, [fileURLToPath(import.meta.url), "service", "run"], { - cwd: APP_ROOT, - detached: true, - stdio: ["ignore", "ignore", "ignore"], - env: process.env - }); - child.unref(); - - writeFileSync(SERVICE_PID_FILE, `${child.pid}\n`); - appendLog(`started pid=${child.pid}`); - printJson({ - started: true, - ...serviceStatus() - }); -} - -function stopService(options: { quiet?: boolean } = {}) { - const pid = readServicePid(); - if (!pid) { - if (!options.quiet) printJson({ stopped: false, reason: "not running" }); - return; - } - - if (isProcessRunning(pid)) { - process.kill(pid, "SIGTERM"); - } - rmSync(SERVICE_PID_FILE, { force: true }); - appendLog(`stop requested pid=${pid}`); - - if (!options.quiet) { - printJson({ stopped: true, pid }); - } -} - -function serviceStatus() { - const pid = readServicePid(); - return { - running: pid ? isProcessRunning(pid) : false, - pid, - version: VERSION, - appRoot: APP_ROOT, - stateDir: STATE_DIR, - pidFile: SERVICE_PID_FILE, - logFile: SERVICE_LOG_FILE - }; -} - function updateAndRestart() { - const wasRunning = serviceStatus().running; - if (wasRunning) stopService({ quiet: true }); + const serviceConfig = { appRoot: APP_ROOT, entryFile: fileURLToPath(import.meta.url), stateDir: STATE_DIR, version: VERSION }; + const wasRunning = serviceStatus(serviceConfig).running; + if (wasRunning) runServiceCommand("stop", serviceConfig); runCommand("git", ["-C", APP_ROOT, "pull", "--ff-only"]); runCommand("bun", ["install"], { cwd: APP_ROOT }); - if (wasRunning) startService(); + if (wasRunning) runServiceCommand("start", serviceConfig); printJson({ updated: true, @@ -1302,26 +1195,6 @@ function ensureStateDir() { mkdirSync(STATE_DIR, { recursive: true }); } -function readServicePid(): number | undefined { - if (!existsSync(SERVICE_PID_FILE)) return undefined; - const pid = Number(readFileSync(SERVICE_PID_FILE, "utf-8").trim()); - return Number.isInteger(pid) && pid > 0 ? pid : undefined; -} - -function isProcessRunning(pid: number): boolean { - try { - process.kill(pid, 0); - return true; - } catch { - return false; - } -} - -function appendLog(message: string) { - ensureStateDir(); - writeFileSync(SERVICE_LOG_FILE, `${new Date().toISOString()} ${message}\n`, { flag: "a" }); -} - function printJson(value: unknown, options: OutputOptions = {}) { protectLargeOutput(value, options); const json = `${JSON.stringify(value, null, 2)}\n`; diff --git a/src/cli/service.test.ts b/src/cli/service.test.ts new file mode 100644 index 0000000..9d0afd1 --- /dev/null +++ b/src/cli/service.test.ts @@ -0,0 +1,31 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { serviceStatus } from "./service.js"; + +const tempDirs: string[] = []; + +afterEach(() => { + for (const dir of tempDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }); + } +}); + +describe("service lifecycle state", () => { + test("clears a stale pid file instead of reporting another process as running", () => { + const stateDir = mkdtempSync(join(tmpdir(), "seal-home-service-")); + tempDirs.push(stateDir); + writeFileSync(join(stateDir, "service.pid"), "999999\n"); + + const status = serviceStatus({ + appRoot: "/tmp/seal-home", + entryFile: "/tmp/seal-home/src/cli.ts", + stateDir, + version: "0.4.2" + }); + + expect(status.running).toBe(false); + expect(status.pid).toBeUndefined(); + }); +}); diff --git a/src/cli/service.ts b/src/cli/service.ts new file mode 100644 index 0000000..f89bbbc --- /dev/null +++ b/src/cli/service.ts @@ -0,0 +1,160 @@ +import { spawn, execFileSync } from "node:child_process"; +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; + +export type ServiceConfig = { + appRoot: string; + entryFile: string; + stateDir: string; + version?: string; +}; + +export async function runServiceCommand(action: string | undefined, config: ServiceConfig) { + switch (action) { + case "run": + await runService(config); + return; + case "start": + startService(config); + return; + case "stop": + stopService(config); + return; + case "restart": + stopService(config, { quiet: true }); + startService(config); + return; + case "status": + case undefined: + console.log(JSON.stringify(serviceStatus(config), null, 2)); + return; + default: + throw new Error("Usage: seal-home service "); + } +} + +export function serviceStatus(config: ServiceConfig) { + const pidFile = getPidFile(config); + const pid = readServicePid(pidFile); + const running = pid ? isSealHomeProcess(pid, config.appRoot) : false; + + if (pid && !running) { + rmSync(pidFile, { force: true }); + } + + return { + running, + pid: running ? pid : undefined, + version: config.version, + appRoot: config.appRoot, + stateDir: config.stateDir, + pidFile, + logFile: getLogFile(config) + }; +} + +async function runService(config: ServiceConfig) { + const pidFile = getPidFile(config); + const logFile = getLogFile(config); + ensureStateDir(config.stateDir); + writeFileSync(pidFile, `${process.pid}\n`, { mode: 0o600 }); + appendLog(logFile, `running pid=${process.pid}`); + + const cleanup = () => { + if (readServicePid(pidFile) === process.pid) { + rmSync(pidFile, { force: true }); + } + appendLog(logFile, `stopped pid=${process.pid}`); + }; + + process.on("SIGTERM", () => { + cleanup(); + process.exit(0); + }); + process.on("SIGINT", () => { + cleanup(); + process.exit(0); + }); + + setInterval(() => {}, 60_000); + await new Promise(() => {}); +} + +function startService(config: ServiceConfig) { + ensureStateDir(config.stateDir); + const current = serviceStatus(config); + if (current.running) { + console.log(JSON.stringify(current, null, 2)); + return; + } + + const child = spawn(process.execPath, [config.entryFile, "service", "run"], { + cwd: config.appRoot, + detached: true, + stdio: ["ignore", "ignore", "ignore"], + env: process.env + }); + child.unref(); + + const pidFile = getPidFile(config); + writeFileSync(pidFile, `${child.pid}\n`, { mode: 0o600 }); + appendLog(getLogFile(config), `started pid=${child.pid}`); + console.log(JSON.stringify({ started: true, ...serviceStatus(config) }, null, 2)); +} + +function stopService(config: ServiceConfig, options: { quiet?: boolean } = {}) { + const pidFile = getPidFile(config); + const pid = readServicePid(pidFile); + if (!pid || !isSealHomeProcess(pid, config.appRoot)) { + rmSync(pidFile, { force: true }); + if (!options.quiet) console.log(JSON.stringify({ stopped: false, reason: "not running" }, null, 2)); + return; + } + + process.kill(pid, "SIGTERM"); + rmSync(pidFile, { force: true }); + appendLog(getLogFile(config), `stop requested pid=${pid}`); + if (!options.quiet) console.log(JSON.stringify({ stopped: true, pid }, null, 2)); +} + +function isSealHomeProcess(pid: number, appRoot: string) { + if (!isProcessRunning(pid)) return false; + + try { + const command = execFileSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" }); + return command.includes(appRoot) && command.includes("service") && command.includes("run"); + } catch { + return false; + } +} + +function isProcessRunning(pid: number) { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +function getPidFile(config: ServiceConfig) { + return join(config.stateDir, "service.pid"); +} + +function getLogFile(config: ServiceConfig) { + return join(config.stateDir, "service.log"); +} + +function readServicePid(path: string): number | undefined { + if (!existsSync(path)) return undefined; + const pid = Number(readFileSync(path, "utf8").trim()); + return Number.isInteger(pid) && pid > 0 ? pid : undefined; +} + +function ensureStateDir(stateDir: string) { + mkdirSync(stateDir, { recursive: true, mode: 0o700 }); +} + +function appendLog(path: string, message: string) { + writeFileSync(path, `${new Date().toISOString()} ${message}\n`, { flag: "a", mode: 0o600 }); +} diff --git a/src/core/auth/hose.ts b/src/core/auth/hose.ts index a0f4a6c..ef04c0c 100644 --- a/src/core/auth/hose.ts +++ b/src/core/auth/hose.ts @@ -40,6 +40,9 @@ type SealTokenResponse = { }; }; +const openapiTokenRequests = new Map>(); +const closeApiTokenRequests = new Map>(); + export function normalizeBaseUrl(url: string): string { return url.replace(/\/+$/, ""); } @@ -112,18 +115,25 @@ export async function ensureHoseOpenapiToken(corp: CorpConfig): Promise if (corp.source.type !== "hose") { throw new Error(`Unsupported Seal source: ${corp.source.type}`); } - const cache = getHoseAuthCache(corp.id); if (isFresh(cache.openapi)) { return cache.openapi.token; } - const openapi = await fetchHoseOpenapiToken(corp.source); - setHoseAuthCache(corp.id, { - ...cache, - openapi - }); - return openapi.token; + const pending = openapiTokenRequests.get(corp.id); + if (pending) return pending; + + const request = fetchHoseOpenapiToken(corp.source) + .then((openapi) => { + setHoseAuthCache(corp.id, { + ...getHoseAuthCache(corp.id), + openapi + }); + return openapi.token; + }) + .finally(() => openapiTokenRequests.delete(corp.id)); + openapiTokenRequests.set(corp.id, request); + return request; } export async function fetchHoseCloseApiToken( @@ -168,19 +178,28 @@ async function ensureHoseCloseApiToken(corp: CorpConfig): Promise { if (corp.source.type !== "hose") { throw new Error(`Unsupported Seal source: ${corp.source.type}`); } + const source = corp.source; const cache = getHoseAuthCache(corp.id); if (isFresh(cache.closeapi) && cache.closeapi.url) { return cache.closeapi; } - const openapiToken = await ensureHoseOpenapiToken(corp); - const closeapi = await fetchHoseCloseApiToken(corp.source, openapiToken); - setHoseAuthCache(corp.id, { - ...getHoseAuthCache(corp.id), - closeapi - }); - return closeapi; + const pending = closeApiTokenRequests.get(corp.id); + if (pending) return pending; + + const request = ensureHoseOpenapiToken(corp) + .then((openapiToken) => fetchHoseCloseApiToken(source, openapiToken)) + .then((closeapi) => { + setHoseAuthCache(corp.id, { + ...getHoseAuthCache(corp.id), + closeapi + }); + return closeapi; + }) + .finally(() => closeApiTokenRequests.delete(corp.id)); + closeApiTokenRequests.set(corp.id, request); + return request; } export async function getHoseEnterpriseUrl(corp: CorpConfig): Promise { diff --git a/src/domains/seal/api.ts b/src/domains/seal/api.ts index d15ca88..bf134a6 100644 --- a/src/domains/seal/api.ts +++ b/src/domains/seal/api.ts @@ -47,6 +47,16 @@ import { BillingStatusDataSchema } 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(response: Response, schema: z.ZodType): Promise { const json = (await response.json()) as { data?: unknown }; return schema.parse(json.data ?? json); @@ -86,11 +96,15 @@ export async function deleteApprovalRule(client: KyInstance, ruleId: string): Pr export async function recodeApprovalRules(client: KyInstance): Promise { const response = await client.post("api/v1/rules/batch-recode", { throwHttpErrors: false }); const body = await response.json().catch(() => ({})); - return { + 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 { @@ -349,8 +363,9 @@ export async function createDelegation( export async function revokeDelegation(client: KyInstance, tokenId: string): Promise { const response = await client.post("api/v1/delegation/revoke", { json: { tokenId } }); - const json = (await response.json()) as { data?: { success?: boolean } }; - return json.data?.success ?? response.ok; + 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( @@ -359,10 +374,9 @@ export async function createLocalUser( ): Promise { 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?: { items?: Array<{ _id: string }> }; - }; - const firstId = rootDepts.data?.items?.[0]?._id; + 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]; } @@ -415,8 +429,9 @@ export async function deleteLocalUser( userId: string ): Promise { const response = await client.delete(`api/v1/contacts/local/users/${userId}`); - const json = (await response.json()) as { data?: { success?: boolean } }; - return json.data?.success ?? response.ok; + 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( @@ -424,8 +439,9 @@ export async function activateLocalUser( userId: string ): Promise { const response = await client.post(`api/v1/contacts/local/users/${userId}/activate`, { json: {} }); - const json = (await response.json()) as { data?: { success?: boolean } }; - return json.data?.success ?? response.ok; + 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( @@ -436,7 +452,7 @@ export async function loginWithPhonePassword( json: params }); const setAuthToken = response.headers.get("set-auth-token"); - const json = (await response.json()) as { user?: unknown; session?: { token?: string } }; + 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"); @@ -595,14 +611,13 @@ export async function getBillingStatus(client: KyInstance): Promise { const response = await client.get("api/v1/billing/plans"); const json = (await response.json()) as { data?: unknown }; - return json.data ?? json; + return JsonResponseSchema.parse(json.data ?? json); } export async function listBillingFeatures(client: KyInstance): Promise { const response = await client.get("api/v1/billing/features"); const json = (await response.json()) as { data?: unknown }; - return json.data ?? json; + return JsonResponseSchema.parse(json.data ?? json); } -