Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
@@ -0,0 +1,369 @@
|
||||
// @vitest-environment node
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import type { DbClient } from "@hivegrid/db/client.server";
|
||||
import {
|
||||
customerPortalCommercialProducts,
|
||||
entitlementLimitTypes,
|
||||
featureKeys,
|
||||
getFeatureGate,
|
||||
standardEntitlementPlans,
|
||||
type EntitlementPlanId,
|
||||
} from "@hivegrid/entitlements";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
assessDatabaseCatalog,
|
||||
buildCustomerPortalCatalogPlan,
|
||||
customerPortalCatalogPlanIsBlocked,
|
||||
customerPortalCatalogPlanIsComplete,
|
||||
LagoCatalogClient,
|
||||
planProviderCatalog,
|
||||
reconcileBasePlanPortalFeatures,
|
||||
type DatabaseCatalogSnapshot,
|
||||
type DatabaseBasePlanSnapshot,
|
||||
type DatabaseProductSnapshot,
|
||||
type ProviderCatalogSnapshot,
|
||||
} from "./catalog";
|
||||
|
||||
const testLagoOrganizationId = "test-staging-organization-id";
|
||||
const testLagoIdentity = {
|
||||
expectedOrganizationIdSha256: createHash("sha256").update(testLagoOrganizationId).digest("hex"),
|
||||
};
|
||||
|
||||
function lagoOrganizationResponse(name = "HiveGrid Staging", id = testLagoOrganizationId): Response {
|
||||
return Response.json({ organization: { lago_id: id, name } });
|
||||
}
|
||||
|
||||
function providerSnapshot(): ProviderCatalogSnapshot {
|
||||
return {
|
||||
plan: {
|
||||
code: "customer_portal_monthly",
|
||||
name: "Customer Portal",
|
||||
description: customerPortalCommercialProducts.monthlyAddOn.description,
|
||||
interval: "monthly",
|
||||
amount_cents: 1_999,
|
||||
amount_currency: "EUR",
|
||||
pay_in_advance: true,
|
||||
taxes: [{ code: "de-vat-19" }],
|
||||
},
|
||||
addOn: {
|
||||
code: "customer_portal_domain_setup",
|
||||
name: "Customer Portal Domain Setup",
|
||||
description: customerPortalCommercialProducts.customDomainSetup.description,
|
||||
amount_cents: 29_999,
|
||||
amount_currency: "EUR",
|
||||
taxes: [{ code: "de-vat-19" }],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function commercialProduct(definition: (typeof customerPortalCommercialProducts)[keyof typeof customerPortalCommercialProducts]): DatabaseProductSnapshot {
|
||||
return {
|
||||
billingProviderId: `hivegrid_commercial_product_${definition.code}`,
|
||||
code: definition.code,
|
||||
title: definition.title,
|
||||
description: definition.description,
|
||||
kind: definition.source,
|
||||
order: definition.catalogOrder,
|
||||
model: 0,
|
||||
active: true,
|
||||
public: definition.public,
|
||||
groupTitle: "Customer Portal",
|
||||
groupDescription: null,
|
||||
badge: null,
|
||||
billingAddressCollection: "auto",
|
||||
hasQuantity: false,
|
||||
canBuyAgain: definition.source === "one_time_setup",
|
||||
lagoPlanCode: definition.source === "recurring_add_on" ? definition.code : null,
|
||||
features: definition.featureKeys.map((name, index) => ({
|
||||
order: index + 1,
|
||||
title: getFeatureGate(name)!.title,
|
||||
name,
|
||||
code: null,
|
||||
type: entitlementLimitTypes.included,
|
||||
value: definition.includedQuantity ?? entitlementLimitTypes.included,
|
||||
quotaValue: null,
|
||||
href: null,
|
||||
badge: getFeatureGate(name)!.title,
|
||||
accumulate: false,
|
||||
})),
|
||||
prices:
|
||||
definition.amountCents === null || definition.currency === null
|
||||
? []
|
||||
: [
|
||||
{
|
||||
billingProviderId: `hivegrid_commercial_price_${definition.code}`,
|
||||
lagoFeeCode: definition.code,
|
||||
molliePriceReference: `hivegrid_commercial_price_${definition.code}`,
|
||||
type: definition.source === "recurring_add_on" ? 1 : 0,
|
||||
billingPeriod: definition.source === "recurring_add_on" ? 3 : 0,
|
||||
price: (definition.amountCents / 100).toFixed(2),
|
||||
currency: definition.currency.toLowerCase(),
|
||||
trialDays: 0,
|
||||
active: true,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function databaseSnapshot(): DatabaseCatalogSnapshot {
|
||||
return {
|
||||
commercialProducts: Object.values(customerPortalCommercialProducts).map(commercialProduct),
|
||||
basePlans: [basePlan("starter"), basePlan("pro"), basePlan("business")],
|
||||
};
|
||||
}
|
||||
|
||||
function basePlan(planCode: EntitlementPlanId): DatabaseBasePlanSnapshot {
|
||||
const plan = standardEntitlementPlans.find((candidate) => candidate.id === planCode)!;
|
||||
const feature = plan.features.find((candidate) => candidate.featureKey === featureKeys.customerPortal)!;
|
||||
return {
|
||||
id: `${planCode}-product-id`,
|
||||
code: planCode,
|
||||
kind: "base_plan",
|
||||
portalFeatures: [
|
||||
{
|
||||
order: Math.round(feature.order),
|
||||
title: feature.label,
|
||||
name: feature.featureKey,
|
||||
code: null,
|
||||
type: feature.limitType,
|
||||
value: feature.limit ?? feature.limitType,
|
||||
quotaValue: null,
|
||||
href: null,
|
||||
badge: getFeatureGate(featureKeys.customerPortal)!.title,
|
||||
accumulate: feature.limitType === entitlementLimitTypes.monthly,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
describe("customer-portal catalog plan", () => {
|
||||
it("recognizes the canonical provider and database state", () => {
|
||||
const plan = buildCustomerPortalCatalogPlan(providerSnapshot(), databaseSnapshot());
|
||||
expect(customerPortalCatalogPlanIsComplete(plan)).toBe(true);
|
||||
expect(customerPortalCatalogPlanIsBlocked(plan)).toBe(false);
|
||||
});
|
||||
|
||||
it("creates missing resources, safely updates tax-only drift, and blocks commercial provider drift", () => {
|
||||
expect(planProviderCatalog({ plan: null, addOn: null }).map((action) => action.action)).toEqual(["create", "create"]);
|
||||
const missingTax = providerSnapshot();
|
||||
missingTax.plan!.taxes = [];
|
||||
missingTax.addOn!.taxes = [];
|
||||
expect(planProviderCatalog(missingTax)).toEqual([
|
||||
expect.objectContaining({ action: "update", driftFields: ["taxCodes"] }),
|
||||
expect.objectContaining({ action: "update", driftFields: ["taxCodes"] }),
|
||||
]);
|
||||
const drifted = providerSnapshot();
|
||||
drifted.plan!.amount_cents = 1;
|
||||
const actions = planProviderCatalog(drifted);
|
||||
expect(actions[0]).toMatchObject({ action: "drift", driftFields: ["amountCents"] });
|
||||
});
|
||||
|
||||
it("distinguishes reconcilable commercial rows from a safely missing base-plan portal feature", () => {
|
||||
const missing = databaseSnapshot();
|
||||
const reconcilable = assessDatabaseCatalog({ ...missing, commercialProducts: missing.commercialProducts.slice(1) });
|
||||
expect(reconcilable.reconcileIssues).toContain("customer_portal_monthly: product missing");
|
||||
expect(reconcilable.blockingIssues).toEqual([]);
|
||||
|
||||
const missingFeature = databaseSnapshot();
|
||||
const baseFeatureReconciliation = assessDatabaseCatalog({
|
||||
...missingFeature,
|
||||
basePlans: missingFeature.basePlans.map((plan) => (plan.code === "business" ? { ...plan, portalFeatures: [] } : plan)),
|
||||
});
|
||||
expect(baseFeatureReconciliation.reconcileIssues).toContain("business: canonical customer_portal feature missing");
|
||||
expect(baseFeatureReconciliation.blockingIssues).toEqual([]);
|
||||
});
|
||||
|
||||
it("blocks a missing base-plan product and never invents a replacement", () => {
|
||||
const snapshot = databaseSnapshot();
|
||||
const assessment = assessDatabaseCatalog({
|
||||
...snapshot,
|
||||
basePlans: snapshot.basePlans.filter((plan) => plan.code !== "business"),
|
||||
});
|
||||
expect(assessment.blockingIssues).toContain("business: expected exactly one canonical base-plan product");
|
||||
expect(assessment.reconcileIssues).not.toContain("business: canonical customer_portal feature missing");
|
||||
|
||||
const duplicateAssessment = assessDatabaseCatalog({
|
||||
...snapshot,
|
||||
basePlans: [...snapshot.basePlans, basePlan("business")],
|
||||
});
|
||||
expect(duplicateAssessment.blockingIssues).toContain("business: expected exactly one canonical base-plan product");
|
||||
});
|
||||
|
||||
it("blocks an existing wrong or duplicate portal feature instead of updating or deleting it", () => {
|
||||
const snapshot = databaseSnapshot();
|
||||
const business = snapshot.basePlans.find((plan) => plan.code === "business")!;
|
||||
const wrongFeature = {
|
||||
...business,
|
||||
portalFeatures: business.portalFeatures.map((feature) => ({ ...feature, type: entitlementLimitTypes.notIncluded, value: 0 })),
|
||||
};
|
||||
const wrongAssessment = assessDatabaseCatalog({
|
||||
...snapshot,
|
||||
basePlans: snapshot.basePlans.map((plan) => (plan === business ? wrongFeature : plan)),
|
||||
});
|
||||
expect(wrongAssessment.blockingIssues).toContain("business: existing customer_portal feature differs from the canonical contract");
|
||||
|
||||
const duplicateAssessment = assessDatabaseCatalog({
|
||||
...snapshot,
|
||||
basePlans: snapshot.basePlans.map((plan) =>
|
||||
plan === business ? { ...business, portalFeatures: [...business.portalFeatures, ...business.portalFeatures] } : plan
|
||||
),
|
||||
});
|
||||
expect(duplicateAssessment.blockingIssues).toContain("business: duplicate customer_portal feature rows");
|
||||
});
|
||||
|
||||
it("creates only a missing canonical portal feature and leaves every other plan feature untouched", async () => {
|
||||
const snapshot = databaseSnapshot();
|
||||
const baseProducts = snapshot.basePlans.map((plan) => ({
|
||||
id: plan.id,
|
||||
code: plan.code,
|
||||
kind: "base_plan",
|
||||
features: plan.code === "business" ? [] : plan.portalFeatures,
|
||||
prices: [],
|
||||
}));
|
||||
const create = vi.fn().mockResolvedValue({});
|
||||
const db = {
|
||||
subscriptionProduct: { findMany: vi.fn().mockResolvedValue(baseProducts) },
|
||||
subscriptionFeature: { create },
|
||||
} as unknown as DbClient;
|
||||
|
||||
await expect(reconcileBasePlanPortalFeatures(db)).resolves.toEqual(["business"]);
|
||||
expect(create).toHaveBeenCalledTimes(1);
|
||||
expect(create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
subscriptionProductId: "business-product-id",
|
||||
order: Math.round(
|
||||
standardEntitlementPlans
|
||||
.find((candidate) => candidate.id === "business")!
|
||||
.features.find((candidate) => candidate.featureKey === featureKeys.customerPortal)!.order
|
||||
),
|
||||
name: featureKeys.customerPortal,
|
||||
type: entitlementLimitTypes.included,
|
||||
value: entitlementLimitTypes.included,
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
it("blocks a title collision that the shared seed helper could otherwise take over", () => {
|
||||
const snapshot = databaseSnapshot();
|
||||
const monthly = snapshot.commercialProducts.find((product) => product.code === "customer_portal_monthly")!;
|
||||
const collision = { ...monthly, billingProviderId: "legacy-product", code: "legacy_customer_portal" };
|
||||
const assessment = assessDatabaseCatalog({
|
||||
...snapshot,
|
||||
commercialProducts: [collision, ...snapshot.commercialProducts.filter((product) => product !== monthly)],
|
||||
});
|
||||
expect(assessment.blockingIssues).toContain("customer_portal_monthly: existing seed-key collision would mutate another product");
|
||||
});
|
||||
|
||||
it("does not report checkout-relevant product or price drift as complete", () => {
|
||||
const snapshot = databaseSnapshot();
|
||||
const monthly = snapshot.commercialProducts.find((product) => product.code === "customer_portal_monthly")!;
|
||||
const driftedMonthly = {
|
||||
...monthly,
|
||||
canBuyAgain: true,
|
||||
prices: monthly.prices.map((price) => ({ ...price, molliePriceReference: "wrong-reference", trialDays: 14 })),
|
||||
};
|
||||
const assessment = assessDatabaseCatalog({
|
||||
...snapshot,
|
||||
commercialProducts: snapshot.commercialProducts.map((product) => (product === monthly ? driftedMonthly : product)),
|
||||
});
|
||||
expect(assessment.reconcileIssues).toEqual(
|
||||
expect.arrayContaining(["customer_portal_monthly: product metadata differs", "customer_portal_monthly: canonical price contract differs"])
|
||||
);
|
||||
});
|
||||
|
||||
it("does not report commercial feature property drift as complete", () => {
|
||||
const snapshot = databaseSnapshot();
|
||||
const monthly = snapshot.commercialProducts.find((product) => product.code === "customer_portal_monthly")!;
|
||||
const driftedMonthly = {
|
||||
...monthly,
|
||||
features: monthly.features.map((feature, index) =>
|
||||
index === 0 ? { ...feature, order: 99, title: "Wrong", type: entitlementLimitTypes.notIncluded, value: 0, badge: null, accumulate: true } : feature
|
||||
),
|
||||
};
|
||||
const assessment = assessDatabaseCatalog({
|
||||
...snapshot,
|
||||
commercialProducts: snapshot.commercialProducts.map((product) => (product === monthly ? driftedMonthly : product)),
|
||||
});
|
||||
expect(assessment.reconcileIssues).toContain("customer_portal_monthly: feature contract differs");
|
||||
});
|
||||
|
||||
it("blocks additional active prices that the shared seed helper cannot remove", () => {
|
||||
const snapshot = databaseSnapshot();
|
||||
const monthly = snapshot.commercialProducts.find((product) => product.code === "customer_portal_monthly")!;
|
||||
const withUnexpectedActivePrice = {
|
||||
...monthly,
|
||||
prices: [...monthly.prices, { ...monthly.prices[0]!, billingPeriod: 4, billingProviderId: "unexpected-yearly", lagoFeeCode: "unexpected-yearly" }],
|
||||
};
|
||||
const assessment = assessDatabaseCatalog({
|
||||
...snapshot,
|
||||
commercialProducts: snapshot.commercialProducts.map((product) => (product === monthly ? withUnexpectedActivePrice : product)),
|
||||
});
|
||||
expect(assessment.blockingIssues).toContain("customer_portal_monthly: unexpected active price cannot be removed by reconciliation");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Lago customer-portal catalog client", () => {
|
||||
it("treats 404 reads as missing without leaking credentials", async () => {
|
||||
const fetchImpl = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockImplementation(async (url) => (String(url).endsWith("/organizations") ? lagoOrganizationResponse() : new Response(null, { status: 404 })));
|
||||
const client = new LagoCatalogClient({ apiUrl: "https://lago.example.test", apiKey: "secret-key", fetchImpl }, testLagoIdentity);
|
||||
await expect(client.readCatalog()).resolves.toEqual({ plan: null, addOn: null });
|
||||
for (const call of fetchImpl.mock.calls) {
|
||||
expect(String(call[0])).not.toContain("secret-key");
|
||||
expect(new Headers(call[1]?.headers).get("authorization")).toBe("Bearer secret-key");
|
||||
}
|
||||
});
|
||||
|
||||
it("creates and updates the exact taxed recurring plan and one-time add-on contracts", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>().mockImplementation(async (url, init) => {
|
||||
if (String(url).endsWith("/organizations")) return lagoOrganizationResponse();
|
||||
const body = JSON.parse(String(init?.body)) as { plan?: unknown; add_on?: unknown };
|
||||
if (body.plan) return Response.json({ plan: providerSnapshot().plan });
|
||||
return Response.json({ add_on: providerSnapshot().addOn });
|
||||
});
|
||||
const client = new LagoCatalogClient({ apiUrl: "https://lago.example.test", apiKey: "secret-key", fetchImpl }, testLagoIdentity);
|
||||
await client.createPlan();
|
||||
await client.createAddOn();
|
||||
await client.updatePlan();
|
||||
await client.updateAddOn();
|
||||
|
||||
expect(JSON.parse(String(fetchImpl.mock.calls[1]?.[1]?.body))).toEqual({
|
||||
plan: expect.objectContaining({
|
||||
code: "customer_portal_monthly",
|
||||
interval: "monthly",
|
||||
amount_cents: 1_999,
|
||||
pay_in_advance: true,
|
||||
tax_codes: ["de-vat-19"],
|
||||
}),
|
||||
});
|
||||
expect(JSON.parse(String(fetchImpl.mock.calls[3]?.[1]?.body))).toEqual({
|
||||
add_on: expect.objectContaining({
|
||||
code: "customer_portal_domain_setup",
|
||||
amount_cents: 29_999,
|
||||
amount_currency: "EUR",
|
||||
tax_codes: ["de-vat-19"],
|
||||
}),
|
||||
});
|
||||
expect(fetchImpl.mock.calls[5]?.[1]?.method).toBe("PUT");
|
||||
expect(JSON.parse(String(fetchImpl.mock.calls[5]?.[1]?.body))).toEqual({
|
||||
plan: expect.objectContaining({ code: "customer_portal_monthly", tax_codes: ["de-vat-19"] }),
|
||||
});
|
||||
expect(fetchImpl.mock.calls[7]?.[1]?.method).toBe("PUT");
|
||||
expect(JSON.parse(String(fetchImpl.mock.calls[7]?.[1]?.body))).toEqual({
|
||||
add_on: expect.objectContaining({ code: "customer_portal_domain_setup", tax_codes: ["de-vat-19"] }),
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["different name", "HiveGrid Production", testLagoOrganizationId],
|
||||
["different id fingerprint", "HiveGrid Staging", "different-organization-id"],
|
||||
])("rejects a Lago organization with a %s before catalog reads or mutations", async (_label, name, id) => {
|
||||
const fetchImpl = vi.fn<typeof fetch>().mockResolvedValue(lagoOrganizationResponse(name, id));
|
||||
const client = new LagoCatalogClient({ apiUrl: "https://lago.example.test", apiKey: "secret-key", fetchImpl }, testLagoIdentity);
|
||||
await expect(client.readCatalog()).rejects.toThrow("Lago organization does not match the canonical staging identity");
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,716 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { normalizeLagoApiUrl } from "../../packages/billing/src/lago";
|
||||
import type { DbClient } from "@hivegrid/db/client.server";
|
||||
import {
|
||||
customerPortalCommercialProducts,
|
||||
customerPortalProductCodes,
|
||||
entitlementLimitTypes,
|
||||
featureKeys,
|
||||
getFeatureGate,
|
||||
hiveGridVat,
|
||||
standardEntitlementPlans,
|
||||
type EntitlementPlanId,
|
||||
} from "@hivegrid/entitlements";
|
||||
import { z } from "zod";
|
||||
|
||||
import { CustomerPortalUatError, normalizeCustomerPortalStagingLagoApiUrl } from "./contracts";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 10_000;
|
||||
const BASE_PLAN_CODES = ["starter", "pro", "business"] as const;
|
||||
const COMMERCIAL_PRODUCT_CODES = Object.values(customerPortalProductCodes);
|
||||
const STAGING_LAGO_ORGANIZATION_NAME = "HiveGrid Staging";
|
||||
const STAGING_LAGO_ORGANIZATION_ID_SHA256 = "3b1134a731c67b704bb0b3298ce031213079966b348aa762800f9c92556085a8";
|
||||
|
||||
const desiredLagoPlan = Object.freeze({
|
||||
code: customerPortalCommercialProducts.monthlyAddOn.code,
|
||||
name: customerPortalCommercialProducts.monthlyAddOn.title,
|
||||
description: customerPortalCommercialProducts.monthlyAddOn.description,
|
||||
interval: "monthly" as const,
|
||||
amountCents: customerPortalCommercialProducts.monthlyAddOn.amountCents!,
|
||||
amountCurrency: customerPortalCommercialProducts.monthlyAddOn.currency!,
|
||||
payInAdvance: true,
|
||||
taxCodes: Object.freeze([hiveGridVat.code]),
|
||||
});
|
||||
|
||||
const desiredLagoAddOn = Object.freeze({
|
||||
code: customerPortalCommercialProducts.customDomainSetup.code,
|
||||
name: customerPortalCommercialProducts.customDomainSetup.title,
|
||||
description: customerPortalCommercialProducts.customDomainSetup.description,
|
||||
amountCents: customerPortalCommercialProducts.customDomainSetup.amountCents!,
|
||||
amountCurrency: customerPortalCommercialProducts.customDomainSetup.currency!,
|
||||
taxCodes: Object.freeze([hiveGridVat.code]),
|
||||
});
|
||||
|
||||
const lagoAppliedTaxSchema = z.object({ code: z.string() });
|
||||
|
||||
const lagoPlanSchema = z.object({
|
||||
code: z.string(),
|
||||
name: z.string(),
|
||||
description: z.string().nullable().optional(),
|
||||
interval: z.string(),
|
||||
amount_cents: z.number().int(),
|
||||
amount_currency: z.string(),
|
||||
pay_in_advance: z.boolean(),
|
||||
taxes: z.array(lagoAppliedTaxSchema).default([]),
|
||||
});
|
||||
const lagoAddOnSchema = z.object({
|
||||
code: z.string(),
|
||||
name: z.string(),
|
||||
description: z.string().nullable().optional(),
|
||||
amount_cents: z.number().int(),
|
||||
amount_currency: z.string(),
|
||||
taxes: z.array(lagoAppliedTaxSchema).default([]),
|
||||
});
|
||||
const lagoPlanResponseSchema = z.object({ plan: lagoPlanSchema });
|
||||
const lagoAddOnResponseSchema = z.object({ add_on: lagoAddOnSchema });
|
||||
const lagoOrganizationResponseSchema = z.object({
|
||||
organization: z.object({ lago_id: z.string().min(1), name: z.string() }),
|
||||
});
|
||||
|
||||
export type LagoPlanSnapshot = z.infer<typeof lagoPlanSchema>;
|
||||
export type LagoAddOnSnapshot = z.infer<typeof lagoAddOnSchema>;
|
||||
|
||||
export type ProviderCatalogSnapshot = {
|
||||
readonly plan: LagoPlanSnapshot | null;
|
||||
readonly addOn: LagoAddOnSnapshot | null;
|
||||
};
|
||||
|
||||
export type ProviderCatalogAction = {
|
||||
readonly resource: "plan" | "add_on";
|
||||
readonly code: string;
|
||||
readonly action: "create" | "update" | "noop" | "drift";
|
||||
readonly driftFields: readonly string[];
|
||||
};
|
||||
|
||||
export type DatabasePriceSnapshot = {
|
||||
readonly billingProviderId: string;
|
||||
readonly lagoFeeCode: string | null;
|
||||
readonly molliePriceReference: string | null;
|
||||
readonly type: number;
|
||||
readonly billingPeriod: number;
|
||||
readonly price: string;
|
||||
readonly currency: string;
|
||||
readonly trialDays: number;
|
||||
readonly active: boolean;
|
||||
};
|
||||
|
||||
export type DatabaseProductSnapshot = {
|
||||
readonly billingProviderId: string;
|
||||
readonly code: string | null;
|
||||
readonly title: string;
|
||||
readonly description: string | null;
|
||||
readonly kind: string;
|
||||
readonly order: number;
|
||||
readonly model: number;
|
||||
readonly active: boolean;
|
||||
readonly public: boolean;
|
||||
readonly groupTitle: string | null;
|
||||
readonly groupDescription: string | null;
|
||||
readonly badge: string | null;
|
||||
readonly billingAddressCollection: string;
|
||||
readonly hasQuantity: boolean;
|
||||
readonly canBuyAgain: boolean;
|
||||
readonly lagoPlanCode: string | null;
|
||||
readonly features: readonly DatabaseFeatureSnapshot[];
|
||||
readonly prices: readonly DatabasePriceSnapshot[];
|
||||
};
|
||||
|
||||
export type DatabaseFeatureSnapshot = {
|
||||
readonly order: number;
|
||||
readonly title: string;
|
||||
readonly name: string;
|
||||
readonly code: string | null;
|
||||
readonly type: number;
|
||||
readonly value: number;
|
||||
readonly quotaValue: unknown;
|
||||
readonly href: string | null;
|
||||
readonly badge: string | null;
|
||||
readonly accumulate: boolean;
|
||||
};
|
||||
|
||||
export type DatabaseBasePlanSnapshot = {
|
||||
readonly id: string;
|
||||
readonly code: string | null;
|
||||
readonly kind: string;
|
||||
readonly portalFeatures: readonly DatabaseFeatureSnapshot[];
|
||||
};
|
||||
|
||||
export type DatabaseCatalogSnapshot = {
|
||||
readonly commercialProducts: readonly DatabaseProductSnapshot[];
|
||||
readonly basePlans: readonly DatabaseBasePlanSnapshot[];
|
||||
};
|
||||
|
||||
export type DatabaseCatalogAssessment = {
|
||||
readonly reconcileIssues: readonly string[];
|
||||
readonly blockingIssues: readonly string[];
|
||||
};
|
||||
|
||||
export type CustomerPortalCatalogPlan = {
|
||||
readonly provider: readonly ProviderCatalogAction[];
|
||||
readonly database: {
|
||||
readonly action: "noop" | "reconcile" | "blocked";
|
||||
readonly reconcileIssues: readonly string[];
|
||||
readonly blockingIssues: readonly string[];
|
||||
};
|
||||
};
|
||||
|
||||
function differentFields<T extends Record<string, unknown>>(actual: T, desired: T, fields: readonly (keyof T)[]): string[] {
|
||||
return fields.filter((field) => actual[field] !== desired[field]).map(String);
|
||||
}
|
||||
|
||||
export function planProviderCatalog(snapshot: ProviderCatalogSnapshot): ProviderCatalogAction[] {
|
||||
const planDrift = snapshot.plan
|
||||
? differentFields(
|
||||
{
|
||||
code: snapshot.plan.code,
|
||||
name: snapshot.plan.name,
|
||||
description: snapshot.plan.description ?? "",
|
||||
interval: snapshot.plan.interval,
|
||||
amountCents: snapshot.plan.amount_cents,
|
||||
amountCurrency: snapshot.plan.amount_currency.toUpperCase(),
|
||||
payInAdvance: snapshot.plan.pay_in_advance,
|
||||
taxCodes: snapshot.plan.taxes
|
||||
.map((tax) => tax.code)
|
||||
.sort()
|
||||
.join(","),
|
||||
},
|
||||
{ ...desiredLagoPlan, taxCodes: [...desiredLagoPlan.taxCodes].sort().join(",") },
|
||||
["code", "name", "description", "interval", "amountCents", "amountCurrency", "payInAdvance", "taxCodes"]
|
||||
)
|
||||
: [];
|
||||
const addOnDrift = snapshot.addOn
|
||||
? differentFields(
|
||||
{
|
||||
code: snapshot.addOn.code,
|
||||
name: snapshot.addOn.name,
|
||||
description: snapshot.addOn.description ?? "",
|
||||
amountCents: snapshot.addOn.amount_cents,
|
||||
amountCurrency: snapshot.addOn.amount_currency.toUpperCase(),
|
||||
taxCodes: snapshot.addOn.taxes
|
||||
.map((tax) => tax.code)
|
||||
.sort()
|
||||
.join(","),
|
||||
},
|
||||
{ ...desiredLagoAddOn, taxCodes: [...desiredLagoAddOn.taxCodes].sort().join(",") },
|
||||
["code", "name", "description", "amountCents", "amountCurrency", "taxCodes"]
|
||||
)
|
||||
: [];
|
||||
|
||||
return [
|
||||
{
|
||||
resource: "plan",
|
||||
code: desiredLagoPlan.code,
|
||||
action: snapshot.plan ? (planDrift.length === 0 ? "noop" : planDrift.every((field) => field === "taxCodes") ? "update" : "drift") : "create",
|
||||
driftFields: planDrift,
|
||||
},
|
||||
{
|
||||
resource: "add_on",
|
||||
code: desiredLagoAddOn.code,
|
||||
action: snapshot.addOn ? (addOnDrift.length === 0 ? "noop" : addOnDrift.every((field) => field === "taxCodes") ? "update" : "drift") : "create",
|
||||
driftFields: addOnDrift,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
type BasePlanPortalFeatureAction = {
|
||||
readonly planCode: EntitlementPlanId;
|
||||
readonly productId: string | null;
|
||||
readonly action: "create" | "noop" | "blocked";
|
||||
readonly issue: string | null;
|
||||
};
|
||||
|
||||
function getBasePlanPortalFeatureDefinition(planCode: EntitlementPlanId): DatabaseFeatureSnapshot {
|
||||
const plan = standardEntitlementPlans.find((candidate) => candidate.id === planCode);
|
||||
const feature = plan?.features.find((candidate) => candidate.featureKey === featureKeys.customerPortal);
|
||||
const registryItem = getFeatureGate(featureKeys.customerPortal);
|
||||
if (!feature || !registryItem) {
|
||||
throw new CustomerPortalUatError(`customer-portal UAT: canonical ${planCode} portal feature definition is unavailable`);
|
||||
}
|
||||
return {
|
||||
// SubscriptionFeature.order is an Int. The entitlement registry deliberately
|
||||
// uses fractional values to place adjacent features, while Prisma/Postgres
|
||||
// persists those values as the nearest integer.
|
||||
order: Math.round(feature.order),
|
||||
title: feature.label,
|
||||
name: feature.featureKey,
|
||||
code: null,
|
||||
type: feature.limitType,
|
||||
value: feature.limit ?? feature.limitType,
|
||||
quotaValue: null,
|
||||
href: null,
|
||||
badge: registryItem.title,
|
||||
accumulate: feature.limitType === entitlementLimitTypes.monthly,
|
||||
};
|
||||
}
|
||||
|
||||
function databaseFeatureMatches(actual: DatabaseFeatureSnapshot, expected: DatabaseFeatureSnapshot): boolean {
|
||||
return (
|
||||
actual.order === expected.order &&
|
||||
actual.title === expected.title &&
|
||||
actual.name === expected.name &&
|
||||
actual.code === expected.code &&
|
||||
actual.type === expected.type &&
|
||||
actual.value === expected.value &&
|
||||
actual.quotaValue === expected.quotaValue &&
|
||||
actual.href === expected.href &&
|
||||
actual.badge === expected.badge &&
|
||||
actual.accumulate === expected.accumulate
|
||||
);
|
||||
}
|
||||
|
||||
function commercialFeaturesMatch(
|
||||
product: DatabaseProductSnapshot,
|
||||
definition: (typeof customerPortalCommercialProducts)[keyof typeof customerPortalCommercialProducts]
|
||||
): boolean {
|
||||
if (product.features.length !== definition.featureKeys.length) return false;
|
||||
return definition.featureKeys.every((featureKey, index) => {
|
||||
const matches = product.features.filter((feature) => feature.name === featureKey);
|
||||
const registryItem = getFeatureGate(featureKey);
|
||||
if (matches.length !== 1 || !registryItem) return false;
|
||||
return databaseFeatureMatches(matches[0]!, {
|
||||
order: index + 1,
|
||||
title: registryItem.title,
|
||||
name: featureKey,
|
||||
code: null,
|
||||
type: entitlementLimitTypes.included,
|
||||
value: definition.includedQuantity ?? entitlementLimitTypes.included,
|
||||
quotaValue: null,
|
||||
href: null,
|
||||
badge: registryItem.title,
|
||||
accumulate: false,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function planBasePlanPortalFeatureReconciliation(snapshot: DatabaseCatalogSnapshot): readonly BasePlanPortalFeatureAction[] {
|
||||
return BASE_PLAN_CODES.map((planCode) => {
|
||||
const matches = snapshot.basePlans.filter((plan) => plan.code === planCode);
|
||||
if (matches.length !== 1) {
|
||||
return {
|
||||
planCode,
|
||||
productId: null,
|
||||
action: "blocked",
|
||||
issue: `${planCode}: expected exactly one canonical base-plan product`,
|
||||
};
|
||||
}
|
||||
const plan = matches[0]!;
|
||||
if (plan.kind !== "base_plan") {
|
||||
return {
|
||||
planCode,
|
||||
productId: plan.id,
|
||||
action: "blocked",
|
||||
issue: `${planCode}: canonical product is not a base plan`,
|
||||
};
|
||||
}
|
||||
if (plan.portalFeatures.length > 1) {
|
||||
return {
|
||||
planCode,
|
||||
productId: plan.id,
|
||||
action: "blocked",
|
||||
issue: `${planCode}: duplicate customer_portal feature rows`,
|
||||
};
|
||||
}
|
||||
const feature = plan.portalFeatures[0];
|
||||
if (!feature) {
|
||||
return {
|
||||
planCode,
|
||||
productId: plan.id,
|
||||
action: "create",
|
||||
issue: `${planCode}: canonical customer_portal feature missing`,
|
||||
};
|
||||
}
|
||||
if (!databaseFeatureMatches(feature, getBasePlanPortalFeatureDefinition(planCode))) {
|
||||
return {
|
||||
planCode,
|
||||
productId: plan.id,
|
||||
action: "blocked",
|
||||
issue: `${planCode}: existing customer_portal feature differs from the canonical contract`,
|
||||
};
|
||||
}
|
||||
return { planCode, productId: plan.id, action: "noop", issue: null };
|
||||
});
|
||||
}
|
||||
|
||||
export function assessDatabaseCatalog(snapshot: DatabaseCatalogSnapshot): DatabaseCatalogAssessment {
|
||||
const reconcileIssues: string[] = [];
|
||||
const blockingIssues: string[] = [];
|
||||
|
||||
for (const definition of Object.values(customerPortalCommercialProducts)) {
|
||||
const expectedBillingProviderId = `hivegrid_commercial_product_${definition.code}`;
|
||||
const seedCollisions = snapshot.commercialProducts.filter(
|
||||
(product) => product.code !== definition.code && (product.title === definition.title || product.billingProviderId === expectedBillingProviderId)
|
||||
);
|
||||
if (seedCollisions.length > 0) {
|
||||
blockingIssues.push(`${definition.code}: existing seed-key collision would mutate another product`);
|
||||
continue;
|
||||
}
|
||||
const matches = snapshot.commercialProducts.filter((product) => product.code === definition.code);
|
||||
if (matches.length > 1) {
|
||||
blockingIssues.push(`${definition.code}: duplicate database products`);
|
||||
continue;
|
||||
}
|
||||
const product = matches[0];
|
||||
if (!product) {
|
||||
reconcileIssues.push(`${definition.code}: product missing`);
|
||||
continue;
|
||||
}
|
||||
if (product.title !== definition.title && product.billingProviderId !== expectedBillingProviderId) {
|
||||
blockingIssues.push(`${definition.code}: canonical code is not reachable through the existing seed keys`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const expectedLagoPlanCode = definition.source === "recurring_add_on" ? definition.code : null;
|
||||
if (
|
||||
product.billingProviderId !== expectedBillingProviderId ||
|
||||
product.title !== definition.title ||
|
||||
product.description !== definition.description ||
|
||||
product.kind !== definition.source ||
|
||||
product.order !== definition.catalogOrder ||
|
||||
product.model !== 0 ||
|
||||
product.active !== true ||
|
||||
product.public !== definition.public ||
|
||||
product.groupTitle !== "Customer Portal" ||
|
||||
product.groupDescription !== null ||
|
||||
product.badge !== null ||
|
||||
product.billingAddressCollection !== "auto" ||
|
||||
product.hasQuantity !== false ||
|
||||
product.canBuyAgain !== (definition.source === "one_time_setup") ||
|
||||
product.lagoPlanCode !== expectedLagoPlanCode
|
||||
) {
|
||||
reconcileIssues.push(`${definition.code}: product metadata differs`);
|
||||
}
|
||||
if (!commercialFeaturesMatch(product, definition)) {
|
||||
reconcileIssues.push(`${definition.code}: feature contract differs`);
|
||||
}
|
||||
|
||||
const activePrices = product.prices.filter((price) => price.active);
|
||||
if (definition.amountCents === null || definition.currency === null) {
|
||||
if (activePrices.length > 0) blockingIssues.push(`${definition.code}: unexpected active price cannot be removed by reconciliation`);
|
||||
continue;
|
||||
}
|
||||
const expectedPeriod = definition.source === "recurring_add_on" ? 3 : 0;
|
||||
const expectedPrice = (definition.amountCents / 100).toFixed(2);
|
||||
const expectedCurrency = definition.currency.toLowerCase();
|
||||
const seedPriceCandidates = product.prices.filter((price) => price.billingPeriod === expectedPeriod && price.currency.toLowerCase() === expectedCurrency);
|
||||
if (seedPriceCandidates.length > 1) {
|
||||
blockingIssues.push(`${definition.code}: duplicate seed-key prices`);
|
||||
continue;
|
||||
}
|
||||
const price = seedPriceCandidates[0];
|
||||
if (!price) {
|
||||
reconcileIssues.push(`${definition.code}: canonical active price missing`);
|
||||
} else {
|
||||
const expectedPriceProviderId = `hivegrid_commercial_price_${definition.code}`;
|
||||
const expectedType = definition.source === "recurring_add_on" ? 1 : 0;
|
||||
if (
|
||||
price.billingProviderId !== expectedPriceProviderId ||
|
||||
price.lagoFeeCode !== definition.code ||
|
||||
price.molliePriceReference !== expectedPriceProviderId ||
|
||||
price.type !== expectedType ||
|
||||
price.price !== expectedPrice ||
|
||||
price.currency !== expectedCurrency ||
|
||||
price.trialDays !== 0 ||
|
||||
!price.active
|
||||
) {
|
||||
reconcileIssues.push(`${definition.code}: canonical price contract differs`);
|
||||
}
|
||||
}
|
||||
const unexpectedActivePrices = activePrices.filter((candidate) => candidate !== price);
|
||||
if (unexpectedActivePrices.length > 0) {
|
||||
blockingIssues.push(`${definition.code}: unexpected active price cannot be removed by reconciliation`);
|
||||
}
|
||||
}
|
||||
|
||||
for (const action of planBasePlanPortalFeatureReconciliation(snapshot)) {
|
||||
if (action.action === "create") reconcileIssues.push(action.issue!);
|
||||
if (action.action === "blocked") blockingIssues.push(action.issue!);
|
||||
}
|
||||
|
||||
return { reconcileIssues, blockingIssues };
|
||||
}
|
||||
|
||||
export function buildCustomerPortalCatalogPlan(provider: ProviderCatalogSnapshot, database: DatabaseCatalogSnapshot): CustomerPortalCatalogPlan {
|
||||
const providerPlan = planProviderCatalog(provider);
|
||||
const databaseAssessment = assessDatabaseCatalog(database);
|
||||
return {
|
||||
provider: providerPlan,
|
||||
database: {
|
||||
action: databaseAssessment.blockingIssues.length > 0 ? "blocked" : databaseAssessment.reconcileIssues.length > 0 ? "reconcile" : "noop",
|
||||
...databaseAssessment,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function customerPortalCatalogPlanIsComplete(plan: CustomerPortalCatalogPlan): boolean {
|
||||
return plan.provider.every((action) => action.action === "noop") && plan.database.action === "noop";
|
||||
}
|
||||
|
||||
export function customerPortalCatalogPlanIsBlocked(plan: CustomerPortalCatalogPlan): boolean {
|
||||
return plan.provider.some((action) => action.action === "drift") || plan.database.action === "blocked";
|
||||
}
|
||||
|
||||
export async function readDatabaseCatalog(db: DbClient): Promise<DatabaseCatalogSnapshot> {
|
||||
const commercialTitles = Object.values(customerPortalCommercialProducts).map((product) => product.title);
|
||||
const commercialBillingProviderIds = Object.values(customerPortalCommercialProducts).map((product) => `hivegrid_commercial_product_${product.code}`);
|
||||
const products = await db.subscriptionProduct.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ code: { in: [...COMMERCIAL_PRODUCT_CODES, ...BASE_PLAN_CODES] } },
|
||||
{ title: { in: commercialTitles } },
|
||||
{ billingProviderId: { in: commercialBillingProviderIds } },
|
||||
],
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
billingProviderId: true,
|
||||
code: true,
|
||||
title: true,
|
||||
description: true,
|
||||
kind: true,
|
||||
order: true,
|
||||
model: true,
|
||||
active: true,
|
||||
public: true,
|
||||
groupTitle: true,
|
||||
groupDescription: true,
|
||||
badge: true,
|
||||
billingAddressCollection: true,
|
||||
hasQuantity: true,
|
||||
canBuyAgain: true,
|
||||
lagoPlanCode: true,
|
||||
features: {
|
||||
select: {
|
||||
order: true,
|
||||
title: true,
|
||||
name: true,
|
||||
code: true,
|
||||
type: true,
|
||||
value: true,
|
||||
quotaValue: true,
|
||||
href: true,
|
||||
badge: true,
|
||||
accumulate: true,
|
||||
},
|
||||
},
|
||||
prices: {
|
||||
select: {
|
||||
billingProviderId: true,
|
||||
lagoFeeCode: true,
|
||||
molliePriceReference: true,
|
||||
type: true,
|
||||
billingPeriod: true,
|
||||
price: true,
|
||||
currency: true,
|
||||
trialDays: true,
|
||||
active: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const snapshots: DatabaseProductSnapshot[] = products.map((product) => ({
|
||||
...product,
|
||||
kind: String(product.kind),
|
||||
features: product.features,
|
||||
prices: product.prices.map((price) => ({ ...price, price: price.price.toFixed(2) })),
|
||||
}));
|
||||
return {
|
||||
commercialProducts: snapshots.filter(
|
||||
(product) =>
|
||||
(product.code !== null && COMMERCIAL_PRODUCT_CODES.includes(product.code as never)) ||
|
||||
commercialTitles.includes(product.title) ||
|
||||
commercialBillingProviderIds.includes(product.billingProviderId)
|
||||
),
|
||||
basePlans: products
|
||||
.filter((product) => product.code !== null && BASE_PLAN_CODES.includes(product.code as never))
|
||||
.map((product) => ({
|
||||
id: product.id,
|
||||
code: product.code,
|
||||
kind: String(product.kind),
|
||||
portalFeatures: product.features.filter((feature) => feature.name === featureKeys.customerPortal),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export async function reconcileBasePlanPortalFeatures(db: DbClient): Promise<readonly EntitlementPlanId[]> {
|
||||
const actions = planBasePlanPortalFeatureReconciliation(await readDatabaseCatalog(db));
|
||||
const blocked = actions.find((action) => action.action === "blocked");
|
||||
if (blocked) {
|
||||
throw new CustomerPortalUatError(`customer-portal UAT: ${blocked.issue}`);
|
||||
}
|
||||
|
||||
const created: EntitlementPlanId[] = [];
|
||||
for (const action of actions) {
|
||||
if (action.action !== "create" || !action.productId) continue;
|
||||
const feature = getBasePlanPortalFeatureDefinition(action.planCode);
|
||||
await db.subscriptionFeature.create({
|
||||
data: {
|
||||
subscriptionProductId: action.productId,
|
||||
order: feature.order,
|
||||
title: feature.title,
|
||||
name: feature.name,
|
||||
code: feature.code,
|
||||
type: feature.type,
|
||||
value: feature.value,
|
||||
href: feature.href,
|
||||
badge: feature.badge,
|
||||
accumulate: feature.accumulate,
|
||||
},
|
||||
});
|
||||
created.push(action.planCode);
|
||||
}
|
||||
return created;
|
||||
}
|
||||
|
||||
export class LagoCatalogClient {
|
||||
private readonly apiUrl: string;
|
||||
private readonly apiKey: string;
|
||||
private readonly fetchImpl: typeof fetch;
|
||||
private readonly timeoutMs: number;
|
||||
private readonly expectedOrganizationIdSha256: string;
|
||||
|
||||
constructor(
|
||||
input: { apiUrl: string; apiKey: string; fetchImpl?: typeof fetch; timeoutMs?: number },
|
||||
testOverrides?: { expectedOrganizationIdSha256: string }
|
||||
) {
|
||||
if (testOverrides && !input.fetchImpl) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: Lago identity test override requires an injected transport");
|
||||
}
|
||||
try {
|
||||
this.apiUrl = testOverrides ? normalizeLagoApiUrl(input.apiUrl) : normalizeCustomerPortalStagingLagoApiUrl(input.apiUrl);
|
||||
} catch {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: LAGO_API_URL is invalid");
|
||||
}
|
||||
this.apiKey = input.apiKey.trim();
|
||||
if (!this.apiKey) throw new CustomerPortalUatError("customer-portal UAT: LAGO_API_KEY is required");
|
||||
this.fetchImpl = input.fetchImpl ?? fetch;
|
||||
this.timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
this.expectedOrganizationIdSha256 = testOverrides?.expectedOrganizationIdSha256 ?? STAGING_LAGO_ORGANIZATION_ID_SHA256;
|
||||
}
|
||||
|
||||
async readCatalog(): Promise<ProviderCatalogSnapshot> {
|
||||
await this.assertStagingOrganization();
|
||||
const [plan, addOn] = await Promise.all([
|
||||
this.request(`/plans/${encodeURIComponent(desiredLagoPlan.code)}`, "GET", undefined, lagoPlanResponseSchema, true),
|
||||
this.request(`/add_ons/${encodeURIComponent(desiredLagoAddOn.code)}`, "GET", undefined, lagoAddOnResponseSchema, true),
|
||||
]);
|
||||
return { plan: plan?.plan ?? null, addOn: addOn?.add_on ?? null };
|
||||
}
|
||||
|
||||
async createPlan(): Promise<void> {
|
||||
await this.assertStagingOrganization();
|
||||
await this.request(
|
||||
"/plans",
|
||||
"POST",
|
||||
{
|
||||
plan: {
|
||||
name: desiredLagoPlan.name,
|
||||
code: desiredLagoPlan.code,
|
||||
description: desiredLagoPlan.description,
|
||||
interval: desiredLagoPlan.interval,
|
||||
amount_cents: desiredLagoPlan.amountCents,
|
||||
amount_currency: desiredLagoPlan.amountCurrency,
|
||||
pay_in_advance: desiredLagoPlan.payInAdvance,
|
||||
tax_codes: desiredLagoPlan.taxCodes,
|
||||
},
|
||||
},
|
||||
lagoPlanResponseSchema
|
||||
);
|
||||
}
|
||||
|
||||
async updatePlan(): Promise<void> {
|
||||
await this.assertStagingOrganization();
|
||||
await this.request(
|
||||
`/plans/${encodeURIComponent(desiredLagoPlan.code)}`,
|
||||
"PUT",
|
||||
{
|
||||
plan: {
|
||||
name: desiredLagoPlan.name,
|
||||
code: desiredLagoPlan.code,
|
||||
description: desiredLagoPlan.description,
|
||||
interval: desiredLagoPlan.interval,
|
||||
amount_cents: desiredLagoPlan.amountCents,
|
||||
amount_currency: desiredLagoPlan.amountCurrency,
|
||||
pay_in_advance: desiredLagoPlan.payInAdvance,
|
||||
tax_codes: desiredLagoPlan.taxCodes,
|
||||
},
|
||||
},
|
||||
lagoPlanResponseSchema
|
||||
);
|
||||
}
|
||||
|
||||
async createAddOn(): Promise<void> {
|
||||
await this.assertStagingOrganization();
|
||||
await this.request(
|
||||
"/add_ons",
|
||||
"POST",
|
||||
{
|
||||
add_on: {
|
||||
name: desiredLagoAddOn.name,
|
||||
code: desiredLagoAddOn.code,
|
||||
description: desiredLagoAddOn.description,
|
||||
amount_cents: desiredLagoAddOn.amountCents,
|
||||
amount_currency: desiredLagoAddOn.amountCurrency,
|
||||
tax_codes: desiredLagoAddOn.taxCodes,
|
||||
},
|
||||
},
|
||||
lagoAddOnResponseSchema
|
||||
);
|
||||
}
|
||||
|
||||
async updateAddOn(): Promise<void> {
|
||||
await this.assertStagingOrganization();
|
||||
await this.request(
|
||||
`/add_ons/${encodeURIComponent(desiredLagoAddOn.code)}`,
|
||||
"PUT",
|
||||
{
|
||||
add_on: {
|
||||
name: desiredLagoAddOn.name,
|
||||
code: desiredLagoAddOn.code,
|
||||
description: desiredLagoAddOn.description,
|
||||
amount_cents: desiredLagoAddOn.amountCents,
|
||||
amount_currency: desiredLagoAddOn.amountCurrency,
|
||||
tax_codes: desiredLagoAddOn.taxCodes,
|
||||
},
|
||||
},
|
||||
lagoAddOnResponseSchema
|
||||
);
|
||||
}
|
||||
|
||||
private async assertStagingOrganization(): Promise<void> {
|
||||
const response = await this.request("/organizations", "GET", undefined, lagoOrganizationResponseSchema);
|
||||
const organization = response?.organization;
|
||||
const idSha256 = organization ? createHash("sha256").update(organization.lago_id).digest("hex") : "";
|
||||
if (organization?.name !== STAGING_LAGO_ORGANIZATION_NAME || idSha256 !== this.expectedOrganizationIdSha256) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: Lago organization does not match the canonical staging identity");
|
||||
}
|
||||
}
|
||||
|
||||
private async request<T>(path: string, method: "GET" | "POST" | "PUT", body: unknown, schema: z.ZodType<T>, allowNotFound = false): Promise<T | null> {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
|
||||
try {
|
||||
const response = await this.fetchImpl(`${this.apiUrl}/api/v1${path}`, {
|
||||
method,
|
||||
headers: {
|
||||
authorization: `Bearer ${this.apiKey}`,
|
||||
accept: "application/json",
|
||||
...(body === undefined ? {} : { "content-type": "application/json" }),
|
||||
},
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
redirect: "error",
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (allowNotFound && response.status === 404) return null;
|
||||
if (!response.ok) throw new CustomerPortalUatError(`customer-portal UAT: Lago catalog request failed with status ${response.status}`);
|
||||
const parsed = schema.safeParse(await response.json());
|
||||
if (!parsed.success) throw new CustomerPortalUatError("customer-portal UAT: Lago catalog response shape is invalid");
|
||||
return parsed.data;
|
||||
} catch (error) {
|
||||
if (error instanceof CustomerPortalUatError) throw error;
|
||||
throw new CustomerPortalUatError("customer-portal UAT: Lago catalog request failed");
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
}
|
||||
+1337
File diff suppressed because it is too large.
Load diff
+2024
File diff suppressed because it is too large.
Load diff
+112
@@ -0,0 +1,112 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
CUSTOMER_PORTAL_UAT_COMMERCIAL_CONFIRMATION,
|
||||
CUSTOMER_PORTAL_UAT_TENANT_SLUG,
|
||||
parseCustomerPortalUatCommand,
|
||||
safeCustomerPortalUatError,
|
||||
} from "./contracts";
|
||||
|
||||
const baseEnvironment = {
|
||||
NODE_ENV: "production",
|
||||
SENTRY_ENVIRONMENT: "staging",
|
||||
RLS_RUNTIME_MODE: "required",
|
||||
DATABASE_RUNTIME_ROLE: "hivegrid_app",
|
||||
DATABASE_URL: "postgresql://hivegrid_app:runtime-secret@db.staging.internal:6432/hivegrid_staging",
|
||||
CUSTOMER_PORTAL_UAT_EXPECTED_DATABASE_HOST: "db.staging.internal",
|
||||
CUSTOMER_PORTAL_UAT_EXPECTED_DATABASE_PORT: "6432",
|
||||
CUSTOMER_PORTAL_UAT_EXPECTED_DATABASE: "hivegrid_staging",
|
||||
CUSTOMER_PORTAL_UAT_OPERATOR_USER_ID: "operator-user-id",
|
||||
CUSTOMER_PORTAL_UAT_EXPECTED_TENANT_ID: "tenant-demo-pro",
|
||||
CUSTOMER_PORTAL_UAT_EXPECTED_STARTER_TENANT_ID: "tenant-demo-starter",
|
||||
CUSTOMER_PORTAL_UAT_EXPECTED_PRO_TENANT_ID: "tenant-demo-pro",
|
||||
CUSTOMER_PORTAL_UAT_EXPECTED_ENTERPRISE_TENANT_ID: "tenant-demo-enterprise",
|
||||
CUSTOMER_PORTAL_UAT_PASSWORD: "Q7!portal-UAT-strong-random-2026",
|
||||
LAGO_API_URL: "http://127.0.0.1:3108",
|
||||
LAGO_API_KEY: "lago-staging-key",
|
||||
AUDIT_CHAIN_SECRET: "staging-audit-chain-secret-at-least-32-bytes",
|
||||
} as const;
|
||||
|
||||
describe("customer-portal UAT command contract", () => {
|
||||
it("defaults to a read-only plan and keeps catalog and fixture inputs separate", () => {
|
||||
const catalog = parseCustomerPortalUatCommand("catalog", [], baseEnvironment);
|
||||
const fixture = parseCustomerPortalUatCommand("fixture", ["--verify"], baseEnvironment);
|
||||
|
||||
expect(catalog).toMatchObject({ target: "catalog", mode: "plan", lagoApiUrl: "http://127.0.0.1:3108" });
|
||||
expect(fixture).toMatchObject({ target: "fixture", mode: "verify", expectedTenantId: "tenant-demo-pro" });
|
||||
expect("password" in catalog).toBe(false);
|
||||
expect("lagoApiKey" in fixture).toBe(false);
|
||||
});
|
||||
|
||||
it("binds the commercial fixture to three distinct explicit tenant ids", () => {
|
||||
const fixture = parseCustomerPortalUatCommand("commercial-fixture", ["--verify"], baseEnvironment);
|
||||
expect(fixture).toMatchObject({
|
||||
target: "commercial-fixture",
|
||||
mode: "verify",
|
||||
expectedStarterTenantId: "tenant-demo-starter",
|
||||
expectedProTenantId: "tenant-demo-pro",
|
||||
expectedEnterpriseTenantId: "tenant-demo-enterprise",
|
||||
});
|
||||
expect(() =>
|
||||
parseCustomerPortalUatCommand("commercial-fixture", [], {
|
||||
...baseEnvironment,
|
||||
CUSTOMER_PORTAL_UAT_EXPECTED_STARTER_TENANT_ID: "same-tenant",
|
||||
CUSTOMER_PORTAL_UAT_EXPECTED_PRO_TENANT_ID: "same-tenant",
|
||||
CUSTOMER_PORTAL_UAT_EXPECTED_ENTERPRISE_TENANT_ID: "tenant-demo-enterprise",
|
||||
})
|
||||
).toThrow("must be distinct");
|
||||
});
|
||||
|
||||
it("requires an exact tenant confirmation for every mutation", () => {
|
||||
expect(() => parseCustomerPortalUatCommand("catalog", ["--apply"], baseEnvironment)).toThrow(`--confirm=${CUSTOMER_PORTAL_UAT_TENANT_SLUG}`);
|
||||
expect(() => parseCustomerPortalUatCommand("catalog", ["--apply", `--confirm=${CUSTOMER_PORTAL_UAT_TENANT_SLUG}`], baseEnvironment)).not.toThrow();
|
||||
expect(() => parseCustomerPortalUatCommand("fixture", ["--plan", `--confirm=${CUSTOMER_PORTAL_UAT_TENANT_SLUG}`], baseEnvironment)).toThrow(
|
||||
"only with --apply"
|
||||
);
|
||||
expect(() => parseCustomerPortalUatCommand("commercial-fixture", ["--apply", `--confirm=${CUSTOMER_PORTAL_UAT_TENANT_SLUG}`], baseEnvironment)).toThrow(
|
||||
`--confirm=${CUSTOMER_PORTAL_UAT_COMMERCIAL_CONFIRMATION}`
|
||||
);
|
||||
expect(() =>
|
||||
parseCustomerPortalUatCommand("commercial-fixture", ["--apply", `--confirm=${CUSTOMER_PORTAL_UAT_COMMERCIAL_CONFIRMATION}`], baseEnvironment)
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["non-production Node runtime", { NODE_ENV: "development" }],
|
||||
["production environment", { SENTRY_ENVIRONMENT: "production" }],
|
||||
["RLS disabled", { RLS_RUNTIME_MODE: "off" }],
|
||||
["wrong runtime role", { DATABASE_RUNTIME_ROLE: "postgres" }],
|
||||
["wrong URL role", { DATABASE_URL: "postgresql://postgres:secret@db.staging.internal:6432/hivegrid_staging" }],
|
||||
["URL host override", { DATABASE_URL: "postgresql://hivegrid_app:secret@db.staging.internal:6432/hivegrid_staging?host=production-db" }],
|
||||
["URL user override", { DATABASE_URL: "postgresql://hivegrid_app:secret@db.staging.internal:6432/hivegrid_staging?user=postgres" }],
|
||||
[
|
||||
"URL options override",
|
||||
{ DATABASE_URL: "postgresql://hivegrid_app:secret@db.staging.internal:6432/hivegrid_staging?options=-c%20hivegrid.environment%3Dstaging" },
|
||||
],
|
||||
["URL service override", { DATABASE_URL: "postgresql://hivegrid_app:secret@db.staging.internal:6432/hivegrid_staging?service=production" }],
|
||||
["libpq PGOPTIONS override", { PGOPTIONS: "-c hivegrid.environment=staging" }],
|
||||
["libpq PGHOST override", { PGHOST: "production-db" }],
|
||||
["libpq PGSERVICE override", { PGSERVICE: "production" }],
|
||||
["wrong database binding", { CUSTOMER_PORTAL_UAT_EXPECTED_DATABASE: "other" }],
|
||||
["migration credential present", { DIRECT_URL: "postgresql://migrator:secret@db/hivegrid" }],
|
||||
["migrator credential present", { MIGRATOR_PASSWORD: "do-not-use" }],
|
||||
["runtime seed flag present", { SEED_ON_BOOT: "true" }],
|
||||
["non-staging Lago endpoint", { LAGO_API_URL: "https://billing.example.test" }],
|
||||
["credential-bearing Lago URL", { LAGO_API_URL: "http://user:pass@127.0.0.1:3108" }],
|
||||
["missing audit secret", { AUDIT_CHAIN_SECRET: "" }],
|
||||
["short audit secret", { AUDIT_CHAIN_SECRET: "too-short" }],
|
||||
])("fails closed for %s", (_label, override) => {
|
||||
expect(() => parseCustomerPortalUatCommand("catalog", [], { ...baseEnvironment, ...override })).toThrow();
|
||||
});
|
||||
|
||||
it("rejects weak fixture passwords without disclosing the supplied value", () => {
|
||||
expect(() => parseCustomerPortalUatCommand("fixture", [], { ...baseEnvironment, CUSTOMER_PORTAL_UAT_PASSWORD: "password" })).toThrow(
|
||||
"strong random secret"
|
||||
);
|
||||
});
|
||||
|
||||
it("does not expose unexpected error details", () => {
|
||||
expect(safeCustomerPortalUatError(new Error("postgresql://user:secret@host/database"))).not.toContain("secret");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,250 @@
|
||||
export const CUSTOMER_PORTAL_UAT_TENANT_SLUG = "demo-pro-crm" as const;
|
||||
export const CUSTOMER_PORTAL_UAT_STARTER_TENANT_SLUG = "demo-starter-crm" as const;
|
||||
export const CUSTOMER_PORTAL_UAT_ENTERPRISE_TENANT_SLUG = "demo-enterprise-crm" as const;
|
||||
export const CUSTOMER_PORTAL_UAT_COMMERCIAL_CONFIRMATION = "demo-starter-crm+demo-pro-crm+demo-enterprise-crm" as const;
|
||||
export const CUSTOMER_PORTAL_UAT_STANDARD_ORIGIN = "https://staging-portal.hivegrid.de" as const;
|
||||
export const CUSTOMER_PORTAL_UAT_ADMIN_EMAIL = "customer-portal-admin-uat@saas-ctrl.com" as const;
|
||||
export const CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL = "customer-portal-uat@saas-ctrl.com" as const;
|
||||
export const CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL = "customer-portal-subcontractor-uat@saas-ctrl.com" as const;
|
||||
export const CUSTOMER_PORTAL_UAT_PROJECT_ID = "rheinmain-shk-v1-project-0001" as const;
|
||||
export const CUSTOMER_PORTAL_UAT_FORBIDDEN_PROJECT_ID = "rheinmain-shk-v1-project-0002" as const;
|
||||
|
||||
export type CustomerPortalUatMode = "plan" | "verify" | "apply";
|
||||
export type CustomerPortalUatTarget = "catalog" | "fixture" | "commercial-fixture";
|
||||
export type CustomerPortalUatEnvironment = Readonly<Record<string, string | undefined>>;
|
||||
|
||||
export type CustomerPortalUatDatabaseBinding = {
|
||||
readonly databaseUrl: string;
|
||||
readonly expectedDatabaseHost: string;
|
||||
readonly expectedDatabasePort: string;
|
||||
readonly expectedDatabaseName: string;
|
||||
readonly operatorUserId: string;
|
||||
readonly auditChainSecret: string;
|
||||
};
|
||||
|
||||
export type CustomerPortalCatalogCommand = CustomerPortalUatDatabaseBinding & {
|
||||
readonly target: "catalog";
|
||||
readonly mode: CustomerPortalUatMode;
|
||||
readonly lagoApiUrl: string;
|
||||
readonly lagoApiKey: string;
|
||||
};
|
||||
|
||||
export type CustomerPortalFixtureCommand = CustomerPortalUatDatabaseBinding & {
|
||||
readonly target: "fixture";
|
||||
readonly mode: CustomerPortalUatMode;
|
||||
readonly expectedTenantId: string;
|
||||
readonly password: string;
|
||||
};
|
||||
|
||||
export type CustomerPortalCommercialFixtureCommand = CustomerPortalUatDatabaseBinding & {
|
||||
readonly target: "commercial-fixture";
|
||||
readonly mode: CustomerPortalUatMode;
|
||||
readonly expectedStarterTenantId: string;
|
||||
readonly expectedProTenantId: string;
|
||||
readonly expectedEnterpriseTenantId: string;
|
||||
readonly password: string;
|
||||
};
|
||||
|
||||
export type CustomerPortalUatCommand = CustomerPortalCatalogCommand | CustomerPortalFixtureCommand | CustomerPortalCommercialFixtureCommand;
|
||||
|
||||
const modeArguments = new Map<string, CustomerPortalUatMode>([
|
||||
["--plan", "plan"],
|
||||
["--verify", "verify"],
|
||||
["--apply", "apply"],
|
||||
]);
|
||||
|
||||
const forbiddenEnvironmentKeys = new Set(["DIRECT_URL", "MIGRATE_ON_BOOT", "SEED_ON_BOOT"]);
|
||||
const allowedStagingLagoApiUrls = new Set(["http://127.0.0.1:3108", "http://10.42.0.4:3108"]);
|
||||
|
||||
export class CustomerPortalUatError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = "CustomerPortalUatError";
|
||||
}
|
||||
}
|
||||
|
||||
function requiredEnvironmentValue(env: CustomerPortalUatEnvironment, name: string): string {
|
||||
const value = env[name]?.trim();
|
||||
if (!value) throw new CustomerPortalUatError(`customer-portal UAT: ${name} is required`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function parseSingleValueArgument(argv: readonly string[], name: string): string | undefined {
|
||||
const prefix = `${name}=`;
|
||||
const values = argv.filter((argument) => argument.startsWith(prefix)).map((argument) => argument.slice(prefix.length));
|
||||
if (values.length > 1) throw new CustomerPortalUatError(`customer-portal UAT: ${name} may only be provided once`);
|
||||
return values[0];
|
||||
}
|
||||
|
||||
function parseMode(argv: readonly string[]): CustomerPortalUatMode {
|
||||
const modes = argv.flatMap((argument) => {
|
||||
const mode = modeArguments.get(argument);
|
||||
return mode ? [mode] : [];
|
||||
});
|
||||
if (modes.length > 1) throw new CustomerPortalUatError("customer-portal UAT: provide exactly one mode");
|
||||
return modes[0] ?? "plan";
|
||||
}
|
||||
|
||||
function assertKnownArguments(argv: readonly string[]): void {
|
||||
for (const argument of argv) {
|
||||
if (modeArguments.has(argument) || argument.startsWith("--confirm=")) continue;
|
||||
throw new CustomerPortalUatError("customer-portal UAT: unknown argument");
|
||||
}
|
||||
}
|
||||
|
||||
function assertOperatorEnvironment(env: CustomerPortalUatEnvironment): void {
|
||||
if (env.NODE_ENV?.trim() !== "production") {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: NODE_ENV must be production so production audit guarantees stay active");
|
||||
}
|
||||
if (env.SENTRY_ENVIRONMENT?.trim() !== "staging") {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: SENTRY_ENVIRONMENT must be staging");
|
||||
}
|
||||
if (env.RLS_RUNTIME_MODE?.trim() !== "required") {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: RLS_RUNTIME_MODE must be required");
|
||||
}
|
||||
if (env.DATABASE_RUNTIME_ROLE?.trim() !== "hivegrid_app") {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: DATABASE_RUNTIME_ROLE must be hivegrid_app");
|
||||
}
|
||||
const auditChainSecret = env.AUDIT_CHAIN_SECRET;
|
||||
if (!auditChainSecret || Buffer.byteLength(auditChainSecret, "utf8") < 32) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: AUDIT_CHAIN_SECRET must contain the canonical staging audit secret");
|
||||
}
|
||||
for (const [name, value] of Object.entries(env)) {
|
||||
if (!value) continue;
|
||||
if (forbiddenEnvironmentKeys.has(name) || name.startsWith("SEED_") || name.startsWith("MIGRATOR_") || name.toUpperCase().startsWith("PG")) {
|
||||
throw new CustomerPortalUatError(`customer-portal UAT: forbidden operator environment key ${name}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeCustomerPortalStagingLagoApiUrl(value: string): string {
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(value);
|
||||
} catch {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: LAGO_API_URL must be the canonical staging endpoint");
|
||||
}
|
||||
if (parsed.username || parsed.password || parsed.search || parsed.hash || (parsed.pathname !== "" && parsed.pathname !== "/")) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: LAGO_API_URL must be the canonical staging endpoint");
|
||||
}
|
||||
const normalized = parsed.origin;
|
||||
if (!allowedStagingLagoApiUrls.has(normalized)) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: LAGO_API_URL must be the canonical staging endpoint");
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function requireStagingLagoApiUrl(env: CustomerPortalUatEnvironment): string {
|
||||
return normalizeCustomerPortalStagingLagoApiUrl(requiredEnvironmentValue(env, "LAGO_API_URL"));
|
||||
}
|
||||
|
||||
function parseDatabaseBinding(env: CustomerPortalUatEnvironment): CustomerPortalUatDatabaseBinding {
|
||||
const databaseUrl = requiredEnvironmentValue(env, "DATABASE_URL");
|
||||
const expectedDatabaseHost = requiredEnvironmentValue(env, "CUSTOMER_PORTAL_UAT_EXPECTED_DATABASE_HOST");
|
||||
const expectedDatabasePort = requiredEnvironmentValue(env, "CUSTOMER_PORTAL_UAT_EXPECTED_DATABASE_PORT");
|
||||
const expectedDatabaseName = requiredEnvironmentValue(env, "CUSTOMER_PORTAL_UAT_EXPECTED_DATABASE");
|
||||
const operatorUserId = requiredEnvironmentValue(env, "CUSTOMER_PORTAL_UAT_OPERATOR_USER_ID");
|
||||
const auditChainSecret = requiredEnvironmentValue(env, "AUDIT_CHAIN_SECRET");
|
||||
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(databaseUrl);
|
||||
} catch {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: DATABASE_URL must be a valid PostgreSQL URL");
|
||||
}
|
||||
const databaseName = decodeURIComponent(parsed.pathname.replace(/^\//u, ""));
|
||||
if (!new Set(["postgres:", "postgresql:"]).has(parsed.protocol)) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: DATABASE_URL must use PostgreSQL");
|
||||
}
|
||||
if (parsed.username !== "hivegrid_app" || !parsed.password) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: DATABASE_URL must authenticate as hivegrid_app");
|
||||
}
|
||||
// pg-connection-string treats URI query parameters such as host, user,
|
||||
// port, database, service and options as connection-setting overrides.
|
||||
// Reject the entire query/fragment surface instead of trying to maintain a
|
||||
// partial deny-list that can silently grow behind this staging mutation
|
||||
// boundary.
|
||||
if (parsed.search || parsed.hash) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: DATABASE_URL must not contain PostgreSQL connection overrides");
|
||||
}
|
||||
if (parsed.hostname !== expectedDatabaseHost || parsed.port !== expectedDatabasePort || databaseName !== expectedDatabaseName) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: DATABASE_URL does not match the explicit staging database binding");
|
||||
}
|
||||
|
||||
return { databaseUrl, expectedDatabaseHost, expectedDatabasePort, expectedDatabaseName, operatorUserId, auditChainSecret };
|
||||
}
|
||||
|
||||
function assertMutationConfirmation(argv: readonly string[], mode: CustomerPortalUatMode, target: CustomerPortalUatTarget): void {
|
||||
const confirmation = parseSingleValueArgument(argv, "--confirm");
|
||||
const expectedConfirmation = target === "commercial-fixture" ? CUSTOMER_PORTAL_UAT_COMMERCIAL_CONFIRMATION : CUSTOMER_PORTAL_UAT_TENANT_SLUG;
|
||||
if (mode === "apply") {
|
||||
if (confirmation !== expectedConfirmation) {
|
||||
throw new CustomerPortalUatError(`customer-portal UAT: apply requires --confirm=${expectedConfirmation}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (confirmation !== undefined) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: --confirm is valid only with --apply");
|
||||
}
|
||||
}
|
||||
|
||||
function requireStrongUatPassword(env: CustomerPortalUatEnvironment): string {
|
||||
const password = requiredEnvironmentValue(env, "CUSTOMER_PORTAL_UAT_PASSWORD");
|
||||
if (password.length < 20 || new Set(password).size < 10 || /^(?:password|passwort|demo|hivegrid)/iu.test(password)) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: CUSTOMER_PORTAL_UAT_PASSWORD must be a strong random secret of at least 20 characters");
|
||||
}
|
||||
return password;
|
||||
}
|
||||
|
||||
export function parseCustomerPortalUatCommand(
|
||||
target: CustomerPortalUatTarget,
|
||||
argv: readonly string[],
|
||||
env: CustomerPortalUatEnvironment
|
||||
): CustomerPortalUatCommand {
|
||||
assertKnownArguments(argv);
|
||||
const mode = parseMode(argv);
|
||||
assertMutationConfirmation(argv, mode, target);
|
||||
assertOperatorEnvironment(env);
|
||||
const database = parseDatabaseBinding(env);
|
||||
|
||||
if (target === "catalog") {
|
||||
return {
|
||||
...database,
|
||||
target,
|
||||
mode,
|
||||
lagoApiUrl: requireStagingLagoApiUrl(env),
|
||||
lagoApiKey: requiredEnvironmentValue(env, "LAGO_API_KEY"),
|
||||
};
|
||||
}
|
||||
|
||||
if (target === "fixture") {
|
||||
return {
|
||||
...database,
|
||||
target,
|
||||
mode,
|
||||
expectedTenantId: requiredEnvironmentValue(env, "CUSTOMER_PORTAL_UAT_EXPECTED_TENANT_ID"),
|
||||
password: requireStrongUatPassword(env),
|
||||
};
|
||||
}
|
||||
|
||||
const expectedStarterTenantId = requiredEnvironmentValue(env, "CUSTOMER_PORTAL_UAT_EXPECTED_STARTER_TENANT_ID");
|
||||
const expectedProTenantId = requiredEnvironmentValue(env, "CUSTOMER_PORTAL_UAT_EXPECTED_PRO_TENANT_ID");
|
||||
const expectedEnterpriseTenantId = requiredEnvironmentValue(env, "CUSTOMER_PORTAL_UAT_EXPECTED_ENTERPRISE_TENANT_ID");
|
||||
if (new Set([expectedStarterTenantId, expectedProTenantId, expectedEnterpriseTenantId]).size !== 3) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: starter, pro, and Enterprise tenant bindings must be distinct");
|
||||
}
|
||||
return {
|
||||
...database,
|
||||
target,
|
||||
mode,
|
||||
expectedStarterTenantId,
|
||||
expectedProTenantId,
|
||||
expectedEnterpriseTenantId,
|
||||
password: requireStrongUatPassword(env),
|
||||
};
|
||||
}
|
||||
|
||||
export function safeCustomerPortalUatError(error: unknown): string {
|
||||
if (error instanceof CustomerPortalUatError) return error.message;
|
||||
return "customer-portal UAT: operator command failed; inspect redacted service logs";
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { computeAuditChainHeadMac, type AuditChainHeadRecord } from "@hivegrid/db/audit-chain-checkpoint.server";
|
||||
|
||||
import { assertCustomerPortalAuditAnchor, assertCustomerPortalDatabaseSession, assertCustomerPortalOperatorIdentity } from "./database";
|
||||
|
||||
const stagingSession = {
|
||||
sessionUser: "hivegrid_app",
|
||||
currentUser: "hivegrid_app",
|
||||
databaseName: "hivegrid_staging",
|
||||
databaseEnvironmentMarked: true,
|
||||
roleIsSuperuser: false,
|
||||
roleBypassesRls: false,
|
||||
roleCanCreateRole: false,
|
||||
roleCanCreateDatabase: false,
|
||||
} as const;
|
||||
|
||||
describe("customer-portal operator database guard", () => {
|
||||
it("accepts only the restricted runtime role on the explicitly bound staging database", () => {
|
||||
expect(() => assertCustomerPortalDatabaseSession(stagingSession, "hivegrid_staging")).not.toThrow();
|
||||
});
|
||||
|
||||
it("fails closed when the independent staging marker is missing or different", () => {
|
||||
expect(() => assertCustomerPortalDatabaseSession({ ...stagingSession, databaseEnvironmentMarked: false }, "hivegrid_staging")).toThrow(
|
||||
"database is not independently marked as staging"
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects a privileged role or a different database even with the staging marker", () => {
|
||||
expect(() => assertCustomerPortalDatabaseSession({ ...stagingSession, sessionUser: "postgres" }, "hivegrid_staging")).toThrow(
|
||||
"database session is not the restricted hivegrid_app role"
|
||||
);
|
||||
expect(() => assertCustomerPortalDatabaseSession(stagingSession, "hivegrid_production")).toThrow(
|
||||
"connected database does not match the explicit staging binding"
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["superuser", { roleIsSuperuser: true }],
|
||||
["BYPASSRLS", { roleBypassesRls: true }],
|
||||
["CREATEROLE", { roleCanCreateRole: true }],
|
||||
["CREATEDB", { roleCanCreateDatabase: true }],
|
||||
])("rejects a hivegrid_app role with %s privilege", (_label, privilege) => {
|
||||
expect(() => assertCustomerPortalDatabaseSession({ ...stagingSession, ...privilege }, "hivegrid_staging")).toThrow(
|
||||
"database session is not the restricted hivegrid_app role"
|
||||
);
|
||||
});
|
||||
|
||||
it("authenticates the existing platform audit anchor and rejects a different long secret", () => {
|
||||
const anchorWithoutMac: Omit<AuditChainHeadRecord, "headMac"> = {
|
||||
chainKey: "platform",
|
||||
tenantId: null,
|
||||
eventId: "event-1",
|
||||
eventHash: "a".repeat(64),
|
||||
eventCreatedAt: new Date("2026-07-17T00:00:00.000Z"),
|
||||
};
|
||||
const canonicalSecret = "canonical-staging-audit-secret-at-least-32-bytes";
|
||||
const anchor = { ...anchorWithoutMac, headMac: computeAuditChainHeadMac(anchorWithoutMac, canonicalSecret) };
|
||||
expect(() => assertCustomerPortalAuditAnchor(anchor, canonicalSecret)).not.toThrow();
|
||||
expect(() => assertCustomerPortalAuditAnchor(anchor, "wrong-but-still-long-audit-secret-at-least-32-bytes")).toThrow(
|
||||
"audit-chain anchor authentication failed"
|
||||
);
|
||||
expect(() => assertCustomerPortalAuditAnchor(null, canonicalSecret)).toThrow("audit-chain anchor authentication failed");
|
||||
});
|
||||
|
||||
it("accepts only the explicitly bound active platform AdminUser", () => {
|
||||
expect(() => assertCustomerPortalOperatorIdentity({ id: "admin-1", status: "active" }, "admin-1")).not.toThrow();
|
||||
expect(() => assertCustomerPortalOperatorIdentity({ id: "admin-2", status: "active" }, "admin-1")).toThrow(
|
||||
"operator identity is not an active AdminUser"
|
||||
);
|
||||
expect(() => assertCustomerPortalOperatorIdentity({ id: "admin-1", status: "disabled" }, "admin-1")).toThrow(
|
||||
"operator identity is not an active AdminUser"
|
||||
);
|
||||
expect(() => assertCustomerPortalOperatorIdentity(null, "admin-1")).toThrow("operator identity is not an active AdminUser");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import { getDbClient, type DbClient } from "@hivegrid/db/client.server";
|
||||
import {
|
||||
auditChainKey,
|
||||
verifyAuditChainHead,
|
||||
type AuditChainHeadRecord,
|
||||
} from "@hivegrid/db/audit-chain-checkpoint.server";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
|
||||
import { CustomerPortalUatError, type CustomerPortalUatDatabaseBinding } from "./contracts";
|
||||
|
||||
type DatabaseSession = {
|
||||
readonly sessionUser: string;
|
||||
readonly currentUser: string;
|
||||
readonly databaseName: string;
|
||||
readonly databaseEnvironmentMarked: boolean;
|
||||
readonly roleIsSuperuser: boolean;
|
||||
readonly roleBypassesRls: boolean;
|
||||
readonly roleCanCreateRole: boolean;
|
||||
readonly roleCanCreateDatabase: boolean;
|
||||
};
|
||||
|
||||
type OperatorIdentity = {
|
||||
readonly id: string;
|
||||
readonly status: string;
|
||||
};
|
||||
|
||||
export function assertCustomerPortalDatabaseSession(session: DatabaseSession | undefined, expectedDatabaseName: string): void {
|
||||
if (
|
||||
!session ||
|
||||
session.sessionUser !== "hivegrid_app" ||
|
||||
session.currentUser !== "hivegrid_app" ||
|
||||
session.roleIsSuperuser ||
|
||||
session.roleBypassesRls ||
|
||||
session.roleCanCreateRole ||
|
||||
session.roleCanCreateDatabase
|
||||
) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: database session is not the restricted hivegrid_app role");
|
||||
}
|
||||
if (session.databaseName !== expectedDatabaseName) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: connected database does not match the explicit staging binding");
|
||||
}
|
||||
if (!session.databaseEnvironmentMarked) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: database is not independently marked as staging");
|
||||
}
|
||||
}
|
||||
|
||||
export function assertCustomerPortalAuditAnchor(head: AuditChainHeadRecord | null, auditChainSecret: string): void {
|
||||
if (!head || head.chainKey !== auditChainKey(null) || head.tenantId !== null || !verifyAuditChainHead(head, auditChainSecret)) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: canonical platform audit-chain anchor authentication failed");
|
||||
}
|
||||
}
|
||||
|
||||
export function assertCustomerPortalOperatorIdentity(operator: OperatorIdentity | null, expectedOperatorId: string): void {
|
||||
if (!operator || operator.id !== expectedOperatorId || operator.status !== "active") {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: operator identity is not an active AdminUser");
|
||||
}
|
||||
}
|
||||
|
||||
export async function withCustomerPortalOperatorDatabase<T>(binding: CustomerPortalUatDatabaseBinding, callback: (db: DbClient) => Promise<T>): Promise<T> {
|
||||
const db = getDbClient({ connectionString: binding.databaseUrl, poolMax: 2 });
|
||||
try {
|
||||
return await runWithRlsContext({ userId: binding.operatorUserId }, async () => {
|
||||
const sessions = await db.$queryRaw<DatabaseSession[]>`
|
||||
SELECT
|
||||
session_user::text AS "sessionUser",
|
||||
current_user::text AS "currentUser",
|
||||
current_database()::text AS "databaseName",
|
||||
role.rolsuper AS "roleIsSuperuser",
|
||||
role.rolbypassrls AS "roleBypassesRls",
|
||||
role.rolcreaterole AS "roleCanCreateRole",
|
||||
role.rolcreatedb AS "roleCanCreateDatabase",
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
FROM pg_catalog.pg_db_role_setting AS setting
|
||||
JOIN pg_catalog.pg_database AS database
|
||||
ON database.oid = setting.setdatabase
|
||||
WHERE database.datname = current_database()
|
||||
AND setting.setrole = 0
|
||||
AND 'hivegrid.environment=staging' = ANY(setting.setconfig)
|
||||
) AS "databaseEnvironmentMarked"
|
||||
FROM pg_catalog.pg_roles AS role
|
||||
WHERE role.rolname = current_user
|
||||
`;
|
||||
const session = sessions[0];
|
||||
assertCustomerPortalDatabaseSession(session, binding.expectedDatabaseName);
|
||||
|
||||
const operator = await db.adminUser.findUnique({
|
||||
where: { id: binding.operatorUserId },
|
||||
select: { id: true, status: true },
|
||||
});
|
||||
assertCustomerPortalOperatorIdentity(operator, binding.operatorUserId);
|
||||
const platformAuditHead = await db.auditChainHead.findUnique({ where: { chainKey: auditChainKey(null) } });
|
||||
assertCustomerPortalAuditAnchor(platformAuditHead, binding.auditChainSecret);
|
||||
return callback(db);
|
||||
});
|
||||
} finally {
|
||||
await db.$disconnect();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
// @vitest-environment node
|
||||
import { readFileSync } from "node:fs";
|
||||
import { FormDefinitionSchema } from "../../packages/form-widget/src";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL,
|
||||
CUSTOMER_PORTAL_UAT_FORBIDDEN_PROJECT_ID,
|
||||
CUSTOMER_PORTAL_UAT_PROJECT_ID,
|
||||
CUSTOMER_PORTAL_UAT_STANDARD_ORIGIN,
|
||||
CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL,
|
||||
CUSTOMER_PORTAL_UAT_TENANT_SLUG,
|
||||
} from "./contracts";
|
||||
import { assessCustomerPortalFixture, customerPortalUatComplaintDefinition, type CustomerPortalFixtureSnapshot } from "./fixture";
|
||||
|
||||
const tenantId = "tenant-demo-pro";
|
||||
const expectedStageId = "stage-expected";
|
||||
const forbiddenStageId = "stage-forbidden";
|
||||
|
||||
function healthySnapshot(): CustomerPortalFixtureSnapshot {
|
||||
return {
|
||||
tenant: {
|
||||
id: tenantId,
|
||||
slug: CUSTOMER_PORTAL_UAT_TENANT_SLUG,
|
||||
active: true,
|
||||
subscription: { planCode: "business", status: "active", frozenAt: null },
|
||||
},
|
||||
projects: [
|
||||
{
|
||||
id: CUSTOMER_PORTAL_UAT_PROJECT_ID,
|
||||
projektname: "Wärmepumpe Mustermann",
|
||||
projekttyp: "waermepumpe",
|
||||
stageId: expectedStageId,
|
||||
archivedAt: null,
|
||||
stage: { name: "Montage", archivedAt: null },
|
||||
},
|
||||
{
|
||||
id: CUSTOMER_PORTAL_UAT_FORBIDDEN_PROJECT_ID,
|
||||
projektname: "Badsanierung Beispiel",
|
||||
projekttyp: "bad",
|
||||
stageId: forbiddenStageId,
|
||||
archivedAt: null,
|
||||
stage: { name: "Planung", archivedAt: null },
|
||||
},
|
||||
],
|
||||
portal: {
|
||||
id: "portal-1",
|
||||
subdomain: CUSTOMER_PORTAL_UAT_TENANT_SLUG,
|
||||
title: "Demo Pro CRM Kundenportal",
|
||||
isPublished: true,
|
||||
authRequireEmailVerification: false,
|
||||
authRequireOrganization: false,
|
||||
authRequireName: true,
|
||||
metadata: { uatFixture: "VA-P26" },
|
||||
},
|
||||
configuration: {
|
||||
lifecycleMode: "customer",
|
||||
enabledProjectTypes: ["waermepumpe", "bad"],
|
||||
uploadMaxFiles: 10,
|
||||
uploadMaxFileSizeBytes: 52_428_800,
|
||||
statusEmailsEnabled: true,
|
||||
welcomeMessage: "Willkommen im HiveGrid Test-Kundenportal.",
|
||||
supportEmail: "support@saas-ctrl.com",
|
||||
imprintUrl: "https://saas-ctrl.com/impressum",
|
||||
privacyUrl: "https://saas-ctrl.com/datenschutz",
|
||||
isDemoData: true,
|
||||
},
|
||||
users: [
|
||||
{
|
||||
id: "customer-1",
|
||||
emailNormalized: CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL,
|
||||
passwordHash: "hash",
|
||||
passwordMatches: true,
|
||||
firstName: "Karla",
|
||||
lastName: "Kundin",
|
||||
kind: "customer",
|
||||
status: "active",
|
||||
archivedAt: null,
|
||||
emailVerifiedAt: new Date("2026-07-17T00:00:00.000Z"),
|
||||
isDemoData: true,
|
||||
},
|
||||
{
|
||||
id: "subcontractor-1",
|
||||
emailNormalized: CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL,
|
||||
passwordHash: "hash",
|
||||
passwordMatches: true,
|
||||
firstName: "Sascha",
|
||||
lastName: "Subunternehmer",
|
||||
kind: "subcontractor",
|
||||
status: "active",
|
||||
archivedAt: null,
|
||||
emailVerifiedAt: new Date("2026-07-17T00:00:00.000Z"),
|
||||
isDemoData: true,
|
||||
},
|
||||
],
|
||||
accesses: [
|
||||
{
|
||||
id: "access-customer",
|
||||
portalUserId: "customer-1",
|
||||
projectId: CUSTOMER_PORTAL_UAT_PROJECT_ID,
|
||||
active: true,
|
||||
revokedAt: null,
|
||||
isDemoData: true,
|
||||
subcontractorAccess: null,
|
||||
},
|
||||
{
|
||||
id: "access-subcontractor",
|
||||
portalUserId: "subcontractor-1",
|
||||
projectId: CUSTOMER_PORTAL_UAT_PROJECT_ID,
|
||||
active: true,
|
||||
revokedAt: null,
|
||||
isDemoData: true,
|
||||
subcontractorAccess: { active: true, revokedAt: null, canUpload: true, isDemoData: true },
|
||||
},
|
||||
],
|
||||
stageVisibilities: [
|
||||
{ stageId: expectedStageId, visible: true, isDemoData: true },
|
||||
{ stageId: forbiddenStageId, visible: true, isDemoData: true },
|
||||
],
|
||||
form: {
|
||||
key: "customer-portal-uat-complaint-key",
|
||||
name: "Kundenportal UAT Reklamation",
|
||||
subtype: "portal_form",
|
||||
status: "published",
|
||||
publishedAt: new Date("2026-07-17T00:00:00.000Z"),
|
||||
isPublic: true,
|
||||
isEnabled: true,
|
||||
isDemoData: true,
|
||||
definition: customerPortalUatComplaintDefinition,
|
||||
targetType: "project",
|
||||
targetEntityId: CUSTOMER_PORTAL_UAT_PROJECT_ID,
|
||||
allowedOrigins: [CUSTOMER_PORTAL_UAT_STANDARD_ORIGIN],
|
||||
notifyEmails: [],
|
||||
config: { honeypotEnabled: false },
|
||||
},
|
||||
inbox: {
|
||||
portalId: "portal-1",
|
||||
portalUserId: "customer-1",
|
||||
projectId: CUSTOMER_PORTAL_UAT_PROJECT_ID,
|
||||
kind: "complaint",
|
||||
status: "open",
|
||||
priority: 100,
|
||||
sourceId: "customer-portal-uat",
|
||||
titleKey: "customerPortal.inbox.items.complaint",
|
||||
metadata: { fixture: "VA-P26" },
|
||||
bundledCount: 1,
|
||||
ownerUserId: null,
|
||||
resolvedAt: null,
|
||||
expiresAt: new Date("2026-07-24T00:00:00.000Z"),
|
||||
isDemoData: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("customer-portal UAT fixture contract", () => {
|
||||
it("locks UAT-owned rows and revalidates the fixture inside the write transaction", () => {
|
||||
const source = readFileSync(new URL("./fixture.ts", import.meta.url), "utf8");
|
||||
expect(source).toContain("lockCustomerPortalFixtureRows(transactionDb, command)");
|
||||
expect(source).toContain("const lockedSnapshot = await readCustomerPortalFixture(transactionDb, command)");
|
||||
expect(source.match(/FOR UPDATE/gu)?.length).toBeGreaterThanOrEqual(8);
|
||||
expect(source).toContain("key: UAT_FORM_KEY");
|
||||
});
|
||||
|
||||
it("accepts the complete deterministic fixture and emits safe E2E handoff data", () => {
|
||||
const assessment = assessCustomerPortalFixture(healthySnapshot(), tenantId, new Date("2026-07-17T10:00:00.000Z"));
|
||||
expect(assessment.action).toBe("noop");
|
||||
expect(assessment.e2e).toEqual({
|
||||
portalBaseUrl: CUSTOMER_PORTAL_UAT_STANDARD_ORIGIN,
|
||||
tenantSlug: CUSTOMER_PORTAL_UAT_TENANT_SLUG,
|
||||
customerEmail: CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL,
|
||||
subcontractorEmail: CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL,
|
||||
subcontractorExpectedProject: "Wärmepumpe Mustermann",
|
||||
subcontractorForbiddenProject: "Badsanierung Beispiel",
|
||||
});
|
||||
expect(JSON.stringify(assessment)).not.toContain("passwordHash");
|
||||
});
|
||||
|
||||
it("marks missing UAT-owned rows as reconcilable", () => {
|
||||
const snapshot = healthySnapshot();
|
||||
const assessment = assessCustomerPortalFixture({ ...snapshot, portal: null, configuration: null, users: [], accesses: [] }, tenantId);
|
||||
expect(assessment.action).toBe("reconcile");
|
||||
expect(assessment.blockingIssues).toEqual([]);
|
||||
});
|
||||
|
||||
it("blocks collisions with non-demo identities and access rows", () => {
|
||||
const snapshot = healthySnapshot();
|
||||
const users = snapshot.users.map((user) => (user.emailNormalized === CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL ? { ...user, isDemoData: false } : user));
|
||||
const accesses = [
|
||||
...snapshot.accesses,
|
||||
{
|
||||
id: "unsafe-extra",
|
||||
portalUserId: "subcontractor-1",
|
||||
projectId: CUSTOMER_PORTAL_UAT_FORBIDDEN_PROJECT_ID,
|
||||
active: true,
|
||||
revokedAt: null,
|
||||
isDemoData: false,
|
||||
subcontractorAccess: null,
|
||||
},
|
||||
];
|
||||
const assessment = assessCustomerPortalFixture({ ...snapshot, users, accesses }, tenantId);
|
||||
expect(assessment.action).toBe("blocked");
|
||||
expect(assessment.blockingIssues).toEqual(
|
||||
expect.arrayContaining(["customer UAT identity is not UAT-owned demo data", "subcontractor has a non-demo extra project access"])
|
||||
);
|
||||
});
|
||||
|
||||
it("does not take over an existing unmarked portal", () => {
|
||||
const snapshot = healthySnapshot();
|
||||
const assessment = assessCustomerPortalFixture({ ...snapshot, portal: { ...snapshot.portal!, metadata: null } }, tenantId);
|
||||
expect(assessment.action).toBe("blocked");
|
||||
expect(assessment.blockingIssues).toContain("existing portal is not marked as the VA-P26 UAT fixture");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["portal standard-host", (snapshot: CustomerPortalFixtureSnapshot) => ({ ...snapshot, portal: { ...snapshot.portal!, subdomain: "wrong" } })],
|
||||
["portal title", (snapshot: CustomerPortalFixtureSnapshot) => ({ ...snapshot, portal: { ...snapshot.portal!, title: "Wrong" } })],
|
||||
[
|
||||
"canonical user name",
|
||||
(snapshot: CustomerPortalFixtureSnapshot) => ({
|
||||
...snapshot,
|
||||
users: snapshot.users.map((user) => (user.emailNormalized === CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL ? { ...user, firstName: "Wrong" } : user)),
|
||||
}),
|
||||
],
|
||||
["form definition", (snapshot: CustomerPortalFixtureSnapshot) => ({ ...snapshot, form: { ...snapshot.form!, definition: { fields: [] } } })],
|
||||
["form key", (snapshot: CustomerPortalFixtureSnapshot) => ({ ...snapshot, form: { ...snapshot.form!, key: "wrong-key" } })],
|
||||
["form config", (snapshot: CustomerPortalFixtureSnapshot) => ({ ...snapshot, form: { ...snapshot.form!, config: { honeypotEnabled: true } } })],
|
||||
[
|
||||
"portal configuration",
|
||||
(snapshot: CustomerPortalFixtureSnapshot) => ({
|
||||
...snapshot,
|
||||
configuration: { ...snapshot.configuration!, lifecycleMode: "subcontractor", statusEmailsEnabled: false, supportEmail: "wrong@example.test" },
|
||||
}),
|
||||
],
|
||||
["form origin", (snapshot: CustomerPortalFixtureSnapshot) => ({ ...snapshot, form: { ...snapshot.form!, allowedOrigins: [CUSTOMER_PORTAL_UAT_STANDARD_ORIGIN, "https://extra.example"] } })],
|
||||
["inbox project", (snapshot: CustomerPortalFixtureSnapshot) => ({ ...snapshot, inbox: { ...snapshot.inbox!, projectId: CUSTOMER_PORTAL_UAT_FORBIDDEN_PROJECT_ID } })],
|
||||
["inbox customer", (snapshot: CustomerPortalFixtureSnapshot) => ({ ...snapshot, inbox: { ...snapshot.inbox!, portalUserId: "subcontractor-1" } })],
|
||||
["inbox kind", (snapshot: CustomerPortalFixtureSnapshot) => ({ ...snapshot, inbox: { ...snapshot.inbox!, kind: "upload" } })],
|
||||
["inbox source", (snapshot: CustomerPortalFixtureSnapshot) => ({ ...snapshot, inbox: { ...snapshot.inbox!, sourceId: "foreign" } })],
|
||||
["inbox title", (snapshot: CustomerPortalFixtureSnapshot) => ({ ...snapshot, inbox: { ...snapshot.inbox!, titleKey: "foreign.title" } })],
|
||||
])("reports %s drift instead of accepting fixture verify", (_label, drift) => {
|
||||
const assessment = assessCustomerPortalFixture(drift(healthySnapshot()), tenantId, new Date("2026-07-17T10:00:00.000Z"));
|
||||
expect(assessment.action).toBe("reconcile");
|
||||
});
|
||||
|
||||
it("does not reactivate non-UAT subcontractor scopes or stage visibility", () => {
|
||||
const snapshot = healthySnapshot();
|
||||
const accesses = snapshot.accesses.map((access) =>
|
||||
access.portalUserId === "subcontractor-1"
|
||||
? {
|
||||
...access,
|
||||
subcontractorAccess: { active: false, revokedAt: new Date("2026-07-16T00:00:00.000Z"), canUpload: false, isDemoData: false },
|
||||
}
|
||||
: access
|
||||
);
|
||||
const stageVisibilities = snapshot.stageVisibilities.map((visibility) =>
|
||||
visibility.stageId === forbiddenStageId ? { ...visibility, visible: false, isDemoData: false } : visibility
|
||||
);
|
||||
const assessment = assessCustomerPortalFixture({ ...snapshot, accesses, stageVisibilities }, tenantId);
|
||||
expect(assessment.action).toBe("blocked");
|
||||
expect(assessment.blockingIssues).toEqual(
|
||||
expect.arrayContaining(["subcontractor scope record is not UAT-owned demo data", `stage visibility ${forbiddenStageId} is not UAT-owned demo data`])
|
||||
);
|
||||
});
|
||||
|
||||
it("does not take over the deterministic project access when it is not demo-owned", () => {
|
||||
const snapshot = healthySnapshot();
|
||||
const accesses = snapshot.accesses.map((access) => (access.portalUserId === "customer-1" ? { ...access, isDemoData: false } : access));
|
||||
const assessment = assessCustomerPortalFixture({ ...snapshot, accesses }, tenantId);
|
||||
expect(assessment.action).toBe("blocked");
|
||||
expect(assessment.blockingIssues).toContain("customer project access is not UAT-owned demo data");
|
||||
});
|
||||
|
||||
it("keeps the fixture complaint form on the shared FormDefinition contract", () => {
|
||||
expect(FormDefinitionSchema.safeParse(customerPortalUatComplaintDefinition).success).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,951 @@
|
||||
import { hashCurrentPassword, verifySupportedPassword } from "../../apps/api/src/auth/password";
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import { publishAuditEventViaOutbox } from "@hivegrid/db/audit-events.server";
|
||||
import type { DbClient } from "@hivegrid/db/client.server";
|
||||
import type { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
|
||||
import {
|
||||
CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL,
|
||||
CUSTOMER_PORTAL_UAT_FORBIDDEN_PROJECT_ID,
|
||||
CUSTOMER_PORTAL_UAT_PROJECT_ID,
|
||||
CUSTOMER_PORTAL_UAT_STANDARD_ORIGIN,
|
||||
CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL,
|
||||
CUSTOMER_PORTAL_UAT_TENANT_SLUG,
|
||||
CustomerPortalUatError,
|
||||
type CustomerPortalFixtureCommand,
|
||||
} from "./contracts";
|
||||
|
||||
const UAT_FORM_SLUG = "customer-portal-uat-complaint";
|
||||
const UAT_FORM_KEY = "customer-portal-uat-complaint-key";
|
||||
const UAT_FORM_NAME = "Kundenportal UAT Reklamation";
|
||||
const UAT_INBOX_SOURCE_KEY = "customer-portal-uat:initial-service-item";
|
||||
const UAT_INBOX_SOURCE_ID = "customer-portal-uat";
|
||||
const UAT_INBOX_TITLE_KEY = "customerPortal.inbox.items.complaint";
|
||||
const UAT_LEGAL_ORIGIN = "https://saas-ctrl.com";
|
||||
const UAT_PORTAL_TITLE = "Demo Pro CRM Kundenportal";
|
||||
const UAT_VERIFIED_AT = new Date("2026-07-17T00:00:00.000Z");
|
||||
|
||||
export const customerPortalUatComplaintDefinition = Object.freeze({
|
||||
title: "Reklamation",
|
||||
submitLabel: "Reklamation senden",
|
||||
successMessage: "Deine Reklamation wurde gespeichert und das Projektteam informiert.",
|
||||
gdprConsentLabel: "Ich stimme der Verarbeitung meiner Angaben zur Bearbeitung der Reklamation zu.",
|
||||
fields: Object.freeze([
|
||||
Object.freeze({ key: "subject", type: "text", label: "Betreff", required: true, validationRules: { minLength: 3, maxLength: 200 } }),
|
||||
Object.freeze({ key: "details", type: "textarea", label: "Beschreibung", required: true, validationRules: { minLength: 3, maxLength: 5_000 } }),
|
||||
]),
|
||||
});
|
||||
|
||||
type FixtureProject = {
|
||||
readonly id: string;
|
||||
readonly projektname: string;
|
||||
readonly projekttyp: string | null;
|
||||
readonly stageId: string;
|
||||
readonly archivedAt: Date | null;
|
||||
readonly stage: { readonly name: string; readonly archivedAt: Date | null };
|
||||
};
|
||||
|
||||
type FixtureUser = {
|
||||
readonly id: string;
|
||||
readonly emailNormalized: string;
|
||||
readonly passwordHash: string | null;
|
||||
readonly passwordMatches: boolean;
|
||||
readonly firstName: string;
|
||||
readonly lastName: string;
|
||||
readonly kind: string;
|
||||
readonly status: string;
|
||||
readonly archivedAt: Date | null;
|
||||
readonly emailVerifiedAt: Date | null;
|
||||
readonly isDemoData: boolean;
|
||||
};
|
||||
|
||||
type FixtureAccess = {
|
||||
readonly id: string;
|
||||
readonly portalUserId: string;
|
||||
readonly projectId: string;
|
||||
readonly active: boolean;
|
||||
readonly revokedAt: Date | null;
|
||||
readonly isDemoData: boolean;
|
||||
readonly subcontractorAccess: {
|
||||
readonly active: boolean;
|
||||
readonly revokedAt: Date | null;
|
||||
readonly canUpload: boolean;
|
||||
readonly isDemoData: boolean;
|
||||
} | null;
|
||||
};
|
||||
|
||||
export type CustomerPortalFixtureSnapshot = {
|
||||
readonly tenant: {
|
||||
readonly id: string;
|
||||
readonly slug: string;
|
||||
readonly active: boolean;
|
||||
readonly subscription: { readonly planCode: string | null; readonly status: string; readonly frozenAt: Date | null } | null;
|
||||
} | null;
|
||||
readonly projects: readonly FixtureProject[];
|
||||
readonly portal: {
|
||||
readonly id: string;
|
||||
readonly subdomain: string;
|
||||
readonly title: string;
|
||||
readonly isPublished: boolean;
|
||||
readonly authRequireEmailVerification: boolean;
|
||||
readonly authRequireOrganization: boolean;
|
||||
readonly authRequireName: boolean;
|
||||
readonly metadata: unknown;
|
||||
} | null;
|
||||
readonly configuration: {
|
||||
readonly lifecycleMode: string;
|
||||
readonly enabledProjectTypes: readonly string[];
|
||||
readonly uploadMaxFiles: number;
|
||||
readonly uploadMaxFileSizeBytes: number;
|
||||
readonly statusEmailsEnabled: boolean;
|
||||
readonly welcomeMessage: string | null;
|
||||
readonly supportEmail: string | null;
|
||||
readonly imprintUrl: string | null;
|
||||
readonly privacyUrl: string | null;
|
||||
readonly isDemoData: boolean;
|
||||
} | null;
|
||||
readonly users: readonly FixtureUser[];
|
||||
readonly accesses: readonly FixtureAccess[];
|
||||
readonly stageVisibilities: readonly {
|
||||
readonly stageId: string;
|
||||
readonly visible: boolean;
|
||||
readonly isDemoData: boolean;
|
||||
}[];
|
||||
readonly form: {
|
||||
readonly key: string;
|
||||
readonly name: string;
|
||||
readonly subtype: string;
|
||||
readonly status: string;
|
||||
readonly publishedAt: Date | null;
|
||||
readonly isPublic: boolean;
|
||||
readonly isEnabled: boolean;
|
||||
readonly isDemoData: boolean;
|
||||
readonly definition: unknown;
|
||||
readonly targetType: string | null;
|
||||
readonly targetEntityId: string | null;
|
||||
readonly allowedOrigins: readonly string[];
|
||||
readonly notifyEmails: readonly string[];
|
||||
readonly config: unknown;
|
||||
} | null;
|
||||
readonly inbox: {
|
||||
readonly portalId: string;
|
||||
readonly portalUserId: string | null;
|
||||
readonly projectId: string | null;
|
||||
readonly kind: string;
|
||||
readonly status: string;
|
||||
readonly priority: number;
|
||||
readonly sourceId: string | null;
|
||||
readonly titleKey: string;
|
||||
readonly metadata: unknown;
|
||||
readonly bundledCount: number;
|
||||
readonly ownerUserId: string | null;
|
||||
readonly resolvedAt: Date | null;
|
||||
readonly expiresAt: Date;
|
||||
readonly isDemoData: boolean;
|
||||
} | null;
|
||||
};
|
||||
|
||||
export type CustomerPortalFixtureAssessment = {
|
||||
readonly action: "noop" | "reconcile" | "blocked";
|
||||
readonly reconcileIssues: readonly string[];
|
||||
readonly blockingIssues: readonly string[];
|
||||
readonly e2e: {
|
||||
readonly portalBaseUrl: typeof CUSTOMER_PORTAL_UAT_STANDARD_ORIGIN;
|
||||
readonly tenantSlug: typeof CUSTOMER_PORTAL_UAT_TENANT_SLUG;
|
||||
readonly customerEmail: typeof CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL;
|
||||
readonly subcontractorEmail: typeof CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL;
|
||||
readonly subcontractorExpectedProject: string | null;
|
||||
readonly subcontractorForbiddenProject: string | null;
|
||||
};
|
||||
};
|
||||
|
||||
function findUser(snapshot: CustomerPortalFixtureSnapshot, email: string): FixtureUser | undefined {
|
||||
return snapshot.users.find((user) => user.emailNormalized === email);
|
||||
}
|
||||
|
||||
function projectById(snapshot: CustomerPortalFixtureSnapshot, id: string): FixtureProject | undefined {
|
||||
return snapshot.projects.find((project) => project.id === id);
|
||||
}
|
||||
|
||||
function isUatOwnedPortal(metadata: unknown): boolean {
|
||||
return typeof metadata === "object" && metadata !== null && "uatFixture" in metadata && metadata.uatFixture === "VA-P26";
|
||||
}
|
||||
|
||||
export function assessCustomerPortalFixture(
|
||||
snapshot: CustomerPortalFixtureSnapshot,
|
||||
expectedTenantId: string,
|
||||
now: Date = new Date()
|
||||
): CustomerPortalFixtureAssessment {
|
||||
const reconcileIssues: string[] = [];
|
||||
const blockingIssues: string[] = [];
|
||||
const expectedProject = projectById(snapshot, CUSTOMER_PORTAL_UAT_PROJECT_ID);
|
||||
const forbiddenProject = projectById(snapshot, CUSTOMER_PORTAL_UAT_FORBIDDEN_PROJECT_ID);
|
||||
|
||||
if (!snapshot.tenant) blockingIssues.push("target tenant is not visible under the operator RLS context");
|
||||
else {
|
||||
if (snapshot.tenant.id !== expectedTenantId || snapshot.tenant.slug !== CUSTOMER_PORTAL_UAT_TENANT_SLUG) {
|
||||
blockingIssues.push("target tenant does not match the explicit demo-pro-crm binding");
|
||||
}
|
||||
if (!snapshot.tenant.active) blockingIssues.push("target tenant is inactive");
|
||||
if (
|
||||
snapshot.tenant.subscription?.planCode !== "business" ||
|
||||
snapshot.tenant.subscription.status.toLowerCase() !== "active" ||
|
||||
snapshot.tenant.subscription.frozenAt !== null
|
||||
) {
|
||||
blockingIssues.push("target tenant must have an active, non-frozen business subscription");
|
||||
}
|
||||
}
|
||||
|
||||
for (const [label, project] of [
|
||||
["expected", expectedProject],
|
||||
["forbidden", forbiddenProject],
|
||||
] as const) {
|
||||
if (!project || project.archivedAt || project.stage.archivedAt || !project.projekttyp) {
|
||||
blockingIssues.push(`${label} deterministic UAT project is missing, archived, or incomplete`);
|
||||
}
|
||||
}
|
||||
if (expectedProject && forbiddenProject && expectedProject.projektname === forbiddenProject.projektname) {
|
||||
blockingIssues.push("expected and forbidden UAT projects must have distinct names");
|
||||
}
|
||||
|
||||
if (!snapshot.portal) reconcileIssues.push("published portal missing");
|
||||
else {
|
||||
if (!isUatOwnedPortal(snapshot.portal.metadata)) blockingIssues.push("existing portal is not marked as the VA-P26 UAT fixture");
|
||||
if (
|
||||
snapshot.portal.subdomain !== CUSTOMER_PORTAL_UAT_TENANT_SLUG ||
|
||||
snapshot.portal.title !== UAT_PORTAL_TITLE ||
|
||||
!snapshot.portal.isPublished ||
|
||||
snapshot.portal.authRequireEmailVerification ||
|
||||
snapshot.portal.authRequireOrganization ||
|
||||
!snapshot.portal.authRequireName
|
||||
) {
|
||||
reconcileIssues.push("portal publication, standard-host, title, or login contract differs");
|
||||
}
|
||||
}
|
||||
|
||||
const requiredProjectTypes = [...new Set([expectedProject?.projekttyp, forbiddenProject?.projekttyp].filter((value): value is string => Boolean(value)))];
|
||||
if (!snapshot.configuration) reconcileIssues.push("portal configuration missing");
|
||||
else {
|
||||
if (!snapshot.configuration.isDemoData) blockingIssues.push("existing portal configuration is not UAT-owned demo data");
|
||||
if (
|
||||
snapshot.configuration.lifecycleMode !== "customer" ||
|
||||
!isDeepStrictEqual([...snapshot.configuration.enabledProjectTypes].sort(), [...requiredProjectTypes].sort()) ||
|
||||
!snapshot.configuration.statusEmailsEnabled ||
|
||||
snapshot.configuration.welcomeMessage !== "Willkommen im HiveGrid Test-Kundenportal." ||
|
||||
snapshot.configuration.supportEmail !== "support@saas-ctrl.com"
|
||||
) {
|
||||
reconcileIssues.push("portal configuration does not enable the deterministic project types");
|
||||
}
|
||||
if (snapshot.configuration.uploadMaxFiles < 2 || snapshot.configuration.uploadMaxFileSizeBytes < 1_024) {
|
||||
reconcileIssues.push("portal upload configuration is insufficient for the P26b journey");
|
||||
}
|
||||
if (!snapshot.configuration.imprintUrl || !snapshot.configuration.privacyUrl) {
|
||||
reconcileIssues.push("portal legal links are incomplete");
|
||||
}
|
||||
}
|
||||
|
||||
const expectedUsers = [
|
||||
{ email: CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL, kind: "customer" },
|
||||
{ email: CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL, kind: "subcontractor" },
|
||||
] as const;
|
||||
for (const expected of expectedUsers) {
|
||||
const user = findUser(snapshot, expected.email);
|
||||
if (!user) {
|
||||
reconcileIssues.push(`${expected.kind} UAT identity missing`);
|
||||
continue;
|
||||
}
|
||||
if (!user.isDemoData) blockingIssues.push(`${expected.kind} UAT identity is not UAT-owned demo data`);
|
||||
const canonicalName = expected.kind === "customer" ? ["Karla", "Kundin"] : ["Sascha", "Subunternehmer"];
|
||||
if (
|
||||
user.firstName !== canonicalName[0] ||
|
||||
user.lastName !== canonicalName[1] ||
|
||||
user.kind !== expected.kind ||
|
||||
user.status !== "active" ||
|
||||
user.archivedAt !== null ||
|
||||
user.emailVerifiedAt === null ||
|
||||
!user.passwordMatches
|
||||
) {
|
||||
reconcileIssues.push(`${expected.kind} UAT identity differs from the login contract`);
|
||||
}
|
||||
}
|
||||
|
||||
if (snapshot.portal && expectedProject) {
|
||||
const customer = findUser(snapshot, CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL);
|
||||
const subcontractor = findUser(snapshot, CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL);
|
||||
for (const [kind, user] of [
|
||||
["customer", customer],
|
||||
["subcontractor", subcontractor],
|
||||
] as const) {
|
||||
if (!user) continue;
|
||||
const activeAccesses = snapshot.accesses.filter((access) => access.portalUserId === user.id && access.active && !access.revokedAt);
|
||||
const expectedAccess = activeAccesses.find((access) => access.projectId === expectedProject.id);
|
||||
if (!expectedAccess) reconcileIssues.push(`${kind} project access missing`);
|
||||
else if (!expectedAccess.isDemoData) blockingIssues.push(`${kind} project access is not UAT-owned demo data`);
|
||||
const extra = activeAccesses.filter((access) => access.projectId !== expectedProject.id);
|
||||
if (extra.some((access) => !access.isDemoData)) blockingIssues.push(`${kind} has a non-demo extra project access`);
|
||||
else if (extra.length > 0) reconcileIssues.push(`${kind} has extra active demo project access`);
|
||||
if (kind === "subcontractor" && expectedAccess) {
|
||||
const sub = expectedAccess.subcontractorAccess;
|
||||
if (sub && !sub.isDemoData) blockingIssues.push("subcontractor scope record is not UAT-owned demo data");
|
||||
else if (!sub || !sub.active || sub.revokedAt || !sub.canUpload) reconcileIssues.push("subcontractor scope record is missing or inactive");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const requiredStageIds = [expectedProject?.stageId, forbiddenProject?.stageId].filter((value): value is string => Boolean(value));
|
||||
for (const stageId of requiredStageIds) {
|
||||
const visibility = snapshot.stageVisibilities.find((candidate) => candidate.stageId === stageId);
|
||||
if (visibility && !visibility.isDemoData) blockingIssues.push(`stage visibility ${stageId} is not UAT-owned demo data`);
|
||||
else if (!visibility?.visible) reconcileIssues.push(`stage visibility ${stageId} is incomplete`);
|
||||
}
|
||||
|
||||
if (!snapshot.form) reconcileIssues.push("project-specific portal complaint form missing");
|
||||
else {
|
||||
if (!snapshot.form.isDemoData) blockingIssues.push("existing UAT complaint form is not UAT-owned demo data");
|
||||
if (
|
||||
snapshot.form.subtype !== "portal_form" ||
|
||||
snapshot.form.key !== UAT_FORM_KEY ||
|
||||
snapshot.form.name !== UAT_FORM_NAME ||
|
||||
snapshot.form.status !== "published" ||
|
||||
snapshot.form.publishedAt === null ||
|
||||
!snapshot.form.isPublic ||
|
||||
!snapshot.form.isEnabled ||
|
||||
!isDeepStrictEqual(snapshot.form.definition, customerPortalUatComplaintDefinition) ||
|
||||
snapshot.form.targetType !== "project" ||
|
||||
snapshot.form.targetEntityId !== CUSTOMER_PORTAL_UAT_PROJECT_ID ||
|
||||
!isDeepStrictEqual(snapshot.form.allowedOrigins, [CUSTOMER_PORTAL_UAT_STANDARD_ORIGIN]) ||
|
||||
!isDeepStrictEqual(snapshot.form.notifyEmails, []) ||
|
||||
!isDeepStrictEqual(snapshot.form.config, { honeypotEnabled: false })
|
||||
) {
|
||||
reconcileIssues.push("portal complaint form differs from the P26b contract");
|
||||
}
|
||||
}
|
||||
|
||||
if (!snapshot.inbox) reconcileIssues.push("open service-inbox UAT item missing");
|
||||
else {
|
||||
if (!snapshot.inbox.isDemoData) blockingIssues.push("existing UAT inbox item is not UAT-owned demo data");
|
||||
const customer = findUser(snapshot, CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL);
|
||||
if (
|
||||
snapshot.inbox.portalId !== snapshot.portal?.id ||
|
||||
snapshot.inbox.portalUserId !== customer?.id ||
|
||||
snapshot.inbox.projectId !== expectedProject?.id ||
|
||||
snapshot.inbox.kind !== "complaint" ||
|
||||
snapshot.inbox.status !== "open" ||
|
||||
snapshot.inbox.priority !== 100 ||
|
||||
snapshot.inbox.sourceId !== UAT_INBOX_SOURCE_ID ||
|
||||
snapshot.inbox.titleKey !== UAT_INBOX_TITLE_KEY ||
|
||||
!isDeepStrictEqual(snapshot.inbox.metadata, { fixture: "VA-P26" }) ||
|
||||
snapshot.inbox.bundledCount !== 1 ||
|
||||
snapshot.inbox.ownerUserId !== null ||
|
||||
snapshot.inbox.resolvedAt !== null ||
|
||||
snapshot.inbox.expiresAt.getTime() <= now.getTime()
|
||||
) {
|
||||
reconcileIssues.push("service-inbox UAT item differs from the canonical project, customer, source, title, or lifecycle contract");
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
action: blockingIssues.length > 0 ? "blocked" : reconcileIssues.length > 0 ? "reconcile" : "noop",
|
||||
reconcileIssues,
|
||||
blockingIssues,
|
||||
e2e: {
|
||||
portalBaseUrl: CUSTOMER_PORTAL_UAT_STANDARD_ORIGIN,
|
||||
tenantSlug: CUSTOMER_PORTAL_UAT_TENANT_SLUG,
|
||||
customerEmail: CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL,
|
||||
subcontractorEmail: CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL,
|
||||
subcontractorExpectedProject: expectedProject?.projektname ?? null,
|
||||
subcontractorForbiddenProject: forbiddenProject?.projektname ?? null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function readCustomerPortalFixture(db: DbClient, command: CustomerPortalFixtureCommand): Promise<CustomerPortalFixtureSnapshot> {
|
||||
const tenant = await db.tenant.findFirst({
|
||||
where: { id: command.expectedTenantId, slug: CUSTOMER_PORTAL_UAT_TENANT_SLUG },
|
||||
select: { id: true, slug: true, active: true, subscription: { select: { planCode: true, status: true, frozenAt: true } } },
|
||||
});
|
||||
const projects = await db.projekt.findMany({
|
||||
where: { tenantId: command.expectedTenantId, id: { in: [CUSTOMER_PORTAL_UAT_PROJECT_ID, CUSTOMER_PORTAL_UAT_FORBIDDEN_PROJECT_ID] } },
|
||||
select: { id: true, projektname: true, projekttyp: true, stageId: true, archivedAt: true, stage: { select: { name: true, archivedAt: true } } },
|
||||
});
|
||||
const portal = await db.portal.findUnique({
|
||||
where: { tenantId: command.expectedTenantId },
|
||||
select: {
|
||||
id: true,
|
||||
subdomain: true,
|
||||
title: true,
|
||||
isPublished: true,
|
||||
authRequireEmailVerification: true,
|
||||
authRequireOrganization: true,
|
||||
authRequireName: true,
|
||||
metadata: true,
|
||||
},
|
||||
});
|
||||
if (!portal) {
|
||||
const [form, inbox] = await Promise.all([
|
||||
db.form.findUnique({ where: { tenantId_slug: { tenantId: command.expectedTenantId, slug: UAT_FORM_SLUG } }, select: fixtureFormSelect }),
|
||||
db.portalServiceInboxItem.findUnique({
|
||||
where: { tenantId_sourceKey: { tenantId: command.expectedTenantId, sourceKey: UAT_INBOX_SOURCE_KEY } },
|
||||
select: fixtureInboxSelect,
|
||||
}),
|
||||
]);
|
||||
return { tenant, projects, portal: null, configuration: null, users: [], accesses: [], stageVisibilities: [], form, inbox };
|
||||
}
|
||||
|
||||
const [configuration, rawUsers, visibleStages, form, inbox] = await Promise.all([
|
||||
db.portalConfiguration.findUnique({
|
||||
where: { portalId_tenantId: { portalId: portal.id, tenantId: command.expectedTenantId } },
|
||||
select: {
|
||||
lifecycleMode: true,
|
||||
enabledProjectTypes: true,
|
||||
uploadMaxFiles: true,
|
||||
uploadMaxFileSizeBytes: true,
|
||||
statusEmailsEnabled: true,
|
||||
welcomeMessage: true,
|
||||
supportEmail: true,
|
||||
imprintUrl: true,
|
||||
privacyUrl: true,
|
||||
isDemoData: true,
|
||||
},
|
||||
}),
|
||||
db.portalUser.findMany({
|
||||
where: {
|
||||
tenantId: command.expectedTenantId,
|
||||
portalId: portal.id,
|
||||
emailNormalized: { in: [CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL, CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL] },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
emailNormalized: true,
|
||||
passwordHash: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
kind: true,
|
||||
status: true,
|
||||
archivedAt: true,
|
||||
emailVerifiedAt: true,
|
||||
isDemoData: true,
|
||||
},
|
||||
}),
|
||||
db.portalStageVisibility.findMany({
|
||||
where: {
|
||||
tenantId: command.expectedTenantId,
|
||||
portalId: portal.id,
|
||||
stageId: { in: projects.map((project) => project.stageId) },
|
||||
},
|
||||
select: { stageId: true, visible: true, isDemoData: true },
|
||||
}),
|
||||
db.form.findUnique({ where: { tenantId_slug: { tenantId: command.expectedTenantId, slug: UAT_FORM_SLUG } }, select: fixtureFormSelect }),
|
||||
db.portalServiceInboxItem.findUnique({
|
||||
where: { tenantId_sourceKey: { tenantId: command.expectedTenantId, sourceKey: UAT_INBOX_SOURCE_KEY } },
|
||||
select: fixtureInboxSelect,
|
||||
}),
|
||||
]);
|
||||
const users: FixtureUser[] = await Promise.all(
|
||||
rawUsers.map(async (user) => ({
|
||||
...user,
|
||||
kind: String(user.kind),
|
||||
status: String(user.status),
|
||||
passwordMatches: user.passwordHash ? await verifySupportedPassword(command.password, user.passwordHash) : false,
|
||||
}))
|
||||
);
|
||||
const accesses =
|
||||
users.length === 0
|
||||
? []
|
||||
: await db.portalProjectAccess.findMany({
|
||||
where: { tenantId: command.expectedTenantId, portalId: portal.id, portalUserId: { in: users.map((user) => user.id) } },
|
||||
select: {
|
||||
id: true,
|
||||
portalUserId: true,
|
||||
projectId: true,
|
||||
active: true,
|
||||
revokedAt: true,
|
||||
isDemoData: true,
|
||||
subcontractorAccess: { select: { active: true, revokedAt: true, canUpload: true, isDemoData: true } },
|
||||
},
|
||||
});
|
||||
return {
|
||||
tenant,
|
||||
projects,
|
||||
portal,
|
||||
configuration,
|
||||
users,
|
||||
accesses,
|
||||
stageVisibilities: visibleStages,
|
||||
form,
|
||||
inbox,
|
||||
};
|
||||
}
|
||||
|
||||
const fixtureFormSelect = {
|
||||
key: true,
|
||||
name: true,
|
||||
subtype: true,
|
||||
status: true,
|
||||
publishedAt: true,
|
||||
isPublic: true,
|
||||
isEnabled: true,
|
||||
isDemoData: true,
|
||||
definition: true,
|
||||
targetType: true,
|
||||
targetEntityId: true,
|
||||
allowedOrigins: true,
|
||||
notifyEmails: true,
|
||||
config: true,
|
||||
} as const;
|
||||
|
||||
const fixtureInboxSelect = {
|
||||
portalId: true,
|
||||
portalUserId: true,
|
||||
projectId: true,
|
||||
kind: true,
|
||||
status: true,
|
||||
priority: true,
|
||||
sourceId: true,
|
||||
titleKey: true,
|
||||
metadata: true,
|
||||
bundledCount: true,
|
||||
ownerUserId: true,
|
||||
resolvedAt: true,
|
||||
expiresAt: true,
|
||||
isDemoData: true,
|
||||
} as const;
|
||||
|
||||
async function passwordHashForUser(snapshot: CustomerPortalFixtureSnapshot, email: string, password: string): Promise<string> {
|
||||
const existing = findUser(snapshot, email);
|
||||
return existing?.passwordMatches && existing.passwordHash ? existing.passwordHash : hashCurrentPassword(password);
|
||||
}
|
||||
|
||||
async function lockCustomerPortalFixtureRows(db: DbClient, command: CustomerPortalFixtureCommand): Promise<void> {
|
||||
const tenantLocks = await db.$queryRaw<Array<{ id: string }>>`
|
||||
SELECT tenant."id"
|
||||
FROM "Tenant" AS tenant
|
||||
WHERE tenant."id" = ${command.expectedTenantId}
|
||||
AND tenant."slug" = ${CUSTOMER_PORTAL_UAT_TENANT_SLUG}
|
||||
FOR UPDATE
|
||||
`;
|
||||
if (tenantLocks.length !== 1) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: target tenant changed after guarded preflight");
|
||||
}
|
||||
await db.$queryRaw`
|
||||
SELECT project."id"
|
||||
FROM "Projekt" AS project
|
||||
WHERE project."tenantId" = ${command.expectedTenantId}
|
||||
AND (project."id" = ${CUSTOMER_PORTAL_UAT_PROJECT_ID} OR project."id" = ${CUSTOMER_PORTAL_UAT_FORBIDDEN_PROJECT_ID})
|
||||
FOR UPDATE
|
||||
`;
|
||||
await db.$queryRaw`
|
||||
SELECT portal."id"
|
||||
FROM "Portal" AS portal
|
||||
WHERE portal."tenantId" = ${command.expectedTenantId}
|
||||
FOR UPDATE
|
||||
`;
|
||||
await db.$queryRaw`
|
||||
SELECT configuration."id"
|
||||
FROM "PortalConfiguration" AS configuration
|
||||
WHERE configuration."tenantId" = ${command.expectedTenantId}
|
||||
FOR UPDATE
|
||||
`;
|
||||
await db.$queryRaw`
|
||||
SELECT portal_user."id"
|
||||
FROM "PortalUser" AS portal_user
|
||||
WHERE portal_user."tenantId" = ${command.expectedTenantId}
|
||||
AND (
|
||||
portal_user."id" IN ('customer-portal-uat-customer', 'customer-portal-uat-subcontractor')
|
||||
OR portal_user."emailNormalized" = ${CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL}
|
||||
OR portal_user."emailNormalized" = ${CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL}
|
||||
)
|
||||
FOR UPDATE
|
||||
`;
|
||||
await db.$queryRaw`
|
||||
SELECT project_access."id"
|
||||
FROM "PortalProjectAccess" AS project_access
|
||||
WHERE project_access."tenantId" = ${command.expectedTenantId}
|
||||
AND project_access."portalUserId" IN (
|
||||
SELECT portal_user."id"
|
||||
FROM "PortalUser" AS portal_user
|
||||
WHERE portal_user."tenantId" = ${command.expectedTenantId}
|
||||
AND (
|
||||
portal_user."id" IN ('customer-portal-uat-customer', 'customer-portal-uat-subcontractor')
|
||||
OR portal_user."emailNormalized" = ${CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL}
|
||||
OR portal_user."emailNormalized" = ${CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL}
|
||||
)
|
||||
)
|
||||
FOR UPDATE
|
||||
`;
|
||||
await db.$queryRaw`
|
||||
SELECT subcontractor_access."id"
|
||||
FROM "PortalSubcontractorAccess" AS subcontractor_access
|
||||
WHERE subcontractor_access."tenantId" = ${command.expectedTenantId}
|
||||
AND subcontractor_access."portalUserId" IN (
|
||||
SELECT portal_user."id"
|
||||
FROM "PortalUser" AS portal_user
|
||||
WHERE portal_user."tenantId" = ${command.expectedTenantId}
|
||||
AND (
|
||||
portal_user."id" IN ('customer-portal-uat-customer', 'customer-portal-uat-subcontractor')
|
||||
OR portal_user."emailNormalized" = ${CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL}
|
||||
OR portal_user."emailNormalized" = ${CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL}
|
||||
)
|
||||
)
|
||||
FOR UPDATE
|
||||
`;
|
||||
await db.$queryRaw`
|
||||
SELECT visibility."id"
|
||||
FROM "PortalStageVisibility" AS visibility
|
||||
WHERE visibility."tenantId" = ${command.expectedTenantId}
|
||||
AND visibility."stageId" IN (
|
||||
SELECT project."stageId"
|
||||
FROM "Projekt" AS project
|
||||
WHERE project."tenantId" = ${command.expectedTenantId}
|
||||
AND (project."id" = ${CUSTOMER_PORTAL_UAT_PROJECT_ID} OR project."id" = ${CUSTOMER_PORTAL_UAT_FORBIDDEN_PROJECT_ID})
|
||||
)
|
||||
FOR UPDATE
|
||||
`;
|
||||
await db.$queryRaw`
|
||||
SELECT form."id"
|
||||
FROM "Form" AS form
|
||||
WHERE form."tenantId" = ${command.expectedTenantId}
|
||||
AND (form."id" = 'customer-portal-uat-complaint-form' OR form."slug" = ${UAT_FORM_SLUG} OR form."key" = ${UAT_FORM_KEY})
|
||||
FOR UPDATE
|
||||
`;
|
||||
await db.$queryRaw`
|
||||
SELECT inbox."id"
|
||||
FROM "PortalServiceInboxItem" AS inbox
|
||||
WHERE inbox."tenantId" = ${command.expectedTenantId}
|
||||
AND (inbox."id" = 'customer-portal-uat-inbox-item' OR inbox."sourceKey" = ${UAT_INBOX_SOURCE_KEY})
|
||||
FOR UPDATE
|
||||
`;
|
||||
}
|
||||
|
||||
export async function applyCustomerPortalFixture(db: DbClient, command: CustomerPortalFixtureCommand, snapshot: CustomerPortalFixtureSnapshot): Promise<void> {
|
||||
const assessment = assessCustomerPortalFixture(snapshot, command.expectedTenantId);
|
||||
if (assessment.action === "blocked") {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: fixture apply is blocked by non-UAT or mismatched staging state");
|
||||
}
|
||||
if (assessment.action === "noop") return;
|
||||
|
||||
const now = new Date();
|
||||
const inboxExpiry = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1_000);
|
||||
|
||||
await db.$transaction(async (tx) => {
|
||||
const transactionDb = tx as unknown as DbClient;
|
||||
await lockCustomerPortalFixtureRows(transactionDb, command);
|
||||
const lockedSnapshot = await readCustomerPortalFixture(transactionDb, command);
|
||||
const lockedAssessment = assessCustomerPortalFixture(lockedSnapshot, command.expectedTenantId);
|
||||
if (lockedAssessment.action === "blocked") {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: fixture ownership changed after guarded preflight");
|
||||
}
|
||||
if (lockedAssessment.action === "noop") return;
|
||||
const expectedProject = projectById(lockedSnapshot, CUSTOMER_PORTAL_UAT_PROJECT_ID);
|
||||
const forbiddenProject = projectById(lockedSnapshot, CUSTOMER_PORTAL_UAT_FORBIDDEN_PROJECT_ID);
|
||||
if (!expectedProject?.projekttyp || !forbiddenProject?.projekttyp) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: deterministic projects changed after guarded preflight");
|
||||
}
|
||||
const [customerPasswordHash, subcontractorPasswordHash] = await Promise.all([
|
||||
passwordHashForUser(lockedSnapshot, CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL, command.password),
|
||||
passwordHashForUser(lockedSnapshot, CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL, command.password),
|
||||
]);
|
||||
const projectTypes = [...new Set([expectedProject.projekttyp, forbiddenProject.projekttyp])];
|
||||
const portal = await tx.portal.upsert({
|
||||
where: { tenantId: command.expectedTenantId },
|
||||
create: {
|
||||
id: "customer-portal-uat-demo-pro-crm",
|
||||
tenantId: command.expectedTenantId,
|
||||
subdomain: CUSTOMER_PORTAL_UAT_TENANT_SLUG,
|
||||
title: UAT_PORTAL_TITLE,
|
||||
isPublished: true,
|
||||
authRequireEmailVerification: false,
|
||||
authRequireOrganization: false,
|
||||
authRequireName: true,
|
||||
metadata: { uatFixture: "VA-P26" },
|
||||
},
|
||||
update: {
|
||||
subdomain: CUSTOMER_PORTAL_UAT_TENANT_SLUG,
|
||||
title: UAT_PORTAL_TITLE,
|
||||
isPublished: true,
|
||||
authRequireEmailVerification: false,
|
||||
authRequireOrganization: false,
|
||||
authRequireName: true,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
await tx.portalConfiguration.upsert({
|
||||
where: { portalId_tenantId: { portalId: portal.id, tenantId: command.expectedTenantId } },
|
||||
create: {
|
||||
id: "customer-portal-uat-configuration",
|
||||
tenantId: command.expectedTenantId,
|
||||
portalId: portal.id,
|
||||
lifecycleMode: "customer",
|
||||
enabledProjectTypes: projectTypes,
|
||||
uploadMaxFiles: 10,
|
||||
uploadMaxFileSizeBytes: 52_428_800,
|
||||
statusEmailsEnabled: true,
|
||||
welcomeMessage: "Willkommen im HiveGrid Test-Kundenportal.",
|
||||
supportEmail: "support@saas-ctrl.com",
|
||||
imprintUrl: `${UAT_LEGAL_ORIGIN}/impressum`,
|
||||
privacyUrl: `${UAT_LEGAL_ORIGIN}/datenschutz`,
|
||||
isDemoData: true,
|
||||
},
|
||||
update: {
|
||||
lifecycleMode: "customer",
|
||||
enabledProjectTypes: projectTypes,
|
||||
uploadMaxFiles: 10,
|
||||
uploadMaxFileSizeBytes: 52_428_800,
|
||||
statusEmailsEnabled: true,
|
||||
welcomeMessage: "Willkommen im HiveGrid Test-Kundenportal.",
|
||||
supportEmail: "support@saas-ctrl.com",
|
||||
imprintUrl: `${UAT_LEGAL_ORIGIN}/impressum`,
|
||||
privacyUrl: `${UAT_LEGAL_ORIGIN}/datenschutz`,
|
||||
isDemoData: true,
|
||||
},
|
||||
});
|
||||
|
||||
const customer = await tx.portalUser.upsert({
|
||||
where: { portalId_emailNormalized: { portalId: portal.id, emailNormalized: CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL } },
|
||||
create: {
|
||||
id: "customer-portal-uat-customer",
|
||||
tenantId: command.expectedTenantId,
|
||||
portalId: portal.id,
|
||||
email: CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL,
|
||||
emailNormalized: CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL,
|
||||
passwordHash: customerPasswordHash,
|
||||
firstName: "Karla",
|
||||
lastName: "Kundin",
|
||||
kind: "customer",
|
||||
status: "active",
|
||||
locale: "de",
|
||||
emailVerifiedAt: UAT_VERIFIED_AT,
|
||||
isDemoData: true,
|
||||
},
|
||||
update: {
|
||||
email: CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL,
|
||||
passwordHash: customerPasswordHash,
|
||||
firstName: "Karla",
|
||||
lastName: "Kundin",
|
||||
kind: "customer",
|
||||
status: "active",
|
||||
locale: "de",
|
||||
emailVerifiedAt: UAT_VERIFIED_AT,
|
||||
archivedAt: null,
|
||||
isDemoData: true,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
const subcontractor = await tx.portalUser.upsert({
|
||||
where: { portalId_emailNormalized: { portalId: portal.id, emailNormalized: CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL } },
|
||||
create: {
|
||||
id: "customer-portal-uat-subcontractor",
|
||||
tenantId: command.expectedTenantId,
|
||||
portalId: portal.id,
|
||||
email: CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL,
|
||||
emailNormalized: CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL,
|
||||
passwordHash: subcontractorPasswordHash,
|
||||
firstName: "Sascha",
|
||||
lastName: "Subunternehmer",
|
||||
kind: "subcontractor",
|
||||
status: "active",
|
||||
locale: "de",
|
||||
emailVerifiedAt: UAT_VERIFIED_AT,
|
||||
isDemoData: true,
|
||||
},
|
||||
update: {
|
||||
email: CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL,
|
||||
passwordHash: subcontractorPasswordHash,
|
||||
firstName: "Sascha",
|
||||
lastName: "Subunternehmer",
|
||||
kind: "subcontractor",
|
||||
status: "active",
|
||||
locale: "de",
|
||||
emailVerifiedAt: UAT_VERIFIED_AT,
|
||||
archivedAt: null,
|
||||
isDemoData: true,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
await tx.portalProjectAccess.updateMany({
|
||||
where: {
|
||||
tenantId: command.expectedTenantId,
|
||||
portalId: portal.id,
|
||||
portalUserId: { in: [customer.id, subcontractor.id] },
|
||||
projectId: { not: CUSTOMER_PORTAL_UAT_PROJECT_ID },
|
||||
isDemoData: true,
|
||||
active: true,
|
||||
},
|
||||
data: { active: false, revokedAt: now },
|
||||
});
|
||||
await tx.portalProjectAccess.upsert({
|
||||
where: { portalId_portalUserId_projectId: { portalId: portal.id, portalUserId: customer.id, projectId: expectedProject.id } },
|
||||
create: {
|
||||
id: "customer-portal-uat-customer-access",
|
||||
tenantId: command.expectedTenantId,
|
||||
portalId: portal.id,
|
||||
portalUserId: customer.id,
|
||||
projectId: expectedProject.id,
|
||||
active: true,
|
||||
statusEmailsEnabled: true,
|
||||
isDemoData: true,
|
||||
},
|
||||
update: { active: true, revokedAt: null, statusEmailsEnabled: true, isDemoData: true },
|
||||
select: { id: true },
|
||||
});
|
||||
const subcontractorAccess = await tx.portalProjectAccess.upsert({
|
||||
where: {
|
||||
portalId_portalUserId_projectId: { portalId: portal.id, portalUserId: subcontractor.id, projectId: expectedProject.id },
|
||||
},
|
||||
create: {
|
||||
id: "customer-portal-uat-subcontractor-access",
|
||||
tenantId: command.expectedTenantId,
|
||||
portalId: portal.id,
|
||||
portalUserId: subcontractor.id,
|
||||
projectId: expectedProject.id,
|
||||
active: true,
|
||||
statusEmailsEnabled: false,
|
||||
isDemoData: true,
|
||||
},
|
||||
update: { active: true, revokedAt: null, statusEmailsEnabled: false, isDemoData: true },
|
||||
select: { id: true },
|
||||
});
|
||||
await tx.portalSubcontractorAccess.upsert({
|
||||
where: {
|
||||
portalId_portalUserId_projectId: { portalId: portal.id, portalUserId: subcontractor.id, projectId: expectedProject.id },
|
||||
},
|
||||
create: {
|
||||
id: "customer-portal-uat-subcontractor-scope",
|
||||
tenantId: command.expectedTenantId,
|
||||
portalId: portal.id,
|
||||
portalUserId: subcontractor.id,
|
||||
projectId: expectedProject.id,
|
||||
projectAccessId: subcontractorAccess.id,
|
||||
companyName: "HiveGrid UAT Subunternehmer",
|
||||
roleLabel: "Montagepartner",
|
||||
visibleStageIds: [expectedProject.stageId],
|
||||
visibleDocumentTypes: [],
|
||||
canSeeOtherSubcontractors: false,
|
||||
canUpload: true,
|
||||
active: true,
|
||||
isDemoData: true,
|
||||
},
|
||||
update: {
|
||||
projectAccessId: subcontractorAccess.id,
|
||||
companyName: "HiveGrid UAT Subunternehmer",
|
||||
roleLabel: "Montagepartner",
|
||||
visibleStageIds: [expectedProject.stageId],
|
||||
visibleDocumentTypes: [],
|
||||
canSeeOtherSubcontractors: false,
|
||||
canUpload: true,
|
||||
active: true,
|
||||
revokedAt: null,
|
||||
isDemoData: true,
|
||||
},
|
||||
});
|
||||
|
||||
for (const project of [expectedProject, forbiddenProject]) {
|
||||
await tx.portalStageVisibility.upsert({
|
||||
where: { portalId_stageId: { portalId: portal.id, stageId: project.stageId } },
|
||||
create: {
|
||||
tenantId: command.expectedTenantId,
|
||||
portalId: portal.id,
|
||||
stageId: project.stageId,
|
||||
visible: true,
|
||||
customerLabel: project.stage.name,
|
||||
isDemoData: true,
|
||||
},
|
||||
update: { visible: true, customerLabel: project.stage.name, isDemoData: true },
|
||||
});
|
||||
}
|
||||
|
||||
await tx.form.upsert({
|
||||
where: { tenantId_slug: { tenantId: command.expectedTenantId, slug: UAT_FORM_SLUG } },
|
||||
create: {
|
||||
id: "customer-portal-uat-complaint-form",
|
||||
key: UAT_FORM_KEY,
|
||||
tenantId: command.expectedTenantId,
|
||||
slug: UAT_FORM_SLUG,
|
||||
name: UAT_FORM_NAME,
|
||||
subtype: "portal_form",
|
||||
status: "published",
|
||||
publishedAt: now,
|
||||
isPublic: true,
|
||||
isDemoData: true,
|
||||
definition: customerPortalUatComplaintDefinition as unknown as Prisma.InputJsonValue,
|
||||
targetType: "project",
|
||||
targetEntityId: expectedProject.id,
|
||||
allowedOrigins: [CUSTOMER_PORTAL_UAT_STANDARD_ORIGIN],
|
||||
notifyEmails: [],
|
||||
config: { honeypotEnabled: false },
|
||||
isEnabled: true,
|
||||
},
|
||||
update: {
|
||||
key: UAT_FORM_KEY,
|
||||
name: UAT_FORM_NAME,
|
||||
subtype: "portal_form",
|
||||
status: "published",
|
||||
publishedAt: now,
|
||||
isPublic: true,
|
||||
isDemoData: true,
|
||||
definition: customerPortalUatComplaintDefinition as unknown as Prisma.InputJsonValue,
|
||||
targetType: "project",
|
||||
targetEntityId: expectedProject.id,
|
||||
allowedOrigins: [CUSTOMER_PORTAL_UAT_STANDARD_ORIGIN],
|
||||
notifyEmails: [],
|
||||
config: { honeypotEnabled: false },
|
||||
isEnabled: true,
|
||||
},
|
||||
});
|
||||
await tx.portalServiceInboxItem.upsert({
|
||||
where: { tenantId_sourceKey: { tenantId: command.expectedTenantId, sourceKey: UAT_INBOX_SOURCE_KEY } },
|
||||
create: {
|
||||
id: "customer-portal-uat-inbox-item",
|
||||
tenantId: command.expectedTenantId,
|
||||
portalId: portal.id,
|
||||
portalUserId: customer.id,
|
||||
projectId: expectedProject.id,
|
||||
kind: "complaint",
|
||||
status: "open",
|
||||
priority: 100,
|
||||
sourceKey: UAT_INBOX_SOURCE_KEY,
|
||||
sourceId: UAT_INBOX_SOURCE_ID,
|
||||
titleKey: UAT_INBOX_TITLE_KEY,
|
||||
metadata: { fixture: "VA-P26" },
|
||||
occurredAt: now,
|
||||
lastOccurredAt: now,
|
||||
bundledCount: 1,
|
||||
expiresAt: inboxExpiry,
|
||||
isDemoData: true,
|
||||
},
|
||||
update: {
|
||||
portalId: portal.id,
|
||||
portalUserId: customer.id,
|
||||
projectId: expectedProject.id,
|
||||
kind: "complaint",
|
||||
status: "open",
|
||||
priority: 100,
|
||||
sourceId: UAT_INBOX_SOURCE_ID,
|
||||
titleKey: UAT_INBOX_TITLE_KEY,
|
||||
metadata: { fixture: "VA-P26" },
|
||||
occurredAt: now,
|
||||
lastOccurredAt: now,
|
||||
bundledCount: 1,
|
||||
expiresAt: inboxExpiry,
|
||||
ownerUserId: null,
|
||||
resolvedAt: null,
|
||||
isDemoData: true,
|
||||
},
|
||||
});
|
||||
|
||||
await publishAuditEventViaOutbox(tx, {
|
||||
tenantId: command.expectedTenantId,
|
||||
actorId: command.operatorUserId,
|
||||
actorType: "operator",
|
||||
action: "customer_portal.uat_fixture.provisioned",
|
||||
targetType: "Portal",
|
||||
targetId: portal.id,
|
||||
sourceModule: "customer-portal-uat",
|
||||
outcome: "success",
|
||||
dataSensitivity: "internal",
|
||||
regulatoryScope: ["none"],
|
||||
metadata: { tenantSlug: CUSTOMER_PORTAL_UAT_TENANT_SLUG, projectCount: 2, portalUserCount: 2 },
|
||||
});
|
||||
});
|
||||
}
|
||||
+637
@@ -0,0 +1,637 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Short-lived loopback adapter for VA-P26a delivered-mail UAT evidence."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import imaplib
|
||||
import json
|
||||
import re
|
||||
import ssl
|
||||
import sys
|
||||
import threading
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from email import policy
|
||||
from email.message import Message
|
||||
from email.parser import BytesParser
|
||||
from email.utils import getaddresses, parsedate_to_datetime
|
||||
from html.parser import HTMLParser
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from typing import Mapping, Sequence
|
||||
from urllib.parse import quote, urlsplit
|
||||
|
||||
|
||||
UTC = timezone.utc
|
||||
LOOPBACK_HOST = "127.0.0.1"
|
||||
DEFAULT_PORT = 4010
|
||||
DEFAULT_IMAP_PORT = 993
|
||||
DEFAULT_MAILBOX = "INBOX"
|
||||
DEFAULT_PRODUCT_NAME = "Demo Pro CRM Kundenportal"
|
||||
MAX_REQUEST_BYTES = 8 * 1024
|
||||
MAX_MESSAGE_BYTES = 1024 * 1024
|
||||
MAX_CANDIDATE_MESSAGES = 50
|
||||
MAX_MAILBOX_ADDRESS_BYTES = 254
|
||||
MAX_LOCAL_PART_BYTES = 64
|
||||
MAX_DOMAIN_BYTES = 253
|
||||
DELIVERY_TOLERANCE = timedelta(seconds=5)
|
||||
MAX_BOUNDARY_AGE = timedelta(minutes=30)
|
||||
MAX_CLOCK_SKEW = timedelta(seconds=30)
|
||||
SETUP_TOKEN_PATTERN = re.compile(r"^[A-Za-z0-9_-]{43}$")
|
||||
CORRELATION_PATTERN = re.compile(r"^[a-z0-9][a-z0-9-]{0,95}$")
|
||||
TENANT_SLUG_PATTERN = re.compile(r"^[a-z0-9][a-z0-9-]{0,62}$")
|
||||
HOST_PATTERN = re.compile(r"^[A-Za-z0-9.-]{1,253}$")
|
||||
LOCAL_PART_PATTERN = re.compile(r"^[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*$")
|
||||
DOMAIN_LABEL_PATTERN = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$")
|
||||
INTERNAL_DATE_PATTERN = re.compile(rb'INTERNALDATE "([^"]+)"')
|
||||
MESSAGE_SIZE_PATTERN = re.compile(rb"RFC822\.SIZE (\d+)")
|
||||
URL_PATTERN = re.compile(r"""https?://[^\s<>"')\]}]+""")
|
||||
RAW_HREF_PATTERN = re.compile(r'''\shref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))''', re.IGNORECASE)
|
||||
SOURCE_PREFIXES = {
|
||||
"portal_admin_invite": "p26a-admin-",
|
||||
"portal_contact_invite": "p26a-contact-",
|
||||
"portal_project_invite": "p26a-project-",
|
||||
}
|
||||
|
||||
|
||||
class ContractError(ValueError):
|
||||
"""The local HTTP request does not match the bounded UAT contract."""
|
||||
|
||||
|
||||
class ConfigurationError(ValueError):
|
||||
"""The operator-only adapter configuration is incomplete or unsafe."""
|
||||
|
||||
|
||||
class MailboxUnavailable(RuntimeError):
|
||||
"""The mailbox could not be read without exposing provider details."""
|
||||
|
||||
|
||||
class AnchorHrefParser(HTMLParser):
|
||||
"""Collects literal anchor hrefs without resolving or fetching them."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__(convert_charrefs=False)
|
||||
self.hrefs: list[str] = []
|
||||
|
||||
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
||||
if tag.lower() != "a":
|
||||
return
|
||||
hrefs = [value for name, value in attrs if name.lower() == "href" and value is not None]
|
||||
raw_hrefs = [next(value for value in match.groups() if value is not None) for match in RAW_HREF_PATTERN.finditer(self.get_starttag_text() or "")]
|
||||
if len(hrefs) == 1 and raw_hrefs == hrefs:
|
||||
self.hrefs.append(hrefs[0])
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AdapterConfig:
|
||||
imap_host: str
|
||||
imap_port: int
|
||||
mailbox: str
|
||||
mailbox_email: str
|
||||
mailbox_password: str
|
||||
portal_origin: str
|
||||
custom_portal_origin: str | None
|
||||
tenant_slug: str
|
||||
expected_subjects: frozenset[str]
|
||||
listen_port: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MailQuery:
|
||||
correlation_key: str
|
||||
recipient: str
|
||||
source: str
|
||||
purpose: str
|
||||
delivered_after: datetime
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DeliveredMail:
|
||||
delivered_at: datetime
|
||||
setup_url: str
|
||||
|
||||
|
||||
def load_config(env: Mapping[str, str]) -> AdapterConfig:
|
||||
imap_host = require_env(env, "PORTAL_SETUP_MAIL_IMAP_HOST").strip()
|
||||
if not HOST_PATTERN.fullmatch(imap_host) or ".." in imap_host or imap_host.startswith((".", "-")):
|
||||
raise ConfigurationError("PORTAL_SETUP_MAIL_IMAP_HOST is invalid.")
|
||||
|
||||
imap_port = parse_port(env.get("PORTAL_SETUP_MAIL_IMAP_PORT", str(DEFAULT_IMAP_PORT)), "PORTAL_SETUP_MAIL_IMAP_PORT")
|
||||
listen_port = parse_port(env.get("PORTAL_SETUP_MAIL_ADAPTER_PORT", str(DEFAULT_PORT)), "PORTAL_SETUP_MAIL_ADAPTER_PORT")
|
||||
mailbox = env.get("PORTAL_SETUP_MAIL_IMAP_FOLDER", DEFAULT_MAILBOX).strip()
|
||||
if not mailbox or len(mailbox) > 128 or any(character in mailbox for character in "\r\n\0"):
|
||||
raise ConfigurationError("PORTAL_SETUP_MAIL_IMAP_FOLDER is invalid.")
|
||||
|
||||
portal_origin = normalize_portal_origin(require_env(env, "E2E_PORTAL_BASE_URL"), "E2E_PORTAL_BASE_URL")
|
||||
custom_portal_origin_raw = env.get("E2E_PORTAL_CUSTOM_DOMAIN_BASE_URL", "").strip()
|
||||
custom_portal_origin = (
|
||||
normalize_portal_origin(custom_portal_origin_raw, "E2E_PORTAL_CUSTOM_DOMAIN_BASE_URL")
|
||||
if custom_portal_origin_raw
|
||||
else None
|
||||
)
|
||||
tenant_slug = require_env(env, "E2E_PORTAL_TENANT_SLUG").strip()
|
||||
if not TENANT_SLUG_PATTERN.fullmatch(tenant_slug):
|
||||
raise ConfigurationError("E2E_PORTAL_TENANT_SLUG is invalid.")
|
||||
|
||||
product_name = env.get("PORTAL_SETUP_MAIL_EXPECTED_PRODUCT_NAME", DEFAULT_PRODUCT_NAME).strip()
|
||||
if not product_name or len(product_name) > 120 or any(character in product_name for character in "\r\n\0"):
|
||||
raise ConfigurationError("PORTAL_SETUP_MAIL_EXPECTED_PRODUCT_NAME is invalid.")
|
||||
|
||||
mailbox_email = require_env(env, "MAILBOX_EMAIL")
|
||||
parse_mailbox_base(mailbox_email)
|
||||
|
||||
return AdapterConfig(
|
||||
imap_host=imap_host,
|
||||
imap_port=imap_port,
|
||||
mailbox=mailbox,
|
||||
mailbox_email=mailbox_email,
|
||||
mailbox_password=require_env(env, "MAILBOX_APP_PASSWORD"),
|
||||
portal_origin=portal_origin,
|
||||
custom_portal_origin=custom_portal_origin,
|
||||
tenant_slug=tenant_slug,
|
||||
expected_subjects=frozenset(
|
||||
{
|
||||
f"Richte deinen Zugang zu {product_name} ein",
|
||||
f"Set up your access to {product_name}",
|
||||
}
|
||||
),
|
||||
listen_port=listen_port,
|
||||
)
|
||||
|
||||
|
||||
def parse_mail_query(payload: object, mailbox_email: str, now: datetime | None = None) -> MailQuery:
|
||||
if not isinstance(payload, dict) or set(payload) != {"correlationKey", "recipient", "source", "purpose", "deliveredAfter"}:
|
||||
raise ContractError("The setup-mail request shape is invalid.")
|
||||
|
||||
correlation_key = require_contract_string(payload, "correlationKey")
|
||||
recipient = require_contract_string(payload, "recipient").lower()
|
||||
source = require_contract_string(payload, "source")
|
||||
purpose = require_contract_string(payload, "purpose")
|
||||
delivered_after_raw = require_contract_string(payload, "deliveredAfter")
|
||||
|
||||
expected_prefix = SOURCE_PREFIXES.get(source)
|
||||
if not expected_prefix or not CORRELATION_PATTERN.fullmatch(correlation_key) or not correlation_key.startswith(expected_prefix):
|
||||
raise ContractError("The invitation correlation contract is invalid.")
|
||||
expected_recipient = invitation_recipient(mailbox_email, correlation_key)
|
||||
if recipient != expected_recipient:
|
||||
raise ContractError("The invitation recipient contract is invalid.")
|
||||
if purpose != "setup":
|
||||
raise ContractError("The invitation purpose is invalid.")
|
||||
|
||||
delivered_after = parse_utc_timestamp(delivered_after_raw)
|
||||
current_time = (now or datetime.now(UTC)).astimezone(UTC)
|
||||
if delivered_after < current_time - MAX_BOUNDARY_AGE or delivered_after > current_time + MAX_CLOCK_SKEW:
|
||||
raise ContractError("The delivery boundary is outside the allowed UAT window.")
|
||||
|
||||
return MailQuery(
|
||||
correlation_key=correlation_key,
|
||||
recipient=recipient,
|
||||
source=source,
|
||||
purpose=purpose,
|
||||
delivered_after=delivered_after,
|
||||
)
|
||||
|
||||
|
||||
def find_delivered_mail(config: AdapterConfig, query: MailQuery) -> DeliveredMail | None:
|
||||
client: imaplib.IMAP4_SSL | None = None
|
||||
try:
|
||||
client = imaplib.IMAP4_SSL(
|
||||
config.imap_host,
|
||||
config.imap_port,
|
||||
ssl_context=ssl.create_default_context(),
|
||||
timeout=5,
|
||||
)
|
||||
client.login(config.mailbox_email, config.mailbox_password)
|
||||
status, _ = client.select(config.mailbox, readonly=True)
|
||||
if status != "OK":
|
||||
raise MailboxUnavailable("Mailbox selection failed.")
|
||||
|
||||
since = (query.delivered_after - DELIVERY_TOLERANCE).strftime("%d-%b-%Y")
|
||||
status, search_data = client.uid("search", None, "SINCE", since)
|
||||
if status != "OK" or not search_data:
|
||||
raise MailboxUnavailable("Mailbox search failed.")
|
||||
|
||||
uids = search_data[0].split()[-MAX_CANDIDATE_MESSAGES:]
|
||||
matches: list[DeliveredMail] = []
|
||||
for uid in reversed(uids):
|
||||
status, fetch_data = client.uid(
|
||||
"fetch",
|
||||
uid,
|
||||
f"(INTERNALDATE RFC822.SIZE BODY.PEEK[]<0.{MAX_MESSAGE_BYTES + 1}>)",
|
||||
)
|
||||
if status != "OK":
|
||||
continue
|
||||
metadata, raw_message = extract_fetch_result(fetch_data)
|
||||
if metadata is None or raw_message is None:
|
||||
continue
|
||||
message_size = parse_message_size(metadata)
|
||||
delivered_at = parse_internal_date(metadata)
|
||||
if message_size is None or message_size > MAX_MESSAGE_BYTES or len(raw_message) > MAX_MESSAGE_BYTES or delivered_at is None:
|
||||
continue
|
||||
match = match_delivered_message(config, query, raw_message, delivered_at)
|
||||
if match:
|
||||
matches.append(match)
|
||||
|
||||
return max(matches, key=lambda match: match.delivered_at) if matches else None
|
||||
except MailboxUnavailable:
|
||||
raise
|
||||
except (imaplib.IMAP4.error, OSError, ssl.SSLError, ValueError):
|
||||
raise MailboxUnavailable("Mailbox lookup failed.") from None
|
||||
finally:
|
||||
if client is not None:
|
||||
try:
|
||||
client.logout()
|
||||
except (imaplib.IMAP4.error, OSError, ssl.SSLError):
|
||||
pass
|
||||
|
||||
|
||||
def match_delivered_message(
|
||||
config: AdapterConfig,
|
||||
query: MailQuery,
|
||||
raw_message: bytes,
|
||||
delivered_at: datetime,
|
||||
now: datetime | None = None,
|
||||
) -> DeliveredMail | None:
|
||||
normalized_delivery = delivered_at.astimezone(UTC)
|
||||
if normalized_delivery + DELIVERY_TOLERANCE < query.delivered_after:
|
||||
return None
|
||||
if normalized_delivery > (now or datetime.now(UTC)).astimezone(UTC) + timedelta(minutes=5):
|
||||
return None
|
||||
|
||||
try:
|
||||
message = BytesParser(policy=policy.default).parsebytes(raw_message)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
if query.recipient not in message_recipients(message):
|
||||
return None
|
||||
if str(message.get("Subject", "")).strip() not in config.expected_subjects:
|
||||
return None
|
||||
|
||||
plain_parts = plain_text_parts(message)
|
||||
html_bodies = html_parts(message)
|
||||
if not plain_parts or not html_bodies:
|
||||
return None
|
||||
|
||||
plain_setup_urls = {
|
||||
url
|
||||
for text in plain_parts
|
||||
for candidate in URL_PATTERN.findall(text)
|
||||
if (
|
||||
url := normalize_setup_url(
|
||||
candidate,
|
||||
config.portal_origin,
|
||||
config.tenant_slug,
|
||||
config.custom_portal_origin,
|
||||
)
|
||||
)
|
||||
is not None
|
||||
}
|
||||
html_setup_urls = {
|
||||
url
|
||||
for html_body in html_bodies
|
||||
for candidate in anchor_hrefs(html_body)
|
||||
if (
|
||||
url := normalize_setup_url(
|
||||
candidate,
|
||||
config.portal_origin,
|
||||
config.tenant_slug,
|
||||
config.custom_portal_origin,
|
||||
)
|
||||
)
|
||||
is not None
|
||||
}
|
||||
if len(plain_setup_urls) != 1 or html_setup_urls != plain_setup_urls:
|
||||
return None
|
||||
return DeliveredMail(delivered_at=normalized_delivery, setup_url=next(iter(plain_setup_urls)))
|
||||
|
||||
|
||||
def make_handler(config: AdapterConfig):
|
||||
consumed: set[str] = set()
|
||||
consumed_lock = threading.Lock()
|
||||
|
||||
class SetupMailHandler(BaseHTTPRequestHandler):
|
||||
server_version = "HiveGridPortalSetupMailAdapter"
|
||||
sys_version = ""
|
||||
|
||||
def do_POST(self) -> None: # noqa: N802 - BaseHTTPRequestHandler API
|
||||
if urlsplit(self.path).path != "/setup-mail" or urlsplit(self.path).query:
|
||||
self.send_empty(404)
|
||||
return
|
||||
if "Authorization" in self.headers:
|
||||
self.send_empty(401)
|
||||
return
|
||||
if self.headers.get("Transfer-Encoding"):
|
||||
self.send_empty(400)
|
||||
return
|
||||
|
||||
raw_length = self.headers.get("Content-Length")
|
||||
if not raw_length:
|
||||
self.send_empty(411)
|
||||
return
|
||||
try:
|
||||
content_length = int(raw_length)
|
||||
except ValueError:
|
||||
self.send_empty(400)
|
||||
return
|
||||
if content_length < 2 or content_length > MAX_REQUEST_BYTES:
|
||||
self.send_empty(413)
|
||||
return
|
||||
if self.headers.get_content_type() != "application/json":
|
||||
self.send_empty(415)
|
||||
return
|
||||
|
||||
try:
|
||||
payload = json.loads(self.rfile.read(content_length))
|
||||
query = parse_mail_query(payload, config.mailbox_email)
|
||||
except (ContractError, UnicodeDecodeError, json.JSONDecodeError):
|
||||
self.send_empty(400)
|
||||
return
|
||||
|
||||
identity = query_identity(query)
|
||||
with consumed_lock:
|
||||
if identity in consumed:
|
||||
self.send_empty(410)
|
||||
return
|
||||
|
||||
try:
|
||||
delivery = find_delivered_mail(config, query)
|
||||
except MailboxUnavailable:
|
||||
self.send_empty(503)
|
||||
return
|
||||
if delivery is None:
|
||||
self.send_empty(202)
|
||||
return
|
||||
|
||||
with consumed_lock:
|
||||
if identity in consumed:
|
||||
self.send_empty(410)
|
||||
return
|
||||
consumed.add(identity)
|
||||
|
||||
self.send_json(
|
||||
200,
|
||||
{
|
||||
"correlationKey": query.correlation_key,
|
||||
"recipient": query.recipient,
|
||||
"source": query.source,
|
||||
"purpose": query.purpose,
|
||||
"deliveredAt": format_utc_timestamp(delivery.delivered_at),
|
||||
"setupUrl": delivery.setup_url,
|
||||
},
|
||||
)
|
||||
|
||||
def do_GET(self) -> None: # noqa: N802 - BaseHTTPRequestHandler API
|
||||
self.send_empty(405)
|
||||
|
||||
def do_HEAD(self) -> None: # noqa: N802 - BaseHTTPRequestHandler API
|
||||
self.send_empty(405)
|
||||
|
||||
def send_empty(self, status: int) -> None:
|
||||
self.send_response(status)
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("Content-Length", "0")
|
||||
self.send_header("X-Content-Type-Options", "nosniff")
|
||||
self.end_headers()
|
||||
|
||||
def send_json(self, status: int, payload: Mapping[str, str]) -> None:
|
||||
body = json.dumps(payload, separators=(",", ":")).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("X-Content-Type-Options", "nosniff")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, _format: str, *args: object) -> None:
|
||||
# The default HTTP access log includes request paths and client data.
|
||||
# This local proof adapter intentionally emits no per-request logs.
|
||||
del args
|
||||
|
||||
return SetupMailHandler
|
||||
|
||||
|
||||
def serve(config: AdapterConfig) -> None:
|
||||
class AdapterServer(ThreadingHTTPServer):
|
||||
daemon_threads = True
|
||||
|
||||
def handle_error(self, _request: object, _client_address: object) -> None:
|
||||
# socketserver otherwise prints tracebacks and client data. This
|
||||
# single-purpose adapter remains silent even on disconnects.
|
||||
return
|
||||
|
||||
server = AdapterServer((LOOPBACK_HOST, config.listen_port), make_handler(config))
|
||||
try:
|
||||
server.serve_forever(poll_interval=0.25)
|
||||
finally:
|
||||
server.server_close()
|
||||
|
||||
|
||||
def message_recipients(message: Message) -> frozenset[str]:
|
||||
header_values: list[str] = []
|
||||
for header in ("To", "Delivered-To", "X-Original-To", "Envelope-To"):
|
||||
header_values.extend(str(value) for value in message.get_all(header, []))
|
||||
return frozenset(address.strip().lower() for _, address in getaddresses(header_values) if address.strip())
|
||||
|
||||
|
||||
def plain_text_parts(message: Message) -> Sequence[str]:
|
||||
parts = message.walk() if message.is_multipart() else (message,)
|
||||
texts: list[str] = []
|
||||
for part in parts:
|
||||
if part.get_content_type() != "text/plain" or part.get_content_disposition() == "attachment":
|
||||
continue
|
||||
try:
|
||||
content = part.get_content()
|
||||
except (LookupError, TypeError, UnicodeDecodeError, ValueError):
|
||||
continue
|
||||
if isinstance(content, str):
|
||||
texts.append(content)
|
||||
return texts
|
||||
|
||||
|
||||
def html_parts(message: Message) -> Sequence[str]:
|
||||
parts = message.walk() if message.is_multipart() else (message,)
|
||||
bodies: list[str] = []
|
||||
for part in parts:
|
||||
if part.get_content_type() != "text/html" or part.get_content_disposition() == "attachment":
|
||||
continue
|
||||
try:
|
||||
content = part.get_content()
|
||||
except (LookupError, TypeError, UnicodeDecodeError, ValueError):
|
||||
continue
|
||||
if isinstance(content, str):
|
||||
bodies.append(content)
|
||||
return bodies
|
||||
|
||||
|
||||
def anchor_hrefs(html_body: str) -> Sequence[str]:
|
||||
parser = AnchorHrefParser()
|
||||
try:
|
||||
parser.feed(html_body)
|
||||
parser.close()
|
||||
except (AssertionError, ValueError):
|
||||
return ()
|
||||
return parser.hrefs
|
||||
|
||||
|
||||
def normalize_setup_url(
|
||||
candidate: str,
|
||||
expected_origin: str,
|
||||
tenant_slug: str,
|
||||
expected_custom_origin: str | None = None,
|
||||
) -> str | None:
|
||||
trimmed = candidate.rstrip(".,;:!?)]}")
|
||||
try:
|
||||
parsed = urlsplit(trimmed)
|
||||
except ValueError:
|
||||
return None
|
||||
expected = urlsplit(expected_origin)
|
||||
if (
|
||||
parsed.username
|
||||
or parsed.password
|
||||
or parsed.query
|
||||
or parsed.fragment
|
||||
):
|
||||
return None
|
||||
candidate_origin = f"{parsed.scheme}://{parsed.netloc}"
|
||||
if candidate_origin == f"{expected.scheme}://{expected.netloc}":
|
||||
expected_prefix = f"/{quote(tenant_slug, safe='')}/setup/"
|
||||
elif expected_custom_origin and candidate_origin == expected_custom_origin:
|
||||
expected_prefix = "/setup/"
|
||||
else:
|
||||
return None
|
||||
if not parsed.path.startswith(expected_prefix):
|
||||
return None
|
||||
token = parsed.path[len(expected_prefix) :]
|
||||
if not SETUP_TOKEN_PATTERN.fullmatch(token):
|
||||
return None
|
||||
return trimmed
|
||||
|
||||
|
||||
def extract_fetch_result(fetch_data: Sequence[object]) -> tuple[bytes | None, bytes | None]:
|
||||
for item in fetch_data:
|
||||
if isinstance(item, tuple) and len(item) >= 2 and isinstance(item[0], bytes) and isinstance(item[1], bytes):
|
||||
return item[0], item[1]
|
||||
return None, None
|
||||
|
||||
|
||||
def parse_message_size(metadata: bytes) -> int | None:
|
||||
match = MESSAGE_SIZE_PATTERN.search(metadata)
|
||||
return int(match.group(1)) if match else None
|
||||
|
||||
|
||||
def parse_internal_date(metadata: bytes) -> datetime | None:
|
||||
match = INTERNAL_DATE_PATTERN.search(metadata)
|
||||
if not match:
|
||||
return None
|
||||
try:
|
||||
parsed = parsedate_to_datetime(match.group(1).decode("ascii"))
|
||||
except (UnicodeDecodeError, TypeError, ValueError):
|
||||
return None
|
||||
return parsed.astimezone(UTC) if parsed.tzinfo else None
|
||||
|
||||
|
||||
def query_identity(query: MailQuery) -> str:
|
||||
encoded = "\0".join([query.correlation_key, query.recipient, query.source, query.purpose]).encode("utf-8")
|
||||
return hashlib.sha256(encoded).hexdigest()
|
||||
|
||||
|
||||
def parse_utc_timestamp(value: str) -> datetime:
|
||||
if not value.endswith("Z"):
|
||||
raise ContractError("deliveredAfter must be an ISO-8601 UTC timestamp.")
|
||||
try:
|
||||
parsed = datetime.fromisoformat(f"{value[:-1]}+00:00")
|
||||
except ValueError:
|
||||
raise ContractError("deliveredAfter must be an ISO-8601 UTC timestamp.") from None
|
||||
if parsed.tzinfo is None:
|
||||
raise ContractError("deliveredAfter must be an ISO-8601 UTC timestamp.")
|
||||
return parsed.astimezone(UTC)
|
||||
|
||||
|
||||
def format_utc_timestamp(value: datetime) -> str:
|
||||
return value.astimezone(UTC).isoformat(timespec="seconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
def normalize_portal_origin(value: str, input_name: str) -> str:
|
||||
try:
|
||||
parsed = urlsplit(value.strip())
|
||||
except ValueError:
|
||||
raise ConfigurationError(f"{input_name} is invalid.") from None
|
||||
if parsed.scheme != "https" or not parsed.netloc or parsed.username or parsed.password or parsed.path not in ("", "/") or parsed.query or parsed.fragment:
|
||||
raise ConfigurationError(f"{input_name} must be an exact HTTPS root origin.")
|
||||
return f"{parsed.scheme}://{parsed.netloc}"
|
||||
|
||||
|
||||
def parse_mailbox_base(value: str) -> tuple[str, str]:
|
||||
if value != value.strip() or any(character in value for character in "\r\n\0"):
|
||||
raise ConfigurationError("MAILBOX_EMAIL is invalid.")
|
||||
try:
|
||||
encoded = value.encode("ascii")
|
||||
except UnicodeEncodeError:
|
||||
raise ConfigurationError("MAILBOX_EMAIL is invalid.") from None
|
||||
if len(encoded) > MAX_MAILBOX_ADDRESS_BYTES or value.count("@") != 1:
|
||||
raise ConfigurationError("MAILBOX_EMAIL is invalid.")
|
||||
|
||||
local_part, domain = value.rsplit("@", 1)
|
||||
if "+" in local_part or not LOCAL_PART_PATTERN.fullmatch(local_part) or len(local_part.encode("ascii")) > MAX_LOCAL_PART_BYTES:
|
||||
raise ConfigurationError("MAILBOX_EMAIL is invalid.")
|
||||
if len(domain.encode("ascii")) > MAX_DOMAIN_BYTES:
|
||||
raise ConfigurationError("MAILBOX_EMAIL is invalid.")
|
||||
labels = domain.split(".")
|
||||
if len(labels) < 2 or any(len(label.encode("ascii")) > 63 or not DOMAIN_LABEL_PATTERN.fullmatch(label) for label in labels):
|
||||
raise ConfigurationError("MAILBOX_EMAIL is invalid.")
|
||||
return local_part.lower(), domain.lower()
|
||||
|
||||
|
||||
def invitation_recipient(mailbox_email: str, correlation_key: str) -> str:
|
||||
local_part, domain = parse_mailbox_base(mailbox_email)
|
||||
derived_local_part = f"{local_part}+{correlation_key}"
|
||||
recipient = f"{derived_local_part}@{domain}"
|
||||
if len(derived_local_part.encode("ascii")) > MAX_LOCAL_PART_BYTES or len(recipient.encode("ascii")) > MAX_MAILBOX_ADDRESS_BYTES:
|
||||
raise ContractError("The invitation recipient contract is invalid.")
|
||||
return recipient
|
||||
|
||||
|
||||
def require_env(env: Mapping[str, str], key: str) -> str:
|
||||
value = env.get(key)
|
||||
if value is None or not value.strip():
|
||||
raise ConfigurationError(f"{key} is required.")
|
||||
return value
|
||||
|
||||
|
||||
def require_contract_string(payload: Mapping[str, object], key: str) -> str:
|
||||
value = payload.get(key)
|
||||
if not isinstance(value, str) or not value or value.strip() != value or len(value) > 256 or any(character in value for character in "\r\n\0"):
|
||||
raise ContractError(f"{key} is invalid.")
|
||||
return value
|
||||
|
||||
|
||||
def parse_port(value: str, key: str) -> int:
|
||||
try:
|
||||
parsed = int(value)
|
||||
except ValueError:
|
||||
raise ConfigurationError(f"{key} is invalid.") from None
|
||||
if parsed < 1 or parsed > 65535:
|
||||
raise ConfigurationError(f"{key} is invalid.")
|
||||
return parsed
|
||||
|
||||
|
||||
def main() -> int:
|
||||
import os
|
||||
|
||||
try:
|
||||
config = load_config(os.environ)
|
||||
serve(config)
|
||||
return 0
|
||||
except ConfigurationError as error:
|
||||
sys.stderr.write(f"{error}\n")
|
||||
return 2
|
||||
except KeyboardInterrupt:
|
||||
return 0
|
||||
except OSError:
|
||||
sys.stderr.write("Portal setup mail adapter could not bind its loopback listener.\n")
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
+367
@@ -0,0 +1,367 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import unittest
|
||||
from dataclasses import replace
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from email.message import EmailMessage
|
||||
from http.client import HTTPConnection
|
||||
from http.server import ThreadingHTTPServer
|
||||
from threading import Thread
|
||||
from unittest.mock import patch
|
||||
from urllib.parse import quote
|
||||
|
||||
from portal_setup_mail_adapter import (
|
||||
AdapterConfig,
|
||||
ConfigurationError,
|
||||
ContractError,
|
||||
DeliveredMail,
|
||||
load_config,
|
||||
make_handler,
|
||||
match_delivered_message,
|
||||
normalize_setup_url,
|
||||
parse_mail_query,
|
||||
)
|
||||
|
||||
|
||||
UTC = timezone.utc
|
||||
NOW = datetime(2026, 7, 19, 12, 0, tzinfo=UTC)
|
||||
TOKEN = "s" * 43
|
||||
MAILBOX_EMAIL = "fixture@example.test"
|
||||
|
||||
|
||||
def config() -> AdapterConfig:
|
||||
return AdapterConfig(
|
||||
imap_host="imap.example.test",
|
||||
imap_port=993,
|
||||
mailbox="INBOX",
|
||||
mailbox_email=MAILBOX_EMAIL,
|
||||
mailbox_password="not-used-by-unit-tests",
|
||||
portal_origin="https://staging-portal.hivegrid.de",
|
||||
custom_portal_origin=None,
|
||||
tenant_slug="demo-pro-crm",
|
||||
expected_subjects=frozenset(
|
||||
{
|
||||
"Richte deinen Zugang zu Demo Pro CRM Kundenportal ein",
|
||||
"Set up your access to Demo Pro CRM Kundenportal",
|
||||
}
|
||||
),
|
||||
listen_port=4010,
|
||||
)
|
||||
|
||||
|
||||
def payload(entrypoint: str = "contact") -> dict[str, str]:
|
||||
source = f"portal_{entrypoint}_invite"
|
||||
key = f"p26a-{entrypoint}-20260719t120000z-123"
|
||||
return {
|
||||
"correlationKey": key,
|
||||
"recipient": f"fixture+{key}@example.test",
|
||||
"source": source,
|
||||
"purpose": "setup",
|
||||
"deliveredAfter": NOW.isoformat(timespec="milliseconds").replace("+00:00", "Z"),
|
||||
}
|
||||
|
||||
|
||||
def message(
|
||||
recipient: str,
|
||||
url: str,
|
||||
subject: str = "Richte deinen Zugang zu Demo Pro CRM Kundenportal ein",
|
||||
html_url: str | None = None,
|
||||
plain_suffix: str = "",
|
||||
) -> bytes:
|
||||
mail = EmailMessage()
|
||||
mail["To"] = recipient
|
||||
mail["From"] = "HiveGrid <noreply@hivegrid.de>"
|
||||
mail["Subject"] = subject
|
||||
mail.set_content(f"Zugang einrichten ({url}){plain_suffix}")
|
||||
mail.add_alternative(f'<p><a href="{html_url or url}">Zugang einrichten</a></p>', subtype="html")
|
||||
return mail.as_bytes()
|
||||
|
||||
|
||||
class PortalSetupMailAdapterTest(unittest.TestCase):
|
||||
def test_parses_a_fresh_source_bound_synthetic_recipient(self) -> None:
|
||||
query = parse_mail_query(payload(), MAILBOX_EMAIL, now=NOW)
|
||||
|
||||
self.assertEqual(query.source, "portal_contact_invite")
|
||||
self.assertEqual(query.correlation_key, "p26a-contact-20260719t120000z-123")
|
||||
|
||||
def test_rejects_source_prefix_and_recipient_mismatches(self) -> None:
|
||||
wrong_source = payload()
|
||||
wrong_source["source"] = "portal_admin_invite"
|
||||
with self.assertRaises(ContractError):
|
||||
parse_mail_query(wrong_source, MAILBOX_EMAIL, now=NOW)
|
||||
|
||||
wrong_recipient = payload()
|
||||
wrong_recipient["recipient"] = "fixture+other@example.test"
|
||||
with self.assertRaises(ContractError):
|
||||
parse_mail_query(wrong_recipient, MAILBOX_EMAIL, now=NOW)
|
||||
|
||||
wrong_domain = payload()
|
||||
wrong_domain["recipient"] = f"fixture+{wrong_domain['correlationKey']}@elsewhere.test"
|
||||
with self.assertRaises(ContractError):
|
||||
parse_mail_query(wrong_domain, MAILBOX_EMAIL, now=NOW)
|
||||
|
||||
def test_matches_exact_recipient_subject_freshness_and_standard_setup_url(self) -> None:
|
||||
query = parse_mail_query(payload(), MAILBOX_EMAIL, now=NOW)
|
||||
setup_url = f"https://staging-portal.hivegrid.de/demo-pro-crm/setup/{TOKEN}"
|
||||
|
||||
delivery = match_delivered_message(config(), query, message(query.recipient, setup_url), NOW + timedelta(seconds=2), now=NOW)
|
||||
|
||||
self.assertIsNotNone(delivery)
|
||||
self.assertEqual(delivery.setup_url if delivery else None, setup_url)
|
||||
|
||||
def test_matches_only_an_explicitly_configured_custom_origin_root_setup_url(self) -> None:
|
||||
query = parse_mail_query(payload(), MAILBOX_EMAIL, now=NOW)
|
||||
custom_origin = "https://portal.customer.example.test"
|
||||
setup_url = f"{custom_origin}/setup/{TOKEN}"
|
||||
custom_config = replace(config(), custom_portal_origin=custom_origin)
|
||||
|
||||
delivery = match_delivered_message(custom_config, query, message(query.recipient, setup_url), NOW, now=NOW)
|
||||
|
||||
self.assertIsNotNone(delivery)
|
||||
self.assertEqual(delivery.setup_url if delivery else None, setup_url)
|
||||
self.assertIsNone(match_delivered_message(config(), query, message(query.recipient, setup_url), NOW, now=NOW))
|
||||
self.assertIsNone(
|
||||
match_delivered_message(
|
||||
custom_config,
|
||||
query,
|
||||
message(query.recipient, f"{custom_origin}/demo-pro-crm/setup/{TOKEN}"),
|
||||
NOW,
|
||||
now=NOW,
|
||||
)
|
||||
)
|
||||
|
||||
def test_matches_exact_plain_cta_when_receiving_mta_joins_the_following_paragraph(self) -> None:
|
||||
query = parse_mail_query(payload(), MAILBOX_EMAIL, now=NOW)
|
||||
custom_origin = "https://portal.customer.example.test"
|
||||
setup_url = f"{custom_origin}/setup/{TOKEN}"
|
||||
custom_config = replace(config(), custom_portal_origin=custom_origin)
|
||||
|
||||
delivery = match_delivered_message(
|
||||
custom_config,
|
||||
query,
|
||||
message(
|
||||
query.recipient,
|
||||
setup_url,
|
||||
plain_suffix="Dieser Link ist sieben Tage gültig.",
|
||||
),
|
||||
NOW,
|
||||
now=NOW,
|
||||
)
|
||||
|
||||
self.assertIsNotNone(delivery)
|
||||
self.assertEqual(delivery.setup_url if delivery else None, setup_url)
|
||||
|
||||
def test_joined_plain_cta_still_rejects_query_path_and_token_mismatches(self) -> None:
|
||||
query = parse_mail_query(payload(), MAILBOX_EMAIL, now=NOW)
|
||||
custom_origin = "https://portal.customer.example.test"
|
||||
setup_url = f"{custom_origin}/setup/{TOKEN}"
|
||||
custom_config = replace(config(), custom_portal_origin=custom_origin)
|
||||
|
||||
for plain_url in (
|
||||
f"{setup_url}?next=1",
|
||||
f"{setup_url}#fragment",
|
||||
f"{setup_url}/extra",
|
||||
f"{custom_origin}/setup/{'x' * 43}",
|
||||
):
|
||||
with self.subTest(plain_url=plain_url):
|
||||
self.assertIsNone(
|
||||
match_delivered_message(
|
||||
custom_config,
|
||||
query,
|
||||
message(
|
||||
query.recipient,
|
||||
plain_url,
|
||||
html_url=setup_url,
|
||||
plain_suffix="Dieser Link ist sieben Tage gültig.",
|
||||
),
|
||||
NOW,
|
||||
now=NOW,
|
||||
)
|
||||
)
|
||||
|
||||
def test_rejects_stale_wrong_subject_and_nonstandard_setup_links(self) -> None:
|
||||
query = parse_mail_query(payload(), MAILBOX_EMAIL, now=NOW)
|
||||
setup_url = f"https://staging-portal.hivegrid.de/demo-pro-crm/setup/{TOKEN}"
|
||||
|
||||
self.assertIsNone(match_delivered_message(config(), query, message(query.recipient, setup_url), NOW - timedelta(seconds=6), now=NOW))
|
||||
self.assertIsNone(match_delivered_message(config(), query, message(query.recipient, setup_url, "Unrelated mail"), NOW, now=NOW))
|
||||
self.assertIsNone(
|
||||
match_delivered_message(
|
||||
config(),
|
||||
query,
|
||||
message(query.recipient, f"https://evil.example.test/demo-pro-crm/setup/{TOKEN}"),
|
||||
NOW,
|
||||
now=NOW,
|
||||
)
|
||||
)
|
||||
|
||||
def test_setup_url_contract_rejects_queries_fragments_and_invalid_tokens(self) -> None:
|
||||
origin = "https://staging-portal.hivegrid.de"
|
||||
base = f"{origin}/demo-pro-crm/setup/{TOKEN}"
|
||||
|
||||
self.assertEqual(normalize_setup_url(base, origin, "demo-pro-crm"), base)
|
||||
self.assertIsNone(normalize_setup_url(f"{base}?next=1", origin, "demo-pro-crm"))
|
||||
self.assertIsNone(normalize_setup_url(f"{base}#fragment", origin, "demo-pro-crm"))
|
||||
self.assertIsNone(normalize_setup_url(f"{origin}/demo-pro-crm/setup/short", origin, "demo-pro-crm"))
|
||||
|
||||
def test_tracking_wrappers_remain_fail_closed(self) -> None:
|
||||
query = parse_mail_query(payload(), MAILBOX_EMAIL, now=NOW)
|
||||
setup_url = f"https://staging-portal.hivegrid.de/demo-pro-crm/setup/{TOKEN}"
|
||||
tracking_urls = (
|
||||
f"https://tracking.example.test/redirect/{TOKEN}",
|
||||
f"https://tracking.example.test/redirect?target={quote(setup_url, safe='')}",
|
||||
)
|
||||
|
||||
for tracking_url in tracking_urls:
|
||||
with self.subTest(tracking_url=tracking_url):
|
||||
self.assertIsNone(normalize_setup_url(tracking_url, config().portal_origin, config().tenant_slug))
|
||||
self.assertIsNone(match_delivered_message(config(), query, message(query.recipient, tracking_url), NOW, now=NOW))
|
||||
|
||||
def test_rejects_plain_direct_setup_with_tracking_wrapped_html_cta(self) -> None:
|
||||
query = parse_mail_query(payload(), MAILBOX_EMAIL, now=NOW)
|
||||
setup_url = f"https://staging-portal.hivegrid.de/demo-pro-crm/setup/{TOKEN}"
|
||||
tracking_url = f"https://tracking.example.test/redirect/{TOKEN}"
|
||||
|
||||
self.assertIsNone(
|
||||
match_delivered_message(
|
||||
config(),
|
||||
query,
|
||||
message(query.recipient, setup_url, html_url=tracking_url),
|
||||
NOW,
|
||||
now=NOW,
|
||||
)
|
||||
)
|
||||
|
||||
def test_rejects_html_cta_that_requires_character_reference_decoding(self) -> None:
|
||||
query = parse_mail_query(payload(), MAILBOX_EMAIL, now=NOW)
|
||||
setup_url = f"https://staging-portal.hivegrid.de/demo-pro-crm/setup/{TOKEN}"
|
||||
encoded_html_url = f"{setup_url[:-1]}s"
|
||||
|
||||
self.assertIsNone(
|
||||
match_delivered_message(
|
||||
config(),
|
||||
query,
|
||||
message(query.recipient, setup_url, html_url=encoded_html_url),
|
||||
NOW,
|
||||
now=NOW,
|
||||
)
|
||||
)
|
||||
|
||||
def test_mailbox_base_and_derived_recipient_fail_closed_on_rfc_limits(self) -> None:
|
||||
base_env = {
|
||||
"PORTAL_SETUP_MAIL_IMAP_HOST": "imap.example.test",
|
||||
"MAILBOX_EMAIL": MAILBOX_EMAIL,
|
||||
"MAILBOX_APP_PASSWORD": "not-used-by-unit-tests",
|
||||
"E2E_PORTAL_BASE_URL": "https://staging-portal.hivegrid.de",
|
||||
"E2E_PORTAL_TENANT_SLUG": "demo-pro-crm",
|
||||
}
|
||||
for invalid in (
|
||||
".fixture@example.test",
|
||||
"fixture@example..test",
|
||||
"fixture@-example.test",
|
||||
"fixture+existing@example.test",
|
||||
"fixture@localhost",
|
||||
f"{'a' * 65}@example.test",
|
||||
"fixture@exämple.test",
|
||||
):
|
||||
with self.subTest(invalid=invalid), self.assertRaises(ConfigurationError):
|
||||
load_config({**base_env, "MAILBOX_EMAIL": invalid})
|
||||
|
||||
too_long = payload()
|
||||
with self.assertRaises(ContractError):
|
||||
parse_mail_query(too_long, f"{'a' * 40}@example.test", now=NOW)
|
||||
|
||||
def test_custom_portal_origin_config_is_optional_and_exact(self) -> None:
|
||||
base_env = {
|
||||
"PORTAL_SETUP_MAIL_IMAP_HOST": "imap.example.test",
|
||||
"MAILBOX_EMAIL": MAILBOX_EMAIL,
|
||||
"MAILBOX_APP_PASSWORD": "not-used-by-unit-tests",
|
||||
"E2E_PORTAL_BASE_URL": "https://staging-portal.hivegrid.de",
|
||||
"E2E_PORTAL_TENANT_SLUG": "demo-pro-crm",
|
||||
}
|
||||
|
||||
self.assertIsNone(load_config(base_env).custom_portal_origin)
|
||||
self.assertEqual(
|
||||
load_config({**base_env, "E2E_PORTAL_CUSTOM_DOMAIN_BASE_URL": "https://portal.customer.example.test"}).custom_portal_origin,
|
||||
"https://portal.customer.example.test",
|
||||
)
|
||||
for invalid in (
|
||||
"http://portal.customer.example.test",
|
||||
"https://portal.customer.example.test/path",
|
||||
"https://portal.customer.example.test?next=1",
|
||||
"https://portal.customer.example.test#fragment",
|
||||
"https://user:password@portal.customer.example.test",
|
||||
):
|
||||
with self.subTest(invalid=invalid), self.assertRaises(ConfigurationError):
|
||||
load_config({**base_env, "E2E_PORTAL_CUSTOM_DOMAIN_BASE_URL": invalid})
|
||||
|
||||
def test_http_contract_consumes_a_correlation_once_across_delivery_boundaries(self) -> None:
|
||||
server, thread = self.start_server()
|
||||
self.addCleanup(self.stop_server, server, thread)
|
||||
first = payload()
|
||||
first["deliveredAfter"] = datetime.now(UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
||||
second = {
|
||||
**first,
|
||||
"deliveredAfter": (datetime.now(UTC) + timedelta(milliseconds=1))
|
||||
.isoformat(timespec="milliseconds")
|
||||
.replace("+00:00", "Z"),
|
||||
}
|
||||
setup_url = f"https://staging-portal.hivegrid.de/demo-pro-crm/setup/{TOKEN}"
|
||||
|
||||
with patch(
|
||||
"portal_setup_mail_adapter.find_delivered_mail",
|
||||
return_value=DeliveredMail(delivered_at=datetime.now(UTC), setup_url=setup_url),
|
||||
) as lookup:
|
||||
first_status, _ = self.request(server, first)
|
||||
second_status, _ = self.request(server, second)
|
||||
|
||||
self.assertEqual(first_status, 200)
|
||||
self.assertEqual(second_status, 410)
|
||||
lookup.assert_called_once()
|
||||
|
||||
def test_http_contract_rejects_present_empty_or_nonempty_authorization(self) -> None:
|
||||
server, thread = self.start_server()
|
||||
self.addCleanup(self.stop_server, server, thread)
|
||||
current = payload()
|
||||
current["deliveredAfter"] = datetime.now(UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
||||
|
||||
with patch("portal_setup_mail_adapter.find_delivered_mail") as lookup:
|
||||
blank_status, _ = self.request(server, current, authorization="")
|
||||
bearer_status, _ = self.request(server, current, authorization="Bearer forbidden")
|
||||
|
||||
self.assertEqual(blank_status, 401)
|
||||
self.assertEqual(bearer_status, 401)
|
||||
lookup.assert_not_called()
|
||||
|
||||
@staticmethod
|
||||
def start_server() -> tuple[ThreadingHTTPServer, Thread]:
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), make_handler(config()))
|
||||
thread = Thread(target=server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True)
|
||||
thread.start()
|
||||
return server, thread
|
||||
|
||||
@staticmethod
|
||||
def stop_server(server: ThreadingHTTPServer, thread: Thread) -> None:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join(timeout=1)
|
||||
|
||||
@staticmethod
|
||||
def request(server: ThreadingHTTPServer, body: dict[str, str], authorization: str | None = None) -> tuple[int, bytes]:
|
||||
encoded = json.dumps(body).encode("utf-8")
|
||||
connection = HTTPConnection("127.0.0.1", server.server_port, timeout=2)
|
||||
connection.putrequest("POST", "/setup-mail")
|
||||
connection.putheader("Content-Type", "application/json")
|
||||
connection.putheader("Content-Length", str(len(encoded)))
|
||||
if authorization is not None:
|
||||
connection.putheader("Authorization", authorization)
|
||||
connection.endheaders(encoded)
|
||||
response = connection.getresponse()
|
||||
response_body = response.read()
|
||||
connection.close()
|
||||
return response.status, response_body
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+284
@@ -0,0 +1,284 @@
|
||||
// @vitest-environment node
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
import { publishAuditEventViaOutbox } from "@hivegrid/db/audit-events.server";
|
||||
import type { DbClient } from "@hivegrid/db/client.server";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { CUSTOMER_PORTAL_UAT_PROJECT_ID, CUSTOMER_PORTAL_UAT_TENANT_SLUG } from "./contracts";
|
||||
import {
|
||||
applyProjectInvitationContact,
|
||||
assessProjectInvitationContact,
|
||||
parseProjectInvitationContactInput,
|
||||
projectInvitationContactIds,
|
||||
type ProjectInvitationContactCommand,
|
||||
type ProjectInvitationContactSnapshot,
|
||||
} from "./project-invitation-contact";
|
||||
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({ publishAuditEventViaOutbox: vi.fn(async () => undefined) }));
|
||||
|
||||
const tenantId = "tenant-demo-pro";
|
||||
const correlationKey = "p26a-project-20260720t120000z-42";
|
||||
const mailboxEmail = "fixture@example.test";
|
||||
const email = `fixture+${correlationKey}@example.test`;
|
||||
|
||||
function command(mode: ProjectInvitationContactCommand["mode"] = "apply"): ProjectInvitationContactCommand {
|
||||
return {
|
||||
target: "fixture",
|
||||
mode,
|
||||
databaseUrl: "postgresql://hivegrid_app:redacted@127.0.0.1:6432/hivegrid_staging",
|
||||
expectedDatabaseHost: "127.0.0.1",
|
||||
expectedDatabasePort: "6432",
|
||||
expectedDatabaseName: "hivegrid_staging",
|
||||
operatorUserId: "operator-user-id",
|
||||
auditChainSecret: "redacted-audit-chain-secret-at-least-32-bytes",
|
||||
expectedTenantId: tenantId,
|
||||
password: "redacted-strong-fixture-password",
|
||||
correlationKey,
|
||||
email,
|
||||
};
|
||||
}
|
||||
|
||||
function healthySnapshot(): ProjectInvitationContactSnapshot {
|
||||
const ids = projectInvitationContactIds(tenantId, correlationKey);
|
||||
const suffix = ids.kontaktId.slice(-12).toUpperCase();
|
||||
return {
|
||||
tenant: { id: tenantId, slug: CUSTOMER_PORTAL_UAT_TENANT_SLUG, active: true },
|
||||
project: {
|
||||
id: CUSTOMER_PORTAL_UAT_PROJECT_ID,
|
||||
tenantId,
|
||||
projekttyp: "sales",
|
||||
archivedAt: null,
|
||||
pipeline: { id: "pipeline-sales", tenantId, archivedAt: null },
|
||||
stage: { id: "stage-open", tenantId, pipelineId: "pipeline-sales", archivedAt: null },
|
||||
},
|
||||
portal: { id: "portal-demo-pro", tenantId, isPublished: true },
|
||||
configuration: { portalId: "portal-demo-pro", tenantId, enabledProjectTypes: ["sales"] },
|
||||
stageVisibility: { portalId: "portal-demo-pro", tenantId, stageId: "stage-open", visible: true },
|
||||
ownerMembership: {
|
||||
tenantId,
|
||||
userId: "customer-portal-uat-tenant-admin",
|
||||
joined: 1,
|
||||
status: 2,
|
||||
user: {
|
||||
id: "customer-portal-uat-tenant-admin",
|
||||
active: true,
|
||||
pendingDeletion: false,
|
||||
pseudonymized: false,
|
||||
},
|
||||
},
|
||||
contacts: [
|
||||
{
|
||||
id: ids.kontaktId,
|
||||
tenantId,
|
||||
createdByUserId: "customer-portal-uat-tenant-admin",
|
||||
kontaktTyp: "privatperson",
|
||||
kontaktStatus: "kontakt",
|
||||
vorname: "Portal",
|
||||
nachname: `Project-${suffix}`,
|
||||
primaerEmail: email,
|
||||
zustaendigerUserId: "customer-portal-uat-tenant-admin",
|
||||
isDemoData: true,
|
||||
archivedAt: null,
|
||||
},
|
||||
],
|
||||
emails: [{ id: ids.kontaktEmailId, tenantId, kontaktId: ids.kontaktId, email, primaer: true }],
|
||||
projectContacts: [
|
||||
{
|
||||
id: ids.projektKontaktId,
|
||||
tenantId,
|
||||
projektId: CUSTOMER_PORTAL_UAT_PROJECT_ID,
|
||||
kontaktId: ids.kontaktId,
|
||||
rolle: "ansprechpartner",
|
||||
primaer: false,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
describe("VA-P26a project invitation contact fixture", () => {
|
||||
it("binds the existing invitation inputs to the dedicated project namespace", () => {
|
||||
expect(
|
||||
parseProjectInvitationContactInput({
|
||||
E2E_PORTAL_INVITATION_ENTRYPOINT: "project",
|
||||
E2E_PORTAL_SETUP_MAIL_FIXTURE_KEY: correlationKey,
|
||||
E2E_PORTAL_INVITATION_EMAIL: email,
|
||||
MAILBOX_EMAIL: mailboxEmail,
|
||||
})
|
||||
).toEqual({ correlationKey, email });
|
||||
expect(() =>
|
||||
parseProjectInvitationContactInput({
|
||||
E2E_PORTAL_INVITATION_ENTRYPOINT: "contact",
|
||||
E2E_PORTAL_SETUP_MAIL_FIXTURE_KEY: correlationKey,
|
||||
E2E_PORTAL_INVITATION_EMAIL: email,
|
||||
MAILBOX_EMAIL: mailboxEmail,
|
||||
})
|
||||
).toThrow("requires the project entrypoint");
|
||||
expect(() =>
|
||||
parseProjectInvitationContactInput({
|
||||
E2E_PORTAL_INVITATION_ENTRYPOINT: "project",
|
||||
E2E_PORTAL_SETUP_MAIL_FIXTURE_KEY: "p26a-project-UPPERCASE",
|
||||
E2E_PORTAL_INVITATION_EMAIL: "fixture+p26a-project-uppercase@example.test",
|
||||
MAILBOX_EMAIL: mailboxEmail,
|
||||
})
|
||||
).toThrow("outside the dedicated P26a project namespace");
|
||||
for (const invalidCorrelationKey of [
|
||||
"p26a-project-with.dot",
|
||||
"p26a-project-with_underscore",
|
||||
"p26a-project-with:colon",
|
||||
`p26a-project-${"a".repeat(84)}`,
|
||||
]) {
|
||||
expect(() =>
|
||||
parseProjectInvitationContactInput({
|
||||
E2E_PORTAL_INVITATION_ENTRYPOINT: "project",
|
||||
E2E_PORTAL_SETUP_MAIL_FIXTURE_KEY: invalidCorrelationKey,
|
||||
E2E_PORTAL_INVITATION_EMAIL: `fixture+${invalidCorrelationKey}@example.test`,
|
||||
MAILBOX_EMAIL: mailboxEmail,
|
||||
})
|
||||
).toThrow("outside the dedicated P26a project namespace");
|
||||
}
|
||||
expect(() =>
|
||||
parseProjectInvitationContactInput({
|
||||
E2E_PORTAL_INVITATION_ENTRYPOINT: "project",
|
||||
E2E_PORTAL_SETUP_MAIL_FIXTURE_KEY: correlationKey,
|
||||
E2E_PORTAL_INVITATION_EMAIL: "fixture+different@example.test",
|
||||
MAILBOX_EMAIL: mailboxEmail,
|
||||
})
|
||||
).toThrow("does not match its fixture key");
|
||||
});
|
||||
|
||||
it("rejects invalid authenticated mailbox bases without exposing them", () => {
|
||||
for (const invalidMailboxEmail of ["fixture+existing@example.test", "fixture@localhost", ".fixture@example.test", "fixture@-example.test"]) {
|
||||
expect(() =>
|
||||
parseProjectInvitationContactInput({
|
||||
E2E_PORTAL_INVITATION_ENTRYPOINT: "project",
|
||||
E2E_PORTAL_SETUP_MAIL_FIXTURE_KEY: correlationKey,
|
||||
E2E_PORTAL_INVITATION_EMAIL: email,
|
||||
MAILBOX_EMAIL: invalidMailboxEmail,
|
||||
})
|
||||
).toThrow("MAILBOX_EMAIL is invalid");
|
||||
}
|
||||
});
|
||||
|
||||
it("derives all row ids from the tenant, project, and correlation key", () => {
|
||||
const digest = createHash("sha256").update(`${tenantId}:${CUSTOMER_PORTAL_UAT_PROJECT_ID}:${correlationKey}`).digest("hex");
|
||||
expect(projectInvitationContactIds(tenantId, correlationKey)).toEqual({
|
||||
kontaktId: `customer-portal-uat-project-kontakt-${digest}`,
|
||||
kontaktEmailId: `customer-portal-uat-project-email-${digest}`,
|
||||
projektKontaktId: `customer-portal-uat-project-link-${digest}`,
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts only the complete UAT-owned rows and emits a redacted handoff", () => {
|
||||
const assessment = assessProjectInvitationContact(healthySnapshot(), command("verify"));
|
||||
expect(assessment).toMatchObject({ action: "noop", reconcileIssues: [], blockingIssues: [] });
|
||||
expect(assessment.handoff).toEqual({
|
||||
projectPath: `/${CUSTOMER_PORTAL_UAT_TENANT_SLUG}/projects/${CUSTOMER_PORTAL_UAT_PROJECT_ID}`,
|
||||
projectContactRowId: projectInvitationContactIds(tenantId, correlationKey).projektKontaktId,
|
||||
});
|
||||
const handoffJson = JSON.stringify(assessment.handoff);
|
||||
expect(handoffJson).not.toContain(email);
|
||||
expect(handoffJson).not.toContain(correlationKey);
|
||||
expect(handoffJson).not.toContain("Project-");
|
||||
});
|
||||
|
||||
it("reconciles missing rows but blocks recipient and ownership collisions", () => {
|
||||
const healthy = healthySnapshot();
|
||||
expect(assessProjectInvitationContact({ ...healthy, contacts: [], emails: [], projectContacts: [] }, command()).action).toBe("reconcile");
|
||||
|
||||
const hiddenProject = assessProjectInvitationContact({ ...healthy, stageVisibility: { ...healthy.stageVisibility!, visible: false } }, command());
|
||||
expect(hiddenProject.action).toBe("blocked");
|
||||
expect(hiddenProject.blockingIssues).toContain("deterministic UAT project is not visible through the published target portal");
|
||||
|
||||
const foreignContact = {
|
||||
...healthy.contacts[0]!,
|
||||
id: "foreign-contact",
|
||||
createdByUserId: "another-user",
|
||||
isDemoData: false,
|
||||
};
|
||||
const collision = assessProjectInvitationContact({ ...healthy, contacts: [...healthy.contacts, foreignContact] }, command());
|
||||
expect(collision.action).toBe("blocked");
|
||||
expect(collision.blockingIssues).toContain("invitation recipient collides with another CRM contact");
|
||||
expect(collision.handoff).toBeNull();
|
||||
|
||||
const foreignOwner = assessProjectInvitationContact({ ...healthy, contacts: [{ ...healthy.contacts[0]!, createdByUserId: "another-user" }] }, command());
|
||||
expect(foreignOwner.action).toBe("blocked");
|
||||
expect(foreignOwner.blockingIssues).toContain("deterministic CRM contact id is not owned by the VA-P26a fixture");
|
||||
});
|
||||
|
||||
it("locks and revalidates before typed writes and appends a redacted audit outbox event", async () => {
|
||||
const missingSnapshot = { ...healthySnapshot(), contacts: [], emails: [], projectContacts: [] };
|
||||
const ids = projectInvitationContactIds(tenantId, correlationKey);
|
||||
const queryRaw = vi.fn().mockResolvedValue([]);
|
||||
queryRaw.mockResolvedValueOnce([{ id: tenantId }]);
|
||||
const kontaktUpsert = vi.fn(async () => ({ id: ids.kontaktId }));
|
||||
const emailUpsert = vi.fn(async () => ({ id: ids.kontaktEmailId }));
|
||||
const projectContactUpsert = vi.fn(async () => ({ id: ids.projektKontaktId }));
|
||||
const tx = {
|
||||
$queryRaw: queryRaw,
|
||||
tenant: { findFirst: vi.fn(async () => missingSnapshot.tenant) },
|
||||
projekt: { findFirst: vi.fn(async () => missingSnapshot.project) },
|
||||
portal: { findFirst: vi.fn(async () => missingSnapshot.portal) },
|
||||
portalConfiguration: { findFirst: vi.fn(async () => missingSnapshot.configuration) },
|
||||
portalStageVisibility: { findFirst: vi.fn(async () => missingSnapshot.stageVisibility) },
|
||||
tenantUser: { findFirst: vi.fn(async () => missingSnapshot.ownerMembership) },
|
||||
kontakt: { findMany: vi.fn(async () => []), upsert: kontaktUpsert },
|
||||
kontaktEmail: { findMany: vi.fn(async () => []), upsert: emailUpsert },
|
||||
projektKontakt: { findMany: vi.fn(async () => []), upsert: projectContactUpsert },
|
||||
};
|
||||
const db = {
|
||||
$transaction: vi.fn(async (operation: (client: typeof tx) => Promise<void>) => operation(tx)),
|
||||
} as unknown as DbClient;
|
||||
|
||||
await applyProjectInvitationContact(db, command(), missingSnapshot);
|
||||
|
||||
expect(queryRaw).toHaveBeenCalledTimes(12);
|
||||
expect(kontaktUpsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { id: ids.kontaktId },
|
||||
create: expect.objectContaining({
|
||||
kontaktTyp: "privatperson",
|
||||
primaerEmail: email,
|
||||
zustaendigerUserId: "customer-portal-uat-tenant-admin",
|
||||
isDemoData: true,
|
||||
}),
|
||||
})
|
||||
);
|
||||
expect(emailUpsert).toHaveBeenCalledWith(expect.objectContaining({ create: expect.objectContaining({ kontaktId: ids.kontaktId, email, primaer: true }) }));
|
||||
expect(projectContactUpsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
create: expect.objectContaining({
|
||||
projektId: CUSTOMER_PORTAL_UAT_PROJECT_ID,
|
||||
kontaktId: ids.kontaktId,
|
||||
rolle: "ansprechpartner",
|
||||
primaer: false,
|
||||
}),
|
||||
})
|
||||
);
|
||||
expect(publishAuditEventViaOutbox).toHaveBeenCalledTimes(1);
|
||||
const auditInput = vi.mocked(publishAuditEventViaOutbox).mock.calls[0]?.[1];
|
||||
expect(auditInput).toMatchObject({
|
||||
action: "customer_portal.uat_project_invitation_contact.provisioned",
|
||||
targetType: "ProjektKontakt",
|
||||
targetId: ids.projektKontaktId,
|
||||
});
|
||||
const auditJson = JSON.stringify(auditInput);
|
||||
expect(auditJson).not.toContain(email);
|
||||
expect(auditJson).not.toContain(correlationKey);
|
||||
});
|
||||
|
||||
it("keeps plan/apply/verify output limited to mode, completion, and handoff", () => {
|
||||
const coreSource = readFileSync(new URL("./project-invitation-contact.ts", import.meta.url), "utf8");
|
||||
const cliSource = readFileSync(new URL("./provision-project-invitation-contact.ts", import.meta.url), "utf8");
|
||||
expect(coreSource.match(/FOR UPDATE/gu)?.length).toBeGreaterThanOrEqual(10);
|
||||
expect(coreSource.match(/lower\(btrim\(/gu)?.length).toBeGreaterThanOrEqual(4);
|
||||
expect(coreSource).toContain("const lockedSnapshot = await readProjectInvitationContact(transactionDb, command)");
|
||||
expect(coreSource).toContain("satisfies Prisma.KontaktUncheckedCreateInput");
|
||||
expect(coreSource).toContain("publishAuditEventViaOutbox(tx");
|
||||
expect(cliSource).toContain("readonly handoff: ProjectInvitationContactHandoff | null");
|
||||
expect(cliSource).not.toContain("readonly assessment:");
|
||||
expect(cliSource).not.toContain("command.email");
|
||||
expect(cliSource).not.toContain("command.correlationKey");
|
||||
});
|
||||
});
|
||||
+584
@@ -0,0 +1,584 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { publishAuditEventViaOutbox } from "@hivegrid/db/audit-events.server";
|
||||
import type { DbClient } from "@hivegrid/db/client.server";
|
||||
import type { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
|
||||
import {
|
||||
CUSTOMER_PORTAL_UAT_PROJECT_ID,
|
||||
CUSTOMER_PORTAL_UAT_TENANT_SLUG,
|
||||
CustomerPortalUatError,
|
||||
type CustomerPortalFixtureCommand,
|
||||
type CustomerPortalUatEnvironment,
|
||||
} from "./contracts";
|
||||
|
||||
const UAT_ADMIN_USER_ID = "customer-portal-uat-tenant-admin";
|
||||
const UAT_PROJECT_KEY_PATTERN = /^p26a-project-[a-z0-9-]{1,83}$/u;
|
||||
const MAILBOX_LOCAL_PART_PATTERN = /^[A-Za-z0-9!#$%&'*\/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*\/=?^_`{|}~-]+)*$/u;
|
||||
const MAILBOX_DOMAIN_LABEL_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/u;
|
||||
const MAX_MAILBOX_ADDRESS_BYTES = 254;
|
||||
const MAX_MAILBOX_LOCAL_PART_BYTES = 64;
|
||||
const MAX_MAILBOX_DOMAIN_BYTES = 253;
|
||||
|
||||
export type ProjectInvitationContactInput = {
|
||||
readonly correlationKey: string;
|
||||
readonly email: string;
|
||||
};
|
||||
|
||||
export type ProjectInvitationContactCommand = CustomerPortalFixtureCommand & ProjectInvitationContactInput;
|
||||
|
||||
export type ProjectInvitationContactIds = {
|
||||
readonly kontaktId: string;
|
||||
readonly kontaktEmailId: string;
|
||||
readonly projektKontaktId: string;
|
||||
};
|
||||
|
||||
export type ProjectInvitationContactSnapshot = {
|
||||
readonly tenant: { readonly id: string; readonly slug: string; readonly active: boolean } | null;
|
||||
readonly project: {
|
||||
readonly id: string;
|
||||
readonly tenantId: string;
|
||||
readonly projekttyp: string | null;
|
||||
readonly archivedAt: Date | null;
|
||||
readonly pipeline: { readonly id: string; readonly tenantId: string; readonly archivedAt: Date | null };
|
||||
readonly stage: {
|
||||
readonly id: string;
|
||||
readonly tenantId: string;
|
||||
readonly pipelineId: string;
|
||||
readonly archivedAt: Date | null;
|
||||
};
|
||||
} | null;
|
||||
readonly portal: { readonly id: string; readonly tenantId: string; readonly isPublished: boolean } | null;
|
||||
readonly configuration: {
|
||||
readonly portalId: string;
|
||||
readonly tenantId: string;
|
||||
readonly enabledProjectTypes: readonly string[];
|
||||
} | null;
|
||||
readonly stageVisibility: {
|
||||
readonly portalId: string;
|
||||
readonly tenantId: string;
|
||||
readonly stageId: string;
|
||||
readonly visible: boolean;
|
||||
} | null;
|
||||
readonly ownerMembership: {
|
||||
readonly tenantId: string;
|
||||
readonly userId: string;
|
||||
readonly joined: number;
|
||||
readonly status: number;
|
||||
readonly user: {
|
||||
readonly id: string;
|
||||
readonly active: boolean;
|
||||
readonly pendingDeletion: boolean;
|
||||
readonly pseudonymized: boolean;
|
||||
};
|
||||
} | null;
|
||||
readonly contacts: readonly {
|
||||
readonly id: string;
|
||||
readonly tenantId: string;
|
||||
readonly createdByUserId: string;
|
||||
readonly kontaktTyp: string;
|
||||
readonly kontaktStatus: string;
|
||||
readonly vorname: string | null;
|
||||
readonly nachname: string | null;
|
||||
readonly primaerEmail: string | null;
|
||||
readonly zustaendigerUserId: string | null;
|
||||
readonly isDemoData: boolean;
|
||||
readonly archivedAt: Date | null;
|
||||
}[];
|
||||
readonly emails: readonly {
|
||||
readonly id: string;
|
||||
readonly tenantId: string;
|
||||
readonly kontaktId: string;
|
||||
readonly email: string;
|
||||
readonly primaer: boolean;
|
||||
}[];
|
||||
readonly projectContacts: readonly {
|
||||
readonly id: string;
|
||||
readonly tenantId: string;
|
||||
readonly projektId: string;
|
||||
readonly kontaktId: string;
|
||||
readonly rolle: string;
|
||||
readonly primaer: boolean;
|
||||
}[];
|
||||
};
|
||||
|
||||
export type ProjectInvitationContactHandoff = {
|
||||
readonly projectPath: string;
|
||||
readonly projectContactRowId: string;
|
||||
};
|
||||
|
||||
export type ProjectInvitationContactAssessment = {
|
||||
readonly action: "noop" | "reconcile" | "blocked";
|
||||
readonly reconcileIssues: readonly string[];
|
||||
readonly blockingIssues: readonly string[];
|
||||
readonly handoff: ProjectInvitationContactHandoff | null;
|
||||
};
|
||||
|
||||
type CanonicalProjectInvitationContact = {
|
||||
readonly ids: ProjectInvitationContactIds;
|
||||
readonly firstName: "Portal";
|
||||
readonly lastName: string;
|
||||
};
|
||||
|
||||
function requiredEnvironmentValue(env: CustomerPortalUatEnvironment, name: string): string {
|
||||
const value = env[name]?.trim();
|
||||
if (!value) throw new CustomerPortalUatError(`customer-portal UAT: ${name} is required for the project invitation fixture`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function parseMailboxBase(env: CustomerPortalUatEnvironment): { readonly localPart: string; readonly domain: string } {
|
||||
const raw = env.MAILBOX_EMAIL;
|
||||
if (!raw || raw !== raw.trim() || Buffer.byteLength(raw, "utf8") > MAX_MAILBOX_ADDRESS_BYTES || Buffer.byteLength(raw, "utf8") !== raw.length) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: MAILBOX_EMAIL is invalid for the project invitation fixture");
|
||||
}
|
||||
const parts = raw.split("@");
|
||||
if (parts.length !== 2) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: MAILBOX_EMAIL is invalid for the project invitation fixture");
|
||||
}
|
||||
const [localPart = "", domain = ""] = parts;
|
||||
const labels = domain.split(".");
|
||||
if (
|
||||
localPart.includes("+") ||
|
||||
!MAILBOX_LOCAL_PART_PATTERN.test(localPart) ||
|
||||
Buffer.byteLength(localPart, "ascii") > MAX_MAILBOX_LOCAL_PART_BYTES ||
|
||||
Buffer.byteLength(domain, "ascii") > MAX_MAILBOX_DOMAIN_BYTES ||
|
||||
labels.length < 2 ||
|
||||
labels.some((label) => Buffer.byteLength(label, "ascii") > 63 || !MAILBOX_DOMAIN_LABEL_PATTERN.test(label))
|
||||
) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: MAILBOX_EMAIL is invalid for the project invitation fixture");
|
||||
}
|
||||
return { localPart: localPart.toLocaleLowerCase("en-US"), domain: domain.toLocaleLowerCase("en-US") };
|
||||
}
|
||||
|
||||
export function parseProjectInvitationContactInput(env: CustomerPortalUatEnvironment): ProjectInvitationContactInput {
|
||||
if (requiredEnvironmentValue(env, "E2E_PORTAL_INVITATION_ENTRYPOINT") !== "project") {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: project invitation fixture requires the project entrypoint");
|
||||
}
|
||||
const correlationKey = requiredEnvironmentValue(env, "E2E_PORTAL_SETUP_MAIL_FIXTURE_KEY");
|
||||
if (!UAT_PROJECT_KEY_PATTERN.test(correlationKey)) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: project invitation fixture key is outside the dedicated P26a project namespace");
|
||||
}
|
||||
const mailbox = parseMailboxBase(env);
|
||||
const derivedLocalPart = `${mailbox.localPart}+${correlationKey}`;
|
||||
const expectedEmail = `${derivedLocalPart}@${mailbox.domain}`;
|
||||
if (Buffer.byteLength(derivedLocalPart, "ascii") > MAX_MAILBOX_LOCAL_PART_BYTES || Buffer.byteLength(expectedEmail, "ascii") > MAX_MAILBOX_ADDRESS_BYTES) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: project invitation recipient does not match its fixture key");
|
||||
}
|
||||
const rawEmail = requiredEnvironmentValue(env, "E2E_PORTAL_INVITATION_EMAIL");
|
||||
if (rawEmail !== env.E2E_PORTAL_INVITATION_EMAIL) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: project invitation recipient does not match its fixture key");
|
||||
}
|
||||
const email = rawEmail.toLocaleLowerCase("en-US");
|
||||
if (email !== expectedEmail) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: project invitation recipient does not match its fixture key");
|
||||
}
|
||||
return { correlationKey, email };
|
||||
}
|
||||
|
||||
export function projectInvitationContactIds(tenantId: string, correlationKey: string): ProjectInvitationContactIds {
|
||||
const digest = createHash("sha256").update(`${tenantId}:${CUSTOMER_PORTAL_UAT_PROJECT_ID}:${correlationKey}`).digest("hex");
|
||||
return {
|
||||
kontaktId: `customer-portal-uat-project-kontakt-${digest}`,
|
||||
kontaktEmailId: `customer-portal-uat-project-email-${digest}`,
|
||||
projektKontaktId: `customer-portal-uat-project-link-${digest}`,
|
||||
};
|
||||
}
|
||||
|
||||
function canonicalContact(command: ProjectInvitationContactCommand): CanonicalProjectInvitationContact {
|
||||
const ids = projectInvitationContactIds(command.expectedTenantId, command.correlationKey);
|
||||
const suffix = ids.kontaktId.slice(-12).toUpperCase();
|
||||
return { ids, firstName: "Portal", lastName: `Project-${suffix}` };
|
||||
}
|
||||
|
||||
function sameEmail(left: string | null, right: string): boolean {
|
||||
return left?.trim().toLocaleLowerCase("en-US") === right;
|
||||
}
|
||||
|
||||
export function assessProjectInvitationContact(
|
||||
snapshot: ProjectInvitationContactSnapshot,
|
||||
command: ProjectInvitationContactCommand
|
||||
): ProjectInvitationContactAssessment {
|
||||
const canonical = canonicalContact(command);
|
||||
const reconcileIssues: string[] = [];
|
||||
const blockingIssues: string[] = [];
|
||||
|
||||
if (
|
||||
!snapshot.tenant ||
|
||||
snapshot.tenant.id !== command.expectedTenantId ||
|
||||
snapshot.tenant.slug !== CUSTOMER_PORTAL_UAT_TENANT_SLUG ||
|
||||
!snapshot.tenant.active
|
||||
) {
|
||||
blockingIssues.push("target tenant is missing, inactive, or outside the explicit demo-pro-crm binding");
|
||||
}
|
||||
if (
|
||||
!snapshot.project ||
|
||||
snapshot.project.id !== CUSTOMER_PORTAL_UAT_PROJECT_ID ||
|
||||
snapshot.project.tenantId !== command.expectedTenantId ||
|
||||
snapshot.project.archivedAt !== null ||
|
||||
!snapshot.project.projekttyp ||
|
||||
snapshot.project.pipeline.tenantId !== command.expectedTenantId ||
|
||||
snapshot.project.pipeline.archivedAt !== null ||
|
||||
snapshot.project.stage.tenantId !== command.expectedTenantId ||
|
||||
snapshot.project.stage.pipelineId !== snapshot.project.pipeline.id ||
|
||||
snapshot.project.stage.archivedAt !== null
|
||||
) {
|
||||
blockingIssues.push("deterministic UAT project, stage, or pipeline is missing, archived, incomplete, or outside the target tenant");
|
||||
}
|
||||
if (
|
||||
!snapshot.portal ||
|
||||
snapshot.portal.tenantId !== command.expectedTenantId ||
|
||||
!snapshot.portal.isPublished ||
|
||||
!snapshot.configuration ||
|
||||
snapshot.configuration.tenantId !== command.expectedTenantId ||
|
||||
snapshot.configuration.portalId !== snapshot.portal.id ||
|
||||
!snapshot.project?.projekttyp ||
|
||||
!snapshot.configuration.enabledProjectTypes.includes(snapshot.project.projekttyp) ||
|
||||
!snapshot.stageVisibility ||
|
||||
snapshot.stageVisibility.tenantId !== command.expectedTenantId ||
|
||||
snapshot.stageVisibility.portalId !== snapshot.portal.id ||
|
||||
snapshot.stageVisibility.stageId !== snapshot.project.stage.id ||
|
||||
!snapshot.stageVisibility.visible
|
||||
) {
|
||||
blockingIssues.push("deterministic UAT project is not visible through the published target portal");
|
||||
}
|
||||
if (
|
||||
!snapshot.ownerMembership ||
|
||||
snapshot.ownerMembership.tenantId !== command.expectedTenantId ||
|
||||
snapshot.ownerMembership.userId !== UAT_ADMIN_USER_ID ||
|
||||
snapshot.ownerMembership.joined !== 1 ||
|
||||
snapshot.ownerMembership.status !== 2 ||
|
||||
snapshot.ownerMembership.user.id !== UAT_ADMIN_USER_ID ||
|
||||
!snapshot.ownerMembership.user.active ||
|
||||
snapshot.ownerMembership.user.pendingDeletion ||
|
||||
snapshot.ownerMembership.user.pseudonymized
|
||||
) {
|
||||
blockingIssues.push("dedicated UAT tenant admin is not an active target-tenant member");
|
||||
}
|
||||
|
||||
const contact = snapshot.contacts.find((candidate) => candidate.id === canonical.ids.kontaktId);
|
||||
const contactCollisions = snapshot.contacts.filter((candidate) => candidate.id !== canonical.ids.kontaktId);
|
||||
if (contactCollisions.length > 0) blockingIssues.push("invitation recipient collides with another CRM contact");
|
||||
if (contact && (!contact.isDemoData || contact.tenantId !== command.expectedTenantId || contact.createdByUserId !== UAT_ADMIN_USER_ID)) {
|
||||
blockingIssues.push("deterministic CRM contact id is not owned by the VA-P26a fixture");
|
||||
} else if (
|
||||
!contact ||
|
||||
contact.kontaktTyp !== "privatperson" ||
|
||||
contact.kontaktStatus !== "kontakt" ||
|
||||
contact.vorname !== canonical.firstName ||
|
||||
contact.nachname !== canonical.lastName ||
|
||||
!sameEmail(contact.primaerEmail, command.email) ||
|
||||
contact.zustaendigerUserId !== UAT_ADMIN_USER_ID ||
|
||||
contact.archivedAt !== null
|
||||
) {
|
||||
reconcileIssues.push("deterministic UAT CRM contact is missing or drifted");
|
||||
}
|
||||
|
||||
const email = snapshot.emails.find((candidate) => candidate.id === canonical.ids.kontaktEmailId);
|
||||
const emailCollisions = snapshot.emails.filter((candidate) => candidate.id !== canonical.ids.kontaktEmailId);
|
||||
if (emailCollisions.length > 0) blockingIssues.push("invitation recipient collides with another CRM email row");
|
||||
if (email && (email.tenantId !== command.expectedTenantId || email.kontaktId !== canonical.ids.kontaktId)) {
|
||||
blockingIssues.push("deterministic CRM email id belongs to another contact");
|
||||
} else if (!email || !sameEmail(email.email, command.email) || !email.primaer) {
|
||||
reconcileIssues.push("deterministic primary CRM email is missing or drifted");
|
||||
}
|
||||
|
||||
const projectContact = snapshot.projectContacts.find((candidate) => candidate.id === canonical.ids.projektKontaktId);
|
||||
const projectContactCollisions = snapshot.projectContacts.filter((candidate) => candidate.id !== canonical.ids.projektKontaktId);
|
||||
if (projectContactCollisions.length > 0) blockingIssues.push("project already has another matching contact assignment");
|
||||
if (
|
||||
projectContact &&
|
||||
(projectContact.tenantId !== command.expectedTenantId ||
|
||||
projectContact.projektId !== CUSTOMER_PORTAL_UAT_PROJECT_ID ||
|
||||
projectContact.kontaktId !== canonical.ids.kontaktId)
|
||||
) {
|
||||
blockingIssues.push("deterministic project-contact id belongs to another assignment");
|
||||
} else if (!projectContact || projectContact.rolle !== "ansprechpartner" || projectContact.primaer) {
|
||||
reconcileIssues.push("deterministic private project-contact assignment is missing or drifted");
|
||||
}
|
||||
|
||||
const action = blockingIssues.length > 0 ? "blocked" : reconcileIssues.length > 0 ? "reconcile" : "noop";
|
||||
return {
|
||||
action,
|
||||
reconcileIssues,
|
||||
blockingIssues,
|
||||
handoff:
|
||||
action === "noop"
|
||||
? {
|
||||
projectPath: `/${CUSTOMER_PORTAL_UAT_TENANT_SLUG}/projects/${CUSTOMER_PORTAL_UAT_PROJECT_ID}`,
|
||||
projectContactRowId: canonical.ids.projektKontaktId,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
export async function readProjectInvitationContact(db: DbClient, command: ProjectInvitationContactCommand): Promise<ProjectInvitationContactSnapshot> {
|
||||
const canonical = canonicalContact(command);
|
||||
const tenant = await db.tenant.findFirst({
|
||||
where: { id: command.expectedTenantId, slug: CUSTOMER_PORTAL_UAT_TENANT_SLUG },
|
||||
select: { id: true, slug: true, active: true },
|
||||
});
|
||||
const project = await db.projekt.findFirst({
|
||||
where: { id: CUSTOMER_PORTAL_UAT_PROJECT_ID, tenantId: command.expectedTenantId },
|
||||
select: {
|
||||
id: true,
|
||||
tenantId: true,
|
||||
projekttyp: true,
|
||||
archivedAt: true,
|
||||
pipeline: { select: { id: true, tenantId: true, archivedAt: true } },
|
||||
stage: { select: { id: true, tenantId: true, pipelineId: true, archivedAt: true } },
|
||||
},
|
||||
});
|
||||
const portal = await db.portal.findFirst({
|
||||
where: { tenantId: command.expectedTenantId },
|
||||
select: { id: true, tenantId: true, isPublished: true },
|
||||
});
|
||||
const configuration = await db.portalConfiguration.findFirst({
|
||||
where: { tenantId: command.expectedTenantId },
|
||||
select: { portalId: true, tenantId: true, enabledProjectTypes: true },
|
||||
});
|
||||
const stageVisibility = project
|
||||
? await db.portalStageVisibility.findFirst({
|
||||
where: { tenantId: command.expectedTenantId, stageId: project.stage.id },
|
||||
select: { portalId: true, tenantId: true, stageId: true, visible: true },
|
||||
})
|
||||
: null;
|
||||
const ownerMembership = await db.tenantUser.findFirst({
|
||||
where: { tenantId: command.expectedTenantId, userId: UAT_ADMIN_USER_ID },
|
||||
select: {
|
||||
tenantId: true,
|
||||
userId: true,
|
||||
joined: true,
|
||||
status: true,
|
||||
user: { select: { id: true, active: true, pendingDeletion: true, pseudonymized: true } },
|
||||
},
|
||||
});
|
||||
const contactMatches = await db.$queryRaw<Array<{ id: string }>>`
|
||||
SELECT contact."id"
|
||||
FROM "Kontakt" AS contact
|
||||
WHERE contact."tenantId" = ${command.expectedTenantId}
|
||||
AND (
|
||||
contact."id" = ${canonical.ids.kontaktId}
|
||||
OR lower(btrim(contact."primaerEmail")) = ${command.email}
|
||||
)
|
||||
`;
|
||||
const contacts = await db.kontakt.findMany({
|
||||
where: { tenantId: command.expectedTenantId, id: { in: contactMatches.map(({ id }) => id) } },
|
||||
select: {
|
||||
id: true,
|
||||
tenantId: true,
|
||||
createdByUserId: true,
|
||||
kontaktTyp: true,
|
||||
kontaktStatus: true,
|
||||
vorname: true,
|
||||
nachname: true,
|
||||
primaerEmail: true,
|
||||
zustaendigerUserId: true,
|
||||
isDemoData: true,
|
||||
archivedAt: true,
|
||||
},
|
||||
});
|
||||
const emailMatches = await db.$queryRaw<Array<{ id: string }>>`
|
||||
SELECT email."id"
|
||||
FROM "KontaktEmail" AS email
|
||||
WHERE email."tenantId" = ${command.expectedTenantId}
|
||||
AND (
|
||||
email."id" = ${canonical.ids.kontaktEmailId}
|
||||
OR email."kontaktId" = ${canonical.ids.kontaktId}
|
||||
OR lower(btrim(email."email")) = ${command.email}
|
||||
)
|
||||
`;
|
||||
const emails = await db.kontaktEmail.findMany({
|
||||
where: { tenantId: command.expectedTenantId, id: { in: emailMatches.map(({ id }) => id) } },
|
||||
select: { id: true, tenantId: true, kontaktId: true, email: true, primaer: true },
|
||||
});
|
||||
const projectContacts = await db.projektKontakt.findMany({
|
||||
where: {
|
||||
tenantId: command.expectedTenantId,
|
||||
OR: [{ id: canonical.ids.projektKontaktId }, { projektId: CUSTOMER_PORTAL_UAT_PROJECT_ID, kontaktId: canonical.ids.kontaktId }],
|
||||
},
|
||||
select: { id: true, tenantId: true, projektId: true, kontaktId: true, rolle: true, primaer: true },
|
||||
});
|
||||
return { tenant, project, portal, configuration, stageVisibility, ownerMembership, contacts, emails, projectContacts };
|
||||
}
|
||||
|
||||
async function lockProjectInvitationContactRows(db: DbClient, command: ProjectInvitationContactCommand): Promise<void> {
|
||||
const canonical = canonicalContact(command);
|
||||
const tenantLocks = await db.$queryRaw<Array<{ id: string }>>`
|
||||
SELECT tenant."id"
|
||||
FROM "Tenant" AS tenant
|
||||
WHERE tenant."id" = ${command.expectedTenantId}
|
||||
AND tenant."slug" = ${CUSTOMER_PORTAL_UAT_TENANT_SLUG}
|
||||
FOR UPDATE
|
||||
`;
|
||||
if (tenantLocks.length !== 1) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: target tenant changed after guarded project-contact preflight");
|
||||
}
|
||||
await db.$queryRaw`
|
||||
SELECT project."id"
|
||||
FROM "Projekt" AS project
|
||||
WHERE project."id" = ${CUSTOMER_PORTAL_UAT_PROJECT_ID}
|
||||
AND project."tenantId" = ${command.expectedTenantId}
|
||||
FOR UPDATE
|
||||
`;
|
||||
await db.$queryRaw`
|
||||
SELECT portal."id"
|
||||
FROM "Portal" AS portal
|
||||
WHERE portal."tenantId" = ${command.expectedTenantId}
|
||||
FOR UPDATE
|
||||
`;
|
||||
await db.$queryRaw`
|
||||
SELECT configuration."id"
|
||||
FROM "PortalConfiguration" AS configuration
|
||||
WHERE configuration."tenantId" = ${command.expectedTenantId}
|
||||
FOR UPDATE
|
||||
`;
|
||||
await db.$queryRaw`
|
||||
SELECT visibility."id"
|
||||
FROM "PortalStageVisibility" AS visibility
|
||||
JOIN "Projekt" AS project
|
||||
ON project."tenantId" = visibility."tenantId"
|
||||
AND project."stageId" = visibility."stageId"
|
||||
WHERE project."id" = ${CUSTOMER_PORTAL_UAT_PROJECT_ID}
|
||||
AND project."tenantId" = ${command.expectedTenantId}
|
||||
FOR UPDATE OF visibility
|
||||
`;
|
||||
await db.$queryRaw`
|
||||
SELECT uat_user."id"
|
||||
FROM "User" AS uat_user
|
||||
WHERE uat_user."id" = ${UAT_ADMIN_USER_ID}
|
||||
FOR UPDATE
|
||||
`;
|
||||
await db.$queryRaw`
|
||||
SELECT membership."id"
|
||||
FROM "TenantUser" AS membership
|
||||
WHERE membership."tenantId" = ${command.expectedTenantId}
|
||||
AND membership."userId" = ${UAT_ADMIN_USER_ID}
|
||||
FOR UPDATE
|
||||
`;
|
||||
await db.$queryRaw`
|
||||
SELECT contact."id"
|
||||
FROM "Kontakt" AS contact
|
||||
WHERE contact."tenantId" = ${command.expectedTenantId}
|
||||
AND (
|
||||
contact."id" = ${canonical.ids.kontaktId}
|
||||
OR lower(btrim(contact."primaerEmail")) = ${command.email}
|
||||
)
|
||||
FOR UPDATE
|
||||
`;
|
||||
await db.$queryRaw`
|
||||
SELECT email."id"
|
||||
FROM "KontaktEmail" AS email
|
||||
WHERE email."tenantId" = ${command.expectedTenantId}
|
||||
AND (
|
||||
email."id" = ${canonical.ids.kontaktEmailId}
|
||||
OR email."kontaktId" = ${canonical.ids.kontaktId}
|
||||
OR lower(btrim(email."email")) = ${command.email}
|
||||
)
|
||||
FOR UPDATE
|
||||
`;
|
||||
await db.$queryRaw`
|
||||
SELECT project_contact."id"
|
||||
FROM "ProjektKontakt" AS project_contact
|
||||
WHERE project_contact."tenantId" = ${command.expectedTenantId}
|
||||
AND (
|
||||
project_contact."id" = ${canonical.ids.projektKontaktId}
|
||||
OR (
|
||||
project_contact."projektId" = ${CUSTOMER_PORTAL_UAT_PROJECT_ID}
|
||||
AND project_contact."kontaktId" = ${canonical.ids.kontaktId}
|
||||
)
|
||||
)
|
||||
FOR UPDATE
|
||||
`;
|
||||
}
|
||||
|
||||
export async function applyProjectInvitationContact(
|
||||
db: DbClient,
|
||||
command: ProjectInvitationContactCommand,
|
||||
snapshot: ProjectInvitationContactSnapshot
|
||||
): Promise<void> {
|
||||
const assessment = assessProjectInvitationContact(snapshot, command);
|
||||
if (assessment.action === "blocked") {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: project invitation contact apply is blocked by unsafe or non-UAT state");
|
||||
}
|
||||
if (assessment.action === "noop") return;
|
||||
|
||||
await db.$transaction(async (tx) => {
|
||||
const transactionDb = tx as unknown as DbClient;
|
||||
await lockProjectInvitationContactRows(transactionDb, command);
|
||||
const lockedSnapshot = await readProjectInvitationContact(transactionDb, command);
|
||||
const lockedAssessment = assessProjectInvitationContact(lockedSnapshot, command);
|
||||
if (lockedAssessment.action === "blocked") {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: project invitation contact ownership changed after guarded preflight");
|
||||
}
|
||||
if (lockedAssessment.action === "noop") return;
|
||||
|
||||
const canonical = canonicalContact(command);
|
||||
const contactCreate = {
|
||||
id: canonical.ids.kontaktId,
|
||||
tenantId: command.expectedTenantId,
|
||||
createdByUserId: UAT_ADMIN_USER_ID,
|
||||
kontaktTyp: "privatperson",
|
||||
kontaktStatus: "kontakt",
|
||||
vorname: canonical.firstName,
|
||||
nachname: canonical.lastName,
|
||||
primaerEmail: command.email,
|
||||
zustaendigerUserId: UAT_ADMIN_USER_ID,
|
||||
isDemoData: true,
|
||||
} satisfies Prisma.KontaktUncheckedCreateInput;
|
||||
const contactUpdate = {
|
||||
kontaktTyp: "privatperson",
|
||||
kontaktStatus: "kontakt",
|
||||
vorname: canonical.firstName,
|
||||
nachname: canonical.lastName,
|
||||
orgName: null,
|
||||
orgMerkmal: null,
|
||||
primaerEmail: command.email,
|
||||
zustaendigerUserId: UAT_ADMIN_USER_ID,
|
||||
isDemoData: true,
|
||||
archivedAt: null,
|
||||
} satisfies Prisma.KontaktUncheckedUpdateInput;
|
||||
await tx.kontakt.upsert({ where: { id: canonical.ids.kontaktId }, create: contactCreate, update: contactUpdate });
|
||||
|
||||
const emailCreate = {
|
||||
id: canonical.ids.kontaktEmailId,
|
||||
tenantId: command.expectedTenantId,
|
||||
kontaktId: canonical.ids.kontaktId,
|
||||
email: command.email,
|
||||
primaer: true,
|
||||
} satisfies Prisma.KontaktEmailUncheckedCreateInput;
|
||||
const emailUpdate = { email: command.email, primaer: true } satisfies Prisma.KontaktEmailUncheckedUpdateInput;
|
||||
await tx.kontaktEmail.upsert({ where: { id: canonical.ids.kontaktEmailId }, create: emailCreate, update: emailUpdate });
|
||||
|
||||
const projectContactCreate = {
|
||||
id: canonical.ids.projektKontaktId,
|
||||
tenantId: command.expectedTenantId,
|
||||
projektId: CUSTOMER_PORTAL_UAT_PROJECT_ID,
|
||||
kontaktId: canonical.ids.kontaktId,
|
||||
rolle: "ansprechpartner",
|
||||
primaer: false,
|
||||
} satisfies Prisma.ProjektKontaktUncheckedCreateInput;
|
||||
const projectContactUpdate = {
|
||||
rolle: "ansprechpartner",
|
||||
primaer: false,
|
||||
} satisfies Prisma.ProjektKontaktUncheckedUpdateInput;
|
||||
await tx.projektKontakt.upsert({
|
||||
where: { id: canonical.ids.projektKontaktId },
|
||||
create: projectContactCreate,
|
||||
update: projectContactUpdate,
|
||||
});
|
||||
|
||||
await publishAuditEventViaOutbox(tx, {
|
||||
tenantId: command.expectedTenantId,
|
||||
actorId: command.operatorUserId,
|
||||
actorType: "operator",
|
||||
action: "customer_portal.uat_project_invitation_contact.provisioned",
|
||||
targetType: "ProjektKontakt",
|
||||
targetId: canonical.ids.projektKontaktId,
|
||||
sourceModule: "customer-portal-uat",
|
||||
outcome: "success",
|
||||
dataSensitivity: "internal",
|
||||
regulatoryScope: ["none"],
|
||||
metadata: { tenantSlug: CUSTOMER_PORTAL_UAT_TENANT_SLUG, projectId: CUSTOMER_PORTAL_UAT_PROJECT_ID },
|
||||
});
|
||||
});
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { CustomerPortalCatalogPlan } from "./catalog";
|
||||
import { assessCatalogAuditRecovery, type CatalogAuditRecoveryRow } from "./provision-catalog";
|
||||
|
||||
function plan(providerAction: "create" | "update" | "noop" = "noop"): CustomerPortalCatalogPlan {
|
||||
return {
|
||||
provider: [
|
||||
{ resource: "plan", code: "customer_portal_monthly", action: providerAction, driftFields: [] },
|
||||
{ resource: "add_on", code: "customer_portal_domain_setup", action: "noop", driftFields: [] },
|
||||
],
|
||||
database: { action: "noop", reconcileIssues: [], blockingIssues: [] },
|
||||
};
|
||||
}
|
||||
|
||||
function row(index: number, action: CatalogAuditRecoveryRow["action"], targetId: string | null): CatalogAuditRecoveryRow {
|
||||
return { id: String(index).padStart(3, "0"), action, targetId, createdAt: new Date(1_700_000_000_000 + index) };
|
||||
}
|
||||
|
||||
describe("customer-portal catalog audit recovery", () => {
|
||||
it("reconciles a canonical provider resource after a committed POST timed out or its created audit failed", () => {
|
||||
const recovery = assessCatalogAuditRecovery(
|
||||
[
|
||||
row(1, "customer_portal.catalog.provider_requested", "customer_portal_monthly"),
|
||||
row(2, "customer_portal.catalog.provider_failed", "customer_portal_monthly"),
|
||||
],
|
||||
plan()
|
||||
);
|
||||
expect(recovery.providerCodesNeedingReconciliation).toEqual(["customer_portal_monthly"]);
|
||||
});
|
||||
|
||||
it("does not mark an unresolved request as reconciled while the provider resource is still missing", () => {
|
||||
const recovery = assessCatalogAuditRecovery([row(1, "customer_portal.catalog.provider_requested", "customer_portal_monthly")], plan("create"));
|
||||
expect(recovery.providerCodesNeedingReconciliation).toEqual([]);
|
||||
});
|
||||
|
||||
it("repairs a missing final provisioned audit after provider or database success", () => {
|
||||
const providerRecovery = assessCatalogAuditRecovery([row(1, "customer_portal.catalog.provider_created", "customer_portal_monthly")], plan());
|
||||
expect(providerRecovery).toMatchObject({
|
||||
providerCodesNeedingReconciliation: [],
|
||||
providerCodesNeedingProvisionedAudit: ["customer_portal_monthly"],
|
||||
needsProvisionedAudit: true,
|
||||
});
|
||||
|
||||
const databaseRecovery = assessCatalogAuditRecovery([row(1, "customer_portal.catalog.database_reconciled", null)], plan());
|
||||
expect(databaseRecovery).toMatchObject({ databaseNeedsProvisionedAudit: true, needsProvisionedAudit: true });
|
||||
});
|
||||
|
||||
it("is quiescent once a later canonical provisioned audit closes the recovery window", () => {
|
||||
const recovery = assessCatalogAuditRecovery(
|
||||
[
|
||||
row(1, "customer_portal.catalog.provider_requested", "customer_portal_monthly"),
|
||||
row(2, "customer_portal.catalog.provider_reconciled", "customer_portal_monthly"),
|
||||
row(3, "customer_portal.catalog.database_reconciled", null),
|
||||
row(4, "customer_portal.catalog.provisioned", null),
|
||||
],
|
||||
plan()
|
||||
);
|
||||
expect(recovery).toEqual({
|
||||
providerCodesNeedingReconciliation: [],
|
||||
providerCodesNeedingProvisionedAudit: [],
|
||||
databaseNeedsProvisionedAudit: false,
|
||||
needsProvisionedAudit: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
+238
@@ -0,0 +1,238 @@
|
||||
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<CatalogExecutionResult> {
|
||||
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<string>();
|
||||
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<typeof reconcileBasePlanPortalFeatures>[0]);
|
||||
const databaseAssessment = assessDatabaseCatalog(await readDatabaseCatalog(tx as unknown as Parameters<typeof readDatabaseCatalog>[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<void> {
|
||||
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;
|
||||
});
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
import { CustomerPortalUatError, parseCustomerPortalUatCommand, safeCustomerPortalUatError, type CustomerPortalCommercialFixtureCommand } from "./contracts";
|
||||
import {
|
||||
applyCustomerPortalCommercialFixture,
|
||||
assessCustomerPortalCommercialFixture,
|
||||
readCustomerPortalCommercialFixture,
|
||||
type CustomerPortalCommercialFixtureAssessment,
|
||||
} from "./commercial-fixture";
|
||||
import { withCustomerPortalOperatorDatabase } from "./database";
|
||||
|
||||
type CommercialFixtureExecutionResult = {
|
||||
readonly mode: CustomerPortalCommercialFixtureCommand["mode"];
|
||||
readonly complete: boolean;
|
||||
readonly assessment: CustomerPortalCommercialFixtureAssessment;
|
||||
};
|
||||
|
||||
function writeResult(result: CommercialFixtureExecutionResult): void {
|
||||
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
||||
}
|
||||
|
||||
async function executeCommercialFixtureCommand(command: CustomerPortalCommercialFixtureCommand): Promise<CommercialFixtureExecutionResult> {
|
||||
return withCustomerPortalOperatorDatabase(command, async (db) => {
|
||||
const inspect = async () => assessCustomerPortalCommercialFixture(await readCustomerPortalCommercialFixture(db, command));
|
||||
const initial = await inspect();
|
||||
if (command.mode === "plan") {
|
||||
return { mode: command.mode, complete: initial.action === "noop", assessment: initial };
|
||||
}
|
||||
if (command.mode === "verify") {
|
||||
if (initial.action !== "noop") {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: commercial fixture verification found missing, drifted, or unsafe state");
|
||||
}
|
||||
return { mode: command.mode, complete: true, assessment: initial };
|
||||
}
|
||||
if (initial.action === "blocked") {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: commercial fixture apply is blocked by non-UAT or mismatched staging state");
|
||||
}
|
||||
|
||||
const snapshot = await readCustomerPortalCommercialFixture(db, command);
|
||||
const preApply = assessCustomerPortalCommercialFixture(snapshot);
|
||||
if (preApply.action === "blocked") {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: commercial fixture state changed during preflight");
|
||||
}
|
||||
await applyCustomerPortalCommercialFixture(db, command, snapshot);
|
||||
const final = await inspect();
|
||||
if (final.action !== "noop") {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: commercial fixture did not converge to the canonical contract");
|
||||
}
|
||||
return { mode: command.mode, complete: true, assessment: final };
|
||||
});
|
||||
}
|
||||
|
||||
export async function main(argv: readonly string[] = process.argv.slice(2), env: NodeJS.ProcessEnv = process.env): Promise<void> {
|
||||
const command = parseCustomerPortalUatCommand("commercial-fixture", argv, env);
|
||||
if (command.target !== "commercial-fixture") throw new CustomerPortalUatError("customer-portal UAT: invalid commercial fixture command");
|
||||
writeResult(await executeCommercialFixtureCommand(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;
|
||||
});
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
|
||||
import { CustomerPortalUatError, parseCustomerPortalUatCommand, safeCustomerPortalUatError, type CustomerPortalFixtureCommand } from "./contracts";
|
||||
import { withCustomerPortalOperatorDatabase } from "./database";
|
||||
import { applyCustomerPortalFixture, assessCustomerPortalFixture, readCustomerPortalFixture, type CustomerPortalFixtureAssessment } from "./fixture";
|
||||
|
||||
type FixtureExecutionResult = {
|
||||
readonly mode: CustomerPortalFixtureCommand["mode"];
|
||||
readonly complete: boolean;
|
||||
readonly assessment: CustomerPortalFixtureAssessment;
|
||||
};
|
||||
|
||||
function writeResult(result: FixtureExecutionResult): void {
|
||||
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
||||
}
|
||||
|
||||
async function executeFixtureCommand(command: CustomerPortalFixtureCommand): Promise<FixtureExecutionResult> {
|
||||
return withCustomerPortalOperatorDatabase(command, (db) =>
|
||||
runWithRlsContext({ tenantId: command.expectedTenantId }, async () => {
|
||||
const inspect = async () => {
|
||||
const snapshot = await readCustomerPortalFixture(db, command);
|
||||
return { snapshot, assessment: assessCustomerPortalFixture(snapshot, command.expectedTenantId) };
|
||||
};
|
||||
|
||||
const initial = await inspect();
|
||||
if (command.mode === "plan") {
|
||||
return { mode: command.mode, complete: initial.assessment.action === "noop", assessment: initial.assessment };
|
||||
}
|
||||
if (command.mode === "verify") {
|
||||
if (initial.assessment.action !== "noop") {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: fixture verification found missing, drifted, or unsafe state");
|
||||
}
|
||||
return { mode: command.mode, complete: true, assessment: initial.assessment };
|
||||
}
|
||||
if (initial.assessment.action === "blocked") {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: fixture apply is blocked by non-UAT or mismatched staging state");
|
||||
}
|
||||
|
||||
await applyCustomerPortalFixture(db, command, initial.snapshot);
|
||||
const final = await inspect();
|
||||
if (final.assessment.action !== "noop") {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: fixture did not converge to the canonical contract");
|
||||
}
|
||||
return { mode: command.mode, complete: true, assessment: final.assessment };
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export async function main(argv: readonly string[] = process.argv.slice(2), env: NodeJS.ProcessEnv = process.env): Promise<void> {
|
||||
const command = parseCustomerPortalUatCommand("fixture", argv, env);
|
||||
if (command.target !== "fixture") throw new CustomerPortalUatError("customer-portal UAT: invalid fixture command");
|
||||
writeResult(await executeFixtureCommand(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;
|
||||
});
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
|
||||
import {
|
||||
CustomerPortalUatError,
|
||||
parseCustomerPortalUatCommand,
|
||||
safeCustomerPortalUatError,
|
||||
type CustomerPortalFixtureCommand,
|
||||
} from "./contracts";
|
||||
import { withCustomerPortalOperatorDatabase } from "./database";
|
||||
import {
|
||||
applyProjectInvitationContact,
|
||||
assessProjectInvitationContact,
|
||||
parseProjectInvitationContactInput,
|
||||
readProjectInvitationContact,
|
||||
type ProjectInvitationContactCommand,
|
||||
type ProjectInvitationContactHandoff,
|
||||
} from "./project-invitation-contact";
|
||||
|
||||
export type ProjectInvitationContactExecutionResult = {
|
||||
readonly mode: CustomerPortalFixtureCommand["mode"];
|
||||
readonly complete: boolean;
|
||||
readonly handoff: ProjectInvitationContactHandoff | null;
|
||||
};
|
||||
|
||||
function writeResult(result: ProjectInvitationContactExecutionResult): void {
|
||||
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
||||
}
|
||||
|
||||
async function executeProjectInvitationContactCommand(
|
||||
command: ProjectInvitationContactCommand
|
||||
): Promise<ProjectInvitationContactExecutionResult> {
|
||||
return withCustomerPortalOperatorDatabase(command, (db) =>
|
||||
runWithRlsContext({ tenantId: command.expectedTenantId }, async () => {
|
||||
const inspect = async () => {
|
||||
const snapshot = await readProjectInvitationContact(db, command);
|
||||
return { snapshot, assessment: assessProjectInvitationContact(snapshot, command) };
|
||||
};
|
||||
const initial = await inspect();
|
||||
if (command.mode === "plan") {
|
||||
return { mode: command.mode, complete: initial.assessment.action === "noop", handoff: initial.assessment.handoff };
|
||||
}
|
||||
if (command.mode === "verify") {
|
||||
if (initial.assessment.action !== "noop" || !initial.assessment.handoff) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: project invitation contact verification found missing, drifted, or unsafe state");
|
||||
}
|
||||
return { mode: command.mode, complete: true, handoff: initial.assessment.handoff };
|
||||
}
|
||||
if (initial.assessment.action === "blocked") {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: project invitation contact apply is blocked by unsafe or non-UAT state");
|
||||
}
|
||||
|
||||
await applyProjectInvitationContact(db, command, initial.snapshot);
|
||||
const final = await inspect();
|
||||
if (final.assessment.action !== "noop" || !final.assessment.handoff) {
|
||||
throw new CustomerPortalUatError("customer-portal UAT: project invitation contact did not converge to the canonical contract");
|
||||
}
|
||||
return { mode: command.mode, complete: true, handoff: final.assessment.handoff };
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export async function main(argv: readonly string[] = process.argv.slice(2), env: NodeJS.ProcessEnv = process.env): Promise<void> {
|
||||
const baseCommand = parseCustomerPortalUatCommand("fixture", argv, env);
|
||||
if (baseCommand.target !== "fixture") throw new CustomerPortalUatError("customer-portal UAT: invalid project invitation fixture command");
|
||||
const command: ProjectInvitationContactCommand = { ...baseCommand, ...parseProjectInvitationContactInput(env) };
|
||||
writeResult(await executeProjectInvitationContactCommand(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;
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user