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.
@@ -0,0 +1,1656 @@
1
+ """Hosted control-plane routes (install flow, connect, billing, console).
2
+
3
+ Kept out of ``server.py`` per ARCH-1: all EXP-6..EXP-21 hosted surface lives
4
+ here. ``dispatch`` is called at the top of each ``do_*`` verb and returns
5
+ True when the path was handled.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import hmac
12
+ import json
13
+ import logging
14
+ import re
15
+ import secrets
16
+ import sqlite3
17
+ import threading
18
+ import time
19
+ import urllib.parse
20
+ from http import HTTPStatus
21
+ from pathlib import Path
22
+ from typing import TYPE_CHECKING, Any
23
+
24
+ if TYPE_CHECKING:
25
+ from selfheal_api.server import SelfHealRequestHandler
26
+
27
+ from selfheal_api.billing import StripeAPIError
28
+ from selfheal_api.dashboard import ConsoleSnapshot, render_console_html
29
+ from selfheal_api.metrics import compute_remediation_metrics
30
+ from selfheal_api.specwatch import (
31
+ MAX_WATCHED_SPECS_PER_ORG,
32
+ run_spec_watch_cycle,
33
+ )
34
+
35
+ logger = logging.getLogger(__name__)
36
+
37
+ _ORG_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
38
+ _STATE_NONCE_TTL_SECONDS = 600.0
39
+ _INSTALL_TOKEN_TTL_SECONDS = 600.0
40
+ _HOSTED_RATE_LIMIT_PER_MINUTE = 30
41
+
42
+
43
+ class HostedStateStore:
44
+ """SQLite-backed store for install-flow state nonces and install tokens.
45
+
46
+ Shares ``SELFHEAL_DB_PATH`` with the other control-plane stores.
47
+ """
48
+
49
+ def __init__(self, db_path: str | Path = ":memory:") -> None:
50
+ resolved = str(db_path)
51
+ if resolved != ":memory:" and not resolved.startswith("file:"):
52
+ Path(resolved).parent.mkdir(parents=True, exist_ok=True)
53
+ self._lock = threading.Lock()
54
+ self._conn = sqlite3.connect(resolved, check_same_thread=False)
55
+ self._conn.execute("PRAGMA busy_timeout=5000")
56
+ self._conn.execute("PRAGMA journal_mode=WAL")
57
+ self._conn.executescript(
58
+ """
59
+ CREATE TABLE IF NOT EXISTS state_nonces (
60
+ nonce TEXT PRIMARY KEY,
61
+ org_id TEXT NOT NULL,
62
+ expires_at REAL NOT NULL,
63
+ created_at REAL NOT NULL
64
+ );
65
+ CREATE TABLE IF NOT EXISTS install_tokens (
66
+ token_hash TEXT PRIMARY KEY,
67
+ org_id TEXT NOT NULL,
68
+ installation_id INTEGER NOT NULL,
69
+ expires_at REAL NOT NULL,
70
+ used_at REAL,
71
+ created_at REAL NOT NULL
72
+ );
73
+ CREATE INDEX IF NOT EXISTS idx_install_tokens_org
74
+ ON install_tokens(org_id, installation_id);
75
+ CREATE TABLE IF NOT EXISTS api_keys (
76
+ key_id TEXT PRIMARY KEY,
77
+ key_hash TEXT NOT NULL UNIQUE,
78
+ org_id TEXT NOT NULL,
79
+ created_at REAL NOT NULL,
80
+ revoked_at REAL
81
+ );
82
+ CREATE INDEX IF NOT EXISTS idx_api_keys_org
83
+ ON api_keys(org_id);
84
+ CREATE TABLE IF NOT EXISTS idempotency_keys (
85
+ key TEXT PRIMARY KEY,
86
+ response_json TEXT,
87
+ created_at REAL NOT NULL
88
+ );
89
+ CREATE TABLE IF NOT EXISTS repo_bindings (
90
+ org_id TEXT NOT NULL,
91
+ repo TEXT NOT NULL,
92
+ installation_id INTEGER NOT NULL,
93
+ base_branch TEXT NOT NULL,
94
+ models_map_json TEXT NOT NULL,
95
+ updated_at REAL NOT NULL,
96
+ PRIMARY KEY (org_id, repo)
97
+ );
98
+ CREATE TABLE IF NOT EXISTS autoheal_runs (
99
+ run_id INTEGER PRIMARY KEY AUTOINCREMENT,
100
+ org_id TEXT NOT NULL,
101
+ repo TEXT NOT NULL,
102
+ model_name TEXT NOT NULL,
103
+ model_path TEXT NOT NULL,
104
+ fingerprint TEXT NOT NULL,
105
+ original_source TEXT NOT NULL,
106
+ status TEXT NOT NULL,
107
+ pr_url TEXT,
108
+ created_at REAL NOT NULL
109
+ );
110
+ CREATE INDEX IF NOT EXISTS idx_autoheal_runs_lookup
111
+ ON autoheal_runs(org_id, repo, model_name, run_id DESC);
112
+ CREATE TABLE IF NOT EXISTS watched_specs (
113
+ org_id TEXT NOT NULL,
114
+ repo TEXT NOT NULL,
115
+ spec_url TEXT NOT NULL,
116
+ etag TEXT,
117
+ last_seen_version TEXT,
118
+ last_seen_hash TEXT,
119
+ updated_at REAL NOT NULL,
120
+ PRIMARY KEY (org_id, repo, spec_url)
121
+ );
122
+ CREATE TABLE IF NOT EXISTS spec_events (
123
+ event_id INTEGER PRIMARY KEY AUTOINCREMENT,
124
+ org_id TEXT NOT NULL,
125
+ repo TEXT NOT NULL,
126
+ spec_url TEXT NOT NULL,
127
+ old_version TEXT,
128
+ new_version TEXT,
129
+ old_hash TEXT,
130
+ new_hash TEXT,
131
+ detected_at REAL NOT NULL
132
+ );
133
+ CREATE INDEX IF NOT EXISTS idx_spec_events_org
134
+ ON spec_events(org_id, event_id DESC);
135
+ """
136
+ )
137
+ self._conn.commit()
138
+
139
+ @staticmethod
140
+ def _hash(value: str) -> str:
141
+ return hashlib.sha256(value.encode("utf-8")).hexdigest()
142
+
143
+ def issue_state_nonce(self, org_id: str, ttl: float = _STATE_NONCE_TTL_SECONDS) -> str:
144
+ """Persist a single-use nonce bound to ``org_id``; returns the nonce."""
145
+ nonce = secrets.token_urlsafe(24)
146
+ now = time.time()
147
+ with self._lock:
148
+ self._conn.execute(
149
+ "INSERT INTO state_nonces (nonce, org_id, expires_at, created_at)"
150
+ " VALUES (?, ?, ?, ?)",
151
+ (nonce, org_id, now + ttl, now),
152
+ )
153
+ self._conn.commit()
154
+ return nonce
155
+
156
+ def consume_state_nonce(self, nonce: str) -> str | None:
157
+ """Atomically consume a nonce, returning its org_id or None."""
158
+ now = time.time()
159
+ with self._lock:
160
+ row = self._conn.execute(
161
+ "SELECT org_id, expires_at FROM state_nonces WHERE nonce = ?",
162
+ (nonce,),
163
+ ).fetchone()
164
+ if row is None:
165
+ return None
166
+ org_id, expires_at = str(row[0]), float(row[1])
167
+ self._conn.execute(
168
+ "DELETE FROM state_nonces WHERE nonce = ?", (nonce,)
169
+ )
170
+ self._conn.commit()
171
+ if expires_at <= now:
172
+ return None
173
+ return org_id
174
+
175
+ def issue_install_token(
176
+ self,
177
+ org_id: str,
178
+ installation_id: int,
179
+ ttl: float = _INSTALL_TOKEN_TTL_SECONDS,
180
+ ) -> str:
181
+ """Mint a single-use install token; returns the raw token once."""
182
+ raw = "sit_" + secrets.token_urlsafe(32)
183
+ now = time.time()
184
+ with self._lock:
185
+ self._conn.execute(
186
+ "INSERT INTO install_tokens"
187
+ " (token_hash, org_id, installation_id, expires_at, used_at, created_at)"
188
+ " VALUES (?, ?, ?, ?, NULL, ?)",
189
+ (self._hash(raw), org_id, installation_id, now + ttl, now),
190
+ )
191
+ self._conn.commit()
192
+ return raw
193
+
194
+ def consume_install_token(self, raw: str) -> tuple[str, int] | None:
195
+ """Atomically consume an install token; returns (org_id, installation_id)."""
196
+ now = time.time()
197
+ token_hash = self._hash(raw)
198
+ with self._lock:
199
+ row = self._conn.execute(
200
+ "SELECT org_id, installation_id, expires_at FROM install_tokens"
201
+ " WHERE token_hash = ? AND used_at IS NULL",
202
+ (token_hash,),
203
+ ).fetchone()
204
+ if row is None:
205
+ return None
206
+ org_id, installation_id, expires_at = (
207
+ str(row[0]),
208
+ int(row[1]),
209
+ float(row[2]),
210
+ )
211
+ # Atomic claim: only one concurrent consumer wins.
212
+ cur = self._conn.execute(
213
+ "UPDATE install_tokens SET used_at = ?"
214
+ " WHERE token_hash = ? AND used_at IS NULL",
215
+ (now, token_hash),
216
+ )
217
+ self._conn.commit()
218
+ if cur.rowcount != 1 or expires_at <= now:
219
+ return None
220
+ return org_id, installation_id
221
+
222
+ def org_owns_installation(self, org_id: str, installation_id: int) -> bool:
223
+ """True if the org has ever been issued an install token for this installation."""
224
+ with self._lock:
225
+ row = self._conn.execute(
226
+ "SELECT 1 FROM install_tokens WHERE org_id = ? AND installation_id = ?"
227
+ " LIMIT 1",
228
+ (org_id, installation_id),
229
+ ).fetchone()
230
+ return row is not None
231
+
232
+ def issue_api_key(self, org_id: str) -> tuple[str, str]:
233
+ """Mint an org API key; returns (key_id, raw ``shk_*`` key) once."""
234
+ key_id = "key_" + secrets.token_hex(8)
235
+ raw = "shk_" + secrets.token_hex(16)
236
+ now = time.time()
237
+ with self._lock:
238
+ self._conn.execute(
239
+ "INSERT INTO api_keys (key_id, key_hash, org_id, created_at, revoked_at)"
240
+ " VALUES (?, ?, ?, ?, NULL)",
241
+ (key_id, self._hash(raw), org_id, now),
242
+ )
243
+ self._conn.commit()
244
+ return key_id, raw
245
+
246
+ def lookup_api_key(self, raw: str) -> str | None:
247
+ """Return org_id for a valid, unrevoked ``shk_*`` key, else None."""
248
+ if not raw.startswith("shk_"):
249
+ return None
250
+ with self._lock:
251
+ row = self._conn.execute(
252
+ "SELECT org_id FROM api_keys"
253
+ " WHERE key_hash = ? AND revoked_at IS NULL",
254
+ (self._hash(raw),),
255
+ ).fetchone()
256
+ return str(row[0]) if row is not None else None
257
+
258
+ def revoke_api_key(self, org_id: str, key_id: str) -> bool:
259
+ """Revoke a key owned by ``org_id``. Returns True if a row was revoked."""
260
+ now = time.time()
261
+ with self._lock:
262
+ cur = self._conn.execute(
263
+ "UPDATE api_keys SET revoked_at = ?"
264
+ " WHERE key_id = ? AND org_id = ? AND revoked_at IS NULL",
265
+ (now, key_id, org_id),
266
+ )
267
+ self._conn.commit()
268
+ return cur.rowcount == 1
269
+
270
+ def revoke_key_by_hash(self, raw: str) -> bool:
271
+ """Revoke the key matching ``raw`` (used by rotate)."""
272
+ now = time.time()
273
+ with self._lock:
274
+ cur = self._conn.execute(
275
+ "UPDATE api_keys SET revoked_at = ?"
276
+ " WHERE key_hash = ? AND revoked_at IS NULL",
277
+ (now, self._hash(raw)),
278
+ )
279
+ self._conn.commit()
280
+ return cur.rowcount == 1
281
+
282
+ def upsert_repo_binding(
283
+ self,
284
+ org_id: str,
285
+ installation_id: int,
286
+ repo: str,
287
+ base_branch: str,
288
+ models_map: dict[str, str],
289
+ ) -> None:
290
+ now = time.time()
291
+ with self._lock:
292
+ self._conn.execute(
293
+ "INSERT INTO repo_bindings"
294
+ " (org_id, repo, installation_id, base_branch, models_map_json, updated_at)"
295
+ " VALUES (?, ?, ?, ?, ?, ?)"
296
+ " ON CONFLICT(org_id, repo) DO UPDATE SET"
297
+ " installation_id = excluded.installation_id,"
298
+ " base_branch = excluded.base_branch,"
299
+ " models_map_json = excluded.models_map_json,"
300
+ " updated_at = excluded.updated_at",
301
+ (
302
+ org_id,
303
+ repo,
304
+ installation_id,
305
+ base_branch,
306
+ json.dumps(models_map, sort_keys=True),
307
+ now,
308
+ ),
309
+ )
310
+ self._conn.commit()
311
+
312
+ def get_repo_binding(
313
+ self, org_id: str, repo: str
314
+ ) -> dict[str, Any] | None:
315
+ with self._lock:
316
+ row = self._conn.execute(
317
+ "SELECT installation_id, base_branch, models_map_json, updated_at"
318
+ " FROM repo_bindings WHERE org_id = ? AND repo = ?",
319
+ (org_id, repo),
320
+ ).fetchone()
321
+ if row is None:
322
+ return None
323
+ return {
324
+ "installation_id": int(row[0]),
325
+ "base_branch": str(row[1]),
326
+ "models_map": json.loads(str(row[2])),
327
+ "updated_at": float(row[3]),
328
+ }
329
+
330
+ def list_repo_bindings(self, org_id: str) -> list[dict[str, Any]]:
331
+ with self._lock:
332
+ rows = self._conn.execute(
333
+ "SELECT repo, installation_id, base_branch, models_map_json, updated_at"
334
+ " FROM repo_bindings WHERE org_id = ? ORDER BY repo",
335
+ (org_id,),
336
+ ).fetchall()
337
+ return [
338
+ {
339
+ "repo": str(r[0]),
340
+ "installation_id": int(r[1]),
341
+ "base_branch": str(r[2]),
342
+ "models_map": json.loads(str(r[3])),
343
+ "updated_at": float(r[4]),
344
+ }
345
+ for r in rows
346
+ ]
347
+
348
+ def record_repair_run(
349
+ self,
350
+ *,
351
+ org_id: str,
352
+ repo: str,
353
+ model_name: str,
354
+ model_path: str,
355
+ fingerprint: str,
356
+ original_source: str,
357
+ status: str,
358
+ pr_url: str | None = None,
359
+ ) -> int:
360
+ """Persist an auto-heal run for revert provenance; returns run_id."""
361
+ now = time.time()
362
+ with self._lock:
363
+ cur = self._conn.execute(
364
+ "INSERT INTO autoheal_runs"
365
+ " (org_id, repo, model_name, model_path, fingerprint,"
366
+ " original_source, status, pr_url, created_at)"
367
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
368
+ (
369
+ org_id,
370
+ repo,
371
+ model_name,
372
+ model_path,
373
+ fingerprint,
374
+ original_source,
375
+ status,
376
+ pr_url,
377
+ now,
378
+ ),
379
+ )
380
+ self._conn.commit()
381
+ return int(cur.lastrowid or 0)
382
+
383
+ def list_repair_runs(self, org_id: str, limit: int = 50) -> list[dict[str, Any]]:
384
+ """Recent auto-heal runs for the console, newest first."""
385
+ with self._lock:
386
+ rows = self._conn.execute(
387
+ "SELECT run_id, repo, model_name, model_path, fingerprint,"
388
+ " status, pr_url, created_at"
389
+ " FROM autoheal_runs WHERE org_id = ?"
390
+ " ORDER BY run_id DESC LIMIT ?",
391
+ (org_id, limit),
392
+ ).fetchall()
393
+ return [
394
+ {
395
+ "run_id": int(r[0]),
396
+ "repo": str(r[1]),
397
+ "model_name": str(r[2]),
398
+ "model_path": str(r[3]),
399
+ "fingerprint": str(r[4]),
400
+ "status": str(r[5]),
401
+ "pr_url": str(r[6]) if r[6] is not None else None,
402
+ "created_at": float(r[7]),
403
+ }
404
+ for r in rows
405
+ ]
406
+
407
+ def list_all_repair_runs(self, limit: int = 1000) -> list[dict[str, Any]]:
408
+ """Recent auto-heal runs across all orgs (metrics rollup)."""
409
+ with self._lock:
410
+ rows = self._conn.execute(
411
+ "SELECT org_id, repo, model_name, model_path, fingerprint,"
412
+ " status, pr_url, created_at"
413
+ " FROM autoheal_runs ORDER BY run_id DESC LIMIT ?",
414
+ (limit,),
415
+ ).fetchall()
416
+ return [
417
+ {
418
+ "org_id": str(r[0]),
419
+ "repo": str(r[1]),
420
+ "model_name": str(r[2]),
421
+ "model_path": str(r[3]),
422
+ "fingerprint": str(r[4]),
423
+ "status": str(r[5]),
424
+ "pr_url": str(r[6]) if r[6] is not None else None,
425
+ "created_at": float(r[7]),
426
+ }
427
+ for r in rows
428
+ ]
429
+
430
+ def latest_pr_opened_run(
431
+ self, org_id: str, repo: str, model_name: str
432
+ ) -> dict[str, Any] | None:
433
+ """Most recent ``pr_opened`` auto-heal run for revert lookups."""
434
+ with self._lock:
435
+ row = self._conn.execute(
436
+ "SELECT run_id, model_path, fingerprint, original_source, pr_url"
437
+ " FROM autoheal_runs"
438
+ " WHERE org_id = ? AND repo = ? AND model_name = ?"
439
+ " AND status = 'pr_opened'"
440
+ " ORDER BY run_id DESC LIMIT 1",
441
+ (org_id, repo, model_name),
442
+ ).fetchone()
443
+ if row is None:
444
+ return None
445
+ return {
446
+ "run_id": int(row[0]),
447
+ "model_path": str(row[1]),
448
+ "fingerprint": str(row[2]),
449
+ "original_source": str(row[3]),
450
+ "pr_url": str(row[4]) if row[4] is not None else None,
451
+ }
452
+
453
+ def upsert_watched_spec(self, org_id: str, repo: str, spec_url: str) -> None:
454
+ now = time.time()
455
+ with self._lock:
456
+ self._conn.execute(
457
+ "INSERT INTO watched_specs"
458
+ " (org_id, repo, spec_url, etag, last_seen_version,"
459
+ " last_seen_hash, updated_at)"
460
+ " VALUES (?, ?, ?, NULL, NULL, NULL, ?)"
461
+ " ON CONFLICT(org_id, repo, spec_url) DO UPDATE SET"
462
+ " updated_at = excluded.updated_at",
463
+ (org_id, repo, spec_url, now),
464
+ )
465
+ self._conn.commit()
466
+
467
+ def count_watched_specs(self, org_id: str) -> int:
468
+ with self._lock:
469
+ row = self._conn.execute(
470
+ "SELECT COUNT(*) FROM watched_specs WHERE org_id = ?",
471
+ (org_id,),
472
+ ).fetchone()
473
+ return int(row[0]) if row else 0
474
+
475
+ def list_watched_specs(self, org_id: str | None = None) -> list[dict[str, Any]]:
476
+ query = (
477
+ "SELECT org_id, repo, spec_url, etag, last_seen_version,"
478
+ " last_seen_hash, updated_at FROM watched_specs"
479
+ )
480
+ params: list[Any] = []
481
+ if org_id is not None:
482
+ query += " WHERE org_id = ?"
483
+ params.append(org_id)
484
+ query += " ORDER BY org_id, repo, spec_url"
485
+ with self._lock:
486
+ rows = self._conn.execute(query, params).fetchall()
487
+ return [
488
+ {
489
+ "org_id": str(r[0]),
490
+ "repo": str(r[1]),
491
+ "spec_url": str(r[2]),
492
+ "etag": str(r[3]) if r[3] is not None else None,
493
+ "last_seen_version": str(r[4]) if r[4] is not None else None,
494
+ "last_seen_hash": str(r[5]) if r[5] is not None else None,
495
+ "updated_at": float(r[6]),
496
+ }
497
+ for r in rows
498
+ ]
499
+
500
+ def update_watched_spec_signature(
501
+ self,
502
+ org_id: str,
503
+ repo: str,
504
+ spec_url: str,
505
+ *,
506
+ etag: str | None,
507
+ version: str | None,
508
+ content_hash: str,
509
+ ) -> None:
510
+ with self._lock:
511
+ self._conn.execute(
512
+ "UPDATE watched_specs SET etag = ?, last_seen_version = ?,"
513
+ " last_seen_hash = ?, updated_at = ?"
514
+ " WHERE org_id = ? AND repo = ? AND spec_url = ?",
515
+ (etag, version, content_hash, time.time(), org_id, repo, spec_url),
516
+ )
517
+ self._conn.commit()
518
+
519
+ def update_watched_spec_etag(
520
+ self, org_id: str, repo: str, spec_url: str, etag: str
521
+ ) -> None:
522
+ with self._lock:
523
+ self._conn.execute(
524
+ "UPDATE watched_specs SET etag = ?, updated_at = ?"
525
+ " WHERE org_id = ? AND repo = ? AND spec_url = ?",
526
+ (etag, time.time(), org_id, repo, spec_url),
527
+ )
528
+ self._conn.commit()
529
+
530
+ def record_spec_event(
531
+ self,
532
+ *,
533
+ org_id: str,
534
+ repo: str,
535
+ spec_url: str,
536
+ old_version: str | None,
537
+ new_version: str | None,
538
+ old_hash: str | None,
539
+ new_hash: str,
540
+ ) -> int:
541
+ with self._lock:
542
+ cur = self._conn.execute(
543
+ "INSERT INTO spec_events"
544
+ " (org_id, repo, spec_url, old_version, new_version,"
545
+ " old_hash, new_hash, detected_at)"
546
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
547
+ (
548
+ org_id,
549
+ repo,
550
+ spec_url,
551
+ old_version,
552
+ new_version,
553
+ old_hash,
554
+ new_hash,
555
+ time.time(),
556
+ ),
557
+ )
558
+ self._conn.commit()
559
+ return int(cur.lastrowid or 0)
560
+
561
+ def list_spec_events(
562
+ self, org_id: str | None = None, limit: int = 50
563
+ ) -> list[dict[str, Any]]:
564
+ query = (
565
+ "SELECT event_id, org_id, repo, spec_url, old_version,"
566
+ " new_version, detected_at FROM spec_events"
567
+ )
568
+ params: list[Any] = []
569
+ if org_id is not None:
570
+ query += " WHERE org_id = ?"
571
+ params.append(org_id)
572
+ query += " ORDER BY event_id DESC LIMIT ?"
573
+ params.append(limit)
574
+ with self._lock:
575
+ rows = self._conn.execute(query, params).fetchall()
576
+ return [
577
+ {
578
+ "event_id": int(r[0]),
579
+ "org_id": str(r[1]),
580
+ "repo": str(r[2]),
581
+ "spec_url": str(r[3]),
582
+ "old_version": str(r[4]) if r[4] is not None else None,
583
+ "new_version": str(r[5]) if r[5] is not None else None,
584
+ "detected_at": float(r[6]),
585
+ }
586
+ for r in rows
587
+ ]
588
+
589
+ def begin_idempotency(self, key: str, ttl: float = 3600.0) -> bool:
590
+ """Claim an idempotency key; False if already claimed within TTL."""
591
+ now = time.time()
592
+ with self._lock:
593
+ self._conn.execute(
594
+ "DELETE FROM idempotency_keys WHERE created_at < ?", (now - ttl,)
595
+ )
596
+ cur = self._conn.execute(
597
+ "INSERT OR IGNORE INTO idempotency_keys (key, response_json, created_at)"
598
+ " VALUES (?, NULL, ?)",
599
+ (key, now),
600
+ )
601
+ self._conn.commit()
602
+ return cur.rowcount == 1
603
+
604
+ def finish_idempotency(self, key: str, response: dict[str, Any]) -> None:
605
+ with self._lock:
606
+ self._conn.execute(
607
+ "UPDATE idempotency_keys SET response_json = ? WHERE key = ?",
608
+ (json.dumps(response), key),
609
+ )
610
+ self._conn.commit()
611
+
612
+ def get_idempotency(self, key: str) -> dict[str, Any] | None:
613
+ with self._lock:
614
+ row = self._conn.execute(
615
+ "SELECT response_json FROM idempotency_keys WHERE key = ?",
616
+ (key,),
617
+ ).fetchone()
618
+ if row is None or row[0] is None:
619
+ return None
620
+ try:
621
+ data: Any = json.loads(str(row[0]))
622
+ except json.JSONDecodeError:
623
+ return None
624
+ return data if isinstance(data, dict) else None
625
+
626
+ def ping(self) -> bool:
627
+ try:
628
+ with self._lock:
629
+ self._conn.execute("SELECT 1").fetchone()
630
+ except sqlite3.Error:
631
+ return False
632
+ return True
633
+
634
+ def close(self) -> None:
635
+ with self._lock:
636
+ self._conn.close()
637
+
638
+
639
+ class _PerKeyRateLimiter:
640
+ """Simple fixed-window per-key rate limiter for hosted public routes."""
641
+
642
+ def __init__(self, limit_per_minute: int = _HOSTED_RATE_LIMIT_PER_MINUTE) -> None:
643
+ self._limit = limit_per_minute
644
+ self._hits: dict[str, tuple[int, float]] = {}
645
+ self._lock = threading.Lock()
646
+
647
+ def allow(self, key: str) -> bool:
648
+ now = time.time()
649
+ window = int(now // 60)
650
+ with self._lock:
651
+ count, stored_window = self._hits.get(key, (0, window))
652
+ if stored_window != window:
653
+ count = 0
654
+ stored_window = window
655
+ if count >= self._limit:
656
+ self._hits[key] = (count, stored_window)
657
+ return False
658
+ self._hits[key] = (count + 1, stored_window)
659
+ if len(self._hits) > 10_000:
660
+ cutoff = window - 2
661
+ self._hits = {
662
+ k: v for k, v in self._hits.items() if v[1] >= cutoff
663
+ }
664
+ return True
665
+
666
+
667
+ _RATE_LIMITER = _PerKeyRateLimiter()
668
+
669
+
670
+ def _client_ip(handler: SelfHealRequestHandler) -> str:
671
+ forwarded = handler.headers.get("X-Forwarded-For", "")
672
+ if forwarded:
673
+ return forwarded.split(",", 1)[0].strip()[:64]
674
+ return handler.client_address[0]
675
+
676
+
677
+ def _json(
678
+ handler: SelfHealRequestHandler, status: HTTPStatus, payload: dict[str, Any]
679
+ ) -> None:
680
+ handler._send_json(status, payload)
681
+
682
+
683
+ def _html(
684
+ handler: SelfHealRequestHandler,
685
+ status: HTTPStatus,
686
+ html_body: str,
687
+ *,
688
+ allow_inline_script: bool = False,
689
+ ) -> None:
690
+ body = html_body.encode("utf-8")
691
+ handler.send_response(status.value)
692
+ handler.send_header("Content-Type", "text/html; charset=utf-8")
693
+ handler.send_header("Content-Length", str(len(body)))
694
+ handler.send_header("X-Request-Id", handler._get_request_id())
695
+ handler.send_header("X-Content-Type-Options", "nosniff")
696
+ handler.send_header("X-Frame-Options", "DENY")
697
+ script_src = "script-src 'unsafe-inline'; " if allow_inline_script else ""
698
+ handler.send_header(
699
+ "Content-Security-Policy",
700
+ f"default-src 'none'; style-src 'unsafe-inline'; {script_src}",
701
+ )
702
+ handler.end_headers()
703
+ handler.wfile.write(body)
704
+
705
+
706
+ def _redirect(handler: SelfHealRequestHandler, location: str) -> None:
707
+ handler.send_response(HTTPStatus.FOUND.value)
708
+ handler.send_header("Location", location)
709
+ handler.send_header("X-Request-Id", handler._get_request_id())
710
+ handler.send_header("Cache-Control", "no-store")
711
+ handler.end_headers()
712
+
713
+
714
+ def _state_secret(handler: SelfHealRequestHandler) -> str | None:
715
+ secret = getattr(handler.server, "state_secret", "") or ""
716
+ return secret or None
717
+
718
+
719
+ def _app_slug(handler: SelfHealRequestHandler) -> str | None:
720
+ return getattr(handler.server, "github_app_slug", None) or None
721
+
722
+
723
+ def _hosted_configured(handler: SelfHealRequestHandler) -> bool:
724
+ return _app_slug(handler) is not None and _state_secret(handler) is not None
725
+
726
+
727
+ def _sign_state(handler: SelfHealRequestHandler, nonce: str, org_id: str) -> str:
728
+ secret = _state_secret(handler)
729
+ assert secret is not None
730
+ mac = hmac.new(
731
+ secret.encode("utf-8"), f"{nonce}:{org_id}".encode(), hashlib.sha256
732
+ ).hexdigest()[:32]
733
+ return f"{nonce}.{mac}"
734
+
735
+
736
+ def _handle_install_link(handler: SelfHealRequestHandler, query: dict[str, list[str]]) -> None:
737
+ org_vals = query.get("org_id")
738
+ org_id = org_vals[0].strip() if org_vals else ""
739
+ if not org_id or not _ORG_ID_RE.match(org_id):
740
+ _json(handler, HTTPStatus.BAD_REQUEST, {"error": "missing or invalid org_id"})
741
+ return
742
+ if not handler._authorize_tenant_read(org_id):
743
+ _json(handler, HTTPStatus.UNAUTHORIZED, {"error": "unauthorized"})
744
+ return
745
+ if not _hosted_configured(handler):
746
+ _json(handler, HTTPStatus.SERVICE_UNAVAILABLE, {"error": "not_configured"})
747
+ return
748
+ if not _RATE_LIMITER.allow(f"install-link:{org_id}:{_client_ip(handler)}"):
749
+ _json(handler, HTTPStatus.TOO_MANY_REQUESTS, {"error": "rate_limited"})
750
+ return
751
+ store: HostedStateStore = handler.server.hosted_store
752
+ nonce = store.issue_state_nonce(org_id)
753
+ state = _sign_state(handler, nonce, org_id)
754
+ slug = _app_slug(handler)
755
+ assert slug is not None
756
+ install_url = (
757
+ f"https://github.com/apps/{urllib.parse.quote(slug, safe='')}"
758
+ f"/installations/new?state={urllib.parse.quote(state, safe='')}"
759
+ )
760
+ _json(handler, HTTPStatus.OK, {"install_url": install_url})
761
+
762
+
763
+ def _handle_install_callback(
764
+ handler: SelfHealRequestHandler, query: dict[str, list[str]]
765
+ ) -> None:
766
+ if not _RATE_LIMITER.allow(f"install-callback:{_client_ip(handler)}"):
767
+ _json(handler, HTTPStatus.TOO_MANY_REQUESTS, {"error": "rate_limited"})
768
+ return
769
+ if not _hosted_configured(handler):
770
+ _json(handler, HTTPStatus.SERVICE_UNAVAILABLE, {"error": "not_configured"})
771
+ return
772
+ state = (query.get("state") or [""])[0].strip()
773
+ installation_raw = (query.get("installation_id") or [""])[0].strip()
774
+ setup_action = (query.get("setup_action") or [""])[0].strip()
775
+ if not state or "." not in state or not installation_raw.isdigit():
776
+ _json(handler, HTTPStatus.BAD_REQUEST, {"error": "invalid callback parameters"})
777
+ return
778
+ nonce, mac = state.rsplit(".", 1)
779
+ store: HostedStateStore = handler.server.hosted_store
780
+ org_id = store.consume_state_nonce(nonce)
781
+ if org_id is None:
782
+ _json(handler, HTTPStatus.BAD_REQUEST, {"error": "invalid or expired state"})
783
+ return
784
+ expected = _sign_state(handler, nonce, org_id).rsplit(".", 1)[1]
785
+ if not hmac.compare_digest(expected, mac):
786
+ _json(handler, HTTPStatus.BAD_REQUEST, {"error": "invalid state signature"})
787
+ return
788
+ installation_id = int(installation_raw)
789
+ if setup_action not in {"install", "update"}:
790
+ _json(
791
+ handler,
792
+ HTTPStatus.BAD_REQUEST,
793
+ {"error": f"unsupported setup_action: {setup_action}"},
794
+ )
795
+ return
796
+ install_token = store.issue_install_token(org_id, installation_id)
797
+ # Token travels in the URL fragment — never logged by servers/proxies.
798
+ _redirect(handler, f"/install/done#token={urllib.parse.quote(install_token, safe='')}")
799
+
800
+
801
+ def _read_json_body(handler: SelfHealRequestHandler) -> dict[str, Any] | None:
802
+ """Read + parse a JSON object body; sends 400 and returns None on failure."""
803
+ length = handler.headers.get("Content-Length")
804
+ try:
805
+ size = int(length) if length else 0
806
+ except ValueError:
807
+ size = 0
808
+ if size <= 0 or size > 64 * 1024:
809
+ _json(handler, HTTPStatus.BAD_REQUEST, {"error": "invalid body"})
810
+ return None
811
+ try:
812
+ body: Any = json.loads(handler.rfile.read(size).decode("utf-8"))
813
+ except (json.JSONDecodeError, UnicodeDecodeError):
814
+ _json(handler, HTTPStatus.BAD_REQUEST, {"error": "invalid JSON body"})
815
+ return None
816
+ if not isinstance(body, dict):
817
+ _json(handler, HTTPStatus.BAD_REQUEST, {"error": "expected JSON object"})
818
+ return None
819
+ return body
820
+
821
+
822
+ def _bearer_token(handler: SelfHealRequestHandler) -> str:
823
+ auth = handler.headers.get("Authorization", "").strip()
824
+ if auth.startswith("Bearer "):
825
+ return auth[7:].strip()
826
+ return ""
827
+
828
+
829
+ def _require_api_key(handler: SelfHealRequestHandler) -> str | None:
830
+ """Authenticate via ``shk_*`` bearer; returns org_id or None (401 sent)."""
831
+ token = _bearer_token(handler)
832
+ org_id = handler.server.hosted_store.lookup_api_key(token)
833
+ if org_id is None:
834
+ _json(handler, HTTPStatus.UNAUTHORIZED, {"error": "invalid or revoked api key"})
835
+ return None
836
+ return org_id
837
+
838
+
839
+ def _handle_connect_exchange(handler: SelfHealRequestHandler) -> None:
840
+ if not _RATE_LIMITER.allow(f"connect-exchange:{_client_ip(handler)}"):
841
+ _json(handler, HTTPStatus.TOO_MANY_REQUESTS, {"error": "rate_limited"})
842
+ return
843
+ body = _read_json_body(handler)
844
+ if body is None:
845
+ return
846
+ install_token = str(body.get("install_token") or "").strip()
847
+ if not install_token:
848
+ _json(handler, HTTPStatus.BAD_REQUEST, {"error": "missing install_token"})
849
+ return
850
+ store: HostedStateStore = handler.server.hosted_store
851
+ consumed = store.consume_install_token(install_token)
852
+ if consumed is None:
853
+ _json(
854
+ handler,
855
+ HTTPStatus.UNAUTHORIZED,
856
+ {"error": "install token invalid, expired, or already used"},
857
+ )
858
+ return
859
+ org_id, installation_id = consumed
860
+ key_id, api_key = store.issue_api_key(org_id)
861
+ _json(
862
+ handler,
863
+ HTTPStatus.OK,
864
+ {
865
+ "org_id": org_id,
866
+ "api_key": api_key,
867
+ "key_id": key_id,
868
+ "installation_id": installation_id,
869
+ },
870
+ )
871
+
872
+
873
+ def _handle_connect_verify(handler: SelfHealRequestHandler) -> None:
874
+ org_id = _require_api_key(handler)
875
+ if org_id is not None:
876
+ _json(handler, HTTPStatus.OK, {"org_id": org_id})
877
+
878
+
879
+ def _handle_connect_rotate(handler: SelfHealRequestHandler) -> None:
880
+ token = _bearer_token(handler)
881
+ org_id = handler.server.hosted_store.lookup_api_key(token)
882
+ if org_id is None:
883
+ _json(handler, HTTPStatus.UNAUTHORIZED, {"error": "invalid or revoked api key"})
884
+ return
885
+ if not _RATE_LIMITER.allow(f"connect-rotate:{org_id}"):
886
+ _json(handler, HTTPStatus.TOO_MANY_REQUESTS, {"error": "rate_limited"})
887
+ return
888
+ store: HostedStateStore = handler.server.hosted_store
889
+ store.revoke_key_by_hash(token)
890
+ key_id, api_key = store.issue_api_key(org_id)
891
+ _json(handler, HTTPStatus.OK, {"org_id": org_id, "api_key": api_key, "key_id": key_id})
892
+
893
+
894
+ def _handle_connect_key_delete(
895
+ handler: SelfHealRequestHandler, key_id: str
896
+ ) -> None:
897
+ org_id = _require_api_key(handler)
898
+ if org_id is None:
899
+ return
900
+ store: HostedStateStore = handler.server.hosted_store
901
+ if not store.revoke_api_key(org_id, key_id):
902
+ _json(handler, HTTPStatus.NOT_FOUND, {"error": "key not found"})
903
+ return
904
+ _json(handler, HTTPStatus.OK, {"revoked": True, "key_id": key_id})
905
+
906
+
907
+ def _handle_connect_bind(handler: SelfHealRequestHandler) -> None:
908
+ org_id = _require_api_key(handler)
909
+ if org_id is None:
910
+ return
911
+ if not _RATE_LIMITER.allow(f"connect-bind:{org_id}"):
912
+ _json(handler, HTTPStatus.TOO_MANY_REQUESTS, {"error": "rate_limited"})
913
+ return
914
+ body = _read_json_body(handler)
915
+ if body is None:
916
+ return
917
+ installation_raw = body.get("installation_id")
918
+ repo = str(body.get("repo") or "").strip()
919
+ base_branch = str(body.get("base_branch") or "").strip() or "main"
920
+ models_map = body.get("models_map") or {}
921
+ if (
922
+ not isinstance(installation_raw, int)
923
+ or isinstance(installation_raw, bool)
924
+ or installation_raw <= 0
925
+ or not repo
926
+ or len(repo) > 256
927
+ or not isinstance(models_map, dict)
928
+ or not all(
929
+ isinstance(k, str) and isinstance(v, str) for k, v in models_map.items()
930
+ )
931
+ ):
932
+ _json(
933
+ handler,
934
+ HTTPStatus.BAD_REQUEST,
935
+ {
936
+ "error": "expected {installation_id:int, repo:str, "
937
+ "base_branch?:str, models_map?:{name:path}}"
938
+ },
939
+ )
940
+ return
941
+ store: HostedStateStore = handler.server.hosted_store
942
+ registry = handler.server.installation_registry
943
+ installation = registry.get_by_installation(installation_raw)
944
+ owns_via_registry = (
945
+ installation is not None and installation.org_id == org_id
946
+ )
947
+ owns_via_token = store.org_owns_installation(org_id, installation_raw)
948
+ if not (owns_via_registry or owns_via_token):
949
+ _json(
950
+ handler,
951
+ HTTPStatus.FORBIDDEN,
952
+ {"error": "installation_id is not bound to this org"},
953
+ )
954
+ return
955
+ store.upsert_repo_binding(
956
+ org_id=org_id,
957
+ installation_id=installation_raw,
958
+ repo=repo,
959
+ base_branch=base_branch,
960
+ models_map=dict(models_map),
961
+ )
962
+ _json(
963
+ handler,
964
+ HTTPStatus.OK,
965
+ {
966
+ "bound": True,
967
+ "org_id": org_id,
968
+ "repo": repo,
969
+ "installation_id": installation_raw,
970
+ },
971
+ )
972
+
973
+
974
+ def _handle_billing_checkout(handler: SelfHealRequestHandler) -> None:
975
+ org_id = _require_api_key(handler)
976
+ if org_id is None:
977
+ return
978
+ if not _RATE_LIMITER.allow(f"billing-checkout:{org_id}"):
979
+ _json(handler, HTTPStatus.TOO_MANY_REQUESTS, {"error": "rate_limited"})
980
+ return
981
+ stripe_api = getattr(handler.server, "stripe_api", None)
982
+ if stripe_api is None:
983
+ _json(handler, HTTPStatus.SERVICE_UNAVAILABLE, {"error": "not_configured"})
984
+ return
985
+ body = _read_json_body(handler)
986
+ if body is None:
987
+ return
988
+ plan = str(body.get("plan") or "").strip().lower()
989
+ price_ids = getattr(handler.server, "stripe_price_ids", {}) or {}
990
+ if plan == "free":
991
+ _json(
992
+ handler,
993
+ HTTPStatus.BAD_REQUEST,
994
+ {"error": "free plan has no checkout; use portal to manage"},
995
+ )
996
+ return
997
+ price_id = price_ids.get(plan, "")
998
+ if not price_id:
999
+ _json(
1000
+ handler,
1001
+ HTTPStatus.BAD_REQUEST,
1002
+ {"error": f"unknown or unconfigured plan: {plan!r}"},
1003
+ )
1004
+ return
1005
+ base = getattr(handler.server, "public_base_url", "http://127.0.0.1:8080")
1006
+ try:
1007
+ session = stripe_api.post_form(
1008
+ "/v1/checkout/sessions",
1009
+ {
1010
+ "mode": "subscription",
1011
+ "client_reference_id": org_id,
1012
+ "metadata[org_id]": org_id,
1013
+ "metadata[plan]": plan,
1014
+ "subscription_data[metadata][org_id]": org_id,
1015
+ "subscription_data[metadata][plan]": plan,
1016
+ "line_items[0][price]": price_id,
1017
+ "line_items[0][quantity]": "1",
1018
+ "success_url": f"{base}/dashboard?org_id={org_id}&billing=success",
1019
+ "cancel_url": f"{base}/dashboard?org_id={org_id}&billing=cancel",
1020
+ },
1021
+ )
1022
+ except StripeAPIError:
1023
+ _json(handler, HTTPStatus.BAD_GATEWAY, {"error": "billing_provider_error"})
1024
+ return
1025
+ url = session.get("url")
1026
+ if not isinstance(url, str) or not url:
1027
+ _json(handler, HTTPStatus.BAD_GATEWAY, {"error": "billing_provider_error"})
1028
+ return
1029
+ _json(
1030
+ handler,
1031
+ HTTPStatus.OK,
1032
+ {"checkout_url": url, "session_id": session.get("id")},
1033
+ )
1034
+
1035
+
1036
+ def _handle_billing_portal(handler: SelfHealRequestHandler) -> None:
1037
+ org_id = _require_api_key(handler)
1038
+ if org_id is None:
1039
+ return
1040
+ if not _RATE_LIMITER.allow(f"billing-portal:{org_id}"):
1041
+ _json(handler, HTTPStatus.TOO_MANY_REQUESTS, {"error": "rate_limited"})
1042
+ return
1043
+ stripe_api = getattr(handler.server, "stripe_api", None)
1044
+ if stripe_api is None:
1045
+ _json(handler, HTTPStatus.SERVICE_UNAVAILABLE, {"error": "not_configured"})
1046
+ return
1047
+ sub = handler.server.billing_store.get_subscription(org_id)
1048
+ customer_id = sub.stripe_customer_id
1049
+ if not customer_id:
1050
+ _json(
1051
+ handler,
1052
+ HTTPStatus.CONFLICT,
1053
+ {"error": "no stripe customer for org; complete checkout first"},
1054
+ )
1055
+ return
1056
+ base = getattr(handler.server, "public_base_url", "http://127.0.0.1:8080")
1057
+ try:
1058
+ session = stripe_api.post_form(
1059
+ "/v1/billing_portal/sessions",
1060
+ {
1061
+ "customer": customer_id,
1062
+ "return_url": f"{base}/dashboard?org_id={org_id}",
1063
+ },
1064
+ )
1065
+ except StripeAPIError:
1066
+ _json(handler, HTTPStatus.BAD_GATEWAY, {"error": "billing_provider_error"})
1067
+ return
1068
+ url = session.get("url")
1069
+ if not isinstance(url, str) or not url:
1070
+ _json(handler, HTTPStatus.BAD_GATEWAY, {"error": "billing_provider_error"})
1071
+ return
1072
+ _json(handler, HTTPStatus.OK, {"portal_url": url})
1073
+
1074
+
1075
+ def _handle_jobs_digest(handler: SelfHealRequestHandler) -> None:
1076
+ jobs_token = getattr(handler.server, "jobs_token", "") or ""
1077
+ if not jobs_token:
1078
+ _json(handler, HTTPStatus.SERVICE_UNAVAILABLE, {"error": "not_configured"})
1079
+ return
1080
+ if not _RATE_LIMITER.allow(f"jobs-digest:{_client_ip(handler)}"):
1081
+ _json(handler, HTTPStatus.TOO_MANY_REQUESTS, {"error": "rate_limited"})
1082
+ return
1083
+ if not hmac.compare_digest(_bearer_token(handler), jobs_token):
1084
+ _json(handler, HTTPStatus.UNAUTHORIZED, {"error": "unauthorized"})
1085
+ return
1086
+ idem_key = handler.headers.get("Idempotency-Key", "").strip()
1087
+ store: HostedStateStore = handler.server.hosted_store
1088
+ if idem_key:
1089
+ prior = store.get_idempotency(idem_key)
1090
+ if prior is not None:
1091
+ _json(handler, HTTPStatus.OK, {**prior, "deduplicated": True})
1092
+ return
1093
+ if not store.begin_idempotency(idem_key):
1094
+ _json(handler, HTTPStatus.CONFLICT, {"error": "request in progress"})
1095
+ return
1096
+ raw_len = handler.headers.get("Content-Length", "")
1097
+ body: dict[str, Any] = {}
1098
+ try:
1099
+ has_body = bool(raw_len) and int(raw_len) > 0
1100
+ except ValueError:
1101
+ has_body = False
1102
+ if has_body:
1103
+ parsed_body = _read_json_body(handler)
1104
+ if parsed_body is None:
1105
+ return
1106
+ body = parsed_body
1107
+ org_id = str(body.get("org_id") or "").strip() or None
1108
+ try:
1109
+ days = float(body.get("days", 7))
1110
+ except (TypeError, ValueError):
1111
+ days = 7.0
1112
+ days = min(max(days, 0.04), 90.0)
1113
+ result = run_org_digests(handler.server, days=days, org_id=org_id)
1114
+ result["days"] = days
1115
+ if idem_key:
1116
+ store.finish_idempotency(idem_key, result)
1117
+ _json(handler, HTTPStatus.OK, result)
1118
+
1119
+
1120
+ def _handle_jobs_revert(handler: SelfHealRequestHandler) -> None:
1121
+ """POST /jobs/revert — open a draft PR restoring pre-remediation source."""
1122
+ jobs_token = getattr(handler.server, "jobs_token", "") or ""
1123
+ if not jobs_token:
1124
+ _json(handler, HTTPStatus.SERVICE_UNAVAILABLE, {"error": "not_configured"})
1125
+ return
1126
+ if not _RATE_LIMITER.allow(f"jobs-revert:{_client_ip(handler)}"):
1127
+ _json(handler, HTTPStatus.TOO_MANY_REQUESTS, {"error": "rate_limited"})
1128
+ return
1129
+ if not hmac.compare_digest(_bearer_token(handler), jobs_token):
1130
+ _json(handler, HTTPStatus.UNAUTHORIZED, {"error": "unauthorized"})
1131
+ return
1132
+ idem_key = handler.headers.get("Idempotency-Key", "").strip()
1133
+ store: HostedStateStore = handler.server.hosted_store
1134
+ if idem_key:
1135
+ prior = store.get_idempotency(idem_key)
1136
+ if prior is not None:
1137
+ _json(handler, HTTPStatus.OK, {**prior, "deduplicated": True})
1138
+ return
1139
+ if not store.begin_idempotency(idem_key):
1140
+ _json(handler, HTTPStatus.CONFLICT, {"error": "request in progress"})
1141
+ return
1142
+
1143
+ body = _read_json_body(handler)
1144
+ if body is None:
1145
+ return
1146
+ org_id = str(body.get("org_id") or "").strip()
1147
+ repo = str(body.get("repo") or "").strip()
1148
+ model_name = str(body.get("model_name") or "").strip()
1149
+ if not org_id or not repo or not model_name:
1150
+ _json(
1151
+ handler,
1152
+ HTTPStatus.BAD_REQUEST,
1153
+ {"error": "expected {org_id, repo, model_name}"},
1154
+ )
1155
+ return
1156
+
1157
+ run_row = store.latest_pr_opened_run(org_id, repo, model_name)
1158
+ if run_row is None:
1159
+ result = {
1160
+ "reverted": False,
1161
+ "error": "no pr_opened auto-heal run found",
1162
+ }
1163
+ if idem_key:
1164
+ store.finish_idempotency(idem_key, result)
1165
+ _json(handler, HTTPStatus.NOT_FOUND, result)
1166
+ return
1167
+
1168
+ auth = getattr(handler.server, "github_app_auth", None)
1169
+ if auth is None:
1170
+ _json(handler, HTTPStatus.SERVICE_UNAVAILABLE, {"error": "not_configured"})
1171
+ return
1172
+ binding = store.get_repo_binding(org_id, repo)
1173
+ if binding is None:
1174
+ _json(handler, HTTPStatus.NOT_FOUND, {"error": "no repo binding"})
1175
+ return
1176
+ if "/" not in repo:
1177
+ _json(handler, HTTPStatus.BAD_REQUEST, {"error": "repo must be owner/name"})
1178
+ return
1179
+ owner, repo_name = repo.split("/", 1)
1180
+ installation_id = int(binding["installation_id"])
1181
+ base_branch = str(binding["base_branch"])
1182
+ model_path = run_row["model_path"]
1183
+ fingerprint = run_row["fingerprint"]
1184
+
1185
+ try:
1186
+ base_sha = auth.get_branch_sha(
1187
+ installation_id, owner, repo_name, base_branch
1188
+ )
1189
+ commit = auth.get_commit(installation_id, owner, repo_name, base_sha)
1190
+ tree_obj = commit.get("tree") if isinstance(commit, dict) else None
1191
+ base_tree_sha = (
1192
+ str(tree_obj.get("sha"))
1193
+ if isinstance(tree_obj, dict) and tree_obj.get("sha")
1194
+ else ""
1195
+ )
1196
+ if not base_tree_sha:
1197
+ raise ValueError("base commit missing tree.sha")
1198
+ blob_sha = auth.create_blob(
1199
+ installation_id,
1200
+ owner,
1201
+ repo_name,
1202
+ run_row["original_source"].encode("utf-8"),
1203
+ )
1204
+ tree_sha = auth.create_tree(
1205
+ installation_id,
1206
+ owner,
1207
+ repo_name,
1208
+ base_tree_sha,
1209
+ [
1210
+ {
1211
+ "path": model_path,
1212
+ "mode": "100644",
1213
+ "type": "blob",
1214
+ "sha": blob_sha,
1215
+ }
1216
+ ],
1217
+ )
1218
+ revert_sha = auth.create_commit(
1219
+ installation_id,
1220
+ owner,
1221
+ repo_name,
1222
+ f"revert(selfheal): restore {model_name} schema",
1223
+ tree_sha,
1224
+ [base_sha],
1225
+ )
1226
+ revert_ref = (
1227
+ f"selfheal-revert/{model_name.lower()}-{fingerprint[:8]}"
1228
+ )
1229
+ auth.create_ref(installation_id, owner, repo_name, revert_ref, revert_sha)
1230
+ client = auth.client_for_installation(installation_id)
1231
+ pr_payload = client.open_pull_request(
1232
+ owner=owner,
1233
+ repo=repo_name,
1234
+ title=f"revert(selfheal): restore {model_name} schema",
1235
+ head=revert_ref,
1236
+ base=base_branch,
1237
+ body=(
1238
+ "## SelfHeal Revert\n\n"
1239
+ f"Restores `{model_path}` to the pre-remediation source "
1240
+ f"from auto-heal run `{run_row['run_id']}` "
1241
+ f"(fingerprint `{fingerprint}`).\n\n"
1242
+ f"Original remediation PR: {run_row.get('pr_url') or 'n/a'}\n"
1243
+ ),
1244
+ draft=True,
1245
+ )
1246
+ raw_url = pr_payload.get("html_url")
1247
+ pr_url = str(raw_url) if isinstance(raw_url, str) and raw_url else None
1248
+ except Exception as exc: # noqa: BLE001 - report provider failure
1249
+ logger.warning("jobs_revert failed org=%s repo=%s: %s", org_id, repo, exc)
1250
+ result = {"reverted": False, "error": "revert_failed", "detail": str(exc)[:300]}
1251
+ if idem_key:
1252
+ store.finish_idempotency(idem_key, result)
1253
+ _json(handler, HTTPStatus.BAD_GATEWAY, result)
1254
+ return
1255
+
1256
+ store.record_repair_run(
1257
+ org_id=org_id,
1258
+ repo=repo,
1259
+ model_name=model_name,
1260
+ model_path=model_path,
1261
+ fingerprint=fingerprint,
1262
+ original_source=run_row["original_source"],
1263
+ status="reverted",
1264
+ pr_url=pr_url,
1265
+ )
1266
+ result = {
1267
+ "reverted": True,
1268
+ "org_id": org_id,
1269
+ "repo": repo,
1270
+ "model_name": model_name,
1271
+ "run_id": run_row["run_id"],
1272
+ "pr_url": pr_url,
1273
+ }
1274
+ if idem_key:
1275
+ store.finish_idempotency(idem_key, result)
1276
+ _json(handler, HTTPStatus.OK, result)
1277
+
1278
+
1279
+ def run_org_digests(
1280
+ server: Any, *, days: float = 7.0, org_id: str | None = None
1281
+ ) -> dict[str, Any]:
1282
+ """Build (and email, when configured) a per-org weekly drift digest."""
1283
+ registry = server.installation_registry
1284
+ ledger = server.drift_ledger
1285
+ orgs = [org_id] if org_id else registry.list_org_ids()
1286
+ since = time.time() - days * 86400.0
1287
+ email_notifier = getattr(server, "email_notifier", None)
1288
+ results: dict[str, Any] = {"orgs": {}, "emailed": []}
1289
+ for org in orgs:
1290
+ events = ledger.list_events(org_id=org, since=since, limit=1000)
1291
+ by_model: dict[str, int] = {}
1292
+ by_kind: dict[str, int] = {}
1293
+ prs = 0
1294
+ for event in events:
1295
+ if event.has_drift:
1296
+ by_model[event.model_name] = by_model.get(event.model_name, 0) + 1
1297
+ for kind in event.issue_kinds:
1298
+ by_kind[kind] = by_kind.get(kind, 0) + 1
1299
+ if event.pr_url:
1300
+ prs += 1
1301
+ top_models = dict(
1302
+ sorted(by_model.items(), key=lambda kv: -kv[1])[:10]
1303
+ )
1304
+ issue_kinds = dict(sorted(by_kind.items()))
1305
+ digest: dict[str, Any] = {
1306
+ "events": len(events),
1307
+ "drift_events": sum(by_model.values()),
1308
+ "prs_opened": prs,
1309
+ "top_models": top_models,
1310
+ "issue_kinds": issue_kinds,
1311
+ }
1312
+ results["orgs"][org] = digest
1313
+ if email_notifier is not None and int(digest["drift_events"]) > 0:
1314
+ lines = [
1315
+ f"SelfHeal weekly digest — last {days:g} days",
1316
+ f"Org: {org}",
1317
+ f"Drift events: {digest['drift_events']} "
1318
+ f"(PRs opened: {prs})",
1319
+ "",
1320
+ "Top models:",
1321
+ ]
1322
+ for model, count in top_models.items():
1323
+ lines.append(f" - {model}: {count}")
1324
+ if issue_kinds:
1325
+ lines.append("")
1326
+ lines.append("Issue kinds:")
1327
+ for kind, count in issue_kinds.items():
1328
+ lines.append(f" - {kind}: {count}")
1329
+ body_text = "\n".join(lines) + "\n"
1330
+ if email_notifier.send_digest(
1331
+ org, f"[SelfHeal] Weekly digest ({org})", body_text
1332
+ ):
1333
+ results["emailed"].append(org)
1334
+ return results
1335
+
1336
+
1337
+ def start_digest_scheduler(server: Any, *, interval_seconds: float) -> threading.Thread:
1338
+ """In-process weekly digest fallback (SELFHEAL_DIGEST_SCHEDULER=inprocess)."""
1339
+
1340
+ def _loop() -> None:
1341
+ while True:
1342
+ time.sleep(interval_seconds)
1343
+ try:
1344
+ run_org_digests(server)
1345
+ except Exception:
1346
+ logger.exception("digest run failed")
1347
+
1348
+ thread = threading.Thread(target=_loop, name="selfheal-digest", daemon=True)
1349
+ thread.start()
1350
+ return thread
1351
+
1352
+
1353
+ def start_specwatch_scheduler(
1354
+ server: Any, *, interval_seconds: float
1355
+ ) -> threading.Thread:
1356
+ """In-process hourly spec-watch poller (EXP-19)."""
1357
+
1358
+ def _loop() -> None:
1359
+ while True:
1360
+ time.sleep(interval_seconds)
1361
+ try:
1362
+ run_spec_watch_cycle(server.hosted_store)
1363
+ except Exception:
1364
+ logger.exception("spec-watch cycle failed")
1365
+
1366
+ thread = threading.Thread(target=_loop, name="selfheal-specwatch", daemon=True)
1367
+ thread.start()
1368
+ return thread
1369
+
1370
+
1371
+ def _handle_org_settings_patch(
1372
+ handler: SelfHealRequestHandler, org_id: str
1373
+ ) -> None:
1374
+ """PATCH /orgs/<id>/settings — per-org alerting/auto-heal settings."""
1375
+ caller_org = _require_api_key(handler)
1376
+ if caller_org is None:
1377
+ return
1378
+ if caller_org != org_id:
1379
+ _json(handler, HTTPStatus.FORBIDDEN, {"error": "org_id mismatch"})
1380
+ return
1381
+ if not _RATE_LIMITER.allow(f"org-settings:{caller_org}"):
1382
+ _json(handler, HTTPStatus.TOO_MANY_REQUESTS, {"error": "rate_limited"})
1383
+ return
1384
+ body = _read_json_body(handler)
1385
+ if body is None:
1386
+ return
1387
+ allowed = {
1388
+ "auto_heal_enabled",
1389
+ "auto_heal_allowed_kinds",
1390
+ "alert_email",
1391
+ "pagerduty_routing_key",
1392
+ }
1393
+ unknown = set(body) - allowed
1394
+ if unknown:
1395
+ _json(
1396
+ handler,
1397
+ HTTPStatus.BAD_REQUEST,
1398
+ {"error": f"unknown settings fields: {sorted(unknown)}"},
1399
+ )
1400
+ return
1401
+ auto_heal = body.get("auto_heal_enabled")
1402
+ if auto_heal is not None and not isinstance(auto_heal, bool):
1403
+ _json(
1404
+ handler,
1405
+ HTTPStatus.BAD_REQUEST,
1406
+ {"error": "auto_heal_enabled must be a boolean"},
1407
+ )
1408
+ return
1409
+ allowed_kinds = body.get("auto_heal_allowed_kinds")
1410
+ if allowed_kinds is not None and (
1411
+ not isinstance(allowed_kinds, list)
1412
+ or not all(isinstance(k, str) for k in allowed_kinds)
1413
+ ):
1414
+ _json(
1415
+ handler,
1416
+ HTTPStatus.BAD_REQUEST,
1417
+ {"error": "auto_heal_allowed_kinds must be a list of strings"},
1418
+ )
1419
+ return
1420
+ for field in ("alert_email", "pagerduty_routing_key"):
1421
+ value = body.get(field)
1422
+ if value is not None and not isinstance(value, str):
1423
+ _json(
1424
+ handler,
1425
+ HTTPStatus.BAD_REQUEST,
1426
+ {"error": f"{field} must be a string"},
1427
+ )
1428
+ return
1429
+ registry = handler.server.installation_registry
1430
+ record = registry.update_org_settings(
1431
+ org_id,
1432
+ auto_heal_enabled=auto_heal,
1433
+ auto_heal_allowed_kinds=allowed_kinds,
1434
+ alert_email=body.get("alert_email"),
1435
+ pagerduty_routing_key=body.get("pagerduty_routing_key"),
1436
+ )
1437
+ if record is None:
1438
+ _json(handler, HTTPStatus.NOT_FOUND, {"error": "unknown org"})
1439
+ return
1440
+ _json(
1441
+ handler,
1442
+ HTTPStatus.OK,
1443
+ {
1444
+ "org_id": org_id,
1445
+ "auto_heal_enabled": record.auto_heal_enabled,
1446
+ "auto_heal_allowed_kinds": list(record.auto_heal_allowed_kinds),
1447
+ "alert_email": record.alert_email,
1448
+ "pagerduty_routing_key_set": record.pagerduty_routing_key is not None,
1449
+ },
1450
+ )
1451
+
1452
+
1453
+ def _handle_install_done(handler: SelfHealRequestHandler) -> None:
1454
+ html = """<!doctype html>
1455
+ <html lang="en"><head><meta charset="utf-8">
1456
+ <title>SelfHeal — install complete</title>
1457
+ <style>
1458
+ body{font-family:system-ui,sans-serif;max-width:640px;margin:4rem auto;padding:0 1rem;color:#1a1a1a}
1459
+ code{background:#f4f4f4;padding:.15rem .4rem;border-radius:4px}
1460
+ #token{word-break:break-all;background:#f4f4f4;padding:.75rem;border-radius:6px;display:none}
1461
+ button{padding:.5rem 1rem;cursor:pointer}
1462
+ </style></head><body>
1463
+ <h1>SelfHeal installed</h1>
1464
+ <p>Copy this one-time install token (valid 10 minutes), then run:</p>
1465
+ <p><code>selfheal connect --token &lt;token&gt;</code></p>
1466
+ <div id="token"></div>
1467
+ <button id="copy" type="button">Copy token</button>
1468
+ <p id="manual" hidden>Token: <code id="tokval"></code></p>
1469
+ <script>
1470
+ (function(){
1471
+ var m = /[#&]token=([^&]+)/.exec(location.hash + '&');
1472
+ var tok = m ? decodeURIComponent(m[1]) : '';
1473
+ var el = document.getElementById('token');
1474
+ if (tok) { el.textContent = tok; el.style.display='block';
1475
+ document.getElementById('copy').onclick = function(){
1476
+ navigator.clipboard.writeText(tok).then(function(){
1477
+ document.getElementById('copy').textContent='Copied';
1478
+ });
1479
+ };
1480
+ } else {
1481
+ document.getElementById('manual').hidden = false;
1482
+ document.getElementById('copy').hidden = true;
1483
+ }
1484
+ })();
1485
+ </script>
1486
+ </body></html>"""
1487
+ _html(handler, HTTPStatus.OK, html, allow_inline_script=True)
1488
+
1489
+
1490
+ def _handle_connect_specs_list(handler: SelfHealRequestHandler) -> None:
1491
+ org_id = _require_api_key(handler)
1492
+ if org_id is None:
1493
+ return
1494
+ specs = handler.server.hosted_store.list_watched_specs(org_id)
1495
+ _json(handler, HTTPStatus.OK, {"org_id": org_id, "specs": specs})
1496
+
1497
+
1498
+ def _handle_connect_specs_add(handler: SelfHealRequestHandler) -> None:
1499
+ org_id = _require_api_key(handler)
1500
+ if org_id is None:
1501
+ return
1502
+ body = _read_json_body(handler)
1503
+ if body is None:
1504
+ return
1505
+ repo = str(body.get("repo") or "").strip()
1506
+ spec_url = str(body.get("spec_url") or "").strip()
1507
+ if not repo or "/" not in repo:
1508
+ _json(handler, HTTPStatus.BAD_REQUEST, {"error": "repo must be owner/name"})
1509
+ return
1510
+ if not spec_url.startswith(("https://", "http://")):
1511
+ _json(
1512
+ handler,
1513
+ HTTPStatus.BAD_REQUEST,
1514
+ {"error": "spec_url must be http(s)"},
1515
+ )
1516
+ return
1517
+ store: HostedStateStore = handler.server.hosted_store
1518
+ if store.get_repo_binding(org_id, repo) is None:
1519
+ _json(handler, HTTPStatus.NOT_FOUND, {"error": "no repo binding"})
1520
+ return
1521
+ if store.count_watched_specs(org_id) >= MAX_WATCHED_SPECS_PER_ORG:
1522
+ _json(handler, HTTPStatus.CONFLICT, {"error": "spec_watch_limit"})
1523
+ return
1524
+ store.upsert_watched_spec(org_id, repo, spec_url)
1525
+ _json(handler, HTTPStatus.OK, {"org_id": org_id, "repo": repo, "spec_url": spec_url})
1526
+
1527
+
1528
+ def _handle_jobs_spec_watch(handler: SelfHealRequestHandler) -> None:
1529
+ """POST /jobs/spec-watch — one poll cycle over watched specs (JOBS_TOKEN)."""
1530
+ jobs_token = getattr(handler.server, "jobs_token", "") or ""
1531
+ if not jobs_token:
1532
+ _json(handler, HTTPStatus.SERVICE_UNAVAILABLE, {"error": "not_configured"})
1533
+ return
1534
+ if not _RATE_LIMITER.allow(f"jobs-specwatch:{_client_ip(handler)}"):
1535
+ _json(handler, HTTPStatus.TOO_MANY_REQUESTS, {"error": "rate_limited"})
1536
+ return
1537
+ if not hmac.compare_digest(_bearer_token(handler), jobs_token):
1538
+ _json(handler, HTTPStatus.UNAUTHORIZED, {"error": "unauthorized"})
1539
+ return
1540
+ body = _read_json_body(handler) or {}
1541
+ org_id = str(body.get("org_id") or "").strip() or None
1542
+ summary = run_spec_watch_cycle(handler.server.hosted_store, org_id=org_id)
1543
+ _json(handler, HTTPStatus.OK, summary)
1544
+
1545
+
1546
+ def _handle_console(handler: SelfHealRequestHandler, query: dict[str, list[str]]) -> None:
1547
+ """GET /console — per-org integration health console (EXP-15).
1548
+
1549
+ Authenticated by ``shk_*`` bearer key; the key's org is authoritative.
1550
+ An optional ``org_id`` query param must match the key's org (else 403).
1551
+ """
1552
+ org_id = _require_api_key(handler)
1553
+ if org_id is None:
1554
+ return
1555
+ requested = query.get("org_id")
1556
+ if requested and requested[0].strip() and requested[0].strip() != org_id:
1557
+ _json(handler, HTTPStatus.FORBIDDEN, {"error": "org_mismatch"})
1558
+ return
1559
+
1560
+ store = handler.server.hosted_store
1561
+ bindings = store.list_repo_bindings(org_id)
1562
+ repair_runs = store.list_repair_runs(org_id, limit=50)
1563
+ summary = handler.server.drift_ledger.get_org_summary(org_id)
1564
+ events = handler.server.drift_ledger.list_events(org_id=org_id, limit=15)
1565
+ sub = handler.server.billing_store.get_subscription(org_id)
1566
+ org_runs = [
1567
+ {**r, "org_id": org_id} for r in store.list_repair_runs(org_id, limit=200)
1568
+ ]
1569
+ org_events = handler.server.drift_ledger.list_events(
1570
+ org_id=org_id, limit=500
1571
+ )
1572
+ rm = compute_remediation_metrics(org_runs, org_events)
1573
+
1574
+ snap = ConsoleSnapshot(
1575
+ org_id=org_id,
1576
+ plan=str(sub.plan),
1577
+ bindings=bindings,
1578
+ total_events=summary.total_events,
1579
+ drifted_events=summary.drifted_events,
1580
+ recent_events=[ev.model_dump(mode="json") for ev in events],
1581
+ repair_runs=repair_runs,
1582
+ patch_correctness=rm.patch_correctness,
1583
+ regression_rate=rm.regression_rate,
1584
+ ttr_seconds_mean=rm.ttr_seconds_mean,
1585
+ watched_specs=store.list_watched_specs(org_id),
1586
+ spec_events=store.list_spec_events(org_id, limit=20),
1587
+ )
1588
+ _html(handler, HTTPStatus.OK, render_console_html(snap))
1589
+
1590
+
1591
+ def dispatch(handler: SelfHealRequestHandler) -> bool:
1592
+ """Route hosted control-plane paths. Returns True if handled."""
1593
+ parsed = urllib.parse.urlparse(handler.path)
1594
+ path = parsed.path
1595
+ query = urllib.parse.parse_qs(parsed.query)
1596
+ method = handler.command
1597
+
1598
+ if method == "GET" and path == "/install/link":
1599
+ _handle_install_link(handler, query)
1600
+ return True
1601
+ if method == "GET" and path == "/install/callback":
1602
+ _handle_install_callback(handler, query)
1603
+ return True
1604
+ if method == "GET" and path == "/install/done":
1605
+ _handle_install_done(handler)
1606
+ return True
1607
+ if method == "GET" and path in {"/console", "/console/"}:
1608
+ _handle_console(handler, query)
1609
+ return True
1610
+ if method == "POST" and path == "/connect/exchange":
1611
+ _handle_connect_exchange(handler)
1612
+ return True
1613
+ if method == "GET" and path == "/connect/verify":
1614
+ _handle_connect_verify(handler)
1615
+ return True
1616
+ if method == "POST" and path == "/connect/rotate":
1617
+ _handle_connect_rotate(handler)
1618
+ return True
1619
+ if method == "POST" and path == "/connect/bind":
1620
+ _handle_connect_bind(handler)
1621
+ return True
1622
+ if method == "POST" and path == "/billing/checkout-session":
1623
+ _handle_billing_checkout(handler)
1624
+ return True
1625
+ if method == "POST" and path == "/billing/portal-session":
1626
+ _handle_billing_portal(handler)
1627
+ return True
1628
+ if method == "POST" and path == "/jobs/digest":
1629
+ _handle_jobs_digest(handler)
1630
+ return True
1631
+ if method == "POST" and path == "/jobs/revert":
1632
+ _handle_jobs_revert(handler)
1633
+ return True
1634
+ if method == "POST" and path == "/jobs/spec-watch":
1635
+ _handle_jobs_spec_watch(handler)
1636
+ return True
1637
+ if method == "GET" and path == "/connect/specs":
1638
+ _handle_connect_specs_list(handler)
1639
+ return True
1640
+ if method == "POST" and path == "/connect/specs":
1641
+ _handle_connect_specs_add(handler)
1642
+ return True
1643
+ if method == "PATCH" and path.startswith("/orgs/"):
1644
+ rest = path[len("/orgs/") :]
1645
+ suffix = "/settings"
1646
+ if rest.endswith(suffix):
1647
+ org = urllib.parse.unquote(rest[: -len(suffix)]).strip("/")
1648
+ if org and _ORG_ID_RE.match(org):
1649
+ _handle_org_settings_patch(handler, org)
1650
+ return True
1651
+ if method == "DELETE" and path.startswith("/connect/keys/"):
1652
+ key_id = urllib.parse.unquote(path[len("/connect/keys/") :]).strip("/")
1653
+ if key_id:
1654
+ _handle_connect_key_delete(handler, key_id)
1655
+ return True
1656
+ return False