@devries-cameron20 / composio-1 / commits / b6aa489d4
Fork 0

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

Add Zod schema (TypeScript) and TypedDict (Python) for typed handling of `composio.connected_account.expired` webhook events. Schemas: - ConnectionExpiredEventSchema: Full webhook event envelope validation - SingleConnectedAccountDetailedResponseSchema: Matches GET API response - WebhookConnectionMetadataSchema: Project and org ID metadata This builds on PR #2553 which loosened V3 detection to accept any composio.* event type. Users can now type-safely parse connection expiration events in their webhook handlers. Linear: PLEN-1398

jkomyno committed Feb 2, 2026 at 23:44 UTC b6aa489d455db1d15b37ab0e1702faab48c39b29
7 files changed +778
python/composio/__init__.py
+18
@@ -4,6 +4,16 @@ from .core.models.tools import (
4 before_execute,
5 schema_modifier,
6 )
7 +from .core.models.webhook_events import (
8 + ConnectionExpiredEvent,
9 + ConnectionState,
10 + ConnectionStatusEnum,
11 + SingleConnectedAccountDetailedResponse,
12 + WebhookConnectionMetadata,
13 + WebhookEvent,
14 + WebhookEventType,
15 + is_connection_expired_event,
16 +)
17 from .core.types import (
18 ToolkitLatestVersion,
19 ToolkitVersion,
@@ -14,8 +24,16 @@ from .sdk import Composio
24
25 __all__ = (
26 "Composio",
27 + "ConnectionExpiredEvent",
28 + "ConnectionState",
29 + "ConnectionStatusEnum",
30 + "SingleConnectedAccountDetailedResponse",
31 + "WebhookConnectionMetadata",
32 + "WebhookEvent",
33 + "WebhookEventType",
34 "after_execute",
35 "before_execute",
36 + "is_connection_expired_event",
37 "schema_modifier",
38 "__version__",
39 "ToolkitLatestVersion",
python/composio/core/models/__init__.py
+18
@@ -5,13 +5,31 @@ from .tool_router import ToolRouter
5 from .toolkits import Toolkits
6 from .tools import Tools
7 from .triggers import Triggers
8 +from .webhook_events import (
9 + ConnectionExpiredEvent,
10 + ConnectionState,
11 + ConnectionStatusEnum,
12 + SingleConnectedAccountDetailedResponse,
13 + WebhookConnectionMetadata,
14 + WebhookEvent,
15 + WebhookEventType,
16 + is_connection_expired_event,
17 +)
18
19 __all__ = [
20 "AuthConfigs",
21 "ConnectedAccounts",
22 + "ConnectionExpiredEvent",
23 + "ConnectionState",
24 + "ConnectionStatusEnum",
25 "MCP",
26 + "SingleConnectedAccountDetailedResponse",
27 "ToolRouter",
28 "Toolkits",
29 "Tools",
30 "Triggers",
31 + "WebhookConnectionMetadata",
32 + "WebhookEvent",
33 + "WebhookEventType",
34 + "is_connection_expired_event",
35 ]
python/composio/core/models/webhook_events.py new
+183
@@ -0,0 +1,183 @@
1 +"""
2 +Webhook event types for typed event handling.
3 +
4 +This module provides TypedDict definitions for specific webhook event types,
5 +enabling type-safe handling of events like connection expiration.
6 +"""
7 +
8 +from __future__ import annotations
9 +
10 +import typing as t
11 +from enum import Enum
12 +
13 +import typing_extensions as te
14 +
15 +
16 +class WebhookEventType(str, Enum):
17 + """Known webhook event types."""
18 +
19 + CONNECTION_EXPIRED = "composio.connected_account.expired"
20 +
21 +
22 +class ConnectionStatusEnum(str, Enum):
23 + """Connection status values."""
24 +
25 + INITIALIZING = "INITIALIZING"
26 + INITIATED = "INITIATED"
27 + ACTIVE = "ACTIVE"
28 + FAILED = "FAILED"
29 + EXPIRED = "EXPIRED"
30 + INACTIVE = "INACTIVE"
31 +
32 +
33 +# =============================================================================
34 +# CONNECTED ACCOUNT DATA (matches GET /api/v3/connected_accounts/{id})
35 +# =============================================================================
36 +
37 +
38 +class ConnectedAccountToolkit(te.TypedDict):
39 + """Toolkit information in connected account response."""
40 +
41 + slug: str
42 +
43 +
44 +class ConnectedAccountAuthConfigDeprecated(te.TypedDict, total=False):
45 + """Deprecated auth config fields."""
46 +
47 + uuid: str
48 +
49 +
50 +class ConnectedAccountAuthConfig(te.TypedDict, total=False):
51 + """Auth config details in connected account response."""
52 +
53 + id: te.Required[str]
54 + auth_scheme: te.Required[str]
55 + is_composio_managed: te.Required[bool]
56 + is_disabled: te.Required[bool]
57 + deprecated: ConnectedAccountAuthConfigDeprecated
58 +
59 +
60 +class ConnectionStateVal(te.TypedDict, total=False):
61 + """Connection state value - varies by auth scheme."""
62 +
63 + status: str
64 + # OAuth2 fields
65 + access_token: str
66 + refresh_token: t.Optional[str]
67 + token_type: str
68 + expires_in: t.Union[int, str, None]
69 + scope: t.Union[str, t.List[str], None]
70 + id_token: str
71 + code_verifier: str
72 + callback_url: str
73 + # OAuth1 fields
74 + oauth_token: str
75 + oauth_token_secret: str
76 + # API Key fields
77 + api_key: str
78 + generic_api_key: str
79 + # Bearer Token fields
80 + token: str
81 + # Basic auth fields
82 + username: str
83 + password: str
84 +
85 +
86 +class ConnectionState(te.TypedDict):
87 + """Connection state data discriminated by auth scheme."""
88 +
89 + authScheme: str
90 + val: ConnectionStateVal
91 +
92 +
93 +class ConnectedAccountDeprecated(te.TypedDict, total=False):
94 + """Deprecated connected account fields."""
95 +
96 + labels: t.List[str]
97 + uuid: str
98 +
99 +
100 +class SingleConnectedAccountDetailedResponse(te.TypedDict, total=False):
101 + """
102 + Connected account data matching GET /api/v3/connected_accounts/{id} response.
103 +
104 + This is used in webhook payloads for connection lifecycle events.
105 + """
106 +
107 + toolkit: te.Required[ConnectedAccountToolkit]
108 + auth_config: te.Required[ConnectedAccountAuthConfig]
109 + id: te.Required[str]
110 + user_id: te.Required[str]
111 + status: te.Required[str] # ConnectionStatusEnum value
112 + created_at: te.Required[str]
113 + updated_at: te.Required[str]
114 + state: te.Required[ConnectionState]
115 + data: te.Required[t.Dict[str, t.Any]]
116 + params: te.Required[t.Dict[str, t.Any]]
117 + status_reason: te.Required[t.Optional[str]]
118 + is_disabled: te.Required[bool]
119 + test_request_endpoint: str
120 + deprecated: ConnectedAccountDeprecated
121 +
122 +
123 +# =============================================================================
124 +# CONNECTION EXPIRED WEBHOOK EVENT
125 +# =============================================================================
126 +
127 +
128 +class WebhookConnectionMetadata(te.TypedDict):
129 + """Webhook metadata for connection events."""
130 +
131 + project_id: str
132 + org_id: str
133 +
134 +
135 +class ConnectionExpiredEvent(te.TypedDict):
136 + """
137 + Connection expired webhook event payload.
138 +
139 + Emitted when a connected account expires due to authentication refresh failure.
140 +
141 + Example:
142 + >>> from composio.core.models.webhook_events import ConnectionExpiredEvent
143 + >>>
144 + >>> def handle_webhook(payload: dict) -> None:
145 + ... if payload.get("type") == "composio.connected_account.expired":
146 + ... event: ConnectionExpiredEvent = payload # type: ignore
147 + ... print(f"Connection {event['data']['id']} expired")
148 + ... print(f"Toolkit: {event['data']['toolkit']['slug']}")
149 + ... print(f"User: {event['data']['user_id']}")
150 + """
151 +
152 + id: str # Unique message ID (e.g., "msg_847cdfcd-d219-4f18-a6dd-91acd42ca94a")
153 + timestamp: str # ISO-8601 timestamp
154 + type: t.Literal["composio.connected_account.expired"]
155 + data: SingleConnectedAccountDetailedResponse
156 + metadata: WebhookConnectionMetadata
157 +
158 +
159 +# Type alias for all webhook events
160 +WebhookEvent = t.Union[ConnectionExpiredEvent]
161 +
162 +
163 +def is_connection_expired_event(payload: t.Dict[str, t.Any]) -> bool:
164 + """
165 + Check if a webhook payload is a connection expired event.
166 +
167 + :param payload: The webhook payload to check
168 + :return: True if this is a connection expired event
169 +
170 + Example:
171 + >>> from composio.core.models.webhook_events import (
172 + ... is_connection_expired_event,
173 + ... ConnectionExpiredEvent,
174 + ... )
175 + >>>
176 + >>> if is_connection_expired_event(payload):
177 + ... event: ConnectionExpiredEvent = payload # type: ignore
178 + ... handle_connection_expired(event)
179 + """
180 + return (
181 + isinstance(payload, dict)
182 + and payload.get("type") == WebhookEventType.CONNECTION_EXPIRED.value
183 + )
python/tests/test_webhook_events.py new
+129
@@ -0,0 +1,129 @@
1 +"""Tests for webhook event types."""
2 +
3 +import pytest
4 +
5 +from composio.core.models.webhook_events import (
6 + ConnectionExpiredEvent,
7 + WebhookEventType,
8 + is_connection_expired_event,
9 +)
10 +
11 +
12 +class TestWebhookEventType:
13 + """Tests for WebhookEventType enum."""
14 +
15 + def test_connection_expired_value(self) -> None:
16 + """Should have correct value for CONNECTION_EXPIRED."""
17 + assert (
18 + WebhookEventType.CONNECTION_EXPIRED.value
19 + == "composio.connected_account.expired"
20 + )
21 +
22 +
23 +class TestIsConnectionExpiredEvent:
24 + """Tests for is_connection_expired_event helper function."""
25 +
26 + @pytest.fixture
27 + def valid_payload(self) -> dict:
28 + """Return a valid connection expired event payload."""
29 + return {
30 + "id": "msg_847cdfcd-d219-4f18-a6dd-91acd42ca94a",
31 + "timestamp": "2026-02-02T10:14:20.955Z",
32 + "type": "composio.connected_account.expired",
33 + "data": {
34 + "toolkit": {"slug": "gmail"},
35 + "auth_config": {
36 + "id": "ac_izZGRCZ9qyxk",
37 + "auth_scheme": "OAUTH2",
38 + "is_composio_managed": True,
39 + "is_disabled": False,
40 + },
41 + "id": "ca__IvSeEzEBjVt",
42 + "user_id": "test-user",
43 + "status": "EXPIRED",
44 + "created_at": "2026-02-02T08:35:44.272Z",
45 + "updated_at": "2026-02-02T10:14:20.949Z",
46 + "state": {
47 + "authScheme": "OAUTH2",
48 + "val": {"status": "EXPIRED"},
49 + },
50 + "data": {},
51 + "params": {},
52 + "status_reason": None,
53 + "is_disabled": False,
54 + },
55 + "metadata": {
56 + "project_id": "pr_koucdrMIwRsf",
57 + "org_id": "4a4ded8f-d3ae-4dea-a229-c30234298b05",
58 + },
59 + }
60 +
61 + def test_returns_true_for_valid_payload(self, valid_payload: dict) -> None:
62 + """Should return True for a valid connection expired event."""
63 + assert is_connection_expired_event(valid_payload) is True
64 +
65 + def test_returns_false_for_trigger_message(self) -> None:
66 + """Should return False for a trigger message event."""
67 + payload = {
68 + "id": "msg_123",
69 + "timestamp": "2026-02-02T10:14:20.955Z",
70 + "type": "composio.trigger.message",
71 + "data": {},
72 + "metadata": {},
73 + }
74 + assert is_connection_expired_event(payload) is False
75 +
76 + def test_returns_false_for_none(self) -> None:
77 + """Should return False for None input."""
78 + assert is_connection_expired_event(None) is False # type: ignore
79 +
80 + def test_returns_false_for_string(self) -> None:
81 + """Should return False for string input."""
82 + assert is_connection_expired_event("string") is False # type: ignore
83 +
84 + def test_returns_false_for_empty_dict(self) -> None:
85 + """Should return False for empty dict."""
86 + assert is_connection_expired_event({}) is False
87 +
88 + def test_returns_false_for_missing_type(self, valid_payload: dict) -> None:
89 + """Should return False when type field is missing."""
90 + del valid_payload["type"]
91 + assert is_connection_expired_event(valid_payload) is False
92 +
93 +
94 +class TestConnectionExpiredEventType:
95 + """Tests for ConnectionExpiredEvent TypedDict structure."""
96 +
97 + def test_type_annotation(self) -> None:
98 + """Should have correct type annotations."""
99 + # This test verifies the TypedDict can be used for type hints
100 + event: ConnectionExpiredEvent = {
101 + "id": "msg_123",
102 + "timestamp": "2026-02-02T10:14:20.955Z",
103 + "type": "composio.connected_account.expired",
104 + "data": {
105 + "toolkit": {"slug": "gmail"},
106 + "auth_config": {
107 + "id": "ac_123",
108 + "auth_scheme": "OAUTH2",
109 + "is_composio_managed": True,
110 + "is_disabled": False,
111 + },
112 + "id": "ca_123",
113 + "user_id": "user_123",
114 + "status": "EXPIRED",
115 + "created_at": "2026-02-02T08:35:44.272Z",
116 + "updated_at": "2026-02-02T10:14:20.949Z",
117 + "state": {"authScheme": "OAUTH2", "val": {}},
118 + "data": {},
119 + "params": {},
120 + "status_reason": None,
121 + "is_disabled": False,
122 + },
123 + "metadata": {"project_id": "pr_123", "org_id": "org_123"},
124 + }
125 +
126 + # Verify type narrowing works
127 + assert event["type"] == "composio.connected_account.expired"
128 + assert event["data"]["toolkit"]["slug"] == "gmail"
129 + assert event["metadata"]["project_id"] == "pr_123"
ts/packages/core/src/index.ts
+1
@@ -17,6 +17,7 @@ export * from './types/connectedAccountAuthStates.types';
17 export * from './types/connectedAccounts.types';
18 export * from './types/toolkit.types';
19 export * from './types/triggers.types';
20 +export * from './types/webhookEvents.types';
21 export * from './types/mcp.types';
22 export * from './types/files.types';
23 export * from './types/connectionRequest.types';
ts/packages/core/src/types/webhookEvents.types.ts new
+164
@@ -0,0 +1,164 @@
1 +import { z } from 'zod/v3';
2 +import { AuthSchemeTypes } from './authConfigs.types';
3 +import { ConnectionStatuses } from './connectedAccountAuthStates.types';
4 +
5 +// =============================================================================
6 +// WEBHOOK EVENT TYPES
7 +// =============================================================================
8 +
9 +export const WebhookEventTypes = {
10 + CONNECTION_EXPIRED: 'composio.connected_account.expired',
11 +} as const;
12 +
13 +export type WebhookEventType = (typeof WebhookEventTypes)[keyof typeof WebhookEventTypes];
14 +
15 +// =============================================================================
16 +// CONNECTED ACCOUNT DATA SCHEMA (matches GET /api/v3/connected_accounts/{id})
17 +// =============================================================================
18 +
19 +/**
20 + * Auth config details included in the connected account response.
21 + */
22 +export const ConnectedAccountAuthConfigSchema = z.object({
23 + /** The nano ID of the auth config */
24 + id: z.string(),
25 + /** @deprecated - use state.authScheme instead */
26 + auth_scheme: z.nativeEnum(AuthSchemeTypes),
27 + /** Whether this auth config is managed by Composio */
28 + is_composio_managed: z.boolean(),
29 + /** Whether the auth config is disabled */
30 + is_disabled: z.boolean(),
31 + /** @deprecated */
32 + deprecated: z
33 + .object({
34 + uuid: z.string(),
35 + })
36 + .optional(),
37 +});
38 +
39 +export type ConnectedAccountAuthConfig = z.infer<typeof ConnectedAccountAuthConfigSchema>;
40 +
41 +/**
42 + * Simplified connection state schema for webhook payloads.
43 + * The full ConnectionDataSchema is too complex for webhook validation;
44 + * this schema accepts any auth scheme and state values.
45 + */
46 +export const WebhookConnectionStateSchema = z.object({
47 + /** The auth scheme type (e.g., 'OAUTH2', 'API_KEY') */
48 + authScheme: z.nativeEnum(AuthSchemeTypes),
49 + /** Connection state values - varies by auth scheme */
50 + val: z.record(z.unknown()),
51 +});
52 +
53 +export type WebhookConnectionState = z.infer<typeof WebhookConnectionStateSchema>;
54 +
55 +/**
56 + * Connected account data schema matching GET /api/v3/connected_accounts/{id} response.
57 + * Used in webhook payloads for connection lifecycle events.
58 + */
59 +export const SingleConnectedAccountDetailedResponseSchema = z.object({
60 + /** Toolkit information */
61 + toolkit: z.object({
62 + slug: z.string().describe('The slug of the toolkit'),
63 + }),
64 + /** Auth config details */
65 + auth_config: ConnectedAccountAuthConfigSchema,
66 + /** The nano ID of the connected account */
67 + id: z.string(),
68 + /** @deprecated - user ID of the connection owner */
69 + user_id: z.string(),
70 + /** Connection status */
71 + status: z.nativeEnum(ConnectionStatuses),
72 + /** ISO-8601 timestamp of creation */
73 + created_at: z.string(),
74 + /** ISO-8601 timestamp of last update */
75 + updated_at: z.string(),
76 + /** Connection state data (auth scheme + state values) */
77 + state: WebhookConnectionStateSchema,
78 + /** @deprecated - use state instead */
79 + data: z.record(z.unknown()),
80 + /** @deprecated - use state instead */
81 + params: z.record(z.unknown()),
82 + /** Reason for the current status (e.g., expiration reason) */
83 + status_reason: z.string().nullable(),
84 + /** Whether the connection is disabled */
85 + is_disabled: z.boolean(),
86 + /** Endpoint for making test requests */
87 + test_request_endpoint: z.string().optional(),
88 + /** @deprecated */
89 + deprecated: z
90 + .object({
91 + labels: z.array(z.string()),
92 + uuid: z.string(),
93 + })
94 + .optional(),
95 +});
96 +
97 +export type SingleConnectedAccountDetailedResponse = z.infer<
98 + typeof SingleConnectedAccountDetailedResponseSchema
99 +>;
100 +
101 +// =============================================================================
102 +// CONNECTION EXPIRED WEBHOOK EVENT SCHEMA
103 +// =============================================================================
104 +
105 +/**
106 + * Webhook metadata for connection events.
107 + * Note: This differs from the trigger webhook metadata in WebhookPayloadV3Schema.
108 + */
109 +export const WebhookConnectionMetadataSchema = z.object({
110 + /** Project nano ID */
111 + project_id: z.string(),
112 + /** Organization UUID */
113 + org_id: z.string(),
114 +});
115 +
116 +export type WebhookConnectionMetadata = z.infer<typeof WebhookConnectionMetadataSchema>;
117 +
118 +/**
119 + * Connection expired webhook event payload.
120 + * Emitted when a connected account expires due to authentication refresh failure.
121 + *
122 + * @example
123 + * ```typescript
124 + * import { ConnectionExpiredEventSchema } from '@composio/core';
125 + *
126 + * // In your webhook handler
127 + * const result = ConnectionExpiredEventSchema.safeParse(webhookPayload);
128 + * if (result.success) {
129 + * const { data, metadata } = result.data;
130 + * console.log(`Connection ${data.id} expired for user ${data.user_id}`);
131 + * console.log(`Toolkit: ${data.toolkit.slug}`);
132 + * console.log(`Project: ${metadata.project_id}`);
133 + * }
134 + * ```
135 + */
136 +export const ConnectionExpiredEventSchema = z.object({
137 + /** Unique message ID (e.g., "msg_847cdfcd-d219-4f18-a6dd-91acd42ca94a") */
138 + id: z.string(),
139 + /** ISO-8601 timestamp of when the event was emitted */
140 + timestamp: z.string(),
141 + /** Event type identifier */
142 + type: z.literal(WebhookEventTypes.CONNECTION_EXPIRED),
143 + /** Connected account data (same as GET /api/v3/connected_accounts/{id}) */
144 + data: SingleConnectedAccountDetailedResponseSchema,
145 + /** Event metadata */
146 + metadata: WebhookConnectionMetadataSchema,
147 +});
148 +
149 +export type ConnectionExpiredEvent = z.infer<typeof ConnectionExpiredEventSchema>;
150 +
151 +// =============================================================================
152 +// UNION TYPE FOR ALL WEBHOOK EVENTS
153 +// =============================================================================
154 +
155 +/**
156 + * Union of all typed webhook event schemas.
157 + * Extend this as new event types are added.
158 + *
159 + * Note: This is separate from WebhookPayloadV3Schema which is a generic schema
160 + * for ANY V3 webhook. This union provides specific types for known events.
161 + */
162 +export const WebhookEventSchema = z.discriminatedUnion('type', [ConnectionExpiredEventSchema]);
163 +
164 +export type WebhookEvent = z.infer<typeof WebhookEventSchema>;
ts/packages/core/test/types/webhookEvents.test.ts new
+265
@@ -0,0 +1,265 @@
1 +import { describe, it, expect } from 'vitest';
2 +import {
3 + ConnectionExpiredEventSchema,
4 + WebhookEventSchema,
5 + WebhookEventTypes,
6 + SingleConnectedAccountDetailedResponseSchema,
7 + WebhookConnectionMetadataSchema,
8 +} from '../../src/types/webhookEvents.types';
9 +
10 +describe('WebhookEventTypes', () => {
11 + it('should have correct event type constants', () => {
12 + expect(WebhookEventTypes.CONNECTION_EXPIRED).toBe('composio.connected_account.expired');
13 + });
14 +});
15 +
16 +describe('WebhookConnectionMetadataSchema', () => {
17 + it('should validate valid metadata', () => {
18 + const validMetadata = {
19 + project_id: 'pr_koucdrMIwRsf',
20 + org_id: '4a4ded8f-d3ae-4dea-a229-c30234298b05',
21 + };
22 +
23 + const result = WebhookConnectionMetadataSchema.safeParse(validMetadata);
24 + expect(result.success).toBe(true);
25 + });
26 +
27 + it('should reject missing project_id', () => {
28 + const invalidMetadata = {
29 + org_id: '4a4ded8f-d3ae-4dea-a229-c30234298b05',
30 + };
31 +
32 + const result = WebhookConnectionMetadataSchema.safeParse(invalidMetadata);
33 + expect(result.success).toBe(false);
34 + });
35 +
36 + it('should reject missing org_id', () => {
37 + const invalidMetadata = {
38 + project_id: 'pr_koucdrMIwRsf',
39 + };
40 +
41 + const result = WebhookConnectionMetadataSchema.safeParse(invalidMetadata);
42 + expect(result.success).toBe(false);
43 + });
44 +});
45 +
46 +describe('SingleConnectedAccountDetailedResponseSchema', () => {
47 + const validConnectedAccountData = {
48 + toolkit: { slug: 'gmail' },
49 + auth_config: {
50 + id: 'ac_izZGRCZ9qyxk',
51 + auth_scheme: 'OAUTH2',
52 + is_composio_managed: true,
53 + is_disabled: false,
54 + },
55 + id: 'ca__IvSeEzEBjVt',
56 + user_id: 'test-user-123',
57 + status: 'EXPIRED',
58 + created_at: '2026-02-02T08:35:44.272Z',
59 + updated_at: '2026-02-02T10:14:20.949Z',
60 + state: {
61 + authScheme: 'OAUTH2',
62 + val: { status: 'EXPIRED', access_token: 'ya29.test' },
63 + },
64 + data: { status: 'EXPIRED' },
65 + params: { status: 'EXPIRED' },
66 + status_reason: 'Token refresh failed',
67 + is_disabled: false,
68 + };
69 +
70 + it('should validate valid connected account data', () => {
71 + const result =
72 + SingleConnectedAccountDetailedResponseSchema.safeParse(validConnectedAccountData);
73 + expect(result.success).toBe(true);
74 + });
75 +
76 + it('should validate connected account with null status_reason', () => {
77 + const data = {
78 + ...validConnectedAccountData,
79 + status_reason: null,
80 + };
81 +
82 + const result = SingleConnectedAccountDetailedResponseSchema.safeParse(data);
83 + expect(result.success).toBe(true);
84 + });
85 +
86 + it('should validate connected account with optional deprecated field', () => {
87 + const data = {
88 + ...validConnectedAccountData,
89 + deprecated: {
90 + labels: ['label1'],
91 + uuid: 'd9641efa-8007-4864-8a41-3164599d65ec',
92 + },
93 + };
94 +
95 + const result = SingleConnectedAccountDetailedResponseSchema.safeParse(data);
96 + expect(result.success).toBe(true);
97 + });
98 +
99 + it('should reject invalid auth_scheme', () => {
100 + const data = {
101 + ...validConnectedAccountData,
102 + auth_config: {
103 + ...validConnectedAccountData.auth_config,
104 + auth_scheme: 'INVALID_SCHEME',
105 + },
106 + };
107 +
108 + const result = SingleConnectedAccountDetailedResponseSchema.safeParse(data);
109 + expect(result.success).toBe(false);
110 + });
111 +
112 + it('should reject invalid status', () => {
113 + const data = {
114 + ...validConnectedAccountData,
115 + status: 'INVALID_STATUS',
116 + };
117 +
118 + const result = SingleConnectedAccountDetailedResponseSchema.safeParse(data);
119 + expect(result.success).toBe(false);
120 + });
121 +});
122 +
123 +describe('ConnectionExpiredEventSchema', () => {
124 + const validPayload = {
125 + id: 'msg_847cdfcd-d219-4f18-a6dd-91acd42ca94a',
126 + timestamp: '2026-02-02T10:14:20.955Z',
127 + type: 'composio.connected_account.expired',
128 + data: {
129 + toolkit: { slug: 'gmail' },
130 + auth_config: {
131 + id: 'ac_izZGRCZ9qyxk',
132 + auth_scheme: 'OAUTH2',
133 + is_composio_managed: true,
134 + is_disabled: false,
135 + },
136 + id: 'ca__IvSeEzEBjVt',
137 + user_id: 'test-user',
138 + status: 'EXPIRED',
139 + created_at: '2026-02-02T08:35:44.272Z',
140 + updated_at: '2026-02-02T10:14:20.949Z',
141 + state: {
142 + authScheme: 'OAUTH2',
143 + val: { status: 'EXPIRED' },
144 + },
145 + data: {},
146 + params: {},
147 + status_reason: null,
148 + is_disabled: false,
149 + },
150 + metadata: {
151 + project_id: 'pr_koucdrMIwRsf',
152 + org_id: '4a4ded8f-d3ae-4dea-a229-c30234298b05',
153 + },
154 + };
155 +
156 + it('validates a valid connection expired event', () => {
157 + const result = ConnectionExpiredEventSchema.safeParse(validPayload);
158 + expect(result.success).toBe(true);
159 + });
160 +
161 + it('extracts typed data from parsed result', () => {
162 + const result = ConnectionExpiredEventSchema.safeParse(validPayload);
163 + expect(result.success).toBe(true);
164 + if (result.success) {
165 + expect(result.data.type).toBe('composio.connected_account.expired');
166 + expect(result.data.data.id).toBe('ca__IvSeEzEBjVt');
167 + expect(result.data.data.toolkit.slug).toBe('gmail');
168 + expect(result.data.data.status).toBe('EXPIRED');
169 + expect(result.data.metadata.project_id).toBe('pr_koucdrMIwRsf');
170 + }
171 + });
172 +
173 + it('rejects invalid event type', () => {
174 + const payload = {
175 + ...validPayload,
176 + type: 'composio.trigger.message',
177 + };
178 + const result = ConnectionExpiredEventSchema.safeParse(payload);
179 + expect(result.success).toBe(false);
180 + });
181 +
182 + it('rejects missing metadata fields', () => {
183 + const payload = {
184 + ...validPayload,
185 + metadata: { project_id: 'pr_abc' }, // missing org_id
186 + };
187 + const result = ConnectionExpiredEventSchema.safeParse(payload);
188 + expect(result.success).toBe(false);
189 + });
190 +
191 + it('rejects missing data fields', () => {
192 + const payload = {
193 + ...validPayload,
194 + data: { toolkit: { slug: 'gmail' } }, // missing required fields
195 + };
196 + const result = ConnectionExpiredEventSchema.safeParse(payload);
197 + expect(result.success).toBe(false);
198 + });
199 +
200 + it('validates payload with status_reason', () => {
201 + const payload = {
202 + ...validPayload,
203 + data: {
204 + ...validPayload.data,
205 + status_reason: 'Token refresh failed due to revoked access',
206 + },
207 + };
208 + const result = ConnectionExpiredEventSchema.safeParse(payload);
209 + expect(result.success).toBe(true);
210 + if (result.success) {
211 + expect(result.data.data.status_reason).toBe('Token refresh failed due to revoked access');
212 + }
213 + });
214 +});
215 +
216 +describe('WebhookEventSchema', () => {
217 + const validConnectionExpiredPayload = {
218 + id: 'msg_847cdfcd-d219-4f18-a6dd-91acd42ca94a',
219 + timestamp: '2026-02-02T10:14:20.955Z',
220 + type: 'composio.connected_account.expired',
221 + data: {
222 + toolkit: { slug: 'gmail' },
223 + auth_config: {
224 + id: 'ac_izZGRCZ9qyxk',
225 + auth_scheme: 'OAUTH2',
226 + is_composio_managed: true,
227 + is_disabled: false,
228 + },
229 + id: 'ca__IvSeEzEBjVt',
230 + user_id: 'test-user',
231 + status: 'EXPIRED',
232 + created_at: '2026-02-02T08:35:44.272Z',
233 + updated_at: '2026-02-02T10:14:20.949Z',
234 + state: {
235 + authScheme: 'OAUTH2',
236 + val: { status: 'EXPIRED' },
237 + },
238 + data: {},
239 + params: {},
240 + status_reason: null,
241 + is_disabled: false,
242 + },
243 + metadata: {
244 + project_id: 'pr_koucdrMIwRsf',
245 + org_id: '4a4ded8f-d3ae-4dea-a229-c30234298b05',
246 + },
247 + };
248 +
249 + it('discriminates by event type for connection expired', () => {
250 + const result = WebhookEventSchema.safeParse(validConnectionExpiredPayload);
251 + expect(result.success).toBe(true);
252 + if (result.success) {
253 + expect(result.data.type).toBe('composio.connected_account.expired');
254 + }
255 + });
256 +
257 + it('rejects unknown event types', () => {
258 + const payload = {
259 + ...validConnectionExpiredPayload,
260 + type: 'composio.unknown.event',
261 + };
262 + const result = WebhookEventSchema.safeParse(payload);
263 + expect(result.success).toBe(false);
264 + });
265 +});