katcloud 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.
@@ -0,0 +1,70 @@
1
+ Metadata-Version: 2.4
2
+ Name: katcloud
3
+ Version: 0.1.0
4
+ Summary: KAT Cloud API Python SDK
5
+ Author: 한국에이아이통신(주)
6
+ License: MIT
7
+ Project-URL: Homepage, https://katcloud.kr
8
+ Project-URL: Documentation, https://katcloud.kr/docs/api
9
+ Project-URL: Repository, https://github.com/katcloud-kr/kat-sdk
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Typing :: Typed
13
+ Requires-Python: >=3.8
14
+ Description-Content-Type: text/markdown
15
+
16
+ # katcloud
17
+
18
+ 한국에이아이통신(주) KAT Cloud API 용 Python SDK 입니다. 표준 라이브러리만 쓰고 Python 3.8 이상에서 동작합니다.
19
+
20
+ KAT Cloud 는 AI 에이전트를 한국 전화망에 연결하는 통신 인프라입니다. 070 번호 발급, 문자, 통화 기록, AI 발신, 웹훅을 API 로 다룹니다.
21
+
22
+ - 문서: https://katcloud.kr/docs/api
23
+ - 콘솔(API 키 발급): https://app.katcloud.kr
24
+
25
+ ## 설치
26
+
27
+ ```bash
28
+ pip install katcloud
29
+ ```
30
+
31
+ ## 사용
32
+
33
+ ```python
34
+ from katcloud import Client, KatError
35
+
36
+ kat = Client(api_key="zpa...") # 또는 환경 변수 KATCLOUD_API_KEY
37
+
38
+ # 번호 발급
39
+ group_id = kat.create_group(group_title="my-agent")
40
+ for group in kat.list_groups():
41
+ print(group["phoneNumber"])
42
+
43
+ # 문자 보내기
44
+ chat_id = kat.send_message("01098765432", "예약이 확정되었습니다.", from_number="07012345678")
45
+
46
+ # AI 발신 (실제 전화가 걸리고 요금이 생길 수 있습니다)
47
+ call = kat.create_ai_outbound_call(group_id, {
48
+ "agentId": 12,
49
+ "callerChannelId": 34,
50
+ "destination": "01098765432",
51
+ "inputs": {},
52
+ })
53
+
54
+ try:
55
+ kat.list_agents(group_id)
56
+ except KatError as e:
57
+ print(e.status, e.code, e.message)
58
+ ```
59
+
60
+ ## 웹훅 서명 검증
61
+
62
+ ```python
63
+ from katcloud import construct_event
64
+
65
+ event = construct_event(raw_body, headers, secret) # 실패하면 WebhookSignatureError
66
+ ```
67
+
68
+ ## 라이선스
69
+
70
+ MIT
@@ -0,0 +1,55 @@
1
+ # katcloud
2
+
3
+ 한국에이아이통신(주) KAT Cloud API 용 Python SDK 입니다. 표준 라이브러리만 쓰고 Python 3.8 이상에서 동작합니다.
4
+
5
+ KAT Cloud 는 AI 에이전트를 한국 전화망에 연결하는 통신 인프라입니다. 070 번호 발급, 문자, 통화 기록, AI 발신, 웹훅을 API 로 다룹니다.
6
+
7
+ - 문서: https://katcloud.kr/docs/api
8
+ - 콘솔(API 키 발급): https://app.katcloud.kr
9
+
10
+ ## 설치
11
+
12
+ ```bash
13
+ pip install katcloud
14
+ ```
15
+
16
+ ## 사용
17
+
18
+ ```python
19
+ from katcloud import Client, KatError
20
+
21
+ kat = Client(api_key="zpa...") # 또는 환경 변수 KATCLOUD_API_KEY
22
+
23
+ # 번호 발급
24
+ group_id = kat.create_group(group_title="my-agent")
25
+ for group in kat.list_groups():
26
+ print(group["phoneNumber"])
27
+
28
+ # 문자 보내기
29
+ chat_id = kat.send_message("01098765432", "예약이 확정되었습니다.", from_number="07012345678")
30
+
31
+ # AI 발신 (실제 전화가 걸리고 요금이 생길 수 있습니다)
32
+ call = kat.create_ai_outbound_call(group_id, {
33
+ "agentId": 12,
34
+ "callerChannelId": 34,
35
+ "destination": "01098765432",
36
+ "inputs": {},
37
+ })
38
+
39
+ try:
40
+ kat.list_agents(group_id)
41
+ except KatError as e:
42
+ print(e.status, e.code, e.message)
43
+ ```
44
+
45
+ ## 웹훅 서명 검증
46
+
47
+ ```python
48
+ from katcloud import construct_event
49
+
50
+ event = construct_event(raw_body, headers, secret) # 실패하면 WebhookSignatureError
51
+ ```
52
+
53
+ ## 라이선스
54
+
55
+ MIT
@@ -0,0 +1,29 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "katcloud"
7
+ version = "0.1.0"
8
+ description = "KAT Cloud API Python SDK"
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ requires-python = ">=3.8"
12
+ dependencies = []
13
+ authors = [{ name = "한국에이아이통신(주)" }]
14
+ classifiers = [
15
+ "License :: OSI Approved :: MIT License",
16
+ "Programming Language :: Python :: 3",
17
+ "Typing :: Typed",
18
+ ]
19
+
20
+ [project.urls]
21
+ Homepage = "https://katcloud.kr"
22
+ Documentation = "https://katcloud.kr/docs/api"
23
+ Repository = "https://github.com/katcloud-kr/kat-sdk"
24
+
25
+ [tool.setuptools.packages.find]
26
+ where = ["src"]
27
+
28
+ [tool.setuptools.package-data]
29
+ katcloud = ["py.typed"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,19 @@
1
+ """KAT Cloud (한국에이아이통신) Python SDK. Docs: https://katcloud.kr/docs/api"""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from .client import DEFAULT_BASE_URL, Client, urllib_transport # noqa: E402
6
+ from .errors import KatError, WebhookSignatureError # noqa: E402
7
+ from .webhook import compute_signature, construct_event, verify_signature # noqa: E402
8
+
9
+ __all__ = [
10
+ "Client",
11
+ "DEFAULT_BASE_URL",
12
+ "KatError",
13
+ "WebhookSignatureError",
14
+ "compute_signature",
15
+ "construct_event",
16
+ "urllib_transport",
17
+ "verify_signature",
18
+ "__version__",
19
+ ]
@@ -0,0 +1,387 @@
1
+ """KAT Cloud API client (stdlib only).
2
+
3
+ Endpoints come from https://katcloud.kr/docs/api and the Studio API doc
4
+ (``apps/studio-api/API_DOCUMENTATION.md``). Nothing here is guessed: where the
5
+ docs do not spell out a request body, the method takes a plain ``dict`` and
6
+ passes it through (marked TODO).
7
+ """
8
+
9
+ import json
10
+ import mimetypes
11
+ import os
12
+ import urllib.error
13
+ import urllib.parse
14
+ import urllib.request
15
+ import uuid
16
+ from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Union, cast
17
+
18
+ from . import __version__
19
+ from .errors import KatError
20
+ from .types import (
21
+ Agent,
22
+ AiOutboundCall,
23
+ AuthCheck,
24
+ AvailableNumber,
25
+ CallHistory,
26
+ CallHistoryPage,
27
+ Channel,
28
+ Group,
29
+ MessageSendResult,
30
+ Webhook,
31
+ WebhookSecret,
32
+ WebhookTestResult,
33
+ )
34
+
35
+ DEFAULT_BASE_URL = "https://studio-gateway.zerocall.kr"
36
+
37
+ # (method, url, headers, body, timeout) -> (status, headers, body)
38
+ Transport = Callable[[str, str, Dict[str, str], Optional[bytes], float], Tuple[int, Mapping[str, str], bytes]]
39
+
40
+
41
+ def urllib_transport(
42
+ method: str, url: str, headers: Dict[str, str], body: Optional[bytes], timeout: float
43
+ ) -> Tuple[int, Mapping[str, str], bytes]:
44
+ """Default transport using ``urllib.request``."""
45
+ req = urllib.request.Request(url, data=body, headers=headers, method=method)
46
+ try:
47
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
48
+ return resp.status, dict(resp.headers.items()), resp.read()
49
+ except urllib.error.HTTPError as e:
50
+ return e.code, dict(e.headers.items()) if e.headers else {}, e.read() or b""
51
+ except (urllib.error.URLError, OSError) as e:
52
+ raise KatError(0, "NETWORK_ERROR", f"{method} {url} failed: {e}") from e
53
+
54
+
55
+ def _clean(params: Mapping[str, Any]) -> Dict[str, Any]:
56
+ return {k: v for k, v in params.items() if v is not None}
57
+
58
+
59
+ def _unwrap(body: Any) -> Any:
60
+ """Strip the documented success envelope ``{"code": "0", "message", "result"}``.
61
+
62
+ The docs say examples "may show only result", so some endpoints may answer
63
+ without the envelope; in that case the body is returned as is.
64
+ """
65
+ if isinstance(body, dict) and "result" in body and "code" in body:
66
+ return body["result"]
67
+ return body
68
+
69
+
70
+ class Client:
71
+ """KAT Cloud API client.
72
+
73
+ >>> kat = Client(api_key="zpa.123.secret")
74
+ >>> kat.list_groups()
75
+ """
76
+
77
+ def __init__(
78
+ self,
79
+ api_key: Optional[str] = None,
80
+ base_url: Optional[str] = None,
81
+ timeout: float = 30.0,
82
+ transport: Optional[Transport] = None,
83
+ ) -> None:
84
+ api_key = api_key or os.environ.get("KATCLOUD_API_KEY")
85
+ if not api_key:
86
+ raise ValueError("api_key is required (or set KATCLOUD_API_KEY)")
87
+ self.api_key = api_key
88
+ self.base_url = (base_url or os.environ.get("KATCLOUD_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
89
+ self.timeout = timeout
90
+ self._transport: Transport = transport or urllib_transport
91
+
92
+ # ------------------------------------------------------------------ core
93
+
94
+ def request(
95
+ self,
96
+ method: str,
97
+ path: str,
98
+ query: Optional[Mapping[str, Any]] = None,
99
+ body: Any = None,
100
+ headers: Optional[Mapping[str, str]] = None,
101
+ raw_body: Optional[bytes] = None,
102
+ ) -> Any:
103
+ """Send a request and return the parsed (unwrapped) JSON, or None for 204.
104
+
105
+ Use this for documented endpoints that have no dedicated method yet
106
+ (chat rooms, agent manuals/tools, payments, ...).
107
+ """
108
+ url = self.base_url + path
109
+ if query:
110
+ q = {k: ("true" if v is True else "false" if v is False else v) for k, v in _clean(query).items()}
111
+ if q:
112
+ url += "?" + urllib.parse.urlencode(q)
113
+ h = {
114
+ "x-api-key": self.api_key,
115
+ "Accept": "application/json",
116
+ "User-Agent": f"katcloud-python/{__version__}",
117
+ }
118
+ data: Optional[bytes] = raw_body
119
+ if body is not None and raw_body is None:
120
+ data = json.dumps(body, ensure_ascii=False).encode("utf-8")
121
+ h["Content-Type"] = "application/json"
122
+ if headers:
123
+ h.update(headers)
124
+
125
+ status, _resp_headers, content = self._transport(method, url, h, data, self.timeout)
126
+ parsed: Any = None
127
+ if content:
128
+ text = content.decode("utf-8", errors="replace")
129
+ try:
130
+ parsed = json.loads(text)
131
+ except ValueError:
132
+ parsed = text
133
+ if status < 200 or status >= 300:
134
+ raise KatError.from_response(status, parsed)
135
+ return _unwrap(parsed)
136
+
137
+ @staticmethod
138
+ def _seg(value: Union[int, str]) -> str:
139
+ return urllib.parse.quote(str(value), safe="")
140
+
141
+ # ------------------------------------------------------------------ auth
142
+
143
+ def auth_check(self) -> AuthCheck:
144
+ """``GET /auth-check``: validate the API key and list its groups."""
145
+ return cast(AuthCheck, self.request("GET", "/auth-check"))
146
+
147
+ # ------------------------------------------------------------- groups / numbers
148
+
149
+ def list_groups(self) -> List[Group]:
150
+ """``GET /group``: groups (each with its phone number) this key can access."""
151
+ return cast(List[Group], self.request("GET", "/group"))
152
+
153
+ def create_group(
154
+ self,
155
+ group_title: Optional[str] = None,
156
+ phone_number: Optional[str] = None,
157
+ plan: Optional[str] = None,
158
+ ) -> Any:
159
+ """``POST /group``: create a group and issue a phone number.
160
+
161
+ ``plan`` is one of ECHO, BASIC (default), BUSINESS, PRO.
162
+ Returns the new group id as a bare number (``123``), as the server does
163
+ (studio-api ``group.controller.ts`` ``issue(): Promise<number>``).
164
+ 403 ``GR047`` means the key owner has not completed identity verification.
165
+ """
166
+ body = _clean({"groupTitle": group_title, "phoneNumber": phone_number, "plan": plan})
167
+ return self.request("POST", "/group", body=body)
168
+
169
+ def delete_group(self, group_id: int) -> None:
170
+ """``DELETE /group/{groupId}``: delete the group and release its number."""
171
+ self.request("DELETE", f"/group/{self._seg(group_id)}")
172
+
173
+ def check_available_number(self) -> AvailableNumber:
174
+ """``GET /phone-number-pool/available``."""
175
+ return cast(AvailableNumber, self.request("GET", "/phone-number-pool/available"))
176
+
177
+ def list_channels(self, group_id: int) -> List[Channel]:
178
+ """``GET /group/{groupId}/channel``: the group's phone numbers (primary first).
179
+
180
+ Documented under AI agents; may require the AI agent feature (403 AG002).
181
+ """
182
+ return cast(List[Channel], self.request("GET", f"/group/{self._seg(group_id)}/channel"))
183
+
184
+ # ------------------------------------------------------------- messages
185
+
186
+ def send_message(
187
+ self,
188
+ to: str,
189
+ content: str,
190
+ from_number: str,
191
+ subject: Optional[str] = None,
192
+ image_list: Optional[Sequence[str]] = None,
193
+ ) -> Any:
194
+ """``POST /message/send``: SMS/LMS/MMS (type decided by the server).
195
+
196
+ ``from_number`` is required per the KAT doc (400 if missing).
197
+ Returns the 32-char ``chatId`` as a bare string, as the server does
198
+ (studio-api ``message.controller.ts`` returns ``chat.id``).
199
+ Note: KAT doc marks this API "Deprecated" in favour of the chat API.
200
+ """
201
+ body = _clean(
202
+ {
203
+ "toPhoneNumber": to,
204
+ "content": content,
205
+ "fromPhoneNumber": from_number,
206
+ "subject": subject,
207
+ "imageList": list(image_list) if image_list else None,
208
+ }
209
+ )
210
+ return self.request("POST", "/message/send", body=body)
211
+
212
+ def get_message_result(self, chat_id: str) -> MessageSendResult:
213
+ """``GET /message/send-result/{chatId}``."""
214
+ return cast(MessageSendResult, self.request("GET", f"/message/send-result/{self._seg(chat_id)}"))
215
+
216
+ def upload_media(self, paths: Sequence[str]) -> Any:
217
+ """``POST /message/media/upload`` (multipart, field ``files``, up to 3).
218
+
219
+ Returns ``{"urls": [...]}``; pass the urls as ``image_list`` to send MMS.
220
+ """
221
+ if not 1 <= len(paths) <= 3:
222
+ raise ValueError("upload 1 to 3 files")
223
+ boundary = "----katcloud" + uuid.uuid4().hex
224
+ parts: List[bytes] = []
225
+ for p in paths:
226
+ name = os.path.basename(p)
227
+ ctype = mimetypes.guess_type(name)[0] or "application/octet-stream"
228
+ with open(p, "rb") as f:
229
+ content = f.read()
230
+ parts.append(
231
+ (
232
+ f"--{boundary}\r\n"
233
+ f'Content-Disposition: form-data; name="files"; filename="{name}"\r\n'
234
+ f"Content-Type: {ctype}\r\n\r\n"
235
+ ).encode("utf-8")
236
+ + content
237
+ + b"\r\n"
238
+ )
239
+ parts.append(f"--{boundary}--\r\n".encode("utf-8"))
240
+ return self.request(
241
+ "POST",
242
+ "/message/media/upload",
243
+ raw_body=b"".join(parts),
244
+ headers={"Content-Type": f"multipart/form-data; boundary={boundary}"},
245
+ )
246
+
247
+ # ------------------------------------------------------------- call history
248
+
249
+ def list_call_history(
250
+ self,
251
+ group_id: int,
252
+ channel_id: Optional[int] = None,
253
+ phone_number: Optional[str] = None,
254
+ keyword: Optional[str] = None,
255
+ updated_after: Optional[str] = None,
256
+ offset: Optional[int] = None,
257
+ limit: Optional[int] = None,
258
+ ) -> CallHistoryPage:
259
+ """``GET /call-history``. ``limit`` max 100.
260
+
261
+ For polling, pass ``updated_after`` (ISO 8601) and feed the last item's
262
+ ``updatedAt`` back in; do not combine with ``offset``.
263
+ """
264
+ q = {
265
+ "groupId": group_id,
266
+ "channelId": channel_id,
267
+ "phoneNumber": phone_number,
268
+ "keyword": keyword,
269
+ "updatedAfter": updated_after,
270
+ "offset": offset,
271
+ "limit": limit,
272
+ }
273
+ return cast(CallHistoryPage, self.request("GET", "/call-history", query=q))
274
+
275
+ def get_call_history(self, call_history_id: str, group_id: int) -> CallHistory:
276
+ """``GET /call-history/{callHistoryId}?groupId=``."""
277
+ return cast(
278
+ CallHistory,
279
+ self.request("GET", f"/call-history/{self._seg(call_history_id)}", query={"groupId": group_id}),
280
+ )
281
+
282
+ # ------------------------------------------------------------- agents
283
+
284
+ def list_agents(
285
+ self, group_id: int, direction: Optional[str] = None, status: Optional[str] = None
286
+ ) -> List[Agent]:
287
+ """``GET /group/{groupId}/agent?direction=&status=``.
288
+
289
+ ``direction``: INBOUND | OUTBOUND, ``status``: ACTIVE | DISABLED.
290
+ """
291
+ return cast(
292
+ List[Agent],
293
+ self.request(
294
+ "GET", f"/group/{self._seg(group_id)}/agent", query={"direction": direction, "status": status}
295
+ ),
296
+ )
297
+
298
+ def get_agent(self, group_id: int, agent_id: int) -> Agent:
299
+ """``GET /group/{groupId}/agent/{agentId}``."""
300
+ return cast(Agent, self.request("GET", f"/group/{self._seg(group_id)}/agent/{self._seg(agent_id)}"))
301
+
302
+ # ------------------------------------------------------------- AI outbound
303
+
304
+ def create_ai_outbound_call(
305
+ self, group_id: int, body: Mapping[str, Any], idempotency_key: Optional[str] = None
306
+ ) -> Any:
307
+ """``POST /group/{groupId}/ai-outbound/calls`` with ``Idempotency-Key``.
308
+
309
+ Places a real phone call (may be billed). Returns ``requestId`` and the
310
+ accepted status; results arrive via ``get_ai_outbound_call`` or the
311
+ ``AI_OUTBOUND`` webhook. Reuse the same ``idempotency_key`` on retry
312
+ (a random UUID is generated if omitted).
313
+
314
+ ``body`` fields (server ``CreateAiOutboundCallRequest``): ``agentId`` (int),
315
+ ``callerChannelId`` (int), ``destination`` (str), ``inputs`` (dict, ``{}`` when
316
+ the agent has no input fields), optional ``timeLimit``, ``queueWhenBusy``,
317
+ ``queueTimeout``, ``record``. ``body`` is passed through unchanged.
318
+ """
319
+ key = idempotency_key or str(uuid.uuid4())
320
+ return self.request(
321
+ "POST",
322
+ f"/group/{self._seg(group_id)}/ai-outbound/calls",
323
+ body=dict(body),
324
+ headers={"Idempotency-Key": key},
325
+ )
326
+
327
+ def get_ai_outbound_call(self, group_id: int, request_id: str) -> AiOutboundCall:
328
+ """``GET /group/{groupId}/ai-outbound/calls/{requestId}``: call/analysis/settlement status."""
329
+ return cast(
330
+ AiOutboundCall,
331
+ self.request("GET", f"/group/{self._seg(group_id)}/ai-outbound/calls/{self._seg(request_id)}"),
332
+ )
333
+
334
+ def list_ai_outbound_calls(
335
+ self, group_id: int, cursor: Optional[str] = None, limit: Optional[int] = None
336
+ ) -> Any:
337
+ """``GET /group/{groupId}/ai-outbound/calls?cursor=&limit=``.
338
+
339
+ TODO: response shape (items / next cursor key) is not documented; raw JSON is returned.
340
+ """
341
+ return self.request(
342
+ "GET", f"/group/{self._seg(group_id)}/ai-outbound/calls", query={"cursor": cursor, "limit": limit}
343
+ )
344
+
345
+ def terminate_ai_outbound_call(
346
+ self, group_id: int, request_id: str, body: Optional[Mapping[str, Any]] = None
347
+ ) -> Any:
348
+ """``POST /group/{groupId}/ai-outbound/calls/{requestId}/termination``.
349
+
350
+ Cancels a call not yet placed, or asks to end one in progress.
351
+ TODO: request body (e.g. a reason) is not documented; ``body`` is passed through.
352
+ """
353
+ return self.request(
354
+ "POST",
355
+ f"/group/{self._seg(group_id)}/ai-outbound/calls/{self._seg(request_id)}/termination",
356
+ body=dict(body) if body is not None else {},
357
+ )
358
+
359
+ # ------------------------------------------------------------- webhooks
360
+
361
+ def list_webhooks(self) -> List[Webhook]:
362
+ """``GET /webhook``."""
363
+ return cast(List[Webhook], self.request("GET", "/webhook"))
364
+
365
+ def create_webhook(self, event_type: str, url: str) -> Webhook:
366
+ """``POST /webhook``: one URL per event type per account."""
367
+ return cast(Webhook, self.request("POST", "/webhook", body={"eventType": event_type, "url": url}))
368
+
369
+ def update_webhook(self, webhook_id: int, url: str) -> Any:
370
+ """``PATCH /webhook/{webhookId}``."""
371
+ return self.request("PATCH", f"/webhook/{self._seg(webhook_id)}", body={"url": url})
372
+
373
+ def delete_webhook(self, webhook_id: int) -> None:
374
+ """``DELETE /webhook/{webhookId}``."""
375
+ self.request("DELETE", f"/webhook/{self._seg(webhook_id)}")
376
+
377
+ def test_webhook(self, webhook_id: int) -> WebhookTestResult:
378
+ """``POST /webhook/{webhookId}/test``: sends a signed payload with ``isTest: true``."""
379
+ return cast(WebhookTestResult, self.request("POST", f"/webhook/{self._seg(webhook_id)}/test"))
380
+
381
+ def get_webhook_secret(self) -> WebhookSecret:
382
+ """``GET /webhook/secret`` (created on first call)."""
383
+ return cast(WebhookSecret, self.request("GET", "/webhook/secret"))
384
+
385
+ def rotate_webhook_secret(self) -> WebhookSecret:
386
+ """``POST /webhook/secret/rotate``: later deliveries are signed with the new secret."""
387
+ return cast(WebhookSecret, self.request("POST", "/webhook/secret/rotate"))
@@ -0,0 +1,54 @@
1
+ """KAT Cloud error types."""
2
+
3
+ from typing import Any, List, Optional
4
+
5
+
6
+ class KatError(Exception):
7
+ """An API error.
8
+
9
+ The KAT Cloud docs describe the error body as
10
+ ``{"status": 401, "code": "AU002", "message": "...", "errors": [...]}``.
11
+ The older Studio API doc shows ``{"statusCode", "message", "error"}``; both
12
+ shapes are accepted here.
13
+
14
+ ``status`` is the HTTP status (0 for network failures), ``code`` the KAT
15
+ error code such as ``AU017`` or ``AG011`` (may be None), ``message`` the
16
+ human-readable text, ``errors`` the optional per-field reasons and ``body``
17
+ the parsed response body (or raw text) for debugging.
18
+ """
19
+
20
+ def __init__(
21
+ self,
22
+ status: int,
23
+ code: Optional[str],
24
+ message: str,
25
+ errors: Optional[List[Any]] = None,
26
+ body: Any = None,
27
+ ) -> None:
28
+ super().__init__(f"[{status}{' ' + code if code else ''}] {message}")
29
+ self.status = status
30
+ self.code = code
31
+ self.message = message
32
+ self.errors = errors or []
33
+ self.body = body
34
+
35
+ @classmethod
36
+ def from_response(cls, http_status: int, body: Any) -> "KatError":
37
+ if isinstance(body, dict):
38
+ status = body.get("status") or body.get("statusCode") or http_status
39
+ try:
40
+ status = int(status)
41
+ except (TypeError, ValueError):
42
+ status = http_status
43
+ code = body.get("code")
44
+ message = body.get("message") or body.get("error") or "Request failed"
45
+ if isinstance(message, list): # validation pipes sometimes return a list
46
+ message = "; ".join(str(m) for m in message)
47
+ errors = body.get("errors") if isinstance(body.get("errors"), list) else None
48
+ return cls(status, str(code) if code is not None else None, str(message), errors, body)
49
+ text = body if isinstance(body, str) and body else f"HTTP {http_status}"
50
+ return cls(http_status, None, text, None, body)
51
+
52
+
53
+ class WebhookSignatureError(Exception):
54
+ """Raised by :func:`katcloud.webhook.construct_event` when verification fails."""
File without changes
@@ -0,0 +1,169 @@
1
+ """Response shapes, taken from the examples in the KAT Cloud / Studio API docs.
2
+
3
+ All TypedDicts are ``total=False``: the docs show examples, not guarantees, so
4
+ any field may be missing. Unknown fields are passed through untouched.
5
+ """
6
+
7
+ from typing import Any, Dict, List, Literal, Optional, TypedDict
8
+
9
+
10
+ class AuthCheck(TypedDict, total=False):
11
+ apiKeyId: int
12
+ userId: int
13
+ name: str
14
+ groupIdList: List[int]
15
+
16
+
17
+ class Group(TypedDict, total=False):
18
+ id: int
19
+ title: str
20
+ phoneNumber: str
21
+ channelId: int
22
+ status: str # ACTIVE | INACTIVE | PENDING
23
+ recordingEnabled: bool
24
+ createdAt: str
25
+
26
+
27
+ class AvailableNumber(TypedDict, total=False):
28
+ isAvailable: bool
29
+ phoneNumber: str
30
+
31
+
32
+ class Channel(TypedDict, total=False):
33
+ id: int
34
+ phoneNumber: str
35
+ displayName: str
36
+ isPrimary: bool
37
+
38
+
39
+ class MessageSendResult(TypedDict, total=False):
40
+ """``GET /message/send-result/{chatId}``."""
41
+
42
+ id: str
43
+ content: str
44
+ subject: str
45
+ imageList: List[str]
46
+ externalMessageId: str
47
+ fromPhoneNumber: str
48
+ toPhoneNumber: str
49
+ sendStatus: str # SUCCESS | FAILED
50
+ chatType: str # SMS | LMS | MMS | RCS | KAKAO
51
+ resultStatus: str # success when 4100, 6600 or 7000
52
+ resultMessage: str
53
+ createdAt: str
54
+
55
+
56
+ class SttLine(TypedDict, total=False):
57
+ role: str
58
+ text: str
59
+ timestamp: float
60
+
61
+
62
+ class RecordingFile(TypedDict, total=False):
63
+ url: str
64
+ expiresAt: str
65
+ contentLength: int
66
+ contentType: str
67
+
68
+
69
+ class CallHistory(TypedDict, total=False):
70
+ callHistoryId: str
71
+ fromNumber: str
72
+ toNumber: str
73
+ isInbound: bool
74
+ status: str # ANSWERED | MISSED | REJECTED | UNKNOWN
75
+ tag: str # AI | DIRECT | AI_TO_DIRECT | UNKNOWN
76
+ duration: int
77
+ summary: str
78
+ sttAI: List[SttLine]
79
+ sttDirect: List[SttLine]
80
+ recordingAI: RecordingFile
81
+ recordingDirect: RecordingFile
82
+ isRecorded: bool
83
+ channelId: int
84
+ groupId: int
85
+ createdAt: str
86
+ updatedAt: str
87
+
88
+
89
+ class CallHistoryPage(TypedDict, total=False):
90
+ data: List[CallHistory]
91
+ total: int
92
+ offset: int
93
+ limit: int
94
+
95
+
96
+ class Agent(TypedDict, total=False):
97
+ id: int
98
+ groupId: int
99
+ name: str
100
+ direction: str # INBOUND | OUTBOUND
101
+ prompt: str
102
+ status: str # ACTIVE | DISABLED
103
+ context: Optional[str]
104
+ greeting: Optional[str]
105
+ voice: Optional[str]
106
+ language: Optional[str]
107
+ liveModel: Optional[str]
108
+ maxCallSeconds: Optional[int]
109
+ aiInterruptionEnabled: Optional[bool]
110
+ version: int
111
+ createdAt: str
112
+ updatedAt: str
113
+
114
+
115
+ class AiOutboundCall(TypedDict, total=False):
116
+ """AI outbound call status.
117
+
118
+ TODO: the REST response of ``GET /group/{groupId}/ai-outbound/calls/{requestId}``
119
+ is not documented field-by-field. These keys come from the ``AI_OUTBOUND``
120
+ webhook payload and may differ from the REST response.
121
+ """
122
+
123
+ requestId: str
124
+ callHistoryId: str
125
+ status: str # COMPLETED | NO_ANSWER | BUSY | REJECTED | CANCELED | FAILED
126
+ endReason: str
127
+ answered: bool
128
+ answeredAt: str
129
+ endedAt: str
130
+ durationSeconds: int
131
+ analysisStatus: str # NOT_APPLICABLE | PENDING | READY | PARTIAL | FAILED
132
+ settlementStatus: str # PENDING | SETTLED | WAIVED
133
+
134
+
135
+ class Webhook(TypedDict, total=False):
136
+ id: int
137
+ eventType: str
138
+ url: str
139
+ createdAt: str
140
+ updatedAt: str
141
+
142
+
143
+ class WebhookTestResult(TypedDict, total=False):
144
+ success: bool
145
+ statusCode: int
146
+ responseTime: int
147
+ error: Optional[str]
148
+
149
+
150
+ class WebhookSecret(TypedDict, total=False):
151
+ secret: str
152
+
153
+
154
+ WebhookEventType = Literal[
155
+ "MESSAGE_RECEIVED",
156
+ "SEND_RESULT",
157
+ "CALL_RECEIVED",
158
+ "CALL_COMPLETED",
159
+ "INTAKE",
160
+ "AI_OUTBOUND",
161
+ ]
162
+
163
+
164
+ class WebhookEvent(TypedDict, total=False):
165
+ eventId: str
166
+ eventType: str
167
+ timestamp: str
168
+ data: Dict[str, Any]
169
+ isTest: bool
@@ -0,0 +1,108 @@
1
+ """Webhook signature verification.
2
+
3
+ Per the KAT Cloud docs every webhook carries two headers:
4
+
5
+ * ``X-Webhook-Timestamp``: send time in unix seconds
6
+ * ``X-Webhook-Signature``: ``"v1=" + hex(HMAC-SHA256(secret, "<timestamp>.<raw body>"))``
7
+
8
+ The secret is the full ``whsec_...`` string (including the prefix), from
9
+ ``GET /webhook/secret``. Verify against the raw bytes, never re-serialised JSON,
10
+ compare in constant time and reject timestamps more than 5 minutes off.
11
+ """
12
+
13
+ import hashlib
14
+ import hmac
15
+ import json
16
+ import time
17
+ from typing import Any, Dict, Iterable, Optional, Union
18
+
19
+ from .errors import WebhookSignatureError
20
+
21
+ TIMESTAMP_HEADER = "X-Webhook-Timestamp"
22
+ SIGNATURE_HEADER = "X-Webhook-Signature"
23
+ DEFAULT_TOLERANCE_SECONDS = 300
24
+
25
+ SecretArg = Union[str, Iterable[str]]
26
+
27
+
28
+ def compute_signature(secret: str, timestamp: Union[str, int], raw_body: bytes) -> str:
29
+ """Return the ``v1=<hex>`` signature KAT Cloud would send for this body."""
30
+ if isinstance(raw_body, str):
31
+ raw_body = raw_body.encode("utf-8")
32
+ digest = hmac.new(
33
+ secret.encode("utf-8"),
34
+ str(timestamp).encode("utf-8") + b"." + raw_body,
35
+ hashlib.sha256,
36
+ ).hexdigest()
37
+ return "v1=" + digest
38
+
39
+
40
+ def verify_signature(
41
+ raw_body: bytes,
42
+ timestamp: Optional[str],
43
+ signature: Optional[str],
44
+ secret: SecretArg,
45
+ tolerance_seconds: int = DEFAULT_TOLERANCE_SECONDS,
46
+ now: Optional[float] = None,
47
+ ) -> bool:
48
+ """Return True if the signature is valid and the timestamp is fresh.
49
+
50
+ ``secret`` may be a single secret or several (e.g. new and previous while
51
+ rotating with ``POST /webhook/secret/rotate``, as the docs suggest).
52
+ """
53
+ if not timestamp or not signature:
54
+ return False
55
+ try:
56
+ ts = int(str(timestamp).strip())
57
+ except ValueError:
58
+ return False
59
+ current = time.time() if now is None else now
60
+ if abs(current - ts) > tolerance_seconds:
61
+ return False
62
+ secrets = [secret] if isinstance(secret, str) else list(secret)
63
+ sig = signature.strip().encode("utf-8")
64
+ ok = False
65
+ for s in secrets:
66
+ if not s:
67
+ continue
68
+ expected = compute_signature(s, str(timestamp).strip(), raw_body).encode("utf-8")
69
+ # evaluate every secret so timing does not reveal which one matched
70
+ ok = hmac.compare_digest(expected, sig) or ok
71
+ return ok
72
+
73
+
74
+ def _header(headers: Any, name: str) -> Optional[str]:
75
+ if headers is None:
76
+ return None
77
+ value = headers.get(name)
78
+ if value is None and isinstance(headers, dict):
79
+ lower = name.lower()
80
+ for k, v in headers.items():
81
+ if k.lower() == lower:
82
+ return v
83
+ return value
84
+
85
+
86
+ def construct_event(
87
+ raw_body: bytes,
88
+ headers: Any,
89
+ secret: SecretArg,
90
+ tolerance_seconds: int = DEFAULT_TOLERANCE_SECONDS,
91
+ now: Optional[float] = None,
92
+ ) -> Dict[str, Any]:
93
+ """Verify then parse a webhook. Raises :class:`WebhookSignatureError`.
94
+
95
+ ``headers`` is any mapping with ``.get`` (``http.server`` headers, Flask
96
+ ``request.headers``, or a plain dict).
97
+ """
98
+ ok = verify_signature(
99
+ raw_body,
100
+ _header(headers, TIMESTAMP_HEADER),
101
+ _header(headers, SIGNATURE_HEADER),
102
+ secret,
103
+ tolerance_seconds=tolerance_seconds,
104
+ now=now,
105
+ )
106
+ if not ok:
107
+ raise WebhookSignatureError("invalid or expired webhook signature")
108
+ return json.loads(raw_body.decode("utf-8") if isinstance(raw_body, bytes) else raw_body)
@@ -0,0 +1,70 @@
1
+ Metadata-Version: 2.4
2
+ Name: katcloud
3
+ Version: 0.1.0
4
+ Summary: KAT Cloud API Python SDK
5
+ Author: 한국에이아이통신(주)
6
+ License: MIT
7
+ Project-URL: Homepage, https://katcloud.kr
8
+ Project-URL: Documentation, https://katcloud.kr/docs/api
9
+ Project-URL: Repository, https://github.com/katcloud-kr/kat-sdk
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Typing :: Typed
13
+ Requires-Python: >=3.8
14
+ Description-Content-Type: text/markdown
15
+
16
+ # katcloud
17
+
18
+ 한국에이아이통신(주) KAT Cloud API 용 Python SDK 입니다. 표준 라이브러리만 쓰고 Python 3.8 이상에서 동작합니다.
19
+
20
+ KAT Cloud 는 AI 에이전트를 한국 전화망에 연결하는 통신 인프라입니다. 070 번호 발급, 문자, 통화 기록, AI 발신, 웹훅을 API 로 다룹니다.
21
+
22
+ - 문서: https://katcloud.kr/docs/api
23
+ - 콘솔(API 키 발급): https://app.katcloud.kr
24
+
25
+ ## 설치
26
+
27
+ ```bash
28
+ pip install katcloud
29
+ ```
30
+
31
+ ## 사용
32
+
33
+ ```python
34
+ from katcloud import Client, KatError
35
+
36
+ kat = Client(api_key="zpa...") # 또는 환경 변수 KATCLOUD_API_KEY
37
+
38
+ # 번호 발급
39
+ group_id = kat.create_group(group_title="my-agent")
40
+ for group in kat.list_groups():
41
+ print(group["phoneNumber"])
42
+
43
+ # 문자 보내기
44
+ chat_id = kat.send_message("01098765432", "예약이 확정되었습니다.", from_number="07012345678")
45
+
46
+ # AI 발신 (실제 전화가 걸리고 요금이 생길 수 있습니다)
47
+ call = kat.create_ai_outbound_call(group_id, {
48
+ "agentId": 12,
49
+ "callerChannelId": 34,
50
+ "destination": "01098765432",
51
+ "inputs": {},
52
+ })
53
+
54
+ try:
55
+ kat.list_agents(group_id)
56
+ except KatError as e:
57
+ print(e.status, e.code, e.message)
58
+ ```
59
+
60
+ ## 웹훅 서명 검증
61
+
62
+ ```python
63
+ from katcloud import construct_event
64
+
65
+ event = construct_event(raw_body, headers, secret) # 실패하면 WebhookSignatureError
66
+ ```
67
+
68
+ ## 라이선스
69
+
70
+ MIT
@@ -0,0 +1,14 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/katcloud/__init__.py
4
+ src/katcloud/client.py
5
+ src/katcloud/errors.py
6
+ src/katcloud/py.typed
7
+ src/katcloud/types.py
8
+ src/katcloud/webhook.py
9
+ src/katcloud.egg-info/PKG-INFO
10
+ src/katcloud.egg-info/SOURCES.txt
11
+ src/katcloud.egg-info/dependency_links.txt
12
+ src/katcloud.egg-info/top_level.txt
13
+ tests/test_client.py
14
+ tests/test_webhook.py
@@ -0,0 +1 @@
1
+ katcloud
@@ -0,0 +1,171 @@
1
+ import json
2
+ import os
3
+ import sys
4
+ import unittest
5
+ import urllib.parse
6
+
7
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
8
+
9
+ from katcloud import Client, KatError # noqa: E402
10
+
11
+
12
+ class FakeTransport:
13
+ """Records requests and returns queued (status, body) responses. No network."""
14
+
15
+ def __init__(self, *responses):
16
+ self.responses = list(responses)
17
+ self.calls = []
18
+
19
+ def __call__(self, method, url, headers, body, timeout):
20
+ self.calls.append({"method": method, "url": url, "headers": headers, "body": body})
21
+ status, payload = self.responses.pop(0) if self.responses else (200, None)
22
+ if payload is None:
23
+ raw = b""
24
+ elif isinstance(payload, (bytes, str)):
25
+ raw = payload if isinstance(payload, bytes) else payload.encode()
26
+ else:
27
+ raw = json.dumps(payload).encode()
28
+ return status, {}, raw
29
+
30
+ @property
31
+ def last(self):
32
+ return self.calls[-1]
33
+
34
+ def last_json(self):
35
+ return json.loads(self.last["body"].decode())
36
+
37
+ def last_query(self):
38
+ return dict(urllib.parse.parse_qsl(urllib.parse.urlparse(self.last["url"]).query))
39
+
40
+
41
+ def make(*responses):
42
+ t = FakeTransport(*responses)
43
+ return Client(api_key="zpa.1.secret", base_url="https://api.test/", transport=t), t
44
+
45
+
46
+ class ClientTests(unittest.TestCase):
47
+ def test_requires_key(self):
48
+ old = os.environ.pop("KATCLOUD_API_KEY", None)
49
+ try:
50
+ with self.assertRaises(ValueError):
51
+ Client(api_key=None, transport=FakeTransport())
52
+ finally:
53
+ if old is not None:
54
+ os.environ["KATCLOUD_API_KEY"] = old
55
+
56
+ def test_auth_header_and_base_url(self):
57
+ kat, t = make((200, {"apiKeyId": 1, "groupIdList": [1]}))
58
+ self.assertEqual(kat.auth_check()["groupIdList"], [1])
59
+ self.assertEqual(t.last["url"], "https://api.test/auth-check")
60
+ self.assertEqual(t.last["headers"]["x-api-key"], "zpa.1.secret")
61
+ self.assertEqual(t.last["method"], "GET")
62
+
63
+ def test_unwraps_success_envelope(self):
64
+ kat, _ = make((200, {"code": "0", "message": "Success", "result": [{"id": 1}]}))
65
+ self.assertEqual(kat.list_groups(), [{"id": 1}])
66
+
67
+ def test_plain_body_is_returned_as_is(self):
68
+ kat, _ = make((200, [{"id": 2, "title": "매장A"}]))
69
+ self.assertEqual(kat.list_groups()[0]["title"], "매장A")
70
+
71
+ def test_create_group_omits_none(self):
72
+ kat, t = make((200, 123))
73
+ self.assertEqual(kat.create_group(group_title="신규 매장"), 123)
74
+ self.assertEqual(t.last["method"], "POST")
75
+ self.assertEqual(t.last_json(), {"groupTitle": "신규 매장"})
76
+
77
+ def test_delete_group_204(self):
78
+ kat, t = make((204, None))
79
+ self.assertIsNone(kat.delete_group(5))
80
+ self.assertEqual(t.last["url"], "https://api.test/group/5")
81
+ self.assertEqual(t.last["method"], "DELETE")
82
+
83
+ def test_send_message(self):
84
+ kat, t = make((200, {"code": "0", "message": "Success", "result": "a" * 32}))
85
+ chat_id = kat.send_message("01098765432", "안녕하세요", from_number="07012345678")
86
+ self.assertEqual(chat_id, "a" * 32)
87
+ self.assertEqual(
88
+ t.last_json(),
89
+ {"toPhoneNumber": "01098765432", "content": "안녕하세요", "fromPhoneNumber": "07012345678"},
90
+ )
91
+ self.assertEqual(t.last["headers"]["Content-Type"], "application/json")
92
+
93
+ def test_call_history_query(self):
94
+ kat, t = make((200, {"data": [], "total": 0, "offset": 0, "limit": 100}))
95
+ kat.list_call_history(1, updated_after="2026-03-12T00:00:00.000Z", limit=100)
96
+ self.assertEqual(
97
+ t.last_query(), {"groupId": "1", "updatedAfter": "2026-03-12T00:00:00.000Z", "limit": "100"}
98
+ )
99
+ kat.get_call_history("abc-1", group_id=1)
100
+ self.assertTrue(t.last["url"].startswith("https://api.test/call-history/abc-1?"))
101
+
102
+ def test_agents_filter(self):
103
+ kat, t = make((200, []))
104
+ kat.list_agents(3, direction="OUTBOUND")
105
+ self.assertEqual(t.last_query(), {"direction": "OUTBOUND"})
106
+ self.assertIn("/group/3/agent?", t.last["url"])
107
+
108
+ def test_ai_outbound(self):
109
+ kat, t = make((200, {"requestId": "r1"}), (200, {"requestId": "r1", "status": "COMPLETED"}), (200, {}), (200, {}))
110
+ kat.create_ai_outbound_call(1, {"agentId": 9}, idempotency_key="k-1")
111
+ self.assertEqual(t.last["url"], "https://api.test/group/1/ai-outbound/calls")
112
+ self.assertEqual(t.last["headers"]["Idempotency-Key"], "k-1")
113
+ self.assertEqual(t.last_json(), {"agentId": 9})
114
+ self.assertEqual(kat.get_ai_outbound_call(1, "r1")["status"], "COMPLETED")
115
+ kat.list_ai_outbound_calls(1, cursor="c", limit=10)
116
+ self.assertEqual(t.last_query(), {"cursor": "c", "limit": "10"})
117
+ kat.terminate_ai_outbound_call(1, "r1")
118
+ self.assertTrue(t.last["url"].endswith("/group/1/ai-outbound/calls/r1/termination"))
119
+ self.assertEqual(t.last["method"], "POST")
120
+
121
+ def test_generated_idempotency_key(self):
122
+ kat, t = make((200, {}))
123
+ kat.create_ai_outbound_call(1, {})
124
+ self.assertTrue(len(t.last["headers"]["Idempotency-Key"]) >= 32)
125
+
126
+ def test_path_segments_are_escaped(self):
127
+ kat, t = make((200, {}))
128
+ kat.get_message_result("../x")
129
+ self.assertEqual(t.last["url"], "https://api.test/message/send-result/..%2Fx")
130
+
131
+ def test_webhook_endpoints(self):
132
+ kat, t = make((200, {"id": 1}), (200, {"secret": "whsec_x"}), (200, {"secret": "whsec_y"}))
133
+ kat.create_webhook("CALL_COMPLETED", "https://example.com/hook")
134
+ self.assertEqual(t.last_json(), {"eventType": "CALL_COMPLETED", "url": "https://example.com/hook"})
135
+ self.assertEqual(kat.get_webhook_secret()["secret"], "whsec_x")
136
+ self.assertEqual(kat.rotate_webhook_secret()["secret"], "whsec_y")
137
+ self.assertTrue(t.last["url"].endswith("/webhook/secret/rotate"))
138
+
139
+
140
+ class ErrorTests(unittest.TestCase):
141
+ def test_documented_error_shape(self):
142
+ kat, _ = make((403, {"status": 403, "code": "AU017", "message": "BUSINESS 요금제만"}))
143
+ with self.assertRaises(KatError) as cm:
144
+ kat.list_groups()
145
+ e = cm.exception
146
+ self.assertEqual((e.status, e.code, e.message), (403, "AU017", "BUSINESS 요금제만"))
147
+
148
+ def test_field_errors(self):
149
+ body = {"status": 400, "code": "AG011", "message": "https 주소만", "errors": [{"field": "url", "reason": "https 주소만"}]}
150
+ kat, _ = make((400, body))
151
+ with self.assertRaises(KatError) as cm:
152
+ kat.list_agents(1)
153
+ self.assertEqual(cm.exception.errors[0]["field"], "url")
154
+
155
+ def test_studio_error_shape(self):
156
+ kat, _ = make((400, {"statusCode": 400, "message": ["content too long"], "error": "Bad Request"}))
157
+ with self.assertRaises(KatError) as cm:
158
+ kat.list_groups()
159
+ self.assertEqual(cm.exception.status, 400)
160
+ self.assertIsNone(cm.exception.code)
161
+ self.assertEqual(cm.exception.message, "content too long")
162
+
163
+ def test_non_json_error(self):
164
+ kat, _ = make((502, "Bad Gateway"))
165
+ with self.assertRaises(KatError) as cm:
166
+ kat.list_groups()
167
+ self.assertEqual((cm.exception.status, cm.exception.message), (502, "Bad Gateway"))
168
+
169
+
170
+ if __name__ == "__main__":
171
+ unittest.main()
@@ -0,0 +1,58 @@
1
+ import hashlib
2
+ import hmac
3
+ import os
4
+ import sys
5
+ import unittest
6
+
7
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
8
+
9
+ from katcloud import WebhookSignatureError, compute_signature, construct_event, verify_signature # noqa: E402
10
+
11
+ SECRET = "whsec_" + "3f" * 32
12
+ BODY = b'{"eventId":"6c1f","eventType":"INTAKE","timestamp":"2026-11-01T06:00:00.000Z","data":{}}'
13
+ TS = "1793512800"
14
+
15
+
16
+ class WebhookTests(unittest.TestCase):
17
+ def test_matches_documented_algorithm(self):
18
+ expected = "v1=" + hmac.new(SECRET.encode(), (TS + ".").encode() + BODY, hashlib.sha256).hexdigest()
19
+ self.assertEqual(compute_signature(SECRET, TS, BODY), expected)
20
+
21
+ def test_valid(self):
22
+ sig = compute_signature(SECRET, TS, BODY)
23
+ self.assertTrue(verify_signature(BODY, TS, sig, SECRET, now=int(TS) + 10))
24
+
25
+ def test_tampered_body(self):
26
+ sig = compute_signature(SECRET, TS, BODY)
27
+ self.assertFalse(verify_signature(BODY + b" ", TS, sig, SECRET, now=int(TS)))
28
+
29
+ def test_wrong_secret(self):
30
+ sig = compute_signature(SECRET, TS, BODY)
31
+ self.assertFalse(verify_signature(BODY, TS, sig, "whsec_other", now=int(TS)))
32
+
33
+ def test_stale_timestamp(self):
34
+ sig = compute_signature(SECRET, TS, BODY)
35
+ self.assertFalse(verify_signature(BODY, TS, sig, SECRET, now=int(TS) + 301))
36
+ self.assertTrue(verify_signature(BODY, TS, sig, SECRET, now=int(TS) + 300))
37
+
38
+ def test_missing_or_bad_headers(self):
39
+ self.assertFalse(verify_signature(BODY, None, "v1=x", SECRET))
40
+ self.assertFalse(verify_signature(BODY, TS, None, SECRET))
41
+ self.assertFalse(verify_signature(BODY, "abc", "v1=x", SECRET))
42
+
43
+ def test_rotation_accepts_any_secret(self):
44
+ sig = compute_signature(SECRET, TS, BODY)
45
+ self.assertTrue(verify_signature(BODY, TS, sig, ["whsec_new", SECRET], now=int(TS)))
46
+
47
+ def test_construct_event_case_insensitive_headers(self):
48
+ sig = compute_signature(SECRET, TS, BODY)
49
+ event = construct_event(
50
+ BODY, {"x-webhook-timestamp": TS, "x-webhook-signature": sig}, SECRET, now=int(TS)
51
+ )
52
+ self.assertEqual(event["eventType"], "INTAKE")
53
+ with self.assertRaises(WebhookSignatureError):
54
+ construct_event(BODY, {"X-Webhook-Timestamp": TS, "X-Webhook-Signature": "v1=00"}, SECRET, now=int(TS))
55
+
56
+
57
+ if __name__ == "__main__":
58
+ unittest.main()