import { pathToFileURL } from "node:url"; import { createAuditEvent, type AuditEventWriterClient } from "@hivegrid/db/audit-events.server"; import { seedStandardEntitlements, type EntitlementsSeedClient } from "@hivegrid/db/entitlements-seed.server"; import { assessDatabaseCatalog, buildCustomerPortalCatalogPlan, customerPortalCatalogPlanIsBlocked, customerPortalCatalogPlanIsComplete, LagoCatalogClient, readDatabaseCatalog, reconcileBasePlanPortalFeatures, type CustomerPortalCatalogPlan, } from "./catalog"; import { CustomerPortalUatError, parseCustomerPortalUatCommand, safeCustomerPortalUatError, type CustomerPortalCatalogCommand } from "./contracts"; import { withCustomerPortalOperatorDatabase } from "./database"; type CatalogExecutionResult = { readonly mode: CustomerPortalCatalogCommand["mode"]; readonly complete: boolean; readonly plan: CustomerPortalCatalogPlan; }; const providerAuditActions = [ "customer_portal.catalog.provider_requested", "customer_portal.catalog.provider_created", "customer_portal.catalog.provider_failed", "customer_portal.catalog.provider_reconciled", ] as const; const catalogAuditActions = [...providerAuditActions, "customer_portal.catalog.database_reconciled", "customer_portal.catalog.provisioned"] as const; export type CatalogAuditRecoveryRow = { readonly id: string; readonly action: (typeof catalogAuditActions)[number]; readonly targetId: string | null; readonly createdAt: Date; }; export type CatalogAuditRecovery = { readonly providerCodesNeedingReconciliation: readonly string[]; readonly providerCodesNeedingProvisionedAudit: readonly string[]; readonly databaseNeedsProvisionedAudit: boolean; readonly needsProvisionedAudit: boolean; }; export function assessCatalogAuditRecovery(rows: readonly CatalogAuditRecoveryRow[], plan: CustomerPortalCatalogPlan): CatalogAuditRecovery { const ordered = [...rows].sort((left, right) => left.createdAt.getTime() - right.createdAt.getTime() || left.id.localeCompare(right.id)); const lastIndex = (predicate: (row: CatalogAuditRecoveryRow) => boolean): number => { for (let index = ordered.length - 1; index >= 0; index -= 1) { if (predicate(ordered[index]!)) return index; } return -1; }; const lastProvisioned = lastIndex((row) => row.action === "customer_portal.catalog.provisioned"); const providerCodesNeedingReconciliation: string[] = []; const providerCodesNeedingProvisionedAudit: string[] = []; for (const action of plan.provider) { const requested = lastIndex((row) => row.targetId === action.code && row.action === "customer_portal.catalog.provider_requested"); const completed = lastIndex( (row) => row.targetId === action.code && (row.action === "customer_portal.catalog.provider_created" || row.action === "customer_portal.catalog.provider_reconciled") ); if (action.action === "noop" && requested > completed) providerCodesNeedingReconciliation.push(action.code); if (completed > lastProvisioned) providerCodesNeedingProvisionedAudit.push(action.code); } const lastDatabaseReconciled = lastIndex((row) => row.action === "customer_portal.catalog.database_reconciled"); const databaseNeedsProvisionedAudit = lastDatabaseReconciled > lastProvisioned; return { providerCodesNeedingReconciliation, providerCodesNeedingProvisionedAudit, databaseNeedsProvisionedAudit, needsProvisionedAudit: providerCodesNeedingProvisionedAudit.length > 0 || databaseNeedsProvisionedAudit, }; } function writeResult(result: CatalogExecutionResult): void { process.stdout.write(`${JSON.stringify(result, null, 2)}\n`); } async function executeCatalogCommand(command: CustomerPortalCatalogCommand): Promise { const lago = new LagoCatalogClient({ apiUrl: command.lagoApiUrl, apiKey: command.lagoApiKey }); return withCustomerPortalOperatorDatabase(command, async (db) => { const inspect = async () => buildCustomerPortalCatalogPlan(await lago.readCatalog(), await readDatabaseCatalog(db)); const initialPlan = await inspect(); const priorAuditRows = await db.auditEvent.findMany({ where: { tenantId: null, sourceModule: "customer-portal-uat", action: { in: [...catalogAuditActions] }, }, select: { id: true, action: true, targetId: true, createdAt: true }, orderBy: [{ createdAt: "asc" }, { id: "asc" }], }); const recovery = assessCatalogAuditRecovery(priorAuditRows as CatalogAuditRecoveryRow[], initialPlan); const auditComplete = recovery.providerCodesNeedingReconciliation.length === 0 && !recovery.needsProvisionedAudit; if (command.mode === "plan") { return { mode: command.mode, complete: customerPortalCatalogPlanIsComplete(initialPlan) && auditComplete, plan: initialPlan }; } if (command.mode === "verify") { if (!customerPortalCatalogPlanIsComplete(initialPlan) || !auditComplete) { throw new CustomerPortalUatError("customer-portal UAT: catalog verification found missing, drifted, or incompletely audited state"); } return { mode: command.mode, complete: true, plan: initialPlan }; } if (customerPortalCatalogPlanIsBlocked(initialPlan)) { throw new CustomerPortalUatError("customer-portal UAT: catalog apply is blocked by existing drift; no mutation was attempted"); } let mutated = false; const providerResourcesAudited = new Set(); for (const action of initialPlan.provider) { const audit = async (phase: "requested" | "created" | "failed" | "reconciled", outcome: "success" | "failure") => createAuditEvent( { tenantId: null, actorId: command.operatorUserId, actorType: "operator", action: `customer_portal.catalog.provider_${phase}`, targetType: action.resource === "plan" ? "LagoPlan" : "LagoAddOn", targetId: action.code, sourceModule: "customer-portal-uat", outcome, dataSensitivity: "internal", regulatoryScope: ["none"], metadata: { resource: action.resource }, }, db as unknown as AuditEventWriterClient ); if (action.action === "noop" && recovery.providerCodesNeedingReconciliation.includes(action.code)) { await audit("reconciled", "success"); providerResourcesAudited.add(action.code); mutated = true; continue; } if (action.action !== "create" && action.action !== "update") continue; await audit("requested", "success"); try { if (action.resource === "plan") { if (action.action === "create") await lago.createPlan(); else await lago.updatePlan(); } else if (action.action === "create") { await lago.createAddOn(); } else { await lago.updateAddOn(); } } catch (error) { await audit("failed", "failure"); throw error; } await audit(action.action === "create" ? "created" : "reconciled", "success"); providerResourcesAudited.add(action.code); mutated = true; } if (initialPlan.database.action === "reconcile") { await db.$transaction(async (tx) => { await seedStandardEntitlements({ client: tx as unknown as EntitlementsSeedClient, plans: [], includeCustomerPortalCommercialProducts: true, }); const basePlanFeaturesCreated = await reconcileBasePlanPortalFeatures(tx as unknown as Parameters[0]); const databaseAssessment = assessDatabaseCatalog(await readDatabaseCatalog(tx as unknown as Parameters[0])); if (databaseAssessment.blockingIssues.length > 0 || databaseAssessment.reconcileIssues.length > 0) { const residualIssues = [...databaseAssessment.blockingIssues, ...databaseAssessment.reconcileIssues].join(", "); throw new CustomerPortalUatError(`customer-portal UAT: database catalog did not converge inside the audited transaction: ${residualIssues}`); } // The app-role outbox intentionally rejects global events. This is an // operator-only, low-volume mutation, so persist its platform audit // directly through the canonical hash-chain writer inside the same // transaction instead of weakening the tenant-scoped outbox policy. await createAuditEvent( { tenantId: null, actorId: command.operatorUserId, actorType: "operator", action: "customer_portal.catalog.database_reconciled", targetType: "CustomerPortalCatalog", sourceModule: "customer-portal-uat", outcome: "success", dataSensitivity: "internal", regulatoryScope: ["none"], metadata: { productCodes: initialPlan.database.reconcileIssues.map((issue) => issue.split(":", 1)[0] ?? "unknown"), basePlanFeaturesCreated, }, }, tx as unknown as AuditEventWriterClient ); }); mutated = true; } const finalPlan = await inspect(); if (!customerPortalCatalogPlanIsComplete(finalPlan)) { throw new CustomerPortalUatError("customer-portal UAT: catalog did not converge to the canonical contract"); } if (mutated || recovery.needsProvisionedAudit) { for (const code of recovery.providerCodesNeedingProvisionedAudit) providerResourcesAudited.add(code); await createAuditEvent( { tenantId: null, actorId: command.operatorUserId, actorType: "operator", action: "customer_portal.catalog.provisioned", targetType: "CustomerPortalCatalog", sourceModule: "customer-portal-uat", outcome: "success", dataSensitivity: "internal", regulatoryScope: ["none"], metadata: { providerResources: [...providerResourcesAudited].sort(), databaseReconciled: initialPlan.database.action === "reconcile" || recovery.databaseNeedsProvisionedAudit, }, }, db as unknown as AuditEventWriterClient ); } return { mode: command.mode, complete: true, plan: finalPlan }; }); } export async function main(argv: readonly string[] = process.argv.slice(2), env: NodeJS.ProcessEnv = process.env): Promise { const command = parseCustomerPortalUatCommand("catalog", argv, env); if (command.target !== "catalog") throw new CustomerPortalUatError("customer-portal UAT: invalid catalog command"); writeResult(await executeCatalogCommand(command)); } const directEntry = process.argv[1] ? pathToFileURL(process.argv[1]).href === import.meta.url : false; if (directEntry) { void main().catch((error) => { process.stderr.write(`${safeCustomerPortalUatError(error)}\n`); process.exitCode = 1; }); }