diff --git a/.changeset/access-context-threading.md b/.changeset/access-context-threading.md new file mode 100644 index 00000000..b5064b83 --- /dev/null +++ b/.changeset/access-context-threading.md @@ -0,0 +1,30 @@ +--- +'@tanstack/cms-core': minor +'@tanstack/cms-api': minor +'@tanstack/cms-client': minor +'@tanstack/search-cms': minor +--- + +Read through an explicit access context. An access context says who reads (the actor and permissions) and in which mode (`live`, `preview` or `edit`). + +- `@tanstack/cms-core/server` exports: + - the `AccessContext` type and its builders: `publicContext()`, `accessContext({ session, mode, agent })`, `systemContext(reason)` (the reason is required), `previewContext`, `previewTokenContext` and `withMode`; + - the checks `canReadCollection`, `canReadDocument`, `assertReadable` and `redactFor`; + - the bound handle `cmsAs(cms, ctx)`, which accepts a `createCms` instance or the `defineCms` result; + - the `…As(ctx, …)` form of every read verb. +- `postRead` hooks receive `access`. +- Event handlers receive `access`, a system context naming the handler, and the outbox `cms` client reads as it (`cms.access`). +- `runOp(name, input, actor, access)` and `cmsTools(actor, { access })` run as an explicit context. A tool call's runtime context under `CMS_ACCESS_KEY` takes precedence. +- `@tanstack/cms-api`: + - builds one context per request with `requestAccessContext(request)`, and the `x-cms-read-mode` header narrows it; + - hands it to operations as `CmsOpContext.access`; + - runs WebMCP and `/api/mcp` as an agent context per request. + - `@tanstack/cms-api/start` builds the context from `getRequest()` and exports `getCmsAccessContext()` for app server functions. +- `@tanstack/cms-client`: `createCmsClient({ mode })` sends the read mode on every call and keys its cache by it. +- `@tanstack/search-cms`: `createCmsSearch({ access })` searches as the context (default `publicContext()`). + +The old forms keep working: the `session`, `publishedOnly` and `publicRead` read options, `runWithSession`, and `createCmsSearch({ session, publishedOnly, publicRead })`. They are deprecated for reads. + +Breaking: `CmsOpContext` has a required `access` field. Code that builds a `CmsOpContext` by hand, for example to call an op's `run` in a test, must add `access: accessContext({ session, mode: 'edit' })`. The interface functions (`executeInterface`, `submitInterface`, …) still take `{ session, actor }`. + +Behaviour change: `getPublicDocument` now skips a draft the caller can't read and returns the next match. Previously that draft shadowed the match and the call returned `null`. diff --git a/.claude/skills/search-integration/SKILL.md b/.claude/skills/search-integration/SKILL.md index 7df3b4c3..a078d2dd 100644 --- a/.claude/skills/search-integration/SKILL.md +++ b/.claude/skills/search-integration/SKILL.md @@ -24,8 +24,10 @@ objects; do not invent `text()`/`number()` builders. Declare and arbitrary JSON need a custom adapter/derived scalar field. Non-facet registry fields can support text filters, such as `notes`. -Register the collection with `defineCms`. On the server, resolve the current -session and create `createCmsSearch({ collection, session })` per request. +Register the collection with `defineCms`. On the server, build the caller's +access context and create `createCmsSearch({ collection, access })` per request +(`publicContext()` for anonymous search, which is the default, or +`accessContext({ session, mode: 'edit' })` for editors). Keep publication, tenant, and authorization restrictions inside the adapter; client filters are user selections and will be pruned for refinement counts. Do not bypass the CMS read path to compute restricted facet counts. diff --git a/app/base/src/schema-registry.server.ts b/app/base/src/schema-registry.server.ts index 730d76da..2b9e1597 100644 --- a/app/base/src/schema-registry.server.ts +++ b/app/base/src/schema-registry.server.ts @@ -476,7 +476,9 @@ export async function discardSchemaDraft( return { ok: true } }) } -export function publishedSchemas(ctx: CmsOpContext): PublishedSchemas { +export function publishedSchemas( + ctx: Pick, +): PublishedSchemas { const config = getCmsConfig() const registry = registryContext.getStore()! return { diff --git a/app/base/tests/base.test.ts b/app/base/tests/base.test.ts index 2b13c8ec..a26dcf77 100644 --- a/app/base/tests/base.test.ts +++ b/app/base/tests/base.test.ts @@ -5,6 +5,7 @@ import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { defineCms, normalizeSession } from '@tanstack/cms-core' import { + accessContext, approve, closeStore, createApiKey, @@ -47,10 +48,14 @@ import { } from '../src/operations.server' let dir: string -const context = (role = 'admin'): CmsOpContext => ({ - actor: 'human', - session: normalizeSession({ id: role, role, name: role }), -}) +const context = (role = 'admin'): CmsOpContext => { + const session = normalizeSession({ id: role, role, name: role }) + return { + actor: 'human', + session, + access: accessContext({ session, mode: 'edit' }), + } +} const owner = { email: 'owner@example.com', name: 'Owner', diff --git a/app/base/tests/schema-registry.test.ts b/app/base/tests/schema-registry.test.ts index 5836fee9..de6636d1 100644 --- a/app/base/tests/schema-registry.test.ts +++ b/app/base/tests/schema-registry.test.ts @@ -5,6 +5,7 @@ import { beforeEach, afterEach, describe, it, expect } from 'vitest' import { defineCms, getCmsConfig, normalizeSession } from '@tanstack/cms-core' import type { CmsOpContext, Doc } from '@tanstack/cms-core' import { + accessContext, closeStore, getStorage, commitDocument, @@ -32,10 +33,14 @@ import { } from '../src/schema-registry.server' let dir: string -const ctx = (role = 'admin'): CmsOpContext => ({ - actor: role, - session: normalizeSession({ id: `test-${role}`, role }), -}) +const ctx = (role = 'admin'): CmsOpContext => { + const session = normalizeSession({ id: `test-${role}`, role }) + return { + actor: role, + session, + access: accessContext({ session, mode: 'edit' }), + } +} const definition = (): CollectionDefinition => ({ name: 'customers', label: 'Customers', diff --git a/app/base/tests/worker.test.ts b/app/base/tests/worker.test.ts index 5d57437d..6722d5dc 100644 --- a/app/base/tests/worker.test.ts +++ b/app/base/tests/worker.test.ts @@ -8,6 +8,7 @@ import { interfaceScheduleHandlers, } from '@tanstack/cms-core' import { + accessContext, closeStore, commitDocument, submitInterface, @@ -64,7 +65,12 @@ describe('Base background interface worker', () => { password: 'worker-owner-password', }) ).user - const ctx = { actor: owner.id, session: normalizeSession(owner) } + const session = normalizeSession(owner) + const ctx = { + actor: owner.id, + session, + access: accessContext({ session, mode: 'edit' }), + } const draft = await saveSchemaDraft( { definition: { diff --git a/app/prm/bakeoff/latest.json b/app/prm/bakeoff/latest.json index 72a26cc4..98185a40 100644 --- a/app/prm/bakeoff/latest.json +++ b/app/prm/bakeoff/latest.json @@ -1,5 +1,5 @@ { - "ranAt": "2026-11-03T23:46:43.841Z", + "ranAt": "2026-11-06T03:03:19.126Z", "mode": "fixture", "winner": "exa", "summary": { diff --git a/docs/api/cms-api.md b/docs/api/cms-api.md index 666a92df..b8642785 100644 --- a/docs/api/cms-api.md +++ b/docs/api/cms-api.md @@ -23,8 +23,8 @@ pnpm add @tanstack/cms-api @tanstack/cms-core | Import | Contents | | --- | --- | -| `@tanstack/cms-api` | `ops`, `allOps`, `findOp`, `invokeOp`, `invokeAnyOp`, operation types, media server functions, `cmsMcp`, AI helpers, the HTTP handlers, and the OpenAPI builder. | -| [`@tanstack/cms-api/start`](#tanstackcms-apistart) | One TanStack Start server function per operation, `callOp`, plus the media server functions. | +| `@tanstack/cms-api` | `ops`, `allOps`, `findOp`, `invokeOp`, `invokeAnyOp`, `requestAccessContext`, operation types, media server functions, `cmsMcp`, AI helpers, the HTTP handlers, and the OpenAPI builder. | +| [`@tanstack/cms-api/start`](#tanstackcms-apistart) | One TanStack Start server function per operation, `callOp`, `getCmsAccessContext`, plus the media server functions. | | [`@tanstack/cms-api/http`](#tanstackcms-apihttp) | `createCmsApiHandler()`, the individual `handle*` functions, and `requestIdFor`, with no TanStack Start dependency. | | [`@tanstack/cms-api/markdown`](#tanstackcms-apimarkdown) | `loadMarkdownDir()` and the frontmatter parser, for markdown files as a data source. No TanStack Start dependency. | @@ -73,7 +73,7 @@ interface ResolvedOp extends CmsOperation( name: N, input: z.output<(typeof ops)[N]['input']>, - ctx?: CmsContext, // { request?: Request; actor?: string } + ctx?: CmsContext, // { request?: Request; actor?: string; access?: AccessContext } ): Promise> function invokeAnyOp( @@ -86,9 +86,9 @@ function invokeAnyOp( Runs an operation the way every transport does: 1. rejects cross-site requests that rely on cookies (`assertTrustedOrigin`), -2. resolves the session from `ctx.request`, +2. takes the caller's access context from `ctx.access`, or builds it from `ctx.request` with `requestAccessContext`, 3. enforces the operation's `access` (and the `ai` rate limit for `agent.use` operations), -4. runs it with the session bound, so nested agent tools see the same caller. +4. runs it with that context (`CmsOpContext.access`), so the operation and nested agent tools read as the same caller. `invokeOp` is typed to the built-in `ops` table (`input` must already match the operation's schema; parse it with `ops[name].input` first when it comes from outside). `invokeAnyOp` looks up `name` in `allOps()` (built-in ops, agent tools, and app-defined `defineOp()` operations), validates `input` against the op's Zod schema, and runs it. @@ -102,6 +102,17 @@ export async function publishedPosts(request: Request) { } ``` +### `requestAccessContext(request?, options?)` + +```ts +function requestAccessContext(request?: Request, options?: { mode?: ReadMode; defaultMode?: ReadMode }): Promise +const READ_MODE_HEADER = 'x-cms-read-mode' +``` + +Builds the access context for one request: `accessContext({ session: await resolveSession(request), mode })` from [`@tanstack/cms-core/server`](./cms-core-server#access-contexts). `mode` is `options.mode`, else the `x-cms-read-mode` header, else `options.defaultMode` (`edit`). Every HTTP handler builds its context this way. Use it in hosts other than TanStack Start, and pass the result as `ctx.access` or to `cmsAs`. An `edit` request context is the widest the caller may read. The public operations (`getPublicDocument`, `listPublishedDocuments`) serve drafts only to callers who may read them, and a `live` header narrows them to published documents. + +`agentActorName(surface, session?)` names the agent actor for a surface (`mcp`, `webmcp`, `content-agent`). It appends the session's `x-cms-agent` name, as in `mcp:claude`. + ### `resolveAuthSession(request?)` ```ts @@ -120,15 +131,15 @@ The caller's session plus the available AI features. This is the `getAuthSession | `CmsOperation` | A built-in operation definition. | | `ResolvedOp` | Any resolved operation from `allOps()` (`source: 'builtin' \| 'agent' \| 'app'`). | | `OpAccess` | `'public' \| Permission`. | -| `CmsContext` | `{ request?: Request; actor?: string }`, the transport context. | -| `CmsOpContext` | `CmsContext & { session: CmsSession; actor: string }`, what `run` receives. | +| `CmsContext` | `{ request?: Request; actor?: string; access?: AccessContext }`, the transport context. | +| `CmsOpContext` | `CmsContext & { session: CmsSession; actor: string; access: AccessContext }`, what `run` receives. Read through `access` (`cmsAs`, `queryDocumentsAs`, `assertReadable`). | | `MediaItem` | Re-exported from `@tanstack/cms-core/server`. | --- ## `@tanstack/cms-api/start` -One `createServerFn` per operation, with the same name, validating input with the operation's schema and running it through `invokeOp` with the current request. Plus `callOp({ data: { name, input } })` to run any operation in `allOps()` (including agent tools and app-defined `defineOp()` operations). They run in-process: no HTTP hop. `@tanstack/cms-ui-react` uses them for everything. +One `createServerFn` per operation, with the same name, validating input with the operation's schema and running it through `invokeOp` with the current request's access context (`requestAccessContext(getRequest())`). Plus `callOp({ data: { name, input } })` to run any operation in `allOps()` (including agent tools and app-defined `defineOp()` operations). They run in-process: no HTTP hop. `@tanstack/cms-ui-react` uses them for everything. Call them with `{ data }`: @@ -186,6 +197,14 @@ function Blog() { Inputs and results match the [operations table](./routes-and-endpoints#operations). `/start` also re-exports the media server functions below and the operation types. +### `getCmsAccessContext(options?)` + +```ts +function getCmsAccessContext(options?: { mode?: ReadMode }): Promise // server-only +``` + +The current Start request's access context, for your own server functions: `cmsAs(cms, await getCmsAccessContext())`. It reads as the request's session, in `options.mode`, else the `x-cms-read-mode` header, else `live` (published only). Pass `{ mode: 'edit' }` to show signed-in editors the drafts they may read. See [Building Pages](../schema/building-pages#2-your-own-server-function-over-the-store). + ### Media server functions Exported from both `@tanstack/cms-api` and `@tanstack/cms-api/start`. @@ -381,7 +400,7 @@ The frontmatter parser handles a YAML subset, one `key: value` per line: strings const cmsMcp: ReturnType // from @tanstack/ai-mcp/server ``` -The CMS as an MCP server named `tanstack-cms`, exposing the agent tools (`cmsTools('mcp')`). `handleMcpApi` authorizes the request with `verifyMcpAccess` and then runs `cmsMcp.fetch(request)` with the caller's session bound. Mount `handleMcpApi`, not `cmsMcp` directly, so access checks and rate limits apply. See [HTTP MCP Server](../mcp/http-mcp-server). +The CMS as an MCP server named `tanstack-cms`, exposing the agent tools (`cmsTools('mcp')`). `handleMcpApi` authorizes the request with `verifyMcpAccess` and then runs `cmsMcp.fetch(request, access)` with the caller's agent context (`accessContext({ session, agent: agentActorName('mcp', session), mode: 'edit' })`). The tools are listed for that context, and every tool call reads and writes as it. Mount `handleMcpApi`, not `cmsMcp` directly, so access checks and rate limits apply. See [HTTP MCP Server](../mcp/http-mcp-server). --- diff --git a/docs/api/cms-client.md b/docs/api/cms-client.md index 80725fda..6942eacb 100644 --- a/docs/api/cms-client.md +++ b/docs/api/cms-client.md @@ -37,9 +37,13 @@ interface CmsClientOptions { baseUrl: string // origin of the API handler, plus any mount prefix; a trailing slash is ignored fetch?: typeof fetch // default: global fetch getAuthHeader?: () => string | undefined | Promise // called per request + cacheScope?: string // see "Cache scope" under @tanstack/cms-client/db + mode?: 'live' | 'preview' | 'edit' // read mode sent as `x-cms-read-mode` } interface CmsClient { + readonly cacheScope?: string + readonly mode?: 'live' | 'preview' | 'edit' op(name: N, input: OpInput): Promise> call(name: string, input?: unknown): Promise collection(name: C): CmsCollectionClient> @@ -59,6 +63,8 @@ const { items, total } = await cms.collection('post').published({ limit: 10 }) console.log(`${items.length} of ${total} posts`) ``` +`mode` asks every call for a read mode. The client sends it as the `x-cms-read-mode` header (`CMS_READ_MODE_HEADER`), and the server builds the caller's access context in that mode. `live` reads published documents only, even for an editor's key. `edit` reads the working copy, meaning the drafts the caller may read. Without `mode` the server reads in `edit`, so a CMS reader's `published()` includes drafts. A client with a `mode` appends it to its cache scope, so live and edit reads never share a query key. + ### `op(name, input)` and `call(name, input?)` `op(name, input)` calls any built-in operation by name: a `POST` with a JSON body to `/api/cms/v1/ops/`, resolving to the `result`. Input and output are typed per operation. `call(name, input?)` hits the same endpoint for untyped or dynamic operations — including agent tools (`list_documents`, `search_documents`, …) and app-defined operations registered with `defineCms({ ops })`. The list of operations and their access levels is in [Routes & HTTP Endpoints](./routes-and-endpoints#operations). diff --git a/docs/api/cms-core-server.md b/docs/api/cms-core-server.md index 008f7074..f46b1509 100644 --- a/docs/api/cms-core-server.md +++ b/docs/api/cms-core-server.md @@ -2,11 +2,14 @@ title: "@tanstack/cms-core/server" id: api-cms-core-server order: 2 -description: "API reference for the server-only exports of @tanstack/cms-core/server: document queries, the draft and review workflow, revisions and scheduling, media, sitemap and redirects, webhooks, export/import/backup, auth guards, API keys, and security helpers." +description: "API reference for the server-only exports of @tanstack/cms-core/server: access contexts and cmsAs, document queries, the draft and review workflow, revisions and scheduling, media, sitemap and redirects, webhooks, export/import/backup, auth guards, API keys, and security helpers." keywords: - tanstack cms - api reference - "@tanstack/cms-core/server" + - access context + - cmsAs + - systemContext - queryDocuments - commitDocument - stageWrite @@ -21,7 +24,102 @@ keywords: Every function reads the config registered by `defineCms()`, so import your `cms.config.ts` first (the router does this in a Start app; the `tanstack-cms` CLI does it for scripts). All store functions are async. The HTTP and server-function operations built on top of these live in [`@tanstack/cms-api`](./cms-api). -The store functions do **not** check permissions on their own. Transports resolve the caller's session and enforce access with the [auth guards](#auth-guards-and-api-keys) before calling them; do the same when you expose them from your own server functions. +Read content through an [access context](#access-contexts): `cmsAs(cms, ctx)` returns the read functions bound to who is reading and in which mode, and returns only what that reader may see. The plain store functions below don't know who is asking, so they don't check permissions. Transports enforce access with the [auth guards](#auth-guards-and-api-keys) before writing, and you should do the same when you expose writes from your own server functions. + +--- + +## Access contexts + +An `AccessContext` says who reads (its actor and permissions) and how (its mode). Every read verb has a context form, so its visibility, redaction and read hooks follow from the context alone: + +```ts +type ReadMode = 'live' | 'preview' | 'edit' + +interface AccessContext { + readonly actor: AccessActor + readonly permissions: ReadonlyArray + readonly mode: ReadMode + readonly session?: CmsSession // absent for a system context + readonly publicRead: boolean // published documents are readable whatever the collection rule + readonly scope?: { collection: string; docId: string } // a preview token's one document +} + +type AccessActor = + | { kind: 'public' } + | { kind: 'user'; id: string | null; role: string | null } + | { kind: 'agent'; agent: string; id: string | null; role: string | null } + | { kind: 'system' | 'scheduler' | 'import'; reason: string } + | { kind: 'preview'; tokenId: string } +``` + +The modes are: + +- `live` reads published documents only. +- `edit` reads the working copy: drafts and staged changes the actor may read. +- `preview` reads one document's working copy through a preview token. + +Contexts are frozen and come from the builders. A copied object is not a context. + +| Builder | Reads as | +| --- | --- | +| `publicContext()` | An anonymous visitor, `live`. | +| `accessContext({ session, mode?, agent?, publicRead? })` | The session's user (`mode` default `live`). With `agent` or `session.agent`, the actor is that agent acting for the user. | +| `systemContext(reason, { mode?, actor? })` | A trusted job that bypasses every access rule (`mode` default `edit`). `reason` is required, so each bypass says why it exists. `actor` is `'system'` (default), `'scheduler'` or `'import'`. | +| `previewContext(record)` / `previewTokenContext(token, collection, docId)` | A verified preview token, scoped to its one document. `previewTokenContext` returns `null` for an invalid token. | +| `withMode(ctx, mode)` | `ctx` in another mode. | + +`isAccessContext(value)` tells a built context from a look-alike. `parseReadMode(value)` parses a mode from a header or query string: it returns `undefined` when the value is empty and throws `BAD_REQUEST` when it is unknown. + +### `cmsAs(cms, ctx)` + +```ts +function cmsAs(cms: Cms | CmsConfig, ctx: AccessContext): CmsReads +``` + +The read verbs bound to `ctx`, scoped to `cms` (a `createCms` instance or the config `defineCms` returned): `queryDocuments`, `groupDocuments`, `queryDocumentSummaries`, `listDocuments`, `readDocument`, `readDocumentWithPending`, `readSingleton`, `readDocumentBySlug`, `findDocumentBySlug`, `populateRelations`, `findReferences`, `listTranslations` and `listRevisions`, plus `context`. They take the same arguments as the functions below, without the `session`, `publishedOnly` and `publicRead` options. Documents the context can't read come back as missing, and fields it can't read are removed. `postRead` hooks receive the context as `access`. + +```ts validate=type +import { defineCms } from '@tanstack/cms-core' +import { + accessContext, + cmsAs, + publicContext, + resolveSession, + systemContext, +} from '@tanstack/cms-core/server' + +const cms = defineCms({ collections: [], blockTypes: [] }) + +export async function homePage() { + return cmsAs(cms, publicContext()).queryDocuments({ collection: 'post', limit: 10 }) +} + +export async function editorDrafts(request: Request) { + const session = await resolveSession(request) + const db = cmsAs(cms, accessContext({ session, mode: 'edit' })) + return db.queryDocuments({ collection: 'post', where: { published: false } }) +} + +export async function sitemapIds() { + const db = cmsAs(cms, systemContext('sitemap build', { mode: 'live' })) + return (await db.listDocuments('page')).map((d) => d.id) +} +``` + +Each verb also has an argument form taking the context first: `queryDocumentsAs(ctx, options)`, `readDocumentAs(ctx, collection, id)`, `readDocumentBySlugAs`, `findDocumentBySlugAs`, `readSingletonAs`, `readDocumentWithPendingAs`, `queryDocumentSummariesAs`, `listDocumentsAs`, `groupDocumentsAs`, `populateRelationsAs`, `findReferencesAs`, `listTranslationsAs` and `listRevisionsAs`. These read against the registered CMS. + +### Checks + +```ts +function canReadCollection(ctx: AccessContext, collection: string): boolean +function canReadDocument(ctx: AccessContext, collection: string, row: { id: string; published: boolean; doc: Doc | null | undefined }): boolean +function assertReadable(ctx: AccessContext, collection: string, row?: { id: string; doc: Doc | null | undefined; published?: boolean }): void // UNAUTHORIZED / FORBIDDEN +function redactFor(ctx: AccessContext, collection: string, doc: T): T +``` + +Use these for reads the verbs don't cover. A system context passes every check. + +In a host, build one context per request. `@tanstack/cms-api` provides `requestAccessContext(request)` for any host, and `getCmsAccessContext()` in `@tanstack/cms-api/start`. Hooks and event handlers receive the context they run with. The older form, binding a session with `runWithSession` and calling the plain functions, still works but is deprecated for reads. --- @@ -514,7 +612,7 @@ For **durable, retried** delivery to app-defined handlers (as opposed to this be ### Async events (dispatcher) -Handlers are declared with `defineEventHandler` ([`@tanstack/cms-core`](./cms-core#events)) and delivered from a transactional outbox: at-least-once, retried with backoff, dead-lettered after `maxAttempts`, and auto-disabled after repeated failures. See [Events & Hooks](../architecture/events-and-hooks) for the full model. +Handlers are declared with `defineEventHandler` ([`@tanstack/cms-core`](./cms-core#events)) and receive `{ event, cms, access }`. `access` is a system context naming the handler (actor `scheduler` for `cron` handlers), and `cms` reads and writes as it. Handlers are delivered from a transactional outbox: at-least-once, retried with backoff, dead-lettered after `maxAttempts`, and auto-disabled after repeated failures. See [Events & Hooks](../architecture/events-and-hooks) for the full model. ```ts function runEventDispatch(options?: { now?: string; limit?: number }): Promise @@ -550,21 +648,21 @@ Drains the outbox once — the cron tick, then claims and delivers due events in ## Agent operations -### `runOp(name, input, actor)` +### `runOp(name, input, actor, access?)` ```ts -function runOp(name: string, input: any, actor: string): Promise +function runOp(name: string, input: any, actor: string, access?: AccessContext): Promise ``` -Runs one of the agent tools from `opSchemas` (`list_documents`, `create_document`, …). Every agent surface funnels through it: the content agent, the MCP server, and the WebMCP endpoint. Write tools always stage their changes for review, recorded with `actor`. When a session is bound with `runWithSession`, the tool's permission and collection access are enforced and field access rules apply. +Runs one of the agent tools from `opSchemas` (`list_documents`, `create_document`, …) as `access`, usually the agent's context: `accessContext({ session, agent: 'content-agent', mode: 'edit' })`. Every agent surface funnels through it: the content agent, the MCP server, and the WebMCP endpoint. Write tools always stage their changes for review, recorded with `actor`. With a session-bearing context, the tool's permission and collection access are enforced and field access rules apply. A system context bypasses them, and a preview context is refused. Without `access`, the session bound by `runWithSession` is used. That fallback is deprecated. ### `cmsTools(actor)` ```ts -function cmsTools(actor: string, options?: { authorizedOnly?: boolean; onResult?: (result: CmsToolResult) => void }): Promise> // @tanstack/ai server tools, one per agent op +function cmsTools(actor: string, options?: { access?: AccessContext; authorizedOnly?: boolean; readOnly?: boolean; include?: (op: CmsOpDefinition) => boolean; onResult?: (result: CmsToolResult) => void }): Promise> // @tanstack/ai server tools, one per agent op ``` -The agent tools as `@tanstack/ai` server tools, for your own `chat()` loops. `@tanstack/cms-api` uses them for content chat and MCP. `authorizedOnly` filters advertised tools against the bound session; execution always rechecks access. `onResult` receives JSON-compatible receipts (`name`, `kind`, `status`, `result`). With an observer, tool errors become structured results so the model can correct its request. Observer failures cannot break a committed tool write. Without these options, the existing MCP catalog and error behavior stay intact. +The agent tools as `@tanstack/ai` server tools, for your own `chat()` loops. `@tanstack/cms-api` uses them for content chat and MCP. Every call runs `runOp` as the agent's context. A host that serves one tool set to many callers passes each call's context in the tool's runtime context, under `CMS_ACCESS_KEY`; the MCP server does this with `handle(request, { context: { [CMS_ACCESS_KEY]: access } })`. Otherwise `options.access` applies, then the session bound by `runWithSession`. `authorizedOnly` filters advertised tools against that context's session; execution always rechecks access. `onResult` receives JSON-compatible receipts (`name`, `kind`, `status`, `result`). With an observer, tool errors become structured results so the model can correct its request. Observer failures cannot break a committed tool write. Without these options, the existing MCP catalog and error behavior stay intact. --- @@ -867,7 +965,7 @@ A request is authenticated, in order, by: a CMS API key (`Authorization: Bearer ```ts function resolveSession(request?: Request, options?: { fresh?: boolean }): Promise // memoized per Request -function runWithSession(session: CmsSession, fn: () => T): T // bind a session for runOp and nested checks +function runWithSession(session: CmsSession, fn: () => T): T // deprecated for reads: pass an access context function currentSession(): CmsSession | undefined function isDevAuth(): boolean // whether an app without `auth` runs as a local admin ``` @@ -894,22 +992,23 @@ Guards throw `CmsError` with `UNAUTHORIZED` for anonymous callers and `FORBIDDEN ```ts validate=type import { - assertCollectionAccess, - queryDocuments, - redactDoc, + accessContext, + assertReadable, + queryDocumentsAs, requirePermission, } from '@tanstack/cms-core/server' export async function listDrafts(request: Request, collection: string) { const session = await requirePermission('content.read', request) - assertCollectionAccess(session, collection, 'read') - const { items } = await queryDocuments({ collection, limit: 50 }) - return items - .filter((i) => !i.published) - .map((i) => ({ id: i.id, doc: redactDoc(collection, i.doc, session) })) + const ctx = accessContext({ session, mode: 'edit' }) + assertReadable(ctx, collection) + const { items } = await queryDocumentsAs(ctx, { collection, limit: 50 }) + return items.filter((i) => !i.published).map((i) => ({ id: i.id, doc: i.doc })) } ``` +The context read returns only documents the session may read, with unreadable fields already removed. + In a TanStack Start server function, get the request with `getRequest()` from `@tanstack/react-start/server`. ### Field and collection access helpers diff --git a/docs/architecture/events-and-hooks.md b/docs/architecture/events-and-hooks.md index 1fc18786..f58811cd 100644 --- a/docs/architecture/events-and-hooks.md +++ b/docs/architecture/events-and-hooks.md @@ -48,7 +48,8 @@ export const post = defineCollection({ // Before a delete transaction: throw to veto. preDelete: ({ id }) => { /* ...guard... */ }, // After a read, before the response: transform the response only. - postRead: ({ doc }) => doc, + // `access` is the reader's context (actor and mode). + postRead: ({ doc, access }) => doc, }, }) ``` @@ -93,7 +94,7 @@ The legacy alias names `beforeValidate`, `beforeChange`, `beforeDelete`, and `af ## Events: after the game -`defineEventHandler` registers a handler, and `defineCms({ eventHandlers })` installs it. Handlers are delivered **at-least-once** from a durable outbox, so they must be idempotent (check-then-write is the blessed pattern). +`defineEventHandler` registers a handler, and `defineCms({ eventHandlers })` installs it. Handlers are delivered **at-least-once** from a durable outbox, so they must be idempotent (check-then-write is the blessed pattern). `run` receives `{ event, cms, access }`. `access` is a system [access context](../api/cms-core-server#access-contexts) naming the handler (actor `scheduler` for `cron` handlers), and `cms` reads as it (`cms.access`). ```ts import { defineCms, defineEventHandler } from '@tanstack/cms-core' diff --git a/docs/schema/building-pages.md b/docs/schema/building-pages.md index 18970834..5b1a68b7 100644 --- a/docs/schema/building-pages.md +++ b/docs/schema/building-pages.md @@ -2,7 +2,7 @@ title: Building Pages & Custom Routes id: building-pages order: 3 -description: "Render CMS content in TanStack Start: the built-in public routes, loading documents with @tanstack/cms-api/start server functions or @tanstack/cms-core/server queries, adding custom routes next to createRoutes(), overriding or dropping package routes, SEO with cmsHead, and moving the admin under a base path." +description: "Render CMS content in TanStack Start: the built-in public routes, loading documents with @tanstack/cms-api/start server functions or cmsAs(cms, ctx) reads from @tanstack/cms-core/server, adding custom routes next to createRoutes(), overriding or dropping package routes, SEO with cmsHead, and moving the admin under a base path." keywords: - tanstack cms - building pages @@ -16,6 +16,8 @@ keywords: - queryDocuments - readDocumentBySlug - readSingleton + - cmsAs + - access context - admin basePath --- @@ -67,23 +69,21 @@ See [`@tanstack/cms-api`](../api/cms-api#tanstackcms-apistart) for every server ### 2. Your own server function over the store -For filters, relations, singletons, or anything the built-in operations don't cover, wrap the `@tanstack/cms-core/server` queries in your own `createServerFn`. All store functions are async. +For filters, relations, singletons, or anything the built-in operations don't cover, write your own `createServerFn` that reads through `cmsAs(cms, ctx)` from `@tanstack/cms-core/server`. It binds the store's read verbs (`queryDocuments`, `readDocument`, `readDocumentBySlug`, `readSingleton`, `findDocumentBySlug`, `populateRelations`, …) to an **access context**: who is reading, and in which mode. Every read returns only what that context may see. Documents it can't read come back as missing, and fields it can't read are removed. All reads are async. ```ts validate=type import { createServerFn } from '@tanstack/react-start' -import { - queryDocuments, - readDocumentBySlug, - readSingleton, -} from '@tanstack/cms-core/server' +import { getCmsAccessContext } from '@tanstack/cms-api/start' +import { cmsAs, publicContext } from '@tanstack/cms-core/server' +import { cms } from './cms.config' export const getChangelog = createServerFn({ method: 'GET' }) .validator((data: { category?: string; page?: number }) => data) .handler(async ({ data }) => { - const settings = await readSingleton('settings', { publishedOnly: true }) - const releases = await queryDocuments({ + const db = cmsAs(cms, publicContext()) + const settings = await db.readSingleton('settings') + const releases = await db.queryDocuments({ collection: 'post', - publishedOnly: true, where: data.category ? { category: data.category } : undefined, sort: { field: 'publishedDate', dir: 'desc' }, limit: 10, @@ -95,12 +95,20 @@ export const getChangelog = createServerFn({ method: 'GET' }) export const getArticle = createServerFn({ method: 'GET' }) .validator((data: { slug: string }) => data) - .handler(({ data }) => - readDocumentBySlug('post', data.slug, { publishedOnly: true, populate: true }), - ) + .handler(async ({ data }) => { + // The visitor's own session: editors see drafts they may read. + const db = cmsAs(cms, await getCmsAccessContext({ mode: 'edit' })) + return db.readDocumentBySlug('post', data.slug, { populate: true }) + }) ``` -These functions talk to the store directly and do **not** check the caller's session, so pass `publishedOnly: true` for public pages. Use `assertCollectionAccess()` and `redactDoc()` from `@tanstack/cms-core/server` if you expose non-public data. +Pick the context that matches the reader: + +- `publicContext()` is an anonymous visitor. It sees published documents and the fields anyone may read. +- `getCmsAccessContext()` from `@tanstack/cms-api/start` reads as the current request's session. It defaults to `live` (published only), and `{ mode: 'edit' }` adds the drafts that session may read. Outside TanStack Start, build it yourself with `accessContext({ session: await resolveSession(request), mode })`. +- `systemContext(reason)` bypasses every access rule. Use it for trusted jobs such as build scripts, sitemaps and imports, never with a visitor's input. The `reason` is required, so each bypass says why it exists. + +The store's plain read functions (`queryDocuments({ publishedOnly: true })`, `readDocumentBySlug(…, { publishedOnly: true })`, and so on) still work, but they don't know who is asking. Without a `session` they read like a system context, so you must pass `publishedOnly: true` yourself. Prefer `cmsAs`. Each verb also exists in argument form (`queryDocumentsAs(ctx, …)`, `readDocumentAs(ctx, …)`) for code that passes the context along. With `populate: true`, each result carries `relations`: a map from each `relation` field name to the target document (or array of documents for `many: true`). The stored IDs are left as they are. `populateRelations(collection, doc)` does the same for a document you already have. diff --git a/docs/schema/collections-and-fields.md b/docs/schema/collections-and-fields.md index 00eac9cd..8feba8b7 100644 --- a/docs/schema/collections-and-fields.md +++ b/docs/schema/collections-and-fields.md @@ -485,7 +485,7 @@ A hook is the engine asking, just before a commit, "anything you want to make us | `preValidate` | `{ doc, id, operation, actor }` | Before validation, on saves and when a change is staged. May return a transformed doc (merged over the input). | | `postValidate` | `{ doc, id, operation, actor }` | After validation, right before a commit (direct save or approval). May return a transformed doc, which is re-validated. | | `preDelete` | `{ id, actor }` | Before a delete commits. Throw to veto. | -| `postRead` | `{ doc, id }` | On every read. May return a transformed doc (the response only; never stored). | +| `postRead` | `{ doc, id, access }` | On every read. May return a transformed doc (the response only; never stored). `access` is the reader's [access context](../api/cms-core-server#access-contexts). | | `afterChange` | `{ doc, id, operation, actor }` | **Deprecated.** After a commit, with the committed document. Use a `document.created` / `document.updated` event handler. | | `afterDelete` | `{ id, actor }` | **Deprecated.** After a delete commits. Use a `document.deleted` event handler. | diff --git a/docs/tutorials/faceted-search.md b/docs/tutorials/faceted-search.md index 980ad197..aac6adaa 100644 --- a/docs/tutorials/faceted-search.md +++ b/docs/tutorials/faceted-search.md @@ -124,8 +124,10 @@ const search = createCmsSearch({ collection: picks }) const result = await search.search({ facets: ['vendor'] }) ``` -Create the adapter **per server request**, passing the resolved CMS `session`. -It defaults to anonymous, published-only reads when no session is supplied. +Create the adapter **per server request**, passing the caller's access context +as `access` (for example `accessContext({ session: await resolveSession(request) })` +from `@tanstack/cms-core/server`). It defaults to `publicContext()`, which is +anonymous and published-only. The older `session` option still works. Hits are `{ id, doc }` and go through CMS after-read hooks and redaction. Facet predicates, sorting, text fields, and facet values are checked against field read permissions. Unreadable or document-dependent field permissions diff --git a/examples/payload-after/src/routeTree.gen.ts b/examples/payload-after/src/routeTree.gen.ts index 38df3fe4..b6f4a185 100644 --- a/examples/payload-after/src/routeTree.gen.ts +++ b/examples/payload-after/src/routeTree.gen.ts @@ -13,10 +13,10 @@ import { Route as DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesIndexRouteImpo import { Route as DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSplatRouteImport } from './../../../packages/ui-react/src/routes/$' import { Route as DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesRobotsDottxtRouteImport } from './../../../packages/ui-react/src/routes/robots.txt' import { Route as DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSitemapDotxmlRouteImport } from './../../../packages/ui-react/src/routes/sitemap.xml' -import { Route as DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdAgentRouteImport } from './../../../packages/ui-react/.generated/3b63267ad9fd/agent' -import { Route as DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdContentRouteImport } from './../../../packages/ui-react/.generated/3b63267ad9fd/content' -import { Route as DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdReviewRouteImport } from './../../../packages/ui-react/.generated/3b63267ad9fd/review' -import { Route as DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdSettingsRouteImport } from './../../../packages/ui-react/.generated/3b63267ad9fd/settings' +import { Route as DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3AgentRouteImport } from './../../../packages/ui-react/.generated/204af191d4b3/agent' +import { Route as DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ContentRouteImport } from './../../../packages/ui-react/.generated/204af191d4b3/content' +import { Route as DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ReviewRouteImport } from './../../../packages/ui-react/.generated/204af191d4b3/review' +import { Route as DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3SettingsRouteImport } from './../../../packages/ui-react/.generated/204af191d4b3/settings' import { Route as DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsRouteImport } from './../../../packages/ui-react/src/routes/api.cms' import { Route as DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmcpRouteImport } from './../../../packages/ui-react/src/routes/api.mcp' import { Route as DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmediaRouteImport } from './../../../packages/ui-react/src/routes/api.media' @@ -24,7 +24,7 @@ import { Route as DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPDotidRouteImp import { Route as DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPostDotidRouteImport } from './../../../packages/ui-react/src/routes/post.$id' import { Route as DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmediaDotnameRouteImport } from './../../../packages/ui-react/src/routes/api.media.$name' import { Route as DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPreviewDotcollectionDotidRouteImport } from './../../../packages/ui-react/src/routes/preview.$collection.$id' -import { Route as DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdEditDotcollectionDotidRouteImport } from './../../../packages/ui-react/.generated/3b63267ad9fd/edit.$collection.$id' +import { Route as DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3EditDotcollectionDotidRouteImport } from './../../../packages/ui-react/.generated/204af191d4b3/edit.$collection.$id' import { Route as DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsDotv1DotsplatRouteImport } from './../../../packages/ui-react/src/routes/api.cms.v1.$' const DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesIndexRoute = @@ -55,32 +55,32 @@ const DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSitemapDotxmlRoute = getParentRoute: () => rootRouteImport, } as any, ) -const DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdAgentRoute = - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdAgentRouteImport.update( +const DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3AgentRoute = + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3AgentRouteImport.update( { id: '/admin/agent', path: '/admin/agent', getParentRoute: () => rootRouteImport, } as any, ) -const DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdContentRoute = - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdContentRouteImport.update( +const DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ContentRoute = + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ContentRouteImport.update( { id: '/admin/content', path: '/admin/content', getParentRoute: () => rootRouteImport, } as any, ) -const DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdReviewRoute = - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdReviewRouteImport.update( +const DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ReviewRoute = + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ReviewRouteImport.update( { id: '/admin/review', path: '/admin/review', getParentRoute: () => rootRouteImport, } as any, ) -const DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdSettingsRoute = - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdSettingsRouteImport.update( +const DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3SettingsRoute = + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3SettingsRouteImport.update( { id: '/admin/settings', path: '/admin/settings', @@ -135,8 +135,8 @@ const DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPreviewDotcollectionDotidR getParentRoute: () => rootRouteImport, } as any, ) -const DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdEditDotcollectionDotidRoute = - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdEditDotcollectionDotidRouteImport.update( +const DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3EditDotcollectionDotidRoute = + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3EditDotcollectionDotidRouteImport.update( { id: '/admin/edit/$collection/$id', path: '/admin/edit/$collection/$id', @@ -157,10 +157,10 @@ export interface FileRoutesByFullPath { '/$': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSplatRoute '/robots.txt': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesRobotsDottxtRoute '/sitemap.xml': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSitemapDotxmlRoute - '/admin/agent': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdAgentRoute - '/admin/content': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdContentRoute - '/admin/review': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdReviewRoute - '/admin/settings': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdSettingsRoute + '/admin/agent': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3AgentRoute + '/admin/content': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ContentRoute + '/admin/review': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ReviewRoute + '/admin/settings': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3SettingsRoute '/api/cms': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsRoute '/api/mcp': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmcpRoute '/api/media': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmediaRoute @@ -168,7 +168,7 @@ export interface FileRoutesByFullPath { '/post/$id': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPostDotidRoute '/api/media/$name': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmediaDotnameRoute '/preview/$collection/$id': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPreviewDotcollectionDotidRoute - '/admin/edit/$collection/$id': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdEditDotcollectionDotidRoute + '/admin/edit/$collection/$id': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3EditDotcollectionDotidRoute '/api/cms/v1/$': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsDotv1DotsplatRoute } export interface FileRoutesByTo { @@ -176,10 +176,10 @@ export interface FileRoutesByTo { '/$': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSplatRoute '/robots.txt': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesRobotsDottxtRoute '/sitemap.xml': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSitemapDotxmlRoute - '/admin/agent': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdAgentRoute - '/admin/content': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdContentRoute - '/admin/review': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdReviewRoute - '/admin/settings': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdSettingsRoute + '/admin/agent': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3AgentRoute + '/admin/content': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ContentRoute + '/admin/review': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ReviewRoute + '/admin/settings': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3SettingsRoute '/api/cms': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsRoute '/api/mcp': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmcpRoute '/api/media': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmediaRoute @@ -187,7 +187,7 @@ export interface FileRoutesByTo { '/post/$id': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPostDotidRoute '/api/media/$name': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmediaDotnameRoute '/preview/$collection/$id': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPreviewDotcollectionDotidRoute - '/admin/edit/$collection/$id': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdEditDotcollectionDotidRoute + '/admin/edit/$collection/$id': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3EditDotcollectionDotidRoute '/api/cms/v1/$': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsDotv1DotsplatRoute } export interface FileRoutesById { @@ -196,10 +196,10 @@ export interface FileRoutesById { '/$': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSplatRoute '/robots.txt': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesRobotsDottxtRoute '/sitemap.xml': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSitemapDotxmlRoute - '/admin/agent': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdAgentRoute - '/admin/content': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdContentRoute - '/admin/review': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdReviewRoute - '/admin/settings': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdSettingsRoute + '/admin/agent': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3AgentRoute + '/admin/content': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ContentRoute + '/admin/review': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ReviewRoute + '/admin/settings': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3SettingsRoute '/api/cms': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsRoute '/api/mcp': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmcpRoute '/api/media': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmediaRoute @@ -207,7 +207,7 @@ export interface FileRoutesById { '/post/$id': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPostDotidRoute '/api/media/$name': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmediaDotnameRoute '/preview/$collection/$id': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPreviewDotcollectionDotidRoute - '/admin/edit/$collection/$id': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdEditDotcollectionDotidRoute + '/admin/edit/$collection/$id': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3EditDotcollectionDotidRoute '/api/cms/v1/$': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsDotv1DotsplatRoute } export interface FileRouteTypes { @@ -275,10 +275,10 @@ export interface RootRouteChildren { DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSplatRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSplatRoute DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesRobotsDottxtRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesRobotsDottxtRoute DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSitemapDotxmlRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSitemapDotxmlRoute - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdAgentRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdAgentRoute - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdContentRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdContentRoute - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdReviewRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdReviewRoute - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdSettingsRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdSettingsRoute + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3AgentRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3AgentRoute + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ContentRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ContentRoute + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ReviewRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ReviewRoute + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3SettingsRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3SettingsRoute DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsRoute DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmcpRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmcpRoute DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmediaRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmediaRoute @@ -286,7 +286,7 @@ export interface RootRouteChildren { DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPostDotidRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPostDotidRoute DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmediaDotnameRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmediaDotnameRoute DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPreviewDotcollectionDotidRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPreviewDotcollectionDotidRoute - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdEditDotcollectionDotidRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdEditDotcollectionDotidRoute + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3EditDotcollectionDotidRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3EditDotcollectionDotidRoute DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsDotv1DotsplatRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsDotv1DotsplatRoute } @@ -324,28 +324,28 @@ declare module '@tanstack/react-router' { id: '/admin/agent' path: '/admin/agent' fullPath: '/admin/agent' - preLoaderRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdAgentRouteImport + preLoaderRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3AgentRouteImport parentRoute: typeof rootRouteImport } '/admin/content': { id: '/admin/content' path: '/admin/content' fullPath: '/admin/content' - preLoaderRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdContentRouteImport + preLoaderRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ContentRouteImport parentRoute: typeof rootRouteImport } '/admin/review': { id: '/admin/review' path: '/admin/review' fullPath: '/admin/review' - preLoaderRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdReviewRouteImport + preLoaderRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ReviewRouteImport parentRoute: typeof rootRouteImport } '/admin/settings': { id: '/admin/settings' path: '/admin/settings' fullPath: '/admin/settings' - preLoaderRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdSettingsRouteImport + preLoaderRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3SettingsRouteImport parentRoute: typeof rootRouteImport } '/api/cms': { @@ -401,7 +401,7 @@ declare module '@tanstack/react-router' { id: '/admin/edit/$collection/$id' path: '/admin/edit/$collection/$id' fullPath: '/admin/edit/$collection/$id' - preLoaderRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdEditDotcollectionDotidRouteImport + preLoaderRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3EditDotcollectionDotidRouteImport parentRoute: typeof rootRouteImport } '/api/cms/v1/$': { @@ -423,14 +423,14 @@ const rootRouteChildren: RootRouteChildren = { DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesRobotsDottxtRoute, DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSitemapDotxmlRoute: DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSitemapDotxmlRoute, - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdAgentRoute: - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdAgentRoute, - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdContentRoute: - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdContentRoute, - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdReviewRoute: - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdReviewRoute, - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdSettingsRoute: - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdSettingsRoute, + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3AgentRoute: + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3AgentRoute, + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ContentRoute: + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ContentRoute, + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ReviewRoute: + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ReviewRoute, + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3SettingsRoute: + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3SettingsRoute, DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsRoute: DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsRoute, DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmcpRoute: @@ -445,8 +445,8 @@ const rootRouteChildren: RootRouteChildren = { DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmediaDotnameRoute, DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPreviewDotcollectionDotidRoute: DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPreviewDotcollectionDotidRoute, - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdEditDotcollectionDotidRoute: - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdEditDotcollectionDotidRoute, + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3EditDotcollectionDotidRoute: + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3EditDotcollectionDotidRoute, DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsDotv1DotsplatRoute: DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsDotv1DotsplatRoute, } diff --git a/packages/api/src/http.ts b/packages/api/src/http.ts index d5929683..0e845a3c 100644 --- a/packages/api/src/http.ts +++ b/packages/api/src/http.ts @@ -34,7 +34,6 @@ */ import { agentOpSchemas, - canAccessCollection, cmsLogger, getCmsConfig, runWithCmsConfig, @@ -56,8 +55,10 @@ import { statusForCode, mediaResponseHeaders, readMedia, - assertCollectionAccess, + accessContext, + assertReadable, assertTrustedOrigin, + canReadDocument, clientKey, rateLimit, requirePermission, @@ -75,13 +76,14 @@ import { verifyMcpAccess, } from '@tanstack/cms-core/server' import type { + AccessContext, CmsErrorCode, ImageFormat, ImageTransform, CmsEvent, } from '@tanstack/cms-core/server' import { cmsMcp } from './mcp' -import { allOps, findOp, invokeAnyOp } from './ops' +import { agentActorName, allOps, findOp, invokeAnyOp } from './ops' import { CMS_API_BASE, CMS_API_VERSION, buildOpenApiDocument } from './openapi' import type { ResolvedOp } from './ops' @@ -261,10 +263,15 @@ async function dispatchCmsApi(request: Request): Promise { const session = await resolveSession(request) await requirePermission('agent.use', session) await rateLimit('mcp', request, session) + const access = accessContext({ + session, + mode: 'edit', + agent: agentActorName('webmcp', session), + }) // `runOp` validates the input through the op's Standard Schema once; no // separate pre-validation here. const result = await runWithSession(session, () => - runOp(op.name, body.input ?? {}, 'webmcp'), + runOp(op.name, body.input ?? {}, 'webmcp', access), ) return json({ result }) } catch (e) { @@ -304,9 +311,15 @@ export async function handleMcpApi(request: Request): Promise { )) as BodyInit) : undefined, }) - return await (session - ? runWithSession(session, () => cmsMcp.fetch(boundedRequest)) - : cmsMcp.fetch(boundedRequest)) + if (!session) return await cmsMcp.fetch(boundedRequest) + const agent = accessContext({ + session, + mode: 'edit', + agent: agentActorName('mcp', session), + }) + return await runWithSession(session, () => + cmsMcp.fetch(boundedRequest, agent), + ) } catch (e) { return opError(e, request) } @@ -543,7 +556,7 @@ function reserveStream(config: ResolvedCmsConfig, client: string): () => void { } async function canSeeEvent( - session: CmsSession, + access: AccessContext, payload: CmsEvent, ): Promise { const collection = getCmsConfig().collections[payload.collection] @@ -551,16 +564,16 @@ async function canSeeEvent( try { const doc = cmsEventDocument(payload) if (!doc && typeof collection.access?.read === 'function') return false + const readable = (d: typeof doc) => + canReadDocument(access, payload.collection, { + id: payload.id, + published: false, + doc: d ?? null, + }) + const previous = cmsEventPreviousDocument(payload) return ( - canAccessCollection(session, collection, 'read', doc ?? null) || - (payload.event === 'change' && - !!cmsEventPreviousDocument(payload) && - canAccessCollection( - session, - collection, - 'read', - cmsEventPreviousDocument(payload), - )) + readable(doc) || + (payload.event === 'change' && !!previous && readable(previous)) ) } catch { return false @@ -588,7 +601,7 @@ export async function handleEventsApi(request: Request): Promise { 'NOT_FOUND', ) } - assertCollectionAccess(session, collectionFilter, 'read') + assertReadable(accessContext({ session, mode: 'edit' }), collectionFilter) } release = reserveStream(getCmsConfig(), clientKey(request, session)) } catch (e) { @@ -626,7 +639,8 @@ export async function handleEventsApi(request: Request): Promise { controller.close() return } - if (!(await canSeeEvent(session, payload))) return + const access = accessContext({ session, mode: 'edit' }) + if (!(await canSeeEvent(access, payload))) return const msg = JSON.stringify({ event: payload.event, collection: payload.collection, diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts index 7845598e..c6ec80ae 100644 --- a/packages/api/src/index.ts +++ b/packages/api/src/index.ts @@ -9,11 +9,14 @@ * handlers the Start route files delegate to. */ export { + agentActorName, allOps, findOp, invokeAnyOp, invokeOp, ops, + READ_MODE_HEADER, + requestAccessContext, resolveAuthSession, runAgent, } from './ops' diff --git a/packages/api/src/interface-ops.ts b/packages/api/src/interface-ops.ts index 3a792eec..216c2729 100644 --- a/packages/api/src/interface-ops.ts +++ b/packages/api/src/interface-ops.ts @@ -1,7 +1,6 @@ import { z } from 'zod' import { getCmsConfig, - canAccessCollection, interfaceDefinitionSchema, interfaceInputSchema, interfaceStateSchema, @@ -9,6 +8,7 @@ import { import type { CmsOpContext, InterfaceDefinition } from '@tanstack/cms-core' import { CmsError, + canReadCollection, createInterfaceQuery, interfaceDriver, executeInterface, @@ -222,7 +222,7 @@ export const interfaceOps = { .filter( (c) => c.name !== interfaceCollectionName() && - canAccessCollection(ctx.session, c, 'read'), + canReadCollection(ctx.access, c.name), ) .map((c) => ({ name: c.name, diff --git a/packages/api/src/mcp.ts b/packages/api/src/mcp.ts index 822a8a64..3952187c 100644 --- a/packages/api/src/mcp.ts +++ b/packages/api/src/mcp.ts @@ -4,34 +4,39 @@ * in-app agent uses. Writes stage into the review queue like every other agent. * * Access is enforced by `handleMcpApi`: callers need a CMS API key or a session - * with `agent.use`, and tools run under that session's role and scope. + * with `agent.use`, and every tool call runs as the agent's access context + * (`cmsMcp.fetch(request, access)`). * * `@tanstack/ai-mcp` and `@tanstack/ai` are optional peers, loaded on the * first MCP request. * * Server-only. */ -import { getCmsConfig } from '@tanstack/cms-core' +import { getCmsConfig, hasPermission } from '@tanstack/cms-core' import { + CMS_ACCESS_KEY, cmsTools, currentSession, isMissingModule, missingPeer, } from '@tanstack/cms-core/server' -import type { ResolvedCmsConfig } from '@tanstack/cms-core' +import type { CmsSession, ResolvedCmsConfig } from '@tanstack/cms-core' +import type { AccessContext } from '@tanstack/cms-core/server' import type * as AiMcpServer from '@tanstack/ai-mcp/server' type McpServer = ReturnType // One server per (config, role-signature), built on first use so app ops // registered with `defineCms({ ops })` are part of its tool list and -// read-only keys only expose read operations in `tools/list`. +// read-only keys only expose read operations in `tools/list`. A server is +// shared by every caller with that signature, so it never holds a caller's +// context: each request hands its own to the tool calls. const servers = new WeakMap< ResolvedCmsConfig, Map> >() -async function createServer(): Promise { +async function createServer(session?: CmsSession): Promise { let mod: typeof AiMcpServer try { mod = await import('@tanstack/ai-mcp/server') @@ -44,23 +49,30 @@ async function createServer(): Promise { return mod.createMCPServer({ name: 'tanstack-cms', version: '1.0.0', - tools: await cmsTools('mcp', { authorizedOnly: true }), + tools: await cmsTools('mcp', { + ...(session && { + include: (op) => + op.access === 'public' || hasPermission(session, op.access), + }), + }), }) } -function serverFor(config: ResolvedCmsConfig): Promise { +function serverFor( + config: ResolvedCmsConfig, + session: CmsSession | undefined, +): Promise { let byRole = servers.get(config) if (!byRole) { byRole = new Map() servers.set(config, byRole) } - const session = currentSession() const cacheKey = session ? `${session.role ?? 'none'}:${[...session.permissions].sort().join(',')}` : '__all__' let server = byRole.get(cacheKey) if (!server) { - server = createServer() + server = createServer(session) server.catch(() => byRole.delete(cacheKey)) byRole.set(cacheKey, server) } @@ -68,6 +80,17 @@ function serverFor(config: ResolvedCmsConfig): Promise { } export const cmsMcp = { - fetch: async (request: Request) => - (await serverFor(getCmsConfig())).fetch(request), + /** + * Serve one MCP request. Tools are listed for, and every call reads and + * writes as, `access` (e.g. `accessContext({ session, agent: 'mcp', + * mode: 'edit' })`). Without it the session bound by `runWithSession` is + * used; that fallback is deprecated. + */ + fetch: async (request: Request, access?: AccessContext) => { + if (!access) { + return (await serverFor(getCmsConfig(), currentSession())).fetch(request) + } + const server = await serverFor(getCmsConfig(), access.session) + return server.handle(request, { context: { [CMS_ACCESS_KEY]: access } }) + }, } diff --git a/packages/api/src/media-ops.ts b/packages/api/src/media-ops.ts index 74f22f2f..6e5206c7 100644 --- a/packages/api/src/media-ops.ts +++ b/packages/api/src/media-ops.ts @@ -8,11 +8,12 @@ */ import { Buffer } from 'node:buffer' import { z } from 'zod' -import { canAccessCollection, getCmsConfig } from '@tanstack/cms-core' +import { getCmsConfig } from '@tanstack/cms-core' import { CmsError, DEFAULT_MAX_UPLOAD_BYTES, - accessibleCollections, + canReadCollection, + canReadDocument, deleteMediaItem, findMediaUsage, getMediaItem, @@ -22,7 +23,7 @@ import { readMedia, readDocumentWithPending, readDocument, - redactDoc, + redactFor, requirePermission, saveMedia, updateMediaItem, @@ -35,17 +36,21 @@ import { okOutput, uploadOutput, } from './outputs' -import type { CmsOpContext, CmsSession } from '@tanstack/cms-core' +import type { CmsOpContext } from '@tanstack/cms-core' +import type { AccessContext } from '@tanstack/cms-core/server' -async function readableMediaUsage(urlOrId: string, session: CmsSession) { - const allowed = new Set(accessibleCollections(session, 'read')) +async function readableMediaUsage( + urlOrId: string, + access: AccessContext, + session: CmsOpContext['session'], +) { const usage = await findMediaUsage(urlOrId) const media = await getMediaItem(urlOrId, session) const needle = media?.url ?? urlOrId return ( await Promise.all( usage - .filter((item) => allowed.has(item.collection)) + .filter((item) => canReadCollection(access, item.collection)) .map(async (item) => { const live = await readDocument(item.collection, item.id) const pending = await readDocumentWithPending( @@ -55,16 +60,15 @@ async function readableMediaUsage(urlOrId: string, session: CmsSession) { for (const doc of [live, pending.doc]) { if ( !doc || - !canAccessCollection( - session, - getCmsConfig().collections[item.collection], - 'read', + !canReadDocument(access, item.collection, { + id: item.id, + published: false, doc, - ) + }) ) continue if ( - JSON.stringify(redactDoc(item.collection, doc, session)).includes( + JSON.stringify(redactFor(access, item.collection, doc)).includes( needle, ) ) @@ -146,7 +150,7 @@ export const mediaOps = { description: 'Documents that reference a media item.', input: mediaUsageInput, run: async (input: z.infer, ctx: CmsOpContext) => - readableMediaUsage(input.urlOrId, ctx.session), + readableMediaUsage(input.urlOrId, ctx.access, ctx.session), }, updateUploadedMedia: { @@ -179,7 +183,11 @@ export const mediaOps = { } catch (error) { if (error instanceof CmsError && error.code === 'CONFLICT') throw new CmsError('Media is still in use.', 'CONFLICT', { - usage: await readableMediaUsage(input.urlOrId, ctx.session), + usage: await readableMediaUsage( + input.urlOrId, + ctx.access, + ctx.session, + ), }) throw error } diff --git a/packages/api/src/ops.ts b/packages/api/src/ops.ts index 6c2d4cc3..c79a5112 100644 --- a/packages/api/src/ops.ts +++ b/packages/api/src/ops.ts @@ -49,19 +49,27 @@ import { saveDraft, deleteDocument, restoreDocument, - findDocumentBySlug, - findReferences, listAudit, listPending, listRevisions, listTranslations, - queryDocumentSummaries, - queryDocuments, readDocument, readDocumentWithPending, - redactDoc, + readDocumentWithPendingAs, + findDocumentBySlugAs, + findReferencesAs, + listRevisionsAs, + queryDocumentsAs, + queryDocumentSummariesAs, + accessContext, + assertReadable, + canReadCollection, + canReadDocument, + parseReadMode, + previewContext, + redactFor, + withMode, protectWrite, - accessibleCollections, assertCollectionAccess, createApiKey, listApiKeys, @@ -111,6 +119,7 @@ import type { Doc, OpAccess, } from '@tanstack/cms-core' +import type { AccessContext, ReadMode } from '@tanstack/cms-core/server' export type { CmsOpContext, OpAccess } @@ -120,6 +129,46 @@ export interface CmsContext { request?: Request /** Recorded on staged writes. Default `human`. */ actor?: string + /** + * The caller's access context, when the host built one (the Start adapter + * does). Without it, one is built from `request` with + * `requestAccessContext`. It must carry a session. + */ + access?: AccessContext +} + +/** The header an HTTP caller narrows its read mode with. */ +export const READ_MODE_HEADER = 'x-cms-read-mode' + +/** + * The access context for one request: its session (`resolveSession`) in + * `options.mode`, else the mode the caller asked for in `x-cms-read-mode`, + * else `options.defaultMode` (`edit`). An `edit` request context is the + * widest the caller may read; ops narrow it (the public reads serve drafts + * only to callers who may read them). Hosts that aren't TanStack Start build + * their contexts with this. + */ +export async function requestAccessContext( + request?: Request, + options?: { mode?: ReadMode; defaultMode?: ReadMode }, +): Promise { + const session = await resolveSession(request) + const mode = + options?.mode ?? + parseReadMode(request?.headers.get(READ_MODE_HEADER)) ?? + options?.defaultMode ?? + 'edit' + return accessContext({ session, mode }) +} + +/** The working copy, as an editor reads it. */ +function editing(ctx: CmsOpContext): AccessContext { + return withMode(ctx.access, 'edit') +} + +/** The agent actor for a surface (`content-agent`, `mcp`, …) and a session. */ +export function agentActorName(surface: string, session?: CmsSession): string { + return session?.agent ? `${surface}:${session.agent}` : surface } /** A built-in operation: a `CmsOpDefinition` keyed by its name in `ops`. */ @@ -343,7 +392,7 @@ function canPublish( * staged for review (an author's edit). */ async function saveAsHuman( - session: CmsSession, + ctx: CmsOpContext, collection: string, id: string, doc: Record, @@ -355,6 +404,7 @@ async function saveAsHuman( publish?: boolean }, ) { + const { session } = ctx const existing = opts.create ? null : await readDocument(collection, id) assertCollectionAccess( session, @@ -388,7 +438,7 @@ async function saveAsHuman( ok: true, staged: true, pendingId: pending.id, - doc: redactDoc(collection, pending.after as Doc, session) as Doc, + doc: redactFor(ctx.access, collection, pending.after as Doc), } } const isDraft = @@ -407,7 +457,7 @@ async function saveAsHuman( staged: false, draft: true, pendingId: pending.id, - doc: redactDoc(collection, pending.after as Doc, session) as Doc, + doc: redactFor(ctx.access, collection, pending.after as Doc), } } const committed = await commitDocument(collection, id, safe, { @@ -422,7 +472,7 @@ async function saveAsHuman( return { ok: true, staged: false, - doc: redactDoc(collection, committed, session), + doc: redactFor(ctx.access, collection, committed), } } @@ -448,16 +498,16 @@ const _ops = { input: z.infer, ctx: CmsOpContext, ) => { - assertCollectionAccess(ctx.session, input.collection, 'read') + const access = editing(ctx) + assertReadable(access, input.collection) // `"me"` is resolved on the server so the client never guesses the id. const assignedTo = input.assignedTo === 'me' ? (ctx.session.user?.id ?? ctx.session.user?.name) : input.assignedTo - return queryDocumentSummaries({ + return queryDocumentSummariesAs(access, { ...input, ...(assignedTo ? { assignedTo } : {}), - session: ctx.session, }) }, }, @@ -470,19 +520,18 @@ const _ops = { input: docRef, output: documentOutput, run: async (input: z.infer, ctx: CmsOpContext) => { - assertCollectionAccess(ctx.session, input.collection, 'read') + const access = editing(ctx) + assertReadable(access, input.collection) const result = await readDocumentWithPending(input.collection, input.id) const live = await readDocument(input.collection, input.id) if (live ?? result.doc) - assertCollectionAccess( - ctx.session, - input.collection, - 'read', - live ?? result.doc, - ) + assertReadable(access, input.collection, { + id: input.id, + doc: live ?? result.doc, + }) return { ...result, - doc: redactDoc(input.collection, result.doc, ctx.session), + doc: redactFor(access, input.collection, result.doc), } }, }, @@ -507,31 +556,19 @@ const _ops = { input: z.infer, ctx: CmsOpContext, ) => { - const found = await findDocumentBySlug(input.slugOrId, { - preferred: input.preferred, - publishedOnly: !hasPermission(ctx.session, 'content.read'), - session: ctx.session, - }) - if ( - found && - found.doc.published !== true && - !canAccessCollection( - ctx.session, - getCmsConfig().collections[found.collection], - 'read', - found.doc, - ) - ) { - return null - } + const found = await findDocumentBySlugAs( + siteRead( + ctx, + ctx.access.mode === 'live' || + !hasPermission(ctx.session, 'content.read'), + ), + input.slugOrId, + { preferred: input.preferred }, + ) return found ? { ...found, - doc: localizeDoc( - found.collection, - redactDoc(found.collection, found.doc, ctx.session), - input.locale, - ) as Doc, + doc: localizeDoc(found.collection, found.doc, input.locale) as Doc, } : null }, @@ -548,22 +585,21 @@ const _ops = { input: z.infer, ctx: CmsOpContext, ) => { - const seeDrafts = canAccessCollection( - ctx.session, - getCmsConfig().collections[input.collection], - 'read', + const result = await queryDocumentsAs( + siteRead( + ctx, + ctx.access.mode === 'live' || + !canReadCollection(editing(ctx), input.collection), + ), + { + collection: input.collection, + where: input.where, + sort: input.sort, + limit: input.limit, + offset: input.offset, + cursor: input.cursor, + }, ) - const result = await queryDocuments({ - collection: input.collection, - publishedOnly: !seeDrafts, - where: input.where, - sort: input.sort, - limit: input.limit, - offset: input.offset, - cursor: input.cursor, - session: ctx.session, - publicRead: true, - }) return { items: result.items.map((i) => ({ id: i.id, @@ -582,51 +618,36 @@ const _ops = { 'Revisions, translations, and inbound references for the document editor (admin).', input: docRef, run: async (input: z.infer, ctx: CmsOpContext) => { - assertCollectionAccess(ctx.session, input.collection, 'read') + const access = editing(ctx) + assertReadable(access, input.collection) const current = await readDocumentWithPending(input.collection, input.id) const live = await readDocument(input.collection, input.id) if (live ?? current.doc) - assertCollectionAccess( - ctx.session, - input.collection, - 'read', - live ?? current.doc, - ) - const allowed = new Set(accessibleCollections(ctx.session, 'read')) + assertReadable(access, input.collection, { + id: input.id, + doc: live ?? current.doc, + }) const [revisions, translations, references] = await Promise.all([ - listRevisions(input.collection, input.id), + listRevisionsAs(access, input.collection, input.id), listTranslations(input.collection, input.id), - findReferences(input.collection, input.id, undefined, ctx.session), + findReferencesAs(access, input.collection, input.id), ]) return { - revisions: revisions - .filter((r) => - canAccessCollection( - ctx.session, - getCmsConfig().collections[input.collection], - 'read', - r.doc, - ), - ) - .map((r) => ({ - ...r, - doc: redactDoc(input.collection, r.doc, ctx.session), - })), + revisions, translations: ( await Promise.all( translations.map(async (translation) => { const doc = await readDocument(input.collection, translation.id) if ( !doc || - !canAccessCollection( - ctx.session, - getCmsConfig().collections[input.collection], - 'read', + !canReadDocument(access, input.collection, { + id: translation.id, + published: false, doc, - ) + }) ) return null - const safe = redactDoc(input.collection, doc, ctx.session) + const safe = redactFor(access, input.collection, doc) return { ...translation, title: String( @@ -642,7 +663,7 @@ const _ops = { references: ( await Promise.all( references - .filter((r) => allowed.has(r.collection)) + .filter((r) => canReadCollection(access, r.collection)) .map(async (reference) => { const doc = await readDocument( reference.collection, @@ -650,15 +671,14 @@ const _ops = { ) if ( !doc || - !canAccessCollection( - ctx.session, - getCmsConfig().collections[reference.collection], - 'read', + !canReadDocument(access, reference.collection, { + id: reference.id, + published: false, doc, - ) + }) ) return null - const safe = redactDoc(reference.collection, doc, ctx.session) + const safe = redactFor(access, reference.collection, doc) return { ...reference, title: String( @@ -721,7 +741,7 @@ const _ops = { ) return { ok: true, - doc: redactDoc(input.collection, doc as Doc, ctx.session) as Doc, + doc: redactFor(ctx.access, input.collection, doc as Doc), } }, }, @@ -734,7 +754,7 @@ const _ops = { input: saveDocInput, output: writeOutput, run: async (input: z.infer, ctx: CmsOpContext) => - saveAsHuman(ctx.session, input.collection, input.id, input.doc, { + saveAsHuman(ctx, input.collection, input.id, input.doc, { expectedPendingVersion: input.expectedPendingVersion, expectedRevision: input.expectedRevision, publish: input.publish, @@ -786,7 +806,7 @@ const _ops = { ) } return saveAsHuman( - ctx.session, + ctx, input.collection, input.id, { ...emptyDoc(collection), ...(input.doc ?? {}) }, @@ -923,7 +943,7 @@ const _ops = { live ?? current, ) await saveAsHuman( - ctx.session, + ctx, collection, id, { ...current, published: action === 'publish' }, @@ -998,11 +1018,10 @@ const _ops = { }, ], }) - return redactDoc( - input.collection, - { ...current, ...proposed } as Doc, - ctx.session, - ) + return redactFor(ctx.access, input.collection, { + ...current, + ...proposed, + } as Doc) }, }, @@ -1012,25 +1031,24 @@ const _ops = { description: 'Review queue: pending writes and audit trail.', input: noInput, run: async (_input: z.infer, ctx: CmsOpContext) => { - const allowed = new Set(accessibleCollections(ctx.session, 'read')) + const access = editing(ctx) const [pending, audit] = await Promise.all([listPending(), listAudit()]) return { pending: pending .filter( (p) => p.source !== 'draft' && - allowed.has(p.collection) && - canAccessCollection( - ctx.session, - getCmsConfig().collections[p.collection], - 'read', - p.before ?? p.after, - ), + canReadCollection(access, p.collection) && + canReadDocument(access, p.collection, { + id: p.docId, + published: false, + doc: p.before ?? p.after, + }), ) .map((p) => ({ ...p, - before: redactDoc(p.collection, p.before, ctx.session), - after: redactDoc(p.collection, p.after, ctx.session), + before: redactFor(access, p.collection, p.before), + after: redactFor(access, p.collection, p.after), })), audit: ( await Promise.all( @@ -1042,7 +1060,7 @@ const _ops = { (a): a is typeof a & { collection: string; docId: string } => a.collection !== undefined && a.docId !== undefined && - allowed.has(a.collection), + canReadCollection(access, a.collection), ) .map(async (entry) => { const doc = @@ -1050,12 +1068,11 @@ const _ops = { (await listRevisions(entry.collection, entry.docId))[0] ?.doc ?? null - return canAccessCollection( - ctx.session, - getCmsConfig().collections[entry.collection], - 'read', + return canReadDocument(access, entry.collection, { + id: entry.docId, + published: false, doc, - ) + }) ? entry : null }), @@ -1104,8 +1121,8 @@ const _ops = { }) return { ...decided, - before: redactDoc(decided.collection, decided.before, ctx.session), - after: redactDoc(decided.collection, decided.after, ctx.session), + before: redactFor(ctx.access, decided.collection, decided.before), + after: redactFor(ctx.access, decided.collection, decided.after), } }, }, @@ -1122,22 +1139,22 @@ const _ops = { const pending = await getPending(input.id) if (!pending) throw new CmsError(`Unknown pending change: ${input.id}`, 'NOT_FOUND') - assertCollectionAccess( - ctx.session, - pending.collection, - 'read', - (await readDocument(pending.collection, pending.docId)) ?? + const access = editing(ctx) + assertReadable(access, pending.collection, { + id: pending.docId, + doc: + (await readDocument(pending.collection, pending.docId)) ?? pending.before ?? pending.after, - ) + }) const decided = await reject(input.id, { expectedVersion: input.expectedVersion, rejecter: ctx.session.user?.name ?? ctx.session.user?.id, }) return { ...decided, - before: redactDoc(decided.collection, decided.before, ctx.session), - after: redactDoc(decided.collection, decided.after, ctx.session), + before: redactFor(access, decided.collection, decided.before), + after: redactFor(access, decided.collection, decided.after), } }, }, @@ -1171,7 +1188,7 @@ const _ops = { const { doc } = await readDocumentWithPending(colName, input.id) if (!doc) throw new CmsError(`No ${colName} with id "${input.id}".`, 'NOT_FOUND') - const readable = redactDoc(colName, doc, ctx.session) + const readable = redactFor(ctx.access, colName, doc) if (blocksFieldName in doc && !(blocksFieldName in readable)) throw new CmsError('The blocks field is not readable.', 'FORBIDDEN') const rawBlocks = readable[blocksFieldName] @@ -1192,11 +1209,10 @@ const _ops = { }, ], }) - const safe = redactDoc( - colName, - { ...doc, [blocksFieldName]: normalizeBlocks(result.blocks) }, - ctx.session, - ) + const safe = redactFor(ctx.access, colName, { + ...doc, + [blocksFieldName]: normalizeBlocks(result.blocks), + }) return { blocks: (safe[blocksFieldName] ?? []) as Array } }, }, @@ -1317,7 +1333,7 @@ const _ops = { if (!doc) throw new CmsError(`No ${colName} with id "${input.id}".`, 'NOT_FOUND') const saved = await saveAsHuman( - ctx.session, + ctx, colName, input.id, { ...doc, [blocksFieldName]: input.blocks }, @@ -1377,7 +1393,10 @@ const _ops = { 'NOT_FOUND', ) } - assertCollectionAccess(ctx.session, input.collection, 'read', current) + assertReadable(editing(ctx), input.collection, { + id: input.id, + doc: current, + }) assertCollectionAccess(ctx.session, input.collection, 'update', current) const { token, record } = await createPreviewToken({ collection: input.collection, @@ -1421,10 +1440,14 @@ const _ops = { // Never distinguish unknown/expired/mismatch to a caller: all 404. throw new CmsError('Preview not found.', 'NOT_FOUND') } - const result = await readDocumentWithPending(input.collection, input.id) + // Read-only, single document: the token's context sees the + // draft/pending version as stored, and nothing else. + const result = await readDocumentWithPendingAs( + previewContext(verified.record), + input.collection, + input.id, + ) if (!result.doc) throw new CmsError('Preview not found.', 'NOT_FOUND') - // Read-only, single document: return the draft/pending version as-is, - // with no session-scoped relations or sibling exposure. return { collection: input.collection, id: input.id, @@ -1526,7 +1549,7 @@ const _ops = { input: z.infer, ctx: CmsOpContext, ) => { - assertCollectionAccess(ctx.session, input.collection, 'read') + assertReadable(editing(ctx), input.collection) return listComments(input.collection, input.id, ctx.session) }, }, @@ -1634,22 +1657,30 @@ async function runResolved( ctx: CmsContext, ): Promise { assertTrustedOrigin(ctx.request) - const session = await resolveSession(ctx.request) + const access = ctx.access ?? (await requestAccessContext(ctx.request)) + const session = access.session + if (!session || access.scope) { + throw new CmsError( + 'Operations run as a session: build the context with accessContext({ session }).', + 'BAD_REQUEST', + ) + } if (op.access !== 'public') await requirePermission(op.access, session) if (op.access === 'agent.use') await rateLimit('ai', ctx.request, session) const actor = ctx.actor ?? 'human' + // The session stays bound for code that still reads `currentSession()`. return runWithSession(session, () => op.agent - ? runOp(op.name, input, actor) - : op.run(input, { request: ctx.request, session, actor }), + ? runOp(op.name, input, actor, access) + : op.run(input, { request: ctx.request, session, actor, access }), ) } /** - * Run a built-in operation the way every transport must: resolve the - * session, enforce the op's declared access, and bind the session for - * `runOp` (agents, MCP) underneath. `input` must already match the op's - * schema. + * Run a built-in operation the way every transport must: take the caller's + * access context (or build it from the request), enforce the op's declared + * access, and run the op with that context. `input` must already match the + * op's schema. */ export async function invokeOp( name: N, @@ -1693,7 +1724,7 @@ function fieldDescriptionSuffix(field: { description?: string }): string { function collectionsBrief(ctx: CmsOpContext): string { return Object.values(getCmsConfig().collections) - .filter((c) => canAccessCollection(ctx.session, c, 'read')) + .filter((c) => canReadCollection(ctx.access, c.name)) .map( (c) => `- ${c.name} ("${c.label}"): fields ${c.fields @@ -1787,6 +1818,7 @@ async function executeAgentChat( toolset === 'none' ? [] : await cmsTools(actor, { + access: agentContext(ctx.access, actor), authorizedOnly: true, readOnly: toolset === 'read', onResult: (result) => { @@ -1876,19 +1908,26 @@ async function executeAgentChat( /** * Run a named agent (`defineCms({ ai: { agents } })`) or the default content * agent (`name` undefined) from server code (e.g. an event handler) without an - * HTTP hop. Binds `options.session` (or the current session / a system admin - * session) so `cmsTools` and `runOp` enforce access and stage writes. + * HTTP hop. The agent acts as `options.access` (an `accessContext`, or a + * `systemContext` for a trusted job), else `options.session`, else the + * session bound by `runWithSession`, else a local admin session; its tools + * enforce that context's access and stage writes. */ export async function runAgent( name: string | undefined, messages: Array<{ role: 'user' | 'assistant'; content: string }>, options?: { + access?: AccessContext session?: CmsSession includeToolResults?: boolean }, ): Promise<{ reply: string; toolResults?: Array }> { const session = - options?.session ?? currentSession() ?? DEFAULT_UNCONFIGURED_SESSION + options?.access?.session ?? + options?.session ?? + currentSession() ?? + DEFAULT_UNCONFIGURED_SESSION + const access = options?.access ?? accessContext({ session, mode: 'edit' }) const actor = (name ? getCmsConfig().ai?.agents?.[name]?.actor : undefined) ?? name ?? @@ -1900,11 +1939,36 @@ export async function runAgent( messages, includeToolResults: options?.includeToolResults, }, - { session, actor }, + { session, actor, access }, ), ) } +/** + * The context an agent's tools act with: the caller's session as the named + * agent actor, in the caller's mode. A trusted context is used as it is. + */ +function agentContext(access: AccessContext, actor: string): AccessContext { + if (!access.session) return access + return accessContext({ + session: access.session, + mode: access.mode, + agent: agentActorName(actor, access.session), + }) +} + +/** + * The public site's read: published documents for everyone, whatever the + * collection's read rule, and drafts only when `liveOnly` is false. + */ +function siteRead(ctx: CmsOpContext, liveOnly: boolean): AccessContext { + return accessContext({ + session: ctx.session, + mode: liveOnly ? 'live' : ctx.access.mode, + publicRead: true, + }) +} + const onPageSystem = () => `You edit the blocks of a CMS page in place. Given the current blocks and an ` + `instruction, return the COMPLETE updated blocks array. Keep blocks the ` + diff --git a/packages/api/src/start.ts b/packages/api/src/start.ts index c52c1b1b..797d0318 100644 --- a/packages/api/src/start.ts +++ b/packages/api/src/start.ts @@ -3,8 +3,10 @@ * * Wraps every CMS operation in a `createServerFn` of the same name. * `@tanstack/cms-ui-react` imports these; they run in-process (no HTTP hop) - * through `invokeOp`, which resolves the session from the incoming request and - * enforces the op's declared access. + * through `invokeOp`, with the access context built from the incoming request + * (`requestAccessContext(getRequest())`), and enforce the op's declared + * access. `getCmsAccessContext()` hands the same context to your own server + * functions. * * Each server function must be a top-level `createServerFn` call for the * Start compiler, so they're spelled out rather than generated; a test keeps @@ -15,256 +17,309 @@ * import { listDocumentSummaries, saveDoc } from '@tanstack/cms-api/start' * ``` */ -import { createServerFn } from '@tanstack/react-start' +import { createServerFn, createServerOnlyFn } from '@tanstack/react-start' import { getRequest } from '@tanstack/react-start/server' import { z } from 'zod' -import { invokeAnyOp, invokeOp, ops } from './ops' +import { invokeAnyOp, invokeOp, ops, requestAccessContext } from './ops' import type { JsonValue, RegisteredOpInput, RegisteredOpName, RegisteredOpOutput, } from '@tanstack/cms-core' +import type { AccessContext, ReadMode } from '@tanstack/cms-core/server' -const req = () => ({ request: getRequest() }) +const req = async () => { + const request = getRequest() + return { request, access: await requestAccessContext(request) } +} + +/** + * The access context of the current Start request, for your own server + * functions: `cmsAs(cms, await getCmsAccessContext())`. It reads as the + * request's session, in `mode`, else the `x-cms-read-mode` header, else + * `live` (published only). Pass `{ mode: 'edit' }` to show a signed-in editor + * the drafts they may read. Other hosts call `requestAccessContext(request)`. + */ +export const getCmsAccessContext = createServerOnlyFn( + (options?: { mode?: ReadMode }): Promise => + requestAccessContext(getRequest(), { + defaultMode: 'live', + ...(options?.mode && { mode: options.mode }), + }), +) export const refreshInterfaceComponents = createServerFn({ method: 'POST' }) .validator(ops.refreshInterfaceComponents.input) - .handler(({ data }) => invokeOp('refreshInterfaceComponents', data, req())) + .handler(async ({ data }) => + invokeOp('refreshInterfaceComponents', data, await req()), + ) export const getInterfaceScheduleStatus = createServerFn({ method: 'GET' }) .validator(ops.getInterfaceScheduleStatus.input) - .handler(({ data }) => invokeOp('getInterfaceScheduleStatus', data, req())) + .handler(async ({ data }) => + invokeOp('getInterfaceScheduleStatus', data, await req()), + ) export const setInterfaceSchedulePaused = createServerFn({ method: 'POST' }) .validator(ops.setInterfaceSchedulePaused.input) - .handler(({ data }) => invokeOp('setInterfaceSchedulePaused', data, req())) + .handler(async ({ data }) => + invokeOp('setInterfaceSchedulePaused', data, await req()), + ) export const refreshInterfaceSnapshot = createServerFn({ method: 'POST' }) .validator(ops.refreshInterfaceSnapshot.input) - .handler(({ data }) => invokeOp('refreshInterfaceSnapshot', data, req())) + .handler(async ({ data }) => + invokeOp('refreshInterfaceSnapshot', data, await req()), + ) export const getInterfaceMetadata = createServerFn({ method: 'GET' }) .validator(ops.getInterfaceMetadata.input) - .handler(({ data }) => invokeOp('getInterfaceMetadata', data, req())) + .handler(async ({ data }) => + invokeOp('getInterfaceMetadata', data, await req()), + ) export const listInterfaces = createServerFn({ method: 'GET' }) .validator(ops.listInterfaces.input) - .handler(({ data }) => invokeOp('listInterfaces', data, req())) + .handler(async ({ data }) => invokeOp('listInterfaces', data, await req())) export const getInterfaceEditor = createServerFn({ method: 'GET' }) .validator(ops.getInterfaceEditor.input) - .handler(({ data }) => invokeOp('getInterfaceEditor', data, req())) + .handler(async ({ data }) => + invokeOp('getInterfaceEditor', data, await req()), + ) export const previewInterface = createServerFn({ method: 'POST' }) .validator(ops.previewInterface.input) - .handler(({ data }) => invokeOp('previewInterface', data, req())) + .handler(async ({ data }) => invokeOp('previewInterface', data, await req())) export const previewInterfaceEvent = createServerFn({ method: 'POST' }) .validator(ops.previewInterfaceEvent.input) - .handler(({ data }) => invokeOp('previewInterfaceEvent', data, req())) + .handler(async ({ data }) => + invokeOp('previewInterfaceEvent', data, await req()), + ) export const submitInterface = createServerFn({ method: 'POST' }) .validator(ops.submitInterface.input) - .handler(({ data }) => invokeOp('submitInterface', data, req())) + .handler(async ({ data }) => invokeOp('submitInterface', data, await req())) export const readInterface = createServerFn({ method: 'POST' }) .validator(ops.readInterface.input) - .handler(({ data }) => invokeOp('readInterface', data, req())) + .handler(async ({ data }) => invokeOp('readInterface', data, await req())) export const dispatchInterfaceEvent = createServerFn({ method: 'POST' }) .validator(ops.dispatchInterfaceEvent.input) - .handler(({ data }) => invokeOp('dispatchInterfaceEvent', data, req())) + .handler(async ({ data }) => + invokeOp('dispatchInterfaceEvent', data, await req()), + ) export const generateInterface = createServerFn({ method: 'POST' }) .validator(ops.generateInterface.input) - .handler(({ data }) => invokeOp('generateInterface', data, req())) + .handler(async ({ data }) => invokeOp('generateInterface', data, await req())) export const getAuthSession = createServerFn({ method: 'GET' }) .validator(ops.getAuthSession.input) - .handler(({ data }) => invokeOp('getAuthSession', data, req())) + .handler(async ({ data }) => invokeOp('getAuthSession', data, await req())) export const listDocumentSummaries = createServerFn({ method: 'GET' }) .validator(ops.listDocumentSummaries.input) - .handler(({ data }) => invokeOp('listDocumentSummaries', data, req())) + .handler(async ({ data }) => + invokeOp('listDocumentSummaries', data, await req()), + ) export const getDocument = createServerFn({ method: 'GET' }) .validator(ops.getDocument.input) - .handler(({ data }) => invokeOp('getDocument', data, req())) + .handler(async ({ data }) => invokeOp('getDocument', data, await req())) export const getPublicDocument = createServerFn({ method: 'GET' }) .validator(ops.getPublicDocument.input) - .handler(({ data }) => invokeOp('getPublicDocument', data, req())) + .handler(async ({ data }) => invokeOp('getPublicDocument', data, await req())) export const listPublishedDocuments = createServerFn({ method: 'GET' }) .validator(ops.listPublishedDocuments.input) - .handler(({ data }) => invokeOp('listPublishedDocuments', data, req())) + .handler(async ({ data }) => + invokeOp('listPublishedDocuments', data, await req()), + ) export const getDocEditorMeta = createServerFn({ method: 'GET' }) .validator(ops.getDocEditorMeta.input) - .handler(({ data }) => invokeOp('getDocEditorMeta', data, req())) + .handler(async ({ data }) => invokeOp('getDocEditorMeta', data, await req())) export const restoreDocRevision = createServerFn({ method: 'POST' }) .validator(ops.restoreDocRevision.input) - .handler(({ data }) => invokeOp('restoreDocRevision', data, req())) + .handler(async ({ data }) => + invokeOp('restoreDocRevision', data, await req()), + ) export const saveDoc = createServerFn({ method: 'POST' }) .validator(ops.saveDoc.input) - .handler(({ data }) => invokeOp('saveDoc', data, req())) + .handler(async ({ data }) => invokeOp('saveDoc', data, await req())) export const discardDraft = createServerFn({ method: 'POST' }) .validator(ops.discardDraft.input) - .handler(({ data }) => invokeOp('discardDraft', data, req())) + .handler(async ({ data }) => invokeOp('discardDraft', data, await req())) export const resolveRedirect = createServerFn({ method: 'GET' }) .validator(ops.resolveRedirect.input) - .handler(({ data }) => invokeOp('resolveRedirect', data, req())) + .handler(async ({ data }) => invokeOp('resolveRedirect', data, await req())) export const createDoc = createServerFn({ method: 'POST' }) .validator(ops.createDoc.input) - .handler(({ data }) => invokeOp('createDoc', data, req())) + .handler(async ({ data }) => invokeOp('createDoc', data, await req())) export const deleteDoc = createServerFn({ method: 'POST' }) .validator(ops.deleteDoc.input) - .handler(({ data }) => invokeOp('deleteDoc', data, req())) + .handler(async ({ data }) => invokeOp('deleteDoc', data, await req())) export const restoreDoc = createServerFn({ method: 'POST' }) .validator(ops.restoreDoc.input) - .handler(({ data }) => invokeOp('restoreDoc', data, req())) + .handler(async ({ data }) => invokeOp('restoreDoc', data, await req())) export const purgeDoc = createServerFn({ method: 'POST' }) .validator(ops.purgeDoc.input) - .handler(({ data }) => invokeOp('purgeDoc', data, req())) + .handler(async ({ data }) => invokeOp('purgeDoc', data, await req())) export const bulkDocuments = createServerFn({ method: 'POST' }) .validator(ops.bulkDocuments.input) - .handler(({ data }) => invokeOp('bulkDocuments', data, req())) + .handler(async ({ data }) => invokeOp('bulkDocuments', data, await req())) export const proposeEdit = createServerFn({ method: 'POST' }) .validator(ops.proposeEdit.input) - .handler(({ data }) => invokeOp('proposeEdit', data, req())) + .handler(async ({ data }) => invokeOp('proposeEdit', data, await req())) export const reviewSnapshot = createServerFn({ method: 'GET' }) .validator(ops.reviewSnapshot.input) - .handler(({ data }) => invokeOp('reviewSnapshot', data, req())) + .handler(async ({ data }) => invokeOp('reviewSnapshot', data, await req())) export const approveChange = createServerFn({ method: 'POST' }) .validator(ops.approveChange.input) - .handler(({ data }) => invokeOp('approveChange', data, req())) + .handler(async ({ data }) => invokeOp('approveChange', data, await req())) export const rejectChange = createServerFn({ method: 'POST' }) .validator(ops.rejectChange.input) - .handler(({ data }) => invokeOp('rejectChange', data, req())) + .handler(async ({ data }) => invokeOp('rejectChange', data, await req())) export const agentChat = createServerFn({ method: 'POST' }) .validator(ops.agentChat.input) - .handler(({ data }) => invokeOp('agentChat', data, req())) + .handler(async ({ data }) => invokeOp('agentChat', data, await req())) export const editPageBlocks = createServerFn({ method: 'POST' }) .validator(ops.editPageBlocks.input) - .handler(({ data }) => invokeOp('editPageBlocks', data, req())) + .handler(async ({ data }) => invokeOp('editPageBlocks', data, await req())) export const editBlockWithAi = createServerFn({ method: 'POST' }) .validator(ops.editBlockWithAi.input) - .handler(({ data }) => invokeOp('editBlockWithAi', data, req())) + .handler(async ({ data }) => invokeOp('editBlockWithAi', data, await req())) export const editFieldWithAi = createServerFn({ method: 'POST' }) .validator(ops.editFieldWithAi.input) - .handler(({ data }) => invokeOp('editFieldWithAi', data, req())) + .handler(async ({ data }) => invokeOp('editFieldWithAi', data, await req())) export const savePageBlocks = createServerFn({ method: 'POST' }) .validator(ops.savePageBlocks.input) - .handler(({ data }) => invokeOp('savePageBlocks', data, req())) + .handler(async ({ data }) => invokeOp('savePageBlocks', data, await req())) export const listApiKeys = createServerFn({ method: 'GET' }) .validator(ops.listApiKeys.input) - .handler(({ data }) => invokeOp('listApiKeys', data, req())) + .handler(async ({ data }) => invokeOp('listApiKeys', data, await req())) export const createApiKey = createServerFn({ method: 'POST' }) .validator(ops.createApiKey.input) - .handler(({ data }) => invokeOp('createApiKey', data, req())) + .handler(async ({ data }) => invokeOp('createApiKey', data, await req())) export const revokeApiKey = createServerFn({ method: 'POST' }) .validator(ops.revokeApiKey.input) - .handler(({ data }) => invokeOp('revokeApiKey', data, req())) + .handler(async ({ data }) => invokeOp('revokeApiKey', data, await req())) export const createPreviewToken = createServerFn({ method: 'POST' }) .validator(ops.createPreviewToken.input) - .handler(({ data }) => invokeOp('createPreviewToken', data, req())) + .handler(async ({ data }) => + invokeOp('createPreviewToken', data, await req()), + ) export const revokePreviewToken = createServerFn({ method: 'POST' }) .validator(ops.revokePreviewToken.input) - .handler(({ data }) => invokeOp('revokePreviewToken', data, req())) + .handler(async ({ data }) => + invokeOp('revokePreviewToken', data, await req()), + ) export const getPreviewDocument = createServerFn({ method: 'GET' }) .validator(ops.getPreviewDocument.input) - .handler(({ data }) => invokeOp('getPreviewDocument', data, req())) + .handler(async ({ data }) => + invokeOp('getPreviewDocument', data, await req()), + ) export const listUserRoleMappings = createServerFn({ method: 'GET' }) .validator(ops.listUserRoleMappings.input) - .handler(({ data }) => invokeOp('listUserRoleMappings', data, req())) + .handler(async ({ data }) => + invokeOp('listUserRoleMappings', data, await req()), + ) export const setUserRole = createServerFn({ method: 'POST' }) .validator(ops.setUserRole.input) - .handler(({ data }) => invokeOp('setUserRole', data, req())) + .handler(async ({ data }) => invokeOp('setUserRole', data, await req())) export const removeUserRole = createServerFn({ method: 'POST' }) .validator(ops.removeUserRole.input) - .handler(({ data }) => invokeOp('removeUserRole', data, req())) + .handler(async ({ data }) => invokeOp('removeUserRole', data, await req())) export const listDbUsers = createServerFn({ method: 'GET' }) .validator(ops.listDbUsers.input) - .handler(({ data }) => invokeOp('listDbUsers', data, req())) + .handler(async ({ data }) => invokeOp('listDbUsers', data, await req())) export const createDbUser = createServerFn({ method: 'POST' }) .validator(ops.createDbUser.input) - .handler(({ data }) => invokeOp('createDbUser', data, req())) + .handler(async ({ data }) => invokeOp('createDbUser', data, await req())) export const setDbUserDisabled = createServerFn({ method: 'POST' }) .validator(ops.setDbUserDisabled.input) - .handler(({ data }) => invokeOp('setDbUserDisabled', data, req())) + .handler(async ({ data }) => invokeOp('setDbUserDisabled', data, await req())) export const listComments = createServerFn({ method: 'GET' }) .validator(ops.listComments.input) - .handler(({ data }) => invokeOp('listComments', data, req())) + .handler(async ({ data }) => invokeOp('listComments', data, await req())) export const resolveComment = createServerFn({ method: 'POST' }) .validator(ops.resolveComment.input) - .handler(({ data }) => invokeOp('resolveComment', data, req())) + .handler(async ({ data }) => invokeOp('resolveComment', data, await req())) export const deleteComment = createServerFn({ method: 'POST' }) .validator(ops.deleteComment.input) - .handler(({ data }) => invokeOp('deleteComment', data, req())) + .handler(async ({ data }) => invokeOp('deleteComment', data, await req())) export const listActivityLog = createServerFn({ method: 'GET' }) .validator(ops.listActivityLog.input) - .handler(({ data }) => invokeOp('listActivityLog', data, req())) + .handler(async ({ data }) => invokeOp('listActivityLog', data, await req())) export const listUploadedMedia = createServerFn({ method: 'GET' }) .validator(ops.listUploadedMedia.input) - .handler(({ data }) => invokeOp('listUploadedMedia', data, req())) + .handler(async ({ data }) => invokeOp('listUploadedMedia', data, await req())) export const getUploadedMedia = createServerFn({ method: 'GET' }) .validator(ops.getUploadedMedia.input) - .handler(({ data }) => invokeOp('getUploadedMedia', data, req())) + .handler(async ({ data }) => invokeOp('getUploadedMedia', data, await req())) export const getMediaUsage = createServerFn({ method: 'GET' }) .validator(ops.getMediaUsage.input) - .handler(({ data }) => invokeOp('getMediaUsage', data, req())) + .handler(async ({ data }) => invokeOp('getMediaUsage', data, await req())) export const updateUploadedMedia = createServerFn({ method: 'POST' }) .validator(ops.updateUploadedMedia.input) - .handler(({ data }) => invokeOp('updateUploadedMedia', data, req())) + .handler(async ({ data }) => + invokeOp('updateUploadedMedia', data, await req()), + ) export const deleteUploadedMedia = createServerFn({ method: 'POST' }) .validator(ops.deleteUploadedMedia.input) - .handler(({ data }) => invokeOp('deleteUploadedMedia', data, req())) + .handler(async ({ data }) => + invokeOp('deleteUploadedMedia', data, await req()), + ) export const uploadImage = createServerFn({ method: 'POST' }) .validator(ops.uploadImage.input) - .handler(({ data }) => invokeOp('uploadImage', data, req())) + .handler(async ({ data }) => invokeOp('uploadImage', data, await req())) export const uploadMedia = createServerFn({ method: 'POST' }) .validator(ops.uploadMedia.input) - .handler(({ data }) => invokeOp('uploadMedia', data, req())) + .handler(async ({ data }) => invokeOp('uploadMedia', data, await req())) export const aiImage = createServerFn({ method: 'POST' }) .validator(ops.aiImage.input) - .handler(({ data }) => invokeOp('aiImage', data, req())) + .handler(async ({ data }) => invokeOp('aiImage', data, await req())) /** Extra per-call options the Start fetcher accepts alongside `data`. */ type CallOpFetchOptions = { @@ -298,8 +353,8 @@ export interface CallOp { export const callOp = createServerFn({ method: 'POST' }) // oxlint-disable-line eslint-js/no-restricted-syntax -- serverFn's inferred type can't structurally match the hand-written CallOp overload; input/output are validated at runtime. .validator(z.object({ name: z.string(), input: z.unknown().optional() })) .handler( - ({ data }) => - invokeAnyOp(data.name, data.input, req()) as Promise, + async ({ data }) => + invokeAnyOp(data.name, data.input, await req()) as Promise, ) as unknown as CallOp // Runtime helpers (`ops`, `invokeOp`, …) come from `@tanstack/cms-api`. This diff --git a/packages/api/tests/access-context.test.ts b/packages/api/tests/access-context.test.ts new file mode 100644 index 00000000..212b1fbe --- /dev/null +++ b/packages/api/tests/access-context.test.ts @@ -0,0 +1,101 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { + accessContext, + commitDocument, + publicContext, + resolveSession, + systemContext, +} from '@tanstack/cms-core/server' +import { createCmsApiHandler } from '../src/http' +import { READ_MODE_HEADER, invokeOp, requestAccessContext } from '../src/ops' +import { cleanup, req, setupCms } from './helpers' + +afterEach(cleanup) + +async function seed() { + setupCms() + await commitDocument('post', 'live', { title: 'Live', published: true }) + await commitDocument('post', 'draft', { title: 'Draft', published: false }) +} + +const ids = (result: { items: Array<{ id: string }> }) => + result.items.map((i) => i.id).sort() + +describe('request access contexts', () => { + it('reads the session, the requested mode, and defaults to edit', async () => { + setupCms() + const editor = await requestAccessContext(req('/', { role: 'editor' })) + expect(editor.actor).toEqual({ + kind: 'user', + id: 'u-editor', + role: 'editor', + }) + expect(editor.mode).toBe('edit') + + const narrowed = await requestAccessContext( + req('/', { role: 'editor', headers: { [READ_MODE_HEADER]: 'live' } }), + ) + expect(narrowed.mode).toBe('live') + expect( + (await requestAccessContext(req('/'), { defaultMode: 'live' })).actor, + ).toEqual({ kind: 'public' }) + await expect( + requestAccessContext( + req('/', { headers: { [READ_MODE_HEADER]: 'everything' } }), + ), + ).rejects.toThrow(/Unknown read mode/) + }) + + it('x-cms-read-mode narrows a public read over HTTP', async () => { + await seed() + const handler = createCmsApiHandler() + const list = async (headers: Record = {}) => { + const res = await handler( + req('/api/cms/v1/ops/listPublishedDocuments', { + method: 'POST', + role: 'editor', + headers: { 'content-type': 'application/json', ...headers }, + body: JSON.stringify({ collection: 'post' }), + }), + ) + return ids( + ((await res.json()) as { result: { items: Array<{ id: string }> } }) + .result, + ) + } + expect(await list()).toEqual(['draft', 'live']) + expect(await list({ [READ_MODE_HEADER]: 'live' })).toEqual(['live']) + }) + + it('ops read as the context the host passes', async () => { + await seed() + const session = await resolveSession(req('/', { role: 'editor' })) + const read = (access: Parameters[0]) => + invokeOp( + 'listPublishedDocuments', + { collection: 'post', limit: 50, offset: 0 }, + { access: accessContext(access) }, + ) + expect(ids(await read({ session, mode: 'edit' }))).toEqual([ + 'draft', + 'live', + ]) + expect(ids(await read({ session, mode: 'live' }))).toEqual(['live']) + expect( + ids( + await invokeOp( + 'listPublishedDocuments', + { collection: 'post', limit: 50, offset: 0 }, + { access: publicContext() }, + ), + ), + ).toEqual(['live']) + await expect( + invokeOp( + 'listPublishedDocuments', + { collection: 'post', limit: 50, offset: 0 }, + { access: systemContext('test') }, + ), + ).rejects.toThrow(/session/) + }) +}) diff --git a/packages/client/src/client.ts b/packages/client/src/client.ts index 38ed7e86..b2d054ab 100644 --- a/packages/client/src/client.ts +++ b/packages/client/src/client.ts @@ -26,10 +26,14 @@ import type { RegisteredOpName, RegisteredOpOutput, } from '@tanstack/cms-core' +import type { ReadMode } from '@tanstack/cms-core/server' /** Path of the versioned HTTP API this client speaks. */ export const CMS_API_PATH = '/api/cms/v1' +/** The header the client asks for its read mode with. */ +export const CMS_READ_MODE_HEADER = 'x-cms-read-mode' + export interface CmsClientOptions { /** Origin (plus any mount prefix) of the API handler, e.g. `https://cms.example.com`. */ baseUrl: string @@ -42,6 +46,13 @@ export interface CmsClientOptions { * per request so tokens can rotate. */ getAuthHeader?: () => string | undefined | Promise + /** + * The read mode every call asks for (sent as `x-cms-read-mode`): `live` + * reads published documents only, `edit` the working copy (drafts the + * caller may read). The server narrows it to what the caller may see. + * Default: the server's (`edit`, so CMS readers see drafts). + */ + mode?: ReadMode } export interface CmsApiResponse { @@ -108,6 +119,8 @@ export interface CmsCollectionClient { export interface CmsClient { readonly cacheScope?: string + /** The read mode the client asks for, when set. */ + readonly mode?: ReadMode /** * Call a CMS operation by name. POSTs a JSON body to * `/api/cms/v1/ops/:name`. Fully typed per operation. @@ -149,6 +162,9 @@ export function createCmsClient(options: CmsClientOptions): CmsClient { const headers = new Headers(init.headers) const auth = await options.getAuthHeader?.() if (auth) headers.set('Authorization', auth) + if (options.mode && !headers.has(CMS_READ_MODE_HEADER)) { + headers.set(CMS_READ_MODE_HEADER, options.mode) + } return doFetch(`${baseUrl}${path}`, { ...init, headers }) } @@ -223,5 +239,6 @@ export function createCmsClient(options: CmsClientOptions): CmsClient { call, collection, cacheScope: options.cacheScope, + ...(options.mode && { mode: options.mode }), } } diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index d6d54543..8cbac47f 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -1,7 +1,12 @@ /** * `@tanstack/cms-client` — framework-agnostic typed fetch client for the CMS API. */ -export { createCmsClient, CmsApiError, CMS_API_PATH } from './client' +export { + createCmsClient, + CmsApiError, + CMS_API_PATH, + CMS_READ_MODE_HEADER, +} from './client' export type { CmsClient, CmsClientOptions, diff --git a/packages/client/src/keys.ts b/packages/client/src/keys.ts index ac2a43d8..b9fe93af 100644 --- a/packages/client/src/keys.ts +++ b/packages/client/src/keys.ts @@ -9,7 +9,9 @@ * * - `scope` is taken from `cms.cacheScope` when set, or derived from the * `CmsClient` object identity so that two clients pointing at different - * APIs cannot collide inside the same `QueryClient`. + * APIs cannot collide inside the same `QueryClient`. A client with a read + * `mode` appends it (`:live`), so live and edit reads never share + * an entry. */ import type { CmsClient } from './client' @@ -29,7 +31,7 @@ export function collectionKey( scope = `client:${++nextClientScope}` clientScopes.set(cms, scope) } - return ['cms', scope, collection] + return ['cms', cms.mode ? `${scope}:${cms.mode}` : scope, collection] } /** diff --git a/packages/client/tests/client.test.ts b/packages/client/tests/client.test.ts index db8833cb..0933884c 100644 --- a/packages/client/tests/client.test.ts +++ b/packages/client/tests/client.test.ts @@ -6,6 +6,8 @@ import { defineCms } from '@tanstack/cms-core' import { closeStore, commitDocument } from '@tanstack/cms-core/server' import { createCmsApiHandler } from '@tanstack/cms-api' import { CmsApiError, createCmsClient } from '../src/index' +import { collectionKey } from '../src/keys' +import type { CmsClientOptions } from '../src/index' let dataDir = '' const handler = createCmsApiHandler() @@ -39,12 +41,13 @@ afterEach(async () => { rmSync(dataDir, { recursive: true, force: true }) }) -function client(auth?: string) { +function client(auth?: string, extra: Partial = {}) { return createCmsClient({ baseUrl: 'http://cms.test/', fetch: (input, init) => handler(new Request(input as string, init as RequestInit)), getAuthHeader: () => auth, + ...extra, }) } @@ -57,6 +60,20 @@ describe('createCmsClient', () => { expect(items[0]).toMatchObject({ id: 'a', doc: { title: 'A' } }) }) + it('asks for its read mode and keys its cache by it', async () => { + await commitDocument('post', 'a', { title: 'A', published: true }) + await commitDocument('post', 'b', { title: 'B', published: false }) + const editor = client('Bearer editor') + expect((await editor.collection('post').published()).total).toBe(2) + const live = client('Bearer editor', { mode: 'live', cacheScope: 'site' }) + expect(live.mode).toBe('live') + expect((await live.collection('post').published()).total).toBe(1) + expect(collectionKey(live, 'post')).toEqual(['cms', 'site:live', 'post']) + expect( + collectionKey(client(undefined, { cacheScope: 'site' }), 'post'), + ).toEqual(['cms', 'site', 'post']) + }) + it('surfaces structured errors', async () => { const err = await client() .collection('post') diff --git a/packages/core/src/events.ts b/packages/core/src/events.ts index 971d04c2..f87bad12 100644 --- a/packages/core/src/events.ts +++ b/packages/core/src/events.ts @@ -12,6 +12,7 @@ * declares `eventHandlers` stays importable in the browser bundle; the handler * runtime lives server-side. */ +import type { AccessContext } from './lib/access-context' import type { Doc, JsonValue } from './schema' /** Events about a single document's lifecycle (all carry a full snapshot). */ @@ -87,6 +88,12 @@ export interface CmsEventEnvelope { export interface ScopedCmsClient { /** The actor writes are attributed to (default `system`). */ readonly actor: string + /** + * The context the client reads with: a system context naming the handler. + * Pass it to the store's `…As` verbs or `cmsAs(cms, access)` for reads the + * client doesn't cover. + */ + readonly access: AccessContext /** Read a committed document (null when absent). */ readDocument: (collection: string, id: string) => Promise /** List committed documents in a collection. */ @@ -116,6 +123,8 @@ export interface ScopedCmsClient { export interface EventHandlerContext { event: CmsEventEnvelope cms: ScopedCmsClient + /** The handler's access context (the same one as `cms.access`). */ + access: AccessContext } /** diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index fb4b99ac..7d74f6dc 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -161,6 +161,7 @@ export type { CollectionRoles, CollectionHooks, ChangeHookArgs, + ReadHookArgs, ContentMigration, SystemMetadata, InferFieldValue, diff --git a/packages/core/src/lib/access-context.ts b/packages/core/src/lib/access-context.ts new file mode 100644 index 00000000..4089f28f --- /dev/null +++ b/packages/core/src/lib/access-context.ts @@ -0,0 +1,51 @@ +/** + * The access context's shape: who is reading, with which permissions, and in + * which read mode. Types only, so client-safe modules (operation and hook + * signatures) can name it; the builders live in `@tanstack/cms-core/server`. + */ +import type { Permission } from './access' +import type { CmsSession } from './auth' + +/** + * - `live`: only published documents (`published` is true). + * - `preview`: drafts too, with staged changes overlaid where a read supports it. + * - `edit`: the working copy, as the editor and agents see it. + */ +export type ReadMode = 'live' | 'preview' | 'edit' + +/** + * Who is reading. Derived from today's `CmsSession` (role plus the optional + * `session.agent`) for `user`, `agent` and `public`; the trusted kinds + * (`system`, `scheduler`, `import`) carry the reason they were built with. + */ +export type AccessActor = + | { kind: 'public' } + | { kind: 'user'; id: string | null; role: string | null } + | { kind: 'agent'; agent: string; id: string | null; role: string | null } + | { kind: 'system'; reason: string } + | { kind: 'scheduler'; reason: string } + | { kind: 'import'; reason: string } + | { kind: 'preview'; tokenId: string } + +/** The kinds of trusted actor `systemContext` can build. */ +export type TrustedActorKind = 'system' | 'scheduler' | 'import' + +/** + * Everything a read derives its visibility and redaction from. Build one + * with `publicContext()`, `accessContext({ session })`, + * `systemContext(reason)` or `previewTokenContext(…)`; never by hand. + */ +export interface AccessContext { + readonly actor: AccessActor + readonly permissions: ReadonlyArray + readonly mode: ReadMode + /** + * The session collection and field rules are checked against. Absent for + * trusted and preview contexts, which bypass the rules. + */ + readonly session?: CmsSession + /** Published documents are readable whatever the collection's read rule. */ + readonly publicRead: boolean + /** A preview context sees this one document and nothing else. */ + readonly scope?: { readonly collection: string; readonly docId: string } +} diff --git a/packages/core/src/ops.ts b/packages/core/src/ops.ts index 3263eda5..315beb0c 100644 --- a/packages/core/src/ops.ts +++ b/packages/core/src/ops.ts @@ -17,6 +17,7 @@ import { z } from 'zod' import { getCmsConfig } from './config' import { CmsError } from './errors' import type { Permission } from './lib/access' +import type { AccessContext } from './lib/access-context' import type { CmsSession } from './lib/auth' import type { InferStandardInput, @@ -45,6 +46,13 @@ export interface CmsOpContext { /** The incoming request, when the transport has one. */ request?: Request session: CmsSession + /** + * The caller's access context, built once per call by the transport (from + * `resolveSession(request)`, or the host's own context). Read with it + * (`cmsAs(cms, ctx.access)` or the store's `…As` verbs) instead of + * re-checking `session` by hand. + */ + access: AccessContext /** * Who is calling, recorded on staged writes: `human` (admin and Start * server functions), `api` (HTTP), or an agent surface (`content-agent`, diff --git a/packages/core/src/schema.ts b/packages/core/src/schema.ts index ccff6e7f..d6a07163 100644 --- a/packages/core/src/schema.ts +++ b/packages/core/src/schema.ts @@ -18,6 +18,7 @@ import { z } from 'zod' import { contentLocales, getCmsConfig } from './config' import type { CollectionAccess, FieldAccess } from './lib/access' +import type { AccessContext } from './lib/access-context' import type { StorageAdapter } from './storage/types' import { isBuiltInFieldType } from './lib/authoring' @@ -348,6 +349,14 @@ export interface ChangeHookArgs { actor: string } +/** What a `postRead` hook receives. */ +export interface ReadHookArgs { + doc: TDoc + id: string + /** The context the document is being read with. */ + access: AccessContext +} + /** * Collection lifecycle hooks: the pre-commit consultation. A hook is the * engine asking "we're about to go into the game: anything you want to make us @@ -379,8 +388,12 @@ export interface CollectionHooks { * `defineEventHandler` in `defineCms({ eventHandlers })`. Removed before 1.0. */ afterChange?: (args: ChangeHookArgs) => MaybePromise - /** After a read, before the response; transforms the response only, never stored. */ - postRead?: (args: { doc: TDoc; id: string }) => MaybePromise + /** + * After a read, before the response; transforms the response only, never + * stored. `access` is the reading context (who reads, in which mode), so a + * hook can tailor the response without reaching for the request. + */ + postRead?: (args: ReadHookArgs) => MaybePromise /** Before a delete transaction; throw to veto. */ preDelete?: (args: { id: string; actor: string }) => MaybePromise /** diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index 750a8393..7c5b5477 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -245,8 +245,57 @@ export type { ContentMigrationStatus, MigrateContentOptions, } from './server/content-migrations' +// Access contexts: who reads, with which permissions, in which mode. +export { + publicContext, + accessContext, + systemContext, + previewContext, + previewTokenContext, + withMode, + isAccessContext, + parseReadMode, + canReadCollection, + canReadDocument, + assertReadable, + redactFor, +} from './server/access-context' +export type { + AccessActor, + AccessContext, + ReadMode, + TrustedActorKind, +} from './server/access-context' +export { cmsAs } from './server/cms-as' +export type { CmsReads } from './server/cms-as' +// The read verbs' context forms, underneath `cmsAs`. +export { + queryDocumentsAs, + groupDocumentsAs, + queryDocumentSummariesAs, + listDocumentsAs, + readDocumentAs, + readDocumentWithPendingAs, + readSingletonAs, + readDocumentBySlugAs, + findDocumentBySlugAs, + populateRelationsAs, + findReferencesAs, + listTranslationsAs, + listRevisionsAs, +} from './server/store' +export type { + ContextQueryOptions, + DocumentWithPending, + ListDocumentsOptions, +} from './server/store' export { agentOps, runOp } from './server/cms-ops' -export { cmsTools, listSkills, proposeSkillInstall } from './server/cms-tools' +export { + cmsTools, + listSkills, + proposeSkillInstall, + CMS_ACCESS_KEY, +} from './server/cms-tools' export type { CoreSkillSummary, CmsToolsOptions } from './server/cms-tools' export { isMissingModule, loadTanstackAi, missingPeer } from './server/optional' export { diff --git a/packages/core/src/server/access-context.ts b/packages/core/src/server/access-context.ts index 9fd84e2f..cebac884 100644 --- a/packages/core/src/server/access-context.ts +++ b/packages/core/src/server/access-context.ts @@ -4,12 +4,10 @@ * storage `publishedOnly` filter, collection and document read rules) and its * field redaction from a context, here and nowhere else. * - * Builders never read the request; the host builds the context. The legacy - * read signatures (`session` / `publishedOnly` / `publicRead`) are mapped onto - * a context by `legacyReadContext`, so they behave exactly as before. - * - * @internal Not exported from any package entry yet: the public shape (and - * the actor inside it) is fixed once authentication and actors are reviewed. + * Builders never read the request; the host builds the context, usually from + * `resolveSession(request)`. The legacy read signatures (`session` / + * `publishedOnly` / `publicRead`) are mapped onto a context by + * `legacyReadContext`, so they behave exactly as before. * * Server-only. */ @@ -19,7 +17,12 @@ import { PERMISSIONS, canAccessCollection } from '../lib/access' import { UNAUTHENTICATED_SESSION } from '../lib/auth' import { collectionHasReadRules, redactDoc } from './access' import { verifyPreviewToken } from './preview-tokens' -import type { Permission } from '../lib/access' +import type { + AccessActor, + AccessContext, + ReadMode, + TrustedActorKind, +} from '../lib/access-context' import type { CmsSession } from '../lib/auth' import type { Doc } from '../schema' import type { @@ -29,52 +32,39 @@ import type { } from '../storage/types' import type { PreviewTokenRecord } from './preview-tokens' -/** - * - `live`: only published documents (`published` is true). - * - `preview`: drafts too, with staged changes overlaid where a read supports it. - * - `edit`: the working copy, as the editor and agents see it. - * - * @internal - */ -export type ReadMode = 'live' | 'preview' | 'edit' - -/** - * Who is reading. - * - * @internal Provisional: derived from today's `CmsSession` (role plus the - * optional `session.agent`) until the actor model is decided. - */ -export type AccessActor = - | { kind: 'public' } - | { - kind: 'user' - id: string | null - role: string | null - agent?: string - } - | { kind: 'system'; reason: string } - | { kind: 'preview'; tokenId: string } - -/** @internal */ -export interface AccessContext { - readonly actor: AccessActor - readonly permissions: ReadonlyArray - readonly mode: ReadMode - /** - * The session collection and field rules are checked against. Absent for - * system and preview contexts, which bypass the rules. - */ - readonly session?: CmsSession - /** Published documents are readable whatever the collection's read rule. */ - readonly publicRead: boolean - /** A preview context sees this one document and nothing else. */ - readonly scope?: { readonly collection: string; readonly docId: string } -} +export type { + AccessActor, + AccessContext, + ReadMode, + TrustedActorKind, +} from '../lib/access-context' const READ_MODES: ReadonlyArray = ['live', 'preview', 'edit'] +const TRUSTED_KINDS: ReadonlyArray = [ + 'system', + 'scheduler', + 'import', +] + +const built = new WeakSet() function frozen(ctx: AccessContext): AccessContext { - return Object.freeze(ctx) + const out = Object.freeze(ctx) + built.add(out) + return out +} + +/** + * Whether `value` is a context one of the builders made. Use it where a + * context arrives untyped (a tool call's runtime context, say); a + * hand-written object never passes. + */ +export function isAccessContext(value: unknown): value is AccessContext { + return ( + typeof value === 'object' && + value !== null && + built.has(value as AccessContext) + ) } function assertMode(mode: ReadMode): ReadMode { @@ -84,11 +74,17 @@ function assertMode(mode: ReadMode): ReadMode { return mode } +/** Parse an untrusted read mode (a header, a query param), or `undefined`. */ +export function parseReadMode( + value: string | null | undefined, +): ReadMode | undefined { + if (value === null || value === undefined || value === '') return undefined + return assertMode(value as ReadMode) +} + /** * An anonymous visitor: published documents only, with the field rules an * unauthenticated session gets. - * - * @internal */ export function publicContext(): AccessContext { return frozen({ @@ -100,28 +96,36 @@ export function publicContext(): AccessContext { }) } +function sessionActor( + session: CmsSession, + agent: string | undefined, +): AccessActor { + if (!session.isAuthenticated) return { kind: 'public' } + const id = session.user?.id ?? null + const role = session.role + const name = agent ?? session.agent + return name + ? { kind: 'agent', agent: name, id, role } + : { kind: 'user', id, role } +} + /** - * Read as `session`. `mode` defaults to `live`, so drafts are an explicit - * opt-in. `publicRead` also lets the session see published documents of - * collections its read rule would hide. - * - * @internal + * Read as `session`, typically `await resolveSession(request)`. `mode` + * defaults to `live`, so drafts are an explicit opt-in. `agent` names the + * agent acting with this session (it defaults to `session.agent`), which + * makes the actor an `agent`. `publicRead` also lets the session see + * published documents of collections its read rule would hide, as the public + * site does. */ export function accessContext(args: { session: CmsSession mode?: ReadMode + agent?: string publicRead?: boolean }): AccessContext { const { session } = args return frozen({ - actor: session.isAuthenticated - ? { - kind: 'user', - id: session.user?.id ?? null, - role: session.role, - ...(session.agent ? { agent: session.agent } : {}), - } - : { kind: 'public' }, + actor: sessionActor(session, args.agent), permissions: [...session.permissions], mode: assertMode(args.mode ?? 'live'), session, @@ -131,14 +135,13 @@ export function accessContext(args: { /** * A trusted read that bypasses every access rule: seeds, migrations, the - * scheduler, scripts. `reason` is required so each use is greppable and - * reviewable. `mode` defaults to `edit`. - * - * @internal + * scheduler, imports, scripts, event handlers. `reason` is required so each + * use is greppable and reviewable. `mode` defaults to `edit`; `actor` names + * the trusted actor (`system` by default, or `scheduler` / `import`). */ export function systemContext( reason: string, - options?: { mode?: ReadMode }, + options?: { mode?: ReadMode; actor?: TrustedActorKind }, ): AccessContext { if (typeof reason !== 'string' || !reason.trim()) { throw new CmsError( @@ -146,8 +149,15 @@ export function systemContext( 'VALIDATION_FAILED', ) } + const kind = options?.actor ?? 'system' + if (!TRUSTED_KINDS.includes(kind)) { + throw new CmsError( + `Unknown trusted actor: ${String(kind)}`, + 'VALIDATION_FAILED', + ) + } return frozen({ - actor: { kind: 'system', reason: reason.trim() }, + actor: { kind, reason: reason.trim() }, permissions: [...PERMISSIONS], mode: assertMode(options?.mode ?? 'edit'), publicRead: false, @@ -157,8 +167,6 @@ export function systemContext( /** * The holder of a verified preview token: the token's one document, drafts * and staged changes included, returned as stored. - * - * @internal */ export function previewContext(record: PreviewTokenRecord): AccessContext { return frozen({ @@ -176,8 +184,6 @@ export function previewContext(record: PreviewTokenRecord): AccessContext { /** * Verify `token` for `collection`/`docId` and build its preview context, or * `null` when the token is unknown, expired, revoked, or bound elsewhere. - * - * @internal */ export async function previewTokenContext( token: string | null | undefined, @@ -188,6 +194,15 @@ export async function previewTokenContext( return verified.ok ? previewContext(verified.record) : null } +/** + * `ctx` reading in another mode, with the same actor and rules. Switching + * mode never widens access: drafts stay subject to the read rules. + */ +export function withMode(ctx: AccessContext, mode: ReadMode): AccessContext { + if (ctx.mode === mode) return ctx + return frozen({ ...ctx, mode: assertMode(mode) }) +} + /** * The context today's read signatures describe. With no session the store * skips access entirely, which is a system read. @@ -220,7 +235,7 @@ export function bypassingContext( /** `ctx` without `publicRead`. @internal */ export function withoutPublicRead(ctx: AccessContext): AccessContext { - return ctx.publicRead ? Object.freeze({ ...ctx, publicRead: false }) : ctx + return ctx.publicRead ? frozen({ ...ctx, publicRead: false }) : ctx } // ---- Derivation --------------------------------------------------------- @@ -249,8 +264,6 @@ function collectionOf(name: string) { /** * Whether `ctx` may read some documents of `collectionName` (before any * per-document rule). - * - * @internal */ export function canReadCollection( ctx: AccessContext, @@ -267,8 +280,6 @@ export function canReadCollection( /** * Whether `ctx` may read one stored document. `doc` is what the collection's * read rule sees; `published` is the stored publish state. - * - * @internal */ export function canReadDocument( ctx: AccessContext, @@ -288,7 +299,7 @@ export function canReadDocument( ) } -/** Remove the fields `ctx` may not read. @internal */ +/** Remove the fields `ctx` may not read. */ export function redactFor( ctx: AccessContext, collectionName: string, @@ -297,6 +308,31 @@ export function redactFor( return ctx.session ? redactDoc(collectionName, doc, ctx.session) : doc } +/** + * Throw unless `ctx` may read `collectionName` (or, given `row`, that one + * document): `UNAUTHORIZED` for an anonymous session, `FORBIDDEN` otherwise. + * Reads that should answer "not found" instead use the `…As` verbs, which + * return `null` for what `ctx` can't see. + */ +export function assertReadable( + ctx: AccessContext, + collectionName: string, + row?: { id: string; doc: Doc | null | undefined; published?: boolean }, +): void { + const ok = row + ? canReadDocument(ctx, collectionName, { + id: row.id, + published: row.published ?? false, + doc: row.doc, + }) + : canReadCollection(ctx, collectionName) + if (ok) return + if (ctx.session && !ctx.session.isAuthenticated) { + throw new CmsError('Unauthorized: authentication required.', 'UNAUTHORIZED') + } + throw new CmsError(`Forbidden: cannot read ${collectionName}.`, 'FORBIDDEN') +} + /** * Query storage for the documents `ctx` may read. Rules storage can't * evaluate (predicate read rules, `publicRead` over a hidden collection, diff --git a/packages/core/src/server/cms-as.ts b/packages/core/src/server/cms-as.ts index 5c76061d..d77c19b2 100644 --- a/packages/core/src/server/cms-as.ts +++ b/packages/core/src/server/cms-as.ts @@ -1,14 +1,15 @@ /** - * The bound read handle: today's read verbs with an access context bound - * once, scoped to one CMS instance. + * The bound read handle: the read verbs with an access context bound once, + * scoped to one CMS instance. This is the idiom for reading content on the + * server; the store's `…As(ctx, …)` verbs are the argument form underneath. * * ```ts - * const db = cmsAs(cms, accessContext({ session })) + * const db = cmsAs(cms, accessContext({ session: await resolveSession(request) })) * await db.queryDocuments({ collection: 'post' }) * ``` * - * @internal The `cms.as(ctx)` method form waits for the public shape of the - * access context; until then this is the argument form underneath it. + * It is a function rather than a `cms.as(ctx)` method because `Cms` lives in + * the client-safe config module, which must not reach the server read verbs. * * Server-only. */ @@ -26,14 +27,15 @@ import { readDocumentWithPendingAs, readSingletonAs, } from './store/read' -import type { Cms } from '../config' +import { listRevisionsAs } from './store/revisions' +import type { Cms, ResolvedCmsConfig } from '../config' import type { AccessContext } from './access-context' type Bound = F extends (ctx: AccessContext, ...args: infer A) => infer R ? (...args: A) => R : never -/** @internal */ +/** The read verbs bound to one context (see `cmsAs`). */ export interface CmsReads { readonly context: AccessContext queryDocuments: Bound @@ -48,21 +50,35 @@ export interface CmsReads { populateRelations: Bound findReferences: Bound listTranslations: Bound + listRevisions: Bound +} + +function isCmsInstance(cms: Cms | ResolvedCmsConfig): cms is Cms { + return ( + typeof (cms as Partial).run === 'function' && + typeof (cms as Partial).register === 'function' && + 'config' in cms + ) } /** - * Bind `ctx` to `cms`'s read verbs. Every call runs with `cms`'s config in - * scope and reads with `ctx`'s visibility and redaction. - * - * @internal + * Bind `ctx` to `cms`'s read verbs. `cms` is a `createCms` instance or the + * config `defineCms` returned. Every call runs with that config in scope and + * reads with `ctx`'s visibility and redaction: a `live` context sees + * published documents only, fields `ctx` can't read are removed, and a + * document it can't see reads as missing. */ -export function cmsAs(cms: Cms, ctx: AccessContext): CmsReads { +export function cmsAs( + cms: Cms | ResolvedCmsConfig, + ctx: AccessContext, +): CmsReads { + const config = isCmsInstance(cms) ? cms.config : cms const bind = , R>( verb: (ctx: AccessContext, ...args: A) => R, ): ((...args: A) => R) => (...args) => - runInConfigScope(cms.config, () => verb(ctx, ...args)) + runInConfigScope(config, () => verb(ctx, ...args)) return Object.freeze({ context: ctx, queryDocuments: bind(queryDocumentsAs), @@ -77,5 +93,6 @@ export function cmsAs(cms: Cms, ctx: AccessContext): CmsReads { populateRelations: bind(populateRelationsAs), findReferences: bind(findReferencesAs), listTranslations: bind(listTranslationsAs), + listRevisions: bind(listRevisionsAs), }) } diff --git a/packages/core/src/server/cms-ops.ts b/packages/core/src/server/cms-ops.ts index 03f287f6..b49727eb 100644 --- a/packages/core/src/server/cms-ops.ts +++ b/packages/core/src/server/cms-ops.ts @@ -1,18 +1,26 @@ /** * Server-side handlers for the CMS operations declared in `../ops`. * - * `runOp(name, input, actor)` is the one place every agent surface funnels - * through — the content agent, the HTTP MCP server, and the `/api/cms` RPC - * (WebMCP). `actor` is recorded on staged writes so the review queue and audit - * trail show who proposed each change. + * `runOp(name, input, actor, access)` is the one place every agent surface + * funnels through — the content agent, the HTTP MCP server, and the + * `/api/cms` RPC (WebMCP). `actor` is recorded on staged writes so the review + * queue and audit trail show who proposed each change; `access` is the + * agent's context, which every read derives its visibility from. * * Server-only. */ import { CmsError } from '../errors' import { configuredOps, opSchemas, validateWithStandardSchema } from '../ops' import { getCmsConfig } from '../config' -import { canAccessCollection } from '../lib/access' -import { accessibleCollections, protectWrite, redactDoc } from './access' +import { protectWrite } from './access' +import { + accessContext, + bypassesRules, + canReadCollection, + redactFor, + systemContext, + withMode, +} from './access-context' import { assertCollectionAccess, currentSession, @@ -20,8 +28,8 @@ import { resolveSession, } from './auth' import * as store from './store' +import type { AccessContext } from './access-context' import type { CollectionAction, Permission } from '../lib/access' -import type { CmsSession } from '../lib/auth' import type { CmsOpDefinition } from '../ops' import type { Doc } from '../schema' @@ -366,8 +374,7 @@ const builtInAgentOps: ReadonlyArray = opSchemas.map( description: schema.description, input: schema.inputSchema, agent: { kind: schema.kind }, - run: (input, ctx) => - dispatch(schema.name, input, ctx.actor, currentSession()), + run: (input, ctx) => dispatch(schema.name, input, ctx.actor, ctx.access), }), ) @@ -377,22 +384,43 @@ export function agentOps(): Array { } /** - * Run an agent operation. When a session is bound (`runWithSession`, which - * every transport does), the op's permission and collection access are - * enforced, unwritable fields are preserved, and unreadable fields are - * redacted. + * The context a `runOp` call without one reads with: the session bound by + * `runWithSession` in edit mode, or a system context. + */ +function ambientOpContext(): AccessContext { + const session = currentSession() + return session + ? accessContext({ session, mode: 'edit' }) + : systemContext('runOp without a session or context') +} + +/** + * Run an agent operation as `access` (an agent's context, usually + * `accessContext({ session, agent, mode: 'edit' })`). With a session-bearing + * context the op's permission and collection access are enforced, + * unwritable fields are preserved, and unreadable fields are redacted; a + * system context bypasses the rules. Without `access`, the session bound by + * `runWithSession` is used (deprecated: pass the context). */ export async function runOp( name: string, input: unknown, actor: string, + access?: AccessContext, ): Promise { const op = agentOps().find((o) => o.name === name) if (!op) throw new CmsError(`Unknown operation: ${name}`, 'NOT_FOUND') + const ctx = access ?? ambientOpContext() + if (ctx.scope) { + throw new CmsError( + 'Forbidden: a preview context cannot run operations.', + 'FORBIDDEN', + ) + } const parsed = await validateWithStandardSchema(op.input, input ?? {}) const data = parsed as { collection?: unknown } | undefined const kind = op.agent?.kind ?? 'read' - const session = currentSession() + const session = ctx.session if (session) { if (op.access !== 'public') await requirePermission(op.access, session) if (typeof data?.collection === 'string') { @@ -415,19 +443,15 @@ export async function runOp( return op.run(data, { session: session ?? (await resolveSession()), actor, + access: ctx, }) } -function visible(session: CmsSession | undefined) { - return session ? accessibleCollections(session, 'read') : undefined -} - -function redact( - session: CmsSession | undefined, - collection: string, - doc: T, -): T { - return session ? redactDoc(collection, doc, session) : doc +function readableCollections(ctx: AccessContext): Array | undefined { + if (bypassesRules(ctx)) return undefined + return Object.keys(getCmsConfig().collections).filter((name) => + canReadCollection(ctx, name), + ) } async function dispatch( @@ -435,27 +459,28 @@ async function dispatch( // oxlint-disable-next-line no-explicit-any -- see runOp input: any, actor: string, - session: CmsSession | undefined, + ctx: AccessContext, ): Promise { + const session = ctx.session switch (name) { case 'list_collections': { - const allowed = visible(session) const all = store.listCollectionsMeta() - return allowed ? all.filter((c) => allowed.includes(c.name)) : all + return bypassesRules(ctx) + ? all + : all.filter((c) => canReadCollection(ctx, c.name)) } case 'list_documents': - return store.listDocuments(input?.collection, { + return store.listDocumentsAs(ctx, input?.collection, { locale: input?.locale, limit: input?.limit, offset: input?.offset, - collections: visible(session), - session, + collections: readableCollections(ctx), }) case 'read_document': - return redact( - session, + return redactFor( + ctx, input.collection, await readOrPending(input.collection, input.id), ) @@ -474,7 +499,7 @@ async function dispatch( }) return { ...staged(pending, QUEUED), - resultingDocument: redact(session, input.collection, pending.after), + resultingDocument: redactFor(ctx, input.collection, pending.after), } } @@ -493,7 +518,7 @@ async function dispatch( }) return { ...staged(pending, QUEUED), - resultingDocument: redact(session, input.collection, pending.after), + resultingDocument: redactFor(ctx, input.collection, pending.after), } } @@ -520,7 +545,7 @@ async function dispatch( pending, 'Restore staged for human approval in the review queue.', ), - resultingDocument: redact(session, input.collection, pending.after), + resultingDocument: redactFor(ctx, input.collection, pending.after), } } @@ -540,41 +565,24 @@ async function dispatch( ) } - case 'search_documents': { - const result = await store.queryDocuments({ - collection: input?.collection, - collections: visible(session), - query: input?.query, - locale: input?.locale, - publishedOnly: input?.publishedOnly, - where: input?.where, - sort: input?.sort, - limit: input?.limit, - offset: input?.offset, - cursor: input?.cursor, - ...(session ? { session } : {}), - }) - return result - } + case 'search_documents': + return store.queryDocumentsAs( + input?.publishedOnly ? withMode(ctx, 'live') : ctx, + { + collection: input?.collection, + collections: readableCollections(ctx), + query: input?.query, + locale: input?.locale, + where: input?.where, + sort: input?.sort, + limit: input?.limit, + offset: input?.offset, + cursor: input?.cursor, + }, + ) - case 'list_revisions': { - const revisions = await store.listRevisions(input.collection, input.id) - return session - ? revisions - .filter((r) => - canAccessCollection( - session, - getCmsConfig().collections[input.collection], - 'read', - r.doc, - ), - ) - .map((r) => ({ - ...r, - doc: redactDoc(input.collection, r.doc, session), - })) - : revisions - } + case 'list_revisions': + return store.listRevisionsAs(ctx, input.collection, input.id) case 'restore_revision': { const pending = (await store.restoreRevision( @@ -588,7 +596,7 @@ async function dispatch( pending, 'Revision restore staged for human approval in the review queue.', ), - resultingDocument: redact(session, input.collection, pending.after), + resultingDocument: redactFor(ctx, input.collection, pending.after), } } @@ -606,7 +614,7 @@ async function dispatch( } case 'list_translations': - return store.listTranslations(input.collection, input.id, session) + return store.listTranslationsAs(ctx, input.collection, input.id) case 'listSkills': return listSkillsCatalog({ wpPlugin: input?.wpPlugin }) diff --git a/packages/core/src/server/cms-tools.ts b/packages/core/src/server/cms-tools.ts index 3d65b7a6..d4c2577b 100644 --- a/packages/core/src/server/cms-tools.ts +++ b/packages/core/src/server/cms-tools.ts @@ -1,8 +1,10 @@ /** * The CMS operations wrapped as `@tanstack/ai` tools, so they can be handed to * both `chat()` (the in-app content agent) and `createMCPServer()` (the HTTP - * MCP server). `cmsTools(actor)` bakes the actor into each handler so the - * review queue can attribute staged writes to the surface that proposed them. + * MCP server). `cmsTools(actor, { access })` bakes the actor and the agent's + * access context into each handler, so the review queue can attribute staged + * writes to the surface that proposed them and every read is scoped to the + * agent. * * `@tanstack/ai` is an optional peer, loaded on first call. * @@ -18,6 +20,8 @@ import { import type { CoreSkillSummary } from './cms-ops' import { loadTanstackAi } from './optional' import { currentSession } from './auth' +import { isAccessContext } from './access-context' +import type { AccessContext } from './access-context' import { hasPermission } from '../lib/access' import { CmsError } from '../errors' @@ -34,11 +38,35 @@ export interface CmsToolsOptions { /** Custom operation filter. */ include?: (op: CmsOpDefinition) => boolean onResult?: (result: CmsToolResult) => void + /** + * The agent's access context, e.g. + * `accessContext({ session, agent: 'content-agent', mode: 'edit' })`. It + * decides `authorizedOnly`, and every tool call reads and writes as it. A + * call's own runtime context (`ctx.context[CMS_ACCESS_KEY]`, which the MCP + * server sets per request) takes precedence. Without either, the session + * bound by `runWithSession` is used; that fallback is deprecated. + */ + access?: AccessContext +} + +/** + * The key a tool call's runtime context (`ctx.context`) carries its access + * context under, for hosts that serve one set of tools to many callers. + */ +export const CMS_ACCESS_KEY = 'cmsAccess' + +function callAccess(toolCtx: unknown): AccessContext | undefined { + const runtime = (toolCtx as { context?: Record } | undefined) + ?.context + const value = runtime?.[CMS_ACCESS_KEY] + return isAccessContext(value) ? value : undefined } export async function cmsTools(actor: string, options?: CmsToolsOptions) { const { toolDefinition } = await loadTanstackAi() - const buildSession = currentSession() + const buildSession = options?.access + ? options.access.session + : currentSession() const observe = ( result: Omit & { result: unknown }, ) => { @@ -71,13 +99,16 @@ export async function cmsTools(actor: string, options?: CmsToolsOptions) { name: op.name, description: op.description, inputSchema: op.input, - }).server(async (input) => { - const execSession = currentSession() ?? buildSession + }).server(async (input, toolCtx?: unknown) => { + const access = callAccess(toolCtx) ?? options?.access + const execSession = access + ? access.session + : (currentSession() ?? buildSession) const resolvedActor = execSession?.agent ? `${actor}:${execSession.agent}` : actor try { - const result = await runOp(op.name, input, resolvedActor) + const result = await runOp(op.name, input, resolvedActor, access) observe({ name: op.name, kind: op.agent?.kind ?? 'read', diff --git a/packages/core/src/server/dispatcher.ts b/packages/core/src/server/dispatcher.ts index 51c661a7..5a674569 100644 --- a/packages/core/src/server/dispatcher.ts +++ b/packages/core/src/server/dispatcher.ts @@ -26,7 +26,8 @@ import { registerDispatchKick, registerDispatchStop, } from './storage' -import { readDocument } from './store/read' +import { readDocumentAs } from './store/read' +import { queryReadableDocuments, systemContext } from './access-context' import { commitDocument, deleteDocument, @@ -38,6 +39,7 @@ import type { EventHandlerDefinition, ScopedCmsClient, } from '../events' +import type { AccessContext } from '../lib/access-context' import type { Doc, JsonValue } from '../schema' import type { EventData, WebhookEventData } from './outbox' import type { @@ -195,6 +197,13 @@ function matchingHandlers(env: CmsEventEnvelope): Array { // --- the scoped client handed to a handler --------------------------------- +/** The system context a handler reads with, named after the handler. */ +function handlerContext(def: ResolvedHandler): AccessContext { + return systemContext(`event handler ${def.id}`, { + actor: def.on === 'cron' ? 'scheduler' : 'system', + }) +} + function scopedClient(def: ResolvedHandler): ScopedCmsClient { const allowed = def.access?.collections const assertWrite = (collection: string): void => { @@ -205,17 +214,23 @@ function scopedClient(def: ResolvedHandler): ScopedCmsClient { ) } } + const access = handlerContext(def) return { actor: SYSTEM_ACTOR, - readDocument: (collection, id) => readDocument(collection, id), + access, + readDocument: (collection, id) => readDocumentAs(access, collection, id), async listDocuments(collection, options) { const storage = await getStorage() - const { items } = await storage.queryDocuments({ - collections: [collection], - ...(options?.locale ? { locale: options.locale } : {}), - ...(options?.limit !== undefined ? { limit: options.limit } : {}), - ...(options?.offset !== undefined ? { offset: options.offset } : {}), - }) + const { items } = await queryReadableDocuments( + storage, + { + collections: [collection], + ...(options?.locale ? { locale: options.locale } : {}), + ...(options?.limit !== undefined ? { limit: options.limit } : {}), + ...(options?.offset !== undefined ? { offset: options.offset } : {}), + }, + access, + ) return items.map((i) => i.doc) }, createDocument(collection, id, doc) { @@ -224,7 +239,7 @@ function scopedClient(def: ResolvedHandler): ScopedCmsClient { }, async updateDocument(collection, id, patch) { assertWrite(collection) - const existing = await readDocument(collection, id) + const existing = await readDocumentAs(access, collection, id) return commitDocument( collection, id, @@ -409,9 +424,12 @@ async function deliver( const attempts = (prior?.attempts ?? (data.deliveries === undefined ? rec.attempts : 0)) + 1 + const client = scopedClient(def) try { await runWithCausation({ causationId: env.id, depth: nextDepth }, () => - Promise.resolve(run({ event: env, cms: scopedClient(def) })), + Promise.resolve( + run({ event: env, cms: client, access: client.access }), + ), ) const state = await getHandlerState(storage, def.id) if (state.failures > 0) { diff --git a/packages/core/src/server/interface-schedules.ts b/packages/core/src/server/interface-schedules.ts index 83d39d5e..1bfee774 100644 --- a/packages/core/src/server/interface-schedules.ts +++ b/packages/core/src/server/interface-schedules.ts @@ -17,6 +17,9 @@ import { runWithSession, } from './auth' +/** Interface runs need the caller's session, not a read context. */ +type InterfaceOpContext = Omit + const statusSchema = z.object({ generation: z.string(), nextRunAt: z.string(), @@ -89,7 +92,7 @@ async function sync(id: string, doc: Doc | null, now: Date) { await putStatus(id, state) return state } -function admin(ctx: CmsOpContext) { +function admin(ctx: InterfaceOpContext) { if ( !ctx.session.isAuthenticated || !ctx.session.isAdmin || @@ -99,7 +102,7 @@ function admin(ctx: CmsOpContext) { } export async function getInterfaceScheduleStatus( id: string, - ctx: CmsOpContext, + ctx: InterfaceOpContext, ) { admin(ctx) const doc = await readDocument(interfaceCollectionName(), id) @@ -113,7 +116,7 @@ export async function getInterfaceScheduleStatus( } export async function setInterfaceSchedulePaused( input: { id: string; paused: boolean; expectedRevision: number }, - ctx: CmsOpContext, + ctx: InterfaceOpContext, ) { admin(ctx) const doc = await readDocument(interfaceCollectionName(), input.id) @@ -147,7 +150,7 @@ export async function setInterfaceSchedulePaused( async function capture( id: string, doc: Doc, - ctx: CmsOpContext, + ctx: InterfaceOpContext, runKey: string, ) { const collection = interfaceCollectionName() @@ -191,7 +194,10 @@ async function capture( ), ) } -export async function refreshInterfaceSnapshot(id: string, ctx: CmsOpContext) { +export async function refreshInterfaceSnapshot( + id: string, + ctx: InterfaceOpContext, +) { admin(ctx) const doc = await readDocument(interfaceCollectionName(), id) if ( diff --git a/packages/core/src/server/interfaces.ts b/packages/core/src/server/interfaces.ts index d84faff4..e643fbe2 100644 --- a/packages/core/src/server/interfaces.ts +++ b/packages/core/src/server/interfaces.ts @@ -28,6 +28,9 @@ import { schemaFor } from '../schema' import { getStorage } from './storage' import { nextCronRun } from '../lib/cron' +/** Interface runs need the caller's session, not a read context. */ +type InterfaceOpContext = Omit + const queryInput = z .object({ collection: z.string().min(1).max(64), @@ -61,7 +64,7 @@ export function interfaceCollectionName() { ) return name } -function author(ctx: CmsOpContext) { +function author(ctx: InterfaceOpContext) { if ( !ctx.session.isAuthenticated || !ctx.session.isAdmin || @@ -72,13 +75,16 @@ function author(ctx: CmsOpContext) { 'FORBIDDEN', ) } -function dataCollection(name: string, ctx: CmsOpContext) { +function dataCollection(name: string, ctx: InterfaceOpContext) { if (name === interfaceCollectionName() || !getCmsConfig().collections[name]) throw new CmsError('Unknown data collection.', 'BAD_REQUEST') assertCollectionAccess(ctx.session, name, 'read') } /** Tools close over the calling session; no database, network, or filesystem is exposed. */ -export function createInterfaceQuery(ctx: CmsOpContext, evidence?: Evidence) { +export function createInterfaceQuery( + ctx: InterfaceOpContext, + evidence?: Evidence, +) { let calls = 0 let rows = 0 return async (input: unknown) => { @@ -110,7 +116,7 @@ const jsonResult = z.record(z.string(), z.json()) export async function executeInterface( raw: unknown, stateInput: unknown, - ctx: CmsOpContext, + ctx: InterfaceOpContext, options?: { componentIds?: Array }, ): Promise<{ result: InterfaceResult; evidence: Evidence }> { const definition = interfaceDefinitionSchema.parse(raw) @@ -176,7 +182,7 @@ async function validateHandlerSyntax(code: string) { async function executeCode( code: string, state: InterfaceState, - ctx: CmsOpContext, + ctx: InterfaceOpContext, query: (input: unknown) => Promise, event?: JsonValue, stageWrites = true, @@ -301,7 +307,7 @@ async function executeCode( } } -export async function listInterfaces(ctx: CmsOpContext) { +export async function listInterfaces(ctx: InterfaceOpContext) { const collection = interfaceCollectionName() assertCollectionAccess(ctx.session, collection, 'read') const docs = await queryDocuments({ @@ -339,7 +345,7 @@ export async function listInterfaces(ctx: CmsOpContext) { } return items } -export async function getInterfaceEditor(id: string, ctx: CmsOpContext) { +export async function getInterfaceEditor(id: string, ctx: InterfaceOpContext) { author(ctx) const collection = interfaceCollectionName() assertCollectionAccess(ctx.session, collection, 'read') @@ -360,7 +366,7 @@ export async function getInterfaceEditor(id: string, ctx: CmsOpContext) { export async function getInterfaceMetadata( id: string, kind: 'page' | 'report', - ctx: CmsOpContext, + ctx: InterfaceOpContext, ) { const collection = interfaceCollectionName() const config = getCmsConfig().collections[collection] @@ -383,7 +389,7 @@ export async function getInterfaceMetadata( } export async function submitInterface( input: z.infer, - ctx: CmsOpContext, + ctx: InterfaceOpContext, ) { author(ctx) const collection = interfaceCollectionName() @@ -469,7 +475,7 @@ export async function refreshInterfaceComponents( expectedRevision: number componentIds: Array }, - ctx: CmsOpContext, + ctx: InterfaceOpContext, ) { const doc = await published(input.id, input.kind, ctx) if (doc.mode !== 'live' || doc._revision !== input.expectedRevision) @@ -498,7 +504,7 @@ export async function refreshInterfaceComponents( ).result, } } -async function published(id: string, kind: string, ctx: CmsOpContext) { +async function published(id: string, kind: string, ctx: InterfaceOpContext) { const collection = interfaceCollectionName() assertCollectionAccess(ctx.session, collection, 'read') const doc = await readDocument(collection, id) @@ -507,7 +513,7 @@ async function published(id: string, kind: string, ctx: CmsOpContext) { assertCollectionAccess(ctx.session, collection, 'read', doc) return doc } -async function snapshotEvidence(evidence: Evidence, ctx: CmsOpContext) { +async function snapshotEvidence(evidence: Evidence, ctx: InterfaceOpContext) { for (const name of evidence.collections) { dataCollection(name, ctx) if (typeof getCmsConfig().collections[name].access?.read === 'function') @@ -547,7 +553,7 @@ export async function readInterface( id: string, kind: 'page' | 'report', state: InterfaceState, - ctx: CmsOpContext, + ctx: InterfaceOpContext, ) { const doc = await published(id, kind, ctx) const title = String( @@ -591,7 +597,7 @@ export async function dispatchInterfaceEvent( event: JsonValue expectedRevision: number }, - ctx: CmsOpContext, + ctx: InterfaceOpContext, ) { const doc = await published(input.id, input.kind, ctx) if (doc.mode !== 'live') @@ -617,7 +623,7 @@ export async function previewInterfaceEvent( state: InterfaceState event: JsonValue }, - ctx: CmsOpContext, + ctx: InterfaceOpContext, ) { author(ctx) return runInterfaceEvent( @@ -634,7 +640,7 @@ async function runInterfaceEvent( componentId: string, stateInput: InterfaceState, event: JsonValue, - ctx: CmsOpContext, + ctx: InterfaceOpContext, stageWrites: boolean, ) { const definition = interfaceDefinitionSchema.parse(raw) diff --git a/packages/core/src/server/store.ts b/packages/core/src/server/store.ts index efe4d3d6..600be6e5 100644 --- a/packages/core/src/server/store.ts +++ b/packages/core/src/server/store.ts @@ -43,6 +43,16 @@ export { listPublicDocuments, findReferences, listTranslations, + queryDocumentSummariesAs, + listDocumentsAs, + readDocumentAs, + readDocumentWithPendingAs, + populateRelationsAs, + readSingletonAs, + readDocumentBySlugAs, + findDocumentBySlugAs, + findReferencesAs, + listTranslationsAs, } from './store/read' export type { TranslationSummary, @@ -50,15 +60,20 @@ export type { DocStatus, DocumentSummaryQuery, DocumentReference, + DocumentWithPending, + ListDocumentsOptions, } from './store/read' export { normalizeWhere, queryDocuments, + queryDocumentsAs, reindexDocuments, groupDocuments, + groupDocumentsAs, } from './store/query' export type { QueryDocumentsOptions, + ContextQueryOptions, WhereInput, QueryDocumentsResult, } from './store/query' @@ -92,6 +107,10 @@ export { unpublishDocument, } from './store/write' export type { CommitOptions, DeleteOptions } from './store/write' -export { listRevisions, restoreRevision } from './store/revisions' +export { + listRevisions, + listRevisionsAs, + restoreRevision, +} from './store/revisions' export { runScheduledPublishing, scheduleDocument } from './store/scheduling' export type { ScheduledPublishResult } from './store/scheduling' diff --git a/packages/core/src/server/store/internal.ts b/packages/core/src/server/store/internal.ts index 47555db6..c9507ace 100644 --- a/packages/core/src/server/store/internal.ts +++ b/packages/core/src/server/store/internal.ts @@ -28,6 +28,7 @@ import type { FieldValidator, JsonValue, } from '../../schema' +import type { AccessContext } from '../../lib/access-context' import type { AuditRecord, PendingRecord, @@ -104,12 +105,13 @@ export async function applyPostRead( collectionName: string, id: string, stored: Doc, + access: AccessContext, ): Promise { const doc = await upgradeStoredDoc(collectionName, id, stored) const hook = collections()[collectionName]?.hooks?.postRead if (!hook) return doc const result = await runHook(collectionName, 'postRead', () => - hook({ doc, id }), + hook({ doc, id, access }), ) return result && typeof result === 'object' ? (result as Doc) : doc } diff --git a/packages/core/src/server/store/query.ts b/packages/core/src/server/store/query.ts index de74f546..fdcfc068 100644 --- a/packages/core/src/server/store/query.ts +++ b/packages/core/src/server/store/query.ts @@ -68,8 +68,6 @@ export interface QueryDocumentsOptions { /** * `QueryDocumentsOptions` without the visibility options, which a context * replaces. - * - * @internal */ export type ContextQueryOptions = Omit< QueryDocumentsOptions, @@ -221,8 +219,6 @@ export function queryDocuments( /** * `queryDocuments` as `ctx`: visibility and redaction come from the context. - * - * @internal */ export async function queryDocumentsAs( ctx: AccessContext, @@ -295,7 +291,7 @@ export async function queryDocumentsAs( const relationsCtx = withoutPublicRead(ctx) const page: QueryDocumentsResult['items'] = [] for (const row of result.items) { - const doc = await applyPostRead(row.collection, row.id, row.doc) + const doc = await applyPostRead(row.collection, row.id, row.doc, ctx) const visible = redactFor(ctx, row.collection, doc) const title = visible[collections()[row.collection]?.titleField ?? 'title'] page.push({ @@ -363,8 +359,6 @@ export function groupDocuments( /** * `groupDocuments` as `ctx`. - * - * @internal */ export async function groupDocumentsAs( ctx: AccessContext, diff --git a/packages/core/src/server/store/read.ts b/packages/core/src/server/store/read.ts index af302bf6..45bc575f 100644 --- a/packages/core/src/server/store/read.ts +++ b/packages/core/src/server/store/read.ts @@ -116,7 +116,7 @@ async function summarize( columns: ReadonlyArray | undefined, ctx: AccessContext, ): Promise { - const original = await applyPostRead(collection.name, row.id, row.doc) + const original = await applyPostRead(collection.name, row.id, row.doc, ctx) const doc = redactFor(ctx, collection.name, original) const rawTitle = doc[collection.titleField] const title = typeof rawTitle === 'string' && rawTitle ? rawTitle : row.id @@ -178,8 +178,6 @@ export function queryDocumentSummaries( /** * `queryDocumentSummaries` as `ctx`. A `live` context lists published * documents only, without pending creates. - * - * @internal */ export async function queryDocumentSummariesAs( ctx: AccessContext, @@ -289,7 +287,7 @@ async function pendingCreateSummaries( const needle = search?.trim().toLowerCase() const summaries: Array = [] for (const p of rows) { - const original = await applyPostRead(collection.name, p.docId, p.after) + const original = await applyPostRead(collection.name, p.docId, p.after, ctx) if ( !canReadDocument(ctx, collection.name, { id: p.docId, @@ -335,7 +333,7 @@ export function listDocuments( ) } -/** @internal */ +/** Options for `listDocuments`. */ export interface ListDocumentsOptions { locale?: string limit?: number @@ -346,8 +344,6 @@ export interface ListDocumentsOptions { /** * `listDocuments` as `ctx`. - * - * @internal */ export async function listDocumentsAs( ctx: AccessContext, @@ -376,6 +372,7 @@ export async function listDocumentsAs( } const UNSCOPED_READ = systemContext('store read by id without a session') +const TRASH_READ = systemContext('trash read') export function readDocument( collectionName: string, @@ -388,8 +385,6 @@ export function readDocument( /** * `readDocument` as `ctx`: `null` when the document is missing or `ctx` * can't see it. - * - * @internal */ export async function readDocumentAs( ctx: AccessContext, @@ -406,7 +401,7 @@ export async function readDocumentAs( const live = isLiveRead(ctx) if (live && !row.published) return null if (!canReadDocument(ctx, collectionName, row)) return null - const doc = await applyPostRead(collectionName, id, row.doc) + const doc = await applyPostRead(collectionName, id, row.doc, ctx) if (live && !doc.published) return null return redactFor(ctx, collectionName, doc) } @@ -422,7 +417,7 @@ export async function readTrashedDocument( const storage = await getStorage() const row = await storage.getDocument(collectionName, id) if (!row || !row.deletedAt) return null - return applyPostRead(collectionName, id, row.doc) + return applyPostRead(collectionName, id, row.doc, TRASH_READ) } /** What `readDocumentWithPending` returns. */ @@ -451,8 +446,6 @@ export function readDocumentWithPending( * `readDocumentWithPending` as `ctx`. The staged overlay applies in `preview` * and `edit` modes; a `live` context reads the published version only. A * document `ctx` can't see reads as missing. - * - * @internal */ export async function readDocumentWithPendingAs( ctx: AccessContext, @@ -485,7 +478,7 @@ export async function readDocumentWithPendingAs( }) ) return hidden - const doc = await applyPostRead(collectionName, id, pending.after) + const doc = await applyPostRead(collectionName, id, pending.after, ctx) return { doc: redactFor(ctx, collectionName, doc), isPending: true, @@ -501,7 +494,7 @@ export async function readDocumentWithPendingAs( return hidden if (isLiveRead(ctx) && !committed?.published) return hidden const doc = committed - ? await applyPostRead(collectionName, id, committed.doc) + ? await applyPostRead(collectionName, id, committed.doc, ctx) : null if (isLiveRead(ctx) && !doc?.published) return hidden return { @@ -535,8 +528,6 @@ export function populateRelations( /** * `populateRelations` as `ctx`. Related documents don't get `publicRead` * visibility: each target is read under the target collection's own rule. - * - * @internal */ export async function populateRelationsAs( context: AccessContext, @@ -570,7 +561,7 @@ export async function populateRelationsAs( const docs: Array = [] for (const row of rows) { if (live && !row.published) continue - const targetDoc = await applyPostRead(targetName, row.id, row.doc) + const targetDoc = await applyPostRead(targetName, row.id, row.doc, ctx) if (live && !targetDoc.published) continue if (!canReadDocument(ctx, targetName, row)) continue docs.push(redactFor(ctx, targetName, targetDoc)) @@ -635,8 +626,6 @@ export function readSingleton( /** * `readSingleton` as `ctx`. - * - * @internal */ export async function readSingletonAs( ctx: AccessContext, @@ -658,7 +647,7 @@ export async function readSingletonAs( if (!row) return null if (live && !row.published) return null if (!canReadDocument(ctx, collectionName, row)) return null - const doc = await applyPostRead(collectionName, row.id, row.doc) + const doc = await applyPostRead(collectionName, row.id, row.doc, ctx) if (live && !doc.published) return null return { id: row.id, doc: redactFor(ctx, collectionName, doc) } } @@ -682,8 +671,6 @@ export function readDocumentBySlug( /** * `readDocumentBySlug` as `ctx`: a match `ctx` can't see is skipped, and the * returned document is redacted. - * - * @internal */ export function readDocumentBySlugAs( ctx: AccessContext, @@ -741,7 +728,7 @@ async function readBySlug( if (!canReadDocument(ctx, collectionName, direct)) return null return withRelations( slugOrId, - await applyPostRead(collectionName, slugOrId, direct.doc), + await applyPostRead(collectionName, slugOrId, direct.doc, ctx), ) } for (const row of await storage.findDocumentsBySlug( @@ -750,7 +737,7 @@ async function readBySlug( )) { if (live && !row.published) continue if (!canReadDocument(ctx, collectionName, row)) continue - const doc = await applyPostRead(collectionName, row.id, row.doc) + const doc = await applyPostRead(collectionName, row.id, row.doc, ctx) if (live && !doc.published) continue return withRelations(row.id, doc) } @@ -781,8 +768,6 @@ export function findDocumentBySlug( /** * `findDocumentBySlug` as `ctx`. - * - * @internal */ export function findDocumentBySlugAs( ctx: AccessContext, @@ -843,7 +828,7 @@ export async function listPublicDocuments( ) out[col] = {} for (const row of items) { - out[col][row.id] = await applyPostRead(col, row.id, row.doc) + out[col][row.id] = await applyPostRead(col, row.id, row.doc, ctx) } } return out @@ -899,8 +884,6 @@ export function findReferences( * `findReferences` as `ctx`: only references from documents `ctx` can see, * through fields it can read. The read mode doesn't apply: references from * drafts and staged changes count. - * - * @internal */ export async function findReferencesAs( ctx: AccessContext, @@ -1054,8 +1037,6 @@ export function listTranslations( /** * `listTranslations` as `ctx`: only the variants `ctx` can see. - * - * @internal */ export async function listTranslationsAs( ctx: AccessContext, @@ -1107,7 +1088,7 @@ export async function listTranslationsAs( const mapped = await storage.getDocuments(collectionName, mappedIds) for (const row of [...linked.items, ...mapped]) { if (row.id === canonicalId || out.has(row.id)) continue - const doc = await applyPostRead(collectionName, row.id, row.doc) + const doc = await applyPostRead(collectionName, row.id, row.doc, ctx) out.set(row.id, summarizeVariant(row.id, doc, false, row.id)) } const live = isLiveRead(ctx) diff --git a/packages/core/src/server/store/review.ts b/packages/core/src/server/store/review.ts index 22f510b5..41e9c9b1 100644 --- a/packages/core/src/server/store/review.ts +++ b/packages/core/src/server/store/review.ts @@ -39,6 +39,7 @@ import { readDocument } from './read' import { commitDeletion } from './write' import { assertCollectionAccess } from '../auth' import { protectWrite } from '../access' +import { systemContext } from '../access-context' import type { CmsSession } from '../../lib/auth' import type { Doc } from '../../schema' import type { PendingSource, StorageOps, WriteType } from '../../storage/types' @@ -61,12 +62,19 @@ export interface StageWriteArgs { * documents until someone approves. A second staged write for the same * document coalesces into the existing pending entry. */ +const STAGE_BEFORE_READ = systemContext('stageWrite: the committed document') + export async function stageWrite(args: StageWriteArgs): Promise { const collection = requireWritableCollection(args.collection) const storage = await getStorage() const beforeRow = await storage.getDocument(args.collection, args.docId) const before = beforeRow - ? await applyPostRead(args.collection, args.docId, beforeRow.doc) + ? await applyPostRead( + args.collection, + args.docId, + beforeRow.doc, + STAGE_BEFORE_READ, + ) : null const existing = await storage.getPendingFor(args.collection, args.docId) diff --git a/packages/core/src/server/store/revisions.ts b/packages/core/src/server/store/revisions.ts index ce329992..6ccdf670 100644 --- a/packages/core/src/server/store/revisions.ts +++ b/packages/core/src/server/store/revisions.ts @@ -5,12 +5,19 @@ */ import { CmsError } from '../../errors' import { protectWrite } from '../access' +import { + bypassesRules, + canReadDocument, + redactFor, + withoutPublicRead, +} from '../access-context' import { assertCollectionAccess } from '../auth' import { upgradeStoredDoc } from '../content-migrations' import { getStorage } from '../storage' import { readDocumentWithPending } from './read' import { stageWrite } from './review' import { commitDocument } from './write' +import type { AccessContext } from '../access-context' import type { CmsSession } from '../../lib/auth' import type { Doc } from '../../schema' import type { Pending, Revision } from './internal' @@ -24,6 +31,29 @@ export async function listRevisions( return storage.listRevisions(collectionName, docId) } +/** + * `listRevisions` as `ctx`: the revisions `ctx` may read, redacted. The read + * mode doesn't apply; history includes unpublished versions. + */ +export async function listRevisionsAs( + ctx: AccessContext, + collectionName: string, + docId: string, +): Promise> { + const revisions = await listRevisions(collectionName, docId) + if (bypassesRules(ctx) && !ctx.scope) return revisions + const scoped = withoutPublicRead(ctx) + return revisions + .filter((r) => + canReadDocument(scoped, collectionName, { + id: docId, + published: false, + doc: r.doc, + }), + ) + .map((r) => ({ ...r, doc: redactFor(scoped, collectionName, r.doc) })) +} + /** Restore a revision (by id or number), staged or as a new revision. */ export async function restoreRevision( collectionName: string, diff --git a/packages/core/tests/access-context.test.ts b/packages/core/tests/access-context.test.ts index c5f7fe9f..845917b1 100644 --- a/packages/core/tests/access-context.test.ts +++ b/packages/core/tests/access-context.test.ts @@ -10,15 +10,19 @@ import { normalizeSession, } from '../src/index' import { + CMS_ACCESS_KEY, closeStore, + cmsTools, commitDocument, createPreviewToken, queryDocuments, readDocumentBySlug, + runOp, stageWrite, } from '../src/server' import { accessContext, + assertReadable, canReadCollection, canReadDocument, legacyReadContext, @@ -26,8 +30,11 @@ import { previewTokenContext, publicContext, redactFor, + isAccessContext, + parseReadMode, storageVisibility, systemContext, + withMode, } from '../src/server/access-context' import { cmsAs } from '../src/server/cms-as' import type { Cms, CmsConfig } from '../src/index' @@ -131,11 +138,19 @@ describe('builders', () => { it('accessContext derives the actor and permissions from the session', () => { const ctx = accessContext({ session: as('author', { agent: 'writer' }) }) expect(ctx.actor).toEqual({ + kind: 'agent', + agent: 'writer', + id: 'u-author', + role: 'author', + }) + expect(accessContext({ session: as('author') }).actor).toEqual({ kind: 'user', id: 'u-author', role: 'author', - agent: 'writer', }) + expect( + accessContext({ session: as('author'), agent: 'content-agent' }).actor, + ).toMatchObject({ kind: 'agent', agent: 'content-agent' }) expect(ctx.permissions).toContain('content.write') expect(ctx.mode).toBe('live') expect(ctx.publicRead).toBe(false) @@ -157,6 +172,48 @@ describe('builders', () => { expect(ctx.session).toBeUndefined() expect(ctx.permissions).toEqual([...PERMISSIONS]) expect(systemContext('sitemap', { mode: 'live' }).mode).toBe('live') + expect(systemContext('nightly', { actor: 'scheduler' }).actor).toEqual({ + kind: 'scheduler', + reason: 'nightly', + }) + expect(systemContext('wp import', { actor: 'import' }).actor.kind).toBe( + 'import', + ) + expect(() => systemContext('x', { actor: 'root' as never })).toThrow( + /Unknown trusted actor/, + ) + }) + + it('withMode switches the mode and keeps the actor; only built contexts pass', () => { + const ctx = accessContext({ session: as('viewer') }) + const edit = withMode(ctx, 'edit') + expect(edit.mode).toBe('edit') + expect(edit.actor).toEqual(ctx.actor) + expect(withMode(ctx, 'live')).toBe(ctx) + expect(isAccessContext(edit)).toBe(true) + expect(isAccessContext({ ...edit })).toBe(false) + expect(isAccessContext(null)).toBe(false) + expect(parseReadMode(null)).toBeUndefined() + expect(parseReadMode('preview')).toBe('preview') + expect(() => parseReadMode('everything')).toThrow(/Unknown read mode/) + }) + + it('assertReadable throws like assertCollectionAccess', async () => { + await createCms(config('assert')).run(() => { + expect(() => + assertReadable( + accessContext({ session: UNAUTHENTICATED_SESSION }), + 'memo', + ), + ).toThrow(/Unauthorized/) + expect(() => + assertReadable(accessContext({ session: as('author') }), 'memo'), + ).toThrow(/Forbidden: cannot read memo/) + expect(() => + assertReadable(accessContext({ session: as('editor') }), 'memo'), + ).not.toThrow() + expect(() => assertReadable(systemContext('x'), 'memo')).not.toThrow() + }) }) it('previewContext is scoped to the token document', () => { @@ -337,6 +394,88 @@ describe('derivation', () => { expect(await handle.readDocumentBySlug('memo', 'm-live')).toBeNull() }) + it('postRead receives the reading context', async () => { + const seen: Array<{ id: string; kind: string; mode: string }> = [] + const note = defineCollection({ + name: 'note', + label: 'Notes', + titleField: 'title', + fields: [{ name: 'title', label: 'Title', type: 'text' }], + hooks: { + postRead: ({ doc, id, access }) => { + seen.push({ id, kind: access.actor.kind, mode: access.mode }) + if (access.actor.kind !== 'public') return + return { ...doc, title: `${String(doc.title)} (public)` } + }, + }, + }) + const cms = createCms({ ...config('hooks'), collections: [note] }) + await cms.run(() => + commitDocument('note', 'n1', { title: 'Hello', published: true }), + ) + const editor = accessContext({ session: as('editor'), mode: 'edit' }) + expect((await cmsAs(cms, editor).readDocument('note', 'n1'))?.title).toBe( + 'Hello', + ) + expect( + (await cmsAs(cms, publicContext()).readDocument('note', 'n1'))?.title, + ).toBe('Hello (public)') + expect(seen).toEqual([ + { id: 'n1', kind: 'user', mode: 'edit' }, + { id: 'n1', kind: 'public', mode: 'live' }, + ]) + }) + + it('runOp and cmsTools read as the context they are given', async () => { + const cms = await seeded() + await cms.run(async () => { + const list = { collection: 'memo' } + const viewer = accessContext({ session: as('viewer'), mode: 'edit' }) + await expect( + runOp('list_documents', list, 'agent', viewer), + ).rejects.toThrow(/Forbidden/) + const asSystem = (await runOp( + 'list_documents', + list, + 'agent', + systemContext('test: list memos'), + )) as Array + expect(asSystem).toHaveLength(2) + await expect( + runOp( + 'list_documents', + list, + 'agent', + previewContext({ + id: 't1', + collection: 'memo', + docId: 'm-draft', + expiresAt: new Date(Date.now() + 60_000).toISOString(), + createdAt: new Date().toISOString(), + createdBy: 'ada', + }), + ), + ).rejects.toThrow(/preview context/) + + const tools = await cmsTools('mcp', { access: viewer }) + const listTool = tools.find((t) => t.name === 'list_documents')! + await expect(listTool.execute!(list, {} as never)).rejects.toThrow( + /Forbidden/, + ) + const editor = accessContext({ session: as('editor'), mode: 'edit' }) + const viaCall = (await listTool.execute!(list, { + context: { [CMS_ACCESS_KEY]: editor }, + } as never)) as Array + expect(viaCall).toHaveLength(2) + // A look-alike object is not a context: the bound one applies. + await expect( + listTool.execute!(list, { + context: { [CMS_ACCESS_KEY]: { ...editor } }, + } as never), + ).rejects.toThrow(/Forbidden/) + }) + }) + it('scopes reads to the bound instance', async () => { const cms = await seeded() const other = createCms(config('other')) @@ -345,6 +484,9 @@ describe('derivation', () => { ) other.register() expect(await ids(cmsAs(cms, publicContext()), 'post')).toEqual(['live']) + expect(await ids(cmsAs(cms.config, publicContext()), 'post')).toEqual([ + 'live', + ]) expect(await ids(cmsAs(other, publicContext()), 'post')).toEqual([ 'elsewhere', ]) diff --git a/packages/core/tests/events.test.ts b/packages/core/tests/events.test.ts index e4a00267..e0c3af45 100644 --- a/packages/core/tests/events.test.ts +++ b/packages/core/tests/events.test.ts @@ -157,6 +157,37 @@ describe('async events: outbox, dispatcher, hooks', () => { expect(event.changedFields).not.toContain('_revision') }) + it('hands each handler a system access context, the same one its cms reads as', async () => { + const seen: Array = [] + setup({ + dataDir: makeTempDir(), + eventHandlers: [ + defineEventHandler({ + id: 'audit', + on: 'document.created', + collection: 'post', + run: async ({ access, cms }) => { + seen.push({ + access, + same: cms.access === access, + doc: await cms.readDocument('post', 'p1'), + }) + }, + }), + ], + }) + await commitDocument('post', 'p1', { title: 'Draft', published: false }) + await runEventDispatch() + expect(seen).toHaveLength(1) + expect(seen[0].access.actor).toEqual({ + kind: 'system', + reason: 'event handler audit', + }) + expect(seen[0].access.mode).toBe('edit') + expect(seen[0].same).toBe(true) + expect(seen[0].doc?.title).toBe('Draft') + }) + // --- Acceptance #5: write-back does not refire; causationId chain visible it('prevents loops via a depth cap while exposing the causation chain', async () => { const created: Array = [] diff --git a/packages/core/tests/interface-schedules.test.ts b/packages/core/tests/interface-schedules.test.ts index 41427284..2578cf1c 100644 --- a/packages/core/tests/interface-schedules.test.ts +++ b/packages/core/tests/interface-schedules.test.ts @@ -27,14 +27,19 @@ import { runInterfaceSchedules, setInterfaceSchedulePaused, submitInterface, + accessContext, } from '../src/server' let dir: string let enabled = true -const ctx = (): CmsOpContext => ({ - actor: 'owner', - session: normalizeSession({ id: 'owner', role: 'admin' }), -}) +const ctx = (): CmsOpContext => { + const session = normalizeSession({ id: 'owner', role: 'admin' }) + return { + actor: 'owner', + session, + access: accessContext({ session, mode: 'edit' }), + } +} const definition = (): InterfaceDefinition => ({ version: 1, initialState: {}, diff --git a/packages/core/tests/interfaces.test.ts b/packages/core/tests/interfaces.test.ts index b74c07cd..bbed6409 100644 --- a/packages/core/tests/interfaces.test.ts +++ b/packages/core/tests/interfaces.test.ts @@ -26,13 +26,18 @@ import { restoreRevision, listPending, redactDoc, + accessContext, } from '../src/server' let dir: string -const context = (role = 'admin'): CmsOpContext => ({ - actor: role, - session: normalizeSession({ id: role, role }), -}) +const context = (role = 'admin'): CmsOpContext => { + const session = normalizeSession({ id: role, role }) + return { + actor: role, + session, + access: accessContext({ session, mode: 'edit' }), + } +} const definition = (): InterfaceDefinition => ({ version: 1, initialState: { min: 0 }, diff --git a/packages/search-cms/src/index.ts b/packages/search-cms/src/index.ts index 4421d30a..26155ce3 100644 --- a/packages/search-cms/src/index.ts +++ b/packages/search-cms/src/index.ts @@ -7,7 +7,12 @@ import { validateFilter, } from '@tanstack/search-core' import { UNAUTHENTICATED_SESSION } from '@tanstack/cms-core' -import { groupDocuments, queryDocuments } from '@tanstack/cms-core/server' +import { + accessContext, + groupDocumentsAs, + queryDocumentsAs, +} from '@tanstack/cms-core/server' +import type { AccessContext } from '@tanstack/cms-core/server' import type { CmsSession, Collection, Doc, Field } from '@tanstack/cms-core' import type { WhereClause } from '@tanstack/cms-core/storage' import type { @@ -165,18 +170,39 @@ function compileValidatedFilter( } export interface CmsSearchOptions { collection: Collection + /** + * Who searches, and in which mode: `publicContext()` for a public site + * search (the default), `accessContext({ session, mode: 'edit' })` for an + * editor searching drafts. Results are what this context may read. When + * set, `session`, `publishedOnly` and `publicRead` are ignored. + */ + access?: AccessContext + /** @deprecated Pass `access: accessContext({ session })`. */ session?: CmsSession + /** + * @deprecated The context's mode decides it (`live` is published only). + * Default `true`. + */ publishedOnly?: boolean + /** @deprecated Pass `access: accessContext({ session, publicRead: true })`. */ publicRead?: boolean locale?: string } + +function searchContext(options: CmsSearchOptions): AccessContext { + if (options.access) return options.access + return accessContext({ + session: options.session ?? UNAUTHENTICATED_SESSION, + mode: (options.publishedOnly ?? true) ? 'live' : 'edit', + publicRead: options.publicRead ?? !options.session?.isAuthenticated, + }) +} + export function createCmsSearch(options: CmsSearchOptions) { const fields = cmsSearchFields(options.collection) + const access = searchContext(options) const base = { collection: options.collection.name, - session: options.session ?? UNAUTHENTICATED_SESSION, - publishedOnly: options.publishedOnly ?? true, - publicRead: options.publicRead ?? !options.session?.isAuthenticated, locale: options.locale, } const where = (plan: QueryPlan): Array => @@ -188,7 +214,7 @@ export function createCmsSearch(options: CmsSearchOptions) { const queryable: Queryable = { async search(plan, signal) { signal?.throwIfAborted() - const result = await queryDocuments({ + const result = await queryDocumentsAs(access, { ...base, where: where(plan), textQuery: textQuery(plan), @@ -206,7 +232,7 @@ export function createCmsSearch(options: CmsSearchOptions) { }, async groupBy(field, plan, signal) { signal?.throwIfAborted() - const groups = await groupDocuments(field, { + const groups = await groupDocumentsAs(access, field, { ...base, where: where(plan), textQuery: textQuery(plan), diff --git a/packages/search-cms/tests/cms.test.ts b/packages/search-cms/tests/cms.test.ts index 77babd6a..2f0441f1 100644 --- a/packages/search-cms/tests/cms.test.ts +++ b/packages/search-cms/tests/cms.test.ts @@ -4,9 +4,15 @@ import { defineCollection, normalizeSession, } from '@tanstack/cms-core' -import { closeStore, getStorage } from '@tanstack/cms-core/server' +import { + accessContext, + closeStore, + getStorage, + publicContext, +} from '@tanstack/cms-core/server' import { sqliteStorage } from '@tanstack/cms-core/storage' import type { Collection } from '@tanstack/cms-core' +import type { AccessContext } from '@tanstack/cms-core/server' import { createCmsSearch, cmsSearchFields } from '../src/index' const collection: Collection = defineCollection({ @@ -117,6 +123,33 @@ it('uses native groups for the public published catalog', async () => { await search.search({ facets: ['vendor', 'material'] }) expect(groupBy).toHaveBeenCalledTimes(2) }) +it('searches as the access context it is given', async () => { + const current = configure() + const total = async (access?: AccessContext) => + ( + await createCmsSearch({ + collection: current, + ...(access && { access }), + }).search({ text: 'warm strumming' }) + ).total + expect(await total()).toBe(2) + expect(await total(publicContext())).toBe(2) + expect(await total(accessContext({ session: viewer(), mode: 'edit' }))).toBe( + 3, + ) + expect(await total(accessContext({ session: viewer(), mode: 'live' }))).toBe( + 2, + ) + expect( + ( + await createCmsSearch({ + collection: current, + session: viewer(), + publishedOnly: false, + }).search({ text: 'warm strumming' }) + ).total, + ).toBe(3) +}) it('applies document-dependent access to totals and all facet counts', async () => { const current = configure({ access: { read: ({ doc }) => !doc || doc.vendor === 'A' },