284 lines
9.8 KiB
TypeScript
284 lines
9.8 KiB
TypeScript
import { createHash, createHmac, randomUUID } from "node:crypto";
|
|
|
|
import { decryptTenantField } from "@hivegrid/db/crypto/tenant-envelope.server";
|
|
import { getDbClient } from "@hivegrid/db/client.server";
|
|
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
|
import { resolveHalloPetraWebhookRlsIdentity } from "@hivegrid/db/rls-resolvers.server";
|
|
import { hallopetraTelephonyProvider, type TelephonyCallEvent } from "@hivegrid/integrations";
|
|
import {
|
|
TELEPHONY_WEBHOOK_QUEUE_NAME,
|
|
buildTelephonyWebhookJob,
|
|
enqueueTelephonyWebhookJob,
|
|
resolveRedisConnectionOptionsFromProcessEnv,
|
|
type TelephonyWebhookQueue,
|
|
} from "@hivegrid/queue";
|
|
import { createFixedWindowRateLimiter } from "@hivegrid/shared-store";
|
|
import type { Context } from "hono";
|
|
|
|
import type { ApiEnv } from "../api-types.js";
|
|
import { getSharedStore } from "../shared-store.js";
|
|
import { getTrustedClientIp } from "../trusted-client-ip.js";
|
|
|
|
const MAX_BODY_BYTES = 256 * 1_024;
|
|
const MAX_SECRET_BYTES = 2_048;
|
|
const RATE_LIMIT_WINDOW_SECONDS = 60;
|
|
const RATE_LIMIT_PER_CLIENT = 1_200;
|
|
const RATE_LIMIT_PER_CONNECTION = 600;
|
|
const SHA256_PATTERN = /^[a-f0-9]{64}$/u;
|
|
|
|
type AuthenticatedHalloPetraEvent = {
|
|
tenantId: string;
|
|
connectionId: string;
|
|
event: TelephonyCallEvent;
|
|
};
|
|
|
|
export type HalloPetraWebhookRouteDependencies = {
|
|
now(): Date;
|
|
checkClientRateLimit(request: Request): Promise<boolean>;
|
|
checkConnectionRateLimit(webhookTokenHash: string): Promise<boolean>;
|
|
authenticateAndNormalize(
|
|
webhookTokenHash: string,
|
|
webhookSecret: string,
|
|
receivedAtIso: string,
|
|
payload: unknown,
|
|
): Promise<AuthenticatedHalloPetraEvent | null>;
|
|
persistEvent(input: AuthenticatedHalloPetraEvent): Promise<{ eventId: string }>;
|
|
enqueue(input: { tenantId: string; connectionId: string; eventId: string }): Promise<void>;
|
|
};
|
|
|
|
function neutral(c: Context<ApiEnv>, status: 202 | 503 = 202) {
|
|
return c.body(null, status);
|
|
}
|
|
|
|
/** Public HalloPetra ingress. Responses never reveal tenant or secret state. */
|
|
export async function postHalloPetraWebhookRequest(
|
|
c: Context<ApiEnv>,
|
|
dependencies: HalloPetraWebhookRouteDependencies = defaultHalloPetraWebhookDependencies(),
|
|
) {
|
|
try {
|
|
if (!(await dependencies.checkClientRateLimit(c.req.raw))) return neutral(c, 503);
|
|
} catch {
|
|
return neutral(c, 503);
|
|
}
|
|
|
|
const webhookSecret = readBearerSecret(c.req.raw.headers.get("authorization"));
|
|
if (!webhookSecret) return neutral(c);
|
|
const webhookTokenHash = hashWebhookToken(webhookSecret);
|
|
|
|
try {
|
|
if (!(await dependencies.checkConnectionRateLimit(webhookTokenHash))) return neutral(c, 503);
|
|
} catch {
|
|
return neutral(c, 503);
|
|
}
|
|
|
|
const payload = await readBoundedJson(c.req.raw);
|
|
if (payload === null) return neutral(c);
|
|
|
|
let authenticated: AuthenticatedHalloPetraEvent | null;
|
|
try {
|
|
authenticated = await dependencies.authenticateAndNormalize(
|
|
webhookTokenHash,
|
|
webhookSecret,
|
|
dependencies.now().toISOString(),
|
|
payload,
|
|
);
|
|
} catch {
|
|
return neutral(c, 503);
|
|
}
|
|
if (!authenticated) return neutral(c);
|
|
|
|
try {
|
|
const persisted = await dependencies.persistEvent(authenticated);
|
|
await dependencies.enqueue({
|
|
tenantId: authenticated.tenantId,
|
|
connectionId: authenticated.connectionId,
|
|
eventId: persisted.eventId,
|
|
});
|
|
} catch {
|
|
return neutral(c, 503);
|
|
}
|
|
|
|
return neutral(c);
|
|
}
|
|
|
|
function defaultHalloPetraWebhookDependencies(): HalloPetraWebhookRouteDependencies {
|
|
return {
|
|
now: () => new Date(),
|
|
checkClientRateLimit: async (request) => {
|
|
const secret = process.env.CRYPTO_SECRET?.trim() || process.env.SESSION_SECRET?.trim();
|
|
if (!secret) throw new Error("HalloPetra webhook rate-limit key secret is unavailable.");
|
|
const clientKey = createHmac("sha256", secret)
|
|
.update(getTrustedClientIp(request) || "unknown", "utf8")
|
|
.digest("hex");
|
|
const limiter = createFixedWindowRateLimiter({
|
|
store: getSharedStore(),
|
|
prefix: "hallopetra-webhook-client",
|
|
windowSeconds: RATE_LIMIT_WINDOW_SECONDS,
|
|
max: RATE_LIMIT_PER_CLIENT,
|
|
});
|
|
return (await limiter.consume(clientKey)).allowed;
|
|
},
|
|
checkConnectionRateLimit: async (webhookTokenHash) => {
|
|
const limiter = createFixedWindowRateLimiter({
|
|
store: getSharedStore(),
|
|
prefix: "hallopetra-webhook-connection",
|
|
windowSeconds: RATE_LIMIT_WINDOW_SECONDS,
|
|
max: RATE_LIMIT_PER_CONNECTION,
|
|
});
|
|
return (await limiter.consume(webhookTokenHash)).allowed;
|
|
},
|
|
authenticateAndNormalize: authenticateAndNormalizeHalloPetraEvent,
|
|
persistEvent: persistHalloPetraEvent,
|
|
enqueue: enqueueHalloPetraEvent,
|
|
};
|
|
}
|
|
|
|
async function authenticateAndNormalizeHalloPetraEvent(
|
|
webhookTokenHash: string,
|
|
webhookSecret: string,
|
|
receivedAtIso: string,
|
|
payload: unknown,
|
|
): Promise<AuthenticatedHalloPetraEvent | null> {
|
|
if (!SHA256_PATTERN.test(webhookTokenHash)) return null;
|
|
const identity = await resolveHalloPetraWebhookRlsIdentity(webhookTokenHash);
|
|
if (!identity) return null;
|
|
|
|
return runWithRlsContext({ tenantId: identity.tenantId }, async () => {
|
|
const db = getDbClient();
|
|
const connection = await db.telephonyConnection.findFirst({
|
|
where: {
|
|
id: identity.resourceId,
|
|
tenantId: identity.tenantId,
|
|
provider: "hallopetra",
|
|
webhookTokenHash,
|
|
},
|
|
select: { id: true, dataConnectionId: true },
|
|
});
|
|
if (!connection) return null;
|
|
|
|
const dataConnection = await db.dataConnection.findFirst({
|
|
where: {
|
|
id: connection.dataConnectionId,
|
|
tenantId: identity.tenantId,
|
|
appId: "hallopetra",
|
|
archivedAt: null,
|
|
connectionStatus: { in: ["active", "degraded"] },
|
|
},
|
|
select: { credentialsCiphertext: true },
|
|
});
|
|
if (!dataConnection?.credentialsCiphertext) return null;
|
|
|
|
const plaintext = await decryptTenantField(identity.tenantId, dataConnection.credentialsCiphertext, {
|
|
client: db as never,
|
|
});
|
|
const credentials = parseCredentialRecord(plaintext);
|
|
const expectedSecret = typeof credentials.webhookSecret === "string" ? credentials.webhookSecret : "";
|
|
const normalized = hallopetraTelephonyProvider.normalizeWebhook(
|
|
{ token: webhookSecret, receivedAtIso, body: payload },
|
|
expectedSecret,
|
|
);
|
|
return normalized.ok
|
|
? { tenantId: identity.tenantId, connectionId: connection.id, event: normalized.event }
|
|
: null;
|
|
});
|
|
}
|
|
|
|
async function persistHalloPetraEvent(input: AuthenticatedHalloPetraEvent): Promise<{ eventId: string }> {
|
|
return runWithRlsContext({ tenantId: input.tenantId }, async () => {
|
|
const db = getDbClient();
|
|
const eventId = randomUUID();
|
|
const inserted = await db.telephonyWebhookEvent.createMany({
|
|
data: {
|
|
id: eventId,
|
|
tenantId: input.tenantId,
|
|
connectionId: input.connectionId,
|
|
eventType: input.event.providerEvent,
|
|
dedupeKey: input.event.dedupeKey,
|
|
authenticationValid: true,
|
|
notificationPayload: input.event as never,
|
|
processingStatus: "pending",
|
|
},
|
|
skipDuplicates: true,
|
|
});
|
|
if (inserted.count === 1) return { eventId };
|
|
|
|
const existing = await db.telephonyWebhookEvent.findUnique({
|
|
where: { tenantId_dedupeKey: { tenantId: input.tenantId, dedupeKey: input.event.dedupeKey } },
|
|
select: { id: true },
|
|
});
|
|
if (!existing) throw new Error("HalloPetra webhook idempotency conflict could not be re-read.");
|
|
return { eventId: existing.id };
|
|
});
|
|
}
|
|
|
|
async function enqueueHalloPetraEvent(input: { tenantId: string; connectionId: string; eventId: string }): Promise<void> {
|
|
const connection = resolveRedisConnectionOptionsFromProcessEnv();
|
|
if (!connection) throw new Error("HalloPetra webhook queue is unavailable.");
|
|
const queueRuntimeModule = "@hivegrid/queue/runtime";
|
|
const runtime = (await import(/* @vite-ignore */ queueRuntimeModule)) as unknown as {
|
|
createQueue(queueName: string, options: { connection: unknown }): TelephonyWebhookQueue;
|
|
};
|
|
const queue = runtime.createQueue(TELEPHONY_WEBHOOK_QUEUE_NAME, { connection });
|
|
try {
|
|
await enqueueTelephonyWebhookJob(
|
|
queue,
|
|
buildTelephonyWebhookJob({
|
|
tenantId: input.tenantId,
|
|
connectionId: input.connectionId,
|
|
webhookEventId: input.eventId,
|
|
}),
|
|
);
|
|
} finally {
|
|
await queue.close();
|
|
}
|
|
}
|
|
|
|
async function readBoundedJson(request: Request): Promise<unknown | null> {
|
|
const contentLength = request.headers.get("content-length");
|
|
if (contentLength !== null) {
|
|
const parsed = Number(contentLength);
|
|
if (!Number.isSafeInteger(parsed) || parsed < 0 || parsed > MAX_BODY_BYTES) return null;
|
|
}
|
|
if (!request.body) return null;
|
|
|
|
const reader = request.body.getReader();
|
|
const decoder = new TextDecoder();
|
|
let totalBytes = 0;
|
|
let text = "";
|
|
try {
|
|
while (true) {
|
|
const { done, value } = await reader.read();
|
|
if (done) break;
|
|
totalBytes += value.byteLength;
|
|
if (totalBytes > MAX_BODY_BYTES) {
|
|
await reader.cancel();
|
|
return null;
|
|
}
|
|
text += decoder.decode(value, { stream: true });
|
|
}
|
|
text += decoder.decode();
|
|
return JSON.parse(text) as unknown;
|
|
} catch {
|
|
return null;
|
|
} finally {
|
|
reader.releaseLock();
|
|
}
|
|
}
|
|
|
|
function readBearerSecret(header: string | null): string | null {
|
|
if (!header) return null;
|
|
const match = /^Bearer ([^\s]+)$/iu.exec(header.trim());
|
|
if (!match?.[1] || Buffer.byteLength(match[1], "utf8") > MAX_SECRET_BYTES) return null;
|
|
return match[1];
|
|
}
|
|
|
|
function hashWebhookToken(token: string): string {
|
|
return createHash("sha256").update(token, "utf8").digest("hex");
|
|
}
|
|
|
|
function parseCredentialRecord(plaintext: string): Record<string, unknown> {
|
|
const value = JSON.parse(plaintext) as unknown;
|
|
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("HalloPetra credentials are invalid.");
|
|
return value as Record<string, unknown>;
|
|
}
|