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,55 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { aircallAdapter, aircallTelephonyProvider } from "./adapter.js";
afterEach(() => {
vi.unstubAllGlobals();
});
describe("Aircall adapters", () => {
it("registers an OAuth Apps Engine adapter without a refresh-token contract", () => {
expect(aircallAdapter).toMatchObject({ key: "aircall", connectionType: "oauth2" });
expect(aircallAdapter.refreshToken).toBeUndefined();
});
it("exposes the provider-neutral telephony operations", () => {
expect(aircallTelephonyProvider.key).toBe("aircall");
expect(aircallTelephonyProvider).toMatchObject({
connect: expect.any(Function),
disconnect: expect.any(Function),
listUsers: expect.any(Function),
listProviderUsers: expect.any(Function),
probe: expect.any(Function),
listUserNumbers: expect.any(Function),
startCall: expect.any(Function),
triggerOutboundCall: expect.any(Function),
createWebhook: expect.any(Function),
subscribeToWebhooks: expect.any(Function),
deleteWebhook: expect.any(Function),
validateWebhook: expect.any(Function),
parseWebhookEvent: expect.any(Function),
normalizeWebhook: expect.any(Function),
getRecordingUrl: expect.any(Function),
});
});
it("probes V1 ping and maps a valid permanent bearer token to active", async () => {
const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 204 }));
vi.stubGlobal("fetch", fetchMock);
await expect(aircallAdapter.validateConnection({ accessToken: "permanent-token" })).resolves.toEqual({
ok: true,
health: "active",
messageKey: "telephony.health.active",
});
expect(new URL(String(fetchMock.mock.calls[0]?.[0])).pathname).toBe("/v1/ping");
});
it("maps a missing token to a Klartext-ready broken state", async () => {
await expect(aircallAdapter.healthCheck({ accessToken: null })).resolves.toEqual({
ok: false,
health: "broken",
messageKey: "telephony.health.tokenInvalid",
});
});
});
@@ -0,0 +1,84 @@
import {
registerIntegrationAdapter,
type AdapterResult,
type AdapterSyncOutcome,
type IntegrationAdapter,
} from "@hivegrid/foundation";
import type { TelephonyProviderInterface } from "../telephony/provider.js";
import {
createAircallWebhook,
deleteAircallWebhook,
listAircallUserNumbers,
listAircallUsers,
pingAircall,
startAircallOutboundCall,
} from "./client.js";
import { AircallError, type AircallCredentials } from "./types.js";
import {
getAircallRecordingUrl,
normalizeAircallWebhook,
parseAircallWebhookEvent,
validateAircallWebhook,
} from "./webhook.js";
function healthFromError(error: unknown): AdapterResult {
if (error instanceof AircallError) {
switch (error.code) {
case "auth_token_invalid":
return { ok: false, health: "broken", messageKey: "telephony.health.tokenInvalid" };
case "auth_scope_missing":
return { ok: false, health: "broken", messageKey: "telephony.health.scopeMissing" };
case "rate_limit_exceeded":
return { ok: true, health: "degraded", messageKey: "telephony.health.rateLimited" };
case "provider_outage":
return { ok: false, health: "degraded", messageKey: "telephony.health.providerOutage" };
default:
return { ok: false, health: "broken", messageKey: "telephony.health.unknown" };
}
}
return { ok: false, health: "broken", messageKey: "telephony.health.unknown" };
}
async function probe(credentials: AircallCredentials): Promise<AdapterResult> {
try {
await pingAircall(credentials);
return { ok: true, health: "active", messageKey: "telephony.health.active" };
} catch (error) {
return healthFromError(error);
}
}
export const aircallAdapter: IntegrationAdapter<AircallCredentials> = registerIntegrationAdapter<AircallCredentials>({
key: "aircall",
connectionType: "oauth2",
validateConnection: probe,
healthCheck: probe,
// Aircall's telephony event engine owns domain processing. The generic sync
// is intentionally a no-op, and no refreshToken method exists because the
// documented Aircall OAuth access token is permanent.
sync: (): Promise<AdapterSyncOutcome> =>
Promise.resolve({
items: [],
summaryKey: "telephony.sync.summary.webhookEngine",
}),
});
export const aircallTelephonyProvider: TelephonyProviderInterface<AircallCredentials> = {
key: "aircall",
connect: pingAircall,
disconnect: (credentials, webhookId) => webhookId ? deleteAircallWebhook(credentials, webhookId) : Promise.resolve(),
probe: pingAircall,
listUsers: listAircallUsers,
listProviderUsers: listAircallUsers,
listUserNumbers: listAircallUserNumbers,
startCall: startAircallOutboundCall,
triggerOutboundCall: startAircallOutboundCall,
createWebhook: createAircallWebhook,
subscribeToWebhooks: createAircallWebhook,
deleteWebhook: deleteAircallWebhook,
validateWebhook: validateAircallWebhook,
parseWebhookEvent: parseAircallWebhookEvent,
normalizeWebhook: normalizeAircallWebhook,
getRecordingUrl: getAircallRecordingUrl,
};
@@ -0,0 +1,200 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import {
AIRCALL_OAUTH_AUTHORIZE_URL,
buildAircallAuthorizationUrl,
createAircallWebhook,
exchangeAircallCodeForToken,
listAircallUserNumbers,
listAircallUsers,
pingAircall,
startAircallOutboundCall,
} from "./client.js";
import { AircallError } from "./types.js";
const CREDENTIALS = { accessToken: "permanent-aircall-access-token" } as const;
afterEach(() => {
vi.unstubAllGlobals();
});
describe("Aircall OAuth and Public API client", () => {
it("builds the official public_api consent URL with CSRF state", () => {
const url = new URL(
buildAircallAuthorizationUrl(
{ clientId: "client-1", clientSecret: "client-secret", redirectUri: "https://app.example.test/integrations/aircall/oauth/callback" },
"signed-state",
),
);
expect(`${url.origin}${url.pathname}`).toBe(AIRCALL_OAUTH_AUTHORIZE_URL);
expect(Object.fromEntries(url.searchParams)).toEqual({
client_id: "client-1",
redirect_uri: "https://app.example.test/integrations/aircall/oauth/callback",
response_type: "code",
scope: "public_api",
state: "signed-state",
});
});
it("exchanges a code for a permanent access token without inventing a refresh token", async () => {
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ access_token: "aircall-token" }));
vi.stubGlobal("fetch", fetchMock);
const tokenSet = await exchangeAircallCodeForToken(
{ clientId: "client-1", clientSecret: "client-secret", redirectUri: "https://app.example.test/callback" },
"authorization-code",
);
expect(tokenSet).toEqual({ accessToken: "aircall-token" });
expect(tokenSet).not.toHaveProperty("refreshToken");
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(init.method).toBe("POST");
expect(init.headers).toEqual({ "content-type": "application/json" });
expect(JSON.parse(String(init.body))).toEqual({
code: "authorization-code",
redirect_uri: "https://app.example.test/callback",
client_id: "client-1",
client_secret: "client-secret",
grant_type: "authorization_code",
});
});
it("uses User V2 and its dedicated numbers endpoint", async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(
jsonResponse({
meta: { current_page: 1, next_page_link: null },
users: [
{
id: 456,
name: "Ada Agent",
email: "ADA@example.test",
available: true,
availability_status: "available",
default_number_id: 673,
},
],
}),
)
.mockResolvedValueOnce(
jsonResponse({
meta: { current_page: 1, next_page_link: null },
numbers: [{ id: 673, name: "Berlin", digits: "+49 30 123 45", country: "de", availability_status: "open" }],
}),
);
vi.stubGlobal("fetch", fetchMock);
await expect(listAircallUsers(CREDENTIALS)).resolves.toEqual([
{
id: "456",
name: "Ada Agent",
email: "ada@example.test",
available: true,
availabilityStatus: "available",
defaultNumberId: "673",
},
]);
await expect(listAircallUserNumbers(CREDENTIALS, "456")).resolves.toEqual([
{ id: "673", label: "Berlin", e164: "+493012345", countryCode: "DE", availabilityStatus: "open" },
]);
expect(new URL(String(fetchMock.mock.calls[0]?.[0])).pathname).toBe("/v2/users");
expect(new URL(String(fetchMock.mock.calls[1]?.[0])).pathname).toBe("/v2/users/456/numbers");
for (const [, init] of fetchMock.mock.calls as Array<[string, RequestInit]>) {
expect(init.headers).toMatchObject({ authorization: `Bearer ${CREDENTIALS.accessToken}` });
}
});
it("probes the permanent bearer token through the documented V1 ping endpoint", async () => {
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ status: "ok" }));
vi.stubGlobal("fetch", fetchMock);
await expect(pingAircall(CREDENTIALS)).resolves.toBeUndefined();
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(url).toBe("https://api.aircall.io/v1/ping");
expect(init.headers).toMatchObject({ authorization: `Bearer ${CREDENTIALS.accessToken}` });
});
it("posts click-to-call to the documented V1 endpoint with number_id and E.164 destination", async () => {
const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 204 }));
vi.stubGlobal("fetch", fetchMock);
await expect(startAircallOutboundCall(CREDENTIALS, { userId: "456", numberId: "673", to: "+49301234567" })).resolves.toEqual({ accepted: true });
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(url).toBe("https://api.aircall.io/v1/users/456/calls");
expect(init.method).toBe("POST");
expect(init.headers).toMatchObject({ authorization: `Bearer ${CREDENTIALS.accessToken}`, "content-type": "application/json" });
expect(JSON.parse(String(init.body))).toEqual({ number_id: 673, to: "+49301234567" });
});
it("creates a webhook and returns the provider token only to the credential boundary", async () => {
const fetchMock = vi.fn().mockResolvedValue(
jsonResponse(
{
webhook: {
webhook_id: "4df567a2-41a4-4d49-91be-2c139344471c",
token: "provider-webhook-token",
active: true,
events: ["call.created", "call.ended"],
},
},
201,
),
);
vi.stubGlobal("fetch", fetchMock);
await expect(
createAircallWebhook(CREDENTIALS, {
name: "HiveGrid",
url: "https://api.example.test/v1/webhooks/telephony/aircall",
events: ["call.created", "call.ended"],
}),
).resolves.toEqual({
id: "4df567a2-41a4-4d49-91be-2c139344471c",
token: "provider-webhook-token",
active: true,
events: ["call.created", "call.ended"],
});
});
it("rejects unsupported webhook events before sending credentials", async () => {
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
await expect(
createAircallWebhook(CREDENTIALS, {
name: "HiveGrid",
url: "https://api.example.test/v1/webhooks/telephony/aircall",
events: ["contact.created"],
}),
).rejects.toMatchObject({ code: "invalid_request" });
expect(fetchMock).not.toHaveBeenCalled();
});
it("maps provider failures without copying bearer tokens or response diagnostics", async () => {
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ troubleshoot: `invalid ${CREDENTIALS.accessToken}` }, 401));
vi.stubGlobal("fetch", fetchMock);
const error = await listAircallUsers(CREDENTIALS).catch((caught: unknown) => caught);
expect(error).toBeInstanceOf(AircallError);
expect(error).toMatchObject({ code: "auth_token_invalid", httpStatus: 401 });
expect(String(error)).not.toContain(CREDENTIALS.accessToken);
expect(JSON.stringify(error)).not.toContain(CREDENTIALS.accessToken);
});
it("rejects non-E.164 destinations before sending credentials", async () => {
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
await expect(startAircallOutboundCall(CREDENTIALS, { userId: "456", numberId: "673", to: "030 12345" })).rejects.toMatchObject({
code: "invalid_request",
});
expect(fetchMock).not.toHaveBeenCalled();
});
});
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
}
@@ -0,0 +1,260 @@
import type {
TelephonyProviderNumber,
TelephonyProviderUser,
TelephonyStartCallInput,
TelephonyStartCallResult,
TelephonyWebhookRegistration,
TelephonyWebhookRegistrationInput,
} from "../telephony/provider.js";
import { fetchProvider, readProviderJson } from "../provider-http.js";
import {
AircallError,
type AircallCredentials,
type AircallNumber,
type AircallOAuthConfig,
type AircallPaginationMeta,
type AircallTokenSet,
type AircallUserV2,
type AircallWebhookRecord,
AIRCALL_CALL_WEBHOOK_EVENTS,
} from "./types.js";
export const AIRCALL_API_BASE = "https://api.aircall.io";
export const AIRCALL_OAUTH_AUTHORIZE_URL = "https://dashboard.aircall.io/oauth/authorize";
export const AIRCALL_OAUTH_TOKEN_URL = `${AIRCALL_API_BASE}/v1/oauth/token`;
export const AIRCALL_OAUTH_SCOPE = "public_api";
const DEFAULT_PAGE_SIZE = 50;
const DEFAULT_MAX_PAGES = 20;
const E164_PATTERN = /^\+[1-9]\d{1,14}$/u;
const PROVIDER_ID_PATTERN = /^\d+$/u;
const WEBHOOK_ID_PATTERN = /^[A-Za-z0-9-]{1,128}$/u;
const SUPPORTED_WEBHOOK_EVENTS = new Set<string>(AIRCALL_CALL_WEBHOOK_EVENTS);
type PageOptions = { readonly perPage?: number; readonly maxPages?: number };
export function resolveAircallOAuthConfig(env: NodeJS.ProcessEnv = process.env): AircallOAuthConfig | null {
const clientId = env.AIRCALL_CLIENT_ID;
const clientSecret = env.AIRCALL_CLIENT_SECRET;
const redirectUri = env.AIRCALL_REDIRECT_URI;
if (!clientId || !clientSecret || !redirectUri) return null;
return { clientId, clientSecret, redirectUri };
}
/** Build Aircall's consent URL. `state` must be a signed tenant/user token. */
export function buildAircallAuthorizationUrl(config: AircallOAuthConfig, state: string): string {
const params = new URLSearchParams({
client_id: config.clientId,
redirect_uri: config.redirectUri,
response_type: "code",
scope: AIRCALL_OAUTH_SCOPE,
state,
});
return `${AIRCALL_OAUTH_AUTHORIZE_URL}?${params.toString()}`;
}
/** Exchange a short-lived authorization code for Aircall's permanent token. */
export async function exchangeAircallCodeForToken(config: AircallOAuthConfig, code: string): Promise<AircallTokenSet> {
const response = await fetchProvider(AIRCALL_OAUTH_TOKEN_URL, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
code,
redirect_uri: config.redirectUri,
client_id: config.clientId,
client_secret: config.clientSecret,
grant_type: "authorization_code",
}),
});
const body = await readProviderJson<{ access_token?: string }>(response);
if (!response.ok || !body.access_token) throw mapAircallError(response.status);
return { accessToken: body.access_token };
}
/** Verify the permanent bearer token against Aircall's lightweight health endpoint. */
export async function pingAircall(credentials: AircallCredentials): Promise<void> {
const accessToken = requireAccessToken(credentials);
const response = await fetchProvider(`${AIRCALL_API_BASE}/v1/ping`, {
headers: bearerHeaders(accessToken),
});
if (!response.ok) throw mapAircallError(response.status);
}
export async function listAircallUsers(credentials: AircallCredentials, options: PageOptions = {}): Promise<readonly TelephonyProviderUser[]> {
const accessToken = requireAccessToken(credentials);
const perPage = boundedInteger(options.perPage, DEFAULT_PAGE_SIZE, 1, 50);
const maxPages = boundedInteger(options.maxPages, DEFAULT_MAX_PAGES, 1, 100);
const users: TelephonyProviderUser[] = [];
for (let page = 1; page <= maxPages; page += 1) {
const params = new URLSearchParams({ page: String(page), per_page: String(perPage), order: "asc" });
const response = await fetchProvider(`${AIRCALL_API_BASE}/v2/users?${params.toString()}`, {
headers: bearerHeaders(accessToken),
});
const body = await readProviderJson<{ meta?: AircallPaginationMeta; users?: AircallUserV2[] }>(response);
if (!response.ok) throw mapAircallError(response.status);
users.push(...(body.users ?? []).map(toProviderUser).filter(isPresent));
if (!body.meta?.next_page_link) break;
}
return users;
}
export async function listAircallUserNumbers(
credentials: AircallCredentials,
userId: string,
options: PageOptions = {},
): Promise<readonly TelephonyProviderNumber[]> {
assertProviderId(userId, "user");
const accessToken = requireAccessToken(credentials);
const perPage = boundedInteger(options.perPage, DEFAULT_PAGE_SIZE, 1, 50);
const maxPages = boundedInteger(options.maxPages, DEFAULT_MAX_PAGES, 1, 100);
const numbers: TelephonyProviderNumber[] = [];
for (let page = 1; page <= maxPages; page += 1) {
const params = new URLSearchParams({ page: String(page), per_page: String(perPage), order: "asc" });
const response = await fetchProvider(`${AIRCALL_API_BASE}/v2/users/${encodeURIComponent(userId)}/numbers?${params.toString()}`, {
headers: bearerHeaders(accessToken),
});
const body = await readProviderJson<{ meta?: AircallPaginationMeta; numbers?: AircallNumber[] }>(response);
if (!response.ok) throw mapAircallError(response.status);
numbers.push(...(body.numbers ?? []).map(toProviderNumber).filter(isPresent));
if (!body.meta?.next_page_link) break;
}
return numbers;
}
/** Aircall accepts this command only for an available desktop Workspace user. */
export async function startAircallOutboundCall(
credentials: AircallCredentials,
input: TelephonyStartCallInput,
): Promise<TelephonyStartCallResult> {
assertProviderId(input.userId, "user");
assertProviderId(input.numberId, "number");
if (!E164_PATTERN.test(input.to)) throw new AircallError("invalid_request");
const accessToken = requireAccessToken(credentials);
const response = await fetchProvider(`${AIRCALL_API_BASE}/v1/users/${encodeURIComponent(input.userId)}/calls`, {
method: "POST",
headers: bearerHeaders(accessToken, true),
body: JSON.stringify({ number_id: Number(input.numberId), to: input.to }),
});
if (!response.ok) throw mapAircallError(response.status);
return { accepted: true };
}
export async function createAircallWebhook(
credentials: AircallCredentials,
input: TelephonyWebhookRegistrationInput,
): Promise<TelephonyWebhookRegistration> {
const accessToken = requireAccessToken(credentials);
assertHttpsUrl(input.url);
const name = input.name.trim();
if (!name || input.events.length === 0 || input.events.some((event) => !SUPPORTED_WEBHOOK_EVENTS.has(event))) {
throw new AircallError("invalid_request");
}
const response = await fetchProvider(`${AIRCALL_API_BASE}/v1/webhooks`, {
method: "POST",
headers: bearerHeaders(accessToken, true),
body: JSON.stringify({ custom_name: name, url: input.url, events: [...input.events] }),
});
const body = await readProviderJson<{ webhook?: AircallWebhookRecord }>(response);
if (!response.ok) throw mapAircallError(response.status);
const webhook = body.webhook;
const id = stringId(webhook?.webhook_id ?? webhook?.id);
if (!id || !webhook?.token) throw new AircallError("unknown", response.status);
return { id, token: webhook.token, active: webhook.active ?? true, events: webhook.events ?? [...input.events] };
}
export async function deleteAircallWebhook(credentials: AircallCredentials, webhookId: string): Promise<void> {
if (!WEBHOOK_ID_PATTERN.test(webhookId)) throw new AircallError("invalid_request");
const accessToken = requireAccessToken(credentials);
const response = await fetchProvider(`${AIRCALL_API_BASE}/v1/webhooks/${encodeURIComponent(webhookId)}`, {
method: "DELETE",
headers: bearerHeaders(accessToken, true),
});
if (response.ok || response.status === 404) return;
throw mapAircallError(response.status);
}
function bearerHeaders(accessToken: string, json = false): Record<string, string> {
return { authorization: `Bearer ${accessToken}`, ...(json ? { "content-type": "application/json" } : {}) };
}
function requireAccessToken(credentials: AircallCredentials): string {
const accessToken = credentials.accessToken?.trim();
if (!accessToken) throw new AircallError("auth_token_invalid");
return accessToken;
}
function assertProviderId(id: string, kind: "user" | "number"): void {
if (!PROVIDER_ID_PATTERN.test(id)) throw new AircallError("invalid_request", undefined);
if (kind === "number" && !Number.isSafeInteger(Number(id))) throw new AircallError("invalid_request");
}
function assertHttpsUrl(value: string): void {
try {
if (new URL(value).protocol !== "https:") throw new Error("not https");
} catch {
throw new AircallError("invalid_request");
}
}
function boundedInteger(value: number | undefined, fallback: number, min: number, max: number): number {
return Number.isSafeInteger(value) && value! >= min && value! <= max ? value! : fallback;
}
function stringId(value: number | string | null | undefined): string | null {
if (typeof value === "number" && Number.isSafeInteger(value)) return String(value);
if (typeof value === "string" && value.trim()) return value.trim();
return null;
}
function normalizeE164(value: string | undefined): string {
if (!value) return "";
const normalized = value.replace(/[^+\d]/gu, "").replace(/(?!^)\+/gu, "");
return E164_PATTERN.test(normalized) ? normalized : "";
}
function toProviderUser(value: AircallUserV2): TelephonyProviderUser | null {
const id = stringId(value.id);
if (!id || !value.email) return null;
return {
id,
name: value.name?.trim() || value.email,
email: value.email.trim().toLowerCase(),
available: value.available ?? false,
availabilityStatus: value.availability_status?.trim() || null,
defaultNumberId: stringId(value.default_number_id),
};
}
function toProviderNumber(value: AircallNumber): TelephonyProviderNumber | null {
const id = stringId(value.id);
const e164 = normalizeE164(value.e164_digits || value.digits);
if (!id || !e164) return null;
return {
id,
label: value.name?.trim() || e164,
e164,
countryCode: value.country?.trim().toUpperCase() || null,
// Aircall's legacy `open` flag does not reliably describe Smartflows.
// Preserve the provider hint rather than deriving a misleading boolean.
availabilityStatus: value.availability_status?.trim() || null,
};
}
function mapAircallError(status: number): AircallError {
if (status === 401) return new AircallError("auth_token_invalid", status);
if (status === 403) return new AircallError("auth_scope_missing", status);
if (status === 429) return new AircallError("rate_limit_exceeded", status);
if (status === 400 || status === 422) return new AircallError("invalid_request", status);
if (status === 404) return new AircallError("not_found", status);
if (status === 405) return new AircallError("user_unavailable", status);
if (status >= 500) return new AircallError("provider_outage", status);
return new AircallError("unknown", status);
}
function isPresent<T>(value: T | null): value is T {
return value !== null;
}
@@ -0,0 +1,105 @@
import type { AircallCallWebhookEventName, AircallWebhookPayload } from "./types.js";
/** Non-secret token used only by provider-contract tests. */
export const AIRCALL_TEST_WEBHOOK_TOKEN = "fixture-aircall-webhook-token";
export const AIRCALL_ENDED_WEBHOOK_FIXTURE: AircallWebhookPayload = {
resource: "call",
event: "call.ended",
timestamp: 1_725_000_030,
token: AIRCALL_TEST_WEBHOOK_TOKEN,
data: {
id: 81_200,
direction: "inbound",
status: "done",
missed_call_reason: null,
started_at: 1_725_000_000,
answered_at: 1_725_000_005,
ended_at: 1_725_000_030,
duration: 30,
raw_digits: "+49 30 123 45 67",
recording: "https://assets.aircall.test/recordings/call-81200.mp3",
user: { id: 456, name: "Ada Agent", email: "Ada.Agent@example.test" },
number: { id: 673, digits: "+49 30 987 65 4", e164_digits: "+4930987654" },
},
};
export const AIRCALL_MISSED_WEBHOOK_FIXTURE: AircallWebhookPayload = {
resource: "call",
event: "call.ended",
timestamp: 1_725_000_120,
token: AIRCALL_TEST_WEBHOOK_TOKEN,
data: {
id: 81_201,
direction: "inbound",
status: "done",
missed_call_reason: "no_available_agent",
started_at: 1_725_000_100,
answered_at: null,
ended_at: 1_725_000_120,
duration: 20,
raw_digits: "+49307654321",
user: null,
number: { id: 673, e164_digits: "+4930987654" },
},
};
const AIRCALL_LIFECYCLE_BASE_DATA = {
id: 81_202,
direction: "inbound",
status: "initializing",
missed_call_reason: null,
started_at: 1_725_000_200,
answered_at: null,
ended_at: null,
duration: 0,
raw_digits: "+493011122233",
user: { id: 457, name: "Berta Agent", email: "berta.agent@example.test" },
number: { id: 674, e164_digits: "+493044455566" },
} as const;
function lifecycleFixture(
event: AircallCallWebhookEventName,
timestamp: number,
data: Record<string, unknown> = {},
): AircallWebhookPayload {
return {
resource: "call",
event,
timestamp,
token: AIRCALL_TEST_WEBHOOK_TOKEN,
data: { ...AIRCALL_LIFECYCLE_BASE_DATA, ...data },
};
}
/** Deterministic contract fixtures for every Aircall event consumed by AK-P15a. */
export const AIRCALL_WEBHOOK_FIXTURES = {
"call.created": lifecycleFixture("call.created", 1_725_000_200),
"call.ringing_on_agent": lifecycleFixture("call.ringing_on_agent", 1_725_000_201, { status: "ringing" }),
"call.agent_declined": lifecycleFixture("call.agent_declined", 1_725_000_202, { status: "agent_declined" }),
"call.answered": lifecycleFixture("call.answered", 1_725_000_205, {
status: "answered",
answered_at: 1_725_000_205,
duration: 5,
}),
"call.hungup": lifecycleFixture("call.hungup", 1_725_000_229, {
status: "hungup",
answered_at: 1_725_000_205,
duration: 29,
}),
"call.ended": AIRCALL_ENDED_WEBHOOK_FIXTURE,
"call.voicemail_left": lifecycleFixture("call.voicemail_left", 1_725_000_230, {
status: "voicemail",
missed_call_reason: "voicemail",
ended_at: 1_725_000_230,
duration: 30,
asset: "https://assets.aircall.test/voicemails/call-81202.mp3",
}),
"call.comm_assets_generated": lifecycleFixture("call.comm_assets_generated", 1_725_000_231, {
status: "done",
answered_at: 1_725_000_205,
ended_at: 1_725_000_230,
duration: 30,
asset: "https://assets.aircall.test/recordings/call-81202.mp3",
}),
} satisfies Readonly<Record<AircallCallWebhookEventName, AircallWebhookPayload>>;
@@ -0,0 +1,4 @@
export * from "./adapter.js";
export * from "./client.js";
export * from "./types.js";
export * from "./webhook.js";
@@ -0,0 +1,127 @@
import type { TelephonyCallEventType } from "../telephony/provider.js";
/** Decrypted OAuth credential shape. Aircall access tokens are permanent. */
export interface AircallCredentials {
readonly accessToken?: string | null;
}
export interface AircallOAuthConfig {
readonly clientId: string;
readonly clientSecret: string;
readonly redirectUri: string;
}
export interface AircallTokenSet {
readonly accessToken: string;
}
export type AircallErrorCode =
| "auth_token_invalid"
| "auth_scope_missing"
| "rate_limit_exceeded"
| "invalid_request"
| "not_found"
| "user_unavailable"
| "provider_outage"
| "not_configured"
| "unknown";
export class AircallError extends Error {
readonly code: AircallErrorCode;
readonly httpStatus?: number;
constructor(code: AircallErrorCode, httpStatus?: number) {
// Provider response bodies can contain sensitive diagnostics. Never attach
// them to an exception that could be logged by an application boundary.
super(code);
this.name = "AircallError";
this.code = code;
this.httpStatus = httpStatus;
}
}
export interface AircallPaginationMeta {
readonly count?: number;
readonly total?: number;
readonly current_page?: number;
readonly per_page?: number;
readonly next_page_link?: string | null;
}
export interface AircallUserV2 {
readonly id?: number | string;
readonly name?: string;
readonly email?: string;
readonly available?: boolean;
readonly availability_status?: string;
readonly default_number_id?: number | string | null;
}
export interface AircallNumber {
readonly id?: number | string;
readonly name?: string;
readonly digits?: string;
readonly e164_digits?: string;
readonly country?: string;
readonly availability_status?: string;
readonly open?: boolean;
}
export interface AircallWebhookRecord {
readonly webhook_id?: string | number;
readonly id?: string | number;
readonly token?: string;
readonly active?: boolean;
readonly events?: string[];
}
export interface AircallCallData {
readonly id?: number | string;
readonly direction?: string;
readonly status?: string;
readonly missed_call_reason?: string | null;
readonly started_at?: number | string | null;
readonly answered_at?: number | string | null;
readonly ended_at?: number | string | null;
readonly duration?: number | string | null;
readonly recording?: string | null;
readonly recording_short_url?: string | null;
readonly voicemail?: string | null;
readonly voicemail_short_url?: string | null;
readonly asset?: string | null;
readonly raw_digits?: string | null;
readonly user?: { readonly id?: number | string; readonly email?: string; readonly name?: string } | null;
readonly number?: { readonly id?: number | string; readonly digits?: string; readonly e164_digits?: string } | null;
}
export interface AircallWebhookPayload {
readonly resource?: string;
readonly event?: string;
readonly timestamp?: number | string;
readonly token?: string;
readonly data?: AircallCallData;
}
export const AIRCALL_CALL_WEBHOOK_EVENTS = [
"call.created",
"call.ringing_on_agent",
"call.agent_declined",
"call.answered",
"call.hungup",
"call.ended",
"call.voicemail_left",
"call.comm_assets_generated",
] as const;
export type AircallCallWebhookEventName = (typeof AIRCALL_CALL_WEBHOOK_EVENTS)[number];
export const AIRCALL_CALL_EVENT_TYPE: Readonly<Record<AircallCallWebhookEventName, TelephonyCallEventType>> = {
"call.created": "created",
"call.ringing_on_agent": "ringing",
"call.agent_declined": "agent_declined",
"call.answered": "answered",
"call.hungup": "hungup",
"call.ended": "ended",
"call.voicemail_left": "voicemail",
"call.comm_assets_generated": "assets_ready",
};
@@ -0,0 +1,116 @@
import { describe, expect, it } from "vitest";
import {
AIRCALL_ENDED_WEBHOOK_FIXTURE,
AIRCALL_MISSED_WEBHOOK_FIXTURE,
AIRCALL_TEST_WEBHOOK_TOKEN,
AIRCALL_WEBHOOK_FIXTURES,
} from "./fixtures.js";
import { AIRCALL_CALL_EVENT_TYPE } from "./types.js";
import {
getAircallRecordingUrl,
normalizeAircallWebhook,
parseAircallWebhookEvent,
validateAircallWebhook,
verifyAircallWebhookToken,
} from "./webhook.js";
describe("Aircall webhook normalization", () => {
it("normalizes a deterministic fixture for every subscribed Aircall event", () => {
for (const [providerEvent, fixture] of Object.entries(AIRCALL_WEBHOOK_FIXTURES)) {
const result = normalizeAircallWebhook(fixture, AIRCALL_TEST_WEBHOOK_TOKEN);
expect(result).toMatchObject({
ok: true,
event: {
providerEvent,
type: AIRCALL_CALL_EVENT_TYPE[providerEvent as keyof typeof AIRCALL_CALL_EVENT_TYPE],
providerCallId: expect.any(String),
},
});
}
});
it("validates the payload token exactly", () => {
expect(verifyAircallWebhookToken(AIRCALL_TEST_WEBHOOK_TOKEN, AIRCALL_TEST_WEBHOOK_TOKEN)).toBe(true);
expect(verifyAircallWebhookToken(`${AIRCALL_TEST_WEBHOOK_TOKEN}-other`, AIRCALL_TEST_WEBHOOK_TOKEN)).toBe(false);
expect(verifyAircallWebhookToken(null, AIRCALL_TEST_WEBHOOK_TOKEN)).toBe(false);
expect(validateAircallWebhook(AIRCALL_ENDED_WEBHOOK_FIXTURE, AIRCALL_TEST_WEBHOOK_TOKEN)).toBe(true);
expect(validateAircallWebhook(AIRCALL_ENDED_WEBHOOK_FIXTURE, "wrong-token")).toBe(false);
});
it("separates authenticated parsing and resolves the recording from normalized media", () => {
const parsed = parseAircallWebhookEvent(AIRCALL_ENDED_WEBHOOK_FIXTURE);
expect(parsed).toMatchObject({ ok: true, event: { type: "ended" } });
if (!parsed.ok) throw new Error("fixture must parse");
expect(getAircallRecordingUrl(parsed.event)).toBe("https://assets.aircall.test/recordings/call-81200.mp3");
expect(JSON.stringify(parsed)).not.toContain(AIRCALL_TEST_WEBHOOK_TOKEN);
});
it("normalizes call.ended and excludes the webhook token", () => {
const result = normalizeAircallWebhook(AIRCALL_ENDED_WEBHOOK_FIXTURE, AIRCALL_TEST_WEBHOOK_TOKEN);
expect(result).toEqual({
ok: true,
event: {
provider: "aircall",
providerEvent: "call.ended",
type: "ended",
dedupeKey: "aircall:call.ended:81200:1725000030:456",
providerCallId: "81200",
occurredAtIso: "2024-08-30T06:40:30.000Z",
direction: "inbound",
status: "done",
externalNumber: "+49301234567",
lineId: "673",
lineNumber: "+4930987654",
providerUserId: "456",
providerUserEmail: "ada.agent@example.test",
startedAtIso: "2024-08-30T06:40:00.000Z",
answeredAtIso: "2024-08-30T06:40:05.000Z",
endedAtIso: "2024-08-30T06:40:30.000Z",
durationSeconds: 30,
missed: false,
missedReason: null,
recordingUrl: "https://assets.aircall.test/recordings/call-81200.mp3",
voicemailUrl: null,
},
});
expect(JSON.stringify(result)).not.toContain(AIRCALL_TEST_WEBHOOK_TOKEN);
});
it("marks an unanswered terminal inbound event as missed", () => {
const result = normalizeAircallWebhook(AIRCALL_MISSED_WEBHOOK_FIXTURE, AIRCALL_TEST_WEBHOOK_TOKEN);
expect(result).toMatchObject({
ok: true,
event: { type: "ended", providerCallId: "81201", missed: true, missedReason: "no_available_agent" },
});
});
it("does not classify hungup or assets events as missed before call.ended", () => {
for (const providerEvent of ["call.hungup", "call.comm_assets_generated"] as const) {
const result = normalizeAircallWebhook(
{
...AIRCALL_MISSED_WEBHOOK_FIXTURE,
event: providerEvent,
data: { ...AIRCALL_MISSED_WEBHOOK_FIXTURE.data, ended_at: null },
},
AIRCALL_TEST_WEBHOOK_TOKEN,
);
expect(result).toMatchObject({ ok: true, event: { missed: false } });
}
});
it("rejects a wrong token without reflecting it", () => {
const result = normalizeAircallWebhook(AIRCALL_ENDED_WEBHOOK_FIXTURE, "different-expected-token");
expect(result).toEqual({ ok: false, reason: "invalid_token" });
expect(JSON.stringify(result)).not.toContain(AIRCALL_TEST_WEBHOOK_TOKEN);
});
it("rejects non-call and unknown call events", () => {
expect(
normalizeAircallWebhook({ ...AIRCALL_ENDED_WEBHOOK_FIXTURE, resource: "contact", event: "contact.created" }, AIRCALL_TEST_WEBHOOK_TOKEN),
).toEqual({ ok: false, reason: "unsupported_event" });
expect(
normalizeAircallWebhook({ ...AIRCALL_ENDED_WEBHOOK_FIXTURE, event: "call.future_event" }, AIRCALL_TEST_WEBHOOK_TOKEN),
).toEqual({ ok: false, reason: "unsupported_event" });
});
});
@@ -0,0 +1,144 @@
import { timingSafeEqual } from "node:crypto";
import type {
TelephonyCallDirection,
TelephonyCallEvent,
TelephonyWebhookNormalizationResult,
} from "../telephony/provider.js";
import {
AIRCALL_CALL_EVENT_TYPE,
type AircallCallWebhookEventName,
type AircallWebhookPayload,
} from "./types.js";
const MAX_WEBHOOK_TOKEN_BYTES = 2_048;
const E164_PATTERN = /^\+[1-9]\d{1,14}$/u;
/** Exact, constant-time comparison. Neither token is returned or logged. */
export function verifyAircallWebhookToken(receivedToken: unknown, expectedToken: string): boolean {
if (typeof receivedToken !== "string" || !receivedToken || !expectedToken) return false;
const received = Buffer.from(receivedToken, "utf8");
const expected = Buffer.from(expectedToken, "utf8");
if (received.length > MAX_WEBHOOK_TOKEN_BYTES || expected.length > MAX_WEBHOOK_TOKEN_BYTES) return false;
if (received.length !== expected.length) return false;
return timingSafeEqual(received, expected);
}
export function normalizeAircallWebhook(payload: unknown, expectedToken: string): TelephonyWebhookNormalizationResult {
if (!isRecord(payload)) return { ok: false, reason: "invalid_payload" };
if (!validateAircallWebhook(payload, expectedToken)) return { ok: false, reason: "invalid_token" };
return parseAircallWebhookEvent(payload);
}
/** Authenticate Aircall's body token without parsing or reflecting it. */
export function validateAircallWebhook(payload: unknown, expectedToken: string): boolean {
return isRecord(payload) && verifyAircallWebhookToken(payload.token, expectedToken);
}
/** Parse a previously authenticated Aircall payload into the provider-neutral event. */
export function parseAircallWebhookEvent(payload: unknown): TelephonyWebhookNormalizationResult {
if (!isRecord(payload)) return { ok: false, reason: "invalid_payload" };
const raw = payload as AircallWebhookPayload;
if (raw.resource !== "call" || !isSupportedCallEvent(raw.event)) return { ok: false, reason: "unsupported_event" };
if (!isRecord(raw.data)) return { ok: false, reason: "invalid_payload" };
const data = raw.data as AircallWebhookPayload["data"] & Record<string, unknown>;
const user = isRecord(data.user) ? data.user : null;
const number = isRecord(data.number) ? data.number : null;
const providerCallId = stringValue(data.id);
const occurredAtIso = unixTimestampToIso(raw.timestamp);
if (!providerCallId || !occurredAtIso) return { ok: false, reason: "invalid_payload" };
const type = AIRCALL_CALL_EVENT_TYPE[raw.event];
const direction = normalizeDirection(data.direction);
const providerUserId = stringValue(user?.id);
const answeredAtIso = unixTimestampToIso(data.answered_at);
const missedReason = nullableString(data.missed_call_reason);
const terminalEvent = type === "ended" || type === "voicemail";
const event: TelephonyCallEvent = {
provider: "aircall",
providerEvent: raw.event,
type,
dedupeKey: ["aircall", raw.event, providerCallId, String(raw.timestamp), providerUserId ?? "-"].join(":"),
providerCallId,
occurredAtIso,
direction,
status: nullableString(data.status),
externalNumber: normalizePhoneNumber(data.raw_digits),
lineId: stringValue(number?.id),
lineNumber: normalizePhoneNumber(number?.e164_digits) ?? normalizePhoneNumber(number?.digits),
providerUserId,
providerUserEmail: normalizeEmail(user?.email),
startedAtIso: unixTimestampToIso(data.started_at),
answeredAtIso,
endedAtIso: unixTimestampToIso(data.ended_at),
durationSeconds: nonNegativeInteger(data.duration),
missed: terminalEvent && direction === "inbound" && (missedReason !== null || answeredAtIso === null),
missedReason,
recordingUrl: firstUrl(data.recording, data.recording_short_url, type === "assets_ready" ? data.asset : null),
voicemailUrl: firstUrl(data.voicemail, data.voicemail_short_url, type === "voicemail" ? data.asset : null),
};
return { ok: true, event };
}
/** Recording media is supplied by terminal/assets webhooks, not a second API. */
export function getAircallRecordingUrl(event: TelephonyCallEvent): string | null {
return event.recordingUrl ?? event.voicemailUrl;
}
function isSupportedCallEvent(value: unknown): value is AircallCallWebhookEventName {
return typeof value === "string" && Object.prototype.hasOwnProperty.call(AIRCALL_CALL_EVENT_TYPE, value);
}
function normalizeDirection(value: unknown): TelephonyCallDirection {
return value === "inbound" || value === "outbound" ? value : "unknown";
}
function unixTimestampToIso(value: unknown): string | null {
const numeric = typeof value === "string" && value.trim() ? Number(value) : value;
if (typeof numeric !== "number" || !Number.isFinite(numeric) || numeric < 0) return null;
const milliseconds = numeric >= 1_000_000_000_000 ? numeric : numeric * 1_000;
const date = new Date(milliseconds);
return Number.isNaN(date.getTime()) ? null : date.toISOString();
}
function nonNegativeInteger(value: unknown): number | null {
const numeric = typeof value === "string" && value.trim() ? Number(value) : value;
return typeof numeric === "number" && Number.isSafeInteger(numeric) && numeric >= 0 ? numeric : null;
}
function stringValue(value: unknown): string | null {
if (typeof value === "number" && Number.isSafeInteger(value)) return String(value);
return typeof value === "string" && value.trim() ? value.trim() : null;
}
function nullableString(value: unknown): string | null {
return typeof value === "string" && value.trim() ? value.trim() : null;
}
function normalizeEmail(value: unknown): string | null {
return typeof value === "string" && value.trim() ? value.trim().toLowerCase() : null;
}
function normalizePhoneNumber(value: unknown): string | null {
if (typeof value !== "string" || !value.trim()) return null;
const normalized = value.trim().replace(/[^+\d]/gu, "").replace(/(?!^)\+/gu, "");
return E164_PATTERN.test(normalized) ? normalized : null;
}
function firstUrl(...values: unknown[]): string | null {
for (const value of values) {
if (typeof value !== "string" || !value) continue;
try {
const url = new URL(value);
if (url.protocol === "https:") return url.toString();
} catch {
// Ignore malformed provider URLs instead of leaking them downstream.
}
}
return null;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}