omniwebhook 0.1.0__tar.gz

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.
Files changed (102) hide show
  1. omniwebhook-0.1.0/.gitignore +20 -0
  2. omniwebhook-0.1.0/LICENSE +21 -0
  3. omniwebhook-0.1.0/PKG-INFO +129 -0
  4. omniwebhook-0.1.0/README.md +95 -0
  5. omniwebhook-0.1.0/interop/agent.py +183 -0
  6. omniwebhook-0.1.0/pyproject.toml +136 -0
  7. omniwebhook-0.1.0/src/omniwebhook/__init__.py +182 -0
  8. omniwebhook-0.1.0/src/omniwebhook/adapters/__init__.py +1 -0
  9. omniwebhook-0.1.0/src/omniwebhook/adapters/clock.py +20 -0
  10. omniwebhook-0.1.0/src/omniwebhook/adapters/crypto.py +25 -0
  11. omniwebhook-0.1.0/src/omniwebhook/adapters/dns/__init__.py +0 -0
  12. omniwebhook-0.1.0/src/omniwebhook/adapters/dns/system.py +51 -0
  13. omniwebhook-0.1.0/src/omniwebhook/adapters/ledger/__init__.py +0 -0
  14. omniwebhook-0.1.0/src/omniwebhook/adapters/ledger/memory.py +35 -0
  15. omniwebhook-0.1.0/src/omniwebhook/adapters/schemes/__init__.py +0 -0
  16. omniwebhook-0.1.0/src/omniwebhook/adapters/schemes/body_signature.py +83 -0
  17. omniwebhook-0.1.0/src/omniwebhook/adapters/schemes/creem.py +13 -0
  18. omniwebhook-0.1.0/src/omniwebhook/adapters/schemes/event_keys.py +37 -0
  19. omniwebhook-0.1.0/src/omniwebhook/adapters/schemes/github.py +15 -0
  20. omniwebhook-0.1.0/src/omniwebhook/adapters/schemes/hmac_body.py +29 -0
  21. omniwebhook-0.1.0/src/omniwebhook/adapters/schemes/mercadopago.py +86 -0
  22. omniwebhook-0.1.0/src/omniwebhook/adapters/schemes/scheme_verifier.py +116 -0
  23. omniwebhook-0.1.0/src/omniwebhook/adapters/schemes/standard/__init__.py +79 -0
  24. omniwebhook-0.1.0/src/omniwebhook/adapters/schemes/standard/native_signer.py +14 -0
  25. omniwebhook-0.1.0/src/omniwebhook/adapters/schemes/standard/reference_signer.py +16 -0
  26. omniwebhook-0.1.0/src/omniwebhook/adapters/schemes/standard/secret.py +31 -0
  27. omniwebhook-0.1.0/src/omniwebhook/adapters/schemes/standard/signer.py +14 -0
  28. omniwebhook-0.1.0/src/omniwebhook/adapters/schemes/standard/standard_signer.py +42 -0
  29. omniwebhook-0.1.0/src/omniwebhook/adapters/schemes/stripe.py +61 -0
  30. omniwebhook-0.1.0/src/omniwebhook/adapters/stores/__init__.py +0 -0
  31. omniwebhook-0.1.0/src/omniwebhook/adapters/stores/firestore.py +174 -0
  32. omniwebhook-0.1.0/src/omniwebhook/adapters/stores/memory.py +71 -0
  33. omniwebhook-0.1.0/src/omniwebhook/adapters/stores/postgres.py +187 -0
  34. omniwebhook-0.1.0/src/omniwebhook/adapters/tokens.py +26 -0
  35. omniwebhook-0.1.0/src/omniwebhook/adapters/transport/__init__.py +0 -0
  36. omniwebhook-0.1.0/src/omniwebhook/adapters/transport/http_client.py +94 -0
  37. omniwebhook-0.1.0/src/omniwebhook/adapters/transport/httpx_transport.py +48 -0
  38. omniwebhook-0.1.0/src/omniwebhook/adapters/transport/threaded.py +13 -0
  39. omniwebhook-0.1.0/src/omniwebhook/application/__init__.py +1 -0
  40. omniwebhook-0.1.0/src/omniwebhook/application/ports.py +180 -0
  41. omniwebhook-0.1.0/src/omniwebhook/application/receive_webhook.py +199 -0
  42. omniwebhook-0.1.0/src/omniwebhook/application/send_webhook.py +305 -0
  43. omniwebhook-0.1.0/src/omniwebhook/domain/__init__.py +1 -0
  44. omniwebhook-0.1.0/src/omniwebhook/domain/blanks.py +10 -0
  45. omniwebhook-0.1.0/src/omniwebhook/domain/delivery.py +43 -0
  46. omniwebhook-0.1.0/src/omniwebhook/domain/destination.py +118 -0
  47. omniwebhook-0.1.0/src/omniwebhook/domain/errors.py +15 -0
  48. omniwebhook-0.1.0/src/omniwebhook/domain/event_key.py +11 -0
  49. omniwebhook-0.1.0/src/omniwebhook/domain/fields.py +31 -0
  50. omniwebhook-0.1.0/src/omniwebhook/domain/freshness.py +10 -0
  51. omniwebhook-0.1.0/src/omniwebhook/domain/incoming_request.py +29 -0
  52. omniwebhook-0.1.0/src/omniwebhook/domain/ip_address.py +146 -0
  53. omniwebhook-0.1.0/src/omniwebhook/domain/message.py +43 -0
  54. omniwebhook-0.1.0/src/omniwebhook/domain/reception.py +26 -0
  55. omniwebhook-0.1.0/src/omniwebhook/domain/reservation.py +9 -0
  56. omniwebhook-0.1.0/src/omniwebhook/domain/retry.py +109 -0
  57. omniwebhook-0.1.0/src/omniwebhook/domain/signature_pairs.py +22 -0
  58. omniwebhook-0.1.0/src/omniwebhook/domain/spec_version.py +5 -0
  59. omniwebhook-0.1.0/src/omniwebhook/domain/timestamp.py +24 -0
  60. omniwebhook-0.1.0/src/omniwebhook/domain/verification.py +24 -0
  61. omniwebhook-0.1.0/src/omniwebhook/entrypoints/__init__.py +1 -0
  62. omniwebhook-0.1.0/src/omniwebhook/entrypoints/asgi.py +18 -0
  63. omniwebhook-0.1.0/src/omniwebhook/entrypoints/receiver.py +55 -0
  64. omniwebhook-0.1.0/src/omniwebhook/entrypoints/requests.py +27 -0
  65. omniwebhook-0.1.0/src/omniwebhook/entrypoints/sender.py +94 -0
  66. omniwebhook-0.1.0/src/omniwebhook/entrypoints/starlette.py +19 -0
  67. omniwebhook-0.1.0/src/omniwebhook/firestore.py +9 -0
  68. omniwebhook-0.1.0/src/omniwebhook/httpx.py +5 -0
  69. omniwebhook-0.1.0/src/omniwebhook/postgres.py +23 -0
  70. omniwebhook-0.1.0/src/omniwebhook/py.typed +0 -0
  71. omniwebhook-0.1.0/src/omniwebhook/standard.py +26 -0
  72. omniwebhook-0.1.0/src/omniwebhook/starlette.py +5 -0
  73. omniwebhook-0.1.0/tests/__init__.py +0 -0
  74. omniwebhook-0.1.0/tests/adapters/__init__.py +0 -0
  75. omniwebhook-0.1.0/tests/adapters/test_almacen_en_memoria.py +15 -0
  76. omniwebhook-0.1.0/tests/adapters/test_dns.py +72 -0
  77. omniwebhook-0.1.0/tests/adapters/test_transportes.py +165 -0
  78. omniwebhook-0.1.0/tests/application/__init__.py +0 -0
  79. omniwebhook-0.1.0/tests/application/test_receive_webhook.py +226 -0
  80. omniwebhook-0.1.0/tests/application/test_send_webhook.py +322 -0
  81. omniwebhook-0.1.0/tests/architecture/__init__.py +0 -0
  82. omniwebhook-0.1.0/tests/architecture/test_dependencias_opcionales.py +18 -0
  83. omniwebhook-0.1.0/tests/architecture/test_dominio_puro.py +50 -0
  84. omniwebhook-0.1.0/tests/contracts/__init__.py +0 -0
  85. omniwebhook-0.1.0/tests/contracts/idempotency_store.py +53 -0
  86. omniwebhook-0.1.0/tests/domain/__init__.py +0 -0
  87. omniwebhook-0.1.0/tests/domain/test_reglas.py +109 -0
  88. omniwebhook-0.1.0/tests/domain/test_spec_version.py +11 -0
  89. omniwebhook-0.1.0/tests/domain/test_vectores_de_emision.py +51 -0
  90. omniwebhook-0.1.0/tests/entrypoints/__init__.py +0 -0
  91. omniwebhook-0.1.0/tests/entrypoints/test_puntos_de_entrada.py +254 -0
  92. omniwebhook-0.1.0/tests/integration/__init__.py +0 -0
  93. omniwebhook-0.1.0/tests/integration/test_almacen_firestore.py +117 -0
  94. omniwebhook-0.1.0/tests/integration/test_almacen_postgres.py +119 -0
  95. omniwebhook-0.1.0/tests/schemes/__init__.py +0 -0
  96. omniwebhook-0.1.0/tests/schemes/test_configuracion.py +173 -0
  97. omniwebhook-0.1.0/tests/schemes/test_vectores.py +94 -0
  98. omniwebhook-0.1.0/tests/support/__init__.py +0 -0
  99. omniwebhook-0.1.0/tests/support/dobles.py +39 -0
  100. omniwebhook-0.1.0/tests/support/servidor.py +63 -0
  101. omniwebhook-0.1.0/tests/support/vectors.py +29 -0
  102. omniwebhook-0.1.0/uv.lock +1691 -0
@@ -0,0 +1,20 @@
1
+ node_modules/
2
+ dist/
3
+ coverage/
4
+ *.tgz
5
+ .DS_Store
6
+ __pycache__/
7
+ *.pyc
8
+ .venv/
9
+ .mypy_cache/
10
+ .pytest_cache/
11
+ .ruff_cache/
12
+ .import_linter_cache/
13
+ .coverage
14
+ htmlcov/
15
+ .env
16
+ .env.*
17
+ ts/LICENSE
18
+
19
+ # Archivos temporales del comprobador de ejemplos
20
+ .docscheck/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Pablo Alaniz
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,129 @@
1
+ Metadata-Version: 2.5
2
+ Name: omniwebhook
3
+ Version: 0.1.0
4
+ Summary: Webhooks firmados que se emiten y se reciben igual en cualquier stack: verificación, frescura, idempotencia y reintentos con las mismas reglas.
5
+ Project-URL: Homepage, https://github.com/PabloAlaniz/omniwebhook
6
+ Project-URL: Repository, https://github.com/PabloAlaniz/omniwebhook
7
+ Project-URL: Specification, https://github.com/PabloAlaniz/omniwebhook/blob/main/spec/SPEC.md
8
+ Author: Pablo Alaniz
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: hmac,idempotency,mercadopago,retries,signature,standard-webhooks,webhook,webhooks
12
+ Classifier: Development Status :: 2 - Pre-Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Natural Language :: Spanish
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Topic :: Internet :: WWW/HTTP
20
+ Classifier: Topic :: Security
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.11
23
+ Provides-Extra: firestore
24
+ Requires-Dist: google-cloud-firestore>=2.16; extra == 'firestore'
25
+ Provides-Extra: httpx
26
+ Requires-Dist: httpx>=0.27; extra == 'httpx'
27
+ Provides-Extra: postgres
28
+ Requires-Dist: psycopg[pool]>=3.2; extra == 'postgres'
29
+ Provides-Extra: standard
30
+ Requires-Dist: standardwebhooks>=1.3; extra == 'standard'
31
+ Provides-Extra: starlette
32
+ Requires-Dist: starlette>=0.37; extra == 'starlette'
33
+ Description-Content-Type: text/markdown
34
+
35
+ # omniwebhook
36
+
37
+ Webhooks firmados que se emiten y se reciben igual en cualquier stack: verificación, frescura,
38
+ idempotencia y reintentos con las mismas reglas en Python y en TypeScript.
39
+
40
+ - **Recibir**: verifica la firma, rechaza lo viejo y lo ambiguo, y procesa cada evento una sola
41
+ vez. Devuelve un resultado tipado en vez de lanzar.
42
+ - **Emitir**: firma con [Standard Webhooks](https://www.standardwebhooks.com/), no entrega a
43
+ direcciones internas y dice cuándo reintentar.
44
+ - **Sincrónico y asincrónico**, con tipos completos y sin dependencias obligatorias. Python 3.11 o
45
+ superior.
46
+
47
+ ```bash
48
+ pip install omniwebhook
49
+ ```
50
+
51
+ ## Recibir
52
+
53
+ ```python
54
+ import json
55
+ import os
56
+
57
+ from omniwebhook import VerifiedEvent, create_async_receiver, stripe_scheme
58
+ from omniwebhook.postgres import AsyncPostgresIdempotencyStore, AsyncPsycopgClient
59
+ from omniwebhook.starlette import to_incoming_request, to_response
60
+
61
+ receive = create_async_receiver(
62
+ verifier=stripe_scheme(secrets=[os.environ.get("STRIPE_WEBHOOK_SECRET", "")]),
63
+ store=AsyncPostgresIdempotencyStore(AsyncPsycopgClient(pool.connection)),
64
+ )
65
+
66
+
67
+ @app.post("/webhooks/stripe")
68
+ async def stripe_webhook(request: Request) -> Response:
69
+ async def procesar(event: VerifiedEvent) -> None:
70
+ await registrar_pago(json.loads(event.request.body))
71
+
72
+ return to_response(await receive.execute(await to_incoming_request(request), procesar))
73
+ ```
74
+
75
+ Esquemas incluidos: `stripe_scheme`, `mercadopago_scheme`, `github_scheme`, `creem_scheme`,
76
+ `hmac_body_scheme` y, en `omniwebhook.standard`, `standard_scheme`.
77
+
78
+ ## Emitir
79
+
80
+ ```python
81
+ import os
82
+
83
+ from omniwebhook import Delivery, Endpoint, MemoryDeliveryLedger, create_sender, random_message_id
84
+ from omniwebhook.standard import standard_signer
85
+
86
+ send = create_sender(
87
+ signer=standard_signer(secrets=[os.environ.get("WEBHOOK_SIGNING_SECRET", "")]),
88
+ ledger=MemoryDeliveryLedger(),
89
+ )
90
+
91
+ attempt = send.execute(
92
+ Delivery(
93
+ endpoint=Endpoint(id="ep_42", url="https://cliente.example/webhooks"),
94
+ message_id=random_message_id(),
95
+ payload=b'{"type":"pedido.creado"}',
96
+ )
97
+ )
98
+ ```
99
+
100
+ ## Módulos y extras
101
+
102
+ | Módulo | Qué trae | Extra |
103
+ |---|---|---|
104
+ | `omniwebhook` | Recepción, emisión, esquemas, almacén en memoria y transporte de la biblioteca estándar | Ninguno |
105
+ | `omniwebhook.standard` | El formato Standard Webhooks: verificar y firmar | `omniwebhook[standard]` |
106
+ | `omniwebhook.postgres` | El almacén de reservas sobre PostgreSQL | `omniwebhook[postgres]`, para el pool de psycopg |
107
+ | `omniwebhook.firestore` | El almacén de reservas sobre Firestore | `omniwebhook[firestore]` |
108
+ | `omniwebhook.starlette` | Ayudas para Starlette y FastAPI | `omniwebhook[starlette]` |
109
+ | `omniwebhook.httpx` | Un transporte asincrónico sobre httpx | `omniwebhook[httpx]` |
110
+
111
+ `omniwebhook.standard` usa por defecto la librería de referencia del formato. Con
112
+ `signer=native_signer` firma con la biblioteca estándar y no hace falta el extra:
113
+
114
+ ```python
115
+ from omniwebhook.standard import native_signer, standard_scheme
116
+
117
+ standard_scheme(secrets=[secreto], signer=native_signer)
118
+ ```
119
+
120
+ ## Documentación
121
+
122
+ - [Guía para recibir](https://github.com/PabloAlaniz/omniwebhook/blob/main/docs/recibir.md)
123
+ - [Guía para emitir](https://github.com/PabloAlaniz/omniwebhook/blob/main/docs/emitir.md)
124
+ - [Especificación](https://github.com/PabloAlaniz/omniwebhook/blob/main/spec/SPEC.md)
125
+ - [Repositorio](https://github.com/PabloAlaniz/omniwebhook#readme)
126
+
127
+ ## Licencia
128
+
129
+ MIT
@@ -0,0 +1,95 @@
1
+ # omniwebhook
2
+
3
+ Webhooks firmados que se emiten y se reciben igual en cualquier stack: verificación, frescura,
4
+ idempotencia y reintentos con las mismas reglas en Python y en TypeScript.
5
+
6
+ - **Recibir**: verifica la firma, rechaza lo viejo y lo ambiguo, y procesa cada evento una sola
7
+ vez. Devuelve un resultado tipado en vez de lanzar.
8
+ - **Emitir**: firma con [Standard Webhooks](https://www.standardwebhooks.com/), no entrega a
9
+ direcciones internas y dice cuándo reintentar.
10
+ - **Sincrónico y asincrónico**, con tipos completos y sin dependencias obligatorias. Python 3.11 o
11
+ superior.
12
+
13
+ ```bash
14
+ pip install omniwebhook
15
+ ```
16
+
17
+ ## Recibir
18
+
19
+ ```python
20
+ import json
21
+ import os
22
+
23
+ from omniwebhook import VerifiedEvent, create_async_receiver, stripe_scheme
24
+ from omniwebhook.postgres import AsyncPostgresIdempotencyStore, AsyncPsycopgClient
25
+ from omniwebhook.starlette import to_incoming_request, to_response
26
+
27
+ receive = create_async_receiver(
28
+ verifier=stripe_scheme(secrets=[os.environ.get("STRIPE_WEBHOOK_SECRET", "")]),
29
+ store=AsyncPostgresIdempotencyStore(AsyncPsycopgClient(pool.connection)),
30
+ )
31
+
32
+
33
+ @app.post("/webhooks/stripe")
34
+ async def stripe_webhook(request: Request) -> Response:
35
+ async def procesar(event: VerifiedEvent) -> None:
36
+ await registrar_pago(json.loads(event.request.body))
37
+
38
+ return to_response(await receive.execute(await to_incoming_request(request), procesar))
39
+ ```
40
+
41
+ Esquemas incluidos: `stripe_scheme`, `mercadopago_scheme`, `github_scheme`, `creem_scheme`,
42
+ `hmac_body_scheme` y, en `omniwebhook.standard`, `standard_scheme`.
43
+
44
+ ## Emitir
45
+
46
+ ```python
47
+ import os
48
+
49
+ from omniwebhook import Delivery, Endpoint, MemoryDeliveryLedger, create_sender, random_message_id
50
+ from omniwebhook.standard import standard_signer
51
+
52
+ send = create_sender(
53
+ signer=standard_signer(secrets=[os.environ.get("WEBHOOK_SIGNING_SECRET", "")]),
54
+ ledger=MemoryDeliveryLedger(),
55
+ )
56
+
57
+ attempt = send.execute(
58
+ Delivery(
59
+ endpoint=Endpoint(id="ep_42", url="https://cliente.example/webhooks"),
60
+ message_id=random_message_id(),
61
+ payload=b'{"type":"pedido.creado"}',
62
+ )
63
+ )
64
+ ```
65
+
66
+ ## Módulos y extras
67
+
68
+ | Módulo | Qué trae | Extra |
69
+ |---|---|---|
70
+ | `omniwebhook` | Recepción, emisión, esquemas, almacén en memoria y transporte de la biblioteca estándar | Ninguno |
71
+ | `omniwebhook.standard` | El formato Standard Webhooks: verificar y firmar | `omniwebhook[standard]` |
72
+ | `omniwebhook.postgres` | El almacén de reservas sobre PostgreSQL | `omniwebhook[postgres]`, para el pool de psycopg |
73
+ | `omniwebhook.firestore` | El almacén de reservas sobre Firestore | `omniwebhook[firestore]` |
74
+ | `omniwebhook.starlette` | Ayudas para Starlette y FastAPI | `omniwebhook[starlette]` |
75
+ | `omniwebhook.httpx` | Un transporte asincrónico sobre httpx | `omniwebhook[httpx]` |
76
+
77
+ `omniwebhook.standard` usa por defecto la librería de referencia del formato. Con
78
+ `signer=native_signer` firma con la biblioteca estándar y no hace falta el extra:
79
+
80
+ ```python
81
+ from omniwebhook.standard import native_signer, standard_scheme
82
+
83
+ standard_scheme(secrets=[secreto], signer=native_signer)
84
+ ```
85
+
86
+ ## Documentación
87
+
88
+ - [Guía para recibir](https://github.com/PabloAlaniz/omniwebhook/blob/main/docs/recibir.md)
89
+ - [Guía para emitir](https://github.com/PabloAlaniz/omniwebhook/blob/main/docs/emitir.md)
90
+ - [Especificación](https://github.com/PabloAlaniz/omniwebhook/blob/main/spec/SPEC.md)
91
+ - [Repositorio](https://github.com/PabloAlaniz/omniwebhook#readme)
92
+
93
+ ## Licencia
94
+
95
+ MIT
@@ -0,0 +1,183 @@
1
+ """Agente de interoperabilidad del paquete de Python.
2
+
3
+ Lee un pedido JSON por línea de la entrada estándar y responde un JSON por línea. Se corre
4
+ con el entorno del paquete: `uv run --project python python python/interop/agent.py`.
5
+ """
6
+
7
+ import base64
8
+ import json
9
+ import sys
10
+ from typing import Any
11
+ from urllib.parse import urlsplit
12
+
13
+ from psycopg_pool import ConnectionPool
14
+ from standardwebhooks import Webhook
15
+
16
+ from omniwebhook import (
17
+ AttemptOutcome,
18
+ ClaimRequest,
19
+ CompleteRequest,
20
+ IncomingRequest,
21
+ OutgoingMessage,
22
+ ReleaseRequest,
23
+ RetryPolicy,
24
+ Signed,
25
+ Verified,
26
+ Verifier,
27
+ classify_delivery,
28
+ creem_scheme,
29
+ evaluate_destination,
30
+ github_scheme,
31
+ hmac_body_scheme,
32
+ http_status_for,
33
+ inspect_destination,
34
+ is_blocked_address,
35
+ mercadopago_scheme,
36
+ next_attempt,
37
+ stripe_scheme,
38
+ )
39
+ from omniwebhook.postgres import PostgresIdempotencyStore, PsycopgClient, postgres_store_schema
40
+ from omniwebhook.standard import standard_scheme, standard_signer
41
+
42
+ Json = dict[str, Any]
43
+
44
+
45
+ class Clock:
46
+ def __init__(self, now: int) -> None:
47
+ self._now = now
48
+
49
+ def now(self) -> int:
50
+ return self._now
51
+
52
+
53
+ def verifier(scheme: str, secrets: list[str], now: int, options: Json) -> Verifier:
54
+ timed: Json = {"secrets": secrets, "clock": Clock(now)}
55
+ if "tolerance_seconds" in options:
56
+ timed["tolerance_seconds"] = options["tolerance_seconds"]
57
+ if scheme == "standard":
58
+ return standard_scheme(**timed)
59
+ if scheme == "stripe":
60
+ return stripe_scheme(**timed)
61
+ if scheme == "mercadopago":
62
+ return mercadopago_scheme(**timed)
63
+ if scheme == "github":
64
+ return github_scheme(secrets=secrets)
65
+ if scheme == "creem":
66
+ return creem_scheme(secrets=secrets)
67
+ if scheme == "hmac-body":
68
+ return hmac_body_scheme(secrets=secrets, **options)
69
+ raise ValueError(f"esquema desconocido: {scheme}")
70
+
71
+
72
+ class Agent:
73
+ def __init__(self) -> None:
74
+ self._pool: ConnectionPool | None = None
75
+ self._store: PostgresIdempotencyStore | None = None
76
+
77
+ def verify(
78
+ self, scheme: str, secrets: list[str], now: int, request: Json, options: Json | None = None
79
+ ) -> Json:
80
+ incoming = IncomingRequest(
81
+ headers=[(name, value) for name, value in request["headers"]],
82
+ query=[(name, value) for name, value in request["query"]],
83
+ body=base64.b64decode(request["body"]),
84
+ )
85
+ result = verifier(scheme, secrets, now, options or {}).verify(incoming)
86
+ if isinstance(result, Verified):
87
+ return {"outcome": "ok", "event_key": result.event_key, "timestamp": result.timestamp}
88
+ return {"outcome": result.outcome}
89
+
90
+ def sign(self, secrets: list[str], id: str, timestamp: int, payload: str) -> Json:
91
+ message = OutgoingMessage(id=id, timestamp=timestamp, payload=base64.b64decode(payload))
92
+ result = standard_signer(secrets=secrets).sign(message)
93
+ if isinstance(result, Signed):
94
+ return {"outcome": "signed", "headers": dict(result.headers)}
95
+ return {"outcome": result.outcome}
96
+
97
+ def reference_verify(self, secret: str, headers: dict[str, str], body: str) -> Json:
98
+ """Lo que firmó el otro paquete, verificado con la librería de referencia del formato."""
99
+ try:
100
+ Webhook(secret).verify(base64.b64decode(body), headers, json_parse=False)
101
+ except Exception:
102
+ return {"valid": False}
103
+ return {"valid": True}
104
+
105
+ def address(self, address: str) -> Json:
106
+ return {"blocked": is_blocked_address(address)}
107
+
108
+ def url(self, url: str, allow_http: bool, resolved: list[str]) -> Json:
109
+ result = evaluate_destination(url, allow_http=allow_http, resolved=resolved)
110
+ inspected = inspect_destination(url, allow_http=allow_http)
111
+ if isinstance(inspected, str):
112
+ return {"result": result}
113
+ # Lo que entiende el analizador de la plataforma, que es el que usa el transporte.
114
+ platform: Json | None
115
+ try:
116
+ parsed = urlsplit(url)
117
+ platform = {"host": parsed.hostname, "port": parsed.port, "scheme": f"{parsed.scheme}:"}
118
+ except ValueError:
119
+ platform = None
120
+ return {
121
+ "result": result,
122
+ "host": inspected.host,
123
+ "literal": inspected.literal_address,
124
+ "platform": platform,
125
+ }
126
+
127
+ def classify(self, status: int | None, failure: Any) -> Json:
128
+ return {"class": classify_delivery(AttemptOutcome(status=status, failure=failure))}
129
+
130
+ def status(self, outcome: Any) -> Json:
131
+ return {"status": http_status_for(outcome)}
132
+
133
+ def retry(self, attempt: int, now: int, random: float, retry_after: str | None, **policy: Any) -> Json:
134
+ following = next_attempt(
135
+ attempt=attempt, now=now, random=random, retry_after=retry_after, policy=RetryPolicy(**policy)
136
+ )
137
+ if following is None:
138
+ return {"exhausted": True}
139
+ return {"exhausted": False, "delay_seconds": following.delay_seconds, "next_at": following.next_at}
140
+
141
+ def store_open(self, url: str, table: str, create: bool) -> Json:
142
+ self._pool = ConnectionPool(url, min_size=1, max_size=2, open=True)
143
+ if create:
144
+ with self._pool.connection() as connection:
145
+ connection.execute(f"DROP TABLE IF EXISTS {table}")
146
+ connection.execute(postgres_store_schema(table))
147
+ self._store = PostgresIdempotencyStore(PsycopgClient(self._pool.connection), table=table)
148
+ return {"ready": True}
149
+
150
+ def store_step(self, op: str, key: str, token: str, **rest: Any) -> Json:
151
+ assert self._store is not None
152
+ rest.pop("expected", None)
153
+ if op == "claim":
154
+ return {"result": self._store.claim(ClaimRequest(key=key, token=token, **rest))}
155
+ if op == "complete":
156
+ return {"result": self._store.complete(CompleteRequest(key=key, token=token, **rest))}
157
+ return {"result": self._store.release(ReleaseRequest(key=key, token=token))}
158
+
159
+ def store_close(self, table: str, drop: bool) -> Json:
160
+ assert self._pool is not None
161
+ if drop:
162
+ with self._pool.connection() as connection:
163
+ connection.execute(f"DROP TABLE IF EXISTS {table}")
164
+ self._pool.close()
165
+ return {"closed": True}
166
+
167
+
168
+ def main() -> None:
169
+ agent = Agent()
170
+ for line in sys.stdin:
171
+ if not line.strip():
172
+ continue
173
+ try:
174
+ data = json.loads(line)
175
+ reply = getattr(agent, data.pop("command"))(**data)
176
+ except Exception as error:
177
+ reply = {"crashed": repr(error)}
178
+ sys.stdout.write(json.dumps(reply) + "\n")
179
+ sys.stdout.flush()
180
+
181
+
182
+ if __name__ == "__main__":
183
+ main()
@@ -0,0 +1,136 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.25"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "omniwebhook"
7
+ version = "0.1.0"
8
+ description = "Webhooks firmados que se emiten y se reciben igual en cualquier stack: verificación, frescura, idempotencia y reintentos con las mismas reglas."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.11"
13
+ authors = [{ name = "Pablo Alaniz" }]
14
+ keywords = ["webhooks", "webhook", "signature", "hmac", "idempotency", "retries", "standard-webhooks", "mercadopago"]
15
+ classifiers = [
16
+ "Development Status :: 2 - Pre-Alpha",
17
+ "Intended Audience :: Developers",
18
+ "Natural Language :: Spanish",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Programming Language :: Python :: 3.14",
23
+ "Topic :: Internet :: WWW/HTTP",
24
+ "Topic :: Security",
25
+ "Typing :: Typed",
26
+ ]
27
+ dependencies = []
28
+
29
+ [project.optional-dependencies]
30
+ # La librería de referencia del formato Standard Webhooks, para `omniwebhook.standard`.
31
+ standard = ["standardwebhooks>=1.3"]
32
+ # El transporte asincrónico de `omniwebhook.httpx`.
33
+ httpx = ["httpx>=0.27"]
34
+ # Las ayudas de `omniwebhook.starlette`, también para FastAPI.
35
+ starlette = ["starlette>=0.37"]
36
+ # Un cliente con pool para el almacén de `omniwebhook.postgres`.
37
+ postgres = ["psycopg[pool]>=3.2"]
38
+ # El almacén de `omniwebhook.firestore`.
39
+ firestore = ["google-cloud-firestore>=2.16"]
40
+
41
+ [project.urls]
42
+ Homepage = "https://github.com/PabloAlaniz/omniwebhook"
43
+ Repository = "https://github.com/PabloAlaniz/omniwebhook"
44
+ Specification = "https://github.com/PabloAlaniz/omniwebhook/blob/main/spec/SPEC.md"
45
+
46
+ [dependency-groups]
47
+ dev = [
48
+ "google-cloud-firestore>=2.34.1",
49
+ "httpx>=0.28.1",
50
+ "import-linter>=2.17",
51
+ "jsonschema>=4.23",
52
+ "mypy>=1.13",
53
+ "psycopg[binary,pool]>=3.3.9",
54
+ "pytest>=8.3",
55
+ "pytest-asyncio>=1.5.0",
56
+ "pytest-cov>=7.0",
57
+ "ruff>=0.8",
58
+ "standardwebhooks>=1.3.0",
59
+ "starlette>=1.10.0",
60
+ "trustme>=1.2.1",
61
+ ]
62
+
63
+ [tool.hatch.build.targets.wheel]
64
+ packages = ["src/omniwebhook"]
65
+
66
+ [tool.pytest.ini_options]
67
+ testpaths = ["tests"]
68
+ addopts = "--cov --cov-report=term-missing:skip-covered -m 'not integration'"
69
+ asyncio_mode = "auto"
70
+ asyncio_default_fixture_loop_scope = "function"
71
+ filterwarnings = ["error", "ignore:Using `httpx` with `starlette.testclient`"]
72
+ markers = ["integration: necesita un servicio externo (PostgreSQL o el emulador de Firestore)"]
73
+
74
+ [tool.coverage.run]
75
+ source_pkgs = ["omniwebhook"]
76
+ branch = true
77
+ # Estos almacenes se prueban contra el servicio de verdad, en los tests de integración.
78
+ omit = [
79
+ "*/omniwebhook/adapters/stores/postgres.py",
80
+ "*/omniwebhook/adapters/stores/firestore.py",
81
+ "*/omniwebhook/postgres.py",
82
+ "*/omniwebhook/firestore.py",
83
+ ]
84
+
85
+ [tool.coverage.report]
86
+ fail_under = 90
87
+ exclude_also = ["if TYPE_CHECKING:", "@overload", "raise NotImplementedError"]
88
+
89
+ [tool.mypy]
90
+ strict = true
91
+ files = ["src", "tests", "interop"]
92
+
93
+ [tool.ruff]
94
+ line-length = 110
95
+ target-version = "py311"
96
+
97
+ [tool.ruff.lint]
98
+ select = ["E", "F", "W", "I", "B", "UP", "SIM", "RUF", "S", "PT", "C4", "TID"]
99
+ # El texto es español: las tildes y la ñ en docstrings y mensajes son a propósito.
100
+ ignore = ["RUF001", "RUF002", "RUF003"]
101
+
102
+ [tool.ruff.lint.per-file-ignores]
103
+ "tests/**" = ["S101", "S105", "S106"]
104
+ # El generador se comprueba a sí mismo con assert y sólo usa secretos sintéticos.
105
+ "../tools/**" = ["S101", "S104", "S105", "SIM905"]
106
+ "interop/**" = ["S101"]
107
+
108
+ # Reglas de arquitectura. Las dependencias apuntan hacia adentro:
109
+ # entrypoints → adapters → application → domain
110
+ # Ver docs/adr/0001-arquitectura-en-capas.md y docs/adr/0002-formato-de-salida-estandar.md.
111
+ [tool.importlinter]
112
+ root_package = "omniwebhook"
113
+ include_external_packages = true
114
+
115
+ [[tool.importlinter.contracts]]
116
+ name = "Las capas dependen hacia adentro"
117
+ type = "layers"
118
+ layers = [
119
+ "omniwebhook.entrypoints",
120
+ "omniwebhook.adapters",
121
+ "omniwebhook.application",
122
+ "omniwebhook.domain",
123
+ ]
124
+
125
+ [[tool.importlinter.contracts]]
126
+ name = "La librería del formato estándar sólo entra por su adaptador"
127
+ type = "forbidden"
128
+ source_modules = ["omniwebhook"]
129
+ forbidden_modules = ["standardwebhooks"]
130
+ ignore_imports = ["omniwebhook.adapters.schemes.standard.reference_signer -> standardwebhooks"]
131
+
132
+ [[tool.importlinter.contracts]]
133
+ name = "El núcleo no depende de paquetes opcionales"
134
+ type = "forbidden"
135
+ source_modules = ["omniwebhook.domain", "omniwebhook.application"]
136
+ forbidden_modules = ["httpx", "starlette", "psycopg", "google"]