Introducing a new way to review your PRs.

Read the announcement

koala73 / worldmonitor

Real-time global intelligence dashboard. AI-powered news aggregation, geopolitical monitoring, and infrastructure tracking in a unified situational awareness interface

View on GitHub

29 documents · Updated Nov 20, 2026

docs / access-control-and-subscriptions

Access control and subscriptions

World Monitor turns a signed-in identity into current product access. Clerk supplies identity and sessions. Convex stores account, billing, preference, and entitlement state. Dodo Payments handles paid plans. The result controls dashboard features, API credentials, usage budgets, checkout, billing self-service, user settings, and MCP client access. See Access and commerce and Convex schema and jobs for the wider product and data-flow boundaries.

Identity and sessions

Identity and sessions establish which account a request belongs to before the system reads account data or performs a protected action. The browser uses Clerk session state, while server paths verify the session and bind account work to the Clerk user ID.

Account identity

The Clerk user ID is the account key. Account records hold product context such as locale, time zone, country, and activity times. Paid-customer records are separate, so an account can exist without billing history.

References: convex/…/auth.ts• L13-65 convex/users.ts• L4-18 convex/schema.ts• L897-945

Session verification

The browser exposes session status and a simple free-or-Pro view for presentation. Server and edge paths verify Clerk bearer tokens before they use account state. A valid session identifies the caller, but it does not prove access to every paid feature.

Protected requests can use a browser session, a durable user API key, a desktop key, an operator-issued enterprise key, or an OAuth bearer token issued to an MCP client. Each path still resolves the account’s current entitlement before it grants paid access.

References: src/…/auth-state.ts• L9-42 src/…/clerk.ts• L472-507 server/auth-session.ts• L209-275 api/_api-key.js• L27-60 api/…/token.ts• L548-594

MCP client authorization

MCP client authorization connects an external client to a human account without giving the client the human’s Clerk session. The client discovers host-specific OAuth metadata, proves control of its redirect target, and uses authorization code with PKCE to obtain a short-lived bearer token and a refresh token.

The authorization service supports stored dynamic registrations and trusted Client ID Metadata Document URLs. It validates the client and redirect URI before it displays consent. Local loopback callbacks are allowed for local tools, with a warning that the callback remains on the local device.

The Pro Clerk path can bounce from the apex grant flow to GET /oauth/authorize-pro. That endpoint verifies the signed grant before it consumes the one-use grant and OAuth nonce, re-checks the current entitlement, issues the Convex MCP token row, and returns a short-lived authorization code. A confirmed free account can complete this path with restricted access, while an entitlement that is still being checked returns a retryable result and a confirmed paid-access lapse returns a terminal result.

The consent flow can use a user API key or the signed-in Pro path. The consent POST accepts only the explicit hosted World Monitor app origin allowlist. It does not trust arbitrary worldmonitor.app subdomains or vendor hosts. The stored nonce and browser binding provide the main request link. OAuth state is short-lived and bound to the browser that started the request. The nonce is consumed once, and the authorization code is also single-use. Refresh tokens rotate, so replay of a rotated token can revoke the token family.

The authorization issuer is captured from the valid World Monitor host that starts the request. This keeps discovery, consent, token exchange, and the protected-resource host aligned even when the response leaves through another World Monitor host.

This diagram shows how an MCP client moves from discovery to an account-bound bearer token.

sequenceDiagram
    participant C as MCP client
    participant M as OAuth metadata
    participant W as World Monitor consent
    participant P as Pro authorization handoff
    participant R as Redis session
    participant V as Convex entitlement

    C->>M: Discover resource and authorization server
    C->>W: Start authorization with PKCE
    W->>R: Store one-use request state and browser binding
    W-->>C: Show consent and account choice
    C->>W: Redeem consent with session or API key
    W->>P: Send signed Pro grant when needed
    P->>R: Consume grant and OAuth nonce once
    P->>V: Verify identity and entitlement
    P-->>C: Redirect with one-use authorization code
    C->>W: Exchange code for tokens
    W-->>C: Bearer access token and refresh token

References: api/…/authorize.js• L24-47 api/…/authorize.js• L268-280 api/…/authorize.js• L326-344 api/…/authorize.js• L366-453 api/…/authorize-pro.ts• L314-507 api/…/authorize-pro.ts• L543-610 api/oauth-authorization-server.ts• L45-100 api/…/_client-metadata.js• L287-355 api/…/_redirect-uri.js• L8-82 api/…/token.ts• L460-595

Session transitions

Signing out or changing accounts is an account boundary. Token state, Convex bindings, checkout state, entitlement state, and delayed preference work must move to the new account only after its identity is ready. This prevents one user’s data or access from appearing under another user.

References: src/…/convex-client.ts• L24-42 src/…/convex-client.ts• L70-124 src/…/checkout.ts• L243-287

Passkey offers

Passkey offers help a signed-in user create a device-bound sign-in credential. Clerk manages the credential. World Monitor limits when the offer appears and reserves a small number of lifetime offer slots on the server so several devices cannot spend the same slot.

References: src/…/passkeys.ts• L4-15 src/…/passkey-offer-state.ts• L191-251 api/…/passkey-offer.ts• L79-201 server/…/passkey-offer-reservation.ts• L17-37

Entitlements and product catalog

An entitlement is the server statement of what an account can use and how long that access lasts. The product catalog defines plan facts and limits. Payment events and controlled complimentary grants produce the current entitlement, which the browser watches and the API gateway checks.

Product plans

The catalog is the shared source for plan identity, billing period, feature flags, limits, display facts, and provider product mappings. Tier gives a broad access order, but named features and limits define the actual commercial rights.

Plan familyMain accessRepresentative limits
FreeCore dashboard useThree dashboards and no paid API keys
ProAdvanced dashboard and AI useTen dashboards, 50 MCP calls/day, 500 dashboard-AI calls/day, and two desktop keys
Pro BusinessPro use for commercial work25 dashboards, export, 250 MCP calls/day, 2,500 dashboard-AI calls/day, and three desktop keys
API StarterREST API and SDK use60 requests/minute and 1,000 REST/MCP requests/day combined
API BusinessHigher-volume REST use300 requests/minute, 10,000 REST/MCP requests/day combined, and five Pro licenses
EnterpriseContract access10,000 API requests/day by default, with more capacity and custom terms by contract

The catalog also controls which products are visible, purchasable, self-serve, or eligible for a plan change. Public catalog data supports pricing and product surfaces, while checkout uses the payment provider’s product price. Monthly and annual variants map to the same plan families but remain separate purchasable products.

References: convex/…/productCatalog.ts• L48-165 convex/…/productCatalog.ts• L172-306 convex/…/productCatalog.ts• L312-533 api/_product-catalog.generated.js• L5-175 api/_product-catalog.generated.js• L206-463

Entitlement resolution

Convex keeps one current entitlement for each user with its plan, features, and end time. Reads fall back to free when no valid entitlement exists. They merge stored values with current catalog defaults, so new fields and structural limits reach older rows without a new payment event.

Payment events remain the source of subscription state. The system combines overlapping subscriptions, accepted Business Pro grants, and complimentary periods, then selects the strongest valid coverage. A hold or cancellation keeps access only through the paid period. When all coverage ends, the account returns to free.

The catalog remains authoritative for structural limits. A stored entitlement with an unknown plan key fails loudly instead of silently becoming free. When a provider webhook names an unmapped product, processing uses a temporary enterprise fallback and logs the mismatch so paid access continues while operators repair the catalog.

An operator can also set an account-level AI routing policy. This policy limits the AI providers that the account may use and is separate from the plan entitlement.

Entitlement writes update the access cache and schedule a delayed current-state resync. The cache action reads the current database state for delayed writes, keeps paid access data separate by provider environment, and reports failed cache writes for operations review. Convex remains the source of truth when cache work is late or a request races with the entitlement write.

References: convex/entitlements.ts• L19-60 convex/…/entitlements.ts• L18-74 convex/…/subscriptionHelpers.ts• L424-513 convex/…/subscriptionHelpers.ts• L657-752 convex/…/cacheActions.ts• L16-140 convex/…/cacheActions.ts• L73-104 convex/schema.ts• L779-823

Access decisions

Protected API paths map to a minimum tier. The gateway checks caller identity and current entitlement before it allows the path. An unrestricted path needs no entitlement check. A missing or expired entitlement grants no paid access.

Verification failure is different from a confirmed free account. A transient billing or backend failure produces a retryable response instead of a misleading upgrade message. A confirmed lapse is a terminal denial. The same decision model serves JSON, HTML, OAuth, and boolean premium surfaces.

The gateway reads Redis first and uses Convex when the cache is missing, expired, or has an old feature shape. It coalesces concurrent reads and briefly remembers transient failures to limit outage load. A confirmed Convex entitlement remains usable even if the cache write fails. Entitlement writes schedule a cache update, and failed updates are surfaced for retry and operations review instead of being hidden.

MCP access adds a paid-tier and feature check. Its result is reused by consent, token creation, OAuth completion, edge handling, and gateway checks so all MCP entry points use the same access rule. The Pro authorization handoff repeats the entitlement check close to code issuance because its signed grant can outlive a recent entitlement change.

References: server/…/entitlement-check.ts• L37-150 server/…/entitlement-check.ts• L473-551 server/…/entitlement-check.ts• L601-756 server/…/entitlement-check.ts• L793-921 server/…/entitlement-check.ts• L946-1035 server/…/pro-mcp-gate.ts api/…/authorize-pro.ts• L484-507 convex/…/cacheActions.ts• L45-140

API key lifecycle

API keys give REST callers a durable credential when an interactive Clerk session is not suitable. Each key belongs to one user and reaches the API gateway before plan and usage checks.

Key issuance

An eligible API plan can create a key from a browser-generated secret. The browser shows the secret once. Convex stores only its hash, a short display prefix, ownership data, and optional Company Monitoring scope. A user can keep up to five active API keys.

API keys and desktop keys are separate credential classes. API keys require API access and can carry Company Monitoring scopes. Desktop keys support the desktop-facing Pro access surface without API-only access, use a separate plan allowance, and do not carry Company Monitoring scopes. A deployment switch can suspend desktop keys without changing stored key rows.

Key scopes are checked against supported Company Monitoring actions. A scoped key also binds to the owner’s active Company Monitoring account. A key without scopes stays outside that product area.

References: src/…/api-keys.ts• L1-8 src/…/api-keys.ts• L38-80 convex/apiKeys.ts• L12-27 convex/apiKeys.ts• L61-159 convex/apiKeys.ts• L211-289

Key use and revocation

The gateway hashes an incoming key and checks for a matching non-revoked record. Listings return metadata rather than secrets. Validation also checks any Company Monitoring scope and account binding. Revocation records the key as inactive and asks the gateway cache to remove it. Revoking a key can also change which sibling keys qualify for a desktop allowance, so the active key cache entries are invalidated together. The invalidation action checks that each cache delete succeeds; if it cannot prove removal, cache expiry limits the remaining acceptance window and the failure is visible to operations.

Key activity is recorded with a debounced last-used time. This gives settings and support views useful activity data without turning every request into a database write.

References: convex/apiKeys.ts• L162-209 convex/apiKeys.ts• L216-264 convex/apiKeys.ts• L282-306 convex/apiKeys.ts• L324-375 src/…/api-keys.ts• L83-145 convex/…/cacheActions.ts• L238-304

Bootstrap validation

Older bootstrap routes accept only canonical unscoped user keys. They check both the key and the owner’s current API entitlement. Invalid credentials, missing access, and unavailable validation are separate outcomes so callers can distinguish a bad key from a service problem.

References: api/_user-api-key.js• L94-120 api/_user-api-key.js• L242-321 api/_user-api-key.js• L324-390 api/_user-api-key.js• L393-446

Checkout and billing

Checkout links a catalog product to a hosted Dodo payment session. The provider handles payment authentication and billing pages. World Monitor checks that the product is an active self-serve offer, limits duplicate and excessive attempts, links the session to the right account, accepts the signed provider event, and turns it into subscription and entitlement state.

Checkout flow

This diagram shows how a product choice becomes account access.

flowchart LR
    A[Choose product] --> B{Signed in?}
    B -- No --> C[Save purchase intent]
    C --> D[Sign in or sign up]
    D --> E[Resume checkout]
    B -- Yes --> E
    E --> F[Check subscription and pending payment]
    F --> G{Allowed product and checkout budget?}
    G -- No --> H[Return typed customer-state outcome]
    G -- Yes --> I[Create hosted payment session]
    I --> J[Complete payment]
    J --> K[Verified provider event]
    K --> L[Update subscription]
    L --> M[Resolve entitlement]
    M --> N[Unlock dashboard and API access]

The checkout edge verifies the session and limits new requests by user and client IP. The internal admission record also limits account attempts to five in ten minutes. Idempotent completed replays return the earlier result instead of creating another provider session. Existing subscriptions block duplicate purchases, while a recent pending payment normally blocks another attempt in the same tier; the customer can explicitly bypass only that pending-payment confirmation. A provider rate limit or timeout returns a retryable outcome after bounded retries.

Checkout accepts only catalog products marked current and self-serve. It records terms assent for an authenticated account before provider work when possible. A trusted return URL, signed account metadata, and optional anonymous claim metadata carry the purchase context through the hosted session. The login email is separately signed for lifecycle mail and may prefill the editable billing form, but the signed account identity remains the webhook ownership proof.

MCP clients can start an upgrade through start_upgrade. This entry point accepts current self-serve products and uses the same checkout rules as the web flow. It returns a browser URL rather than handling payment. Existing subscriptions, pending payments, unavailable products, and rate limits are returned as customer-state outcomes.

Checkout metadata can also preserve referral, acquisition, and MCP funnel context for later subscription records. A verified webhook remains the durable activation path.

References: api/create-checkout.ts• L126-292 api/…/checkout.ts• L34-63 api/…/checkout.ts• L107-254 convex/…/checkout.ts• L53-95 convex/…/checkout.ts• L185-360 convex/…/checkout.ts• L363-503 convex/…/checkout.ts• L522-580 convex/…/checkoutRateLimit.ts• L78-173 convex/…/subscriptionHelpers.ts• L1310-1712

Subscription activation

Payment completion does not directly unlock the browser. A signed provider webhook creates or updates subscription state. Entitlement recomputation considers all covering subscriptions and grants, then the browser watch receives the new snapshot.

Dodo sends both dedicated lifecycle events and a catch-all subscription.updated event. The catch-all routes known status values through the same active, hold, cancellation, and expiry rules. This preserves paid-through cancellation and out-of-order protection. An unknown status is retained for review while the system recomputes access defensively instead of silently discarding the event.

When a paid period ended recently but local state may be stale, the request path can verify the subscription with Dodo before it makes a final access decision. A user-level lease coalesces concurrent checks. The result is active, retryable verification, or a confirmed lapse. A daily reconciliation sweep pages through stale active rows, backs off transient failures, requires repeated definitive not-found results before expiry, and stops mass downgrades when a provider or environment error makes many rows look missing.

Subscription identity is kept separate from customer billing identity. The system preserves provider customer IDs across lifecycle events and only opens a portal for a customer that belongs exclusively to the requesting account. Deleted accounts retain billing evidence for provider reconciliation, but late events do not restore personal data or access.

When the login email and checkout email differ, lifecycle mail goes to the login address. It uses signed checkout evidence only while that evidence is valid and compares its issue time with the account’s current identity record. A best-effort pointer can direct the buyer to the checkout inbox.

References: convex/…/subscriptionHelpers.ts• L1310-1712 convex/…/subscriptionHelpers.ts• L1763-1887 convex/…/subscriptionHelpers.ts• L1956-2075 convex/…/subscriptionHelpers.ts• L2238-2308 convex/…/billing.ts• L116-195 convex/…/billing.ts• L1216-1257 convex/…/billing.ts• L1347-1540 convex/…/billing.ts• L1592-1787 convex/…/billing.ts• L2171-2482 convex/…/subscriptionEmails.ts• L217-257

Subscription lifecycle emails

Subscription events can start welcome, reactivation, cancellation-confirmation, payment-recovery, and winback messages. Email work is separate from entitlement processing, so an email failure does not change access.

Welcome and reactivation mail goes to the login address. When the billing address differs, a best-effort sign-in pointer goes to the checkout inbox. Each customer and admin send is guarded separately, and deleted accounts are skipped. Plan-specific welcome content uses an explicit Pro allowlist so a new or non-Pro plan does not receive unsupported Pro claims.

Payment-recovery mail follows an open payment episode at day 0, day 3, and day 7. A daily scan retries missed sends and schedules at most one due step per subscription. Winback mail is a single marketing message about 30 days after access ends, within a bounded window, and includes an unsubscribe path. Cancellation confirmation is retried for a short period while access remains active.

Every detached send checks live subscription coverage, the episode, suppression state, and the send ledger before delivery and again after any pacing wait. A shared send pace protects the email provider, while retry around the pacing reservation handles concurrent writers. The final ledger write follows delivery, so transient send failures remain eligible for a later scan.

References: convex/…/subscriptionEmails.ts• L27-65 convex/…/subscriptionEmails.ts• L217-257 convex/…/subscriptionEmails.ts• L260-321 convex/…/subscriptionEmails.ts• L395-617 convex/…/subscriptionEmails.ts• L707-774 convex/…/subscriptionEmails.ts• L779-823 convex/…/subscriptionEmails.ts• L1215-1407 convex/…/subscriptionEmails.ts• L1410-1563

Customer portal

Manage Billing creates a personalized Dodo Customer Portal session for the signed-in user. It prefers the provider customer identity tied to that user’s subscription and falls back only to same-user legacy evidence. Lifecycle events preserve a known customer identity when later provider payloads omit it. A customer linked to another account is rejected instead of opening another account’s billing page.

The portal opens in a new browser context on web or in the operating system browser on desktop. Plan changes are available only for products whose catalog rules support the provider operation. Missing customer data and provider failures use structured billing errors so the client can show a useful recovery path.

References: convex/…/billing.ts• L402-487 convex/…/billing.ts• L1086-1214 convex/…/billing.ts• L3770-3794 convex/…/subscriptionHelpers.ts• L1144-1167 src/…/billing.ts• L332-460 convex/…/productCatalog.ts• L155-164

Usage limits

Usage limits protect provider capacity and define the service included in each plan. The system keeps separate meters for REST traffic, MCP calls, dashboard AI work, and short bursts because they have different cost and traffic patterns.

REST allowances

API plans have a per-minute burst limit and a daily included allowance. The gateway assigns both to the authenticated user or API-key owner. Rejected requests receive standard rate-limit information.

The daily meter uses an atomic reservation. Work that starts remains counted. A Redis failure does not unexpectedly block an entitled API customer; the system serves the request without a count and records the degraded state.

References: convex/…/productCatalog.ts• L48-75 server/…/api-key-rate-limit.ts• L1-17 server/…/api-key-rate-limit.ts• L120-205

MCP and AI quotas

MCP calls reserve daily capacity before dispatch. A successful reservation is spent even if the tool later fails. A rejection before dispatch returns its reservation. The settings quota view reads the same meter and allowance used by enforcement.

API-tier MCP usage shares the REST daily budget. Pro plans use a dedicated MCP allowance, while dashboard AI calls use a separate allowance. Endpoint burst limits remain separate from plan entitlement, so a valid plan can still receive a short-term rate-limit response. Legacy cache entries are refreshed when they lack fields needed for current quota or credential decisions.

References: api/…/quota.ts• L8-18 api/…/quota.ts• L76-177 api/…/mcp-quota.ts• L124-199 convex/…/productCatalog.ts• L67-83 convex/…/entitlements.ts• L30-74 server/…/entitlement-check.ts• L601-669

User preference controls

Preferences control how the product looks and behaves for one user. They are separate from billing access. Sign-in state decides whether local choices can also sync to Convex.

Local preference controls

Settings cover display, language, maps, AI behavior, media quality, live streams, panels, and data actions. Users can export or import settings as JSON. Some controls depend on a parent capability, so the interface does not present a child option as active when its parent is off.

References: src/…/preferences-content.ts• L123-247 src/…/preferences-content.ts• L249-386 src/…/preferences-content.ts• L410-426 src/…/preferences-content.ts• L445-531

Cloud preference sync

Cloud Sync is a web-only feature for signed-in users. It stores a versioned preference set in Convex. The client merges local dirty keys when devices change at the same time, and compare-and-set writes prevent an older device from replacing newer cloud state.

The server limits write rate and preference size. It preserves omission-safe fields when an older client does not know about newer settings. Sign-out cancels delayed work and keeps sync state tied to the old account.

References: src/…/preferences-content.ts• L388-408 convex/userPreferences.ts• L18-47 convex/userPreferences.ts• L84-176 convex/userPreferences.ts• L231-307 src/…/cloud-prefs-sync.ts• L742-827 src/…/cloud-prefs-sync.ts• L865-961

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep plan keys aligned across the catalog, provider product mappings, public catalog, checkout product eligibility, entitlement recomputation, plan precedence, and lifecycle email allowlists.
  • Keep each entitlement feature aligned across catalog defaults, Convex storage, cache data, gateway consumers, and the rule for missing legacy fields.
  • Keep API credential classes aligned across edge routing, key validation, bootstrap validation, OAuth token resolution, and entitlement checks. Anonymous session tokens must not gain paid authority.
  • Keep API-key scope rules aligned between issuance and validation. Preserve the unscoped bootstrap contract.
  • Keep API and desktop key rules aligned across plan gates, key caps, edge validation, cache invalidation, and deployment disable switches. Desktop keys must not gain API-only or Company Monitoring scope.
  • Keep OAuth client metadata trust, redirect URI allowlists, explicit hosted-app origin checks, signed grant verification, consent checks, issuer metadata, browser binding, and token exchange rules aligned. Preserve one-use grant, nonce, state, and token-family revocation.
  • Keep the Pro OAuth handoff aligned with the grant payload, Redis one-use records, entitlement re-check, MCP token issuance, discriminated authorization-code shape, and rollback path.
  • Keep checkout identity metadata aligned with webhook ownership, anonymous claims, signed login-email selection, lifecycle email recipients, and billing-email records.
  • Keep checkout admission, subscription duplicate guards, pending-payment bypass behavior, product allowlists, and provider retry outcomes aligned across the edge and Convex relay.
  • Keep customer identity evidence aligned across subscription rows, customer rows, deletion tombstones, and portal ownership checks. A fallback must not cross account boundaries.
  • Keep subscription state separate from derived entitlement state. Renewal uncertainty must not cause an unsafe downgrade.
  • Keep subscription.updated status routing aligned with the dedicated lifecycle rules. Preserve event-time ordering checks and the defensive path for new provider statuses.
  • Keep overlapping subscription, complimentary grant, and Business Pro coverage rules aligned across plan changes, expiry, and reconciliation.
  • Keep renewal reconciliation aligned across request-time verification, daily scans, retry backoff, repeated not-found confirmation, and the mass-downgrade breaker.
  • Keep lifecycle email eligibility aligned with live coverage, cancellation episodes, suppression purpose, send pacing, ledger state, and the bounded scan windows.
  • Keep quota readers on the same counter and allowance resolver as reservation paths. API-tier MCP usage must remain shared with REST.
  • Keep preference schema evolution omission-safe. Preserve write limits, blob limits, version checks, and account-bound sync cancellation.

Important failure modes

TriggerConsequenceGuard
Billing lookup or entitlement verification failsA paid customer could receive a false upgrade denialShared billing classification returns a retryable response for unverifiable state; server/…/entitlement-check.ts• L793-864
A recently ended subscription has uncertain local stateAccess could be downgraded before the provider confirms the lapseA user-level lease coalesces on-demand checks and reports pending or failed verification; convex/…/billing.ts• L1347-1540, convex/…/billing.ts• L1960-2167
A provider lookup returns one transient error or one not-found resultA paying customer could be downgraded by a temporary provider or network faultReconciliation backs off transient results and requires repeated definitive not-found evidence before expiry; convex/…/billing.ts• L1905-1931, convex/…/billing.ts• L1738-1787
Many subscriptions appear missing from the providerA provider configuration error could downgrade a large customer groupA per-cycle mass-not-found breaker halts further downgrades and routes rows back to retry; convex/…/billing.ts• L2285-2361
A confirmed subscription lapse has no remaining coveragePaid access is denied with a terminal responseOnly subscription_lapsed is terminal; server/…/entitlement-check.ts• L839-863
A stale cache lacks a current access or quota fieldA paid feature or allowance could use the wrong valueShape checks force a Convex refresh for fields that require current data; server/…/entitlement-check.ts• L601-669
An entitlement cache update fails after a database writeEdge access can lag behind the current entitlementThe cache action logs and rethrows failed writes for monitoring and retry; Convex remains the source of truth; convex/…/cacheActions.ts• L84-140
A warm revoked-key cache entry is not removedA revoked credential could remain usable until cache expiryKey changes invalidate user-key and related bootstrap entries, and the invalidation checks every delete result; convex/apiKeys.ts• L324-375, convex/…/cacheActions.ts• L238-304
A stored entitlement has an unknown plan keyAccess could silently fall back to the wrong planPlan lookup fails loudly; convex/…/entitlements.ts• L18-28
A provider webhook names an unmapped productWebhook retries could block entitlement updatesProduct resolution logs the mismatch and uses a temporary enterprise fallback; convex/…/subscriptionHelpers.ts• L904-1007
A subscription.updated event has a new or unknown statusThe provider change may not update the stored lifecycle statusThe event is retained, entitlement state is recomputed defensively, and the unknown status is logged; convex/…/subscriptionHelpers.ts• L2238-2308
A delayed subscription event arrives after a newer eventA newer subscription state could be overwrittenLifecycle handlers reject older event timestamps before applying state; convex/…/subscriptionHelpers.ts• L362-371, convex/…/subscription-updated.test.ts• L238-250
A checkout product is no longer current or self-serveA buyer could purchase a product that the catalog does not supportCheckout validates the provider product against current catalog eligibility before session creation; convex/…/checkout.ts• L85-95, convex/…/checkout.ts• L537-542
A checkout is replayed or a pending payment already existsThe account could create duplicate payment workEdge idempotency, account admission, subscription guards, and the pending-payment guard run before provider work; api/create-checkout.ts• L136-176, convex/…/checkout.ts• L231-291, convex/…/checkout.ts• L321-327
A pending-payment guard query has a transient infrastructure errorA valid buyer could be blocked from starting checkoutThe guard fails open and logs the error; convex/…/checkout.ts• L266-289
A provider rate limit or timeout occurs during checkout creationThe buyer may receive a hard failure or repeat an uncertain purchaseA bounded retry ladder returns typed timeout or rate-limit outcomes and records terminal pressure; convex/…/checkout.ts• L424-502
A portal customer ID is shared with another accountManage Billing could expose another account’s billing pagePortal resolution requires exclusive ownership across current and legacy evidence; convex/…/billing.ts• L1086-1125
A webhook omits a customer ID or emailLater portal or recovery mail could lose the known customer dataLifecycle updates preserve the prior customer ID and billing email; convex/…/subscriptionHelpers.ts• L1144-1202
Login and checkout emails differThe buyer may receive activation mail at an address that cannot sign inSigned checkout metadata selects the fresher login address and sends a best-effort pointer to the billing inbox; convex/…/subscriptionHelpers.ts• L1223-1292, convex/…/subscriptionEmails.ts• L217-257
A recovery or cancellation email waits behind provider pacing while the account changes stateA recovered, resubscribed, or no-longer-paid user could receive stale payment adviceEligibility is checked before and after the wait, and cancellation confirmation has a bounded retry scan; convex/…/subscriptionEmails.ts• L1215-1363, convex/…/subscriptionEmails.ts• L1471-1527
A lifecycle email send fails before its ledger row is writtenA due message could be lost or a later retry could duplicate itDetached sends use a paced queue and a daily scan, then write the ledger after delivery; convex/…/subscriptionEmails.ts• L1350-1407, convex/…/subscriptionEmails.ts• L1418-1548
An OAuth grant, nonce, or authorization code is replayedA second client could mint an account-bound tokenHMAC verification happens before Redis access, and the grant and nonce are atomically consumed once; api/…/authorize-pro.ts• L334-430
A signed grant does not match its Redis record or URL nonceA valid-looking grant could be used for another request or accountThe handoff checks nonce equality and strict user-and-expiry equality before issuing a token; api/…/authorize-pro.ts• L358-422
The Pro OAuth handoff cannot verify current entitlementA user could see a false Pro denial or receive access during a billing checkIt returns a retryable verification page for uncertain state, a terminal lapse page for confirmed loss, and only a Pro upsell for insufficient access; api/…/authorize-pro.ts• L171-195, api/…/authorize-pro.ts• L484-507
Authorization-code storage fails after an MCP token row is issuedAn orphaned Pro MCP token row could remainThe handoff attempts a best-effort token rollback before returning an error; api/…/authorize-pro.ts• L543-591
An OAuth consent POST comes from an untrusted originA foreign page could attempt to drive the consent endpointThe explicit hosted app origin allowlist is checked before nonce processing; api/…/authorize.js• L268-280, api/_cors.js• L1-9
A preference write is too large or comes from an old accountNew settings could be rejected or cross an account boundaryConvex checks size and version, while sync work checks the current account before writing; convex/userPreferences.ts• L126-176, src/…/cloud-prefs-sync.ts• L940-955

Key files

FileWhy to read it
convex/…/auth.tsDefines the server boundary for the current Clerk identity.
server/auth-session.tsShows edge session verification outcomes.
api/_api-key.jsShows how browser tokens, user keys, enterprise keys, and desktop requests are routed.
api/…/authorize.jsShows consent, API-key authorization, explicit app-origin checks, browser binding, issuer capture, and one-use authorization state.
api/…/authorize-pro.tsShows the signed Pro grant handoff, entitlement re-check, MCP token issuance, rollback, and one-use OAuth code path.
api/…/token.tsShows OAuth code exchange, refresh validation, and token-family recovery.
convex/…/productCatalog.tsDefines plans, features, limits, billing periods, and product operations.
api/_product-catalog.generated.jsShows the public product facts and provider product mappings used by API-facing surfaces.
convex/entitlements.tsShows authenticated entitlement reads, free fallback, and account AI routing policy.
convex/…/entitlements.tsShows catalog default merging and shared MCP budget data.
server/…/entitlement-check.tsShows tier-gated paths, cache and Convex fallback, legacy-shape refresh, and billing verification outcomes.
convex/apiKeys.tsShows API-key and desktop-key ownership, hashed storage, scopes, account bindings, caps, and revocation.
convex/…/cacheActions.tsShows entitlement cache sync, current-state resync, and immediate invalidation of warm credential entries.
api/create-checkout.tsShows checkout edge identity, limits, replay handling, and public errors.
api/…/checkout.tsShows the MCP upgrade handoff and customer-state responses.
convex/…/checkout.tsShows product eligibility, account admission, duplicate-purchase guards, hosted-session handoff, and signed checkout identity metadata.
convex/…/subscriptionHelpers.tsShows provider identity resolution, subscription status dispatch, subscription coverage, entitlement recomputation, renewal repair, and lifecycle transitions.
convex/…/subscription-updated.test.tsShows the paid-through, status-routing, defensive, and event-ordering guarantees for catch-all subscription updates.
convex/…/billing.tsShows customer-portal ownership, request-time renewal verification, daily renewal reconciliation, and billing recovery.
convex/…/subscriptionEmails.tsShows subscription lifecycle, recovery, suppression, pacing, cancellation confirmation, winback, and email delivery.
server/…/api-key-rate-limit.tsShows REST burst and daily allowance enforcement.
api/…/quota.tsShows MCP quota reservation and budget selection.
convex/userPreferences.tsShows preference storage, limits, version checks, and safe schema evolution.
src/…/cloud-prefs-sync.tsShows account-safe preference synchronization.
api/…/passkey-offer.tsShows the passkey offer and reservation boundary.