Skip to content
Merged
180 changes: 180 additions & 0 deletions docs/contributing/architecture/entitlements.md
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`).
3 changes: 3 additions & 0 deletions docs/contributing/architecture/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ to become.
MCP auth.
- [Authorization](./authorization.md): role-based access control (RBAC), admin
routes, and the `any`-access exception to per-user isolation.
- [Entitlements](./entitlements.md): per-user plans (`users.plan`), per-plan
resource limits, and the shared `assertWithinEntitlement` enforcement helper
(NULL plan = legacy/unlimited).
- [Data Storage](./data-storage.md): what is stored in D1, KV, and Durable
Objects.
- [Usage Metering](./usage-metering.md): per-user usage events, the
Expand Down
12 changes: 12 additions & 0 deletions docs/contributing/architecture/primitives.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,18 @@ primitives:
docs:
- docs/contributing/architecture/authorization.md

- id: entitlements
group: auth
name: Plans & entitlements
summary:
Per-user plan column (users.plan) with per-plan resource limits and the
shared assertWithinEntitlement guard; NULL plan means legacy/unlimited and
disables enforcement entirely.
code:
- packages/worker/src/entitlements/
docs:
- docs/contributing/architecture/entitlements.md

# --- User-facing assistant primitives -----------------------------------
- id: capability-registry
group: assistant
Expand Down
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).
Comment on lines +3 to +4

Copy link
Copy Markdown

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:

#!/bin/bash
# Confirm which migration actually adds the users.plan column
rg -n --iglob '*.sql' -e 'ADD COLUMN[[:space:]]+plan' -e 'plan[[:space:]]+TEXT' packages/worker/migrations
echo '--- 0046 header/plan refs ---'
fd '0046' packages/worker/migrations --exec rg -n 'plan|email_verified_at' {}

Repository: kentcdodds/kody

Length of output: 489


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- packages/worker/migrations/0048-user-plans-and-entitlement-counters.sql ---'
cat -n packages/worker/migrations/0048-user-plans-and-entitlement-counters.sql

echo '--- packages/worker/src/entitlements/test-schema.ts (relevant lines) ---'
rg -n -A4 -B4 '0046|0048|plan|email_verified_at|entitlement_daily_counters' packages/worker/src/entitlements/test-schema.ts

Repository: kentcdodds/kody

Length of output: 2451


Update the schema-history note in packages/worker/src/entitlements/test-schema.ts. 0046-invites-email-verification.sql adds users.plan, so the 0048 mapping there is stale and should point to 0046 instead.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/worker/migrations/0048-user-plans-and-entitlement-counters.sql`
around lines 3 - 4, The schema-history note in test-schema.ts is stale: the
users.plan column is introduced by 0046-invites-email-verification.sql, not
0048-user-plans-and-entitlement-counters.sql. Update the mapping/comment in the
schema history entry referenced by test-schema.ts so it points to 0046, and keep
the rest of the entitlement history notes aligned with the actual migration that
added users.plan.

-- 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)
);
7 changes: 7 additions & 0 deletions packages/worker/src/app/account-deletion.node.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -499,6 +499,10 @@ test('deleteUserAccount cascades user-scoped rows for the requested user', async
email_attachments: [{ id: 'ea-1', message_id: 'em-1' }],
email_delivery_events: [{ id: 'ed-1', user_id: userAaa }],
email_sender_identities: [{ id: 'ei-1', user_id: userAaa }],
entitlement_daily_counters: [
{ user_id: userAaa, resource: 'email_sends_per_day', day: '2026-07-05' },
{ user_id: userBbb, resource: 'email_sends_per_day', day: '2026-07-05' },
],
community_listings: [
{ id: 'listing-1', owner_user_id: userAaa },
{ id: 'listing-2', owner_user_id: userBbb },
Expand Down Expand Up @@ -652,6 +656,9 @@ test('deleteUserAccount cascades user-scoped rows for the requested user', async
expect(rows.repo_sessions).toEqual([])
expect(rows.email_attachments).toEqual([])
expect(rows.email_messages).toEqual([])
expect(rows.entitlement_daily_counters).toEqual([
{ user_id: userBbb, resource: 'email_sends_per_day', day: '2026-07-05' },
])
expect(rows.package_runtime_runs).toEqual([
{
id: 'run-3',
Expand Down
1 change: 1 addition & 0 deletions packages/worker/src/app/account-deletion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ const userScopedTables: ReadonlyArray<UserScopedDeleteTarget> = [
{ kind: 'user_id', table: 'email_inbox_addresses' },
{ kind: 'user_id', table: 'email_inboxes' },
{ kind: 'user_id', table: 'email_sender_identities' },
{ kind: 'user_id', table: 'entitlement_daily_counters' },
{
kind: 'community_listing_child',
table: 'community_ratings',
Expand Down
3 changes: 3 additions & 0 deletions packages/worker/src/app/handlers/account-secrets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,7 @@ async function handleConnectOauthAction(input: {
const accessSaved = await saveSecret({
env: input.env,
userId: input.user.mcpUser.userId,
userEmail: input.user.mcpUser.email,
name: accessTokenSecretName,
value: accessToken,
scope: 'user',
Expand All @@ -329,6 +330,7 @@ async function handleConnectOauthAction(input: {
await saveSecret({
env: input.env,
userId: input.user.mcpUser.userId,
userEmail: input.user.mcpUser.email,
name: refreshTokenSecretName,
value: refreshToken,
scope: 'user',
Expand Down Expand Up @@ -805,6 +807,7 @@ async function handleSaveAction(input: {
await saveSecret({
env: input.env,
userId: input.user.mcpUser.userId,
userEmail: input.user.mcpUser.email,
name,
value,
scope,
Expand Down
14 changes: 14 additions & 0 deletions packages/worker/src/email/outbound.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { sendCloudflareEmail } from '#app/email/cloudflare-email.ts'
import { isAccountEmailVerified } from '#app/email-verification.ts'
import { consumeDailyEntitlement } from '#worker/entitlements/service.ts'
import { recordUsage } from '#worker/usage/record-usage.ts'
import { normalizeEmailAddress } from './address.ts'
import {
Expand All @@ -26,6 +27,10 @@ type SendEmailEnv = Pick<
export type EmailSendInput = {
env: SendEmailEnv
userId: string
/**
* Acting user's account email (not the message from/to). Used for the
* verified-account gate and for entitlement plan lookup.
*/
accountEmail: string
from: string
to: string | Array<string>
Expand Down Expand Up @@ -216,6 +221,15 @@ export async function sendOutboundEmail(
const html = input.html?.trim() || null
if (!text && !html) throw new Error('Email text or HTML body is required.')

// Atomic check-and-increment: the counter tracks attempts for every user
// (plan or not) and denies the send when a plan's daily limit is reached.
await consumeDailyEntitlement({
db: input.env.APP_DB,
userId: input.userId,
email: input.accountEmail,
resource: 'email_sends_per_day',
})
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

const existingThreadId = original?.threadId ?? input.threadId ?? null
const thread = existingThreadId
? null
Expand Down
Loading
Loading