dex-connector-superdurable-webhook 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,37 @@
1
+ Metadata-Version: 2.5
2
+ Name: dex-connector-superdurable-webhook
3
+ Version: 0.1.0
4
+ Summary: Super Durable Webhook connector for Dex Flows
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.11
7
+ Requires-Dist: dex-connectors-sdk==0.1.0
8
+ Requires-Dist: dex-python-sdk>=1.28.0
9
+ Requires-Dist: httpx>=0.27
10
+ Description-Content-Type: text/markdown
11
+
12
+ # Super Durable Webhook Python connector
13
+
14
+ The `dex-connector-superdurable-webhook` package implements `sendEvent` for
15
+ Python Dex Flows. It sends one JSON value to the connection's HTTPS
16
+ `deliveryUrl` with Standard Webhooks `webhook-id`, `webhook-timestamp`, and
17
+ `webhook-signature` headers. The same Dex call retains its webhook ID across
18
+ retries. The receiver must deduplicate that ID as described in the
19
+ [connector contract](../README.md#the-sendevent-mutation).
20
+
21
+ The Python package does not implement the Go `requestReceived` Trigger.
22
+ Configure `signing_secret` and `deliveryUrl` in Dex Web **Connections**, using
23
+ the [provider setup guide](../README.md#sender-setup). The secret never enters
24
+ Flow input or Results. An invalid destination or payload selects
25
+ `defect`; a definite receiver rejection selects `rejected`. Both are optional
26
+ branches, so the [runnable Flow](examples/send_event/flow.py) leaves them
27
+ unwired and fails when selected.
28
+
29
+ `SendEventInput.payload` accepts any JSON value, including `None` for JSON
30
+ `null`. Pass UTF-8 JSON `bytes` to send and sign the exact bytes supplied;
31
+ otherwise the connector encodes the Python value as JSON before checking
32
+ `maxBodyBytes`.
33
+
34
+ Run the [send event example](examples/send_event/README.md) to exercise the
35
+ package through a Dex Worker and Client. Its static connection name is
36
+ `webhook-forwarding`. The example's `SendSignedWebhookEvent` Step exposes no
37
+ operation-specific configuration fields in Dex Web.
@@ -0,0 +1,19 @@
1
+ dex_connectors/superdurable_webhook/__init__.py,sha256=goaqnYzAq9s9Crm-_QUWFc0x6Ul4OkIfmRn8Xw5ISaA,685
2
+ dex_connectors/superdurable_webhook/client.py,sha256=ouLONbri9W37s1jhA-Ar3PVn8hCk-jqqLUsUlgfi2Fo,2551
3
+ dex_connectors/superdurable_webhook/connection.py,sha256=rwDdBYdLZ5n_xVBJbvCyKUlqxsB469SiLi3aeIvdwUQ,351
4
+ dex_connectors/superdurable_webhook/dex-connector.json,sha256=e9ZJMjs7tJDP5-b5STHe4T3ohpDd0qGGVM5qqEV2nZk,878
5
+ dex_connectors/superdurable_webhook/models.py,sha256=UgBxL8XVv9hTbb8ItiGkIdXkBBHJJtpzdMy_WkDO8iE,215
6
+ dex_connectors/superdurable_webhook/operations.py,sha256=IdvXrYJm350Th9BlJ-NB0YgkDVPE3hB3gwSna4uuT4M,6304
7
+ dex_connectors/superdurable_webhook/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ dex_connectors/superdurable_webhook/steps.py,sha256=GPcq_6i3U2UNmCPoiBaxI9ojM_vBYMcmpTDZA5qg4h0,206
9
+ dex_connectors/superdurable_webhook/_generated/__init__.py,sha256=ShfMsAGzSt4xuhCaf20ibgtfXl4pXomZb00ovUw6CeI,66
10
+ dex_connectors/superdurable_webhook/_generated/config.py,sha256=r06pDJkoeX5BZeS5WBL-iN7Lln4JiMYsVMCbSaZCbz0,838
11
+ dex_connectors/superdurable_webhook/_generated/connection.py,sha256=ecD7_AM7txLDWaVY--FBSAeScFu2dQaiZuzdq2FO1GM,8426
12
+ dex_connectors/superdurable_webhook/_generated/definitions.py,sha256=USkWE_sIxbOEpAzHAZaf00F6c7J-sAW92aCNLsioMz4,1301
13
+ dex_connectors/superdurable_webhook/_generated/mock.py,sha256=DFHAIzw9GGA76VDajnYWMnf_HJUGps8emuTmVNM62CU,2955
14
+ dex_connectors/superdurable_webhook/_generated/models.py,sha256=aITmQfDQTGzPAuOfh_oGdHUYGnVLmF4EAyOATYzbq1Q,1394
15
+ dex_connectors/superdurable_webhook/_generated/steps.py,sha256=L6VELPCGoox8fO0GgbUTjaldkCjwunpGrGoKlAGOQmg,3018
16
+ dex_connectors/superdurable_webhook/webhookmock/__init__.py,sha256=sEODfqQ6BJ0_cxRmH7FUHlzuhGC26jntpGD0cmUtm_U,167
17
+ dex_connector_superdurable_webhook-0.1.0.dist-info/METADATA,sha256=A3v3q_HfO9f1Z_e9d9ykzY8bBrtanJV8-XW6TvA8fJo,1791
18
+ dex_connector_superdurable_webhook-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
19
+ dex_connector_superdurable_webhook-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,23 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
3
+ """Signed Standard Webhooks event delivery for Dex Flows."""
4
+
5
+ from .client import Client, Config, Credentials
6
+ from .connection import Connection, new_connection, new_connection_with_operations, new_project_connection
7
+ from .models import SendEventInput, SendEventOutput
8
+ from .operations import SendEventOperation
9
+ from .steps import new_send_event_step
10
+
11
+ __all__ = [
12
+ "Client",
13
+ "Config",
14
+ "Credentials",
15
+ "Connection",
16
+ "SendEventInput",
17
+ "SendEventOutput",
18
+ "SendEventOperation",
19
+ "new_connection",
20
+ "new_connection_with_operations",
21
+ "new_project_connection",
22
+ "new_send_event_step",
23
+ ]
@@ -0,0 +1,2 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
@@ -0,0 +1,33 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
3
+ # ruff: noqa
4
+
5
+ from dataclasses import dataclass
6
+
7
+ from dex_connectors.sdk import SecretString
8
+
9
+
10
+ @dataclass(frozen=True, slots=True)
11
+ class Config:
12
+
13
+ signature_prefix: str
14
+ event_id_header: str
15
+ event_id_pointer: str
16
+ forwarded_headers: tuple[str, ...]
17
+ delivery_url: str
18
+ verification: str = "hmacSha256"
19
+ signature_header: str = "X-Signature-256"
20
+ signature_encoding: str = "hex"
21
+ timestamp_tolerance_seconds: int = 300
22
+ token_header: str = "X-Webhook-Token"
23
+ max_body_bytes: int = 1048576
24
+
25
+ setattr(Config, '__module__', 'dex_connectors.superdurable_webhook.client')
26
+
27
+
28
+ @dataclass(frozen=True, slots=True)
29
+ class Credentials:
30
+
31
+ signing_secret: SecretString
32
+
33
+ setattr(Credentials, '__module__', 'dex_connectors.superdurable_webhook.client')
@@ -0,0 +1,179 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
3
+ # ruff: noqa
4
+
5
+ from typing import Any
6
+
7
+ import httpx
8
+ from dex_connectors.sdk import ConnectionRef, Mutation, Call, SecretString
9
+ from dex_connectors.sdk.projectconfig import ConnectionKey, LoadedProject
10
+
11
+ from ..client import Client, Config, Credentials
12
+ from .definitions import CONNECTOR_ID, SEND_EVENT_DEFINITION
13
+ from ..models import SendEventInput, SendEventOutput
14
+
15
+ class Connection:
16
+
17
+ __slots__ = ('_send_event', '_client', 'reference')
18
+
19
+ def __init__(self,
20
+ reference: ConnectionRef,
21
+ send_event: Mutation[SendEventInput, SendEventOutput],
22
+ client: Client | None = None,
23
+ ) -> None:
24
+ reference.validate()
25
+ if reference.provider != CONNECTOR_ID or send_event is None:
26
+ raise ValueError("Webhook connection provider and operations are required")
27
+ if send_event.definition().operation != SEND_EVENT_DEFINITION.operation:
28
+ raise ValueError("Webhook connection operation identity differs")
29
+ self.reference = reference
30
+ self._send_event = send_event
31
+ self._client = client
32
+
33
+ def send_event(self) -> Mutation[SendEventInput, SendEventOutput]:
34
+ return self._send_event
35
+
36
+ async def aclose(self) -> None:
37
+ if self._client is not None:
38
+ await self._client.aclose()
39
+
40
+ def __repr__(self) -> str:
41
+ return "superdurable_webhook.Connection([REDACTED])"
42
+
43
+ def __reduce__(self) -> tuple[object, ...]:
44
+ raise TypeError("Webhook connections cannot be serialized")
45
+
46
+ setattr(Connection, '__module__', 'dex_connectors.superdurable_webhook.connection')
47
+
48
+
49
+ def new_connection(client: Client, reference: ConnectionRef) -> Connection:
50
+ if client is None:
51
+ raise ValueError("Webhook client is required")
52
+ return Connection(reference, client.send_event(), client)
53
+
54
+ setattr(new_connection, '__module__', 'dex_connectors.superdurable_webhook.connection')
55
+
56
+
57
+ def new_connection_with_operations(
58
+ send_event: Mutation[SendEventInput, SendEventOutput],
59
+ reference: ConnectionRef,
60
+ ) -> Connection:
61
+ return Connection(reference, send_event)
62
+
63
+ setattr(new_connection_with_operations, '__module__', 'dex_connectors.superdurable_webhook.connection')
64
+
65
+
66
+ class _ProjectCredentialSource:
67
+
68
+ def __init__(self, project: LoadedProject, key: ConnectionKey) -> None:
69
+ self.project = project
70
+ self.key = key
71
+
72
+ async def resolve(self, call: Call) -> Credentials:
73
+ material = await self.project.resolve_credential(self.key, str(call.id))
74
+ if not isinstance(material, dict):
75
+ raise ValueError("Webhook stored credential does not match the connector credential fields")
76
+ if set(material) - set(('signing_secret',)):
77
+ raise ValueError("Webhook stored credential does not match the connector credential fields")
78
+ signing_secret = material.get("signing_secret")
79
+ if signing_secret is not None and not (isinstance(signing_secret, str)):
80
+ raise ValueError("Webhook credential signing_secret has an invalid type")
81
+ if not signing_secret:
82
+ raise ValueError("Webhook credential signing_secret is required")
83
+ return Credentials(SecretString(signing_secret))
84
+
85
+
86
+ def new_project_connection(
87
+ project: LoadedProject, connection_name: str, http_client: httpx.AsyncClient | None = None
88
+ ) -> Connection:
89
+ if project is None:
90
+ raise ValueError("Webhook connection requires loaded project configuration")
91
+ reference = ConnectionRef(CONNECTOR_ID, connection_name)
92
+ reference.validate()
93
+ key = ConnectionKey(CONNECTOR_ID, connection_name)
94
+ matching = [
95
+ entry
96
+ for entry in project.configuration.connections
97
+ if entry.connector_id == CONNECTOR_ID and entry.connection_name == connection_name
98
+ ]
99
+ if len(matching) != 1:
100
+ raise ValueError("Webhook project connection is missing or duplicated")
101
+ if matching[0].provider != CONNECTOR_ID:
102
+ raise ValueError("Webhook project connection provider differs")
103
+ config = _decode_config(matching[0].configuration)
104
+ client = Client(config, _ProjectCredentialSource(project, key), http_client)
105
+ return new_connection(client, reference)
106
+
107
+ setattr(new_project_connection, '__module__', 'dex_connectors.superdurable_webhook.connection')
108
+
109
+
110
+ def _decode_config(value: dict[str, Any]) -> Config:
111
+ if set(value) - {"verification", "signatureHeader", "signaturePrefix", "signatureEncoding", "timestampToleranceSeconds", "tokenHeader", "eventIdHeader", "eventIdPointer", "maxBodyBytes", "forwardedHeaders", "deliveryUrl"}:
112
+ raise ValueError("Webhook configuration has unknown fields")
113
+ config_arguments: dict[str, Any] = {}
114
+ if "verification" in value:
115
+ verification = value["verification"]
116
+ if not (isinstance(verification, str) and verification in ('hmacSha256', 'standardWebhooks', 'sharedToken')):
117
+ raise ValueError("Webhook configuration verification has an invalid type")
118
+ config_arguments['verification'] = verification
119
+ if "signatureHeader" in value:
120
+ signature_header = value["signatureHeader"]
121
+ if not (isinstance(signature_header, str)):
122
+ raise ValueError("Webhook configuration signatureHeader has an invalid type")
123
+ config_arguments['signature_header'] = signature_header
124
+ if "signaturePrefix" in value:
125
+ signature_prefix = value["signaturePrefix"]
126
+ if not (isinstance(signature_prefix, str)):
127
+ raise ValueError("Webhook configuration signaturePrefix has an invalid type")
128
+ config_arguments['signature_prefix'] = signature_prefix
129
+ else:
130
+ config_arguments['signature_prefix'] = ''
131
+ if "signatureEncoding" in value:
132
+ signature_encoding = value["signatureEncoding"]
133
+ if not (isinstance(signature_encoding, str) and signature_encoding in ('hex', 'base64')):
134
+ raise ValueError("Webhook configuration signatureEncoding has an invalid type")
135
+ config_arguments['signature_encoding'] = signature_encoding
136
+ if "timestampToleranceSeconds" in value:
137
+ timestamp_tolerance_seconds = value["timestampToleranceSeconds"]
138
+ if not (type(timestamp_tolerance_seconds) is int):
139
+ raise ValueError("Webhook configuration timestampToleranceSeconds has an invalid type")
140
+ config_arguments['timestamp_tolerance_seconds'] = timestamp_tolerance_seconds
141
+ if "tokenHeader" in value:
142
+ token_header = value["tokenHeader"]
143
+ if not (isinstance(token_header, str)):
144
+ raise ValueError("Webhook configuration tokenHeader has an invalid type")
145
+ config_arguments['token_header'] = token_header
146
+ if "eventIdHeader" in value:
147
+ event_id_header = value["eventIdHeader"]
148
+ if not (isinstance(event_id_header, str)):
149
+ raise ValueError("Webhook configuration eventIdHeader has an invalid type")
150
+ config_arguments['event_id_header'] = event_id_header
151
+ else:
152
+ config_arguments['event_id_header'] = ''
153
+ if "eventIdPointer" in value:
154
+ event_id_pointer = value["eventIdPointer"]
155
+ if not (isinstance(event_id_pointer, str)):
156
+ raise ValueError("Webhook configuration eventIdPointer has an invalid type")
157
+ config_arguments['event_id_pointer'] = event_id_pointer
158
+ else:
159
+ config_arguments['event_id_pointer'] = ''
160
+ if "maxBodyBytes" in value:
161
+ max_body_bytes = value["maxBodyBytes"]
162
+ if not (type(max_body_bytes) is int):
163
+ raise ValueError("Webhook configuration maxBodyBytes has an invalid type")
164
+ config_arguments['max_body_bytes'] = max_body_bytes
165
+ if "forwardedHeaders" in value:
166
+ forwarded_headers = value["forwardedHeaders"]
167
+ if not (isinstance(forwarded_headers, list) and all(isinstance(item, str) for item in forwarded_headers)):
168
+ raise ValueError("Webhook configuration forwardedHeaders has an invalid type")
169
+ config_arguments['forwarded_headers'] = tuple(forwarded_headers)
170
+ else:
171
+ config_arguments['forwarded_headers'] = ()
172
+ if "deliveryUrl" in value:
173
+ delivery_url = value["deliveryUrl"]
174
+ if not (isinstance(delivery_url, str)):
175
+ raise ValueError("Webhook configuration deliveryUrl has an invalid type")
176
+ config_arguments['delivery_url'] = delivery_url
177
+ else:
178
+ config_arguments['delivery_url'] = ''
179
+ return Config(**config_arguments)
@@ -0,0 +1,36 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
3
+ # ruff: noqa
4
+
5
+ from datetime import timedelta
6
+
7
+ from dex_connectors.sdk import (
8
+ BranchDefinition,
9
+ MutationDefinition,
10
+ OperationRef,
11
+ QueryDefinition,
12
+ RetryPolicy,
13
+ StepDefaults,
14
+ default_connector_step_execute_retry_policy,
15
+ )
16
+
17
+ CONNECTOR_ID = "webhook"
18
+ PROVIDER = "webhook"
19
+ SEND_EVENT_OPERATION_ID = "sendEvent"
20
+ DEFECT = "defect"
21
+ DELIVERED = "delivered"
22
+ REJECTED = "rejected"
23
+
24
+ SEND_EVENT_DEFINITION = MutationDefinition(
25
+ OperationRef(CONNECTOR_ID, SEND_EVENT_OPERATION_ID),
26
+ (
27
+ BranchDefinition(DELIVERED, "The receiver answered 2xx and accepted the event.", False),
28
+ BranchDefinition(REJECTED, "The receiver answered a redirect or a 4xx other than 408, 409, 425, and 429, so it refused the event; the Result carries the status code. A 409 is retried with the same webhook-id instead, and fails the Flow when the retry budget runs out.", True),
29
+ BranchDefinition(DEFECT, "The connection has no valid deliveryUrl or signing secret, or the payload is not one JSON value within maxBodyBytes.", True),
30
+ ),
31
+ StepDefaults(
32
+ timedelta(seconds=30),
33
+ 2,
34
+ execute_retry=RetryPolicy(timedelta(seconds=1), 2, timedelta(seconds=30), 5, timedelta(seconds=120)),
35
+ ),
36
+ )
@@ -0,0 +1,68 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
3
+ # ruff: noqa
4
+
5
+ from datetime import datetime
6
+
7
+ from dex_connectors.sdk import ConnectionRef, Failure, FailureKind
8
+ from dex_connectors.sdk.connectormock import Case, Mutation
9
+
10
+ from ..connection import Connection, new_connection_with_operations
11
+ from ..models import SendEventInput, SendEventOutput
12
+ from .definitions import CONNECTOR_ID, DEFECT, DELIVERED, REJECTED, SEND_EVENT_DEFINITION
13
+
14
+ def send_event_delivered(value: SendEventOutput, failure: Failure | None = None) -> Case[SendEventOutput]:
15
+ return Case.branch_result(DELIVERED, value, failure)
16
+
17
+ setattr(send_event_delivered, '__module__', "dex_connectors.superdurable_webhook.webhookmock")
18
+
19
+ def send_event_rejected(value: SendEventOutput, failure: Failure | None = None) -> Case[SendEventOutput]:
20
+ return Case.branch_result(REJECTED, value, failure)
21
+
22
+ setattr(send_event_rejected, '__module__', "dex_connectors.superdurable_webhook.webhookmock")
23
+
24
+ def send_event_defect(value: SendEventOutput, failure: Failure | None = None) -> Case[SendEventOutput]:
25
+ return Case.branch_result(DEFECT, value, failure)
26
+
27
+ setattr(send_event_defect, '__module__', "dex_connectors.superdurable_webhook.webhookmock")
28
+
29
+ def send_event_retry(failure: Failure, after_seconds: float = 0) -> Case[SendEventOutput]:
30
+ return Case.retry(failure, after_seconds)
31
+
32
+ setattr(send_event_retry, '__module__', "dex_connectors.superdurable_webhook.webhookmock")
33
+
34
+ def send_event_submission_delivered() -> Case[SendEventOutput]:
35
+ return Case.branch_result(DELIVERED, SendEventOutput(webhook_id='msg_00000000000000000000000000000001', status_code=202))
36
+
37
+ setattr(send_event_submission_delivered, '__module__', "dex_connectors.superdurable_webhook.webhookmock")
38
+
39
+ def send_event_submission_rejected() -> Case[SendEventOutput]:
40
+ return Case.branch_result(REJECTED, SendEventOutput(webhook_id='msg_00000000000000000000000000000002', status_code=422), Failure(FailureKind.PROVIDER_REJECTION, CONNECTOR_ID, "sendEvent", "The receiver answered HTTP 422."))
41
+
42
+ setattr(send_event_submission_rejected, '__module__', "dex_connectors.superdurable_webhook.webhookmock")
43
+
44
+
45
+ class Mock:
46
+
47
+ def __init__(self, connection_name: str = "webhook") -> None:
48
+ self.send_event_script: Mutation[SendEventInput, SendEventOutput] = Mutation(SEND_EVENT_DEFINITION)
49
+ self.send_event_script.default(send_event_submission_delivered())
50
+ self._connection = new_connection_with_operations(
51
+ send_event=self.send_event_script,
52
+ reference=ConnectionRef(CONNECTOR_ID, connection_name),
53
+ )
54
+
55
+ def connection(self) -> Connection:
56
+ return self._connection
57
+
58
+ setattr(Mock, '__module__', "dex_connectors.superdurable_webhook.webhookmock")
59
+
60
+ __all__ = [
61
+ "Mock",
62
+ "send_event_delivered",
63
+ "send_event_rejected",
64
+ "send_event_defect",
65
+ "send_event_retry",
66
+ "send_event_submission_delivered",
67
+ "send_event_submission_rejected",
68
+ ]
@@ -0,0 +1,29 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
3
+ # ruff: noqa
4
+
5
+ from dataclasses import dataclass, field as _dataclass_field
6
+ from typing import Any
7
+
8
+ # SendEventInput is one JSON event that sendEvent POSTs to the connection's deliveryUrl.
9
+ @dataclass(frozen=True, slots=True)
10
+ class SendEventInput:
11
+ # Payload is the complete JSON request body, such as {"type":"form.submitted","data":{...}}. It must be
12
+ # one valid JSON value of at most maxBodyBytes bytes; an empty or invalid payload selects defect.
13
+ payload: Any = None
14
+
15
+
16
+ setattr(SendEventInput, '__module__', 'dex_connectors.superdurable_webhook.models')
17
+
18
+
19
+ # SendEventOutput describes one sendEvent attempt's outcome. It never holds the payload or response body.
20
+ @dataclass(frozen=True, slots=True)
21
+ class SendEventOutput:
22
+ # WebhookID is the webhook-id header value. It is derived from the Step's idempotency key, so every
23
+ # retry and duplicate dispatch of one Step execution sends the same ID and receivers can deduplicate.
24
+ webhook_id: str = _dataclass_field(default='', metadata={'dex_json_name': 'webhookId'})
25
+ # StatusCode is the receiver's HTTP status, or zero when no response arrived.
26
+ status_code: int = _dataclass_field(default=0, metadata={'dex_json_name': 'statusCode', 'dex_json_omit_default': True})
27
+
28
+
29
+ setattr(SendEventOutput, '__module__', 'dex_connectors.superdurable_webhook.models')
@@ -0,0 +1,75 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
3
+ # ruff: noqa
4
+
5
+ from collections.abc import Callable, Mapping
6
+ from typing import Any, TypeVar
7
+
8
+ import dex
9
+ from dex_connectors.sdk import (
10
+ MutationResult,
11
+ MutationStep,
12
+ MutationStepConfig,
13
+ StepAnnotations,
14
+ )
15
+
16
+ from ..connection import Connection
17
+ from ..models import SendEventInput, SendEventOutput
18
+
19
+ StepInput = TypeVar("StepInput")
20
+
21
+ def new_send_event_step(
22
+ *,
23
+ step_type: str,
24
+ step_input_type: type[StepInput],
25
+ annotations: StepAnnotations | Mapping[str, str],
26
+ connection: Connection,
27
+ connection_name: str,
28
+ map_to_operation_input: Callable[[StepInput], SendEventInput],
29
+ delivered: dex.StepTarget[MutationResult[SendEventOutput]],
30
+ rejected: dex.StepTarget[MutationResult[SendEventOutput]] | None = None,
31
+ defect: dex.StepTarget[MutationResult[SendEventOutput]] | None = None,
32
+ result_attribute: dex.Attribute[MutationResult[SendEventOutput]] | None = None,
33
+ step_options_override: dex.StepOptions | None = None,
34
+ ) -> MutationStep[StepInput, SendEventInput, SendEventOutput]:
35
+ if connection is None or connection.reference.name != connection_name:
36
+ raise ValueError("Webhook Step connection name must match its connection reference")
37
+ if isinstance(annotations, StepAnnotations):
38
+ step_annotations = annotations
39
+ else:
40
+ if not isinstance(annotations, Mapping) or set(annotations) != {"groupId", "groupLabel", "explanation"}:
41
+ raise ValueError("Webhook Step annotations require groupId, groupLabel, and explanation")
42
+ if any(not isinstance(value, str) for value in annotations.values()):
43
+ raise ValueError("Webhook Step annotations must be strings")
44
+ step_annotations = StepAnnotations(annotations["groupId"], annotations["groupLabel"], annotations["explanation"])
45
+ branches = {
46
+ "delivered": delivered,
47
+ }
48
+ if rejected is not None:
49
+ branches["rejected"] = rejected
50
+ if defect is not None:
51
+ branches["defect"] = defect
52
+ return MutationStep(
53
+ MutationStepConfig(
54
+ step_type=step_type,
55
+ step_input_type=step_input_type,
56
+ annotations=step_annotations,
57
+ operation=_bound_operation(connection, "send_event"),
58
+ connection=connection.reference,
59
+ map_to_operation_input=map_to_operation_input,
60
+ branches=branches,
61
+ result_attribute=result_attribute,
62
+ step_options_override=step_options_override,
63
+ )
64
+ )
65
+
66
+ setattr(new_send_event_step, '__module__', 'dex_connectors.superdurable_webhook.steps')
67
+
68
+
69
+ def _bound_operation(connection: Connection, operation_name: str) -> Any:
70
+ source = getattr(connection, operation_name, None)
71
+ if source is None:
72
+ source = getattr(getattr(connection, "operations", None), operation_name, None)
73
+ if source is None:
74
+ raise ValueError(f"connection operation {operation_name} is missing")
75
+ return source() if callable(source) else source
@@ -0,0 +1,73 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
3
+ """Signed Standard Webhooks delivery client."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from collections.abc import Callable
8
+ from datetime import UTC, datetime
9
+ from typing import TYPE_CHECKING
10
+ from urllib.parse import urlsplit, urlunsplit
11
+
12
+ import httpx
13
+ from dex_connectors.sdk import CredentialProvider
14
+ from dex_connectors.sdk.providerhttp import new_provider_http_client
15
+
16
+ from ._generated.config import Config as Config
17
+ from ._generated.config import Credentials as Credentials
18
+
19
+ if TYPE_CHECKING:
20
+ from .operations import SendEventOperation
21
+
22
+
23
+ class Client:
24
+ """Hold validated delivery settings and resolve the signing secret per call."""
25
+
26
+ def __init__(
27
+ self,
28
+ config: Config,
29
+ credentials: CredentialProvider[Credentials],
30
+ http_client: httpx.AsyncClient | None = None,
31
+ clock: Callable[[], datetime] | None = None,
32
+ ) -> None:
33
+ if config is None or credentials is None:
34
+ raise ValueError("webhook settings and credentials are required")
35
+ if config.max_body_bytes <= 0:
36
+ raise ValueError("webhook maxBodyBytes must be positive")
37
+ self.delivery_url = _validate_delivery_url(config.delivery_url)
38
+ self.max_body_bytes = config.max_body_bytes
39
+ self.credentials = credentials
40
+ self.http_client = http_client or new_provider_http_client(25)
41
+ self.clock = clock or (lambda: datetime.now(UTC))
42
+
43
+ def send_event(self) -> SendEventOperation:
44
+ """Bind the signed event delivery Mutation."""
45
+ from .operations import SendEventOperation
46
+
47
+ return SendEventOperation(self)
48
+
49
+ async def aclose(self) -> None:
50
+ """Close the owned provider HTTP client after Worker shutdown."""
51
+ await self.http_client.aclose()
52
+
53
+
54
+ def _validate_delivery_url(value: str) -> str:
55
+ if not value:
56
+ return ""
57
+ if any(ord(character) <= 32 or ord(character) > 126 for character in value):
58
+ raise ValueError("webhook deliveryUrl must be printable ASCII without spaces")
59
+ parsed = urlsplit(value)
60
+ if (
61
+ parsed.scheme != "https"
62
+ or not parsed.hostname
63
+ or parsed.username
64
+ or parsed.password
65
+ or parsed.fragment
66
+ ):
67
+ raise ValueError(
68
+ "webhook deliveryUrl must be an absolute HTTPS URL without credentials or a fragment"
69
+ )
70
+ canonical_url = urlunsplit(parsed)
71
+ if value.endswith("?") and not canonical_url.endswith("?"):
72
+ canonical_url += "?"
73
+ return canonical_url
@@ -0,0 +1,12 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
3
+ """Named webhook connection bindings."""
4
+
5
+ from ._generated.connection import (
6
+ Connection,
7
+ new_connection,
8
+ new_connection_with_operations,
9
+ new_project_connection,
10
+ )
11
+
12
+ __all__ = ["Connection", "new_connection", "new_connection_with_operations", "new_project_connection"]
@@ -0,0 +1,39 @@
1
+ {
2
+ "connectorId": "webhook",
3
+ "releaseTag": "connectors/superdurable/webhook/go/v0.24.0",
4
+ "package": {
5
+ "ecosystem": "pypi",
6
+ "name": "dex-connector-superdurable-webhook",
7
+ "version": "0.1.0"
8
+ },
9
+ "factories": [
10
+ {
11
+ "name": "new_send_event_step",
12
+ "kind": "mutation",
13
+ "operationId": "sendEvent",
14
+ "fields": {
15
+ "stepType": "step_type",
16
+ "annotations": "annotations",
17
+ "connectionName": "connection_name",
18
+ "resultAttribute": "result_attribute"
19
+ },
20
+ "branches": [
21
+ {
22
+ "id": "delivered",
23
+ "field": "delivered",
24
+ "optional": false
25
+ },
26
+ {
27
+ "id": "rejected",
28
+ "field": "rejected",
29
+ "optional": true
30
+ },
31
+ {
32
+ "id": "defect",
33
+ "field": "defect",
34
+ "optional": true
35
+ }
36
+ ]
37
+ }
38
+ ]
39
+ }
@@ -0,0 +1,7 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
3
+ """Public event delivery models."""
4
+
5
+ from ._generated.models import SendEventInput, SendEventOutput
6
+
7
+ __all__ = ["SendEventInput", "SendEventOutput"]
@@ -0,0 +1,138 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
3
+ """Invoke the signed Standard Webhooks sendEvent operation."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import base64
8
+ import binascii
9
+ import hashlib
10
+ import hmac
11
+ import json
12
+
13
+ from dex_connectors.sdk import (
14
+ Call,
15
+ CallID,
16
+ Failure,
17
+ FailureKind,
18
+ IdempotencyKey,
19
+ MutationAttempt,
20
+ MutationDefinition,
21
+ Receipt,
22
+ )
23
+ from dex_connectors.sdk.projectconfig.broker import CredentialBrokerUnavailableError
24
+ from dex_connectors.sdk.providerhttp import ProviderTransportError, parse_retry_after, send_traced
25
+
26
+ from ._generated.definitions import SEND_EVENT_DEFINITION
27
+ from .client import Client
28
+ from .models import SendEventInput, SendEventOutput
29
+
30
+
31
+ class SendEventOperation:
32
+ """Deliver JSON with a stable webhook ID and fresh signature per attempt."""
33
+
34
+ def __init__(self, client: Client) -> None:
35
+ self.client = client
36
+
37
+ def definition(self) -> MutationDefinition:
38
+ """Return the generated sendEvent Mutation definition."""
39
+ return SEND_EVENT_DEFINITION
40
+
41
+ def idempotency_key(self, call_id: CallID, input: SendEventInput) -> IdempotencyKey:
42
+ """Derive Standard Webhooks' msg_ ID from the stable Dex call ID."""
43
+ return IdempotencyKey("msg_" + str(call_id).replace("-", ""))
44
+
45
+ async def invoke(self, call: Call, input: SendEventInput) -> MutationAttempt[SendEventOutput]:
46
+ """Send once and classify definite, retryable, and local outcomes."""
47
+ webhook_id = str(call.idempotency_key)
48
+ output = SendEventOutput(webhook_id=webhook_id)
49
+ if not self.client.delivery_url:
50
+ return _defect(output, FailureKind.VALIDATION, "the connection has no deliveryUrl")
51
+ try:
52
+ payload = (bytes(input.payload) if isinstance(input.payload, (bytes, bytearray)) else
53
+ json.dumps(input.payload, ensure_ascii=False, separators=(",", ":"),
54
+ allow_nan=False).encode())
55
+ json.loads(payload.decode("utf-8"), parse_constant=lambda value: _reject_json_constant(value))
56
+ except (TypeError, ValueError, UnicodeDecodeError, UnicodeEncodeError):
57
+ return _defect(output, FailureKind.VALIDATION, "sendEvent payload must be one valid JSON value")
58
+ if len(payload) > self.client.max_body_bytes:
59
+ return _defect(output, FailureKind.VALIDATION, "sendEvent payload exceeds maxBodyBytes")
60
+ try:
61
+ credentials = await self.client.credentials.resolve(call)
62
+ except CredentialBrokerUnavailableError:
63
+ return MutationAttempt.retry(_failure(FailureKind.AVAILABILITY, "credential broker unavailable"))
64
+ except Exception:
65
+ return _defect(output, FailureKind.AUTHENTICATION, "webhook signing secret unavailable")
66
+ secret = credentials.signing_secret.reveal()
67
+ if not secret:
68
+ return _defect(output, FailureKind.AUTHENTICATION, "webhook signing secret unavailable")
69
+ if secret.startswith("whsec_"):
70
+ try:
71
+ key = base64.b64decode(secret[6:].replace("\r", "").replace("\n", ""), validate=True)
72
+ except (ValueError, binascii.Error, UnicodeEncodeError):
73
+ return _defect(output, FailureKind.VALIDATION, "whsec_ signing secret is invalid")
74
+ if not key:
75
+ return _defect(output, FailureKind.VALIDATION, "whsec_ signing secret is invalid")
76
+ else:
77
+ key = secret.encode()
78
+ timestamp = str(int(self.client.clock().timestamp()))
79
+ digest = hmac.new(
80
+ key, webhook_id.encode() + b"." + timestamp.encode() + b"." + payload, hashlib.sha256
81
+ ).digest()
82
+ headers = {
83
+ "Content-Type": "application/json",
84
+ "webhook-id": webhook_id,
85
+ "webhook-timestamp": timestamp,
86
+ "webhook-signature": "v1," + base64.b64encode(digest).decode(),
87
+ }
88
+ try:
89
+ request = self.client.http_client.build_request(
90
+ "POST", self.client.delivery_url, headers=headers, content=payload
91
+ )
92
+ except Exception:
93
+ return _defect(output, FailureKind.LOCAL_DEFECT, "the sendEvent request could not be built")
94
+ try:
95
+ response, _ = await send_traced(self.client.http_client, request)
96
+ except ProviderTransportError as error:
97
+ kind = FailureKind.AVAILABILITY if error.provably_not_sent else FailureKind.TRANSPORT
98
+ return MutationAttempt.retry(_failure(kind, "receiver did not answer the event"))
99
+ status = response.status_code
100
+ await response.aclose()
101
+ output = SendEventOutput(webhook_id, status)
102
+ if 200 <= status < 300:
103
+ return MutationAttempt.branch_result("delivered", output, Receipt(provider_object_id=webhook_id))
104
+ delay = parse_retry_after(response.headers.get("Retry-After", ""), self.client.clock())
105
+ if status in (408, 429):
106
+ return MutationAttempt.retry(
107
+ _failure(FailureKind.RATE_LIMIT, f"receiver answered HTTP {status}"), delay
108
+ )
109
+ if status == 409:
110
+ return MutationAttempt.retry(_failure(FailureKind.CONFLICT, "receiver answered HTTP 409"), delay)
111
+ if status == 425 or status >= 500:
112
+ return MutationAttempt.retry(
113
+ _failure(FailureKind.AVAILABILITY, f"receiver answered HTTP {status}"), delay
114
+ )
115
+ kind = {
116
+ 401: FailureKind.AUTHENTICATION,
117
+ 403: FailureKind.AUTHORIZATION,
118
+ 404: FailureKind.NOT_FOUND,
119
+ 410: FailureKind.NOT_FOUND,
120
+ }.get(status, FailureKind.PROVIDER_REJECTION)
121
+ return MutationAttempt.branch_result(
122
+ "rejected",
123
+ output,
124
+ Receipt(provider_object_id=webhook_id),
125
+ _failure(kind, f"receiver answered HTTP {status}"),
126
+ )
127
+
128
+
129
+ def _failure(kind: FailureKind, message: str) -> Failure:
130
+ return Failure(kind, "webhook", "sendEvent", message)
131
+
132
+
133
+ def _reject_json_constant(value: str) -> None:
134
+ raise ValueError(f"invalid JSON constant {value}")
135
+
136
+
137
+ def _defect(output: SendEventOutput, kind: FailureKind, message: str) -> MutationAttempt[SendEventOutput]:
138
+ return MutationAttempt.branch_result("defect", output, Receipt(), _failure(kind, message))
File without changes
@@ -0,0 +1,7 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
3
+ """Operation-specific event delivery Step factory."""
4
+
5
+ from ._generated.steps import new_send_event_step
6
+
7
+ __all__ = ["new_send_event_step"]
@@ -0,0 +1,6 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
3
+ # ruff: noqa: F403
4
+
5
+ from .._generated.mock import *
6
+ from .._generated.mock import __all__ as __all__