u2auth 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- u2auth/__init__.py +23 -0
- u2auth/client.py +202 -0
- u2auth/helpers.py +114 -0
- u2auth/py.typed +0 -0
- u2auth/webhook.py +56 -0
- u2auth-0.1.0.dist-info/METADATA +125 -0
- u2auth-0.1.0.dist-info/RECORD +10 -0
- u2auth-0.1.0.dist-info/WHEEL +5 -0
- u2auth-0.1.0.dist-info/licenses/LICENSE +21 -0
- u2auth-0.1.0.dist-info/top_level.txt +1 -0
u2auth/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""U2Auth Python SDK."""
|
|
2
|
+
|
|
3
|
+
from .client import Client, U2AuthError
|
|
4
|
+
from .helpers import (
|
|
5
|
+
generate_secret,
|
|
6
|
+
generate_qr_code_uri,
|
|
7
|
+
generate_recovery_codes,
|
|
8
|
+
generate_totp,
|
|
9
|
+
validate_totp,
|
|
10
|
+
)
|
|
11
|
+
from .webhook import verify_webhook, WebhookEvent
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"Client",
|
|
15
|
+
"U2AuthError",
|
|
16
|
+
"generate_secret",
|
|
17
|
+
"generate_totp",
|
|
18
|
+
"validate_totp",
|
|
19
|
+
"generate_qr_code_uri",
|
|
20
|
+
"generate_recovery_codes",
|
|
21
|
+
"verify_webhook",
|
|
22
|
+
"WebhookEvent",
|
|
23
|
+
]
|
u2auth/client.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
"""U2Auth API client — sync, stdlib only."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import time
|
|
5
|
+
import urllib.error
|
|
6
|
+
import urllib.parse
|
|
7
|
+
import urllib.request
|
|
8
|
+
from typing import Any, Dict, Optional
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
_DEFAULT_BASE_URL = "https://app.u2secured.io"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class U2AuthError(Exception):
|
|
15
|
+
"""Raised when the U2Auth API returns a 4xx/5xx error."""
|
|
16
|
+
|
|
17
|
+
def __init__(self, status_code: int, code: str, message: str) -> None:
|
|
18
|
+
super().__init__(f"U2Auth API error {status_code} {code}: {message}")
|
|
19
|
+
self.status_code = status_code
|
|
20
|
+
self.code = code
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Client:
|
|
24
|
+
"""Synchronous U2Auth API client."""
|
|
25
|
+
|
|
26
|
+
def __init__(self, api_key: str, *, base_url: str = _DEFAULT_BASE_URL) -> None:
|
|
27
|
+
self._api_key = api_key
|
|
28
|
+
self._base_url = base_url.rstrip("/")
|
|
29
|
+
|
|
30
|
+
def verify_totp(self, secret: str, code: str) -> Dict[str, Any]:
|
|
31
|
+
"""Verify a TOTP code. Returns {'valid': bool}."""
|
|
32
|
+
return self._post("/api/v1/sdk/totp/verify", {"secret": secret, "code": code})
|
|
33
|
+
|
|
34
|
+
def request_push(
|
|
35
|
+
self,
|
|
36
|
+
user_identifier: str,
|
|
37
|
+
context: str,
|
|
38
|
+
*,
|
|
39
|
+
webhook_url: Optional[str] = None,
|
|
40
|
+
ttl: Optional[int] = None,
|
|
41
|
+
) -> Dict[str, Any]:
|
|
42
|
+
"""Create a push approval request. Returns {approval_id, status, expires_at}."""
|
|
43
|
+
body: Dict[str, Any] = {
|
|
44
|
+
"user_identifier": user_identifier,
|
|
45
|
+
"context": context,
|
|
46
|
+
}
|
|
47
|
+
if webhook_url is not None:
|
|
48
|
+
body["webhook_url"] = webhook_url
|
|
49
|
+
if ttl is not None:
|
|
50
|
+
body["ttl"] = ttl
|
|
51
|
+
return self._post("/api/v1/sdk/push/request", body)
|
|
52
|
+
|
|
53
|
+
def get_push_status(self, approval_id: str) -> Dict[str, Any]:
|
|
54
|
+
"""Get the status of a push approval request. Returns {approval_id, status}."""
|
|
55
|
+
return self._get(f"/api/v1/sdk/push/{approval_id}/status")
|
|
56
|
+
|
|
57
|
+
def wait_for_approval(
|
|
58
|
+
self, approval_id: str, timeout: float = 120, interval: float = 2
|
|
59
|
+
) -> Dict[str, Any]:
|
|
60
|
+
"""Poll get_push_status until the approval is no longer pending or timeout elapses."""
|
|
61
|
+
deadline = time.monotonic() + timeout
|
|
62
|
+
while True:
|
|
63
|
+
status = self.get_push_status(approval_id)
|
|
64
|
+
if status.get("status") != "pending":
|
|
65
|
+
return status
|
|
66
|
+
if time.monotonic() >= deadline:
|
|
67
|
+
raise U2AuthError(0, "WAIT_TIMEOUT", "timed out waiting for approval")
|
|
68
|
+
time.sleep(interval)
|
|
69
|
+
|
|
70
|
+
def create_pairing_code(self, user_identifier: str) -> Dict[str, Any]:
|
|
71
|
+
"""Mint a pairing code binding user_identifier — your own opaque id for
|
|
72
|
+
the user — to whichever account redeems it in the U2 Secured app. Pass
|
|
73
|
+
the same string to request_push afterwards.
|
|
74
|
+
|
|
75
|
+
Returns {'code', 'expires_at'}.
|
|
76
|
+
"""
|
|
77
|
+
return self._post(
|
|
78
|
+
"/api/v1/sdk/pairing-codes", {"user_identifier": user_identifier}
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
def delete_enrolment(self, user_identifier: str) -> None:
|
|
82
|
+
"""Remove the link between this app and user_identifier.
|
|
83
|
+
|
|
84
|
+
Raises U2AuthError with code 'ENROLMENT_NOT_FOUND' if there was none.
|
|
85
|
+
"""
|
|
86
|
+
query = urllib.parse.urlencode({"user_identifier": user_identifier})
|
|
87
|
+
self._delete(f"/api/v1/sdk/enrolments?{query}")
|
|
88
|
+
|
|
89
|
+
def list_enrolments(
|
|
90
|
+
self,
|
|
91
|
+
*,
|
|
92
|
+
limit: int = 25,
|
|
93
|
+
cursor: str = "",
|
|
94
|
+
sort: str = "created_at",
|
|
95
|
+
order: str = "desc",
|
|
96
|
+
) -> Dict[str, Any]:
|
|
97
|
+
"""List the enrolments for this app. The app is resolved from the
|
|
98
|
+
API key — there is no app_id parameter. limit <= 0 is treated as
|
|
99
|
+
unset and omitted from the query, same as an empty cursor.
|
|
100
|
+
|
|
101
|
+
cursor is opaque and bound to the sort/order that minted it — pass
|
|
102
|
+
it back verbatim on the next call. Replaying it under a different
|
|
103
|
+
sort/order raises U2AuthError with code 'INVALID_CURSOR'.
|
|
104
|
+
|
|
105
|
+
Raises U2AuthError with code 'INVALID_LIMIT' if limit is outside
|
|
106
|
+
1..100, or 'INVALID_SORT' for an unrecognised sort.
|
|
107
|
+
|
|
108
|
+
Returns {'items': [...], 'next_cursor': '...'}.
|
|
109
|
+
"""
|
|
110
|
+
params: Dict[str, Any] = {}
|
|
111
|
+
if limit > 0:
|
|
112
|
+
params["limit"] = limit
|
|
113
|
+
if cursor:
|
|
114
|
+
params["cursor"] = cursor
|
|
115
|
+
params["sort"] = sort
|
|
116
|
+
params["order"] = order
|
|
117
|
+
query = urllib.parse.urlencode(params)
|
|
118
|
+
return self._get(f"/api/v1/sdk/enrolments?{query}")
|
|
119
|
+
|
|
120
|
+
def list_enrolment_events(
|
|
121
|
+
self, enrolment_id: str, *, limit: int = 25, cursor: str = ""
|
|
122
|
+
) -> Dict[str, Any]:
|
|
123
|
+
"""List the authentication events recorded for one enrolment.
|
|
124
|
+
limit <= 0 is treated as unset and omitted from the query, same as
|
|
125
|
+
an empty cursor.
|
|
126
|
+
|
|
127
|
+
cursor is opaque; pass it back verbatim on the next call to page.
|
|
128
|
+
|
|
129
|
+
Raises U2AuthError with code 'ENROLMENT_NOT_FOUND' if there is no
|
|
130
|
+
such enrolment, 'INVALID_LIMIT' if limit is outside 1..100, or
|
|
131
|
+
'INVALID_CURSOR' if cursor is malformed or was minted for a
|
|
132
|
+
different enrolment.
|
|
133
|
+
|
|
134
|
+
Returns {'items': [...], 'next_cursor': '...'}.
|
|
135
|
+
"""
|
|
136
|
+
params: Dict[str, Any] = {}
|
|
137
|
+
if limit > 0:
|
|
138
|
+
params["limit"] = limit
|
|
139
|
+
if cursor:
|
|
140
|
+
params["cursor"] = cursor
|
|
141
|
+
query = urllib.parse.urlencode(params)
|
|
142
|
+
enrolment_path = urllib.parse.quote(enrolment_id, safe="")
|
|
143
|
+
path = f"/api/v1/sdk/enrolments/{enrolment_path}/events"
|
|
144
|
+
return self._get(f"{path}?{query}" if query else path)
|
|
145
|
+
|
|
146
|
+
def _post(self, path: str, body: Dict[str, Any]) -> Dict[str, Any]:
|
|
147
|
+
data = json.dumps(body).encode()
|
|
148
|
+
req = urllib.request.Request(
|
|
149
|
+
self._base_url + path,
|
|
150
|
+
data=data,
|
|
151
|
+
headers={
|
|
152
|
+
"Authorization": f"Bearer {self._api_key}",
|
|
153
|
+
"Content-Type": "application/json",
|
|
154
|
+
},
|
|
155
|
+
method="POST",
|
|
156
|
+
)
|
|
157
|
+
return self._send(req)
|
|
158
|
+
|
|
159
|
+
def _get(self, path: str) -> Dict[str, Any]:
|
|
160
|
+
req = urllib.request.Request(
|
|
161
|
+
self._base_url + path,
|
|
162
|
+
headers={"Authorization": f"Bearer {self._api_key}"},
|
|
163
|
+
method="GET",
|
|
164
|
+
)
|
|
165
|
+
return self._send(req)
|
|
166
|
+
|
|
167
|
+
def _delete(self, path: str) -> None:
|
|
168
|
+
"""DELETE with no response body. Separate from _send, which always
|
|
169
|
+
json-decodes — a 204 carries an empty body."""
|
|
170
|
+
req = urllib.request.Request(
|
|
171
|
+
self._base_url + path,
|
|
172
|
+
headers={"Authorization": f"Bearer {self._api_key}"},
|
|
173
|
+
method="DELETE",
|
|
174
|
+
)
|
|
175
|
+
try:
|
|
176
|
+
with urllib.request.urlopen(req):
|
|
177
|
+
return None
|
|
178
|
+
except urllib.error.HTTPError as exc:
|
|
179
|
+
body = exc.read()
|
|
180
|
+
try:
|
|
181
|
+
payload = json.loads(body)
|
|
182
|
+
err = payload.get("error", {})
|
|
183
|
+
code = err.get("code", "UNKNOWN")
|
|
184
|
+
message = err.get("message", "unknown error")
|
|
185
|
+
except (json.JSONDecodeError, AttributeError):
|
|
186
|
+
code, message = "UNKNOWN", body.decode(errors="replace")
|
|
187
|
+
raise U2AuthError(exc.code, code, message) from exc
|
|
188
|
+
|
|
189
|
+
def _send(self, req: urllib.request.Request) -> Dict[str, Any]:
|
|
190
|
+
try:
|
|
191
|
+
with urllib.request.urlopen(req) as resp:
|
|
192
|
+
return json.loads(resp.read())
|
|
193
|
+
except urllib.error.HTTPError as exc:
|
|
194
|
+
body = exc.read()
|
|
195
|
+
try:
|
|
196
|
+
payload = json.loads(body)
|
|
197
|
+
err = payload.get("error", {})
|
|
198
|
+
code = err.get("code", "UNKNOWN")
|
|
199
|
+
message = err.get("message", "unknown error")
|
|
200
|
+
except (json.JSONDecodeError, AttributeError):
|
|
201
|
+
code, message = "UNKNOWN", body.decode(errors="replace")
|
|
202
|
+
raise U2AuthError(exc.code, code, message) from exc
|
u2auth/helpers.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Local TOTP helpers — no network calls."""
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import hashlib
|
|
5
|
+
import hmac
|
|
6
|
+
import os
|
|
7
|
+
import secrets
|
|
8
|
+
import string
|
|
9
|
+
import struct
|
|
10
|
+
import time
|
|
11
|
+
from typing import Optional
|
|
12
|
+
from urllib.parse import urlencode, quote
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def generate_secret(byte_len: int = 20) -> str:
|
|
16
|
+
"""Generate a cryptographically random base32-encoded TOTP secret."""
|
|
17
|
+
raw = os.urandom(byte_len)
|
|
18
|
+
return base64.b32encode(raw).decode("ascii").rstrip("=")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def generate_qr_code_uri(
|
|
22
|
+
issuer: str,
|
|
23
|
+
account: str,
|
|
24
|
+
secret: str,
|
|
25
|
+
*,
|
|
26
|
+
algorithm: str = "SHA1",
|
|
27
|
+
digits: int = 6,
|
|
28
|
+
period: int = 30,
|
|
29
|
+
) -> str:
|
|
30
|
+
"""Build an otpauth://totp/... URI suitable for QR code display."""
|
|
31
|
+
label = f"{quote(issuer)}:{quote(account)}"
|
|
32
|
+
params = urlencode(
|
|
33
|
+
{
|
|
34
|
+
"secret": secret,
|
|
35
|
+
"issuer": issuer,
|
|
36
|
+
"algorithm": algorithm,
|
|
37
|
+
"digits": digits,
|
|
38
|
+
"period": period,
|
|
39
|
+
}
|
|
40
|
+
)
|
|
41
|
+
return f"otpauth://totp/{label}?{params}"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def generate_recovery_codes(count: int = 10) -> list[str]:
|
|
45
|
+
"""Generate count random 8-character alphanumeric recovery codes."""
|
|
46
|
+
charset = string.ascii_uppercase + string.digits
|
|
47
|
+
return [
|
|
48
|
+
"".join(secrets.choice(charset) for _ in range(8))
|
|
49
|
+
for _ in range(count)
|
|
50
|
+
]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _decode_totp_secret(secret: str) -> bytes:
|
|
54
|
+
"""Accept padded and unpadded base32, in either case."""
|
|
55
|
+
s = secret.strip().upper()
|
|
56
|
+
return base64.b32decode(s + "=" * (-len(s) % 8))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def generate_totp(
|
|
60
|
+
secret: str,
|
|
61
|
+
at: Optional[float] = None,
|
|
62
|
+
digits: int = 6,
|
|
63
|
+
period_sec: int = 30,
|
|
64
|
+
) -> str:
|
|
65
|
+
"""Compute the RFC 6238 code for a secret at a Unix instant.
|
|
66
|
+
|
|
67
|
+
Exposed mainly so tests can drive a fixed clock; most callers want
|
|
68
|
+
:func:`validate_totp`.
|
|
69
|
+
"""
|
|
70
|
+
at = time.time() if at is None else at
|
|
71
|
+
counter = int(at // period_sec)
|
|
72
|
+
mac = hmac.new(
|
|
73
|
+
_decode_totp_secret(secret), struct.pack(">Q", counter), hashlib.sha1
|
|
74
|
+
).digest()
|
|
75
|
+
offset = mac[-1] & 0x0F
|
|
76
|
+
truncated = struct.unpack(">I", mac[offset : offset + 4])[0] & 0x7FFFFFFF
|
|
77
|
+
return str(truncated % (10**digits)).zfill(digits)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def validate_totp(
|
|
81
|
+
secret: str,
|
|
82
|
+
code: str,
|
|
83
|
+
at: Optional[float] = None,
|
|
84
|
+
digits: int = 6,
|
|
85
|
+
period_sec: int = 30,
|
|
86
|
+
) -> bool:
|
|
87
|
+
"""Verify a TOTP code locally, without a network call.
|
|
88
|
+
|
|
89
|
+
Runs the same RFC 6238 check the U2 Secured Authenticator backend runs,
|
|
90
|
+
including the +/-1 window tolerance for clock drift, and returns the same
|
|
91
|
+
answer -- the shared vectors in ``sdk/testvectors/totp.json`` are asserted
|
|
92
|
+
against the backend's own implementation to keep the two from drifting.
|
|
93
|
+
Prefer this when a login must not depend on a third party being reachable:
|
|
94
|
+
the developer's backend already holds the secret, so no round trip is
|
|
95
|
+
required to check a code.
|
|
96
|
+
|
|
97
|
+
What it does NOT provide, and ``client.verify_totp()`` does:
|
|
98
|
+
|
|
99
|
+
* the shared brute-force lockout, which spans all your backend instances
|
|
100
|
+
* an entry in the Activity feed of the developer portal
|
|
101
|
+
|
|
102
|
+
Neither call protects against replay on its own -- a code stays valid for
|
|
103
|
+
its whole window. Bind a successful check to a single login attempt.
|
|
104
|
+
"""
|
|
105
|
+
at = time.time() if at is None else at
|
|
106
|
+
supplied = code.strip()
|
|
107
|
+
ok = False
|
|
108
|
+
for delta in (-1, 0, 1):
|
|
109
|
+
candidate = generate_totp(secret, at + delta * period_sec, digits, period_sec)
|
|
110
|
+
# Compare every window with no early return, so neither the matching
|
|
111
|
+
# window nor the number of correct digits leaks through timing.
|
|
112
|
+
if hmac.compare_digest(candidate, supplied):
|
|
113
|
+
ok = True
|
|
114
|
+
return ok
|
u2auth/py.typed
ADDED
|
File without changes
|
u2auth/webhook.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Webhook signature verification for RK Auth."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import hmac
|
|
4
|
+
import json
|
|
5
|
+
import time
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Optional, Union
|
|
8
|
+
|
|
9
|
+
from .client import U2AuthError
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class WebhookEvent:
|
|
14
|
+
approval_id: str
|
|
15
|
+
status: str
|
|
16
|
+
reason: Optional[str] = None
|
|
17
|
+
resolved_at: Optional[str] = None
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def verify_webhook(
|
|
21
|
+
payload: Union[bytes, str],
|
|
22
|
+
sig_header: str,
|
|
23
|
+
secret: str,
|
|
24
|
+
tolerance: int = 300,
|
|
25
|
+
) -> WebhookEvent:
|
|
26
|
+
"""Verify the X-U2Auth-Signature over the RAW payload; return the parsed event or raise U2AuthError."""
|
|
27
|
+
body = payload.decode("utf-8") if isinstance(payload, (bytes, bytearray)) else payload
|
|
28
|
+
t, v1 = _parse_sig_header(sig_header)
|
|
29
|
+
expected = hmac.new(secret.encode("utf-8"), f"{t}.{body}".encode("utf-8"), hashlib.sha256).hexdigest()
|
|
30
|
+
if not hmac.compare_digest(expected, v1):
|
|
31
|
+
raise U2AuthError(0, "INVALID_SIGNATURE", "invalid webhook signature")
|
|
32
|
+
if abs(int(time.time()) - t) > tolerance:
|
|
33
|
+
raise U2AuthError(0, "TIMESTAMP_OUT_OF_TOLERANCE", "webhook timestamp out of tolerance")
|
|
34
|
+
data = json.loads(body)
|
|
35
|
+
return WebhookEvent(
|
|
36
|
+
approval_id=data["approval_id"],
|
|
37
|
+
status=data["status"],
|
|
38
|
+
reason=data.get("reason"),
|
|
39
|
+
resolved_at=data.get("resolved_at"),
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _parse_sig_header(h: str):
|
|
44
|
+
t = None
|
|
45
|
+
v1 = None
|
|
46
|
+
for part in h.split(","):
|
|
47
|
+
kv = part.strip().split("=", 1)
|
|
48
|
+
if len(kv) != 2:
|
|
49
|
+
continue
|
|
50
|
+
if kv[0] == "t":
|
|
51
|
+
t = int(kv[1])
|
|
52
|
+
elif kv[0] == "v1":
|
|
53
|
+
v1 = kv[1]
|
|
54
|
+
if t is None or v1 is None:
|
|
55
|
+
raise U2AuthError(0, "INVALID_SIGNATURE", "malformed signature header")
|
|
56
|
+
return t, v1
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: u2auth
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: U2Auth SDK for Python — TOTP verification, push approvals, and local TOTP helpers
|
|
5
|
+
Author-email: DollarMates Dev <dev@dollarmates.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://auth.u2secured.com/developer/docs
|
|
8
|
+
Project-URL: Source, https://github.com/u2secured/u2auth
|
|
9
|
+
Project-URL: Issues, https://github.com/u2secured/u2auth/issues
|
|
10
|
+
Keywords: 2fa,mfa,totp,push,authentication,u2secured
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Security
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Provides-Extra: dev
|
|
18
|
+
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
19
|
+
Requires-Dist: build>=1.0; extra == "dev"
|
|
20
|
+
Requires-Dist: twine>=5.0; extra == "dev"
|
|
21
|
+
Dynamic: license-file
|
|
22
|
+
|
|
23
|
+
# u2auth
|
|
24
|
+
|
|
25
|
+
Python SDK for the U2Auth platform — TOTP verification, push approvals, and local TOTP helpers.
|
|
26
|
+
|
|
27
|
+
## Install
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install u2auth
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Quick Start
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from u2auth import Client, generate_secret, generate_qr_code_uri
|
|
37
|
+
|
|
38
|
+
client = Client("rka_your_api_key")
|
|
39
|
+
result = client.verify_totp("BASE32SECRET", "123456")
|
|
40
|
+
push = client.request_push("user@example.com", "Login from Chrome")
|
|
41
|
+
status = client.get_push_status(push["approval_id"])
|
|
42
|
+
secret = generate_secret()
|
|
43
|
+
uri = generate_qr_code_uri("MyApp", "user@example.com", secret)
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## API Reference
|
|
47
|
+
|
|
48
|
+
### `Client(api_key, *, base_url?)`
|
|
49
|
+
|
|
50
|
+
Sync API client. `base_url` defaults to `https://app.u2secured.io`.
|
|
51
|
+
|
|
52
|
+
### `client.verify_totp(secret, code) -> dict`
|
|
53
|
+
|
|
54
|
+
Calls `POST /api/v1/sdk/totp/verify`. Returns `{"valid": bool}`.
|
|
55
|
+
|
|
56
|
+
### `client.request_push(user_identifier, context, *, webhook_url?, ttl?) -> dict`
|
|
57
|
+
|
|
58
|
+
Calls `POST /api/v1/sdk/push/request`. Returns `{approval_id, status, expires_at}`.
|
|
59
|
+
|
|
60
|
+
`user_identifier` matching is case-sensitive and otherwise unnormalised — it's your own key into
|
|
61
|
+
your system, not ours, so folding case could silently merge two genuinely different users. Pass
|
|
62
|
+
the exact same string here as the one given to `create_pairing_code`. A mismatch (most often a
|
|
63
|
+
casing difference) raises `U2AuthError` with code `ENROLMENT_NOT_FOUND` — no enrolment at all for
|
|
64
|
+
that identifier — which is distinct from `NO_DEVICE` (enrolled, but no confirmed device yet).
|
|
65
|
+
|
|
66
|
+
### `client.get_push_status(approval_id) -> dict`
|
|
67
|
+
|
|
68
|
+
Calls `GET /api/v1/sdk/push/{id}/status`. Returns `{approval_id, status}`.
|
|
69
|
+
|
|
70
|
+
### `client.delete_enrolment(user_identifier) -> None`
|
|
71
|
+
|
|
72
|
+
Calls `DELETE /api/v1/sdk/enrolments`. Raises `U2AuthError` with code `ENROLMENT_NOT_FOUND` if there was none.
|
|
73
|
+
|
|
74
|
+
### `client.list_enrolments(*, limit=25, cursor="", sort="created_at", order="desc") -> dict`
|
|
75
|
+
|
|
76
|
+
Calls `GET /api/v1/sdk/enrolments`. The app is resolved from the API key — there is no `app_id` parameter. Returns `{"items": [...], "next_cursor": "..."}`.
|
|
77
|
+
|
|
78
|
+
`sort` is one of `"created_at"`, `"user_identifier"`, `"last_auth_at"`; `order` is `"asc"` or `"desc"`. `next_cursor` is opaque and bound to the `sort`/`order` that minted it — pass it back verbatim on the next call. Replaying it under a different `sort`/`order` raises `U2AuthError` with code `INVALID_CURSOR`. `limit <= 0` is treated as unset and omitted from the query, same as an empty `cursor`; a `limit` outside `1..100` raises code `INVALID_LIMIT`.
|
|
79
|
+
|
|
80
|
+
For an enrolment that has never authenticated, `last_auth_at` and `last_auth_outcome` are both `None` rather than a zero time / empty string.
|
|
81
|
+
|
|
82
|
+
### `client.list_enrolment_events(enrolment_id, *, limit=25, cursor="") -> dict`
|
|
83
|
+
|
|
84
|
+
Calls `GET /api/v1/sdk/enrolments/{enrolment_id}/events`. Returns `{"items": [...], "next_cursor": "..."}`.
|
|
85
|
+
|
|
86
|
+
`limit <= 0` is treated as unset and omitted from the query, same as an empty `cursor`. Raises `U2AuthError` with code `ENROLMENT_NOT_FOUND` if there is no such enrolment, `INVALID_LIMIT` if `limit` is outside `1..100`, or `INVALID_CURSOR` if `cursor` is malformed or was minted for a different enrolment. Each event's `place` is a coarse, city-level location (`{"city", "region", "country"}` — never a coordinate) or `None` when no fix was captured; `region` can legitimately be an empty string, which is distinct from a `None` place.
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
cursor = ""
|
|
90
|
+
while True:
|
|
91
|
+
page = client.list_enrolments(limit=50, cursor=cursor)
|
|
92
|
+
for enrolment in page["items"]:
|
|
93
|
+
print(enrolment["user_identifier"], enrolment["last_auth_at"])
|
|
94
|
+
if not page["next_cursor"]:
|
|
95
|
+
break
|
|
96
|
+
cursor = page["next_cursor"]
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### Helpers (no API call)
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
generate_secret(byte_len=20) -> str
|
|
103
|
+
generate_qr_code_uri(issuer, account, secret, *, algorithm="SHA1", digits=6, period=30) -> str
|
|
104
|
+
generate_recovery_codes(count=10) -> list[str]
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
### Error Handling
|
|
108
|
+
|
|
109
|
+
API errors raise `U2AuthError` with `.status_code` and `.code` attributes.
|
|
110
|
+
|
|
111
|
+
## Verifying webhooks
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
from u2auth import verify_webhook, U2AuthError
|
|
115
|
+
|
|
116
|
+
try:
|
|
117
|
+
event = verify_webhook(raw_body, request.headers["X-U2Auth-Signature"], webhook_secret)
|
|
118
|
+
except U2AuthError:
|
|
119
|
+
... # reject: bad signature or stale timestamp
|
|
120
|
+
# event.approval_id, event.status, event.reason, event.resolved_at
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Pass the **raw request body** (bytes/str), not a re-serialized dict. Handlers should dedupe on `event.approval_id`.
|
|
124
|
+
|
|
125
|
+
The push-request response includes `match_number` (the 2-digit number to show on your login page); `get_push_status` returns `status` plus `reason`/`resolved_at` once resolved.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
u2auth/__init__.py,sha256=tiTajnC3zjxD5TcCTLqUt4dfbr7eRnugfgCXF3QEskU,469
|
|
2
|
+
u2auth/client.py,sha256=GJjCtns8gyHu63T2rLuy6ahJ_LJ8jXEkIRx6COeUgac,7719
|
|
3
|
+
u2auth/helpers.py,sha256=yHg6V5o8rHUWgQ-TB07ztSr1Zq0XEzBawEF-H037chE,3621
|
|
4
|
+
u2auth/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
u2auth/webhook.py,sha256=i5y9fsaR3w2H3jLRUtRdTAQl2G9tHwQRPc4IhFhW6n4,1716
|
|
6
|
+
u2auth-0.1.0.dist-info/licenses/LICENSE,sha256=4PSfIgR896S-GpMq_hAIN2-hDOEd2OIDGqrKbnYmLDQ,1076
|
|
7
|
+
u2auth-0.1.0.dist-info/METADATA,sha256=axlURP-4gzLu8R-ZVPftla8hfxtq2PD_N6ZOnmSuNq0,5379
|
|
8
|
+
u2auth-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
9
|
+
u2auth-0.1.0.dist-info/top_level.txt,sha256=bTAZaEsnKAqfnlgtCo3i7cuV4Hi_d-6RRM9H8dWaOK0,7
|
|
10
|
+
u2auth-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 DollarMates Pty Ltd
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
u2auth
|