purpleume 0.1.0b0__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 (32) hide show
  1. purpleume-0.1.0b0/.gitignore +9 -0
  2. purpleume-0.1.0b0/LICENSE +201 -0
  3. purpleume-0.1.0b0/NOTICE +2 -0
  4. purpleume-0.1.0b0/PKG-INFO +362 -0
  5. purpleume-0.1.0b0/README.md +328 -0
  6. purpleume-0.1.0b0/examples/server.py +122 -0
  7. purpleume-0.1.0b0/pyproject.toml +67 -0
  8. purpleume-0.1.0b0/src/purpleume/__init__.py +167 -0
  9. purpleume-0.1.0b0/src/purpleume/_core.py +277 -0
  10. purpleume-0.1.0b0/src/purpleume/_ed25519.py +144 -0
  11. purpleume-0.1.0b0/src/purpleume/_ops.py +468 -0
  12. purpleume-0.1.0b0/src/purpleume/_version.py +3 -0
  13. purpleume-0.1.0b0/src/purpleume/async_client.py +389 -0
  14. purpleume-0.1.0b0/src/purpleume/client.py +396 -0
  15. purpleume-0.1.0b0/src/purpleume/errors.py +178 -0
  16. purpleume-0.1.0b0/src/purpleume/events.py +304 -0
  17. purpleume-0.1.0b0/src/purpleume/models.py +727 -0
  18. purpleume-0.1.0b0/src/purpleume/py.typed +0 -0
  19. purpleume-0.1.0b0/src/purpleume/token.py +494 -0
  20. purpleume-0.1.0b0/src/purpleume/webhook.py +164 -0
  21. purpleume-0.1.0b0/tests/conftest.py +130 -0
  22. purpleume-0.1.0b0/tests/data/extra_token_vectors.json +129 -0
  23. purpleume-0.1.0b0/tests/data/token_vectors.json +177 -0
  24. purpleume-0.1.0b0/tests/data/webhook_signature_vectors.json +114 -0
  25. purpleume-0.1.0b0/tests/test_async_client.py +210 -0
  26. purpleume-0.1.0b0/tests/test_client.py +798 -0
  27. purpleume-0.1.0b0/tests/test_contract.py +78 -0
  28. purpleume-0.1.0b0/tests/test_ed25519.py +67 -0
  29. purpleume-0.1.0b0/tests/test_models.py +66 -0
  30. purpleume-0.1.0b0/tests/test_token.py +320 -0
  31. purpleume-0.1.0b0/tests/test_vectors_in_sync.py +38 -0
  32. purpleume-0.1.0b0/tests/test_webhook.py +330 -0
@@ -0,0 +1,9 @@
1
+ .venv/
2
+ .venv-*/
3
+ dist/
4
+ build/
5
+ *.egg-info/
6
+ __pycache__/
7
+ *.pyc
8
+ .pytest_cache/
9
+ .mypy_cache/
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,2 @@
1
+ purpleUMe SDK
2
+ Copyright 2026 Purple Computer, Inc.
@@ -0,0 +1,362 @@
1
+ Metadata-Version: 2.5
2
+ Name: purpleume
3
+ Version: 0.1.0b0
4
+ Summary: Server SDK for purpleUMe: connection tokens, REST API client, webhook verification.
5
+ Project-URL: Homepage, https://purpleume.com
6
+ Project-URL: Documentation, https://purpleume.com/docs
7
+ Author-email: "Purple Computer, Inc." <support@purpleume.com>
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ License-File: NOTICE
11
+ Keywords: jwt,purpleume,sfu,video,webhook,webrtc
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Topic :: Communications :: Conferencing
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.9
26
+ Provides-Extra: async
27
+ Requires-Dist: httpx<1,>=0.24; extra == 'async'
28
+ Provides-Extra: dev
29
+ Requires-Dist: build==1.6.1; extra == 'dev'
30
+ Requires-Dist: httpx==0.28.1; extra == 'dev'
31
+ Requires-Dist: mypy==2.4.1; extra == 'dev'
32
+ Requires-Dist: pytest==9.2.0; extra == 'dev'
33
+ Description-Content-Type: text/markdown
34
+
35
+ # purpleume (Python server SDK)
36
+
37
+ Server-side helpers for [purpleUMe](https://purpleume.com), real-time video (SFU) with built-in
38
+ video moderation:
39
+
40
+ - **Connection tokens**, signed locally with your API secret. No network call.
41
+ - **REST API client**: rooms, participants, usage, webhooks, events, moderation.
42
+ - **Webhook verification** and typed events.
43
+
44
+ This package runs on *your server*. It does not send or receive media (the Web, iOS and Android
45
+ SDKs do), and the API secret (`pum_sk_...`) must never reach a browser or a mobile app.
46
+
47
+ ## Install
48
+
49
+ ```
50
+ pip install purpleume # tokens, sync client, webhooks: no dependencies
51
+ pip install "purpleume[async]" # adds AsyncClient (uses httpx)
52
+ ```
53
+
54
+ Python 3.9 or later. Fully typed (`py.typed`).
55
+
56
+ Preview release (`0.1.0b0`) during beta testing: the API can still change between preview versions.
57
+ While only preview versions exist, `pip install purpleume` installs the latest one. The first
58
+ published version already supports the region `global` (the default for locally signed tokens).
59
+
60
+ ## Mint a token for a browser client
61
+
62
+ Your backend authenticates the user, mints a token and hands it to the client, which passes it to
63
+ `Room.connect(token)`.
64
+
65
+ ```python
66
+ import os
67
+ from purpleume import AccessToken, Grants
68
+
69
+ tokens = AccessToken(os.environ["PURPLEUME_API_SECRET"])
70
+
71
+ token = tokens.mint(
72
+ room="standup",
73
+ identity="user-42", # your id for the participant; unique within the room
74
+ ttl=3600, # seconds, 60..86400 (default 3600)
75
+ name="Aiko", # optional display name (at most 128 characters)
76
+ metadata='{"role":"host"}', # optional opaque string (at most 1024 characters)
77
+ grants=Grants(publish=True, subscribe=True, sources=["camera", "microphone"]),
78
+ )
79
+ ```
80
+
81
+ - `region` is normally left out: it defaults to `"global"`, purpleUMe places the room and the client
82
+ connects to `wss://global.rtc.purpleume.com/rtc`. `client.regions.list()` returns the regions.
83
+ - Omitted grants mean "allowed". `Grants(sources=[])` is different from leaving `sources` out: the
84
+ empty list means no source may be published.
85
+ - A viewer: `grants=Grants(publish=False)`.
86
+ - `moderation=True/False` overrides the project's moderation default for this participant (only if
87
+ the project allows token overrides).
88
+ - `create_token(api_secret, room=..., identity=...)` is the same as a one-liner.
89
+ - `decode_token(token)` returns the header and claims for debugging. It verifies nothing.
90
+ - Expiry only matters when joining: a participant who is already in the room is not disconnected
91
+ when the token expires.
92
+
93
+ Inputs are validated with the server's rules and a `purpleume.ValidationError` (a `ValueError`) is
94
+ raised before anything is signed.
95
+
96
+ `client.tokens.create(...)` mints the same kind of token on the server instead (`POST /v1/tokens`);
97
+ there `region` may be left out and defaults to the project's default region.
98
+
99
+ Tokens are EdDSA (Ed25519) JWTs. The signing key is not the API secret but an Ed25519 key derived
100
+ from it: `verify_key = HMAC-SHA256(secret, "rtc-token-v1")`, then the 32-byte seed
101
+ `HMAC-SHA256(verify_key, "rtc-token-ed25519-v1")`. purpleUMe's media servers hold only the public
102
+ key (`tokens.public_key`, `derive_public_key`), which verifies tokens but cannot create them. The
103
+ SDK has no dependencies: Ed25519 (RFC 8032) is implemented in pure Python in `purpleume._ed25519`
104
+ and checked against the RFC's test vectors. `AccessToken(secret, algorithm="HS256")` signs the
105
+ legacy HS256 format, which the platform accepts only during a transition period; use the default.
106
+
107
+ ## Mint a token for WHIP ingest (OBS, GStreamer, FFmpeg)
108
+
109
+ For WHIP the connection token is the stream key. Give it a lifetime that covers the whole stream
110
+ plus reconnects (the token is checked on every reconnect), and one token per encoder.
111
+
112
+ ```python
113
+ token = tokens.mint(
114
+ room="town-hall",
115
+ identity="obs-main",
116
+ ttl=4 * 3600, # event length + 1 hour; the maximum is 24 hours
117
+ grants=Grants(publish=True, subscribe=False, sources=["camera", "microphone"]),
118
+ )
119
+ whip_url = "https://global.rtc.purpleume.com/whip" # same region as the token (default "global")
120
+ # OBS: Settings -> Stream -> Service "WHIP", Server = whip_url, Bearer Token = token
121
+ ```
122
+
123
+ To cut a stream off, remove the participant with a ban (see below); a ban also refuses the token
124
+ afterwards.
125
+
126
+ ## REST API
127
+
128
+ ```python
129
+ from purpleume import Client, NotFoundError
130
+
131
+ client = Client(os.environ["PURPLEUME_API_SECRET"]) # base_url, timeout=30.0, max_retries=2
132
+
133
+ # list rooms: one page (as in the Node and Go SDKs, `list` is always a single request)
134
+ page = client.rooms.list(limit=50)
135
+ page.data, page.next_cursor # pass cursor=page.next_cursor for the next page
136
+
137
+ # or every room: the iterator fetches pages as needed
138
+ for room in client.rooms.list_all():
139
+ print(room.name, room.participant_count, room.created_at)
140
+
141
+ # participants: one page (default 100, at most 500) or all of them
142
+ page = client.participants.list("standup", limit=500)
143
+ for p in client.participants.list_all("standup"):
144
+ print(p.identity, [t.source for t in p.tracks])
145
+
146
+ # remove (kick) a participant; ban=True keeps the identity out until its tokens expire
147
+ try:
148
+ client.participants.remove("standup", "user-42", ban=True)
149
+ except NotFoundError:
150
+ pass # already gone
151
+
152
+ client.participants.mute("standup", "user-42", muted=True, sources=["microphone"])
153
+ client.rooms.close("standup")
154
+ ```
155
+
156
+ Every room-addressed call takes `region=`; without it the project's default region is used.
157
+
158
+ | Group | Methods |
159
+ | --- | --- |
160
+ | `client.tokens` | `create` |
161
+ | `client.regions` | `list` (each `Region` has `edges`, which users normally connect through, and `cores`, the sites where rooms live (`global`: Fremont, Amsterdam), a cover the client SDKs connect to only when no edge can be used) |
162
+ | `client.rooms` | `list` (one page), `list_all` (iterator), `get`, `close` |
163
+ | `client.participants` | `list(room, cursor=, limit=)` (one page), `list_all(room)` (iterator), `remove(room, identity, ban=False)`, `mute(room, identity, muted=True, sources=None)` |
164
+ | `client.usage` | `get(from_date=, to_date=, granularity=, region=)` (`free_tier` is per billing period: `period_start` / `period_end`) |
165
+ | `client.webhooks` | `list`, `create`, `get`, `update`, `delete`, `rotate_secret`, `test`, `list_deliveries` (one page), `list_all_deliveries` (iterator), `resend_delivery` |
166
+ | `client.events` | `list` (one page), `list_all` (iterator) |
167
+ | `client.moderation` | `get_settings`, `update_settings`, `list_incidents` (one page), `list_all_incidents` (iterator) |
168
+
169
+ The naming is the one of the Node and Go SDKs: a paginated `list...` returns one `Page` (`.data`,
170
+ `.next_cursor`) and takes `cursor=`; the matching `list_all...` iterates over every item across
171
+ pages and fetches lazily. `regions.list` and `webhooks.list` are not paginated and return plain
172
+ lists.
173
+
174
+ Results are frozen dataclasses with snake_case attributes (`room.participant_count`); timestamps
175
+ are timezone-aware `datetime` objects; `.raw` holds the JSON object as received. Enumerated values
176
+ (`status`, `reason`, ...) are plain strings, so a value added later does not break your code.
177
+
178
+ ### Async
179
+
180
+ ```python
181
+ from purpleume import AsyncClient
182
+
183
+ async with AsyncClient(api_secret) as client:
184
+ page = await client.rooms.list(limit=50)
185
+ async for room in client.rooms.list_all():
186
+ ...
187
+ await client.participants.remove("standup", "user-42")
188
+ ```
189
+
190
+ Same groups and methods as `Client`. Requires `httpx` (`pip install "purpleume[async]"`).
191
+
192
+ ### Errors
193
+
194
+ Every error is a `purpleume.PurpleumeError` with `code` (stable, machine-readable), `message`,
195
+ `status` (HTTP status or `None`), `request_id` and `retry_after` (seconds, when the server sent it).
196
+
197
+ | Exception | When |
198
+ | --- | --- |
199
+ | `ValidationError` (also a `ValueError`) | An argument was rejected locally; nothing was sent |
200
+ | `InvalidRequestError` | 400 |
201
+ | `AuthenticationError` | 401: missing, wrong or revoked API key |
202
+ | `PermissionDeniedError` | 403: `forbidden`, `account_suspended`, `limit_exceeded`, ... (see `code`) |
203
+ | `NotFoundError` | 404 |
204
+ | `ConflictError` | 409, and every `webhook_disabled` (test send or resend to a disabled endpoint) |
205
+ | `RateLimitError` | 429 after the retries were used up |
206
+ | `ServerError` | 5xx after the retries were used up |
207
+ | `APIError` | Base of the seven above; also any other status, or a body that is not what the API documents (`code="invalid_response"`) |
208
+ | `APIConnectionError` | No response: DNS, TCP, TLS, timeout (`code="network_error"`) |
209
+ | `WebhookSignatureError` | Webhook verification failed (`reason`) |
210
+
211
+ `purpleume.ErrorCode` holds the documented REST codes as `str` constants (`ErrorCode.NOT_FOUND`,
212
+ `ErrorCode.WEBHOOK_DISABLED`, ...; `ErrorCode.ALL` lists them). `e.code` stays a plain `str`: the API
213
+ may add codes, and an unknown one is passed through unchanged (`ErrorCode.is_known(e.code)` is then
214
+ `False`) with the exception class chosen by the HTTP status.
215
+
216
+ ```python
217
+ from purpleume import PurpleumeError, RateLimitError
218
+
219
+ try:
220
+ client.rooms.get("standup")
221
+ except RateLimitError as e:
222
+ print("slow down for", e.retry_after, "seconds")
223
+ except PurpleumeError as e:
224
+ print(e.status, e.code, e.message, e.request_id) # give request_id to support
225
+ ```
226
+
227
+ ### Retries
228
+
229
+ A failed call is retried up to `max_retries` times (default 2, so at most 3 attempts):
230
+
231
+ - **429** is retried for every call. The client waits as long as `Retry-After` says; if that is more
232
+ than 60 seconds it raises `RateLimitError` at once instead of blocking.
233
+ - **5xx, network errors and timeouts** are retried only for calls that are safe to repeat: every
234
+ `GET`, `DELETE` and `PATCH`, plus `tokens.create` and `participants.mute`. They wait
235
+ 0.5 s, 1 s, 2 s, ... (capped at 8 s) with random jitter.
236
+ - `webhooks.create`, `rotate_secret`, `test` and `resend_delivery` are **never** retried after a 5xx
237
+ or a network error, because the first attempt may have been applied. If one of them fails that
238
+ way, check the state (`webhooks.list()`) before repeating it.
239
+
240
+ `Client(..., max_retries=0)` turns retries off. `timeout` applies to each attempt. Redirects are
241
+ not followed. The API secret is never logged and does not appear in `repr(client)` or in exception
242
+ messages.
243
+
244
+ ## Webhooks
245
+
246
+ purpleUMe POSTs events as JSON with a `Purpleume-Signature: t=<unix>,v1=<hex>` header.
247
+ `verify_webhook` checks the signature against the **raw request body** and returns a typed `Event`.
248
+
249
+ ```python
250
+ from purpleume import verify_webhook, WebhookSignatureError, ParticipantEventData
251
+
252
+ event = verify_webhook(raw_body, signature_header, webhook_secret) # tolerance=300 seconds
253
+
254
+ if event.type == "participant.left" and isinstance(event.data, ParticipantEventData):
255
+ print(event.data.participant.identity, event.data.reason, event.data.duration_seconds)
256
+ ```
257
+
258
+ - Pass the body **as bytes, exactly as received**. A body that was parsed and re-serialised does
259
+ not verify.
260
+ - A timestamp more than `tolerance` seconds old *or* in the future is rejected.
261
+ - During a secret rotation deliveries carry two `v1` values for 24 hours; a match on either is
262
+ accepted, so switching your configured secret at any point in that window works.
263
+ - An event type this SDK version does not know is returned with `event.data` as `UnknownEventData`
264
+ (`event.data.raw`, `event.raw`) instead of raising. Ignore the types you do not handle.
265
+ - Deliveries can repeat and are not ordered: de-duplicate on `event.id`.
266
+ - Answer with a 2xx within 10 seconds; do slow work after responding.
267
+ - `verify_webhook_request(raw_body, headers, secret)` finds the header for you;
268
+ `sign_webhook(body, secret, timestamp)` produces a header for testing your receiver.
269
+
270
+ | `event.type` | `event.data` |
271
+ | --- | --- |
272
+ | `room.started`, `room.finished` | `RoomEventData` (`room`, `usage` on finished) |
273
+ | `participant.joined`, `participant.left` | `ParticipantEventData` (`room`, `participant`, `reason`, `duration_seconds`) |
274
+ | `track.published`, `track.unpublished` | `TrackEventData` (`room`, `participant`, `track`) |
275
+ | `moderation.flagged` | `ModerationFlaggedData` (`incident_id`, `category`, `score`, `action`, ...) |
276
+ | `moderation.unavailable`, `moderation.recovered` | `ModerationAvailabilityData` (`fail_mode`, `affected_rooms`) |
277
+ | `usage.free_tier_threshold` | `FreeTierThresholdData` (`meter`, `percent`, `used`, `included`, and the billing period `period_start` / `period_end` as aware UTC datetimes) |
278
+ | `webhook.test` | `WebhookTestData` (`message`) |
279
+
280
+ ### Flask
281
+
282
+ ```python
283
+ from flask import Flask, request
284
+ from purpleume import verify_webhook, WebhookSignatureError
285
+
286
+ app = Flask(__name__)
287
+
288
+ @app.post("/webhooks/purpleume")
289
+ def purpleume_webhook():
290
+ raw = request.get_data() # bytes; call this instead of request.json / request.form
291
+ try:
292
+ event = verify_webhook(raw, request.headers.get("Purpleume-Signature", ""), WEBHOOK_SECRET)
293
+ except WebhookSignatureError:
294
+ return "", 400
295
+ handle(event)
296
+ return "", 204
297
+ ```
298
+
299
+ ### FastAPI / Starlette
300
+
301
+ ```python
302
+ from fastapi import FastAPI, Request, Response
303
+ from purpleume import verify_webhook, WebhookSignatureError
304
+
305
+ app = FastAPI()
306
+
307
+ @app.post("/webhooks/purpleume")
308
+ async def purpleume_webhook(request: Request) -> Response:
309
+ raw = await request.body() # bytes; do not declare a Pydantic body parameter for this route
310
+ try:
311
+ event = verify_webhook(raw, request.headers.get("purpleume-signature", ""), WEBHOOK_SECRET)
312
+ except WebhookSignatureError:
313
+ return Response(status_code=400)
314
+ handle(event)
315
+ return Response(status_code=204)
316
+ ```
317
+
318
+ ### Django
319
+
320
+ ```python
321
+ from django.http import HttpResponse
322
+ from django.views.decorators.csrf import csrf_exempt
323
+ from django.views.decorators.http import require_POST
324
+ from purpleume import verify_webhook, WebhookSignatureError
325
+
326
+ @csrf_exempt
327
+ @require_POST
328
+ def purpleume_webhook(request):
329
+ raw = request.body # bytes; read it before touching request.POST
330
+ try:
331
+ event = verify_webhook(raw, request.headers.get("Purpleume-Signature", ""), WEBHOOK_SECRET)
332
+ except WebhookSignatureError:
333
+ return HttpResponse(status=400)
334
+ handle(event)
335
+ return HttpResponse(status=204)
336
+ ```
337
+
338
+ (With Django REST Framework, read `request.body` before `request.data`.)
339
+
340
+ ## Example without a framework
341
+
342
+ [`examples/server.py`](examples/server.py) is a token endpoint plus a webhook receiver on the
343
+ standard library's `http.server`.
344
+
345
+ ## Development
346
+
347
+ ```
348
+ python -m venv .venv
349
+ .venv/Scripts/python -m pip install -e ".[dev]" # POSIX: .venv/bin/python
350
+ .venv/Scripts/python -m pytest
351
+ .venv/Scripts/python -m mypy
352
+ .venv/Scripts/python -m build
353
+ ```
354
+
355
+ `tests/data/` holds copies of the canonical test vectors of the main repository
356
+ (`internal/token/testdata/vectors.json`, `internal/webhook/testdata/signature_vectors.json`).
357
+ `tests/test_vectors_in_sync.py` fails when a copy differs from the original.
358
+
359
+ ## License
360
+
361
+ Apache License 2.0 (`Apache-2.0`). Copyright 2026 Purple Computer, Inc. See [`LICENSE`](LICENSE) and [`NOTICE`](NOTICE).
362
+ Copyright 2026 Purple Computer, Inc.