Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,43 @@ All notable changes to LightCMS are documented here, organized by version.

---

## [7.5.0] - 2026-11-09

Agents now act as the person who connected them, the agent sandbox is enforced by the server, and merging an agent's own work is a permission an admin grants on purpose.

### Upgrade notes
- **Every OAuth connection has to sign in again once.** Tokens issued before 7.5.0 belong to no one and are refused. New connections start with **Sandbox** access: choose **Full** on the consent page, or later at Connected Apps, for an agent that should edit the live site directly.
- **`merge_fork` through an API key or connection now needs a permission.** An admin turns on "Can merge its own forks" for the key (API Keys) or connection (Connected Apps), and it then merges only forks it created. Forks made before 7.5.0 have no recorded creator; a person merges them at `/cm/forks/{id}`. Every merge, by anyone, now needs the `digest` from the fork's diff.
- **On first start the server deletes the "System (OAuth)" API key** and the stored copy of its value. Nothing else used it.
- OAuth access tokens are accepted only at `/mcp`. `/mcp` no longer accepts a browser session.
- `POST /api/v1/assets` no longer accepts `file_path`; send `data_base64`.

### Security
- **OAuth connections act as the person who signed in, not as an admin.** Tokens were exchanged for one stored admin key, so every connection had admin rights whoever approved it. A connection is now a grant naming the person, and each request loads their current role: a role change, a disabled account or a disconnected app takes effect at once. `/mcp` calls the REST API in-process as the caller, so no credential crosses a socket, and each MCP session is bound to the credential that opened it.
- **Tokens are bound to this server's `/mcp` resource** (RFC 8707). Authorization codes and refresh tokens are single-use, atomically; a used refresh token that comes back ends the connection. `/oauth/revoke` revokes (it used to do nothing). Client registration is rate limited and size limited, and redirect URIs must be `https` or loopback. The consent page says who the app will act as and where it sends you back, and an account still on a temporary password can't connect apps.
- **The agent sandbox is enforced by the server.** It was a variable in one MCP session: the REST API didn't know about it, ending it lifted every restriction, and webhooks, settings, theme, redirects, imports and approvals ignored it. Every key and connection is now **Sandbox** (it can change only forks it created) or **Full**. A default-deny table refuses every other write from a sandboxed caller, whichever tool sends it. Sandboxed uploads are limited to new images, PDFs, fonts and text. An open sandbox is recorded on the key or connection, so it holds across sessions and restarts.
- **Merging is bound to what was reviewed.** The fork diff covers every field a merge writes, compares complete values (a change past the first 2,000 characters used to be invisible), and lists a new page's content. It returns a digest; the merge must send it and is refused if the fork or a live page it changes was edited since. Submitting a sandbox freezes its fork.
- **An API key is refused when its owner is disabled or can't be loaded.** A failed owner lookup used to hand the key to the first admin permanently. Only a key with no owner on record is adopted, and it keeps its scopes and sandbox flag.
- **Publishing needs `content.publish` on every path**: creating or updating with `published`, bulk create, imports, auto-publishing import sources, reverting to a version, restoring a deleted page, and merging with `publish_new`.
- **Uploads no longer read files on the server.** `POST /api/v1/assets` read any `file_path` it was given, and on the hosted `/mcp` endpoint `upload_asset` read `file_path` from the server's disk. The stdio MCP binary still reads files from your own machine.

### Added
- **Connected Apps** (`/cm/connected-apps`): see, change and disconnect your OAuth connections; admins see everyone's.
- **Access settings on API keys**: Sandbox or Full, and "Can merge its own forks" (admins only). New keys made in the admin UI are Sandbox.
- **The review on the fork page**: `/cm/forks/{id}` shows every change field by field, with long values expandable, and merges exactly what it shows.
- `GET /api/v1/sandbox`, `POST /api/v1/sandbox`, `POST /api/v1/sandbox/end`.

### Changed
- **Merges are recorded in page history and can be undone.** Each live page a merge creates or changes gets a version with who made the change; `rollback_agent_session` undoes a session's merge. Versions now also record `noindex` and the author, so reverting restores them (older versions leave those fields as they are). A merged page's static file is rendered from the whole merged page, so its meta description, tags and author render as merged.
- **A fork is claimed while it is merged**, so a second merge of the same fork (an agent retrying, two people at once) is refused instead of applying twice. A new page a merge creates goes live only as the merge says: a schedule set on the fork copy is dropped, and fork copies can't be scheduled.
- Changes made through `/mcp` are recorded as agent changes with a server-generated agent session; the audit log names the key or connection used.
- Rate limits count per key or connection rather than per raw token.

### Internal
- The `/api/v1` routes moved from `cmd/server/main.go` to `internal/handlers/api_routes.go` (`MountAPI`), so tests can walk the real router.

---

## [7.4.6] - 2026-11-06

### Fixed
Expand Down
17 changes: 12 additions & 5 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,10 +178,15 @@ When creating or updating content via MCP or admin UI, the following markup feat

## Agentic Safety Features (v7.0+)

- **Agent sandbox sessions**: `start_agent_sandbox` makes all content writes go into a fork (copy-on-write); live content is untouched until a human reviews the diff at `/cm/forks/{id}` and merges. Publishing/deleting/bulk ops are blocked while sandboxed. PREFER sandbox mode for multi-page or risky edits.
- **Sandbox-only API keys**: keys created with `sandbox_only: true` are server-side restricted — content writes must target a fork; publish/delete/settings/search-replace are rejected. Keys can also carry a `scopes` permission allowlist.
- **Session ledger & rollback**: each MCP session has an agent-session ID recorded in the audit log; `get_agent_session_changes` shows everything the session touched, `rollback_agent_session` undoes it as a unit.
- **Provenance**: every content version records actor (human|agent), via (ui|api|copilot), and the agent session.
- **Credentials act as a person (7.5)**: an API key acts as its owner; an OAuth connection (`oauth_grants`) acts as the person who approved it. `auth.CredentialResolver` loads that person on every request (current role, disabled refused, revoked connection refused). There is no shared system key. OAuth tokens are bound to `BASE_URL/mcp` and refused at `/api/v1`; `/mcp` refuses cookies.
- **`/mcp` calls the REST API in-process** (`internal/mcp/http_handler.go`): the caller travels in the request context (`middleware.WithInternalCaller`), never as a credential, and the SDK binds each MCP session to the credential that opened it (`TokenInfo.UserID`). Only that file may call `WithInternalCaller`. A tool or resource handler must pass its `ctx` to the API client: a call without the caller fails closed. A panic in a REST handler is recovered in the transport.
- **Access: Sandbox or Full (7.5)**: every key and connection has it (`SandboxOnly`), plus `CanMergeOwnForks`, which only a signed-in admin can turn on for an account that can merge (consent page, `/cm/api-keys`, `/cm/connected-apps`; never through the API). New OAuth connections and keys made in the UI default to Sandbox.
- **The sandbox is enforced in the REST layer**: `auth.SessionUser.Sandboxed()` (Sandbox access, or an open sandbox) → `handlers.SandboxGate` refuses every write route not in `sandboxWriteRoutes` (`internal/handlers/api_sandbox.go`); the handlers behind allowed routes hold the caller to forks its credential created (`ContentFork.CreatedByCredential`) and to new non-executable uploads. Adding a write route to `/api/v1` fails `TestSandboxRoutes_EveryWriteRouteIsDecided` until it is listed as allowed (with why it can't reach the live site) or refused. MCP tools don't block anything themselves.
- **Agent sandbox sessions**: `start_agent_sandbox` (REST `POST /api/v1/sandbox`) records the open fork on the key or connection (`active_sandbox_fork`), so it holds in every session and across restarts; writes go into the fork (copy-on-write). `end_agent_sandbox` submit freezes the fork (`SubmittedAt`: no key or connection can change it) and never lifts Sandbox access. Merging, archiving or deleting the fork closes the sandbox (`ForkService.releaseSandboxes`). PREFER sandbox mode for multi-page or risky edits.
- **Merging is bound to a review**: `ForkService.Review` diffs every field a merge writes, in full, and returns a digest of the fork and live pages; `Merge` takes it and returns `ErrForkChanged` if anything changed. Through a key or connection, a merge needs `CanMergeOwnForks`, a role that can merge, and a fork that credential created and has not submitted (`APIMergeFork`). `Merge` claims the fork (status `merging`, expiring after 10 minutes) and takes the digest from exactly the pages it applies. A submitted fork is frozen for every key and connection on every route that changes it (edit, delete, revert, restore, archive, delete fork). Merges write a version per page and list `created_ids`/`updated_ids` in the `fork.merge` audit entry, which session rollback reads.
- **Sandbox-only API keys**: keys created with `sandbox_only: true` are the same Sandbox access. Keys can also carry a `scopes` permission allowlist.
- **Session ledger & rollback**: each MCP session has an agent-session ID recorded in the audit log (the HTTP endpoint generates it; the stdio binary sends its own); `get_agent_session_changes` shows everything the session touched, `rollback_agent_session` undoes it as a unit, merges included.
- **Provenance**: every content version records actor (human|agent), via (ui|api|copilot), and the agent session; the audit log also names the key or connection (`credential`).
- **Maintenance reports**: a daily scan surfaces stale pages, missing meta descriptions, and drafts via `get_maintenance_report` — treat it as a work queue.
- **Public read-only MCP**: `/mcp-public` (no auth) exposes search_site/get_page/list_pages/get_site_info to visitors' agents; `/llms.txt` and `/llms-full.txt` serve AI crawlers.
- **Admin copilot**: `/cm/copilot` lets editors drive content operations in natural language (requires ANTHROPIC_API_KEY; model via LIGHTCMS_COPILOT_MODEL).
Expand Down Expand Up @@ -215,7 +220,7 @@ Hard-won rules from building v7. Violating these has bitten us before:

### Provenance & agent sessions
- Every content mutation path must stamp `services.WithEditorEmail` and `services.WithProvenance` on the context (the /api/v1 middleware does this for API calls; the admin UI and copilot do it explicitly). Session rollback (`/api/v1/agent-sessions/{id}/rollback`) selects revert targets BY PROVENANCE — a session's own versions are never rollback targets. Timestamps race (a session's version write can land before its async audit entry); do not reintroduce timestamp-based selection.
- The MCP server sends `X-Agent-Session` on every request; audit logs record it.
- The MCP server sends `X-Agent-Session` on every request; audit logs record it. From other API clients the header is only a label. OAuth callers are always recorded as agents (`handlers.StampProvenance`).

### Performance: content queries need projections
- `models.Content` carries a ~4KB embedding vector and full data map per document. List-style endpoints (llms.txt, feeds, indexes) MUST use MongoDB projections — loading full documents made /llms.txt take 40+ seconds and starve the 1GB production VM.
Expand All @@ -226,6 +231,7 @@ Hard-won rules from building v7. Violating these has bitten us before:
- The handlers package has its OWN cleanup list (`cleanupCollections` in `internal/handlers/testhelper_test.go`), separate from `testutil.CleanupCollections`: add a new collection to both. It did not drop `content_forks` until 7.4.3, and `createTestFork` derives the preview token from the fork name, so a test that looks a fork up by token should use a unique name.
- When the Atlas test cluster is flaky a full `go test ./...` can fail a different handful of tests on each run (stalls of 15–100s, "i/o timeout", "server selection"). Read the failure text before debugging; a test that fails fast and repeatably on its own is real, the rest are the network.
- New MongoDB collections MUST be added to `CleanupCollections` in `internal/testutil/testutil.go`, or leftover data makes tests flake across runs (bit us with `maintenance_reports`).
- The `/api/v1` routes and their middleware are registered in `internal/handlers/api_routes.go` (`APIHandler.MountAPI`), so tests can mount and walk the real router; `cmd/server/main.go` only calls it.
- Tests must not write tracked files. The handlers and services write `static/sitemap.xml`, `static/css/theme-vars.css` and the admin editor's uploads relative to the working directory, which under `go test` is the package directory, where copies of the first two are checked in. `TestMain` in `internal/handlers` and `internal/services` points them at a temp directory (`sitemapFile`, `services.ThemeCSSFile`, `UploadsDir`) and fails the run if any tracked file under the package changed (`testutil.SnapshotTrackedFiles`). Give any new file the server writes the same kind of variable.
- Tests asserting on collection contents should match by seeded paths/IDs, not exact counts — background goroutines (index regen, keyword rebuild) can insert content mid-test.
- Coverage gate: Codecov ≥80% (target margin ~85%); codecov.yml excludes cmd/, testutil, internal/handlers, content_watcher.go. Codecov's line metric reads ~2 points BELOW `go tool cover` statement totals.
Expand Down Expand Up @@ -418,6 +424,7 @@ go run cmd/resetpw/main.go [email] # Reset specific user, or first admin if no
- Path traversal protection on all file operations
- Login rate limiting: Escalating lockout (10→1min, 15→5min, 20+→15min)
- Passwords: bcrypt with cost=12
- A request that changes what is published (create or update with `published`, bulk create, imports and auto-publishing import sources, revert, restore, `publish_new`) needs `content.publish`, whatever path it takes.
- RBAC: every REST endpoint calls `requirePermission`, and every `/cm` route is declared in `handlers.AdminRoutes` (`internal/handlers/admin_routes.go`) with the permission it needs — the one its `/api/v1` equivalent requires. `RegisterAdminRoutes` is the only place `/cm` routes are registered and puts the check in front of the handler (styled 403 page for forms and pages, JSON 403 for routes marked `JSON`). To add an admin route, add a line to that table; do not call `admin.HandleFunc` in `main.go`.
- `TestAdminRoutes_EveryWriteRouteIsGuarded` walks the registered router and fails if a non-GET `/cm` route has no permission and is not in `writeRoutesWithoutPermission` (login, logout, the two own-password routes, each with its reason). `TestAdminRoutes_RoleMatrix` sends every route as viewer, contributor, editor and admin against a hand-written expectation (`adminRoleMatrix`): changing who may call a route means changing that table on purpose.
- Rules the route table cannot express live in the handler: `UpdateContent` lets a contributor (`content.create` without `content.edit`) save a live draft only; `DeleteContent` needs `content.delete`, or `fork.create` for a fork copy; `DeleteAPIKey` only revokes the caller's own key below `apikey.manage_all` (the API route answers 403 for someone else's key and 404 for an admin deleting one that does not exist — `APIKeyService` deletes return `ErrAPIKeyNotFound` when nothing matched); `SiteConfiguration` leaves the Cloudflare token out of the page below `settings.edit`.
Expand Down
8 changes: 6 additions & 2 deletions MCP.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,9 @@ claude mcp add --transport http lightcms https://yoursite.example.com/mcp \
--header "Authorization: Bearer lc_your_key_here"
```

For remote clients (Cowork, etc.) that can't carry embedded credentials, OAuth 2.1 discovery is available at `/.well-known/oauth-authorization-server`. The client handles authorization automatically — just provide your LightCMS URL.
For remote clients (Cowork, etc.) that can't carry embedded credentials, OAuth 2.1 discovery is available at `/.well-known/oauth-authorization-server`. The client handles authorization automatically — just provide your LightCMS URL. You sign in, and choose the connection's access: **Sandbox** (default: it can change only forks it creates) or **Full** (anything your role can do).

On the hosted endpoint, `upload_asset` takes `data_base64`; `file_path` reads a local file only when the MCP server runs on your own machine (the stdio binary).

---

Expand Down Expand Up @@ -453,7 +455,9 @@ In this example, `author` and `excerpt` are stored as content fields because the

## 10. Security Notes

- All MCP tools require a valid API key (`Authorization: Bearer lc_...`) or a valid OAuth 2.1 access token.
- All MCP tools require a valid API key (`Authorization: Bearer lc_...`) or a valid OAuth 2.1 access token. Either acts as a person (the key's owner, or whoever approved the connection), with that person's current role.
- A key or connection set to **Sandbox** access can change only forks it created; the server refuses everything else, whichever tool asks. `start_agent_sandbox` records the open sandbox on the key or connection, so it holds across sessions and restarts.
- `merge_fork` needs the `digest` from `get_fork_diff`, and refuses if anything changed since. Through a key or connection it merges only forks that key or connection created, and only when an admin has allowed it to merge its own forks.
- Import tools (`import_markdown`, `import_csv`, `create_import_source`, `trigger_import_source`) require at minimum **editor** role. `delete_import_source` requires editor or admin.
- `cancel_import_job` requires editor or admin role.
- RSS feed URLs are fetched server-side by the LightCMS backend. Ensure your LightCMS server has outbound HTTP access to the feed host if you are running behind a firewall or NAT.
Expand Down
Loading