Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -0,0 +1,37 @@
import { readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
function source(file: string): string {
return readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), file), "utf8");
}
describe("KWP activity and sync-run summary i18n contract", () => {
it("persists semantic keys for project, archive and inbound synchronization", () => {
const sources = [
source("project-domain.server.ts"),
source("project-sync.server.ts"),
source("archive-file.server.ts"),
source("inbound-sync.server.ts"),
].join("\n");
for (const key of [
"activity.runtime.kwp.projectConnected",
"activity.runtime.kwp.projectDisconnectedRestored",
"activity.runtime.kwp.contactImported",
"activity.runtime.kwp.projectMissing",
"activity.runtime.kwp.projectStageChanged",
"activity.runtime.kwp.projectUpdated",
"activity.runtime.kwp.archiveImported",
"activity.runtime.kwp.inboundDataUpdated",
"integrations.sync.summary.kwpProjectImported",
"integrations.sync.summary.kwpProjectSyncStarted",
"integrations.sync.summary.kwpArchiveImportStarted",
"integrations.sync.summary.kwpInboundSyncStarted",
]) {
expect(sources).toContain(key);
}
expect(sources).not.toMatch(/summaryText:\s*`(?:KWP|Projekt|Archivdatei|Termine)/u);
});
});
@@ -0,0 +1,100 @@
import { afterEach, describe, expect, it, vi } from "vitest";
const clientMocks = vi.hoisted(() => ({
probeKwpHealth: vi.fn(),
refreshKwpAccessToken: vi.fn(),
}));
vi.mock("./client.js", async () => {
const actual = await vi.importActual<typeof import("./client.js")>("./client.js");
return {
...actual,
probeKwpHealth: clientMocks.probeKwpHealth,
refreshKwpAccessToken: clientMocks.refreshKwpAccessToken,
};
});
import { getCatalogEntry } from "../catalog.js";
import { kwpAdapter } from "./adapter.js";
import { KWP_APP_ID, KWP_OIDC_ISSUER, KWP_REQUIRED_OAUTH_SCOPES, KwpError, type KwpCredentials } from "./client.js";
const CREDENTIALS: KwpCredentials = {
accessToken: "kwp-access-token",
refreshToken: "kwp-refresh-token",
expiresAt: "2026-07-20T13:00:00.000Z",
issuer: KWP_OIDC_ISSUER,
clientId: "_extern-geerkens2",
clientSecret: "kwp-client-secret",
customerCode: "geerkens2",
scopes: [...KWP_REQUIRED_OAUTH_SCOPES],
};
afterEach(() => {
vi.clearAllMocks();
});
describe("KWP Apps Engine adapter", () => {
it("registers KWP as an ERP OAuth2 app with no manual credential fields", () => {
expect(kwpAdapter).toMatchObject({ key: KWP_APP_ID, connectionType: "oauth2" });
expect(kwpAdapter.refreshToken).toEqual(expect.any(Function));
expect(getCatalogEntry(KWP_APP_ID)).toMatchObject({
key: KWP_APP_ID,
category: "erp",
connectionType: "oauth2",
connectionSchema: { fields: [] },
});
});
it("maps a successful read-only version probe to active", async () => {
clientMocks.probeKwpHealth.mockResolvedValue('{"version":"8.1 N3"}');
await expect(kwpAdapter.validateConnection(CREDENTIALS)).resolves.toEqual({
ok: true,
health: "active",
messageKey: "integrations.kwp.health.active",
});
expect(clientMocks.probeKwpHealth).toHaveBeenCalledWith(CREDENTIALS);
});
it("maps provider and credential failures to Klartext-ready health states", async () => {
clientMocks.probeKwpHealth.mockRejectedValueOnce(new KwpError("rate_limit_exceeded", 429));
await expect(kwpAdapter.healthCheck(CREDENTIALS)).resolves.toEqual({
ok: false,
health: "degraded",
messageKey: "integrations.kwp.health.rateLimited",
});
clientMocks.probeKwpHealth.mockRejectedValueOnce(new KwpError("auth_token_invalid", 401));
await expect(kwpAdapter.healthCheck(CREDENTIALS)).resolves.toEqual({
ok: false,
health: "broken",
messageKey: "integrations.kwp.health.tokenInvalid",
});
clientMocks.probeKwpHealth.mockRejectedValueOnce(new KwpError("mandant_unconfirmed"));
await expect(kwpAdapter.healthCheck(CREDENTIALS)).resolves.toEqual({
ok: false,
health: "broken",
messageKey: "integrations.kwp.health.mandantUnconfirmed",
});
});
it("returns rotated credentials and expiry through the generic refresh contract", async () => {
const rotated: KwpCredentials = {
...CREDENTIALS,
accessToken: "rotated-access",
refreshToken: "rotated-refresh",
expiresAt: "2026-07-20T14:00:00.000Z",
};
clientMocks.refreshKwpAccessToken.mockResolvedValue(rotated);
await expect(kwpAdapter.refreshToken?.(CREDENTIALS)).resolves.toEqual({
creds: rotated,
expiresAt: new Date("2026-07-20T14:00:00.000Z"),
});
});
it("fails closed when generic sync is invoked before the queue slice", async () => {
await expect(kwpAdapter.sync(CREDENTIALS)).rejects.toThrow("kwp_sync_not_available");
});
});
@@ -0,0 +1,60 @@
import {
registerIntegrationAdapter,
type AdapterResult,
type AdapterSyncOutcome,
type AdapterTokenRefresh,
type IntegrationAdapter,
} from "@hivegrid/foundation";
import { KWP_APP_ID, KwpError, probeKwpHealth, refreshKwpAccessToken, type KwpCredentials } from "./client.js";
function healthFromError(error: unknown): AdapterResult {
if (error instanceof KwpError) {
switch (error.code) {
case "auth_token_invalid":
return { ok: false, health: "broken", messageKey: "integrations.kwp.health.tokenInvalid" };
case "auth_scope_missing":
return { ok: false, health: "broken", messageKey: "integrations.kwp.health.scopeMissing" };
case "rate_limit_exceeded":
// Existing connections may be marked degraded by healthCheck, but a
// fresh OAuth callback must not persist credentials without one proven
// Resource-API response. `ok: false` keeps validation fail-closed.
return { ok: false, health: "degraded", messageKey: "integrations.kwp.health.rateLimited" };
case "provider_outage":
return { ok: false, health: "degraded", messageKey: "integrations.kwp.health.providerOutage" };
case "relay_host_invalid":
case "relay_not_found":
return { ok: false, health: "broken", messageKey: "integrations.kwp.health.relayInvalid" };
case "invalid_credentials":
return { ok: false, health: "broken", messageKey: "integrations.kwp.health.credentialsInvalid" };
case "mandant_unconfirmed":
return { ok: false, health: "broken", messageKey: "integrations.kwp.health.mandantUnconfirmed" };
default:
return { ok: false, health: "broken", messageKey: "integrations.kwp.health.unknown" };
}
}
return { ok: false, health: "broken", messageKey: "integrations.kwp.health.unknown" };
}
async function probe(credentials: KwpCredentials): Promise<AdapterResult> {
try {
await probeKwpHealth(credentials);
return { ok: true, health: "active", messageKey: "integrations.kwp.health.active" };
} catch (error) {
return healthFromError(error);
}
}
export const kwpAdapter: IntegrationAdapter<KwpCredentials> = registerIntegrationAdapter<KwpCredentials>({
key: KWP_APP_ID,
connectionType: "oauth2",
validateConnection: probe,
healthCheck: probe,
refreshToken: async (credentials: KwpCredentials): Promise<AdapterTokenRefresh<KwpCredentials>> => {
const next = await refreshKwpAccessToken(credentials);
return { creds: next, expiresAt: new Date(next.expiresAt) };
},
// Sync/outbox delivery remains in the later VR-P32a slice. Reject explicitly
// so an accidental generic invocation cannot record a false green no-op run.
sync: (): Promise<AdapterSyncOutcome> => Promise.reject(new Error("kwp_sync_not_available")),
});
@@ -0,0 +1,68 @@
import { getDbClient } from "@hivegrid/db/client.server";
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
import {
type KwpArchiveDiscoveryBatch,
type KwpArchiveDiscoveryCursor,
loadKwpArchiveDiscoveryBatch,
} from "./inbound-reader.js";
import { KwpProjectDomainError } from "./project-domain.server.js";
export async function discoverKwpProjectArchiveBatch(input: {
readonly bindingId: string;
readonly cursor?: KwpArchiveDiscoveryCursor;
}): Promise<KwpArchiveDiscoveryBatch> {
const bindingId = normalizeId(input.bindingId);
const tenantId = requireTenantContext();
const prepared = await getDbClient().$transaction(async (tx) => {
const binding = await tx.appEntityBinding.findFirst({
where: {
id: bindingId,
tenantId,
externalEntityType: "kwp_project",
localEntityType: "project",
state: "active",
},
select: { dataConnectionId: true, externalId: true, localId: true },
});
if (!binding) throw new KwpProjectDomainError("project_not_found");
const [project, connection] = await Promise.all([
tx.projekt.findFirst({
where: { id: binding.localId, tenantId, archivedAt: null },
select: { id: true },
}),
tx.dataConnection.findFirst({
where: {
id: binding.dataConnectionId,
tenantId,
appId: "kwp",
archivedAt: null,
connectionStatus: { in: ["active", "degraded"] },
},
select: { id: true },
}),
]);
if (!project || !connection) throw new KwpProjectDomainError("project_not_found");
return {
connectionId: binding.dataConnectionId,
externalProjectNumber: binding.externalId,
};
});
return loadKwpArchiveDiscoveryBatch({
...prepared,
...(input.cursor ? { cursor: input.cursor } : {}),
});
}
function requireTenantContext(): string {
const tenantId = getRlsExecutionContext()?.tenantId?.trim();
if (!tenantId) throw new KwpProjectDomainError("project_not_found");
return tenantId;
}
function normalizeId(value: string): string {
const normalized = value.trim();
if (!/^[A-Za-z0-9_-]{8,191}$/u.test(normalized)) throw new KwpProjectDomainError("project_not_found");
return normalized;
}
@@ -0,0 +1,59 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
getRlsExecutionContext: vi.fn(),
loadBatch: vi.fn(),
transaction: vi.fn(),
bindingFindFirst: vi.fn(),
projectFindFirst: vi.fn(),
connectionFindFirst: vi.fn(),
}));
vi.mock("@hivegrid/db/client.server", () => ({
getDbClient: () => ({ $transaction: mocks.transaction }),
}));
vi.mock("@hivegrid/db/rls-context.server", () => ({ getRlsExecutionContext: mocks.getRlsExecutionContext }));
vi.mock("./inbound-reader.js", () => ({ loadKwpArchiveDiscoveryBatch: mocks.loadBatch }));
import { discoverKwpProjectArchiveBatch } from "./archive-discovery.server.js";
const tx = {
appEntityBinding: { findFirst: mocks.bindingFindFirst },
projekt: { findFirst: mocks.projectFindFirst },
dataConnection: { findFirst: mocks.connectionFindFirst },
};
describe("KWP archive discovery", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.getRlsExecutionContext.mockReturnValue({ tenantId: "tenant-1" });
mocks.transaction.mockImplementation(async (callback) => callback(tx));
mocks.bindingFindFirst.mockResolvedValue({ dataConnectionId: "connection-1", externalId: "P-100", localId: "project-1" });
mocks.projectFindFirst.mockResolvedValue({ id: "project-1" });
mocks.connectionFindFirst.mockResolvedValue({ id: "connection-1" });
mocks.loadBatch.mockResolvedValue({ archiveFiles: [], processedFolders: 1, cursor: null });
});
it("resolves the tenant-scoped project binding before provider reads", async () => {
const cursor = { pendingFolderIds: [5], visitedFolderIds: [0, 1, 2, 3, 4] };
await expect(discoverKwpProjectArchiveBatch({ bindingId: "binding_1", cursor })).resolves.toEqual({
archiveFiles: [],
processedFolders: 1,
cursor: null,
});
expect(mocks.bindingFindFirst).toHaveBeenCalledWith(expect.objectContaining({
where: expect.objectContaining({ tenantId: "tenant-1", state: "active" }),
}));
expect(mocks.loadBatch).toHaveBeenCalledWith({
connectionId: "connection-1",
externalProjectNumber: "P-100",
cursor,
});
});
it("fails closed before provider I/O when the binding is unavailable", async () => {
mocks.bindingFindFirst.mockResolvedValueOnce(null);
await expect(discoverKwpProjectArchiveBatch({ bindingId: "binding_1" })).rejects.toThrow("project_not_found");
expect(mocks.loadBatch).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,655 @@
import { createHash, randomUUID } from "node:crypto";
import { logActivity } from "@hivegrid/activity";
import { getDbClient } from "@hivegrid/db/client.server";
import type { Prisma } from "@hivegrid/db/prisma-browser";
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
import { TenantStorageCapacityError, withTenantStorageWriteReservation } from "@hivegrid/db/storage-capacity.server";
import { auditEvent } from "@hivegrid/foundation";
import { fetchOutboundHttpWithRedirects, readLimitedResponseText, type OutboundHttpAddressResolver } from "@hivegrid/foundation/outbound-http";
import { z } from "zod";
import { KWP_INBOUND_BOUNDS, type KwpInboundArchiveFile } from "./inbound-reader.js";
import { KwpProjectDomainError } from "./project-domain.server.js";
import { executeKwpReadOperation } from "./resource-client.server.js";
import { fingerprintKwpSnapshot } from "./resource-client.js";
const ARCHIVE_FILE_ENTITY_TYPE = "kwp_archive_file";
const EXCHANGE_JSON_LIMIT_BYTES = 64 * 1024;
const exportInfoSchema = z
.object({
dateigroesse: z.number().int(),
exchangeFileUri: z.string().url().nullable().optional(),
dateiname: z.string().nullable().optional(),
})
.strict();
export type KwpArchiveStorage = {
putObject(input: {
key: string;
body: Uint8Array | ReadableStream<Uint8Array>;
contentType?: string;
metadata?: Record<string, string>;
}): Promise<{ bucket: string; key: string }>;
deleteObject(input: { key: string }): Promise<unknown>;
};
export type KwpArchiveScanEnqueuer = (input: {
readonly bucket: string;
readonly key: string;
readonly tenantId: string;
readonly fileId: string;
readonly contentType: string;
}) => Promise<void>;
export type KwpArchiveFileSyncResult = {
readonly runId: string;
readonly fileId: string;
readonly projectId: string;
readonly storageKey: string;
readonly state: "created" | "replayed";
};
export async function syncKwpArchiveFile(input: {
readonly bindingId: string;
readonly archiveFile: KwpInboundArchiveFile;
readonly storage: KwpArchiveStorage;
readonly storageBucket: string;
readonly enqueueScan: KwpArchiveScanEnqueuer;
readonly fetchImpl?: typeof fetch;
readonly addressResolver?: OutboundHttpAddressResolver;
readonly now?: Date;
}): Promise<KwpArchiveFileSyncResult> {
const now = input.now ?? new Date();
const prepared = await prepareArchiveFileSync(normalizeId(input.bindingId), input.archiveFile, normalizeStorageBucket(input.storageBucket), now);
if (prepared.existing) {
if (prepared.existing.needsScan) {
await input.enqueueScan({
bucket: prepared.existing.bucket,
key: prepared.existing.storageKey,
tenantId: prepared.tenantId,
fileId: prepared.existing.fileId,
contentType: prepared.existing.mimeType,
});
}
return {
runId: prepared.runId,
fileId: prepared.existing.fileId,
projectId: prepared.projectId,
storageKey: prepared.existing.storageKey,
state: "replayed",
};
}
try {
const exported = await exportArchiveFile({
connectionId: prepared.connectionId,
descriptor: input.archiveFile,
fetchImpl: input.fetchImpl,
addressResolver: input.addressResolver,
});
const storageKey = buildArchiveStorageKey(prepared.tenantId, prepared.connectionId, input.archiveFile.externalId, exported.displayName);
const targetFileId = `file_${randomUUID()}`;
const outcome = await withTenantStorageWriteReservation({
reservation: {
tenantId: prepared.tenantId,
actorUserId: prepared.actorUserId,
targetFileId,
originalFilename: exported.displayName,
mimeType: exported.mimeType,
sizeBytes: exported.sizeBytes,
},
runTransaction: (operation) => getDbClient().$transaction(operation),
upload: () =>
input.storage.putObject({
key: storageKey,
body: exported.body,
contentType: exported.mimeType,
metadata: {
source: "kwp",
project: createHash("sha256").update(prepared.projectId).digest("hex"),
external: createHash("sha256").update(input.archiveFile.externalId).digest("hex"),
},
}),
commit: async (tx, stored) => {
const created = await persistArchiveFile(
tx,
prepared,
input.archiveFile,
targetFileId,
{
storageKey: stored.key,
bucket: stored.bucket,
displayName: exported.displayName,
mimeType: exported.mimeType,
sizeBytes: exported.sizeBytes,
},
now
);
return { ...created, bucket: stored.bucket, uploadedStorageKey: stored.key };
},
rollbackUpload: (stored) => input.storage.deleteObject({ key: stored?.key ?? storageKey }).then(() => undefined),
});
if (outcome.replayed && outcome.uploadedStorageKey !== outcome.storageKey) {
await input.storage.deleteObject({ key: outcome.uploadedStorageKey });
}
await input.enqueueScan({
bucket: outcome.bucket,
key: outcome.storageKey,
tenantId: prepared.tenantId,
fileId: outcome.fileId,
contentType: exported.mimeType,
});
return {
runId: prepared.runId,
fileId: outcome.fileId,
projectId: prepared.projectId,
storageKey: outcome.storageKey,
state: outcome.replayed ? "replayed" : "created",
};
} catch (error) {
if (error instanceof TenantStorageCapacityError && error.code === "STORAGE_RESERVATION_INVALID") {
const replay = await loadArchiveFileReplay(prepared, input.archiveFile, now).catch(() => null);
if (replay) {
if (replay.needsScan) {
await input.enqueueScan({
bucket: input.storageBucket,
key: replay.storageKey,
tenantId: prepared.tenantId,
fileId: replay.fileId,
contentType: replay.mimeType,
});
}
return {
runId: prepared.runId,
fileId: replay.fileId,
projectId: prepared.projectId,
storageKey: replay.storageKey,
state: "replayed",
};
}
}
await failArchiveRun(prepared, error, now);
throw error;
}
}
type PreparedArchiveFileSync = {
readonly tenantId: string;
readonly runId: string;
readonly connectionId: string;
readonly projectId: string;
readonly externalProjectNumber: string;
readonly actorUserId: string;
readonly existing: {
readonly fileId: string;
readonly storageKey: string;
readonly mimeType: string;
readonly bucket: string;
readonly needsScan: boolean;
} | null;
};
async function prepareArchiveFileSync(
bindingId: string,
archiveFile: KwpInboundArchiveFile,
storageBucket: string,
now: Date
): Promise<PreparedArchiveFileSync> {
const tenantId = requireTenantContext();
return getDbClient().$transaction(async (tx) => {
const binding = await tx.appEntityBinding.findFirst({
where: {
id: bindingId,
tenantId,
externalEntityType: "kwp_project",
localEntityType: "project",
state: "active",
},
select: { dataConnectionId: true, externalId: true, localId: true },
});
if (!binding) throw new KwpProjectDomainError("project_not_found");
const [connection, project, existingBinding] = await Promise.all([
tx.dataConnection.findFirst({
where: {
id: binding.dataConnectionId,
tenantId,
appId: "kwp",
archivedAt: null,
connectionStatus: { in: ["active", "degraded"] },
},
select: { createdByUserId: true },
}),
tx.projekt.findFirst({
where: { id: binding.localId, tenantId, archivedAt: null },
select: { id: true, createdByUserId: true },
}),
tx.appEntityBinding.findUnique({
where: {
tenantId_dataConnectionId_externalEntityType_externalId: {
tenantId,
dataConnectionId: binding.dataConnectionId,
externalEntityType: ARCHIVE_FILE_ENTITY_TYPE,
externalId: archiveFile.externalId,
},
},
select: { localId: true },
}),
]);
if (!connection || !project) throw new KwpProjectDomainError("project_not_found");
const actorUserId = await resolveActorUserId(tx, tenantId, connection.createdByUserId ?? project.createdByUserId);
if (!actorUserId) throw new KwpProjectDomainError("project_not_found");
const existingFile = existingBinding
? await tx.file.findFirst({
where: { id: existingBinding.localId, tenantId, archivedAt: null },
select: { id: true, storageKey: true, mimeType: true, scanStatus: true },
})
: null;
const run = await tx.appSyncRun.create({
data: {
tenantId,
dataConnectionId: binding.dataConnectionId,
kind: "scheduled",
status: existingFile ? "completed" : "running",
itemsTotal: 1,
itemsSucceeded: existingFile ? 1 : 0,
summaryText: existingFile ? "integrations.sync.summary.kwpArchiveAlreadyPresent" : "integrations.sync.summary.kwpArchiveImportStarted",
startedAt: now,
completedAt: existingFile ? now : null,
},
});
return {
tenantId,
runId: run.id,
connectionId: binding.dataConnectionId,
projectId: project.id,
externalProjectNumber: binding.externalId,
actorUserId,
existing: existingFile
? {
fileId: existingFile.id,
storageKey: existingFile.storageKey,
mimeType: existingFile.mimeType,
bucket: storageBucket,
needsScan: existingFile.scanStatus === "pending" || existingFile.scanStatus === "skipped",
}
: null,
};
});
}
async function exportArchiveFile(input: {
readonly connectionId: string;
readonly descriptor: KwpInboundArchiveFile;
readonly fetchImpl?: typeof fetch;
readonly addressResolver?: OutboundHttpAddressResolver;
}): Promise<{
readonly body: Uint8Array;
readonly displayName: string;
readonly mimeType: string;
readonly sizeBytes: number;
}> {
const exportInfo = exportInfoSchema.parse(
await executeKwpReadOperation({
connectionId: input.connectionId,
operationId: "archivExternalExportDatei",
operationInput: {
query: {
guid: randomUUID(),
revisionId: input.descriptor.revisionId,
},
},
})
);
if (!exportInfo.exchangeFileUri || exportInfo.dateigroesse < 0 || exportInfo.dateigroesse > KWP_INBOUND_BOUNDS.maxArchiveFileBytes) {
throw new KwpProjectDomainError("project_not_found");
}
const exchangeResponse = await safeDownload(exportInfo.exchangeFileUri, input);
if (!exchangeResponse.ok) throw new Error("KWP archive exchange request failed.");
const exchange = await readLimitedResponseText(exchangeResponse, EXCHANGE_JSON_LIMIT_BYTES);
if (exchange.truncated) throw new Error("KWP archive exchange response exceeded its limit.");
const downloadUrl = parseExchangeDownloadUrl(exchange.body);
const fileResponse = await safeDownload(downloadUrl, input);
if (!fileResponse.ok || !fileResponse.body) throw new Error("KWP archive download failed.");
const declaredLength = parseContentLength(fileResponse.headers.get("content-length"));
const advertisedSize = declaredLength ?? exportInfo.dateigroesse;
if (advertisedSize < 0 || advertisedSize > KWP_INBOUND_BOUNDS.maxArchiveFileBytes) {
await fileResponse.body.cancel().catch(() => undefined);
throw new Error("KWP archive file exceeded its size limit.");
}
const body = new Uint8Array(await new Response(limitBody(fileResponse.body, KWP_INBOUND_BOUNDS.maxArchiveFileBytes)).arrayBuffer());
if (body.byteLength <= 0 || (declaredLength !== null && body.byteLength !== declaredLength)) {
throw new Error("KWP archive file size did not match its declared size.");
}
return {
body,
displayName: safeFileName(exportInfo.dateiname ?? input.descriptor.displayName),
mimeType: safeMimeType(fileResponse.headers.get("content-type"), input.descriptor.providerFileType),
sizeBytes: body.byteLength,
};
}
async function safeDownload(
url: string,
input: { readonly fetchImpl?: typeof fetch; readonly addressResolver?: OutboundHttpAddressResolver }
): Promise<Response> {
return fetchOutboundHttpWithRedirects(
url,
{
method: "GET",
headers: { accept: "application/json, application/octet-stream;q=0.9, */*;q=0.1" },
},
{
fetchImpl: input.fetchImpl,
addressResolver: input.addressResolver,
timeoutMs: 30_000,
redirectLimit: 3,
urlValidator: requireHttpsUrl,
}
);
}
function parseExchangeDownloadUrl(value: string): string {
let parsed: unknown;
try {
parsed = JSON.parse(value);
} catch {
throw new Error("KWP archive exchange response was not valid JSON.");
}
const candidate =
typeof parsed === "string"
? parsed
: isRecord(parsed)
? ["downloadUrl", "downloadUri", "fileUrl", "fileUri", "url", "uri"]
.map((key) => parsed[key])
.find((entry): entry is string => typeof entry === "string")
: undefined;
if (!candidate) throw new Error("KWP archive exchange response did not contain a download URL.");
return requireHttpsUrl(candidate);
}
async function persistArchiveFile(
tx: Prisma.TransactionClient,
prepared: PreparedArchiveFileSync,
descriptor: KwpInboundArchiveFile,
targetFileId: string,
stored: {
readonly storageKey: string;
readonly bucket: string;
readonly displayName: string;
readonly mimeType: string;
readonly sizeBytes: number;
},
now: Date
): Promise<{ readonly fileId: string; readonly replayed: boolean; readonly storageKey: string }> {
const replay = await tx.appEntityBinding.findUnique({
where: {
tenantId_dataConnectionId_externalEntityType_externalId: {
tenantId: prepared.tenantId,
dataConnectionId: prepared.connectionId,
externalEntityType: ARCHIVE_FILE_ENTITY_TYPE,
externalId: descriptor.externalId,
},
},
select: { localId: true },
});
if (replay) {
const existingFile = await tx.file.findFirstOrThrow({
where: { id: replay.localId, tenantId: prepared.tenantId },
select: { id: true, storageKey: true },
});
await completeArchiveRun(tx, prepared, now);
return { fileId: existingFile.id, storageKey: existingFile.storageKey, replayed: true };
}
const file = await tx.file.create({
data: {
id: targetFileId,
tenantId: prepared.tenantId,
createdByUserId: prepared.actorUserId,
displayName: stored.displayName,
mimeType: stored.mimeType,
sizeBytes: stored.sizeBytes,
storageKey: stored.storageKey,
previewStatus: "pending",
scanStatus: "pending",
source: "api",
tags: ["kwp"],
notes: descriptor.documentType,
},
});
await tx.fileEntityLink.create({
data: {
tenantId: prepared.tenantId,
createdByUserId: prepared.actorUserId,
fileId: file.id,
entityType: "project",
entityId: prepared.projectId,
linkRole: "kwp_archive",
},
});
const normalizedSnapshot = { projectId: prepared.projectId, ...descriptor };
await tx.appEntityBinding.create({
data: {
tenantId: prepared.tenantId,
dataConnectionId: prepared.connectionId,
externalEntityType: ARCHIVE_FILE_ENTITY_TYPE,
localEntityType: "file",
externalId: descriptor.externalId,
localId: file.id,
state: "active",
normalizedSnapshot: normalizedSnapshot as Prisma.InputJsonValue,
fingerprint: fingerprintKwpSnapshot(normalizedSnapshot),
lastSeenAt: now,
lastSyncedAt: now,
},
});
await tx.appSyncItem.create({
data: {
tenantId: prepared.tenantId,
syncRunId: prepared.runId,
entityType: ARCHIVE_FILE_ENTITY_TYPE,
entityId: file.id,
externalId: descriptor.externalId,
operation: "created",
status: "synced",
},
});
await auditEvent(
{
tenantId: prepared.tenantId,
actorType: "system",
action: "KWP_ARCHIVE_FILE_IMPORTED",
targetType: "file",
targetId: file.id,
metadata: {
source: "kwp",
projectId: prepared.projectId,
revision: descriptor.revision,
},
},
tx as never
);
await logActivity(
{
tenantId: prepared.tenantId,
actorKind: "system",
activityType: "project_updated",
subjectType: "project",
subjectId: prepared.projectId,
summaryText: "activity.runtime.kwp.archiveImported",
metadata: { source: "kwp", fileId: file.id },
},
{ client: tx }
);
await completeArchiveRun(tx, prepared, now);
return { fileId: file.id, storageKey: file.storageKey, replayed: false };
}
async function completeArchiveRun(tx: Prisma.TransactionClient, prepared: PreparedArchiveFileSync, now: Date): Promise<void> {
await tx.appSyncRun.updateMany({
where: { id: prepared.runId, tenantId: prepared.tenantId, status: "running" },
data: {
status: "completed",
itemsTotal: 1,
itemsSucceeded: 1,
summaryText: "integrations.sync.summary.kwpArchiveImported",
completedAt: now,
},
});
}
async function loadArchiveFileReplay(
prepared: PreparedArchiveFileSync,
descriptor: KwpInboundArchiveFile,
now: Date
): Promise<{ readonly fileId: string; readonly storageKey: string; readonly mimeType: string; readonly needsScan: boolean } | null> {
return getDbClient().$transaction(async (tx) => {
const binding = await tx.appEntityBinding.findUnique({
where: {
tenantId_dataConnectionId_externalEntityType_externalId: {
tenantId: prepared.tenantId,
dataConnectionId: prepared.connectionId,
externalEntityType: ARCHIVE_FILE_ENTITY_TYPE,
externalId: descriptor.externalId,
},
},
select: { localId: true },
});
if (!binding) return null;
const file = await tx.file.findFirst({
where: { id: binding.localId, tenantId: prepared.tenantId },
select: { id: true, storageKey: true, mimeType: true, scanStatus: true },
});
if (!file) return null;
await completeArchiveRun(tx, prepared, now);
return {
fileId: file.id,
storageKey: file.storageKey,
mimeType: file.mimeType,
needsScan: file.scanStatus === "pending" || file.scanStatus === "skipped",
};
});
}
async function failArchiveRun(prepared: PreparedArchiveFileSync, error: unknown, now: Date): Promise<void> {
await getDbClient().appSyncRun.updateMany({
where: { id: prepared.runId, tenantId: prepared.tenantId, status: "running" },
data: {
status: "failed",
itemsTotal: 1,
itemsFailed: 1,
summaryText: buildArchiveFailureSummary(error),
completedAt: now,
},
});
}
function buildArchiveFailureSummary(error: unknown): string {
const code = error && typeof error === "object" && "code" in error ? (error as { code?: unknown }).code : null;
if (code === "provider_outage" || code === "rate_limit_exceeded" || code === "auth_token_invalid") {
return "integrations.sync.summary.kwpArchiveTemporaryFailure";
}
if (code === "auth_scope_missing" || code === "capability_paused" || code === "contract_drift") {
return "integrations.sync.summary.kwpArchiveUnavailable";
}
return "integrations.sync.summary.kwpArchiveFailed";
}
async function resolveActorUserId(tx: Prisma.TransactionClient, tenantId: string, preferredUserId: string | null | undefined): Promise<string | null> {
if (preferredUserId) {
const preferred = await tx.tenantUser.findFirst({
where: { tenantId, userId: preferredUserId },
select: { userId: true },
});
if (preferred) return preferred.userId;
}
const fallback = await tx.tenantUser.findFirst({
where: { tenantId },
select: { userId: true },
orderBy: { createdAt: "asc" },
});
return fallback?.userId ?? null;
}
function limitBody(body: ReadableStream<Uint8Array>, limit: number): ReadableStream<Uint8Array> {
let bytes = 0;
return body.pipeThrough(
new TransformStream<Uint8Array, Uint8Array>({
transform(chunk, controller) {
bytes += chunk.byteLength;
if (bytes > limit) {
controller.error(new Error("KWP archive file exceeded its size limit."));
return;
}
controller.enqueue(chunk);
},
})
);
}
function buildArchiveStorageKey(tenantId: string, connectionId: string, externalId: string, fileName: string): string {
const identity = createHash("sha256").update(`${connectionId}:${externalId}`).digest("hex");
return `tenants/${safePathPart(tenantId)}/kwp-archive/${identity}/${safeFileName(fileName)}`;
}
function safeFileName(value: string): string {
const name = value.replaceAll("\\", "/").split("/").at(-1)?.trim() ?? "";
const normalized = name.replace(/[\u0000-\u001f\u007f]/gu, "").slice(0, 255);
return normalized || "kwp-datei.bin";
}
function safePathPart(value: string): string {
return value.replace(/[^A-Za-z0-9_-]/gu, "_").slice(0, 191);
}
function safeMimeType(contentType: string | null, providerType: string | null): string {
const fromHeader = contentType?.split(";")[0]?.trim().toLowerCase();
if (fromHeader && /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/u.test(fromHeader)) {
return fromHeader;
}
if (providerType?.trim().toLowerCase() === "pdf") return "application/pdf";
return "application/octet-stream";
}
function parseContentLength(value: string | null): number | null {
if (!value || !/^\d+$/u.test(value)) return null;
const parsed = Number(value);
return Number.isSafeInteger(parsed) ? parsed : null;
}
function requireHttpsUrl(value: string): string {
const url = new URL(value);
if (url.protocol !== "https:" || url.username || url.password) {
throw new Error("KWP archive URL is not allowed.");
}
return url.toString();
}
function normalizeStorageBucket(value: string): string {
const bucket = value.trim();
if (!bucket || bucket.length > 255) throw new Error("KWP archive storage bucket is invalid.");
return bucket;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function requireTenantContext(): string {
const tenantId = getRlsExecutionContext()?.tenantId?.trim();
if (!tenantId) throw new KwpProjectDomainError("project_not_found");
return tenantId;
}
function normalizeId(value: string): string {
const normalized = value.trim();
if (!/^[A-Za-z0-9_-]{3,191}$/u.test(normalized)) throw new KwpProjectDomainError("project_not_found");
return normalized;
}
export const __kwpArchiveInternals = {
buildArchiveStorageKey,
parseExchangeDownloadUrl,
safeFileName,
safeMimeType,
};
@@ -0,0 +1,360 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
auditEvent: vi.fn(),
logActivity: vi.fn(),
executeRead: vi.fn(),
getRlsExecutionContext: vi.fn(),
transaction: vi.fn(),
runUpdateMany: vi.fn(),
projectBindingFindFirst: vi.fn(),
archiveBindingFindUnique: vi.fn(),
archiveBindingCreate: vi.fn(),
connectionFindFirst: vi.fn(),
projectFindFirst: vi.fn(),
tenantUserFindFirst: vi.fn(),
fileFindFirst: vi.fn(),
fileFindFirstOrThrow: vi.fn(),
fileCreate: vi.fn(),
linkCreate: vi.fn(),
runCreate: vi.fn(),
itemCreate: vi.fn(),
events: [] as string[],
withStorageReservation: vi.fn(),
StorageCapacityError: class StorageCapacityError extends Error {
constructor(readonly code: string) {
super(code);
}
},
}));
vi.mock("@hivegrid/activity", () => ({ logActivity: mocks.logActivity }));
vi.mock("@hivegrid/db/client.server", () => ({
getDbClient: () => ({
$transaction: mocks.transaction,
appSyncRun: { updateMany: mocks.runUpdateMany },
}),
}));
vi.mock("@hivegrid/db/rls-context.server", () => ({ getRlsExecutionContext: mocks.getRlsExecutionContext }));
vi.mock("@hivegrid/db/storage-capacity.server", () => ({
TenantStorageCapacityError: mocks.StorageCapacityError,
withTenantStorageWriteReservation: mocks.withStorageReservation,
}));
vi.mock("@hivegrid/foundation", () => ({ auditEvent: mocks.auditEvent }));
vi.mock("./resource-client.server.js", () => ({ executeKwpReadOperation: mocks.executeRead }));
import { __kwpArchiveInternals, syncKwpArchiveFile } from "./archive-file.server.js";
const now = new Date("2026-07-24T10:00:00.000Z");
const descriptor = {
externalId: "20:21:22",
headerId: 20,
revisionId: 22,
revision: 1,
folderId: 0,
displayName: "plan.pdf",
documentType: "ZEICHNUNG",
providerFileType: "PDF",
providerSizeBytes: 3,
lastModifiedAt: null,
};
const tx = {
appEntityBinding: {
findFirst: mocks.projectBindingFindFirst,
findUnique: mocks.archiveBindingFindUnique,
create: mocks.archiveBindingCreate,
},
dataConnection: { findFirst: mocks.connectionFindFirst },
projekt: { findFirst: mocks.projectFindFirst },
tenantUser: { findFirst: mocks.tenantUserFindFirst },
file: { findFirst: mocks.fileFindFirst, findFirstOrThrow: mocks.fileFindFirstOrThrow, create: mocks.fileCreate },
fileEntityLink: { create: mocks.linkCreate },
appSyncRun: { create: mocks.runCreate, updateMany: mocks.runUpdateMany },
appSyncItem: { create: mocks.itemCreate },
};
beforeEach(() => {
vi.clearAllMocks();
mocks.events.length = 0;
mocks.getRlsExecutionContext.mockReturnValue({ tenantId: "tenant-1" });
mocks.transaction.mockImplementation(async (callback) => {
mocks.events.push("tx:start");
const result = await callback(tx);
mocks.events.push("tx:end");
return result;
});
mocks.withStorageReservation.mockImplementation(async (input) => {
await input.runTransaction(async () => {
mocks.events.push("reserve");
});
const stored = await input.upload();
return input.runTransaction((transaction: typeof tx) => input.commit(transaction, stored));
});
mocks.projectBindingFindFirst.mockResolvedValue({
dataConnectionId: "connection-1",
externalId: "P-100",
localId: "project-1",
});
mocks.connectionFindFirst.mockResolvedValue({ createdByUserId: "user-1" });
mocks.projectFindFirst.mockResolvedValue({ id: "project-1", createdByUserId: "user-1" });
mocks.tenantUserFindFirst.mockResolvedValue({ userId: "user-1" });
mocks.archiveBindingFindUnique.mockResolvedValue(null);
mocks.runCreate.mockResolvedValue({ id: "run-1" });
mocks.runUpdateMany.mockResolvedValue({ count: 1 });
mocks.fileCreate.mockResolvedValue({ id: "file-1", storageKey: "tenants/tenant-1/kwp-archive/hash/plan.pdf" });
mocks.linkCreate.mockResolvedValue({ id: "link-1" });
mocks.archiveBindingCreate.mockResolvedValue({});
mocks.itemCreate.mockResolvedValue({});
mocks.executeRead.mockResolvedValue({
dateigroesse: 3,
exchangeFileUri: "https://exchange.example/file.json",
dateiname: "../plan.pdf",
});
});
describe("KWP archive file importer", () => {
it("downloads outside DB, writes a pending file atomically and then enqueues fail-closed scanning", async () => {
const fetchImpl = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(Response.json({ downloadUrl: "https://blob.example/plan.pdf" }))
.mockResolvedValueOnce(
new Response(new Uint8Array([1, 2, 3]), {
status: 200,
headers: { "content-type": "application/pdf", "content-length": "3" },
})
);
const putObject = vi.fn().mockImplementation(async () => {
mocks.events.push("storage");
return { bucket: "files", key: "tenants/tenant-1/kwp-archive/hash/plan.pdf" };
});
const deleteObject = vi.fn();
const enqueueScan = vi.fn().mockImplementation(async () => {
mocks.events.push("scan");
});
await expect(
syncKwpArchiveFile({
bindingId: "binding-1",
archiveFile: descriptor,
storage: { putObject, deleteObject },
storageBucket: "files",
enqueueScan,
fetchImpl,
addressResolver: async () => ["203.0.113.10"],
now,
})
).resolves.toMatchObject({
runId: "run-1",
fileId: "file-1",
projectId: "project-1",
state: "created",
});
expect(mocks.events).toEqual(["tx:start", "tx:end", "tx:start", "reserve", "tx:end", "storage", "tx:start", "tx:end", "scan"]);
expect(mocks.withStorageReservation).toHaveBeenCalledWith(
expect.objectContaining({
reservation: expect.objectContaining({ tenantId: "tenant-1", actorUserId: "user-1", sizeBytes: 3 }),
})
);
expect(mocks.executeRead).toHaveBeenCalledWith(
expect.objectContaining({
operationId: "archivExternalExportDatei",
operationInput: { query: expect.objectContaining({ revisionId: 22 }) },
})
);
expect(mocks.fileCreate).toHaveBeenCalledWith({
data: expect.objectContaining({
displayName: "plan.pdf",
mimeType: "application/pdf",
scanStatus: "pending",
source: "api",
}),
});
expect(mocks.linkCreate).toHaveBeenCalledWith({
data: expect.objectContaining({
entityType: "project",
entityId: "project-1",
linkRole: "kwp_archive",
}),
});
expect(enqueueScan).toHaveBeenCalledWith(expect.objectContaining({ fileId: "file-1", tenantId: "tenant-1" }));
});
it("blocks a private exchange target before file or storage mutation", async () => {
const fetchImpl = vi.fn<typeof fetch>().mockResolvedValueOnce(Response.json({ url: "https://127.0.0.1/private" }));
const putObject = vi.fn();
await expect(
syncKwpArchiveFile({
bindingId: "binding-1",
archiveFile: descriptor,
storage: { putObject, deleteObject: vi.fn() },
storageBucket: "files",
enqueueScan: vi.fn(),
fetchImpl,
addressResolver: async () => ["203.0.113.10"],
now,
})
).rejects.toThrow(/not allowed|blocked/u);
expect(putObject).not.toHaveBeenCalled();
expect(mocks.fileCreate).not.toHaveBeenCalled();
expect(mocks.runUpdateMany).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({ status: "failed" }),
})
);
});
it("fails closed before reservation when the downloaded byte length is not reliable", async () => {
const fetchImpl = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(Response.json({ downloadUrl: "https://blob.example/plan.pdf" }))
.mockResolvedValueOnce(
new Response(new Uint8Array([1, 2]), {
status: 200,
headers: { "content-type": "application/pdf", "content-length": "3" },
})
);
const putObject = vi.fn();
await expect(
syncKwpArchiveFile({
bindingId: "binding-1",
archiveFile: descriptor,
storage: { putObject, deleteObject: vi.fn() },
storageBucket: "files",
enqueueScan: vi.fn(),
fetchImpl,
addressResolver: async () => ["203.0.113.10"],
now,
})
).rejects.toThrow("did not match its declared size");
expect(mocks.withStorageReservation).not.toHaveBeenCalled();
expect(putObject).not.toHaveBeenCalled();
});
it("removes a race-lost upload while preserving and scanning the existing file", async () => {
mocks.archiveBindingFindUnique
.mockResolvedValueOnce(null)
.mockResolvedValueOnce({ localId: "file-existing" })
.mockResolvedValueOnce({ localId: "file-existing" });
mocks.fileFindFirstOrThrow.mockResolvedValueOnce({
id: "file-existing",
storageKey: "tenants/tenant-1/kwp-archive/existing/plan.pdf",
});
mocks.fileFindFirst.mockResolvedValueOnce({
id: "file-existing",
storageKey: "tenants/tenant-1/kwp-archive/existing/plan.pdf",
mimeType: "application/pdf",
scanStatus: "pending",
});
mocks.withStorageReservation.mockImplementationOnce(async (input) => {
const stored = await input.upload();
const outcome = await input.runTransaction((transaction: typeof tx) => input.commit(transaction, stored));
if (outcome.replayed) {
await input.rollbackUpload(stored);
throw new mocks.StorageCapacityError("STORAGE_RESERVATION_INVALID");
}
return outcome;
});
const fetchImpl = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(Response.json({ downloadUrl: "https://blob.example/plan.pdf" }))
.mockResolvedValueOnce(
new Response(new Uint8Array([1, 2, 3]), {
status: 200,
headers: { "content-type": "application/pdf", "content-length": "3" },
})
);
const putObject = vi.fn().mockResolvedValue({
bucket: "files",
key: "tenants/tenant-1/kwp-archive/race/plan.pdf",
});
const deleteObject = vi.fn().mockResolvedValue(undefined);
const enqueueScan = vi.fn();
await expect(
syncKwpArchiveFile({
bindingId: "binding-1",
archiveFile: descriptor,
storage: { putObject, deleteObject },
storageBucket: "files",
enqueueScan,
fetchImpl,
addressResolver: async () => ["203.0.113.10"],
now,
})
).resolves.toMatchObject({
state: "replayed",
fileId: "file-existing",
storageKey: "tenants/tenant-1/kwp-archive/existing/plan.pdf",
});
expect(deleteObject).toHaveBeenCalledWith({ key: "tenants/tenant-1/kwp-archive/race/plan.pdf" });
expect(enqueueScan).toHaveBeenCalledWith(
expect.objectContaining({
fileId: "file-existing",
key: "tenants/tenant-1/kwp-archive/existing/plan.pdf",
})
);
});
it("keeps the connection active in the failure status for temporary provider outages", async () => {
mocks.executeRead.mockRejectedValueOnce(Object.assign(new Error("upstream 500"), { code: "provider_outage" }));
await expect(
syncKwpArchiveFile({
bindingId: "binding-1",
archiveFile: descriptor,
storage: { putObject: vi.fn(), deleteObject: vi.fn() },
storageBucket: "files",
enqueueScan: vi.fn(),
now,
})
).rejects.toMatchObject({ code: "provider_outage" });
expect(mocks.runUpdateMany).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
status: "failed",
summaryText: "integrations.sync.summary.kwpArchiveTemporaryFailure",
}),
})
);
});
it("repairs scan enqueue on replay without repeating provider or storage calls", async () => {
mocks.archiveBindingFindUnique.mockResolvedValueOnce({ localId: "file-existing" });
mocks.fileFindFirst.mockResolvedValueOnce({
id: "file-existing",
storageKey: "tenants/tenant-1/kwp-archive/existing/plan.pdf",
mimeType: "application/pdf",
scanStatus: "pending",
});
const enqueueScan = vi.fn();
await expect(
syncKwpArchiveFile({
bindingId: "binding-1",
archiveFile: descriptor,
storage: { putObject: vi.fn(), deleteObject: vi.fn() },
storageBucket: "files",
enqueueScan,
now,
})
).resolves.toMatchObject({ state: "replayed", fileId: "file-existing" });
expect(mocks.executeRead).not.toHaveBeenCalled();
expect(mocks.fileCreate).not.toHaveBeenCalled();
expect(enqueueScan).toHaveBeenCalledWith({
bucket: "files",
key: "tenants/tenant-1/kwp-archive/existing/plan.pdf",
tenantId: "tenant-1",
fileId: "file-existing",
contentType: "application/pdf",
});
});
it("parses only explicit exchange URL keys and sanitizes filenames", () => {
expect(__kwpArchiveInternals.parseExchangeDownloadUrl(JSON.stringify({ fileUri: "https://blob.example/a" }))).toBe("https://blob.example/a");
expect(() => __kwpArchiveInternals.parseExchangeDownloadUrl(JSON.stringify({ nested: { url: "https://blob.example/a" } }))).toThrow(/did not contain/u);
expect(__kwpArchiveInternals.safeFileName("../../plan\u0000.pdf")).toBe("plan.pdf");
});
});
@@ -0,0 +1,481 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import {
KWP_OAUTH_SCOPE,
KWP_OIDC_ISSUER,
KWP_REQUIRED_OAUTH_SCOPES,
KwpError,
discoverKwpMandants,
isValidKwpContextCode,
isValidKwpReturnedOAuthScopes,
probeKwpHealth,
refreshKwpAccessToken,
resolveKwpRelayBaseUrl,
validateKwpOnlineUrl,
type KwpCredentials,
type KwpOutboundRequestOptions,
} from "./client.js";
const PUBLIC_ADDRESS_RESOLVER = async (): Promise<readonly string[]> => ["93.184.216.34"];
const NOW = new Date("2026-07-20T12:00:00.000Z");
const DOMAIN_SCOPES = "adresse-extern archiv-extern termin-extern vorgang-extern aktivitaet-extern";
const CREDENTIALS: KwpCredentials = {
accessToken: "kwp-access-token",
refreshToken: "kwp-refresh-token",
expiresAt: "2026-07-20T13:00:00.000Z",
issuer: KWP_OIDC_ISSUER,
clientId: "_extern-geerkens2",
clientSecret: "kwp-client-secret",
customerCode: "geerkens2",
scopes: [...KWP_REQUIRED_OAUTH_SCOPES],
mandantBinding: { kind: "selected", code: "mandant1", label: "Mandant 1" },
};
afterEach(() => {
vi.unstubAllGlobals();
});
describe("KWP OAuth client", () => {
it("validates the KWP HTTPS host allowlist", () => {
expect(validateKwpOnlineUrl("https://geerkens2.app04.kwp-online.de/relay/geerkens2/pwa")).toBe("https://geerkens2.app04.kwp-online.de/relay/geerkens2/pwa");
expect(() => validateKwpOnlineUrl("http://geerkens2.app04.kwp-online.de")).toThrowError(KwpError);
expect(() => validateKwpOnlineUrl("https://kwp-online.de.evil.test")).toThrowError(KwpError);
expect(() => validateKwpOnlineUrl("https://user@kwp-online.de")).toThrowError(KwpError);
expect(() => validateKwpOnlineUrl("https://kwp-online.de:8443")).toThrowError(KwpError);
});
it("uses one canonical 128-character context-code contract", () => {
expect(isValidKwpContextCode("geerkens2")).toBe(true);
expect(isValidKwpContextCode(`a${"_".repeat(127)}`)).toBe(true);
for (const value of ["", " geerkens2", "geerkens.2", "geerkens/2", `a${"_".repeat(128)}`]) {
expect(isValidKwpContextCode(value)).toBe(false);
}
});
it.each([
["domain scopes only", DOMAIN_SCOPES],
["openid only as technical scope", `openid ${DOMAIN_SCOPES}`],
["offline_access only as technical scope", `${DOMAIN_SCOPES} offline_access`],
["both technical scopes", KWP_OAUTH_SCOPE],
["leading and trailing whitespace", ` ${DOMAIN_SCOPES}\topenid `],
["repeated mixed whitespace", `openid\n${DOMAIN_SCOPES.replaceAll(" ", "\t ")}\noffline_access`],
])("accepts a returned scope echo with %s", (_name, scopes) => {
expect(isValidKwpReturnedOAuthScopes(scopes)).toBe(true);
});
it.each([
["an empty value", ""],
["a whitespace-only value", " \t\n "],
["a missing domain scope", "adresse-extern archiv-extern termin-extern vorgang-extern"],
["an unknown scope", `${DOMAIN_SCOPES} email`],
["an unknown identity scope", `${DOMAIN_SCOPES} profile`],
["an unknown domain-shaped scope", `${DOMAIN_SCOPES} projekt-extern`],
["a duplicate scope", `${DOMAIN_SCOPES} adresse-extern`],
["wrong capitalization", "Adresse-extern archiv-extern termin-extern vorgang-extern aktivitaet-extern"],
])("rejects a returned scope echo with %s", (_name, scopes) => {
expect(isValidKwpReturnedOAuthScopes(scopes)).toBe(false);
});
it.each(DOMAIN_SCOPES.split(" "))("rejects a returned scope echo missing %s", (missingScope) => {
const scopes = DOMAIN_SCOPES.split(" ")
.filter((scope) => scope !== missingScope)
.join(" ");
expect(isValidKwpReturnedOAuthScopes(scopes)).toBe(false);
});
it("resolves the relay from the official load balancer without hard-coding an app host", async () => {
const fetchMock = vi.fn().mockResolvedValue(new Response("https://geerkens2.app04.kwp-online.de"));
await expect(resolveKwpRelayBaseUrl("geerkens2", outboundOptions(fetchMock))).resolves.toBe("https://geerkens2.app04.kwp-online.de");
const endpoint = new URL(String(fetchMock.mock.calls[0]?.[0]));
expect(`${endpoint.origin}${endpoint.pathname}`).toBe("https://loadbalancer.kwp-online.de/Relay/GetAppUrl");
expect(endpoint.searchParams.get("linkId")).toBe("geerkens2");
});
it("rejects a relay response outside kwp-online.de before sending a bearer token", async () => {
const fetchMock = vi.fn().mockResolvedValue(new Response("https://kwp-online.de.evil.test"));
await expect(resolveKwpRelayBaseUrl("geerkens2", outboundOptions(fetchMock))).rejects.toMatchObject({
code: "relay_host_invalid",
});
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it("runs read-only health through the resolved relay with the selected mandant", async () => {
const fetchMock = vi.fn().mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de")).mockResolvedValueOnce(jsonResponse(1));
await expect(probeKwpHealth(CREDENTIALS, outboundOptions(fetchMock))).resolves.toBe("1");
const [healthUrl, healthInit] = fetchMock.mock.calls[1] as [string, RequestInit];
const endpoint = new URL(healthUrl);
expect(endpoint.pathname).toBe("/relay/geerkens2/pwa/api/Core/GetApiVersion");
expect(endpoint.searchParams.get("mandant")).toBe("mandant1");
expect(new Headers(healthInit.headers).get("authorization")).toBe(`Bearer ${CREDENTIALS.accessToken}`);
expect(healthInit.method).toBe("GET");
});
it("omits the mandant query only for an explicitly confirmed none binding", async () => {
const fetchMock = vi.fn().mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de")).mockResolvedValueOnce(jsonResponse(1));
await expect(probeKwpHealth({ ...CREDENTIALS, mandantBinding: { kind: "none" } }, outboundOptions(fetchMock))).resolves.toBe("1");
const endpoint = new URL(String(fetchMock.mock.calls[1]?.[0]));
expect(endpoint.searchParams.has("mandant")).toBe(false);
});
it("rejects an unconfirmed legacy binding before making a health request", async () => {
const fetchMock = vi.fn();
const { mandantBinding: _mandantBinding, ...unconfirmedCredentials } = CREDENTIALS;
await expect(probeKwpHealth(unconfirmedCredentials, outboundOptions(fetchMock))).rejects.toMatchObject({ code: "mandant_unconfirmed" });
expect(fetchMock).not.toHaveBeenCalled();
});
it.each([[{ kind: "selected", code: "" }], [{ kind: "selected", code: "mandant1", label: "" }], [{ kind: "none", code: "mandant1" }], [{ kind: "unknown" }]])(
"rejects an invalid explicit mandant binding before making a health request",
async (mandantBinding) => {
const fetchMock = vi.fn();
await expect(
probeKwpHealth({ ...CREDENTIALS, mandantBinding: mandantBinding as unknown as KwpCredentials["mandantBinding"] }, outboundOptions(fetchMock))
).rejects.toMatchObject({ code: "invalid_credentials" });
expect(fetchMock).not.toHaveBeenCalled();
}
);
it("discovers, normalizes, sorts, and deduplicates mandants without sending a mandant query", async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de"))
.mockResolvedValueOnce(
jsonResponse([
{ id: 12, kuerzel: "beta", bezeichnung: " duplicate " },
{ id: 4, kuerzel: "alpha", bezeichnung: null },
{ id: 3, kuerzel: "beta", bezeichnung: " Beta GmbH " },
{ id: 9, kuerzel: "gamma", bezeichnung: " " },
])
);
await expect(discoverKwpMandants(CREDENTIALS, outboundOptions(fetchMock))).resolves.toEqual([
{ id: 4, code: "alpha" },
{ id: 3, code: "beta", label: "Beta GmbH" },
{ id: 9, code: "gamma" },
]);
const [discoveryUrl, discoveryInit] = fetchMock.mock.calls[1] as [string, RequestInit];
const endpoint = new URL(discoveryUrl);
expect(endpoint.pathname).toBe("/relay/geerkens2/pwa/api/Mandant/Load");
expect(endpoint.searchParams.has("mandant")).toBe(false);
expect(discoveryInit.method).toBe("GET");
expect(new Headers(discoveryInit.headers).get("accept")).toBe("application/json");
expect(new Headers(discoveryInit.headers).get("authorization")).toBe(`Bearer ${CREDENTIALS.accessToken}`);
});
it("allows mandant discovery while the legacy binding is still unconfirmed", async () => {
const { mandantBinding: _mandantBinding, ...unconfirmedCredentials } = CREDENTIALS;
const fetchMock = vi.fn().mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de")).mockResolvedValueOnce(jsonResponse([]));
await expect(discoverKwpMandants(unconfirmedCredentials, outboundOptions(fetchMock))).resolves.toEqual([]);
});
it.each([
["a non-array response", { id: 1, kuerzel: "alpha", bezeichnung: "Alpha" }],
["a non-object entry", [null]],
["a missing DTO property", [{ id: 1, kuerzel: "alpha" }]],
["an extra DTO property", [{ id: 1, kuerzel: "alpha", bezeichnung: "Alpha", tenant: "secret" }]],
["a fractional id", [{ id: 1.5, kuerzel: "alpha", bezeichnung: "Alpha" }]],
["an id outside int32", [{ id: 2_147_483_648, kuerzel: "alpha", bezeichnung: "Alpha" }]],
["a null code", [{ id: 1, kuerzel: null, bezeichnung: "Alpha" }]],
["an invalid code", [{ id: 1, kuerzel: "alpha/beta", bezeichnung: "Alpha" }]],
["a non-string label", [{ id: 1, kuerzel: "alpha", bezeichnung: 42 }]],
["a control character in the label", [{ id: 1, kuerzel: "alpha", bezeichnung: "Alpha\u0000Beta" }]],
["an oversized label", [{ id: 1, kuerzel: "alpha", bezeichnung: "a".repeat(257) }]],
])("rejects %s as an invalid discovery response", async (_name, body) => {
const fetchMock = vi.fn().mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de")).mockResolvedValueOnce(jsonResponse(body));
await expect(discoverKwpMandants(CREDENTIALS, outboundOptions(fetchMock))).rejects.toMatchObject({
code: "invalid_response",
httpStatus: 200,
});
});
it("bounds mandant discovery by entry count and response bytes", async () => {
const tooManyEntries = Array.from({ length: 101 }, (_, index) => ({
id: index,
kuerzel: `m${index}`,
bezeichnung: null,
}));
const entryFetch = vi.fn().mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de")).mockResolvedValueOnce(jsonResponse(tooManyEntries));
await expect(discoverKwpMandants(CREDENTIALS, outboundOptions(entryFetch))).rejects.toMatchObject({ code: "invalid_response" });
const responseFetch = vi
.fn()
.mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de"))
.mockResolvedValueOnce(jsonResponse([{ id: 1, kuerzel: "alpha", bezeichnung: "a".repeat(17 * 1024) }]));
await expect(discoverKwpMandants(CREDENTIALS, outboundOptions(responseFetch))).rejects.toMatchObject({ code: "invalid_response" });
});
it.each([
[401, "auth_token_invalid"],
[403, "mandant_discovery_unavailable"],
[404, "mandant_discovery_unavailable"],
[429, "rate_limit_exceeded"],
[503, "provider_outage"],
])("classifies mandant discovery HTTP %i as %s", async (status, code) => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de"))
.mockResolvedValueOnce(jsonResponse({ diagnostic: CREDENTIALS.accessToken }, status));
const error = await discoverKwpMandants(CREDENTIALS, outboundOptions(fetchMock)).catch((caught: unknown) => caught);
expect(error).toMatchObject({ code, httpStatus: status });
expect(JSON.stringify(error)).not.toContain(CREDENTIALS.accessToken);
});
it("rotates one-time refresh tokens centrally and rejects a missing replacement", async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(jsonResponse({ access_token: "rotated-access", refresh_token: "rotated-refresh", expires_in: 300 }))
.mockResolvedValueOnce(jsonResponse({ access_token: "next-access", expires_in: 300 }));
vi.stubGlobal("fetch", fetchMock);
const rotated = await refreshKwpAccessToken(CREDENTIALS, { now: () => NOW });
expect(rotated).toMatchObject({
accessToken: "rotated-access",
refreshToken: "rotated-refresh",
expiresAt: "2026-07-20T12:05:00.000Z",
mandantBinding: CREDENTIALS.mandantBinding,
});
await expect(refreshKwpAccessToken(CREDENTIALS, { now: () => NOW })).rejects.toMatchObject({
code: "invalid_response",
diagnosticCode: "missing_refresh_token",
});
for (const [tokenUrl, tokenInit] of fetchMock.mock.calls as Array<[string, RequestInit]>) {
expect(tokenUrl).toBe("https://id.kwp-online.de/realms/kwp-federated/protocol/openid-connect/token");
const form = new URLSearchParams(String(tokenInit.body));
expect(form.get("grant_type")).toBe("refresh_token");
expect(form.get("scope")).toBe(KWP_OAUTH_SCOPE);
expect(form.get("scope")?.split(" ")).not.toContain("email");
}
});
it.each([
["unconfirmed", undefined],
["confirmed without a bnWin mandant", { kind: "none" }],
["selected", { kind: "selected", code: "mandant1", label: "Mandant 1" }],
] as const)("preserves the %s mandant binding during refresh", async (_name, mandantBinding) => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(jsonResponse({ access_token: "next-access", refresh_token: "next-refresh", expires_in: 300 })));
const refreshed = await refreshKwpAccessToken({ ...CREDENTIALS, mandantBinding }, { now: () => NOW });
expect(refreshed.mandantBinding).toEqual(mandantBinding);
});
it("chains the persisted one-time refresh token from r1 to r2 to r3", async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(jsonResponse({ access_token: "access-2", refresh_token: "refresh-2", expires_in: 300 }))
.mockResolvedValueOnce(jsonResponse({ access_token: "access-3", refresh_token: "refresh-3", expires_in: 300 }));
vi.stubGlobal("fetch", fetchMock);
const second = await refreshKwpAccessToken({ ...CREDENTIALS, refreshToken: "refresh-1" }, { now: () => NOW });
const third = await refreshKwpAccessToken(second, { now: () => new Date("2026-07-20T12:05:00.000Z") });
expect(second).toMatchObject({ accessToken: "access-2", refreshToken: "refresh-2" });
expect(third).toMatchObject({ accessToken: "access-3", refreshToken: "refresh-3", expiresAt: "2026-07-20T12:10:00.000Z" });
expect(fetchMock.mock.calls.map(([, init]) => new URLSearchParams(String((init as RequestInit).body)).get("refresh_token"))).toEqual([
"refresh-1",
"refresh-2",
]);
});
it.each([
[400, "auth_token_invalid"],
[401, "auth_token_invalid"],
[403, "auth_scope_missing"],
[408, "refresh_outcome_unknown"],
[429, "rate_limit_exceeded"],
[503, "refresh_outcome_unknown"],
])("classifies token endpoint HTTP %i as %s", async (status, code) => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(jsonResponse({ error: "redacted" }, status)));
await expect(refreshKwpAccessToken(CREDENTIALS)).rejects.toMatchObject({ code, httpStatus: status });
});
it.each([
[400, "auth_token_invalid"],
[503, "refresh_outcome_unknown"],
])("classifies a non-object token error body at HTTP %i as %s", async (status, code) => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(jsonResponse(null, status)));
await expect(refreshKwpAccessToken(CREDENTIALS)).rejects.toMatchObject({ code, httpStatus: status });
});
it("rejects a successful non-object token body as an invalid response", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(jsonResponse(null)));
await expect(refreshKwpAccessToken(CREDENTIALS)).rejects.toMatchObject({
code: "invalid_response",
httpStatus: 200,
diagnosticCode: "token_response_not_object",
});
});
it("rejects a successful non-JSON token body with a redacted diagnostic", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("{not-json", { status: 200 })));
await expect(refreshKwpAccessToken(CREDENTIALS)).rejects.toMatchObject({
code: "invalid_response",
httpStatus: 200,
diagnosticCode: "token_response_not_json",
});
});
it.each([
["temporarily_unavailable", "provider_outage"],
["server_error", "provider_outage"],
["invalid_scope", "auth_scope_missing"],
["invalid_grant", "auth_token_invalid"],
["invalid_client", "invalid_credentials"],
])("classifies allowlisted OAuth error %s as %s without retaining the provider body", async (providerError, code) => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(jsonResponse({ error: providerError, error_description: CREDENTIALS.refreshToken }, 400)));
const error = await refreshKwpAccessToken(CREDENTIALS).catch((caught: unknown) => caught);
expect(error).toMatchObject({ code, httpStatus: 400 });
expect(JSON.stringify(error)).not.toContain(CREDENTIALS.refreshToken);
});
it.each(["temporarily_unavailable", "server_error"])(
"keeps an explicit OAuth %s response replay-safe even at HTTP 503",
async (providerError) => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(jsonResponse({ error: providerError }, 503)));
await expect(refreshKwpAccessToken(CREDENTIALS)).rejects.toMatchObject({ code: "provider_outage", httpStatus: 503 });
},
);
it("classifies a token POST without a response as an ambiguous refresh outcome", async () => {
vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new TypeError("network unavailable")));
await expect(refreshKwpAccessToken(CREDENTIALS)).rejects.toMatchObject({ code: "refresh_outcome_unknown" });
});
it("rejects non-canonical stored scopes before requesting a refresh token", async () => {
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
await expect(refreshKwpAccessToken({ ...CREDENTIALS, scopes: DOMAIN_SCOPES.split(" ") }, { now: () => NOW })).rejects.toMatchObject({
code: "invalid_credentials",
});
expect(fetchMock).not.toHaveBeenCalled();
});
it("fails closed with redacted diagnostics on unsafe refresh responses", async () => {
const responses = [
[{ refresh_token: "next-no-access", expires_in: 300 }, "missing_access_token"],
[{ access_token: "access", expires_in: 300 }, "missing_refresh_token"],
[{ access_token: "access", refresh_token: CREDENTIALS.refreshToken, expires_in: 300 }, "refresh_token_not_rotated"],
[{ access_token: "access", refresh_token: ` ${CREDENTIALS.refreshToken} `, expires_in: 300 }, "refresh_token_not_rotated"],
[{ access_token: "access", refresh_token: "next-1", expires_in: 300, scope: `${KWP_OAUTH_SCOPE} email` }, "scope_mismatch"],
[{ access_token: "access", refresh_token: "next-duplicate", expires_in: 300, scope: `${DOMAIN_SCOPES} adresse-extern` }, "scope_mismatch"],
[{ access_token: "access", refresh_token: "next-empty", expires_in: 300, scope: " \t\n " }, "scope_mismatch"],
[
{
access_token: "access",
refresh_token: "next-case",
expires_in: 300,
scope: `Adresse-extern ${DOMAIN_SCOPES.split(" ").slice(1).join(" ")}`,
},
"scope_mismatch",
],
[
{
access_token: "access",
refresh_token: "next-missing",
expires_in: 300,
scope: "adresse-extern archiv-extern termin-extern vorgang-extern",
},
"scope_mismatch",
],
[{ access_token: "access", refresh_token: "next-zero", expires_in: 0 }, "invalid_expiry"],
[{ access_token: "access", refresh_token: "next-2", expires_in: 301 }, "invalid_expiry"],
[{ access_token: "access", refresh_token: "next-3", expires_in: 300.5 }, "invalid_expiry"],
];
for (const [response, diagnosticCode] of responses) {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(jsonResponse(response)));
await expect(refreshKwpAccessToken(CREDENTIALS, { now: () => NOW })).rejects.toMatchObject({
code: "invalid_response",
diagnosticCode,
});
}
});
it.each([1, 299, 300])("accepts a positive contract-bounded expires_in of %i seconds", async (expiresIn) => {
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue(
jsonResponse({ access_token: "access", refresh_token: "next-valid", expires_in: expiresIn }),
),
);
await expect(refreshKwpAccessToken(CREDENTIALS, { now: () => NOW })).resolves.toMatchObject({
expiresAt: new Date(NOW.getTime() + expiresIn * 1_000).toISOString(),
refreshToken: "next-valid",
});
});
it.each([
["domain scopes only", DOMAIN_SCOPES],
["openid only as technical scope", `openid ${DOMAIN_SCOPES}`],
["offline_access only as technical scope", `${DOMAIN_SCOPES} offline_access`],
["both technical scopes", [...KWP_REQUIRED_OAUTH_SCOPES].reverse().join(" ")],
["mixed repeated whitespace", `\topenid ${DOMAIN_SCOPES.replaceAll(" ", "\n ")}\toffline_access\n`],
])("accepts refresh scope echo with %s and keeps canonical stored scopes", async (_name, scope) => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(jsonResponse({ access_token: "access", refresh_token: "next-valid", expires_in: 300, scope })));
await expect(refreshKwpAccessToken(CREDENTIALS, { now: () => NOW })).resolves.toMatchObject({
refreshToken: "next-valid",
scopes: [...KWP_REQUIRED_OAUTH_SCOPES],
});
});
it("accepts only a finite int32 API-major response", async () => {
for (const body of ["", '"1"', "1.5", "2147483648", '{"version":1}', "true", "null"]) {
const fetchMock = vi.fn().mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de")).mockResolvedValueOnce(new Response(body));
await expect(probeKwpHealth(CREDENTIALS, outboundOptions(fetchMock))).rejects.toMatchObject({ code: "invalid_response", httpStatus: 200 });
}
const plainTextFetch = vi
.fn()
.mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de"))
.mockResolvedValueOnce(new Response("2147483647"));
await expect(probeKwpHealth(CREDENTIALS, outboundOptions(plainTextFetch))).resolves.toBe("2147483647");
});
it("maps provider failures without exposing tokens or provider diagnostics", async () => {
const healthFetch = vi
.fn()
.mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de"))
.mockResolvedValueOnce(jsonResponse({ diagnostic: CREDENTIALS.accessToken }, 401));
const healthError = await probeKwpHealth(CREDENTIALS, outboundOptions(healthFetch)).catch((error: unknown) => error);
expect(healthError).toMatchObject({ code: "auth_token_invalid", httpStatus: 401 });
expect(JSON.stringify(healthError)).not.toContain(CREDENTIALS.accessToken);
const tokenFetch = vi.fn().mockResolvedValue(jsonResponse({ diagnostic: CREDENTIALS.refreshToken }, 400));
vi.stubGlobal("fetch", tokenFetch);
const refreshError = await refreshKwpAccessToken(CREDENTIALS).catch((error: unknown) => error);
expect(refreshError).toMatchObject({ code: "auth_token_invalid", httpStatus: 400 });
expect(JSON.stringify(refreshError)).not.toContain(CREDENTIALS.refreshToken);
});
});
function outboundOptions(fetchImpl: typeof fetch): KwpOutboundRequestOptions {
return { fetchImpl, addressResolver: PUBLIC_ADDRESS_RESOLVER };
}
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
}
@@ -0,0 +1,605 @@
import {
fetchOutboundHttpWithRedirects,
OutboundHttpUrlValidationError,
readLimitedResponseText,
type OutboundHttpFetchOptions,
} from "@hivegrid/foundation/outbound-http";
import { fetchProvider, readProviderJson } from "../provider-http.js";
export const KWP_APP_ID = "kwp";
export const KWP_OIDC_ISSUER = "https://id.kwp-online.de/realms/kwp-federated";
export const KWP_REQUIRED_OAUTH_SCOPES = Object.freeze([
"openid",
"adresse-extern",
"archiv-extern",
"termin-extern",
"vorgang-extern",
"aktivitaet-extern",
"offline_access",
] as const);
export const KWP_OAUTH_SCOPE = KWP_REQUIRED_OAUTH_SCOPES.join(" ");
const KWP_REQUIRED_DOMAIN_OAUTH_SCOPES = KWP_REQUIRED_OAUTH_SCOPES.filter((scope) => scope.endsWith("-extern"));
const KWP_RETURNED_OAUTH_SCOPE_SET = new Set<string>(KWP_REQUIRED_OAUTH_SCOPES);
const KWP_TOKEN_URL = `${KWP_OIDC_ISSUER}/protocol/openid-connect/token`;
const KWP_LOAD_BALANCER_URL = "https://loadbalancer.kwp-online.de/Relay/GetAppUrl";
const KWP_RESPONSE_LIMIT_BYTES = 16 * 1024;
const KWP_ACCESS_TOKEN_TTL_SECONDS = 5 * 60;
const KWP_CONTEXT_CODE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u;
const KWP_MANDANT_RESPONSE_MAX_ENTRIES = 100;
const KWP_MANDANT_LABEL_MAX_LENGTH = 256;
const CONTROL_CHARACTER_PATTERN = /[\u0000-\u001f\u007f]/u;
export type KwpMandantBinding = { readonly kind: "none" } | { readonly kind: "selected"; readonly code: string; readonly label?: string };
export interface KwpMandant {
readonly id: number;
readonly code: string;
readonly label?: string;
}
export interface KwpCredentials {
readonly accessToken: string;
readonly refreshToken: string;
readonly expiresAt: string;
readonly issuer: string;
readonly clientId: string;
readonly clientSecret: string;
readonly customerCode: string;
readonly scopes: readonly string[];
/** Missing only while a legacy/pending connection still awaits confirmation. */
readonly mandantBinding?: KwpMandantBinding;
}
interface KwpOAuthClientConfig {
readonly issuer: string;
readonly clientId: string;
readonly clientSecret: string;
readonly customerCode: string;
readonly mandantBinding?: KwpMandantBinding;
}
export type KwpOutboundRequestOptions = Pick<OutboundHttpFetchOptions, "fetchImpl" | "addressResolver" | "timeoutMs" | "redirectLimit" | "pinResolvedAddress">;
export interface KwpTokenRequestOptions {
readonly now?: () => Date;
}
export type KwpErrorCode =
| "auth_scope_missing"
| "auth_token_invalid"
| "capability_paused"
| "contract_drift"
| "invalid_credentials"
| "invalid_response"
| "mandant_discovery_unavailable"
| "mandant_unconfirmed"
| "provider_outage"
| "resource_not_found"
| "rate_limit_exceeded"
| "refresh_outcome_unknown"
| "relay_host_invalid"
| "relay_not_found"
| "unknown";
export type KwpRefreshDiagnosticCode =
| "invalid_clock"
| "invalid_expiry"
| "missing_access_token"
| "missing_refresh_token"
| "refresh_token_not_rotated"
| "scope_mismatch"
| "token_response_not_json"
| "token_response_not_object";
export class KwpError extends Error {
readonly code: KwpErrorCode;
readonly httpStatus?: number;
readonly diagnosticCode?: KwpRefreshDiagnosticCode;
constructor(code: KwpErrorCode, httpStatus?: number, diagnosticCode?: KwpRefreshDiagnosticCode) {
// Provider bodies may contain tokens or customer diagnostics. Keep the
// exception deliberately limited to stable, Klartext-mappable codes.
super(code);
this.name = "KwpError";
this.code = code;
this.httpStatus = httpStatus;
this.diagnosticCode = diagnosticCode;
}
}
/** Validate a credential snapshot before any business-resource request. */
export function assertKwpResourceCredentials(credentials: KwpCredentials): void {
validateCredentials(credentials, "resource");
}
/**
* Validate KWP's optional token-response scope echo. KWP may omit either
* technical scope (`openid` / `offline_access`) from that echo, while all five
* licensed `*-extern` scopes remain mandatory. Callers keep the canonical
* seven-scope request policy instead of persisting this provider representation.
*/
export function isValidKwpReturnedOAuthScopes(value: unknown): value is string {
if (typeof value !== "string") return false;
const normalized = value.trim();
if (normalized.length === 0) return false;
const scopes = normalized.split(/\s+/u);
const scopeSet = new Set(scopes);
return (
scopes.every((scope) => KWP_RETURNED_OAUTH_SCOPE_SET.has(scope)) &&
scopeSet.size === scopes.length &&
KWP_REQUIRED_DOMAIN_OAUTH_SCOPES.every((scope) => scopeSet.has(scope))
);
}
interface KwpTokenResponse {
readonly access_token?: unknown;
readonly refresh_token?: unknown;
readonly expires_in?: unknown;
readonly scope?: unknown;
readonly error?: unknown;
}
/** Refresh through central Keycloak and require KWP's documented one-time token rotation. */
export async function refreshKwpAccessToken(credentials: KwpCredentials, options: KwpTokenRequestOptions = {}): Promise<KwpCredentials> {
const config = validateCredentials(credentials, "refresh");
const token = await requestKwpToken(
new URLSearchParams({
grant_type: "refresh_token",
refresh_token: credentials.refreshToken,
client_id: config.clientId,
client_secret: config.clientSecret,
scope: KWP_OAUTH_SCOPE,
})
);
const rotatedRefreshToken = readTokenValue(token.refresh_token);
if (!rotatedRefreshToken) {
throw new KwpError("invalid_response", undefined, "missing_refresh_token");
}
if (rotatedRefreshToken === credentials.refreshToken.trim()) {
// KWP refresh tokens are single-use. Keeping the consumed token would make
// the next refresh fail while falsely persisting a healthy credential set.
throw new KwpError("invalid_response", undefined, "refresh_token_not_rotated");
}
if (token.scope !== undefined && !isValidKwpReturnedOAuthScopes(token.scope)) {
throw new KwpError("invalid_response", undefined, "scope_mismatch");
}
return toCredentials(config, token, rotatedRefreshToken, options.now?.() ?? new Date());
}
/** Resolve the current tenant relay. The provider returns a plain-text HTTPS base URL. */
export async function resolveKwpRelayBaseUrl(customerCode: string, options: KwpOutboundRequestOptions = {}): Promise<string> {
const normalizedCustomerCode = normalizeCustomerCode(customerCode);
const endpoint = new URL(KWP_LOAD_BALANCER_URL);
endpoint.searchParams.set("linkId", normalizedCustomerCode);
const response = await fetchKwpOutbound(endpoint.toString(), { method: "GET", headers: { accept: "text/plain" } }, options);
if (!response.ok) {
throw mapRelayError(response.status);
}
const relayBody = await readKwpResponseBody(response);
return normalizeRelayBaseUrl(relayBody);
}
/**
* Discover the bnWin mandants visible to the authenticated user. This setup-only
* request deliberately omits the `mandant` query parameter because it is the
* operation that establishes the binding in the first place.
*/
export async function discoverKwpMandants(credentials: KwpCredentials, options: KwpOutboundRequestOptions = {}): Promise<KwpMandant[]> {
const config = validateCredentials(credentials, "discovery");
const relayBaseUrl = await resolveKwpRelayBaseUrl(config.customerCode, options);
const endpoint = new URL(`/relay/${encodeURIComponent(config.customerCode)}/pwa/api/Mandant/Load`, `${relayBaseUrl}/`);
const response = await fetchKwpOutbound(
endpoint.toString(),
{
method: "GET",
headers: { accept: "application/json", authorization: `Bearer ${credentials.accessToken}` },
},
options
);
if (!response.ok) {
throw mapMandantDiscoveryError(response.status);
}
return parseKwpMandants(await readKwpResponseBody(response), response.status);
}
/** Read-only Apps Engine health probe against the dynamically resolved KWP relay. */
export async function probeKwpHealth(credentials: KwpCredentials, options: KwpOutboundRequestOptions = {}): Promise<string> {
const config = validateCredentials(credentials, "health");
const relayBaseUrl = await resolveKwpRelayBaseUrl(config.customerCode, options);
const endpoint = new URL(`/relay/${encodeURIComponent(config.customerCode)}/pwa/api/Core/GetApiVersion`, `${relayBaseUrl}/`);
if (config.mandantBinding?.kind === "selected") {
endpoint.searchParams.set("mandant", config.mandantBinding.code);
}
const response = await fetchKwpOutbound(
endpoint.toString(),
{
method: "GET",
headers: { accept: "application/json", authorization: `Bearer ${credentials.accessToken}` },
},
options
);
if (!response.ok) {
throw mapHealthError(response.status);
}
const body = await readKwpResponseBody(response);
return parseKwpApiMajorVersion(body, response.status);
}
/** Canonical KWP tenant/mandant code contract shared by OAuth, callback and relay calls. */
export function isValidKwpContextCode(value: unknown): value is string {
return typeof value === "string" && KWP_CONTEXT_CODE_PATTERN.test(value);
}
/** Feature-specific policy applied before DNS resolution and on every redirect. */
export function validateKwpOnlineUrl(endpoint: string): string {
let url: URL;
try {
url = new URL(endpoint);
} catch {
throw new KwpError("relay_host_invalid");
}
const hostname = url.hostname.toLowerCase();
const allowedHost = hostname === "kwp-online.de" || hostname.endsWith(".kwp-online.de");
if (
url.protocol !== "https:" ||
!allowedHost ||
hostname.endsWith(".") ||
Boolean(url.username || url.password) ||
(url.port !== "" && url.port !== "443") ||
Boolean(url.hash)
) {
throw new KwpError("relay_host_invalid");
}
return url.toString();
}
function validateOAuthConfig(config: KwpOAuthClientConfig): KwpOAuthClientConfig {
assertCentralIssuer(config.issuer);
const mandantBinding = normalizeMandantBinding(config.mandantBinding);
return {
issuer: KWP_OIDC_ISSUER,
clientId: requireValue(config.clientId),
clientSecret: requireValue(config.clientSecret),
customerCode: normalizeCustomerCode(config.customerCode),
...(mandantBinding ? { mandantBinding } : {}),
};
}
function validateCredentials(credentials: KwpCredentials, operation: "discovery" | "health" | "refresh" | "resource"): KwpOAuthClientConfig {
const config = validateOAuthConfig(credentials);
if (!hasExactRequiredScopes(credentials.scopes) || !Number.isFinite(Date.parse(credentials.expiresAt))) {
throw new KwpError("invalid_credentials");
}
if (operation === "health" || operation === "discovery" || operation === "resource") {
requireValue(credentials.accessToken);
} else {
requireValue(credentials.refreshToken);
}
if ((operation === "health" || operation === "resource") && !config.mandantBinding) {
throw new KwpError("mandant_unconfirmed");
}
return config;
}
function hasExactRequiredScopes(scopes: readonly string[]): boolean {
if (scopes.length !== KWP_REQUIRED_OAUTH_SCOPES.length || new Set(scopes).size !== scopes.length) {
return false;
}
return KWP_REQUIRED_OAUTH_SCOPES.every((scope) => scopes.includes(scope)) && !scopes.includes("email");
}
async function requestKwpToken(form: URLSearchParams): Promise<KwpTokenResponse> {
let response: Response;
try {
response = await fetchProvider(KWP_TOKEN_URL, {
method: "POST",
headers: { accept: "application/json", "content-type": "application/x-www-form-urlencoded" },
body: form.toString(),
});
} catch {
// The POST may already have consumed KWP's one-time refresh token even
// though no response reached HiveGrid. Keep that ambiguity distinct from
// a demonstrably non-consuming provider response: replaying the same token
// here could consume a rotated token twice.
throw new KwpError("refresh_outcome_unknown");
}
let body: unknown;
try {
body = await readProviderJson<unknown>(response, KWP_RESPONSE_LIMIT_BYTES);
} catch {
if (!response.ok) {
throw mapTokenError(response.status);
}
throw new KwpError("invalid_response", response.status, "token_response_not_json");
}
if (!response.ok) {
throw mapTokenError(response.status, isJsonObject(body) ? body.error : undefined);
}
if (!isJsonObject(body)) {
throw new KwpError("invalid_response", response.status, "token_response_not_object");
}
return body as unknown as KwpTokenResponse;
}
function isJsonObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function toCredentials(config: KwpOAuthClientConfig, token: KwpTokenResponse, refreshToken: string, now: Date): KwpCredentials {
const accessToken = readTokenValue(token.access_token);
if (!accessToken) {
throw new KwpError("invalid_response", undefined, "missing_access_token");
}
const expiresIn = token.expires_in;
if (
typeof expiresIn !== "number" ||
!Number.isSafeInteger(expiresIn) ||
expiresIn <= 0 ||
expiresIn > KWP_ACCESS_TOKEN_TTL_SECONDS
) {
throw new KwpError("invalid_response", undefined, "invalid_expiry");
}
if (!Number.isFinite(now.getTime())) {
throw new KwpError("invalid_response", undefined, "invalid_clock");
}
const expiresAt = new Date(now.getTime() + expiresIn * 1_000);
if (!Number.isFinite(expiresAt.getTime())) {
throw new KwpError("invalid_response", undefined, "invalid_expiry");
}
return {
accessToken,
refreshToken,
expiresAt: expiresAt.toISOString(),
issuer: KWP_OIDC_ISSUER,
clientId: config.clientId,
clientSecret: config.clientSecret,
customerCode: config.customerCode,
// Persist HiveGrid's canonical request/policy set, never the provider's
// potentially reduced token-response scope echo.
scopes: [...KWP_REQUIRED_OAUTH_SCOPES],
...(config.mandantBinding ? { mandantBinding: config.mandantBinding } : {}),
};
}
async function fetchKwpOutbound(endpoint: string, init: RequestInit, options: KwpOutboundRequestOptions): Promise<Response> {
try {
return await fetchOutboundHttpWithRedirects(endpoint, init, {
...options,
allowCrossOriginRedirects: false,
urlValidator: validateKwpOnlineUrl,
});
} catch (error) {
if (error instanceof KwpError) {
throw error;
}
if (error instanceof OutboundHttpUrlValidationError) {
throw new KwpError("relay_host_invalid");
}
throw new KwpError("provider_outage");
}
}
async function readKwpResponseBody(response: Response): Promise<string> {
try {
const result = await readLimitedResponseText(response, KWP_RESPONSE_LIMIT_BYTES);
if (result.truncated) {
throw new KwpError("invalid_response", response.status);
}
return result.body.trim();
} catch (error) {
if (error instanceof KwpError) {
throw error;
}
throw new KwpError("invalid_response", response.status);
}
}
function normalizeRelayBaseUrl(value: string): string {
const validated = validateKwpOnlineUrl(value);
const url = new URL(validated);
if ((url.pathname !== "" && url.pathname !== "/") || url.search) {
throw new KwpError("relay_host_invalid");
}
return url.origin;
}
function assertCentralIssuer(issuer: string): void {
let normalized: string;
try {
const url = new URL(issuer);
if (url.search || url.hash || url.username || url.password) {
throw new Error("invalid issuer");
}
normalized = url.toString().replace(/\/$/u, "");
} catch {
throw new KwpError("invalid_credentials");
}
if (normalized !== KWP_OIDC_ISSUER) {
throw new KwpError("invalid_credentials");
}
}
function normalizeCustomerCode(value: string): string {
const normalized = value.trim();
if (!isValidKwpContextCode(normalized)) {
throw new KwpError("invalid_credentials");
}
return normalized;
}
function normalizeMandantBinding(value: KwpMandantBinding | undefined): KwpMandantBinding | undefined {
if (value === undefined) return undefined;
if (!isJsonObject(value)) throw new KwpError("invalid_credentials");
const keys = Object.keys(value);
if (value.kind === "none") {
if (keys.length !== 1 || keys[0] !== "kind" || !Object.hasOwn(value, "kind")) throw new KwpError("invalid_credentials");
return { kind: "none" };
}
if (value.kind !== "selected" || !Object.hasOwn(value, "kind") || !keys.every((key) => key === "kind" || key === "code" || key === "label")) {
throw new KwpError("invalid_credentials");
}
if (!Object.hasOwn(value, "code") || typeof value.code !== "string" || keys.length < 2 || keys.length > 3) {
throw new KwpError("invalid_credentials");
}
const code = normalizeCustomerCode(value.code);
const label = normalizeMandantLabel(value.label);
return { kind: "selected", code, ...(label ? { label } : {}) };
}
function requireValue(value: string): string {
if (typeof value !== "string" || !value.trim()) {
throw new KwpError("invalid_credentials");
}
return value;
}
function readTokenValue(value: unknown): string | null {
return typeof value === "string" && value.trim() ? value.trim() : null;
}
function parseKwpApiMajorVersion(body: string, status: number): string {
let value: unknown;
try {
value = JSON.parse(body);
} catch {
throw new KwpError("invalid_response", status);
}
if (typeof value !== "number" || !Number.isInteger(value) || value < -2_147_483_648 || value > 2_147_483_647) {
throw new KwpError("invalid_response", status);
}
return String(value);
}
function parseKwpMandants(body: string, status: number): KwpMandant[] {
let value: unknown;
try {
value = JSON.parse(body);
} catch {
throw new KwpError("invalid_response", status);
}
if (!Array.isArray(value) || value.length > KWP_MANDANT_RESPONSE_MAX_ENTRIES) {
throw new KwpError("invalid_response", status);
}
const normalized = value.map((entry) => normalizeKwpMandant(entry, status));
normalized.sort(compareKwpMandants);
const uniqueByCode = new Map<string, KwpMandant>();
for (const mandant of normalized) {
if (!uniqueByCode.has(mandant.code)) uniqueByCode.set(mandant.code, mandant);
}
return [...uniqueByCode.values()];
}
function normalizeKwpMandant(value: unknown, status: number): KwpMandant {
if (!isJsonObject(value)) throw new KwpError("invalid_response", status);
const keys = Object.keys(value);
if (
keys.length !== 3 ||
!keys.every((key) => key === "id" || key === "kuerzel" || key === "bezeichnung") ||
!Object.hasOwn(value, "id") ||
!Object.hasOwn(value, "kuerzel") ||
!Object.hasOwn(value, "bezeichnung") ||
typeof value.id !== "number" ||
!Number.isInteger(value.id) ||
value.id < -2_147_483_648 ||
value.id > 2_147_483_647 ||
(value.kuerzel !== null && typeof value.kuerzel !== "string") ||
(value.bezeichnung !== null && typeof value.bezeichnung !== "string")
) {
throw new KwpError("invalid_response", status);
}
// The OpenAPI DTO permits null, but a null code cannot form a selected
// binding. Reject it instead of silently turning a multi-mandant tenant into
// the semantically different `none` binding.
if (value.kuerzel === null) throw new KwpError("invalid_response", status);
const code = normalizeDiscoveredMandantCode(value.kuerzel, status);
const label = normalizeDiscoveredMandantLabel(value.bezeichnung, status);
return { id: value.id, code, ...(label ? { label } : {}) };
}
function normalizeDiscoveredMandantCode(value: string, status: number): string {
const normalized = value.trim();
if (!isValidKwpContextCode(normalized)) throw new KwpError("invalid_response", status);
return normalized;
}
function normalizeDiscoveredMandantLabel(value: string | null, status: number): string | undefined {
if (value === null) return undefined;
const normalized = value.trim();
if (normalized.length > KWP_MANDANT_LABEL_MAX_LENGTH || CONTROL_CHARACTER_PATTERN.test(normalized)) {
throw new KwpError("invalid_response", status);
}
return normalized || undefined;
}
function normalizeMandantLabel(value: unknown): string | undefined {
if (value === undefined) return undefined;
if (typeof value !== "string") throw new KwpError("invalid_credentials");
const normalized = value.trim();
if (!normalized || normalized.length > KWP_MANDANT_LABEL_MAX_LENGTH || CONTROL_CHARACTER_PATTERN.test(normalized)) {
throw new KwpError("invalid_credentials");
}
return normalized;
}
function compareKwpMandants(left: KwpMandant, right: KwpMandant): number {
if (left.code !== right.code) return left.code < right.code ? -1 : 1;
if (left.id !== right.id) return left.id - right.id;
const leftLabel = left.label ?? "";
const rightLabel = right.label ?? "";
return leftLabel === rightLabel ? 0 : leftLabel < rightLabel ? -1 : 1;
}
function mapTokenError(status: number, providerError?: unknown): KwpError {
if (status === 408) return new KwpError("refresh_outcome_unknown", status);
if (status === 429) return new KwpError("rate_limit_exceeded", status);
if (typeof providerError === "string") {
if (providerError === "temporarily_unavailable" || providerError === "server_error") {
return new KwpError("provider_outage", status);
}
if (providerError === "invalid_scope") return new KwpError("auth_scope_missing", status);
if (providerError === "invalid_grant") return new KwpError("auth_token_invalid", status);
if (providerError === "invalid_client" || providerError === "unauthorized_client" || providerError === "unsupported_grant_type") {
return new KwpError("invalid_credentials", status);
}
}
// A generic 5xx does not prove whether Keycloak consumed KWP's single-use
// refresh token before an intermediary replaced or truncated the response.
// Only the explicit OAuth errors above are safe to replay.
if (status >= 500) return new KwpError("refresh_outcome_unknown", status);
if (status === 400 || status === 401) return new KwpError("auth_token_invalid", status);
if (status === 403) return new KwpError("auth_scope_missing", status);
return new KwpError("unknown", status);
}
function mapRelayError(status: number): KwpError {
if (status === 404) return new KwpError("relay_not_found", status);
if (status === 429) return new KwpError("rate_limit_exceeded", status);
if (status >= 500) return new KwpError("provider_outage", status);
return new KwpError("unknown", status);
}
function mapHealthError(status: number): KwpError {
if (status === 401) return new KwpError("auth_token_invalid", status);
if (status === 403) return new KwpError("auth_scope_missing", status);
if (status === 404) return new KwpError("relay_not_found", status);
if (status === 429) return new KwpError("rate_limit_exceeded", status);
if (status >= 500) return new KwpError("provider_outage", status);
return new KwpError("unknown", status);
}
function mapMandantDiscoveryError(status: number): KwpError {
if (status === 401) return new KwpError("auth_token_invalid", status);
if (status === 403 || status === 404) return new KwpError("mandant_discovery_unavailable", status);
if (status === 429) return new KwpError("rate_limit_exceeded", status);
if (status >= 500) return new KwpError("provider_outage", status);
return new KwpError("unknown", status);
}
@@ -0,0 +1,626 @@
import { getDbClient } from "@hivegrid/db/client.server";
import type { Prisma } from "@hivegrid/db/prisma-browser";
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
import { auditEvent, notify } from "@hivegrid/foundation";
import { loadScopedSemanticContracts, loadProjectSemanticContract, validateProjectAdapterAgainstCurrentContract } from "./resource-client.server.js";
import { getKwpScopedCapabilityKey, KWP_PROJECT_ADAPTER_REVISION, KWP_PROJECT_CAPABILITY, type KwpSemanticContract } from "./resource-client.js";
import { listKwpCapabilities, type KwpCapability, type KwpCapabilitySemanticContract } from "./scoped-contract.js";
export type KwpContractSentinelResult =
| { readonly status: "initialized" | "unchanged"; readonly fingerprint: string }
| { readonly status: "paused"; readonly fingerprint: string; readonly previousFingerprint: string; readonly diff: KwpRedactedContractDiff };
export type KwpRedactedContractDiff = {
readonly added: readonly string[];
readonly removed: readonly string[];
readonly changed: readonly string[];
readonly truncated: boolean;
};
export type KwpScopedContractSentinelResult = Readonly<Record<KwpCapability, KwpContractSentinelResult>>;
export class KwpContractSentinelError extends Error {
readonly code: "not_found" | "stale_write" | "validation_required";
constructor(code: KwpContractSentinelError["code"]) {
super(code);
this.name = "KwpContractSentinelError";
this.code = code;
}
}
export async function runKwpProjectContractSentinel(input: { readonly connectionId: string }): Promise<KwpContractSentinelResult> {
const tenantId = requireTenantContext();
const connectionId = normalizeId(input.connectionId);
// Tenant OpenAPI is provider I/O and must finish before the short state tx.
const current = await loadProjectSemanticContract({ connectionId });
const now = new Date();
return getDbClient().$transaction(async (tx) => {
const connection = await tx.dataConnection.findFirst({
where: { id: connectionId, tenantId, appId: "kwp", archivedAt: null },
select: { id: true, createdByUserId: true },
});
if (!connection) throw new KwpContractSentinelError("not_found");
const state = await tx.kwpCapabilityState.findUnique({
where: {
tenantId_dataConnectionId_capability: {
tenantId,
dataConnectionId: connectionId,
capability: KWP_PROJECT_CAPABILITY,
},
},
});
const approvedFingerprint = state?.approvedFingerprint;
const previousSnapshot = approvedFingerprint
? await tx.kwpApiContractSnapshot.findUnique({
where: {
tenantId_dataConnectionId_capability_semanticFingerprint: {
tenantId,
dataConnectionId: connectionId,
capability: KWP_PROJECT_CAPABILITY,
semanticFingerprint: approvedFingerprint,
},
},
})
: null;
await persistContractSnapshot(tx, tenantId, connectionId, current, now);
if (!state || !approvedFingerprint) {
const recoversUninitializedPause = state?.status === "paused";
await tx.kwpCapabilityState.upsert({
where: {
tenantId_dataConnectionId_capability: {
tenantId,
dataConnectionId: connectionId,
capability: KWP_PROJECT_CAPABILITY,
},
},
create: {
tenantId,
dataConnectionId: connectionId,
capability: KWP_PROJECT_CAPABILITY,
status: "active",
observedFingerprint: current.semanticFingerprint,
approvedFingerprint: current.semanticFingerprint,
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
revision: 1,
lastCheckedAt: now,
approvedAt: now,
},
update: {
status: "active",
reasonCode: null,
observedFingerprint: current.semanticFingerprint,
approvedFingerprint: current.semanticFingerprint,
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
revision: { increment: 1 },
pausedAt: null,
lastCheckedAt: now,
approvedAt: now,
},
});
if (recoversUninitializedPause) {
await tx.kwpErrorReport.updateMany({
where: {
tenantId,
dataConnectionId: connectionId,
capability: KWP_PROJECT_CAPABILITY,
resolvedAt: null,
},
data: { resolvedAt: now },
});
await auditEvent(
{
tenantId,
actorType: "system",
action: "KWP_CONTRACT_BASELINE_RECOVERED",
targetType: "DataConnection",
targetId: connectionId,
metadata: {
capability: KWP_PROJECT_CAPABILITY,
approvedFingerprint: current.semanticFingerprint,
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
},
},
tx as never
);
}
return { status: "initialized", fingerprint: current.semanticFingerprint };
}
if (approvedFingerprint === current.semanticFingerprint) {
await tx.kwpCapabilityState.update({
where: { id: state.id },
data: {
observedFingerprint: current.semanticFingerprint,
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
revision: { increment: 1 },
lastCheckedAt: now,
},
});
return { status: "unchanged", fingerprint: current.semanticFingerprint };
}
const diff = buildRedactedContractDiff(previousSnapshot?.consumedContract ?? {}, current.consumedContract);
await tx.kwpCapabilityState.update({
where: { id: state.id },
data: {
status: "paused",
reasonCode: "kwp.project.contract_drift",
observedFingerprint: current.semanticFingerprint,
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
revision: { increment: 1 },
pausedAt: now,
lastCheckedAt: now,
},
});
await tx.kwpErrorReport.create({
data: {
tenantId,
dataConnectionId: connectionId,
capability: KWP_PROJECT_CAPABILITY,
code: "kwp.project.contract_drift",
redactedDetails: {
previousFingerprint: approvedFingerprint,
observedFingerprint: current.semanticFingerprint,
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
diff,
},
},
});
await auditEvent(
{
tenantId,
actorType: "system",
action: "KWP_CONTRACT_DRIFT_DETECTED",
targetType: "DataConnection",
targetId: connectionId,
metadata: {
capability: KWP_PROJECT_CAPABILITY,
previousFingerprint: approvedFingerprint,
observedFingerprint: current.semanticFingerprint,
},
},
tx as never
);
await notify(
{
tenantId,
userId: connection.createdByUserId,
category: "integrations",
messageKey: "integrations.kwp.project.contractDrift",
sourceKey: `kwp-contract:${connectionId}:${current.semanticFingerprint}`,
payloadMetadata: { connectionId, capability: KWP_PROJECT_CAPABILITY },
},
tx as never
);
return {
status: "paused",
fingerprint: current.semanticFingerprint,
previousFingerprint: approvedFingerprint,
diff,
};
});
}
/** Runs the complete licensed OpenAPI contract through five independent state
* machines. Drift in one family cannot pause another family or OAuth health. */
export async function runKwpScopedContractSentinel(input: { readonly connectionId: string }): Promise<KwpScopedContractSentinelResult> {
const tenantId = requireTenantContext();
const connectionId = normalizeId(input.connectionId);
const contracts = await loadScopedSemanticContracts({ connectionId });
const byCapability = new Map(contracts.map((contract) => [contract.capability, contract]));
const now = new Date();
return getDbClient().$transaction(async (tx) => {
const connection = await tx.dataConnection.findFirst({
where: { id: connectionId, tenantId, appId: "kwp", archivedAt: null },
select: { id: true, createdByUserId: true },
});
if (!connection) throw new KwpContractSentinelError("not_found");
const results = {} as Record<KwpCapability, KwpContractSentinelResult>;
for (const capability of listKwpCapabilities()) {
const current = byCapability.get(capability);
if (!current) throw new KwpContractSentinelError("validation_required");
results[capability] = await reconcileScopedContractState({
tx,
tenantId,
connectionId,
createdByUserId: connection.createdByUserId,
capability,
current,
now,
});
}
return results;
});
}
export async function runKwpAllContractSentinels(input: { readonly connectionId: string }): Promise<
KwpContractSentinelResult & {
readonly scoped: KwpScopedContractSentinelResult;
}
> {
const project = await runKwpProjectContractSentinel(input);
const scoped = await runKwpScopedContractSentinel(input);
return { ...project, scoped };
}
export async function approveKwpProjectContract(input: {
readonly tenantId: string;
readonly connectionId: string;
readonly expectedRevision: number;
readonly observedFingerprint: string;
readonly validationProjectNumber: string;
readonly actorUserId: string;
}): Promise<void> {
assertTenantContext(input.tenantId);
const connectionId = normalizeId(input.connectionId);
const actorUserId = normalizeId(input.actorUserId);
const observedFingerprint = normalizeFingerprint(input.observedFingerprint);
// Approval is impossible until this exact adapter parses current project and
// address responses successfully. The call is read-only and allowed while
// the capability itself is paused.
await validateProjectAdapterAgainstCurrentContract({
connectionId,
externalProjectNumber: input.validationProjectNumber.trim(),
});
const now = new Date();
await getDbClient().$transaction(async (tx) => {
const state = await tx.kwpCapabilityState.findUnique({
where: {
tenantId_dataConnectionId_capability: {
tenantId: input.tenantId,
dataConnectionId: connectionId,
capability: KWP_PROJECT_CAPABILITY,
},
},
});
if (!state || state.status !== "paused" || state.revision !== input.expectedRevision || state.observedFingerprint !== observedFingerprint) {
throw new KwpContractSentinelError("stale_write");
}
const snapshot = await tx.kwpApiContractSnapshot.findUnique({
where: {
tenantId_dataConnectionId_capability_semanticFingerprint: {
tenantId: input.tenantId,
dataConnectionId: connectionId,
capability: KWP_PROJECT_CAPABILITY,
semanticFingerprint: observedFingerprint,
},
},
});
if (!snapshot || snapshot.adapterRevision !== KWP_PROJECT_ADAPTER_REVISION) {
throw new KwpContractSentinelError("validation_required");
}
const updated = await tx.kwpCapabilityState.updateMany({
where: {
id: state.id,
tenantId: input.tenantId,
revision: input.expectedRevision,
observedFingerprint,
},
data: {
status: "active",
reasonCode: null,
approvedFingerprint: observedFingerprint,
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
revision: { increment: 1 },
pausedAt: null,
approvedAt: now,
approvedByUserId: actorUserId,
lastCheckedAt: now,
},
});
if (updated.count !== 1) throw new KwpContractSentinelError("stale_write");
await tx.kwpErrorReport.updateMany({
where: {
tenantId: input.tenantId,
dataConnectionId: connectionId,
capability: KWP_PROJECT_CAPABILITY,
resolvedAt: null,
},
data: { resolvedAt: now, resolvedByUserId: actorUserId },
});
await auditEvent(
{
tenantId: input.tenantId,
actorId: actorUserId,
actorType: "user",
action: "KWP_CONTRACT_DRIFT_APPROVED",
targetType: "DataConnection",
targetId: connectionId,
metadata: {
capability: KWP_PROJECT_CAPABILITY,
approvedFingerprint: observedFingerprint,
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
},
},
tx as never
);
});
}
export function buildRedactedContractDiff(previous: unknown, current: unknown): KwpRedactedContractDiff {
const previousLeaves = flattenContract(previous);
const currentLeaves = flattenContract(current);
const added: string[] = [];
const removed: string[] = [];
const changed: string[] = [];
for (const path of currentLeaves.keys()) {
if (!previousLeaves.has(path)) added.push(path);
else if (previousLeaves.get(path) !== currentLeaves.get(path)) changed.push(path);
}
for (const path of previousLeaves.keys()) if (!currentLeaves.has(path)) removed.push(path);
added.sort();
removed.sort();
changed.sort();
const total = added.length + removed.length + changed.length;
const limit = 100;
return {
added: added.slice(0, limit),
removed: removed.slice(0, Math.max(0, limit - Math.min(limit, added.length))),
changed: changed.slice(0, Math.max(0, limit - Math.min(limit, added.length + removed.length))),
truncated: total > limit,
};
}
async function persistContractSnapshot(
tx: Prisma.TransactionClient,
tenantId: string,
connectionId: string,
contract: KwpSemanticContract,
now: Date
): Promise<void> {
await tx.kwpApiContractSnapshot.upsert({
where: {
tenantId_dataConnectionId_capability_semanticFingerprint: {
tenantId,
dataConnectionId: connectionId,
capability: KWP_PROJECT_CAPABILITY,
semanticFingerprint: contract.semanticFingerprint,
},
},
create: {
tenantId,
dataConnectionId: connectionId,
capability: KWP_PROJECT_CAPABILITY,
apiVersion: contract.apiVersion,
semanticFingerprint: contract.semanticFingerprint,
consumedContract: contract.consumedContract as Prisma.InputJsonValue,
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
validatedAt: now,
},
update: {
apiVersion: contract.apiVersion,
consumedContract: contract.consumedContract as Prisma.InputJsonValue,
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
validatedAt: now,
},
});
}
async function reconcileScopedContractState(input: {
readonly tx: Prisma.TransactionClient;
readonly tenantId: string;
readonly connectionId: string;
readonly createdByUserId: string | null;
readonly capability: KwpCapability;
readonly current: KwpCapabilitySemanticContract;
readonly now: Date;
}): Promise<KwpContractSentinelResult> {
const capabilityKey = getKwpScopedCapabilityKey(input.capability);
const state = await input.tx.kwpCapabilityState.findUnique({
where: {
tenantId_dataConnectionId_capability: {
tenantId: input.tenantId,
dataConnectionId: input.connectionId,
capability: capabilityKey,
},
},
});
const approvedFingerprint = state?.approvedFingerprint;
const previousSnapshot = approvedFingerprint
? await input.tx.kwpApiContractSnapshot.findUnique({
where: {
tenantId_dataConnectionId_capability_semanticFingerprint: {
tenantId: input.tenantId,
dataConnectionId: input.connectionId,
capability: capabilityKey,
semanticFingerprint: approvedFingerprint,
},
},
})
: null;
await persistScopedContractSnapshot(input.tx, input.tenantId, input.connectionId, capabilityKey, input.current, input.now);
if (!state) {
await input.tx.kwpCapabilityState.create({
data: {
tenantId: input.tenantId,
dataConnectionId: input.connectionId,
capability: capabilityKey,
status: "active",
observedFingerprint: input.current.semanticFingerprint,
approvedFingerprint: input.current.semanticFingerprint,
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
revision: 1,
lastCheckedAt: input.now,
approvedAt: input.now,
},
});
return { status: "initialized", fingerprint: input.current.semanticFingerprint };
}
if (!approvedFingerprint) {
await input.tx.kwpCapabilityState.update({
where: { id: state.id },
data: {
observedFingerprint: input.current.semanticFingerprint,
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
revision: { increment: 1 },
lastCheckedAt: input.now,
},
});
return {
status: "paused",
fingerprint: input.current.semanticFingerprint,
previousFingerprint: input.current.semanticFingerprint,
diff: emptyContractDiff(),
};
}
if (approvedFingerprint === input.current.semanticFingerprint) {
await input.tx.kwpCapabilityState.update({
where: { id: state.id },
data: {
observedFingerprint: input.current.semanticFingerprint,
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
revision: { increment: 1 },
lastCheckedAt: input.now,
},
});
return { status: "unchanged", fingerprint: input.current.semanticFingerprint };
}
const diff = buildRedactedContractDiff(previousSnapshot?.consumedContract ?? {}, input.current.consumedContract);
const reasonCode = `kwp.${input.capability}.contract_drift`;
await input.tx.kwpCapabilityState.update({
where: { id: state.id },
data: {
status: "paused",
reasonCode,
observedFingerprint: input.current.semanticFingerprint,
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
revision: { increment: 1 },
pausedAt: input.now,
lastCheckedAt: input.now,
},
});
await input.tx.kwpErrorReport.create({
data: {
tenantId: input.tenantId,
dataConnectionId: input.connectionId,
capability: capabilityKey,
code: reasonCode,
redactedDetails: {
previousFingerprint: approvedFingerprint,
observedFingerprint: input.current.semanticFingerprint,
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
diff,
},
},
});
await auditEvent(
{
tenantId: input.tenantId,
actorType: "system",
action: "KWP_CONTRACT_DRIFT_DETECTED",
targetType: "DataConnection",
targetId: input.connectionId,
metadata: {
capability: capabilityKey,
previousFingerprint: approvedFingerprint,
observedFingerprint: input.current.semanticFingerprint,
},
},
input.tx as never
);
await notify(
{
tenantId: input.tenantId,
userId: input.createdByUserId,
category: "integrations",
messageKey: "integrations.kwp.project.contractDrift",
sourceKey: `kwp-contract:${input.connectionId}:${capabilityKey}:${input.current.semanticFingerprint}`,
payloadMetadata: { connectionId: input.connectionId, capability: capabilityKey },
},
input.tx as never
);
return {
status: "paused",
fingerprint: input.current.semanticFingerprint,
previousFingerprint: approvedFingerprint,
diff,
};
}
async function persistScopedContractSnapshot(
tx: Prisma.TransactionClient,
tenantId: string,
connectionId: string,
capability: string,
contract: KwpCapabilitySemanticContract,
now: Date
): Promise<void> {
await tx.kwpApiContractSnapshot.upsert({
where: {
tenantId_dataConnectionId_capability_semanticFingerprint: {
tenantId,
dataConnectionId: connectionId,
capability,
semanticFingerprint: contract.semanticFingerprint,
},
},
create: {
tenantId,
dataConnectionId: connectionId,
capability,
apiVersion: contract.apiVersion,
semanticFingerprint: contract.semanticFingerprint,
consumedContract: contract.consumedContract as Prisma.InputJsonValue,
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
validatedAt: now,
},
update: {
apiVersion: contract.apiVersion,
consumedContract: contract.consumedContract as Prisma.InputJsonValue,
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
validatedAt: now,
},
});
}
function emptyContractDiff(): KwpRedactedContractDiff {
return { added: [], removed: [], changed: [], truncated: false };
}
function flattenContract(value: unknown, prefix = "$", result = new Map<string, string>()): Map<string, string> {
if (Array.isArray(value)) {
value.forEach((item, index) => flattenContract(item, `${prefix}[${index}]`, result));
return result;
}
if (value && typeof value === "object") {
for (const [key, nested] of Object.entries(value as Record<string, unknown>)) {
flattenContract(nested, `${prefix}.${key}`, result);
}
return result;
}
result.set(prefix, JSON.stringify(value));
return result;
}
function requireTenantContext(): string {
const tenantId = getRlsExecutionContext()?.tenantId?.trim();
if (!tenantId) throw new KwpContractSentinelError("not_found");
return tenantId;
}
function assertTenantContext(tenantId: string): void {
if (requireTenantContext() !== normalizeId(tenantId)) throw new KwpContractSentinelError("not_found");
}
function normalizeId(value: string): string {
const normalized = value.trim();
if (!/^[A-Za-z0-9_-]{3,191}$/u.test(normalized)) throw new KwpContractSentinelError("not_found");
return normalized;
}
function normalizeFingerprint(value: string): string {
const normalized = value.trim().toLowerCase();
if (!/^[a-f0-9]{64}$/u.test(normalized)) throw new KwpContractSentinelError("stale_write");
return normalized;
}
@@ -0,0 +1,349 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
transaction: vi.fn(),
loadProjectSemanticContract: vi.fn(),
loadScopedSemanticContracts: vi.fn(),
validateProjectAdapterAgainstCurrentContract: vi.fn(),
getRlsExecutionContext: vi.fn(),
auditEvent: vi.fn(),
notify: vi.fn(),
connectionFindFirst: vi.fn(),
stateFindUnique: vi.fn(),
stateCreate: vi.fn(),
stateUpsert: vi.fn(),
stateUpdate: vi.fn(),
stateUpdateMany: vi.fn(),
snapshotFindUnique: vi.fn(),
snapshotUpsert: vi.fn(),
reportCreate: vi.fn(),
reportUpdateMany: vi.fn(),
events: [] as string[],
}));
vi.mock("@hivegrid/db/client.server", () => ({
getDbClient: () => ({ $transaction: mocks.transaction }),
}));
vi.mock("@hivegrid/db/rls-context.server", () => ({
getRlsExecutionContext: mocks.getRlsExecutionContext,
}));
vi.mock("@hivegrid/foundation", () => ({
auditEvent: mocks.auditEvent,
notify: mocks.notify,
}));
vi.mock("./resource-client.server.js", () => ({
loadProjectSemanticContract: mocks.loadProjectSemanticContract,
loadScopedSemanticContracts: mocks.loadScopedSemanticContracts,
validateProjectAdapterAgainstCurrentContract: mocks.validateProjectAdapterAgainstCurrentContract,
}));
import {
approveKwpProjectContract,
buildRedactedContractDiff,
runKwpScopedContractSentinel,
runKwpProjectContractSentinel,
} from "./contract-sentinel.server.js";
import { KWP_PROJECT_ADAPTER_REVISION } from "./resource-client.js";
const tx = {
dataConnection: { findFirst: mocks.connectionFindFirst },
kwpCapabilityState: {
findUnique: mocks.stateFindUnique,
create: mocks.stateCreate,
upsert: mocks.stateUpsert,
update: mocks.stateUpdate,
updateMany: mocks.stateUpdateMany,
},
kwpApiContractSnapshot: {
findUnique: mocks.snapshotFindUnique,
upsert: mocks.snapshotUpsert,
},
kwpErrorReport: {
create: mocks.reportCreate,
updateMany: mocks.reportUpdateMany,
},
};
beforeEach(() => {
vi.clearAllMocks();
mocks.events.length = 0;
mocks.getRlsExecutionContext.mockReturnValue({ tenantId: "tenant-1", userId: "user-1" });
mocks.transaction.mockImplementation(async (callback) => {
mocks.events.push("tx");
return callback(tx);
});
mocks.connectionFindFirst.mockResolvedValue({ id: "connection-1", createdByUserId: "user-1" });
mocks.snapshotUpsert.mockResolvedValue({});
mocks.reportCreate.mockResolvedValue({});
mocks.reportUpdateMany.mockResolvedValue({ count: 1 });
mocks.stateUpdate.mockResolvedValue({});
mocks.stateCreate.mockResolvedValue({});
mocks.stateUpsert.mockResolvedValue({});
mocks.stateUpdateMany.mockResolvedValue({ count: 1 });
mocks.auditEvent.mockResolvedValue(undefined);
mocks.notify.mockResolvedValue(undefined);
mocks.validateProjectAdapterAgainstCurrentContract.mockImplementation(async () => {
mocks.events.push("adapter-validation");
});
});
describe("KWP project contract sentinel diff", () => {
it("reports only semantic leaf paths and never includes values", () => {
const diff = buildRedactedContractDiff(
{
project: {
fields: {
projNr: { type: "string" },
internalToken: "must-not-leak",
},
},
},
{
project: {
fields: {
projNr: { type: "integer" },
newField: { type: "string" },
},
},
}
);
expect(diff).toEqual({
added: ["$.project.fields.newField.type"],
removed: ["$.project.fields.internalToken"],
changed: ["$.project.fields.projNr.type"],
truncated: false,
});
expect(JSON.stringify(diff)).not.toContain("must-not-leak");
});
it("caps an operator-visible diff at one hundred paths", () => {
const current = Object.fromEntries(Array.from({ length: 125 }, (_, index) => [`field${index}`, { type: "string" }]));
const diff = buildRedactedContractDiff({}, current);
expect(diff.added).toHaveLength(100);
expect(diff.removed).toHaveLength(0);
expect(diff.changed).toHaveLength(0);
expect(diff.truncated).toBe(true);
});
});
describe("KWP project contract capability state", () => {
it("recovers and audits an uninitialized response-schema pause against the current semantic contract", async () => {
const fingerprint = "a".repeat(64);
mocks.loadProjectSemanticContract.mockResolvedValue({
apiVersion: "v1",
semanticFingerprint: fingerprint,
consumedContract: { project: { projNr: { type: "string" } } },
});
mocks.stateFindUnique.mockResolvedValue({
id: "state-1",
status: "paused",
approvedFingerprint: null,
});
await expect(runKwpProjectContractSentinel({ connectionId: "connection-1" })).resolves.toEqual({
status: "initialized",
fingerprint,
});
expect(mocks.stateUpsert).toHaveBeenCalledWith(
expect.objectContaining({
update: expect.objectContaining({
status: "active",
reasonCode: null,
approvedFingerprint: fingerprint,
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
}),
})
);
expect(mocks.reportUpdateMany).toHaveBeenCalledWith({
where: {
tenantId: "tenant-1",
dataConnectionId: "connection-1",
capability: "project-import",
resolvedAt: null,
},
data: { resolvedAt: expect.any(Date) },
});
expect(mocks.auditEvent).toHaveBeenCalledWith(
expect.objectContaining({
action: "KWP_CONTRACT_BASELINE_RECOVERED",
metadata: expect.objectContaining({
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
approvedFingerprint: fingerprint,
}),
}),
tx
);
});
it("pauses only the project import capability when the consumed semantic contract drifts", async () => {
mocks.loadProjectSemanticContract.mockResolvedValue({
apiVersion: "v2",
semanticFingerprint: "b".repeat(64),
consumedContract: { project: { projNr: { type: "integer" } } },
});
mocks.stateFindUnique.mockResolvedValue({
id: "state-1",
approvedFingerprint: "a".repeat(64),
});
mocks.snapshotFindUnique.mockResolvedValue({
consumedContract: { project: { projNr: { type: "string" } } },
});
const result = await runKwpProjectContractSentinel({ connectionId: "connection-1" });
expect(result).toMatchObject({
status: "paused",
fingerprint: "b".repeat(64),
previousFingerprint: "a".repeat(64),
});
expect(mocks.stateUpdate).toHaveBeenCalledWith({
where: { id: "state-1" },
data: expect.objectContaining({
status: "paused",
reasonCode: "kwp.project.contract_drift",
observedFingerprint: "b".repeat(64),
}),
});
expect(mocks.reportCreate).toHaveBeenCalledWith({
data: expect.objectContaining({
capability: "project-import",
code: "kwp.project.contract_drift",
redactedDetails: expect.objectContaining({
previousFingerprint: "a".repeat(64),
observedFingerprint: "b".repeat(64),
}),
}),
});
expect(mocks.notify).toHaveBeenCalledWith(
expect.objectContaining({
messageKey: "integrations.kwp.project.contractDrift",
}),
tx
);
});
it("validates the current adapter before safely approving the exact observed fingerprint", async () => {
const fingerprint = "c".repeat(64);
mocks.stateFindUnique.mockResolvedValue({
id: "state-1",
status: "paused",
revision: 5,
observedFingerprint: fingerprint,
});
mocks.snapshotFindUnique.mockResolvedValue({
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
});
await approveKwpProjectContract({
tenantId: "tenant-1",
connectionId: "connection-1",
expectedRevision: 5,
observedFingerprint: fingerprint,
validationProjectNumber: "P-100",
actorUserId: "user-1",
});
expect(mocks.events).toEqual(["adapter-validation", "tx"]);
expect(mocks.validateProjectAdapterAgainstCurrentContract).toHaveBeenCalledWith({
connectionId: "connection-1",
externalProjectNumber: "P-100",
});
expect(mocks.stateUpdateMany).toHaveBeenCalledWith({
where: expect.objectContaining({
id: "state-1",
revision: 5,
tenantId: "tenant-1",
observedFingerprint: fingerprint,
}),
data: expect.objectContaining({
status: "active",
approvedFingerprint: fingerprint,
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
}),
});
expect(mocks.reportUpdateMany).toHaveBeenCalledWith({
where: expect.objectContaining({
tenantId: "tenant-1",
dataConnectionId: "connection-1",
capability: "project-import",
resolvedAt: null,
}),
data: expect.objectContaining({ resolvedByUserId: "user-1" }),
});
});
});
describe("KWP scoped contract capability state", () => {
it("pauses only the drifted family while all other scoped capabilities remain active", async () => {
const capabilities = ["activity", "address", "archive", "project", "schedule"] as const;
mocks.loadScopedSemanticContracts.mockResolvedValue(
capabilities.map((capability) => ({
apiVersion: "v1",
capability,
semanticFingerprint: capability === "address" ? "b".repeat(64) : "a".repeat(64),
consumedContract: { capability, response: { type: capability === "address" ? "integer" : "string" } },
}))
);
mocks.stateFindUnique.mockImplementation(async (query) => {
const capability = query.where.tenantId_dataConnectionId_capability.capability as string;
return {
id: `state-${capability}`,
status: "active",
approvedFingerprint: "a".repeat(64),
};
});
mocks.snapshotFindUnique.mockResolvedValue({
consumedContract: { capability: "address", response: { type: "string" } },
});
const result = await runKwpScopedContractSentinel({ connectionId: "connection-1" });
expect(result.address).toMatchObject({
status: "paused",
fingerprint: "b".repeat(64),
previousFingerprint: "a".repeat(64),
});
expect(result.activity.status).toBe("unchanged");
expect(result.archive.status).toBe("unchanged");
expect(result.project.status).toBe("unchanged");
expect(result.schedule.status).toBe("unchanged");
expect(mocks.stateUpdate).toHaveBeenCalledTimes(5);
expect(mocks.stateUpdate).toHaveBeenCalledWith({
where: { id: "state-kwp-scoped-address" },
data: expect.objectContaining({
status: "paused",
reasonCode: "kwp.address.contract_drift",
observedFingerprint: "b".repeat(64),
}),
});
expect(mocks.reportCreate).toHaveBeenCalledWith({
data: expect.objectContaining({
capability: "kwp-scoped-address",
code: "kwp.address.contract_drift",
}),
});
expect(mocks.notify).toHaveBeenCalledTimes(1);
});
it("initializes all five capabilities independently on a first revision", async () => {
const capabilities = ["activity", "address", "archive", "project", "schedule"] as const;
mocks.loadScopedSemanticContracts.mockResolvedValue(
capabilities.map((capability, index) => ({
apiVersion: "v1",
capability,
semanticFingerprint: String(index + 1).repeat(64),
consumedContract: { capability },
}))
);
mocks.stateFindUnique.mockResolvedValue(null);
const result = await runKwpScopedContractSentinel({ connectionId: "connection-1" });
expect(Object.values(result).map((entry) => entry.status)).toEqual(["initialized", "initialized", "initialized", "initialized", "initialized"]);
expect(mocks.stateCreate).toHaveBeenCalledTimes(5);
expect(mocks.snapshotUpsert).toHaveBeenCalledTimes(5);
});
});
@@ -0,0 +1,190 @@
// Generated by scripts/generate-kwp-scoped-contract.mjs. Do not edit manually.
export const KWP_SCOPED_OPERATION_INVENTORY = Object.freeze({
sourceOperationCount: 554,
scopedOperationCount: 113,
readOperationCount: 77,
mutationOperationCount: 36,
excludedOperationCount: 441,
} as const);
export const KWP_SCOPED_OPERATIONS = Object.freeze([
{ id: "aktivitaetAddAktivitaet", capability: "activity", mode: "mutation", method: "POST", path: "/api/Aktivitaet/AddAktivitaet" },
{ id: "aktivitaetAddAktivitaetBase", capability: "activity", mode: "mutation", method: "POST", path: "/api/Aktivitaet/AddAktivitaetBase" },
{ id: "aktivitaetAddHilfreich", capability: "activity", mode: "mutation", method: "POST", path: "/api/Aktivitaet/AddHilfreich" },
{ id: "aktivitaetAddInfoEintrag", capability: "activity", mode: "mutation", method: "POST", path: "/api/Aktivitaet/AddInfoEintrag" },
{ id: "aktivitaetAddVerknuepfung", capability: "activity", mode: "mutation", method: "POST", path: "/api/Aktivitaet/AddVerknuepfung" },
{ id: "aktivitaetAddZusatzadresse", capability: "activity", mode: "mutation", method: "POST", path: "/api/Aktivitaet/AddZusatzadresse" },
{ id: "aktivitaetDeleteHilfreich", capability: "activity", mode: "mutation", method: "POST", path: "/api/Aktivitaet/DeleteHilfreich" },
{ id: "aktivitaetDeleteInfoEintrag", capability: "activity", mode: "mutation", method: "DELETE", path: "/api/Aktivitaet/DeleteInfoEintrag" },
{ id: "aktivitaetDeleteVerknuepfung", capability: "activity", mode: "mutation", method: "POST", path: "/api/Aktivitaet/DeleteVerknuepfung" },
{ id: "aktivitaetDeleteZusatzadresse", capability: "activity", mode: "mutation", method: "POST", path: "/api/Aktivitaet/DeleteZusatzadresse" },
{ id: "aktivitaetLoadAktivitaetTerminIdGet", capability: "activity", mode: "read", method: "GET", path: "/api/Aktivitaet/LoadAktivitaetTerminId" },
{ id: "aktivitaetLoadAktivitaetTerminIdPost", capability: "activity", mode: "read", method: "POST", path: "/api/Aktivitaet/LoadAktivitaetTerminId" },
{ id: "aktivitaetLoadArten", capability: "activity", mode: "read", method: "GET", path: "/api/Aktivitaet/LoadArten" },
{ id: "aktivitaetLoadKennzeichen", capability: "activity", mode: "read", method: "GET", path: "/api/Aktivitaet/LoadKennzeichen" },
{ id: "aktivitaetSaveAktivitaetProperties", capability: "activity", mode: "mutation", method: "POST", path: "/api/Aktivitaet/SaveAktivitaetProperties" },
{ id: "aktivitaetSaveInfoEintrag", capability: "activity", mode: "mutation", method: "POST", path: "/api/Aktivitaet/SaveInfoEintrag" },
{ id: "aktivitaetSaveInformierteBenutzer", capability: "activity", mode: "mutation", method: "POST", path: "/api/Aktivitaet/SaveInformierteBenutzer" },
{
id: "aktivitaetSaveInformierteBenutzerProperties",
capability: "activity",
mode: "mutation",
method: "POST",
path: "/api/Aktivitaet/SaveInformierteBenutzerProperties",
},
{ id: "aktivitaetSaveZusatzadresse", capability: "activity", mode: "mutation", method: "POST", path: "/api/Aktivitaet/SaveZusatzadresse" },
{ id: "aktivitaetenverwaltungCount", capability: "activity", mode: "read", method: "POST", path: "/api/Aktivitaetenverwaltung/Count" },
{ id: "aktivitaetenverwaltungGetSetup", capability: "activity", mode: "read", method: "GET", path: "/api/Aktivitaetenverwaltung/GetSetup" },
{ id: "aktivitaetenverwaltungLoadAdressen", capability: "activity", mode: "read", method: "GET", path: "/api/Aktivitaetenverwaltung/LoadAdressen" },
{ id: "aktivitaetenverwaltungLoadAktivitaet", capability: "activity", mode: "read", method: "GET", path: "/api/Aktivitaetenverwaltung/LoadAktivitaet" },
{ id: "aktivitaetenverwaltungLoadAktivitaeten", capability: "activity", mode: "read", method: "GET", path: "/api/Aktivitaetenverwaltung/LoadAktivitaeten" },
{
id: "aktivitaetenverwaltungLoadAktivitaetenByAdresskuerzel",
capability: "activity",
mode: "read",
method: "GET",
path: "/api/Aktivitaetenverwaltung/LoadAktivitaetenByAdresskuerzel",
},
{
id: "aktivitaetenverwaltungLoadAktivitaetenByVorgang",
capability: "activity",
mode: "read",
method: "GET",
path: "/api/Aktivitaetenverwaltung/LoadAktivitaetenByVorgang",
},
{ id: "aktivitaetenverwaltungLoadEinstellungen", capability: "activity", mode: "read", method: "GET", path: "/api/Aktivitaetenverwaltung/LoadEinstellungen" },
{
id: "aktivitaetenverwaltungLoadVerknuepfungen",
capability: "activity",
mode: "read",
method: "GET",
path: "/api/Aktivitaetenverwaltung/LoadVerknuepfungen",
},
{
id: "aktivitaetenverwaltungSaveEinstellungen",
capability: "activity",
mode: "mutation",
method: "POST",
path: "/api/Aktivitaetenverwaltung/SaveEinstellungen",
},
{ id: "aktivitaetenverwaltungSearch", capability: "activity", mode: "read", method: "POST", path: "/api/Aktivitaetenverwaltung/Search" },
{ id: "adresseAddAdresse", capability: "address", mode: "mutation", method: "POST", path: "/api/Adresse/AddAdresse" },
{ id: "adresseAddAnsprechpartner", capability: "address", mode: "mutation", method: "POST", path: "/api/Adresse/AddAnsprechpartner" },
{ id: "adresseAddKontakt", capability: "address", mode: "mutation", method: "POST", path: "/api/Adresse/AddKontakt" },
{ id: "adresseCheckDebitKreditNummerVergeben", capability: "address", mode: "read", method: "POST", path: "/api/Adresse/CheckDebitKreditNummerVergeben" },
{ id: "adresseGetDebitKreditNummer", capability: "address", mode: "read", method: "POST", path: "/api/Adresse/GetDebitKreditNummer" },
{ id: "adresseGetGeoLocation", capability: "address", mode: "read", method: "POST", path: "/api/Adresse/GetGeoLocation" },
{ id: "adresseGetSetup", capability: "address", mode: "read", method: "GET", path: "/api/Adresse/GetSetup" },
{ id: "adresseLoadAdressDetails", capability: "address", mode: "read", method: "GET", path: "/api/Adresse/LoadAdressDetails" },
{ id: "adresseLoadAdressKomplett", capability: "address", mode: "read", method: "GET", path: "/api/Adresse/LoadAdressKomplett" },
{ id: "adresseLoadAnreden", capability: "address", mode: "read", method: "GET", path: "/api/Adresse/LoadAnreden" },
{ id: "adresseLoadAnruferInformation", capability: "address", mode: "read", method: "GET", path: "/api/Adresse/LoadAnruferInformation" },
{ id: "adresseLoadAnsprechpartnerById", capability: "address", mode: "read", method: "GET", path: "/api/Adresse/LoadAnsprechpartnerById" },
{ id: "adresseLoadBriefanreden", capability: "address", mode: "read", method: "GET", path: "/api/Adresse/LoadBriefanreden" },
{ id: "adresseLoadSelekts", capability: "address", mode: "read", method: "GET", path: "/api/Adresse/LoadSelekts" },
{ id: "adresseLoadWunschtermine", capability: "address", mode: "read", method: "GET", path: "/api/Adresse/LoadWunschtermine" },
{ id: "adresseRemoveAnsprechpartner", capability: "address", mode: "mutation", method: "POST", path: "/api/Adresse/RemoveAnsprechpartner" },
{ id: "adresseRemoveKontakt", capability: "address", mode: "mutation", method: "POST", path: "/api/Adresse/RemoveKontakt" },
{ id: "adresseSaveAdresse", capability: "address", mode: "mutation", method: "POST", path: "/api/Adresse/SaveAdresse" },
{ id: "adresseSaveAnsprechpartner", capability: "address", mode: "mutation", method: "POST", path: "/api/Adresse/SaveAnsprechpartner" },
{ id: "adresseSaveKontakt", capability: "address", mode: "mutation", method: "POST", path: "/api/Adresse/SaveKontakt" },
{ id: "adresseSearch", capability: "address", mode: "read", method: "POST", path: "/api/Adresse/Search" },
{ id: "adresseSearchBenutzerfeldInhalt", capability: "address", mode: "read", method: "POST", path: "/api/Adresse/SearchBenutzerfeldInhalt" },
{ id: "adresseSearchKontakt", capability: "address", mode: "read", method: "POST", path: "/api/Adresse/SearchKontakt" },
{ id: "archivExternalCountHeader", capability: "archive", mode: "read", method: "GET", path: "/api/archiv-extern/CountHeader" },
{ id: "archivExternalDeleteEintrag", capability: "archive", mode: "mutation", method: "DELETE", path: "/api/archiv-extern/DeleteEintrag" },
{ id: "archivExternalExportDatei", capability: "archive", mode: "read", method: "GET", path: "/api/archiv-extern/ExportDatei" },
{ id: "archivExternalGetBezug", capability: "archive", mode: "read", method: "GET", path: "/api/archiv-extern/GetBezug" },
{ id: "archivExternalGetSetup", capability: "archive", mode: "read", method: "GET", path: "/api/archiv-extern/GetSetup" },
{ id: "archivExternalImportAdditionalDatei", capability: "archive", mode: "mutation", method: "POST", path: "/api/archiv-extern/ImportAdditionalDatei" },
{ id: "archivExternalImportDatei", capability: "archive", mode: "mutation", method: "POST", path: "/api/archiv-extern/ImportDatei" },
{ id: "archivExternalLoadDateienByVerzeichnisId", capability: "archive", mode: "read", method: "GET", path: "/api/archiv-extern/LoadDateienByVerzeichnisId" },
{ id: "archivExternalLoadEinstellungen", capability: "archive", mode: "read", method: "GET", path: "/api/archiv-extern/LoadEinstellungen" },
{ id: "archivExternalLoadEintragDetails", capability: "archive", mode: "read", method: "GET", path: "/api/archiv-extern/LoadEintragDetails" },
{
id: "archivExternalLoadLetzteRevisionArchivEintragFilesForIds",
capability: "archive",
mode: "read",
method: "POST",
path: "/api/archiv-extern/LoadLetzteRevisionArchivEintragFilesForIds",
},
{ id: "archivExternalLoadVerzeichnisse", capability: "archive", mode: "read", method: "GET", path: "/api/archiv-extern/LoadVerzeichnisse" },
{
id: "archivExternalSearchDateienByVerzeichnisId",
capability: "archive",
mode: "read",
method: "GET",
path: "/api/archiv-extern/SearchDateienByVerzeichnisId",
},
{ id: "archivExternalSearchVorgaenge", capability: "archive", mode: "read", method: "POST", path: "/api/archiv-extern/SearchVorgaenge" },
{ id: "projektLoad", capability: "project", mode: "read", method: "GET", path: "/api/Projekt/Load" },
{ id: "projektLoadKategorien", capability: "project", mode: "read", method: "GET", path: "/api/Projekt/LoadKategorien" },
{ id: "projektLoadSachbearbeiter", capability: "project", mode: "read", method: "GET", path: "/api/Projekt/LoadSachbearbeiter" },
{ id: "projektSave", capability: "project", mode: "mutation", method: "POST", path: "/api/Projekt/Save" },
{ id: "projektSearch", capability: "project", mode: "read", method: "POST", path: "/api/Projekt/Search" },
{ id: "projektampelGetSetup", capability: "project", mode: "read", method: "GET", path: "/api/Projektampel/GetSetup" },
{ id: "projektampelLoadBenutzerDetails", capability: "project", mode: "read", method: "GET", path: "/api/Projektampel/LoadBenutzerDetails" },
{ id: "projektampelLoadBenutzerNachFilter", capability: "project", mode: "read", method: "GET", path: "/api/Projektampel/LoadBenutzerNachFilter" },
{ id: "projektampelLoadEinstellungen", capability: "project", mode: "read", method: "GET", path: "/api/Projektampel/LoadEinstellungen" },
{ id: "projektampelLoadProjektDetailsGet", capability: "project", mode: "read", method: "GET", path: "/api/Projektampel/LoadProjektDetails" },
{ id: "projektampelLoadProjektDetailsPost", capability: "project", mode: "read", method: "POST", path: "/api/Projektampel/LoadProjektDetails" },
{ id: "projektampelLoadProjekteNachFilter", capability: "project", mode: "read", method: "GET", path: "/api/Projektampel/LoadProjekteNachFilter" },
{
id: "projektampelResetBenutzergruppenFilter",
capability: "project",
mode: "mutation",
method: "POST",
path: "/api/Projektampel/ResetBenutzergruppenFilter",
},
{ id: "projektampelResetProjektFilter", capability: "project", mode: "mutation", method: "POST", path: "/api/Projektampel/ResetProjektFilter" },
{ id: "projektampelSaveEinstellungen", capability: "project", mode: "mutation", method: "POST", path: "/api/Projektampel/SaveEinstellungen" },
{ id: "projektampelSearch", capability: "project", mode: "read", method: "POST", path: "/api/Projektampel/Search" },
{ id: "vorgangAnzeigeGetSetup", capability: "project", mode: "read", method: "GET", path: "/api/VorgangAnzeige/GetSetup" },
{ id: "vorgangAnzeigeLoadAdressen", capability: "project", mode: "read", method: "GET", path: "/api/VorgangAnzeige/LoadAdressen" },
{ id: "vorgangAnzeigeLoadAngebote", capability: "project", mode: "read", method: "POST", path: "/api/VorgangAnzeige/LoadAngebote" },
{ id: "vorgangAnzeigeLoadAnzahlen", capability: "project", mode: "read", method: "GET", path: "/api/VorgangAnzeige/LoadAnzahlen" },
{ id: "vorgangAnzeigeLoadBestellungen", capability: "project", mode: "read", method: "POST", path: "/api/VorgangAnzeige/LoadBestellungen" },
{ id: "vorgangAnzeigeLoadDetails", capability: "project", mode: "read", method: "GET", path: "/api/VorgangAnzeige/LoadDetails" },
{ id: "vorgangAnzeigeLoadEingangsrechnungen", capability: "project", mode: "read", method: "POST", path: "/api/VorgangAnzeige/LoadEingangsrechnungen" },
{ id: "vorgangAnzeigeLoadMontageauftraege", capability: "project", mode: "read", method: "POST", path: "/api/VorgangAnzeige/LoadMontageauftraege" },
{ id: "vorgangAnzeigeLoadNachtraege", capability: "project", mode: "read", method: "POST", path: "/api/VorgangAnzeige/LoadNachtraege" },
{ id: "vorgangAnzeigeLoadPositionen", capability: "project", mode: "read", method: "POST", path: "/api/VorgangAnzeige/LoadPositionen" },
{ id: "vorgangAnzeigeLoadRechnungen", capability: "project", mode: "read", method: "POST", path: "/api/VorgangAnzeige/LoadRechnungen" },
{ id: "vorgangAnzeigeLoadRegieauftraege", capability: "project", mode: "read", method: "POST", path: "/api/VorgangAnzeige/LoadRegieauftraege" },
{ id: "vorgangAnzeigeLoadTableMeta", capability: "project", mode: "read", method: "GET", path: "/api/VorgangAnzeige/LoadTableMeta" },
{ id: "vorgangAnzeigeLoadVorgaenge", capability: "project", mode: "read", method: "GET", path: "/api/VorgangAnzeige/LoadVorgaenge" },
{ id: "vorgangAnzeigeSaveTableMeta", capability: "project", mode: "mutation", method: "POST", path: "/api/VorgangAnzeige/SaveTableMeta" },
{ id: "vorgangInfoLoadVorgangInfo", capability: "project", mode: "read", method: "GET", path: "/api/VorgangInfo/LoadVorgangInfo" },
{ id: "monteursteuerungGetSetup", capability: "schedule", mode: "read", method: "GET", path: "/api/Monteursteuerung/GetSetup" },
{ id: "monteursteuerungLoadTermine", capability: "schedule", mode: "read", method: "POST", path: "/api/Monteursteuerung/LoadTermine" },
{
id: "monteursteuerungLoadTermineProjektplanung",
capability: "schedule",
mode: "read",
method: "POST",
path: "/api/Monteursteuerung/LoadTermineProjektplanung",
},
{ id: "terminDeleteTermin", capability: "schedule", mode: "mutation", method: "POST", path: "/api/Termin/DeleteTermin" },
{ id: "terminGetTeilnehmerverfuegbargeit", capability: "schedule", mode: "read", method: "POST", path: "/api/Termin/GetTeilnehmerverfuegbargeit" },
{ id: "terminGetTerminUeberschneidungen", capability: "schedule", mode: "read", method: "POST", path: "/api/Termin/GetTerminUeberschneidungen" },
{ id: "terminLoadEigeneTermine", capability: "schedule", mode: "read", method: "GET", path: "/api/Termin/LoadEigeneTermine" },
{ id: "terminLoadFeiertage", capability: "schedule", mode: "read", method: "GET", path: "/api/Termin/LoadFeiertage" },
{
id: "terminLoadLastWartungAuftragTerminIntervall",
capability: "schedule",
mode: "read",
method: "GET",
path: "/api/Termin/LoadLastWartungAuftragTerminIntervall",
},
{ id: "terminLoadTerminById", capability: "schedule", mode: "read", method: "GET", path: "/api/Termin/LoadTerminById" },
{ id: "terminLoadTermine", capability: "schedule", mode: "read", method: "GET", path: "/api/Termin/LoadTermine" },
{ id: "terminPublishTermin", capability: "schedule", mode: "mutation", method: "POST", path: "/api/Termin/PublishTermin" },
{ id: "terminSaveTermin", capability: "schedule", mode: "mutation", method: "POST", path: "/api/Termin/SaveTermin" },
{ id: "terminSaveTerminAktivitaet", capability: "schedule", mode: "mutation", method: "POST", path: "/api/Termin/SaveTerminAktivitaet" },
] as const);
export type KwpScopedOperation = (typeof KWP_SCOPED_OPERATIONS)[number];
export type KwpScopedOperationId = KwpScopedOperation["id"];
export type KwpReadOperationId = Extract<KwpScopedOperation, { readonly mode: "read" }>["id"];
export type KwpMutationOperationId = Extract<KwpScopedOperation, { readonly mode: "mutation" }>["id"];
export type KwpCapability = KwpScopedOperation["capability"];
@@ -0,0 +1,156 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const executeKwpReadOperation = vi.fn();
vi.mock("./resource-client.server.js", () => ({ executeKwpReadOperation }));
describe("KWP inbound reader", () => {
beforeEach(() => {
executeKwpReadOperation.mockReset();
});
it("normalizes plantafel, activity and material data without private records", async () => {
executeKwpReadOperation.mockImplementation(async ({ operationId, operationInput }) => {
if (operationId === "monteursteuerungLoadTermineProjektplanung") {
return [{
projektnummer: "P-100",
termine: [
{ terminId: 1, terminVon: "2026-08-01T08:00:00.000Z", terminBis: null, betreff: "Montage", beschreibung: "Vor Ort", statusId: 5, typId: 2, privat: false },
{ terminId: 2, terminVon: "2026-08-02T08:00:00.000Z", terminBis: null, betreff: "Privat", beschreibung: null, statusId: 5, typId: 2, privat: true },
],
}];
}
if (operationId === "aktivitaetenverwaltungLoadAktivitaetenByVorgang") {
expect(operationInput.query).toMatchObject({ vorgangNr: "P-100", vorgangArt: 0, offset: 0, count: 100 });
return [
{ aktivitaetenId: 10, betreff: "Rückruf", status: 200, privat: false, datumZuErledigenBis: "2026-08-03T10:00:00.000Z" },
{ aktivitaetenId: 11, betreff: "Nicht übernehmen", status: 100, privat: true },
];
}
if (operationId === "vorgangAnzeigeLoadPositionen") {
expect(operationInput.body).toMatchObject({ art: 1, vorgangNr: "P-100", offset: 0, count: 100, mitLangtext: true });
return [{ positionNummer: "01.01", menge: 2, text: "Ventil", einheit: "Stk", positionKennzeichen: 0, einzelpreis: 12.5, gesamtpreis: 25, langtext: "DN 20" }];
}
if (operationId === "archivExternalLoadVerzeichnisse") {
return { verzeichnisId: 0, benutzerOrdner: [], standardOrdner: [], anzahlEintraege: 1 };
}
if (operationId === "archivExternalLoadDateienByVerzeichnisId") {
return [{
betreff: "Plan",
dokumenttyp: "ZEICHNUNG",
letzteAenderungAm: "2026-08-01T12:00:00.000Z",
headerId: 20,
ordnerId: 0,
files: [{ id: 21, revisionId: 22, revision: 1, dateityp: "PDF", dateiname: "plan.pdf", link: false, sizeInByte: 123 }],
}];
}
throw new Error(`unexpected ${operationId}`);
});
const { loadKwpProjectInboundSnapshot } = await import("./inbound-reader.js");
const result = await loadKwpProjectInboundSnapshot({
connectionId: "connection_1",
externalProjectNumber: " P-100 ",
now: new Date("2026-07-24T00:00:00.000Z"),
});
expect(result.appointments).toEqual([{
externalId: "1",
title: "Montage",
description: "Vor Ort",
startsAt: "2026-08-01T08:00:00.000Z",
endsAt: null,
statusId: 5,
typeId: 2,
}]);
expect(result.tasks).toEqual([{
externalId: "10",
title: "Rückruf",
status: "in_progress",
deadline: "2026-08-03T10:00:00.000Z",
completedAt: null,
}]);
expect(result.materialPositions[0]).toMatchObject({ externalId: "P-100:01.01", text: "Ventil", totalPrice: 25 });
expect(executeKwpReadOperation).not.toHaveBeenCalledWith(expect.objectContaining({
operationId: "archivExternalLoadVerzeichnisse",
}));
});
it("discovers large archive trees in resumable bounded batches", async () => {
executeKwpReadOperation.mockImplementation(async ({ operationId, operationInput }) => {
const folderId = operationInput.query.verzeichnisId as number;
if (operationId === "archivExternalLoadVerzeichnisse") {
const childFolderIds = [-2, -1, 1, 2, 3, 4];
return {
verzeichnisId: folderId,
benutzerOrdner: folderId === 0
? childFolderIds.map((id) => ({ id, bezeichnung: `Ordner ${id}`, anzahlEintraege: 1, gesperrt: false }))
: [],
standardOrdner: [],
anzahlEintraege: 1,
};
}
if (operationId === "archivExternalLoadDateienByVerzeichnisId") {
return [{
betreff: `Plan ${folderId}`,
dokumenttyp: "ZEICHNUNG",
letzteAenderungAm: null,
headerId: 100 + folderId,
ordnerId: folderId,
files: [{ id: 200 + folderId, revisionId: 300 + folderId, revision: 1, dateityp: "PDF", dateiname: `plan-${folderId}.pdf`, link: false, sizeInByte: 123 }],
}];
}
throw new Error(`unexpected ${operationId}`);
});
const { loadKwpArchiveDiscoveryBatch } = await import("./inbound-reader.js");
const first = await loadKwpArchiveDiscoveryBatch({
connectionId: "connection_1",
externalProjectNumber: "P-100",
});
expect(first).toMatchObject({ processedFolders: 5 });
expect(first.archiveFiles).toHaveLength(5);
expect(first.cursor).toEqual({ pendingFolderIds: [3, 4], visitedFolderIds: [0, -2, -1, 1, 2] });
const second = await loadKwpArchiveDiscoveryBatch({
connectionId: "connection_1",
externalProjectNumber: "P-100",
cursor: first.cursor!,
});
expect(second).toMatchObject({ processedFolders: 2, cursor: null });
expect(second.archiveFiles.map((file) => file.externalId)).toEqual(["103:203:303", "104:204:304"]);
await expect(loadKwpArchiveDiscoveryBatch({
connectionId: "connection_1",
externalProjectNumber: "P-100",
cursor: { pendingFolderIds: [2_147_483_648], visitedFolderIds: [] },
})).rejects.toThrow("KWP archive cursor is invalid.");
});
it("pages with stable offsets and fails closed at the bounded ceiling", async () => {
executeKwpReadOperation.mockImplementation(async ({ operationId, operationInput }) => {
if (operationId === "monteursteuerungLoadTermineProjektplanung") return [];
if (operationId === "vorgangAnzeigeLoadPositionen") return [];
if (operationId === "archivExternalLoadVerzeichnisse") return { verzeichnisId: 0, benutzerOrdner: [], standardOrdner: [], anzahlEintraege: 0 };
if (operationId === "archivExternalLoadDateienByVerzeichnisId") return [];
if (operationId === "aktivitaetenverwaltungLoadAktivitaetenByVorgang") {
const offset = operationInput.query.offset as number;
return Array.from({ length: 100 }, (_, index) => ({
aktivitaetenId: offset + index,
betreff: "Aktivität",
status: 100,
privat: false,
}));
}
throw new Error(`unexpected ${operationId}`);
});
const { loadKwpProjectInboundSnapshot } = await import("./inbound-reader.js");
await expect(loadKwpProjectInboundSnapshot({
connectionId: "connection_1",
externalProjectNumber: "P-100",
})).rejects.toEqual(expect.objectContaining({ area: "activity" }));
const offsets = executeKwpReadOperation.mock.calls
.filter(([input]) => input.operationId === "aktivitaetenverwaltungLoadAktivitaetenByVorgang")
.map(([input]) => input.operationInput.query.offset);
expect(offsets).toEqual([0, 100, 200, 300, 400]);
});
});
@@ -0,0 +1,431 @@
import { z } from "zod";
import { executeKwpReadOperation } from "./resource-client.server.js";
const PAGE_SIZE = 100;
const MAX_PAGED_ITEMS = 500;
const ARCHIVE_FOLDER_BATCH_SIZE = 5;
const MAX_ARCHIVE_FOLDERS = 1_000;
const MAX_ARCHIVE_FILE_BYTES = 100 * 1024 * 1024;
const MIN_KWP_FOLDER_ID = -2_147_483_648;
const MAX_KWP_FOLDER_ID = 2_147_483_647;
const PROJECT_RESULT_KIND = 1;
const PROJECT_ARCHIVE_REFERENCE_KIND = 1;
const nullableText = z.string().nullable().optional();
const nullableDate = z.string().datetime({ offset: true }).nullable().optional();
const appointmentSchema = z.object({
terminId: z.number().int(),
terminVon: nullableDate,
terminBis: nullableDate,
betreff: nullableText,
beschreibung: nullableText,
statusId: z.number().int(),
typId: z.number().int(),
privat: z.boolean(),
}).passthrough();
const projectScheduleSchema = z.object({
projektnummer: nullableText,
termine: z.array(appointmentSchema).nullable().optional(),
}).passthrough();
const activitySchema = z.object({
aktivitaetenId: z.number().int(),
betreff: nullableText,
datumWiedervorlage: nullableDate,
datumZuErledigenBis: nullableDate,
datumErledigt: nullableDate,
status: z.union([z.literal(100), z.literal(200), z.literal(210), z.literal(300)]),
privat: z.boolean().nullable().optional(),
}).passthrough();
const materialPositionSchema = z.object({
positionNummer: nullableText,
menge: z.number().finite().nullable().optional(),
text: nullableText,
einheit: nullableText,
positionKennzeichen: z.number().int(),
einzelpreis: z.number().finite().nullable().optional(),
gesamtpreis: z.number().finite().nullable().optional(),
langtext: nullableText,
}).passthrough();
const archiveFolderSchema = z.object({
id: z.number().int(),
bezeichnung: nullableText,
anzahlEintraege: z.number().int(),
gesperrt: z.boolean(),
}).passthrough();
const archiveDirectorySchema = z.object({
verzeichnisId: z.number().int(),
benutzerOrdner: z.array(archiveFolderSchema).nullable().optional(),
standardOrdner: z.array(archiveFolderSchema).nullable().optional(),
anzahlEintraege: z.number().int(),
}).passthrough();
const archiveEntryFileSchema = z.object({
id: z.number().int(),
revisionId: z.number().int(),
revision: z.number().int(),
dateityp: nullableText,
dateiname: nullableText,
link: z.boolean(),
sizeInByte: z.number().int().nullable().optional(),
}).passthrough();
const archiveEntrySchema = z.object({
betreff: nullableText,
dokumenttyp: nullableText,
letzteAenderungAm: nullableDate,
headerId: z.number().int(),
ordnerId: z.number().int(),
files: z.array(archiveEntryFileSchema).nullable().optional(),
}).passthrough();
export type KwpInboundAppointment = {
readonly externalId: string;
readonly title: string;
readonly description: string | null;
readonly startsAt: string;
readonly endsAt: string | null;
readonly statusId: number;
readonly typeId: number;
};
export type KwpInboundTask = {
readonly externalId: string;
readonly title: string;
readonly status: "open" | "in_progress" | "blocked" | "done";
readonly deadline: string | null;
readonly completedAt: string | null;
};
export type KwpInboundMaterialPosition = {
readonly externalId: string;
readonly positionNumber: string | null;
readonly text: string;
readonly longText: string | null;
readonly quantity: number | null;
readonly unit: string | null;
readonly unitPrice: number | null;
readonly totalPrice: number | null;
readonly positionMarker: number;
};
export type KwpInboundArchiveFile = {
readonly externalId: string;
readonly headerId: number;
readonly revisionId: number;
readonly revision: number;
readonly folderId: number;
readonly displayName: string;
readonly documentType: string | null;
readonly providerFileType: string | null;
readonly providerSizeBytes: number | null;
readonly lastModifiedAt: string | null;
};
export type KwpProjectInboundSnapshot = {
readonly appointments: readonly KwpInboundAppointment[];
readonly tasks: readonly KwpInboundTask[];
readonly materialPositions: readonly KwpInboundMaterialPosition[];
};
export type KwpInboundArea = "appointments" | "tasks" | "material";
export type KwpArchiveDiscoveryCursor = {
readonly pendingFolderIds: readonly number[];
readonly visitedFolderIds: readonly number[];
};
export type KwpArchiveDiscoveryBatch = {
readonly archiveFiles: readonly KwpInboundArchiveFile[];
readonly processedFolders: number;
readonly cursor: KwpArchiveDiscoveryCursor | null;
};
export class KwpInboundLimitError extends Error {
constructor(readonly area: "activity" | "archive" | "material") {
super(`KWP inbound ${area} result exceeded the bounded import window.`);
this.name = "KwpInboundLimitError";
}
}
export async function loadKwpProjectInboundSnapshot(input: {
readonly connectionId: string;
readonly externalProjectNumber: string;
readonly now?: Date;
}): Promise<KwpProjectInboundSnapshot> {
const projectNumber = normalizeProjectNumber(input.externalProjectNumber);
const now = input.now ?? new Date();
const [appointments, tasks, materialPositions] = await Promise.all([
loadAppointments(input.connectionId, projectNumber, now),
loadTasks(input.connectionId, projectNumber),
loadMaterialPositions(input.connectionId, projectNumber),
]);
return { appointments, tasks, materialPositions };
}
export async function loadKwpProjectInboundArea(input: {
readonly area: KwpInboundArea;
readonly connectionId: string;
readonly externalProjectNumber: string;
readonly now?: Date;
}): Promise<KwpProjectInboundSnapshot> {
const projectNumber = normalizeProjectNumber(input.externalProjectNumber);
const empty = { appointments: [], tasks: [], materialPositions: [] } satisfies KwpProjectInboundSnapshot;
if (input.area === "appointments") {
return { ...empty, appointments: await loadAppointments(input.connectionId, projectNumber, input.now ?? new Date()) };
}
if (input.area === "tasks") {
return { ...empty, tasks: await loadTasks(input.connectionId, projectNumber) };
}
return { ...empty, materialPositions: await loadMaterialPositions(input.connectionId, projectNumber) };
}
export async function loadKwpArchiveDiscoveryBatch(input: {
readonly connectionId: string;
readonly externalProjectNumber: string;
readonly cursor?: KwpArchiveDiscoveryCursor;
}): Promise<KwpArchiveDiscoveryBatch> {
const projectNumber = normalizeProjectNumber(input.externalProjectNumber);
const cursor = normalizeArchiveCursor(input.cursor);
const pending = [...cursor.pendingFolderIds];
const visited = new Set(cursor.visitedFolderIds);
const files: KwpInboundArchiveFile[] = [];
let processedFolders = 0;
while (pending.length > 0 && processedFolders < ARCHIVE_FOLDER_BATCH_SIZE) {
const folderId = pending.shift()!;
if (visited.has(folderId)) continue;
if (visited.size >= MAX_ARCHIVE_FOLDERS) throw new KwpInboundLimitError("archive");
visited.add(folderId);
processedFolders += 1;
const directory = archiveDirectorySchema.parse(await executeKwpReadOperation({
connectionId: input.connectionId,
operationId: "archivExternalLoadVerzeichnisse",
operationInput: {
query: {
bezugsart: PROJECT_ARCHIVE_REFERENCE_KIND,
bezugsnummer: projectNumber,
verzeichnisId: folderId,
},
},
}));
for (const folder of [...(directory.benutzerOrdner ?? []), ...(directory.standardOrdner ?? [])]) {
if (!folder.gesperrt && !visited.has(folder.id) && !pending.includes(folder.id)) pending.push(folder.id);
}
if (new Set([...visited, ...pending]).size > MAX_ARCHIVE_FOLDERS) throw new KwpInboundLimitError("archive");
const entries = await loadPaged("archive", async (offset) => {
const response = await executeKwpReadOperation({
connectionId: input.connectionId,
operationId: "archivExternalLoadDateienByVerzeichnisId",
operationInput: {
query: {
bezugsart: PROJECT_ARCHIVE_REFERENCE_KIND,
bezugsnummer: projectNumber,
verzeichnisId: folderId,
offset,
count: PAGE_SIZE,
},
},
});
return z.array(archiveEntrySchema).parse(response);
});
files.push(...mapArchiveFiles(entries));
}
return {
archiveFiles: deduplicateByExternalId(files),
processedFolders,
cursor: pending.length > 0
? { pendingFolderIds: pending, visitedFolderIds: [...visited] }
: null,
};
}
async function loadAppointments(connectionId: string, projectNumber: string, now: Date): Promise<KwpInboundAppointment[]> {
const from = new Date(now);
from.setUTCMonth(from.getUTCMonth() - 3);
const until = new Date(now);
until.setUTCFullYear(until.getUTCFullYear() + 1);
const response = await executeKwpReadOperation({
connectionId,
operationId: "monteursteuerungLoadTermineProjektplanung",
operationInput: {
body: {
von: from.toISOString(),
bis: until.toISOString(),
nurProjekteMitTerminen: true,
maxAnzahlProjekte: 1_000,
},
},
});
const projects = z.array(projectScheduleSchema).parse(response);
const project = projects.find((entry) => entry.projektnummer?.trim() === projectNumber);
return (project?.termine ?? [])
.filter((entry) => entry.privat !== true && Boolean(entry.terminVon))
.map((entry) => ({
externalId: String(entry.terminId),
title: normalizeText(entry.betreff, `KWP-Termin ${entry.terminId}`),
description: normalizeOptionalText(entry.beschreibung),
startsAt: entry.terminVon!,
endsAt: entry.terminBis ?? null,
statusId: entry.statusId,
typeId: entry.typId,
}));
}
async function loadTasks(connectionId: string, projectNumber: string): Promise<KwpInboundTask[]> {
const rows = await loadPaged("activity", async (offset) => {
const response = await executeKwpReadOperation({
connectionId,
operationId: "aktivitaetenverwaltungLoadAktivitaetenByVorgang",
operationInput: {
query: {
vorgangNr: projectNumber,
vorgangArt: 0,
offset,
count: PAGE_SIZE,
filterTyp: 0,
},
},
});
return z.array(activitySchema).parse(response);
});
return rows
.filter((entry) => entry.privat !== true)
.map((entry) => ({
externalId: String(entry.aktivitaetenId),
title: normalizeText(entry.betreff, `KWP-Aktivität ${entry.aktivitaetenId}`),
status: mapActivityStatus(entry.status),
deadline: entry.datumZuErledigenBis ?? entry.datumWiedervorlage ?? null,
completedAt: entry.status === 300 ? (entry.datumErledigt ?? null) : null,
}));
}
async function loadMaterialPositions(connectionId: string, projectNumber: string): Promise<KwpInboundMaterialPosition[]> {
const rows = await loadPaged("material", async (offset) => {
const response = await executeKwpReadOperation({
connectionId,
operationId: "vorgangAnzeigeLoadPositionen",
operationInput: {
body: {
art: PROJECT_RESULT_KIND,
vorgangNr: projectNumber,
count: PAGE_SIZE,
offset,
mitLangtext: true,
},
},
});
return z.array(materialPositionSchema).parse(response);
});
return rows.map((entry, index) => {
const positionNumber = normalizeOptionalText(entry.positionNummer);
const stablePart = positionNumber ?? `unnummeriert-${index + 1}`;
return {
externalId: `${projectNumber}:${stablePart}`,
positionNumber,
text: normalizeText(entry.text, `KWP-Position ${stablePart}`),
longText: normalizeOptionalText(entry.langtext),
quantity: entry.menge ?? null,
unit: normalizeOptionalText(entry.einheit),
unitPrice: entry.einzelpreis ?? null,
totalPrice: entry.gesamtpreis ?? null,
positionMarker: entry.positionKennzeichen,
};
});
}
function mapArchiveFiles(entries: readonly z.infer<typeof archiveEntrySchema>[]): KwpInboundArchiveFile[] {
const files: KwpInboundArchiveFile[] = [];
for (const entry of entries) {
for (const file of entry.files ?? []) {
if (file.link || (file.sizeInByte ?? 0) > MAX_ARCHIVE_FILE_BYTES) continue;
files.push({
externalId: `${entry.headerId}:${file.id}:${file.revisionId}`,
headerId: entry.headerId,
revisionId: file.revisionId,
revision: file.revision,
folderId: entry.ordnerId,
displayName: normalizeText(file.dateiname, normalizeText(entry.betreff, `KWP-Datei ${file.id}`)),
documentType: normalizeOptionalText(entry.dokumenttyp),
providerFileType: normalizeOptionalText(file.dateityp),
providerSizeBytes: file.sizeInByte ?? null,
lastModifiedAt: entry.letzteAenderungAm ?? null,
});
}
}
return files;
}
function normalizeArchiveCursor(cursor: KwpArchiveDiscoveryCursor | undefined): KwpArchiveDiscoveryCursor {
if (!cursor) return { pendingFolderIds: [0], visitedFolderIds: [] };
const pendingFolderIds = normalizeFolderIds(cursor.pendingFolderIds);
const visitedFolderIds = normalizeFolderIds(cursor.visitedFolderIds);
if (pendingFolderIds.length === 0 || pendingFolderIds.length + visitedFolderIds.length > MAX_ARCHIVE_FOLDERS) {
throw new KwpInboundLimitError("archive");
}
return { pendingFolderIds, visitedFolderIds };
}
function normalizeFolderIds(values: readonly number[]): number[] {
if (
!Array.isArray(values)
|| values.some((value) => !Number.isInteger(value) || value < MIN_KWP_FOLDER_ID || value > MAX_KWP_FOLDER_ID)
) {
throw new Error("KWP archive cursor is invalid.");
}
return [...new Set(values)];
}
async function loadPaged<Row>(
area: "activity" | "archive" | "material",
loadPage: (offset: number) => Promise<readonly Row[]>,
): Promise<Row[]> {
const rows: Row[] = [];
while (rows.length < MAX_PAGED_ITEMS) {
const page = await loadPage(rows.length);
rows.push(...page);
if (page.length < PAGE_SIZE) return rows;
}
throw new KwpInboundLimitError(area);
}
function mapActivityStatus(status: 100 | 200 | 210 | 300): KwpInboundTask["status"] {
if (status === 200) return "in_progress";
if (status === 210) return "blocked";
if (status === 300) return "done";
return "open";
}
function normalizeProjectNumber(value: string): string {
const normalized = value.trim();
if (!normalized || normalized.length > 191) throw new Error("KWP project number is invalid.");
return normalized;
}
function normalizeText(value: string | null | undefined, fallback: string): string {
return normalizeOptionalText(value) ?? fallback;
}
function normalizeOptionalText(value: string | null | undefined): string | null {
const normalized = value?.trim();
return normalized ? normalized.slice(0, 2_000) : null;
}
function deduplicateByExternalId<Row extends { readonly externalId: string }>(rows: readonly Row[]): Row[] {
return [...new Map(rows.map((row) => [row.externalId, row])).values()];
}
export const KWP_INBOUND_BOUNDS = Object.freeze({
archiveFolderBatchSize: ARCHIVE_FOLDER_BATCH_SIZE,
maxArchiveFileBytes: MAX_ARCHIVE_FILE_BYTES,
maxArchiveFolders: MAX_ARCHIVE_FOLDERS,
maxPagedItems: MAX_PAGED_ITEMS,
pageSize: PAGE_SIZE,
});
@@ -0,0 +1,601 @@
import { logActivity } from "@hivegrid/activity";
import { getDbClient } from "@hivegrid/db/client.server";
import type { Prisma } from "@hivegrid/db/prisma-browser";
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
import { auditEvent } from "@hivegrid/foundation";
import {
type KwpInboundAppointment,
type KwpInboundArea,
type KwpInboundMaterialPosition,
type KwpInboundTask,
type KwpProjectInboundSnapshot,
loadKwpProjectInboundArea,
} from "./inbound-reader.js";
import { KwpProjectDomainError } from "./project-domain.server.js";
import { fingerprintKwpSnapshot } from "./resource-client.js";
const APPOINTMENT_ENTITY_TYPE = "kwp_appointment";
const TASK_ENTITY_TYPE = "kwp_activity";
const MATERIAL_ENTITY_TYPE = "kwp_material_position";
type InboundBinding = {
readonly id: string;
readonly externalEntityType: string;
readonly externalId: string;
readonly localId: string;
readonly fingerprint: string;
readonly revision: number;
};
type PreparedInboundSync = {
readonly tenantId: string;
readonly runId: string;
readonly connectionId: string;
readonly projectId: string;
readonly externalProjectNumber: string;
readonly actorUserId: string;
readonly bindings: readonly InboundBinding[];
};
export type KwpInboundSyncResult = {
readonly runId: string;
readonly projectId: string;
readonly appointments: number;
readonly tasks: number;
readonly materialPositions: number;
readonly failedAreas: readonly KwpInboundArea[];
readonly changed: boolean;
};
const INBOUND_AREAS = ["appointments", "tasks", "material"] as const satisfies readonly KwpInboundArea[];
export async function syncKwpProjectInbound(input: {
readonly bindingId: string;
readonly now?: Date;
}): Promise<KwpInboundSyncResult> {
const now = input.now ?? new Date();
const prepared = await prepareInboundSync(normalizeId(input.bindingId), now);
try {
const reads = await Promise.allSettled(INBOUND_AREAS.map(async (area) => ({
area,
snapshot: await loadKwpProjectInboundArea({
area,
connectionId: prepared.connectionId,
externalProjectNumber: prepared.externalProjectNumber,
now,
}),
})));
const successful = reads.flatMap((read) => read.status === "fulfilled" ? [read.value] : []);
if (successful.length === 0) {
const failure = reads.find((read) => read.status === "rejected");
throw failure?.status === "rejected" ? failure.reason : new Error("KWP inbound reads failed.");
}
const failedAreas = INBOUND_AREAS.filter((_, index) => reads[index]?.status === "rejected");
const snapshot: KwpProjectInboundSnapshot = {
appointments: successful.flatMap(({ snapshot: areaSnapshot }) => areaSnapshot.appointments),
tasks: successful.flatMap(({ snapshot: areaSnapshot }) => areaSnapshot.tasks),
materialPositions: successful.flatMap(({ snapshot: areaSnapshot }) => areaSnapshot.materialPositions),
};
const result = await applyInboundSnapshot(prepared, snapshot, new Set(successful.map(({ area }) => area)), failedAreas, now);
await finishInboundRun(prepared, result, now);
return result;
} catch (error) {
await failInboundRun(prepared, now);
throw error;
}
}
async function prepareInboundSync(bindingId: string, now: Date): Promise<PreparedInboundSync> {
const tenantId = requireTenantContext();
return getDbClient().$transaction(async (tx) => {
const binding = await tx.appEntityBinding.findFirst({
where: {
id: bindingId,
tenantId,
externalEntityType: "kwp_project",
localEntityType: "project",
state: "active",
},
select: { dataConnectionId: true, externalId: true, localId: true },
});
if (!binding) throw new KwpProjectDomainError("project_not_found");
const [project, connection, bindings] = await Promise.all([
tx.projekt.findFirst({
where: { id: binding.localId, tenantId, archivedAt: null },
select: { id: true, createdByUserId: true },
}),
tx.dataConnection.findFirst({
where: {
id: binding.dataConnectionId,
tenantId,
appId: "kwp",
archivedAt: null,
connectionStatus: { in: ["active", "degraded"] },
},
select: { createdByUserId: true },
}),
tx.appEntityBinding.findMany({
where: {
tenantId,
dataConnectionId: binding.dataConnectionId,
externalEntityType: { in: [APPOINTMENT_ENTITY_TYPE, TASK_ENTITY_TYPE, MATERIAL_ENTITY_TYPE] },
normalizedSnapshot: { path: ["projectId"], equals: binding.localId },
state: { in: ["active", "missing"] },
},
select: {
id: true,
externalEntityType: true,
externalId: true,
localId: true,
fingerprint: true,
revision: true,
},
}),
]);
if (!project || !connection) throw new KwpProjectDomainError("project_not_found");
const actorUserId = await resolveActorUserId(tx, tenantId, connection.createdByUserId ?? project.createdByUserId);
if (!actorUserId) throw new KwpProjectDomainError("project_not_found");
const run = await tx.appSyncRun.create({
data: {
tenantId,
dataConnectionId: binding.dataConnectionId,
kind: "scheduled",
status: "running",
summaryText: "integrations.sync.summary.kwpInboundSyncStarted",
startedAt: now,
},
});
return {
tenantId,
runId: run.id,
connectionId: binding.dataConnectionId,
projectId: project.id,
externalProjectNumber: binding.externalId,
actorUserId,
bindings,
};
});
}
async function applyInboundSnapshot(
prepared: PreparedInboundSync,
snapshot: KwpProjectInboundSnapshot,
successfulAreas: ReadonlySet<KwpInboundArea>,
failedAreas: readonly KwpInboundArea[],
now: Date,
): Promise<KwpInboundSyncResult> {
return getDbClient().$transaction(async (tx) => {
const bindings = new Map(prepared.bindings.map((binding) => [bindingKey(binding.externalEntityType, binding.externalId), binding]));
const seen = new Set<string>();
let changed = false;
for (const appointment of snapshot.appointments) {
const result = await reconcileAppointment(tx, prepared, bindings.get(bindingKey(APPOINTMENT_ENTITY_TYPE, appointment.externalId)), appointment, now);
seen.add(bindingKey(APPOINTMENT_ENTITY_TYPE, appointment.externalId));
changed ||= result;
}
for (const task of snapshot.tasks) {
const result = await reconcileTask(tx, prepared, bindings.get(bindingKey(TASK_ENTITY_TYPE, task.externalId)), task, now);
seen.add(bindingKey(TASK_ENTITY_TYPE, task.externalId));
changed ||= result;
}
for (const position of snapshot.materialPositions) {
const result = await reconcileMaterialPosition(tx, prepared, bindings.get(bindingKey(MATERIAL_ENTITY_TYPE, position.externalId)), position, now);
seen.add(bindingKey(MATERIAL_ENTITY_TYPE, position.externalId));
changed ||= result;
}
for (const binding of prepared.bindings) {
if (!successfulAreas.has(areaForEntityType(binding.externalEntityType))) continue;
if (seen.has(bindingKey(binding.externalEntityType, binding.externalId))) continue;
const updated = await tx.appEntityBinding.updateMany({
where: { id: binding.id, tenantId: prepared.tenantId, revision: binding.revision, state: { in: ["active", "missing"] } },
data: {
state: "missing",
revision: { increment: 1 },
missingSince: now,
},
});
if (updated.count !== 1) throw new KwpProjectDomainError("stale_write");
await recordSyncItem(tx, prepared, binding.externalEntityType, binding.localId, binding.externalId, "skipped", "KWP-Datensatz wurde im aktuellen Abruffenster nicht gefunden.");
changed = true;
}
if (changed) {
await auditEvent({
tenantId: prepared.tenantId,
actorType: "system",
action: "KWP_PROJECT_INBOUND_RECONCILED",
targetType: "project",
targetId: prepared.projectId,
metadata: {
source: "kwp",
appointments: snapshot.appointments.length,
tasks: snapshot.tasks.length,
materialPositions: snapshot.materialPositions.length,
},
}, tx as never);
await logActivity({
tenantId: prepared.tenantId,
actorKind: "system",
activityType: "project_updated",
subjectType: "project",
subjectId: prepared.projectId,
summaryText: "activity.runtime.kwp.inboundDataUpdated",
metadata: { source: "kwp" },
}, { client: tx });
}
return {
runId: prepared.runId,
projectId: prepared.projectId,
appointments: snapshot.appointments.length,
tasks: snapshot.tasks.length,
materialPositions: snapshot.materialPositions.length,
failedAreas,
changed,
};
});
}
async function reconcileAppointment(
tx: Prisma.TransactionClient,
prepared: PreparedInboundSync,
binding: InboundBinding | undefined,
appointment: KwpInboundAppointment,
now: Date,
): Promise<boolean> {
const normalizedSnapshot = { projectId: prepared.projectId, ...appointment };
const fingerprint = fingerprintKwpSnapshot(normalizedSnapshot);
if (!binding) {
const local = await tx.projektTermin.create({
data: {
tenantId: prepared.tenantId,
projektId: prepared.projectId,
createdByUserId: prepared.actorUserId,
titel: appointment.title,
beschreibung: appointment.description,
startAt: new Date(appointment.startsAt),
endAt: appointment.endsAt ? new Date(appointment.endsAt) : null,
status: "geplant",
},
});
await createBinding(tx, prepared, APPOINTMENT_ENTITY_TYPE, "project_appointment", appointment.externalId, local.id, normalizedSnapshot, fingerprint, now);
await recordSyncItem(tx, prepared, APPOINTMENT_ENTITY_TYPE, local.id, appointment.externalId, "created");
return true;
}
if (binding.fingerprint === fingerprint) {
await touchBinding(tx, prepared, binding, normalizedSnapshot, fingerprint, now);
await recordSyncItem(tx, prepared, APPOINTMENT_ENTITY_TYPE, binding.localId, appointment.externalId, "skipped");
return false;
}
const local = await tx.projektTermin.findFirst({ where: { id: binding.localId, tenantId: prepared.tenantId, projektId: prepared.projectId } });
if (!local) throw new KwpProjectDomainError("project_not_found");
await tx.projektTermin.update({
where: { id: local.id },
data: {
titel: appointment.title,
beschreibung: appointment.description,
startAt: new Date(appointment.startsAt),
endAt: appointment.endsAt ? new Date(appointment.endsAt) : null,
archivedAt: null,
},
});
await updateBinding(tx, prepared, binding, normalizedSnapshot, fingerprint, {
title: local.titel,
description: local.beschreibung,
startsAt: local.startAt.toISOString(),
endsAt: local.endAt?.toISOString() ?? null,
}, now);
await recordSyncItem(tx, prepared, APPOINTMENT_ENTITY_TYPE, local.id, appointment.externalId, "updated");
return true;
}
async function reconcileTask(
tx: Prisma.TransactionClient,
prepared: PreparedInboundSync,
binding: InboundBinding | undefined,
task: KwpInboundTask,
now: Date,
): Promise<boolean> {
const normalizedSnapshot = { projectId: prepared.projectId, ...task };
const fingerprint = fingerprintKwpSnapshot(normalizedSnapshot);
if (!binding) {
const local = await tx.task.create({
data: {
tenantId: prepared.tenantId,
createdByUserId: prepared.actorUserId,
assignedToUserId: prepared.actorUserId,
title: task.title,
status: task.status,
priority: "normal",
deadline: task.deadline ? new Date(task.deadline) : null,
linkedEntityType: "project",
linkedEntityId: prepared.projectId,
source: "api",
sourceRef: `kwp:${prepared.connectionId}:${task.externalId}`,
completedAt: task.completedAt ? new Date(task.completedAt) : null,
},
});
await createBinding(tx, prepared, TASK_ENTITY_TYPE, "task", task.externalId, local.id, normalizedSnapshot, fingerprint, now);
await recordSyncItem(tx, prepared, TASK_ENTITY_TYPE, local.id, task.externalId, "created");
return true;
}
if (binding.fingerprint === fingerprint) {
await touchBinding(tx, prepared, binding, normalizedSnapshot, fingerprint, now);
await recordSyncItem(tx, prepared, TASK_ENTITY_TYPE, binding.localId, task.externalId, "skipped");
return false;
}
const local = await tx.task.findFirst({ where: { id: binding.localId, tenantId: prepared.tenantId, linkedEntityType: "project", linkedEntityId: prepared.projectId } });
if (!local) throw new KwpProjectDomainError("project_not_found");
await tx.task.update({
where: { id: local.id },
data: {
title: task.title,
status: task.status,
deadline: task.deadline ? new Date(task.deadline) : null,
completedAt: task.completedAt ? new Date(task.completedAt) : null,
archivedAt: null,
},
});
await updateBinding(tx, prepared, binding, normalizedSnapshot, fingerprint, {
title: local.title,
status: local.status,
deadline: local.deadline?.toISOString() ?? null,
completedAt: local.completedAt?.toISOString() ?? null,
}, now);
await recordSyncItem(tx, prepared, TASK_ENTITY_TYPE, local.id, task.externalId, "updated");
return true;
}
async function reconcileMaterialPosition(
tx: Prisma.TransactionClient,
prepared: PreparedInboundSync,
binding: InboundBinding | undefined,
position: KwpInboundMaterialPosition,
now: Date,
): Promise<boolean> {
const normalizedSnapshot = { projectId: prepared.projectId, ...position };
const fingerprint = fingerprintKwpSnapshot(normalizedSnapshot);
if (!binding) {
const local = await tx.kwpMaterialPosition.create({
data: materialData(prepared, position, fingerprint, now),
});
await createBinding(tx, prepared, MATERIAL_ENTITY_TYPE, MATERIAL_ENTITY_TYPE, position.externalId, local.id, normalizedSnapshot, fingerprint, now);
await recordSyncItem(tx, prepared, MATERIAL_ENTITY_TYPE, local.id, position.externalId, "created");
return true;
}
if (binding.fingerprint === fingerprint) {
await touchBinding(tx, prepared, binding, normalizedSnapshot, fingerprint, now);
await tx.kwpMaterialPosition.updateMany({
where: { id: binding.localId, tenantId: prepared.tenantId, projektId: prepared.projectId },
data: { lastSeenAt: now, lastSyncedAt: now, archivedAt: null },
});
await recordSyncItem(tx, prepared, MATERIAL_ENTITY_TYPE, binding.localId, position.externalId, "skipped");
return false;
}
const local = await tx.kwpMaterialPosition.findFirst({
where: { id: binding.localId, tenantId: prepared.tenantId, projektId: prepared.projectId },
});
if (!local) throw new KwpProjectDomainError("project_not_found");
await tx.kwpMaterialPosition.update({
where: { id: local.id },
data: materialData(prepared, position, fingerprint, now),
});
await updateBinding(tx, prepared, binding, normalizedSnapshot, fingerprint, {
positionNumber: local.positionNumber,
text: local.text,
longText: local.longText,
quantity: decimalText(local.quantity),
unit: local.unit,
unitPrice: decimalText(local.unitPrice),
totalPrice: decimalText(local.totalPrice),
positionMarker: local.positionMarker,
}, now);
await recordSyncItem(tx, prepared, MATERIAL_ENTITY_TYPE, local.id, position.externalId, "updated");
return true;
}
function materialData(
prepared: PreparedInboundSync,
position: KwpInboundMaterialPosition,
fingerprint: string,
now: Date,
) {
return {
tenantId: prepared.tenantId,
dataConnectionId: prepared.connectionId,
projektId: prepared.projectId,
externalId: position.externalId,
positionNumber: position.positionNumber,
text: position.text,
longText: position.longText,
quantity: position.quantity,
unit: position.unit,
unitPrice: position.unitPrice,
totalPrice: position.totalPrice,
positionMarker: position.positionMarker,
normalizedFingerprint: fingerprint,
lastSeenAt: now,
lastSyncedAt: now,
archivedAt: null,
};
}
async function createBinding(
tx: Prisma.TransactionClient,
prepared: PreparedInboundSync,
externalEntityType: string,
localEntityType: string,
externalId: string,
localId: string,
normalizedSnapshot: Record<string, unknown>,
fingerprint: string,
now: Date,
): Promise<void> {
await tx.appEntityBinding.create({
data: {
tenantId: prepared.tenantId,
dataConnectionId: prepared.connectionId,
externalEntityType,
localEntityType,
externalId,
localId,
state: "active",
normalizedSnapshot: normalizedSnapshot as Prisma.InputJsonValue,
fingerprint,
lastSeenAt: now,
lastSyncedAt: now,
},
});
}
async function touchBinding(
tx: Prisma.TransactionClient,
prepared: PreparedInboundSync,
binding: InboundBinding,
normalizedSnapshot: Record<string, unknown>,
fingerprint: string,
now: Date,
): Promise<void> {
const updated = await tx.appEntityBinding.updateMany({
where: { id: binding.id, tenantId: prepared.tenantId, revision: binding.revision, state: { in: ["active", "missing"] } },
data: {
state: "active",
normalizedSnapshot: normalizedSnapshot as Prisma.InputJsonValue,
fingerprint,
revision: { increment: 1 },
lastSeenAt: now,
lastSyncedAt: now,
missingSince: null,
},
});
if (updated.count !== 1) throw new KwpProjectDomainError("stale_write");
}
async function updateBinding(
tx: Prisma.TransactionClient,
prepared: PreparedInboundSync,
binding: InboundBinding,
normalizedSnapshot: Record<string, unknown>,
fingerprint: string,
overwrittenLocalSnapshot: Record<string, unknown>,
now: Date,
): Promise<void> {
const updated = await tx.appEntityBinding.updateMany({
where: { id: binding.id, tenantId: prepared.tenantId, revision: binding.revision, state: { in: ["active", "missing"] } },
data: {
state: "active",
normalizedSnapshot: normalizedSnapshot as Prisma.InputJsonValue,
fingerprint,
overwrittenLocalSnapshot: overwrittenLocalSnapshot as Prisma.InputJsonValue,
revision: { increment: 1 },
lastSeenAt: now,
lastSyncedAt: now,
missingSince: null,
},
});
if (updated.count !== 1) throw new KwpProjectDomainError("stale_write");
}
async function recordSyncItem(
tx: Prisma.TransactionClient,
prepared: PreparedInboundSync,
entityType: string,
entityId: string,
externalId: string,
operation: "created" | "updated" | "skipped",
errorText?: string,
): Promise<void> {
await tx.appSyncItem.create({
data: {
tenantId: prepared.tenantId,
syncRunId: prepared.runId,
entityType,
entityId,
externalId,
operation,
status: errorText || operation === "skipped" ? "skipped" : "synced",
errorText,
},
});
}
async function resolveActorUserId(
tx: Prisma.TransactionClient,
tenantId: string,
preferredUserId: string | null | undefined,
): Promise<string | null> {
if (preferredUserId) {
const membership = await tx.tenantUser.findFirst({
where: { tenantId, userId: preferredUserId },
select: { userId: true },
});
if (membership) return membership.userId;
}
const fallback = await tx.tenantUser.findFirst({
where: { tenantId },
select: { userId: true },
orderBy: { createdAt: "asc" },
});
return fallback?.userId ?? null;
}
async function finishInboundRun(
prepared: PreparedInboundSync,
result: KwpInboundSyncResult,
now: Date,
): Promise<void> {
const itemsTotal = result.appointments + result.tasks + result.materialPositions;
const successfulAreaCount = INBOUND_AREAS.length - result.failedAreas.length;
await getDbClient().appSyncRun.updateMany({
where: { id: prepared.runId, tenantId: prepared.tenantId, status: "running" },
data: {
status: result.failedAreas.length > 0 ? "partial" : "completed",
itemsTotal: itemsTotal + INBOUND_AREAS.length,
itemsSucceeded: itemsTotal + successfulAreaCount,
itemsFailed: result.failedAreas.length,
summaryText: result.failedAreas.length > 0
? "integrations.sync.summary.kwpInboundPartial"
: result.changed
? "integrations.sync.summary.kwpInboundUpdated"
: "integrations.sync.summary.kwpInboundUnchanged",
completedAt: now,
},
});
}
function areaForEntityType(entityType: string): KwpInboundArea {
if (entityType === APPOINTMENT_ENTITY_TYPE) return "appointments";
if (entityType === TASK_ENTITY_TYPE) return "tasks";
return "material";
}
async function failInboundRun(prepared: PreparedInboundSync, now: Date): Promise<void> {
await getDbClient().appSyncRun.updateMany({
where: { id: prepared.runId, tenantId: prepared.tenantId, status: "running" },
data: {
status: "failed",
itemsFailed: 1,
summaryText: "integrations.sync.summary.kwpInboundFailed",
completedAt: now,
},
});
}
function decimalText(value: unknown): string | null {
return value === null || value === undefined ? null : String(value);
}
function bindingKey(entityType: string, externalId: string): string {
return `${entityType}:${externalId}`;
}
function requireTenantContext(): string {
const tenantId = getRlsExecutionContext()?.tenantId?.trim();
if (!tenantId) throw new KwpProjectDomainError("project_not_found");
return tenantId;
}
function normalizeId(value: string): string {
const normalized = value.trim();
if (!/^[A-Za-z0-9_-]{3,191}$/u.test(normalized)) throw new KwpProjectDomainError("project_not_found");
return normalized;
}
@@ -0,0 +1,263 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
auditEvent: vi.fn(),
logActivity: vi.fn(),
loadArea: vi.fn(),
getRlsExecutionContext: vi.fn(),
transaction: vi.fn(),
runUpdateMany: vi.fn(),
bindingFindFirst: vi.fn(),
bindingFindMany: vi.fn(),
bindingCreate: vi.fn(),
bindingUpdateMany: vi.fn(),
projectFindFirst: vi.fn(),
connectionFindFirst: vi.fn(),
tenantUserFindFirst: vi.fn(),
runCreate: vi.fn(),
itemCreate: vi.fn(),
appointmentCreate: vi.fn(),
appointmentFindFirst: vi.fn(),
appointmentUpdate: vi.fn(),
taskCreate: vi.fn(),
taskFindFirst: vi.fn(),
taskUpdate: vi.fn(),
materialCreate: vi.fn(),
materialFindFirst: vi.fn(),
materialUpdate: vi.fn(),
materialUpdateMany: vi.fn(),
events: [] as string[],
}));
vi.mock("@hivegrid/activity", () => ({ logActivity: mocks.logActivity }));
vi.mock("@hivegrid/db/client.server", () => ({
getDbClient: () => ({
$transaction: mocks.transaction,
appSyncRun: { updateMany: mocks.runUpdateMany },
}),
}));
vi.mock("@hivegrid/db/rls-context.server", () => ({ getRlsExecutionContext: mocks.getRlsExecutionContext }));
vi.mock("@hivegrid/foundation", () => ({ auditEvent: mocks.auditEvent }));
vi.mock("./inbound-reader.js", () => ({ loadKwpProjectInboundArea: mocks.loadArea }));
import { syncKwpProjectInbound } from "./inbound-sync.server.js";
const now = new Date("2026-07-24T09:00:00.000Z");
const projectBinding = {
dataConnectionId: "connection-1",
externalId: "P-100",
localId: "project-1",
};
const snapshot = {
appointments: [{
externalId: "appointment-1",
title: "Montage",
description: null,
startsAt: "2026-08-01T08:00:00.000Z",
endsAt: null,
statusId: 1,
typeId: 2,
}],
tasks: [{
externalId: "activity-1",
title: "Rückruf",
status: "open" as const,
deadline: null,
completedAt: null,
}],
materialPositions: [{
externalId: "P-100:01",
positionNumber: "01",
text: "Ventil",
longText: null,
quantity: 2,
unit: "Stk",
unitPrice: 12.5,
totalPrice: 25,
positionMarker: 0,
}],
};
const tx = {
appEntityBinding: {
findFirst: mocks.bindingFindFirst,
findMany: mocks.bindingFindMany,
create: mocks.bindingCreate,
updateMany: mocks.bindingUpdateMany,
},
projekt: { findFirst: mocks.projectFindFirst },
dataConnection: { findFirst: mocks.connectionFindFirst },
tenantUser: { findFirst: mocks.tenantUserFindFirst },
appSyncRun: { create: mocks.runCreate },
appSyncItem: { create: mocks.itemCreate },
projektTermin: {
create: mocks.appointmentCreate,
findFirst: mocks.appointmentFindFirst,
update: mocks.appointmentUpdate,
},
task: {
create: mocks.taskCreate,
findFirst: mocks.taskFindFirst,
update: mocks.taskUpdate,
},
kwpMaterialPosition: {
create: mocks.materialCreate,
findFirst: mocks.materialFindFirst,
update: mocks.materialUpdate,
updateMany: mocks.materialUpdateMany,
},
};
beforeEach(() => {
vi.clearAllMocks();
mocks.events.length = 0;
mocks.getRlsExecutionContext.mockReturnValue({ tenantId: "tenant-1" });
mocks.transaction.mockImplementation(async (callback) => {
mocks.events.push("tx:start");
const value = await callback(tx);
mocks.events.push("tx:end");
return value;
});
mocks.bindingFindFirst.mockResolvedValue(projectBinding);
mocks.bindingFindMany.mockResolvedValue([]);
mocks.bindingCreate.mockResolvedValue({});
mocks.bindingUpdateMany.mockResolvedValue({ count: 1 });
mocks.projectFindFirst.mockResolvedValue({ id: "project-1", createdByUserId: "user-1" });
mocks.connectionFindFirst.mockResolvedValue({ createdByUserId: "user-1" });
mocks.tenantUserFindFirst.mockResolvedValue({ userId: "user-1" });
mocks.runCreate.mockResolvedValue({ id: "run-1" });
mocks.runUpdateMany.mockResolvedValue({ count: 1 });
mocks.itemCreate.mockResolvedValue({});
mocks.appointmentCreate.mockResolvedValue({ id: "appointment-local-1" });
mocks.taskCreate.mockResolvedValue({ id: "task-local-1" });
mocks.materialCreate.mockResolvedValue({ id: "material-local-1" });
mocks.loadArea.mockImplementation(async ({ area }) => {
mocks.events.push(`provider:${area}`);
return {
appointments: area === "appointments" ? snapshot.appointments : [],
tasks: area === "tasks" ? snapshot.tasks : [],
materialPositions: area === "material" ? snapshot.materialPositions : [],
};
});
});
describe("KWP project inbound sync", () => {
it("performs all provider I/O before one atomic local reconciliation", async () => {
await expect(syncKwpProjectInbound({ bindingId: "binding-1", now })).resolves.toMatchObject({
runId: "run-1",
projectId: "project-1",
appointments: 1,
tasks: 1,
materialPositions: 1,
failedAreas: [],
changed: true,
});
expect(mocks.events).toEqual([
"tx:start",
"tx:end",
"provider:appointments",
"provider:tasks",
"provider:material",
"tx:start",
"tx:end",
]);
expect(mocks.appointmentCreate).toHaveBeenCalledWith({ data: expect.objectContaining({ projektId: "project-1", titel: "Montage" }) });
expect(mocks.taskCreate).toHaveBeenCalledWith({ data: expect.objectContaining({
linkedEntityId: "project-1",
source: "api",
sourceRef: "kwp:connection-1:activity-1",
}) });
expect(mocks.materialCreate).toHaveBeenCalledWith({ data: expect.objectContaining({
externalId: "P-100:01",
totalPrice: 25,
}) });
expect(mocks.bindingCreate).toHaveBeenCalledTimes(3);
expect(mocks.itemCreate).toHaveBeenCalledTimes(3);
expect(mocks.itemCreate).toHaveBeenNthCalledWith(1, {
data: expect.objectContaining({ operation: "created", status: "synced" }),
});
expect(mocks.runUpdateMany).toHaveBeenCalledWith(expect.objectContaining({
data: expect.objectContaining({
status: "completed",
itemsTotal: 6,
itemsSucceeded: 6,
}),
}));
expect(mocks.auditEvent).toHaveBeenCalledOnce();
expect(mocks.logActivity).toHaveBeenCalledOnce();
});
it("applies healthy areas and leaves failed-area bindings untouched", async () => {
mocks.bindingFindMany.mockResolvedValueOnce([{
id: "child-binding-1",
externalEntityType: "kwp_appointment",
externalId: "appointment-old",
localId: "appointment-local-old",
fingerprint: "old",
revision: 2,
}]);
mocks.loadArea.mockImplementation(async ({ area }) => {
mocks.events.push(`provider:${area}`);
if (area === "appointments") throw Object.assign(new Error("KWP unavailable"), { code: "provider_outage" });
return {
appointments: [],
tasks: area === "tasks" ? snapshot.tasks : [],
materialPositions: area === "material" ? snapshot.materialPositions : [],
};
});
await expect(syncKwpProjectInbound({ bindingId: "binding-1", now })).resolves.toMatchObject({
appointments: 0,
tasks: 1,
materialPositions: 1,
failedAreas: ["appointments"],
});
expect(mocks.appointmentCreate).not.toHaveBeenCalled();
expect(mocks.taskCreate).toHaveBeenCalledOnce();
expect(mocks.materialCreate).toHaveBeenCalledOnce();
expect(mocks.bindingUpdateMany).not.toHaveBeenCalledWith(expect.objectContaining({
where: expect.objectContaining({ id: "child-binding-1" }),
}));
expect(mocks.runUpdateMany).toHaveBeenCalledWith(expect.objectContaining({
data: expect.objectContaining({
status: "partial",
itemsFailed: 1,
summaryText: "integrations.sync.summary.kwpInboundPartial",
}),
}));
});
it("does not reconcile locally when every provider area fails", async () => {
mocks.loadArea.mockRejectedValue(Object.assign(new Error("KWP unavailable"), { code: "provider_outage" }));
await expect(syncKwpProjectInbound({ bindingId: "binding-1", now })).rejects.toThrow("KWP unavailable");
expect(mocks.appointmentCreate).not.toHaveBeenCalled();
expect(mocks.taskCreate).not.toHaveBeenCalled();
expect(mocks.materialCreate).not.toHaveBeenCalled();
expect(mocks.runUpdateMany).toHaveBeenCalledWith(expect.objectContaining({
data: expect.objectContaining({ status: "failed", itemsFailed: 1 }),
}));
});
it("rejects a stale binding revision instead of accepting last-write-wins", async () => {
mocks.bindingFindMany.mockResolvedValueOnce([{
id: "child-binding-1",
externalEntityType: "kwp_appointment",
externalId: "appointment-1",
localId: "appointment-local-1",
fingerprint: "old",
revision: 4,
}]);
mocks.appointmentFindFirst.mockResolvedValueOnce({
id: "appointment-local-1",
titel: "Alt",
beschreibung: null,
startAt: new Date("2026-07-01T08:00:00.000Z"),
endAt: null,
});
mocks.appointmentUpdate.mockResolvedValueOnce({});
mocks.bindingUpdateMany.mockResolvedValueOnce({ count: 0 });
await expect(syncKwpProjectInbound({ bindingId: "binding-1", now })).rejects.toThrow("stale_write");
expect(mocks.runUpdateMany).toHaveBeenLastCalledWith(expect.objectContaining({
data: expect.objectContaining({ status: "failed" }),
}));
});
});
@@ -0,0 +1,3 @@
export * from "./client.js";
export * from "./oauth-attempt.js";
export { kwpAdapter } from "./adapter.js";
@@ -0,0 +1,62 @@
import { describe, expect, it } from "vitest";
import {
KWP_LEGACY_MANDANT_SELECTION_KIND,
KWP_MANDANT_SELECTION_KIND,
KWP_OAUTH_RESERVATION_KIND,
parseKwpOAuthReservationBundle,
parseKwpPendingAttemptLifecycle,
} from "./oauth-attempt.js";
const PREVIOUS = {
credentialsCiphertext: "tenant-envelope-ciphertext",
connectionStatus: "active",
lastHealthCheck: "2026-07-20T11:00:00.000Z",
healthMessageKey: "integrations.health.active",
tokenExpiresAt: "2026-07-20T13:00:00.000Z",
createdByUserId: "user_1",
} as const;
describe("KWP pending OAuth-attempt codec", () => {
it("keeps the previous stable connection opaque and restorable", () => {
const encoded = JSON.stringify({
kind: KWP_OAUTH_RESERVATION_KIND,
customerCode: "geerkens2",
previous: PREVIOUS,
issuedAt: "2026-07-20T12:00:00.000Z",
expiresAt: "2026-07-20T12:10:00.000Z",
});
expect(parseKwpOAuthReservationBundle(encoded)).toEqual({
kind: KWP_OAUTH_RESERVATION_KIND,
customerCode: "geerkens2",
previous: PREVIOUS,
issuedAt: "2026-07-20T12:00:00.000Z",
expiresAt: "2026-07-20T12:10:00.000Z",
});
expect(parseKwpPendingAttemptLifecycle(encoded)).toEqual({ phase: "oauth", previous: PREVIOUS });
});
it("treats the legacy v1 selection envelope as a first-time attempt", () => {
const encoded = JSON.stringify({
kind: KWP_LEGACY_MANDANT_SELECTION_KIND,
oauth: {},
discovery: {},
issuedAt: "2026-07-20T12:00:00.000Z",
});
expect(parseKwpPendingAttemptLifecycle(encoded)).toEqual({ phase: "mandant", previous: null });
});
it("rejects malformed restoration snapshots instead of applying them", () => {
const encoded = JSON.stringify({
kind: KWP_MANDANT_SELECTION_KIND,
previous: { ...PREVIOUS, connectionStatus: "pending" },
oauth: {},
discovery: {},
issuedAt: "2026-07-20T12:00:00.000Z",
});
expect(parseKwpPendingAttemptLifecycle(encoded)).toBeNull();
});
});
@@ -0,0 +1,156 @@
import { isValidKwpContextCode } from "./client.js";
export const KWP_OAUTH_RESERVATION_KIND = "kwp_oauth_reservation_v1" as const;
export const KWP_MANDANT_SELECTION_KIND = "kwp_mandant_selection_v2" as const;
export const KWP_LEGACY_MANDANT_SELECTION_KIND = "kwp_mandant_selection_v1" as const;
export const KWP_OAUTH_PENDING_HEALTH_KEY = "integrations.kwp.health.oauthPending" as const;
export const KWP_MANDANT_SELECTION_HEALTH_KEY = "integrations.kwp.health.mandantSelectionRequired" as const;
const MAX_CIPHERTEXT_LENGTH = 1_000_000;
const MAX_CONTEXT_ID_LENGTH = 256;
const MAX_HEALTH_KEY_LENGTH = 512;
export type KwpRestorableConnectionStatus = "active" | "degraded" | "broken" | "revoked";
/**
* Opaque snapshot of the working connection that existed before reconnect.
* The ciphertext remains tenant-envelope encrypted even inside the encrypted
* pending envelope, so cleanup can restore it without ever exposing tokens.
*/
export type KwpRestorableConnectionSnapshot = {
readonly credentialsCiphertext: string | null;
readonly connectionStatus: KwpRestorableConnectionStatus;
readonly lastHealthCheck: string | null;
readonly healthMessageKey: string | null;
readonly tokenExpiresAt: string | null;
readonly createdByUserId: string | null;
};
export type KwpOAuthReservationBundle = {
readonly kind: typeof KWP_OAUTH_RESERVATION_KIND;
readonly customerCode: string;
readonly previous: KwpRestorableConnectionSnapshot | null;
readonly issuedAt: string;
readonly expiresAt: string;
};
export type KwpPendingAttemptLifecycle = {
readonly phase: "oauth" | "mandant";
readonly previous: KwpRestorableConnectionSnapshot | null;
};
/**
* Parse only the lifecycle portion shared by web and worker. The web service
* performs the stricter OAuth/discovery validation before exposing a selection;
* the worker needs only a trustworthy restoration snapshot for expired rows.
*/
export function parseKwpPendingAttemptLifecycle(plaintext: string): KwpPendingAttemptLifecycle | null {
let value: unknown;
try {
value = JSON.parse(plaintext);
} catch {
return null;
}
if (!isRecord(value)) return null;
const previous = parsePreviousSnapshot(value.previous);
// Compatibility for pending rows written by the first Mandant-flow build.
// That format could not preserve a previous active connection, so `null` is
// the only safe restoration target.
if (value.kind === KWP_LEGACY_MANDANT_SELECTION_KIND && value.previous === undefined) {
if (!isCanonicalIsoTimestamp(value.issuedAt) || !isRecord(value.oauth) || !isRecord(value.discovery)) return null;
return { phase: "mandant", previous: null };
}
if (previous === undefined) return null;
if (value.kind === KWP_OAUTH_RESERVATION_KIND) {
if (
!isValidKwpContextCode(value.customerCode) ||
!isCanonicalIsoTimestamp(value.issuedAt) ||
!isCanonicalIsoTimestamp(value.expiresAt)
) {
return null;
}
return { phase: "oauth", previous };
}
if (value.kind === KWP_MANDANT_SELECTION_KIND) {
if (!isCanonicalIsoTimestamp(value.issuedAt) || !isRecord(value.oauth) || !isRecord(value.discovery)) return null;
return { phase: "mandant", previous };
}
return null;
}
export function parseKwpOAuthReservationBundle(plaintext: string): KwpOAuthReservationBundle | null {
let value: unknown;
try {
value = JSON.parse(plaintext);
} catch {
return null;
}
if (!isRecord(value) || value.kind !== KWP_OAUTH_RESERVATION_KIND) return null;
const previous = parsePreviousSnapshot(value.previous);
if (
previous === undefined ||
!isValidKwpContextCode(value.customerCode) ||
!isCanonicalIsoTimestamp(value.issuedAt) ||
!isCanonicalIsoTimestamp(value.expiresAt)
) {
return null;
}
return {
kind: KWP_OAUTH_RESERVATION_KIND,
customerCode: value.customerCode,
previous,
issuedAt: value.issuedAt,
expiresAt: value.expiresAt,
};
}
function parsePreviousSnapshot(value: unknown): KwpRestorableConnectionSnapshot | null | undefined {
if (value === null) return null;
if (!isRecord(value)) return undefined;
if (
!isNullableBoundedString(value.credentialsCiphertext, MAX_CIPHERTEXT_LENGTH, false) ||
!isRestorableStatus(value.connectionStatus) ||
!isNullableCanonicalIsoTimestamp(value.lastHealthCheck) ||
!isNullableBoundedString(value.healthMessageKey, MAX_HEALTH_KEY_LENGTH, true) ||
!isNullableCanonicalIsoTimestamp(value.tokenExpiresAt) ||
!isNullableBoundedString(value.createdByUserId, MAX_CONTEXT_ID_LENGTH, false)
) {
return undefined;
}
return {
credentialsCiphertext: value.credentialsCiphertext,
connectionStatus: value.connectionStatus,
lastHealthCheck: value.lastHealthCheck,
healthMessageKey: value.healthMessageKey,
tokenExpiresAt: value.tokenExpiresAt,
createdByUserId: value.createdByUserId,
};
}
function isRestorableStatus(value: unknown): value is KwpRestorableConnectionStatus {
return value === "active" || value === "degraded" || value === "broken" || value === "revoked";
}
function isNullableCanonicalIsoTimestamp(value: unknown): value is string | null {
return value === null || isCanonicalIsoTimestamp(value);
}
function isCanonicalIsoTimestamp(value: unknown): value is string {
if (typeof value !== "string") return false;
const timestamp = Date.parse(value);
return Number.isFinite(timestamp) && new Date(timestamp).toISOString() === value;
}
function isNullableBoundedString(value: unknown, maxLength: number, allowEmpty: boolean): value is string | null {
return value === null || (typeof value === "string" && value.length <= maxLength && (allowEmpty || value.length > 0));
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
@@ -0,0 +1,373 @@
import { createHash } from "node:crypto";
import { getDbClient } from "@hivegrid/db/client.server";
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
import { KwpError } from "./client.js";
import { runKwpResourceSession, searchProjects } from "./resource-client.server.js";
import {
KWP_PROJECT_STATUS_LABELS,
type KwpProjectDetails,
type KwpProjectSearchResult,
type KwpProjectStatus,
} from "./resource-client.js";
const DISCOVERY_INTERVAL_MS = 6 * 60 * 60_000;
const ACTIVE_REFRESH_INTERVAL_MS = 24 * 60 * 60_000;
const MISSING_REFRESH_INTERVAL_MS = 6 * 60 * 60_000;
const HYDRATION_BATCH_SIZE = 20;
const DISCOVERY_WRITE_BATCH_SIZE = 1_000;
const SEARCH_RESULT_LIMIT = 50;
export type KwpProjectCatalogSummary = {
readonly status: "pending" | "syncing" | "ready" | "partial" | "paused";
readonly discoveredCount: number;
readonly hydratedCount: number;
readonly lastDiscoveryAt: string | null;
readonly lastCompletedAt: string | null;
};
export type KwpProjectCatalogSyncResult = {
readonly discoveredCount: number;
readonly hydratedCount: number;
readonly processed: number;
readonly hasMore: boolean;
readonly status: KwpProjectCatalogSummary["status"];
};
export async function getKwpProjectCatalogSummary(input: {
readonly connectionId: string;
}): Promise<KwpProjectCatalogSummary> {
const tenantId = requireTenantId();
const state = await getDbClient().kwpProjectCatalogState.findUnique({
where: {
tenantId_dataConnectionId: {
tenantId,
dataConnectionId: normalizeConnectionId(input.connectionId),
},
},
});
return {
status: state?.status ?? "pending",
discoveredCount: state?.discoveredCount ?? 0,
hydratedCount: state?.hydratedCount ?? 0,
lastDiscoveryAt: state?.lastDiscoveryAt?.toISOString() ?? null,
lastCompletedAt: state?.lastCompletedAt?.toISOString() ?? null,
};
}
export async function searchKwpProjectCatalog(input: {
readonly connectionId: string;
readonly query: string;
readonly limit?: number;
}): Promise<KwpProjectSearchResult[]> {
const tenantId = requireTenantId();
const dataConnectionId = normalizeConnectionId(input.connectionId);
const normalizedQuery = normalizeSearchText(input.query);
if (normalizedQuery.length < 2) return [];
const take = Math.min(Math.max(input.limit ?? SEARCH_RESULT_LIMIT, 1), SEARCH_RESULT_LIMIT);
const rows = await getDbClient().kwpProjectCatalogItem.findMany({
where: {
tenantId,
dataConnectionId,
state: "active",
searchText: { contains: normalizedQuery },
status: { not: null },
},
orderBy: [{ externalProjectNumber: "asc" }],
take,
});
return rows
.sort((left, right) => Number(right.externalProjectNumber === input.query.trim()) - Number(left.externalProjectNumber === input.query.trim()))
.map((row) => {
const status = row.status as KwpProjectStatus;
return {
externalProjectNumber: row.externalProjectNumber,
name: row.name,
projectAddressCode: row.projectAddressCode,
invoiceAddressCode: row.invoiceAddressCode,
clientAddressCode: row.clientAddressCode,
status,
statusLabel: KWP_PROJECT_STATUS_LABELS[status],
};
});
}
/** Cache-first manual search. A targeted provider read keeps newly-created KWP
* projects discoverable before the background catalog reaches them. Only
* transient provider failures may fall back to an already-populated cache. */
export async function searchAndCacheKwpProjects(input: {
readonly connectionId: string;
readonly query: string;
}): Promise<KwpProjectSearchResult[]> {
const cached = await searchKwpProjectCatalog(input);
try {
const live = await searchProjects(input);
await cacheKwpProjectSearchResults({ connectionId: input.connectionId, results: live });
return mergeSearchResults(live, cached);
} catch (error) {
if (cached.length > 0 && isTransientKwpError(error)) return cached;
throw error;
}
}
export async function cacheKwpProjectSearchResults(input: {
readonly connectionId: string;
readonly results: readonly KwpProjectSearchResult[];
readonly now?: Date;
}): Promise<void> {
if (input.results.length === 0) return;
const tenantId = requireTenantId();
const dataConnectionId = normalizeConnectionId(input.connectionId);
const now = input.now ?? new Date();
const nextRefreshAt = new Date(now.getTime() + ACTIVE_REFRESH_INTERVAL_MS);
await getDbClient().$transaction((tx) =>
Promise.all(
input.results.map((result) => {
const normalized = normalizeSearchResult(result);
return tx.kwpProjectCatalogItem.upsert({
where: {
tenantId_dataConnectionId_externalProjectNumber: {
tenantId,
dataConnectionId,
externalProjectNumber: normalized.externalProjectNumber,
},
},
create: {
tenantId,
dataConnectionId,
...normalized,
state: "active",
discoveredAt: now,
lastSeenAt: now,
lastSyncedAt: now,
nextRefreshAt,
},
update: {
...normalized,
state: "active",
lastSeenAt: now,
lastSyncedAt: now,
nextRefreshAt,
missingSince: null,
refreshAttempts: 0,
lastErrorCode: null,
},
});
}),
),
);
}
export async function cacheKwpProjectDetails(input: {
readonly connectionId: string;
readonly details: KwpProjectDetails;
}): Promise<void> {
const tenantId = requireTenantId();
const dataConnectionId = normalizeConnectionId(input.connectionId);
const now = new Date();
await getDbClient().kwpProjectCatalogItem.updateMany({
where: {
tenantId,
dataConnectionId,
externalProjectNumber: input.details.externalProjectNumber,
},
data: {
name: input.details.name,
searchText: normalizeSearchText(`${input.details.externalProjectNumber} ${input.details.name}`),
startDate: input.details.startDate ? new Date(input.details.startDate) : null,
orderValue: input.details.orderValue,
lastSeenAt: now,
lastSyncedAt: now,
},
});
}
/** Three-phase bounded catalog worker:
* 1. short RLS state read,
* 2. provider reads outside database transactions,
* 3. short batched RLS writes.
*
* LoadProjekteNachFilter has no pagination and is explicitly treated as the
* connection's setting-visible discovery set, not as a guaranteed full export.
*/
export async function syncKwpProjectCatalog(input: {
readonly connectionId: string;
readonly now?: Date;
}): Promise<KwpProjectCatalogSyncResult> {
const tenantId = requireTenantId();
const dataConnectionId = normalizeConnectionId(input.connectionId);
const now = input.now ?? new Date();
const db = getDbClient();
const initialState = await db.kwpProjectCatalogState.upsert({
where: { tenantId_dataConnectionId: { tenantId, dataConnectionId } },
create: { tenantId, dataConnectionId, status: "pending", nextDiscoveryAt: now },
update: {},
});
try {
return await runKwpResourceSession({ connectionId: dataConnectionId }, async (resource) => {
let discoveredCount = initialState.discoveredCount;
if (initialState.nextDiscoveryAt <= now) {
const projectNumbers = await resource.listProjectNumbers();
for (let offset = 0; offset < projectNumbers.length; offset += DISCOVERY_WRITE_BATCH_SIZE) {
const batch = projectNumbers.slice(offset, offset + DISCOVERY_WRITE_BATCH_SIZE);
await db.kwpProjectCatalogItem.createMany({
data: batch.map((externalProjectNumber) => ({
tenantId,
dataConnectionId,
externalProjectNumber,
name: externalProjectNumber,
searchText: normalizeSearchText(externalProjectNumber),
normalizedFingerprint: fingerprint({ externalProjectNumber }),
state: "discovered" as const,
discoveredAt: now,
lastSeenAt: now,
nextRefreshAt: now,
})),
skipDuplicates: true,
});
}
discoveredCount = projectNumbers.length;
await db.kwpProjectCatalogState.update({
where: { tenantId_dataConnectionId: { tenantId, dataConnectionId } },
data: {
status: projectNumbers.length === 0 ? "ready" : "syncing",
discoveredCount,
lastDiscoveryAt: now,
nextDiscoveryAt: new Date(now.getTime() + DISCOVERY_INTERVAL_MS),
lastErrorCode: null,
revision: { increment: 1 },
},
});
}
const due = await db.kwpProjectCatalogItem.findMany({
where: {
tenantId,
dataConnectionId,
state: { in: ["discovered", "active", "missing"] },
nextRefreshAt: { lte: now },
},
orderBy: [{ state: "asc" }, { nextRefreshAt: "asc" }, { externalProjectNumber: "asc" }],
take: HYDRATION_BATCH_SIZE,
select: { externalProjectNumber: true },
});
let processed = 0;
for (const item of due) {
const matches = await resource.searchProjects(item.externalProjectNumber);
const exact = matches.find((result) => result.externalProjectNumber === item.externalProjectNumber);
if (exact) {
await cacheKwpProjectSearchResults({ connectionId: dataConnectionId, results: [exact], now });
} else {
await db.kwpProjectCatalogItem.update({
where: {
tenantId_dataConnectionId_externalProjectNumber: {
tenantId,
dataConnectionId,
externalProjectNumber: item.externalProjectNumber,
},
},
data: {
state: "missing",
missingSince: now,
lastSyncedAt: now,
nextRefreshAt: new Date(now.getTime() + MISSING_REFRESH_INTERVAL_MS),
refreshAttempts: { increment: 1 },
lastErrorCode: "resource_not_found",
},
});
}
processed += 1;
}
const [hydratedCount, remaining] = await Promise.all([
db.kwpProjectCatalogItem.count({
where: { tenantId, dataConnectionId, lastSyncedAt: { not: null } },
}),
db.kwpProjectCatalogItem.count({
where: {
tenantId,
dataConnectionId,
state: { in: ["discovered", "active", "missing"] },
nextRefreshAt: { lte: now },
},
}),
]);
const hasMore = remaining > 0;
const status = hasMore ? "syncing" : "ready";
await db.kwpProjectCatalogState.update({
where: { tenantId_dataConnectionId: { tenantId, dataConnectionId } },
data: {
status,
discoveredCount,
hydratedCount,
lastCompletedAt: hasMore ? undefined : now,
lastErrorCode: null,
revision: { increment: 1 },
},
});
return { discoveredCount, hydratedCount, processed, hasMore, status };
});
} catch (error) {
const paused = error instanceof KwpError && ["auth_scope_missing", "capability_paused", "contract_drift"].includes(error.code);
await db.kwpProjectCatalogState.updateMany({
where: { tenantId, dataConnectionId },
data: {
status: paused ? "paused" : "partial",
lastErrorCode: error instanceof KwpError ? error.code : "provider_outage",
revision: { increment: 1 },
},
});
throw error;
}
}
function normalizeSearchResult(result: KwpProjectSearchResult) {
return {
externalProjectNumber: result.externalProjectNumber,
name: result.name,
searchText: normalizeSearchText(`${result.externalProjectNumber} ${result.name}`),
status: result.status,
projectAddressCode: result.projectAddressCode,
invoiceAddressCode: result.invoiceAddressCode,
clientAddressCode: result.clientAddressCode,
normalizedFingerprint: fingerprint(result),
};
}
function mergeSearchResults(
primary: readonly KwpProjectSearchResult[],
secondary: readonly KwpProjectSearchResult[],
): KwpProjectSearchResult[] {
return [...new Map([...primary, ...secondary].map((result) => [result.externalProjectNumber, result])).values()].slice(0, SEARCH_RESULT_LIMIT);
}
function normalizeSearchText(value: string): string {
return value
.normalize("NFKD")
.replace(/\p{Diacritic}/gu, "")
.trim()
.toLocaleLowerCase("de-DE")
.slice(0, 1_024);
}
function fingerprint(value: unknown): string {
return createHash("sha256").update(JSON.stringify(value)).digest("hex");
}
function isTransientKwpError(error: unknown): boolean {
return error instanceof KwpError && ["auth_token_invalid", "provider_outage", "rate_limit_exceeded"].includes(error.code);
}
function requireTenantId(): string {
const tenantId = getRlsExecutionContext()?.tenantId?.trim();
if (!tenantId) throw new KwpError("invalid_credentials");
return tenantId;
}
function normalizeConnectionId(value: string): string {
const normalized = value.trim();
if (!/^[A-Za-z0-9_-]{8,191}$/u.test(normalized)) throw new KwpError("invalid_credentials");
return normalized;
}
@@ -0,0 +1,152 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
db: {
kwpProjectCatalogState: {
findUnique: vi.fn(),
upsert: vi.fn(),
update: vi.fn(),
updateMany: vi.fn(),
},
kwpProjectCatalogItem: {
findMany: vi.fn(),
createMany: vi.fn(),
upsert: vi.fn(),
update: vi.fn(),
updateMany: vi.fn(),
count: vi.fn(),
},
$transaction: vi.fn(),
},
resource: {
listProjectNumbers: vi.fn(),
searchProjects: vi.fn(),
},
searchProjects: vi.fn(),
}));
vi.mock("@hivegrid/db/client.server", () => ({
getDbClient: () => mocks.db,
}));
vi.mock("@hivegrid/db/rls-context.server", () => ({
getRlsExecutionContext: () => ({ tenantId: "tenant_1" }),
}));
vi.mock("./resource-client.server.js", () => ({
runKwpResourceSession: (_input: unknown, operation: (resource: typeof mocks.resource) => Promise<unknown>) =>
operation(mocks.resource),
searchProjects: mocks.searchProjects,
}));
import { KwpError } from "./client.js";
import {
searchAndCacheKwpProjects,
searchKwpProjectCatalog,
syncKwpProjectCatalog,
} from "./project-catalog.server.js";
const RESULT = {
externalProjectNumber: "P-100",
name: "Heizung Schule",
projectAddressCode: "ADR-1",
invoiceAddressCode: null,
clientAddressCode: null,
status: 8 as const,
statusLabel: "Erhalten",
};
beforeEach(() => {
vi.clearAllMocks();
mocks.db.$transaction.mockImplementation((operation: (tx: typeof mocks.db) => Promise<unknown>) =>
operation(mocks.db));
mocks.db.kwpProjectCatalogItem.upsert.mockResolvedValue({});
mocks.db.kwpProjectCatalogState.update.mockResolvedValue({});
mocks.db.kwpProjectCatalogState.updateMany.mockResolvedValue({ count: 1 });
});
describe("KWP project catalog", () => {
it("searches the normalized local cache and maps stable KWP status labels", async () => {
mocks.db.kwpProjectCatalogItem.findMany.mockResolvedValue([{
externalProjectNumber: "P-100",
name: "Heizung Schule",
projectAddressCode: "ADR-1",
invoiceAddressCode: null,
clientAddressCode: null,
status: 8,
}]);
await expect(searchKwpProjectCatalog({
connectionId: "connection_1",
query: " Heizung ",
})).resolves.toEqual([RESULT]);
expect(mocks.db.kwpProjectCatalogItem.findMany).toHaveBeenCalledWith(expect.objectContaining({
where: expect.objectContaining({
tenantId: "tenant_1",
dataConnectionId: "connection_1",
searchText: { contains: "heizung" },
}),
take: 50,
}));
});
it("returns cached results during a transient provider outage", async () => {
mocks.db.kwpProjectCatalogItem.findMany.mockResolvedValue([{
externalProjectNumber: RESULT.externalProjectNumber,
name: RESULT.name,
projectAddressCode: RESULT.projectAddressCode,
invoiceAddressCode: RESULT.invoiceAddressCode,
clientAddressCode: RESULT.clientAddressCode,
status: RESULT.status,
}]);
mocks.searchProjects.mockRejectedValue(new KwpError("provider_outage", 503));
await expect(searchAndCacheKwpProjects({
connectionId: "connection_1",
query: "Heizung",
})).resolves.toEqual([RESULT]);
});
it("discovers and hydrates a bounded batch without provider I/O inside a database transaction", async () => {
const now = new Date("2026-07-24T12:00:00.000Z");
mocks.db.kwpProjectCatalogState.upsert.mockResolvedValue({
discoveredCount: 0,
nextDiscoveryAt: now,
});
mocks.resource.listProjectNumbers.mockResolvedValue(["P-100", "P-200"]);
mocks.db.kwpProjectCatalogItem.createMany.mockResolvedValue({ count: 2 });
mocks.db.kwpProjectCatalogItem.findMany.mockResolvedValue([
{ externalProjectNumber: "P-100" },
{ externalProjectNumber: "P-200" },
]);
mocks.resource.searchProjects.mockImplementation(async (query: string) => [{
...RESULT,
externalProjectNumber: query,
name: `Projekt ${query}`,
}]);
mocks.db.kwpProjectCatalogItem.count
.mockResolvedValueOnce(2)
.mockResolvedValueOnce(0);
await expect(syncKwpProjectCatalog({
connectionId: "connection_1",
now,
})).resolves.toEqual({
discoveredCount: 2,
hydratedCount: 2,
processed: 2,
hasMore: false,
status: "ready",
});
expect(mocks.resource.listProjectNumbers).toHaveBeenCalledTimes(1);
expect(mocks.resource.searchProjects).toHaveBeenCalledTimes(2);
expect(mocks.db.kwpProjectCatalogItem.createMany).toHaveBeenCalledWith(expect.objectContaining({
skipDuplicates: true,
data: expect.arrayContaining([
expect.objectContaining({ externalProjectNumber: "P-100", state: "discovered" }),
]),
}));
expect(mocks.db.$transaction).toHaveBeenCalledTimes(2);
expect(mocks.db.$transaction.mock.invocationCallOrder.every((order) =>
mocks.resource.searchProjects.mock.invocationCallOrder.every((providerOrder) => providerOrder !== order))).toBe(true);
});
});
@@ -0,0 +1,637 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
auditEvent: vi.fn(),
logActivity: vi.fn(),
publishOutboxEvent: vi.fn(),
publishSearchUpsertEvent: vi.fn(),
getRlsExecutionContext: vi.fn(),
transaction: vi.fn(),
bindingFindFirst: vi.fn(),
bindingFindUnique: vi.fn(),
bindingFindUniqueOrThrow: vi.fn(),
bindingCreate: vi.fn(),
bindingUpdateMany: vi.fn(),
bindingFindMany: vi.fn(),
projectFindFirst: vi.fn(),
projectCreate: vi.fn(),
projectUpdateMany: vi.fn(),
contactFindFirst: vi.fn(),
contactFindMany: vi.fn(),
connectionFindFirst: vi.fn(),
capabilityFindUnique: vi.fn(),
capabilityUpsert: vi.fn(),
routingFindUnique: vi.fn(),
stageFindFirst: vi.fn(),
sequenceUpdate: vi.fn(),
syncRunCreate: vi.fn(),
syncItemCreate: vi.fn(),
executeRaw: vi.fn(),
queryRaw: vi.fn(),
searchUpsert: vi.fn(),
searchProjects: vi.fn(),
loadProjectDetails: vi.fn(),
loadAddressDetails: vi.fn(),
}));
vi.mock("@hivegrid/activity", () => ({ logActivity: mocks.logActivity }));
vi.mock("@hivegrid/db/client.server", () => ({
getDbClient: () => ({
$transaction: mocks.transaction,
appEntityBinding: {
findUnique: mocks.bindingFindUnique,
},
kontakt: {
findFirst: mocks.contactFindFirst,
findMany: mocks.contactFindMany,
},
kwpProjectRouting: {
findUnique: mocks.routingFindUnique,
},
}),
}));
vi.mock("@hivegrid/db/outbox", () => ({
publishOutboxEvent: mocks.publishOutboxEvent,
}));
vi.mock("@hivegrid/db/rls-context.server", () => ({
getRlsExecutionContext: mocks.getRlsExecutionContext,
}));
vi.mock("@hivegrid/foundation", () => ({
auditEvent: mocks.auditEvent,
}));
vi.mock("@hivegrid/search", () => ({
crmContactsIndex: { name: "crm-contacts" },
projectsIndex: { name: "projects" },
publishSearchUpsertEvent: mocks.publishSearchUpsertEvent,
}));
vi.mock("./resource-client.server.js", () => ({
loadAddressDetails: mocks.loadAddressDetails,
loadProjectDetails: mocks.loadProjectDetails,
searchProjects: mocks.searchProjects,
}));
import {
importKwpProject,
previewKwpProjectImport,
restoreAndUnlinkKwpProject,
unlinkKwpProject,
} from "./project-domain.server.js";
const beforeProject = {
id: "project-1",
tenantId: "tenant-1",
projektNummer: "P-00042",
projektname: "KWP name",
beschreibung: "Local note",
projekttyp: null,
quelle: "kwp",
pipelineId: "pipeline-kwp",
stageId: "stage-kwp",
startDatum: new Date("2026-07-01T00:00:00.000Z"),
deadline: null,
auftragsvolumen: 42_500,
potenziellerAuftragswert: null,
projektAdresseId: "address-kwp",
rechnungsAdresseId: null,
bauherrAdresseId: null,
zustaendigePersonId: "user-1",
projektleiterId: null,
wonAt: null,
lostAt: null,
archivedAt: null,
createdAt: new Date("2026-06-01T00:00:00.000Z"),
updatedAt: new Date("2026-07-23T10:00:00.000Z"),
};
const restoredProject = {
...beforeProject,
projektname: "Local name",
pipelineId: "pipeline-local",
stageId: "stage-local",
startDatum: new Date("2026-05-01T00:00:00.000Z"),
auftragsvolumen: 12_000,
projektAdresseId: "address-local",
updatedAt: new Date("2026-07-23T10:01:00.000Z"),
};
const binding = {
id: "binding-1",
tenantId: "tenant-1",
dataConnectionId: "connection-1",
externalEntityType: "kwp_project",
localEntityType: "project",
externalId: "KWP-4711",
localId: "project-1",
state: "active",
revision: 4,
normalizedSnapshot: {},
overwrittenLocalSnapshot: {
projektname: "Local name",
pipelineId: "pipeline-local",
stageId: "stage-local",
startDatum: "2026-05-01T00:00:00.000Z",
auftragsvolumen: 12_000,
projektAdresseId: "address-local",
rechnungsAdresseId: null,
bauherrAdresseId: null,
},
};
const tx = {
appEntityBinding: {
findFirst: mocks.bindingFindFirst,
findUnique: mocks.bindingFindUnique,
findUniqueOrThrow: mocks.bindingFindUniqueOrThrow,
create: mocks.bindingCreate,
updateMany: mocks.bindingUpdateMany,
findMany: mocks.bindingFindMany,
},
projekt: {
findFirst: mocks.projectFindFirst,
create: mocks.projectCreate,
updateMany: mocks.projectUpdateMany,
},
dataConnection: { findFirst: mocks.connectionFindFirst },
kwpCapabilityState: {
findUnique: mocks.capabilityFindUnique,
upsert: mocks.capabilityUpsert,
},
kwpProjectRouting: { findUnique: mocks.routingFindUnique },
pipelineStage: { findFirst: mocks.stageFindFirst },
hiveNumberSeq: { update: mocks.sequenceUpdate },
appSyncRun: { create: mocks.syncRunCreate },
appSyncItem: { create: mocks.syncItemCreate },
$executeRaw: mocks.executeRaw,
$queryRaw: mocks.queryRaw,
searchIndexEntry: { upsert: mocks.searchUpsert },
};
beforeEach(() => {
vi.clearAllMocks();
mocks.getRlsExecutionContext.mockReturnValue({ tenantId: "tenant-1", userId: "user-1" });
mocks.transaction.mockImplementation((callback) => callback(tx));
mocks.bindingFindFirst.mockResolvedValue(binding);
mocks.bindingFindUnique.mockResolvedValue(null);
mocks.bindingFindUniqueOrThrow.mockResolvedValue(binding);
mocks.bindingCreate.mockResolvedValue({ id: "binding-created" });
mocks.bindingUpdateMany.mockResolvedValue({ count: 1 });
mocks.bindingFindMany.mockResolvedValue([]);
mocks.projectFindFirst
.mockResolvedValueOnce(beforeProject)
.mockResolvedValueOnce(restoredProject);
mocks.projectUpdateMany.mockResolvedValue({ count: 1 });
mocks.contactFindFirst.mockResolvedValue(null);
mocks.contactFindMany.mockResolvedValue([]);
mocks.connectionFindFirst.mockResolvedValue({ id: "connection-1" });
mocks.capabilityFindUnique.mockResolvedValue({ status: "active" });
mocks.capabilityUpsert.mockResolvedValue({});
mocks.routingFindUnique.mockResolvedValue({
pipelineId: "pipeline-kwp",
stageId: "stage-kwp",
});
mocks.stageFindFirst.mockResolvedValue({ id: "stage-kwp", stageKind: "neutral" });
mocks.sequenceUpdate.mockResolvedValue({});
mocks.syncRunCreate.mockResolvedValue({ id: "run-1" });
mocks.syncItemCreate.mockResolvedValue({ id: "item-1" });
mocks.executeRaw.mockResolvedValue(1);
mocks.queryRaw.mockResolvedValue([{ nextNumber: 42, padding: 5, prefix: "P-" }]);
mocks.searchProjects.mockResolvedValue([{
externalProjectNumber: "KWP-4711",
name: "KWP name",
projectAddressCode: null,
invoiceAddressCode: null,
clientAddressCode: null,
status: 8,
statusLabel: "Erhalten",
}]);
mocks.loadProjectDetails.mockResolvedValue({
externalProjectNumber: "KWP-4711",
name: "KWP name",
startDate: "2026-07-01T00:00:00.000Z",
orderValue: 42_500,
addressCode: null,
addressName: null,
});
mocks.searchUpsert.mockResolvedValue(undefined);
mocks.publishSearchUpsertEvent.mockResolvedValue(undefined);
mocks.auditEvent.mockResolvedValue(undefined);
mocks.logActivity.mockResolvedValue(undefined);
});
describe("KWP project ownership restore", () => {
it("unlinks first and restores the captured local A state with optimistic locking", async () => {
await restoreAndUnlinkKwpProject({
tenantId: "tenant-1",
projectId: "project-1",
expectedBindingRevision: 4,
expectedProjectUpdatedAt: beforeProject.updatedAt.toISOString(),
actorUserId: "user-1",
});
expect(mocks.bindingUpdateMany).toHaveBeenCalledWith(expect.objectContaining({
where: { id: "binding-1", tenantId: "tenant-1", revision: 4 },
data: expect.objectContaining({ state: "unlinked", revision: { increment: 1 } }),
}));
expect(mocks.projectUpdateMany).toHaveBeenCalledWith({
where: {
id: "project-1",
tenantId: "tenant-1",
updatedAt: beforeProject.updatedAt,
archivedAt: null,
},
data: expect.objectContaining({
projektname: "Local name",
pipelineId: "pipeline-local",
stageId: "stage-local",
startDatum: new Date("2026-05-01T00:00:00.000Z"),
auftragsvolumen: 12_000,
projektAdresseId: "address-local",
}),
});
expect(mocks.bindingUpdateMany.mock.invocationCallOrder[0]).toBeLessThan(
mocks.projectUpdateMany.mock.invocationCallOrder[0]!,
);
expect(mocks.auditEvent).toHaveBeenCalledWith(
expect.objectContaining({ action: "KWP_PROJECT_RESTORED_AND_UNLINKED" }),
tx,
);
});
it("rejects a stale local entity instead of applying last-write-wins", async () => {
mocks.projectUpdateMany.mockResolvedValueOnce({ count: 0 });
await expect(restoreAndUnlinkKwpProject({
tenantId: "tenant-1",
projectId: "project-1",
expectedBindingRevision: 4,
expectedProjectUpdatedAt: beforeProject.updatedAt.toISOString(),
actorUserId: "user-1",
})).rejects.toEqual(expect.objectContaining({ code: "stale_write" }));
expect(mocks.auditEvent).not.toHaveBeenCalled();
});
it("plain unlink preserves every local project field", async () => {
mocks.projectFindFirst.mockReset().mockResolvedValue(beforeProject);
await unlinkKwpProject({
tenantId: "tenant-1",
projectId: "project-1",
expectedBindingRevision: 4,
actorUserId: "user-1",
});
expect(mocks.projectUpdateMany).not.toHaveBeenCalled();
expect(mocks.bindingUpdateMany).toHaveBeenCalledWith(expect.objectContaining({
data: expect.objectContaining({ state: "unlinked" }),
}));
});
});
describe("KWP project create and link", () => {
const createdProject = {
...beforeProject,
id: "project-created",
projektNummer: "P-00042",
projektname: "KWP name",
quelle: "kwp",
pipelineId: "pipeline-kwp",
stageId: "stage-kwp",
startDatum: new Date("2026-07-01T00:00:00.000Z"),
auftragsvolumen: 42_500,
createdAt: new Date("2026-07-23T10:00:00.000Z"),
updatedAt: new Date("2026-07-23T10:00:00.000Z"),
};
it("creates a local project number while retaining KWP projNr only as an external binding", async () => {
mocks.bindingFindFirst.mockReset();
mocks.projectFindFirst.mockReset().mockResolvedValue(createdProject);
mocks.projectCreate.mockResolvedValue(createdProject);
await expect(importKwpProject({
connectionId: "connection-1",
externalProjectNumber: "KWP-4711",
actorUserId: "user-1",
target: { kind: "create" },
addressDecisions: [],
})).resolves.toEqual({
projectId: "project-created",
created: true,
bindingId: "binding-created",
});
expect(mocks.projectCreate).toHaveBeenCalledWith({
data: expect.objectContaining({
projektNummer: "P-00042",
projektname: "KWP name",
quelle: "kwp",
}),
});
expect(mocks.bindingCreate).toHaveBeenCalledWith({
data: expect.objectContaining({
externalId: "KWP-4711",
localId: "project-created",
externalEntityType: "kwp_project",
localEntityType: "project",
}),
});
expect(JSON.stringify(mocks.projectCreate.mock.calls)).not.toContain('"projektNummer":"KWP-4711"');
expect(mocks.publishOutboxEvent).not.toHaveBeenCalled();
});
it("links by explicit stale-safe diff and never overwrites the local project number", async () => {
const localBefore = {
...beforeProject,
projektname: "Local name",
pipelineId: "pipeline-local",
stageId: "stage-local",
startDatum: new Date("2026-05-01T00:00:00.000Z"),
auftragsvolumen: 12_000,
};
const linked = {
...localBefore,
projektname: "KWP name",
pipelineId: "pipeline-kwp",
stageId: "stage-kwp",
startDatum: new Date("2026-07-01T00:00:00.000Z"),
auftragsvolumen: 42_500,
updatedAt: new Date("2026-07-23T10:01:00.000Z"),
};
mocks.bindingFindFirst.mockReset();
mocks.projectFindFirst
.mockReset()
.mockResolvedValueOnce(localBefore)
.mockResolvedValueOnce(linked)
.mockResolvedValueOnce(linked);
await expect(importKwpProject({
connectionId: "connection-1",
externalProjectNumber: "KWP-4711",
actorUserId: "user-1",
target: {
kind: "link",
projectId: "project-1",
expectedUpdatedAt: localBefore.updatedAt.toISOString(),
},
addressDecisions: [],
})).resolves.toMatchObject({
projectId: "project-1",
created: false,
});
expect(mocks.projectCreate).not.toHaveBeenCalled();
expect(mocks.projectUpdateMany).toHaveBeenCalledWith(expect.objectContaining({
where: {
id: "project-1",
tenantId: "tenant-1",
updatedAt: localBefore.updatedAt,
archivedAt: null,
},
data: expect.not.objectContaining({ projektNummer: expect.anything() }),
}));
expect(mocks.bindingCreate).toHaveBeenCalledWith({
data: expect.objectContaining({
externalId: "KWP-4711",
localId: "project-1",
overwrittenLocalSnapshot: expect.objectContaining({
projektname: "Local name",
pipelineId: "pipeline-local",
stageId: "stage-local",
}),
}),
});
expect(mocks.publishOutboxEvent).not.toHaveBeenCalled();
});
it("rejects a stale link diff before any local mutation", async () => {
const local = {
...beforeProject,
updatedAt: new Date("2026-07-23T10:02:00.000Z"),
};
mocks.bindingFindFirst.mockReset();
mocks.projectFindFirst.mockReset().mockResolvedValue(local);
await expect(importKwpProject({
connectionId: "connection-1",
externalProjectNumber: "KWP-4711",
actorUserId: "user-1",
target: {
kind: "link",
projectId: "project-1",
expectedUpdatedAt: "2026-07-23T10:00:00.000Z",
},
addressDecisions: [],
})).rejects.toEqual(expect.objectContaining({ code: "stale_write" }));
expect(mocks.projectUpdateMany).not.toHaveBeenCalled();
expect(mocks.bindingCreate).not.toHaveBeenCalled();
});
it("replays an already bound import without creating a second project or binding", async () => {
const activeBinding = {
id: "binding-1",
tenantId: "tenant-1",
dataConnectionId: "connection-1",
externalEntityType: "kwp_project",
localEntityType: "project",
externalId: "KWP-4711",
localId: "project-1",
state: "active",
revision: 7,
};
const linked = {
...beforeProject,
projektname: "KWP name",
pipelineId: "pipeline-kwp",
stageId: "stage-kwp",
updatedAt: new Date("2026-07-23T10:01:00.000Z"),
};
mocks.bindingFindFirst.mockReset();
mocks.bindingFindUnique.mockResolvedValue(activeBinding);
mocks.bindingFindUniqueOrThrow.mockResolvedValue({ ...activeBinding, revision: 8 });
mocks.projectFindFirst
.mockReset()
.mockResolvedValueOnce(beforeProject)
.mockResolvedValueOnce(linked)
.mockResolvedValueOnce(linked);
await expect(importKwpProject({
connectionId: "connection-1",
externalProjectNumber: "KWP-4711",
actorUserId: "user-1",
target: { kind: "create" },
addressDecisions: [],
})).resolves.toEqual({
projectId: "project-1",
created: false,
bindingId: "binding-1",
});
expect(mocks.projectCreate).not.toHaveBeenCalled();
expect(mocks.bindingCreate).not.toHaveBeenCalled();
expect(mocks.bindingUpdateMany).toHaveBeenCalledWith(expect.objectContaining({
where: { id: "binding-1", tenantId: "tenant-1", revision: 7 },
data: expect.objectContaining({
state: "active",
localId: "project-1",
revision: { increment: 1 },
}),
}));
});
it("turns a parallel replay into a stale write instead of duplicating data", async () => {
mocks.bindingFindFirst.mockReset();
mocks.bindingFindUnique.mockResolvedValue({
id: "binding-1",
tenantId: "tenant-1",
dataConnectionId: "connection-1",
externalEntityType: "kwp_project",
localEntityType: "project",
externalId: "KWP-4711",
localId: "project-1",
state: "active",
revision: 7,
});
mocks.projectFindFirst
.mockReset()
.mockResolvedValueOnce(beforeProject)
.mockResolvedValueOnce(beforeProject)
.mockResolvedValueOnce(beforeProject);
mocks.bindingUpdateMany.mockResolvedValueOnce({ count: 0 });
await expect(importKwpProject({
connectionId: "connection-1",
externalProjectNumber: "KWP-4711",
actorUserId: "user-1",
target: { kind: "create" },
addressDecisions: [],
})).rejects.toEqual(expect.objectContaining({ code: "stale_write" }));
expect(mocks.projectCreate).not.toHaveBeenCalled();
expect(mocks.bindingCreate).not.toHaveBeenCalled();
});
});
describe("KWP project address preview", () => {
const address = {
externalAddressCode: "ADR-1",
name: "Geerkens GmbH",
firstName: null,
addition: null,
street: "Werkstraße 7",
postalCode: "52511",
city: "Geilenkirchen",
country: "DE",
invoiceEmail: "rechnung@example.test",
email: "info@example.test",
phone: "+49 2451 123",
mobile: null,
contactPeople: [{
externalContactId: "person-1",
firstName: "Maria",
lastName: "Muster",
addition: null,
email: "maria@example.test",
phone: null,
mobile: "+49 170 123",
}],
};
it("loads a shared address code once and reuses its durable binding for all three roles", async () => {
mocks.searchProjects.mockResolvedValueOnce([{
externalProjectNumber: "KWP-4711",
name: "KWP name",
projectAddressCode: "ADR-1",
invoiceAddressCode: "ADR-1",
clientAddressCode: "ADR-1",
status: 8,
statusLabel: "Erhalten",
}]);
mocks.loadAddressDetails.mockResolvedValueOnce(address);
mocks.bindingFindUnique.mockResolvedValue({
id: "address-binding-1",
localId: "contact-1",
state: "active",
});
mocks.contactFindFirst.mockResolvedValue({
id: "contact-1",
kontaktTyp: "organisation",
vorname: null,
nachname: null,
orgName: "Geerkens GmbH",
primaerEmail: "info@example.test",
adresse: {
strasse: "Werkstraße 7",
plz: "52511",
ort: "Geilenkirchen",
},
});
const preview = await previewKwpProjectImport({
connectionId: "connection-1",
externalProjectNumber: "KWP-4711",
});
expect(mocks.loadAddressDetails).toHaveBeenCalledOnce();
expect(preview.addresses.map((entry) => entry.role)).toEqual(["project", "invoice", "client"]);
for (const role of preview.addresses) {
expect(role.address.externalAddressCode).toBe("ADR-1");
expect(role.candidates).toEqual([expect.objectContaining({
id: "contact-1",
reason: "external_binding",
})]);
expect(role.address.contactPeople).toHaveLength(1);
}
});
it("rejects duplicate role decisions before the local transaction", async () => {
mocks.searchProjects.mockResolvedValueOnce([{
externalProjectNumber: "KWP-4711",
name: "KWP name",
projectAddressCode: "ADR-1",
invoiceAddressCode: null,
clientAddressCode: null,
status: 8,
statusLabel: "Erhalten",
}]);
mocks.loadAddressDetails.mockResolvedValueOnce(address);
await expect(importKwpProject({
connectionId: "connection-1",
externalProjectNumber: "KWP-4711",
actorUserId: "user-1",
target: { kind: "create" },
addressDecisions: [
{ role: "project", addressCode: "ADR-1", addressContact: { kind: "create" }, primaryContact: null },
{ role: "project", addressCode: "ADR-1", addressContact: { kind: "create" }, primaryContact: null },
],
})).rejects.toEqual(expect.objectContaining({ code: "address_decision_invalid" }));
expect(mocks.transaction).not.toHaveBeenCalled();
});
it("accepts at most one selected person per role and rejects an unknown person", async () => {
mocks.searchProjects.mockResolvedValueOnce([{
externalProjectNumber: "KWP-4711",
name: "KWP name",
projectAddressCode: "ADR-1",
invoiceAddressCode: null,
clientAddressCode: null,
status: 8,
statusLabel: "Erhalten",
}]);
mocks.loadAddressDetails.mockResolvedValueOnce(address);
await expect(importKwpProject({
connectionId: "connection-1",
externalProjectNumber: "KWP-4711",
actorUserId: "user-1",
target: { kind: "create" },
addressDecisions: [{
role: "project",
addressCode: "ADR-1",
addressContact: { kind: "create" },
primaryContact: {
externalContactId: "unknown-person",
contact: { kind: "create" },
},
}],
})).rejects.toEqual(expect.objectContaining({ code: "address_decision_invalid" }));
expect(mocks.transaction).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,645 @@
import { logActivity } from "@hivegrid/activity";
import { getDbClient } from "@hivegrid/db/client.server";
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
import type { Prisma } from "@hivegrid/db/prisma-browser";
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
import { auditEvent } from "@hivegrid/foundation";
import { buildWorkflowTriggerOutboxEvent } from "@hivegrid/queue";
import {
KwpProjectDomainError,
loadKwpBoundProject,
publishKwpContactSearch,
publishKwpProjectSearch,
syncKwpPrimaryContactChannels,
} from "./project-domain.server.js";
import { runKwpResourceSession } from "./resource-client.server.js";
import {
fingerprintKwpSnapshot,
KWP_PROJECT_CAPABILITY,
type KwpAddressDetails,
type KwpProjectSearchResult,
} from "./resource-client.js";
const PROJECT_ENTITY_TYPE = "kwp_project";
const ADDRESS_ENTITY_TYPE = "kwp_address";
const ADDRESS_CONTACT_ENTITY_TYPE = "kwp_address_contact";
const ADDRESS_SYNC_INTERVAL_MS = 60 * 60_000;
type PreparedProjectSync = {
tenantId: string;
runId: string;
connectionId: string;
binding: {
id: string;
revision: number;
externalId: string;
fingerprint: string;
missingSince: Date | null;
};
project: Awaited<ReturnType<typeof loadKwpBoundProject>>;
addressBindings: Array<{
id: string;
revision: number;
externalEntityType: string;
externalId: string;
localId: string;
fingerprint: string;
lastSyncedAt: Date | null;
}>;
};
type LoadedProviderSnapshot = {
search: KwpProjectSearchResult;
details: {
externalProjectNumber: string;
name: string;
startDate: string | null;
orderValue: number | null;
};
addresses: Map<string, KwpAddressDetails>;
};
export type KwpProjectSyncResult = {
readonly runId: string;
readonly state: "synced" | "unchanged" | "missing" | "quarantined";
readonly projectId: string;
readonly stageChanged: boolean;
};
export async function syncKwpProjectBinding(input: {
readonly bindingId: string;
readonly now?: Date;
}): Promise<KwpProjectSyncResult> {
const now = input.now ?? new Date();
const prepared = await prepareProjectSync(normalizeId(input.bindingId), now);
try {
const loaded = await loadProviderSnapshot(prepared, now);
if (!loaded) {
const result = await markProjectMissing(prepared, now);
await finishRun(prepared, result.state, now);
return result;
}
const result = await applyProviderSnapshot(prepared, loaded, now);
await finishRun(prepared, result.state, now);
return result;
} catch (error) {
await failRun(prepared, error, now);
throw error;
}
}
async function prepareProjectSync(bindingId: string, now: Date): Promise<PreparedProjectSync> {
const tenantId = requireTenantContext();
return getDbClient().$transaction(async (tx) => {
const binding = await tx.appEntityBinding.findFirst({
where: {
id: bindingId,
tenantId,
externalEntityType: PROJECT_ENTITY_TYPE,
localEntityType: "project",
state: { in: ["active", "missing"] },
},
});
if (!binding) throw new KwpProjectDomainError("project_not_found");
const capability = await tx.kwpCapabilityState.findUnique({
where: {
tenantId_dataConnectionId_capability: {
tenantId,
dataConnectionId: binding.dataConnectionId,
capability: KWP_PROJECT_CAPABILITY,
},
},
select: { status: true },
});
if (capability?.status === "paused") throw new KwpProjectDomainError("capability_paused");
const project = await loadKwpBoundProject(tx, tenantId, binding.localId);
const addressBindings = await tx.appEntityBinding.findMany({
where: {
tenantId,
dataConnectionId: binding.dataConnectionId,
externalEntityType: { in: [ADDRESS_ENTITY_TYPE, ADDRESS_CONTACT_ENTITY_TYPE] },
state: { in: ["active", "missing"] },
},
select: {
id: true,
revision: true,
externalEntityType: true,
externalId: true,
localId: true,
fingerprint: true,
lastSyncedAt: true,
},
});
const run = await tx.appSyncRun.create({
data: {
tenantId,
dataConnectionId: binding.dataConnectionId,
kind: "scheduled",
status: "running",
itemsTotal: 1,
summaryText: "integrations.sync.summary.kwpProjectSyncStarted",
startedAt: now,
},
});
return {
tenantId,
runId: run.id,
connectionId: binding.dataConnectionId,
binding: {
id: binding.id,
revision: binding.revision,
externalId: binding.externalId,
fingerprint: binding.fingerprint,
missingSince: binding.missingSince,
},
project,
addressBindings,
};
});
}
async function loadProviderSnapshot(prepared: PreparedProjectSync, now: Date): Promise<LoadedProviderSnapshot | null> {
return runKwpResourceSession({ connectionId: prepared.connectionId }, async (resource) => {
const matches = await resource.searchProjects(prepared.binding.externalId);
const search = matches.find((entry) => entry.externalProjectNumber === prepared.binding.externalId);
if (!search) return null;
const details = await resource.loadProjectDetails(prepared.binding.externalId);
const codes = [...new Set([
search.projectAddressCode,
search.invoiceAddressCode,
search.clientAddressCode,
].filter((value): value is string => Boolean(value)))];
const mainBindings = new Map(
prepared.addressBindings
.filter((binding) => binding.externalEntityType === ADDRESS_ENTITY_TYPE)
.map((binding) => [binding.externalId, binding]),
);
const addresses = new Map<string, KwpAddressDetails>();
for (const code of codes) {
const binding = mainBindings.get(code);
const due = !binding?.lastSyncedAt || now.getTime() - binding.lastSyncedAt.getTime() >= ADDRESS_SYNC_INTERVAL_MS;
if (due) addresses.set(code, await resource.loadAddressDetails(code));
}
return { search, details, addresses };
});
}
async function markProjectMissing(prepared: PreparedProjectSync, now: Date): Promise<KwpProjectSyncResult> {
await getDbClient().$transaction(async (tx) => {
const updated = await tx.appEntityBinding.updateMany({
where: {
id: prepared.binding.id,
tenantId: prepared.tenantId,
revision: prepared.binding.revision,
state: { in: ["active", "missing"] },
},
data: {
state: "missing",
revision: { increment: 1 },
missingSince: prepared.binding.missingSince ?? now,
},
});
if (updated.count !== 1) throw new KwpProjectDomainError("stale_write");
await tx.appSyncItem.create({
data: {
tenantId: prepared.tenantId,
syncRunId: prepared.runId,
entityType: PROJECT_ENTITY_TYPE,
entityId: prepared.project.id,
externalId: prepared.binding.externalId,
operation: "skipped",
status: "skipped",
errorText: "KWP-Projekt wurde nicht gefunden; lokale Daten bleiben erhalten.",
},
});
await auditEvent({
tenantId: prepared.tenantId,
actorType: "system",
action: "KWP_PROJECT_MARKED_MISSING",
targetType: "project",
targetId: prepared.project.id,
metadata: { externalProjectNumber: prepared.binding.externalId },
}, tx as never);
await logActivity({
tenantId: prepared.tenantId,
actorKind: "system",
activityType: "project_updated",
subjectType: "project",
subjectId: prepared.project.id,
summaryText: "activity.runtime.kwp.projectMissing",
metadata: { source: "kwp", state: "missing" },
}, { client: tx });
});
return { runId: prepared.runId, state: "missing", projectId: prepared.project.id, stageChanged: false };
}
async function applyProviderSnapshot(
prepared: PreparedProjectSync,
loaded: LoadedProviderSnapshot,
now: Date,
): Promise<KwpProjectSyncResult> {
const projectSnapshot = {
externalProjectNumber: loaded.search.externalProjectNumber,
name: loaded.details.name,
status: loaded.search.status,
statusLabel: loaded.search.statusLabel,
startDate: loaded.details.startDate,
orderValue: loaded.details.orderValue,
addressCodes: {
project: loaded.search.projectAddressCode,
invoice: loaded.search.invoiceAddressCode,
client: loaded.search.clientAddressCode,
},
};
const projectFingerprint = fingerprintKwpSnapshot(projectSnapshot);
return getDbClient().$transaction(async (tx) => {
const binding = await tx.appEntityBinding.findFirst({
where: {
id: prepared.binding.id,
tenantId: prepared.tenantId,
revision: prepared.binding.revision,
state: { in: ["active", "missing"] },
},
});
if (!binding) throw new KwpProjectDomainError("stale_write");
let project = await loadKwpBoundProject(tx, prepared.tenantId, prepared.project.id);
if (project.updatedAt.getTime() !== prepared.project.updatedAt.getTime()) {
throw new KwpProjectDomainError("stale_write");
}
const routing = await tx.kwpProjectRouting.findUnique({
where: {
tenantId_dataConnectionId_externalStatus: {
tenantId: prepared.tenantId,
dataConnectionId: prepared.connectionId,
externalStatus: loaded.search.status,
},
},
});
const stage = routing
? await tx.pipelineStage.findFirst({
where: {
id: routing.stageId,
tenantId: prepared.tenantId,
pipelineId: routing.pipelineId,
archivedAt: null,
pipeline: { tenantId: prepared.tenantId, archivedAt: null },
},
})
: null;
if (!routing || !stage) {
await tx.appEntityBinding.update({
where: { id: binding.id },
data: { state: "quarantined", revision: { increment: 1 }, lastSeenAt: now },
});
await tx.appSyncItem.create({
data: {
tenantId: prepared.tenantId,
syncRunId: prepared.runId,
entityType: PROJECT_ENTITY_TYPE,
entityId: project.id,
externalId: binding.externalId,
operation: "skipped",
status: "failed",
errorText: "Für den KWP-Status fehlt eine gültige Pipeline-/Stage-Zuordnung.",
},
});
return { runId: prepared.runId, state: "quarantined", projectId: project.id, stageChanged: false };
}
const requiredCodes = [
loaded.search.projectAddressCode,
loaded.search.invoiceAddressCode,
loaded.search.clientAddressCode,
].filter((value): value is string => Boolean(value));
const mainBindings = new Map(
prepared.addressBindings
.filter((entry) => entry.externalEntityType === ADDRESS_ENTITY_TYPE)
.map((entry) => [entry.externalId, entry]),
);
if (requiredCodes.some((code) => !mainBindings.has(code))) {
await tx.appEntityBinding.update({
where: { id: binding.id },
data: { state: "quarantined", revision: { increment: 1 }, lastSeenAt: now },
});
await tx.appSyncItem.create({
data: {
tenantId: prepared.tenantId,
syncRunId: prepared.runId,
entityType: PROJECT_ENTITY_TYPE,
entityId: project.id,
externalId: binding.externalId,
operation: "skipped",
status: "failed",
errorText: "Ein KWP-Adresscode hat sich geändert und muss bewusst zugeordnet werden.",
},
});
return { runId: prepared.runId, state: "quarantined", projectId: project.id, stageChanged: false };
}
for (const [code, address] of loaded.addresses) {
const addressBinding = mainBindings.get(code);
if (addressBinding) {
await reconcileAddressBinding(tx, prepared, addressBinding, address, now);
}
const personBindings = prepared.addressBindings.filter(
(entry) => entry.externalEntityType === ADDRESS_CONTACT_ENTITY_TYPE && entry.externalId.startsWith(`${code}:`),
);
for (const personBinding of personBindings) {
const externalContactId = personBinding.externalId.slice(code.length + 1);
const person = address.contactPeople.find((entry) => entry.externalContactId === externalContactId);
if (!person) {
await tx.appEntityBinding.updateMany({
where: { id: personBinding.id, tenantId: prepared.tenantId, revision: personBinding.revision },
data: { state: "missing", revision: { increment: 1 }, missingSince: now },
});
continue;
}
await reconcilePersonBinding(tx, prepared, personBinding, person, now);
}
}
const stageChanged = project.pipelineId !== routing.pipelineId || project.stageId !== routing.stageId;
const projectChanged =
projectFingerprint !== prepared.binding.fingerprint ||
project.projektname !== loaded.details.name ||
stageChanged ||
project.startDatum?.toISOString() !== loaded.details.startDate ||
decimalToNumber(project.auftragsvolumen) !== loaded.details.orderValue;
if (projectChanged) {
const updated = await tx.projekt.updateMany({
where: { id: project.id, tenantId: prepared.tenantId, updatedAt: prepared.project.updatedAt, archivedAt: null },
data: {
projektname: loaded.details.name,
pipelineId: routing.pipelineId,
stageId: routing.stageId,
startDatum: loaded.details.startDate ? new Date(loaded.details.startDate) : null,
auftragsvolumen: loaded.details.orderValue,
wonAt: stage.stageKind === "gewonnen" ? (project.wonAt ?? now) : null,
lostAt: stage.stageKind === "verloren" ? (project.lostAt ?? now) : null,
lostReasonId: null,
undoStageChangeUntil: null,
},
});
if (updated.count !== 1) throw new KwpProjectDomainError("stale_write");
project = await loadKwpBoundProject(tx, prepared.tenantId, project.id);
}
if (stageChanged) {
const change = await tx.projektStageChange.create({
data: {
tenantId: prepared.tenantId,
projektId: project.id,
fromStageId: prepared.project.stageId,
toStageId: routing.stageId,
changedByUserId: null,
undoUntil: null,
},
});
await publishOutboxEvent(
tx as unknown as OutboxPublisherTransaction,
buildWorkflowTriggerOutboxEvent({
tenantId: prepared.tenantId,
event: "project.stage_changed",
data: {
projectId: project.id,
projectNumber: project.projektNummer,
fromStageId: prepared.project.stageId,
toStageId: routing.stageId,
stageKind: stage.stageKind,
source: "kwp",
},
userId: null,
sourceId: `project:${project.id}:kwp-stage:${change.id}`,
}),
);
await logActivity({
tenantId: prepared.tenantId,
actorKind: "system",
activityType: "project_stage_changed",
subjectType: "project",
subjectId: project.id,
summaryText: "activity.runtime.kwp.projectStageChanged",
metadata: { source: "kwp", fromStageId: prepared.project.stageId, toStageId: routing.stageId },
}, { client: tx });
} else if (projectChanged || loaded.addresses.size > 0) {
await logActivity({
tenantId: prepared.tenantId,
actorKind: "system",
activityType: "project_updated",
subjectType: "project",
subjectId: project.id,
summaryText: "activity.runtime.kwp.projectUpdated",
metadata: { source: "kwp" },
}, { client: tx });
}
const bindingUpdated = await tx.appEntityBinding.updateMany({
where: { id: binding.id, tenantId: prepared.tenantId, revision: binding.revision },
data: {
state: "active",
normalizedSnapshot: projectSnapshot,
fingerprint: projectFingerprint,
revision: { increment: 1 },
lastSeenAt: now,
lastSyncedAt: now,
missingSince: null,
},
});
if (bindingUpdated.count !== 1) throw new KwpProjectDomainError("stale_write");
await tx.appSyncItem.create({
data: {
tenantId: prepared.tenantId,
syncRunId: prepared.runId,
entityType: PROJECT_ENTITY_TYPE,
entityId: project.id,
externalId: binding.externalId,
operation: projectChanged || loaded.addresses.size > 0 ? "updated" : "skipped",
status: projectChanged || loaded.addresses.size > 0 ? "synced" : "skipped",
},
});
if (projectChanged || loaded.addresses.size > 0) {
await auditEvent({
tenantId: prepared.tenantId,
actorType: "system",
action: "KWP_PROJECT_RECONCILED",
targetType: "project",
targetId: project.id,
metadata: { source: "kwp", stageChanged },
}, tx as never);
await publishKwpProjectSearch(tx, project, binding.externalId);
}
return {
runId: prepared.runId,
state: projectChanged || loaded.addresses.size > 0 ? "synced" : "unchanged",
projectId: project.id,
stageChanged,
};
});
}
async function reconcileAddressBinding(
tx: Prisma.TransactionClient,
prepared: PreparedProjectSync,
binding: PreparedProjectSync["addressBindings"][number],
address: KwpAddressDetails,
now: Date,
): Promise<void> {
const contact = await tx.kontakt.findFirst({
where: { id: binding.localId, tenantId: prepared.tenantId, archivedAt: null },
include: { adresse: true },
});
if (!contact) throw new KwpProjectDomainError("contact_not_found");
const isPerson = Boolean(address.firstName);
const primaryEmail = address.email ?? address.invoiceEmail;
const primaryPhone = address.phone ?? address.mobile;
const updated = await tx.kontakt.updateMany({
where: { id: contact.id, tenantId: prepared.tenantId, updatedAt: contact.updatedAt },
data: {
kontaktTyp: isPerson ? "privatperson" : "organisation",
vorname: isPerson ? address.firstName : null,
nachname: isPerson ? (address.name ?? address.externalAddressCode) : null,
orgName: isPerson ? null : (address.name ?? address.externalAddressCode),
primaerEmail: primaryEmail,
primaerTelefon: primaryPhone,
},
});
if (updated.count !== 1) throw new KwpProjectDomainError("stale_write");
await syncKwpPrimaryContactChannels(
tx,
prepared.tenantId,
contact.id,
primaryEmail,
primaryPhone,
);
if (contact.adresseId) {
const addressUpdated = await tx.adresse.updateMany({
where: { id: contact.adresseId, tenantId: prepared.tenantId, updatedAt: contact.adresse?.updatedAt },
data: {
strasse: address.street,
hausnummer: null,
plz: address.postalCode,
ort: address.city,
land: address.country ?? "DE",
},
});
if (addressUpdated.count !== 1) throw new KwpProjectDomainError("stale_write");
}
const bindingUpdated = await tx.appEntityBinding.updateMany({
where: { id: binding.id, tenantId: prepared.tenantId, revision: binding.revision },
data: {
state: "active",
normalizedSnapshot: address,
fingerprint: fingerprintKwpSnapshot(address),
revision: { increment: 1 },
lastSeenAt: now,
lastSyncedAt: now,
missingSince: null,
},
});
if (bindingUpdated.count !== 1) throw new KwpProjectDomainError("stale_write");
const refreshed = await tx.kontakt.findUniqueOrThrow({ where: { id: contact.id }, include: { adresse: true } });
await publishKwpContactSearch(tx, refreshed);
}
async function reconcilePersonBinding(
tx: Prisma.TransactionClient,
prepared: PreparedProjectSync,
binding: PreparedProjectSync["addressBindings"][number],
person: KwpAddressDetails["contactPeople"][number],
now: Date,
): Promise<void> {
const contact = await tx.kontakt.findFirst({
where: { id: binding.localId, tenantId: prepared.tenantId, archivedAt: null },
include: { adresse: true },
});
if (!contact) throw new KwpProjectDomainError("contact_not_found");
const updated = await tx.kontakt.updateMany({
where: { id: contact.id, tenantId: prepared.tenantId, updatedAt: contact.updatedAt },
data: {
kontaktTyp: "privatperson",
vorname: person.firstName,
nachname: person.lastName ?? person.externalContactId,
orgName: null,
primaerEmail: person.email,
primaerTelefon: person.phone ?? person.mobile,
},
});
if (updated.count !== 1) throw new KwpProjectDomainError("stale_write");
await syncKwpPrimaryContactChannels(
tx,
prepared.tenantId,
contact.id,
person.email,
person.phone ?? person.mobile,
);
const bindingUpdated = await tx.appEntityBinding.updateMany({
where: { id: binding.id, tenantId: prepared.tenantId, revision: binding.revision },
data: {
state: "active",
normalizedSnapshot: person,
fingerprint: fingerprintKwpSnapshot(person),
revision: { increment: 1 },
lastSeenAt: now,
lastSyncedAt: now,
missingSince: null,
},
});
if (bindingUpdated.count !== 1) throw new KwpProjectDomainError("stale_write");
const refreshed = await tx.kontakt.findUniqueOrThrow({ where: { id: contact.id }, include: { adresse: true } });
await publishKwpContactSearch(tx, refreshed);
}
async function finishRun(prepared: PreparedProjectSync, state: KwpProjectSyncResult["state"], now: Date): Promise<void> {
const failed = state === "quarantined" ? 1 : 0;
await getDbClient().appSyncRun.updateMany({
where: { id: prepared.runId, tenantId: prepared.tenantId, status: "running" },
data: {
status: failed ? "partial" : "completed",
itemsTotal: 1,
itemsSucceeded: failed ? 0 : 1,
itemsFailed: failed,
summaryText: runSummary(prepared.binding.externalId, state),
completedAt: now,
},
});
}
async function failRun(prepared: PreparedProjectSync, _error: unknown, now: Date): Promise<void> {
await getDbClient().appSyncRun.updateMany({
where: { id: prepared.runId, tenantId: prepared.tenantId, status: "running" },
data: {
status: "failed",
itemsTotal: 1,
itemsFailed: 1,
summaryText: "integrations.sync.summary.kwpProjectFailed",
completedAt: now,
},
});
}
function runSummary(_externalId: string, state: KwpProjectSyncResult["state"]): string {
if (state === "unchanged") return "integrations.sync.summary.kwpProjectUnchanged";
if (state === "missing") return "integrations.sync.summary.kwpProjectMissing";
if (state === "quarantined") return "integrations.sync.summary.kwpProjectQuarantined";
return "integrations.sync.summary.kwpProjectUpdated";
}
function decimalToNumber(value: unknown): number | null {
if (value === null || value === undefined) return null;
const parsed = Number(String(value));
return Number.isFinite(parsed) ? parsed : null;
}
function requireTenantContext(): string {
const tenantId = getRlsExecutionContext()?.tenantId?.trim();
if (!tenantId) throw new KwpProjectDomainError("project_not_found");
return tenantId;
}
function normalizeId(value: string): string {
const normalized = value.trim();
if (!/^[A-Za-z0-9_-]{3,191}$/u.test(normalized)) throw new KwpProjectDomainError("project_not_found");
return normalized;
}
@@ -0,0 +1,287 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
KwpProjectDomainError: class KwpProjectDomainError extends Error {
readonly code: string;
constructor(code: string) {
super(code);
this.code = code;
}
},
auditEvent: vi.fn(),
logActivity: vi.fn(),
publishOutboxEvent: vi.fn(),
buildWorkflowTriggerOutboxEvent: vi.fn((input) => input),
transaction: vi.fn(),
runKwpResourceSession: vi.fn(),
loadKwpBoundProject: vi.fn(),
publishKwpContactSearch: vi.fn(),
publishKwpProjectSearch: vi.fn(),
bindingFindFirst: vi.fn(),
bindingFindMany: vi.fn(),
bindingUpdate: vi.fn(),
bindingUpdateMany: vi.fn(),
capabilityFindUnique: vi.fn(),
routingFindUnique: vi.fn(),
stageFindFirst: vi.fn(),
stageChangeCreate: vi.fn(),
runCreate: vi.fn(),
runUpdateMany: vi.fn(),
itemCreate: vi.fn(),
projectUpdateMany: vi.fn(),
getRlsExecutionContext: vi.fn(),
resourceSearch: vi.fn(),
resourceLoadProjectDetails: vi.fn(),
events: [] as string[],
}));
vi.mock("@hivegrid/activity", () => ({ logActivity: mocks.logActivity }));
vi.mock("@hivegrid/db/client.server", () => ({
getDbClient: () => ({
$transaction: mocks.transaction,
appSyncRun: { updateMany: mocks.runUpdateMany },
}),
}));
vi.mock("@hivegrid/db/outbox", () => ({ publishOutboxEvent: mocks.publishOutboxEvent }));
vi.mock("@hivegrid/db/rls-context.server", () => ({
getRlsExecutionContext: mocks.getRlsExecutionContext,
}));
vi.mock("@hivegrid/foundation", () => ({ auditEvent: mocks.auditEvent }));
vi.mock("@hivegrid/queue", () => ({ buildWorkflowTriggerOutboxEvent: mocks.buildWorkflowTriggerOutboxEvent }));
vi.mock("./project-domain.server.js", () => ({
KwpProjectDomainError: mocks.KwpProjectDomainError,
loadKwpBoundProject: mocks.loadKwpBoundProject,
publishKwpContactSearch: mocks.publishKwpContactSearch,
publishKwpProjectSearch: mocks.publishKwpProjectSearch,
syncKwpPrimaryContactChannels: vi.fn(),
}));
vi.mock("./resource-client.server.js", () => ({
runKwpResourceSession: mocks.runKwpResourceSession,
}));
import { syncKwpProjectBinding } from "./project-sync.server.js";
const now = new Date("2026-07-23T13:00:00.000Z");
const project = {
id: "project-1",
tenantId: "tenant-1",
projektNummer: "P-00042",
projektname: "Local",
pipelineId: "pipeline-1",
stageId: "stage-1",
startDatum: null,
auftragsvolumen: null,
wonAt: null,
lostAt: null,
updatedAt: new Date("2026-07-23T12:00:00.000Z"),
};
const binding = {
id: "binding-1",
tenantId: "tenant-1",
dataConnectionId: "connection-1",
externalId: "KWP-4711",
localId: "project-1",
revision: 7,
fingerprint: "old",
missingSince: null,
};
const tx = {
appEntityBinding: {
findFirst: mocks.bindingFindFirst,
findMany: mocks.bindingFindMany,
update: mocks.bindingUpdate,
updateMany: mocks.bindingUpdateMany,
},
kwpCapabilityState: { findUnique: mocks.capabilityFindUnique },
kwpProjectRouting: { findUnique: mocks.routingFindUnique },
pipelineStage: { findFirst: mocks.stageFindFirst },
appSyncRun: { create: mocks.runCreate },
appSyncItem: { create: mocks.itemCreate },
projekt: { updateMany: mocks.projectUpdateMany },
projektStageChange: { create: mocks.stageChangeCreate },
};
beforeEach(() => {
vi.clearAllMocks();
mocks.events.length = 0;
mocks.getRlsExecutionContext.mockReturnValue({ tenantId: "tenant-1" });
mocks.transaction.mockImplementation(async (callback) => {
mocks.events.push("tx:start");
const result = await callback(tx);
mocks.events.push("tx:end");
return result;
});
mocks.bindingFindFirst.mockResolvedValue(binding);
mocks.bindingFindMany.mockResolvedValue([]);
mocks.bindingUpdateMany.mockResolvedValue({ count: 1 });
mocks.bindingUpdate.mockResolvedValue({});
mocks.capabilityFindUnique.mockResolvedValue({ status: "active" });
mocks.routingFindUnique.mockResolvedValue({
pipelineId: "pipeline-2",
stageId: "stage-2",
});
mocks.stageFindFirst.mockResolvedValue({
id: "stage-2",
name: "In Arbeit",
stageKind: "neutral",
});
mocks.stageChangeCreate.mockResolvedValue({ id: "change-1" });
mocks.loadKwpBoundProject.mockResolvedValue(project);
mocks.runCreate.mockResolvedValue({ id: "run-1" });
mocks.runUpdateMany.mockResolvedValue({ count: 1 });
mocks.itemCreate.mockResolvedValue({ id: "item-1" });
mocks.auditEvent.mockResolvedValue(undefined);
mocks.logActivity.mockResolvedValue(undefined);
mocks.resourceSearch.mockResolvedValue([]);
mocks.resourceLoadProjectDetails.mockResolvedValue({
externalProjectNumber: "KWP-4711",
name: "KWP Project",
startDate: "2026-07-01T00:00:00.000Z",
orderValue: 42_500,
});
mocks.runKwpResourceSession.mockImplementation(async (_input, callback) => {
mocks.events.push("provider");
return callback({
searchProjects: mocks.resourceSearch,
loadProjectDetails: mocks.resourceLoadProjectDetails,
loadAddressDetails: vi.fn(),
});
});
});
describe("KWP three-phase project sync", () => {
it("does provider I/O between short transactions and marks a missing project without deleting local data", async () => {
const result = await syncKwpProjectBinding({ bindingId: "binding-1", now });
expect(result).toEqual({
runId: "run-1",
state: "missing",
projectId: "project-1",
stageChanged: false,
});
expect(mocks.events).toEqual([
"tx:start",
"tx:end",
"provider",
"tx:start",
"tx:end",
]);
expect(mocks.bindingUpdateMany).toHaveBeenCalledWith({
where: {
id: "binding-1",
tenantId: "tenant-1",
revision: 7,
state: { in: ["active", "missing"] },
},
data: {
state: "missing",
revision: { increment: 1 },
missingSince: now,
},
});
expect(mocks.projectUpdateMany).not.toHaveBeenCalled();
expect(mocks.itemCreate).toHaveBeenCalledWith({
data: expect.objectContaining({ operation: "skipped", status: "skipped" }),
});
expect(mocks.runUpdateMany).toHaveBeenLastCalledWith(expect.objectContaining({
data: expect.objectContaining({ status: "completed", itemsSucceeded: 1 }),
}));
});
it("records a failed run but performs no local partial mutation on network failure", async () => {
mocks.runKwpResourceSession.mockImplementationOnce(async () => {
mocks.events.push("provider");
throw new Error("provider unavailable");
});
await expect(syncKwpProjectBinding({ bindingId: "binding-1", now }))
.rejects.toThrow("provider unavailable");
expect(mocks.bindingUpdateMany).not.toHaveBeenCalled();
expect(mocks.projectUpdateMany).not.toHaveBeenCalled();
expect(mocks.itemCreate).not.toHaveBeenCalled();
expect(mocks.runUpdateMany).toHaveBeenCalledWith(expect.objectContaining({
data: expect.objectContaining({ status: "failed", itemsFailed: 1 }),
}));
});
it("atomically reconciles a later stage change and emits the existing event with source=kwp", async () => {
mocks.resourceSearch.mockResolvedValueOnce([{
externalProjectNumber: "KWP-4711",
name: "KWP Project",
projectAddressCode: null,
invoiceAddressCode: null,
clientAddressCode: null,
status: 8,
statusLabel: "Erhalten",
}]);
mocks.projectUpdateMany.mockResolvedValue({ count: 1 });
mocks.loadKwpBoundProject
.mockResolvedValueOnce(project)
.mockResolvedValueOnce(project)
.mockResolvedValueOnce({
...project,
projektname: "KWP Project",
pipelineId: "pipeline-2",
stageId: "stage-2",
startDatum: new Date("2026-07-01T00:00:00.000Z"),
auftragsvolumen: 42_500,
updatedAt: new Date("2026-07-23T13:00:00.000Z"),
});
await expect(syncKwpProjectBinding({ bindingId: "binding-1", now })).resolves.toEqual({
runId: "run-1",
state: "synced",
projectId: "project-1",
stageChanged: true,
});
expect(mocks.events).toEqual(["tx:start", "tx:end", "provider", "tx:start", "tx:end"]);
expect(mocks.projectUpdateMany).toHaveBeenCalledWith(expect.objectContaining({
where: expect.objectContaining({
id: "project-1",
tenantId: "tenant-1",
updatedAt: project.updatedAt,
}),
data: expect.objectContaining({
projektname: "KWP Project",
pipelineId: "pipeline-2",
stageId: "stage-2",
}),
}));
expect(mocks.buildWorkflowTriggerOutboxEvent).toHaveBeenCalledWith(expect.objectContaining({
event: "project.stage_changed",
data: expect.objectContaining({
projectId: "project-1",
fromStageId: "stage-1",
toStageId: "stage-2",
source: "kwp",
}),
}));
expect(mocks.publishOutboxEvent).toHaveBeenCalledOnce();
expect(mocks.publishKwpProjectSearch).toHaveBeenCalledOnce();
});
it("quarantines an unknown status without mutating the project", async () => {
mocks.resourceSearch.mockResolvedValueOnce([{
externalProjectNumber: "KWP-4711",
name: "KWP Project",
projectAddressCode: null,
invoiceAddressCode: null,
clientAddressCode: null,
status: 99,
statusLabel: "Unbekannt",
}]);
mocks.routingFindUnique.mockResolvedValueOnce(null);
await expect(syncKwpProjectBinding({ bindingId: "binding-1", now })).resolves.toEqual({
runId: "run-1",
state: "quarantined",
projectId: "project-1",
stageChanged: false,
});
expect(mocks.projectUpdateMany).not.toHaveBeenCalled();
expect(mocks.publishOutboxEvent).not.toHaveBeenCalled();
expect(mocks.bindingUpdateMany).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,666 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createSharedStore, MemoryAdapter } from "@hivegrid/shared-store";
const mocks = vi.hoisted(() => ({
transaction: vi.fn(),
connectionFindFirst: vi.fn(),
capabilityFindUnique: vi.fn(),
capabilityUpsert: vi.fn(),
capabilityUpdateMany: vi.fn(),
reportCreate: vi.fn(),
reportUpdateMany: vi.fn(),
auditEvent: vi.fn(),
decryptTenantField: vi.fn(),
getRlsExecutionContext: vi.fn(),
executeReadOperation: vi.fn(),
searchProjects: vi.fn(),
createKwpResourceTransport: vi.fn(),
claimExpiringTokenRefreshForConnection: vi.fn(),
executeClaimedTokenRefresh: vi.fn(),
persistClaimedTokenRefresh: vi.fn(),
loggerInfo: vi.fn(),
loggerError: vi.fn(),
}));
vi.mock("@hivegrid/db/client.server", () => ({
getDbClient: () => ({
$transaction: mocks.transaction,
}),
}));
vi.mock("@hivegrid/db/crypto/tenant-envelope.server", () => ({
decryptTenantField: mocks.decryptTenantField,
}));
vi.mock("@hivegrid/db/rls-context.server", () => ({
getRlsExecutionContext: mocks.getRlsExecutionContext,
}));
vi.mock("@hivegrid/foundation", () => ({
auditEvent: mocks.auditEvent,
}));
vi.mock("@hivegrid/logger", () => ({
defaultLogger: {},
createChildLogger: () => ({
info: mocks.loggerInfo,
error: mocks.loggerError,
}),
}));
vi.mock("../worker-tasks.server.js", () => ({
KWP_TOKEN_REFRESH_WINDOW_MS: 2 * 60_000,
TOKEN_REFRESH_CLAIM_MESSAGE_KEY: "integrations.health.refreshInProgress",
TOKEN_REFRESH_RETRY_MESSAGE_KEY: "integrations.health.refreshRetryPending",
claimExpiringTokenRefreshForConnection: mocks.claimExpiringTokenRefreshForConnection,
executeClaimedTokenRefresh: mocks.executeClaimedTokenRefresh,
persistClaimedTokenRefresh: mocks.persistClaimedTokenRefresh,
}));
vi.mock("./resource-client.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("./resource-client.js")>();
return {
...actual,
createKwpResourceTransport: mocks.createKwpResourceTransport,
};
});
import {
__resetKwpResourceSharedStoreForTests,
__setKwpResourceSharedStoreForTests,
executeKwpReadOperation,
readKwpProjectCapabilityFailureCode,
revalidateAndRecoverKwpProjectSearch,
searchProjects,
} from "./resource-client.server.js";
import { KWP_PROJECT_ADAPTER_REVISION } from "./resource-client.js";
import { KwpError } from "./client.js";
const credentials = {
accessToken: "access-secret",
refreshToken: "refresh-secret",
expiresAt: "2099-07-23T12:00:00.000Z",
issuer: "https://idp4.kwp-online.de/realms/kwp",
clientId: "_extern-geerkens2",
clientSecret: "client-secret",
customerCode: "geerkens2",
scopes: ["offline_access"],
mandantBinding: { kind: "selected", code: "mandant1" },
};
const tx = {
dataConnection: { findFirst: mocks.connectionFindFirst },
kwpCapabilityState: {
findUnique: mocks.capabilityFindUnique,
upsert: mocks.capabilityUpsert,
updateMany: mocks.capabilityUpdateMany,
},
kwpErrorReport: {
create: mocks.reportCreate,
updateMany: mocks.reportUpdateMany,
},
};
beforeEach(() => {
vi.clearAllMocks();
__resetKwpResourceSharedStoreForTests();
mocks.getRlsExecutionContext.mockReturnValue({ tenantId: "tenant-1" });
mocks.connectionFindFirst.mockResolvedValue({
id: "connection-1",
credentialsCiphertext: "encrypted",
connectionStatus: "active",
tokenExpiresAt: new Date(credentials.expiresAt),
healthMessageKey: "integrations.kwp.health.active",
});
mocks.capabilityFindUnique.mockResolvedValue({ status: "active" });
mocks.capabilityUpsert.mockResolvedValue({});
mocks.capabilityUpdateMany.mockResolvedValue({ count: 1 });
mocks.reportCreate.mockResolvedValue({});
mocks.reportUpdateMany.mockResolvedValue({ count: 1 });
mocks.auditEvent.mockResolvedValue(undefined);
mocks.decryptTenantField.mockResolvedValue(JSON.stringify(credentials));
mocks.transaction.mockImplementation((callback) => callback(tx));
mocks.searchProjects.mockResolvedValue([]);
mocks.executeReadOperation.mockResolvedValue({});
mocks.claimExpiringTokenRefreshForConnection.mockResolvedValue({ state: "skipped" });
mocks.persistClaimedTokenRefresh.mockResolvedValue({ refreshed: 1, failed: 0, retryScheduled: 0 });
mocks.createKwpResourceTransport.mockImplementation((_credentials, options) => ({
executeReadOperation: async (operationId: string, input: unknown) => {
await options.consumeBudget();
return mocks.executeReadOperation(operationId, input);
},
searchProjects: async (query: string) => {
await options.consumeBudget();
return mocks.searchProjects(query);
},
}));
});
afterEach(() => {
vi.unstubAllEnvs();
vi.useRealTimers();
});
describe("KWP resource server boundary", () => {
it("reuses a fresh access token without rotating KWP's one-time refresh token", async () => {
__setKwpResourceSharedStoreForTests(createSharedStore({ namespace: "kwp-resource-server-fresh-token", adapter: new MemoryAdapter() }));
await expect(searchProjects({ connectionId: "connection-1", query: "Projekt" })).resolves.toEqual([]);
expect(mocks.claimExpiringTokenRefreshForConnection).not.toHaveBeenCalled();
expect(mocks.createKwpResourceTransport).toHaveBeenCalledWith(credentials, expect.any(Object));
});
it("rotates and persists an expiring token exactly before the resource window", async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-07-31T18:00:00.000Z"));
vi.stubEnv("KWP_HIVEGRID_TENANT_ID", "tenant-1");
const expiringCredentials = { ...credentials, expiresAt: "2026-07-31T18:01:00.000Z", refreshToken: "refresh-1" };
const rotatedCredentials = { ...credentials, expiresAt: "2026-07-31T18:05:00.000Z", accessToken: "access-2", refreshToken: "refresh-2" };
const expiringRow = {
id: "connection-1",
credentialsCiphertext: "encrypted-1",
connectionStatus: "active",
tokenExpiresAt: new Date(expiringCredentials.expiresAt),
healthMessageKey: "integrations.kwp.health.active",
};
const refreshedRow = {
...expiringRow,
credentialsCiphertext: "encrypted-2",
tokenExpiresAt: new Date(rotatedCredentials.expiresAt),
};
const claim = {
tenantId: "tenant-1",
connectionId: "connection-1",
appId: "kwp",
ownerUserId: "user-1",
credentials: expiringCredentials,
credentialsCiphertext: expiringRow.credentialsCiphertext,
tokenExpiresAt: expiringRow.tokenExpiresAt,
claimedAt: new Date("2026-07-31T18:00:00.000Z"),
previousConnectionStatus: "active",
previousHealthMessageKey: "integrations.kwp.health.active",
previousLastHealthCheck: new Date("2026-07-31T17:55:00.000Z"),
} as const;
mocks.connectionFindFirst.mockResolvedValueOnce(expiringRow).mockResolvedValueOnce(refreshedRow);
mocks.decryptTenantField
.mockResolvedValueOnce(JSON.stringify(expiringCredentials))
.mockResolvedValueOnce(JSON.stringify(rotatedCredentials));
mocks.claimExpiringTokenRefreshForConnection.mockResolvedValueOnce({ state: "claimed", claim });
mocks.executeClaimedTokenRefresh.mockResolvedValueOnce({
ok: true,
creds: rotatedCredentials,
expiresAt: refreshedRow.tokenExpiresAt,
});
__setKwpResourceSharedStoreForTests(createSharedStore({ namespace: "kwp-resource-server-demand-token", adapter: new MemoryAdapter() }));
await expect(searchProjects({ connectionId: "connection-1", query: "Projekt" })).resolves.toEqual([]);
expect(mocks.claimExpiringTokenRefreshForConnection).toHaveBeenCalledWith(
tx,
"tenant-1",
"connection-1",
expect.objectContaining({
windowMs: 2 * 60_000,
kwpHiveGridTenantId: "tenant-1",
}),
);
expect(mocks.executeClaimedTokenRefresh).toHaveBeenCalledTimes(1);
expect(mocks.persistClaimedTokenRefresh).toHaveBeenCalledWith(tx, claim, {
ok: true,
creds: rotatedCredentials,
expiresAt: refreshedRow.tokenExpiresAt,
});
expect(mocks.createKwpResourceTransport).toHaveBeenCalledWith(rotatedCredentials, expect.any(Object));
});
it("makes a parallel resource caller follow the same durable rotation instead of refreshing twice", async () => {
vi.stubEnv("KWP_HIVEGRID_TENANT_ID", "tenant-1");
const now = Date.now();
const expiringCredentials = { ...credentials, expiresAt: new Date(now + 60_000).toISOString(), refreshToken: "refresh-parallel-1" };
const rotatedCredentials = {
...credentials,
expiresAt: new Date(now + 5 * 60_000).toISOString(),
accessToken: "access-parallel-2",
refreshToken: "refresh-parallel-2",
};
const claimedAt = new Date(now);
const claim = {
tenantId: "tenant-1",
connectionId: "connection-1",
appId: "kwp",
ownerUserId: "user-1",
credentials: expiringCredentials,
credentialsCiphertext: "encrypted-parallel-1",
tokenExpiresAt: new Date(expiringCredentials.expiresAt),
claimedAt,
previousConnectionStatus: "active",
previousHealthMessageKey: "integrations.kwp.health.active",
previousLastHealthCheck: new Date(now - 5 * 60_000),
} as const;
let state: "expired" | "claimed" | "fresh" = "expired";
mocks.connectionFindFirst.mockImplementation(async () => ({
id: "connection-1",
credentialsCiphertext: state === "fresh" ? "encrypted-parallel-2" : "encrypted-parallel-1",
connectionStatus: state === "claimed" ? "degraded" : "active",
tokenExpiresAt: new Date(state === "fresh" ? rotatedCredentials.expiresAt : expiringCredentials.expiresAt),
healthMessageKey: state === "claimed" ? "integrations.health.refreshInProgress" : "integrations.kwp.health.active",
}));
mocks.decryptTenantField.mockImplementation(async () => JSON.stringify(state === "fresh" ? rotatedCredentials : expiringCredentials));
mocks.claimExpiringTokenRefreshForConnection.mockImplementation(async () => {
if (state !== "expired") return { state: "skipped" } as const;
state = "claimed";
return { state: "claimed", claim } as const;
});
let releaseProvider!: () => void;
const providerBarrier = new Promise<void>((resolve) => {
releaseProvider = resolve;
});
mocks.executeClaimedTokenRefresh.mockImplementation(async () => {
await providerBarrier;
return { ok: true, creds: rotatedCredentials, expiresAt: new Date(rotatedCredentials.expiresAt) } as const;
});
mocks.persistClaimedTokenRefresh.mockImplementation(async () => {
state = "fresh";
return { refreshed: 1, failed: 0, retryScheduled: 0 };
});
__setKwpResourceSharedStoreForTests(createSharedStore({ namespace: "kwp-resource-server-parallel-token", adapter: new MemoryAdapter() }));
const leader = searchProjects({ connectionId: "connection-1", query: "Projekt" });
await vi.waitFor(() => expect(mocks.executeClaimedTokenRefresh).toHaveBeenCalledTimes(1));
const follower = searchProjects({ connectionId: "connection-1", query: "Projekt" });
await vi.waitFor(() => expect(mocks.claimExpiringTokenRefreshForConnection).toHaveBeenCalledTimes(2));
releaseProvider();
await expect(Promise.all([leader, follower])).resolves.toEqual([[], []]);
expect(mocks.executeClaimedTokenRefresh).toHaveBeenCalledTimes(1);
expect(mocks.persistClaimedTokenRefresh).toHaveBeenCalledTimes(1);
expect(mocks.createKwpResourceTransport).toHaveBeenCalledTimes(2);
expect(mocks.createKwpResourceTransport).toHaveBeenNthCalledWith(1, rotatedCredentials, expect.any(Object));
expect(mocks.createKwpResourceTransport).toHaveBeenNthCalledWith(2, rotatedCredentials, expect.any(Object));
});
it("retries only local persistence after KWP returned the one surviving successor", async () => {
vi.stubEnv("KWP_HIVEGRID_TENANT_ID", "tenant-1");
const now = Date.now();
const expiringCredentials = { ...credentials, expiresAt: new Date(now + 60_000).toISOString(), refreshToken: "refresh-retry-1" };
const rotatedCredentials = {
...credentials,
expiresAt: new Date(now + 5 * 60_000).toISOString(),
accessToken: "access-retry-2",
refreshToken: "refresh-retry-2",
};
const claim = {
tenantId: "tenant-1",
connectionId: "connection-1",
appId: "kwp",
ownerUserId: "user-1",
credentials: expiringCredentials,
credentialsCiphertext: "encrypted-retry-1",
tokenExpiresAt: new Date(expiringCredentials.expiresAt),
claimedAt: new Date(now),
previousConnectionStatus: "active",
previousHealthMessageKey: "integrations.kwp.health.active",
previousLastHealthCheck: new Date(now - 5 * 60_000),
} as const;
let persisted = false;
mocks.connectionFindFirst.mockImplementation(async () => ({
id: "connection-1",
credentialsCiphertext: persisted ? "encrypted-retry-2" : "encrypted-retry-1",
connectionStatus: persisted ? "active" : "degraded",
tokenExpiresAt: new Date(persisted ? rotatedCredentials.expiresAt : expiringCredentials.expiresAt),
healthMessageKey: persisted ? "integrations.kwp.health.active" : "integrations.health.refreshInProgress",
}));
mocks.decryptTenantField.mockImplementation(async () => JSON.stringify(persisted ? rotatedCredentials : expiringCredentials));
mocks.claimExpiringTokenRefreshForConnection.mockResolvedValueOnce({ state: "claimed", claim });
mocks.executeClaimedTokenRefresh.mockResolvedValueOnce({
ok: true,
creds: rotatedCredentials,
expiresAt: new Date(rotatedCredentials.expiresAt),
});
mocks.persistClaimedTokenRefresh
.mockRejectedValueOnce(Object.assign(new Error(`temporary ${expiringCredentials.refreshToken}`), { code: "P2010" }))
.mockImplementationOnce(async () => {
persisted = true;
return { refreshed: 1, failed: 0, retryScheduled: 0 };
});
__setKwpResourceSharedStoreForTests(createSharedStore({ namespace: "kwp-resource-server-persist-retry", adapter: new MemoryAdapter() }));
await expect(searchProjects({ connectionId: "connection-1", query: "Projekt" })).resolves.toEqual([]);
expect(mocks.executeClaimedTokenRefresh).toHaveBeenCalledTimes(1);
expect(mocks.persistClaimedTokenRefresh).toHaveBeenCalledTimes(2);
expect(mocks.loggerError).toHaveBeenCalledWith(
expect.objectContaining({ attempt: 1, maxAttempts: 6, failureClass: "database_known", errorCode: "P2010", delayMs: 250 }),
"integrations.kwp-token-demand.persistence-failed",
);
expect(JSON.stringify(mocks.loggerError.mock.calls)).not.toContain(expiringCredentials.refreshToken);
});
it("exposes only stable capability failure codes to route loaders", () => {
expect(readKwpProjectCapabilityFailureCode(new KwpError("contract_drift"))).toBe("contract_drift");
expect(readKwpProjectCapabilityFailureCode(new KwpError("capability_paused"))).toBe("capability_paused");
expect(readKwpProjectCapabilityFailureCode(new KwpError("auth_scope_missing", 403))).toBe("auth_scope_missing");
expect(readKwpProjectCapabilityFailureCode(new KwpError("provider_outage", 503))).toBeNull();
expect(readKwpProjectCapabilityFailureCode(new Error("contract_drift"))).toBeNull();
});
it("blocks a paused capability before constructing a provider transport", async () => {
mocks.capabilityFindUnique.mockResolvedValueOnce({ status: "paused" });
await expect(
searchProjects({
connectionId: "connection-1",
query: "Projekt",
})
).rejects.toMatchObject({ code: "capability_paused" });
expect(mocks.createKwpResourceTransport).not.toHaveBeenCalled();
expect(mocks.decryptTenantField).not.toHaveBeenCalled();
});
it("recovers a sticky response-schema pause only after the current search response validates", async () => {
const fingerprint = "a".repeat(64);
const result = {
externalProjectNumber: "P-100",
name: "Projekt 100",
projectAddressCode: null,
invoiceAddressCode: null,
clientAddressCode: null,
status: 8,
statusLabel: "Erhalten",
};
mocks.capabilityFindUnique
.mockResolvedValueOnce({ status: "paused" })
.mockResolvedValueOnce({
id: "capability-1",
status: "paused",
reasonCode: "kwp.project.contract_drift",
approvedFingerprint: fingerprint,
observedFingerprint: fingerprint,
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
revision: 7,
});
mocks.searchProjects.mockResolvedValueOnce([result]);
__setKwpResourceSharedStoreForTests(createSharedStore({ namespace: "kwp-resource-server-recovery", adapter: new MemoryAdapter() }));
await expect(
revalidateAndRecoverKwpProjectSearch({
connectionId: "connection-1",
query: "Projekt",
})
).resolves.toEqual([result]);
expect(mocks.capabilityUpdateMany).toHaveBeenCalledWith({
where: {
id: "capability-1",
tenantId: "tenant-1",
dataConnectionId: "connection-1",
capability: "project-import",
status: "paused",
reasonCode: "kwp.project.contract_drift",
approvedFingerprint: fingerprint,
observedFingerprint: fingerprint,
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
revision: 7,
},
data: {
status: "active",
reasonCode: null,
revision: { increment: 1 },
pausedAt: null,
lastCheckedAt: expect.any(Date),
},
});
expect(mocks.reportUpdateMany).toHaveBeenCalledWith({
where: {
tenantId: "tenant-1",
dataConnectionId: "connection-1",
capability: "project-import",
code: "kwp.project.contract_drift",
resolvedAt: null,
},
data: { resolvedAt: expect.any(Date) },
});
expect(mocks.auditEvent).toHaveBeenCalledWith(
expect.objectContaining({
action: "KWP_RESPONSE_SCHEMA_RECOVERED",
metadata: {
capability: "project-import",
approvedFingerprint: fingerprint,
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
},
}),
tx
);
});
it.each([
{
name: "semantic fingerprint drift",
namespace: "semantic-drift",
state: {
reasonCode: "kwp.project.contract_drift",
approvedFingerprint: "a".repeat(64),
observedFingerprint: "b".repeat(64),
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
},
},
{
name: "provider permission failure",
namespace: "provider-permission",
state: {
reasonCode: "kwp.project.missing_provider_permission",
approvedFingerprint: "a".repeat(64),
observedFingerprint: "a".repeat(64),
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
},
},
])("keeps $name paused after a valid reprobe", async ({ namespace, state }) => {
mocks.capabilityFindUnique
.mockResolvedValueOnce({ status: "paused" })
.mockResolvedValueOnce({
id: "capability-1",
status: "paused",
revision: 7,
...state,
});
__setKwpResourceSharedStoreForTests(createSharedStore({ namespace: `kwp-resource-server-no-recovery-${namespace}`, adapter: new MemoryAdapter() }));
await expect(
revalidateAndRecoverKwpProjectSearch({
connectionId: "connection-1",
query: "Projekt",
})
).rejects.toMatchObject({ code: "capability_paused" });
expect(mocks.capabilityUpdateMany).not.toHaveBeenCalled();
expect(mocks.reportUpdateMany).not.toHaveBeenCalled();
expect(mocks.auditEvent).not.toHaveBeenCalled();
});
it("does not recover when the response still fails current adapter validation", async () => {
mocks.capabilityFindUnique.mockResolvedValueOnce({ status: "paused" });
mocks.searchProjects.mockRejectedValueOnce(new KwpError("contract_drift"));
__setKwpResourceSharedStoreForTests(createSharedStore({ namespace: "kwp-resource-server-invalid-reprobe", adapter: new MemoryAdapter() }));
await expect(
revalidateAndRecoverKwpProjectSearch({
connectionId: "connection-1",
query: "Projekt",
})
).rejects.toMatchObject({ code: "contract_drift" });
expect(mocks.capabilityUpdateMany).not.toHaveBeenCalled();
expect(mocks.reportUpdateMany).not.toHaveBeenCalled();
expect(mocks.auditEvent).not.toHaveBeenCalled();
});
it("keeps the capability paused when the optimistic recovery write is stale", async () => {
const fingerprint = "a".repeat(64);
mocks.capabilityFindUnique
.mockResolvedValueOnce({ status: "paused" })
.mockResolvedValueOnce({
id: "capability-1",
status: "paused",
reasonCode: "kwp.project.contract_drift",
approvedFingerprint: fingerprint,
observedFingerprint: fingerprint,
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
revision: 7,
});
mocks.capabilityUpdateMany.mockResolvedValueOnce({ count: 0 });
__setKwpResourceSharedStoreForTests(createSharedStore({ namespace: "kwp-resource-server-stale-recovery", adapter: new MemoryAdapter() }));
await expect(
revalidateAndRecoverKwpProjectSearch({
connectionId: "connection-1",
query: "Projekt",
})
).rejects.toMatchObject({ code: "capability_paused" });
expect(mocks.reportUpdateMany).not.toHaveBeenCalled();
expect(mocks.auditEvent).not.toHaveBeenCalled();
});
it("pauses only project import on 403 and persists a token-free diagnostic", async () => {
mocks.searchProjects.mockRejectedValueOnce(new KwpError("auth_scope_missing", 403));
__setKwpResourceSharedStoreForTests(createSharedStore({ namespace: "kwp-resource-server-403", adapter: new MemoryAdapter() }));
await expect(
searchProjects({
connectionId: "connection-1",
query: "Projekt",
})
).rejects.toMatchObject({ code: "auth_scope_missing", httpStatus: 403 });
expect(mocks.capabilityUpsert).toHaveBeenCalledWith(
expect.objectContaining({
where: {
tenantId_dataConnectionId_capability: {
tenantId: "tenant-1",
dataConnectionId: "connection-1",
capability: "project-import",
},
},
update: expect.objectContaining({
status: "paused",
reasonCode: "kwp.project.missing_provider_permission",
}),
})
);
const report = mocks.reportCreate.mock.calls[0]?.[0];
expect(report).toEqual({
data: expect.objectContaining({
tenantId: "tenant-1",
dataConnectionId: "connection-1",
capability: "project-import",
code: "kwp.project.missing_provider_permission",
redactedDetails: {
adapterRevision: expect.any(String),
httpClass: "forbidden",
},
}),
});
expect(JSON.stringify(report)).not.toContain(credentials.accessToken);
expect(JSON.stringify(report)).not.toContain(credentials.refreshToken);
});
it("gates and pauses only the exact scoped capability selected by an operation id", async () => {
mocks.executeReadOperation.mockRejectedValueOnce(new KwpError("auth_scope_missing", 403));
__setKwpResourceSharedStoreForTests(createSharedStore({ namespace: "kwp-resource-server-scoped-403", adapter: new MemoryAdapter() }));
await expect(
executeKwpReadOperation({
connectionId: "connection-1",
operationId: "archivExternalGetSetup",
})
).rejects.toMatchObject({ code: "auth_scope_missing", httpStatus: 403 });
expect(mocks.capabilityFindUnique).toHaveBeenCalledWith({
where: {
tenantId_dataConnectionId_capability: {
tenantId: "tenant-1",
dataConnectionId: "connection-1",
capability: "kwp-scoped-archive",
},
},
select: { status: true },
});
expect(mocks.capabilityUpsert).toHaveBeenCalledWith(
expect.objectContaining({
where: {
tenantId_dataConnectionId_capability: {
tenantId: "tenant-1",
dataConnectionId: "connection-1",
capability: "kwp-scoped-archive",
},
},
update: expect.objectContaining({
status: "paused",
reasonCode: "kwp.archive.missing_provider_permission",
}),
})
);
});
it("shares one OAuth-client budget across connections and waits for reset without provider retry loops", async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-08-01T12:00:00.000Z"));
__setKwpResourceSharedStoreForTests(createSharedStore({ namespace: "kwp-resource-server-budget", adapter: new MemoryAdapter() }));
mocks.connectionFindFirst.mockImplementation(async (args: { where: { id: string } }) => ({
id: args.where.id,
credentialsCiphertext: `encrypted-${args.where.id}`,
connectionStatus: "active",
tokenExpiresAt: new Date(credentials.expiresAt),
healthMessageKey: "integrations.kwp.health.active",
}));
mocks.decryptTenantField.mockImplementation(async (_tenantId: string, ciphertext: string) =>
JSON.stringify({
...credentials,
clientId: "shared-oauth-client",
customerCode: ciphertext.endsWith("connection-2") ? "customer-two" : "customer-one",
})
);
for (let request = 0; request < 50; request += 1) {
await expect(
searchProjects({
connectionId: request % 2 === 0 ? "connection-1" : "connection-2",
query: "Projekt",
})
).resolves.toEqual([]);
}
let settled = false;
const waitingRequest = searchProjects({
connectionId: "connection-2",
query: "Projekt",
}).then((result) => {
settled = true;
return result;
});
await vi.advanceTimersByTimeAsync(0);
expect(settled).toBe(false);
expect(mocks.searchProjects).toHaveBeenCalledTimes(50);
expect(mocks.loggerInfo).toHaveBeenCalledWith(
expect.objectContaining({ delayMs: 60_100, waitCycle: 1, budgetPerMinute: 50 }),
"integrations.kwp-resource-budget.waiting"
);
await vi.advanceTimersByTimeAsync(60_100);
await expect(waitingRequest).resolves.toEqual([]);
expect(mocks.searchProjects).toHaveBeenCalledTimes(51);
expect(mocks.capabilityUpsert).not.toHaveBeenCalled();
});
it("fails closed before provider I/O when the shared budget store is unavailable", async () => {
const adapter = new MemoryAdapter();
vi.spyOn(adapter, "eval").mockRejectedValueOnce(new Error("redis unavailable"));
__setKwpResourceSharedStoreForTests(createSharedStore({ namespace: "kwp-resource-server-budget-outage", adapter }));
await expect(
searchProjects({
connectionId: "connection-1",
query: "Projekt",
})
).rejects.toMatchObject({ code: "rate_limit_exceeded", httpStatus: 429 });
expect(mocks.searchProjects).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,621 @@
import { createHash } from "node:crypto";
import { resolveKwpRuntimeEnv, resolveSharedRedisUrl } from "@hivegrid/config";
import { getDbClient } from "@hivegrid/db/client.server";
import { decryptTenantField } from "@hivegrid/db/crypto/tenant-envelope.server";
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
import { auditEvent } from "@hivegrid/foundation";
import { createChildLogger, defaultLogger } from "@hivegrid/logger";
import {
createFixedWindowRateLimiter,
createSharedStore,
type FixedWindowDecision,
type FixedWindowRateLimiter,
type SharedStore,
} from "@hivegrid/shared-store";
import {
KWP_TOKEN_REFRESH_WINDOW_MS,
TOKEN_REFRESH_CLAIM_MESSAGE_KEY,
TOKEN_REFRESH_RETRY_MESSAGE_KEY,
claimExpiringTokenRefreshForConnection,
executeClaimedTokenRefresh,
persistClaimedTokenRefresh,
type TokenRefreshProviderResult,
} from "../worker-tasks.server.js";
import {
createKwpResourceTransport,
getKwpScopedCapabilityKey,
KWP_PROJECT_ADAPTER_REVISION,
KWP_PROJECT_CAPABILITY,
KWP_RESOURCE_BUDGET_PER_MINUTE,
type KwpAddressDetails,
type KwpProjectDetails,
type KwpProjectSearchResult,
type KwpSemanticContract,
} from "./resource-client.js";
import { getKwpScopedOperation, type KwpCapabilitySemanticContract, type KwpOperationInput, type KwpReadOperationId } from "./scoped-contract.js";
export { KWP_PROJECT_CAPABILITY } from "./resource-client.js";
import { KWP_APP_ID, KwpError, type KwpCredentials } from "./client.js";
type CredentialSnapshot = {
readonly tenantId: string;
readonly connectionId: string;
readonly credentials: KwpCredentials;
readonly connectionStatus: string;
readonly tokenExpiresAt: Date;
readonly healthMessageKey: string | null;
};
let sharedStore: SharedStore | null = null;
const kwpTokenLogger = createChildLogger(defaultLogger, { component: "integrations", scope: "kwp-token-demand" });
const kwpResourceBudgetLogger = createChildLogger(defaultLogger, { component: "integrations", scope: "kwp-resource-budget" });
const KWP_REFRESH_PERSIST_RETRY_DELAYS_MS = [250, 1_000, 5_000, 15_000, 30_000] as const;
const KWP_REFRESH_FOLLOWER_POLL_DELAYS_MS = [50, 100, 250, 500, 1_000, 2_000, 3_000, 5_000] as const;
const KWP_RESOURCE_BUDGET_WINDOW_SECONDS = 60;
const KWP_RESOURCE_BUDGET_RESET_PADDING_MS = 100;
export type KwpProjectCapabilityFailureCode = "auth_scope_missing" | "capability_paused" | "contract_drift";
/** Exposes only the stable, redacted capability state needed by route loaders.
* Provider payloads and credential material never cross this boundary. */
export function readKwpProjectCapabilityFailureCode(error: unknown): KwpProjectCapabilityFailureCode | null {
if (!(error instanceof KwpError)) return null;
if (error.code === "auth_scope_missing" || error.code === "capability_paused" || error.code === "contract_drift") {
return error.code;
}
return null;
}
export async function searchProjects(input: { readonly connectionId: string; readonly query: string }): Promise<KwpProjectSearchResult[]> {
return withKwpResource(input.connectionId, (resource) => resource.searchProjects(input.query));
}
export async function listProjectNumbers(input: { readonly connectionId: string }): Promise<string[]> {
return withKwpResource(input.connectionId, (resource) => resource.listProjectNumbers());
}
/** Reprobes a response-schema pause through the current adapter. Recovery is
* allowed only while OpenAPI still matches the approved fingerprint; genuine
* semantic drift and provider-permission failures remain paused. */
export async function revalidateAndRecoverKwpProjectSearch(input: {
readonly connectionId: string;
readonly query: string;
}): Promise<KwpProjectSearchResult[]> {
const connectionId = normalizeConnectionId(input.connectionId);
const tenantId = requireTenantId();
const results = await withKwpResource(connectionId, (resource) => resource.searchProjects(input.query), {
allowPaused: true,
capability: KWP_PROJECT_CAPABILITY,
});
const now = new Date();
const recovered = await getDbClient().$transaction(async (tx) => {
const state = await tx.kwpCapabilityState.findUnique({
where: {
tenantId_dataConnectionId_capability: {
tenantId,
dataConnectionId: connectionId,
capability: KWP_PROJECT_CAPABILITY,
},
},
});
if (state?.status === "active") return true;
if (
!state ||
state.reasonCode !== "kwp.project.contract_drift" ||
!state.approvedFingerprint ||
state.observedFingerprint !== state.approvedFingerprint ||
state.adapterRevision !== KWP_PROJECT_ADAPTER_REVISION
) {
return false;
}
const updated = await tx.kwpCapabilityState.updateMany({
where: {
id: state.id,
tenantId,
dataConnectionId: connectionId,
capability: KWP_PROJECT_CAPABILITY,
status: "paused",
reasonCode: "kwp.project.contract_drift",
approvedFingerprint: state.approvedFingerprint,
observedFingerprint: state.approvedFingerprint,
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
revision: state.revision,
},
data: {
status: "active",
reasonCode: null,
revision: { increment: 1 },
pausedAt: null,
lastCheckedAt: now,
},
});
if (updated.count !== 1) return false;
await tx.kwpErrorReport.updateMany({
where: {
tenantId,
dataConnectionId: connectionId,
capability: KWP_PROJECT_CAPABILITY,
code: "kwp.project.contract_drift",
resolvedAt: null,
},
data: { resolvedAt: now },
});
await auditEvent(
{
tenantId,
actorType: "system",
action: "KWP_RESPONSE_SCHEMA_RECOVERED",
targetType: "DataConnection",
targetId: connectionId,
metadata: {
capability: KWP_PROJECT_CAPABILITY,
approvedFingerprint: state.approvedFingerprint,
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
},
},
tx as never
);
return true;
});
if (!recovered) throw new KwpError("capability_paused");
return results;
}
/** One short credential-snapshot transaction followed by typed provider I/O.
* The callback never receives URL, token, mandant or raw credential material. */
export async function runKwpResourceSession<T>(
input: { readonly connectionId: string; readonly allowPaused?: boolean },
operation: (resource: ReturnType<typeof createKwpResourceTransport>) => Promise<T>
): Promise<T> {
return withKwpResource(input.connectionId, operation, {
allowPaused: input.allowPaused,
capability: KWP_PROJECT_CAPABILITY,
});
}
/** Exact operation-id boundary for the complete licensed read surface. Fachcode
* cannot provide a provider URL, path, token, mandant or mutation id. */
export async function executeKwpReadOperation<T = unknown>(input: {
readonly connectionId: string;
readonly operationId: KwpReadOperationId;
readonly operationInput?: KwpOperationInput;
}): Promise<T> {
const operation = getKwpScopedOperation(input.operationId);
return withKwpResource(input.connectionId, (resource) => resource.executeReadOperation<T>(input.operationId, input.operationInput), {
capability: getKwpScopedCapabilityKey(operation.capability),
});
}
export async function loadProjectDetails(input: { readonly connectionId: string; readonly projectNumber: string }): Promise<KwpProjectDetails> {
return withKwpResource(input.connectionId, (resource) => resource.loadProjectDetails(input.projectNumber));
}
export async function loadAddressDetails(input: { readonly connectionId: string; readonly addressCode: string }): Promise<KwpAddressDetails> {
return withKwpResource(input.connectionId, (resource) => resource.loadAddressDetails(input.addressCode));
}
export async function loadProjectSemanticContract(input: { readonly connectionId: string }): Promise<KwpSemanticContract> {
return withKwpResource(input.connectionId, (resource) => resource.loadSemanticContract(), { allowPaused: true });
}
export async function loadScopedSemanticContracts(input: { readonly connectionId: string }): Promise<readonly KwpCapabilitySemanticContract[]> {
return withKwpResource(input.connectionId, (resource) => resource.loadScopedSemanticContracts(), { allowPaused: true, capability: KWP_PROJECT_CAPABILITY });
}
/** Operator/tenant-admin approval proof: the current adapter must validate a
* real, explicitly selected read-only response while the capability is paused. */
export async function validateProjectAdapterAgainstCurrentContract(input: {
readonly connectionId: string;
readonly externalProjectNumber: string;
}): Promise<void> {
await withKwpResource(
input.connectionId,
async (resource) => {
const matches = await resource.searchProjects(input.externalProjectNumber);
const selected = matches.find((entry) => entry.externalProjectNumber === input.externalProjectNumber.trim());
if (!selected) throw new KwpError("resource_not_found", 404);
await resource.loadProjectDetails(selected.externalProjectNumber);
const addressCodes = [
...new Set([selected.projectAddressCode, selected.invoiceAddressCode, selected.clientAddressCode].filter((value): value is string => Boolean(value))),
];
for (const addressCode of addressCodes) await resource.loadAddressDetails(addressCode);
},
{ allowPaused: true }
);
}
async function withKwpResource<T>(
connectionId: string,
operation: (resource: ReturnType<typeof createKwpResourceTransport>) => Promise<T>,
options: { allowPaused?: boolean; capability?: string } = {}
): Promise<T> {
const capability = options.capability ?? KWP_PROJECT_CAPABILITY;
const snapshot = await ensureKwpCredentialSnapshot({
connectionId: normalizeConnectionId(connectionId),
capability,
...(options.allowPaused === undefined ? {} : { allowPaused: options.allowPaused }),
});
const resource = createKwpResourceTransport(snapshot.credentials, {
consumeBudget: () => consumeKwpResourceBudget(snapshot.credentials.clientId),
});
try {
return await operation(resource);
} catch (error) {
if (error instanceof KwpError && (error.code === "contract_drift" || error.code === "auth_scope_missing")) {
await pauseCapability(snapshot, capability, error.code);
}
throw error;
}
}
/**
* Demand-driven KWP access-token gate. Every real resource session and the
* scheduled health probe passes through this boundary. The durable claim in
* worker-tasks serializes web and worker replicas before KWP's one-time
* refresh token is consumed; followers wait for the persisted successor
* instead of starting a second rotation.
*/
export async function ensureKwpAccessTokenForConnection(input: {
readonly connectionId: string;
readonly allowPaused?: boolean;
readonly capability?: string;
}): Promise<void> {
await ensureKwpCredentialSnapshot(input);
}
async function ensureKwpCredentialSnapshot(input: {
readonly connectionId: string;
readonly allowPaused?: boolean;
readonly capability?: string;
}): Promise<CredentialSnapshot> {
const connectionId = normalizeConnectionId(input.connectionId);
const options = {
...(input.allowPaused === undefined ? {} : { allowPaused: input.allowPaused }),
...(input.capability === undefined ? {} : { capability: input.capability }),
};
const initial = await loadCredentialSnapshot(connectionId, options);
if (isKwpAccessTokenFresh(initial, new Date())) return initial;
const db = getDbClient();
const claimAt = new Date();
const { hiveGridTenantId } = resolveKwpRuntimeEnv();
const claimResult = await db.$transaction((tx) =>
claimExpiringTokenRefreshForConnection(
tx as unknown as Parameters<typeof claimExpiringTokenRefreshForConnection>[0],
initial.tenantId,
connectionId,
{
now: claimAt,
claimAt,
windowMs: KWP_TOKEN_REFRESH_WINDOW_MS,
// Preserve the process-wide Geerkens pilot boundary in addition to
// the caller's exact RLS tenant context and entitlement check.
...(hiveGridTenantId ? { kwpHiveGridTenantId: hiveGridTenantId } : {}),
},
),
);
if (claimResult.state === "failed") {
kwpTokenLogger.info(
{ tenantId: initial.tenantId, connectionId, reason: claimResult.reason },
"integrations.kwp-token-demand.claim-failed",
);
throw new KwpError("invalid_credentials");
}
if (claimResult.state === "claimed") {
const providerResult = await executeClaimedTokenRefresh(claimResult.claim);
if (!providerResult.ok) {
kwpTokenLogger.info(
{
tenantId: initial.tenantId,
connectionId,
reason: providerResult.reason,
disposition: providerResult.disposition,
httpStatus: providerResult.httpStatus ?? null,
diagnosticCode: providerResult.diagnosticCode ?? null,
},
"integrations.kwp-token-demand.provider-failed",
);
}
const persisted = await persistDemandRefreshWithRetry({
tenantId: initial.tenantId,
connectionId,
claim: claimResult.claim,
providerResult,
});
kwpTokenLogger.info(
{
tenantId: initial.tenantId,
connectionId,
outcome:
persisted.refreshed === 1
? "refreshed"
: persisted.retryScheduled === 1
? "retry_scheduled"
: persisted.failed === 1
? "reconnect_required"
: "already_resolved_or_raced",
...(providerResult.ok ? { tokenExpiresAt: providerResult.expiresAt.toISOString() } : {}),
},
"integrations.kwp-token-demand.connection-completed",
);
if (!providerResult.ok) {
throw new KwpError(
providerResult.reason === "unexpected" ? "unknown" : providerResult.reason,
providerResult.httpStatus,
providerResult.diagnosticCode,
);
}
}
return waitForDemandRefreshFollower(connectionId, options);
}
function isKwpAccessTokenFresh(snapshot: CredentialSnapshot, now: Date): boolean {
return (
snapshot.healthMessageKey !== TOKEN_REFRESH_CLAIM_MESSAGE_KEY &&
snapshot.healthMessageKey !== TOKEN_REFRESH_RETRY_MESSAGE_KEY &&
snapshot.tokenExpiresAt.getTime() > now.getTime() + KWP_TOKEN_REFRESH_WINDOW_MS
);
}
async function waitForDemandRefreshFollower(
connectionId: string,
options: { allowPaused?: boolean; capability?: string },
): Promise<CredentialSnapshot> {
for (const delayMs of KWP_REFRESH_FOLLOWER_POLL_DELAYS_MS) {
const snapshot = await loadCredentialSnapshot(connectionId, options);
if (isKwpAccessTokenFresh(snapshot, new Date())) return snapshot;
if (snapshot.healthMessageKey === TOKEN_REFRESH_RETRY_MESSAGE_KEY) {
throw new KwpError("provider_outage");
}
if (snapshot.healthMessageKey !== TOKEN_REFRESH_CLAIM_MESSAGE_KEY) {
throw new KwpError("invalid_credentials");
}
await wait(delayMs);
}
throw new KwpError("provider_outage");
}
async function persistDemandRefreshWithRetry(input: {
readonly tenantId: string;
readonly connectionId: string;
readonly claim: Parameters<typeof persistClaimedTokenRefresh>[1];
readonly providerResult: TokenRefreshProviderResult;
}): Promise<Awaited<ReturnType<typeof persistClaimedTokenRefresh>>> {
const db = getDbClient();
const maxAttempts = KWP_REFRESH_PERSIST_RETRY_DELAYS_MS.length + 1;
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
try {
return await db.$transaction((tx) =>
persistClaimedTokenRefresh(
tx as unknown as Parameters<typeof persistClaimedTokenRefresh>[0],
input.claim,
input.providerResult,
),
);
} catch (error) {
const delayMs = KWP_REFRESH_PERSIST_RETRY_DELAYS_MS[attempt - 1];
kwpTokenLogger.error(
{
tenantId: input.tenantId,
connectionId: input.connectionId,
stage: "persist",
attempt,
maxAttempts,
retryScheduled: delayMs !== undefined,
...classifyKwpRefreshPersistenceFailure(error),
...(delayMs === undefined ? {} : { delayMs }),
},
"integrations.kwp-token-demand.persistence-failed",
);
if (delayMs === undefined) {
throw new KwpError("invalid_credentials");
}
await wait(delayMs);
}
}
throw new KwpError("invalid_credentials");
}
function classifyKwpRefreshPersistenceFailure(error: unknown): {
failureClass: "database_known" | "database_unavailable" | "database_validation" | "timeout" | "unknown";
errorCode?: string;
} {
if (typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" && /^P\d{4}$/u.test(error.code)) {
return { failureClass: "database_known", errorCode: error.code };
}
const errorName = error instanceof Error ? error.name : null;
if (errorName === "PrismaClientInitializationError" || errorName === "PrismaClientRustPanicError") {
return { failureClass: "database_unavailable" };
}
if (errorName === "PrismaClientValidationError") return { failureClass: "database_validation" };
if (errorName === "AbortError" || errorName === "TimeoutError") return { failureClass: "timeout" };
return { failureClass: "unknown" };
}
function wait(delayMs: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, delayMs));
}
async function loadCredentialSnapshot(connectionId: string, options: { allowPaused?: boolean; capability?: string } = {}): Promise<CredentialSnapshot> {
const capabilityKey = options.capability ?? KWP_PROJECT_CAPABILITY;
const tenantId = requireTenantId();
const db = getDbClient();
return db.$transaction(async (tx) => {
const [connection, capability] = await Promise.all([
tx.dataConnection.findFirst({
where: {
id: connectionId,
tenantId,
appId: KWP_APP_ID,
archivedAt: null,
connectionStatus: { in: ["active", "degraded"] },
},
select: {
id: true,
credentialsCiphertext: true,
connectionStatus: true,
tokenExpiresAt: true,
healthMessageKey: true,
},
}),
tx.kwpCapabilityState.findUnique({
where: {
tenantId_dataConnectionId_capability: {
tenantId,
dataConnectionId: connectionId,
capability: capabilityKey,
},
},
select: { status: true },
}),
]);
if (!connection?.credentialsCiphertext || !connection.tokenExpiresAt) throw new KwpError("invalid_credentials");
if (!options.allowPaused && capability?.status === "paused") throw new KwpError("capability_paused");
let credentials: unknown;
try {
credentials = JSON.parse(await decryptTenantField(tenantId, connection.credentialsCiphertext, { client: tx as never }));
} catch {
throw new KwpError("invalid_credentials");
}
return {
tenantId,
connectionId: connection.id,
credentials: credentials as KwpCredentials,
connectionStatus: connection.connectionStatus,
tokenExpiresAt: connection.tokenExpiresAt,
healthMessageKey: connection.healthMessageKey,
};
});
}
function requireTenantId(): string {
const tenantId = getRlsExecutionContext()?.tenantId?.trim();
if (!tenantId) throw new KwpError("invalid_credentials");
return tenantId;
}
async function pauseCapability(snapshot: CredentialSnapshot, capability: string, failureCode: "contract_drift" | "auth_scope_missing"): Promise<void> {
const reasonPrefix = capability === KWP_PROJECT_CAPABILITY ? "kwp.project" : capability.replace("kwp-scoped-", "kwp.");
const reasonCode = failureCode === "auth_scope_missing" ? `${reasonPrefix}.missing_provider_permission` : `${reasonPrefix}.contract_drift`;
const now = new Date();
const db = getDbClient();
await db.$transaction(async (tx) => {
await tx.kwpCapabilityState.upsert({
where: {
tenantId_dataConnectionId_capability: {
tenantId: snapshot.tenantId,
dataConnectionId: snapshot.connectionId,
capability,
},
},
create: {
tenantId: snapshot.tenantId,
dataConnectionId: snapshot.connectionId,
capability,
status: "paused",
reasonCode,
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
revision: 1,
pausedAt: now,
lastCheckedAt: now,
},
update: {
status: "paused",
reasonCode,
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
revision: { increment: 1 },
pausedAt: now,
lastCheckedAt: now,
},
});
await tx.kwpErrorReport.create({
data: {
tenantId: snapshot.tenantId,
dataConnectionId: snapshot.connectionId,
capability: KWP_PROJECT_CAPABILITY,
code: reasonCode,
redactedDetails: {
adapterRevision: KWP_PROJECT_ADAPTER_REVISION,
httpClass: failureCode === "auth_scope_missing" ? "forbidden" : "schema",
},
},
});
});
}
async function consumeKwpResourceBudget(clientId: string): Promise<void> {
const key = createHash("sha256").update(clientId.trim()).digest("hex");
let limiter: FixedWindowRateLimiter;
try {
limiter = createFixedWindowRateLimiter({
store: getKwpResourceStore(),
prefix: "oauth-client-v2",
windowSeconds: KWP_RESOURCE_BUDGET_WINDOW_SECONDS,
max: KWP_RESOURCE_BUDGET_PER_MINUTE,
});
} catch {
throw new KwpError("rate_limit_exceeded", 429);
}
let waitCycle = 0;
while (true) {
let decision: FixedWindowDecision;
try {
decision = await limiter.consume(key);
} catch {
// A shared-budget outage must fail closed; a replica-local fallback
// could breach KWP's provider-wide hard cap.
throw new KwpError("rate_limit_exceeded", 429);
}
if (decision.allowed) return;
waitCycle += 1;
const untilResetMs = decision.resetAt.getTime() - Date.now();
const delayMs = Math.min(
KWP_RESOURCE_BUDGET_WINDOW_SECONDS * 1_000 + KWP_RESOURCE_BUDGET_RESET_PADDING_MS,
Math.max(KWP_RESOURCE_BUDGET_RESET_PADDING_MS, untilResetMs + KWP_RESOURCE_BUDGET_RESET_PADDING_MS)
);
kwpResourceBudgetLogger.info(
{
delayMs,
waitCycle,
budgetPerMinute: KWP_RESOURCE_BUDGET_PER_MINUTE,
},
"integrations.kwp-resource-budget.waiting"
);
await wait(delayMs);
}
}
function getKwpResourceStore(): SharedStore {
sharedStore ??= createSharedStore({
namespace: "kwp-resource-budget",
redisUrl: resolveSharedRedisUrl(),
});
return sharedStore;
}
function normalizeConnectionId(value: string): string {
const normalized = value.trim();
if (!/^[A-Za-z0-9_-]{8,191}$/u.test(normalized)) throw new KwpError("invalid_credentials");
return normalized;
}
export function __setKwpResourceSharedStoreForTests(store: SharedStore): void {
sharedStore = store;
}
export function __resetKwpResourceSharedStoreForTests(): void {
sharedStore = null;
}
export type { KwpAddressDetails, KwpProjectDetails, KwpProjectSearchResult, KwpSemanticContract } from "./resource-client.js";
export type { KwpCapabilitySemanticContract, KwpOperationInput, KwpReadOperationId } from "./scoped-contract.js";
@@ -0,0 +1,662 @@
import { describe, expect, it, vi } from "vitest";
import {
assertKwpReadOperationAllowed,
buildKwpSemanticContract,
createKwpResourceTransport,
KWP_ADDRESS_DETAILS_PATH,
KWP_PROJECT_CATALOG_PATH,
KWP_PROJECT_DETAILS_PATH,
KWP_PROJECT_SEARCH_PATH,
} from "./resource-client.js";
import { KWP_OIDC_ISSUER, KWP_REQUIRED_OAUTH_SCOPES, type KwpCredentials, type KwpOutboundRequestOptions } from "./client.js";
import { KWP_SCOPED_OPERATIONS } from "./scoped-contract.js";
const CREDENTIALS: KwpCredentials = {
accessToken: "access-secret",
refreshToken: "refresh-secret",
expiresAt: "2026-07-23T12:00:00.000Z",
issuer: KWP_OIDC_ISSUER,
clientId: "_extern-geerkens2",
clientSecret: "client-secret",
customerCode: "geerkens2",
scopes: [...KWP_REQUIRED_OAUTH_SCOPES],
mandantBinding: { kind: "selected", code: "mandant1" },
};
const PUBLIC_ADDRESS_RESOLVER = async (): Promise<readonly string[]> => ["93.184.216.34"];
describe("KWP project resource transport", () => {
it("executes only targeted search and normalizes the consumed fields", async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de"))
.mockResolvedValueOnce(
jsonResponse([
{
projNr: " P-100 ",
projBezeichnung: " Heizung Schule ",
projAdr: "ADR-1",
rechAdr: "ADR-2",
bauHrAdr: "ADR-3",
auftragStatus: 8,
},
])
);
const consumeBudget = vi.fn().mockResolvedValue(undefined);
const resource = createKwpResourceTransport(CREDENTIALS, {
consumeBudget,
outboundOptions: outboundOptions(fetchMock),
});
await expect(resource.searchProjects(" Schule ")).resolves.toEqual([
{
externalProjectNumber: "P-100",
name: "Heizung Schule",
projectAddressCode: "ADR-1",
invoiceAddressCode: "ADR-2",
clientAddressCode: "ADR-3",
status: 8,
statusLabel: "Erhalten",
},
]);
expect(consumeBudget).toHaveBeenCalledTimes(2);
const [url, init] = fetchMock.mock.calls[1] as [string, RequestInit];
expect(new URL(url).pathname).toBe(`/relay/geerkens2/pwa${KWP_PROJECT_SEARCH_PATH}`);
expect(new URL(url).searchParams.get("mandant")).toBe("mandant1");
expect(init.method).toBe("POST");
expect(JSON.parse(String(init.body))).toEqual({ value: "Schule" });
});
it("skips search rows without the optional routing status while keeping routable results available", async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de"))
.mockResolvedValueOnce(
jsonResponse([
{
projNr: "P-NO-STATUS",
projBezeichnung: "Noch nicht routbar",
},
{
projNr: "P-ROUTABLE",
projBezeichnung: "Routbares Projekt",
auftragStatus: 7,
},
])
);
const resource = createKwpResourceTransport(CREDENTIALS, {
consumeBudget: async () => undefined,
outboundOptions: outboundOptions(fetchMock),
});
await expect(resource.searchProjects("Projekt")).resolves.toEqual([
{
externalProjectNumber: "P-ROUTABLE",
name: "Routbares Projekt",
projectAddressCode: null,
invoiceAddressCode: null,
clientAddressCode: null,
status: 7,
statusLabel: "Zugesagt",
},
]);
});
it("discovers the setting-visible project catalog without an empty search", async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de"))
.mockResolvedValueOnce(
jsonResponse([
{ projNr: " P-100 ", anzahlAktivitaeten: 3 },
{ projNr: "P-200", anzahlAktivitaeten: 0 },
{ projNr: "P-100", anzahlAktivitaeten: 4 },
{ projNr: null, anzahlAktivitaeten: 0 },
])
);
const resource = createKwpResourceTransport(CREDENTIALS, {
consumeBudget: async () => undefined,
outboundOptions: outboundOptions(fetchMock),
});
await expect(resource.listProjectNumbers()).resolves.toEqual(["P-100", "P-200"]);
const [url, init] = fetchMock.mock.calls[1] as [string, RequestInit];
expect(new URL(url).pathname).toBe(`/relay/geerkens2/pwa${KWP_PROJECT_CATALOG_PATH}`);
expect(new URL(url).searchParams.get("mandant")).toBe("mandant1");
expect(init.method).toBe("GET");
expect(init.body).toBeUndefined();
});
it("still rejects a present search status outside the consumed KWP enum", async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de"))
.mockResolvedValueOnce(
jsonResponse([
{
projNr: "P-INVALID-STATUS",
projBezeichnung: "Ungültiger Status",
auftragStatus: 10,
},
])
);
const resource = createKwpResourceTransport(CREDENTIALS, {
consumeBudget: async () => undefined,
outboundOptions: outboundOptions(fetchMock),
});
await expect(resource.searchProjects("Projekt")).rejects.toMatchObject({
code: "contract_drift",
});
});
it("accepts omitted optional fields from live project and address responses", async () => {
const detailsFetch = vi
.fn()
.mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de"))
.mockResolvedValueOnce(
jsonResponse({
projNr: "P-100",
projBezeichnung: "Heizung Schule",
adresse: {
adrNrGes: "ADR-1",
name: "Schule",
zusatz: "Altbau",
strasse: "Dorfstraße 1",
ort: { ortId: 1, plz: "12345", ort: "Berlin" },
},
auftragssumme: 42_500,
})
);
const detailsResource = createKwpResourceTransport(CREDENTIALS, {
consumeBudget: async () => undefined,
outboundOptions: outboundOptions(detailsFetch),
});
await expect(detailsResource.loadProjectDetails("P-100")).resolves.toEqual({
externalProjectNumber: "P-100",
name: "Heizung Schule",
startDate: null,
orderValue: 42_500,
addressCode: "ADR-1",
addressName: "Schule",
});
const addressFetch = vi
.fn()
.mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de"))
.mockResolvedValueOnce(
jsonResponse({
adrNrGes: "ADR-1",
name: "Schule",
zusatz: "Altbau",
strasse: "Dorfstraße 1",
ort: { ortId: 1, plz: "12345", ort: "Berlin" },
// Real KWP tenants return null for these documented object fields.
// They are not consumed by project import and must not create a
// capability-wide false-positive contract pause.
ortPstf: null,
briefanrede: null,
selekt1: null,
selekt2: null,
bank: null,
kontakte: [
{
kontaktId: 1,
kontaktart: 2,
kontakt: "info@example.test",
kontaktartTyp: 0,
kontaktName: "E-Mail",
ansprechpartnerId: null,
},
],
ansprechpartner: [],
})
);
const addressResource = createKwpResourceTransport(CREDENTIALS, {
consumeBudget: async () => undefined,
outboundOptions: outboundOptions(addressFetch),
});
await expect(addressResource.loadAddressDetails("ADR-1")).resolves.toMatchObject({
externalAddressCode: "ADR-1",
firstName: null,
country: null,
invoiceEmail: null,
email: "info@example.test",
contactPeople: [],
});
});
it("still rejects an invalid consumed address field while ignoring unconsumed nullable drift", async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de"))
.mockResolvedValueOnce(
jsonResponse({
adrNrGes: "ADR-1",
name: "Schule",
ortPstf: null,
briefanrede: null,
selekt1: null,
selekt2: null,
bank: null,
kontakte: [{ kontaktart: 99, kontakt: "invalid@example.test", ansprechpartnerId: null }],
})
);
const resource = createKwpResourceTransport(CREDENTIALS, {
consumeBudget: async () => undefined,
outboundOptions: outboundOptions(fetchMock),
});
await expect(resource.loadAddressDetails("ADR-1")).rejects.toMatchObject({
code: "contract_drift",
});
});
it("rejects empty or one-character search without provider I/O", async () => {
const fetchMock = vi.fn();
const consumeBudget = vi.fn();
const resource = createKwpResourceTransport(CREDENTIALS, {
consumeBudget,
outboundOptions: outboundOptions(fetchMock),
});
await expect(resource.searchProjects(" ")).rejects.toMatchObject({ code: "invalid_credentials" });
await expect(resource.searchProjects("x")).rejects.toMatchObject({ code: "invalid_credentials" });
expect(consumeBudget).not.toHaveBeenCalled();
expect(fetchMock).not.toHaveBeenCalled();
});
it("loads project details by GET and detects a renamed consumed field", async () => {
const validFetch = vi
.fn()
.mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de"))
.mockResolvedValueOnce(
jsonResponse({
projNr: "P-100",
projBezeichnung: "Heizung Schule",
beginn: "2026-07-01T00:00:00+02:00",
adresse: {
adrNrGes: "ADR-1",
name: "Schule",
vorname: null,
zusatz: null,
strasse: "Dorfstraße 1",
ort: { ortId: 1, land: "DE", plz: "12345", ort: "Berlin" },
debitKreditNr: 987654,
},
sachBearb: null,
vertrieb: null,
auftragssumme: 42_500,
})
);
const validResource = createKwpResourceTransport(CREDENTIALS, {
consumeBudget: async () => undefined,
outboundOptions: outboundOptions(validFetch),
});
await expect(validResource.loadProjectDetails("P-100")).resolves.toEqual({
externalProjectNumber: "P-100",
name: "Heizung Schule",
startDate: "2026-06-30T22:00:00.000Z",
orderValue: 42_500,
addressCode: "ADR-1",
addressName: "Schule",
});
const [url, init] = validFetch.mock.calls[1] as [string, RequestInit];
expect(new URL(url).pathname).toBe(`/relay/geerkens2/pwa${KWP_PROJECT_DETAILS_PATH}`);
expect(new URL(url).searchParams.get("projNr")).toBe("P-100");
expect(init.method).toBe("GET");
expect(init.body).toBeUndefined();
const driftFetch = vi
.fn()
.mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de"))
.mockResolvedValueOnce(
jsonResponse({
projektNummer: "P-100",
projBezeichnung: "Heizung Schule",
beginn: null,
adresse: { adrNrGes: null, name: null, vorname: null, zusatz: null, strasse: null, ort: { ortId: 1, land: null, plz: null, ort: null } },
sachBearb: null,
vertrieb: null,
auftragssumme: null,
})
);
const driftResource = createKwpResourceTransport(CREDENTIALS, {
consumeBudget: async () => undefined,
outboundOptions: outboundOptions(driftFetch),
});
await expect(driftResource.loadProjectDetails("P-100")).rejects.toMatchObject({ code: "contract_drift" });
});
it("discards prohibited financial, tax, birthday, note and user fields", async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de"))
.mockResolvedValueOnce(
jsonResponse({
adrNrGes: "ADR-1",
name: "Geerkens GmbH",
vorname: null,
zusatz: "Niederlassung",
strasse: "Werkstraße 7",
ort: { ortId: 1, land: "DE", plz: "52511", ort: "Geilenkirchen" },
rechnungsmailadresse: "rechnung@example.test",
kontakte: [
{ kontaktId: 1, kontaktart: 2, kontakt: "info@example.test", kontaktName: "E-Mail", bemerkung: "secret", ansprechpartnerId: null },
{ kontaktId: 2, kontaktart: 0, kontakt: "+49 123", kontaktName: "Telefon", bemerkung: null, ansprechpartnerId: null },
],
ansprechpartner: [
{
nachname: "Muster",
vorname: "Maria",
ansprechpartnerId: 99,
zusatz: null,
geburtstag: "1980-01-01T00:00:00Z",
benutzerFeld1: "never-store",
bemerkung: "internal",
kontakte: [{ kontaktId: 3, kontaktart: 2, kontakt: "maria@example.test", kontaktName: "E-Mail", bemerkung: null, ansprechpartnerId: 99 }],
},
],
iban: "DE001234",
bank: { bezeichnung: "Secret Bank" },
kreditLimit: 100_000,
ustId: "DE123",
hinweis: "internal",
benutzerFeld1: "never-store",
})
);
const resource = createKwpResourceTransport(CREDENTIALS, {
consumeBudget: async () => undefined,
outboundOptions: outboundOptions(fetchMock),
});
const address = await resource.loadAddressDetails("ADR-1");
expect(address).toMatchObject({
externalAddressCode: "ADR-1",
name: "Geerkens GmbH",
invoiceEmail: "rechnung@example.test",
email: "info@example.test",
phone: "+49 123",
contactPeople: [
{
externalContactId: "99",
firstName: "Maria",
lastName: "Muster",
email: "maria@example.test",
},
],
});
const persisted = JSON.stringify(address).toLowerCase();
for (const prohibited of [
'"iban"',
'"bank"',
'"kreditlimit"',
'"ustid"',
'"geburtstag"',
'"hinweis"',
'"benutzerfeld1"',
'"bemerkung"',
"de001234",
"never-store",
]) {
expect(persisted).not.toContain(prohibited.toLowerCase());
}
expect(new URL(String(fetchMock.mock.calls[1]?.[0])).pathname).toBe(`/relay/geerkens2/pwa${KWP_ADDRESS_DETAILS_PATH}`);
});
it("blocks every KWP write or non-allowlisted read before transport", () => {
for (const operation of KWP_SCOPED_OPERATIONS) {
const assertion = () => assertKwpReadOperationAllowed(operation.method, operation.path);
if (operation.mode === "read") expect(assertion).not.toThrow();
else expect(assertion).toThrow();
}
expect(() => assertKwpReadOperationAllowed("GET", "/api/Core/GetApiVersion")).toThrow();
expect(() => assertKwpReadOperationAllowed("GET", KWP_PROJECT_DETAILS_PATH)).not.toThrow();
});
it("executes exact generic GET and read-POST operation ids without exposing a free path", async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de"))
.mockResolvedValueOnce(jsonResponse({}))
.mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de"))
.mockResolvedValueOnce(jsonResponse([]));
const resource = createKwpResourceTransport(CREDENTIALS, {
consumeBudget: async () => undefined,
outboundOptions: outboundOptions(fetchMock),
});
await expect(resource.executeReadOperation("monteursteuerungGetSetup")).resolves.toEqual({});
await expect(resource.executeReadOperation("vorgangAnzeigeLoadPositionen", { body: {} })).resolves.toEqual([]);
const getUrl = new URL(String(fetchMock.mock.calls[1]?.[0]));
expect(getUrl.pathname).toBe("/relay/geerkens2/pwa/api/Monteursteuerung/GetSetup");
expect(getUrl.searchParams.get("mandant")).toBe("mandant1");
expect((fetchMock.mock.calls[1]?.[1] as RequestInit).method).toBe("GET");
const postUrl = new URL(String(fetchMock.mock.calls[3]?.[0]));
expect(postUrl.pathname).toBe("/relay/geerkens2/pwa/api/VorgangAnzeige/LoadPositionen");
expect(postUrl.searchParams.get("mandant")).toBe("mandant1");
expect((fetchMock.mock.calls[3]?.[1] as RequestInit).method).toBe("POST");
expect(JSON.parse(String((fetchMock.mock.calls[3]?.[1] as RequestInit).body))).toEqual({});
});
it("fails closed for an unconfirmed mandant and classifies 403 without exposing the provider body", async () => {
const { mandantBinding: _binding, ...unconfirmed } = CREDENTIALS;
expect(() =>
createKwpResourceTransport(unconfirmed, {
consumeBudget: async () => undefined,
})
).toThrowError(expect.objectContaining({ code: "mandant_unconfirmed" }));
const fetchMock = vi
.fn()
.mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de"))
.mockResolvedValueOnce(jsonResponse({ token: CREDENTIALS.accessToken }, 403));
const resource = createKwpResourceTransport(CREDENTIALS, {
consumeBudget: async () => undefined,
outboundOptions: outboundOptions(fetchMock),
});
const error = await resource.searchProjects("Projekt").catch((caught: unknown) => caught);
expect(error).toMatchObject({ code: "auth_scope_missing", httpStatus: 403 });
expect(JSON.stringify(error)).not.toContain(CREDENTIALS.accessToken);
});
it.each([
[401, "auth_token_invalid"],
[429, "rate_limit_exceeded"],
[503, "provider_outage"],
])("classifies HTTP %i without hidden refresh or request retry", async (status, code) => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de"))
.mockResolvedValueOnce(jsonResponse({ token: CREDENTIALS.accessToken }, status));
const resource = createKwpResourceTransport(CREDENTIALS, {
consumeBudget: async () => undefined,
outboundOptions: outboundOptions(fetchMock),
});
await expect(resource.searchProjects("Projekt")).rejects.toMatchObject({
code,
httpStatus: status,
});
expect(fetchMock).toHaveBeenCalledTimes(2);
expect(JSON.stringify(fetchMock.mock.results)).not.toContain(CREDENTIALS.refreshToken);
});
it("fingerprints only the consumed semantic OpenAPI slice", () => {
const base = openApiFixture();
const first = buildKwpSemanticContract(base);
const unrelated = structuredClone(base);
unrelated.paths["/api/Unrelated/Save"] = { post: { responses: { 200: {} } } };
unrelated.components.schemas.Unrelated = { type: "object", properties: { value: { type: "string" } } };
expect(buildKwpSemanticContract(unrelated).semanticFingerprint).toBe(first.semanticFingerprint);
const architectOnly = structuredClone(base);
architectOnly.components.schemas["Kwp.Api.Service.Dto.Projekte.DtoSearchResultProjekt"].properties.archAdr = {
type: "integer",
};
expect(buildKwpSemanticContract(architectOnly).semanticFingerprint).toBe(first.semanticFingerprint);
const changed = structuredClone(base);
changed.components.schemas["Kwp.Api.Model.Values.ProjektHauptstatus"].enum.push(10);
expect(buildKwpSemanticContract(changed).semanticFingerprint).not.toBe(first.semanticFingerprint);
const renamed = structuredClone(base);
delete renamed.components.schemas["Kwp.Api.Service.Dto.Projekte.DtoSearchResultProjekt"].properties.projNr;
expect(() => buildKwpSemanticContract(renamed)).toThrowError(expect.objectContaining({ code: "contract_drift" }));
});
it("accepts the larger tenant OpenAPI while keeping business responses capped at one MiB", async () => {
const openApi = openApiFixture();
openApi.paths["/api/Unrelated/Large"] = {
get: {
description: "x".repeat(2 * 1024 * 1024),
responses: { 200: {} },
},
};
const openApiFetch = vi.fn().mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de")).mockResolvedValueOnce(jsonResponse(openApi));
const openApiResource = createKwpResourceTransport(CREDENTIALS, {
consumeBudget: async () => undefined,
outboundOptions: outboundOptions(openApiFetch),
});
await expect(openApiResource.loadSemanticContract()).resolves.toMatchObject({
apiVersion: "v1",
});
const oversizedBusinessResponse = [
{
projNr: "P-100",
projBezeichnung: "Heizung Schule",
auftragStatus: 8,
ignored: "x".repeat(1024 * 1024),
},
];
const searchFetch = vi
.fn()
.mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de"))
.mockResolvedValueOnce(jsonResponse(oversizedBusinessResponse));
const searchResource = createKwpResourceTransport(CREDENTIALS, {
consumeBudget: async () => undefined,
outboundOptions: outboundOptions(searchFetch),
});
await expect(searchResource.searchProjects("Projekt")).rejects.toMatchObject({
code: "contract_drift",
});
});
it("rejects an OpenAPI response above the dedicated eight MiB ceiling", async () => {
const openApi = openApiFixture();
openApi.paths["/api/Unrelated/Oversized"] = {
get: {
description: "x".repeat(8 * 1024 * 1024),
responses: { 200: {} },
},
};
const fetchMock = vi.fn().mockResolvedValueOnce(new Response("https://geerkens2.app04.kwp-online.de")).mockResolvedValueOnce(jsonResponse(openApi));
const resource = createKwpResourceTransport(CREDENTIALS, {
consumeBudget: async () => undefined,
outboundOptions: outboundOptions(fetchMock),
});
await expect(resource.loadSemanticContract()).rejects.toMatchObject({
code: "contract_drift",
});
});
});
function outboundOptions(fetchImpl: typeof fetch): KwpOutboundRequestOptions {
return { fetchImpl, addressResolver: PUBLIC_ADDRESS_RESOLVER };
}
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
}
function openApiFixture(): {
info: { version: string };
paths: Record<string, any>;
components: { schemas: Record<string, any> };
} {
const response = (schema: string) => ({
"200": { content: { "application/json": { schema: { $ref: `#/components/schemas/${schema}` } } } },
});
const property = (type: string) => ({ type, nullable: true });
return {
info: { version: "v1" },
paths: {
[KWP_PROJECT_SEARCH_PATH]: {
post: {
parameters: [{ name: "mandant", in: "query", schema: { type: "string" } }],
requestBody: { content: { "application/json": { schema: { $ref: "#/components/schemas/Kwp.Api.Service.Dto.DtoValue" } } } },
responses: response("Kwp.Api.Service.Dto.Projekte.DtoSearchResultProjekt"),
},
},
[KWP_PROJECT_DETAILS_PATH]: {
get: {
parameters: [{ name: "projNr", in: "query", schema: { type: "string" } }],
responses: response("Kwp.Api.Service.Dto.Projektampel.DtoProjektampelProjekt"),
},
},
[KWP_ADDRESS_DETAILS_PATH]: {
get: {
parameters: [{ name: "adresskuerzel", in: "query", schema: { type: "string" } }],
responses: response("Kwp.Api.Service.Dto.Adressen.DtoAdresseKomplett"),
},
},
},
components: {
schemas: {
"Kwp.Api.Service.Dto.DtoValue": { type: "object", properties: { value: property("string") } },
"Kwp.Api.Service.Dto.Projekte.DtoSearchResultProjekt": {
type: "object",
properties: Object.fromEntries(
["projNr", "projBezeichnung", "projAdr", "rechAdr", "archAdr", "bauHrAdr", "auftragStatus"].map((name) => [
name,
property(name === "auftragStatus" ? "integer" : "string"),
])
),
},
"Kwp.Api.Model.Values.ProjektHauptstatus": { type: "integer", format: "int32", enum: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] },
"Kwp.Api.Service.Dto.Projektampel.DtoProjektampelProjekt": {
type: "object",
properties: Object.fromEntries(
["projNr", "projBezeichnung", "beginn", "adresse", "sachBearb", "vertrieb", "auftragssumme"].map((name) => [name, property("string")])
),
},
"Kwp.Api.Service.Dto.Adressen.DtoAdresse": {
type: "object",
properties: Object.fromEntries(["adrNrGes", "name", "vorname", "zusatz", "strasse", "ort"].map((name) => [name, property("string")])),
},
"Kwp.Api.Service.Dto.Adressen.DtoAdresseKomplett": {
type: "object",
properties: Object.fromEntries(
["adrNrGes", "name", "vorname", "zusatz", "strasse", "ort", "rechnungsmailadresse", "kontakte", "ansprechpartner"].map((name) => [
name,
property("string"),
])
),
},
"Kwp.Api.Service.Dto.Adressen.DtoOrt": {
type: "object",
properties: Object.fromEntries(["ortId", "land", "plz", "ort"].map((name) => [name, property("string")])),
},
"Kwp.Api.Service.Dto.Adressen.DtoKontakt": {
type: "object",
properties: Object.fromEntries(["kontaktId", "kontaktart", "kontakt", "kontaktName", "ansprechpartnerId"].map((name) => [name, property("string")])),
},
"Kwp.Api.Service.Dto.Adressen.DtoAnsprechpartner": {
type: "object",
properties: Object.fromEntries(["nachname", "vorname", "ansprechpartnerId", "zusatz", "kontakte"].map((name) => [name, property("string")])),
},
"Kwp.Api.Model.Values.Adresse.Kontaktart": { type: "integer", format: "int32", enum: [0, 1, 2, 3, 4, 5] },
},
},
};
}
@@ -0,0 +1,598 @@
import { createHash } from "node:crypto";
import { fetchOutboundHttpWithRedirects, OutboundHttpUrlValidationError, readLimitedResponseText } from "@hivegrid/foundation/outbound-http";
import { z } from "zod";
import {
assertKwpResourceCredentials,
KwpError,
resolveKwpRelayBaseUrl,
validateKwpOnlineUrl,
type KwpCredentials,
type KwpOutboundRequestOptions,
} from "./client.js";
import {
assertKwpReadOperationId,
buildKwpCapabilitySemanticContract,
getKwpScopedOperation,
KWP_SCOPED_OPERATIONS,
listKwpCapabilities,
parseKwpOperationResponse,
validateKwpOperationInput,
type KwpCapability,
type KwpCapabilitySemanticContract,
type KwpOperationInput,
type KwpReadOperationId,
} from "./scoped-contract.js";
export const KWP_PROJECT_CAPABILITY = "project-import";
export const KWP_PROJECT_ADAPTER_REVISION = "kwp-project-v5";
export const KWP_PROJECT_SEARCH_PATH = "/api/Projekt/Search";
export const KWP_PROJECT_DETAILS_PATH = "/api/Projektampel/LoadProjektDetails";
export const KWP_PROJECT_CATALOG_PATH = "/api/Projektampel/LoadProjekteNachFilter";
export const KWP_ADDRESS_DETAILS_PATH = "/api/Adresse/LoadAdressKomplett";
export const KWP_OPENAPI_PATH = "/swagger/v1/swagger.json";
export const KWP_RESOURCE_BUDGET_PER_MINUTE = 50;
export const KWP_SCOPED_CAPABILITY_KEYS: Readonly<Record<KwpCapability, string>> = Object.freeze({
activity: "kwp-scoped-activity",
address: "kwp-scoped-address",
archive: "kwp-scoped-archive",
project: "kwp-scoped-project",
schedule: "kwp-scoped-schedule",
});
const KWP_RESOURCE_RESPONSE_LIMIT_BYTES = 1024 * 1024;
const KWP_PROJECT_CATALOG_RESPONSE_LIMIT_BYTES = 16 * 1024 * 1024;
const KWP_OPENAPI_RESPONSE_LIMIT_BYTES = 8 * 1024 * 1024;
const KWP_PROJECT_SEARCH_MAX_ENTRIES = 500;
const KWP_PROJECT_CATALOG_MAX_ENTRIES = 100_000;
const KWP_QUERY_MAX_LENGTH = 191;
const KWP_EXTERNAL_ID_MAX_LENGTH = 191;
const nullableString = z.string().max(2_048).nullable();
const optionalNullableString = nullableString.optional().default(null);
const int32 = z.number().int().min(-2_147_483_648).max(2_147_483_647);
const int64Safe = z.number().int().safe();
const kwpStatusSchema = z.number().int().min(0).max(9);
const rawOrtSchema = z
.object({
ortId: int32.optional().default(0),
land: optionalNullableString,
plz: optionalNullableString,
ort: optionalNullableString,
})
.strip();
const rawAddressSummarySchema = z
.object({
adrNrGes: optionalNullableString,
name: optionalNullableString,
vorname: optionalNullableString,
zusatz: optionalNullableString,
strasse: optionalNullableString,
ort: rawOrtSchema.optional().default({}),
})
.strip();
const rawContactChannelSchema = z
.object({
kontaktart: z.number().int().min(0).max(5),
kontakt: optionalNullableString,
ansprechpartnerId: int64Safe.nullable().optional().default(null),
})
.strip();
const rawContactPersonSchema = z
.object({
nachname: optionalNullableString,
vorname: optionalNullableString,
ansprechpartnerId: int64Safe,
zusatz: optionalNullableString,
kontakte: z.array(rawContactChannelSchema).max(100).nullable().optional().default(null),
})
.strip();
const rawProjectSearchResultSchema = z
.object({
projNr: optionalNullableString,
projBezeichnung: optionalNullableString,
projAdr: optionalNullableString,
rechAdr: optionalNullableString,
bauHrAdr: optionalNullableString,
auftragStatus: kwpStatusSchema.optional(),
})
.strip();
const rawProjectDetailsSchema = z
.object({
projNr: optionalNullableString,
projBezeichnung: optionalNullableString,
beginn: z.string().datetime({ offset: true }).nullable().optional().default(null),
adresse: rawAddressSummarySchema.optional().default({}),
auftragssumme: z.number().finite().nullable().optional().default(null),
})
.strip();
const rawProjectCatalogEntrySchema = z
.object({
projNr: optionalNullableString,
anzahlAktivitaeten: int32.optional().default(0),
})
.strip();
const rawAddressDetailsSchema = z
.object({
adrNrGes: optionalNullableString,
name: optionalNullableString,
vorname: optionalNullableString,
zusatz: optionalNullableString,
strasse: optionalNullableString,
ort: rawOrtSchema.optional().default({}),
rechnungsmailadresse: optionalNullableString,
kontakte: z.array(rawContactChannelSchema).max(100).nullable().optional().default(null),
ansprechpartner: z.array(rawContactPersonSchema).max(100).nullable().optional().default(null),
})
.strip();
const openApiSchema = z
.object({
info: z.object({ version: z.string().min(1).max(64) }).passthrough(),
paths: z.record(z.unknown()),
components: z.object({ schemas: z.record(z.unknown()) }).passthrough(),
})
.passthrough();
export const KWP_PROJECT_STATUS_LABELS = Object.freeze({
0: "Noch nicht vergeben",
1: "Nicht erhalten",
2: "Neu ausgeschrieben",
3: "Ersatzangebot",
4: "Zurückgestellt",
5: "Nicht erhalten: zu teuer",
6: "Nicht erhalten: sonstige Gründe",
7: "Zugesagt",
8: "Erhalten",
9: "Abgeschlossen",
} as const);
export type KwpProjectStatus = keyof typeof KWP_PROJECT_STATUS_LABELS;
export type KwpProjectSearchResult = {
readonly externalProjectNumber: string;
readonly name: string;
readonly projectAddressCode: string | null;
readonly invoiceAddressCode: string | null;
readonly clientAddressCode: string | null;
readonly status: KwpProjectStatus;
readonly statusLabel: string;
};
export type KwpProjectDetails = {
readonly externalProjectNumber: string;
readonly name: string;
readonly startDate: string | null;
readonly orderValue: number | null;
readonly addressCode: string | null;
readonly addressName: string | null;
};
export type KwpAddressContactPerson = {
readonly externalContactId: string;
readonly firstName: string | null;
readonly lastName: string | null;
readonly addition: string | null;
readonly email: string | null;
readonly phone: string | null;
readonly mobile: string | null;
};
export type KwpAddressDetails = {
readonly externalAddressCode: string;
readonly name: string | null;
readonly firstName: string | null;
readonly addition: string | null;
readonly street: string | null;
readonly postalCode: string | null;
readonly city: string | null;
readonly country: string | null;
readonly invoiceEmail: string | null;
readonly email: string | null;
readonly phone: string | null;
readonly mobile: string | null;
readonly contactPeople: readonly KwpAddressContactPerson[];
};
export type KwpSemanticContract = {
readonly apiVersion: string;
readonly semanticFingerprint: string;
readonly consumedContract: Record<string, unknown>;
};
export type KwpResourceTransportDependencies = {
readonly consumeBudget: () => Promise<void>;
readonly outboundOptions?: KwpOutboundRequestOptions;
};
export function createKwpResourceTransport(credentials: KwpCredentials, dependencies: KwpResourceTransportDependencies) {
assertKwpResourceCredentials(credentials);
return Object.freeze({
executeReadOperation: async <T = unknown>(operationId: KwpReadOperationId, input: KwpOperationInput = {}): Promise<T> => {
assertKwpReadOperationId(operationId);
validateKwpOperationInput(operationId, input);
const operation = getKwpScopedOperation(operationId);
const value = await requestJson(credentials, dependencies, operation.method, operation.path, input.query, input.body);
return parseKwpOperationResponse(operationId, value) as T;
},
searchProjects: async (query: string): Promise<KwpProjectSearchResult[]> => {
const normalizedQuery = normalizeSearchQuery(query);
const value = await executeProjectedRead(credentials, dependencies, "projektSearch", { body: { value: normalizedQuery } });
const parsed = z.array(rawProjectSearchResultSchema).max(KWP_PROJECT_SEARCH_MAX_ENTRIES).safeParse(value);
if (!parsed.success) throw new KwpError("contract_drift");
return parsed.data.flatMap(normalizeProjectSearchResult);
},
listProjectNumbers: async (): Promise<string[]> => {
const value = await executeProjectedRead(credentials, dependencies, "projektampelLoadProjekteNachFilter", {});
const parsed = z.array(rawProjectCatalogEntrySchema).max(KWP_PROJECT_CATALOG_MAX_ENTRIES).safeParse(value);
if (!parsed.success) throw new KwpError("contract_drift");
return [...new Set(parsed.data.map((entry) => normalizeNullableIdentifier(entry.projNr)).filter((entry): entry is string => Boolean(entry)))];
},
loadProjectDetails: async (projectNumber: string): Promise<KwpProjectDetails> => {
const normalizedProjectNumber = normalizeExternalId(projectNumber);
const value = await executeProjectedRead(credentials, dependencies, "projektampelLoadProjektDetailsGet", { query: { projNr: normalizedProjectNumber } });
const parsed = rawProjectDetailsSchema.safeParse(value);
if (!parsed.success) throw new KwpError("contract_drift");
const externalProjectNumber = requireProviderIdentifier(parsed.data.projNr);
if (externalProjectNumber !== normalizedProjectNumber) throw new KwpError("contract_drift");
return {
externalProjectNumber,
name: normalizeRequiredText(parsed.data.projBezeichnung, externalProjectNumber),
startDate: parsed.data.beginn ? new Date(parsed.data.beginn).toISOString() : null,
orderValue: parsed.data.auftragssumme,
addressCode: normalizeNullableIdentifier(parsed.data.adresse.adrNrGes),
addressName: normalizeNullableText(parsed.data.adresse.name),
};
},
loadAddressDetails: async (addressCode: string): Promise<KwpAddressDetails> => {
const normalizedAddressCode = normalizeExternalId(addressCode);
const value = await executeProjectedRead(credentials, dependencies, "adresseLoadAdressKomplett", { query: { adresskuerzel: normalizedAddressCode } });
const parsed = rawAddressDetailsSchema.safeParse(value);
if (!parsed.success) throw new KwpError("contract_drift");
const externalAddressCode = requireProviderIdentifier(parsed.data.adrNrGes);
if (externalAddressCode !== normalizedAddressCode) throw new KwpError("contract_drift");
const primaryChannels = normalizeChannels(parsed.data.kontakte ?? [], null);
return {
externalAddressCode,
name: normalizeNullableText(parsed.data.name),
firstName: normalizeNullableText(parsed.data.vorname),
addition: normalizeNullableText(parsed.data.zusatz),
street: normalizeNullableText(parsed.data.strasse),
postalCode: normalizeNullableText(parsed.data.ort.plz),
city: normalizeNullableText(parsed.data.ort.ort),
country: normalizeNullableText(parsed.data.ort.land),
invoiceEmail: normalizeEmail(parsed.data.rechnungsmailadresse),
...primaryChannels,
contactPeople: (parsed.data.ansprechpartner ?? []).map((person) => {
const channels = normalizeChannels(person.kontakte ?? [], person.ansprechpartnerId);
return {
externalContactId: String(person.ansprechpartnerId),
firstName: normalizeNullableText(person.vorname),
lastName: normalizeNullableText(person.nachname),
addition: normalizeNullableText(person.zusatz),
...channels,
};
}),
};
},
loadSemanticContract: async (): Promise<KwpSemanticContract> => {
const value = await requestOpenApi(credentials, dependencies);
return buildKwpSemanticContract(value);
},
loadScopedSemanticContracts: async (): Promise<readonly KwpCapabilitySemanticContract[]> => {
const value = await requestOpenApi(credentials, dependencies);
return listKwpCapabilities().map((capability) => buildKwpCapabilitySemanticContract(value, capability));
},
});
}
export function assertKwpReadOperationAllowed(method: string, path: string): void {
const normalizedMethod = method.toUpperCase();
const allowed =
KWP_SCOPED_OPERATIONS.some((operation) => operation.mode === "read" && operation.method === normalizedMethod && operation.path === path) ||
(normalizedMethod === "GET" && path === KWP_OPENAPI_PATH);
if (!allowed) throw new KwpError("invalid_credentials");
}
export function buildKwpScopedSemanticContracts(value: unknown): Readonly<Record<KwpCapability, KwpCapabilitySemanticContract>> {
return Object.fromEntries(listKwpCapabilities().map((capability) => [capability, buildKwpCapabilitySemanticContract(value, capability)])) as Record<
KwpCapability,
KwpCapabilitySemanticContract
>;
}
export function getKwpScopedCapabilityKey(capability: KwpCapability): string {
return KWP_SCOPED_CAPABILITY_KEYS[capability];
}
export function buildKwpSemanticContract(value: unknown): KwpSemanticContract {
const parsed = openApiSchema.safeParse(value);
if (!parsed.success) throw new KwpError("contract_drift");
const consumedContract = {
operations: {
projectSearch: selectOperation(parsed.data.paths, KWP_PROJECT_SEARCH_PATH, "post"),
projectDetails: selectOperation(parsed.data.paths, KWP_PROJECT_DETAILS_PATH, "get"),
addressDetails: selectOperation(parsed.data.paths, KWP_ADDRESS_DETAILS_PATH, "get"),
},
schemas: selectConsumedSchemas(parsed.data.components.schemas),
};
const canonical = canonicalJson(consumedContract);
return {
apiVersion: parsed.data.info.version,
semanticFingerprint: createHash("sha256").update(canonical).digest("hex"),
consumedContract,
};
}
export function fingerprintKwpSnapshot(value: unknown): string {
return createHash("sha256").update(canonicalJson(value)).digest("hex");
}
function normalizeProjectSearchResult(value: z.infer<typeof rawProjectSearchResultSchema>): KwpProjectSearchResult[] {
const externalProjectNumber = normalizeNullableIdentifier(value.projNr);
if (!externalProjectNumber || value.auftragStatus === undefined) return [];
const status = value.auftragStatus as KwpProjectStatus;
return [
{
externalProjectNumber,
name: normalizeRequiredText(value.projBezeichnung, externalProjectNumber),
projectAddressCode: normalizeNullableIdentifier(value.projAdr),
invoiceAddressCode: normalizeNullableIdentifier(value.rechAdr),
clientAddressCode: normalizeNullableIdentifier(value.bauHrAdr),
status,
statusLabel: KWP_PROJECT_STATUS_LABELS[status],
},
];
}
function normalizeChannels(channels: readonly z.infer<typeof rawContactChannelSchema>[], contactPersonId: number | null) {
const scoped = channels.filter((channel) => channel.ansprechpartnerId === contactPersonId);
return {
email: normalizeEmail(scoped.find((channel) => channel.kontaktart === 2)?.kontakt ?? null),
phone: normalizeNullableText(scoped.find((channel) => channel.kontaktart === 0)?.kontakt ?? null),
mobile: normalizeNullableText(scoped.find((channel) => channel.kontaktart === 4)?.kontakt ?? null),
};
}
async function requestJson(
credentials: KwpCredentials,
dependencies: KwpResourceTransportDependencies,
method: string,
path: string,
query?: Readonly<Record<string, unknown>>,
body?: unknown
): Promise<unknown> {
assertKwpReadOperationAllowed(method, path);
await dependencies.consumeBudget();
const relayBaseUrl = await resolveKwpRelayBaseUrl(credentials.customerCode, dependencies.outboundOptions);
const endpoint = new URL(`/relay/${encodeURIComponent(credentials.customerCode)}/pwa${path}`, `${relayBaseUrl}/`);
if (credentials.mandantBinding?.kind === "selected" && path !== KWP_OPENAPI_PATH) {
endpoint.searchParams.set("mandant", credentials.mandantBinding.code);
}
for (const [name, value] of Object.entries(query ?? {})) {
appendQueryValue(endpoint.searchParams, name, value);
}
await dependencies.consumeBudget();
let response: Response;
try {
response = await fetchOutboundHttpWithRedirects(
endpoint.toString(),
{
method: method.toUpperCase(),
headers: {
accept: "application/json",
authorization: `Bearer ${credentials.accessToken}`,
...(body === undefined ? {} : { "content-type": "application/json" }),
},
...(body === undefined ? {} : { body: JSON.stringify(body) }),
},
{
...dependencies.outboundOptions,
allowCrossOriginRedirects: false,
urlValidator: validateKwpOnlineUrl,
}
);
} catch (error) {
if (error instanceof KwpError) throw error;
if (error instanceof OutboundHttpUrlValidationError) throw new KwpError("relay_host_invalid");
throw new KwpError("provider_outage");
}
if (!response.ok) throw mapResourceError(response.status);
let responseText: string;
try {
const responseLimit =
path === KWP_OPENAPI_PATH
? KWP_OPENAPI_RESPONSE_LIMIT_BYTES
: path === KWP_PROJECT_CATALOG_PATH
? KWP_PROJECT_CATALOG_RESPONSE_LIMIT_BYTES
: KWP_RESOURCE_RESPONSE_LIMIT_BYTES;
const read = await readLimitedResponseText(response, responseLimit);
if (read.truncated) throw new KwpError("contract_drift", response.status);
responseText = read.body;
} catch (error) {
if (error instanceof KwpError) throw error;
throw new KwpError("contract_drift", response.status);
}
try {
return JSON.parse(responseText) as unknown;
} catch {
throw new KwpError("contract_drift", response.status);
}
}
/**
* The project-import domain intentionally validates a smaller Zod projection
* than the complete scoped adapter. KWP's live address payload may use `null`
* for documented-but-unconsumed object fields. Those provider inconsistencies
* must not pause project import while every field HiveGrid actually maps still
* satisfies its explicit schema. The generic 77-operation adapter continues to
* use the full checked-in OpenAPI validator in executeReadOperation().
*/
async function executeProjectedRead(
credentials: KwpCredentials,
dependencies: KwpResourceTransportDependencies,
operationId: KwpReadOperationId,
input: KwpOperationInput
): Promise<unknown> {
assertKwpReadOperationId(operationId);
validateKwpOperationInput(operationId, input);
const operation = getKwpScopedOperation(operationId);
return requestJson(credentials, dependencies, operation.method, operation.path, input.query, input.body);
}
async function requestOpenApi(credentials: KwpCredentials, dependencies: KwpResourceTransportDependencies): Promise<unknown> {
return requestJson(credentials, dependencies, "GET", KWP_OPENAPI_PATH);
}
function appendQueryValue(target: URLSearchParams, name: string, value: unknown): void {
if (value === undefined || value === null) return;
if (Array.isArray(value)) {
for (const entry of value) appendQueryValue(target, name, entry);
return;
}
if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") {
throw new KwpError("invalid_credentials");
}
target.append(name, String(value));
}
function mapResourceError(status: number): KwpError {
if (status === 401) return new KwpError("auth_token_invalid", status);
if (status === 403) return new KwpError("auth_scope_missing", status);
if (status === 404) return new KwpError("resource_not_found", status);
if (status === 429) return new KwpError("rate_limit_exceeded", status);
if (status >= 500) return new KwpError("provider_outage", status);
return new KwpError("unknown", status);
}
function normalizeSearchQuery(value: string): string {
const normalized = value.trim();
if (normalized.length < 2 || normalized.length > KWP_QUERY_MAX_LENGTH || /[\u0000-\u001f\u007f]/u.test(normalized)) {
throw new KwpError("invalid_credentials");
}
return normalized;
}
function normalizeExternalId(value: string): string {
const normalized = value.trim();
if (!normalized || normalized.length > KWP_EXTERNAL_ID_MAX_LENGTH || /[\u0000-\u001f\u007f]/u.test(normalized)) {
throw new KwpError("invalid_credentials");
}
return normalized;
}
function requireProviderIdentifier(value: string | null): string {
const normalized = normalizeNullableIdentifier(value);
if (!normalized) throw new KwpError("contract_drift");
return normalized;
}
function normalizeNullableIdentifier(value: string | null): string | null {
if (value === null) return null;
const normalized = value.trim();
if (!normalized || normalized.length > KWP_EXTERNAL_ID_MAX_LENGTH || /[\u0000-\u001f\u007f]/u.test(normalized)) return null;
return normalized;
}
function normalizeNullableText(value: string | null): string | null {
if (value === null) return null;
const normalized = value.trim();
return normalized && !/[\u0000-\u001f\u007f]/u.test(normalized) ? normalized.slice(0, 512) : null;
}
function normalizeRequiredText(value: string | null, fallback: string): string {
return normalizeNullableText(value) ?? fallback;
}
function normalizeEmail(value: string | null): string | null {
const normalized = normalizeNullableText(value)?.toLowerCase() ?? null;
return normalized && /^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(normalized) ? normalized : null;
}
function selectOperation(paths: Record<string, unknown>, path: string, method: "get" | "post"): unknown {
const pathItem = asRecord(paths[path]);
const operation = asRecord(pathItem?.[method]);
if (!operation) throw new KwpError("contract_drift");
return {
method,
path,
parameters: Array.isArray(operation.parameters)
? operation.parameters.map((parameter) => {
const record = asRecord(parameter);
return record ? { name: record.name, in: record.in, schema: record.schema } : null;
})
: [],
requestSchema: asRecord(asRecord(asRecord(operation.requestBody)?.content)?.["application/json"])?.schema ?? null,
responseSchema: asRecord(asRecord(asRecord(asRecord(operation.responses)?.["200"])?.content)?.["application/json"])?.schema ?? null,
};
}
const CONSUMED_SCHEMA_FIELDS = Object.freeze({
"Kwp.Api.Service.Dto.DtoValue": ["value"],
"Kwp.Api.Service.Dto.Projekte.DtoSearchResultProjekt": ["projNr", "projBezeichnung", "projAdr", "rechAdr", "bauHrAdr", "auftragStatus"],
"Kwp.Api.Model.Values.ProjektHauptstatus": [],
"Kwp.Api.Service.Dto.Projektampel.DtoProjektampelProjekt": ["projNr", "projBezeichnung", "beginn", "adresse", "auftragssumme"],
"Kwp.Api.Service.Dto.Adressen.DtoAdresse": ["adrNrGes", "name", "vorname", "zusatz", "strasse", "ort"],
"Kwp.Api.Service.Dto.Adressen.DtoAdresseKomplett": [
"adrNrGes",
"name",
"vorname",
"zusatz",
"strasse",
"ort",
"rechnungsmailadresse",
"kontakte",
"ansprechpartner",
],
"Kwp.Api.Service.Dto.Adressen.DtoOrt": ["ortId", "land", "plz", "ort"],
"Kwp.Api.Service.Dto.Adressen.DtoKontakt": ["kontaktart", "kontakt", "ansprechpartnerId"],
"Kwp.Api.Service.Dto.Adressen.DtoAnsprechpartner": ["nachname", "vorname", "ansprechpartnerId", "zusatz", "kontakte"],
"Kwp.Api.Model.Values.Adresse.Kontaktart": [],
} as const);
function selectConsumedSchemas(schemas: Record<string, unknown>): Record<string, unknown> {
return Object.fromEntries(
Object.entries(CONSUMED_SCHEMA_FIELDS).map(([name, fields]) => {
const schema = asRecord(schemas[name]);
if (!schema) throw new KwpError("contract_drift");
const properties = asRecord(schema.properties) ?? {};
for (const field of fields) if (!(field in properties)) throw new KwpError("contract_drift");
return [
name,
fields.length === 0
? { type: schema.type, format: schema.format, enum: schema.enum }
: {
type: schema.type,
properties: Object.fromEntries(fields.map((field) => [field, properties[field]])),
},
];
})
);
}
function asRecord(value: unknown): Record<string, unknown> | null {
return typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : null;
}
function canonicalJson(value: unknown): string {
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
if (value && typeof value === "object") {
return `{${Object.entries(value as Record<string, unknown>)
.sort(([left], [right]) => left.localeCompare(right))
.map(([key, nested]) => `${JSON.stringify(key)}:${canonicalJson(nested)}`)
.join(",")}}`;
}
return JSON.stringify(value) ?? "null";
}
@@ -0,0 +1,199 @@
import { describe, expect, it } from "vitest";
import scopedOpenApi from "./contract/kwp-scoped-openapi.json" with { type: "json" };
import {
buildKwpCapabilitySemanticContract,
getKwpScopedOperation,
KWP_SCOPED_OPERATIONS,
KWP_SCOPED_OPERATION_INVENTORY,
listKwpCapabilities,
parseKwpOperationResponse,
rejectKwpMutationOperation,
validateKwpOperationInput,
validateKwpOperationResponse,
validateKwpScopedOpenApi,
type KwpMutationOperationId,
type KwpOperationInput,
} from "./scoped-contract.js";
type JsonRecord = Record<string, unknown>;
describe("KWP scoped contract", () => {
it("keeps the complete licensed inventory explicit and duplicate-free", () => {
expect(KWP_SCOPED_OPERATION_INVENTORY).toEqual({
sourceOperationCount: 554,
scopedOperationCount: 113,
readOperationCount: 77,
mutationOperationCount: 36,
excludedOperationCount: 441,
});
expect(new Set(KWP_SCOPED_OPERATIONS.map((operation) => operation.id))).toHaveLength(113);
expect(new Set(KWP_SCOPED_OPERATIONS.map((operation) => `${operation.method} ${operation.path}`))).toHaveLength(113);
expect(KWP_SCOPED_OPERATIONS.filter((operation) => operation.mode === "read")).toHaveLength(77);
expect(KWP_SCOPED_OPERATIONS.filter((operation) => operation.mode === "mutation")).toHaveLength(36);
});
it("keeps provider documentation markup out of the runtime contract", () => {
expect(JSON.stringify(scopedOpenApi)).not.toContain('"description":');
});
it("compiles and fixture-validates every scoped request and response schema", () => {
const document = scopedOpenApi as unknown as JsonRecord;
for (const operation of KWP_SCOPED_OPERATIONS) {
const contract = readOperationContract(document, operation.path, operation.method);
const input = buildInputFixture(document, contract);
const response = buildResponseFixture(document, contract);
expect(() => validateKwpOperationInput(operation.id, input)).not.toThrow();
expect(() => validateKwpOperationResponse(operation.id, response)).not.toThrow();
}
});
it("keeps all mutation contracts unavailable to runtime transport", () => {
const mutations = KWP_SCOPED_OPERATIONS.filter((operation) => operation.mode === "mutation");
expect(mutations).toHaveLength(36);
for (const operation of mutations) {
expect(() => rejectKwpMutationOperation(operation.id as KwpMutationOperationId)).toThrowError("invalid_credentials");
}
});
it("rejects caller-controlled mandant context", () => {
expect(() =>
validateKwpOperationInput("projektSearch", {
query: { mandant: "other-tenant" },
body: { value: "Projekt" },
})
).toThrowError("invalid_credentials");
});
it("removes forbidden address data from generic adapter responses", () => {
const parsed = parseKwpOperationResponse("adresseLoadAdressKomplett", {
adrNrGes: "A-1",
iban: "DE001234",
bank: "Provider Bank",
kreditLimit: 12_500,
steuerNummer: "TAX-1",
geburtstag: "1990-01-01T00:00:00.000Z",
hinweis: "internal",
bemerkung: "private",
benutzerFeld1: "custom",
ansprechpartner: [
{
ansprechpartnerId: 1,
nachname: "Kontakt",
benutzerFeld2: "nested",
},
],
});
expect(parsed).toEqual({
adrNrGes: "A-1",
ansprechpartner: [
{
ansprechpartnerId: 1,
nachname: "Kontakt",
},
],
});
});
it("isolates semantic drift by capability", () => {
validateKwpScopedOpenApi(scopedOpenApi);
const baseline = Object.fromEntries(
listKwpCapabilities().map((capability) => [capability, buildKwpCapabilitySemanticContract(scopedOpenApi, capability).semanticFingerprint])
);
const drifted = structuredClone(scopedOpenApi) as unknown as JsonRecord;
const paths = drifted.paths as JsonRecord;
const addressPath = paths["/api/Adresse/LoadAdressDetails"] as JsonRecord;
const addressGet = addressPath.get as JsonRecord;
const parameters = addressGet.parameters as JsonRecord[];
const addressCode = parameters.find((parameter) => parameter.name === "adresskuerzel");
(addressCode!.schema as JsonRecord).maxLength = 190;
const observed = Object.fromEntries(
listKwpCapabilities().map((capability) => [capability, buildKwpCapabilitySemanticContract(drifted, capability).semanticFingerprint])
);
expect(observed.address).not.toBe(baseline.address);
expect(observed.activity).toBe(baseline.activity);
expect(observed.archive).toBe(baseline.archive);
expect(observed.project).toBe(baseline.project);
expect(observed.schedule).toBe(baseline.schedule);
});
it("rejects unknown operation ids without exposing a free path", () => {
expect(() => getKwpScopedOperation("freePath" as never)).toThrowError("invalid_credentials");
});
});
function readOperationContract(document: JsonRecord, path: string, method: string): JsonRecord {
const paths = document.paths as JsonRecord;
return (paths[path] as JsonRecord)[method.toLowerCase()] as JsonRecord;
}
function buildInputFixture(document: JsonRecord, operation: JsonRecord): KwpOperationInput {
const input: { query?: JsonRecord; body?: unknown } = {};
const query: JsonRecord = {};
const parameters = Array.isArray(operation.parameters) ? operation.parameters : [];
for (const parameterValue of parameters) {
const parameter = parameterValue as JsonRecord;
if (parameter.in !== "query" || parameter.name === "mandant" || parameter.required !== true) {
continue;
}
query[String(parameter.name)] = buildSchemaFixture(document, parameter.schema);
}
if (Object.keys(query).length > 0) input.query = query;
const requestBody = operation.requestBody as JsonRecord | undefined;
const bodySchema = selectContentSchema(requestBody?.content);
if (bodySchema) input.body = buildSchemaFixture(document, bodySchema);
return input;
}
function buildResponseFixture(document: JsonRecord, operation: JsonRecord): unknown {
const responses = operation.responses as JsonRecord;
const success = (responses["200"] ?? responses["201"] ?? responses["202"] ?? responses["204"]) as JsonRecord;
const schema = selectContentSchema(success?.content);
return schema ? buildSchemaFixture(document, schema) : undefined;
}
function selectContentSchema(contentValue: unknown): unknown | null {
const content = contentValue as JsonRecord | undefined;
for (const type of ["application/json", "text/json", "text/plain"]) {
const media = content?.[type] as JsonRecord | undefined;
if (media?.schema) return media.schema;
}
return null;
}
function buildSchemaFixture(document: JsonRecord, schemaValue: unknown): unknown {
const schema = schemaValue as JsonRecord;
if (typeof schema.$ref === "string") {
const name = schema.$ref.replace("#/components/schemas/", "");
const components = document.components as JsonRecord;
const schemas = components.schemas as JsonRecord;
return buildSchemaFixture(document, schemas[name]);
}
if (schema.nullable === true) return null;
if (schema.example !== undefined) return structuredClone(schema.example);
if (schema.default !== undefined) return structuredClone(schema.default);
if (Array.isArray(schema.enum) && schema.enum.length > 0) return schema.enum[0];
if (schema.type === "object" || schema.properties) {
const properties = (schema.properties ?? {}) as JsonRecord;
const required = Array.isArray(schema.required) ? schema.required : [];
return Object.fromEntries(required.map((name) => [String(name), buildSchemaFixture(document, properties[String(name)])]));
}
if (schema.type === "array") {
const minimum = typeof schema.minItems === "number" ? schema.minItems : 0;
return Array.from({ length: minimum }, () => buildSchemaFixture(document, schema.items));
}
if (schema.type === "boolean") return false;
if (schema.type === "integer" || schema.type === "number") {
return typeof schema.minimum === "number" ? schema.minimum : 0;
}
if (schema.type === "string") {
if (schema.format === "date-time") return "2026-07-24T00:00:00.000Z";
if (schema.format === "uuid") return "00000000-0000-4000-8000-000000000000";
if (schema.format === "uri") return "https://example.invalid/fixture";
return "fixture";
}
return {};
}
@@ -0,0 +1,333 @@
import { createHash } from "node:crypto";
import { Ajv, type AnySchema, type ValidateFunction } from "ajv";
import scopedOpenApi from "./contract/kwp-scoped-openapi.json" with { type: "json" };
import {
KWP_SCOPED_OPERATIONS,
type KwpCapability,
type KwpMutationOperationId,
type KwpReadOperationId,
type KwpScopedOperation,
type KwpScopedOperationId,
} from "./contract/catalog.generated.js";
import { KwpError } from "./client.js";
export {
KWP_SCOPED_OPERATIONS,
KWP_SCOPED_OPERATION_INVENTORY,
type KwpCapability,
type KwpMutationOperationId,
type KwpReadOperationId,
type KwpScopedOperation,
type KwpScopedOperationId,
} from "./contract/catalog.generated.js";
export type KwpOperationInput = {
readonly query?: Readonly<Record<string, unknown>>;
readonly body?: unknown;
};
export type KwpCapabilitySemanticContract = {
readonly apiVersion: string;
readonly capability: KwpCapability;
readonly semanticFingerprint: string;
readonly consumedContract: Record<string, unknown>;
};
type OpenApiDocument = {
readonly info: { readonly version: string };
readonly paths: Readonly<Record<string, unknown>>;
readonly components: {
readonly schemas: Readonly<Record<string, unknown>>;
};
};
type OperationContract = {
readonly parameters?: readonly unknown[];
readonly requestBody?: unknown;
readonly responses?: Readonly<Record<string, unknown>>;
};
const operationById = new Map<KwpScopedOperationId, KwpScopedOperation>(KWP_SCOPED_OPERATIONS.map((operation) => [operation.id, operation]));
const validatorByOperation = new Map<KwpScopedOperationId, { readonly input: ValidateFunction; readonly response: ValidateFunction | null }>();
const ajv = new Ajv({
allErrors: true,
removeAdditional: "all",
strict: false,
validateFormats: false,
});
const contract = scopedOpenApi as unknown as OpenApiDocument;
const KWP_ADDRESS_FORBIDDEN_FIELDS = new Set([
"bank",
"bemerkung",
"benutzerfeld1",
"benutzerfeld2",
"benutzerfeld3",
"benutzerfeld4",
"benutzerfeld5",
"geburtstag",
"hinweis",
"iban",
"kreditlimit",
"steuernummer",
"steuerid",
"ustid",
"ustidnr",
]);
export function getKwpScopedOperation(operationId: KwpScopedOperationId): KwpScopedOperation {
const operation = operationById.get(operationId);
if (!operation) throw new KwpError("invalid_credentials");
return operation;
}
export function assertKwpReadOperationId(operationId: KwpScopedOperationId): asserts operationId is KwpReadOperationId {
if (getKwpScopedOperation(operationId).mode !== "read") {
throw new KwpError("invalid_credentials");
}
}
/**
* Mutation contracts are intentionally present for drift/fixture coverage but
* cannot become provider calls until VEXT-6 and a later product approval.
*/
export function rejectKwpMutationOperation(operationId: KwpMutationOperationId): never {
const operation = getKwpScopedOperation(operationId);
if (operation.mode !== "mutation") throw new KwpError("invalid_credentials");
throw new KwpError("invalid_credentials");
}
export function validateKwpOperationInput(operationId: KwpScopedOperationId, input: KwpOperationInput): void {
assertNoInjectedContext(input);
const validators = getOperationValidators(operationId);
if (!validators.input(input)) throw new KwpError("invalid_credentials");
}
export function validateKwpOperationResponse(operationId: KwpScopedOperationId, value: unknown): void {
parseKwpOperationResponse(operationId, value);
}
export function parseKwpOperationResponse(operationId: KwpScopedOperationId, value: unknown): unknown {
const validator = getOperationValidators(operationId).response;
const operation = getKwpScopedOperation(operationId);
const clonedValue = structuredClone(value);
const safeValue = operation.capability === "address" ? redactForbiddenAddressFields(clonedValue) : clonedValue;
if (validator && !validator(safeValue)) throw new KwpError("contract_drift");
if (!validator && value !== undefined && value !== null && value !== "") {
throw new KwpError("contract_drift");
}
return safeValue;
}
export function buildKwpCapabilitySemanticContract(value: unknown, capability: KwpCapability): KwpCapabilitySemanticContract {
const live = parseOpenApiDocument(value);
const operations = KWP_SCOPED_OPERATIONS.filter((operation) => operation.capability === capability);
const selectedPaths: Record<string, Record<string, unknown>> = {};
for (const operation of operations) {
const pathItem = asRecord(live.paths[operation.path]);
const operationContract = asRecord(pathItem?.[operation.method.toLowerCase()]);
if (!operationContract) throw new KwpError("contract_drift");
selectedPaths[operation.path] ??= {};
selectedPaths[operation.path]![operation.method.toLowerCase()] = selectSemanticOperation(operationContract, operation);
}
const schemaNames = collectReferencedSchemaNames(selectedPaths, live.components.schemas);
const schemas = Object.fromEntries([...schemaNames].sort((left, right) => left.localeCompare(right)).map((name) => [name, live.components.schemas[name]]));
const consumedContract = {
operations: canonicalize(selectedPaths),
schemas: canonicalize(schemas),
};
return {
apiVersion: live.info.version,
capability,
semanticFingerprint: createHash("sha256").update(JSON.stringify(consumedContract)).digest("hex"),
consumedContract,
};
}
export function validateKwpScopedOpenApi(value: unknown): void {
for (const capability of listKwpCapabilities()) {
buildKwpCapabilitySemanticContract(value, capability);
}
}
export function listKwpCapabilities(): readonly KwpCapability[] {
return ["activity", "address", "archive", "project", "schedule"];
}
function getOperationValidators(operationId: KwpScopedOperationId) {
const cached = validatorByOperation.get(operationId);
if (cached) return cached;
const operation = getKwpScopedOperation(operationId);
const operationContract = getSnapshotOperationContract(operation);
const validators = {
input: ajv.compile(buildInputSchema(operationContract)),
response: buildResponseSchema(operationContract),
};
validatorByOperation.set(operationId, validators);
return validators;
}
function getSnapshotOperationContract(operation: KwpScopedOperation): OperationContract {
const pathItem = asRecord(contract.paths[operation.path]);
const value = asRecord(pathItem?.[operation.method.toLowerCase()]);
if (!value) throw new KwpError("contract_drift");
return value as OperationContract;
}
function buildInputSchema(operation: OperationContract): AnySchema {
const queryParameters = (operation.parameters ?? [])
.map(asRecord)
.filter((parameter): parameter is Record<string, unknown> => parameter !== null && parameter.in === "query" && parameter.name !== "mandant");
const queryProperties = Object.fromEntries(queryParameters.map((parameter) => [String(parameter.name), parameter.schema ?? {}]));
const requiredQuery = queryParameters.filter((parameter) => parameter.required === true).map((parameter) => String(parameter.name));
const requestBody = asRecord(operation.requestBody);
const bodySchema = selectJsonSchemaFromContent(requestBody?.content);
const properties: Record<string, unknown> = {};
const required: string[] = [];
if (queryParameters.length > 0) {
properties.query = {
type: "object",
properties: queryProperties,
required: requiredQuery,
additionalProperties: false,
};
if (requiredQuery.length > 0) required.push("query");
}
if (bodySchema) {
properties.body = bodySchema;
if (requestBody?.required === true) required.push("body");
}
return withComponents({
type: "object",
properties,
required,
additionalProperties: false,
});
}
function buildResponseSchema(operation: OperationContract): ValidateFunction | null {
const responses = operation.responses ?? {};
const success = asRecord(responses["200"] ?? responses["201"] ?? responses["202"] ?? responses["204"]);
const responseSchema = selectJsonSchemaFromContent(success?.content);
return responseSchema ? ajv.compile(withComponents(responseSchema)) : null;
}
function selectJsonSchemaFromContent(value: unknown): unknown | null {
const content = asRecord(value);
if (!content) return null;
for (const contentType of ["application/json", "text/json", "text/plain"]) {
const media = asRecord(content[contentType]);
if (media?.schema) return media.schema;
}
return null;
}
function withComponents(schema: unknown): AnySchema {
return {
...(asRecord(schema) ?? {}),
components: contract.components,
} as AnySchema;
}
function assertNoInjectedContext(input: KwpOperationInput): void {
const query = input.query ?? {};
const forbidden = Object.keys(query).some((name) => name.toLowerCase() === "mandant" || name.toLowerCase() === "x-kwp-client-version");
if (forbidden) throw new KwpError("invalid_credentials");
}
function redactForbiddenAddressFields(value: unknown): unknown {
if (Array.isArray(value)) return value.map(redactForbiddenAddressFields);
const record = asRecord(value);
if (!record) return value;
return Object.fromEntries(
Object.entries(record)
.filter(([key]) => !KWP_ADDRESS_FORBIDDEN_FIELDS.has(key.toLowerCase()))
.map(([key, nested]) => [key, redactForbiddenAddressFields(nested)])
);
}
function parseOpenApiDocument(value: unknown): OpenApiDocument {
const document = asRecord(value);
const info = asRecord(document?.info);
const paths = asRecord(document?.paths);
const components = asRecord(document?.components);
const schemas = asRecord(components?.schemas);
if (!document || typeof info?.version !== "string" || info.version.length === 0 || !paths || !schemas) {
throw new KwpError("contract_drift");
}
return {
info: { version: info.version },
paths,
components: { schemas },
};
}
function selectSemanticOperation(operationContract: Record<string, unknown>, operation: KwpScopedOperation): Record<string, unknown> {
const parameters = Array.isArray(operationContract.parameters)
? operationContract.parameters.map((parameter) => {
const record = asRecord(parameter);
return record
? {
name: record.name,
in: record.in,
required: record.required ?? false,
schema: record.schema ?? null,
}
: null;
})
: [];
const requestBody = asRecord(operationContract.requestBody);
const responses = asRecord(operationContract.responses);
const success = asRecord(responses?.["200"] ?? responses?.["201"] ?? responses?.["202"] ?? responses?.["204"]);
return {
id: operation.id,
method: operation.method,
path: operation.path,
mode: operation.mode,
parameters,
requestSchema: selectJsonSchemaFromContent(requestBody?.content),
responseSchema: selectJsonSchemaFromContent(success?.content),
};
}
function collectReferencedSchemaNames(value: unknown, schemas: Readonly<Record<string, unknown>>): Set<string> {
const found = new Set<string>();
const pending = [...findRefs(value)];
while (pending.length > 0) {
const ref = pending.pop();
if (!ref) continue;
const prefix = "#/components/schemas/";
if (!ref.startsWith(prefix)) throw new KwpError("contract_drift");
const name = decodeURIComponent(ref.slice(prefix.length));
if (found.has(name)) continue;
const schema = schemas[name];
if (!schema) throw new KwpError("contract_drift");
found.add(name);
pending.push(...findRefs(schema));
}
return found;
}
function findRefs(value: unknown): string[] {
if (Array.isArray(value)) return value.flatMap(findRefs);
const record = asRecord(value);
if (!record) return [];
return Object.entries(record).flatMap(([key, nested]) => (key === "$ref" && typeof nested === "string" ? [nested] : findRefs(nested)));
}
function canonicalize(value: unknown): unknown {
if (Array.isArray(value)) return value.map(canonicalize);
const record = asRecord(value);
if (!record) return value;
return Object.fromEntries(
Object.entries(record)
.sort(([left], [right]) => left.localeCompare(right))
.map(([key, nested]) => [key, canonicalize(nested)])
);
}
function asRecord(value: unknown): Record<string, unknown> | null {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
return value as Record<string, unknown>;
}