The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Add the Teams activities route (#28000)
Abdul Rahmanec593a4fe718
diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/__tests__/teams-activities-resolver.test.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/__tests__/teams-activities-resolver.test.tsnew file mode 100644index 00000000000..03dd3cff432--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/__tests__/teams-activities-resolver.test.ts@@ -0,0 +1,156 @@+import { Response } from 'twenty-sdk/logic-function';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { TEAMS_ACTIVITIES_ENQUEUE_UNIVERSAL_IDENTIFIER } from 'src/features/chat/constants/universal-identifiers';+import { teamsActivitiesResolverHandler } from 'src/features/chat/logic-functions/teams-activities-resolver';+import { TeamsActivityTokenInvalidError } from 'src/features/chat/logic-functions/types/teams-activity-token-invalid-error';+import { type TeamsInboundActivity } from 'src/features/chat/logic-functions/types/teams-inbound-activity.type';++const { kvGetMock, verifyTokenMock } = vi.hoisted(() => ({+ kvGetMock: vi.fn(),+ verifyTokenMock: vi.fn(),+}));++vi.mock('twenty-sdk/logic-function', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ kv: { get: kvGetMock },+}));++vi.mock(+ 'src/features/chat/logic-functions/utils/verify-teams-activity-token',+ () => ({ verifyTeamsActivityTokenOrThrow: verifyTokenMock }),+);++const SERVICE_URL = 'https://smba.trafficmanager.net/emea/';++const MESSAGE_ACTIVITY: TeamsInboundActivity = {+ type: 'message',+ id: 'activity-1',+ text: 'hello',+ serviceUrl: SERVICE_URL,+ conversation: { id: 'conversation-1', conversationType: 'personal' },+ channelData: { tenant: { id: 'tenant-1' } },+};++const resolve = (activity: TeamsInboundActivity | null) =>+ teamsActivitiesResolverHandler({+ headers: { authorization: 'Bearer bot-framework-token' },+ body: activity,+ });++describe('teamsActivitiesResolverHandler', () => {+ beforeEach(() => {+ vi.resetAllMocks();+ vi.stubEnv('TEAMS_BOT_APP_ID', 'bot-app-id');+ vi.stubEnv('TEAMS_BOT_APP_PASSWORD', 'bot-app-password');+ vi.stubEnv('TEAMS_BOT_TENANT_ID', 'bot-tenant-id');+ verifyTokenMock.mockResolvedValue(SERVICE_URL);+ kvGetMock.mockResolvedValue('workspace-1');+ });++ it('routes a verified message to the workspace that claimed its tenant', async () => {+ const result = await resolve(MESSAGE_ACTIVITY);++ expect(result).toEqual({+ workspaceId: 'workspace-1',+ targetLogicFunctionUniversalIdentifier:+ TEAMS_ACTIVITIES_ENQUEUE_UNIVERSAL_IDENTIFIER,+ payload: {+ activity: MESSAGE_ACTIVITY,+ serviceUrl: SERVICE_URL,+ tenantId: 'tenant-1',+ },+ });+ expect(verifyTokenMock.mock.calls).toEqual([+ [+ {+ authorizationHeader: 'Bearer bot-framework-token',+ activityServiceUrl: SERVICE_URL,+ botAppId: 'bot-app-id',+ },+ ],+ ]);+ expect(kvGetMock.mock.calls).toEqual([+ ['teams-tenant:tenant-1', { scope: 'SERVER' }],+ ]);+ });++ it('rejects an activity whose token does not verify', async () => {+ verifyTokenMock.mockRejectedValue(+ new TeamsActivityTokenInvalidError('signature verification failed'),+ );++ const result = await resolve(MESSAGE_ACTIVITY);++ expect(result).toEqual(+ new Response({ error: 'Unauthorized' }, { status: 401 }),+ );+ expect(kvGetMock).not.toHaveBeenCalled();+ });++ it('fails with a server error when the signing keys cannot be loaded', async () => {+ verifyTokenMock.mockRejectedValue(new Error('Key endpoint unavailable'));++ await expect(resolve(MESSAGE_ACTIVITY)).rejects.toThrow(+ 'Key endpoint unavailable',+ );+ expect(kvGetMock).not.toHaveBeenCalled();+ });++ it('refuses activities while the bot credentials are not configured', async () => {+ vi.stubEnv('TEAMS_BOT_APP_ID', '');++ const result = await resolve(MESSAGE_ACTIVITY);++ expect(result).toBeInstanceOf(Response);+ expect(result).toMatchObject({ status: 503 });+ expect(verifyTokenMock).not.toHaveBeenCalled();+ });++ it.each([+ [+ 'a body without a serviceUrl',+ null,+ new Response({ error: 'Missing Teams activity' }, { status: 400 }),+ ],+ [+ 'a non-message activity',+ { ...MESSAGE_ACTIVITY, type: 'conversationUpdate' },+ new Response({ ok: true, skipped: 'Not a message' }),+ ],+ [+ 'an activity without a tenant',+ { ...MESSAGE_ACTIVITY, channelData: undefined },+ new Response({ ok: true, skipped: 'No tenant on the activity' }),+ ],+ ])('does not dispatch %s', async (_, activity, expectedResponse) => {+ expect(await resolve(activity)).toEqual(expectedResponse);+ expect(kvGetMock).not.toHaveBeenCalled();+ });++ it('reads the tenant from the conversation when channelData has none', async () => {+ const result = await resolve({+ ...MESSAGE_ACTIVITY,+ channelData: undefined,+ conversation: { id: 'conversation-1', tenantId: 'tenant-2' },+ });++ expect(result).toMatchObject({ payload: { tenantId: 'tenant-2' } });+ expect(kvGetMock.mock.calls).toEqual([+ ['teams-tenant:tenant-2', { scope: 'SERVER' }],+ ]);+ });++ it('does not dispatch when no workspace claims the tenant', async () => {+ kvGetMock.mockResolvedValue(null);++ const result = await resolve(MESSAGE_ACTIVITY);++ expect(result).toEqual(+ new Response({+ ok: true,+ skipped: 'No workspace claims this Teams tenant',+ }),+ );+ });+});diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/teams-activities-resolver.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/teams-activities-resolver.tsnew file mode 100644index 00000000000..2ebe38c0728--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/teams-activities-resolver.ts@@ -0,0 +1,96 @@+import { isNonEmptyString } from '@sniptt/guards';+import { defineLogicFunction, type RoutePayload } from 'twenty-sdk/define';+import {+ kv,+ Response,+ type ServerRouteResolverResult,+} from 'twenty-sdk/logic-function';++import {+ TEAMS_ACTIVITIES_ENQUEUE_UNIVERSAL_IDENTIFIER,+ TEAMS_ACTIVITIES_ROUTE_UNIVERSAL_IDENTIFIER,+} from 'src/features/chat/constants/universal-identifiers';+import { type TeamsActivitiesDispatchPayload } from 'src/features/chat/logic-functions/types/teams-activities-dispatch-payload.type';+import { TeamsActivityTokenInvalidError } from 'src/features/chat/logic-functions/types/teams-activity-token-invalid-error';+import { type TeamsInboundActivity } from 'src/features/chat/logic-functions/types/teams-inbound-activity.type';+import { buildTeamsTenantKvKey } from 'src/features/chat/logic-functions/utils/build-teams-tenant-kv-key';+import { getTeamsBotCredentials } from 'src/features/chat/logic-functions/utils/get-teams-bot-credentials';+import { verifyTeamsActivityTokenOrThrow } from 'src/features/chat/logic-functions/utils/verify-teams-activity-token';++export const teamsActivitiesResolverHandler = async (+ routePayload: Pick<RoutePayload<TeamsInboundActivity>, 'headers' | 'body'>,+): Promise<ServerRouteResolverResult> => {+ const activity = routePayload.body;++ if (!isNonEmptyString(activity?.serviceUrl)) {+ return new Response({ error: 'Missing Teams activity' }, { status: 400 });+ }++ const botCredentials = getTeamsBotCredentials();++ if (!botCredentials.success) {+ return new Response({ error: botCredentials.error }, { status: 503 });+ }++ const serviceUrl = await verifyTeamsActivityTokenOrThrow({+ authorizationHeader: routePayload.headers.authorization,+ activityServiceUrl: activity.serviceUrl,+ botAppId: botCredentials.credentials.appId,+ }).catch((error: unknown) => {+ if (error instanceof TeamsActivityTokenInvalidError) {+ return null;+ }++ throw error;+ });++ if (!isNonEmptyString(serviceUrl)) {+ return new Response({ error: 'Unauthorized' }, { status: 401 });+ }++ if (activity.type !== 'message') {+ return new Response({ ok: true, skipped: 'Not a message' });+ }++ const tenantId =+ activity.channelData?.tenant?.id ?? activity.conversation?.tenantId;++ if (!isNonEmptyString(tenantId)) {+ return new Response({ ok: true, skipped: 'No tenant on the activity' });+ }++ const workspaceId = await kv.get<string>(buildTeamsTenantKvKey(tenantId), {+ scope: 'SERVER',+ });++ if (!isNonEmptyString(workspaceId)) {+ return new Response({+ ok: true,+ skipped: 'No workspace claims this Teams tenant',+ });+ }++ return {+ workspaceId,+ targetLogicFunctionUniversalIdentifier:+ TEAMS_ACTIVITIES_ENQUEUE_UNIVERSAL_IDENTIFIER,+ payload: {+ activity,+ serviceUrl,+ tenantId,+ } satisfies TeamsActivitiesDispatchPayload,+ };+};++export default defineLogicFunction({+ universalIdentifier: TEAMS_ACTIVITIES_ROUTE_UNIVERSAL_IDENTIFIER,+ name: 'teams-activities-resolver',+ description:+ 'Receives Microsoft Teams bot activities, verifies the Bot Framework token, and routes message activities to the workspace that claimed their tenant.',+ timeoutSeconds: 15,+ handler: teamsActivitiesResolverHandler,+ serverRouteTriggerSettings: {+ httpMethods: ['POST'],+ forwardedRequestHeaders: ['authorization'],+ },+});diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/types/teams-activity-token-invalid-error.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/types/teams-activity-token-invalid-error.tsnew file mode 100644index 00000000000..6c06c7c365d--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/types/teams-activity-token-invalid-error.ts@@ -0,0 +1 @@+export class TeamsActivityTokenInvalidError extends Error {}diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/types/teams-inbound-activity.type.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/types/teams-inbound-activity.type.tsindex 48494e6f718..222cde81573 100644--- a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/types/teams-inbound-activity.type.ts+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/types/teams-inbound-activity.type.ts@@ -5,11 +5,16 @@ export type TeamsInboundActivity = {type?: string;id?: string;text?: string;+ serviceUrl?: string;from?: TeamsChannelAccount;recipient?: TeamsChannelAccount;conversation?: {id?: string;conversationType?: string;+ tenantId?: string;+ };+ channelData?: {+ tenant?: { id?: string };};entities?: TeamsActivityEntity[];};diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/__tests__/verify-teams-activity-token.test.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/__tests__/verify-teams-activity-token.test.tsindex 598edac94f8..2486b8a8a5d 100644--- a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/__tests__/verify-teams-activity-token.test.ts+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/__tests__/verify-teams-activity-token.test.ts@@ -3,6 +3,7 @@ import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';import { TEAMS_BOT_CONNECTOR_ISSUER } from 'src/features/chat/logic-functions/constants/teams-bot-connector-issuer';import { TEAMS_CHANNEL_ID } from 'src/features/chat/logic-functions/constants/teams-channel-id';+import { TeamsActivityTokenInvalidError } from 'src/features/chat/logic-functions/types/teams-activity-token-invalid-error';import { type TeamsBotConnectorKey } from 'src/features/chat/logic-functions/types/teams-bot-connector-key.type';import { verifyTeamsActivityTokenOrThrow } from 'src/features/chat/logic-functions/utils/verify-teams-activity-token';@@ -160,6 +161,16 @@ describe('verifyTeamsActivityTokenOrThrow', () => {).rejects.toThrow('Missing or malformed Authorization header');});+ it('should let a signing key load failure through rather than report the token as invalid', async () => {+ const keyLoadError = new Error('Key endpoint unavailable');++ loadKeysMock.mockRejectedValue(keyLoadError);++ await expect(verifyToken(await signActivityToken())).rejects.toBe(+ keyLoadError,+ );+ });+it('should reject a token signed with a key the Bot Connector does not publish', async () => {await expect(verifyToken(await signActivityToken({ keyId: 'unknown-key' })),@@ -176,7 +187,7 @@ describe('verifyTeamsActivityTokenOrThrow', () => {it('should reject a token from another issuer', async () => {await expect(verifyToken(await signActivityToken({ issuer: 'https://evil.example' })),- ).rejects.toThrow();+ ).rejects.toBeInstanceOf(TeamsActivityTokenInvalidError);});it('should reject a token minted for another bot', async () => {@@ -184,13 +195,13 @@ describe('verifyTeamsActivityTokenOrThrow', () => {verifyToken(await signActivityToken({ audience: 'someone-elses-app-id' }),),- ).rejects.toThrow();+ ).rejects.toBeInstanceOf(TeamsActivityTokenInvalidError);});it('should reject an expired token beyond the clock tolerance', async () => {await expect(verifyToken(await signActivityToken({ expiresIn: '-10m' })),- ).rejects.toThrow();+ ).rejects.toBeInstanceOf(TeamsActivityTokenInvalidError);});it('should reject a token whose serviceUrl claim points elsewhere', async () => {@@ -218,6 +229,8 @@ describe('verifyTeamsActivityTokenOrThrow', () => {.setExpirationTime('5m').sign(symmetricSecret);- await expect(verifyToken(forgedToken)).rejects.toThrow();+ await expect(verifyToken(forgedToken)).rejects.toBeInstanceOf(+ TeamsActivityTokenInvalidError,+ );});});diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/resolve-teams-bot-connector-key-or-throw.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/resolve-teams-bot-connector-key-or-throw.tsindex 0d8858e256b..5fc4b08cf85 100644--- a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/resolve-teams-bot-connector-key-or-throw.ts+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/resolve-teams-bot-connector-key-or-throw.ts@@ -1,6 +1,7 @@import { isDefined } from 'twenty-sdk/utils';import { type LoadTeamsBotConnectorKeys } from 'src/features/chat/logic-functions/types/load-teams-bot-connector-keys.type';+import { TeamsActivityTokenInvalidError } from 'src/features/chat/logic-functions/types/teams-activity-token-invalid-error';import { type TeamsBotConnectorKey } from 'src/features/chat/logic-functions/types/teams-bot-connector-key.type';import { getTeamsBotConnectorKeys } from 'src/features/chat/logic-functions/utils/get-teams-bot-connector-keys';@@ -34,7 +35,7 @@ export const resolveTeamsBotConnectorKeyOrThrow = async ({return refreshedKey;}- throw new Error(+ throw new TeamsActivityTokenInvalidError('Teams activity token is signed with a key the Bot Connector does not publish',);};diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/verify-teams-activity-token.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/verify-teams-activity-token.tsindex 48157ebceab..a1bb33ce837 100644--- a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/verify-teams-activity-token.ts+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/verify-teams-activity-token.ts@@ -1,10 +1,11 @@import { isNonEmptyString } from '@sniptt/guards';-import { decodeProtectedHeader, importJWK, jwtVerify } from 'jose';+import { decodeProtectedHeader, errors, importJWK, jwtVerify } from 'jose';import { isDefined } from 'twenty-sdk/utils';import { TEAMS_BOT_CONNECTOR_ISSUER } from 'src/features/chat/logic-functions/constants/teams-bot-connector-issuer';import { TEAMS_JWT_CLOCK_TOLERANCE_SECONDS } from 'src/features/chat/logic-functions/constants/teams-jwt-clock-tolerance-seconds';import { type LoadTeamsBotConnectorKeys } from 'src/features/chat/logic-functions/types/load-teams-bot-connector-keys.type';+import { TeamsActivityTokenInvalidError } from 'src/features/chat/logic-functions/types/teams-activity-token-invalid-error';import { isTeamsEndorsedKey } from 'src/features/chat/logic-functions/utils/is-teams-endorsed-key';import { normalizeTeamsServiceUrl } from 'src/features/chat/logic-functions/utils/normalize-teams-service-url';import { resolveTeamsBotConnectorKeyOrThrow } from 'src/features/chat/logic-functions/utils/resolve-teams-bot-connector-key-or-throw';@@ -58,7 +59,7 @@ export const verifyTeamsActivityTokenOrThrow = async ({const token = extractBearerToken(authorizationHeader);if (!isDefined(token)) {- throw new Error(+ throw new TeamsActivityTokenInvalidError('Missing or malformed Authorization header on the Teams activity',);}@@ -66,7 +67,9 @@ export const verifyTeamsActivityTokenOrThrow = async ({const keyId = readKeyId(token);if (!isDefined(keyId)) {- throw new Error('Teams activity token names no signing key');+ throw new TeamsActivityTokenInvalidError(+ 'Teams activity token names no signing key',+ );}const signingKey = await resolveTeamsBotConnectorKeyOrThrow({@@ -75,7 +78,7 @@ export const verifyTeamsActivityTokenOrThrow = async ({});if (!isTeamsEndorsedKey(signingKey)) {- throw new Error(+ throw new TeamsActivityTokenInvalidError('Teams activity token is signed with a key not endorsed for Teams',);}@@ -89,18 +92,26 @@ export const verifyTeamsActivityTokenOrThrow = async ({algorithms: ['RS256'],clockTolerance: TEAMS_JWT_CLOCK_TOLERANCE_SECONDS,},- );+ ).catch((error: unknown) => {+ if (error instanceof errors.JOSEError) {+ throw new TeamsActivityTokenInvalidError(error.message);+ }++ throw error;+ });const serviceUrlClaim = readServiceUrlClaim(payload);if (!isDefined(serviceUrlClaim)) {- throw new Error('Teams activity token has no serviceUrl claim');+ throw new TeamsActivityTokenInvalidError(+ 'Teams activity token has no serviceUrl claim',+ );}const verifiedServiceUrl = normalizeTeamsServiceUrl(serviceUrlClaim);if (verifiedServiceUrl !== normalizeTeamsServiceUrl(activityServiceUrl)) {- throw new Error(+ throw new TeamsActivityTokenInvalidError('Teams activity serviceUrl does not match the serviceUrl claim',);}