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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions .changeset/access-fail-closed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
---
'@tanstack/cms-core': minor
'@tanstack/cms-api': minor
'@tanstack/cms-cli': minor
'@tanstack/search-cms': minor
---

**Breaking:** reads fail closed. A read without an access context is a public read, and nothing reads with an ambient session.

- The plain read functions in `@tanstack/cms-core/server` are deprecated and read as `publicContext()`: published documents only, redacted for an anonymous visitor. They used to read everything, drafts included. The affected functions are `queryDocuments`, `groupDocuments`, `queryDocumentSummaries`, `listDocuments`, `readDocument`, `readDocumentWithPending`, `readSingleton`, `readDocumentBySlug`, `findDocumentBySlug`, `populateRelations`, `findReferences`, `listTranslations` and `listRevisions`. They are removed in a later alpha. Read with `cmsAs(cms, ctx)` or the `…As(ctx, …)` form instead.
- Their `session`, `publishedOnly` and `publicRead` options are removed, along with the `ContextQueryOptions` type. `createCmsSearch` no longer takes `session`, `publishedOnly` or `publicRead`; pass `access`.
- `runWithSession` and `currentSession` are removed. Pass the session, or an access context, to the call that needs it:
- `runOp(name, input, actor, access)` and `cmsMcp.fetch(request, access)` require a context, and throw `UNAUTHORIZED` without one.
- A `cmsTools` call with neither a per-call context (`CMS_ACCESS_KEY`) nor `options.access` fails with `UNAUTHORIZED`.
- `afterChange` and `afterDelete` hooks receive the writer's `session` (new `DeleteHookArgs` type).
- `createApiKey(input, { session })`, `revokeApiKey(id, { session })` and `recordAdminAudit({ …, session })` take the acting session for the audit log.
- `resolveSession()` without a request resolves as a request with no credentials.
- The `search_documents` agent tool takes `mode` (`live`, `preview` or `edit`) instead of `publishedOnly`. A mode wider than the caller's own is ignored. The new `narrowMode(ctx, mode)` does the same for app code.
- `tanstack-cms atproto publish` publishes the published version of a document.

Leaks fixed:

- `readDocumentBySlug` and `findDocumentBySlug` check access on the matched document.
- Populated relations follow the reading context, including `publicRead`, so a `publicRead` reader sees published targets the way it sees published sources. A relation into a collection the reader can't read is left out.
- A preview token's document is redacted as for an anonymous visitor.

Migration: run `pnpm codemod access-context`. It rewrites calls to the `…As` form:

- a call that passed a `session` becomes `accessContext({ session, mode })`;
- `publishedOnly: true` becomes `publicContext()`;
- an unscoped read becomes `systemContext('access-context codemod: was an unscoped read')`, with a warning.

Replace each such reason with a real one, or with the visitor's context where the read serves the public. Replace `runWithSession(session, fn)` by hand with an explicit `session` option or context. See "Reads take an access context" in the upgrade guide.
6 changes: 3 additions & 3 deletions .claude/skills/emdash-to-tanstack-cms/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -223,8 +223,8 @@ Self-test: `node scripts/portable-text-to-markdown.mjs`.
`content` (hardcode them with a comment naming the file); titles, slugs,
excerpts, and a Portable Text body survived; and loading through the engine
works (`seedContent({ force: true })` or `parseCmsExport` + `importContent`,
then `queryDocuments({ where: { tags: 'opinion' } })` and
`readDocument`/`queryDocuments` with `populate: true` resolving `authors`).
then `queryDocumentsAs(ctx, { where: { tags: 'opinion' } })` and
`readDocumentAs`/`queryDocuments` with `populate: true` resolving `authors`).
`closeStore()` after each test.
- Live check: `pnpm --filter <app> dev`, then
`curl -X POST localhost:<port>/api/cms/v1/ops/listDocumentSummaries -H 'content-type: application/json' -d '{"collection":"post","status":"all"}'`
Expand All @@ -240,7 +240,7 @@ tables you used, the Portable Text coverage, how the content was loaded, and a

- **Hierarchical taxonomies** — flattened into a `multiselect` (parents lost),
or modelled as a collection + `relation`. Taxonomy archive pages
(`/category/<slug>`) need an app route (`queryDocuments({ where })`).
(`/category/<slug>`) need an app route (`queryDocumentsAs(ctx, { where })`).
- **Bylines** — the built-in post page renders the plain-text `author` field
(declared as `bylineField`), not the `authors` relation; byline roles and ordering beyond the array order
need app work.
Expand Down
54 changes: 27 additions & 27 deletions .claude/skills/payload-to-tanstack-cms/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,31 +116,31 @@ functions (AI adapter factories, `webhooks[].secret: () => process.env.X`).

**Field types** (Payload → core `type`):

| Payload | core `type` | Notes |
| --------------------------------------------- | ----------------------------------- | ------------------------------------------------------------------------- |
| `text` | `text` | |
| `textarea` | `textarea` | |
| `email` | `email` | format-validated |
| `number` | `number` | `min`/`max` carry over |
| `checkbox` | `boolean` | |
| `select`, `radio` | `select` with `options` | `{ label, value }` options carry over as-is |
| `select` with `hasMany` | `multiselect` with `options` | |
| `date` | `datetime` (or `date` for day-only) | Payload stores ISO datetimes |
| `code` | `textarea` | or a `code` block inside `blocks` |
| `json` | `json` | |
| `point` | `json` or a `group` of two numbers | no geo queries |
| `upload` (`relationTo: 'media'`) | `image` | stores the media URL string |
| `relationship` (one target) | `relation` + `collection` | stores the target id |
| `relationship` with `hasMany` | `relation` + `many: true` | array of ids; `populateRelations` / `populate: true` resolves them |
| `relationship` polymorphic (`relationTo: []`) | — | split into one `relation` per target, or `json` — gap report |
| `richText` (Lexical), flat | `richtext` (or `markdown`) | both store Markdown; see §5 |
| `richText` (Lexical), in a block | `richText` block `markdown` | see §5 |
| `blocks` | `blocks` | map each block type → core block (below); keep blocks one level deep |
| `group` | `group` with `fields` | nested object |
| `array` | `array` with `fields` | list of nested objects; `minRows`/`maxRows` → `min`/`max` |
| `tabs` (named) | `group` per tab | unnamed tabs, `row`, `collapsible` are layout only → flatten their fields |
| a text slug (`/about` paths) | `text` + `unique: true` | use `slug` only for kebab-case values (it validates the format) |
| `join`, `ui` | — | `join` is a computed reverse lookup: `queryDocuments({ where })` instead |
| Payload | core `type` | Notes |
| --------------------------------------------- | ----------------------------------- | ------------------------------------------------------------------------------- |
| `text` | `text` | |
| `textarea` | `textarea` | |
| `email` | `email` | format-validated |
| `number` | `number` | `min`/`max` carry over |
| `checkbox` | `boolean` | |
| `select`, `radio` | `select` with `options` | `{ label, value }` options carry over as-is |
| `select` with `hasMany` | `multiselect` with `options` | |
| `date` | `datetime` (or `date` for day-only) | Payload stores ISO datetimes |
| `code` | `textarea` | or a `code` block inside `blocks` |
| `json` | `json` | |
| `point` | `json` or a `group` of two numbers | no geo queries |
| `upload` (`relationTo: 'media'`) | `image` | stores the media URL string |
| `relationship` (one target) | `relation` + `collection` | stores the target id |
| `relationship` with `hasMany` | `relation` + `many: true` | array of ids; `populateRelations` / `populate: true` resolves them |
| `relationship` polymorphic (`relationTo: []`) | — | split into one `relation` per target, or `json` — gap report |
| `richText` (Lexical), flat | `richtext` (or `markdown`) | both store Markdown; see §5 |
| `richText` (Lexical), in a block | `richText` block `markdown` | see §5 |
| `blocks` | `blocks` | map each block type → core block (below); keep blocks one level deep |
| `group` | `group` with `fields` | nested object |
| `array` | `array` with `fields` | list of nested objects; `minRows`/`maxRows` → `min`/`max` |
| `tabs` (named) | `group` per tab | unnamed tabs, `row`, `collapsible` are layout only → flatten their fields |
| a text slug (`/about` paths) | `text` + `unique: true` | use `slug` only for kebab-case values (it validates the format) |
| `join`, `ui` | — | `join` is a computed reverse lookup: `queryDocumentsAs(ctx, { where })` instead |

**Field options:** `required` → `required: true`; `unique` → `unique: true`;
`index` → `index: true`; `defaultValue` → `defaultValue`; `admin.description` →
Expand Down Expand Up @@ -176,7 +176,7 @@ Payload `{ data, originalDoc, req, operation }` → core
`{ doc, id }` (`postRead`), `{ id, actor }` (`preDelete`). Return the
transformed doc from `preValidate` / `postValidate` / `postRead`; throw to
abort a write. Keep hooks under about 50ms. Replace `req.payload.find(…)` with
`queryDocuments`/`readDocument` from `@tanstack/cms-core/server`, and attach
`queryDocuments`/`readDocumentAs` from `@tanstack/cms-core/server`, and attach
those hooks in the runtime config
(`defineCms(definition, { collections: { post: { hooks } } })`). Hooks that
only fan out to other systems (cache purges, search indexing) usually become
Expand Down Expand Up @@ -272,7 +272,7 @@ custom nodes and list what isn't converted in the gap report. Self-test:
survived (titles, slugs, a Lexical-converted body); and loading through the
engine works (`seedContent({ force: true })` or `parseCmsExport` +
`importContent` from `@tanstack/cms-core/server`, then `queryDocuments` /
`readDocument`, with `populate: true` for relations). `closeStore()` after
`readDocumentAs`, with `populate: true` for relations). `closeStore()` after
each test.
- Live check: `pnpm --filter <app> dev`, then
`curl -X POST localhost:<port>/api/cms/v1/ops/listDocumentSummaries -H 'content-type: application/json' -d '{"collection":"post","status":"all"}'`
Expand Down
39 changes: 25 additions & 14 deletions .claude/skills/voting/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@ they sort and filter through the indexed read path), and the write path is a
server function composed from the same store primitives the admin uses.

All store functions from `@tanstack/cms-core/server` are **async** —
`await` every `readDocument`, `queryDocuments`, `commitDocument`, and
`deleteDocument`.
`await` every `readDocumentAs`, `queryDocumentsAs`, `commitDocument`, and
`deleteDocument`. Every read takes an access context: `publicContext()` for
what a visitor may see (published posts), and a named
`systemContext(reason)` for the server-owned vote records.

## 0. Prerequisites

Expand Down Expand Up @@ -124,22 +126,29 @@ import { createServerFn } from '@tanstack/react-start'
import {
commitDocument,
deleteDocument,
queryDocuments,
readDocument,
publicContext,
queryDocumentsAs,
readDocumentAs,
requireAuthenticated,
systemContext,
} from '@tanstack/cms-core/server'

// Votes and the cached tallies are maintained by the server, not the voter.
const VOTES = systemContext('voting: votes and tallies are server-owned')

export async function castVoteForVoter(
postId: string,
value: 1 | -1,
voterId: string,
) {
if (value !== 1 && value !== -1) throw new Error('Invalid vote')
const post = await readDocument('post', postId)
if (!post) throw new Error('Post not found')
// Voters only ever see published posts.
if (!(await readDocumentAs(publicContext(), 'post', postId))) {
throw new Error('Post not found')
}

const id = voteId(postId, voterId)
const existing = await readDocument('vote', id)
const existing = await readDocumentAs(VOTES, 'vote', id)
if (existing && Number(existing.value) === value) {
await deleteDocument('vote', id, { actor: voterId }) // retract
} else {
Expand All @@ -151,12 +160,15 @@ export async function castVoteForVoter(
)
}
// Recount from source; never trust client-supplied counts.
const votes = await queryDocuments({
const votes = await queryDocumentsAs(VOTES, {
collection: 'vote',
where: { post: postId },
})
const upvotes = votes.items.filter((v) => Number(v.doc.value) > 0).length
const downvotes = votes.items.filter((v) => Number(v.doc.value) < 0).length
// Re-read the stored post: a public read may leave out fields the commit
// would then drop.
const post = await readDocumentAs(VOTES, 'post', postId)
await commitDocument(
'post',
postId,
Expand All @@ -178,7 +190,7 @@ export const castVote = createServerFn({ method: 'POST' })
})
```

The worked example also resolves posts by slug (`readDocumentBySlug`) so
The worked example also resolves posts by slug (`readDocumentBySlugAs`) so
links using either form work.

**Atomicity gap (report it, don't hide it).** `commitDocument` and
Expand Down Expand Up @@ -216,9 +228,9 @@ report (§8). Concurrent votes on the same post can also race the tally
```ts
// What the UI needs for one post:
export async function getVoteState(postId: string, voterId?: string) {
const post = await readDocument('post', postId)
const post = await readDocumentAs(publicContext(), 'post', postId)
const mine = voterId
? await readDocument('vote', voteId(postId, voterId))
? await readDocumentAs(VOTES, 'vote', voteId(postId, voterId))
: null
return {
upvotes: Number(post?.upvotes ?? 0),
Expand All @@ -230,9 +242,8 @@ export async function getVoteState(postId: string, voterId?: string) {

// Top posts — score is an indexed number field:
export async function getTopPosts(limit = 10) {
return queryDocuments({
return queryDocumentsAs(publicContext(), {
collection: 'post',
publishedOnly: true,
sort: { field: 'score', dir: 'desc' },
limit,
})
Expand Down Expand Up @@ -289,7 +300,7 @@ a temp `dataDir` per test via `defineCms({ dataDir, collections: [...] })` and
- invalid value / unknown post / malformed voter id throw
- `getVoteState` reports the caller's own vote
- `getTopPosts` orders by score desc
- vote docs appear in `queryDocuments({ collection: 'vote' })` (auditability)
- vote docs appear in `queryDocumentsAs(VOTES, { collection: 'vote' })` (auditability)

Then write the **gap report**: every place where you reached for something
the core doesn't have. Known ones in 1.0: composable transactions across
Expand Down
4 changes: 2 additions & 2 deletions .claude/skills/wordpress-to-tanstack-cms/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ WXR reader (`parseWxr`, `resolveFeaturedImages`). Self-tests:
titles, slugs, authors, terms, featured images, and a Gutenberg and a
classic body survived; loading through the engine works
(`seedContent({ force: true })` or `parseCmsExport` + `importContent`, then
`queryDocuments({ where: { categories: '<term>' } })` and `readDocument`);
`queryDocumentsAs(ctx, { where: { categories: '<term>' } })` and `readDocumentAs`);
and `resolveRedirect('/<old-permalink>/')` from `@tanstack/cms-core/server`
returns the new URL. `closeStore()` after each test.
- Live check: `pnpm --filter <app> dev`, then
Expand All @@ -216,7 +216,7 @@ tables you used, the HTML/Gutenberg coverage, how the content was loaded, and a

- **Taxonomy archives and hierarchy** — categories/tags are `multiselect`
values (parents flattened); `/category/<slug>` and `/tag/<slug>` archive
pages need app routes (`queryDocuments({ where })`).
pages need app routes (`queryDocumentsAs(ctx, { where })`).
- **Media bytes** — `hero`/inline images migrate as URLs pointing at the old
`wp-content/uploads` (or CDN). Re-home them into the media library
(`/api/media`, local or `s3Media()`) and rewrite references before the old
Expand Down
Loading
Loading