signops 0.2.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,20 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ push:
5
+ tags: ["v*"]
6
+
7
+ jobs:
8
+ publish:
9
+ runs-on: ubuntu-latest
10
+ environment: pypi
11
+ permissions:
12
+ id-token: write
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+ - uses: actions/setup-python@v5
16
+ with:
17
+ python-version: "3.12"
18
+ - run: python -m pip install build
19
+ - run: python -m build
20
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,6 @@
1
+ node_modules/
2
+ dist/
3
+ dist-pub/
4
+ __pycache__/
5
+ *.pyc
6
+ .env
signops-0.2.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 SignOps
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.
signops-0.2.0/PKG-INFO ADDED
@@ -0,0 +1,49 @@
1
+ Metadata-Version: 2.5
2
+ Name: signops
3
+ Version: 0.2.0
4
+ Summary: SignOps for Python: push notifications to Android, iOS and the web, push approval of logins, passkeys and webhooks.
5
+ Project-URL: Homepage, https://signops.dev/
6
+ Project-URL: Documentation, https://signops.dev/docs/
7
+ Project-URL: Repository, https://github.com/signops-dev/signops-python
8
+ Project-URL: Issues, https://github.com/signops-dev/signops-python/issues
9
+ Author-email: SignOps <hello@signops.dev>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: apns,fcm,passkeys,push authentication,push notifications,signops,web push,webauthn
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.9
18
+ Description-Content-Type: text/markdown
19
+
20
+ # signops
21
+
22
+ SignOps for Python: push notifications to Android, iOS and the web, push approval of logins, passkeys and webhooks, on one API key and your own user ids. Website: https://signops.dev. Docs: https://signops.dev/docs/
23
+
24
+ Not on PyPI yet. Until it is, install from this repository:
25
+
26
+ ```sh
27
+ pip install git+https://github.com/signops-dev/signops-python
28
+ ```
29
+
30
+ ```python
31
+ import os
32
+ from signops import SignOps, SignOpsError
33
+
34
+ signops = SignOps(os.environ["SIGNOPS_KEY"]) # sk_live_... or sk_test_...
35
+
36
+ signops.devices.add(user_id="usr_8f21c4", token=fcm_token, platform="android")
37
+ signops.push.send(user_id="usr_8f21c4", title="Your order is out for delivery", body="Ravi is 10 minutes away.")
38
+ signops.push.send(topic="offers", title="Weekend offer", body="20% off fruit", send_at="2026-10-24T18:00:00+05:30")
39
+
40
+ challenge = signops.approve.create(user_id="usr_8f21c4", context="Sign in from Chrome on Windows")
41
+ result = signops.approve.wait(challenge.id, timeout=120) # show challenge.match on your login page first
42
+ if result.status == "approved":
43
+ start_session(result.user_id)
44
+
45
+ check = signops.passkeys.verify(request.form["signops_token"])
46
+ event = signops.webhooks.verify(request.get_data(), request.headers["SignOps-Signature"]) # SIGNOPS_WEBHOOK_SECRET
47
+ ```
48
+
49
+ Results read as `result.valid` or `result["valid"]`. Errors raise `SignOpsError` with `status`, `code` and `message`. Every POST carries an `Idempotency-Key`, so retries never send twice. Standard library only; Python 3.9 or later.
@@ -0,0 +1,30 @@
1
+ # signops
2
+
3
+ SignOps for Python: push notifications to Android, iOS and the web, push approval of logins, passkeys and webhooks, on one API key and your own user ids. Website: https://signops.dev. Docs: https://signops.dev/docs/
4
+
5
+ Not on PyPI yet. Until it is, install from this repository:
6
+
7
+ ```sh
8
+ pip install git+https://github.com/signops-dev/signops-python
9
+ ```
10
+
11
+ ```python
12
+ import os
13
+ from signops import SignOps, SignOpsError
14
+
15
+ signops = SignOps(os.environ["SIGNOPS_KEY"]) # sk_live_... or sk_test_...
16
+
17
+ signops.devices.add(user_id="usr_8f21c4", token=fcm_token, platform="android")
18
+ signops.push.send(user_id="usr_8f21c4", title="Your order is out for delivery", body="Ravi is 10 minutes away.")
19
+ signops.push.send(topic="offers", title="Weekend offer", body="20% off fruit", send_at="2026-10-24T18:00:00+05:30")
20
+
21
+ challenge = signops.approve.create(user_id="usr_8f21c4", context="Sign in from Chrome on Windows")
22
+ result = signops.approve.wait(challenge.id, timeout=120) # show challenge.match on your login page first
23
+ if result.status == "approved":
24
+ start_session(result.user_id)
25
+
26
+ check = signops.passkeys.verify(request.form["signops_token"])
27
+ event = signops.webhooks.verify(request.get_data(), request.headers["SignOps-Signature"]) # SIGNOPS_WEBHOOK_SECRET
28
+ ```
29
+
30
+ Results read as `result.valid` or `result["valid"]`. Errors raise `SignOpsError` with `status`, `code` and `message`. Every POST carries an `Idempotency-Key`, so retries never send twice. Standard library only; Python 3.9 or later.
@@ -0,0 +1,20 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "signops"
7
+ version = "0.2.0"
8
+ description = "SignOps for Python: push notifications to Android, iOS and the web, push approval of logins, passkeys and webhooks."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ authors = [{ name = "SignOps", email = "hello@signops.dev" }]
13
+ classifiers = ["Development Status :: 4 - Beta", "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Typing :: Typed"]
14
+ keywords = ["push notifications", "fcm", "apns", "web push", "passkeys", "webauthn", "push authentication", "signops"]
15
+
16
+ [project.urls]
17
+ Homepage = "https://signops.dev/"
18
+ Documentation = "https://signops.dev/docs/"
19
+ Repository = "https://github.com/signops-dev/signops-python"
20
+ Issues = "https://github.com/signops-dev/signops-python/issues"
@@ -0,0 +1,341 @@
1
+ """SignOps for Python: push notifications to Android, iOS and the web, push approval of logins, passkeys and webhooks.
2
+
3
+ from signops import SignOps
4
+ signops = SignOps(os.environ["SIGNOPS_KEY"])
5
+ signops.push.send(user_id="usr_8f21c4", title="Your order is out for delivery", body="Ravi is 10 minutes away.")
6
+
7
+ Docs: https://signops.dev/docs/. Standard library only, Python 3.9 and later.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ import hmac
14
+ import json
15
+ import os
16
+ import random
17
+ import time
18
+ import uuid
19
+ import urllib.error
20
+ import urllib.parse
21
+ import urllib.request
22
+ from typing import Any, Dict, List, Optional, Union
23
+
24
+ __version__ = "0.2.0"
25
+ __all__ = ["SignOps", "SignOpsError", "Obj"]
26
+
27
+
28
+ class SignOpsError(Exception):
29
+ """An error from the API, with its HTTP status and the documented code (invalid_request, not_allowed, ...)."""
30
+
31
+ def __init__(self, status: int, code: str, message: str):
32
+ super().__init__(message)
33
+ self.status = status
34
+ self.code = code
35
+ self.message = message
36
+
37
+
38
+ class Obj(dict):
39
+ """A result you can read as result["valid"] or result.valid."""
40
+
41
+ def __getattr__(self, name: str) -> Any:
42
+ try:
43
+ return self[name]
44
+ except KeyError as e:
45
+ raise AttributeError(name) from e
46
+
47
+
48
+ def _wrap(v: Any) -> Any:
49
+ if isinstance(v, dict):
50
+ return Obj({k: _wrap(x) for k, x in v.items()})
51
+ if isinstance(v, list):
52
+ return [_wrap(x) for x in v]
53
+ return v
54
+
55
+
56
+ def _q(s: str) -> str:
57
+ return urllib.parse.quote(s, safe="")
58
+
59
+
60
+ class SignOps:
61
+ def __init__(self, key: Optional[str] = None, base_url: str = "https://api.signops.dev", webhook_secret: Optional[str] = None,
62
+ timeout: float = 30, max_retries: int = 2):
63
+ key = key or os.environ.get("SIGNOPS_KEY")
64
+ if not key:
65
+ raise ValueError("SignOps: pass your secret key, or set SIGNOPS_KEY.")
66
+ if key.startswith("pk_"):
67
+ raise ValueError("SignOps: this is a publishable key. On your server use the secret key, sk_live_... or sk_test_....")
68
+ self._key = key
69
+ self._base = base_url.rstrip("/")
70
+ self._timeout = timeout
71
+ self._retries = max_retries
72
+ self._hook_secret = webhook_secret or os.environ.get("SIGNOPS_WEBHOOK_SECRET")
73
+ self.push = _Push(self)
74
+ self.devices = _Devices(self)
75
+ self.topics = _Topics(self)
76
+ self.templates = _Templates(self)
77
+ self.approve = _Approve(self)
78
+ self.passkeys = _Passkeys(self)
79
+ self.totp = _Totp(self)
80
+ self.users = _Users(self)
81
+ self.otp = _Otp(self)
82
+ self.magic_links = _MagicLinks(self)
83
+ self.webhooks = _Webhooks(self)
84
+
85
+ def request(self, method: str, path: str, body: Optional[Dict[str, Any]] = None, idempotency_key: Optional[str] = None, timeout: Optional[float] = None) -> Any:
86
+ """Any API call. Every POST carries an Idempotency-Key, so retries on 429, 5xx and network errors never send twice."""
87
+ headers = {"Authorization": f"Bearer {self._key}", "User-Agent": f"signops-python/{__version__}", "Accept": "application/json"}
88
+ data = None
89
+ if body is not None:
90
+ data = json.dumps({k: v for k, v in body.items() if v is not None}).encode()
91
+ headers["Content-Type"] = "application/json"
92
+ if method == "POST":
93
+ headers["Idempotency-Key"] = idempotency_key or str(uuid.uuid4())
94
+ for attempt in range(self._retries + 1):
95
+ req = urllib.request.Request(self._base + path, data=data, method=method, headers=headers)
96
+ try:
97
+ with urllib.request.urlopen(req, timeout=timeout or self._timeout) as r:
98
+ return _wrap(json.loads(r.read() or b"{}"))
99
+ except urllib.error.HTTPError as e:
100
+ try:
101
+ j = json.loads(e.read() or b"{}")
102
+ except ValueError:
103
+ j = {}
104
+ # A locked user stays locked for minutes: retrying would only wait, so it is raised at once.
105
+ if (e.code == 429 or e.code >= 500) and (j.get("error") or {}).get("code") != "user_locked" and attempt < self._retries:
106
+ wait = float(e.headers.get("Retry-After") or 0) or 0.5 * 2 ** attempt
107
+ time.sleep(min(wait, 10) + random.random() * 0.1)
108
+ continue
109
+ err = j.get("error") or {}
110
+ raise SignOpsError(e.code, err.get("code", "error"), err.get("message", f"SignOps answered {e.code}")) from None
111
+ except (urllib.error.URLError, TimeoutError, OSError) as e:
112
+ if attempt < self._retries:
113
+ time.sleep(0.5 * 2 ** attempt)
114
+ continue
115
+ raise SignOpsError(0, "network_error", f"Could not reach SignOps: {e}") from None
116
+ raise SignOpsError(0, "network_error", "Could not reach SignOps")
117
+
118
+
119
+ class _Push:
120
+ def __init__(self, s: SignOps):
121
+ self._s = s
122
+
123
+ def send(self, user_id: Optional[str] = None, user_ids: Optional[List[str]] = None, topic: Optional[str] = None, all: Optional[bool] = None,
124
+ title: Optional[str] = None, body: Optional[str] = None, image: Optional[str] = None, link: Optional[str] = None,
125
+ data: Optional[Dict[str, Any]] = None, send_at: Optional[str] = None, collapse_key: Optional[str] = None,
126
+ template: Optional[str] = None, fields: Optional[Dict[str, Any]] = None, fields_by_user: Optional[Dict[str, Dict[str, Any]]] = None,
127
+ idempotency_key: Optional[str] = None) -> Obj:
128
+ """To one of user_id, user_ids (up to 1,000), topic or all=True. send_at is an ISO time with a zone, up to 30 days ahead.
129
+ template is a template's name, filled with fields; fields_by_user gives each of user_ids its own fields."""
130
+ return self._s.request("POST", "/v1/push", dict(user_id=user_id, user_ids=user_ids, topic=topic, all=all, title=title, body=body, image=image,
131
+ link=link, data=data, send_at=send_at, collapse_key=collapse_key, template=template,
132
+ fields=fields, fields_by_user=fields_by_user), idempotency_key)
133
+
134
+ def get(self, id: str) -> Obj:
135
+ return self._s.request("GET", f"/v1/push/{_q(id)}")
136
+
137
+ def cancel(self, id: str) -> Obj:
138
+ """Only a scheduled push can be cancelled."""
139
+ return self._s.request("DELETE", f"/v1/push/{_q(id)}")
140
+
141
+
142
+ class _Devices:
143
+ def __init__(self, s: SignOps):
144
+ self._s = s
145
+
146
+ def add(self, user_id: str, token: Union[str, Dict[str, Any]], platform: str, name: Optional[str] = None) -> Obj:
147
+ """token is the FCM or APNs token, or for web the PushSubscription your page got. platform is android, ios or web."""
148
+ return self._s.request("POST", "/v1/devices", dict(user_id=user_id, token=token, platform=platform, name=name))
149
+
150
+ def remove(self, id: str) -> Obj:
151
+ return self._s.request("DELETE", f"/v1/devices/{_q(id)}")
152
+
153
+ def list(self, user_id: str) -> List[Obj]:
154
+ return self._s.request("GET", f"/v1/devices?user_id={_q(user_id)}")["data"]
155
+
156
+
157
+ class _Topics:
158
+ def __init__(self, s: SignOps):
159
+ self._s = s
160
+
161
+ def subscribe(self, topic: str, user_id: str) -> Obj:
162
+ return self._s.request("POST", f"/v1/topics/{_q(topic)}/subscribe", dict(user_id=user_id))
163
+
164
+ def unsubscribe(self, topic: str, user_id: str) -> Obj:
165
+ return self._s.request("POST", f"/v1/topics/{_q(topic)}/unsubscribe", dict(user_id=user_id))
166
+
167
+
168
+ class _Templates:
169
+ def __init__(self, s: SignOps):
170
+ self._s = s
171
+
172
+ def list(self) -> List[Obj]:
173
+ return self._s.request("GET", "/v1/templates")["data"]
174
+
175
+ def get(self, name: str) -> Obj:
176
+ return self._s.request("GET", f"/v1/templates/{_q(name)}")
177
+
178
+ def save(self, name: str, title: Optional[str] = None, body: Optional[str] = None, description: Optional[str] = None,
179
+ image: Optional[str] = None, link: Optional[str] = None, data: Optional[Dict[str, str]] = None) -> Obj:
180
+ """Creates or replaces a template by name. Write {{field}} or {{field|default}} where values go."""
181
+ return self._s.request("POST", "/v1/templates", dict(name=name, title=title, body=body, description=description, image=image, link=link, data=data))
182
+
183
+ def remove(self, name: str) -> Obj:
184
+ return self._s.request("DELETE", f"/v1/templates/{_q(name)}")
185
+
186
+
187
+ class _Approve:
188
+ def __init__(self, s: SignOps):
189
+ self._s = s
190
+
191
+ def enroll_token(self, user_id: str) -> Obj:
192
+ """A one-time token your app passes to the SDK to trust this phone for the signed-in user. Good for 10 minutes."""
193
+ return self._s.request("POST", "/v1/approve/enroll-token", dict(user_id=user_id))
194
+
195
+ def create(self, user_id: str, context: str, city: Optional[str] = None, browser: Optional[str] = None, ip: Optional[str] = None) -> Obj:
196
+ """Pushes to the user's trusted phones. Show result.match on your login page."""
197
+ return self._s.request("POST", "/v1/approve", dict(user_id=user_id, context=context, city=city, browser=browser, ip=ip))
198
+
199
+ def get(self, id: str) -> Obj:
200
+ return self._s.request("GET", f"/v1/approve/{_q(id)}")
201
+
202
+ def wait(self, id: str, timeout: int = 120) -> Obj:
203
+ """Blocks until the user answers or the request expires, up to timeout seconds (at most 120)."""
204
+ until = time.time() + min(timeout, 120)
205
+ while True:
206
+ left = max(0, int(until - time.time()))
207
+ a = self._s.request("GET", f"/v1/approve/{_q(id)}?wait={min(left, 25)}", timeout=40)
208
+ if a["status"] != "pending" or time.time() >= until:
209
+ return a
210
+
211
+ def create_and_wait(self, user_id: str, context: str, timeout: int = 120, **kw: Any) -> Obj:
212
+ a = self.create(user_id, context, **kw)
213
+ r = self.wait(a["id"], timeout)
214
+ r["match"] = a.get("match")
215
+ return r
216
+
217
+ def cancel(self, id: str) -> Obj:
218
+ return self._s.request("POST", f"/v1/approve/{_q(id)}/cancel", {})
219
+
220
+ def untrust(self, device_id: str) -> Obj:
221
+ return self._s.request("POST", f"/v1/approve/devices/{_q(device_id)}/remove", {})
222
+
223
+
224
+ class _Passkeys:
225
+ def __init__(self, s: SignOps):
226
+ self._s = s
227
+
228
+ def registration_token(self, user_id: str, user_name: Optional[str] = None, display_name: Optional[str] = None, rp_id: Optional[str] = None) -> Obj:
229
+ return self._s.request("POST", "/v1/passkeys/registration-token", dict(user_id=user_id, user_name=user_name, display_name=display_name, rp_id=rp_id))
230
+
231
+ def verify(self, signops_token: str) -> Obj:
232
+ """Confirms the signops_token from the browser's passkeys.signIn. Single use. result.valid and result.user_id."""
233
+ return self._s.request("POST", "/v1/passkeys/verify", dict(signops_token=signops_token))
234
+
235
+ def list(self, user_id: str) -> List[Obj]:
236
+ return self._s.request("GET", f"/v1/passkeys?user_id={_q(user_id)}")["data"]
237
+
238
+ def remove(self, id: str) -> Obj:
239
+ return self._s.request("DELETE", f"/v1/passkeys/{_q(id)}")
240
+
241
+
242
+ class _Totp:
243
+ """Authenticator app codes. Wrong codes count toward the user's lock: a locked user raises SignOpsError with code user_locked."""
244
+ def __init__(self, s: SignOps):
245
+ self._s = s
246
+
247
+ def enroll(self, user_id: str, label: Optional[str] = None, issuer: Optional[str] = None) -> Obj:
248
+ """Starts enrolment. Show qr_svg (or secret) to the user; nothing works until confirm."""
249
+ return self._s.request("POST", "/v1/totp/enroll", {"user_id": user_id, "label": label, "issuer": issuer})
250
+
251
+ def confirm(self, user_id: str, code: str) -> Obj:
252
+ """The first code from the app. Returns the 10 backup codes, shown to the user once."""
253
+ return self._s.request("POST", "/v1/totp/confirm", {"user_id": user_id, "code": code})
254
+
255
+ def verify(self, user_id: str, code: str) -> Obj:
256
+ """A 6-digit code or a backup code. Each works once."""
257
+ return self._s.request("POST", "/v1/totp/verify", {"user_id": user_id, "code": code})
258
+
259
+ def backup_codes(self, user_id: str) -> Obj:
260
+ return self._s.request("POST", "/v1/totp/backup-codes", {"user_id": user_id})
261
+
262
+ def status(self, user_id: str) -> Obj:
263
+ return self._s.request("GET", f"/v1/users/{_q(user_id)}/totp")
264
+
265
+ def remove(self, user_id: str) -> Obj:
266
+ return self._s.request("DELETE", f"/v1/users/{_q(user_id)}/totp")
267
+
268
+
269
+ class _Users:
270
+ def __init__(self, s: SignOps):
271
+ self._s = s
272
+
273
+ def delete(self, user_id: str) -> Obj:
274
+ """Erases everything held under the user id (DPDP Act). Answers with what was removed."""
275
+ return self._s.request("DELETE", f"/v1/users/{_q(user_id)}")
276
+
277
+ def export(self, user_id: str) -> Obj:
278
+ """Everything SignOps holds on the user, as one document."""
279
+ return self._s.request("GET", f"/v1/users/{_q(user_id)}/export")
280
+
281
+ def record_consent(self, user_id: str, purpose: str, granted: bool, source: Optional[str] = None, text: Optional[str] = None) -> Obj:
282
+ return self._s.request("POST", f"/v1/users/{_q(user_id)}/consent", {"purpose": purpose, "granted": granted, "source": source, "text": text})
283
+
284
+ def consent(self, user_id: str) -> Obj:
285
+ return self._s.request("GET", f"/v1/users/{_q(user_id)}/consent")
286
+
287
+ def lock(self, user_id: str) -> Obj:
288
+ return self._s.request("GET", f"/v1/users/{_q(user_id)}/lock")
289
+
290
+ def unlock(self, user_id: str) -> Obj:
291
+ return self._s.request("DELETE", f"/v1/users/{_q(user_id)}/lock")
292
+
293
+
294
+ class _Otp:
295
+ def __init__(self, s: SignOps):
296
+ self._s = s
297
+
298
+ def send(self, email: str, app_name: Optional[str] = None) -> Obj:
299
+ return self._s.request("POST", "/v1/otp/send", dict(email=email, app_name=app_name))
300
+
301
+ def verify(self, otp_id: str, code: str) -> Obj:
302
+ return self._s.request("POST", "/v1/otp/verify", dict(otp_id=otp_id, code=code))
303
+
304
+
305
+ class _MagicLinks:
306
+ """Sign-in links by email. The link opens redirect_url with ?signops_token= added; pass that token to verify, once."""
307
+
308
+ def __init__(self, s: SignOps):
309
+ self._s = s
310
+
311
+ def send(self, email: str, redirect_url: str, app_name: Optional[str] = None, language: Optional[str] = None, ip: Optional[str] = None) -> Obj:
312
+ return self._s.request("POST", "/v1/magic-links", dict(email=email, redirect_url=redirect_url, app_name=app_name, language=language, ip=ip))
313
+
314
+ def verify(self, token: str) -> Obj:
315
+ return self._s.request("POST", "/v1/magic-links/verify", dict(token=token))
316
+
317
+ def get(self, link_id: str) -> Obj:
318
+ return self._s.request("GET", f"/v1/magic-links/{_q(link_id)}")
319
+
320
+
321
+ class _Webhooks:
322
+ def __init__(self, s: SignOps):
323
+ self._s = s
324
+
325
+ def verify(self, payload: Union[bytes, str], header: Optional[str], secret: Optional[str] = None, tolerance: int = 300) -> Obj:
326
+ """Checks the SignOps-Signature header against the raw body and returns the event. Raises SignOpsError if it does not match."""
327
+ key = secret or self._s._hook_secret
328
+ if not key:
329
+ raise ValueError("SignOps: no webhook secret. Pass it, or set SIGNOPS_WEBHOOK_SECRET.")
330
+ parts = dict(p.strip().split("=", 1) for p in (header or "").split(",") if "=" in p)
331
+ try:
332
+ t = int(parts.get("t", ""))
333
+ except ValueError:
334
+ raise SignOpsError(400, "invalid_signature", "No SignOps-Signature header, or it is not t=...,v1=...") from None
335
+ if abs(time.time() - t) > tolerance:
336
+ raise SignOpsError(400, "invalid_signature", "The event is older than 5 minutes.")
337
+ body = payload.decode() if isinstance(payload, bytes) else payload
338
+ want = hmac.new(key.encode(), f"{t}.{body}".encode(), hashlib.sha256).hexdigest()
339
+ if not hmac.compare_digest(want, parts.get("v1", "")):
340
+ raise SignOpsError(400, "invalid_signature", "The signature does not match. Check the secret and that the body is the raw one.")
341
+ return _wrap(json.loads(body))
File without changes
@@ -0,0 +1,74 @@
1
+ """Runs against the real API with a test key: SIGNOPS_KEY=sk_test_... python3 -m unittest discover -s tests"""
2
+ import hashlib
3
+ import hmac
4
+ import json
5
+ import os
6
+ import sys
7
+ import time
8
+ import unittest
9
+
10
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
11
+ from signops import SignOps, SignOpsError # noqa: E402
12
+
13
+ KEY = os.environ.get("SIGNOPS_KEY")
14
+
15
+
16
+ @unittest.skipUnless(KEY, "set SIGNOPS_KEY to a test key")
17
+ class Api(unittest.TestCase):
18
+ s = SignOps(KEY, base_url=os.environ.get("SIGNOPS_BASE", "https://api.signops.dev")) if KEY else None
19
+
20
+ def test_devices_topics_push(self):
21
+ d = self.s.devices.add(user_id="usr_py", token=f"py-test-token-{time.time()}", platform="android", name="Python test")
22
+ self.assertTrue(d.id.startswith("dev_"))
23
+ self.assertGreaterEqual(len(self.s.devices.list("usr_py")), 1)
24
+ self.s.topics.subscribe("py-test", user_id="usr_py")
25
+ p = self.s.push.send(topic="py-test", title="From signops for Python", body="Test", data={"order": 1})
26
+ self.assertTrue(p.id.startswith("msg_"))
27
+ later = self.s.push.send(user_id="usr_py", title="Later", body="x", send_at=time.strftime("%Y-%m-%dT%H:%M:%S+00:00", time.gmtime(time.time() + 3600)))
28
+ self.assertEqual(later.status, "scheduled")
29
+ self.assertEqual(self.s.push.cancel(later.id).status, "cancelled")
30
+ self.assertTrue(self.s.devices.remove(d.id).removed)
31
+
32
+ def test_templates(self):
33
+ t = self.s.templates.save("py_paid", title="Rs {{amount}} received", body="Thanks {{name|there}}")
34
+ self.assertEqual([f.name for f in t.fields], ["amount", "name"])
35
+ self.s.devices.add(user_id="usr_py_t", token=f"py-tpl-{time.time()}", platform="android")
36
+ self.assertEqual(self.s.push.send(user_id="usr_py_t", template="py_paid", fields={"amount": 499}).template, "py_paid")
37
+ with self.assertRaises(SignOpsError) as e:
38
+ self.s.push.send(user_id="usr_py_t", template="py_paid")
39
+ self.assertIn("amount", e.exception.message)
40
+ self.s.templates.remove("py_paid")
41
+
42
+ def test_errors(self):
43
+ with self.assertRaises(SignOpsError) as e:
44
+ self.s.push.send(title="no target")
45
+ self.assertEqual((e.exception.status, e.exception.code), (400, "invalid_request"))
46
+ with self.assertRaises(SignOpsError) as e:
47
+ self.s.approve.create(user_id="usr_nobody", context="x")
48
+ self.assertEqual(e.exception.code, "not_found")
49
+ with self.assertRaises(SignOpsError) as e:
50
+ self.s.otp.send(email="a@example.in")
51
+ self.assertEqual(e.exception.code, "not_allowed")
52
+ self.assertTrue(self.s.approve.enroll_token("usr_py").token.startswith("enr_"))
53
+
54
+
55
+ class Webhooks(unittest.TestCase):
56
+ def test_verify(self):
57
+ s = SignOps("sk_test_x", webhook_secret="whsec_test")
58
+ body = json.dumps({"id": "evt_1", "type": "push.sent", "data": {}})
59
+ t = int(time.time())
60
+ header = f"t={t},v1={hmac.new(b'whsec_test', f'{t}.{body}'.encode(), hashlib.sha256).hexdigest()}"
61
+ self.assertEqual(s.webhooks.verify(body, header).type, "push.sent")
62
+ self.assertEqual(s.webhooks.verify(body.encode(), header)["id"], "evt_1")
63
+ with self.assertRaises(SignOpsError):
64
+ s.webhooks.verify(body + " ", header)
65
+ with self.assertRaises(SignOpsError):
66
+ s.webhooks.verify(body, f"t={t - 600},v1=00")
67
+
68
+ def test_publishable_key_refused(self):
69
+ with self.assertRaises(ValueError):
70
+ SignOps("pk_test_x")
71
+
72
+
73
+ if __name__ == "__main__":
74
+ unittest.main()