Refine CLI service and align project metadata

This commit is contained in:
gitea committed 2026-07-30 19:13:54 +08:00
1 parent 802c32c6bd
commit 2ca45d935e
11 files changed
+285 -184

No files matched your search

+8 -135
View File
@@ -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 <start|stop|restart|status>");
}
}
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`;
+31
View File
@@ -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();
});
});
+160
View File
@@ -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 <start|stop|restart|status>");
}
}
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 });
}
+33 -14
View File
@@ -40,6 +40,9 @@ type SealTokenResponse = {
};
};
const openapiTokenRequests = new Map<string, Promise<string>>();
const closeApiTokenRequests = new Map<string, Promise<TokenEntry>>();
export function normalizeBaseUrl(url: string): string {
return url.replace(/\/+$/, "");
}
@@ -112,18 +115,25 @@ export async function ensureHoseOpenapiToken(corp: CorpConfig): Promise<string>
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<TokenEntry> {
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<string> {
+31 -16
View File
@@ -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<T>(response: Response, schema: z.ZodType<T>): Promise<T> {
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<unknown> {
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<RuleSetVersion[]> {
@@ -349,8 +363,9 @@ export async function createDelegation(
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?: { 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<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?: { 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<boolean> {
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<boolean> {
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<BillingStatu
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 json.data ?? json;
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 json.data ?? json;
return JsonResponseSchema.parse(json.data ?? json);
}