datapi-selfheal 0.3.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.
- datapi_selfheal-0.3.0.dist-info/METADATA +313 -0
- datapi_selfheal-0.3.0.dist-info/RECORD +35 -0
- datapi_selfheal-0.3.0.dist-info/WHEEL +5 -0
- datapi_selfheal-0.3.0.dist-info/entry_points.txt +3 -0
- datapi_selfheal-0.3.0.dist-info/licenses/LICENSE +21 -0
- datapi_selfheal-0.3.0.dist-info/top_level.txt +3 -0
- selfheal_api/__init__.py +106 -0
- selfheal_api/_sandbox_exec.py +124 -0
- selfheal_api/autoheal.py +658 -0
- selfheal_api/billing.py +738 -0
- selfheal_api/cli.py +958 -0
- selfheal_api/dashboard.py +1094 -0
- selfheal_api/eval_fixtures.py +39 -0
- selfheal_api/github_app.py +1050 -0
- selfheal_api/github_jwt.py +145 -0
- selfheal_api/ledger.py +305 -0
- selfheal_api/metrics.py +259 -0
- selfheal_api/middleware.py +297 -0
- selfheal_api/modelgen.py +333 -0
- selfheal_api/notifier.py +426 -0
- selfheal_api/remediation.py +277 -0
- selfheal_api/replay.py +126 -0
- selfheal_api/sandbox.py +157 -0
- selfheal_api/server.py +1480 -0
- selfheal_api/server_hosted.py +1656 -0
- selfheal_api/specwatch.py +203 -0
- selfheal_api/worker.py +212 -0
- sentinel/__init__.py +33 -0
- sentinel/detector.py +626 -0
- sentinel/guard.py +345 -0
- sentinel/llm_fallback.py +256 -0
- synthesizer/__init__.py +31 -0
- synthesizer/openapi_emitter.py +181 -0
- synthesizer/patcher.py +944 -0
- synthesizer/zod_emitter.py +336 -0
selfheal_api/billing.py
ADDED
|
@@ -0,0 +1,738 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import hmac
|
|
5
|
+
import json
|
|
6
|
+
import sqlite3
|
|
7
|
+
import threading
|
|
8
|
+
import time
|
|
9
|
+
import urllib.error
|
|
10
|
+
import urllib.parse
|
|
11
|
+
import urllib.request
|
|
12
|
+
from enum import StrEnum
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from pydantic import BaseModel, ConfigDict
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class PlanTier(StrEnum):
|
|
20
|
+
FREE = "free"
|
|
21
|
+
PRO = "pro"
|
|
22
|
+
TEAM = "team"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class PlanLimits(BaseModel):
|
|
26
|
+
model_config = ConfigDict(frozen=True)
|
|
27
|
+
|
|
28
|
+
max_requests_per_minute: int
|
|
29
|
+
max_llm_calls: int
|
|
30
|
+
max_models: int
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
PLAN_CATALOG: dict[PlanTier, PlanLimits] = {
|
|
34
|
+
PlanTier.FREE: PlanLimits(
|
|
35
|
+
max_requests_per_minute=30,
|
|
36
|
+
max_llm_calls=10,
|
|
37
|
+
max_models=3,
|
|
38
|
+
),
|
|
39
|
+
PlanTier.PRO: PlanLimits(
|
|
40
|
+
max_requests_per_minute=120,
|
|
41
|
+
max_llm_calls=200,
|
|
42
|
+
max_models=25,
|
|
43
|
+
),
|
|
44
|
+
PlanTier.TEAM: PlanLimits(
|
|
45
|
+
max_requests_per_minute=600,
|
|
46
|
+
max_llm_calls=2000,
|
|
47
|
+
max_models=200,
|
|
48
|
+
),
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class SubscriptionState(BaseModel):
|
|
53
|
+
org_id: str
|
|
54
|
+
plan: PlanTier = PlanTier.FREE
|
|
55
|
+
status: str = "active"
|
|
56
|
+
stripe_customer_id: str | None = None
|
|
57
|
+
stripe_subscription_id: str | None = None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def verify_stripe_signature(
|
|
61
|
+
secret: str,
|
|
62
|
+
payload: bytes,
|
|
63
|
+
sig_header: str,
|
|
64
|
+
*,
|
|
65
|
+
tolerance_s: int = 300,
|
|
66
|
+
now: int | None = None,
|
|
67
|
+
) -> bool:
|
|
68
|
+
"""Verify Stripe `Stripe-Signature` header (`t=<ts>,v1=<hex>`) with replay protection."""
|
|
69
|
+
if not secret or not sig_header or tolerance_s < 0:
|
|
70
|
+
return False
|
|
71
|
+
|
|
72
|
+
timestamp: int | None = None
|
|
73
|
+
v1_signatures: list[str] = []
|
|
74
|
+
|
|
75
|
+
for part in sig_header.split(","):
|
|
76
|
+
item = part.strip()
|
|
77
|
+
if "=" not in item:
|
|
78
|
+
continue
|
|
79
|
+
key, value = item.split("=", 1)
|
|
80
|
+
key = key.strip()
|
|
81
|
+
value = value.strip()
|
|
82
|
+
if key == "t":
|
|
83
|
+
try:
|
|
84
|
+
timestamp = int(value)
|
|
85
|
+
except ValueError:
|
|
86
|
+
return False
|
|
87
|
+
elif key == "v1" and value:
|
|
88
|
+
v1_signatures.append(value.lower())
|
|
89
|
+
|
|
90
|
+
if timestamp is None or not v1_signatures:
|
|
91
|
+
return False
|
|
92
|
+
|
|
93
|
+
current_ts = int(time.time()) if now is None else now
|
|
94
|
+
if abs(current_ts - timestamp) > tolerance_s:
|
|
95
|
+
return False
|
|
96
|
+
|
|
97
|
+
signed_payload = f"{timestamp}.".encode() + payload
|
|
98
|
+
expected = hmac.new(
|
|
99
|
+
secret.encode("utf-8"),
|
|
100
|
+
signed_payload,
|
|
101
|
+
hashlib.sha256,
|
|
102
|
+
).hexdigest()
|
|
103
|
+
|
|
104
|
+
return any(hmac.compare_digest(expected, sig) for sig in v1_signatures)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class BillingStore:
|
|
108
|
+
"""Thread-safe SQLite-backed store for per-org subscriptions and Stripe event deduplication."""
|
|
109
|
+
|
|
110
|
+
_MAX_PROCESSED_EVENTS = 10_000
|
|
111
|
+
|
|
112
|
+
def __init__(
|
|
113
|
+
self,
|
|
114
|
+
db_path: str | Path = ":memory:",
|
|
115
|
+
*,
|
|
116
|
+
max_processed_events: int = _MAX_PROCESSED_EVENTS,
|
|
117
|
+
max_events: int | None = None,
|
|
118
|
+
) -> None:
|
|
119
|
+
resolved_max = max_events if max_events is not None else max_processed_events
|
|
120
|
+
if resolved_max < 1:
|
|
121
|
+
raise ValueError("max_processed_events must be >= 1")
|
|
122
|
+
|
|
123
|
+
resolved_path = str(db_path)
|
|
124
|
+
if resolved_path != ":memory:" and not resolved_path.startswith("file:"):
|
|
125
|
+
Path(resolved_path).parent.mkdir(parents=True, exist_ok=True)
|
|
126
|
+
|
|
127
|
+
self._lock = threading.Lock()
|
|
128
|
+
self._closed = False
|
|
129
|
+
self._max_events = resolved_max
|
|
130
|
+
self._conn = sqlite3.connect(resolved_path, check_same_thread=False)
|
|
131
|
+
self._initialize_schema()
|
|
132
|
+
|
|
133
|
+
def _initialize_schema(self) -> None:
|
|
134
|
+
with self._lock:
|
|
135
|
+
self._conn.execute("PRAGMA busy_timeout=5000;")
|
|
136
|
+
self._conn.execute("PRAGMA journal_mode=WAL")
|
|
137
|
+
self._conn.execute(
|
|
138
|
+
"""
|
|
139
|
+
CREATE TABLE IF NOT EXISTS subscriptions (
|
|
140
|
+
org_id TEXT PRIMARY KEY,
|
|
141
|
+
tier TEXT NOT NULL,
|
|
142
|
+
status TEXT NOT NULL,
|
|
143
|
+
stripe_customer_id TEXT,
|
|
144
|
+
stripe_subscription_id TEXT,
|
|
145
|
+
updated_at REAL NOT NULL
|
|
146
|
+
)
|
|
147
|
+
"""
|
|
148
|
+
)
|
|
149
|
+
self._conn.execute(
|
|
150
|
+
"""
|
|
151
|
+
CREATE TABLE IF NOT EXISTS processed_events (
|
|
152
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
153
|
+
event_id TEXT NOT NULL UNIQUE
|
|
154
|
+
)
|
|
155
|
+
"""
|
|
156
|
+
)
|
|
157
|
+
self._conn.execute(
|
|
158
|
+
"""
|
|
159
|
+
CREATE TABLE IF NOT EXISTS customer_org_map (
|
|
160
|
+
customer_id TEXT PRIMARY KEY,
|
|
161
|
+
org_id TEXT NOT NULL
|
|
162
|
+
)
|
|
163
|
+
"""
|
|
164
|
+
)
|
|
165
|
+
self._conn.execute(
|
|
166
|
+
"""
|
|
167
|
+
CREATE TABLE IF NOT EXISTS event_watermarks (
|
|
168
|
+
scope_key TEXT PRIMARY KEY,
|
|
169
|
+
created_ts INTEGER NOT NULL
|
|
170
|
+
)
|
|
171
|
+
"""
|
|
172
|
+
)
|
|
173
|
+
self._conn.commit()
|
|
174
|
+
|
|
175
|
+
def get_subscription(self, org_id: str) -> SubscriptionState:
|
|
176
|
+
with self._lock:
|
|
177
|
+
row = self._conn.execute(
|
|
178
|
+
"""
|
|
179
|
+
SELECT org_id, tier, status, stripe_customer_id, stripe_subscription_id
|
|
180
|
+
FROM subscriptions
|
|
181
|
+
WHERE org_id = ?
|
|
182
|
+
""",
|
|
183
|
+
(org_id,),
|
|
184
|
+
).fetchone()
|
|
185
|
+
if row is None:
|
|
186
|
+
return SubscriptionState(org_id=org_id)
|
|
187
|
+
return SubscriptionState(
|
|
188
|
+
org_id=str(row[0]),
|
|
189
|
+
plan=PlanTier(str(row[1])),
|
|
190
|
+
status=str(row[2]),
|
|
191
|
+
stripe_customer_id=str(row[3]) if row[3] is not None else None,
|
|
192
|
+
stripe_subscription_id=str(row[4]) if row[4] is not None else None,
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
def list_org_ids(self) -> list[str]:
|
|
196
|
+
with self._lock:
|
|
197
|
+
rows = self._conn.execute(
|
|
198
|
+
"SELECT org_id FROM subscriptions ORDER BY org_id ASC"
|
|
199
|
+
).fetchall()
|
|
200
|
+
return [str(row[0]) for row in rows]
|
|
201
|
+
|
|
202
|
+
def upsert_subscription(self, state: SubscriptionState) -> SubscriptionState:
|
|
203
|
+
now = time.time()
|
|
204
|
+
with self._lock:
|
|
205
|
+
self._conn.execute(
|
|
206
|
+
"""
|
|
207
|
+
INSERT INTO subscriptions (
|
|
208
|
+
org_id,
|
|
209
|
+
tier,
|
|
210
|
+
status,
|
|
211
|
+
stripe_customer_id,
|
|
212
|
+
stripe_subscription_id,
|
|
213
|
+
updated_at
|
|
214
|
+
) VALUES (?, ?, ?, ?, ?, ?)
|
|
215
|
+
ON CONFLICT(org_id) DO UPDATE SET
|
|
216
|
+
tier = excluded.tier,
|
|
217
|
+
status = excluded.status,
|
|
218
|
+
stripe_customer_id = excluded.stripe_customer_id,
|
|
219
|
+
stripe_subscription_id = excluded.stripe_subscription_id,
|
|
220
|
+
updated_at = excluded.updated_at
|
|
221
|
+
""",
|
|
222
|
+
(
|
|
223
|
+
state.org_id,
|
|
224
|
+
state.plan.value,
|
|
225
|
+
state.status,
|
|
226
|
+
state.stripe_customer_id,
|
|
227
|
+
state.stripe_subscription_id,
|
|
228
|
+
now,
|
|
229
|
+
),
|
|
230
|
+
)
|
|
231
|
+
if state.stripe_customer_id:
|
|
232
|
+
self._conn.execute(
|
|
233
|
+
"""
|
|
234
|
+
INSERT INTO customer_org_map (customer_id, org_id)
|
|
235
|
+
VALUES (?, ?)
|
|
236
|
+
ON CONFLICT(customer_id) DO UPDATE SET
|
|
237
|
+
org_id = excluded.org_id
|
|
238
|
+
""",
|
|
239
|
+
(state.stripe_customer_id, state.org_id),
|
|
240
|
+
)
|
|
241
|
+
self._conn.commit()
|
|
242
|
+
return state.model_copy()
|
|
243
|
+
|
|
244
|
+
def get_limits(self, org_id: str) -> PlanLimits:
|
|
245
|
+
sub = self.get_subscription(org_id)
|
|
246
|
+
if sub.status in {"canceled", "unpaid"}:
|
|
247
|
+
return PLAN_CATALOG[PlanTier.FREE]
|
|
248
|
+
return PLAN_CATALOG[sub.plan]
|
|
249
|
+
|
|
250
|
+
def find_org_by_stripe_ids(
|
|
251
|
+
self,
|
|
252
|
+
*,
|
|
253
|
+
customer_id: str | None = None,
|
|
254
|
+
subscription_id: str | None = None,
|
|
255
|
+
) -> str | None:
|
|
256
|
+
with self._lock:
|
|
257
|
+
if subscription_id:
|
|
258
|
+
row = self._conn.execute(
|
|
259
|
+
"""
|
|
260
|
+
SELECT org_id FROM subscriptions
|
|
261
|
+
WHERE stripe_subscription_id = ?
|
|
262
|
+
LIMIT 1
|
|
263
|
+
""",
|
|
264
|
+
(subscription_id,),
|
|
265
|
+
).fetchone()
|
|
266
|
+
if row is not None:
|
|
267
|
+
return str(row[0])
|
|
268
|
+
if customer_id:
|
|
269
|
+
row = self._conn.execute(
|
|
270
|
+
"""
|
|
271
|
+
SELECT org_id FROM subscriptions
|
|
272
|
+
WHERE stripe_customer_id = ?
|
|
273
|
+
LIMIT 1
|
|
274
|
+
""",
|
|
275
|
+
(customer_id,),
|
|
276
|
+
).fetchone()
|
|
277
|
+
if row is not None:
|
|
278
|
+
return str(row[0])
|
|
279
|
+
map_row = self._conn.execute(
|
|
280
|
+
"""
|
|
281
|
+
SELECT org_id FROM customer_org_map
|
|
282
|
+
WHERE customer_id = ?
|
|
283
|
+
LIMIT 1
|
|
284
|
+
""",
|
|
285
|
+
(customer_id,),
|
|
286
|
+
).fetchone()
|
|
287
|
+
if map_row is not None:
|
|
288
|
+
return str(map_row[0])
|
|
289
|
+
return None
|
|
290
|
+
|
|
291
|
+
def mark_event_processed(self, event_id: str) -> bool:
|
|
292
|
+
"""Record `event_id` if unseen. Returns True if new, False if duplicate."""
|
|
293
|
+
with self._lock:
|
|
294
|
+
cursor = self._conn.execute(
|
|
295
|
+
"INSERT OR IGNORE INTO processed_events (event_id) VALUES (?)",
|
|
296
|
+
(event_id,),
|
|
297
|
+
)
|
|
298
|
+
if cursor.rowcount == 0:
|
|
299
|
+
return False
|
|
300
|
+
self._conn.execute(
|
|
301
|
+
"""
|
|
302
|
+
DELETE FROM processed_events
|
|
303
|
+
WHERE seq NOT IN (
|
|
304
|
+
SELECT seq FROM processed_events
|
|
305
|
+
ORDER BY seq DESC
|
|
306
|
+
LIMIT ?
|
|
307
|
+
)
|
|
308
|
+
""",
|
|
309
|
+
(self._max_events,),
|
|
310
|
+
)
|
|
311
|
+
self._conn.commit()
|
|
312
|
+
return True
|
|
313
|
+
|
|
314
|
+
def is_event_processed(self, event_id: str) -> bool:
|
|
315
|
+
with self._lock:
|
|
316
|
+
row = self._conn.execute(
|
|
317
|
+
"SELECT 1 FROM processed_events WHERE event_id = ? LIMIT 1",
|
|
318
|
+
(event_id,),
|
|
319
|
+
).fetchone()
|
|
320
|
+
return row is not None
|
|
321
|
+
|
|
322
|
+
def is_stale_event(
|
|
323
|
+
self,
|
|
324
|
+
*,
|
|
325
|
+
org_id: str,
|
|
326
|
+
subscription_id: str | None = None,
|
|
327
|
+
created: int | None = None,
|
|
328
|
+
) -> bool:
|
|
329
|
+
"""Return True if a newer Stripe event timestamp has already been applied."""
|
|
330
|
+
if created is None:
|
|
331
|
+
return False
|
|
332
|
+
with self._lock:
|
|
333
|
+
org_row = self._conn.execute(
|
|
334
|
+
"SELECT created_ts FROM event_watermarks WHERE scope_key = ?",
|
|
335
|
+
(f"org:{org_id}",),
|
|
336
|
+
).fetchone()
|
|
337
|
+
if org_row is not None and created < int(org_row[0]):
|
|
338
|
+
return True
|
|
339
|
+
if subscription_id:
|
|
340
|
+
sub_row = self._conn.execute(
|
|
341
|
+
"SELECT created_ts FROM event_watermarks WHERE scope_key = ?",
|
|
342
|
+
(f"sub:{subscription_id}",),
|
|
343
|
+
).fetchone()
|
|
344
|
+
if sub_row is not None and created < int(sub_row[0]):
|
|
345
|
+
return True
|
|
346
|
+
return False
|
|
347
|
+
|
|
348
|
+
def record_event_created(
|
|
349
|
+
self,
|
|
350
|
+
*,
|
|
351
|
+
org_id: str,
|
|
352
|
+
subscription_id: str | None = None,
|
|
353
|
+
created: int | None = None,
|
|
354
|
+
) -> None:
|
|
355
|
+
"""Record the latest processed Stripe event `created` timestamp."""
|
|
356
|
+
if created is None:
|
|
357
|
+
return
|
|
358
|
+
with self._lock:
|
|
359
|
+
self._conn.execute(
|
|
360
|
+
"""
|
|
361
|
+
INSERT INTO event_watermarks (scope_key, created_ts)
|
|
362
|
+
VALUES (?, ?)
|
|
363
|
+
ON CONFLICT(scope_key) DO UPDATE SET
|
|
364
|
+
created_ts = MAX(event_watermarks.created_ts, excluded.created_ts)
|
|
365
|
+
""",
|
|
366
|
+
(f"org:{org_id}", created),
|
|
367
|
+
)
|
|
368
|
+
if subscription_id:
|
|
369
|
+
self._conn.execute(
|
|
370
|
+
"""
|
|
371
|
+
INSERT INTO event_watermarks (scope_key, created_ts)
|
|
372
|
+
VALUES (?, ?)
|
|
373
|
+
ON CONFLICT(scope_key) DO UPDATE SET
|
|
374
|
+
created_ts = MAX(event_watermarks.created_ts, excluded.created_ts)
|
|
375
|
+
""",
|
|
376
|
+
(f"sub:{subscription_id}", created),
|
|
377
|
+
)
|
|
378
|
+
self._conn.commit()
|
|
379
|
+
|
|
380
|
+
def ping(self) -> bool:
|
|
381
|
+
"""Check database connectivity, returning False if closed or on SQLite errors."""
|
|
382
|
+
with self._lock:
|
|
383
|
+
if self._closed:
|
|
384
|
+
return False
|
|
385
|
+
try:
|
|
386
|
+
self._conn.execute("SELECT 1").fetchone()
|
|
387
|
+
except sqlite3.Error:
|
|
388
|
+
return False
|
|
389
|
+
return True
|
|
390
|
+
|
|
391
|
+
def close(self) -> None:
|
|
392
|
+
"""Close the underlying SQLite connection."""
|
|
393
|
+
with self._lock:
|
|
394
|
+
if not self._closed:
|
|
395
|
+
self._conn.close()
|
|
396
|
+
self._closed = True
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def _parse_plan_tier(raw: Any) -> PlanTier | None:
|
|
400
|
+
if not isinstance(raw, str):
|
|
401
|
+
return None
|
|
402
|
+
normalized = raw.strip().lower()
|
|
403
|
+
try:
|
|
404
|
+
return PlanTier(normalized)
|
|
405
|
+
except ValueError:
|
|
406
|
+
return None
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _extract_org_id(data_obj: dict[str, Any], store: BillingStore) -> str | None:
|
|
410
|
+
metadata = data_obj.get("metadata")
|
|
411
|
+
if isinstance(metadata, dict):
|
|
412
|
+
raw_org = metadata.get("org_id")
|
|
413
|
+
if isinstance(raw_org, str) and raw_org.strip():
|
|
414
|
+
return raw_org.strip()
|
|
415
|
+
|
|
416
|
+
client_ref = data_obj.get("client_reference_id")
|
|
417
|
+
if isinstance(client_ref, str) and client_ref.strip():
|
|
418
|
+
return client_ref.strip()
|
|
419
|
+
|
|
420
|
+
customer_id = data_obj.get("customer") if isinstance(data_obj.get("customer"), str) else None
|
|
421
|
+
sub_id = data_obj.get("subscription")
|
|
422
|
+
if not isinstance(sub_id, str):
|
|
423
|
+
sub_id = data_obj.get("id") if isinstance(data_obj.get("id"), str) else None
|
|
424
|
+
|
|
425
|
+
return store.find_org_by_stripe_ids(customer_id=customer_id, subscription_id=sub_id)
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def _extract_plan_from_subscription(data_obj: dict[str, Any]) -> PlanTier | None:
|
|
429
|
+
metadata = data_obj.get("metadata")
|
|
430
|
+
if isinstance(metadata, dict):
|
|
431
|
+
plan = _parse_plan_tier(metadata.get("plan") or metadata.get("tier"))
|
|
432
|
+
if plan is not None:
|
|
433
|
+
return plan
|
|
434
|
+
|
|
435
|
+
items = data_obj.get("items")
|
|
436
|
+
if isinstance(items, dict):
|
|
437
|
+
item_list = items.get("data")
|
|
438
|
+
if isinstance(item_list, list) and item_list:
|
|
439
|
+
first_item = item_list[0]
|
|
440
|
+
if isinstance(first_item, dict):
|
|
441
|
+
price = first_item.get("price")
|
|
442
|
+
if isinstance(price, dict):
|
|
443
|
+
plan = _parse_plan_tier(price.get("lookup_key"))
|
|
444
|
+
if plan is not None:
|
|
445
|
+
return plan
|
|
446
|
+
price_meta = price.get("metadata")
|
|
447
|
+
if isinstance(price_meta, dict):
|
|
448
|
+
plan = _parse_plan_tier(price_meta.get("plan"))
|
|
449
|
+
if plan is not None:
|
|
450
|
+
return plan
|
|
451
|
+
return None
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def handle_stripe_webhook(
|
|
455
|
+
secret: str,
|
|
456
|
+
body: bytes,
|
|
457
|
+
sig_header: str,
|
|
458
|
+
store: BillingStore,
|
|
459
|
+
*,
|
|
460
|
+
now: int | None = None,
|
|
461
|
+
) -> tuple[int, dict[str, Any]]:
|
|
462
|
+
"""Verify, deduplicate, and apply Stripe billing webhook events."""
|
|
463
|
+
if not verify_stripe_signature(secret, body, sig_header, now=now):
|
|
464
|
+
return 401, {"error": "invalid_signature"}
|
|
465
|
+
|
|
466
|
+
try:
|
|
467
|
+
parsed = json.loads(body.decode("utf-8"))
|
|
468
|
+
except (UnicodeDecodeError, json.JSONDecodeError):
|
|
469
|
+
return 400, {"error": "invalid_json"}
|
|
470
|
+
|
|
471
|
+
if not isinstance(parsed, dict):
|
|
472
|
+
return 400, {"error": "invalid_payload"}
|
|
473
|
+
|
|
474
|
+
event_id = parsed.get("id")
|
|
475
|
+
event_type = parsed.get("type")
|
|
476
|
+
if (
|
|
477
|
+
not isinstance(event_id, str)
|
|
478
|
+
or not event_id
|
|
479
|
+
or not isinstance(event_type, str)
|
|
480
|
+
or not event_type
|
|
481
|
+
):
|
|
482
|
+
return 400, {"error": "missing_event_fields"}
|
|
483
|
+
|
|
484
|
+
if store.is_event_processed(event_id):
|
|
485
|
+
return 200, {"received": True, "duplicate": True, "event_id": event_id}
|
|
486
|
+
|
|
487
|
+
raw_created = parsed.get("created")
|
|
488
|
+
event_created = (
|
|
489
|
+
raw_created
|
|
490
|
+
if isinstance(raw_created, int) and not isinstance(raw_created, bool)
|
|
491
|
+
else None
|
|
492
|
+
)
|
|
493
|
+
|
|
494
|
+
data = parsed.get("data")
|
|
495
|
+
data_obj: dict[str, Any] = (
|
|
496
|
+
data.get("object", {}) if isinstance(data, dict) and isinstance(data.get("object"), dict)
|
|
497
|
+
else {}
|
|
498
|
+
)
|
|
499
|
+
|
|
500
|
+
if event_type == "checkout.session.completed":
|
|
501
|
+
org_id = _extract_org_id(data_obj, store)
|
|
502
|
+
if org_id is None:
|
|
503
|
+
return 400, {"error": "missing_org_id", "event_id": event_id, "retryable": True}
|
|
504
|
+
|
|
505
|
+
metadata = data_obj.get("metadata")
|
|
506
|
+
raw_plan = metadata.get("plan") if isinstance(metadata, dict) else None
|
|
507
|
+
plan = _parse_plan_tier(raw_plan) or PlanTier.PRO
|
|
508
|
+
|
|
509
|
+
customer_id = (
|
|
510
|
+
data_obj.get("customer")
|
|
511
|
+
if isinstance(data_obj.get("customer"), str)
|
|
512
|
+
else None
|
|
513
|
+
)
|
|
514
|
+
subscription_id = (
|
|
515
|
+
data_obj.get("subscription")
|
|
516
|
+
if isinstance(data_obj.get("subscription"), str)
|
|
517
|
+
else None
|
|
518
|
+
)
|
|
519
|
+
|
|
520
|
+
if not store.mark_event_processed(event_id):
|
|
521
|
+
return 200, {"received": True, "duplicate": True, "event_id": event_id}
|
|
522
|
+
if store.is_stale_event(
|
|
523
|
+
org_id=org_id, subscription_id=subscription_id, created=event_created
|
|
524
|
+
):
|
|
525
|
+
return 200, {
|
|
526
|
+
"received": True,
|
|
527
|
+
"ignored": True,
|
|
528
|
+
"stale": True,
|
|
529
|
+
"event_id": event_id,
|
|
530
|
+
"event_type": event_type,
|
|
531
|
+
"org_id": org_id,
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
updated = store.upsert_subscription(
|
|
535
|
+
SubscriptionState(
|
|
536
|
+
org_id=org_id,
|
|
537
|
+
plan=plan,
|
|
538
|
+
status="active",
|
|
539
|
+
stripe_customer_id=customer_id,
|
|
540
|
+
stripe_subscription_id=subscription_id,
|
|
541
|
+
)
|
|
542
|
+
)
|
|
543
|
+
store.record_event_created(
|
|
544
|
+
org_id=org_id, subscription_id=subscription_id, created=event_created
|
|
545
|
+
)
|
|
546
|
+
return 200, {
|
|
547
|
+
"received": True,
|
|
548
|
+
"event_id": event_id,
|
|
549
|
+
"event_type": event_type,
|
|
550
|
+
"org_id": updated.org_id,
|
|
551
|
+
"plan": updated.plan.value,
|
|
552
|
+
"status": updated.status,
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
if event_type == "customer.subscription.updated":
|
|
556
|
+
org_id = _extract_org_id(data_obj, store)
|
|
557
|
+
if org_id is None:
|
|
558
|
+
return 400, {"error": "missing_org_id", "event_id": event_id, "retryable": True}
|
|
559
|
+
|
|
560
|
+
current = store.get_subscription(org_id)
|
|
561
|
+
subscription_id = (
|
|
562
|
+
data_obj.get("id")
|
|
563
|
+
if isinstance(data_obj.get("id"), str)
|
|
564
|
+
else current.stripe_subscription_id
|
|
565
|
+
)
|
|
566
|
+
|
|
567
|
+
if not store.mark_event_processed(event_id):
|
|
568
|
+
return 200, {"received": True, "duplicate": True, "event_id": event_id}
|
|
569
|
+
if store.is_stale_event(
|
|
570
|
+
org_id=org_id, subscription_id=subscription_id, created=event_created
|
|
571
|
+
):
|
|
572
|
+
return 200, {
|
|
573
|
+
"received": True,
|
|
574
|
+
"ignored": True,
|
|
575
|
+
"stale": True,
|
|
576
|
+
"event_id": event_id,
|
|
577
|
+
"event_type": event_type,
|
|
578
|
+
"org_id": org_id,
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
parsed_plan = _extract_plan_from_subscription(data_obj)
|
|
582
|
+
new_plan = parsed_plan if parsed_plan is not None else current.plan
|
|
583
|
+
|
|
584
|
+
raw_status = data_obj.get("status")
|
|
585
|
+
new_status = raw_status if isinstance(raw_status, str) and raw_status else current.status
|
|
586
|
+
|
|
587
|
+
customer_id = (
|
|
588
|
+
data_obj.get("customer")
|
|
589
|
+
if isinstance(data_obj.get("customer"), str)
|
|
590
|
+
else current.stripe_customer_id
|
|
591
|
+
)
|
|
592
|
+
|
|
593
|
+
updated = store.upsert_subscription(
|
|
594
|
+
SubscriptionState(
|
|
595
|
+
org_id=org_id,
|
|
596
|
+
plan=new_plan,
|
|
597
|
+
status=new_status,
|
|
598
|
+
stripe_customer_id=customer_id,
|
|
599
|
+
stripe_subscription_id=subscription_id,
|
|
600
|
+
)
|
|
601
|
+
)
|
|
602
|
+
store.record_event_created(
|
|
603
|
+
org_id=org_id, subscription_id=subscription_id, created=event_created
|
|
604
|
+
)
|
|
605
|
+
return 200, {
|
|
606
|
+
"received": True,
|
|
607
|
+
"event_id": event_id,
|
|
608
|
+
"event_type": event_type,
|
|
609
|
+
"org_id": updated.org_id,
|
|
610
|
+
"plan": updated.plan.value,
|
|
611
|
+
"status": updated.status,
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
if event_type == "customer.subscription.deleted":
|
|
615
|
+
org_id = _extract_org_id(data_obj, store)
|
|
616
|
+
if org_id is None:
|
|
617
|
+
return 400, {"error": "missing_org_id", "event_id": event_id, "retryable": True}
|
|
618
|
+
|
|
619
|
+
current = store.get_subscription(org_id)
|
|
620
|
+
subscription_id = (
|
|
621
|
+
data_obj.get("id")
|
|
622
|
+
if isinstance(data_obj.get("id"), str)
|
|
623
|
+
else current.stripe_subscription_id
|
|
624
|
+
)
|
|
625
|
+
|
|
626
|
+
if not store.mark_event_processed(event_id):
|
|
627
|
+
return 200, {"received": True, "duplicate": True, "event_id": event_id}
|
|
628
|
+
if store.is_stale_event(
|
|
629
|
+
org_id=org_id, subscription_id=subscription_id, created=event_created
|
|
630
|
+
):
|
|
631
|
+
return 200, {
|
|
632
|
+
"received": True,
|
|
633
|
+
"ignored": True,
|
|
634
|
+
"stale": True,
|
|
635
|
+
"event_id": event_id,
|
|
636
|
+
"event_type": event_type,
|
|
637
|
+
"org_id": org_id,
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
customer_id = (
|
|
641
|
+
data_obj.get("customer")
|
|
642
|
+
if isinstance(data_obj.get("customer"), str)
|
|
643
|
+
else current.stripe_customer_id
|
|
644
|
+
)
|
|
645
|
+
|
|
646
|
+
updated = store.upsert_subscription(
|
|
647
|
+
SubscriptionState(
|
|
648
|
+
org_id=org_id,
|
|
649
|
+
plan=PlanTier.FREE,
|
|
650
|
+
status="canceled",
|
|
651
|
+
stripe_customer_id=customer_id,
|
|
652
|
+
stripe_subscription_id=subscription_id,
|
|
653
|
+
)
|
|
654
|
+
)
|
|
655
|
+
store.record_event_created(
|
|
656
|
+
org_id=org_id, subscription_id=subscription_id, created=event_created
|
|
657
|
+
)
|
|
658
|
+
return 200, {
|
|
659
|
+
"received": True,
|
|
660
|
+
"event_id": event_id,
|
|
661
|
+
"event_type": event_type,
|
|
662
|
+
"org_id": updated.org_id,
|
|
663
|
+
"plan": updated.plan.value,
|
|
664
|
+
"status": updated.status,
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
if not store.mark_event_processed(event_id):
|
|
668
|
+
return 200, {"received": True, "duplicate": True, "event_id": event_id}
|
|
669
|
+
return 200, {
|
|
670
|
+
"received": True,
|
|
671
|
+
"ignored": True,
|
|
672
|
+
"event_id": event_id,
|
|
673
|
+
"event_type": event_type,
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
|
|
677
|
+
class StripeAPIError(Exception):
|
|
678
|
+
"""Stripe API call failed (network or non-2xx response)."""
|
|
679
|
+
|
|
680
|
+
def __init__(self, message: str, status_code: int | None = None) -> None:
|
|
681
|
+
super().__init__(message)
|
|
682
|
+
self.status_code = status_code
|
|
683
|
+
|
|
684
|
+
|
|
685
|
+
class StripeAPI:
|
|
686
|
+
"""Minimal Stripe REST client (stdlib urllib, form-encoded POST).
|
|
687
|
+
|
|
688
|
+
Zero-runtime-dependency, consistent with the GitHubAppAuth posture.
|
|
689
|
+
"""
|
|
690
|
+
|
|
691
|
+
def __init__(
|
|
692
|
+
self,
|
|
693
|
+
secret_key: str,
|
|
694
|
+
api_base_url: str = "https://api.stripe.com",
|
|
695
|
+
timeout_seconds: float = 15.0,
|
|
696
|
+
allow_insecure_http: bool = False,
|
|
697
|
+
) -> None:
|
|
698
|
+
if not secret_key.strip():
|
|
699
|
+
raise ValueError("secret_key must be non-empty")
|
|
700
|
+
parsed = urllib.parse.urlparse(api_base_url)
|
|
701
|
+
if not allow_insecure_http and (
|
|
702
|
+
parsed.scheme != "https" or not parsed.netloc
|
|
703
|
+
):
|
|
704
|
+
raise ValueError("api_base_url must use https://")
|
|
705
|
+
self._secret_key = secret_key
|
|
706
|
+
self._api_base_url = api_base_url.rstrip("/")
|
|
707
|
+
self._timeout_seconds = timeout_seconds
|
|
708
|
+
|
|
709
|
+
def post_form(self, path: str, params: dict[str, str]) -> dict[str, Any]:
|
|
710
|
+
"""POST form-encoded params; returns the decoded JSON object."""
|
|
711
|
+
body = urllib.parse.urlencode(params).encode("utf-8")
|
|
712
|
+
req = urllib.request.Request(
|
|
713
|
+
f"{self._api_base_url}{path}",
|
|
714
|
+
data=body,
|
|
715
|
+
headers={
|
|
716
|
+
"Authorization": f"Bearer {self._secret_key}",
|
|
717
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
718
|
+
"Accept": "application/json",
|
|
719
|
+
},
|
|
720
|
+
method="POST",
|
|
721
|
+
)
|
|
722
|
+
try:
|
|
723
|
+
with urllib.request.urlopen(req, timeout=self._timeout_seconds) as resp:
|
|
724
|
+
raw = resp.read().decode("utf-8")
|
|
725
|
+
except urllib.error.HTTPError as exc:
|
|
726
|
+
detail = exc.read().decode("utf-8", errors="replace")[:300]
|
|
727
|
+
raise StripeAPIError(
|
|
728
|
+
f"Stripe API error {exc.code}: {detail}", status_code=exc.code
|
|
729
|
+
) from exc
|
|
730
|
+
except OSError as exc:
|
|
731
|
+
raise StripeAPIError(f"Stripe API unreachable: {exc}") from exc
|
|
732
|
+
try:
|
|
733
|
+
data: Any = json.loads(raw) if raw else {}
|
|
734
|
+
except json.JSONDecodeError as exc:
|
|
735
|
+
raise StripeAPIError("Stripe API returned invalid JSON") from exc
|
|
736
|
+
if not isinstance(data, dict):
|
|
737
|
+
raise StripeAPIError("Stripe API returned non-object JSON")
|
|
738
|
+
return data
|