Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 104 additions & 3 deletions engraphis/billing.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,30 @@ def _finalize_webhook(delivery_id: str, fulfillment_id: str,
finally:
conn.close()

def _polar_subscription_id(data: dict, *, object_is_subscription: bool = False) -> str:
"""Extract a Polar subscription id from direct or nested event data."""
from engraphis.inspector.webhooks import _extract_subscription_id
sub_id = _extract_subscription_id(data, object_is_subscription=object_is_subscription)
if sub_id:
return sub_id
order = data.get("order") or {}
if isinstance(order, dict):
return _extract_subscription_id(order)
return ""


def _polar_order_id(data: dict) -> str:
"""Extract a Polar order id from direct or nested event data."""
from engraphis.inspector.webhooks import _extract_order_id
order_id = _extract_order_id(data)
if order_id:
return order_id
order = data.get("order") or {}
if isinstance(order, dict):
return _extract_order_id(order)
return ""


def _release_claims(*claim_ids: str) -> None:
"""Best-effort rollback used only while returning a retryable failure."""
for claim_id in claim_ids:
Expand Down Expand Up @@ -485,6 +509,66 @@ def _order_id(data: dict) -> str:
return ""


def _revoke_refunded_order(data: dict, webhook_id: str) -> JSONResponse:
"""Refunds return the money, so revoke the affected key(s) immediately."""
subscription_id = _polar_subscription_id(data)
order_id = _polar_order_id(data)
if not subscription_id and not order_id:
return JSONResponse({"status": "ignored", "reason": "missing refund target",
"type": "order.refunded"}, status_code=202)

delivery_claim = "dlv:" + webhook_id
if not reserve_webhook(delivery_claim):
logger.info("polar webhook: duplicate refund delivery %s ignored", webhook_id)
return JSONResponse({"status": "duplicate", "revoked": 0}, status_code=202)

try:
from engraphis.inspector.license_registry import (
revoke_by_order, revoke_by_subscription)
if subscription_id:
revoked = revoke_by_subscription(subscription_id)
target = {"subscription_id": subscription_id}
else:
revoked = revoke_by_order(order_id)
target = {"order_id": order_id}
except Exception: # noqa: BLE001 — force Polar to retry if durable revoke failed
release_webhook(delivery_claim)
logger.exception("polar webhook: refund revocation failed")
return JSONResponse({"error": "revocation failed"}, status_code=503)

logger.warning("polar webhook: refund revoked %d license key(s) for %s",
revoked, target)
return JSONResponse({"status": "revoked", "reason": "refund",
"revoked": revoked, **target}, status_code=202)


def _revoke_subscription_event(data: dict, webhook_id: str, *,
reason: str) -> JSONResponse:
"""Definitive subscription revocation: access should end now, not at expiry."""
subscription_id = _polar_subscription_id(data, object_is_subscription=True)
if not subscription_id:
return JSONResponse({"status": "ignored", "reason": "missing subscription id",
"type": "subscription.revoked"}, status_code=202)

delivery_claim = "dlv:" + webhook_id
if not reserve_webhook(delivery_claim):
logger.info("polar webhook: duplicate revocation delivery %s ignored", webhook_id)
return JSONResponse({"status": "duplicate", "revoked": 0}, status_code=202)

try:
from engraphis.inspector.license_registry import revoke_by_subscription
revoked = revoke_by_subscription(subscription_id)
except Exception: # noqa: BLE001 — force Polar to retry if durable revoke failed
release_webhook(delivery_claim)
logger.exception("polar webhook: subscription revocation failed")
return JSONResponse({"error": "revocation failed"}, status_code=503)

logger.warning("polar webhook: %s revoked %d license key(s) for subscription %s",
reason, revoked, subscription_id)
return JSONResponse({"status": "revoked", "reason": reason, "revoked": revoked,
"subscription_id": subscription_id}, status_code=202)


def _event_modified_at(data: dict) -> Optional[float]:
"""Epoch of the event object's own last-modification time, if the payload carries
one (Polar sends ``modified_at`` on Subscription objects). Used to reject an
Expand Down Expand Up @@ -758,16 +842,30 @@ async def polar_webhook(request: Request):
# ONE key per order and ONE per trial, no matter which/how many events fire:
# order.paid -> paid activation, trial conversion, and each renewal
# (a fresh order.paid per cycle). Fulfillment "order:<id>".
# order.refunded -> immediate revocation. Money returned means the key is
# returned too.
# subscription.canceled -> no revocation. The customer paid for the current period;
# the signed key expiry remains the entitlement boundary.
# subscription.revoked -> immediate revocation after the paid period actually ends
# or on merchant/admin immediate revocation.
# subscription.created -> ONLY when the subscription is in a free trial, to grant
# an immediate trial-length key. Fulfillment "trial:<sub id>".
# subscription.updated -> Team seat count changed mid-cycle (add/remove seats via
# the Customer Portal). Only when status is active AND the
# seat count actually differs from the last known baseline
# for this subscription (see get_known_seats /
# the Customer Portal). Only when status is active/trialing
# AND the seat count actually differs from the last known
# baseline for this subscription (see get_known_seats /
# record_known_seats) — trialing updates wait for payment,
# and unrelated updates cannot spam replacement keys.
# A non-trial subscription.created is a no-op: its paid key comes from order.paid, so
# a canceled trial can never keep Pro — the short trial key just expires.
if event_type == "order.refunded":
return _revoke_refunded_order(data, webhook_id)
if event_type in ("subscription.canceled", "subscription.cancelled"):
return JSONResponse({"status": "ignored", "reason": "paid period honored",
"type": event_type}, status_code=202)
if event_type == "subscription.revoked":
return _revoke_subscription_event(data, webhook_id,
reason="subscription_revoked")
pending_seat_baseline = None # (sub_id, seats, event_ts); persisted after key issuance
seat_lock_claim = ""
if event_type == "order.paid":
Expand All @@ -792,6 +890,9 @@ async def polar_webhook(request: Request):
elif event_type == "subscription.updated":
status = event_status
sub_id = str(data.get("id") or "").strip()[:128]
if status == "revoked":
return _revoke_subscription_event(data, webhook_id,
reason="subscription_revoked")
if status != "active" or not sub_id:
return JSONResponse({"status": "ignored", "reason": "not an active "
"subscription", "type": event_type}, status_code=202)
Expand Down
6 changes: 4 additions & 2 deletions engraphis/dashboard_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,11 +93,12 @@ def create_app() -> FastAPI:
# which is why a naive app.mount('/mcp', mcp.streamable_http_app()) raises
# 'Task group is not initialized'). The endpoint is built at '/' inside the sub-app
# so mounting under /mcp lines up (Starlette strips the mount prefix).
import importlib.util as _importlib_util
import contextlib as _contextlib
_mcp_asgi = None
_mcp_mgr = None
try:
if importlib.util.find_spec("mcp") is None:
if _importlib_util.find_spec("mcp") is None:
raise ImportError("the optional mcp package is not installed")
import engraphis.mcp_server as _mcp_mod
# The MCP session manager's run() is once-per-instance, but create_app() may be
Expand Down Expand Up @@ -149,7 +150,7 @@ async def _lifespan(app: FastAPI):
# dashboard; the machine-readable schema remains available behind the normal gate.
app = FastAPI(title="Engraphis Dashboard", docs_url=None, redoc_url=None,
openapi_url="/api/openapi.json", lifespan=_lifespan)
app.state.mcp_over_http = False
app.state.mcp_over_http = _mcp_asgi is not None

# Honour the advertised allow-list on the actual GA dashboard entrypoint. A
# wildcard can never carry browser credentials.
Expand Down Expand Up @@ -322,6 +323,7 @@ async def _auth_gate(request: Request, call_next):
# and authenticated with a per-user bearer token. Each MCP tool then enforces its
# own viewer/member/admin role while reusing the dashboard's shared MemoryService.
if path == "/mcp" or path.startswith("/mcp/"):

if not (team_enabled and auth_store is not None
and licensing.has_feature("team")):
return JSONResponse({"error": "a Team license is required to connect agents",
Expand Down
Loading