setsig-sdk 1.0.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.
setsig/__init__.py ADDED
@@ -0,0 +1,71 @@
1
+ """setsig Python SDK."""
2
+
3
+ from .client import Setsig
4
+ from .crypto import compute_signature, verify_signature
5
+ from .errors import (
6
+ AuthenticationError,
7
+ GeofenceOutOfBoundsError,
8
+ InsufficientCreditsError,
9
+ PaywallBlockedError,
10
+ CrossBorderCreditRequiredError,
11
+ PaywallTierRequiredError,
12
+ AttestationFailedError,
13
+ VisualProofRequiredError,
14
+ StaleVisualProofError,
15
+ InvalidImageHashError,
16
+ RateLimitError,
17
+ ReplayAttackError,
18
+ SetsigError,
19
+ SignatureVerificationError,
20
+ )
21
+ from .types import (
22
+ BillingBalance,
23
+ CreateVenueRequest,
24
+ EstimateCostRequest,
25
+ EstimateCostResponse,
26
+ GenerateTokenRequest,
27
+ GenerateTokenResponse,
28
+ TokenFormat,
29
+ UpdateVenueRequest,
30
+ Venue,
31
+ VerifySessionRequest,
32
+ VerifySessionResponse,
33
+ VisualProofSummary,
34
+ WebhookEvent,
35
+ )
36
+ from .webhooks import Webhooks
37
+
38
+ __all__ = [
39
+ "Setsig",
40
+ "Webhooks",
41
+ "compute_signature",
42
+ "verify_signature",
43
+ "SetsigError",
44
+ "AuthenticationError",
45
+ "InsufficientCreditsError",
46
+ "PaywallBlockedError",
47
+ "CrossBorderCreditRequiredError",
48
+ "PaywallTierRequiredError",
49
+ "AttestationFailedError",
50
+ "VisualProofRequiredError",
51
+ "StaleVisualProofError",
52
+ "InvalidImageHashError",
53
+ "ReplayAttackError",
54
+ "GeofenceOutOfBoundsError",
55
+ "RateLimitError",
56
+ "SignatureVerificationError",
57
+ "TokenFormat",
58
+ "GenerateTokenRequest",
59
+ "GenerateTokenResponse",
60
+ "VerifySessionRequest",
61
+ "VerifySessionResponse",
62
+ "VisualProofSummary",
63
+ "Venue",
64
+ "CreateVenueRequest",
65
+ "UpdateVenueRequest",
66
+ "BillingBalance",
67
+ "EstimateCostRequest",
68
+ "EstimateCostResponse",
69
+ "WebhookEvent",
70
+ ]
71
+
setsig/client.py ADDED
@@ -0,0 +1,555 @@
1
+ """setsig client implementation using standard library HTTP transport."""
2
+
3
+ import json
4
+ import random
5
+ import time
6
+ import urllib.error
7
+ import urllib.request
8
+ from typing import Any, Dict, List, Optional, Union
9
+
10
+ from .errors import (
11
+ AuthenticationError,
12
+ GeofenceOutOfBoundsError,
13
+ InsufficientCreditsError,
14
+ PaywallBlockedError,
15
+ CrossBorderCreditRequiredError,
16
+ PaywallTierRequiredError,
17
+ AttestationFailedError,
18
+ VisualProofRequiredError,
19
+ StaleVisualProofError,
20
+ InvalidImageHashError,
21
+ RateLimitError,
22
+ ReplayAttackError,
23
+ SetsigError,
24
+ )
25
+ from .types import (
26
+ BillingBalance,
27
+ EstimateCostResponse,
28
+ GenerateTokenResponse,
29
+ TerminalSessionResponse,
30
+ TokenFormat,
31
+ Venue,
32
+ VerifySessionResponse,
33
+ VisualProofPayload,
34
+ VisualProofSummary,
35
+ )
36
+ from .webhooks import Webhooks
37
+
38
+ DEFAULT_BASE_URL = "https://api.setsig.com"
39
+ DEFAULT_TIMEOUT = 15.0
40
+ DEFAULT_MAX_RETRIES = 3
41
+ SDK_VERSION = "0.8.0"
42
+
43
+
44
+ class _HTTPClient:
45
+ """Internal HTTP client with automatic retries and exponential backoff."""
46
+
47
+ def __init__(
48
+ self,
49
+ api_key: str,
50
+ base_url: str = DEFAULT_BASE_URL,
51
+ timeout: float = DEFAULT_TIMEOUT,
52
+ max_retries: int = DEFAULT_MAX_RETRIES,
53
+ ):
54
+ self.api_key = api_key
55
+ self.base_url = base_url.rstrip("/")
56
+ self.timeout = timeout
57
+ self.max_retries = max(0, max_retries)
58
+
59
+ def request(
60
+ self,
61
+ method: str,
62
+ path: str,
63
+ body: Optional[Dict[str, Any]] = None,
64
+ idempotency_key: Optional[str] = None,
65
+ ) -> Dict[str, Any]:
66
+ url = f"{self.base_url}{path}"
67
+ data_bytes = json.dumps(body).encode("utf-8") if body is not None else None
68
+
69
+ backoff = 0.2
70
+ last_error: Optional[Exception] = None
71
+
72
+ for attempt in range(self.max_retries + 1):
73
+ if attempt > 0:
74
+ jitter = random.uniform(0.0, 0.1)
75
+ time.sleep(backoff + jitter)
76
+ backoff *= 2
77
+
78
+ req = urllib.request.Request(url, data=data_bytes, method=method)
79
+ req.add_header("Authorization", f"Bearer {self.api_key}")
80
+ req.add_header("Content-Type", "application/json")
81
+ req.add_header("Accept", "application/json")
82
+ req.add_header("User-Agent", f"setsig-python/{SDK_VERSION}")
83
+ req.add_header("X-Setsig-Client", f"sdk-python/{SDK_VERSION}")
84
+ if idempotency_key:
85
+ req.add_header("Idempotency-Key", idempotency_key)
86
+
87
+ try:
88
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
89
+ resp_body = resp.read()
90
+ if not resp_body:
91
+ return {}
92
+ return json.loads(resp_body.decode("utf-8"))
93
+ except urllib.error.HTTPError as exc:
94
+ raw_err = exc.read().decode("utf-8")
95
+ err_dict = {}
96
+ try:
97
+ err_dict = json.loads(raw_err)
98
+ except Exception:
99
+ pass
100
+
101
+ err_msg = err_dict.get("message") or err_dict.get("error") or exc.reason
102
+ code = err_dict.get("code")
103
+ status = exc.code
104
+
105
+ if status == 429:
106
+ retry_after_hdr = exc.headers.get("Retry-After")
107
+ retry_after = int(retry_after_hdr) if retry_after_hdr and retry_after_hdr.isdigit() else None
108
+ rate_err = RateLimitError(
109
+ message=err_msg,
110
+ status_code=status,
111
+ retry_after=retry_after,
112
+ code=code,
113
+ )
114
+ last_error = rate_err
115
+ if attempt < self.max_retries:
116
+ if retry_after:
117
+ backoff = float(retry_after)
118
+ continue
119
+ raise rate_err
120
+
121
+ if status >= 500 and attempt < self.max_retries:
122
+ last_error = SetsigError(
123
+ message=err_msg,
124
+ status_code=status,
125
+ code=code,
126
+ body=err_dict,
127
+ )
128
+ continue
129
+
130
+ if code == "ERR_PAYWALL_BLOCKED":
131
+ raise PaywallBlockedError(message=err_msg, status_code=status, code=code, body=err_dict)
132
+ if code == "ERR_CROSS_BORDER_CREDIT_REQUIRED":
133
+ raise CrossBorderCreditRequiredError(message=err_msg, status_code=status, code=code, body=err_dict)
134
+ if code == "ERR_PAYWALL_TIER_REQUIRED":
135
+ raise PaywallTierRequiredError(message=err_msg, status_code=status, code=code, body=err_dict)
136
+ if code == "ERR_ATTESTATION_FAILED":
137
+ raise AttestationFailedError(message=err_msg, status_code=status, code=code, body=err_dict)
138
+ if code == "ERR_VISUAL_PROOF_REQUIRED":
139
+ raise VisualProofRequiredError(message=err_msg, status_code=status, code=code, body=err_dict)
140
+ if code == "ERR_STALE_VISUAL_PROOF":
141
+ raise StaleVisualProofError(message=err_msg, status_code=status, code=code, body=err_dict)
142
+ if code == "ERR_INVALID_IMAGE_HASH":
143
+ raise InvalidImageHashError(message=err_msg, status_code=status, code=code, body=err_dict)
144
+
145
+ if status in (401, 403):
146
+ raise AuthenticationError(
147
+ message=err_msg,
148
+ status_code=status,
149
+ code=code,
150
+ body=err_dict,
151
+ )
152
+ if status == 402:
153
+ raise InsufficientCreditsError(
154
+ message=err_msg,
155
+ status_code=status,
156
+ code=code,
157
+ body=err_dict,
158
+ )
159
+ if status == 409 and (code == "DOUBLE_SPEND_REPLAY_ATTACK" or "replay" in err_msg.lower()):
160
+ raise ReplayAttackError(
161
+ message=err_msg,
162
+ status_code=status,
163
+ code=code,
164
+ body=err_dict,
165
+ )
166
+ if status == 422 and ("geofence" in err_msg.lower() or "distance" in err_msg.lower()):
167
+ raise GeofenceOutOfBoundsError(
168
+ message=err_msg,
169
+ status_code=status,
170
+ code=code,
171
+ body=err_dict,
172
+ )
173
+
174
+ raise SetsigError(
175
+ message=err_msg,
176
+ status_code=status,
177
+ code=code,
178
+ body=err_dict,
179
+ )
180
+ except urllib.error.URLError as exc:
181
+ last_error = exc
182
+ continue
183
+
184
+ if last_error:
185
+ if isinstance(last_error, SetsigError):
186
+ raise last_error
187
+ raise SetsigError(f"Network error: {last_error}")
188
+ raise SetsigError("Request failed after retries")
189
+
190
+
191
+ class TokensResource:
192
+ """Manages dynamic presence TOTP tokens."""
193
+
194
+ def __init__(self, http_client: _HTTPClient):
195
+ self._http = http_client
196
+
197
+ def generate(
198
+ self,
199
+ venue_id: str,
200
+ ttl: int = 60,
201
+ format: Union[TokenFormat, str] = TokenFormat.RAW,
202
+ metadata: Optional[Dict[str, str]] = None,
203
+ idempotency_key: Optional[str] = None,
204
+ ) -> GenerateTokenResponse:
205
+ fmt_val = format.value if isinstance(format, TokenFormat) else format
206
+ payload: Dict[str, Any] = {
207
+ "venue_id": venue_id,
208
+ "ttl": ttl,
209
+ "format": fmt_val,
210
+ }
211
+ if metadata:
212
+ payload["metadata"] = metadata
213
+
214
+ res = self._http.request(
215
+ "POST",
216
+ "/v1/tokens/generate",
217
+ body=payload,
218
+ idempotency_key=idempotency_key,
219
+ )
220
+ data = res.get("data", res)
221
+ return GenerateTokenResponse(
222
+ token_id=data["token_id"],
223
+ venue_id=data["venue_id"],
224
+ dynamic_code=data["dynamic_code"],
225
+ expires_at=data["expires_at"],
226
+ payload=data["payload"],
227
+ qr_data_url=data.get("qr_data_url"),
228
+ qr_svg=data.get("qr_svg"),
229
+ )
230
+
231
+
232
+ class SessionsResource:
233
+ """Manages physical presence verification sessions."""
234
+
235
+ def __init__(self, http_client: _HTTPClient):
236
+ self._http = http_client
237
+
238
+ def verify(
239
+ self,
240
+ venue_id: str,
241
+ token_id: str,
242
+ client_token: str,
243
+ latitude: float,
244
+ longitude: float,
245
+ accuracy: float,
246
+ altitude: Optional[float] = None,
247
+ speed: Optional[float] = None,
248
+ heading: Optional[float] = None,
249
+ attestation_token: Optional[str] = None,
250
+ visual_proof_token: Optional[str] = None,
251
+ client_ip: Optional[str] = None,
252
+ idempotency_key: Optional[str] = None,
253
+ ) -> VerifySessionResponse:
254
+ payload: Dict[str, Any] = {
255
+ "venue_id": venue_id,
256
+ "token_id": token_id,
257
+ "client_token": client_token,
258
+ "latitude": latitude,
259
+ "longitude": longitude,
260
+ "accuracy": accuracy,
261
+ }
262
+ if altitude is not None:
263
+ payload["altitude"] = altitude
264
+ if speed is not None:
265
+ payload["speed"] = speed
266
+ if heading is not None:
267
+ payload["heading"] = heading
268
+ if attestation_token is not None:
269
+ payload["attestation_token"] = attestation_token
270
+ if visual_proof_token is not None:
271
+ payload["visual_proof_token"] = visual_proof_token
272
+ if client_ip is not None:
273
+ payload["client_ip"] = client_ip
274
+
275
+ res = self._http.request(
276
+ "POST",
277
+ "/v1/sessions/verify",
278
+ body=payload,
279
+ idempotency_key=idempotency_key,
280
+ )
281
+ data = res.get("data", res)
282
+
283
+ visual_proof = None
284
+ if data.get("visual_proof"):
285
+ vp = data["visual_proof"]
286
+ visual_proof = VisualProofSummary(
287
+ status=vp.get("status", "UNKNOWN"),
288
+ liveness_score=vp.get("liveness_score", 0.0),
289
+ visual_tamper_score=vp.get("visual_tamper_score", 0.0),
290
+ captured_at=vp.get("captured_at", ""),
291
+ storage_key=vp.get("storage_key"),
292
+ analysis_notes=vp.get("analysis_notes", []),
293
+ )
294
+
295
+ return VerifySessionResponse(
296
+ session_id=data["session_id"],
297
+ tenant_id=data["tenant_id"],
298
+ venue_id=data["venue_id"],
299
+ status=data["status"],
300
+ verified_at=data["verified_at"],
301
+ distance_meters=data["distance_meters"],
302
+ risk_score=data["risk_score"],
303
+ visual_proof=visual_proof,
304
+ claim_tokens=data.get("claim_tokens", []),
305
+ )
306
+
307
+ def get(self, session_id: str) -> VerifySessionResponse:
308
+ res = self._http.request("GET", f"/v1/sessions/{session_id}")
309
+ data = res.get("data", res)
310
+
311
+ visual_proof = None
312
+ if data.get("visual_proof"):
313
+ vp = data["visual_proof"]
314
+ visual_proof = VisualProofSummary(
315
+ status=vp.get("status", "UNKNOWN"),
316
+ liveness_score=vp.get("liveness_score", 0.0),
317
+ visual_tamper_score=vp.get("visual_tamper_score", 0.0),
318
+ captured_at=vp.get("captured_at", ""),
319
+ storage_key=vp.get("storage_key"),
320
+ analysis_notes=vp.get("analysis_notes", []),
321
+ )
322
+
323
+ return VerifySessionResponse(
324
+ session_id=data["session_id"],
325
+ tenant_id=data["tenant_id"],
326
+ venue_id=data["venue_id"],
327
+ status=data["status"],
328
+ verified_at=data["verified_at"],
329
+ distance_meters=data["distance_meters"],
330
+ risk_score=data["risk_score"],
331
+ visual_proof=visual_proof,
332
+ claim_tokens=data.get("claim_tokens", []),
333
+ )
334
+
335
+
336
+ class VenuesResource:
337
+ """Manages physical venues and geofence perimeters."""
338
+
339
+ def __init__(self, http_client: _HTTPClient):
340
+ self._http = http_client
341
+
342
+ def create(
343
+ self,
344
+ name: str,
345
+ latitude: float,
346
+ longitude: float,
347
+ radius_meters: float,
348
+ strict_attestation: bool = False,
349
+ strict_visual_proof: bool = False,
350
+ ) -> Venue:
351
+ payload = {
352
+ "name": name,
353
+ "latitude": latitude,
354
+ "longitude": longitude,
355
+ "radius_meters": radius_meters,
356
+ "strict_attestation": strict_attestation,
357
+ "strict_visual_proof": strict_visual_proof,
358
+ }
359
+ res = self._http.request("POST", "/v1/venues", body=payload)
360
+ data = res.get("data", res)
361
+ return Venue(
362
+ id=data["id"],
363
+ tenant_id=data["tenant_id"],
364
+ name=data["name"],
365
+ latitude=data["latitude"],
366
+ longitude=data["longitude"],
367
+ radius_meters=data["radius_meters"],
368
+ strict_attestation=data["strict_attestation"],
369
+ strict_visual_proof=data["strict_visual_proof"],
370
+ status=data["status"],
371
+ created_at=data["created_at"],
372
+ updated_at=data["updated_at"],
373
+ dynamic_seed_secret=data.get("dynamic_seed_secret"),
374
+ )
375
+
376
+ def get(self, venue_id: str) -> Venue:
377
+ res = self._http.request("GET", f"/v1/venues/{venue_id}")
378
+ data = res.get("data", res)
379
+ return Venue(
380
+ id=data["id"],
381
+ tenant_id=data["tenant_id"],
382
+ name=data["name"],
383
+ latitude=data["latitude"],
384
+ longitude=data["longitude"],
385
+ radius_meters=data["radius_meters"],
386
+ strict_attestation=data["strict_attestation"],
387
+ strict_visual_proof=data["strict_visual_proof"],
388
+ status=data["status"],
389
+ created_at=data["created_at"],
390
+ updated_at=data["updated_at"],
391
+ dynamic_seed_secret=data.get("dynamic_seed_secret"),
392
+ )
393
+
394
+ def list(self, limit: Optional[int] = None, offset: Optional[int] = None) -> List[Venue]:
395
+ params = []
396
+ if limit is not None:
397
+ params.append(f"limit={limit}")
398
+ if offset is not None:
399
+ params.append(f"offset={offset}")
400
+ query = f"?{'&'.join(params)}" if params else ""
401
+
402
+ res = self._http.request("GET", f"/v1/venues{query}")
403
+ data = res.get("data", res)
404
+ venues_raw = data.get("venues", data if isinstance(data, list) else [])
405
+ return [
406
+ Venue(
407
+ id=v["id"],
408
+ tenant_id=v["tenant_id"],
409
+ name=v["name"],
410
+ latitude=v["latitude"],
411
+ longitude=v["longitude"],
412
+ radius_meters=v["radius_meters"],
413
+ strict_attestation=v["strict_attestation"],
414
+ strict_visual_proof=v["strict_visual_proof"],
415
+ status=v["status"],
416
+ created_at=v["created_at"],
417
+ updated_at=v["updated_at"],
418
+ dynamic_seed_secret=v.get("dynamic_seed_secret"),
419
+ )
420
+ for v in venues_raw
421
+ ]
422
+
423
+ def update(
424
+ self,
425
+ venue_id: str,
426
+ name: Optional[str] = None,
427
+ radius_meters: Optional[float] = None,
428
+ strict_attestation: Optional[bool] = None,
429
+ strict_visual_proof: Optional[bool] = None,
430
+ ) -> Venue:
431
+ payload: Dict[str, Any] = {}
432
+ if name is not None:
433
+ payload["name"] = name
434
+ if radius_meters is not None:
435
+ payload["radius_meters"] = radius_meters
436
+ if strict_attestation is not None:
437
+ payload["strict_attestation"] = strict_attestation
438
+ if strict_visual_proof is not None:
439
+ payload["strict_visual_proof"] = strict_visual_proof
440
+
441
+ res = self._http.request("PATCH", f"/v1/venues/{venue_id}", body=payload)
442
+ data = res.get("data", res)
443
+ return Venue(
444
+ id=data["id"],
445
+ tenant_id=data["tenant_id"],
446
+ name=data["name"],
447
+ latitude=data["latitude"],
448
+ longitude=data["longitude"],
449
+ radius_meters=data["radius_meters"],
450
+ strict_attestation=data["strict_attestation"],
451
+ strict_visual_proof=data["strict_visual_proof"],
452
+ status=data["status"],
453
+ created_at=data["created_at"],
454
+ updated_at=data["updated_at"],
455
+ dynamic_seed_secret=data.get("dynamic_seed_secret"),
456
+ )
457
+
458
+ def rotate_secret(self, venue_id: str) -> Dict[str, Any]:
459
+ """Rotates cryptographic TOTP secret for a venue."""
460
+ res = self._http.request("POST", f"/v1/venues/{venue_id}/rotate-secret")
461
+ return res.get("data", res)
462
+
463
+ def delete(self, venue_id: str) -> None:
464
+ self._http.request("DELETE", f"/v1/venues/{venue_id}")
465
+
466
+
467
+ class TerminalsResource:
468
+ """Manages kiosk displays and Gatekeeper turnstile sessions."""
469
+
470
+ def __init__(self, http_client: _HTTPClient):
471
+ self._http = http_client
472
+
473
+ def create_session(self, terminal_key: str, venue_id: str) -> TerminalSessionResponse:
474
+ payload = {
475
+ "terminal_key": terminal_key,
476
+ "venue_id": venue_id,
477
+ }
478
+ res = self._http.request("POST", "/v1/terminals/session", body=payload)
479
+ data = res.get("data", res)
480
+ return TerminalSessionResponse(
481
+ status=data.get("status", "authenticated"),
482
+ terminal_session_token=data.get("terminal_session_token", ""),
483
+ venue_name=data.get("venue_name", "Turnstile Display"),
484
+ totp_interval_seconds=data.get("totp_interval_seconds", 60),
485
+ scope=data.get("scope", "tokens:generate_only"),
486
+ )
487
+
488
+
489
+ class BillingResource:
490
+ """Manages ledger balances and geo-cost estimates."""
491
+
492
+ def __init__(self, http_client: _HTTPClient):
493
+ self._http = http_client
494
+
495
+ def get_balance(self) -> BillingBalance:
496
+ res = self._http.request("GET", "/v1/billing/balance")
497
+ data = res.get("data", res)
498
+ return BillingBalance(
499
+ balance_credits=data["balance_credits"],
500
+ currency=data["currency"],
501
+ tier=data["tier"],
502
+ auto_topup=data["auto_topup"],
503
+ )
504
+
505
+ def estimate_cost(
506
+ self,
507
+ country_code: str,
508
+ strict_attestation: bool,
509
+ strict_visual_proof: bool,
510
+ quantity: int,
511
+ ) -> EstimateCostResponse:
512
+ payload = {
513
+ "country_code": country_code,
514
+ "strict_attestation": strict_attestation,
515
+ "strict_visual_proof": strict_visual_proof,
516
+ "quantity": quantity,
517
+ }
518
+ res = self._http.request("POST", "/v1/billing/estimate", body=payload)
519
+ data = res.get("data", res)
520
+ return EstimateCostResponse(
521
+ unit_cost_credits=data["unit_cost_credits"],
522
+ total_cost_credits=data["total_cost_credits"],
523
+ geo_multiplier=data["geo_multiplier"],
524
+ currency=data["currency"],
525
+ )
526
+
527
+
528
+ class Setsig:
529
+ """The primary client for setsig infrastructure."""
530
+
531
+ def __init__(
532
+ self,
533
+ api_key: str,
534
+ base_url: str = DEFAULT_BASE_URL,
535
+ timeout: float = DEFAULT_TIMEOUT,
536
+ max_retries: int = DEFAULT_MAX_RETRIES,
537
+ webhook_secret: Optional[str] = None,
538
+ ):
539
+ if not api_key:
540
+ raise AuthenticationError("API key must be provided")
541
+
542
+ self._http = _HTTPClient(
543
+ api_key=api_key,
544
+ base_url=base_url,
545
+ timeout=timeout,
546
+ max_retries=max_retries,
547
+ )
548
+
549
+ self.tokens = TokensResource(self._http)
550
+ self.sessions = SessionsResource(self._http)
551
+ self.venues = VenuesResource(self._http)
552
+ self.billing = BillingResource(self._http)
553
+ self.terminals = TerminalsResource(self._http)
554
+ self.webhooks = Webhooks(secret=webhook_secret)
555
+
setsig/crypto.py ADDED
@@ -0,0 +1,72 @@
1
+ """Timing-safe cryptographic utilities for setsig webhook verification."""
2
+
3
+ import hmac
4
+ import hashlib
5
+ import time
6
+ from typing import Tuple
7
+
8
+ from .errors import SignatureVerificationError
9
+
10
+
11
+ def compute_signature(payload: bytes, timestamp: int, secret: str) -> str:
12
+ """Computes the expected HMAC-SHA256 signature for a webhook payload."""
13
+ signed_payload = f"t={timestamp}.".encode("utf-8") + payload
14
+ mac = hmac.new(secret.encode("utf-8"), signed_payload, hashlib.sha256)
15
+ return mac.hexdigest()
16
+
17
+
18
+ def parse_header(header: str) -> Tuple[int, str]:
19
+ """Parses the X-Setsig-Signature header into (timestamp, signature)."""
20
+ if not header:
21
+ raise SignatureVerificationError("Missing X-Setsig-Signature header")
22
+
23
+ timestamp_str = None
24
+ signature = None
25
+
26
+ for item in header.split(","):
27
+ parts = item.strip().split("=", 1)
28
+ if len(parts) == 2:
29
+ key, value = parts[0].strip(), parts[1].strip()
30
+ if key == "t":
31
+ timestamp_str = value
32
+ elif key == "v1":
33
+ signature = value
34
+
35
+ if not timestamp_str or not signature:
36
+ raise SignatureVerificationError(
37
+ "Malformed signature header format; expected t=timestamp,v1=signature"
38
+ )
39
+
40
+ try:
41
+ timestamp = int(timestamp_str)
42
+ except ValueError as exc:
43
+ raise SignatureVerificationError("Invalid timestamp in signature header") from exc
44
+
45
+ return timestamp, signature
46
+
47
+
48
+ def verify_signature(
49
+ payload: bytes,
50
+ header: str,
51
+ secret: str,
52
+ tolerance: float = 300.0,
53
+ ) -> None:
54
+ """
55
+ Validates the authenticity of an incoming setsig webhook payload.
56
+
57
+ Uses `hmac.compare_digest` to protect against side-channel timing attacks.
58
+ Raises `SignatureVerificationError` if the signature is invalid or timestamp is outside tolerance.
59
+ """
60
+ timestamp, received_signature = parse_header(header)
61
+
62
+ current_time = time.time()
63
+ if abs(current_time - timestamp) > tolerance:
64
+ raise SignatureVerificationError(
65
+ f"Webhook timestamp expired or in future. Drift: {abs(current_time - timestamp):.1f}s > {tolerance}s"
66
+ )
67
+
68
+ expected_signature = compute_signature(payload, timestamp, secret)
69
+
70
+ if not hmac.compare_digest(expected_signature, received_signature):
71
+ raise SignatureVerificationError("Webhook signature verification failed")
72
+
setsig/errors.py ADDED
@@ -0,0 +1,108 @@
1
+ """Exception hierarchy for the setsig Python SDK."""
2
+
3
+ from typing import Optional, Any, Dict
4
+
5
+
6
+ class SetsigError(Exception):
7
+ """Base exception for all setsig errors."""
8
+
9
+ def __init__(
10
+ self,
11
+ message: str,
12
+ status_code: Optional[int] = None,
13
+ code: Optional[str] = None,
14
+ body: Optional[Dict[str, Any]] = None,
15
+ ):
16
+ super().__init__(message)
17
+ self.message = message
18
+ self.status_code = status_code
19
+ self.code = code
20
+ self.body = body
21
+
22
+ def __str__(self) -> str:
23
+ if self.status_code and self.code:
24
+ return f"SetsigError (HTTP {self.status_code} - {self.code}): {self.message}"
25
+ if self.status_code:
26
+ return f"SetsigError (HTTP {self.status_code}): {self.message}"
27
+ return f"SetsigError: {self.message}"
28
+
29
+
30
+ class AuthenticationError(SetsigError):
31
+ """Raised when authentication fails due to invalid or missing API key (HTTP 401/403)."""
32
+
33
+
34
+ class InsufficientCreditsError(SetsigError):
35
+ """Raised when account credit balance is depleted (HTTP 402)."""
36
+
37
+
38
+ class PaywallBlockedError(SetsigError):
39
+ """Raised when verification services are locked due to zero/depleted prepaid balance (HTTP 402)."""
40
+
41
+ def __init__(
42
+ self,
43
+ message: str = "Verification services locked due to depleted prepaid balance",
44
+ status_code: int = 402,
45
+ code: str = "ERR_PAYWALL_BLOCKED",
46
+ body: Optional[Dict[str, Any]] = None,
47
+ ):
48
+ super().__init__(message, status_code=status_code, code=code, body=body)
49
+ details = (body or {}).get("details", {})
50
+ self.paywall_url: Optional[str] = details.get("paywall_url")
51
+ self.current_balance: Optional[float] = details.get("current_balance")
52
+ self.required_min_topup: Optional[float] = details.get("required_min_topup")
53
+ self.currency: Optional[str] = details.get("currency")
54
+
55
+
56
+ class CrossBorderCreditRequiredError(SetsigError):
57
+ """Raised when verifying at an international venue without local currency or FX buffer (HTTP 402)."""
58
+
59
+
60
+ class PaywallTierRequiredError(SetsigError):
61
+ """Raised when requested feature requires a higher tier plan or subscription (HTTP 403)."""
62
+
63
+
64
+ class AttestationFailedError(SetsigError):
65
+ """Raised when hardware attestation fails due to rooted device or emulator (HTTP 403)."""
66
+
67
+
68
+ class VisualProofRequiredError(SetsigError):
69
+ """Raised when venue policy mandates photographic proof of presence (HTTP 422)."""
70
+
71
+
72
+ class StaleVisualProofError(SetsigError):
73
+ """Raised when photo timestamp exceeds 10-second cryptographic tolerance (HTTP 400)."""
74
+
75
+
76
+ class InvalidImageHashError(SetsigError):
77
+ """Raised when photo SHA-256 hash does not match uploaded cloud image (HTTP 400)."""
78
+
79
+
80
+ class ReplayAttackError(SetsigError):
81
+ """Raised when a dynamic token or client device token is reused / double-spent (HTTP 409)."""
82
+
83
+
84
+ class GeofenceOutOfBoundsError(SetsigError):
85
+ """Raised when physical client telemetry fails venue perimeter constraints (HTTP 422)."""
86
+
87
+
88
+ class RateLimitError(SetsigError):
89
+ """Raised when requests exceed configured tenant rate limits (HTTP 429)."""
90
+
91
+ def __init__(
92
+ self,
93
+ message: str,
94
+ status_code: int = 429,
95
+ retry_after: Optional[int] = None,
96
+ code: Optional[str] = None,
97
+ ):
98
+ super().__init__(message, status_code=status_code, code=code)
99
+ self.retry_after = retry_after
100
+
101
+ def __str__(self) -> str:
102
+ if self.retry_after:
103
+ return f"RateLimitError: Rate limit exceeded. Retry after {self.retry_after}s: {self.message}"
104
+ return f"RateLimitError: {self.message}"
105
+
106
+
107
+ class SignatureVerificationError(SetsigError):
108
+ """Raised when webhook signature verification fails or timestamp expired."""
setsig/types.py ADDED
@@ -0,0 +1,175 @@
1
+ """Data models and type definitions for setsig Python SDK."""
2
+
3
+ from dataclasses import dataclass, field
4
+ from enum import Enum
5
+ from typing import Any, Dict, List, Optional
6
+
7
+
8
+ class TokenFormat(str, Enum):
9
+ RAW = "raw"
10
+ DATA_URL = "data_url"
11
+ SVG = "svg"
12
+
13
+
14
+ @dataclass
15
+ class GenerateTokenRequest:
16
+ venue_id: str
17
+ ttl: int = 60
18
+ format: TokenFormat = TokenFormat.RAW
19
+ metadata: Optional[Dict[str, str]] = None
20
+
21
+
22
+ @dataclass
23
+ class GenerateTokenResponse:
24
+ token_id: str
25
+ venue_id: str
26
+ dynamic_code: str
27
+ expires_at: str
28
+ payload: str
29
+ qr_data_url: Optional[str] = None
30
+ qr_svg: Optional[str] = None
31
+
32
+
33
+ @dataclass
34
+ class VisualProofPayload:
35
+ image_hash_sha256: str
36
+ storage_key: str
37
+ captured_at: str
38
+ liveness_score: Optional[float] = None
39
+
40
+
41
+ @dataclass
42
+ class VerifySessionRequest:
43
+ venue_id: str
44
+ token_id: str
45
+ client_token: str
46
+ latitude: float
47
+ longitude: float
48
+ accuracy: float
49
+ altitude: Optional[float] = None
50
+ speed: Optional[float] = None
51
+ heading: Optional[float] = None
52
+ attestation_token: Optional[str] = None
53
+ visual_proof_token: Optional[str] = None
54
+ visual_proof: Optional[VisualProofPayload] = None
55
+ client_ip: Optional[str] = None
56
+
57
+
58
+ @dataclass
59
+ class VisualProofSummary:
60
+ status: str
61
+ liveness_score: float
62
+ visual_tamper_score: float
63
+ captured_at: str
64
+ storage_key: Optional[str] = None
65
+ analysis_notes: List[str] = field(default_factory=list)
66
+
67
+
68
+ @dataclass
69
+ class VerifySessionResponse:
70
+ session_id: str
71
+ tenant_id: str
72
+ venue_id: str
73
+ status: str
74
+ verified_at: str
75
+ distance_meters: float
76
+ risk_score: float
77
+ visual_proof: Optional[VisualProofSummary] = None
78
+ claim_tokens: List[str] = field(default_factory=list)
79
+
80
+
81
+ @dataclass
82
+ class Venue:
83
+ id: str
84
+ tenant_id: str
85
+ name: str
86
+ latitude: float
87
+ longitude: float
88
+ radius_meters: float
89
+ strict_attestation: bool
90
+ strict_visual_proof: bool
91
+ status: str
92
+ created_at: str
93
+ updated_at: str
94
+ reference_id: Optional[str] = None
95
+ country_code: Optional[str] = None
96
+ hardware_profile: Optional[str] = None
97
+ hardware_config: Optional[Dict[str, Any]] = None
98
+ visual_proof_prompt: Optional[str] = None
99
+ dynamic_seed_secret: Optional[str] = None
100
+
101
+
102
+ @dataclass
103
+ class CreateVenueRequest:
104
+ name: str
105
+ latitude: float
106
+ longitude: float
107
+ radius_meters: float
108
+ reference_id: Optional[str] = None
109
+ country_code: Optional[str] = None
110
+ hardware_profile: Optional[str] = None
111
+ hardware_config: Optional[Dict[str, Any]] = None
112
+ strict_attestation: bool = False
113
+ strict_visual_proof: bool = False
114
+ visual_proof_prompt: Optional[str] = None
115
+
116
+
117
+ @dataclass
118
+ class UpdateVenueRequest:
119
+ name: Optional[str] = None
120
+ reference_id: Optional[str] = None
121
+ country_code: Optional[str] = None
122
+ radius_meters: Optional[float] = None
123
+ hardware_profile: Optional[str] = None
124
+ hardware_config: Optional[Dict[str, Any]] = None
125
+ strict_attestation: Optional[bool] = None
126
+ strict_visual_proof: Optional[bool] = None
127
+ visual_proof_prompt: Optional[str] = None
128
+
129
+
130
+ @dataclass
131
+ class TerminalSessionRequest:
132
+ terminal_key: str
133
+ venue_id: str
134
+
135
+
136
+ @dataclass
137
+ class TerminalSessionResponse:
138
+ status: str
139
+ terminal_session_token: str
140
+ venue_name: str
141
+ totp_interval_seconds: int
142
+ scope: str
143
+
144
+
145
+ @dataclass
146
+ class BillingBalance:
147
+ balance_credits: int
148
+ currency: str
149
+ tier: str
150
+ auto_topup: bool
151
+
152
+
153
+ @dataclass
154
+ class EstimateCostRequest:
155
+ country_code: str
156
+ strict_attestation: bool
157
+ strict_visual_proof: bool
158
+ quantity: int
159
+
160
+
161
+ @dataclass
162
+ class EstimateCostResponse:
163
+ unit_cost_credits: int
164
+ total_cost_credits: int
165
+ geo_multiplier: float
166
+ currency: str
167
+
168
+
169
+ @dataclass
170
+ class WebhookEvent:
171
+ id: str
172
+ event: str
173
+ timestamp: int
174
+ data: Dict[str, Any]
175
+
setsig/webhooks.py ADDED
@@ -0,0 +1,88 @@
1
+ """Webhook event construction and framework helpers."""
2
+
3
+ import json
4
+ from typing import Any, Callable, Optional, Union
5
+
6
+ from .crypto import verify_signature
7
+ from .errors import SignatureVerificationError
8
+ from .types import WebhookEvent
9
+
10
+
11
+ class Webhooks:
12
+ """Namespace for webhook cryptographic verification and event parsing."""
13
+
14
+ def __init__(self, secret: Optional[str] = None):
15
+ self.secret = secret
16
+
17
+ def construct_event(
18
+ self,
19
+ payload: Union[bytes, str],
20
+ header: str,
21
+ secret: Optional[str] = None,
22
+ tolerance: float = 300.0,
23
+ ) -> WebhookEvent:
24
+ """
25
+ Parses and cryptographically verifies an incoming setsig webhook.
26
+
27
+ Args:
28
+ payload: Raw request body as bytes or string.
29
+ header: Value of X-Setsig-Signature header.
30
+ secret: Webhook signing secret (falls back to client configured secret).
31
+ tolerance: Maximum permissible clock drift in seconds (default: 300s).
32
+
33
+ Returns:
34
+ Validated WebhookEvent instance.
35
+ """
36
+ signing_secret = secret or self.secret
37
+ if not signing_secret:
38
+ raise SignatureVerificationError("Webhook secret must be provided")
39
+
40
+ payload_bytes = payload.encode("utf-8") if isinstance(payload, str) else payload
41
+
42
+ verify_signature(payload_bytes, header, signing_secret, tolerance=tolerance)
43
+
44
+ try:
45
+ data = json.loads(payload_bytes.decode("utf-8"))
46
+ except Exception as exc:
47
+ raise SignatureVerificationError(f"Failed to decode webhook JSON: {exc}") from exc
48
+
49
+ return WebhookEvent(
50
+ id=data.get("id", ""),
51
+ event=data.get("event", ""),
52
+ timestamp=data.get("timestamp", 0),
53
+ data=data.get("data", {}),
54
+ )
55
+
56
+
57
+ def create_flask_webhook_view(
58
+ secret: str,
59
+ event_handler: Callable[[WebhookEvent], Any],
60
+ tolerance: float = 300.0,
61
+ ):
62
+ """
63
+ Creates a Flask-compatible view function for setsig webhooks.
64
+ """
65
+ try:
66
+ from flask import request, jsonify, abort # type: ignore
67
+ except ImportError:
68
+ raise ImportError("Flask is not installed. Install with `pip install flask`")
69
+
70
+ webhooks = Webhooks(secret=secret)
71
+
72
+ def view():
73
+ header = request.headers.get("X-Setsig-Signature")
74
+ if not header:
75
+ abort(400, "Missing X-Setsig-Signature header")
76
+
77
+ try:
78
+ event = webhooks.construct_event(
79
+ request.get_data(), header, tolerance=tolerance
80
+ )
81
+ except SignatureVerificationError as exc:
82
+ abort(401, str(exc))
83
+
84
+ result = event_handler(event)
85
+ return jsonify({"received": True, "result": result}), 200
86
+
87
+ return view
88
+
@@ -0,0 +1,145 @@
1
+ Metadata-Version: 2.4
2
+ Name: setsig-sdk
3
+ Version: 1.0.0
4
+ Summary: Official Python SDK for setsig.com, Proof of Physical Presence and Verification Infrastructure
5
+ Author-email: setsig Developer Relations <dev@setsig.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://setsig.com
8
+ Project-URL: Documentation, https://setsig.com/docs
9
+ Project-URL: Repository, https://github.com/setsig/setsig-python
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Security :: Cryptography
18
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Dynamic: license-file
23
+
24
+ # setsig-python
25
+
26
+ Official Python SDK for [setsig.com](https://setsig.com) — Physical Presence & Verification Infrastructure-as-a-Service (PaaS/IaaS).
27
+
28
+ [![PyPI version](https://badge.fury.io/py/setsig.svg)](https://badge.fury.io/py/setsig)
29
+ [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)
30
+
31
+ Zero external dependencies! Built natively using the Python standard library (`urllib.request`, `hmac`, `hashlib`, `dataclasses`).
32
+
33
+ ---
34
+
35
+ ## Installation
36
+
37
+ ```bash
38
+ pip install setsig-sdk
39
+ ```
40
+
41
+ Requirements: Python 3.10 or newer.
42
+
43
+ ---
44
+
45
+ ## Quickstart
46
+
47
+ ### 1. Initialize Client
48
+
49
+ ```python
50
+ from setsig import Setsig, TokenFormat
51
+
52
+ client = Setsig(
53
+ api_key="sk_live_...",
54
+ timeout=10.0,
55
+ max_retries=3,
56
+ )
57
+
58
+ # Generate a dynamic presence QR token for your venue
59
+ token = client.tokens.generate(
60
+ venue_id="ven_ist_headquarters",
61
+ ttl=60,
62
+ format=TokenFormat.SVG,
63
+ idempotency_key="idemp_tok_001",
64
+ )
65
+
66
+ print(f"Dynamic Token Generated: {token.dynamic_code} (Expires: {token.expires_at})")
67
+ ```
68
+
69
+ ---
70
+
71
+ ### 2. Verify Session (Telemetric Presence & Attestation)
72
+
73
+ ```python
74
+ from setsig import (
75
+ Setsig,
76
+ ReplayAttackError,
77
+ GeofenceOutOfBoundsError,
78
+ InsufficientCreditsError,
79
+ )
80
+
81
+ try:
82
+ result = client.sessions.verify(
83
+ venue_id="ven_ist_headquarters",
84
+ token_id=token.token_id,
85
+ client_token="device_bound_token_...",
86
+ latitude=41.0082,
87
+ longitude=28.9784,
88
+ accuracy=4.2,
89
+ attestation_token="hardware_attest_jwt_...",
90
+ visual_proof_token="vpt_...",
91
+ )
92
+ print(f"Verified! Distance: {result.distance_meters}m, Risk: {result.risk_score}")
93
+ except ReplayAttackError as e:
94
+ print(f"Security Alert: Double-spend / Replay detected: {e}")
95
+ except GeofenceOutOfBoundsError as e:
96
+ print(f"Boundary Alert: User outside geofence perimeter: {e}")
97
+ except InsufficientCreditsError as e:
98
+ print(f"Billing Alert: Credits exhausted: {e}")
99
+ ```
100
+
101
+ ---
102
+
103
+ ### 3. Verify Incoming Webhooks (Timing-Safe Comparison)
104
+
105
+ Cryptographic replay resistance and timing attack mitigation:
106
+
107
+ ```python
108
+ from setsig import Webhooks, SignatureVerificationError
109
+
110
+ webhooks = Webhooks(secret="whsec_...")
111
+
112
+ # Inside your FastAPI / Flask / Django request handler:
113
+ try:
114
+ event = webhooks.construct_event(
115
+ payload=raw_request_body_bytes,
116
+ header=request.headers.get("X-Setsig-Signature"),
117
+ tolerance=300.0, # 5 minutes
118
+ )
119
+
120
+ if event.event == "session.verified":
121
+ print(f"Session {event.data['session_id']} verified physically!")
122
+ elif event.event == "venue.anomaly_detected":
123
+ print(f"Venue alert: {event.data}")
124
+
125
+ except SignatureVerificationError as exc:
126
+ # 401 Unauthorized
127
+ print(f"Tampered webhook rejected: {exc}")
128
+ ```
129
+
130
+ ---
131
+
132
+ ## Features
133
+
134
+ - **Zero External Dependencies:** No bloat, pure Python standard library.
135
+ - **Timing-Safe Cryptography:** Signature verification uses `hmac.compare_digest` to defend against timing side-channel attacks.
136
+ - **Automatic Retries & Exponential Backoff with Jitter:** Handles 429 Rate Limits and 5xx network interruptions gracefully.
137
+ - **Idempotency Keys:** Supports `idempotency_key` parameter to prevent accidental duplicate token generation or double-charges.
138
+ - **Typed Error Hierarchy:** Clean exceptions matching the setsig error model (`AuthenticationError`, `ReplayAttackError`, `GeofenceOutOfBoundsError`, `InsufficientCreditsError`, `RateLimitError`).
139
+
140
+ ---
141
+
142
+ ## License
143
+
144
+ Apache-2.0 License. Commercial verification engine intellectual property held by AVCI Ventures.
145
+
@@ -0,0 +1,11 @@
1
+ setsig/__init__.py,sha256=KRPW36-K3Myd9GZ1GnF7gktv2M5xhPN1IJQVDX_GUoc,1686
2
+ setsig/client.py,sha256=rEde4p32F71NHnSBMdd8-uqwj8BRmTYc6SRKOk8TSU4,20122
3
+ setsig/crypto.py,sha256=ncVuGxzqZ6QXcIYTmzFAYo05ZNO-FmCYdfVbtI_sUAw,2380
4
+ setsig/errors.py,sha256=HnRpi__mFX3xjV9PmwPy3fvLZT8maqEqG8T0CaMHNJw,3771
5
+ setsig/types.py,sha256=IaxA6AINOcPraGz4eerIgwWK8xvm4hLyqu-mMEE72Qc,3854
6
+ setsig/webhooks.py,sha256=6Ye1hciDp6NcU-ZtTPy9oeAWnI7LhgCgENqjNDc619Q,2749
7
+ setsig_sdk-1.0.0.dist-info/licenses/LICENSE,sha256=kHuu_fpgy-8FSBqlKsFZflnryyEOOk37PfTtYX046iE,721
8
+ setsig_sdk-1.0.0.dist-info/METADATA,sha256=l_hXaWjQmQDsi-uatQO77saQOXyELKNVBi0qjh5sMG8,4518
9
+ setsig_sdk-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ setsig_sdk-1.0.0.dist-info/top_level.txt,sha256=MwcOWiEpyVOHg_QZB6Uqrx3TqWP_WXOqSY8m0wg6aM4,7
11
+ setsig_sdk-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,17 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ Copyright 2026 setsig (AVCI Ventures)
6
+
7
+ Licensed under the Apache License, Version 2.0 (the "License");
8
+ you may not use this file except in compliance with the License.
9
+ You may obtain a copy of the License at
10
+
11
+ http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ Unless required by applicable law or agreed to in writing, software
14
+ distributed under the License is distributed on an "AS IS" BASIS,
15
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ See the License for the specific language governing permissions and
17
+ limitations under the License.
@@ -0,0 +1 @@
1
+ setsig