import { defineCommand } from "citty"; import consola from "consola"; import type { PluginCapabilityUseChainRow, VerifyChainResult } from "@hivegrid/plugin-runtime"; const PLUGIN_AUDIT_VERIFY_BATCH_SIZE = 5_000; export type PluginCapabilityUseChainStoredRow = PluginCapabilityUseChainRow & { readonly prevHash?: string | null; readonly rowHash?: string | null; }; export type PluginsVerifyAuditChainArgs = { tenantId: string; pluginId?: string | null; from?: string | null; to?: string | null; json?: boolean; }; export type PluginsVerifyAuditChainDeps = { readRows: (args: { tenantId: string; from: Date | null; to: Date | null; batchSize: number }) => AsyncIterable; verify: (rows: ReadonlyArray) => VerifyChainResult; output: { error: (message: string) => void; info: (message: string) => void; json: (value: unknown) => void; }; }; export type PluginsVerifyAuditChainOutcome = { exitCode: 0 | 1; matchingPluginRows: number; ok: boolean; rowCount: number; }; function parseIsoDate(raw: string | null | undefined, label: string): Date | null { if (!raw || raw.length === 0) return null; const date = new Date(raw); if (Number.isNaN(date.getTime())) { throw new Error(`Invalid --${label} value ${JSON.stringify(raw)} (expected ISO-8601).`); } return date; } export async function runPluginsVerifyAuditChain( args: PluginsVerifyAuditChainArgs, deps: PluginsVerifyAuditChainDeps ): Promise { const tenantId = args.tenantId.trim(); if (tenantId.length === 0) { deps.output.error("Missing --tenantId."); return { exitCode: 1, matchingPluginRows: 0, ok: false, rowCount: 0 }; } const pluginId = args.pluginId?.trim() || null; const from = parseIsoDate(args.from ?? null, "from"); const to = parseIsoDate(args.to ?? null, "to"); const rows: PluginCapabilityUseChainStoredRow[] = []; for await (const row of deps.readRows({ tenantId, from, to, batchSize: PLUGIN_AUDIT_VERIFY_BATCH_SIZE })) { rows.push(row); } const matchingPluginRows = pluginId ? rows.filter((row) => row.pluginId === pluginId).length : rows.length; const result = deps.verify(rows); const payload = { tenantId, pluginId, from: from?.toISOString() ?? null, to: to?.toISOString() ?? null, rowCount: rows.length, matchingPluginRows, ok: result.ok, firstBreak: result.ok ? null : result, }; if (args.json) { deps.output.json(payload); } else if (result.ok) { deps.output.info( `plugin capability-use chain OK — tenant=${tenantId} rows=${rows.length}` + (pluginId ? ` matchingPluginRows=${matchingPluginRows} pluginId=${pluginId}` : "") ); } else { deps.output.error( `plugin capability-use chain BROKEN — tenant=${tenantId} rows=${rows.length}` + ` firstBreakId=${result.brokenRowId} reason=${result.reason}` + (pluginId ? ` matchingPluginRows=${matchingPluginRows} pluginId=${pluginId}` : "") ); } return { exitCode: result.ok ? 0 : 1, matchingPluginRows, ok: result.ok, rowCount: rows.length }; } export const pluginsVerifyAuditChainCommand = defineCommand({ meta: { name: "verify-audit-chain", description: "Verify tenant PluginCapabilityUse hash-chain integrity.", }, args: { tenantId: { type: "string", required: true, description: "Tenant ID whose capability-use chain should be verified." }, pluginId: { type: "string", required: false, description: "Optional plugin id to include matching-row counts in output. The full tenant chain is still verified." }, from: { type: "string", required: false, description: "Lower bound (inclusive) ISO-8601 timestamp." }, to: { type: "string", required: false, description: "Upper bound (exclusive) ISO-8601 timestamp." }, json: { type: "boolean", required: false, default: false, description: "Emit one JSON object instead of human-readable text." }, }, async run({ args }) { const { getReadDbClient } = await import("@hivegrid/db/client.server"); const { verifyPluginCapabilityUseChain } = await import("@hivegrid/plugin-runtime"); const db = getReadDbClient(); async function* readRows(opts: { tenantId: string; from: Date | null; to: Date | null; batchSize: number; }): AsyncIterable { const where: Record = { tenantId: opts.tenantId }; if (opts.from || opts.to) { const range: Record = {}; if (opts.from) range.gte = opts.from; if (opts.to) range.lt = opts.to; where.timestamp = range; } let cursor: string | undefined; while (true) { const page = (await db.pluginCapabilityUse.findMany({ where, orderBy: [{ timestamp: "asc" }, { id: "asc" }], take: opts.batchSize, ...(cursor ? { skip: 1, cursor: { id: cursor } } : {}), })) as Array & { timestamp: Date | string }>; for (const row of page) { yield { ...row, timestamp: row.timestamp instanceof Date ? row.timestamp.toISOString() : String(row.timestamp), }; } if (page.length < opts.batchSize) return; cursor = page[page.length - 1]?.id; } } try { const outcome = await runPluginsVerifyAuditChain( { tenantId: String(args.tenantId), pluginId: args.pluginId ? String(args.pluginId) : null, from: args.from ? String(args.from) : null, to: args.to ? String(args.to) : null, json: Boolean(args.json), }, { readRows, verify: verifyPluginCapabilityUseChain, output: { error: (message) => consola.error(message), info: (message) => consola.success(message), json: (value) => consola.log(JSON.stringify(value)), }, } ); process.exitCode = outcome.exitCode; } catch (error) { consola.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; } }, });