Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/modules/telephony/services/HalloPetraConnectionService.server.ts
T

190 lines
6.4 KiB
TypeScript

import { createHash, randomBytes } from "node:crypto";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
import {
AppsEngineServiceError,
createConnection,
disconnectConnection,
reconnectConnection,
} from "~/utils/integrations/appsEngineService.server";
const HALLOPETRA_APP_ID = "hallopetra";
const HALLOPETRA_CONNECTION_LABEL = "HalloPetra";
export class HalloPetraConnectError extends Error {
readonly code: "not_configured" | "invalid_key" | "provider_conflict" | "slot_conflict" | "persistence_failed";
constructor(code: HalloPetraConnectError["code"]) {
super(code);
this.name = "HalloPetraConnectError";
this.code = code;
}
}
export type HalloPetraConnectResult = {
readonly dataConnectionId: string;
readonly telephonyConnectionId: string;
/** Shown once so the admin can configure HalloPetra's custom header. */
readonly webhookSecret: string;
readonly webhookUrl: string;
};
/** Connect or rotate one tenant's API-key based HalloPetra slot. */
export async function connectHalloPetra(input: {
readonly tenantId: string;
readonly userId: string;
readonly apiKey: string;
}): Promise<HalloPetraConnectResult> {
const apiKey = input.apiKey.trim();
if (!apiKey || apiKey.length > 2_048) throw new HalloPetraConnectError("invalid_key");
const webhookUrl = resolveWebhookUrl();
const snapshot = await withTenantRLS(input.tenantId, async (tx) => {
const telephony = await tx.telephonyConnection.findMany({
where: { tenantId: input.tenantId },
select: { id: true, provider: true, dataConnectionId: true },
});
const dataConnections = telephony.length
? await tx.dataConnection.findMany({
where: { tenantId: input.tenantId, id: { in: telephony.map((row) => row.dataConnectionId) } },
select: { id: true, appId: true, connectionStatus: true },
})
: [];
return { telephony, dataConnections };
});
const dataById = new Map(snapshot.dataConnections.map((row) => [row.id, row]));
const activeOtherProvider = snapshot.telephony.find((row) => {
if (row.provider === "hallopetra") return false;
const status = dataById.get(row.dataConnectionId)?.connectionStatus;
return status === "active" || status === "degraded" || status === "pending";
});
if (activeOtherProvider) throw new HalloPetraConnectError("provider_conflict");
const hallopetraSlots = snapshot.telephony.filter((row) => row.provider === "hallopetra");
if (hallopetraSlots.length > 1) throw new HalloPetraConnectError("slot_conflict");
const slot = hallopetraSlots[0] ?? null;
if (slot && dataById.get(slot.dataConnectionId)?.appId !== HALLOPETRA_APP_ID) {
throw new HalloPetraConnectError("slot_conflict");
}
// HalloPetra supports arbitrary headers but issues no native webhook secret.
// A separate high-entropy credential avoids reusing the provider API key.
const webhookSecret = randomBytes(32).toString("base64url");
const credentials = { apiKey, webhookSecret };
let dataConnectionId: string;
let createdFresh = false;
try {
if (slot) {
dataConnectionId = slot.dataConnectionId;
await reconnectConnection({
tenantId: input.tenantId,
connectionId: dataConnectionId,
expectedAppId: HALLOPETRA_APP_ID,
credentials,
actorUserId: input.userId,
});
} else {
const created = await createConnection({
tenantId: input.tenantId,
appId: HALLOPETRA_APP_ID,
label: HALLOPETRA_CONNECTION_LABEL,
credentials,
createdByUserId: input.userId,
});
dataConnectionId = created.id;
createdFresh = true;
}
} catch (error) {
if (error instanceof HalloPetraConnectError) throw error;
if (error instanceof AppsEngineServiceError && error.messageKey === "telephony.health.tokenInvalid") {
throw new HalloPetraConnectError("invalid_key");
}
throw new HalloPetraConnectError("persistence_failed");
}
try {
const telephonyConnection = await withTenantRLS(input.tenantId, (tx) =>
tx.telephonyConnection.upsert({
where: { tenantId_provider: { tenantId: input.tenantId, provider: "hallopetra" } },
create: {
tenantId: input.tenantId,
dataConnectionId,
provider: "hallopetra",
providerAccountName: HALLOPETRA_CONNECTION_LABEL,
webhookId: null,
webhookTokenHash: hashWebhookSecret(webhookSecret),
},
update: {
dataConnectionId,
providerAccountName: HALLOPETRA_CONNECTION_LABEL,
webhookId: null,
webhookTokenHash: hashWebhookSecret(webhookSecret),
},
select: { id: true },
})
);
return {
dataConnectionId,
telephonyConnectionId: telephonyConnection.id,
webhookSecret,
webhookUrl,
};
} catch {
if (createdFresh) {
await disconnectConnection({
tenantId: input.tenantId,
connectionId: dataConnectionId,
expectedAppId: HALLOPETRA_APP_ID,
actorUserId: input.userId,
}).catch(() => undefined);
} else {
await markConnectionBroken(input.tenantId, dataConnectionId);
}
throw new HalloPetraConnectError("persistence_failed");
}
}
export function halloPetraWebhookConfigured(): boolean {
try {
resolveWebhookUrl();
return true;
} catch {
return false;
}
}
function resolveWebhookUrl(): string {
const value = loadRequiredWebConfig().hallopetra?.webhookUrl?.trim();
if (!value) throw new HalloPetraConnectError("not_configured");
try {
const url = new URL(value);
const localHttp =
url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
if (url.protocol !== "https:" && !localHttp) {
throw new Error("HTTPS required");
}
return url.toString();
} catch {
throw new HalloPetraConnectError("not_configured");
}
}
function hashWebhookSecret(secret: string): string {
return createHash("sha256").update(secret, "utf8").digest("hex");
}
async function markConnectionBroken(tenantId: string, dataConnectionId: string): Promise<void> {
await withTenantRLS(tenantId, (tx) =>
tx.dataConnection.updateMany({
where: { id: dataConnectionId, tenantId, appId: HALLOPETRA_APP_ID },
data: {
connectionStatus: "broken",
healthMessageKey: "telephony.health.unknown",
lastHealthCheck: new Date(),
},
})
).catch(() => undefined);
}