diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e3d684..659c536 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/CLAUDE.md b/CLAUDE.md index e2fe0b9..577a792 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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). @@ -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. @@ -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. @@ -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`. diff --git a/MCP.md b/MCP.md index f180914..374af7d 100644 --- a/MCP.md +++ b/MCP.md @@ -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). --- @@ -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. diff --git a/README.md b/README.md index 57eab5a..dfceee9 100644 --- a/README.md +++ b/README.md @@ -38,8 +38,8 @@ LightCMS is a Go-powered content management system built for the AI era. It's si | Feature | Summary | |---------|---------| -| **Agent Sandbox ("PRs for content")** | Agents work in an isolated fork with copy-on-write; humans review a per-field diff and merge. Live content is untouchable until merge. | -| **Agent Governance** | Scoped API keys, sandbox-only keys (server-enforced), per-session change ledger with one-call rollback, and per-version provenance (human vs agent, which session). | +| **Agent Sandbox ("PRs for content")** | Agents work in an isolated fork with copy-on-write; a person reviews a complete per-field diff and merges exactly what was reviewed. The server enforces it: a Sandbox key or connection can't change the live site at all. | +| **Agent Governance** | Every key and OAuth connection acts as a person and is Sandbox or Full; merging its own forks is a separate permission only an admin grants. Per-session change ledger with one-call rollback (merges included), and per-version provenance (human vs agent, which session, which key or connection). | | **Admin Copilot** | `/cm/copilot` — edit, create, and publish content in plain language, with RBAC and full audit logging. | | **llms.txt + JSON-LD** | Auto-generated `/llms.txt` and `/llms-full.txt` for AI crawlers, schema.org structured data on every page. | | **MCP for Readers** | Public read-only MCP endpoint at `/mcp-public` — visitors' agents can search and read the site natively. | @@ -93,7 +93,7 @@ LightCMS is a Go-powered content management system built for the AI era. It's si **AI-Native**: Built from the ground up for the AI era: - **MCP Integration**: Full Model Context Protocol server with 130 tools and 3 prompt resources for website management. Supports both local stdio and HTTP streamable transports — connect from Claude Code, Claude Desktop, or any MCP-compatible client. -- **OAuth 2.1 for Remote Agents**: Sandboxed desktop apps like Claude's Cowork can securely connect over HTTP using OAuth 2.1 with PKCE. No embedded passwords — just authorize once and the agent manages your site. +- **OAuth 2.1 for Remote Agents**: Sandboxed desktop apps like Claude's Cowork can securely connect over HTTP using OAuth 2.1 with PKCE. No embedded passwords: sign in once, choose what the agent may do, and it acts as you within that. - **Fork-Friendly**: Designed to be forked and customized by Claude Code. Ask Claude to add new content types, modify templates, or build custom features — the codebase is structured for AI-assisted development. - **Natural Language Website Management**: Skip the admin UI entirely. Create pages, manage assets, customize themes, and publish content through conversation. @@ -176,7 +176,7 @@ Recommended agent pattern for large updates: `list_content` → transform in par - **Rate Limiting**: Per-IP and global rate limiting for DDoS protection ### Developer & Integration -- **REST API**: Full `/api/v1/` JSON API with API key and OAuth token authentication, RBAC-enforced +- **REST API**: Full `/api/v1/` JSON API with API key authentication, RBAC-enforced - **MCP Server**: 130 tools + 3 prompt resources for agentic website management (stdio + HTTP streamable) - **OAuth 2.1**: Authorization code flow with PKCE for remote MCP clients — no embedded passwords - **CLI Tool**: Command-line interface for all content management operations @@ -843,17 +843,21 @@ LightCMS implements OAuth 2.1 so that remote MCP clients (like Claude's Cowork) | Endpoint | Purpose | |----------|---------| | `POST /oauth/register` | Dynamic client registration (RFC 7591) | -| `GET /oauth/authorize` | Authorization page (admin login + consent) | +| `GET /oauth/authorize` | Authorization page (sign-in + consent) | | `POST /oauth/token` | Token exchange and refresh | | `POST /oauth/revoke` | Token revocation (RFC 7009) | | `GET /oauth/jwks` | JWKS endpoint (opaque tokens, returns empty) | ### Security +- **A connection acts as the person who approved it** (v7.5): every request loads that person's current role, so a role change, a disabled account or a disconnected app takes effect at once. The person also chooses the connection's access on the consent page: **Sandbox** (the default; it can change only forks it creates) or **Full** (anything their role can do). An admin can also let it merge its own forks. +- **Tokens are for this server's MCP endpoint only** (RFC 8707): `/mcp` accepts them, `/api/v1` does not, and an MCP session stays bound to the connection that opened it. - **PKCE (S256)** required for all authorization requests -- **Token rotation**: refresh tokens are single-use; a new pair is issued each time +- **Single use**: authorization codes and refresh tokens are consumed atomically; a refresh token that comes back after it was used ends the connection - **Short-lived access tokens**: 1-hour TTL -- **Refresh tokens**: 30-day TTL, revocable +- **Refresh tokens**: 30-day TTL +- **Revocation**: `POST /oauth/revoke` (client credentials required) ends a token, or with a refresh token the whole connection; people disconnect apps at **Connected Apps** (`/cm/connected-apps`) +- **Registration**: rate limited per address; redirect URIs must be `https`, or `http` to this device (loopback) - **Rate limiting**: failed login attempts trigger progressive lockouts (1 min → 5 min → 15 min) - **All tokens stored as SHA-256 hashes** in the database @@ -861,29 +865,27 @@ LightCMS implements OAuth 2.1 so that remote MCP clients (like Claude's Cowork) 1. Client fetches `/.well-known/oauth-authorization-server` to discover endpoints 2. Client calls `POST /oauth/register` with its name and redirect URI -3. Client redirects admin to `/oauth/authorize` with PKCE challenge -4. Admin enters password and approves access +3. Client sends you to `/oauth/authorize` with a PKCE challenge +4. You sign in, see who the app will act as and where it sends you back, choose its access, and approve 5. Client exchanges the authorization code for access + refresh tokens -6. Client uses the access token as a Bearer token on `/mcp` or `/api/v1/` endpoints +6. Client uses the access token as a Bearer token on `/mcp` This is all handled automatically by MCP-compatible clients — you just provide your LightCMS URL and approve the connection. ## REST API -LightCMS provides a full REST API at `/api/v1/` authenticated with API keys or OAuth tokens. All endpoints enforce RBAC — the permissions of the authenticated user (or key owner) determine what's allowed. +LightCMS provides a full REST API at `/api/v1/` authenticated with API keys. All endpoints enforce RBAC — the permissions of the key's owner, limited by the key's access, determine what's allowed. (OAuth access tokens are issued for the MCP endpoint and are not accepted here.) ### Authentication -Include an API key or OAuth access token in the `Authorization` header: +Include an API key in the `Authorization` header: ```bash -# With API key curl -H "Authorization: Bearer lc_your_key_here" http://localhost:8082/api/v1/content - -# With OAuth token -curl -H "Authorization: Bearer " http://localhost:8082/api/v1/content ``` +A key set to **Sandbox** access (the default for keys created in the admin UI) can read the site and change only forks it creates: every other write is refused with `403`. `GET/POST /api/v1/sandbox` and `POST /api/v1/sandbox/end` open and close a sandbox fork for the key. + ### Endpoints | Resource | Endpoints | @@ -986,9 +988,11 @@ Best for sandboxed desktop apps that can't run local binaries. The HTTP MCP endp 1. The client discovers your LightCMS instance via well-known endpoints 2. It registers as an OAuth client (one-time, automatic) -3. You authorize the client by entering your admin password in the browser +3. You sign in in the browser and choose its access: **Sandbox** (default) or **Full** 4. The client receives short-lived access tokens and refreshes them automatically +The connection acts as you, with your role, limited by the access you chose. See and change it, or disconnect it, at `/cm/connected-apps`. + **To connect from a remote MCP client**, just provide your LightCMS URL (e.g., `https://yoursite.example.com`). The client handles the rest using standard OAuth 2.1 discovery. **Discovery endpoints:** @@ -1006,7 +1010,17 @@ The MCP HTTP endpoint accepts both authentication methods: - **API keys** (`lc_` prefix) — long-lived, created in admin panel - **OAuth 2.1 tokens** — short-lived, obtained through the authorization flow -Both methods enforce RBAC based on the authenticated user's role. +Both act as a person (the key's owner, or whoever approved the connection) and enforce that person's role, limited by the key's or connection's access. Each MCP session is bound to the credential that opened it, and its tools call the REST API in-process as that caller. + +### Agent access: Sandbox, Full, and merging (v7.5) + +| Setting | What it allows | +|---------|----------------| +| **Sandbox** | Read the site; create forks and change only the forks this key or connection created; upload new images, PDFs, fonts and text files (nothing executable, nothing replaced). Everything else is refused by the server, whichever tool sends it. | +| **Full** | Anything the owner's role allows. `start_agent_sandbox` still works as an opt-in safety net: while it is open the server holds the key or connection to its fork. | +| **Can merge its own forks** | Off by default; only an admin can turn it on, for an account that can merge. Lets `merge_fork` merge forks this key or connection created, after reviewing them with `get_fork_diff`. Without it, a person merges at `/cm/forks/{id}`. | + +Every merge names the review it was approved from: `get_fork_diff` returns a `digest`, and `merge_fork` refuses if the fork or a live page it changes was edited since. Merges write a version for each page they change, so `rollback_agent_session` undoes them. ### Available Tools (130 total) + 3 Prompt Resources diff --git a/build.json b/build.json index 0504afb..57be340 100644 --- a/build.json +++ b/build.json @@ -1 +1 @@ -{"version":"7.4.6"} +{"version":"7.5.0"} \ No newline at end of file diff --git a/internal/apiclient/client.go b/internal/apiclient/client.go index 6d2816c..3c2d8aa 100644 --- a/internal/apiclient/client.go +++ b/internal/apiclient/client.go @@ -982,12 +982,14 @@ func (c *Client) RemoveForkPage(ctx context.Context, forkID, pageID string) erro return c.do(ctx, "DELETE", "/forks/"+forkID+"/pages/"+pageID, nil, nil) } -// MergeFork merges all fork pages into live content. With publishNew, pages -// the merge creates are also published (held pages stay drafts). -func (c *Client) MergeFork(ctx context.Context, forkID string, publishNew bool) (*ForkMergeResult, error) { - var body interface{} +// MergeFork merges all fork pages into live content, exactly as reviewed: +// digest is the one GetForkDiff returned, and the merge is refused if the fork +// or a page it changes was edited since. With publishNew, pages the merge +// creates are also published (held pages stay drafts). +func (c *Client) MergeFork(ctx context.Context, forkID string, publishNew bool, digest string) (*ForkMergeResult, error) { + body := map[string]interface{}{"digest": digest} if publishNew { - body = map[string]bool{"publish_new": true} + body["publish_new"] = true } var result ForkMergeResult if err := c.do(ctx, "POST", "/forks/"+forkID+"/merge", body, &result); err != nil { diff --git a/internal/apiclient/client_coverage_test.go b/internal/apiclient/client_coverage_test.go index a9872ce..afb918e 100644 --- a/internal/apiclient/client_coverage_test.go +++ b/internal/apiclient/client_coverage_test.go @@ -85,8 +85,8 @@ func TestClientWrappers(t *testing.T) { "ForkPage": func(c *Client) error { _, err := c.ForkPage(ctx, "f", "c", "/p"); return err }, "ListForkPages": func(c *Client) error { _, err := c.ListForkPages(ctx, "f"); return err }, "RemoveForkPage": func(c *Client) error { return c.RemoveForkPage(ctx, "f", "p") }, - "MergeFork": func(c *Client) error { _, err := c.MergeFork(ctx, "f", false); return err }, - "MergeForkPublishNew": func(c *Client) error { _, err := c.MergeFork(ctx, "f", true); return err }, + "MergeFork": func(c *Client) error { _, err := c.MergeFork(ctx, "f", false, "d"); return err }, + "MergeForkPublishNew": func(c *Client) error { _, err := c.MergeFork(ctx, "f", true, "d"); return err }, "PurgeForkCopies": func(c *Client) error { _, err := c.PurgeForkCopies(ctx, "f", false); return err }, "PurgeForkCopiesDry": func(c *Client) error { _, err := c.PurgeForkCopies(ctx, "f", true); return err }, "SearchContentForks": func(c *Client) error { _, err := c.SearchContent(ctx, "q", "", false, true); return err }, diff --git a/internal/apiclient/types.go b/internal/apiclient/types.go index 35fe489..637f146 100644 --- a/internal/apiclient/types.go +++ b/internal/apiclient/types.go @@ -55,6 +55,7 @@ type ForkPageDiff struct { type ForkDiff struct { ForkID string `json:"fork_id"` Pages []ForkPageDiff `json:"pages"` + Digest string `json:"digest,omitempty"` // merge_fork needs it: it pins the merge to this review Status string `json:"status,omitempty"` // Set on merged forks: their copies are gone, so Pages is empty. MergedCreated int `json:"merged_created,omitempty"` diff --git a/internal/auth/permissions.go b/internal/auth/permissions.go index 3858c50..7ecdbda 100644 --- a/internal/auth/permissions.go +++ b/internal/auth/permissions.go @@ -174,13 +174,18 @@ var sandboxAllowedPerms = map[string]bool{ // UserHasPermission checks a permission against the user's role, then // narrows by the API key's scopes (when set) and sandbox-only restriction. func UserHasPermission(u *SessionUser, perm string) bool { - if u == nil { - return false - } - if !HasPermission(u.Role, perm) { + if u.Sandboxed() && !sandboxAllowedPerms[perm] { return false } - if u.Sandboxed() && !sandboxAllowedPerms[perm] { + return RoleAndScopesAllow(u, perm) +} + +// RoleAndScopesAllow checks a permission against the user's role and the +// API key's scopes, leaving the sandbox out. It is for the one step a +// separate grant opens to a sandboxed caller: merging a fork it created +// when CanMergeOwnForks is set. +func RoleAndScopesAllow(u *SessionUser, perm string) bool { + if u == nil || !HasPermission(u.Role, perm) { return false } if len(u.Scopes) > 0 { diff --git a/internal/handlers/admin_csrf_ui_guard_test.go b/internal/handlers/admin_csrf_ui_guard_test.go index a00f0e9..8b6b5a2 100644 --- a/internal/handlers/admin_csrf_ui_guard_test.go +++ b/internal/handlers/admin_csrf_ui_guard_test.go @@ -249,7 +249,8 @@ func TestAdminLayout_ConfirmDeleteAndRevertAreTextSafe(t *testing.T) { } // Delete in the admin is a soft delete with Restore: no dialog may call it -// irreversible. (Merging a fork really cannot be undone and still says so.) +// irreversible. Since 7.5 a merge keeps each page's previous version, so its +// confirmation says that instead of calling it irreversible. func TestAdminTemplates_DeleteWordingMatchesSoftDelete(t *testing.T) { undone := regexp.MustCompile(`(?i)cannot be undone|can't be undone|permanently delet`) for _, name := range sortedAdminTemplateNames() { @@ -266,7 +267,8 @@ func TestAdminTemplates_DeleteWordingMatchesSoftDelete(t *testing.T) { if !strings.Contains(form, "can be restored") { t.Error("the Delete Page confirmation no longer says the page can be restored") } - if !strings.Contains(adminTemplates["fork_detail"], "cannot be undone") { - t.Error("the fork merge confirmation lost its warning; a merge really cannot be undone") + merge := adminTemplates["fork_detail"] + if strings.Contains(merge, "cannot be undone") || !strings.Contains(merge, "previous version stays in its history") { + t.Error("the fork merge confirmation should say each page's previous version is kept, not that a merge cannot be undone") } } diff --git a/internal/handlers/admin_templates.go b/internal/handlers/admin_templates.go index eef30eb..1190276 100644 --- a/internal/handlers/admin_templates.go +++ b/internal/handlers/admin_templates.go @@ -7919,14 +7919,17 @@ async function doSearch(q) { {{if eq .Fork.Status "active"}} 👁 Start Preview {{if .CanMerge}} -
+ {{if .ReviewDigest}} + {{.CSRFField}} +
+ {{end}}
{{.CSRFField}} @@ -7973,6 +7976,55 @@ async function doSearch(q) { {{end}} + {{if .Fork.SubmittedAt}} +
Submitted for review by {{.Fork.SubmittedByEmail}} on {{.Fork.SubmittedAt.Format "Jan 2, 2006 15:04"}}. The agent that made it can't change it any more.
+ {{end}} + {{if .ReviewError}}
{{.ReviewError}}
{{end}} + {{if .Review}} + +

Everything a merge would change on the live site, field by field. Merging applies exactly this: if the fork or one of these live pages changes before you merge, the merge is refused and you review again.

+ + {{range .Review}} +
+

{{.Path}} + {{if eq .Status "added"}}new page{{else}}changed{{end}} + {{if .Conflict}}live page edited since it was forked{{end}} +

+ {{if .Fields}} +
+ + {{if ne .Status "added"}}{{end}} + + {{range .Fields}} + + + {{if not .IsNew}} + + {{end}} + + + {{end}} + +
FieldLive nowAfter merge
{{.Name}}{{if .LiveLong}}
{{.LivePreview}} Show all
{{.Live}}
{{else}}
{{.Live}}
{{end}}
{{if .ForkLong}}
{{.ForkPreview}} Show all
{{.Fork}}
{{else}}
{{.Fork}}
{{end}}
+
+ {{else}} +

Nothing differs from the live page.

+ {{end}} +
+ {{end}} + {{end}} +