orbit-security 1.2.5__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.
Files changed (95) hide show
  1. orbit_security/__init__.py +51 -0
  2. orbit_security/_runtime_paths.py +52 -0
  3. orbit_security/agency_retainer.py +803 -0
  4. orbit_security/agency_teardown_publisher.py +170 -0
  5. orbit_security/agent_perimeter_sentinel.py +144 -0
  6. orbit_security/ast_sentinel.py +661 -0
  7. orbit_security/baseline_diff.py +494 -0
  8. orbit_security/billing/__init__.py +79 -0
  9. orbit_security/billing/catalog.py +275 -0
  10. orbit_security/billing/fulfillment.py +359 -0
  11. orbit_security/billing/onboarding.py +497 -0
  12. orbit_security/billing/stripe_client.py +316 -0
  13. orbit_security/billing/webhooks.py +372 -0
  14. orbit_security/billing_onboarding.py +52 -0
  15. orbit_security/blackboard.py +940 -0
  16. orbit_security/cert_transparency.py +710 -0
  17. orbit_security/cisa_kev.py +432 -0
  18. orbit_security/cli.py +236 -0
  19. orbit_security/cli_handlers/__init__.py +37 -0
  20. orbit_security/cli_handlers/commands.py +310 -0
  21. orbit_security/cli_handlers/diff_cmd.py +100 -0
  22. orbit_security/cli_handlers/scan_cmd.py +265 -0
  23. orbit_security/client_bundle_exporter.py +1436 -0
  24. orbit_security/cloud_sentinels.py +1405 -0
  25. orbit_security/core_affinity.py +101 -0
  26. orbit_security/deal_desk.py +660 -0
  27. orbit_security/dns_cache.py +462 -0
  28. orbit_security/egress_guard.py +349 -0
  29. orbit_security/epss.py +359 -0
  30. orbit_security/event_shuttle.py +434 -0
  31. orbit_security/fleet.py +549 -0
  32. orbit_security/gemini_cli_bridge.py +590 -0
  33. orbit_security/geo_panel.py +455 -0
  34. orbit_security/ghost_dns.py +407 -0
  35. orbit_security/github_sentinel.py +466 -0
  36. orbit_security/ground_truth_gate.py +175 -0
  37. orbit_security/inbox_agent.py +1271 -0
  38. orbit_security/inbox_guardrail.py +278 -0
  39. orbit_security/inbox_triage_bridge.py +166 -0
  40. orbit_security/input_sanitizer.py +130 -0
  41. orbit_security/mailer.py +194 -0
  42. orbit_security/models.py +80 -0
  43. orbit_security/network_bonding.py +331 -0
  44. orbit_security/notifications.py +671 -0
  45. orbit_security/opencode_remediation.py +488 -0
  46. orbit_security/osint_verifier.py +586 -0
  47. orbit_security/perimeter/__init__.py +88 -0
  48. orbit_security/perimeter/_hooks.py +11 -0
  49. orbit_security/perimeter/cms_kev.py +659 -0
  50. orbit_security/perimeter/dns_auth.py +407 -0
  51. orbit_security/perimeter/exposures.py +341 -0
  52. orbit_security/perimeter/http_surface.py +536 -0
  53. orbit_security/perimeter/probes.py +134 -0
  54. orbit_security/perimeter/safety.py +209 -0
  55. orbit_security/perimeter/takeover.py +258 -0
  56. orbit_security/perimeter/tls_monitor.py +670 -0
  57. orbit_security/playtest_guard.py +424 -0
  58. orbit_security/private_alerting.py +415 -0
  59. orbit_security/public_apis_osint.py +134 -0
  60. orbit_security/py.typed +0 -0
  61. orbit_security/radar_lead_enricher.py +645 -0
  62. orbit_security/radar_proposal_stager.py +553 -0
  63. orbit_security/radar_telemetry.py +2088 -0
  64. orbit_security/recon.py +849 -0
  65. orbit_security/recon_harvester.py +463 -0
  66. orbit_security/remediation.py +843 -0
  67. orbit_security/report_verifier.py +421 -0
  68. orbit_security/reporter.py +854 -0
  69. orbit_security/reporting/__init__.py +15 -0
  70. orbit_security/reporting/client_portal.py +691 -0
  71. orbit_security/scanner.py +337 -0
  72. orbit_security/scoring.py +573 -0
  73. orbit_security/sherlock_osint.py +276 -0
  74. orbit_security/signatures.py +454 -0
  75. orbit_security/stripe_checkout.py +489 -0
  76. orbit_security/stripe_webhook.py +226 -0
  77. orbit_security/threat_radar.py +513 -0
  78. orbit_security/tools/__init__.py +193 -0
  79. orbit_security/tools/adhx_client.py +392 -0
  80. orbit_security/tools/attack_tree.py +603 -0
  81. orbit_security/tools/compact_radar_feed.py +209 -0
  82. orbit_security/tools/deploy_oracle_sentinel.py +281 -0
  83. orbit_security/tools/duckdb_analytics.py +302 -0
  84. orbit_security/tools/embedding_search.py +460 -0
  85. orbit_security/tools/everything_search.py +468 -0
  86. orbit_security/tools/ffmpeg_renderer.py +484 -0
  87. orbit_security/tools/gemini_multimodal.py +387 -0
  88. orbit_security/tools/koa_gemma_router.py +367 -0
  89. orbit_security/tools/secret_harvester.py +103 -0
  90. orbit_security/tools/xh_probe.py +546 -0
  91. orbit_security/tools/yt_threat_harvester.py +410 -0
  92. orbit_security-1.2.5.dist-info/METADATA +369 -0
  93. orbit_security-1.2.5.dist-info/RECORD +95 -0
  94. orbit_security-1.2.5.dist-info/WHEEL +4 -0
  95. orbit_security-1.2.5.dist-info/entry_points.txt +5 -0
@@ -0,0 +1,803 @@
1
+ """Orbit Security: Multi-Tenant Agency White-Label Retainer Tier (agency_retainer.py).
2
+
3
+ Provides multi-tenant agency retainer management, tiered subscriptions
4
+ (Starter $299/mo, Scale $499/mo, Enterprise $999/mo), client domain perimeter
5
+ tracking, custom agency domain branding, and white-label portal rendering.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import asdict, dataclass, field
11
+ import datetime
12
+ from enum import Enum
13
+ import html
14
+ import json
15
+ import logging
16
+ from pathlib import Path
17
+ import re
18
+ from typing import Any, Dict, List, Optional, Tuple
19
+
20
+ from orbit_security.models import AgencyBranding, DomainAuditResult, Severity
21
+
22
+ logger = logging.getLogger("orbit_security.agency_retainer")
23
+
24
+ DEFAULT_RETAINERS_DATA_PATH = Path(__file__).resolve().parent.parent.parent / "data" / "agency_retainers.json"
25
+ DEFAULT_LANDING_PORTALS_DIR = Path(__file__).resolve().parent.parent.parent / "landing" / "portals"
26
+ DEFAULT_PORTALS_OUTPUT_DIR = DEFAULT_LANDING_PORTALS_DIR
27
+
28
+
29
+ class RetainerTier(str, Enum):
30
+ STARTER = "Starter" # $299/mo - Up to 15 domains, weekly scans
31
+ SCALE = "Scale" # $499/mo - Up to 50 domains, daily scans, custom portal domain, SLA certs
32
+ ENTERPRISE = "Enterprise" # $999/mo - Unlimited domains, continuous scans, video roasts, dedicated IP pool
33
+
34
+
35
+ @dataclass
36
+ class TierPolicy:
37
+ monthly_price: int
38
+ max_domains: int
39
+ scan_frequency: str
40
+ custom_portal_enabled: bool
41
+ sla_certificates_enabled: bool
42
+ video_roasts_enabled: bool
43
+ webhook_integrations_enabled: bool
44
+
45
+
46
+ TIER_POLICIES: Dict[RetainerTier, TierPolicy] = {
47
+ RetainerTier.STARTER: TierPolicy(
48
+ monthly_price=299,
49
+ max_domains=15,
50
+ scan_frequency="weekly",
51
+ custom_portal_enabled=False,
52
+ sla_certificates_enabled=False,
53
+ video_roasts_enabled=False,
54
+ webhook_integrations_enabled=False,
55
+ ),
56
+ RetainerTier.SCALE: TierPolicy(
57
+ monthly_price=499,
58
+ max_domains=50,
59
+ scan_frequency="daily",
60
+ custom_portal_enabled=True,
61
+ sla_certificates_enabled=True,
62
+ video_roasts_enabled=False,
63
+ webhook_integrations_enabled=True,
64
+ ),
65
+ RetainerTier.ENTERPRISE: TierPolicy(
66
+ monthly_price=999,
67
+ max_domains=-1, # unlimited
68
+ scan_frequency="continuous",
69
+ custom_portal_enabled=True,
70
+ sla_certificates_enabled=True,
71
+ video_roasts_enabled=True,
72
+ webhook_integrations_enabled=True,
73
+ ),
74
+ }
75
+
76
+
77
+ # Maximum number of per-scan snapshots retained per client site (rolling window).
78
+ MAX_SCAN_HISTORY = 12
79
+
80
+
81
+ @dataclass
82
+ class AgencyClientSite:
83
+ domain: str
84
+ client_name: str
85
+ status: str = "active" # active, paused
86
+ last_score: int = 100
87
+ last_grade: str = "A+"
88
+ critical_findings: int = 0
89
+ high_findings: int = 0
90
+ medium_findings: int = 0
91
+ last_scanned: Optional[str] = None
92
+ # Rolling history of prior scans (oldest first). Each entry:
93
+ # {"score", "grade", "critical", "high", "medium", "scanned_at"}.
94
+ scan_history: List[Dict[str, Any]] = field(default_factory=list)
95
+ # Quick last-vs-current comparison (None until a second scan establishes history).
96
+ previous_score: Optional[int] = None
97
+ previous_grade: Optional[str] = None
98
+ score_delta: Optional[int] = None
99
+
100
+ def get_score_trend(self) -> str:
101
+ """Classify the score trend since the previous scan.
102
+
103
+ Returns one of:
104
+ - "baseline": no prior scan history, score_delta is None
105
+ - "improved": score_delta > 0
106
+ - "declined": score_delta < 0
107
+ - "stable": score_delta == 0
108
+ """
109
+ if self.score_delta is None:
110
+ return "baseline"
111
+ if self.score_delta > 0:
112
+ return "improved"
113
+ if self.score_delta < 0:
114
+ return "declined"
115
+ return "stable"
116
+
117
+
118
+ @dataclass
119
+ class AgencyRetainer:
120
+ agency_id: str
121
+ agency_name: str
122
+ tier: RetainerTier = RetainerTier.SCALE
123
+ monthly_price: int = 499
124
+ custom_domain: Optional[str] = None # e.g. "security.eastsideco.com"
125
+ agency_tagline: str = "Managed Web & Security Operations"
126
+ primary_color: str = "#0B132B"
127
+ accent_color: str = "#48CAE4"
128
+ support_email: str = "security@agency.example.com"
129
+ website: str = "https://agency.example.com"
130
+ logo_svg: Optional[str] = None
131
+ client_domains: List[AgencyClientSite] = field(default_factory=list)
132
+ billing_status: str = "active" # active, past_due, trial
133
+ stripe_customer_id: Optional[str] = None # Stripe customer id (from Checkout Session)
134
+ stripe_subscription_id: Optional[str] = None # Stripe subscription id (from Checkout Session)
135
+ sla_guarantee: str = "99.9% Perimeter Uptime & <15-Min Takeover Alert Guarantee"
136
+ created_at: str = field(
137
+ default_factory=lambda: datetime.datetime.now(datetime.timezone.utc).isoformat()
138
+ )
139
+ last_audit_at: Optional[str] = None
140
+
141
+ def get_policy(self) -> TierPolicy:
142
+ return TIER_POLICIES.get(self.tier, TIER_POLICIES[RetainerTier.SCALE])
143
+
144
+ def can_add_domain(self) -> bool:
145
+ policy = self.get_policy()
146
+ if policy.max_domains == -1:
147
+ return True
148
+ return len(self.client_domains) < policy.max_domains
149
+
150
+ def to_branding(self) -> AgencyBranding:
151
+ return AgencyBranding(
152
+ agency_name=self.agency_name,
153
+ agency_tagline=self.agency_tagline,
154
+ primary_color=self.primary_color,
155
+ accent_color=self.accent_color,
156
+ support_email=self.support_email,
157
+ website=self.website,
158
+ )
159
+
160
+
161
+ class AgencyRetainerManager:
162
+ """Manages multi-tenant agency retainers and client domain perimeters."""
163
+
164
+ def __init__(self, data_path: Optional[Path] = None):
165
+ from orbit_security._runtime_paths import resolve_isolated_data_path
166
+
167
+ self.data_path = resolve_isolated_data_path(data_path, DEFAULT_RETAINERS_DATA_PATH)
168
+ self.agencies: Dict[str, AgencyRetainer] = {}
169
+ self.load()
170
+
171
+ def load(self):
172
+ """Loads agency retainers from disk or initializes defaults."""
173
+ if not self.data_path.exists():
174
+ self._populate_seed_agencies()
175
+ self.save()
176
+ return
177
+
178
+ try:
179
+ with open(self.data_path, "r", encoding="utf-8") as f:
180
+ data = json.load(f)
181
+ loaded = {}
182
+ for item in data.get("agencies", []):
183
+ clients = [
184
+ AgencyClientSite(**c) if isinstance(c, dict) else AgencyClientSite(domain=c, client_name=c)
185
+ for c in item.get("client_domains", [])
186
+ ]
187
+ item["client_domains"] = clients
188
+ if "tier" in item and isinstance(item["tier"], str):
189
+ item["tier"] = RetainerTier(item["tier"])
190
+ loaded[item["agency_id"]] = AgencyRetainer(**item)
191
+ self.agencies = loaded
192
+ if not self.agencies:
193
+ self._populate_seed_agencies()
194
+ self.save()
195
+ except Exception as e:
196
+ logger.warning(f"Error loading agency retainers: {e}")
197
+ self._populate_seed_agencies()
198
+
199
+ def save(self):
200
+ """Persists retainers to disk."""
201
+ self.data_path.parent.mkdir(parents=True, exist_ok=True)
202
+ raw_agencies = []
203
+ for a in self.agencies.values():
204
+ d = asdict(a)
205
+ d["tier"] = a.tier.value
206
+ raw_agencies.append(d)
207
+
208
+ data = {
209
+ "version": "1.0",
210
+ "updated_at": datetime.datetime.now(datetime.timezone.utc).isoformat(),
211
+ "agencies": raw_agencies,
212
+ }
213
+ with open(self.data_path, "w", encoding="utf-8") as f:
214
+ json.dump(data, f, indent=2)
215
+
216
+ def _populate_seed_agencies(self):
217
+ """Default seed partner agencies in Cohort 2 ready for retainer portals."""
218
+ seeds = [
219
+ AgencyRetainer(
220
+ agency_id="eastside-co",
221
+ agency_name="Eastside Co",
222
+ tier=RetainerTier.SCALE,
223
+ monthly_price=499,
224
+ custom_domain="security.eastsideco.com",
225
+ agency_tagline="Enterprise Shopify Plus Technical Solutions",
226
+ primary_color="#0B132B",
227
+ accent_color="#48CAE4",
228
+ support_email="ops@eastsideco.com",
229
+ website="https://eastsideco.com",
230
+ client_domains=[
231
+ AgencyClientSite(domain="candykittens.co.uk", client_name="Candy Kittens", last_score=85, last_grade="B"),
232
+ AgencyClientSite(domain="wildfang.com", client_name="Wildfang Apparel", last_score=95, last_grade="A+"),
233
+ AgencyClientSite(domain="trolli.com", client_name="Trolli Candies", last_score=75, last_grade="C", critical_findings=1),
234
+ ],
235
+ ),
236
+ AgencyRetainer(
237
+ agency_id="we-make-websites",
238
+ agency_name="We Make Websites",
239
+ tier=RetainerTier.SCALE,
240
+ monthly_price=499,
241
+ custom_domain="security.wemakewebsites.com",
242
+ agency_tagline="The International Shopify Plus Agency",
243
+ primary_color="#181824",
244
+ accent_color="#6366F1",
245
+ support_email="ops@wemakewebsites.com",
246
+ website="https://wemakewebsites.com",
247
+ client_domains=[
248
+ AgencyClientSite(domain="haslemerecellar.co.uk", client_name="Haslemere Cellar", last_score=92, last_grade="A"),
249
+ AgencyClientSite(domain="skinnydip.com", client_name="Skinnydip London", last_score=88, last_grade="A"),
250
+ ],
251
+ ),
252
+ AgencyRetainer(
253
+ agency_id="barrel",
254
+ agency_name="Barrel",
255
+ tier=RetainerTier.STARTER,
256
+ monthly_price=299,
257
+ custom_domain="security.barrelny.com",
258
+ agency_tagline="Digital Marketing & DTC Commerce Architecture",
259
+ primary_color="#111827",
260
+ accent_color="#10B981",
261
+ support_email="support@barrelny.com",
262
+ website="https://barrelny.com",
263
+ client_domains=[
264
+ AgencyClientSite(domain="edenbrothers.com", client_name="Eden Brothers", last_score=90, last_grade="A"),
265
+ ],
266
+ ),
267
+ AgencyRetainer(
268
+ agency_id="swanky",
269
+ agency_name="Swanky Agency",
270
+ tier=RetainerTier.SCALE,
271
+ monthly_price=499,
272
+ custom_domain="security.swankyagency.com",
273
+ agency_tagline="Global Shopify Plus & Subscription Specialists",
274
+ primary_color="#0F172A",
275
+ accent_color="#F59E0B",
276
+ support_email="support@swankyagency.com",
277
+ website="https://swankyagency.com",
278
+ client_domains=[
279
+ AgencyClientSite(domain="loop-earplugs.com", client_name="Loop Earplugs", last_score=96, last_grade="A+"),
280
+ AgencyClientSite(domain="chillysbottles.com", client_name="Chilly's Bottles", last_score=84, last_grade="B"),
281
+ ],
282
+ ),
283
+ ]
284
+ self.agencies = {a.agency_id: a for a in seeds}
285
+
286
+ def register_agency(
287
+ self,
288
+ agency_id: str,
289
+ agency_name: str,
290
+ tier: RetainerTier = RetainerTier.SCALE,
291
+ custom_domain: Optional[str] = None,
292
+ support_email: Optional[str] = None,
293
+ primary_color: str = "#0F172A",
294
+ accent_color: str = "#3B82F6",
295
+ agency_tagline: str = "Managed Web & Security Operations",
296
+ website: str = "https://example.com",
297
+ ) -> AgencyRetainer:
298
+ """Enrolls a new web agency into an Orbit White-Label Retainer tier."""
299
+ clean_id = re.sub(r"[^a-zA-Z0-9_-]", "-", agency_id.lower().strip())
300
+ policy = TIER_POLICIES.get(tier, TIER_POLICIES[RetainerTier.SCALE])
301
+
302
+ retainer = AgencyRetainer(
303
+ agency_id=clean_id,
304
+ agency_name=agency_name,
305
+ tier=tier,
306
+ monthly_price=policy.monthly_price,
307
+ custom_domain=custom_domain,
308
+ agency_tagline=agency_tagline,
309
+ primary_color=primary_color,
310
+ accent_color=accent_color,
311
+ support_email=support_email or f"ops@{clean_id}.example.com",
312
+ website=website,
313
+ )
314
+ self.agencies[clean_id] = retainer
315
+ self.save()
316
+ return retainer
317
+
318
+ def get_agency(self, agency_id: str) -> Optional[AgencyRetainer]:
319
+ return self.agencies.get(agency_id)
320
+
321
+ def list_agencies(self) -> List[AgencyRetainer]:
322
+ return list(self.agencies.values())
323
+
324
+ def add_client_domain(
325
+ self,
326
+ agency_id: str,
327
+ domain: str,
328
+ client_name: Optional[str] = None,
329
+ ) -> bool:
330
+ """Adds a client domain under an agency's retainer quota."""
331
+ agency = self.get_agency(agency_id)
332
+ if not agency:
333
+ raise KeyError(f"Agency '{agency_id}' not found.")
334
+
335
+ if not agency.can_add_domain():
336
+ limit = agency.get_policy().max_domains
337
+ raise ValueError(
338
+ f"Agency '{agency.agency_name}' has reached its {agency.tier.value} tier domain limit ({limit} domains). "
339
+ "Upgrade to Scale or Enterprise to add more client perimeters."
340
+ )
341
+
342
+ clean_domain = domain.strip().lower()
343
+ for site in agency.client_domains:
344
+ if site.domain == clean_domain:
345
+ return False # Already monitored
346
+
347
+ agency.client_domains.append(
348
+ AgencyClientSite(
349
+ domain=clean_domain,
350
+ client_name=client_name or clean_domain,
351
+ )
352
+ )
353
+ self.save()
354
+ return True
355
+
356
+ def remove_client_domain(self, agency_id: str, domain: str) -> bool:
357
+ """Removes a client domain from an agency's monitoring list."""
358
+ agency = self.get_agency(agency_id)
359
+ if not agency:
360
+ return False
361
+
362
+ clean_domain = domain.strip().lower()
363
+ initial_len = len(agency.client_domains)
364
+ agency.client_domains = [s for s in agency.client_domains if s.domain != clean_domain]
365
+ if len(agency.client_domains) < initial_len:
366
+ self.save()
367
+ return True
368
+ return False
369
+
370
+ def update_site_audit(
371
+ self,
372
+ agency_id: str,
373
+ domain: str,
374
+ score: int,
375
+ grade: str,
376
+ critical_count: int = 0,
377
+ high_count: int = 0,
378
+ medium_count: int = 0,
379
+ ) -> bool:
380
+ """Updates security score and findings counts for an agency client site."""
381
+ agency = self.get_agency(agency_id)
382
+ if not agency:
383
+ return False
384
+
385
+ clean_domain = domain.strip().lower()
386
+ now_iso = datetime.datetime.now(datetime.timezone.utc).isoformat()
387
+ agency.last_audit_at = now_iso
388
+
389
+ for site in agency.client_domains:
390
+ if site.domain == clean_domain:
391
+ # Snapshot the *pre-update* values onto the rolling history first,
392
+ # so we can diff old vs. new before overwriting.
393
+ has_prior_scan = site.last_scanned is not None
394
+ if has_prior_scan:
395
+ site.scan_history.append(
396
+ {
397
+ "score": site.last_score,
398
+ "grade": site.last_grade,
399
+ "critical": site.critical_findings,
400
+ "high": site.high_findings,
401
+ "medium": site.medium_findings,
402
+ "scanned_at": site.last_scanned,
403
+ }
404
+ )
405
+ # Cap the rolling window to the most recent MAX_SCAN_HISTORY entries.
406
+ if len(site.scan_history) > MAX_SCAN_HISTORY:
407
+ site.scan_history = site.scan_history[-MAX_SCAN_HISTORY:]
408
+ site.previous_score = site.last_score
409
+ site.previous_grade = site.last_grade
410
+ site.score_delta = score - site.last_score
411
+ else:
412
+ # First real scan: baseline established, no delta yet.
413
+ site.previous_score = None
414
+ site.previous_grade = None
415
+ site.score_delta = None
416
+
417
+ site.last_score = score
418
+ site.last_grade = grade
419
+ site.critical_findings = critical_count
420
+ site.high_findings = high_count
421
+ site.medium_findings = medium_count
422
+ site.last_scanned = now_iso
423
+ self.save()
424
+ return True
425
+ return False
426
+
427
+ def export_agency_posture_pdf(
428
+ self,
429
+ agency_id: str,
430
+ output_dir: Optional[Path] = None,
431
+ kev_epss_highlights: Optional[List[Dict[str, Any]]] = None,
432
+ ) -> Path:
433
+ """Generates a White-Label Executive Fleet Posture PDF for an enrolled agency (Project #4)."""
434
+ from orbit_security.reporter import ReportGenerator
435
+
436
+ agency = self.get_agency(agency_id)
437
+ if not agency:
438
+ raise KeyError(f"Agency '{agency_id}' not found.")
439
+
440
+ out_dir = Path(output_dir or (DEFAULT_RETAINERS_DATA_PATH.parent / "reports"))
441
+ out_dir.mkdir(parents=True, exist_ok=True)
442
+ out_path = out_dir / f"{agency.agency_id}_security_posture.pdf"
443
+ ReportGenerator.generate_white_label_fleet_pdf(
444
+ agency=agency,
445
+ output_path=str(out_path),
446
+ kev_epss_highlights=kev_epss_highlights,
447
+ )
448
+ return out_path
449
+
450
+
451
+ class AgencyPortalRenderer:
452
+ """Generates standalone, responsive HTML/CSS/JS co-branded portals for agency retainers."""
453
+
454
+ @staticmethod
455
+ def render_portal_html(agency: AgencyRetainer) -> str:
456
+ """Renders an interactive, client-ready security portal for the agency."""
457
+ p_color = agency.primary_color
458
+ a_color = agency.accent_color
459
+ domains = agency.client_domains
460
+ total_domains = len(domains)
461
+ avg_score = int(sum(d.last_score for d in domains) / total_domains) if total_domains > 0 else 100
462
+ critical_total = sum(d.critical_findings for d in domains)
463
+ high_total = sum(d.high_findings for d in domains)
464
+
465
+ # Build table rows
466
+ rows_html = []
467
+ for site in domains:
468
+ score = site.last_score
469
+ grade = site.last_grade
470
+ badge_color = "#10B981" if score >= 88 else ("#F59E0B" if score >= 70 else "#EF4444")
471
+ status_text = "🟢 SECURE" if score >= 88 else ("🟡 WARNING" if score >= 70 else "🔴 AT RISK")
472
+ last_scanned_fmt = (
473
+ site.last_scanned[:16].replace("T", " ") if site.last_scanned else "Scheduled"
474
+ )
475
+
476
+ # Per-client change indicator (delta badge + trend arrow).
477
+ trend = site.get_score_trend()
478
+ if trend == "baseline":
479
+ delta_html = (
480
+ '<span class="px-1.5 py-0.5 rounded text-[10px] font-bold font-mono text-gray-400 '
481
+ 'bg-gray-800/60 border border-gray-700" title="First scan — baseline established">baseline</span>'
482
+ )
483
+ else:
484
+ delta_val = int(site.score_delta or 0)
485
+ delta_color = "#10B981" if trend == "improved" else ("#EF4444" if trend == "declined" else "#94A3B8")
486
+ arrow = "↑" if trend == "improved" else ("↓" if trend == "declined" else "→")
487
+ sign = "+" if delta_val > 0 else ""
488
+ delta_html = (
489
+ f'<span class="ml-1.5 px-1.5 py-0.5 rounded text-[10px] font-bold font-mono" '
490
+ f'style="color: {delta_color}; background: {delta_color}22; border: 1px solid {delta_color}55" '
491
+ f'title="Change since last scan">{arrow} {sign}{delta_val}</span>'
492
+ )
493
+
494
+ rows_html.append(f"""
495
+ <tr class="border-b border-gray-800 hover:bg-gray-800/40 transition">
496
+ <td class="py-4 px-6 font-medium text-white flex items-center gap-3">
497
+ <span class="w-2.5 h-2.5 rounded-full" style="background-color: {badge_color}"></span>
498
+ <div>
499
+ <div class="font-bold">{html.escape(site.client_name)}</div>
500
+ <div class="text-xs text-gray-400 font-mono">{html.escape(site.domain)}</div>
501
+ </div>
502
+ </td>
503
+ <td class="py-4 px-6 text-center">
504
+ <span class="px-2.5 py-1 rounded text-xs font-bold font-mono" style="background-color: {badge_color}22; color: {badge_color}; border: 1px solid {badge_color}55">
505
+ {score}/100 ({grade})
506
+ </span>{delta_html}
507
+ </td>
508
+ <td class="py-4 px-6 text-center">
509
+ <span class="text-xs font-semibold px-2 py-0.5 rounded {'text-red-400 bg-red-950/40 border border-red-800/50' if site.critical_findings > 0 else 'text-gray-400'}">
510
+ {site.critical_findings} Critical / {site.high_findings} High
511
+ </span>
512
+ </td>
513
+ <td class="py-4 px-6 text-center text-xs text-gray-400 font-mono">
514
+ {last_scanned_fmt}
515
+ </td>
516
+ <td class="py-4 px-6 text-right">
517
+ <div class="flex items-center justify-end gap-2">
518
+ <button onclick="auditDomain('{html.escape(site.domain)}')" class="px-3 py-1.5 rounded text-xs font-semibold text-white bg-blue-600/30 hover:bg-blue-600/60 border border-blue-500/50 transition flex items-center gap-1.5">
519
+ <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>
520
+ Audit Now
521
+ </button>
522
+ <button onclick="downloadReport('{html.escape(site.domain)}', '{html.escape(site.client_name)}', {score})" class="px-3 py-1.5 rounded text-xs font-semibold text-gray-200 bg-gray-800 hover:bg-gray-700 border border-gray-700 transition flex items-center gap-1.5">
523
+ <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
524
+ Report
525
+ </button>
526
+ </div>
527
+ </td>
528
+ </tr>
529
+ """)
530
+
531
+ rows_joined = "\n".join(rows_html)
532
+
533
+ html_content = f"""<!DOCTYPE html>
534
+ <html lang="en" class="dark">
535
+ <head>
536
+ <meta charset="UTF-8">
537
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
538
+ <title>{html.escape(agency.agency_name)} | Client Security Fleet Command</title>
539
+ <script src="https://cdn.tailwindcss.com"></script>
540
+ <style>
541
+ :root {{
542
+ --agency-primary: {p_color};
543
+ --agency-accent: {a_color};
544
+ }}
545
+ body {{
546
+ background-color: #0b0f17;
547
+ color: #e2e8f0;
548
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
549
+ }}
550
+ .brand-gradient {{
551
+ background: linear-gradient(135deg, {p_color} 0%, #1e293b 100%);
552
+ }}
553
+ .accent-border {{
554
+ border-color: {a_color};
555
+ }}
556
+ .accent-text {{
557
+ color: {a_color};
558
+ }}
559
+ .accent-bg {{
560
+ background-color: {a_color};
561
+ }}
562
+ </style>
563
+ </head>
564
+ <body class="min-h-screen flex flex-col">
565
+
566
+ <!-- Top Navigation Bar -->
567
+ <header class="border-b border-gray-800 bg-[#0d131f]/80 backdrop-blur-md sticky top-0 z-50">
568
+ <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-16 flex items-center justify-between">
569
+ <div class="flex items-center gap-3">
570
+ <div class="w-9 h-9 rounded-lg flex items-center justify-center font-bold text-white shadow-lg" style="background: linear-gradient(135deg, {a_color}, {p_color});">
571
+ 🛡️
572
+ </div>
573
+ <div>
574
+ <h1 class="text-base font-bold text-white tracking-tight">{html.escape(agency.agency_name)}</h1>
575
+ <p class="text-xs text-gray-400">{html.escape(agency.agency_tagline)}</p>
576
+ </div>
577
+ </div>
578
+ <div class="flex items-center gap-4">
579
+ <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">
580
+ <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 mr-2 animate-pulse"></span>
581
+ {agency.tier.value} SLA Retainer Active
582
+ </span>
583
+ {f'<span class="text-xs font-mono text-gray-400 hidden sm:inline-block px-2.5 py-1 bg-gray-800/80 rounded border border-gray-700">{html.escape(agency.custom_domain)}</span>' if agency.custom_domain else ''}
584
+ <a href="mailto:{html.escape(agency.support_email)}" class="text-xs font-semibold px-3 py-1.5 rounded bg-gray-800 hover:bg-gray-700 text-gray-200 border border-gray-700 transition">
585
+ Contact Ops
586
+ </a>
587
+ </div>
588
+ </div>
589
+ </header>
590
+
591
+ <!-- Main Command Center Body -->
592
+ <main class="flex-1 max-w-7xl w-full mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-8">
593
+
594
+ <!-- Executive Banner -->
595
+ <div class="rounded-2xl p-6 sm:p-8 border border-gray-800 relative overflow-hidden brand-gradient shadow-2xl">
596
+ <div class="relative z-10 max-w-3xl">
597
+ <div class="inline-block px-3 py-1 rounded text-xs font-semibold uppercase tracking-wider text-cyan-300 bg-cyan-950/60 border border-cyan-800/60 mb-3">
598
+ Managed Perimeter Hygiene & Sentinel Protection
599
+ </div>
600
+ <h2 class="text-2xl sm:text-3xl font-extrabold text-white tracking-tight">
601
+ Client Attack Surface & DNS Security Fleet
602
+ </h2>
603
+ <p class="mt-2 text-sm text-gray-300">
604
+ Continuous 24/7 DNS audit sentinel, subdomain takeover prevention, and email authentication enforcement for your client portfolio.
605
+ </p>
606
+ <div class="mt-4 flex flex-wrap gap-4 text-xs font-mono text-gray-300">
607
+ <span class="flex items-center gap-1.5">
608
+ <svg class="w-4 h-4 text-emerald-400" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/></svg>
609
+ {agency.sla_guarantee}
610
+ </span>
611
+ </div>
612
+ </div>
613
+ </div>
614
+
615
+ <!-- Telemetry Metrics Grid -->
616
+ <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
617
+ <div class="bg-[#0f172a]/60 rounded-xl p-5 border border-gray-800 shadow">
618
+ <div class="text-xs font-medium text-gray-400 uppercase tracking-wider">Monitored Perimeters</div>
619
+ <div class="mt-2 flex items-baseline justify-between">
620
+ <div class="text-3xl font-black text-white font-mono">{total_domains}</div>
621
+ <span class="text-xs font-semibold text-emerald-400 bg-emerald-950/50 px-2 py-0.5 rounded border border-emerald-800/40">100% Active</span>
622
+ </div>
623
+ </div>
624
+ <div class="bg-[#0f172a]/60 rounded-xl p-5 border border-gray-800 shadow">
625
+ <div class="text-xs font-medium text-gray-400 uppercase tracking-wider">Fleet Health Average</div>
626
+ <div class="mt-2 flex items-baseline justify-between">
627
+ <div class="text-3xl font-black text-white font-mono">{avg_score}/100</div>
628
+ <span class="text-xs font-semibold {'text-emerald-400 bg-emerald-950/50 border-emerald-800/40' if avg_score >= 88 else 'text-amber-400 bg-amber-950/50 border-amber-800/40'} px-2 py-0.5 rounded border">
629
+ {'Grade A+' if avg_score >= 95 else ('Grade A' if avg_score >= 88 else 'Attention')}
630
+ </span>
631
+ </div>
632
+ </div>
633
+ <div class="bg-[#0f172a]/60 rounded-xl p-5 border border-gray-800 shadow">
634
+ <div class="text-xs font-medium text-gray-400 uppercase tracking-wider">Critical Takeover Flaws</div>
635
+ <div class="mt-2 flex items-baseline justify-between">
636
+ <div class="text-3xl font-black {'text-red-400' if critical_total > 0 else 'text-emerald-400'} font-mono">{critical_total}</div>
637
+ <span class="text-xs font-semibold {'text-red-400 bg-red-950/50 border-red-800/40' if critical_total > 0 else 'text-emerald-400 bg-emerald-950/50 border-emerald-800/40'} px-2 py-0.5 rounded border">
638
+ {'Requires Action' if critical_total > 0 else 'Zero Dangling CNAMEs'}
639
+ </span>
640
+ </div>
641
+ </div>
642
+ <div class="bg-[#0f172a]/60 rounded-xl p-5 border border-gray-800 shadow">
643
+ <div class="text-xs font-medium text-gray-400 uppercase tracking-wider">Retainer Tier SLA</div>
644
+ <div class="mt-2 flex items-baseline justify-between">
645
+ <div class="text-2xl font-black text-cyan-400 font-mono">${agency.monthly_price}<span class="text-xs text-gray-400">/mo</span></div>
646
+ <span class="text-xs font-semibold text-cyan-400 bg-cyan-950/50 px-2 py-0.5 rounded border border-cyan-800/40">{agency.tier.value}</span>
647
+ </div>
648
+ </div>
649
+ </div>
650
+
651
+ <!-- Managed Client Fleet Table -->
652
+ <div class="bg-[#0f172a]/80 rounded-xl border border-gray-800 shadow-xl overflow-hidden">
653
+ <div class="px-6 py-4 border-b border-gray-800 flex items-center justify-between">
654
+ <div>
655
+ <h3 class="text-lg font-bold text-white">Client Portfolio Health</h3>
656
+ <p class="text-xs text-gray-400">Live perimetral posture across all enrolled client domains</p>
657
+ </div>
658
+ <span class="text-xs font-mono text-gray-400">{total_domains} Domains Enrolled</span>
659
+ </div>
660
+
661
+ <div class="overflow-x-auto">
662
+ <table class="w-full text-left text-sm text-gray-300">
663
+ <thead class="bg-[#0b0f17]/90 text-xs uppercase font-semibold text-gray-400 border-b border-gray-800">
664
+ <tr>
665
+ <th class="py-3 px-6">Client & Domain</th>
666
+ <th class="py-3 px-6 text-center">Hygiene Score</th>
667
+ <th class="py-3 px-6 text-center">Vulnerabilities</th>
668
+ <th class="py-3 px-6 text-center">Last Scan</th>
669
+ <th class="py-3 px-6 text-right">Actions</th>
670
+ </tr>
671
+ </thead>
672
+ <tbody>
673
+ {rows_joined}
674
+ </tbody>
675
+ </table>
676
+ </div>
677
+ </div>
678
+
679
+ </main>
680
+
681
+ <!-- Footer -->
682
+ <footer class="border-t border-gray-800 bg-[#0d131f] py-6 text-center text-xs text-gray-500">
683
+ <div class="max-w-7xl mx-auto px-4 flex flex-col sm:flex-row items-center justify-between gap-4">
684
+ <p>© {datetime.datetime.now().year} {html.escape(agency.agency_name)}. All Rights Reserved. Managed Security Retainer.</p>
685
+ <p class="font-mono text-gray-600">Encrypted Transport • Automated DNS Sentinel • 24/7 SLA Guarantee</p>
686
+ </div>
687
+ </footer>
688
+
689
+ <!-- Interactive Client-Side Audit & Report Scripts -->
690
+ <script>
691
+ function auditDomain(domain) {{
692
+ alert('Initiating real-time DoH audit for ' + domain + '... Resolving DNS perimeter...');
693
+ window.open('https://dns.google/resolve?name=' + encodeURIComponent(domain) + '&type=ANY', '_blank');
694
+ }}
695
+
696
+ function downloadReport(domain, clientName, score) {{
697
+ const reportText = `# Security Audit Report - ${{clientName}} (${{domain}})\\n` +
698
+ `Prepared by: {agency.agency_name} ({agency.agency_tagline})\\n` +
699
+ `Audit Score: ${{score}}/100\\n` +
700
+ `Date: ${{new Date().toUTCString()}}\\n\\n` +
701
+ `## Executive Summary\\nThis report verifies the external DNS hygiene and attack surface perimeter for ${{domain}} under the {agency.agency_name} Retainer SLA.\\n\\n` +
702
+ `Status: ${{score >= 88 ? 'CLEAN & COMPLIANT' : 'REMEDIATION RECOMMENDED'}}\\n`;
703
+
704
+ const blob = new Blob([reportText], {{ type: 'text/markdown' }});
705
+ const url = URL.createObjectURL(blob);
706
+ const a = document.createElement('a');
707
+ a.href = url;
708
+ a.download = `security_audit_${{domain.replace(/[^a-zA-Z0-9]/g, '_')}}.md`;
709
+ a.click();
710
+ URL.revokeObjectURL(url);
711
+ }}
712
+ </script>
713
+ </body>
714
+ </html>"""
715
+ return html_content
716
+
717
+ @staticmethod
718
+ def save_portal(
719
+ agency: AgencyRetainer,
720
+ output_dir: Optional[Path] = None,
721
+ landing_dir: Optional[Path] = None,
722
+ ) -> Tuple[Path, Optional[Path]]:
723
+ """Generates and writes portal HTML files for docs/ and landing/ sites."""
724
+ from orbit_security._runtime_paths import is_pytest_active, resolve_isolated_data_path
725
+
726
+ out_dir = resolve_isolated_data_path(output_dir, DEFAULT_PORTALS_OUTPUT_DIR)
727
+ out_dir.mkdir(parents=True, exist_ok=True)
728
+ file_path = out_dir / f"{agency.agency_id}.html"
729
+
730
+ html_content = AgencyPortalRenderer.render_portal_html(agency)
731
+ with open(file_path, "w", encoding="utf-8") as f:
732
+ f.write(html_content)
733
+
734
+ landing_path: Optional[Path] = None
735
+ if landing_dir is not None:
736
+ landing_dir.mkdir(parents=True, exist_ok=True)
737
+ landing_path = landing_dir / f"{agency.agency_id}.html"
738
+ with open(landing_path, "w", encoding="utf-8") as f:
739
+ f.write(html_content)
740
+ elif not is_pytest_active() and (output_dir is None or Path(output_dir) == DEFAULT_PORTALS_OUTPUT_DIR):
741
+ if DEFAULT_LANDING_PORTALS_DIR.parent.exists():
742
+ DEFAULT_LANDING_PORTALS_DIR.mkdir(parents=True, exist_ok=True)
743
+ landing_path = DEFAULT_LANDING_PORTALS_DIR / f"{agency.agency_id}.html"
744
+ with open(landing_path, "w", encoding="utf-8") as f:
745
+ f.write(html_content)
746
+
747
+ return file_path, landing_path
748
+
749
+ @staticmethod
750
+ def provision_all_enrolled_portals(
751
+ manager: AgencyRetainerManager,
752
+ docs_dir: Optional[Path] = None,
753
+ landing_dir: Optional[Path] = None,
754
+ ) -> Dict[str, Any]:
755
+ """Batch provisions co-branded HTML portals and partner directory index for all enrolled agencies (Project #14)."""
756
+ from orbit_security._runtime_paths import resolve_isolated_data_path
757
+
758
+ out_docs = resolve_isolated_data_path(docs_dir, DEFAULT_PORTALS_OUTPUT_DIR)
759
+ out_landing = resolve_isolated_data_path(landing_dir, DEFAULT_LANDING_PORTALS_DIR)
760
+ out_docs.mkdir(parents=True, exist_ok=True)
761
+ out_landing.mkdir(parents=True, exist_ok=True)
762
+
763
+ agencies = manager.list_agencies()
764
+ provisioned: List[str] = []
765
+ directory_cards: List[str] = []
766
+
767
+ for agency in agencies:
768
+ AgencyPortalRenderer.save_portal(agency, output_dir=out_docs, landing_dir=out_landing)
769
+ provisioned.append(agency.agency_id)
770
+ dom_count = len(agency.client_domains)
771
+ avg_score = int(sum(d.last_score for d in agency.client_domains) / dom_count) if dom_count else 100
772
+ directory_cards.append(
773
+ f'<a href="{html.escape(agency.agency_id)}.html" class="block p-5 rounded-xl bg-slate-900 border border-slate-800 hover:border-cyan-500/50 transition">'
774
+ f'<div class="flex items-center justify-between mb-2">'
775
+ f'<span class="font-bold text-white text-base">{html.escape(agency.agency_name)}</span>'
776
+ f'<span class="px-2 py-0.5 rounded text-xs font-mono bg-emerald-500/10 text-emerald-400 border border-emerald-500/30">{avg_score}/100</span>'
777
+ f'</div>'
778
+ f'<p class="text-xs text-slate-400 mb-3">{html.escape(agency.agency_tagline)}</p>'
779
+ f'<div class="text-[11px] font-mono text-cyan-400">{dom_count} Enrolled Domains &bull; {html.escape(agency.tier.value)} Tier &rarr;</div>'
780
+ f'</a>'
781
+ )
782
+
783
+ index_html = (
784
+ "<!DOCTYPE html>\n<html lang=\"en\" class=\"dark\">\n<head>\n"
785
+ "<meta charset=\"UTF-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n"
786
+ "<title>Orbit Security | Enrolled Agency White-Label Portals</title>\n"
787
+ "<script src=\"https://cdn.tailwindcss.com\"></script>\n"
788
+ "</head>\n<body class=\"bg-[#0b0f17] text-slate-200 min-h-screen p-8 font-sans\">\n"
789
+ "<div class=\"max-w-5xl mx-auto space-y-6\">\n"
790
+ "<h1 class=\"text-2xl font-extrabold text-white\">Enrolled Agency Partner Portals</h1>\n"
791
+ "<div class=\"grid grid-cols-1 md:grid-cols-2 gap-4\">\n"
792
+ + "\n".join(directory_cards)
793
+ + "\n</div>\n</div>\n</body>\n</html>\n"
794
+ )
795
+ (out_docs / "index.html").write_text(index_html, encoding="utf-8")
796
+ (out_landing / "index.html").write_text(index_html, encoding="utf-8")
797
+
798
+ return {
799
+ "provisioned_count": len(provisioned),
800
+ "agency_ids": provisioned,
801
+ "docs_dir": str(out_docs),
802
+ "landing_dir": str(out_landing),
803
+ }