Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

feat(core): add typed schema for connection expired webhook events

jkomynob6aa489d455d
diff --git a/python/composio/__init__.py b/python/composio/__init__.py
index 033f38717..873185230 100644
--- a/python/composio/__init__.py
+++ b/python/composio/__init__.py
@@ -4,6 +4,16 @@ from .core.models.tools import (
before_execute,
schema_modifier,
)
+from .core.models.webhook_events import (
+ ConnectionExpiredEvent,
+ ConnectionState,
+ ConnectionStatusEnum,
+ SingleConnectedAccountDetailedResponse,
+ WebhookConnectionMetadata,
+ WebhookEvent,
+ WebhookEventType,
+ is_connection_expired_event,
+)
from .core.types import (
ToolkitLatestVersion,
ToolkitVersion,
@@ -14,8 +24,16 @@ from .sdk import Composio
__all__ = (
"Composio",
+ "ConnectionExpiredEvent",
+ "ConnectionState",
+ "ConnectionStatusEnum",
+ "SingleConnectedAccountDetailedResponse",
+ "WebhookConnectionMetadata",
+ "WebhookEvent",
+ "WebhookEventType",
"after_execute",
"before_execute",
+ "is_connection_expired_event",
"schema_modifier",
"__version__",
"ToolkitLatestVersion",
diff --git a/python/composio/core/models/__init__.py b/python/composio/core/models/__init__.py
index 667535670..85e1c55a2 100644
--- a/python/composio/core/models/__init__.py
+++ b/python/composio/core/models/__init__.py
@@ -5,13 +5,31 @@ from .tool_router import ToolRouter
from .toolkits import Toolkits
from .tools import Tools
from .triggers import Triggers
+from .webhook_events import (
+ ConnectionExpiredEvent,
+ ConnectionState,
+ ConnectionStatusEnum,
+ SingleConnectedAccountDetailedResponse,
+ WebhookConnectionMetadata,
+ WebhookEvent,
+ WebhookEventType,
+ is_connection_expired_event,
+)
__all__ = [
"AuthConfigs",
"ConnectedAccounts",
+ "ConnectionExpiredEvent",
+ "ConnectionState",
+ "ConnectionStatusEnum",
"MCP",
+ "SingleConnectedAccountDetailedResponse",
"ToolRouter",
"Toolkits",
"Tools",
"Triggers",
+ "WebhookConnectionMetadata",
+ "WebhookEvent",
+ "WebhookEventType",
+ "is_connection_expired_event",
]
diff --git a/python/composio/core/models/webhook_events.py b/python/composio/core/models/webhook_events.py
new file mode 100644
index 000000000..929451c20
--- /dev/null
+++ b/python/composio/core/models/webhook_events.py
@@ -0,0 +1,183 @@
+"""
+Webhook event types for typed event handling.
+
+This module provides TypedDict definitions for specific webhook event types,
+enabling type-safe handling of events like connection expiration.
+"""
+
+from __future__ import annotations
+
+import typing as t
+from enum import Enum
+
+import typing_extensions as te
+
+
+class WebhookEventType(str, Enum):
+ """Known webhook event types."""
+
+ CONNECTION_EXPIRED = "composio.connected_account.expired"
+
+
+class ConnectionStatusEnum(str, Enum):
+ """Connection status values."""
+
+ INITIALIZING = "INITIALIZING"
+ INITIATED = "INITIATED"
+ ACTIVE = "ACTIVE"
+ FAILED = "FAILED"
+ EXPIRED = "EXPIRED"
+ INACTIVE = "INACTIVE"
+
+
+# =============================================================================
+# CONNECTED ACCOUNT DATA (matches GET /api/v3/connected_accounts/{id})
+# =============================================================================
+
+
+class ConnectedAccountToolkit(te.TypedDict):
+ """Toolkit information in connected account response."""
+
+ slug: str
+
+
+class ConnectedAccountAuthConfigDeprecated(te.TypedDict, total=False):
+ """Deprecated auth config fields."""
+
+ uuid: str
+
+
+class ConnectedAccountAuthConfig(te.TypedDict, total=False):
+ """Auth config details in connected account response."""
+
+ id: te.Required[str]
+ auth_scheme: te.Required[str]
+ is_composio_managed: te.Required[bool]
+ is_disabled: te.Required[bool]
+ deprecated: ConnectedAccountAuthConfigDeprecated
+
+
+class ConnectionStateVal(te.TypedDict, total=False):
+ """Connection state value - varies by auth scheme."""
+
+ status: str
+ # OAuth2 fields
+ access_token: str
+ refresh_token: t.Optional[str]
+ token_type: str
+ expires_in: t.Union[int, str, None]
+ scope: t.Union[str, t.List[str], None]
+ id_token: str
+ code_verifier: str
+ callback_url: str
+ # OAuth1 fields
+ oauth_token: str
+ oauth_token_secret: str
+ # API Key fields
+ api_key: str
+ generic_api_key: str
+ # Bearer Token fields
+ token: str
+ # Basic auth fields
+ username: str
+ password: str
+
+
+class ConnectionState(te.TypedDict):
+ """Connection state data discriminated by auth scheme."""
+
+ authScheme: str
+ val: ConnectionStateVal
+
+
+class ConnectedAccountDeprecated(te.TypedDict, total=False):
+ """Deprecated connected account fields."""
+
+ labels: t.List[str]
+ uuid: str
+
+
+class SingleConnectedAccountDetailedResponse(te.TypedDict, total=False):
+ """
+ Connected account data matching GET /api/v3/connected_accounts/{id} response.
+
+ This is used in webhook payloads for connection lifecycle events.
+ """
+
+ toolkit: te.Required[ConnectedAccountToolkit]
+ auth_config: te.Required[ConnectedAccountAuthConfig]
+ id: te.Required[str]
+ user_id: te.Required[str]
+ status: te.Required[str] # ConnectionStatusEnum value
+ created_at: te.Required[str]
+ updated_at: te.Required[str]
+ state: te.Required[ConnectionState]
+ data: te.Required[t.Dict[str, t.Any]]
+ params: te.Required[t.Dict[str, t.Any]]
+ status_reason: te.Required[t.Optional[str]]
+ is_disabled: te.Required[bool]
+ test_request_endpoint: str
+ deprecated: ConnectedAccountDeprecated
+
+
+# =============================================================================
+# CONNECTION EXPIRED WEBHOOK EVENT
+# =============================================================================
+
+
+class WebhookConnectionMetadata(te.TypedDict):
+ """Webhook metadata for connection events."""
+
+ project_id: str
+ org_id: str
+
+
+class ConnectionExpiredEvent(te.TypedDict):
+ """
+ Connection expired webhook event payload.
+
+ Emitted when a connected account expires due to authentication refresh failure.
+
+ Example:
+ >>> from composio.core.models.webhook_events import ConnectionExpiredEvent
+ >>>
+ >>> def handle_webhook(payload: dict) -> None:
+ ... if payload.get("type") == "composio.connected_account.expired":
+ ... event: ConnectionExpiredEvent = payload # type: ignore
+ ... print(f"Connection {event['data']['id']} expired")
+ ... print(f"Toolkit: {event['data']['toolkit']['slug']}")
+ ... print(f"User: {event['data']['user_id']}")
+ """
+
+ id: str # Unique message ID (e.g., "msg_847cdfcd-d219-4f18-a6dd-91acd42ca94a")
+ timestamp: str # ISO-8601 timestamp
+ type: t.Literal["composio.connected_account.expired"]
+ data: SingleConnectedAccountDetailedResponse
+ metadata: WebhookConnectionMetadata
+
+
+# Type alias for all webhook events
+WebhookEvent = t.Union[ConnectionExpiredEvent]
+
+
+def is_connection_expired_event(payload: t.Dict[str, t.Any]) -> bool:
+ """
+ Check if a webhook payload is a connection expired event.
+
+ :param payload: The webhook payload to check
+ :return: True if this is a connection expired event
+
+ Example:
+ >>> from composio.core.models.webhook_events import (
+ ... is_connection_expired_event,
+ ... ConnectionExpiredEvent,
+ ... )
+ >>>
+ >>> if is_connection_expired_event(payload):
+ ... event: ConnectionExpiredEvent = payload # type: ignore
+ ... handle_connection_expired(event)
+ """
+ return (
+ isinstance(payload, dict)
+ and payload.get("type") == WebhookEventType.CONNECTION_EXPIRED.value
+ )
diff --git a/python/tests/test_webhook_events.py b/python/tests/test_webhook_events.py
new file mode 100644
index 000000000..d19dc1bc1
--- /dev/null
+++ b/python/tests/test_webhook_events.py
@@ -0,0 +1,129 @@
+"""Tests for webhook event types."""
+
+import pytest
+
+from composio.core.models.webhook_events import (
+ ConnectionExpiredEvent,
+ WebhookEventType,
+ is_connection_expired_event,
+)
+
+
+class TestWebhookEventType:
+ """Tests for WebhookEventType enum."""
+
+ def test_connection_expired_value(self) -> None:
+ """Should have correct value for CONNECTION_EXPIRED."""
+ assert (
+ WebhookEventType.CONNECTION_EXPIRED.value
+ == "composio.connected_account.expired"
+ )
+
+
+class TestIsConnectionExpiredEvent:
+ """Tests for is_connection_expired_event helper function."""
+
+ @pytest.fixture
+ def valid_payload(self) -> dict:
+ """Return a valid connection expired event payload."""
+ return {
+ "id": "msg_847cdfcd-d219-4f18-a6dd-91acd42ca94a",
+ "timestamp": "2026-02-02T10:14:20.955Z",
+ "type": "composio.connected_account.expired",
+ "data": {
+ "toolkit": {"slug": "gmail"},
+ "auth_config": {
+ "id": "ac_izZGRCZ9qyxk",
+ "auth_scheme": "OAUTH2",
+ "is_composio_managed": True,
+ "is_disabled": False,
+ },
+ "id": "ca__IvSeEzEBjVt",
+ "user_id": "test-user",
+ "status": "EXPIRED",
+ "created_at": "2026-02-02T08:35:44.272Z",
+ "updated_at": "2026-02-02T10:14:20.949Z",
+ "state": {
+ "authScheme": "OAUTH2",
+ "val": {"status": "EXPIRED"},
+ },
+ "data": {},
+ "params": {},
+ "status_reason": None,
+ "is_disabled": False,
+ },
+ "metadata": {
+ "project_id": "pr_koucdrMIwRsf",
+ "org_id": "4a4ded8f-d3ae-4dea-a229-c30234298b05",
+ },
+ }
+
+ def test_returns_true_for_valid_payload(self, valid_payload: dict) -> None:
+ """Should return True for a valid connection expired event."""
+ assert is_connection_expired_event(valid_payload) is True
+
+ def test_returns_false_for_trigger_message(self) -> None:
+ """Should return False for a trigger message event."""
+ payload = {
+ "id": "msg_123",
+ "timestamp": "2026-02-02T10:14:20.955Z",
+ "type": "composio.trigger.message",
+ "data": {},
+ "metadata": {},
+ }
+ assert is_connection_expired_event(payload) is False
+
+ def test_returns_false_for_none(self) -> None:
+ """Should return False for None input."""
+ assert is_connection_expired_event(None) is False # type: ignore
+
+ def test_returns_false_for_string(self) -> None:
+ """Should return False for string input."""
+ assert is_connection_expired_event("string") is False # type: ignore
+
+ def test_returns_false_for_empty_dict(self) -> None:
+ """Should return False for empty dict."""
+ assert is_connection_expired_event({}) is False
+
+ def test_returns_false_for_missing_type(self, valid_payload: dict) -> None:
+ """Should return False when type field is missing."""
+ del valid_payload["type"]
+ assert is_connection_expired_event(valid_payload) is False
+
+
+class TestConnectionExpiredEventType:
+ """Tests for ConnectionExpiredEvent TypedDict structure."""
+
+ def test_type_annotation(self) -> None:
+ """Should have correct type annotations."""
+ # This test verifies the TypedDict can be used for type hints
+ event: ConnectionExpiredEvent = {
+ "id": "msg_123",
+ "timestamp": "2026-02-02T10:14:20.955Z",
+ "type": "composio.connected_account.expired",
+ "data": {
+ "toolkit": {"slug": "gmail"},
+ "auth_config": {
+ "id": "ac_123",
+ "auth_scheme": "OAUTH2",
+ "is_composio_managed": True,
+ "is_disabled": False,
+ },
+ "id": "ca_123",
+ "user_id": "user_123",
+ "status": "EXPIRED",
+ "created_at": "2026-02-02T08:35:44.272Z",
+ "updated_at": "2026-02-02T10:14:20.949Z",
+ "state": {"authScheme": "OAUTH2", "val": {}},
+ "data": {},
+ "params": {},
+ "status_reason": None,
+ "is_disabled": False,
+ },
+ "metadata": {"project_id": "pr_123", "org_id": "org_123"},
+ }
+
+ # Verify type narrowing works
+ assert event["type"] == "composio.connected_account.expired"
+ assert event["data"]["toolkit"]["slug"] == "gmail"
+ assert event["metadata"]["project_id"] == "pr_123"
diff --git a/ts/packages/core/src/index.ts b/ts/packages/core/src/index.ts
index 501503b49..a35acb8bb 100644
--- a/ts/packages/core/src/index.ts
+++ b/ts/packages/core/src/index.ts
@@ -17,6 +17,7 @@ export * from './types/connectedAccountAuthStates.types';
export * from './types/connectedAccounts.types';
export * from './types/toolkit.types';
export * from './types/triggers.types';
+export * from './types/webhookEvents.types';
export * from './types/mcp.types';
export * from './types/files.types';
export * from './types/connectionRequest.types';
diff --git a/ts/packages/core/src/types/webhookEvents.types.ts b/ts/packages/core/src/types/webhookEvents.types.ts
new file mode 100644
index 000000000..4993e6b08
--- /dev/null
+++ b/ts/packages/core/src/types/webhookEvents.types.ts
@@ -0,0 +1,164 @@
+import { z } from 'zod/v3';
+import { AuthSchemeTypes } from './authConfigs.types';
+import { ConnectionStatuses } from './connectedAccountAuthStates.types';
+
+// =============================================================================
+// WEBHOOK EVENT TYPES
+// =============================================================================
+
+export const WebhookEventTypes = {
+ CONNECTION_EXPIRED: 'composio.connected_account.expired',
+} as const;
+
+export type WebhookEventType = (typeof WebhookEventTypes)[keyof typeof WebhookEventTypes];
+
+// =============================================================================
+// CONNECTED ACCOUNT DATA SCHEMA (matches GET /api/v3/connected_accounts/{id})
+// =============================================================================
+
+/**
+ * Auth config details included in the connected account response.
+ */
+export const ConnectedAccountAuthConfigSchema = z.object({
+ /** The nano ID of the auth config */
+ id: z.string(),
+ /** @deprecated - use state.authScheme instead */
+ auth_scheme: z.nativeEnum(AuthSchemeTypes),
+ /** Whether this auth config is managed by Composio */
+ is_composio_managed: z.boolean(),
+ /** Whether the auth config is disabled */
+ is_disabled: z.boolean(),
+ /** @deprecated */
+ deprecated: z
+ .object({
+ uuid: z.string(),
+ })
+ .optional(),
+});
+
+export type ConnectedAccountAuthConfig = z.infer<typeof ConnectedAccountAuthConfigSchema>;
+
+/**
+ * Simplified connection state schema for webhook payloads.
+ * The full ConnectionDataSchema is too complex for webhook validation;
+ * this schema accepts any auth scheme and state values.
+ */
+export const WebhookConnectionStateSchema = z.object({
+ /** The auth scheme type (e.g., 'OAUTH2', 'API_KEY') */
+ authScheme: z.nativeEnum(AuthSchemeTypes),
+ /** Connection state values - varies by auth scheme */
+ val: z.record(z.unknown()),
+});
+
+export type WebhookConnectionState = z.infer<typeof WebhookConnectionStateSchema>;
+
+/**
+ * Connected account data schema matching GET /api/v3/connected_accounts/{id} response.
+ * Used in webhook payloads for connection lifecycle events.
+ */
+export const SingleConnectedAccountDetailedResponseSchema = z.object({
+ /** Toolkit information */
+ toolkit: z.object({
+ slug: z.string().describe('The slug of the toolkit'),
+ }),
+ /** Auth config details */
+ auth_config: ConnectedAccountAuthConfigSchema,
+ /** The nano ID of the connected account */
+ id: z.string(),
+ /** @deprecated - user ID of the connection owner */
+ user_id: z.string(),
+ /** Connection status */
+ status: z.nativeEnum(ConnectionStatuses),
+ /** ISO-8601 timestamp of creation */
+ created_at: z.string(),
+ /** ISO-8601 timestamp of last update */
+ updated_at: z.string(),
+ /** Connection state data (auth scheme + state values) */
+ state: WebhookConnectionStateSchema,
+ /** @deprecated - use state instead */
+ data: z.record(z.unknown()),
+ /** @deprecated - use state instead */
+ params: z.record(z.unknown()),
+ /** Reason for the current status (e.g., expiration reason) */
+ status_reason: z.string().nullable(),
+ /** Whether the connection is disabled */
+ is_disabled: z.boolean(),
+ /** Endpoint for making test requests */
+ test_request_endpoint: z.string().optional(),
+ /** @deprecated */
+ deprecated: z
+ .object({
+ labels: z.array(z.string()),
+ uuid: z.string(),
+ })
+ .optional(),
+});
+
+export type SingleConnectedAccountDetailedResponse = z.infer<
+ typeof SingleConnectedAccountDetailedResponseSchema
+>;
+
+// =============================================================================
+// CONNECTION EXPIRED WEBHOOK EVENT SCHEMA
+// =============================================================================
+
+/**
+ * Webhook metadata for connection events.
+ * Note: This differs from the trigger webhook metadata in WebhookPayloadV3Schema.
+ */
+export const WebhookConnectionMetadataSchema = z.object({
+ /** Project nano ID */
+ project_id: z.string(),
+ /** Organization UUID */
+ org_id: z.string(),
+});
+
+export type WebhookConnectionMetadata = z.infer<typeof WebhookConnectionMetadataSchema>;
+
+/**
+ * Connection expired webhook event payload.
+ * Emitted when a connected account expires due to authentication refresh failure.
+ *
+ * @example
+ * ```typescript
+ * import { ConnectionExpiredEventSchema } from '@composio/core';
+ *
+ * // In your webhook handler
+ * const result = ConnectionExpiredEventSchema.safeParse(webhookPayload);
+ * if (result.success) {
+ * const { data, metadata } = result.data;
+ * console.log(`Connection ${data.id} expired for user ${data.user_id}`);
+ * console.log(`Toolkit: ${data.toolkit.slug}`);
+ * console.log(`Project: ${metadata.project_id}`);
+ * }
+ * ```
+ */
+export const ConnectionExpiredEventSchema = z.object({
+ /** Unique message ID (e.g., "msg_847cdfcd-d219-4f18-a6dd-91acd42ca94a") */
+ id: z.string(),
+ /** ISO-8601 timestamp of when the event was emitted */
+ timestamp: z.string(),
+ /** Event type identifier */
+ type: z.literal(WebhookEventTypes.CONNECTION_EXPIRED),
+ /** Connected account data (same as GET /api/v3/connected_accounts/{id}) */
+ data: SingleConnectedAccountDetailedResponseSchema,
+ /** Event metadata */
+ metadata: WebhookConnectionMetadataSchema,
+});
+
+export type ConnectionExpiredEvent = z.infer<typeof ConnectionExpiredEventSchema>;
+
+// =============================================================================
+// UNION TYPE FOR ALL WEBHOOK EVENTS
+// =============================================================================
+
+/**
+ * Union of all typed webhook event schemas.
+ * Extend this as new event types are added.
+ *
+ * Note: This is separate from WebhookPayloadV3Schema which is a generic schema
+ * for ANY V3 webhook. This union provides specific types for known events.
+ */
+export const WebhookEventSchema = z.discriminatedUnion('type', [ConnectionExpiredEventSchema]);
+
+export type WebhookEvent = z.infer<typeof WebhookEventSchema>;
diff --git a/ts/packages/core/test/types/webhookEvents.test.ts b/ts/packages/core/test/types/webhookEvents.test.ts
new file mode 100644
index 000000000..b276980a9
--- /dev/null
+++ b/ts/packages/core/test/types/webhookEvents.test.ts
@@ -0,0 +1,265 @@
+import { describe, it, expect } from 'vitest';
+import {
+ ConnectionExpiredEventSchema,
+ WebhookEventSchema,
+ WebhookEventTypes,
+ SingleConnectedAccountDetailedResponseSchema,
+ WebhookConnectionMetadataSchema,
+} from '../../src/types/webhookEvents.types';
+
+describe('WebhookEventTypes', () => {
+ it('should have correct event type constants', () => {
+ expect(WebhookEventTypes.CONNECTION_EXPIRED).toBe('composio.connected_account.expired');
+ });
+});
+
+describe('WebhookConnectionMetadataSchema', () => {
+ it('should validate valid metadata', () => {
+ const validMetadata = {
+ project_id: 'pr_koucdrMIwRsf',
+ org_id: '4a4ded8f-d3ae-4dea-a229-c30234298b05',
+ };
+
+ const result = WebhookConnectionMetadataSchema.safeParse(validMetadata);
+ expect(result.success).toBe(true);
+ });
+
+ it('should reject missing project_id', () => {
+ const invalidMetadata = {
+ org_id: '4a4ded8f-d3ae-4dea-a229-c30234298b05',
+ };
+
+ const result = WebhookConnectionMetadataSchema.safeParse(invalidMetadata);
+ expect(result.success).toBe(false);
+ });
+
+ it('should reject missing org_id', () => {
+ const invalidMetadata = {
+ project_id: 'pr_koucdrMIwRsf',
+ };
+
+ const result = WebhookConnectionMetadataSchema.safeParse(invalidMetadata);
+ expect(result.success).toBe(false);
+ });
+});
+
+describe('SingleConnectedAccountDetailedResponseSchema', () => {
+ const validConnectedAccountData = {
+ toolkit: { slug: 'gmail' },
+ auth_config: {
+ id: 'ac_izZGRCZ9qyxk',
+ auth_scheme: 'OAUTH2',
+ is_composio_managed: true,
+ is_disabled: false,
+ },
+ id: 'ca__IvSeEzEBjVt',
+ user_id: 'test-user-123',
+ status: 'EXPIRED',
+ created_at: '2026-02-02T08:35:44.272Z',
+ updated_at: '2026-02-02T10:14:20.949Z',
+ state: {
+ authScheme: 'OAUTH2',
+ val: { status: 'EXPIRED', access_token: 'ya29.test' },
+ },
+ data: { status: 'EXPIRED' },
+ params: { status: 'EXPIRED' },
+ status_reason: 'Token refresh failed',
+ is_disabled: false,
+ };
+
+ it('should validate valid connected account data', () => {
+ const result =
+ SingleConnectedAccountDetailedResponseSchema.safeParse(validConnectedAccountData);
+ expect(result.success).toBe(true);
+ });
+
+ it('should validate connected account with null status_reason', () => {
+ const data = {
+ ...validConnectedAccountData,
+ status_reason: null,
+ };
+
+ const result = SingleConnectedAccountDetailedResponseSchema.safeParse(data);
+ expect(result.success).toBe(true);
+ });
+
+ it('should validate connected account with optional deprecated field', () => {
+ const data = {
+ ...validConnectedAccountData,
+ deprecated: {
+ labels: ['label1'],
+ uuid: 'd9641efa-8007-4864-8a41-3164599d65ec',
+ },
+ };
+
+ const result = SingleConnectedAccountDetailedResponseSchema.safeParse(data);
+ expect(result.success).toBe(true);
+ });
+
+ it('should reject invalid auth_scheme', () => {
+ const data = {
+ ...validConnectedAccountData,
+ auth_config: {
+ ...validConnectedAccountData.auth_config,
+ auth_scheme: 'INVALID_SCHEME',
+ },
+ };
+
+ const result = SingleConnectedAccountDetailedResponseSchema.safeParse(data);
+ expect(result.success).toBe(false);
+ });
+
+ it('should reject invalid status', () => {
+ const data = {
+ ...validConnectedAccountData,
+ status: 'INVALID_STATUS',
+ };
+
+ const result = SingleConnectedAccountDetailedResponseSchema.safeParse(data);
+ expect(result.success).toBe(false);
+ });
+});
+
+describe('ConnectionExpiredEventSchema', () => {
+ const validPayload = {
+ id: 'msg_847cdfcd-d219-4f18-a6dd-91acd42ca94a',
+ timestamp: '2026-02-02T10:14:20.955Z',
+ type: 'composio.connected_account.expired',
+ data: {
+ toolkit: { slug: 'gmail' },
+ auth_config: {
+ id: 'ac_izZGRCZ9qyxk',
+ auth_scheme: 'OAUTH2',
+ is_composio_managed: true,
+ is_disabled: false,
+ },
+ id: 'ca__IvSeEzEBjVt',
+ user_id: 'test-user',
+ status: 'EXPIRED',
+ created_at: '2026-02-02T08:35:44.272Z',
+ updated_at: '2026-02-02T10:14:20.949Z',
+ state: {
+ authScheme: 'OAUTH2',
+ val: { status: 'EXPIRED' },
+ },
+ data: {},
+ params: {},
+ status_reason: null,
+ is_disabled: false,
+ },
+ metadata: {
+ project_id: 'pr_koucdrMIwRsf',
+ org_id: '4a4ded8f-d3ae-4dea-a229-c30234298b05',
+ },
+ };
+
+ it('validates a valid connection expired event', () => {
+ const result = ConnectionExpiredEventSchema.safeParse(validPayload);
+ expect(result.success).toBe(true);
+ });
+
+ it('extracts typed data from parsed result', () => {
+ const result = ConnectionExpiredEventSchema.safeParse(validPayload);
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.data.type).toBe('composio.connected_account.expired');
+ expect(result.data.data.id).toBe('ca__IvSeEzEBjVt');
+ expect(result.data.data.toolkit.slug).toBe('gmail');
+ expect(result.data.data.status).toBe('EXPIRED');
+ expect(result.data.metadata.project_id).toBe('pr_koucdrMIwRsf');
+ }
+ });
+
+ it('rejects invalid event type', () => {
+ const payload = {
+ ...validPayload,
+ type: 'composio.trigger.message',
+ };
+ const result = ConnectionExpiredEventSchema.safeParse(payload);
+ expect(result.success).toBe(false);
+ });
+
+ it('rejects missing metadata fields', () => {
+ const payload = {
+ ...validPayload,
+ metadata: { project_id: 'pr_abc' }, // missing org_id
+ };
+ const result = ConnectionExpiredEventSchema.safeParse(payload);
+ expect(result.success).toBe(false);
+ });
+
+ it('rejects missing data fields', () => {
+ const payload = {
+ ...validPayload,
+ data: { toolkit: { slug: 'gmail' } }, // missing required fields
+ };
+ const result = ConnectionExpiredEventSchema.safeParse(payload);
+ expect(result.success).toBe(false);
+ });
+
+ it('validates payload with status_reason', () => {
+ const payload = {
+ ...validPayload,
+ data: {
+ ...validPayload.data,
+ status_reason: 'Token refresh failed due to revoked access',
+ },
+ };
+ const result = ConnectionExpiredEventSchema.safeParse(payload);
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.data.data.status_reason).toBe('Token refresh failed due to revoked access');
+ }
+ });
+});
+
+describe('WebhookEventSchema', () => {
+ const validConnectionExpiredPayload = {
+ id: 'msg_847cdfcd-d219-4f18-a6dd-91acd42ca94a',
+ timestamp: '2026-02-02T10:14:20.955Z',
+ type: 'composio.connected_account.expired',
+ data: {
+ toolkit: { slug: 'gmail' },
+ auth_config: {
+ id: 'ac_izZGRCZ9qyxk',
+ auth_scheme: 'OAUTH2',
+ is_composio_managed: true,
+ is_disabled: false,
+ },
+ id: 'ca__IvSeEzEBjVt',
+ user_id: 'test-user',
+ status: 'EXPIRED',
+ created_at: '2026-02-02T08:35:44.272Z',
+ updated_at: '2026-02-02T10:14:20.949Z',
+ state: {
+ authScheme: 'OAUTH2',
+ val: { status: 'EXPIRED' },
+ },
+ data: {},
+ params: {},
+ status_reason: null,
+ is_disabled: false,
+ },
+ metadata: {
+ project_id: 'pr_koucdrMIwRsf',
+ org_id: '4a4ded8f-d3ae-4dea-a229-c30234298b05',
+ },
+ };
+
+ it('discriminates by event type for connection expired', () => {
+ const result = WebhookEventSchema.safeParse(validConnectionExpiredPayload);
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.data.type).toBe('composio.connected_account.expired');
+ }
+ });
+
+ it('rejects unknown event types', () => {
+ const payload = {
+ ...validConnectionExpiredPayload,
+ type: 'composio.unknown.event',
+ };
+ const result = WebhookEventSchema.safeParse(payload);
+ expect(result.success).toBe(false);
+ });
+});