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,327 @@
import { createHash } from "node:crypto";
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
loadRequiredWebConfig: vi.fn(),
getRlsExecutionContext: vi.fn(),
buildAircallAuthorizationUrl: vi.fn(),
createAircallWebhook: vi.fn(),
deleteAircallWebhook: vi.fn(),
exchangeAircallCodeForToken: vi.fn(),
listAircallUsers: vi.fn(),
pingAircall: vi.fn(),
resolveAircallOAuthConfig: vi.fn(),
reconnectConnection: vi.fn(),
runWithConnectionCredentials: vi.fn(),
tx: {
dataConnection: {
create: vi.fn(),
findFirst: vi.fn(),
findMany: vi.fn(),
updateMany: vi.fn(),
},
telephonyConnection: {
create: vi.fn(),
findMany: vi.fn(),
findUnique: vi.fn(),
upsert: vi.fn(),
},
telephonyUserBinding: {
createMany: vi.fn(),
deleteMany: vi.fn(),
findMany: vi.fn(),
},
tenantUser: {
findMany: vi.fn(),
},
},
}));
vi.mock("@hivegrid/config", () => ({ loadRequiredWebConfig: mocks.loadRequiredWebConfig }));
vi.mock("@hivegrid/db/rls-context.server", () => ({ getRlsExecutionContext: mocks.getRlsExecutionContext }));
vi.mock("@hivegrid/integrations", () => ({
AIRCALL_CALL_WEBHOOK_EVENTS: ["call.created", "call.ended"],
buildAircallAuthorizationUrl: mocks.buildAircallAuthorizationUrl,
createAircallWebhook: mocks.createAircallWebhook,
deleteAircallWebhook: mocks.deleteAircallWebhook,
exchangeAircallCodeForToken: mocks.exchangeAircallCodeForToken,
listAircallUsers: mocks.listAircallUsers,
pingAircall: mocks.pingAircall,
resolveAircallOAuthConfig: mocks.resolveAircallOAuthConfig,
}));
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
withTenantRLS: (_tenantId: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => callback(mocks.tx),
}));
vi.mock("~/utils/integrations/appsEngineService.server", () => ({
reconnectConnection: mocks.reconnectConnection,
runWithConnectionCredentials: mocks.runWithConnectionCredentials,
}));
import { AircallConnectError, buildAircallInstallUrl, completeAircallOAuthCallback } from "./AircallConnectionService.server";
import { signAircallOAuthState, verifyAircallOAuthState } from "./aircallOAuthState.server";
const TENANT_ID = "tenant-1";
const USER_ID = "user-1";
const DATA_CONNECTION_ID = "data-connection-1";
const TELEPHONY_CONNECTION_ID = "telephony-connection-1";
const STATE_SECRET = "aircall-state-secret-for-tests";
beforeEach(() => {
vi.clearAllMocks();
mocks.loadRequiredWebConfig.mockReturnValue({
appName: "HiveGrid",
cryptoSecret: STATE_SECRET,
sessionSecret: "session-secret",
aircall: {
clientId: "aircall-client",
clientSecret: "aircall-client-secret",
redirectUri: "https://app.example.test/integrations/aircall/oauth/callback",
webhookUrl: "https://api.example.test/v1/webhooks/telephony/aircall",
},
});
mocks.resolveAircallOAuthConfig.mockReturnValue({
clientId: "aircall-client",
clientSecret: "aircall-client-secret",
redirectUri: "https://app.example.test/integrations/aircall/oauth/callback",
});
mocks.buildAircallAuthorizationUrl.mockImplementation(
(_config: unknown, state: string) => `https://dashboard.aircall.test/oauth/authorize?state=${encodeURIComponent(state)}`
);
mocks.getRlsExecutionContext.mockReturnValue({ tenantId: TENANT_ID, userId: USER_ID });
mocks.tx.telephonyConnection.findUnique.mockResolvedValue({
id: TELEPHONY_CONNECTION_ID,
dataConnectionId: DATA_CONNECTION_ID,
webhookId: "old-webhook-id",
});
mocks.tx.telephonyConnection.findMany.mockResolvedValue([]);
mocks.tx.dataConnection.findMany.mockResolvedValue([{ id: DATA_CONNECTION_ID, connectionStatus: "active" }]);
mocks.tx.dataConnection.findFirst.mockResolvedValue({ connectionStatus: "active" });
mocks.tx.telephonyConnection.upsert.mockResolvedValue({ id: TELEPHONY_CONNECTION_ID });
mocks.tx.telephonyUserBinding.findMany.mockResolvedValue([{ tenantUserId: "membership-manual", providerUserId: "aircall-manual" }]);
mocks.tx.tenantUser.findMany.mockResolvedValue([
{ id: "membership-auto", user: { email: "Ada@Example.test" } },
{ id: "membership-manual", user: { email: "manual@example.test" } },
]);
mocks.tx.telephonyUserBinding.deleteMany.mockResolvedValue({ count: 0 });
mocks.tx.telephonyUserBinding.createMany.mockResolvedValue({ count: 1 });
mocks.tx.dataConnection.updateMany.mockResolvedValue({ count: 1 });
mocks.exchangeAircallCodeForToken.mockResolvedValue({ accessToken: "new-permanent-access-token" });
mocks.pingAircall.mockResolvedValue(undefined);
mocks.listAircallUsers.mockResolvedValue([
{
id: "aircall-auto",
name: "Ada Agent",
email: "ada@example.test",
available: true,
availabilityStatus: "available",
defaultNumberId: "number-1",
},
{
id: "aircall-manual",
name: "Manual Agent",
email: "manual@example.test",
available: true,
availabilityStatus: "available",
defaultNumberId: null,
},
]);
mocks.createAircallWebhook.mockResolvedValue({
id: "new-webhook-id",
token: "raw-new-webhook-token",
active: true,
events: ["call.created", "call.ended"],
});
mocks.reconnectConnection.mockResolvedValue(undefined);
mocks.deleteAircallWebhook.mockResolvedValue(undefined);
mocks.runWithConnectionCredentials.mockImplementation(async (_input: unknown, callback: (credentials: Record<string, unknown>) => Promise<unknown>) =>
callback({ accessToken: "old-permanent-access-token", webhookToken: "raw-old-webhook-token" })
);
});
describe("Aircall connection lifecycle", () => {
it("reuses the tenant slot and binds it into the signed install state", async () => {
const authorizationUrl = await buildAircallInstallUrl({
tenantId: TENANT_ID,
tenantSlug: "acme",
userId: USER_ID,
});
const state = new URL(authorizationUrl).searchParams.get("state");
expect(state).toBeTruthy();
expect(verifyAircallOAuthState(state!, { secret: STATE_SECRET })).toMatchObject({
ok: true,
payload: {
tenantId: TENANT_ID,
tenantSlug: "acme",
userId: USER_ID,
connectionId: DATA_CONNECTION_ID,
},
});
expect(mocks.tx.dataConnection.create).not.toHaveBeenCalled();
});
it("creates one pending Apps Engine slot when the tenant has none", async () => {
mocks.tx.telephonyConnection.findUnique.mockResolvedValueOnce(null);
mocks.tx.dataConnection.findMany.mockResolvedValueOnce([]);
mocks.tx.dataConnection.create.mockResolvedValueOnce({ id: DATA_CONNECTION_ID, connectionStatus: "pending" });
mocks.tx.telephonyConnection.create.mockResolvedValueOnce({ id: TELEPHONY_CONNECTION_ID });
await buildAircallInstallUrl({ tenantId: TENANT_ID, tenantSlug: "acme", userId: USER_ID });
expect(mocks.tx.dataConnection.create).toHaveBeenCalledWith({
data: expect.objectContaining({
tenantId: TENANT_ID,
appId: "aircall",
connectionStatus: "pending",
createdByUserId: USER_ID,
}),
select: { id: true, connectionStatus: true },
});
expect(mocks.tx.telephonyConnection.create).toHaveBeenCalledWith({
data: { tenantId: TENANT_ID, provider: "aircall", dataConnectionId: DATA_CONNECTION_ID },
select: { id: true },
});
});
it("stores secrets only through DataConnection and auto-binds unique email matches", async () => {
const state = signAircallOAuthState({
tenantId: TENANT_ID,
tenantSlug: "acme",
userId: USER_ID,
connectionId: DATA_CONNECTION_ID,
});
await expect(completeAircallOAuthCallback({ code: "one-time-code", state })).resolves.toEqual({
tenantId: TENANT_ID,
tenantSlug: "acme",
dataConnectionId: DATA_CONNECTION_ID,
telephonyConnectionId: TELEPHONY_CONNECTION_ID,
providerUserCount: 2,
autoBoundUserCount: 1,
});
expect(mocks.reconnectConnection).toHaveBeenCalledWith({
tenantId: TENANT_ID,
connectionId: DATA_CONNECTION_ID,
expectedAppId: "aircall",
actorUserId: USER_ID,
credentials: {
accessToken: "new-permanent-access-token",
webhookToken: "raw-new-webhook-token",
},
});
expect(mocks.pingAircall).toHaveBeenCalledWith({ accessToken: "new-permanent-access-token" });
expect(mocks.createAircallWebhook).toHaveBeenCalledWith(
{ accessToken: "new-permanent-access-token" },
{
name: "HiveGrid",
url: "https://api.example.test/v1/webhooks/telephony/aircall",
events: ["call.created", "call.ended"],
}
);
expect(mocks.reconnectConnection.mock.calls[0]?.[0].credentials).not.toHaveProperty("refreshToken");
const upsertInput = mocks.tx.telephonyConnection.upsert.mock.calls[0]?.[0];
const expectedHash = createHash("sha256").update("raw-new-webhook-token", "utf8").digest("hex");
expect(upsertInput).toMatchObject({
update: { dataConnectionId: DATA_CONNECTION_ID, webhookId: "new-webhook-id", webhookTokenHash: expectedHash },
});
expect(JSON.stringify(upsertInput)).not.toContain("raw-new-webhook-token");
expect(JSON.stringify(upsertInput)).not.toContain("new-permanent-access-token");
expect(mocks.tx.telephonyUserBinding.createMany).toHaveBeenCalledWith({
data: [
expect.objectContaining({
tenantId: TENANT_ID,
connectionId: TELEPHONY_CONNECTION_ID,
tenantUserId: "membership-auto",
providerUserId: "aircall-auto",
providerEmail: "ada@example.test",
source: "email_auto",
}),
],
skipDuplicates: true,
});
expect(mocks.deleteAircallWebhook).toHaveBeenCalledWith({ accessToken: "old-permanent-access-token" }, "old-webhook-id");
});
it("rejects a callback outside the state-bound RLS identity before exchange", async () => {
mocks.getRlsExecutionContext.mockReturnValue({ tenantId: TENANT_ID, userId: "different-user" });
const state = signAircallOAuthState({
tenantId: TENANT_ID,
tenantSlug: "acme",
userId: USER_ID,
connectionId: DATA_CONNECTION_ID,
});
await expect(completeAircallOAuthCallback({ code: "one-time-code", state })).rejects.toEqual(
expect.objectContaining<Partial<AircallConnectError>>({ code: "invalid_state" })
);
expect(mocks.exchangeAircallCodeForToken).not.toHaveBeenCalled();
});
it("deletes a newly-created webhook if encrypted credential persistence fails", async () => {
mocks.tx.dataConnection.findFirst.mockResolvedValue({ connectionStatus: "pending" });
mocks.reconnectConnection.mockRejectedValue(new Error("database unavailable"));
const state = signAircallOAuthState({
tenantId: TENANT_ID,
tenantSlug: "acme",
userId: USER_ID,
connectionId: DATA_CONNECTION_ID,
});
await expect(completeAircallOAuthCallback({ code: "one-time-code", state })).rejects.toEqual(
expect.objectContaining<Partial<AircallConnectError>>({ code: "persistence_failed" })
);
expect(mocks.runWithConnectionCredentials).not.toHaveBeenCalled();
expect(mocks.deleteAircallWebhook).toHaveBeenCalledWith({ accessToken: "new-permanent-access-token" }, "new-webhook-id");
});
it("marks a successful reinstall degraded when the previous webhook cannot be removed", async () => {
mocks.deleteAircallWebhook.mockRejectedValueOnce(new Error("provider unavailable"));
const state = signAircallOAuthState({
tenantId: TENANT_ID,
tenantSlug: "acme",
userId: USER_ID,
connectionId: DATA_CONNECTION_ID,
});
await expect(completeAircallOAuthCallback({ code: "one-time-code", state })).rejects.toEqual(
expect.objectContaining<Partial<AircallConnectError>>({ code: "webhook_failed" })
);
expect(mocks.deleteAircallWebhook).toHaveBeenCalledWith({ accessToken: "old-permanent-access-token" }, "old-webhook-id");
expect(mocks.tx.dataConnection.updateMany).toHaveBeenCalledWith({
where: { id: DATA_CONNECTION_ID, tenantId: TENANT_ID, appId: "aircall" },
data: {
connectionStatus: "degraded",
healthMessageKey: "telephony.health.staleWebhookCleanupFailed",
lastHealthCheck: expect.any(Date),
},
});
});
it("stops when legacy data already contains multiple Aircall slots", async () => {
mocks.tx.telephonyConnection.findUnique.mockResolvedValueOnce(null);
mocks.tx.dataConnection.findMany.mockResolvedValueOnce([
{ id: "slot-1", connectionStatus: "active" },
{ id: "slot-2", connectionStatus: "revoked" },
]);
await expect(buildAircallInstallUrl({ tenantId: TENANT_ID, tenantSlug: "acme", userId: USER_ID })).rejects.toEqual(
expect.objectContaining<Partial<AircallConnectError>>({ code: "slot_conflict" })
);
expect(mocks.buildAircallAuthorizationUrl).not.toHaveBeenCalled();
});
it("requires the active HalloPetra provider to be disconnected before Aircall OAuth starts", async () => {
mocks.tx.telephonyConnection.findMany.mockResolvedValueOnce([{ dataConnectionId: "hallopetra-data-1" }]);
mocks.tx.dataConnection.findFirst.mockResolvedValueOnce({ id: "hallopetra-data-1" });
await expect(buildAircallInstallUrl({ tenantId: TENANT_ID, tenantSlug: "acme", userId: USER_ID })).rejects.toEqual(
expect.objectContaining<Partial<AircallConnectError>>({ code: "provider_conflict" }),
);
expect(mocks.buildAircallAuthorizationUrl).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,464 @@
import { createHash } from "node:crypto";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
import {
AIRCALL_CALL_WEBHOOK_EVENTS,
buildAircallAuthorizationUrl,
createAircallWebhook,
deleteAircallWebhook,
exchangeAircallCodeForToken,
listAircallUsers,
pingAircall,
resolveAircallOAuthConfig,
type AircallOAuthConfig,
type TelephonyProviderUser,
} from "@hivegrid/integrations";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
import { reconnectConnection, runWithConnectionCredentials } from "~/utils/integrations/appsEngineService.server";
import { signAircallOAuthState, verifyAircallOAuthState, type AircallOAuthStatePayload } from "./aircallOAuthState.server";
const AIRCALL_APP_ID = "aircall";
const AIRCALL_CONNECTION_LABEL = "Aircall";
type AircallConnectionStatus = "pending" | "active" | "degraded" | "broken" | "revoked";
type AircallSlot = {
readonly telephonyConnectionId: string;
readonly dataConnectionId: string;
readonly connectionStatus: AircallConnectionStatus;
readonly webhookId: string | null;
};
type AircallRuntimeConfig = {
readonly oauth: AircallOAuthConfig;
readonly webhookUrl: string;
readonly webhookName: string;
};
type PreviousCredentials = {
readonly accessToken: string;
};
export class AircallConnectError extends Error {
readonly code:
| "not_configured"
| "invalid_state"
| "provider_conflict"
| "slot_conflict"
| "exchange_failed"
| "webhook_failed"
| "persistence_failed";
constructor(code: AircallConnectError["code"]) {
super(code);
this.name = "AircallConnectError";
this.code = code;
}
}
export type AircallConnectResult = {
readonly tenantId: string;
readonly tenantSlug: string;
readonly dataConnectionId: string;
readonly telephonyConnectionId: string;
readonly providerUserCount: number;
readonly autoBoundUserCount: number;
};
export function aircallOAuthConfigured(): boolean {
try {
resolveRuntimeConfig();
return true;
} catch {
return false;
}
}
/** Reserve/reuse the tenant's only Aircall slot and build a fresh install URL. */
export async function buildAircallInstallUrl(input: { tenantId: string; tenantSlug: string; userId: string }): Promise<string> {
const config = resolveRuntimeConfig();
const slot = await ensureAircallSlot(input.tenantId, input.userId);
const state = signAircallOAuthState({
tenantId: input.tenantId,
tenantSlug: input.tenantSlug,
userId: input.userId,
connectionId: slot.dataConnectionId,
});
return buildAircallAuthorizationUrl(config.oauth, state);
}
/**
* Complete a fresh install or reinstall. Aircall has no refresh/revoke-token
* endpoint: reinstallation replaces the permanent token and its webhook.
*/
export async function completeAircallOAuthCallback(input: { code: string; state: string }): Promise<AircallConnectResult> {
const verified = verifyAircallOAuthState(input.state);
if (!verified.ok) throw new AircallConnectError("invalid_state");
const payload = verified.payload;
const rlsContext = getRlsExecutionContext();
if (rlsContext?.tenantId !== payload.tenantId || rlsContext.userId !== payload.userId) {
throw new AircallConnectError("invalid_state");
}
const config = resolveRuntimeConfig();
const slot = await readAircallSlot(payload.tenantId, payload.connectionId);
if (!slot) throw new AircallConnectError("invalid_state");
if (slot.connectionStatus === "active" || slot.connectionStatus === "degraded") {
let callbackStarted = false;
try {
return await runWithConnectionCredentials(
{
tenantId: payload.tenantId,
connectionId: slot.dataConnectionId,
expectedAppId: AIRCALL_APP_ID,
},
async (credentials) => {
callbackStarted = true;
return finishAircallInstall({ input, config, slot, payload, previousCredentials: parsePreviousCredentials(credentials) });
}
);
} catch (error) {
// An inconsistent legacy slot may have no decryptable credentials. That
// must not prevent a fresh OAuth install from repairing it. Errors after
// provider setup began are never retried here.
if (callbackStarted) throw error;
}
}
return finishAircallInstall({ input, config, slot, payload, previousCredentials: null });
}
async function finishAircallInstall(input: {
readonly input: { readonly code: string; readonly state: string };
readonly config: AircallRuntimeConfig;
readonly slot: AircallSlot;
readonly payload: AircallOAuthStatePayload;
readonly previousCredentials: PreviousCredentials | null;
}): Promise<AircallConnectResult> {
let accessToken: string;
let providerUsers: readonly TelephonyProviderUser[];
try {
const tokenSet = await exchangeAircallCodeForToken(input.config.oauth, input.input.code);
accessToken = tokenSet.accessToken;
await pingAircall({ accessToken });
// A successful company-wide User V2 read proves that the consent granted
// the public_api scope. Aircall itself restricts installation to company admins.
providerUsers = await listAircallUsers({ accessToken });
} catch {
throw new AircallConnectError("exchange_failed");
}
let webhook: Awaited<ReturnType<typeof createAircallWebhook>>;
try {
webhook = await createAircallWebhook(
{ accessToken },
{
name: input.config.webhookName,
url: input.config.webhookUrl,
events: AIRCALL_CALL_WEBHOOK_EVENTS,
}
);
} catch {
throw new AircallConnectError("webhook_failed");
}
const credentials = { accessToken, webhookToken: webhook.token } satisfies Record<string, unknown>;
try {
await reconnectConnection({
tenantId: input.payload.tenantId,
connectionId: input.slot.dataConnectionId,
expectedAppId: AIRCALL_APP_ID,
credentials,
actorUserId: input.payload.userId,
});
} catch {
await deleteAircallWebhook({ accessToken }, webhook.id).catch(() => undefined);
throw new AircallConnectError("persistence_failed");
}
const webhookTokenHash = hashWebhookToken(webhook.token);
let persisted: { readonly telephonyConnectionId: string; readonly autoBoundUserCount: number };
try {
persisted = await withTenantRLS(input.payload.tenantId, async (tx) => {
const connection = await tx.telephonyConnection.upsert({
where: { tenantId_provider: { tenantId: input.payload.tenantId, provider: "aircall" } },
create: {
tenantId: input.payload.tenantId,
dataConnectionId: input.slot.dataConnectionId,
provider: "aircall",
webhookId: webhook.id,
webhookTokenHash,
},
update: {
dataConnectionId: input.slot.dataConnectionId,
webhookId: webhook.id,
webhookTokenHash,
},
select: { id: true },
});
const autoBoundUserCount = await replaceAutomaticBindings({
tx,
tenantId: input.payload.tenantId,
connectionId: connection.id,
providerUsers,
});
return { telephonyConnectionId: connection.id, autoBoundUserCount };
});
} catch {
await Promise.all([
deleteAircallWebhook({ accessToken }, webhook.id).catch(() => undefined),
markConnectionBroken(input.payload.tenantId, input.slot.dataConnectionId),
]);
throw new AircallConnectError("persistence_failed");
}
if (input.previousCredentials && input.slot.webhookId && input.slot.webhookId !== webhook.id) {
try {
await deleteAircallWebhook({ accessToken: input.previousCredentials.accessToken }, input.slot.webhookId);
} catch {
// The new connection is already usable. Surface the stale provider
// webhook explicitly instead of reporting a clean reinstall while an
// unmanaged webhook keeps delivering events. A durable cleanup retry
// would require a dedicated provider-operation outbox.
await markConnectionDegraded(input.payload.tenantId, input.slot.dataConnectionId);
throw new AircallConnectError("webhook_failed");
}
}
return {
tenantId: input.payload.tenantId,
tenantSlug: input.payload.tenantSlug,
dataConnectionId: input.slot.dataConnectionId,
telephonyConnectionId: persisted.telephonyConnectionId,
providerUserCount: providerUsers.length,
autoBoundUserCount: persisted.autoBoundUserCount,
};
}
async function ensureAircallSlot(tenantId: string, actorUserId: string): Promise<AircallSlot> {
try {
return await withTenantRLS(tenantId, async (tx) => {
const [telephony, candidates, otherProviderSlots] = await Promise.all([
tx.telephonyConnection.findUnique({
where: { tenantId_provider: { tenantId, provider: "aircall" } },
select: { id: true, dataConnectionId: true, webhookId: true },
}),
tx.dataConnection.findMany({
where: { tenantId, appId: AIRCALL_APP_ID },
select: { id: true, connectionStatus: true },
orderBy: { createdAt: "asc" },
take: 2,
}),
tx.telephonyConnection.findMany({
where: { tenantId, provider: { not: "aircall" } },
select: { dataConnectionId: true },
}),
]);
if (otherProviderSlots.length > 0) {
const activeOtherProvider = await tx.dataConnection.findFirst({
where: {
tenantId,
id: { in: otherProviderSlots.map((slot) => slot.dataConnectionId) },
connectionStatus: { in: ["pending", "active", "degraded"] },
archivedAt: null,
},
select: { id: true },
});
if (activeOtherProvider) throw new AircallConnectError("provider_conflict");
}
if (candidates.length > 1 || (telephony && candidates.some((candidate) => candidate.id !== telephony.dataConnectionId))) {
throw new AircallConnectError("slot_conflict");
}
if (telephony) {
const dataConnection = candidates.find((candidate) => candidate.id === telephony.dataConnectionId);
if (!dataConnection) throw new AircallConnectError("slot_conflict");
return {
telephonyConnectionId: telephony.id,
dataConnectionId: telephony.dataConnectionId,
connectionStatus: dataConnection.connectionStatus,
webhookId: telephony.webhookId,
};
}
const dataConnection =
candidates[0] ??
(await tx.dataConnection.create({
data: {
tenantId,
appId: AIRCALL_APP_ID,
label: AIRCALL_CONNECTION_LABEL,
connectionStatus: "pending",
healthMessageKey: "integrations.health.notConnected",
createdByUserId: actorUserId,
},
select: { id: true, connectionStatus: true },
}));
const created = await tx.telephonyConnection.create({
data: { tenantId, provider: "aircall", dataConnectionId: dataConnection.id },
select: { id: true },
});
return {
telephonyConnectionId: created.id,
dataConnectionId: dataConnection.id,
connectionStatus: dataConnection.connectionStatus,
webhookId: null,
};
});
} catch (error) {
if (error instanceof AircallConnectError) throw error;
// A concurrent admin may have won the unique (tenant, provider) insert.
// Re-read the canonical slot; the losing DataConnection insert rolled back.
const concurrentSlot = await readAircallSlotForTenant(tenantId);
if (concurrentSlot) return concurrentSlot;
throw error;
}
}
async function readAircallSlot(tenantId: string, dataConnectionId: string): Promise<AircallSlot | null> {
const slot = await readAircallSlotForTenant(tenantId);
return slot?.dataConnectionId === dataConnectionId ? slot : null;
}
async function readAircallSlotForTenant(tenantId: string): Promise<AircallSlot | null> {
return withTenantRLS(tenantId, async (tx) => {
const telephony = await tx.telephonyConnection.findUnique({
where: { tenantId_provider: { tenantId, provider: "aircall" } },
select: { id: true, dataConnectionId: true, webhookId: true },
});
if (!telephony) return null;
const dataConnection = await tx.dataConnection.findFirst({
where: { id: telephony.dataConnectionId, tenantId, appId: AIRCALL_APP_ID },
select: { connectionStatus: true },
});
if (!dataConnection) return null;
return {
telephonyConnectionId: telephony.id,
dataConnectionId: telephony.dataConnectionId,
connectionStatus: dataConnection.connectionStatus,
webhookId: telephony.webhookId,
};
});
}
async function replaceAutomaticBindings(input: {
readonly tx: TenantRlsClient;
readonly tenantId: string;
readonly connectionId: string;
readonly providerUsers: readonly TelephonyProviderUser[];
}): Promise<number> {
const [memberships, manualBindings] = await Promise.all([
input.tx.tenantUser.findMany({
where: {
tenantId: input.tenantId,
status: TenantUserStatus.ACTIVE,
user: { active: true },
},
select: { id: true, user: { select: { email: true } } },
}),
input.tx.telephonyUserBinding.findMany({
where: { tenantId: input.tenantId, connectionId: input.connectionId, source: "manual" },
select: { tenantUserId: true, providerUserId: true },
}),
]);
const manualTenantUsers = new Set(manualBindings.map((binding) => binding.tenantUserId));
const manualProviderUsers = new Set(manualBindings.map((binding) => binding.providerUserId));
const tenantByEmail = uniqueByEmail(memberships.map((membership) => ({ email: membership.user.email, value: membership.id })));
const providerByEmail = uniqueByEmail(input.providerUsers.map((providerUser) => ({ email: providerUser.email, value: providerUser })));
const automaticBindings = [...providerByEmail.entries()]
.map(([email, providerUser]) => {
const tenantUserId = tenantByEmail.get(email);
if (!tenantUserId || manualTenantUsers.has(tenantUserId) || manualProviderUsers.has(providerUser.id)) return null;
return {
tenantId: input.tenantId,
connectionId: input.connectionId,
tenantUserId,
providerUserId: providerUser.id,
providerEmail: email,
providerDisplayName: providerUser.name,
defaultProviderNumberId: providerUser.defaultNumberId,
source: "email_auto" as const,
};
})
.filter(isPresent);
await input.tx.telephonyUserBinding.deleteMany({
where: { tenantId: input.tenantId, connectionId: input.connectionId, source: "email_auto" },
});
if (automaticBindings.length > 0) {
await input.tx.telephonyUserBinding.createMany({ data: automaticBindings, skipDuplicates: true });
}
return automaticBindings.length;
}
function uniqueByEmail<T>(rows: readonly { readonly email: string; readonly value: T }[]): Map<string, T> {
const values = new Map<string, T>();
const duplicates = new Set<string>();
for (const row of rows) {
const email = row.email.trim().toLowerCase();
if (!email || duplicates.has(email)) continue;
if (values.has(email)) {
values.delete(email);
duplicates.add(email);
} else {
values.set(email, row.value);
}
}
return values;
}
function parsePreviousCredentials(credentials: Readonly<Record<string, unknown>>): PreviousCredentials | null {
const accessToken = typeof credentials.accessToken === "string" ? credentials.accessToken.trim() : "";
return accessToken ? { accessToken } : null;
}
function resolveRuntimeConfig(): AircallRuntimeConfig {
const webConfig = loadRequiredWebConfig();
const aircall = webConfig.aircall;
const oauth = resolveAircallOAuthConfig({
AIRCALL_CLIENT_ID: aircall?.clientId,
AIRCALL_CLIENT_SECRET: aircall?.clientSecret,
AIRCALL_REDIRECT_URI: aircall?.redirectUri,
});
const webhookUrl = aircall?.webhookUrl?.trim();
if (!oauth || !webhookUrl) throw new AircallConnectError("not_configured");
return { oauth, webhookUrl, webhookName: webConfig.appName };
}
function hashWebhookToken(token: string): string {
return createHash("sha256").update(token, "utf8").digest("hex");
}
async function markConnectionBroken(tenantId: string, dataConnectionId: string): Promise<void> {
await withTenantRLS(tenantId, (tx) =>
tx.dataConnection.updateMany({
where: { id: dataConnectionId, tenantId, appId: AIRCALL_APP_ID },
data: { connectionStatus: "broken", healthMessageKey: "telephony.health.unknown", lastHealthCheck: new Date() },
})
).catch(() => undefined);
}
async function markConnectionDegraded(tenantId: string, dataConnectionId: string): Promise<void> {
await withTenantRLS(tenantId, (tx) =>
tx.dataConnection.updateMany({
where: { id: dataConnectionId, tenantId, appId: AIRCALL_APP_ID },
data: {
connectionStatus: "degraded",
healthMessageKey: "telephony.health.staleWebhookCleanupFailed",
lastHealthCheck: new Date(),
},
})
).catch(() => undefined);
}
function isPresent<T>(value: T | null): value is T {
return value !== null;
}
@@ -0,0 +1,136 @@
import { createHash } from "node:crypto";
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
loadRequiredWebConfig: vi.fn(),
createConnection: vi.fn(),
reconnectConnection: vi.fn(),
disconnectConnection: vi.fn(),
tx: {
dataConnection: { findMany: vi.fn(), updateMany: vi.fn() },
telephonyConnection: { findMany: vi.fn(), upsert: vi.fn() },
},
}));
vi.mock("@hivegrid/config", () => ({ loadRequiredWebConfig: mocks.loadRequiredWebConfig }));
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
withTenantRLS: (_tenantId: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => callback(mocks.tx),
}));
vi.mock("~/utils/integrations/appsEngineService.server", () => ({
AppsEngineServiceError: class AppsEngineServiceError extends Error {
messageKey: string;
constructor(messageKey: string) {
super(messageKey);
this.messageKey = messageKey;
}
},
createConnection: mocks.createConnection,
reconnectConnection: mocks.reconnectConnection,
disconnectConnection: mocks.disconnectConnection,
}));
import { connectHalloPetra, HalloPetraConnectError } from "./HalloPetraConnectionService.server";
beforeEach(() => {
vi.clearAllMocks();
mocks.loadRequiredWebConfig.mockReturnValue({
hallopetra: { webhookUrl: "https://api.example.test/v1/webhooks/telephony/hallopetra" },
});
mocks.tx.telephonyConnection.findMany.mockResolvedValue([]);
mocks.tx.dataConnection.findMany.mockResolvedValue([]);
mocks.tx.telephonyConnection.upsert.mockResolvedValue({ id: "telephony-1" });
mocks.createConnection.mockResolvedValue({ id: "data-1" });
mocks.reconnectConnection.mockResolvedValue(undefined);
mocks.disconnectConnection.mockResolvedValue(undefined);
mocks.tx.dataConnection.updateMany.mockResolvedValue({ count: 1 });
});
describe("HalloPetra connection lifecycle", () => {
it("creates an API-key DataConnection and a separate one-time webhook secret", async () => {
const result = await connectHalloPetra({ tenantId: "tenant-1", userId: "user-1", apiKey: "provider-api-key" });
expect(result).toMatchObject({
dataConnectionId: "data-1",
telephonyConnectionId: "telephony-1",
webhookUrl: "https://api.example.test/v1/webhooks/telephony/hallopetra",
});
expect(result.webhookSecret).toMatch(/^[A-Za-z0-9_-]{40,}$/u);
expect(result.webhookSecret).not.toBe("provider-api-key");
expect(mocks.createConnection).toHaveBeenCalledWith({
tenantId: "tenant-1",
appId: "hallopetra",
label: "HalloPetra",
credentials: { apiKey: "provider-api-key", webhookSecret: result.webhookSecret },
createdByUserId: "user-1",
});
expect(mocks.tx.telephonyConnection.upsert).toHaveBeenCalledWith({
where: { tenantId_provider: { tenantId: "tenant-1", provider: "hallopetra" } },
create: expect.objectContaining({
tenantId: "tenant-1",
dataConnectionId: "data-1",
provider: "hallopetra",
webhookTokenHash: createHash("sha256").update(result.webhookSecret).digest("hex"),
}),
update: expect.objectContaining({ dataConnectionId: "data-1" }),
select: { id: true },
});
});
it("reuses the historical HalloPetra slot and rotates its webhook secret", async () => {
mocks.tx.telephonyConnection.findMany.mockResolvedValue([
{ id: "telephony-1", provider: "hallopetra", dataConnectionId: "data-1" },
]);
mocks.tx.dataConnection.findMany.mockResolvedValue([
{ id: "data-1", appId: "hallopetra", connectionStatus: "revoked" },
]);
const result = await connectHalloPetra({ tenantId: "tenant-1", userId: "user-1", apiKey: "new-api-key" });
expect(mocks.reconnectConnection).toHaveBeenCalledWith({
tenantId: "tenant-1",
connectionId: "data-1",
expectedAppId: "hallopetra",
credentials: { apiKey: "new-api-key", webhookSecret: result.webhookSecret },
actorUserId: "user-1",
});
expect(mocks.createConnection).not.toHaveBeenCalled();
});
it("requires an explicit disconnect before switching away from an active provider", async () => {
mocks.tx.telephonyConnection.findMany.mockResolvedValue([
{ id: "telephony-aircall", provider: "aircall", dataConnectionId: "data-aircall" },
]);
mocks.tx.dataConnection.findMany.mockResolvedValue([
{ id: "data-aircall", appId: "aircall", connectionStatus: "active" },
]);
await expect(
connectHalloPetra({ tenantId: "tenant-1", userId: "user-1", apiKey: "provider-api-key" }),
).rejects.toEqual(expect.objectContaining<Partial<HalloPetraConnectError>>({ code: "provider_conflict" }));
expect(mocks.createConnection).not.toHaveBeenCalled();
});
it("fails closed when the public webhook URL is not configured", async () => {
mocks.loadRequiredWebConfig.mockReturnValue({ hallopetra: {} });
await expect(
connectHalloPetra({ tenantId: "tenant-1", userId: "user-1", apiKey: "provider-api-key" }),
).rejects.toMatchObject({ code: "not_configured" });
});
it("only permits HTTPS, except HTTP on an explicit loopback host", async () => {
mocks.loadRequiredWebConfig.mockReturnValue({
hallopetra: { webhookUrl: "ftp://localhost/v1/webhooks/telephony/hallopetra" },
});
await expect(
connectHalloPetra({ tenantId: "tenant-1", userId: "user-1", apiKey: "provider-api-key" }),
).rejects.toMatchObject({ code: "not_configured" });
mocks.loadRequiredWebConfig.mockReturnValue({
hallopetra: { webhookUrl: "http://127.0.0.1:3001/v1/webhooks/telephony/hallopetra" },
});
await expect(
connectHalloPetra({ tenantId: "tenant-1", userId: "user-1", apiKey: "provider-api-key" }),
).resolves.toMatchObject({ webhookUrl: "http://127.0.0.1:3001/v1/webhooks/telephony/hallopetra" });
});
});
@@ -0,0 +1,189 @@
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);
}
@@ -0,0 +1,751 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { CatalogError } from "@hivegrid/foundation";
const mocks = vi.hoisted(() => {
class MockAircallError extends Error {
readonly code: string;
constructor(code: string) {
super(code);
this.code = code;
}
}
class MockAppsEngineServiceError extends Error {}
return {
MockAircallError,
MockAppsEngineServiceError,
rlsTenantIds: [] as string[],
createAuditEvent: vi.fn(),
providerListUsers: vi.fn(),
providerStartCall: vi.fn(),
providerDeleteWebhook: vi.fn(),
checkConnectionHealth: vi.fn(),
disconnectConnection: vi.fn(),
runWithConnectionCredentials: vi.fn(),
aircallOAuthConfigured: vi.fn(),
halloPetraWebhookConfigured: vi.fn(),
tx: {
telephonyConnection: {
findFirst: vi.fn(),
findMany: vi.fn(),
updateMany: vi.fn(),
},
dataConnection: {
findFirst: vi.fn(),
findMany: vi.fn(),
},
tenantUser: {
findMany: vi.fn(),
findFirst: vi.fn(),
},
telephonyUserBinding: {
findFirst: vi.fn(),
deleteMany: vi.fn(),
create: vi.fn(),
},
telephonyCallSession: {
findMany: vi.fn(),
findFirst: vi.fn(),
updateMany: vi.fn(),
},
kontakt: {
findMany: vi.fn(),
findFirst: vi.fn(),
},
inboxLead: {
findMany: vi.fn(),
findFirst: vi.fn(),
},
projekt: {
findMany: vi.fn(),
findFirst: vi.fn(),
},
kontaktTelefon: {
findMany: vi.fn(),
findFirst: vi.fn(),
},
projektKontakt: {
findMany: vi.fn(),
findFirst: vi.fn(),
},
},
};
});
vi.mock("@hivegrid/db/audit-events.server", () => ({
createAuditEvent: mocks.createAuditEvent,
}));
vi.mock("@hivegrid/integrations", () => ({
AircallError: mocks.MockAircallError,
aircallTelephonyProvider: {
listUsers: mocks.providerListUsers,
startCall: mocks.providerStartCall,
deleteWebhook: mocks.providerDeleteWebhook,
},
}));
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
withTenantRLS: (tenantId: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => {
mocks.rlsTenantIds.push(tenantId);
return callback(mocks.tx);
},
}));
vi.mock("~/utils/integrations/appsEngineService.server", () => ({
AppsEngineServiceError: mocks.MockAppsEngineServiceError,
checkConnectionHealth: mocks.checkConnectionHealth,
disconnectConnection: mocks.disconnectConnection,
runWithConnectionCredentials: mocks.runWithConnectionCredentials,
}));
vi.mock("./AircallConnectionService.server", () => ({
aircallOAuthConfigured: mocks.aircallOAuthConfigured,
}));
vi.mock("./HalloPetraConnectionService.server", () => ({
halloPetraWebhookConfigured: mocks.halloPetraWebhookConfigured,
}));
import {
checkTelephonyConnection,
disconnectTelephonyConnection,
loadProjectTelephonyClickToCallVM,
loadTelephonyCallDetail,
loadTelephonyCalls,
loadTelephonyClickToCallVM,
loadTelephonySettings,
overrideTelephonyCallMatch,
saveTelephonyCallNote,
saveTelephonyUserBinding,
startTelephonyEntityCall,
startTelephonyOutboundCall,
TelephonyServiceError,
} from "./TelephonyService.server";
import type { TelephonyRouteContext } from "../routes/telephonyAccess.server";
const TENANT_ID = "tenant_1";
const USER_ID = "user_1";
const TENANT_USER_ID = "tenant_user_1";
const DATA_CONNECTION_ID = "data_connection_1";
const TELEPHONY_CONNECTION_ID = "telephony_connection_1";
function context(permissions: readonly string[]): TelephonyRouteContext {
return {
tenantId: TENANT_ID,
userId: USER_ID,
tenantUserId: TENANT_USER_ID,
permissions,
hasModule: true,
};
}
function call(overrides: Record<string, unknown> = {}) {
return {
id: "call_1",
createdAt: new Date("2026-07-15T09:59:00.000Z"),
updatedAt: new Date("2026-07-15T10:02:00.000Z"),
tenantId: TENANT_ID,
connectionId: TELEPHONY_CONNECTION_ID,
connection: { provider: "aircall" as const },
providerCallId: "aircall_1",
providerUserId: "provider_user_1",
tenantUserId: TENANT_USER_ID,
direction: "inbound" as const,
status: "completed" as const,
fromNumber: "+49301234567",
toNumber: "+49307654321",
startedAt: new Date("2026-07-15T10:00:00.000Z"),
answeredAt: new Date("2026-07-15T10:00:05.000Z"),
endedAt: new Date("2026-07-15T10:02:00.000Z"),
durationSeconds: 115,
matchedKontaktId: "contact_1",
matchedLeadId: null,
matchedProjektId: null,
matchConfidence: "hard" as const,
manualOverrideAt: null,
manualOverrideUserId: null,
noteMarkdown: "## Ergebnis\nAm Freitag zurückrufen",
recordingUrl: "https://recordings.aircall.test/call_1",
isDemoData: false,
archivedAt: null,
...overrides,
};
}
beforeEach(() => {
vi.clearAllMocks();
mocks.rlsTenantIds.length = 0;
mocks.aircallOAuthConfigured.mockReturnValue(true);
mocks.halloPetraWebhookConfigured.mockReturnValue(true);
mocks.createAuditEvent.mockResolvedValue(undefined);
mocks.providerListUsers.mockResolvedValue([]);
mocks.providerStartCall.mockResolvedValue({ accepted: true });
mocks.providerDeleteWebhook.mockResolvedValue(undefined);
mocks.checkConnectionHealth.mockResolvedValue({
status: "active",
messageKey: "telephony.health.active",
});
mocks.disconnectConnection.mockResolvedValue(undefined);
mocks.runWithConnectionCredentials.mockImplementation(async (_input: unknown, callback: (credentials: Record<string, unknown>) => Promise<unknown>) =>
callback({ accessToken: "permanent-token" })
);
mocks.tx.telephonyConnection.findFirst.mockResolvedValue(null);
mocks.tx.telephonyConnection.findMany.mockResolvedValue([]);
mocks.tx.telephonyConnection.updateMany.mockResolvedValue({ count: 1 });
mocks.tx.dataConnection.findFirst.mockResolvedValue(null);
mocks.tx.dataConnection.findMany.mockResolvedValue([]);
mocks.tx.tenantUser.findMany.mockResolvedValue([]);
mocks.tx.tenantUser.findFirst.mockResolvedValue(null);
mocks.tx.telephonyUserBinding.findFirst.mockResolvedValue(null);
mocks.tx.telephonyUserBinding.deleteMany.mockResolvedValue({ count: 0 });
mocks.tx.telephonyUserBinding.create.mockResolvedValue({ id: "binding_1" });
mocks.tx.telephonyCallSession.findMany.mockResolvedValue([]);
mocks.tx.telephonyCallSession.findFirst.mockResolvedValue(null);
mocks.tx.telephonyCallSession.updateMany.mockResolvedValue({ count: 1 });
mocks.tx.kontakt.findMany.mockResolvedValue([]);
mocks.tx.kontakt.findFirst.mockResolvedValue(null);
mocks.tx.inboxLead.findMany.mockResolvedValue([]);
mocks.tx.inboxLead.findFirst.mockResolvedValue(null);
mocks.tx.projekt.findMany.mockResolvedValue([]);
mocks.tx.projekt.findFirst.mockResolvedValue(null);
mocks.tx.kontaktTelefon.findMany.mockResolvedValue([]);
mocks.tx.kontaktTelefon.findFirst.mockResolvedValue(null);
mocks.tx.projektKontakt.findMany.mockResolvedValue([]);
mocks.tx.projektKontakt.findFirst.mockResolvedValue(null);
});
describe("TelephonyService", () => {
it("builds settings from one tenant slot and merges unmatched provider users", async () => {
mocks.tx.telephonyConnection.findMany.mockResolvedValue([{
id: TELEPHONY_CONNECTION_ID,
dataConnectionId: DATA_CONNECTION_ID,
provider: "aircall",
providerAccountName: "Example Aircall",
webhookId: "webhook_1",
userBindings: [
{
providerUserId: "provider_user_1",
providerEmail: "jane@example.test",
providerDisplayName: "Jane Provider",
defaultProviderNumberId: "number_1",
tenantUserId: TENANT_USER_ID,
source: "email_auto",
},
],
}]);
mocks.tx.dataConnection.findMany.mockResolvedValue([{
id: DATA_CONNECTION_ID,
appId: "aircall",
label: "Aircall",
connectionStatus: "active",
lastHealthCheck: new Date("2026-07-15T09:00:00.000Z"),
healthMessageKey: "telephony.health.active",
}]);
mocks.tx.tenantUser.findMany.mockResolvedValue([
{
id: TENANT_USER_ID,
user: {
email: "jane@example.test",
firstName: "Jane",
lastName: "Doe",
},
},
]);
mocks.providerListUsers.mockResolvedValue([
{
id: "provider_user_1",
name: "Jane Provider",
email: "jane@example.test",
available: true,
availabilityStatus: "available",
defaultNumberId: "number_1",
},
{
id: "provider_user_2",
name: "Unmatched User",
email: "unmatched@example.test",
available: false,
availabilityStatus: null,
defaultNumberId: null,
},
]);
const vm = await loadTelephonySettings(context(["telephony.manage"]), "acme & sons");
expect(vm).toMatchObject({
status: "ready",
data: {
providerConfigured: true,
connectHref: "/integrations/aircall/oauth/install?tenant=acme%20%26%20sons",
connection: {
id: DATA_CONNECTION_ID,
status: "active",
bindings: [
{ id: "provider_user_1", match: "email", hivegridUserId: TENANT_USER_ID },
{ id: "provider_user_2", match: "unmatched", hivegridUserId: null },
],
},
},
});
expect(mocks.runWithConnectionCredentials).toHaveBeenCalledWith(
{
tenantId: TENANT_ID,
connectionId: DATA_CONNECTION_ID,
expectedAppId: "aircall",
},
expect.any(Function)
);
expect(new Set(mocks.rlsTenantIds)).toEqual(new Set([TENANT_ID]));
});
it("limits call-list queries to the bound tenant user without read-all", async () => {
mocks.tx.telephonyCallSession.findMany.mockResolvedValue([call()]);
mocks.tx.tenantUser.findMany.mockResolvedValue([
{
id: TENANT_USER_ID,
user: { email: "jane@example.test", firstName: "Jane", lastName: "Doe" },
},
]);
mocks.tx.kontakt.findMany.mockResolvedValue([
{
id: "contact_1",
kontaktTyp: "privatperson",
vorname: "Clara",
nachname: "Weiss",
orgName: null,
primaerEmail: "clara@example.test",
primaerTelefon: "+49301234567",
},
]);
const vm = await loadTelephonyCalls(context(["telephony.read_own"]), "acme");
expect(mocks.tx.telephonyCallSession.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({
tenantId: TENANT_ID,
tenantUserId: TENANT_USER_ID,
}),
})
);
expect(vm).toMatchObject({
status: "ready",
data: {
canReadAll: false,
rows: [
{
id: "call_1",
counterpartLabel: "Clara Weiss",
matchConfidence: "exact",
boundUserLabel: "Jane Doe",
detailHref: "/acme/calls/call_1",
},
],
},
});
});
it("returns the 404 catalog contract for a foreign call detail", async () => {
await expect(loadTelephonyCallDetail(context(["telephony.read_own"]), "acme", "foreign_call")).rejects.toBeInstanceOf(CatalogError);
expect(mocks.tx.telephonyCallSession.findFirst).toHaveBeenCalledWith({
where: {
id: "foreign_call",
tenantId: TENANT_ID,
archivedAt: null,
tenantUserId: TENANT_USER_ID,
},
include: { connection: { select: { provider: true } } },
});
});
it("saves a note only through the caller's tenant visibility and audits metadata", async () => {
await saveTelephonyCallNote(context(["telephony.call"]), {
callId: "call_1",
noteMarkdown: "## Result",
});
expect(mocks.tx.telephonyCallSession.updateMany).toHaveBeenCalledWith({
where: {
id: "call_1",
tenantId: TENANT_ID,
archivedAt: null,
tenantUserId: TENANT_USER_ID,
},
data: { noteMarkdown: "## Result" },
});
expect(mocks.createAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({
tenantId: TENANT_ID,
actorId: USER_ID,
action: "TELEPHONY_CALL_NOTE_SAVED",
metadata: { noteLength: 9 },
})
);
});
it("validates a match in the same tenant before persisting a manual override", async () => {
mocks.tx.telephonyCallSession.findFirst.mockResolvedValue({ id: "call_1" });
mocks.tx.kontakt.findFirst.mockResolvedValue({ id: "contact_2" });
await overrideTelephonyCallMatch(context(["telephony.manage"]), {
callId: "call_1",
match: { type: "contact", id: "contact_2" },
});
expect(mocks.tx.kontakt.findFirst).toHaveBeenCalledWith({
where: { id: "contact_2", tenantId: TENANT_ID, archivedAt: null },
select: { id: true },
});
expect(mocks.tx.telephonyCallSession.updateMany).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: "call_1", tenantId: TENANT_ID, archivedAt: null },
data: expect.objectContaining({
matchedKontaktId: "contact_2",
matchedLeadId: null,
matchedProjektId: null,
matchConfidence: "manual",
manualOverrideUserId: USER_ID,
}),
})
);
});
it("replaces conflicting mappings with one validated manual binding", async () => {
mocks.tx.telephonyConnection.findFirst.mockResolvedValue({
id: TELEPHONY_CONNECTION_ID,
dataConnectionId: DATA_CONNECTION_ID,
provider: "aircall",
webhookId: "webhook_1",
});
mocks.providerListUsers.mockResolvedValue([
{
id: "provider_user_2",
name: "Jane Provider",
email: "jane@example.test",
available: true,
availabilityStatus: "available",
defaultNumberId: "number_2",
},
]);
mocks.tx.tenantUser.findFirst.mockResolvedValue({ id: TENANT_USER_ID });
await saveTelephonyUserBinding(context(["telephony.manage"]), {
dataConnectionId: DATA_CONNECTION_ID,
providerUserId: "provider_user_2",
tenantUserId: TENANT_USER_ID,
});
expect(mocks.tx.telephonyUserBinding.deleteMany).toHaveBeenCalledWith({
where: {
tenantId: TENANT_ID,
connectionId: TELEPHONY_CONNECTION_ID,
OR: [{ providerUserId: "provider_user_2" }, { tenantUserId: TENANT_USER_ID }],
},
});
expect(mocks.tx.telephonyUserBinding.create).toHaveBeenCalledWith({
data: expect.objectContaining({
tenantId: TENANT_ID,
connectionId: TELEPHONY_CONNECTION_ID,
providerUserId: "provider_user_2",
tenantUserId: TENANT_USER_ID,
source: "manual",
}),
});
});
it("starts click-to-call only with the encrypted connection callback and bound Aircall ids", async () => {
mocks.tx.dataConnection.findFirst.mockResolvedValue({ id: DATA_CONNECTION_ID, appId: "aircall" });
mocks.tx.telephonyConnection.findFirst.mockResolvedValue({
id: TELEPHONY_CONNECTION_ID,
dataConnectionId: DATA_CONNECTION_ID,
provider: "aircall",
});
mocks.tx.telephonyUserBinding.findFirst.mockResolvedValue({
providerUserId: "provider_user_1",
defaultProviderNumberId: "number_1",
});
await expect(startTelephonyOutboundCall(context(["telephony.call"]), "+49301234567")).resolves.toEqual({ accepted: true });
expect(mocks.providerStartCall).toHaveBeenCalledWith(
{ accessToken: "permanent-token" },
{
userId: "provider_user_1",
numberId: "number_1",
to: "+49301234567",
}
);
expect(mocks.createAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({
action: "TELEPHONY_OUTBOUND_CALL_REQUESTED",
metadata: { providerUserId: "provider_user_1" },
})
);
});
it("normalizes and de-duplicates multiple entity numbers before enabling Aircall", async () => {
mocks.tx.telephonyConnection.findFirst.mockResolvedValue({
id: TELEPHONY_CONNECTION_ID,
dataConnectionId: DATA_CONNECTION_ID,
provider: "aircall",
});
mocks.tx.dataConnection.findFirst.mockResolvedValue({ id: DATA_CONNECTION_ID, appId: "aircall" });
mocks.tx.telephonyUserBinding.findFirst.mockResolvedValue({ defaultProviderNumberId: "number_1" });
const vm = await loadTelephonyClickToCallVM(context(["telephony.call"]), [
{ id: "phone_1", label: "Office", e164: "+49 30 1234567", primary: false },
{ id: "phone_2", label: "Primary", e164: "0049 30 1234567", primary: true },
{ id: "phone_3", label: "Mobile", e164: "+491701234567", primary: false },
{ id: "phone_invalid", label: "Invalid", e164: "030 123", primary: false },
]);
expect(vm).toEqual({
mode: "provider",
numbers: [
{ id: "phone_2", label: "Primary", e164: "+49301234567", primary: true },
{ id: "phone_3", label: "Mobile", e164: "+491701234567", primary: false },
],
requiresSelection: true,
reasonKey: null,
});
});
it("keeps valid numbers as tel fallback when the user has no Aircall binding", async () => {
mocks.tx.telephonyConnection.findFirst.mockResolvedValue({
id: TELEPHONY_CONNECTION_ID,
dataConnectionId: DATA_CONNECTION_ID,
provider: "aircall",
});
mocks.tx.dataConnection.findFirst.mockResolvedValue({ id: DATA_CONNECTION_ID, appId: "aircall" });
const vm = await loadTelephonyClickToCallVM(context(["telephony.call"]), [{ id: "phone_1", label: "Office", e164: "+49301234567", primary: true }]);
expect(vm).toMatchObject({ mode: "tel-fallback", reasonKey: "telephony.call.fallback.noBinding" });
});
it("keeps HalloPetra inbound-only and never sends click-to-call to its adapter", async () => {
mocks.tx.dataConnection.findFirst.mockResolvedValue({ id: DATA_CONNECTION_ID, appId: "hallopetra" });
mocks.tx.telephonyConnection.findFirst.mockResolvedValue({
id: TELEPHONY_CONNECTION_ID,
dataConnectionId: DATA_CONNECTION_ID,
provider: "hallopetra",
});
await expect(
loadTelephonyClickToCallVM(context(["telephony.call"]), [
{ id: "phone_1", label: "Office", e164: "+49301234567", primary: true },
]),
).resolves.toMatchObject({
mode: "tel-fallback",
reasonKey: "telephony.call.fallback.providerInboundOnly",
});
await expect(startTelephonyOutboundCall(context(["telephony.call"]), "+49301234567")).rejects.toMatchObject({
messageKey: "telephony.call.fallback.providerInboundOnly",
});
expect(mocks.providerStartCall).not.toHaveBeenCalled();
});
it("loads every valid number from contacts actually linked to the project", async () => {
mocks.tx.projektKontakt.findMany.mockResolvedValue([
{ kontaktId: "contact_primary", primaer: true },
{ kontaktId: "contact_secondary", primaer: false },
]);
mocks.tx.kontaktTelefon.findMany.mockResolvedValue([
{ id: "phone_primary", kontaktId: "contact_primary", telefon: "+49301111111", primaer: true },
{ id: "phone_secondary", kontaktId: "contact_secondary", telefon: "+49302222222", primaer: true },
]);
const vm = await loadProjectTelephonyClickToCallVM(context(["telephony.call"]), {
projectId: "project_1",
contacts: [
{ contactId: "contact_primary", label: "Ada Primary", primary: true },
{ contactId: "contact_secondary", label: "Ben Secondary", primary: false },
{ contactId: "contact_not_linked", label: "Foreign", primary: false },
],
});
expect(mocks.tx.projektKontakt.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: {
tenantId: TENANT_ID,
projektId: "project_1",
kontaktId: { in: ["contact_primary", "contact_secondary", "contact_not_linked"] },
},
})
);
expect(mocks.tx.kontaktTelefon.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: { tenantId: TENANT_ID, kontaktId: { in: ["contact_primary", "contact_secondary"] } },
})
);
expect(vm.numbers).toEqual([
{ id: "phone_primary", label: "Ada Primary", e164: "+49301111111", primary: true },
{ id: "phone_secondary", label: "Ben Secondary", e164: "+49302222222", primary: false },
]);
});
it("verifies the submitted number against the same-tenant entity before calling Aircall", async () => {
mocks.tx.kontaktTelefon.findFirst.mockResolvedValue({ telefon: "+49 30 1234567" });
mocks.tx.dataConnection.findFirst.mockResolvedValue({ id: DATA_CONNECTION_ID, appId: "aircall" });
mocks.tx.telephonyConnection.findFirst.mockResolvedValue({
id: TELEPHONY_CONNECTION_ID,
dataConnectionId: DATA_CONNECTION_ID,
provider: "aircall",
});
mocks.tx.telephonyUserBinding.findFirst.mockResolvedValue({
providerUserId: "provider_user_1",
defaultProviderNumberId: "number_1",
});
await expect(
startTelephonyEntityCall(context(["telephony.call"]), {
entityType: "contact",
entityId: "contact_1",
numberId: "phone_1",
destination: "+49 (30) 1234567",
})
).resolves.toEqual({ accepted: true });
expect(mocks.tx.kontaktTelefon.findFirst).toHaveBeenCalledWith({
where: {
id: "phone_1",
tenantId: TENANT_ID,
kontaktId: "contact_1",
kontakt: { archivedAt: null },
},
select: { telefon: true },
});
expect(mocks.providerStartCall).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ to: "+49301234567" }));
});
it("rejects a tampered entity number before reaching the provider", async () => {
mocks.tx.kontaktTelefon.findFirst.mockResolvedValue({ telefon: "+49301111111" });
await expect(
startTelephonyEntityCall(context(["telephony.call"]), {
entityType: "contact",
entityId: "contact_1",
numberId: "phone_1",
destination: "+49302222222",
})
).rejects.toBeInstanceOf(CatalogError);
expect(mocks.providerStartCall).not.toHaveBeenCalled();
});
it("binds a lead click-to-call request to the lead-owned phone field", async () => {
mocks.tx.inboxLead.findFirst.mockResolvedValue({ telefon: "+49303333333" });
mocks.tx.dataConnection.findFirst.mockResolvedValue({ id: DATA_CONNECTION_ID, appId: "aircall" });
mocks.tx.telephonyConnection.findFirst.mockResolvedValue({
id: TELEPHONY_CONNECTION_ID,
dataConnectionId: DATA_CONNECTION_ID,
provider: "aircall",
});
mocks.tx.telephonyUserBinding.findFirst.mockResolvedValue({
providerUserId: "provider_user_1",
defaultProviderNumberId: "number_1",
});
await startTelephonyEntityCall(context(["telephony.call"]), {
entityType: "lead",
entityId: "lead_1",
numberId: "lead:lead_1",
destination: "+49303333333",
});
expect(mocks.tx.inboxLead.findFirst).toHaveBeenCalledWith({
where: { id: "lead_1", tenantId: TENANT_ID, archivedAt: null },
select: { telefon: true },
});
expect(mocks.providerStartCall).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ to: "+49303333333" }));
});
it("rejects a project number that is not linked to the addressed project", async () => {
mocks.tx.kontaktTelefon.findFirst.mockResolvedValue({
kontaktId: "contact_1",
telefon: "+49304444444",
});
mocks.tx.projektKontakt.findFirst.mockResolvedValue(null);
await expect(
startTelephonyEntityCall(context(["telephony.call"]), {
entityType: "project",
entityId: "project_1",
numberId: "phone_1",
destination: "+49304444444",
})
).rejects.toBeInstanceOf(CatalogError);
expect(mocks.tx.projektKontakt.findFirst).toHaveBeenCalledWith({
where: {
tenantId: TENANT_ID,
projektId: "project_1",
kontaktId: "contact_1",
projekt: { archivedAt: null },
},
select: { id: true },
});
expect(mocks.providerStartCall).not.toHaveBeenCalled();
});
it("delegates health and disconnect lifecycle after tenant-scoped slot lookup", async () => {
mocks.tx.telephonyConnection.findFirst.mockResolvedValue({
id: TELEPHONY_CONNECTION_ID,
dataConnectionId: DATA_CONNECTION_ID,
provider: "aircall",
webhookId: "webhook_1",
});
const ctx = context(["telephony.manage"]);
await checkTelephonyConnection(ctx, "acme", DATA_CONNECTION_ID);
await disconnectTelephonyConnection(ctx, DATA_CONNECTION_ID);
expect(mocks.checkConnectionHealth).toHaveBeenCalledWith({
tenantId: TENANT_ID,
connectionId: DATA_CONNECTION_ID,
notificationDeeplink: "/acme/settings/integrations/telephony",
});
expect(mocks.providerDeleteWebhook).toHaveBeenCalledWith({ accessToken: "permanent-token" }, "webhook_1");
expect(mocks.disconnectConnection).toHaveBeenCalledWith({
tenantId: TENANT_ID,
connectionId: DATA_CONNECTION_ID,
expectedAppId: "aircall",
actorUserId: USER_ID,
});
expect(mocks.tx.telephonyConnection.updateMany).toHaveBeenCalledWith({
where: { id: TELEPHONY_CONNECTION_ID, tenantId: TENANT_ID },
data: { webhookId: null, webhookTokenHash: null },
});
});
it("keeps the local Aircall connection intact when provider webhook deletion fails", async () => {
mocks.tx.telephonyConnection.findFirst.mockResolvedValue({
id: TELEPHONY_CONNECTION_ID,
dataConnectionId: DATA_CONNECTION_ID,
provider: "aircall",
webhookId: "webhook_1",
});
mocks.providerDeleteWebhook.mockRejectedValue(new Error("provider unavailable"));
await expect(disconnectTelephonyConnection(context(["telephony.manage"]), DATA_CONNECTION_ID)).rejects.toEqual(
expect.objectContaining<Partial<TelephonyServiceError>>({
messageKey: "telephony.settings.disconnect.providerError",
})
);
expect(mocks.disconnectConnection).not.toHaveBeenCalled();
expect(mocks.tx.telephonyConnection.updateMany).not.toHaveBeenCalled();
});
it("returns a Klartext error instead of calling Aircall for invalid numbers", async () => {
await expect(startTelephonyOutboundCall(context(["telephony.call"]), "030 12345")).rejects.toEqual(
expect.objectContaining<Partial<TelephonyServiceError>>({
messageKey: "telephony.call.error.invalidNumber",
})
);
expect(mocks.runWithConnectionCredentials).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,51 @@
import { describe, expect, it } from "vitest";
import { signAircallOAuthState, verifyAircallOAuthState } from "./aircallOAuthState.server";
const INPUT = {
tenantId: "tenant-1",
tenantSlug: "acme",
userId: "user-1",
connectionId: "connection-1",
} as const;
const SECRET = "aircall-oauth-state-test-secret";
const NOW = 1_725_000_000_000;
describe("Aircall OAuth state", () => {
it("round-trips the tenant, user, reserved slot and nonce", () => {
const state = signAircallOAuthState(INPUT, { secret: SECRET, now: () => NOW, nonce: () => "nonce-1" });
expect(verifyAircallOAuthState(state, { secret: SECRET, now: () => NOW + 60_000 })).toEqual({
ok: true,
payload: { ...INPUT, nonce: "nonce-1", createdAt: NOW },
});
});
it("rejects tampering before decoding trusted context", () => {
const state = signAircallOAuthState(INPUT, { secret: SECRET, now: () => NOW, nonce: () => "nonce-1" });
const [body, signature] = state.split(".");
expect(verifyAircallOAuthState(`${body}x.${signature}`, { secret: SECRET, now: () => NOW })).toEqual({
ok: false,
reason: "bad-signature",
});
});
it("expires after ten minutes and rejects implausible future tokens", () => {
const state = signAircallOAuthState(INPUT, { secret: SECRET, now: () => NOW, nonce: () => "nonce-1" });
expect(verifyAircallOAuthState(state, { secret: SECRET, now: () => NOW + 10 * 60_000 + 1 })).toEqual({
ok: false,
reason: "expired",
});
expect(verifyAircallOAuthState(state, { secret: SECRET, now: () => NOW - 30_001 })).toEqual({
ok: false,
reason: "expired",
});
});
it("rejects malformed and oversized values without throwing", () => {
expect(verifyAircallOAuthState("not-signed", { secret: SECRET, now: () => NOW })).toEqual({ ok: false, reason: "malformed" });
expect(verifyAircallOAuthState("x".repeat(4_097), { secret: SECRET, now: () => NOW })).toEqual({ ok: false, reason: "malformed" });
});
});
@@ -0,0 +1,118 @@
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { loadRequiredWebConfig } from "@hivegrid/config";
const STATE_TTL_MS = 10 * 60 * 1_000;
const MAX_FUTURE_SKEW_MS = 30_000;
const MAX_STATE_LENGTH = 4_096;
const PAYLOAD_VERSION = "v1";
export interface AircallOAuthStatePayload {
readonly tenantId: string;
readonly tenantSlug: string;
readonly userId: string;
readonly connectionId: string;
readonly nonce: string;
/** Epoch milliseconds. */
readonly createdAt: number;
}
export type VerifyAircallOAuthStateResult =
| { readonly ok: true; readonly payload: AircallOAuthStatePayload }
| { readonly ok: false; readonly reason: "malformed" | "bad-signature" | "expired" };
type StateOptions = {
readonly now?: () => number;
readonly nonce?: () => string;
readonly secret?: string;
};
/** Sign tenant, initiating user and the reserved Aircall slot for ten minutes. */
export function signAircallOAuthState(
input: Pick<AircallOAuthStatePayload, "tenantId" | "tenantSlug" | "userId" | "connectionId">,
options: StateOptions = {}
): string {
const payload: AircallOAuthStatePayload = {
...input,
nonce: options.nonce ? options.nonce() : randomBytes(24).toString("base64url"),
createdAt: options.now ? options.now() : Date.now(),
};
if (!isValidPayload(payload)) {
throw new Error("Aircall OAuth state input is invalid");
}
const body = Buffer.from(JSON.stringify({ v: PAYLOAD_VERSION, p: payload }), "utf8").toString("base64url");
return `${body}.${sign(body, stateSecret(options.secret))}`;
}
export function verifyAircallOAuthState(state: string, options: Pick<StateOptions, "now" | "secret"> = {}): VerifyAircallOAuthStateResult {
if (!state || state.length > MAX_STATE_LENGTH) return { ok: false, reason: "malformed" };
const separator = state.lastIndexOf(".");
if (separator <= 0 || separator === state.length - 1) return { ok: false, reason: "malformed" };
const body = state.slice(0, separator);
const receivedSignature = state.slice(separator + 1);
let expectedSignature: string;
try {
expectedSignature = sign(body, stateSecret(options.secret));
} catch {
return { ok: false, reason: "malformed" };
}
const received = Buffer.from(receivedSignature, "utf8");
const expected = Buffer.from(expectedSignature, "utf8");
if (received.length !== expected.length || !timingSafeEqual(received, expected)) {
return { ok: false, reason: "bad-signature" };
}
let decoded: { readonly v?: unknown; readonly p?: unknown };
try {
decoded = JSON.parse(Buffer.from(body, "base64url").toString("utf8")) as { readonly v?: unknown; readonly p?: unknown };
} catch {
return { ok: false, reason: "malformed" };
}
if (decoded.v !== PAYLOAD_VERSION || !isValidPayload(decoded.p)) {
return { ok: false, reason: "malformed" };
}
const now = options.now ? options.now() : Date.now();
const age = now - decoded.p.createdAt;
const tooOld = age > STATE_TTL_MS;
const tooFarInFuture = age < -MAX_FUTURE_SKEW_MS;
if (tooOld || tooFarInFuture) {
return { ok: false, reason: "expired" };
}
return { ok: true, payload: decoded.p };
}
function stateSecret(override?: string): string {
if (override) return override;
const config = loadRequiredWebConfig();
const secret = config.cryptoSecret || config.sessionSecret;
if (!secret) throw new Error("Aircall OAuth state secret is missing");
return secret;
}
function sign(body: string, secret: string): string {
return createHmac("sha256", secret).update(body).digest("base64url");
}
function isValidPayload(value: unknown): value is AircallOAuthStatePayload {
if (!isRecord(value)) return false;
return (
boundedString(value.tenantId, 256) &&
boundedString(value.tenantSlug, 256) &&
boundedString(value.userId, 256) &&
boundedString(value.connectionId, 256) &&
boundedString(value.nonce, 256) &&
typeof value.createdAt === "number" &&
Number.isSafeInteger(value.createdAt) &&
value.createdAt >= 0
);
}
function boundedString(value: unknown, maxLength: number): value is string {
return typeof value === "string" && value.length > 0 && value.length <= maxLength;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}