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-and-commerce

Identity, access, and commerce

WorldMonitor ties user identity to access, paid plans, and delivery settings across the browser, HTTP API, and Convex. Clerk establishes the user session, Convex stores the user’s durable account and billing state, and the API checks the resulting identity and entitlements before it serves protected data or accepts paid-user settings.

Identity and session model

Browser identity

The browser uses Clerk as the source of truth for sign-in, sign-up, session changes, and sign-out. The Clerk SDK loads after the first paint unless a user action needs it sooner, while src/…/auth-state.ts exposes a small reactive session with a user id, profile fields, and a free or pro role for the UI.

The browser also obtains a bearer token for Convex and protected HTTP requests. The token uses the convex template when available, then falls back to a normal Clerk session token. The client drops cached credentials when the account changes so a request from an old session cannot become a request for the new user.

References: src/…/clerk.ts• L1-22 src/…/clerk.ts• L472-507 src/…/clerk.ts• L531-541 src/…/auth-state.ts• L9-42

Convex identity

Convex resolves the current user from the verified Clerk identity subject. Public functions use that subject rather than a user id supplied by the browser, and required writes reject an absent identity. A development-only fallback exists for local Convex development; it is not used as a production identity path.

The shared Convex client installs the current Clerk token as its auth provider. It waits for Convex to confirm the same user before it starts user-scoped reads or writes. On the first authenticated session it also creates or updates the durable users record with account metadata such as locale and time zone.

References: convex/…/auth.ts• L4-35 convex/…/auth.ts• L51-65 src/…/convex-client.ts• L70-124 src/…/convex-client.ts• L192-217 convex/users.ts• L62-118

HTTP sessions

The HTTP layer accepts Clerk bearer tokens for signed-in users and short-lived wms_ session tokens for anonymous browser access. A session token can pass a basic public route check, but it is not proof of a user or paid access. Desktop requests use an operator-issued enterprise key rather than browser session credentials.

The edge gateway can also resolve a user-owned wm_ API key. It hashes the presented key and asks Convex for the owner, so the key itself is not stored in the database. Gateway routes then apply their own access and rate rules to the resolved identity. Bootstrap API-key paths use the same hashed identity and entitlement model, but accept only legacy unscoped user keys; scoped Company Monitoring keys and desktop keys remain for surfaces with their dedicated validators. Explicit machine credentials take priority over ambient browser cookies, so a stale cookie cannot silently replace a supplied key.

See the API platform page for the wider route and gateway model.

References: api/wm-session.js• L1-19 api/wm-session.js• L201-258 api/_api-key.js• L6-60 api/_api-key.js• L79-136 server/…/auth-session.ts• L11-49 server/…/user-api-key.ts• L118-166 api/_user-api-key.js• L240-355 server/gateway.ts• L1212-1243

Access and entitlement model

Entitlement state

An entitlement is the materialized answer to “what may this user use now?” It names a plan, its feature set, and the time until which that access is valid. Convex derives this state from all covering subscriptions rather than from the webhook event alone. It also considers accepted Business Pro grants and active complimentary access, then selects the strongest live source; when no source covers the user it writes a free state. A complimentary grant can preserve paid access after a subscription expires until its own end time. When several subscriptions cover an account, plan capability precedence resolves same-tier differences before the system uses the longest remaining period for the same plan.

The authenticated Convex query returns free-tier defaults when no user or live entitlement exists. For a live row, it merges current catalog defaults at read time so new feature fields reach the browser before the next billing event; stored values still preserve user-specific choices. Active subscriptions remain candidates while renewal evidence is reconciled. An on-hold or cancelled subscription preserves access only through its current paid period. This keeps a payment-retry window useful without allowing an unresolved hold to grant access forever. The browser receives entitlement changes through a live Convex subscription. The API reads the same state through a short Redis cache with a Convex fallback. Convex refreshes that cache after entitlement writes and schedules a later read of current database state to cover request races; cache failure does not change the Convex source of truth.

References: convex/entitlements.ts• L19-60 convex/entitlements.ts• L63-90 convex/…/entitlements.ts• L18-75 convex/…/subscriptionHelpers.ts• L367-457 convex/…/subscriptionHelpers.ts• L492-668 convex/…/cacheActions.ts• L16-80 convex/…/cacheActions.ts• L84-140 src/…/entitlements.ts• L18-54 src/…/entitlements.ts• L122-189 server/…/entitlement-check.ts• L435-471 convex/…/comp-entitlement.test.ts• L25-138 convex/…/comp-entitlement.test.ts• L207-283 convex/…/comp-entitlement.test.ts• L295-445 convex/…/comp-entitlement.test.ts• L475-639 convex/…/comp-entitlement.test.ts• L755-842

Plan capabilities

The catalog is the shared language for products, prices, plan names, and feature limits. Tiers provide a broad access order, but named feature fields remain important because plans at the same tier can differ. The generated public facts in api/_product-catalog.generated.js carry that catalog view and public product facts to pricing, OAuth consent, and other HTTP surfaces, so they must stay aligned with the canonical plan rules.

The public pricing catalog combines those product facts with current provider prices. It normally serves a seeded public view, can read provider prices directly when the seed is unavailable, and uses short-lived static fallback prices when no live price source is available. The response identifies its price source so the pricing surface and operators can distinguish a live catalog from a degraded one.

Plan familyTierMain access meaning
Free0Core dashboard use with no paid API, paid MCP, export, or notification access
Pro1Paid intelligence features, MCP access, and Pro dashboards
Pro Business1Pro access plus commercial use, exports, more dashboards, and a larger MCP allowance
API Starter and API Business2REST API and API-key access with different request limits; MCP uses the REST daily budget
Enterprise3The highest API and support level with no self-serve checkout

apiAccess, mcpAccess, dataExport, dashboard counts, and plan limits are separate checks. For example, Pro has MCP access but does not issue REST API keys, while Pro Business shares Pro’s tier but adds commercial export rights. API plans publish one daily number for REST and MCP; their MCP calls consume the same daily budget rather than a second MCP allowance. Enterprise has no daily cap in the catalog.

The five-factor country scorecard is a public HTTP capability, while its sibling resilience routes remain tier-gated. Removing the scorecard paths from the HTTP entitlement map does not change the separate access rules for MCP tools.

An API Business owner can grant Pro access to accepted invitees. The current product facts describe up to five Pro licenses in that plan, while the team-seat flow reserves four invitee seats in addition to the owner. The grant follows the owner’s covering Business subscription and does not create a second subscription for the invitee.

The MCP quota view follows the same budget decision as MCP enforcement. A dedicated MCP counter serves Pro and Pro Business, while an API plan can use the shared REST counter. A confirmed free account is a separate paid-funnel path with a small daily MCP allowance, so its display reads the free-account counter instead of the paid-plan counter.

Stored entitlement rows retain plan features from the time of grant. When catalog rules change, the entitlement resolver merges current catalog defaults with stored values and lets structural catalog rules replace retired or unsafe limit markers. This prevents an old row from keeping a separate MCP budget or an old unlimited allowance after the catalog changes.

The API platform page describes how route families consume these access decisions. The Persistent application state page describes how entitlement and user records fit into Convex state.

References: convex/…/productCatalog.ts• L48-140 convex/…/productCatalog.ts• L172-306 convex/…/productCatalog.ts• L312-533 convex/…/productCatalog.ts• L647-685 api/_product-catalog.generated.js• L5-46 api/_product-catalog.generated.js• L65-174 api/_product-catalog.generated.js• L206-252 api/_product-catalog.generated.js• L254-443 convex/…/entitlements.ts• L18-75 convex/…/subscriptionHelpers.ts• L545-585 convex/…/subscriptionHelpers.ts• L682-780 api/product-catalog.js• L58-90 api/product-catalog.js• L143-194 api/product-catalog.js• L217-254 api/…/quota.ts• L97-163 api/…/mcp-quota.ts• L127-173 api/…/upgrade-constants.ts• L7-18 server/…/entitlement-check.ts• L131-174

Business seat grants

Business seat grants extend one active API Business subscription to named teammates without creating separate billing records. The owner must use a corporate email domain and can invite up to four teammates; pending, accepted, and unexpired invites count toward that limit.

An invite is sent to the target address and can be accepted only by a signed-in account with a verified matching corporate email. A successful acceptance records the invitee and gives that account Pro access while the owner’s Business subscription covers it. The owner can revoke a seat, and the system also removes the grant when the Business subscription stops covering. Expired or revoked invites free their seat for later use.

References: convex/…/businessSeats.ts• L1-9 convex/…/businessSeats.ts• L38-42 convex/…/businessSeats.ts• L125-243 convex/…/businessSeats.ts• L322-371 convex/…/businessSeats.ts• L425-529

API-key lifecycle

API keys are a paid API credential for plans whose catalog entry sets apiAccess. The browser creates a random wm_ key, sends only its prefix and SHA-256 hash to Convex, and shows the plaintext once. Convex stores the hash and ownership record, not the secret.

Users can list and revoke their own keys. The system allows up to five active keys per user, and revocation asks the edge cache to remove the key entry so the gateway stops accepting it without waiting for the normal cache lifetime. Keys have an api or desktop kind. The generic bootstrap and OAuth paths accept only an unscoped api key; desktop-aware surfaces decide separately whether a desktop key is allowed. A key can also carry a Company Monitoring scope. Scoped keys require a valid active Company Monitoring account owned by the same user; malformed or stale scope bindings do not authenticate through the general API-key path.

Bootstrap API-key validation adds a boundary before protected API work. It rate-limits requests by client IP, resolves the hashed key through Convex, and checks the owner’s current apiAccess entitlement. It returns a valid principal only for an unscoped legacy user key. Cache entries carry a version and key kind, so an old or malformed entry is revalidated rather than trusted. A malformed or unsupported key is an authentication failure, a missing or lapsed API entitlement is an access denial, and a validation-service outage is a retryable service error rather than an invalid-key result. Commerce lifecycle changes also invalidate warm user-key and related embed-key cache entries so revocation or a lapsed entitlement does not wait for cache expiry.

References: convex/apiKeys.ts• L11-27 convex/apiKeys.ts• L61-95 convex/apiKeys.ts• L107-159 convex/apiKeys.ts• L193-264 src/…/api-keys.ts• L21-80 src/…/api-keys.ts• L102-145 api/_user-api-key.js• L12-135 api/_user-api-key.js• L240-355 api/_user-api-key.js• L357-446 api/_user-api-key.js• L464-469 convex/…/cacheActions.ts• L288-319

OAuth client discovery

OAuth lets MCP clients discover WorldMonitor, obtain a user-bound bearer token, and connect without receiving a WorldMonitor secret. Authorization-server and protected-resource metadata are built for the host that serves the request, so the issuer, resource, and endpoints stay consistent across the supported WorldMonitor hosts and MCP resource paths.

Clients can use a stored dynamic registration or a trusted Client ID Metadata Document (CIMD), which is a vendor-published document that describes a public OAuth client. CIMD is limited to an explicit trust list and validated redirect data. A vetted snapshot can cover a temporary vendor fetch failure, but a withdrawn or invalid document does not become trusted through the snapshot. Dynamic registration also has bounded request and metadata sizes and fails closed when its admission check cannot make a rate-limit decision.

Registered callbacks use a shared policy. Most vendor callbacks must match an exact allowlist. Google Connected Apps use only the documented HTTPS Google hosts and path forms, while local clients can use approved HTTP loopback callbacks with any port. Registration, authorization, and Pro grant issuance use the same policy, so a callback accepted at one stage cannot become invalid or broader at another stage. Existing registered clients are checked against the current allowlist again during authorization and Pro completion, so a later callback removal takes effect without waiting for registration expiry.

The authorization page presents a signed-in Pro path and keeps the legacy API-key form behind an explicit disclosure. The API-key path remains available for clients that use that credential class, while the Pro path gives a free account a basic allowance and uses Pro for a higher daily allowance. An invalid key or temporary validation failure gets a fresh consent nonce so the original one-time request cannot be reused.

The authorization request uses an exact registered callback and PKCE. The consent flow stores the client, callback, issuer, and PKCE data in a short-lived browser-bound request. Each flow gets its own first-party cookie, and the cookie can span the supported WorldMonitor hosts without exposing its value to script. The POST consumes that request once, re-checks the client and callback, and takes security-critical values from the stored request rather than mutable form fields. It also accepts only hosted WorldMonitor app origins. The issuer is captured from the supported host that starts the flow, with a safe WorldMonitor fallback, and is returned with the authorization response so a client can confirm that the response came from the server it selected.

This discovery and consent path is shared by the API-key and Pro MCP paths. The API-key path keeps its legacy credential boundary, while the Pro path binds the later OAuth token to the signed-in user and Convex MCP access state.

References: api/oauth-authorization-server.ts• L45-103 api/oauth-protected-resource.ts• L23-93 api/…/_client-metadata.js• L1-16 api/…/_client-metadata.js• L18-70 api/…/_client-metadata.js• L239-355 api/…/_client-metadata.js• L358-395 api/…/_client-metadata-snapshots.js• L1-13 api/…/_redirect-uri.js• L1-7 api/…/_redirect-uri.js• L71-115 api/…/authorize.js• L25-47 api/…/authorize.js• L135-141 api/…/authorize.js• L145-240 api/…/authorize.js• L270-348 api/…/authorize.js• L351-471 api/…/_browser-binding.js• L1-73 api/…/register.js• L23-47 api/…/register.js• L115-191

OAuth token access

The OAuth token endpoint supports both the older environment-key path and the signed-in Pro MCP path. An authorization code exchange creates short-lived access and refresh credentials. A Pro credential carries the Clerk user and its MCP token so later requests can resolve both the account and the delegated MCP access without exposing the user’s secret.

The endpoint re-checks the client before it consumes a CIMD-backed code or rotates a refresh token. This lets a vendor document change take effect while preserving a retry path for a temporary metadata outage. PKCE protects the one-time authorization code, and the response keeps the legacy API-key and Pro token shapes separate so both credential classes remain readable.

Refresh tokens rotate within a family. The service checks the Pro MCP token against Convex on each Pro refresh, rejects an authoritative revocation, and preserves the refresh token when Convex is temporarily unavailable. A short replay grace record lets the same client recover the successor pair after a lost response or duplicate refresh, but only while that successor is still unused. Reuse of a rotated token outside that grace path can revoke the whole family, which makes re-authorization the recovery path after a confirmed replay.

Refresh recovery keeps a short-lived in-flight marker separate from durable family replay evidence. If a refresh attempt cannot complete, the service can restore the token with its original expiry or protect the attempt with a family-free tombstone. This prevents a temporary Redis or Convex failure from being mistaken for replay while still preserving the family revocation signal after a confirmed reuse. Refresh families use a 30-day sliding idle window, and the family evidence lasts as long as a token could still be presented.

The endpoint rate-limits token requests by client IP when its Redis limiter is available. A limiter outage is marked as degraded rather than treated as permission to skip token storage and credential checks. Token persistence and grant validation still protect the grant itself.

References: api/…/token.ts• L1-30 api/…/token.ts• L481-616 api/…/token.ts• L618-844 api/…/token.ts• L846-968 api/…/token.ts• L997-1075 api/…/token.ts• L1078-1115 api/…/_refresh-recovery.ts• L4-29 api/…/_refresh-recovery.ts• L119-204 api/…/_refresh-recovery.ts• L229-274 api/…/_refresh-recovery.ts• L329-501 api/…/authorize-pro.ts• L312-354 api/…/authorize-pro.ts• L396-507 api/…/authorize-pro.ts• L538-605

Protected request decisions

Protected HTTP routes first establish an identity, then compare the route’s required tier with the user’s entitlement. Unrestricted routes do not need an entitlement lookup. A valid Clerk pro role can preserve legacy tier-1 access on some read paths, but data-changing paid operations such as notification setup still require a current Convex entitlement record.

When the system cannot verify billing, it must not turn that infrastructure problem into a false “free user” answer. Tier gates return a retryable verification response where the shared contract supports it; a confirmed lapsed subscription is the terminal billing denial. The bootstrap wm_ path follows the same distinction for API access, using retryable service responses when key or entitlement validation cannot run.

References: server/…/entitlement-check.ts• L806-919 api/…/entitlement.ts• L46-70 api/notification-channels.ts• L360-464 api/_user-api-key.js• L405-469 server/auth-session.ts• L209-275

Account deletion fence

Account deletion places a durable write fence around user data. Convex checks for any account-deletion record inside the same write transaction, so deletion and new personal-data writes cannot pass each other. The fence remains after failed or completed requests to stop stale sessions and delayed callbacks from recreating data after cleanup.

The boundary applies to commerce and access writes as well as ordinary preferences. Checkout admission, subscription claiming, billing activation records, and complimentary entitlements reject with a structured deletion-in-progress result while the account is fenced. Anonymous purchases can move to a signed-in user only through the server-issued claim proof and the same deletion check. Late billing events retain only tombstoned billing evidence and do not restore personal data, access, or lifecycle email work.

References: convex/…/guard.ts• L5-28 convex/…/checkout.ts• L55-74 convex/…/billing.ts• L699-747 convex/…/billing.ts• L3784-3799 convex/…/billing.ts• L3989-4004 convex/…/subscriptionHelpers.ts• L149-235 convex/…/subscriptionHelpers.ts• L1209-1211 convex/…/registry.ts• L1-7

Product purchase and subscription flow

Checkout flow

Checkout begins from the pricing page or a locked dashboard feature. The browser sends a product id and a trusted return URL to /api/create-checkout with a Clerk bearer token. The edge route validates the token, checks completed idempotent replays before the per-user and per-client-IP admission limits, and relays the request to Convex. Convex validates the product and applies duplicate-subscription and pending-payment checks before it asks Dodo Payments for a hosted checkout session.

The browser stores a short-lived pending intent when sign-in is needed. The intent expires after 15 minutes and can resume only for the user who saved it, or for the first authenticated user after an anonymous save. Account changes clear checkout state so one user cannot inherit another user’s purchase attempt. An anonymous checkout also receives a signed claim proof so a later authenticated session can move its billing records to the verified account.

The web client navigates to Dodo’s hosted page so payment authentication and fraud checks run at the top level. The desktop client hands the same hosted URL to the operating system browser because its embedded view cannot provide the required payment environment. Dodo returns the buyer to the web dashboard on the web path, while desktop access updates through the shared live entitlement state. In both cases, the durable Pro result comes from the subscription webhook and entitlement update rather than from the payment page alone.

After Dodo returns a hosted session, Convex records a short-lived checkout-session event. This event measures buyers who reached the hosted payment form and can join to a Dodo payment through its session id; it is not the source of payment or entitlement truth. The record is account-owned, pruned after 90 days, and best effort so a logging failure never blocks a live checkout.

This is the main commerce path:

flowchart LR
    A[Pricing page or locked feature] --> B[Clerk bearer session]
    B --> C[/api/create-checkout]
    C --> D[Convex checkout action]
    D --> E[Dodo hosted checkout]
    E --> F[Dodo subscription webhook]
    F --> G[Convex subscription and entitlement state]
    G --> H[Browser or desktop live update]
    G --> I[Protected API access]
    D --> J[Checkout session event]
    J -. funnel measurement .-> K[Dodo payment session link]

The Access control and subscriptions page covers the detailed subscription and checkout rules.

References: api/create-checkout.ts• L105-176 api/create-checkout.ts• L178-235 src/…/checkout.ts• L143-180 src/…/checkout.ts• L243-287 src/…/checkout.ts• L343-386 src/…/checkout.ts• L435-511 src/…/checkout.ts• L571-607 src/…/checkout.ts• L762-802 convex/…/checkout.ts• L55-74 convex/…/checkout.ts• L300-377 convex/…/checkout.ts• L424-503 convex/…/checkoutSessionLog.ts• L1-65

Checkout resilience

Checkout resilience is the boundary between a temporary provider problem and a failed purchase attempt. The edge relay limits each user and each client IP, and returns completed idempotent replays without creating another provider session. The browser retries one transient edge transport failure with the same idempotency key, but it does not repeat a response already returned by the relay.

The client keeps a short local cooldown for provider rate limits and idempotency conflicts. It treats a successful response without a safe hosted URL as a retryable service failure rather than navigating to an unknown destination. It gives duplicate subscriptions and pending payments separate confirmation paths: an existing subscription opens billing only after user confirmation, while a pending payment can be bypassed only after the user confirms a new attempt. Convex records terminal provider rate limits and timeouts so operators can see pressure on the shared payment key without changing the buyer’s retry path. Checkout-session logging is outside this purchase path, so a failed funnel record does not change the provider result.

References: api/create-checkout.ts• L136-176 api/create-checkout.ts• L197-209 api/create-checkout.ts• L237-293 convex/…/checkout.ts• L55-74 convex/…/checkout.ts• L397-503 convex/…/checkoutRateLimit.ts• L37-60 convex/…/checkoutRateLimit.ts• L146-258 convex/…/checkoutSessionLog.ts• L49-65 src/…/checkout.ts• L513-535 src/…/checkout.ts• L610-718 src/…/checkout.ts• L802-913

Subscription lifecycle

Dodo webhooks are the source of billing events. Convex turns subscription events into durable subscription records and recomputes the user’s entitlement from all current coverage sources. The lifecycle handlers protect against older events arriving late, and the catch-all update event routes by its reported status so paid-through cancellation and expiry keep the same access rules.

An active or renewed subscription can cover access without a fixed end guard, while an on-hold or cancelled subscription covers access only through its current paid period. A user with more than one subscription receives the strongest covering plan rather than the plan named by the latest event. Accepted Business Pro grants follow a covering API Business subscription and are revoked when that subscription no longer covers or leaves the Business tier. Plan ids resolve through the product mapping and legacy aliases before a monitored fallback prevents an unknown provider product from wedging entitlement updates.

Webhook identity uses trusted checkout metadata, a known customer record, or an already tracked subscription. If a settled activation or payment event still has no owner, Convex durably records an unattributed billing event before it acknowledges the webhook and queues an operations alert. Charged events alert at once because the buyer may have paid without access; uncharged attempts use a per-customer quiet period so repeated card failures remain a useful sales signal rather than an alert storm. An operator can later attribute a charged event and replay it for the correct account.

Payment and refund events create an audit record rather than changing subscription state. Their status keeps successful, failed, cancelled, processing, and customer-action states distinct, so a payment that waits for customer authentication is not treated as a failed charge. A lost dispute can expire the related subscription, while a full refund on an active uncancelled subscription raises an operator alert instead of silently revoking access.

Cancellation does not always end access at once. A cancelled subscription can remain active through the paid period, while an on-hold subscription represents a payment problem that needs billing attention. If renewal evidence is stale, the API and browser expose a verification state instead of immediately showing a free-plan upgrade prompt. Recent stale renewals can trigger one coalesced provider check on the request path; a scheduled sweep handles the wider backlog, backs off transient failures, and downgrades only after repeated definitive provider absence. A single missing response cannot remove paid access, and a mass of provider 404s stops further downgrades until the provider configuration is checked.

Manage Billing creates a user-specific Dodo customer portal session. The resolver prefers customer evidence on the user’s subscription records, falls back to legacy payload data or a same-user customer record, and rejects a customer linked to another user. The edge portal route verifies the Clerk bearer token, applies a user-scoped rate limit, and uses idempotency so repeated clicks do not create competing portal sessions.

Billing email repair keeps the provider’s billing address and WorldMonitor’s local recipient state aligned after a hard bounce. The billing view exposes the effective recipient and bounce status only while the subscription still receives billing mail. A user-owned update checks customer ownership and suppression rules, changes each Dodo customer first, then mirrors successful results locally; provider failures remain structured and do not hide partial updates.

Portal failures remain distinct from missing or shared customer data. Convex returns structured error kinds for those cases, while provider failures are logged for diagnosis and exposed to the client as a portal error that can use the existing recovery surface.

References: convex/…/subscriptionHelpers.ts• L251-311 convex/…/subscriptionHelpers.ts• L492-668 convex/…/subscriptionHelpers.ts• L1310-1712 convex/…/subscriptionHelpers.ts• L1763-1887 convex/…/subscriptionHelpers.ts• L1957-2075 convex/…/billing.ts• L430-487 convex/…/billing.ts• L1216-1539 convex/…/billing.ts• L1592-1787 convex/…/billing.ts• L1840-2035 convex/…/billing.ts• L2171-2458 convex/…/cacheActions.ts• L142-319 convex/…/subscriptionHelpers.ts• L77-100 convex/…/unattributedPayments.ts• L20-29 convex/…/unattributedPayments.ts• L58-163 convex/…/unattributedPayments.ts• L216-292

Lifecycle email delivery

Subscription email delivery is a downstream response to billing state. Welcome and reactivation messages tell the customer what access is active, while payment-failure, cancellation, and winback messages guide the next billing action without blocking webhook processing.

The daily lifecycle process re-checks the subscription, entitlement coverage, billing episode, email suppression state, and prior-send ledger before it sends. It checks again after any provider pacing wait, so recovery, a new cancellation episode, or a new entitlement can cancel a detached send. It uses the same effective billing-recipient rule as the billing view, so a newer user repair can redirect later dunning mail without letting an older webhook overwrite it. It sends payment reminders during an on-hold episode, retries cancellation confirmation while access remains active, and sends one winback message about 30 days after access ends when no other subscription covers the account. A shared send pace protects the email provider during a backlog, and winback mail carries a marketing unsubscribe path.

The activation path sends a welcome only for a new subscription and sends a reactivation message only after prior access ended. It chooses the freshest trusted login address while keeping the checkout address available as the billing contact. When the checkout address differs from the login address, the welcome flow sends a sign-in pointer to the checkout inbox. The pointer is best effort, so a bad checkout address cannot prevent the main welcome or the operations notice. Deleted accounts stop lifecycle mail while retaining the billing evidence needed for later review.

References: convex/…/subscriptionHelpers.ts• L77-100 convex/…/subscriptionHelpers.ts• L1310-1712 convex/…/subscriptionEmails.ts• L376-527 convex/…/subscriptionEmails.ts• L640-688 convex/…/subscriptionEmails.ts• L739-910 convex/…/subscriptionEmails.ts• L1036-1134 convex/…/subscriptionEmails.ts• L1177-1369 convex/…/subscriptionEmails.ts• L1372-1524

Entitlement activation

After a successful checkout, the browser waits for the entitlement change that the webhook produces. The dashboard can use that live transition to unlock paid panels and to show a first-session activation experience. The wait uses live change events, bounded polling, and a late grace period, then shows a refresh action if the application state does not change in time.

Desktop does not need a redirect back into the app. The operating system browser completes payment, and the desktop app observes the same Convex entitlement state. The activation record is supplementary product state that records how a new Pro user engages with setup; the subscription and entitlement records remain the authority for access.

References: src/…/checkout.ts• L762-802 src/…/checkout.ts• L989-1149 src/…/checkout.ts• L1195-1250 src/…/checkout-entitlement-wait.ts• L1-200 convex/…/billing.ts• L676-727 convex/schema.ts• L698-758

Notification permissions and delivery

Notification entitlement

Notifications are a Pro capability. The settings surface shows the channel and rule controls only when the live entitlement reaches tier 1; otherwise it offers an upgrade path. The edge endpoint and the Convex write mutations enforce the same paid boundary so a caller cannot bypass the UI.

Notification state has two parts. A channel links an account to a delivery destination, while an alert rule says which events, scope, cadence, and severity may use that channel.

References: src/…/notifications-settings.ts• L178-219 convex/notificationChannels.ts• L45-75 convex/alertRules.ts• L14-55 api/notification-channels.ts• L360-464

Delivery channels

Users can connect Telegram, email, Slack, Discord, an HTTPS webhook, or browser push. External channels use a link, OAuth flow, or protected webhook value. A connected channel can be removed, and removing it also removes that channel from the user’s alert rules so later saves do not silently refer to a destination that no longer exists.

Alert rules support real-time or digest delivery, sensitivity, quiet hours, time zone, country scope, and optional watchlist ticker scope. Real-time delivery is limited to critical events; higher-volume event classes use a digest cadence. This keeps channel permission separate from the content and timing choices made by the user.

References: src/…/notification-channels.ts• L8-55 src/…/notifications-settings.ts• L427-589 convex/notificationChannels.ts• L457-559 convex/alertRules.ts• L57-80 convex/alertRules.ts• L192-270

Browser push permission

Browser push has an additional permission boundary owned by the browser. The client asks for notification permission, reuses or creates the browser’s push subscription, and registers its endpoint with the authenticated account. The server accepts only known push-service hosts before it stores the endpoint.

The browser permission is per browser, while the stored channel is per account. A blocked browser therefore does not prove that the account has no working push channel on another device. If the same device changes accounts, the endpoint moves to the current account so two users cannot receive each other’s alerts.

sequenceDiagram
    participant U as User
    participant B as Browser
    participant E as Edge API
    participant C as Convex
    participant R as Notification relay

    U->>B: Enable browser notifications
    B->>B: Request permission and create push subscription
    B->>E: Register endpoint with Clerk bearer
    E->>C: Check Pro and save account channel
    C-->>E: Channel accepted
    E-->>B: Registration result
    R->>C: Read active channels and alert rules
    R->>B: Send alert through push service

The Alerts and notification delivery page covers the downstream event and relay path.

References: src/…/push-notifications.ts• L26-53 src/…/push-notifications.ts• L122-173 src/…/push-notifications.ts• L219-239 api/notification-channels.ts• L111-139 api/notification-channels.ts• L571-609 convex/notificationChannels.ts• L247-340

Cross-layer account flow

The same account must remain identifiable across all three layers. A Clerk session supplies the identity, Convex confirms that identity before user-scoped work, and the API or Convex function checks the durable entitlement before it grants paid behavior.

flowchart TB
    A[Clerk sign-in] --> B[Browser auth state]
    B --> C[Clerk bearer token]
    C --> D{Request surface}
    D -->|Convex WebSocket| E[Convex identity subject]
    D -->|HTTP API| F[Edge JWT or API-key validation]
    E --> G[User, subscription, and entitlement state]
    F --> G
    G --> H{Plan and feature decision}
    H -->|Allowed| I[Dashboard, API, checkout, or notification write]
    H -->|Not allowed| J[Upgrade, retry, or billing action]

Account changes are treated as boundaries, not as ordinary refreshes. Active subscriptions, entitlement listeners, checkout intents, API-key operations, OAuth refreshes, and notification writes check that the user who started the operation is still the current user. Account deletion adds a durable Convex fence so delayed commerce or preference writes cannot recreate personal data after cleanup begins.

See Web client experience for browser composition and Persistent application state for the Convex data model.

Change checklist

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

  • Keep the Clerk token audience, issuer, and Convex setAuth contract aligned. A token that passes edge validation but fails Convex validation can make all user-scoped live reads look empty.
  • Keep convex/…/productCatalog.ts, api/product-catalog.js, api/_product-catalog.generated.js, generated browser product facts, and the seeded productPlans records aligned. A new plan must have one consistent product id, plan key, feature set, price source, and checkout visibility.
  • Keep the catalog’s MCP budget marker and limits aligned with api/…/quota.ts, the MCP reservation path, the allowance resource, and api/…/mcp-quota.ts. A shared-budget change must move both enforcement and display to the same counter.
  • Keep the free-account MCP allowance separate from the catalog’s free-plan MCP limit. The paid-funnel ceiling and its counter are a separate contract.
  • When adding a paid feature, update the UI gate, the HTTP gate, and the Convex write or action boundary. A UI-only gate does not protect direct API calls.
  • Preserve the difference between a confirmed free or lapsed answer and an entitlement verification failure. The first can show an upgrade or resubscribe action; the second needs a retryable response.
  • Keep the entitlement recompute after the subscription row update and make it consider every covering subscription, accepted Business Pro grant, and active complimentary source. Updating from only the triggering webhook can hide stronger access that still covers the user.
  • Keep read-time catalog merging aligned with stored entitlement features. New catalog fields must reach clients without overwriting valid per-user feature values.
  • Keep the meaning of active, on_hold, and cancelled aligned with currentPeriodEnd. A payment hold or cancellation must not preserve access beyond the paid-through date.
  • Keep entitlement cache writes environment-scoped and aligned with the Convex source row. The delayed resync must read current state rather than replay an old entitlement snapshot, and the Enterprise account block must not disappear from the cached view.
  • Keep cache invalidation for user API keys and embed keys tied to the same lifecycle transitions as their Convex records. A stale warm entry can outlive a revoke or entitlement lapse if only the database changes.
  • Keep the bootstrap API-key validator and the gateway validator aligned on cache version, key shape, key kind, cached principal shape, and scoped-key handling. A shared cache entry with the wrong shape can make one validator reject a key accepted by the other.
  • Keep Company Monitoring scope validation, account ownership, and the dedicated scoped-key validator aligned. A key with a stored scope must not fall back to the unscoped bootstrap principal.
  • Keep deployment-prefixed API-key caches separate from the cross-deployment entitlement cache. A change to either cache contract must preserve the short retry window for lapsed or unverified billing states.
  • Preserve the bootstrap API-key status contract. Invalid credentials use 401, missing or lapsed API access uses 403, validation outages use 503 with retry guidance, and rate-limit responses remain distinct.
  • Keep OAuth metadata issuer, resource, and endpoint origins aligned with the supported host allowlist. Host-derived metadata must retain Vary: Host so one host cannot receive another host’s discovery document.
  • Keep the trusted CIMD URL list, its vetted snapshots, and the redirect-uri policy aligned. Add or remove a client in all related trust and review records, and keep transient fetch failure separate from a withdrawn or invalid document.
  • Keep the shared redirect policy aligned across dynamic registration, API-key consent, Pro grant minting, and token exchange. Authorization GET and POST plus Pro completion must re-check the current redirect allowlist even for an existing registration.
  • Keep OAuth registration admission and payload bounds fail closed. A missing or uncertain rate-limit decision must not persist a client record, and a larger redirect or metadata record must not bypass the stored-size limits.
  • Keep the OAuth consent origin allowlist, browser binding, stored issuer, and exact redirect policy aligned. A newly supported WorldMonitor host must be accepted by consent without trusting foreign origins or weakening the one-time nonce boundary.
  • Keep each OAuth consent binding tied to its own nonce and cookie. Cross-host consent needs the first-party domain scope, while parallel tabs need distinct cookie names so one flow cannot redeem another.
  • Keep the OAuth consent, Pro authorization, and token exchange paths aligned on exact redirect matching, PKCE, the stored issuer, browser binding, and one-time request or code use. A client metadata change must not leave one path more permissive than another.
  • Keep OAuth Pro token records and their bearer resolver aligned. The grant kind, user binding, MCP token binding, and refresh-family data must remain readable by both authorization-code and refresh-token paths.
  • Keep token client revalidation ahead of one-time code consumption and refresh rotation. A transient metadata failure must preserve a retry path, while a withdrawn client must not receive a new credential.
  • Keep refresh-family replay evidence and refresh-token recovery state separate. A temporary restore failure must not become family revocation evidence, and a confirmed rotated-token replay must still revoke the family.
  • Keep the refresh idle window, family pointer TTL, revocation marker TTL, and replay-grace window aligned. Replay evidence must outlive any token that can still be presented, while the short grace path must not hide later reuse.
  • Keep complimentary-grant validation aligned with subscription expiry and entitlement recompute. A grant must preserve access only through its own end time and must not be shortened by an unrelated subscription event.
  • Keep entitlement schema validators tolerant of both legacy feature rows and current catalog fields. A new optional feature must be accepted by stored rows and cache-sync actions before catalog updates reach production.
  • Keep renewal reconciliation aligned across the request rescue path, scheduled sweep, provider status mapping, repeated-not-found confirmation, and entitlement recompute. A transient Dodo failure must retry, while a confirmed missing subscription must eventually leave the active set. Keep the mass-not-found circuit breaker aligned with the downgrade path so provider or configuration failure cannot remove many paying users at once.
  • Keep Business seat grants aligned across the catalog’s bundled-license claim, the four-invite seat cap, corporate-domain checks, verified invitee email, grant status, and entitlement recompute. A plan or cap change must update both the owner controls and the acceptance path.
  • Keep customer-portal customer resolution user-scoped across current subscription fields, legacy payloads, customer records, and deleted-customer records. A fallback must recover old data without opening another user’s billing portal.
  • Keep the billing recipient resolver aligned across the billing view, dunning context, and lifecycle sends. A newer local repair must outrank an older webhook, while a newer webhook must be able to replace the repair.
  • Keep billing email repair user-scoped across Dodo customer ownership, suppression checks, provider updates, local mirrors, cooldowns, and the account-deletion fence. A partial provider update must not make local state claim that every customer changed.
  • Keep lifecycle email episode keys, access-end dates, suppression checks, pacing, and send ledgers aligned. A detached reminder must re-check state after its pacing wait, and a winback must not send while another entitlement covers the account.
  • Keep payment event status mapping aligned with the provider event types. processing and requires_customer_action are pending states, not failed charges, and refund or dispute records must remain separate from subscription state changes.
  • Keep unattributed payment recording ahead of webhook acknowledgement. A charged event must remain durable and visible for manual attribution, while repeated uncharged events from one customer must use the quiet period rather than create an alert storm.
  • Keep payment-event identity resolution aligned with subscription ownership, signed checkout metadata, customer records, and unattributed-event handling. A deterministic identity miss must remain visible to operations without granting access to an unknown account.
  • Keep checkout-session events linked by the provider session id and keyed by account ownership. Retention, anonymous-to-authenticated claims, and deletion cleanup must preserve funnel counts without making the event log a billing authority.
  • Keep the account-deletion fence ahead of every user-scoped commerce write, and update the deletion registry and cleanup batches when a new user-owned table is added. A missing fence or registry entry can allow stale data to return after deletion.
  • Keep the portal edge route and Convex action error kinds aligned. Missing customers, shared customers, provider errors, rate limits, and relay failures need different recovery paths.
  • Keep browser push permission and account channel state as separate contracts. A permission change must not remove a valid channel record or an alert-rule channel by accident.
  • Keep alert-rule delivery mode and sensitivity validation atomic when both fields change. The real-time and digest combinations have different allowed event severity.

Important failure modes

TriggerConsequenceGuard
Clerk token is invalid, expired, or issued for the wrong audienceHTTP requests return unauthenticated and Convex user reads do not attach to the accountEdge JWT verification checks issuer, audience, signature, subject, and expiry; Convex uses the verified identity subject
An anonymous wms_ session is treated as a paid or user-bound credentialA public browser session could reach a route that needs a real account or entitlementSession-shaped keys are accepted only for non-forced basic access; premium paths require a user key, enterprise key, or Clerk identity
A caller sends an explicit non-session key while a stale browser cookie is presentThe request could run under the wrong credential classHeader credentials remain authoritative, and desktop origins require a valid enterprise key
Convex entitlement lookup fails during a paid requestA paying user could receive a false upgrade denialShared entitlement gates return a retryable verification result when the lookup was attempted but did not produce an answer
An entitlement cache write or delayed resync failsThe API can read an older decision until the short cache lifetime ends, but the durable entitlement remains correctCache writes report the failure, the API falls back to Convex on a miss, and the resync reads current database state
OAuth metadata names a different issuer or resource origin from the host that served itAn MCP client can reject discovery or send tokens to the wrong serverMetadata derives its origin from an allowlisted host, varies cached responses by host, and returns matching issuer, resource, and endpoint origins
A dynamic registration request exceeds its size bound or registration admission is unavailableA client record is not created, or uncontrolled registration traffic could reach storageRegistration bounds the body and metadata, and persists only after a definite rate-limit decision
A CIMD client URL is untrusted, invalid, or no longer publishes an accepted documentAuthorization stops before a client can receive a codeOnly trusted URLs are fetched; documents are checked against the client id and redirect rules, with snapshots used only for transient failures
A callback is outside the exact vendor list, Google Connected Apps path policy, or HTTP loopback policyRegistration or authorization stops before a code can reach an unintended destinationThe shared redirect helper checks the approved policy at registration and again during API-key consent and Pro completion
A consent POST comes from a foreign origin or a different browserA client could attempt cross-site authorization or a forwarded consent link could be redeemedHosted origins are allowlisted, the nonce is single-use, and the per-flow browser binding must match the stored request
A redirect URI is accepted by consent but not by Pro completion or token exchangeA code can be sent to an unintended callback or a valid client cannot finishEach stage re-checks exact registered callbacks and the current allowlist; loopback port variance is limited to approved public clients
OAuth client metadata is unavailable after a one-time code or consent record is consumedThe MCP client loses a valid handshake and must restartCIMD is resolved before consuming the relevant one-shot record, and the consent path creates a fresh retry nonce for transient failures
A Pro OAuth refresh reaches Convex during a transient outageA valid client could be forced to sign in again because its refresh token was consumed too soonThe refresh attempt is restored and returns a retryable server response; only a confirmed revocation returns invalid_grant
A rotated OAuth refresh token is replayedThe attacker or the original client could continue using sibling tokensPersistent refresh-family evidence lets the service revoke the family and require re-authorization
Refresh recovery fails after the token is consumedA client can lose a valid refresh token, or a temporary failure can be mistaken for replayThe service restores the original expiry when possible, keeps in-flight state short-lived, and writes a family-free tombstone only after confirmed recovery failure
A client retries a refresh after a lost response or two refreshes run at onceA valid client can be forced to sign in again even though rotation already succeededA short client-bound successor record returns the same pair only while the successor remains unused; later or cross-client reuse revokes the family
A scoped API key has no valid Company Monitoring account or has a mismatched account bindingA key can be rejected, or a malformed credential could cross a tenant boundaryConvex validates scope values and owner account identity before returning the key principal; malformed bindings fail closed
A wm_ key is malformed, revoked, desktop-kind, or scoped for a dedicated product but sent to the generic bootstrap pathThe request is rejected as invalid instead of being treated as a generic user principalThe bootstrap validator checks the canonical key form, cache shape, key kind, and scope binding, then accepts only legacy unscoped API-key results
Key or entitlement validation cannot reach ConvexA caller could be misclassified as invalid or free during an infrastructure outageThe bootstrap path returns a no-store 503 with retry guidance and keeps validation failure separate from 401 and 403 results
The bootstrap key rate-limit store is unavailable or its counter has no valid expiryUnchecked bootstrap traffic could reach validation, or a valid request could be rejected without a clear service signalThe rate-limit check fails closed with a degraded 503 and uses a fixed-window counter with an expiry
The public catalog seed is empty and live provider reads also failThe pricing page could lose its product view or show stale live data as currentThe endpoint uses static fallback prices with a short cache and marks the response source as fallback; partial live reads are marked partial
The catalog and MCP quota resolver disagree about a shared budgetMCP usage can be enforced against one counter while settings report another numberThe catalog marker, budget resolver, counter-key helper, and quota endpoint share the same budget decision
A free-account MCP caller is read from the paid Pro counterSettings can show zero usage while the free allowance is consumed and enforced elsewhereThe quota endpoint classifies the caller first and reads the free-account counter with the same daily ceiling as the call site
Redis is unavailable while the quota display is readSettings shows zero usage even though enforcement may have rejected or reserved callsThe display endpoint fails soft and remains informational; reservation paths fail closed before dispatch
A Business owner invites a non-corporate address, exceeds the invite cap, or accepts with an unverified different emailA seat can be granted outside the plan’s intended organization or the owner can over-issue licensesThe owner and invitee use server-side corporate-domain checks, pending invites count toward the four-seat cap, and acceptance requires a verified matching address
A Business subscription stops covering after a seat was acceptedThe invitee could retain Pro access after the owner loses the qualifying planGrant revocation follows subscription coverage and recomputes the invitee entitlement; direct removal uses the same recompute path
A user starts checkout with an active subscription or another pending paymentA duplicate subscription or stacked payment may be createdConvex checks both billing state and pending payment state before creating the Dodo session; the pending-payment block can be bypassed only after explicit confirmation
A checkout retry reaches the edge relay with the same idempotency keyA second provider session may be created, or the user may consume the admission budget twiceThe edge checks completed idempotency before the per-user and client-IP admission limits and scopes the request to the validated user
A user exceeds the checkout admission window, the client-IP window, or an admission store cannot confirm capacityRepeated checkout attempts can overload the provider, or unknown capacity can authorize uncontrolled workConvex allows a small per-user window; the edge applies fail-closed per-user and client-IP limits
Dodo rate-limits the shared checkout key or a checkout attempt times outThe buyer may wait through bounded retries and then receive a retryable failure without a hosted sessionThe checkout action parses provider wait hints, limits total attempts and time, retries one timeout, and returns typed terminal outcomes
The edge relay times out while Convex may still be creating a sessionA browser retry could overlap the first request and create duplicate provider sessionsThe relay uses a bounded fetch, the browser has a single transport retry, and idempotency replays completed requests
The terminal checkout rate-limit alarm cannot write its eventThe buyer still receives the provider retry response, but the rate alarm can lose the occurrenceThe recorder fails open for checkout and emits a separate operations error when the alarm write fails
Checkout-session logging fails after Dodo creates a sessionFunnel reporting misses a buyer who can still complete paymentThe log write is best effort and the live hosted session remains the purchase path
The hosted checkout handoff fails on desktopThe buyer may see no checkout or may be told to check a browser that never openedThe client reports the handoff failure and keeps a retry surface; it distinguishes a native browser handoff from a WebView fallback
A checkout intent survives past its time limit or belongs to another userA later sign-in could start a purchase the user did not request, or expose another user’s purchase contextPending intents carry an owner and timestamp; the client discards stale or cross-user intents and clears state on account changes
Anonymous checkout data is claimed with a bare or injected idAnother account could receive payment, customer, or entitlement recordsClaiming requires a UUID-v4 anonymous id, the server-issued signed claim proof, the current authenticated user, and a writable account
A complimentary grant uses an unknown plan or a non-positive durationBilling state can contain invalid access or a support grant can silently failThe grant accepts only known catalog plans and a positive finite duration, then records matching validity and complimentary end times
A subscription event expires one covered subscription while another subscription or complimentary grant remains liveThe entitlement can drop to free or to a weaker plan even though paid or granted access still covers the userRecompute examines all covering sources, applies plan precedence, and preserves a valid complimentary period
Dodo sends an unknown product idEntitlement processing could stop and leave a paid account without current accessProduct mapping checks the database, aliases, and code catalog, then uses an alerted highest-paid fallback instead of failing the webhook
A settled activation or payment event has no trusted account identityA paid customer can remain unattributed, or repeated retries can create a delivery stormExisting subscription ownership, signed metadata, and known customer records are checked first; the event is durably recorded before acknowledgement and queued for manual attribution
An unattributed uncharged payment repeats for one customerOperations can receive a flood of alerts for one failing payment methodUncharged events use a per-customer 24-hour notification quiet period; charged events are not throttled
A payment processing or customer-action event is stored as failedPending-payment checks and user-facing billing state can report a false terminal failureEvent status derives from both the webhook type and provider intent status
A full refund arrives without a prior subscription cancellationThe user can keep paid access until an operator finds the process gapThe system records the refund and raises an operator alert; it does not silently revoke access
Dodo webhook processing failsThe provider may retry, but local subscription and entitlement state stays unchanged until a successful attemptWebhook work is transactional and records the event only after dispatch succeeds
A subscription is cancelled before its paid period endsAccess may be removed too early if cancellation is treated as immediate expiryCoverage is evaluated against the current paid-through period
Renewal verification receives a transient Dodo error or a single 404A paying user could be downgraded because provider evidence was incompleteRequest and scheduled paths mark the attempt for retry; only repeated definitive not-found results can expire the local subscription
A provider outage makes many subscriptions appear missingA broad outage could downgrade a large part of the paid baseReconciliation uses backoff, repeated-not-found confirmation, and a mass-not-found circuit breaker
Manage Billing finds no customer or finds one linked to another userThe user cannot open billing, or a portal could expose another account’s invoicesThe resolver uses same-user evidence and rejects shared customer ownership with a structured NO_CUSTOMER result
Dodo fails while creating a customer portal sessionThe user sees an opaque or misleading server errorConvex logs the provider cause and returns structured DODO_PORTAL_ERROR data for client classification
The billing address hard-bounces or a billing email update changes only some Dodo customersPayment and dunning messages can go to a dead address, or local state can claim that a provider update completed when it did notThe shared recipient resolver exposes the active address and bounce state; the repair checks exclusive ownership, updates Dodo before local mirrors, and reports partial provider failure
An account-deletion request exists while checkout, claiming, or billing writes runNew commerce data can be created after cleanup or a delayed callback can restore personal recordsassertAccountWritable reads the durable fence in the write transaction and returns ACCOUNT_DELETION_IN_PROGRESS
A detached lifecycle email runs after recovery, expiry, suppression, or a new billing episodeThe user can receive a false payment warning, cancellation confirmation, or winback messageThe send action re-checks live state before and after its pacing wait, then uses episode, suppression, and sent-step records
Browser notification permission is denied or unsupportedPush cannot be added on that browser, while other account channels may still workThe UI reports the browser state separately and keeps an existing account channel removable
The same browser push endpoint is linked to two accountsAlerts could cross account boundaries on a shared deviceConvex transfers the endpoint to the current user before saving the new channel
A user switches accounts while a checkout, key, OAuth refresh, or notification write is in flightData or credentials could be attached to the wrong userClient operations pin the starting user and re-check account identity before completing

Key files

FileWhy to read it
src/…/clerk.tsBrowser Clerk loading, sign-in, sign-out, session listeners, and bearer-token access
src/…/auth-state.tsSmall reactive auth state consumed by the web client
src/…/convex-client.tsClerk-to-Convex auth binding and per-user Convex readiness
server/auth-session.tsServer-side Clerk JWT verification and plan-role resolution
server/gateway.tsShared HTTP request path where credentials and route access meet
api/_user-api-key.jsBootstrap user-key validation, rate limits, cache versions, key kinds, and API entitlement checks
convex/…/auth.tsConvex identity resolution and required-user boundary
convex/…/guard.tsDurable write fence used while an account is being deleted
convex/…/productCatalog.tsCanonical product, plan, feature, and limit definitions
api/_product-catalog.generated.jsGenerated public plan facts, product mappings, tier limits, and fallback prices
api/product-catalog.jsPublic pricing catalog view and its live, seeded, and fallback price sources
convex/entitlements.tsAuthenticated entitlement reads, catalog merging, and free-tier fallback
convex/…/entitlements.tsPlan-feature resolution and migration-safe merging of stored entitlement values
convex/…/comp-entitlement.test.tsCoverage for complimentary access, multi-subscription precedence, expiry guards, and optional feature fields
convex/…/subscriptionHelpers.tsWebhook-to-subscription state, entitlement recomputation, renewal reconciliation, paid-period coverage, Business Pro grants, payment event handling, billing recipients, and unattributed billing events
convex/…/billing.tsSubscription display, renewal verification and reconciliation, customer ownership resolution, portal access, billing email repair, anonymous claim, account-deletion checks, and billing lifecycle state
convex/…/businessSeats.tsAPI Business invite, seat cap, verified acceptance, revocation, and team-access email flow
convex/…/unattributedPayments.tsDurable handling and operations alerts for paid or failed events without a known account
convex/…/cacheActions.tsEntitlement synchronization and lifecycle invalidation of warm edge caches
server/…/entitlement-check.tsHTTP entitlement lookup, tier map, cache, public route exceptions, and billing-verification contract
api/…/quota.tsShared MCP budget choice, daily limit resolution, and counter selection
api/oauth-authorization-server.tsHost-consistent OAuth authorization-server discovery metadata and agent registration claims
api/oauth-protected-resource.tsProtected-resource metadata for the MCP resource paths
api/…/_client-metadata.jsTrusted client discovery, CIMD validation, caching, and redirect checks
api/…/_client-metadata-snapshots.jsReviewed fallback metadata for trusted clients during transient fetch failures
api/…/_redirect-uri.jsShared OAuth callback allowlist, Google Connected Apps policy, and loopback policy
api/…/_browser-binding.jsPer-flow browser binding for cross-host consent and forwarded-nonce protection
api/…/register.jsDynamic client registration admission, bounds, and callback policy
api/…/authorize.jsAPI-key consent, hosted-origin checks, browser binding, issuer capture, one-time authorization codes, current callback checks, and retry handling
api/…/authorize-pro.tsUser-bound Pro MCP authorization, current callback checks, and entitlement re-check
api/…/token.tsOAuth code exchange, legacy and Pro token records, client revalidation, refresh rotation, and replay handling
api/…/_refresh-recovery.tsRefresh-token recovery state, replay grace, family evidence, and safe handling of failed restores
api/create-checkout.tsAuthenticated edge checkout relay, per-user and client-IP admission, idempotency, and error contract
convex/…/checkout.tsCheckout guards, account-deletion fence, signed identity metadata, Dodo session creation, and session-event recording
convex/…/checkoutSessionLog.tsAccount-owned checkout funnel events, provider-session joins, retention, and counts
convex/…/checkoutRateLimit.tsBounded handling of Dodo rate limits and checkout timeouts
convex/…/checkoutRateLimitAlarm.tsDurable terminal checkout failure records and operations alerts
src/…/checkout.tsBrowser and desktop checkout handoff, user-bound retry state, return handling, and entitlement activation feedback
api/customer-portal.tsAuthenticated customer-portal relay, rate limit, idempotency, and relay error mapping
convex/…/webhookMutations.tsSubscription and payment event dispatch with idempotent processing
convex/…/subscriptionEmails.tsSubscription welcome, dunning, cancellation, winback, suppression, pacing, and email delivery rules
src/…/notifications-settings.tsUser-facing notification controls and paid-feature presentation
api/notification-channels.tsAuthenticated notification API and entitlement boundary
convex/notificationChannels.tsDurable channel records, Pro checks, and account-safe push registration
convex/alertRules.tsDurable alert preferences and delivery-mode validation