Reorganize repo structure and standards references

This commit is contained in:
david committed 2026-06-29 05:03:42 +02:00
1 parent 3cb93a81be
commit be2054274d
5885 files changed
+2588 -195

No files matched your search

@@ -0,0 +1,137 @@
import { describe, expect, it, vi } from "vitest";
import type { AuditPdfEvent, AuditPdfIntegrity, AuditPdfReportInput } from "@toolctrl/exports/audit-pdf";
import { runAuditExportPdf, type AuditExportPdfDependencies } from "./export-pdf.js";
function makeEvent(over: Partial<AuditPdfEvent> = {}): AuditPdfEvent {
return {
id: "audit_1",
createdAt: new Date("2026-05-17T00:00:00.000Z"),
tenantId: "tenant_1",
actorType: "user",
actorId: "user_1",
actorEmail: null,
actorIp: null,
actorUserAgent: null,
action: "widget.created",
targetType: "widget",
targetId: "widget_1",
requestId: null,
sourceModule: "crm",
outcome: "success",
dataSensitivity: "internal",
regulatoryScope: ["soc2"],
metadata: null,
previousHash: null,
eventHash: "h1",
...over,
};
}
type TestState = {
writtenPath: string | null;
writtenBytes: Uint8Array | null;
renderInput: AuditPdfReportInput | null;
};
function makeDeps(opts: {
events: ReadonlyArray<AuditPdfEvent>;
integrity?: AuditPdfIntegrity;
}): {
deps: AuditExportPdfDependencies;
state: TestState;
logger: { info: ReturnType<typeof vi.fn>; error: ReturnType<typeof vi.fn> };
} {
const state: TestState = { writtenPath: null, writtenBytes: null, renderInput: null };
const logger = { info: vi.fn(), error: vi.fn() };
const deps: AuditExportPdfDependencies = {
loadEvents: async () => opts.events,
verify: () => opts.integrity ?? { ok: true, inspected: opts.events.length, firstBreakId: null, reason: null },
render: async (input) => {
state.renderInput = input;
// Fake PDF bytes — the renderer is unit-tested separately in
// @toolctrl/exports.
return new Uint8Array([0x25, 0x50, 0x44, 0x46, 0x2d, 0x31, 0x2e, 0x37]); // "%PDF-1.7"
},
writeOutput: async (path, bytes) => {
state.writtenPath = path;
state.writtenBytes = bytes;
},
logger,
now: () => new Date("2026-05-17T12:00:00.000Z"),
};
return { deps, state, logger };
}
describe("runAuditExportPdf", () => {
it("rejects empty --tenant", async () => {
const { deps, logger } = makeDeps({ events: [] });
const out = await runAuditExportPdf({ tenant: " ", out: "/tmp/x.pdf" }, deps);
expect(out.exitCode).toBe(1);
expect(logger.error).toHaveBeenCalledWith(expect.stringContaining("Missing --tenant"));
});
it("rejects missing --out", async () => {
const { deps, logger } = makeDeps({ events: [] });
const out = await runAuditExportPdf({ tenant: "t1", out: "" }, deps);
expect(out.exitCode).toBe(1);
expect(logger.error).toHaveBeenCalledWith(expect.stringContaining("Missing --out"));
});
it("renders + writes a PDF and exits 0 when the chain is intact", async () => {
const events = [makeEvent(), makeEvent({ id: "audit_2", action: "widget.updated", previousHash: "h1", eventHash: "h2" })];
const { deps, state, logger } = makeDeps({ events });
const out = await runAuditExportPdf(
{
tenant: "tenant_1",
from: "2026-05-01T00:00:00.000Z",
to: "2026-05-17T00:00:00.000Z",
regulatoryScope: "soc2",
out: "/tmp/report.pdf",
generatedBy: "ops-bot",
},
deps
);
expect(out.exitCode).toBe(0);
expect(out.rowCount).toBe(2);
expect(state.writtenPath).toBe("/tmp/report.pdf");
expect(state.writtenBytes?.[0]).toBe(0x25); // '%'
expect(state.renderInput?.tenantId).toBe("tenant_1");
expect(state.renderInput?.filterSummary).toContain("regulatoryScope=soc2");
expect(state.renderInput?.events).toHaveLength(2);
expect(state.renderInput?.integrity.ok).toBe(true);
expect(logger.info).toHaveBeenCalledWith(expect.stringContaining("audit-pdf written"));
});
it("treats tenant=__platform__ as null tenantId in the loader", async () => {
const events: AuditPdfEvent[] = [];
let captured: { tenantId: string | null } | null = null;
const { deps: baseDeps } = makeDeps({ events });
const deps: AuditExportPdfDependencies = {
...baseDeps,
loadEvents: async (args) => {
captured = { tenantId: args.tenantId };
return events;
},
};
await runAuditExportPdf({ tenant: "__platform__", out: "/tmp/x.pdf" }, deps);
expect(captured).toEqual({ tenantId: null });
});
it("exits 1 when integrity is broken — but still writes the file as evidence", async () => {
const events = [makeEvent()];
const { deps, state, logger } = makeDeps({
events,
integrity: { ok: false, inspected: 1, firstBreakId: "audit_1", reason: "hash-mismatch" },
});
const out = await runAuditExportPdf({ tenant: "t1", out: "/tmp/x.pdf" }, deps);
expect(out.exitCode).toBe(1);
expect(state.writtenPath).toBe("/tmp/x.pdf");
expect(logger.error).toHaveBeenCalledWith(expect.stringContaining("BROKEN CHAIN"));
});
it("throws when --from is not parseable", async () => {
const { deps } = makeDeps({ events: [] });
await expect(runAuditExportPdf({ tenant: "t1", from: "garbage", out: "/tmp/x.pdf" }, deps)).rejects.toThrow(/Invalid --from/);
});
});
@@ -0,0 +1,218 @@
/**
* `toolctrl audit export-pdf --tenant <id> [--from] [--to] [--regulatory-scope]
* --out <path>`
*
* Renders a tamper-evident PDF compliance report from AuditEvent rows for
* the given tenant and time-range. The report header includes a
* `verifyAuditChain` integrity check; the body lists each event in
* chronological order with hash + actor + outcome + scope.
*
* Renders via @react-pdf/renderer through `@toolctrl/exports/audit-pdf`.
*
* See docs/improvement-plan/10-compliance-polish/compliance-audit-export.md.
*/
import { writeFile } from "node:fs/promises";
import { defineCommand } from "citty";
import consola from "consola";
import type { AuditPdfEvent, AuditPdfIntegrity, AuditPdfReportInput } from "@toolctrl/exports/audit-pdf";
const AUDIT_PDF_QUERY_LIMIT = 5_000;
export type AuditExportPdfArgs = {
tenant: string;
from?: string | null;
to?: string | null;
regulatoryScope?: string | null;
out: string;
generatedBy?: string | null;
};
export type AuditExportPdfDependencies = {
/** Load matching AuditEvent rows in chronological order. */
loadEvents: (args: {
tenantId: string | null;
from: Date | null;
to: Date | null;
regulatoryScope: string | null;
limit: number;
}) => Promise<ReadonlyArray<AuditPdfEvent>>;
/** Compute hash-chain integrity over the loaded events. */
verify: (events: ReadonlyArray<AuditPdfEvent>) => AuditPdfIntegrity;
/** Render the PDF document to a byte buffer. */
render: (input: AuditPdfReportInput) => Promise<Uint8Array>;
/** Write the rendered bytes to the chosen output path. */
writeOutput: (path: string, bytes: Uint8Array) => Promise<void>;
/** Logger sink. */
logger: {
info: (msg: string) => void;
error: (msg: string) => void;
};
/** Optional `now` clock for tests. */
now?: () => Date;
};
export type AuditExportPdfOutcome = {
exitCode: 0 | 1;
rowCount: number;
byteLength: number;
outPath: string;
};
function parseIsoDate(raw: string | null | undefined, label: string): Date | null {
if (!raw || raw.length === 0) return null;
const d = new Date(raw);
if (Number.isNaN(d.getTime())) {
throw new Error(`Invalid --${label} value ${JSON.stringify(raw)} (expected ISO-8601).`);
}
return d;
}
export async function runAuditExportPdf(
args: AuditExportPdfArgs,
deps: AuditExportPdfDependencies
): Promise<AuditExportPdfOutcome> {
const tenantArg = args.tenant.trim();
if (tenantArg.length === 0) {
deps.logger.error("Missing --tenant.");
return { exitCode: 1, rowCount: 0, byteLength: 0, outPath: args.out };
}
if (!args.out || args.out.trim().length === 0) {
deps.logger.error("Missing --out.");
return { exitCode: 1, rowCount: 0, byteLength: 0, outPath: args.out };
}
const from = parseIsoDate(args.from ?? null, "from");
const to = parseIsoDate(args.to ?? null, "to");
const tenantId = tenantArg === "__platform__" ? null : tenantArg;
const regulatoryScope = args.regulatoryScope?.trim() || null;
const events = await deps.loadEvents({ tenantId, from, to, regulatoryScope, limit: AUDIT_PDF_QUERY_LIMIT });
const integrity = deps.verify(events);
const filterSummary = [
regulatoryScope ? `regulatoryScope=${regulatoryScope}` : null,
]
.filter((s): s is string => s !== null)
.join(" ");
const input: AuditPdfReportInput = {
tenantId,
from: from?.toISOString() ?? null,
to: to?.toISOString() ?? null,
filterSummary,
integrity,
events,
...(args.generatedBy ? { generatedBy: args.generatedBy } : {}),
generatedAt: (deps.now ?? (() => new Date()))(),
};
const bytes = await deps.render(input);
await deps.writeOutput(args.out, bytes);
if (integrity.ok) {
deps.logger.info(`audit-pdf written — out=${args.out} rows=${events.length} bytes=${bytes.length} integrity=ok`);
} else {
deps.logger.error(
`audit-pdf written WITH BROKEN CHAIN — out=${args.out} rows=${events.length} bytes=${bytes.length} firstBreakId=${integrity.firstBreakId ?? "?"} reason=${integrity.reason ?? "unknown"}`
);
}
return {
exitCode: integrity.ok ? 0 : 1,
rowCount: events.length,
byteLength: bytes.length,
outPath: args.out,
};
}
export const auditExportPdfCommand = defineCommand({
meta: { name: "export-pdf", description: "Render a tamper-evident PDF compliance report for a tenant." },
args: {
tenant: { type: "string", required: true, description: "Tenant ID (use --tenant=__platform__ for platform events)." },
from: { type: "string", required: false, description: "Lower bound (inclusive) ISO-8601 createdAt." },
to: { type: "string", required: false, description: "Upper bound (exclusive) ISO-8601 createdAt." },
"regulatory-scope": { type: "string", required: false, description: "Filter by regulatoryScope value (gdpr | hipaa | soc2 | pci)." },
out: { type: "string", required: true, description: "Output file path (e.g. ./audit-report.pdf)." },
"generated-by": { type: "string", required: false, description: "Operator display name to embed on the cover page." },
},
async run({ args }) {
const [{ getReadDbClient }, { verifyAuditChain }, { serializeAuditEventsToPdf }] = await Promise.all([
import("@toolctrl/db/client.server"),
import("@toolctrl/db/audit-hash"),
import("@toolctrl/exports/audit-pdf"),
]);
const db = getReadDbClient();
const outcome = await runAuditExportPdf(
{
tenant: String(args.tenant),
...(args.from !== undefined ? { from: String(args.from) } : {}),
...(args.to !== undefined ? { to: String(args.to) } : {}),
...(args["regulatory-scope"] !== undefined ? { regulatoryScope: String(args["regulatory-scope"]) } : {}),
out: String(args.out),
...(args["generated-by"] !== undefined ? { generatedBy: String(args["generated-by"]) } : {}),
},
{
async loadEvents({ tenantId, from, to, regulatoryScope, limit }) {
const where: Record<string, unknown> = { tenantId };
if (from || to) {
const range: Record<string, Date> = {};
if (from) range.gte = from;
if (to) range.lt = to;
where.createdAt = range;
}
if (regulatoryScope) {
where.regulatoryScope = { hasSome: [regulatoryScope] };
}
const rows = (await db.auditEvent.findMany({
where,
orderBy: { createdAt: "asc" },
take: limit,
})) as unknown as ReadonlyArray<AuditPdfEvent>;
return rows;
},
verify(events) {
// Convert to AuditChainEvent-compatible shape: id + createdAt as
// strings, the rest matching AuditPdfEvent.
const chainEvents = events.map((e) => ({
id: e.id,
createdAt: e.createdAt instanceof Date ? e.createdAt.toISOString() : String(e.createdAt),
tenantId: e.tenantId,
actorType: e.actorType,
actorId: e.actorId,
actorEmail: e.actorEmail,
actorIp: e.actorIp,
actorUserAgent: e.actorUserAgent,
action: e.action,
targetType: e.targetType,
targetId: e.targetId,
requestId: e.requestId,
sourceModule: e.sourceModule,
outcome: e.outcome,
dataSensitivity: e.dataSensitivity,
regulatoryScope: e.regulatoryScope as string[],
metadata: e.metadata,
previousHash: e.previousHash,
eventHash: e.eventHash,
}));
const result = verifyAuditChain(chainEvents);
return {
ok: result.ok,
inspected: result.inspected,
firstBreakId: result.firstBreak?.eventId ?? null,
reason: result.firstBreak?.reason ?? null,
};
},
render: serializeAuditEventsToPdf,
writeOutput: async (path, bytes) => writeFile(path, bytes),
logger: {
info: (msg) => consola.success(msg),
error: (msg) => consola.error(msg),
},
}
);
process.exitCode = outcome.exitCode;
},
});
@@ -0,0 +1,17 @@
import { defineCommand } from "citty";
import { auditVerifyChainCommand } from "./verify-chain.js";
import { auditExportPdfCommand } from "./export-pdf.js";
export const auditCommand = defineCommand({
meta: {
name: "audit",
description: "AuditEvent compliance operations (hash-chain verify, PDF report export).",
},
subCommands: {
"verify-chain": auditVerifyChainCommand,
"export-pdf": auditExportPdfCommand,
},
});
export { auditVerifyChainCommand, auditExportPdfCommand };
@@ -0,0 +1,150 @@
import { describe, expect, it, vi } from "vitest";
import { computeAuditHash, verifyAuditChain } from "@toolctrl/db/audit-hash";
import {
runAuditVerifyChain,
type AuditVerifyChainDependencies,
type AuditVerifyChainRow,
} from "./verify-chain.js";
function makeOutput() {
return {
info: vi.fn<(msg: string) => void>(),
error: vi.fn<(msg: string) => void>(),
json: vi.fn<(obj: unknown) => void>(),
};
}
function basePayload(over: Partial<AuditVerifyChainRow> = {}): AuditVerifyChainRow {
return {
id: "audit_1",
createdAt: "2026-05-17T00:00:00.000Z",
tenantId: "tenant_1",
actorType: "user",
actorId: "user_1",
actorEmail: null,
actorIp: null,
actorUserAgent: null,
action: "x.do",
targetType: null,
targetId: null,
requestId: null,
sourceModule: null,
outcome: "success",
dataSensitivity: "internal",
regulatoryScope: [],
metadata: null,
previousHash: null,
eventHash: null,
...over,
};
}
function hashFor(row: AuditVerifyChainRow): string {
return computeAuditHash({
previousHash: row.previousHash,
payload: {
id: row.id,
createdAt: row.createdAt,
tenantId: row.tenantId,
actorType: row.actorType,
actorId: row.actorId,
actorEmail: row.actorEmail,
actorIp: row.actorIp,
actorUserAgent: row.actorUserAgent,
action: row.action,
targetType: row.targetType,
targetId: row.targetId,
requestId: row.requestId,
sourceModule: row.sourceModule,
outcome: row.outcome,
dataSensitivity: row.dataSensitivity,
regulatoryScope: row.regulatoryScope,
metadata: row.metadata,
},
});
}
function makeDeps(rows: AuditVerifyChainRow[]): AuditVerifyChainDependencies & { output: ReturnType<typeof makeOutput> } {
const output = makeOutput();
return {
output,
verify: verifyAuditChain,
async *readRows() {
for (const row of rows) yield row;
},
};
}
describe("runAuditVerifyChain", () => {
it("returns exit code 0 + prints OK message for an intact chain", async () => {
const r1 = basePayload();
r1.eventHash = hashFor(r1);
const r2 = basePayload({ id: "audit_2", action: "x.do2", previousHash: r1.eventHash });
r2.eventHash = hashFor(r2);
const deps = makeDeps([r1, r2]);
const result = await runAuditVerifyChain({ tenant: "tenant_1" }, deps);
expect(result.exitCode).toBe(0);
expect(result.ok).toBe(true);
expect(result.inspected).toBe(2);
expect(deps.output.info).toHaveBeenCalledWith(expect.stringContaining("audit-chain OK"));
});
it("returns exit code 1 with a diagnostic on hash mismatch", async () => {
const r1 = basePayload();
r1.eventHash = hashFor(r1);
// tamper: change metadata but keep stored hash
const tampered = { ...r1, metadata: { tampered: true } };
const deps = makeDeps([tampered]);
const result = await runAuditVerifyChain({ tenant: "tenant_1" }, deps);
expect(result.exitCode).toBe(1);
expect(result.ok).toBe(false);
expect(deps.output.error).toHaveBeenCalledWith(expect.stringContaining("audit-chain BROKEN"));
expect(deps.output.error).toHaveBeenCalledWith(expect.stringContaining("hash-mismatch"));
});
it("emits a single JSON object when --json is set", async () => {
const r1 = basePayload();
r1.eventHash = hashFor(r1);
const deps = makeDeps([r1]);
const result = await runAuditVerifyChain({ tenant: "tenant_1", json: true }, deps);
expect(result.exitCode).toBe(0);
expect(deps.output.info).not.toHaveBeenCalled();
expect(deps.output.json).toHaveBeenCalledTimes(1);
const arg = deps.output.json.mock.calls[0]?.[0] as Record<string, unknown>;
expect(arg).toMatchObject({ tenantId: "tenant_1", ok: true, inspected: 1 });
});
it("rejects an empty tenant arg", async () => {
const deps = makeDeps([]);
const result = await runAuditVerifyChain({ tenant: " " }, deps);
expect(result.exitCode).toBe(1);
expect(deps.output.error).toHaveBeenCalledWith(expect.stringContaining("Missing --tenant"));
});
it("parses ISO-8601 --from/--to and propagates them to the reader", async () => {
const captured: { from: Date | null; to: Date | null }[] = [];
const deps: AuditVerifyChainDependencies & { output: ReturnType<typeof makeOutput> } = {
output: makeOutput(),
verify: () => ({ ok: true, inspected: 0, firstBreak: null }),
async *readRows(opts) {
captured.push({ from: opts.from, to: opts.to });
return;
},
};
await runAuditVerifyChain({ tenant: "t1", from: "2026-01-01T00:00:00.000Z", to: "2026-05-17T00:00:00.000Z" }, deps);
expect(captured[0]?.from?.toISOString()).toBe("2026-01-01T00:00:00.000Z");
expect(captured[0]?.to?.toISOString()).toBe("2026-05-17T00:00:00.000Z");
});
it("throws when --from is not parseable", async () => {
const deps = makeDeps([]);
await expect(runAuditVerifyChain({ tenant: "t1", from: "not-a-date" }, deps)).rejects.toThrow(/Invalid --from/);
});
});
@@ -0,0 +1,169 @@
/**
* `toolctrl audit verify-chain --tenant <id> [--from <iso8601>] [--to <iso8601>] [--json]`
*
* Thin CLI wrapper around `verifyAuditChain` from @toolctrl/db/audit-hash.
* Loads the per-tenant AuditEvent chain in chronological order, recomputes
* each event's eventHash and compares it against the stored value. Exits
* 0 on intact chain, non-zero with first-break diagnostics otherwise.
*
* Design notes:
* - Reads via getReadDbClient — the verifier is read-only.
* - Streams rows in batches of 5_000 by id ascending; the verifier
* consumes rows in createdAt order so we sort each batch before
* appending to the running chain state. For tenants with > a few
* hundred thousand events the operator should run the verifier
* against a time-restricted range to keep memory bounded.
* - `--json` switches the printer to a single machine-readable JSON
* object on stdout (no consola decorations).
*
* See docs/improvement-plan/10-compliance-polish/compliance-audit-export.md.
*/
import { defineCommand } from "citty";
import consola from "consola";
import type { AuditChainEvent, VerifyAuditChainResult } from "@toolctrl/db/audit-hash";
const AUDIT_VERIFY_BATCH_SIZE = 5_000;
export type AuditVerifyChainArgs = {
tenant: string;
from?: string | null;
to?: string | null;
json?: boolean;
};
export type AuditVerifyChainRow = AuditChainEvent;
export type AuditVerifyChainDependencies = {
/** Cursor-iterable read of events ordered by createdAt ascending. */
readRows: (args: { tenantId: string; from: Date | null; to: Date | null; batchSize: number }) => AsyncIterable<AuditVerifyChainRow>;
/** Chain verifier — usually `verifyAuditChain` from @toolctrl/db/audit-hash. */
verify: (events: ReadonlyArray<AuditVerifyChainRow>, options?: { secret?: string | null }) => VerifyAuditChainResult;
/** Output sink. Tests pass an array collector; production wires consola. */
output: { info: (msg: string) => void; json: (obj: unknown) => void; error: (msg: string) => void };
/** Optional secret override (otherwise reads AUDIT_CHAIN_SECRET env). */
secret?: string | null;
};
export type AuditVerifyChainOutcome = {
exitCode: 0 | 1;
inspected: number;
ok: boolean;
};
function parseIsoDate(raw: string | null | undefined, label: string): Date | null {
if (!raw || raw.length === 0) return null;
const d = new Date(raw);
if (Number.isNaN(d.getTime())) {
throw new Error(`Invalid --${label} value ${JSON.stringify(raw)} (expected ISO-8601).`);
}
return d;
}
export async function runAuditVerifyChain(
args: AuditVerifyChainArgs,
deps: AuditVerifyChainDependencies
): Promise<AuditVerifyChainOutcome> {
const tenantId = args.tenant.trim();
if (tenantId.length === 0) {
deps.output.error("Missing --tenant.");
return { exitCode: 1, inspected: 0, ok: false };
}
const from = parseIsoDate(args.from ?? null, "from");
const to = parseIsoDate(args.to ?? null, "to");
// Collect rows. The verifier is stateful per-chain (compares against the
// previous event's stored hash) so we load the whole window in-memory.
// For tenants beyond ~100k events the operator should pass a date range.
const rows: AuditVerifyChainRow[] = [];
for await (const row of deps.readRows({ tenantId, from, to, batchSize: AUDIT_VERIFY_BATCH_SIZE })) {
rows.push(row);
}
const result = deps.verify(rows, deps.secret !== undefined ? { secret: deps.secret } : {});
if (args.json) {
deps.output.json({
tenantId,
from: from?.toISOString() ?? null,
to: to?.toISOString() ?? null,
inspected: result.inspected,
ok: result.ok,
firstBreak: result.firstBreak,
});
} else if (result.ok) {
deps.output.info(`audit-chain OK — tenant=${tenantId} inspected=${result.inspected}`);
} else {
deps.output.error(
`audit-chain BROKEN — tenant=${tenantId} inspected=${result.inspected} firstBreakId=${result.firstBreak?.eventId ?? "?"} reason=${result.firstBreak?.reason ?? "unknown"}`
);
}
return { exitCode: result.ok ? 0 : 1, inspected: result.inspected, ok: result.ok };
}
export const auditVerifyChainCommand = defineCommand({
meta: { name: "verify-chain", description: "Verify the AuditEvent hash-chain integrity for a tenant." },
args: {
tenant: { type: "string", required: true, description: "Tenant ID to verify (use --tenant=__platform__ for platform events)." },
from: { type: "string", required: false, description: "Lower bound (inclusive) ISO-8601 createdAt." },
to: { type: "string", required: false, description: "Upper bound (exclusive) ISO-8601 createdAt." },
json: { type: "boolean", required: false, default: false, description: "Emit a single JSON object instead of human-readable text." },
},
async run({ args }) {
const { verifyAuditChain } = await import("@toolctrl/db/audit-hash");
const { getReadDbClient } = await import("@toolctrl/db/client.server");
const db = getReadDbClient();
const tenantId = String(args.tenant);
async function* readRows(opts: { tenantId: string; from: Date | null; to: Date | null; batchSize: number }): AsyncIterable<AuditVerifyChainRow> {
const where: Record<string, unknown> = {
tenantId: opts.tenantId === "__platform__" ? null : opts.tenantId,
};
if (opts.from || opts.to) {
const range: Record<string, Date> = {};
if (opts.from) range.gte = opts.from;
if (opts.to) range.lt = opts.to;
where.createdAt = range;
}
let cursor: string | undefined;
while (true) {
const page: AuditVerifyChainRow[] = (await db.auditEvent.findMany({
where,
orderBy: [{ createdAt: "asc" }, { id: "asc" }],
take: opts.batchSize,
...(cursor ? { skip: 1, cursor: { id: cursor } } : {}),
})) as unknown as AuditVerifyChainRow[];
for (const row of page) yield row;
if (page.length < opts.batchSize) return;
cursor = page[page.length - 1]?.id;
}
}
const tenantArg = String(args.tenant);
const fromArg = args.from ? String(args.from) : null;
const toArg = args.to ? String(args.to) : null;
const jsonArg = Boolean(args.json);
try {
const outcome = await runAuditVerifyChain(
{ tenant: tenantArg, ...(fromArg !== null ? { from: fromArg } : {}), ...(toArg !== null ? { to: toArg } : {}), json: jsonArg },
{
readRows,
verify: verifyAuditChain,
output: {
info: (msg) => consola.success(msg),
json: (obj) => consola.log(JSON.stringify(obj)),
error: (msg) => consola.error(msg),
},
}
);
process.exitCode = outcome.exitCode;
// Surface the tenant for ops cross-referencing.
void tenantId;
} catch (error) {
consola.error(error instanceof Error ? error.message : String(error));
process.exitCode = 1;
}
},
});