Repository navigation
Per-user plans and entitlement/quota enforcement #619
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 7 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
ca628d2
Add entitlements module: per-user plans, limits config, and shared en…
cursoragent 019e99f
Enforce per-plan entitlements at resource creation points
cursoragent ebb8d49
Merge origin/main (community deletion cascade, storage inventory cove…
cursoragent 50c50b9
Make daily entitlement consumption atomic (review feedback)
cursoragent ae14e6d
ci: re-trigger validate for HEAD (previous synchronize event produced…
cursoragent d79c643
Merge origin/main (invite signup, usage metering, audit events)
cursoragent f2c265a
Drop duplicate users.plan ALTER from migration 0048
cursoragent d88dbd3
ci: re-run preview after resetting the wedged pr-619 preview D1 database
cursoragent File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,180 @@ | ||
| # Entitlements (plans and quotas) | ||
|
|
||
| Per-user plans with per-plan resource limits. This is Kody's denial-of-wallet | ||
| protection for open signup: it bounds how many billable resources a single | ||
| account can consume. It deliberately contains **no payment code** — billing | ||
| integration comes later, after usage metering informs the limit numbers. | ||
|
|
||
| Module: `packages/worker/src/entitlements/` | ||
|
|
||
| - `plans.ts` — plan names (`partner`, `personal`, `pro`), the `PlanLimits` | ||
| config per plan, the `EntitlementResource` registry, and | ||
| `resolvePlanLimit(plan, resource)`. | ||
| - `errors.ts` — the one typed error (`EntitlementLimitError`) and the one | ||
| user-facing message builder every enforcement point uses. | ||
| - `service.ts` — `getUserPlan`, `assertWithinEntitlement`, built-in D1 usage | ||
| counters, and the daily-counter helpers for rate-style limits. | ||
|
|
||
| ## The NULL-plan invariant | ||
|
|
||
| `users.plan` is a nullable TEXT column (added by migration | ||
| `0046-invites-email-verification.sql`). **NULL means legacy/unlimited**: nothing | ||
| is enforced, and no counting query runs, for users without a plan. Unknown | ||
| stored plan values are also treated as NULL so plan renames can never lock users | ||
| out. Enforcement activates only when a known plan name is set — existing | ||
| accounts keep working unchanged. | ||
|
|
||
| ## Plan lookup | ||
|
|
||
| The MCP `userId` is the SHA-256 hash of the normalized account email | ||
| (`createStableUserIdFromEmail`), so `users.plan` cannot be joined on that id | ||
| directly. `getUserPlan(db, { userId, email })`: | ||
|
|
||
| 1. Normalizes the email and returns null (unlimited) when it is absent. | ||
| 2. Verifies `sha256(email) === userId` and returns null on mismatch, without | ||
| touching D1. This keeps the per-user-isolation invariant honest and makes | ||
| synthetic runtime contexts (package-scoped caller contexts with `email: ''`, | ||
| workflow-internal users, test fixtures) fail open. | ||
| 3. Reads `SELECT plan FROM users WHERE email = ?` and validates the value | ||
| against the plan registry. | ||
|
|
||
| Consequence: enforcement points must have the acting user's account email | ||
| available. Both auth surfaces provide it — app sessions expose | ||
| `user.mcpUser.email` and MCP caller contexts expose | ||
| `ctx.callerContext.user.email`. Code paths that genuinely have no user email | ||
| (for example package-manifest job sync or workflow-spawned inline code) are | ||
| documented fail-open gaps, acceptable because they are only reachable after a | ||
| user action that is itself gated. | ||
|
|
||
| ## The error shape | ||
|
|
||
| Every enforcement point throws `EntitlementLimitError` from | ||
| `entitlements/errors.ts` and lets it propagate unchanged. Its `details` field is | ||
| the stable programmatic contract: | ||
|
|
||
| ```ts | ||
| { | ||
| code: 'entitlement_limit_exceeded', | ||
| resource: EntitlementResource, // e.g. 'scheduled_jobs' | ||
| plan: PlanName | null, // null when a global fallback limit applied | ||
| limit: number, | ||
| current: number, | ||
| upgradeHint: string, | ||
| } | ||
| ``` | ||
|
|
||
| The `message` is built by `buildEntitlementLimitMessage` and is the single | ||
| user-facing string across MCP and UI surfaces: | ||
|
|
||
| > Plan limit reached: your "personal" plan allows at most 10 scheduled jobs and | ||
| > you currently have 10. Remove or finish existing scheduled jobs you no longer | ||
| > need, or ask the operator of this Kody deployment to upgrade your plan. | ||
|
|
||
| Rules: | ||
|
|
||
| - Never compose a custom denial message at an enforcement point; change the | ||
| builder if the message needs work. | ||
| - Never catch and rewrap `EntitlementLimitError` (use `isEntitlementLimitError` | ||
| if a surface must detect it). MCP execute results and UI handlers serialize | ||
| `error.message`, so the message carries the full context even across Durable | ||
| Object / RPC boundaries. | ||
|
|
||
| ## Counting strategy | ||
|
|
||
| - **Row-count limits** (saved packages, scheduled jobs, repo sessions, secrets, | ||
| concurrent workflows, running package services) are counted **directly from | ||
| their source D1 tables at the enforcement point** via built-in counters in | ||
| `service.ts`. They do not depend on any metering or rollup tables. | ||
| - **Rate-style limits** (email sends per day) use the | ||
| `entitlement_daily_counters` table keyed by `(user_id, resource, day)` with | ||
| UTC day keys. Call `consumeDailyEntitlement` on every attempt: it checks the | ||
| plan limit and increments the counter in one conditional D1 upsert (no | ||
| check-then-increment race), and still increments (uncapped) for users without | ||
| a plan so counters reflect real usage the moment a plan is assigned. Counting | ||
| attempts rather than successes keeps the limit abuse-resistant. | ||
| `incrementDailyEntitlementCounter` remains for raw counter writes (tests, | ||
| backfills). | ||
| - **Boolean allowances** (persistent package services) are modeled as limit `0` | ||
| (not allowed) vs `null` (allowed) so the numeric contract stays uniform. | ||
| - `maxStorageBytes` is defined in the limits config but not yet enforced; it has | ||
| no built-in counter and requires `getCurrent` when it gains an enforcement | ||
| point. | ||
|
|
||
| Because the plan check happens before any counting, enforcement adds zero | ||
| counting overhead for NULL-plan users. | ||
|
|
||
| ### Concurrency | ||
|
|
||
| Row-count limits are check-then-insert: the count query and the later insert are | ||
| separate statements, so a burst of concurrent creates can overshoot a limit by a | ||
| few rows before the next check sees the new count. That is an accepted trade-off | ||
| — these limits are order-of-magnitude denial-of-wallet caps, not billing-grade | ||
| accounting, and folding every insert into a conditional statement would couple | ||
| the entitlements module to each resource's write path. The rate-style path does | ||
| not share this window: `consumeDailyEntitlement` checks and increments in a | ||
| single conditional upsert. | ||
|
|
||
| ## How to add an enforcement point | ||
|
|
||
| The exemplar is job scheduling: `createJob` in | ||
| `packages/worker/src/jobs/service.ts`. | ||
|
|
||
| 1. Find the service-layer function that **creates** the resource (enforce on | ||
| creation, not updates), as early as possible — before any side effects like | ||
| entity-source creation. | ||
| 2. Make sure the acting user's `userId` **and** account email reach that | ||
| function. Thread an explicit `userEmail` parameter if the service only | ||
| receives `userId` today; MCP capabilities get it from | ||
| `requireMcpUser(ctx.callerContext).email`, app handlers from the session | ||
| user. | ||
| 3. Call the single helper and let it throw: | ||
|
|
||
| ```ts | ||
| import { assertWithinEntitlement } from '#worker/entitlements/service.ts' | ||
|
|
||
| await assertWithinEntitlement({ | ||
| db: env.APP_DB, | ||
| userId, | ||
| email: userEmail, | ||
| resource: 'scheduled_jobs', | ||
| }) | ||
| ``` | ||
|
|
||
| Use `fallbackLimit` only to preserve a pre-existing global backstop for | ||
| plan-less users (the workflow concurrency limit absorbed the | ||
| `WORKFLOW_CONCURRENT_LIMIT` env var this way via | ||
| `getWorkflowConcurrencyBackstop`). Use `getCurrent` only when the built-in D1 | ||
| counter cannot express the resource. | ||
|
|
||
| 4. If the resource is a new one, register it in `plans.ts` | ||
| (`entitlementResources`, `PlanLimits`, `planLimits`, | ||
| `entitlementResourceLabels`, `resolvePlanLimit`) and add a built-in counter | ||
| in `service.ts` when it is D1-countable. | ||
| 5. Test both sides: a plan user at the limit is denied with | ||
| `details.code === 'entitlement_limit_exceeded'` (assert `resource`, `plan`, | ||
| `limit`, `current`), and a NULL-plan user is unaffected. Build the test | ||
| user's id with `createStableUserIdFromEmail(email)` so the plan lookup's hash | ||
| verification passes. | ||
|
|
||
| ## Enforcement points | ||
|
|
||
| | Resource | Enforcement point | | ||
| | ----------------------------- | -------------------------------------------------------------------------------- | | ||
| | `scheduled_jobs` | `createJob` in `packages/worker/src/jobs/service.ts` (exemplar) | | ||
| | `saved_packages` | new-package branch of `package_save` and projection insert | | ||
| | `package_services` | `service_start` capability path | | ||
| | `persistent_package_services` | `service_start` for services declared `mode: 'persistent'` | | ||
| | `repo_sessions` | `repo_open_session` before creating a new session | | ||
| | `email_sends_per_day` | `sendOutboundEmail` (atomic `consumeDailyEntitlement`) | | ||
| | `secrets` | new-entry branch of `saveSecret` in `packages/worker/src/mcp/secrets/service.ts` | | ||
| | `concurrent_workflows` | `createDynamicCallableWorkflow` (plan limit, env-var backstop for NULL plan) | | ||
| | `storage_bytes` | not yet enforced | | ||
|
|
||
| ## Related tables and coordination | ||
|
|
||
| - `users.plan` — added by the invite-signup migration | ||
| (`0046-invites-email-verification.sql`); the entitlements module is the | ||
| consumer of that column. | ||
| - `entitlement_daily_counters` — rate counters, created by migration | ||
| `0048-user-plans-and-entitlement-counters.sql`; included in the | ||
| account-deletion cascade (`packages/worker/src/app/account-deletion.ts`). |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
20 changes: 20 additions & 0 deletions
20
packages/worker/migrations/0048-user-plans-and-entitlement-counters.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| -- Entitlement enforcement primitives. | ||
| -- | ||
| -- The nullable users.plan column is added by migration | ||
| -- 0046-invites-email-verification.sql (NULL means legacy/unlimited). | ||
| -- Plan values are validated in code against the plan names defined in | ||
| -- packages/worker/src/entitlements/plans.ts, so new plans do not require a | ||
| -- schema migration. | ||
|
|
||
| -- Daily counters for rate-style entitlements (for example email sends per | ||
| -- day). Row-count limits (packages, jobs, secrets, repo sessions) are counted | ||
| -- directly from their source tables at the enforcement point and do not use | ||
| -- this table. | ||
| CREATE TABLE IF NOT EXISTS entitlement_daily_counters ( | ||
| user_id TEXT NOT NULL, | ||
| resource TEXT NOT NULL, | ||
| day TEXT NOT NULL, | ||
| count INTEGER NOT NULL DEFAULT 0, | ||
| updated_at TEXT NOT NULL, | ||
| PRIMARY KEY (user_id, resource, day) | ||
| ); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
Repository: kentcdodds/kody
Length of output: 489
🏁 Script executed:
Repository: kentcdodds/kody
Length of output: 2451
Update the schema-history note in
packages/worker/src/entitlements/test-schema.ts.0046-invites-email-verification.sqladdsusers.plan, so the0048mapping there is stale and should point to0046instead.🤖 Prompt for AI Agents