Repository navigation
fix(core): implement pagination for search() and searchCollection() (#1463) - #1578
Conversation
…1463) The search API advertised keyset pagination through its types (SearchOptions.cursor, SearchResponse.nextCursor) but searchWithDb never read the incoming cursor nor populated nextCursor, so results were silently capped at `limit` with no way to fetch a second page — "load more" buttons wired against the documented shape never appeared. Results are merged from per-collection FTS queries and re-sorted by score, so there is no single stable keyset column to encode the way getEmDashCollection does. Page the merged, score-sorted set by offset instead, carried opaquely in the cursor's orderValue (reusing encodeCursor/decodeCursor for the same base64-JSON shape and InvalidCursorError handling). Each collection fetches its top (offset + limit + 1) rows so the merged window ranks correctly and a further page is detectable; a nextCursor is issued only when more results exist past the page. searchCollection() gets the same treatment. The /_emdash/api/search endpoint now accepts a `cursor` query param and returns nextCursor; a malformed cursor surfaces as a 400 INVALID_CURSOR via the existing handleError mapping. Co-Authored-By: Claude Opus 4.8 <[email protected]>
🦋 Changeset detectedLatest commit: b5b49bd The changes in this PR will be included in the next version bump. This PR includes changesets to release 16 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
|
Could not push formatting changes to this fork. The contributor may have "Allow edits by maintainers" disabled. Please run the formatter locally: |
@emdash-cms/admin
@emdash-cms/auth
@emdash-cms/auth-atproto
@emdash-cms/blocks
@emdash-cms/cloudflare
@emdash-cms/contentful-to-portable-text
emdash
create-emdash
@emdash-cms/gutenberg-to-portable-text
@emdash-cms/plugin-cli
@emdash-cms/plugin-types
@emdash-cms/registry-client
@emdash-cms/registry-lexicons
@emdash-cms/sandbox-workerd
@emdash-cms/x402
@emdash-cms/plugin-ai-moderation
@emdash-cms/plugin-atproto
@emdash-cms/plugin-audit-log
@emdash-cms/plugin-color
@emdash-cms/plugin-embeds
@emdash-cms/plugin-field-kit
@emdash-cms/plugin-forms
@emdash-cms/plugin-webhook-notifier
commit: |
Convert code-block indentation to tabs to satisfy `oxfmt --check`. Co-Authored-By: Claude Opus 4.8 <[email protected]>
There was a problem hiding this comment.
This is the right change: the search API has been advertising cursor/nextCursor that searchWithDb simply ignored, so any "load more" wired against it was broken. Offset-based pagination is a reasonable fit here because cross-collection results are merged and re-sorted by bm25, so there is no stable per-row keyset to encode.
The implementation is sound for the chosen approach. The per-collection fetch of offset + limit + 1 is sufficient to produce the globally-merged window [offset, offset + limit) (any row beyond that window has a within-collection rank of at least offset + limit, so it cannot appear earlier globally), and allResults.length > offset + limit correctly detects a next page. Tests cover the basic cursor walk, final-page omission, malformed cursor rejection, and the single-collection path.
Three gaps remain:
- MCP search tool is now inconsistent. It calls
searchWithDbbut does not expose acursorparameter, while other MCP list tools do. Pagination works from the HTTP API and the programmaticsearch()function, but not from MCP. decodeSearchOffsetdoesn't verify the cursor marker. It readsorderValuebut ignores theidfield, so a numericorderValuefrom an unrelated cursor (e.g. a content-list cursor) is accepted as a search offset.- No upper bound on decoded offset. Because the cursor is only base64-JSON — not signed — a client can decode, substitute a huge integer, and re-encode. That makes a single request fetch
offset + limit + 1rows per collection, which is a straightforward deep-pagination DoS amplification.
None of these are merge blockers on their own, but they are real consistency/security holes that should be closed before this ships.
Findings
-
[needs fixing]
packages/core/src/mcp/server.ts:1739The MCP
searchtool callssearchWithDb, which now supportscursor, but the tool's input schema does not include acursorparameter. Other MCP list tools already accept one (e.g.cursor: z.string().min(1).max(2048).optional()). Without it, MCP clients cannot consume the new pagination, leaving the MCP surface inconsistent with the HTTP/programmatic API.limit: z.number().int().min(1).max(50).optional().describe("Max results (default 20)"), cursor: z.string().min(1).max(2048).optional().describe("Pagination cursor from a previous response"),Then pass
cursor: args.cursorto thesearchWithDbcall below. -
[needs fixing]
packages/core/src/search/query.ts:48decodeSearchOffsetextractsorderValuebut ignores the cursor marker stored in theidslot. A cursor from another API (e.g. a content-list cursor) whoseorderValuehappens to parse as an integer will be accepted as a search offset, producing the wrong page silently instead of failing fast.Validate that
id === SEARCH_CURSOR_MARKERbefore trustingorderValue:function decodeSearchOffset(cursor: string): number { const { orderValue, id } = decodeCursor(cursor); if (id !== SEARCH_CURSOR_MARKER) { throw new InvalidCursorError(cursor); } const offset = Number(orderValue); if (!Number.isInteger(offset) || offset < 0) { throw new InvalidCursorError(cursor); } return offset; } -
[needs fixing]
packages/core/src/search/query.ts:48The decoded offset is unbounded. Because the cursor is just base64-encoded JSON, a client can forge one with a very large offset, causing
searchWithDbto requestoffset + limit + 1rows per collection in a single query — a deep-pagination DoS amplification.Add a sane maximum offset and reject anything beyond it as an invalid cursor:
/** Reasonable ceiling for search pagination offset to bound per-collection fetches. */ const MAX_SEARCH_OFFSET = 10_000; function decodeSearchOffset(cursor: string): number { const { orderValue, id } = decodeCursor(cursor); if (id !== SEARCH_CURSOR_MARKER) { throw new InvalidCursorError(cursor); } const offset = Number(orderValue); if (!Number.isInteger(offset) || offset < 0 || offset > MAX_SEARCH_OFFSET) { throw new InvalidCursorError(cursor); } return offset; }(The exact cap can be tuned; the important part is bounding the value before it reaches the LIMIT clause.)
…, cap offset Addresses review findings on #1578: - MCP `search` tool now accepts and passes through a `cursor` argument so MCP clients can consume the pagination the API and search() already advertise. - decodeSearchOffset now checks the cursor's marker before trusting orderValue, so a numeric orderValue from an unrelated cursor type (e.g. content-list) is rejected instead of silently misread. - Adds a MAX_SEARCH_OFFSET ceiling so a forged cursor can't force an unbounded offset + limit + 1 fetch per collection.
What does this PR do?
The search API advertised keyset pagination through its types —
SearchOptions.cursorandSearchResponse.nextCursor— butsearchWithDbnever read the incoming cursor nor populatednextCursor. Results were silently capped atlimitwith no way to fetch a second page, so any "load more" wired against the documented shape got a button that never appears (and acursorthat's discarded).This implements real pagination for both
search()andsearchCollection().Why offset, not pure keyset: search results are merged from per-collection FTS queries and re-sorted by
bm25score, so there's no single stable keyset column to encode the waygetEmDashCollectionencodes(orderValue, id). Instead we page the merged, score-sorted set by offset, carried opaquely in the cursor'sorderValue— reusingencodeCursor/decodeCursorso the cursor keeps the same base64-JSON shape andInvalidCursorErrorhandling as the rest of the API.Each collection fetches its top
(offset + limit + 1)rows, which is exactly what's needed for the merged window[offset, offset + limit)to rank correctly even when the whole window comes from one collection, plus one row to detect a further page. AnextCursoris issued only when at least one result exists past the page.search()/searchWithDbandsearchCollection()both honourcursorand returnnextCursor./_emdash/api/searchendpoint now accepts acursorquery param and returnsnextCursor; a malformed cursor surfaces as400 INVALID_CURSORvia the existinghandleErrormapping.Closes #1463
Type of change
Checklist
pnpm typecheckpassespnpm lintpassespnpm testpasses (or targeted tests for my change)pnpm formathas been runAI-generated code disclosure
Screenshots / test output
New
tests/integration/search/pagination.test.tscovers: nextCursor presence past the limit, omission on the final page, a cursor walk over disjoint pages covering every match exactly once, malformed-cursor rejection, and single-collection pagination.