266 lines
9.7 KiB
TypeScript
266 lines
9.7 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 { resolveAircallWebhookRlsIdentity } from "@hivegrid/db/rls-resolvers.server";
|
|
import { aircallTelephonyProvider, 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_TOKEN_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 AuthenticatedAircallEvent = {
|
|
tenantId: string;
|
|
connectionId: string;
|
|
event: TelephonyCallEvent;
|
|
};
|
|
|
|
export type AircallWebhookRouteDependencies = {
|
|
checkClientRateLimit(request: Request): Promise<boolean>;
|
|
checkConnectionRateLimit(webhookTokenHash: string): Promise<boolean>;
|
|
authenticateAndNormalize(webhookTokenHash: string, payload: unknown): Promise<AuthenticatedAircallEvent | null>;
|
|
persistEvent(input: AuthenticatedAircallEvent): 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 Aircall ingress. Responses never reveal tenant or credential state. */
|
|
export async function postAircallWebhookRequest(
|
|
c: Context<ApiEnv>,
|
|
dependencies: AircallWebhookRouteDependencies = defaultAircallWebhookDependencies(),
|
|
) {
|
|
try {
|
|
// Aircall treats every 2xx response as accepted. A throttled, otherwise
|
|
// valid delivery must remain retryable instead of being lost silently.
|
|
if (!(await dependencies.checkClientRateLimit(c.req.raw))) return neutral(c, 503);
|
|
} catch {
|
|
return neutral(c, 503);
|
|
}
|
|
|
|
const payload = await readBoundedJson(c.req.raw);
|
|
const token = readWebhookToken(payload);
|
|
if (!token) return neutral(c);
|
|
const webhookTokenHash = hashWebhookToken(token);
|
|
|
|
try {
|
|
if (!(await dependencies.checkConnectionRateLimit(webhookTokenHash))) return neutral(c, 503);
|
|
} catch {
|
|
return neutral(c, 503);
|
|
}
|
|
|
|
let authenticated: AuthenticatedAircallEvent | null;
|
|
try {
|
|
authenticated = await dependencies.authenticateAndNormalize(webhookTokenHash, 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 {
|
|
// Aircall retries non-2xx responses. Persistence is idempotent, so a retry
|
|
// can safely enqueue an event that survived a temporary queue outage.
|
|
return neutral(c, 503);
|
|
}
|
|
|
|
return neutral(c);
|
|
}
|
|
|
|
function defaultAircallWebhookDependencies(): AircallWebhookRouteDependencies {
|
|
return {
|
|
checkClientRateLimit: async (request) => {
|
|
const secret = process.env.CRYPTO_SECRET?.trim() || process.env.SESSION_SECRET?.trim();
|
|
if (!secret) throw new Error("Aircall 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: "aircall-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: "aircall-webhook-connection",
|
|
windowSeconds: RATE_LIMIT_WINDOW_SECONDS,
|
|
max: RATE_LIMIT_PER_CONNECTION,
|
|
});
|
|
return (await limiter.consume(webhookTokenHash)).allowed;
|
|
},
|
|
authenticateAndNormalize: authenticateAndNormalizeAircallEvent,
|
|
persistEvent: persistAircallEvent,
|
|
enqueue: enqueueAircallEvent,
|
|
};
|
|
}
|
|
|
|
async function authenticateAndNormalizeAircallEvent(webhookTokenHash: string, payload: unknown): Promise<AuthenticatedAircallEvent | null> {
|
|
if (!SHA256_PATTERN.test(webhookTokenHash)) return null;
|
|
const identity = await resolveAircallWebhookRlsIdentity(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: "aircall",
|
|
webhookTokenHash,
|
|
},
|
|
select: { id: true, dataConnectionId: true },
|
|
});
|
|
if (!connection) return null;
|
|
|
|
const dataConnection = await db.dataConnection.findFirst({
|
|
where: {
|
|
id: connection.dataConnectionId,
|
|
tenantId: identity.tenantId,
|
|
appId: "aircall",
|
|
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 expectedToken = typeof credentials.webhookToken === "string" ? credentials.webhookToken : "";
|
|
const normalized = aircallTelephonyProvider.normalizeWebhook(payload, expectedToken);
|
|
return normalized.ok
|
|
? { tenantId: identity.tenantId, connectionId: connection.id, event: normalized.event }
|
|
: null;
|
|
});
|
|
}
|
|
|
|
async function persistAircallEvent(input: AuthenticatedAircallEvent): 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("Aircall webhook idempotency conflict could not be re-read.");
|
|
return { eventId: existing.id };
|
|
});
|
|
}
|
|
|
|
async function enqueueAircallEvent(input: { tenantId: string; connectionId: string; eventId: string }): Promise<void> {
|
|
const connection = resolveRedisConnectionOptionsFromProcessEnv();
|
|
if (!connection) throw new Error("Aircall 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 readWebhookToken(payload: unknown): string | null {
|
|
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return null;
|
|
const token = (payload as Record<string, unknown>).token;
|
|
if (typeof token !== "string" || token.length === 0 || Buffer.byteLength(token, "utf8") > MAX_TOKEN_BYTES) return null;
|
|
return token;
|
|
}
|
|
|
|
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("Aircall credentials are invalid.");
|
|
return value as Record<string, unknown>;
|
|
}
|