# Security Security-relevant patterns in the Worker, and the reasoning behind them. This doc is the authoritative record of what is protected, what is intentionally out of scope, and the invariants future changes must not regress. See the 2026-05-01 and 2026-07-01 internal security audits for the underlying findings, and [the 2026-09-16 codebase audit](../audits/2026-09-16-codebase-audit.md) for a later cross-cutting review. Kody is a multi-worker Cloudflare app: a TanStack Start browser UI and OAuth-protected MCP HTTP on origin, platform Durable Objects on `kody-platform`, package apps on `kody-runtime`, and cron on `kody-jobs`. It is multi-user, so the overarching invariant is that **every read/write path is scoped by `userId`**. Cross-user data sharing is a bug, not a feature. See [architecture](architecture/index.md#production-worker-fleet). ## Invariants for future agents (do not regress) Read this list before touching auth, routing, response construction, or the package-app surfaces: 1. **First-party HTML keeps its security headers.** All trusted account/auth pages must go through `render()` (`packages/worker/src/app/render.ts`), which applies `packages/worker/src/app/security-headers.ts`. Never add `'unsafe-inline'` to the CSP `script-src`. The scroll-restoration restore script is allowed only by its sha256 hash, not by relaxing `script-src`. 2. **Untrusted surfaces stay off the strict CSP.** Hosted package apps (`https://{username}./*` in production, or `/@username/packages/*` when served inline) execute author-supplied HTML/JS and intentionally do not use the first-party CSP. Do not "unify" the two. Because they have no CSP backstop, their isolation comes from the origin they run on and the credentials they never receive — see invariant 9. 3. **Developer-only routes fail closed.** Anything that runs attacker-authored content or aids debugging must be gated behind `isNonProductionRuntime` (`packages/worker/src/app/deployment-env.ts`) so it is unreachable in production. 4. **Credential endpoints are rate limited.** Any new endpoint that accepts a password, token, or reset code must join the shared `auth:ip` bucket: either list the path in `packages/worker/src/origin-handler.ts` (`rateLimitedAuthPaths`), or consume the same bucket from the Start function that handles the request (password reset and two-factor login do this today). 5. **New passwords go through the shared policy.** Use `getPasswordPolicyError` from `@kody-internal/shared/password-policy.ts` wherever a password is set. 6. **OAuth PKCE stays S256-only.** Keep the `getPkceValidationError` check in `oauth-handlers.ts` (reject `code_challenge_method` other than S256 when a challenge is present). `@cloudflare/workers-oauth-provider` is S256-only (no `allowPlainPKCE`); see the OAuth section below. 7. **Every data path is `userId`-scoped.** New D1 queries, Durable Object names, and Vectorize filters must include `userId`. Prefer parameterized SQL (`.prepare(...).bind(...)`); never interpolate user input into SQL. 8. **Untrusted markdown renders through the safe renderer only.** Community READMEs (and any future third-party-authored markdown shown on first-party pages) must go through `packages/worker/start/components/markdown-view.tsx`, which builds JSX from an allowlist of TanStack Markdown document nodes: raw HTML renders as escaped text (first-party guides may additionally emit allowlisted `
`/`` and GitHub-style `> [!TIP]` callouts; untrusted markdown never does), and links are restricted to absolute `http:`/`https:`/`mailto:` URLs with `/@...` user-scope paths and `/packages/...` package-app mount paths refused on any host so a README can never point viewers at hosted package endpoints. `` is emitted only for in-repo relative image paths rewritten to that package's first-party `/assets/` route (published or pinned package bytes, sniffed type, size-capped) and only when the viewed markdown is that same commit. Remote and other author-chosen URLs stay links. Never render third-party markdown via an HTML string, `innerHTML`, or a markdown-to-HTML renderer. 9. **Package code never receives first-party credentials, and never executes on the app origin in production.** Every request handed to package code goes through `createPackageCodeRequest` (`packages/worker/src/app/handlers/package-app.ts`), which strips `Cookie`, `Authorization`, `Proxy-Authorization`, and every `X-Kody-*` header — for the forwarded HTTP request _and_ the realtime connect upgrade, because the realtime `connect` hook is handed the request headers too. Production also sets `PACKAGE_APP_BASE_URL` so package apps run on their own registrable domain, cross-site from the app origin. Do not add a first-party route to the package-app origin, and do not reintroduce cookie forwarding "just for convenience". See [Hosted package app origin isolation](#hosted-package-app-origin-isolation). 10. **CSRF protection is `SameSite=Lax` + JSON content types, not tokens.** Every mutating first-party endpoint must keep requiring a JSON `Content-Type` (which cross-site form posts cannot send) and the `kody_session` cookie must stay `SameSite=Lax`. Do not add a mutating endpoint that accepts `application/x-www-form-urlencoded` or `multipart/form-data` from the browser, and do not relax the cookie to `SameSite=None`, without adding CSRF tokens at the same time. 11. **Email change requires a verified current address.** `POST /account/email-change.json` refuses to start a change when `users.email_verified_at` is null (403, audit reason `email_unverified`). Starting a change also requires the current password. The new address must confirm via `/verify-email-change` before `users.email` updates. After that commit, Kody emails the previous address (`email_changed` transactional kind) with a partial mask of the new address, when/IP/UA/country when available, and links to account settings, password reset, and `support@` on the system email domain. A former-email claim collision at password or social-login signup is a controlled 409 with audit reason `former_email_claimed` (copy tells the person to sign in with the email that account uses now, or release the address from Account settings — never leaking the current email). The owner re-verifies the former address (`POST /account/email-claim-release.json` plus `/verify-email-claim-release`) to drop the claim; that path is rate limited. New accounts get random `stable_user_id` values. Only `users.email` and active `user_email_claims` rows reserve an address; a legacy email-hash `stable_user_id` reserves nothing and is never recomputed from an email. 12. **Unverified accounts are reclaimed on a provider-verified social match.** When a social login profile presents a verified email that matches `users.email` and `email_verified_at` is null, treat the row as a possible squat before linking: rotate `password_hash` to an unusable sentinel, stamp `password_changed_at` (browser sessions and MCP bearers fail closed), revoke MCP grants, delete TOTP rows, passkeys, other `oauth_connections`, and outstanding `password_resets`, then link the provider and mark the account verified. An already-verified match only links and signs in. 13. **Unverified person accounts older than seven days are purged.** The hourly `unverified_account_purge` lane deletes `person` accounts whose `email_verified_at` is still null, `created_at` is older than seven days, and no `oauth_connections` row exists. The `oauth_connections` exemption is sound only because signed-in provider linking refuses a live `email_verified_at IS NULL` row (the insert is fenced on `email_verified_at IS NOT NULL AND deleting_at IS NULL`) and unauthenticated social sign-in always verifies. Each candidate is claimed with an atomic `UPDATE` that restamps `deleting_at` only while that eligibility still holds. Once claimed, email verification and social-login reclaim refuse the fenced row. A claim-created fence is released only on pre-cleanup failures (active writers or inventory); a partial-cleanup failure leaves the fence for retry. Never-attempted rows are processed before retries. Deletion uses the inventory-driven account-deletion path. Each purge writes an `unverified_account_purged` audit row; each failed deletion writes an `unverified_account_purge_failed` audit row (hashed email, reason `: ` with email addresses redacted and bounded to 200 characters) and a Sentry event tagged `scheduled.lane`, so a lane that fails every hour is visible without Workers Logs. Both are best-effort: an `AUDIT_DB` or Sentry outage is logged and skipped, not fatal. Operators run one pass on demand with the admin-only `adminUnverifiedAccountPurgeRun` MCP capability (`dryRun` previews the next claim page; results carry stable user ids, never emails or usernames). Password signups are the only unverified path; social-login accounts are verified at creation. Signed-in linking of a provider to a password account also requires that live verified email. 14. **Password-reset confirmation clears second factors and linked providers.** `confirmWebsitePasswordReset` on `/reset-password` disables TOTP, deletes passkeys and `oauth_connections`, and tells the owner in the confirmation email. Signed-in `changePassword` leaves those factors in place. 15. **User-secret trust grants are never applied by MCP or package runtimes.** `resourceLock({ kind: 'secret', name, package_id })` returns a website approval URL and does not write `allowed_packages`. Community fork adoption widens implicit user-secret read/use for a fork, so only the signed-in account session writes it (`adopt-community-fork` on `POST /account/packages.json`, from the package settings page). `communityForkAdopt` is read-only and returns that link. Interactive `execute` runs imported package code with the agent's caller context, so no `kody.*` capability may adopt: an unadopted fork would adopt itself. Package apps, jobs, webhooks, and other package runtimes cannot adopt or grant themselves secrets. 16. **Agents may narrow access; only owners widen it.** An agent or package runtime holding only Use on a resource (`secret:use`, `integration:use`) may lock a resource that any context can use to its first package, since that only removes access. Adding a package to an existing grant list returns `approval_required` with an owner `approval_url` and writes nothing. Integration and MCP server locks decide through `planPackageLock` ([`allowed-packages.ts`](../../packages/worker/src/mcp/secrets/allowed-packages.ts)), and a table-driven contract test with one row per kind ([`resource-lock.node.test.ts`](../../packages/worker/src/mcp/capabilities/secrets/resource-lock.node.test.ts)) fails when a kind widens or a new kind has no row. ## Variant check A security fix covers the pattern, not only the reported line. Before shipping, look for the same pattern in: - **Sibling kinds** of the same operation (for example every `resourceLock` kind, every grant-list mutator, every surface that reaches the same service). - **The other repo.** kody-hq/kody and kody-hq/kody-celld implement many of the same flows; check the matching code in the one you are not fixing. - **Docs** that describe the behavior, including guides that promise a security property. Fix any claim the code does not back, and link the claim to its test (see [Documentation](./documentation.md)). Record what you checked under **Variants checked** in the PR body. ## First-party HTTP security headers `render()` attaches the header set in `packages/worker/src/app/security-headers.ts` to every trusted HTML response (login, signup, account pages, the OAuth consent screen, and the SPA shell): - `Content-Security-Policy` with `script-src 'self' https://cdn.usefathom.com` (no `'unsafe-inline'`; the Fathom Analytics tracker is the only allowed external script; its image pageview beacon is allowed in `img-src` and its `sendBeacon` duration/event pings are allowed in `connect-src`; the scroll-restoration restore script is an inline classic script allowed only by its sha256 hash), `img-src` also allowlists `https://static.scarf.sh` for the Scarf page pixel on public marketing and docs, `frame-ancestors 'none'`, `base-uri 'self'`, `object-src 'none'`, `form-action 'self'`, `worker-src 'self' blob:` (for Sentry Session Replay), and `connect-src` limited to `'self'` plus the Fathom, Cloudflare Web Analytics, and Turnstile beacon hosts. The client bundle loads as an external module. `style-src` allows `'unsafe-inline'` because SSR-streamed styles arrive as inline `