diff --git a/.changeset/39084-comment-threads-query.md b/.changeset/39084-comment-threads-query.md new file mode 100644 index 00000000000..05fc2b84c61 --- /dev/null +++ b/.changeset/39084-comment-threads-query.md @@ -0,0 +1,13 @@ +--- +'@objectstack/spec': minor +'@objectstack/objectql': patch +'@objectstack/plugin-audit': patch +'@objectstack/client': patch +--- + +feat(plugin-audit,spec,client): one read returns the comment threads on the records a list filter selects, as the caller + +Clause-②: yes (widening) +Metadata-protocol: added + +Widened: a new route, `POST /api/v1/comments/threads/query`, mounted by plugin-audit's comment registrar beside the resolution and own-comment delete doors. The body (`CommentThreadsQueryRequestSchema`, strict) names an object and carries a list's filter in the `GET /data/{object}` syntax, with `showResolved`, `onlyMine`, `limit` (1 to `COMMENT_THREADS_MAX_LIMIT`, default `COMMENT_THREADS_DEFAULT_LIMIT`) and an opaque keyset `cursor`; the answer (`CommentThreadsQueryResponseSchema`) is one page of the object's top-level comments on the records the filter selects and the caller may read, newest first, each with its record's id and display name, its reply count at any depth and its latest three distinct repliers, and the next page's cursor. Every step runs as the caller: the engine plans the caller's read of the object with the filter (`ObjectQL#planReadScope`) and places it in the comment read as one subquery, so a view past the 1,000-id cap is answered in full; its refusals are the answer (`PERMISSION_DENIED` for a caller with no read on the object or a filter on a field the caller cannot read, `INVALID_FILTER` on MongoDB and OData). A query parameter, an unknown body key, a `limit` out of range or a cursor the read did not issue is `400 VALIDATION_ERROR` before anything is read, and a filter the list read cannot lower is `400 INVALID_FILTER`, as `GET /data/{object}` answers it, never dropped; an object with `enable.feeds: false` is `403 FEEDS_DISABLED`. The read is served on a kernel with an HTTP server; the hosted dispatcher's `/comments` domain does not claim it. `client.comments.queryThreads` is its SDK method. `@objectstack/objectql` exports the `PlanReadScopeOptions` and `ReadScopeComparand` types. No new error code. `Metadata-protocol: added`: the request and response schemas enter the `api` authorable-surface shard, which the level axis reads as added keys, so `@objectstack/spec` is a `minor`; nothing an author writes in an object, view or app definition changes. diff --git a/content/docs/api/data-api.mdx b/content/docs/api/data-api.mdx index cf5c6550bf9..a541a5990c1 100644 --- a/content/docs/api/data-api.mdx +++ b/content/docs/api/data-api.mdx @@ -682,6 +682,84 @@ the approvals-family read and is unchanged. --- +## Comment threads + +The discussions on the records a list shows, in one read: what a list page's +comment panel asks. Served by `@objectstack/plugin-audit` on a kernel with an +HTTP server; the SDK method is `client.comments.queryThreads`. + +### `POST /comments/threads/query` + +The body (`CommentThreadsQueryRequestSchema`) names the object and carries the +list's own filter, in the syntax `GET /data/:object` accepts: the saved view's +filter AND the reader's temporary filters. A search box is not a filter and is +not sent. + +| Key | Meaning | +| :--- | :--- | +| `object` | The object whose records the list shows. Required; not `sys_comment`. | +| `filter` | The list's filter. Absent: every record of the object the caller may read. | +| `showResolved` | `true` answers resolved threads too. Absent: unresolved threads only. | +| `onlyMine` | `true` answers only the threads the caller started, replied in or is mentioned in. | +| `limit` | Threads per page, 1 to 50. Absent: 25. | +| `cursor` | The previous page's `nextCursor`, as it was answered. Absent: the first page. | + +The answer is one page of the object's top-level comments on the records the +filter selects and the caller may read, newest first, and the cursor of the +next page (`null` on the last): + +```json +{ "success": true, "data": { + "threads": [{ + "comment": { "id": "cmt_9", "body": "Can we ship Friday?", "author_id": "usr_1", "is_resolved": false, "created_at": "2026-12-02T09:30:00.000Z" }, + "record": { "id": "acc_1", "name": "Acme" }, + "replyCount": 4, + "repliers": [{ "id": "usr_2", "name": "Ben", "avatarUrl": null }] + }], + "nextCursor": "WyIyMDI2LTEyLTAy..." +} } +``` + +`replyCount` counts the replies under the thread at any depth; `repliers` are +the latest distinct ones, newest first, at most three. `record.name` is the +record's title field read as the caller (`Record #` and the id when it is +empty or not served). + +Every step runs as the caller. The records are the caller's own read of the +object with the filter, planned by the engine and placed in the comment read +as one subquery, so a view of any size is answered in full; where the engine +cannot prove that read it reads the ids as the caller and refuses past its cap +(`400 INVALID_FILTER`), never a part of the view. The comment read is an +ordinary read of `sys_comment`, so the comment read gate decides as on +`GET /data/sys_comment`. The cursor is a keyset over creation time and id: a +comment posted while you page does not repeat or skip a thread. + +Refusals: + +- any query parameter, a body key outside the table, a `limit` out of range, a + `cursor` the read did not issue, or `object: "sys_comment"`: `400 VALIDATION_ERROR`, + before anything is read; +- a filter the list read cannot lower (a filter array that is not a comparison, + a prefix `["and"|"or", ...]` node or a list of those, an infix join, or a + value that is neither a filter object nor a filter array): `400 INVALID_FILTER`, + before anything is read, the answer `GET /data/{object}` gives the same value; + `null` and `[]` are no filter; +- no signed-in caller: `401 UNAUTHENTICATED`; +- an unknown object: `404 OBJECT_NOT_FOUND`; an object the data door does not + serve: the data door's own refusal; an object with `enable.feeds: false`: + `403 FEEDS_DISABLED`; +- a caller with no read on the object, or a filter naming a field the caller + cannot read: `403 PERMISSION_DENIED`, the object read's own refusal, never an + empty answer; +- an object on a driver that cannot run the subquery (MongoDB, OData): + `400 INVALID_FILTER`. + +A kernel with no HTTP server (a hosted tenant kernel) serves the other comment +doors through the dispatcher's `/comments` domain, which does not claim this +read, so it is not served there. + +--- + ## Analytics Semantic BI queries using a cube-style API. Provided by `@objectstack/service-analytics` — diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 60b69060fc0..6a664ccff33 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1756 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1761 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -23,7 +23,7 @@ counts are sums of the rows they head. Regenerate with | Module | Pages | Schemas | Description | | :--- | ---: | ---: | :--- | | [AI Protocol](/docs/references/ai) | 18 | 108 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | -| [API Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/api) | 38 | 534 | REST contracts, endpoints, routing, realtime, batch, discovery. | +| [API Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/api) | 39 | 539 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Automation Protocol](/docs/references/automation) | 16 | 82 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. | | [Data Protocol](/docs/references/data) | 35 | 198 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | | [Identity Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/identity) | 5 | 27 | Users and accounts, organizations, positions, SCIM provisioning. | @@ -36,7 +36,7 @@ counts are sums of the rows they head. Regenerate with | [Studio Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/system) | 40 | 298 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 17 | 188 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **225** | **1756** | 14 protocol modules | +| **Total** | **226** | **1761** | 14 protocol modules | --- @@ -71,7 +71,7 @@ Agents, tools, skills, RAG and knowledge sources, model registry, conversations. ## API Protocol -**Source:** `packages/spec/src/api/` · **Import:** `@objectstack/spec/api` · **38 pages, 534 schemas** +**Source:** `packages/spec/src/api/` · **Import:** `@objectstack/spec/api` · **39 pages, 539 schemas** REST contracts, endpoints, routing, realtime, batch, discovery. @@ -84,6 +84,7 @@ REST contracts, endpoints, routing, realtime, batch, discovery. | [`auth-endpoints.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/auth-endpoints.md) | `AuthEndpoint`, `AuthFeaturesConfig`, `AuthProviderInfo`, `DeviceRequestResponse`, `DeviceTokenResponse`, `EmailPasswordConfigPublic`, `GetAuthConfigResponse`, `OneTimeTokenHandoffQuery`, `OneTimeTokenVerifyRequest`, `OneTimeTokenVerifyResponse`, `OrganizationEditionChoice` | | [`automation-api.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/automation-api.md) | `AutomationApiErrorCode`, `AutomationFlowPathParams`, `AutomationRunPathParams`, `CloneFlowRequest`, `CloneFlowResponse`, `CreateFlowRequest`, `CreateFlowResponse`, `DeleteFlowRequest`, `DeleteFlowResponse`, `FlowFailureDetails`, `FlowInnerRefusal`, `GetFlowRequest`, `GetFlowResponse`, `GetRunRequest`, `GetRunResponse`, `ListRunsRequest`, `ListRunsResponse`, `RecordUpdateStart`, `RecordUpdateStartsRequest`, `RecordUpdateStartsResponse`, `ResumeFailureDetails`, `ToggleFlowRequest`, `ToggleFlowResponse`, `TriggerFlowRequest`, `TriggerFlowResponse`, `UpdateFlowRequest`, `UpdateFlowResponse` | | [`batch.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/batch.md) | `BatchConfig`, `BatchOperationResult`, `BatchOperationType`, `BatchOptions`, `BatchRecord`, `BatchUpdateRequest`, `BatchUpdateResponse`, `CrossObjectBatchDroppedFields`, `CrossObjectBatchOperation`, `CrossObjectBatchRequest`, `CrossObjectBatchResponse`, `DeleteManyRequest`, `UpdateManyRecord`, `UpdateManyRequest` | +| [`comment-threads.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/comment-threads.md) | `CommentThread`, `CommentThreadRecord`, `CommentThreadReplier`, `CommentThreadsQueryRequest`, `CommentThreadsQueryResponse` | | [`contract.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/contract.md) | `ApiError`, `BaseResponse`, `BatchLoadingStrategy`, `BulkRequest`, `BulkResponse`, `CreateRequest`, `DataLoaderConfig`, `DeleteResponse`, `ExportRequest`, `IdRequest`, `ListRecordResponse`, `ModificationResult`, `QueryOptimizationConfig`, `RecordData`, `SingleRecordResponse`, `UpdateRequest` | | [`discovery.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/discovery.md) | `ApiRoutes`, `AuthFamilies`, `CapabilityDescriptor`, `Discovery`, `DiscoveryEnvironment`, `EnvironmentType`, `RouteHealthEntry`, `RouteHealthReport`, `ServiceInfo`, `ServiceSelfInfo`, `ServiceStatus`, `WellKnownCapabilities` | | [`dispatcher.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/dispatcher.md) | `DispatcherConfig`, `DispatcherErrorCode`, `DispatcherErrorResponse`, `DispatcherRoute` | diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md index 268737d3e5b..400ff95902c 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md @@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate. | Dir | Sites | |---|---| -| `api/` | 550 | +| `api/` | 555 | diff --git a/packages/client/src/client-url-conformance.test.ts b/packages/client/src/client-url-conformance.test.ts index 1e21171a8d0..29d3d3d035b 100644 --- a/packages/client/src/client-url-conformance.test.ts +++ b/packages/client/src/client-url-conformance.test.ts @@ -50,6 +50,7 @@ import { REST_ROUTE_LEDGER } from '../../rest/src/rest-route-ledger'; import { STORAGE_ROUTE_LEDGER } from '../../services/service-storage/src/storage-route-ledger'; import { I18N_ROUTE_LEDGER } from '../../services/service-i18n/src/i18n-route-ledger'; import { AUTH_ROUTE_LEDGER } from '../../plugins/plugin-auth/src/auth-route-ledger'; +import { COMMENT_ROUTE_LEDGER } from '../../plugins/plugin-audit/src/comment-route-ledger'; const BASE = 'http://localhost:9'; @@ -119,6 +120,10 @@ const PATTERNS: Pattern[] = [ ...STORAGE_ROUTE_LEDGER.map((r) => r.route).flatMap((r) => compile(r, '', 'storage')), ...I18N_ROUTE_LEDGER.map((r) => r.route).flatMap((r) => compile(r, '', 'i18n')), ...AUTH_ROUTE_LEDGER.map((r) => r.route).flatMap((r) => compile(r, '', 'auth')), + // The comment registrar's own mount (plugin-audit, self-hosted only): the + // threads read is SDK surface (`comments.queryThreads`), so the URL that + // method builds is matched against the ledger of the registrar that mounts it. + ...COMMENT_ROUTE_LEDGER.map((r) => r.route).flatMap((r) => compile(r, '', 'comments')), ] // Exact rows before wildcard families, so a URL that a real route covers is // never CREDITED to a `**` prefix claim that happens to sit earlier in the @@ -481,3 +486,30 @@ describe('client URL conformance ↔ the union of all four route ledgers (#3642) ).toBe(0); }); }); + +describe('the comment registrar ledger ↔ @objectstack/client', () => { + it('every comment ledger row naming a client method resolves to a real function', () => { + const client = new ObjectStackClient({ baseUrl: BASE }); + const broken = COMMENT_ROUTE_LEDGER.filter((e) => e.client != null) + .filter((e) => typeof e.client!.split('.').reduce((o, k) => (o == null ? o : (o as Record)[k]), client) !== 'function') + .map((e) => `${e.route} → client.${e.client}`); + expect(broken).toEqual([]); + expect(COMMENT_ROUTE_LEDGER.filter((e) => e.disposition === 'sdk').map((e) => e.client)).toEqual(['comments.queryThreads']); + }); + + it('comments.queryThreads POSTs the request as the JSON body to the threads read, and resolves the answer\'s data', async () => { + const data = { threads: [], nextCursor: null }; + const calls: Array<{ verb: string; url: string; body: unknown }> = []; + const client = new ObjectStackClient({ + baseUrl: BASE, + fetch: async (input: RequestInfo | URL, init?: RequestInit) => { + calls.push({ verb: (init?.method ?? 'GET').toUpperCase(), url: String(input), body: init?.body }); + return makeResponse({ success: true, data }); + }, + }); + const request = { object: 'account', filter: [['status', '=', 'open']], showResolved: true, limit: 10, cursor: 'c' }; + await expect(client.comments.queryThreads(request)).resolves.toEqual(data); + expect(calls.map((c) => `${c.verb} ${c.url}`)).toEqual([`POST ${BASE}/api/v1/comments/threads/query`]); + expect(JSON.parse(String(calls[0].body))).toEqual(request); + }); +}); diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index 209a0771218..67fa63ba180 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -9,6 +9,8 @@ import { GetRecordLocksResponse, RecordPageRequest, RecordPageResponse, + CommentThreadsQueryRequest, + CommentThreadsQueryResponse, // [#32200] The batch dataset-query answer `analytics.queryDatasetBatch` // resolves to the `data` of. DatasetQueryBatchResponse, @@ -7468,6 +7470,33 @@ export class ObjectStackClient { * record, served under the data surface. Every route 501s * [NOT_IMPLEMENTED] on deployments without the sharing service. */ + /** + * Comment threads across records. Served by plugin-audit's comment + * registrar on a kernel with an HTTP server. + */ + comments = { + /** + * The comment threads on the records a list filter selects — + * `POST /api/v1/comments/threads/query`, declared by + * `CommentThreadsQueryRequestSchema` / `CommentThreadsQueryResponseSchema` + * (`@objectstack/spec/api`). One page of top-level comments on the records + * of `request.object` that `request.filter` (the `GET /data/{object}` + * filter syntax) selects and the caller may read, newest first, each with + * its record's id and name, its reply count and its latest repliers. + * Pass the answer's `nextCursor` back as `request.cursor` for the next + * page. Unresolved threads only unless `showResolved`; only the caller's + * own threads (started, replied in, mentioned in) when `onlyMine`. A + * caller with no read on the object rejects with that read's refusal. + */ + queryThreads: async (request: CommentThreadsQueryRequest): Promise => { + const res = await this.fetch(`${this.baseUrl}/api/v1/comments/threads/query`, { + method: 'POST', + body: JSON.stringify(request), + }); + return this.unwrapResponse(res); + }, + }; + shares = { /** List the sharing grants on a record. */ list: async (object: string, recordId: string): Promise => { @@ -9694,6 +9723,8 @@ export type { RecordLockEntry, RecordPageRequest, RecordPageResponse, + CommentThreadsQueryRequest, + CommentThreadsQueryResponse, RealtimeConnectRequest, RealtimeConnectResponse, RealtimeSubscribeRequest, diff --git a/packages/objectql/src/index.ts b/packages/objectql/src/index.ts index bed59b9a9ed..66a935ff7e6 100644 --- a/packages/objectql/src/index.ts +++ b/packages/objectql/src/index.ts @@ -278,6 +278,10 @@ export type { DatasourceDef } from './engine.js'; // refuses the filter rather than truncate it, and its words name this number. // Exported so a caller running the two-step route itself can page by it. export { RELATION_FILTER_ID_CAP } from './relation-filter-lowering.js'; +// What `ObjectQL#planReadScope` takes besides the two object names, and the `$in` +// comparand it answers, so an in-process caller can name both (the comment threads +// read in plugin-audit plans and places one per request). +export type { PlanReadScopeOptions, ReadScopeComparand } from './engine-query-lowering.js'; // [ADR-0155 D4, plan step 5] The seam's recognition of D4's two classes and // its reader of a driver's `fixedReadLeaves` declaration, so an evaluator that // declines before it compiles (the analytics native compiler) asks the seam diff --git a/packages/plugins/plugin-audit/src/audit-plugin.ts b/packages/plugins/plugin-audit/src/audit-plugin.ts index bce2850adc2..95445a23cb1 100644 --- a/packages/plugins/plugin-audit/src/audit-plugin.ts +++ b/packages/plugins/plugin-audit/src/audit-plugin.ts @@ -73,6 +73,7 @@ import { type CommentDoorsEngine, type CommentPostingGate, } from './comment-routes.js'; +import { COMMENT_THREADS_QUERY_ROUTE } from './comment-threads-query.js'; import { createCommentDoorMember } from './comment-doors-member.js'; import { admitMentionRecipients } from './mention-recipient-gate.js'; import { installActivityReadVisibility } from './activity-read-visibility.js'; @@ -1159,7 +1160,11 @@ export class AuditPlugin implements Plugin { * (`comment-routes.ts`): whoever can read a thread resolves and reopens * it, and a member removes a comment they wrote (ruling records * 7063285032 and 7069889899), past the row floor and without a `delete` - * grant. + * grant; + * - the comment threads read (`comment-threads-query.ts`): the threads on + * the records a list filter selects, as the caller. It is mounted here + * only: the dispatcher's `/comments` domain does not claim it, so a kernel + * with no HTTP server does not serve it, and the line below says so. * * Every service the doors read is read per request, so a provider that * registers after this hook is still seen. A kernel with no HTTP server (a @@ -1184,14 +1189,16 @@ export class AuditPlugin implements Plugin { ctx.logger.info( `AuditPlugin: comment doors mounted on the 'comments' service for the dispatcher's /comments domain ` + `(no HTTP server on this kernel): DELETE ${COMMENT_REACTION_REMOVE_ROUTE}, PUT ${COMMENT_RESOLUTION_ROUTE} ` + - `and DELETE ${COMMENT_REMOVE_ROUTE}`, + `and DELETE ${COMMENT_REMOVE_ROUTE}; the comment threads read POST ${COMMENT_THREADS_QUERY_ROUTE} is not ` + + `served on this kernel (the dispatcher's /comments domain does not claim it; it is mounted only on a kernel ` + + `with an HTTP server)`, ); return; } registerCommentDoors(http, ctx); ctx.logger.info( `AuditPlugin: comment doors mounted at DELETE ${COMMENT_REACTION_REMOVE_ROUTE}, PUT ${COMMENT_RESOLUTION_ROUTE} ` + - `and DELETE ${COMMENT_REMOVE_ROUTE}`, + `and DELETE ${COMMENT_REMOVE_ROUTE}, and the comment threads read at POST ${COMMENT_THREADS_QUERY_ROUTE}`, ); } @@ -1228,7 +1235,10 @@ export class AuditPlugin implements Plugin { * read per request. The ONE registration both faces run: the self-hosted mount * on the kernel's `http.server` (`mountCommentDoors`) and the private table * behind the `comments` slot's `handleCommentDoor` (`comment-doors-member.ts`), - * so the two cannot answer a request differently. + * so the two cannot answer a request differently. `registerCommentDoorsRoutes` + * also mounts the comment threads read; the member's table carries it too, but + * the member matches only the three doors, so only the self-hosted mount + * serves it. */ function registerCommentDoors(http: IHttpServer, ctx: PluginContext): void { const optional = (name: string): T | undefined => { diff --git a/packages/plugins/plugin-audit/src/comment-route-ledger.conformance.test.ts b/packages/plugins/plugin-audit/src/comment-route-ledger.conformance.test.ts index dc45bce63f6..bd934cd23ad 100644 --- a/packages/plugins/plugin-audit/src/comment-route-ledger.conformance.test.ts +++ b/packages/plugins/plugin-audit/src/comment-route-ledger.conformance.test.ts @@ -3,7 +3,7 @@ /** * Comment-door route-ledger conformance — the package-local guard every * `*-route-ledger.ts` pairs with. `registerCommentDoorsRoutes` is a - * standalone, synchronous function that calls `http.put` and `http.delete` and touches neither + * standalone, synchronous function that calls `http.put`, `http.delete` and `http.post` and touches neither * argument before a request arrives, so a capturing mock `IHttpServer` * enumerates its real surface (the seam the print, storage and settings ledgers * use), and the two directions fail here by name on every `pnpm test` of this @@ -58,4 +58,10 @@ describe('comment-door route ledger ↔ registerCommentDoorsRoutes enumeration', expect(live.size).toBe(ledgerKeys().size); expect(COMMENT_ROUTE_LEDGER.every((e) => e.disposition === 'sdk' || (e.note ?? '').length > 0)).toBe(true); }); + + it('an sdk row names the client method, and the threads read is one', () => { + const sdk = COMMENT_ROUTE_LEDGER.filter((e) => e.disposition === 'sdk'); + expect(sdk.filter((e) => !e.client).map((e) => e.route)).toEqual([]); + expect(sdk.map((e) => `${e.route} → ${e.client}`)).toContain('POST /api/v1/comments/threads/query → comments.queryThreads'); + }); }); diff --git a/packages/plugins/plugin-audit/src/comment-route-ledger.ts b/packages/plugins/plugin-audit/src/comment-route-ledger.ts index 361bca2bbe7..e44902de29b 100644 --- a/packages/plugins/plugin-audit/src/comment-route-ledger.ts +++ b/packages/plugins/plugin-audit/src/comment-route-ledger.ts @@ -11,9 +11,12 @@ * fails when the registrar mounts a route with no row here, and when a row * names a route it no longer mounts. * - * A GAP, NOT SDK SURFACE YET. The consumer is the console's comment panel (its - * ✓ and its Delete on the viewer's own comment). `@objectstack/client` has no - * method for either, so both rows are acknowledged `gap`s. + * TWO GAPS AND ONE SDK ROW. The consumer of the two doors is the console's + * comment panel (its ✓ and its Delete on the viewer's own comment). + * `@objectstack/client` has no method for either, so both rows are + * acknowledged `gap`s. The comment threads read is `sdk`: `client.comments.queryThreads` + * (the client's URL conformance suite matches the URL that method builds + * against this ledger, and resolves the method this row names). * * This module is package-internal (not exported from the index): it is the * guard's data, not public API. It stays import-free. @@ -37,4 +40,5 @@ export const COMMENT_ROUTE_LEDGER: readonly CommentRouteLedgerEntry[] = [ note: "resolve or reopen a thread by its top-level sys_comment row for any reader of it, writing is_resolved alone; the console's comment panel is the consumer and the SDK has no method yet" }, { route: 'DELETE /api/v1/comments/:id', family: 'comments', disposition: 'gap', note: "remove the caller's own sys_comment row, needing no object delete grant; the console's comment panel is the consumer and the SDK has no method yet" }, + { route: 'POST /api/v1/comments/threads/query', family: 'comments', disposition: 'sdk', client: 'comments.queryThreads' }, ]; diff --git a/packages/plugins/plugin-audit/src/comment-routes.test.ts b/packages/plugins/plugin-audit/src/comment-routes.test.ts index 2234ca13050..24364aacd2e 100644 --- a/packages/plugins/plugin-audit/src/comment-routes.test.ts +++ b/packages/plugins/plugin-audit/src/comment-routes.test.ts @@ -22,6 +22,7 @@ import { type CommentDoorsEngine, type CommentDoorsRoutesDeps, } from './comment-routes.js'; +import { COMMENT_THREADS_QUERY_ROUTE } from './comment-threads-query.js'; type Handler = (req: unknown, res: unknown) => unknown; @@ -62,11 +63,15 @@ function untouchedEngine() { const MEMBER = { userId: 'u_member', positions: ['org_member'], permissions: [] } as any; describe('the comment doors — what the registrar mounts', () => { - it('mounts the resolution door and the own-comment delete door, and touches nothing before a request', () => { + it('mounts the resolution door, the own-comment delete door and the threads read, and touches nothing before a request', () => { const getEngine = vi.fn(); const resolveCaller = vi.fn(); const routes = mount({ getEngine, resolveCaller }); - expect([...routes.keys()].sort()).toEqual([`DELETE ${COMMENT_REMOVE_ROUTE}`, `PUT ${COMMENT_RESOLUTION_ROUTE}`]); + expect([...routes.keys()].sort()).toEqual([ + `DELETE ${COMMENT_REMOVE_ROUTE}`, + `POST ${COMMENT_THREADS_QUERY_ROUTE}`, + `PUT ${COMMENT_RESOLUTION_ROUTE}`, + ]); expect(getEngine).not.toHaveBeenCalled(); expect(resolveCaller).not.toHaveBeenCalled(); }); diff --git a/packages/plugins/plugin-audit/src/comment-routes.ts b/packages/plugins/plugin-audit/src/comment-routes.ts index 02620df1f63..13efac49a9d 100644 --- a/packages/plugins/plugin-audit/src/comment-routes.ts +++ b/packages/plugins/plugin-audit/src/comment-routes.ts @@ -25,6 +25,7 @@ import { COMMENT_RESOLVED_FIELD, refuseResolutionOnReply, } from './comment-resolution.js'; +import { registerCommentThreadsQueryRoute, type CommentThreadsEngine } from './comment-threads-query.js'; /** * The comment doors: two verbs a member uses on `sys_comment` rows that the @@ -36,6 +37,11 @@ import { * - **The own-comment delete door**, `DELETE /api/v1/comments/:id`: remove a * comment the caller wrote. * + * The registrar also mounts the comment threads read, + * `POST /api/v1/comments/threads/query` (`comment-threads-query.ts`): the + * threads on the records a list filter selects, read as the caller. It is a + * read, not a door past the row floor, and lives in its own module. + * * ## Why doors, and not the data door * * The platform's row floor (`owner_only_writes`, the default permission sets) @@ -185,10 +191,19 @@ export interface CommentPostingGate { canWriteObject?(object: string, operation: 'insert' | 'update', context?: unknown, data?: unknown): Promise; } -/** Mount both comment doors on `http`. Nothing on `deps` is called until a request arrives. */ +/** + * Mount both comment doors and the comment threads read on `http`. Nothing on + * `deps` is called until a request arrives. The threads read asks the same + * engine for `planReadScope` and `getSchema` per request, and answers `503` + * when the registered engine has neither. + */ export function registerCommentDoorsRoutes(http: IHttpServer, deps: CommentDoorsRoutesDeps): void { http.put(COMMENT_RESOLUTION_ROUTE, (req, res) => handleResolution(req, res, deps)); registerOwnRowDeleteRoute(http, COMMENT_REMOVAL_DOOR, deps); + registerCommentThreadsQueryRoute(http, { + getEngine: () => deps.getEngine?.() as unknown as CommentThreadsEngine | undefined, + resolveCaller: (req) => deps.resolveCaller(req), + }); } /** The stored resolution the door answers with. */ diff --git a/packages/plugins/plugin-audit/src/comment-threads-query.integration.test.ts b/packages/plugins/plugin-audit/src/comment-threads-query.integration.test.ts new file mode 100644 index 00000000000..81d0b3ae6fe --- /dev/null +++ b/packages/plugins/plugin-audit/src/comment-threads-query.integration.test.ts @@ -0,0 +1,181 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The comment threads read through the real engine — what only the real + * engine and driver decide. + * + * Same rig as `comment-participants.integration.test.ts`: real kernel, real + * ObjectQL, real AuditPlugin, real SQLite driver; the read is + * `queryCommentThreads`, the body the route runs after its shell. Pinned + * here: the list filter in its array form scoping the threads to the records + * it selects (the planned scope placed in a real comment read), top-level + * only and newest first, the reply count over nested replies and the latest + * repliers from the stored author columns, the record names by the object's + * title field, the resolved and "involving me" toggles over the stored + * columns, and the keyset cursor walking every thread exactly once while a + * comment is posted between pages and while two threads share a creation + * time. + * + * The composition with the security service — members with different row + * scope, a view past the id cap answered in full as one threads statement, + * the PostgreSQL cell — is + * `packages/qa/dogfood/test/comment-threads-query.dogfood.test.ts`, which can + * compose plugin-security and the SQL driver where this package cannot. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql'; +import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; + +import { AuditPlugin } from './audit-plugin.js'; +import { queryCommentThreads } from './comment-threads-query.js'; +import { installDefaultOrganization } from './default-organization.testkit.js'; + +const COMMENT = 'sys_comment'; +const ACCOUNT = 'ctq_account'; +const HARNESS_PACKAGE = 'com.objectstack.audit.test.comment-threads-query'; + +const SYS = { isSystem: true } as const; +const as = (userId: string) => ({ userId, positions: ['org_member'] }) as any; +const ANN = as('u_ann'); +const BEN = as('u_ben'); +const CAL = as('u_cal'); +const DEE = as('u_dee'); + +const accountObject = { + name: ACCOUNT, + label: 'Account', + nameField: 'title', + fields: { + title: { name: 'title', label: 'Title', type: 'text' as const }, + status: { name: 'status', label: 'Status', type: 'text' as const }, + }, +}; + +type Row = Record; + +describe('the comment threads read on the real engine and SQLite', () => { + let kernel: ObjectKernel; + let engine: ObjectQL; + const acc: Record = {}; + const root: Record = {}; + + const post = async (accountKey: string, by: Row, extra: Row = {}): Promise => { + const created = await engine.insert(COMMENT, { thread_id: `${ACCOUNT}:${acc[accountKey]}`, body: 'text', ...extra }, { context: by }); + return String(created.id); + }; + const read = (by: Row, request: Row) => queryCommentThreads(engine as any, { object: ACCOUNT, ...request } as any, by); + const ids = (answer: { threads: Array<{ comment: Row }> }) => answer.threads.map((t) => String(t.comment.id)); + const OPEN_FILTER = [['status', '=', 'open']]; + + beforeAll(async () => { + kernel = new ObjectKernel({ logger: { level: 'silent' } }); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new AuditPlugin()); + await kernel.bootstrap(); + engine = kernel.getService('objectql'); + const driver = new SqliteWasmDriver({ filename: ':memory:' }); + await driver.connect(); + engine.registerDriver(driver, true); + engine.registry.registerObject(accountObject as any, HARNESS_PACKAGE); + await engine.syncSchemas(); + await installDefaultOrganization(engine); + + // Five accounts; the filter `status = open` selects three of them. + for (const [key, status] of [['a1', 'open'], ['a2', 'open'], ['a3', 'open'], ['a4', 'closed'], ['a5', 'closed']] as const) { + acc[key] = String((await engine.insert(ACCOUNT, { title: `Account ${key}`, status }, { context: SYS })).id); + } + // Oldest first: a1's thread, a4's (outside the filter), a2's resolved one, a3's mention, a2's second. + root.a1 = await post('a1', ANN); + root.a4 = await post('a4', ANN); + root.a2resolved = await post('a2', BEN); + root.a3 = await post('a3', DEE, { mentions: JSON.stringify(['u_cal']) }); + root.a2 = await post('a2', DEE); + // Replies on a1's thread, one nested two deep, four distinct repliers. + const r1 = await post('a1', BEN, { parent_id: root.a1 }); + await post('a1', CAL, { parent_id: r1 }); + await post('a1', DEE, { parent_id: root.a1 }); + await post('a1', ANN, { parent_id: r1 }); + await post('a1', BEN, { parent_id: root.a1 }); + await engine.update(COMMENT, { is_resolved: true }, { where: { id: root.a2resolved }, context: SYS }); + }, 120_000); + + afterAll(async () => { + if (kernel) await Promise.race([kernel.shutdown(), new Promise((r) => setTimeout(r, 10_000))]); + }, 30_000); + + it('a filter selecting 3 of 5 records answers only the open top-level threads on those 3, newest first', async () => { + const answer = await read(ANN, { filter: OPEN_FILTER }); + expect(ids(answer)).toEqual([root.a2, root.a3, root.a1]); + expect(answer.nextCursor).toBeNull(); + for (const t of answer.threads) { + expect(t.comment.parent_id ?? null).toBeNull(); + expect(t.comment.object_name).toBe(ACCOUNT); + } + }); + + it('each thread carries its record\'s id and title, its replies at any depth and its latest three distinct repliers', async () => { + const answer = await read(ANN, { filter: OPEN_FILTER }); + const a1 = answer.threads.find((t) => t.comment.id === root.a1)!; + expect(a1.record).toEqual({ id: acc.a1, name: 'Account a1' }); + expect(a1.replyCount).toBe(5); + // Newest first: Ben (the last reply), Ann, Dee — Cal replied earlier and is the fourth. + expect(a1.repliers.map((r) => r.id)).toEqual(['u_ben', 'u_ann', 'u_dee']); + const a3 = answer.threads.find((t) => t.comment.id === root.a3)!; + expect(a3).toMatchObject({ record: { id: acc.a3, name: 'Account a3' }, replyCount: 0, repliers: [] }); + }); + + it('showResolved answers the resolved thread too; the object form of the same filter answers the same', async () => { + expect(ids(await read(ANN, { filter: OPEN_FILTER, showResolved: true }))).toEqual([root.a2, root.a3, root.a2resolved, root.a1]); + expect(ids(await read(ANN, { filter: { status: 'open' } }))).toEqual([root.a2, root.a3, root.a1]); + }); + + it('no filter answers every record\'s threads', async () => { + expect(ids(await read(ANN, {}))).toEqual([root.a2, root.a3, root.a4, root.a1]); + }); + + it('onlyMine answers the threads the caller started, replied in or is mentioned in', async () => { + expect(ids(await read(ANN, { filter: OPEN_FILTER, onlyMine: true }))).toEqual([root.a1]); + expect(ids(await read(CAL, { filter: OPEN_FILTER, onlyMine: true }))).toEqual([root.a3, root.a1]); + expect(ids(await read(DEE, { filter: OPEN_FILTER, onlyMine: true }))).toEqual([root.a2, root.a3, root.a1]); + expect(ids(await read(as('u_nobody'), { filter: OPEN_FILTER, onlyMine: true }))).toEqual([]); + }); + + it('limit and cursor walk every thread once, with no repeat, while a new comment is posted between pages', async () => { + const seen: string[] = []; + let cursor: string | undefined; + let posted: string | undefined; + for (let pageNo = 0; pageNo < 10; pageNo++) { + const answer = await read(BEN, { showResolved: true, limit: 2, ...(cursor ? { cursor } : {}) }); + seen.push(...ids(answer)); + if (pageNo === 0) posted = await post('a1', CAL); + if (!answer.nextCursor) break; + cursor = answer.nextCursor; + } + expect(seen).toEqual([root.a2, root.a3, root.a2resolved, root.a4, root.a1]); + expect(new Set(seen).size).toBe(seen.length); + // The comment posted mid-walk is newer than the first page, so it is the next first page's head. + expect(ids(await read(BEN, { showResolved: true, limit: 1 }))).toEqual([posted]); + await engine.delete(COMMENT, { where: { id: posted }, context: SYS }); + }); + + it('two threads with the same creation time are both answered once, ordered by id', async () => { + const tieA = await post('a5', ANN); + const tieB = await post('a5', ANN); + const driver = engine.getDriverForObject(COMMENT) as any; + const at = '2020-01-01T00:00:00.000Z'; + await driver.update(COMMENT, tieA, { created_at: at }); + await driver.update(COMMENT, tieB, { created_at: at }); + const filter = [['status', '=', 'closed']]; + const walked: string[] = []; + let cursor: string | undefined; + for (let i = 0; i < 10; i++) { + const answer = await read(ANN, { filter, limit: 1, ...(cursor ? { cursor } : {}) }); + walked.push(...ids(answer)); + if (!answer.nextCursor) break; + cursor = answer.nextCursor; + } + expect(walked).toEqual([root.a4, ...[tieA, tieB].sort().reverse()]); + }); +}); diff --git a/packages/plugins/plugin-audit/src/comment-threads-query.test.ts b/packages/plugins/plugin-audit/src/comment-threads-query.test.ts new file mode 100644 index 00000000000..bad001bd7bb --- /dev/null +++ b/packages/plugins/plugin-audit/src/comment-threads-query.test.ts @@ -0,0 +1,457 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The comment threads read's own shell and assembly + * (`comment-threads-query.ts`), over a recording engine: every refusal the + * read gives before the engine is asked, the reads it hands the engine (each + * one carrying the caller's own context, the planned scope placed in the one + * threads read), the per-request planning of that scope for two users, the + * cursor, and the thread assembly (reply count at any depth, latest distinct + * repliers, record names). + * + * The same read on the real engine and SQL driver — one statement for the + * threads, a view past the id cap answered in full, the comment read gate — + * is `comment-threads-query.integration.test.ts`; at HTTP, as members with + * different row scope, `packages/qa/dogfood/test/comment-threads-query.dogfood.test.ts`. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { AuthzStoreUnavailableError } from '@objectstack/core'; +import { COMMENT_THREADS_DEFAULT_LIMIT, COMMENT_THREADS_MAX_LIMIT } from '@objectstack/spec/api'; + +import { + COMMENT_THREADS_QUERY_ROUTE, + decodeThreadsCursor, + encodeThreadsCursor, + registerCommentThreadsQueryRoute, + threadExtras, + type CommentThreadsEngine, + type CommentThreadsQueryDeps, +} from './comment-threads-query.js'; + +type Handler = (req: unknown, res: unknown) => unknown; +type Row = Record; + +const ACCOUNT = 'account'; +const SCHEMAS: Record = { + account: { name: ACCOUNT, nameField: 'name', fields: { name: { type: 'text' }, status: { type: 'text' } } }, + quiet: { name: 'quiet', enable: { feeds: false }, fields: { name: { type: 'text' } } }, + hidden: { name: 'hidden', enable: { apiEnabled: false }, fields: { name: { type: 'text' } } }, + sys_comment: { name: 'sys_comment', fields: {} }, +}; + +const ANN = { userId: 'u_ann', positions: ['org_member'], permissions: [] } as any; +const BEN = { userId: 'u_ben', positions: ['org_member'], permissions: [] } as any; + +interface Recorded { + plans: Array<{ object: string; target: string; options: any; scope: object }>; + finds: Array<{ object: string; query: any }>; +} + +/** + * An engine that records every call. `planReadScope` answers a fresh token per + * call, so a test can tell which call's scope a later read carries. `threads` + * is what the threads read answers; replies and records come from `replies` + * and `records`. + */ +function recordingEngine(opts: { threads?: Row[]; replies?: Row[]; records?: Row[]; planError?: Error } = {}) { + const recorded: Recorded = { plans: [], finds: [] }; + const engine: CommentThreadsEngine & { recorded: Recorded } = { + recorded, + getSchema: vi.fn((object: string) => SCHEMAS[object]), + planReadScope: vi.fn(async (object: string, target: string, options: any) => { + if (opts.planError) throw opts.planError; + const scope = { planned: target, for: options?.context?.userId, n: recorded.plans.length }; + recorded.plans.push({ object, target, options, scope }); + return scope as any; + }), + find: vi.fn(async (object: string, query: any) => { + recorded.finds.push({ object, query }); + if (object === 'sys_comment' && query.where?.parent_id?.$null === true) return (opts.threads ?? []).slice(0, query.limit); + if (object === 'sys_comment') return opts.replies ?? []; + return opts.records ?? []; + }), + }; + return engine; +} + +function mount(deps: CommentThreadsQueryDeps): Handler { + let handler: Handler | undefined; + const record = (verb: string) => (path: string, h: Handler) => { + if (verb === 'POST' && path === COMMENT_THREADS_QUERY_ROUTE) handler = h; + }; + registerCommentThreadsQueryRoute( + { get: record('GET'), post: record('POST'), put: record('PUT'), patch: record('PATCH'), delete: record('DELETE') } as any, + deps, + ); + if (!handler) throw new Error('the registrar mounted no threads read'); + return handler; +} + +async function call(deps: CommentThreadsQueryDeps, req: Partial<{ query: any; body: any }>) { + const answer: { status: number; body: any } = { status: 200, body: undefined }; + const res = { + status(code: number) { + answer.status = code; + return res; + }, + json(body: unknown) { + answer.body = body; + }, + }; + await mount(deps)({ method: 'POST', path: COMMENT_THREADS_QUERY_ROUTE, params: {}, query: {}, headers: {}, ...req }, res); + return answer; +} + +const as = (caller: any, engine: CommentThreadsEngine | undefined): CommentThreadsQueryDeps => ({ + getEngine: () => engine, + resolveCaller: async () => caller, +}); + +const thread = (id: string, recordId: string, createdAt: string, extra: Row = {}): Row => ({ + id, + object_name: ACCOUNT, + record_id: recordId, + parent_id: null, + author_id: 'u_ann', + body: id, + created_at: createdAt, + ...extra, +}); + +describe('the comment threads read — answers given before the engine is asked', () => { + const untouched = (engine: ReturnType) => { + expect(engine.getSchema).not.toHaveBeenCalled(); + expect(engine.planReadScope).not.toHaveBeenCalled(); + expect(engine.find).not.toHaveBeenCalled(); + }; + + it('mounts exactly one route, and reads no service before a request', () => { + const getEngine = vi.fn(); + const resolveCaller = vi.fn(); + const routes: string[] = []; + const record = (verb: string) => (path: string) => routes.push(`${verb} ${path}`); + registerCommentThreadsQueryRoute( + { get: record('GET'), post: record('POST'), put: record('PUT'), patch: record('PATCH'), delete: record('DELETE') } as any, + { getEngine, resolveCaller }, + ); + expect(routes).toEqual([`POST ${COMMENT_THREADS_QUERY_ROUTE}`]); + expect(getEngine).not.toHaveBeenCalled(); + expect(resolveCaller).not.toHaveBeenCalled(); + }); + + it('anonymous is 401 UNAUTHENTICATED', async () => { + const engine = recordingEngine(); + const answer = await call(as({}, engine), { body: { object: ACCOUNT } }); + expect(answer.status).toBe(401); + expect(answer.body?.error?.code).toBe('UNAUTHENTICATED'); + untouched(engine); + }); + + it('a permission store that cannot be read answers its own 503, and a held sign-in its policy\'s 403', async () => { + const engine = recordingEngine(); + const down = await call( + { + getEngine: () => engine, + resolveCaller: async () => { + throw new AuthzStoreUnavailableError('sys_user_permission_set', new Error('connection refused')); + }, + }, + { body: { object: ACCOUNT } }, + ); + expect(down.status).toBe(503); + expect(down.body?.error?.code).toBe('SERVICE_UNAVAILABLE'); + const held = await call(as({ ...ANN, authGate: { code: 'PASSWORD_EXPIRED', message: 'Expired.' } }, engine), { body: { object: ACCOUNT } }); + expect(held.status).toBe(403); + expect(held.body?.error?.code).toBe('PASSWORD_EXPIRED'); + untouched(engine); + }); + + it('any query parameter is 400 VALIDATION_ERROR naming it, and the engine is not asked', async () => { + const engine = recordingEngine(); + const answer = await call(as(ANN, engine), { query: { limit: '5' }, body: { object: ACCOUNT } }); + expect(answer.status).toBe(400); + expect(answer.body?.error?.code).toBe('VALIDATION_ERROR'); + expect(answer.body?.error?.message).toContain("'limit'"); + untouched(engine); + }); + + it('an unknown body key, a missing object, a limit out of range or a bad toggle is 400 VALIDATION_ERROR, engine never asked', async () => { + for (const body of [ + { object: ACCOUNT, search: 'acme' }, + {}, + undefined, + [], + { object: ACCOUNT, limit: 0 }, + { object: ACCOUNT, limit: COMMENT_THREADS_MAX_LIMIT + 1 }, + { object: ACCOUNT, limit: '10' }, + { object: ACCOUNT, showResolved: 'yes' }, + ]) { + const engine = recordingEngine(); + const answer = await call(as(ANN, engine), { body }); + expect(answer.status, JSON.stringify(body)).toBe(400); + expect(answer.body?.error?.code, JSON.stringify(body)).toBe('VALIDATION_ERROR'); + untouched(engine); + } + const engine = recordingEngine(); + const unknown = await call(as(ANN, engine), { body: { object: ACCOUNT, search: 'acme' } }); + expect(JSON.stringify(unknown.body?.error?.details)).toContain('search'); + }); + + it('a cursor this read did not issue is 400 VALIDATION_ERROR, engine never asked', async () => { + for (const cursor of [ + 'not a cursor', + 'abc', + encodeThreadsCursor({ createdAt: '2026-12-02T10:00:02.000Z', id: 'y' }).slice(0, -2) + '!!', + // Well-formed, but its creation time is no instant: never issued here, so + // not left to the engine's temporal door to refuse as a filter. + encodeThreadsCursor({ createdAt: 'x', id: 'y' }), + encodeThreadsCursor({ createdAt: '2026-13-45T99:00:00Z', id: 'y' }), + // Filter placeholders and blanks in either member: the engine's token + // resolver would answer them as a filter the client never wrote. + encodeThreadsCursor({ createdAt: '{not_a_token}', id: 'y' }), + encodeThreadsCursor({ createdAt: '{30_days_ago}', id: 'y' }), + encodeThreadsCursor({ createdAt: ' ', id: 'y' }), + encodeThreadsCursor({ createdAt: '2026-12-02T10:00:02.000Z', id: '{not_a_token}' }), + encodeThreadsCursor({ createdAt: '2026-12-02T10:00:02.000Z', id: '{current_user_id}' }), + encodeThreadsCursor({ createdAt: '2026-12-02T10:00:02.000Z', id: ' ' }), + ]) { + const engine = recordingEngine(); + const answer = await call(as(ANN, engine), { body: { object: ACCOUNT, cursor } }); + expect(answer.status, cursor).toBe(400); + expect(answer.body?.error?.code, cursor).toBe('VALIDATION_ERROR'); + untouched(engine); + } + }); + + it('a filter the list read\'s lowering refuses is a 400, engine never asked', async () => { + const engine = recordingEngine(); + const answer = await call(as(ANN, engine), { body: { object: ACCOUNT, filter: [['status', 'between']] } }); + expect(answer.status).toBe(400); + untouched(engine); + }); + + it('a filter array the list read cannot lower is 400 INVALID_FILTER, never dropped to "every record"', async () => { + const refused: unknown[] = [ + [5], + [{ status: 'open' }], + // The infix join is not a shape; the prefix form is. + [['status', '=', 'open'], 'or', ['status', '=', 'won']], + // A malformed child of a logical node would be dropped by the lowering. + ['or', [5]], + ['and', ['status', '=', 'open'], [5]], + ['status', 'no-such-operator', 'open'], + 5, + 'status = open', + true, + ]; + for (const filter of refused) { + const engine = recordingEngine(); + const answer = await call(as(ANN, engine), { body: { object: ACCOUNT, filter } }); + expect(answer.status, JSON.stringify(filter)).toBe(400); + expect(answer.body?.error?.code, JSON.stringify(filter)).toBe('INVALID_FILTER'); + untouched(engine); + } + }); + + it('no filter, null and [] plan the caller\'s read with no where; the prefix "or" lowers to $or', async () => { + for (const filter of [undefined, null, []]) { + const engine = recordingEngine(); + const answer = await call(as(ANN, engine), { body: { object: ACCOUNT, ...(filter === undefined ? {} : { filter }) } }); + expect(answer.status, JSON.stringify(filter)).toBe(200); + expect(engine.recorded.plans[0]?.options.where, JSON.stringify(filter)).toBeUndefined(); + } + const engine = recordingEngine(); + const answer = await call(as(ANN, engine), { + body: { object: ACCOUNT, filter: ['or', ['status', '=', 'open'], ['status', '=', 'won']] }, + }); + expect(answer.status).toBe(200); + expect(engine.recorded.plans[0]?.options.where).toEqual({ $or: [{ status: 'open' }, { status: 'won' }] }); + }); + + it('no engine that plans a read scope is 503 SERVICE_UNAVAILABLE', async () => { + const none = await call(as(ANN, undefined), { body: { object: ACCOUNT } }); + expect(none.status).toBe(503); + expect(none.body?.error?.code).toBe('SERVICE_UNAVAILABLE'); + const plain = await call(as(ANN, { find: vi.fn(), getSchema: vi.fn() } as any), { body: { object: ACCOUNT } }); + expect(plain.status).toBe(503); + }); +}); + +describe('the comment threads read — the object, before any record is read', () => { + it('sys_comment itself is 400 VALIDATION_ERROR; an unknown object is 404 OBJECT_NOT_FOUND', async () => { + const engine = recordingEngine(); + const self = await call(as(ANN, engine), { body: { object: 'sys_comment' } }); + expect(self.status).toBe(400); + expect(self.body?.error?.code).toBe('VALIDATION_ERROR'); + const unknown = await call(as(ANN, engine), { body: { object: 'no_such_object' } }); + expect(unknown.status).toBe(404); + expect(unknown.body?.error?.code).toBe('OBJECT_NOT_FOUND'); + expect(engine.planReadScope).not.toHaveBeenCalled(); + expect(engine.find).not.toHaveBeenCalled(); + }); + + it('an object with comments switched off is 403 FEEDS_DISABLED, and one the data door does not serve answers the door\'s refusal', async () => { + const engine = recordingEngine(); + const quiet = await call(as(ANN, engine), { body: { object: 'quiet' } }); + expect(quiet.status).toBe(403); + expect(quiet.body?.error?.code).toBe('FEEDS_DISABLED'); + const hidden = await call(as(ANN, engine), { body: { object: 'hidden' } }); + expect(hidden.status).toBe(404); + expect(hidden.body?.error?.code).toBe('OBJECT_API_DISABLED'); + expect(engine.planReadScope).not.toHaveBeenCalled(); + expect(engine.find).not.toHaveBeenCalled(); + }); + + it('the planned read\'s own refusal is the answer, and no comment is read', async () => { + const denied = Object.assign(new Error("Permission denied: read on 'account'"), { code: 'PERMISSION_DENIED', status: 403 }); + const engine = recordingEngine({ planError: denied }); + const answer = await call(as(ANN, engine), { body: { object: ACCOUNT, filter: { status: 'open' } } }); + expect(answer.status).toBe(403); + expect(answer.body?.error?.code).toBe('PERMISSION_DENIED'); + expect(engine.find).not.toHaveBeenCalled(); + }); +}); + +describe('the comment threads read — what it hands the engine', () => { + it('plans the caller\'s read of the object with the filter, and places that scope in ONE threads read under the same context', async () => { + const engine = recordingEngine({ threads: [thread('c1', 'a1', '2026-12-02T10:00:00.000Z')], records: [{ id: 'a1', name: 'Acme' }] }); + const answer = await call(as(ANN, engine), { body: { object: ACCOUNT, filter: [['status', '=', 'open']] } }); + expect(answer.status, JSON.stringify(answer.body)).toBe(200); + + expect(engine.recorded.plans).toHaveLength(1); + const [plan] = engine.recorded.plans; + expect(plan.object).toBe('sys_comment'); + expect(plan.target).toBe(ACCOUNT); + expect(plan.options.context).toBe(ANN); + expect(plan.options.where).toEqual({ status: 'open' }); + + const threadReads = engine.recorded.finds.filter((f) => f.object === 'sys_comment' && f.query.where?.parent_id?.$null === true); + expect(threadReads).toHaveLength(1); + const [read] = threadReads; + expect(read.query.context).toBe(ANN); + expect(read.query.where.object_name).toBe(ACCOUNT); + expect(read.query.where.record_id.$in).toBe(plan.scope); + expect(read.query.where.is_resolved).toEqual({ $ne: true }); + expect(read.query.where.participants).toBeUndefined(); + expect(read.query.orderBy).toEqual([{ field: 'created_at', order: 'desc' }, { field: 'id', order: 'desc' }]); + expect(read.query.limit).toBe(COMMENT_THREADS_DEFAULT_LIMIT + 1); + + // Every other read is the caller's too: nothing here reads as the system. + for (const f of engine.recorded.finds) expect(f.query.context, f.object).toBe(ANN); + }); + + it('showResolved drops the unresolved condition; onlyMine asks the stored participants for the caller', async () => { + const engine = recordingEngine(); + await call(as(BEN, engine), { body: { object: ACCOUNT, showResolved: true, onlyMine: true, limit: 5 } }); + const [read] = engine.recorded.finds; + expect(read.query.where.is_resolved).toBeUndefined(); + expect(read.query.where.participants).toEqual({ $contains: 'u_ben' }); + expect(read.query.limit).toBe(6); + }); + + it('two users through one door: each request plans its own scope under its own context, and the next request plans again', async () => { + const engine = recordingEngine({ threads: [thread('c1', 'a1', '2026-12-02T10:00:00.000Z')] }); + const deps: CommentThreadsQueryDeps = { + getEngine: () => engine, + resolveCaller: async (req: any) => (req.headers.who === 'ben' ? BEN : ANN), + }; + const send = async (who: string) => { + const res = { status: () => res, json: () => undefined } as any; + await mount(deps)({ method: 'POST', query: {}, params: {}, headers: { who }, body: { object: ACCOUNT } }, res); + }; + await send('ann'); + await send('ben'); + await send('ann'); + + expect(engine.recorded.plans.map((p) => p.options.context.userId)).toEqual(['u_ann', 'u_ben', 'u_ann']); + const threadReads = engine.recorded.finds.filter((f) => f.object === 'sys_comment' && f.query.where?.parent_id?.$null === true); + expect(threadReads).toHaveLength(3); + threadReads.forEach((read, i) => { + // The scope a request places is the one planned in that request, for that caller. + expect(read.query.where.record_id.$in).toBe(engine.recorded.plans[i].scope); + expect(read.query.context).toBe(engine.recorded.plans[i].options.context); + }); + // Ann's second request did not reuse her first scope. + expect(threadReads[2].query.where.record_id.$in).not.toBe(threadReads[0].query.where.record_id.$in); + }); + + it('a full page answers a cursor that resumes after its last thread; the last page answers null', async () => { + const rows = [ + thread('c3', 'a1', '2026-12-02T10:00:03.000Z'), + thread('c2', 'a1', '2026-12-02T10:00:02.000Z'), + thread('c1', 'a1', '2026-12-02T10:00:01.000Z'), + ]; + const engine = recordingEngine({ threads: rows }); + const first = await call(as(ANN, engine), { body: { object: ACCOUNT, limit: 2 } }); + expect(first.body.data.threads.map((t: Row) => t.comment.id)).toEqual(['c3', 'c2']); + expect(decodeThreadsCursor(first.body.data.nextCursor)).toEqual({ createdAt: '2026-12-02T10:00:02.000Z', id: 'c2' }); + + const engine2 = recordingEngine({ threads: rows.slice(2) }); + const second = await call(as(ANN, engine2), { body: { object: ACCOUNT, limit: 2, cursor: first.body.data.nextCursor } }); + expect(second.body.data.nextCursor).toBeNull(); + const [read] = engine2.recorded.finds; + expect(read.query.where.$or).toEqual([ + { created_at: { $lt: '2026-12-02T10:00:02.000Z' } }, + { $and: [{ created_at: '2026-12-02T10:00:02.000Z' }, { id: { $lt: 'c2' } }] }, + ]); + }); + + it('a Date creation time keys the cursor by its ISO text', () => { + const at = new Date('2026-12-02T10:00:02.000Z'); + const cursor = encodeThreadsCursor({ createdAt: at.toISOString(), id: 'ü-1' }); + expect(cursor).toMatch(/^[A-Za-z0-9_-]+$/); + expect(decodeThreadsCursor(cursor)).toEqual({ createdAt: '2026-12-02T10:00:02.000Z', id: 'ü-1' }); + }); + + it('an empty page reads no replies and no record names', async () => { + const engine = recordingEngine({ threads: [] }); + const answer = await call(as(ANN, engine), { body: { object: ACCOUNT } }); + expect(answer.body.data).toEqual({ threads: [], nextCursor: null }); + expect(engine.recorded.finds).toHaveLength(1); + }); +}); + +describe('the comment threads read — the thread assembly', () => { + it('counts replies at any depth, names the latest three distinct repliers newest first, and leaves an orphan out', () => { + const roots = [thread('t1', 'a1', '2026-12-02T09:00:00.000Z'), thread('t2', 'a2', '2026-12-02T09:00:00.000Z')]; + // Newest first, as the replies read orders them. + const replies: Row[] = [ + { id: 'r6', parent_id: 'r1', author_id: 'u_dee', author_name: 'Dee', author_avatar_url: null }, + { id: 'r5', parent_id: 'r2', author_id: 'u_cal', author_name: 'Cal', author_avatar_url: 'https://x/c.png' }, + { id: 'r4', parent_id: 't1', author_id: 'u_dee', author_name: 'Dee', author_avatar_url: null }, + { id: 'r3', parent_id: 't1', author_id: 'u_eve', author_name: '', author_avatar_url: '' }, + { id: 'r2', parent_id: 't1', author_id: 'u_ben', author_name: 'Ben', author_avatar_url: null }, + { id: 'r1', parent_id: 't1', author_id: 'u_ann', author_name: 'Ann', author_avatar_url: null }, + { id: 'rx', parent_id: 'gone', author_id: 'u_zed', author_name: 'Zed', author_avatar_url: null }, + ]; + const extras = threadExtras(roots, replies); + expect(extras.get('t1')?.count).toBe(6); + expect(extras.get('t1')?.repliers).toEqual([ + { id: 'u_dee', name: 'Dee', avatarUrl: null }, + { id: 'u_cal', name: 'Cal', avatarUrl: 'https://x/c.png' }, + { id: 'u_eve', name: null, avatarUrl: null }, + ]); + expect(extras.get('t2')).toEqual({ count: 0, repliers: [] }); + }); + + it('each thread carries the record id and its display name, read as the caller; a record not read falls to the floor', async () => { + const engine = recordingEngine({ + threads: [thread('c2', 'a2', '2026-12-02T10:00:02.000Z'), thread('c1', 'a1', '2026-12-02T10:00:01.000Z')], + replies: [{ id: 'r1', parent_id: 'c1', author_id: 'u_ben', author_name: 'Ben', author_avatar_url: null }], + records: [{ id: 'a1', name: 'Acme' }], + }); + const answer = await call(as(ANN, engine), { body: { object: ACCOUNT } }); + expect(answer.status).toBe(200); + expect(answer.body.data.threads.map((t: Row) => [t.comment.id, t.record, t.replyCount, t.repliers.map((r: Row) => r.id)])).toEqual([ + ['c2', { id: 'a2', name: 'Record #a2' }, 0, []], + ['c1', { id: 'a1', name: 'Acme' }, 1, ['u_ben']], + ]); + const namesRead = engine.recorded.finds.find((f) => f.object === ACCOUNT); + expect(namesRead?.query.where).toEqual({ id: { $in: ['a2', 'a1'] } }); + expect(namesRead?.query.fields).toEqual(['id', 'name']); + const repliesRead = engine.recorded.finds.find((f) => f.object === 'sys_comment' && f.query.where?.parent_id?.$null === false); + expect(repliesRead?.query.where).toMatchObject({ object_name: ACCOUNT, record_id: { $in: ['a2', 'a1'] } }); + expect(repliesRead?.query.fields).toEqual(['id', 'parent_id', 'author_id', 'author_name', 'author_avatar_url', 'created_at']); + }); +}); diff --git a/packages/plugins/plugin-audit/src/comment-threads-query.ts b/packages/plugins/plugin-audit/src/comment-threads-query.ts new file mode 100644 index 00000000000..d52aea330a5 --- /dev/null +++ b/packages/plugins/plugin-audit/src/comment-threads-query.ts @@ -0,0 +1,566 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { + ANONYMOUS_DENY_CODE, + ANONYMOUS_DENY_MESSAGE, + ANONYMOUS_DENY_STATUS, + evaluateAuthGate, + isApiKeyLifecycleRefusalError, + isAuthzStoreUnavailableError, + isUninterpretableTemporalComparand, + objectNotFoundError, + shouldDenyAnonymous, + type OwnRowDeleteRoutesDeps, +} from '@objectstack/core'; +import type { PlanReadScopeOptions, ReadScopeComparand } from '@objectstack/objectql'; +import { + COMMENT_THREADS_DEFAULT_LIMIT, + COMMENT_THREADS_MAX_REPLIERS, + CommentThreadsQueryRequestSchema, + zodIssuesToFields, + type CommentThread, + type CommentThreadReplier, + type CommentThreadsQueryRequestParsed, + type CommentThreadsQueryResponse, + type ErrorCode, +} from '@objectstack/spec/api'; +import type { IHttpRequest, IHttpResponse, IHttpServer } from '@objectstack/spec/contracts'; +import { + VALID_AST_OPERATORS, + apiExposureDenialReason, + classifyFilterToken, + isFilterAST, + parseFilterAST, + resolveDisplayField, + resolveRecordDisplayName, +} from '@objectstack/spec/data'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { resolveThrownHttpError, sendError, sendOk, sendServerFault } from '@objectstack/types'; + +import { COMMENT_PARTICIPANTS_COLUMN } from './comment-participants.js'; +import { COMMENT_RESOLVED_FIELD, isReplyRow } from './comment-resolution.js'; + +/** + * The comment threads read, `POST /api/v1/comments/threads/query`: the + * top-level comments on the records a list filter selects, as the caller — + * the read a list page's comment panel asks (the request and answer contract + * is `CommentThreadsQueryRequestSchema` / `CommentThreadsQueryResponseSchema` + * in `@objectstack/spec/api`, whose header states what a client may rely on). + * + * ## Every step as the caller + * + * Nothing here reads as the system. Each read below is an ordinary + * caller-context read, so every gate a list read meets is met here too: + * + * 1. **The caller**, resolved by the platform's one composition, as the + * other comment doors resolve it. Anonymous: `UNAUTHENTICATED` / `401`; + * a held sign-in: `403` with the authentication policy's own code. + * 2. **The request**: no query parameter, and a body the strict schema + * takes; anything else is `VALIDATION_ERROR` / `400`, answered before the + * engine is asked anything. The `cursor` must be one this read issued + * (its creation time an instant the `datetime` rule reads), else + * `VALIDATION_ERROR` / `400`. The filter must be one the list read's own + * lowering takes: a filter object, or a filter array `isFilterAST` takes + * and `parseFilterAST` lowers to a condition (`[]` and `null` are no + * filter). Anything else is the lowering's `INVALID_FILTER` / `400`, the + * answer `GET /data/{object}` gives the same value: a filter that lowered + * to nothing would answer every record the caller reads. + * 3. **The object**: registered (else `OBJECT_NOT_FOUND` / `404`), served by + * the data door for a record read (`apiExposureDenialReason(enable, + * 'get')`, the decision the comment read gate reads too — else the data + * door's own `OBJECT_API_DISABLED` / `404` or + * `OBJECT_API_METHOD_NOT_ALLOWED` / `405`), not `sys_comment`, and with + * comments on (`enable.feeds` not `false`, else `FEEDS_DISABLED` / `403`, + * the code the comment write gate answers). + * 4. **The records**: the engine plans the caller's read of the object with + * the filter (`ObjectQL#planReadScope`) and hands back the `$in` + * comparand that scopes `sys_comment.record_id` to it — one nested + * subquery where the planned read is provably the id read, else the ids + * the caller reads under the engine's cap, refused past it. That read's + * own refusals are the answer: `PERMISSION_DENIED` for a caller with no + * read on the object or a filter naming a field the caller cannot read, + * `INVALID_FILTER` on a driver that cannot run the subquery. + * 5. **The threads**: ONE `find` on `sys_comment` — the object, the scope, + * top-level only, unresolved unless asked, "involving me" + * (`participants` contains the caller) when asked, after the cursor — + * newest first by `(created_at, id)`, one row past the page to learn + * whether another page follows. The comment read gate ANDs its own + * condition in, as on `GET /data/sys_comment`. + * 6. **The page's extras**: the replies on the page's records (author + * columns and the parent pointer only), from which each thread's reply + * count at any depth and its latest distinct repliers are taken; and the + * page's records' display names, one read of the object for their ids. + * + * ## The planned scope is planned per request, never kept + * + * The comparand step 4 returns carries the read scope of the context it was + * planned under. So it is planned inside the request that places it and + * placed under the same context, and nothing here caches it: a second + * caller's request plans its own. A test pins two users through one door. + * + * ## Threads, replies, and the record page's rule + * + * A thread is a top-level comment and every reply under it at any depth: a + * reply is placed in a thread by following `parent_id` up to its top-level + * comment, at most 16 hops, the rule a thread's participants are kept by + * (`comment-participants.ts`) and the one the console groups a record's + * comments by. A reply whose chain leaves the record's discussion counts in + * no thread. + * + * ## What is not served here + * + * A kernel with no `http.server` (a hosted tenant kernel) reaches the other + * comment doors through the runtime dispatcher's `/comments` domain. That + * domain does not claim this route, so this read is served by the + * self-hosted mount only; `AuditPlugin` says so in its boot line on a kernel + * with no HTTP server. + */ + +/** The read's route. */ +export const COMMENT_THREADS_QUERY_ROUTE = '/api/v1/comments/threads/query'; + +/** The object the threads live on. */ +const COMMENT_OBJECT = 'sys_comment'; + +/** How many `parent_id` hops a reply is followed to its thread's top-level comment — the participants rule's bound. */ +const THREAD_ROOT_MAX_HOPS = 16; + +/** Reply rows read per page in step 6; a page of threads whose records hold more is read in further pages. */ +const REPLY_PAGE_SIZE = 1_000; + +/** The reply columns step 6 reads: the pointer it follows and the author it shows. */ +const REPLY_FIELDS = ['id', 'parent_id', 'author_id', 'author_name', 'author_avatar_url', 'created_at']; + +/** Newest first, `id` breaking ties: the order the threads are paged in. */ +const NEWEST_FIRST = [ + { field: 'created_at', order: 'desc' as const }, + { field: 'id', order: 'desc' as const }, +]; + +type Row = Record; + +/** The slice of the data engine the read uses — `ObjectQL`'s own members. */ +export interface CommentThreadsEngine { + find(object: string, query: Record): Promise; + planReadScope(object: string, target: string, options?: PlanReadScopeOptions): Promise; + /** The registered object definition, or `undefined` for a name the registry does not hold. */ + getSchema(object: string): unknown; +} + +/** What the read is composed over — every service read when a request arrives. */ +export interface CommentThreadsQueryDeps { + /** The data engine; `undefined` when none is registered. */ + getEngine(): CommentThreadsEngine | undefined; + /** Resolve the caller of a request; `undefined` names nobody. */ + resolveCaller: OwnRowDeleteRoutesDeps['resolveCaller']; +} + +/** Mount the read on `http`. Nothing on `deps` is called until a request arrives. */ +export function registerCommentThreadsQueryRoute(http: IHttpServer, deps: CommentThreadsQueryDeps): void { + http.post(COMMENT_THREADS_QUERY_ROUTE, (req, res) => handleCommentThreadsQuery(req, res, deps)); +} + +/** A refusal this module throws: the ADR-0112 envelope's `code` and `status`. */ +function refusal(code: ErrorCode, status: number, message: string, extra: Record = {}): Error { + const err = new Error(message) as Error & Record; + err.code = code; + err.status = status; + Object.assign(err, extra); + return err; +} + +const idOf = (value: unknown): string | null => + (typeof value === 'string' || typeof value === 'number') && String(value) !== '' ? String(value) : null; + +function asRows(result: unknown): Row[] { + if (Array.isArray(result)) return result as Row[]; + if (result && typeof result === 'object' && Array.isArray((result as { records?: unknown }).records)) { + return (result as { records: Row[] }).records; + } + return []; +} + +/** A stored instant as the text the keyset compares: an ISO string for a `Date`, the stored text otherwise. */ +function instantText(value: unknown): string | null { + if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value.toISOString(); + if (typeof value === 'string' && value !== '') return value; + if (typeof value === 'number' && Number.isFinite(value)) return new Date(value).toISOString(); + return null; +} + +/** The keyset position a cursor carries: the last thread's creation time and id. */ +interface CursorPosition { + createdAt: string; + id: string; +} + +/** Encode a position as an opaque, URL-safe cursor. */ +export function encodeThreadsCursor(position: CursorPosition): string { + const text = encodeURIComponent(JSON.stringify([position.createdAt, position.id])); + return btoa(text).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); +} + +/** + * The spelling of a stored instant a cursor may carry: a calendar day, a time + * of day and an optional zone, as `toISOString` and the SQL drivers write it. + * A filter placeholder (`{30_days_ago}`) or blank text is not one. + */ +const CURSOR_INSTANT_RE = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:Z|[+-]\d{2}(?::?\d{2})?)?$/; + +/** Decode a cursor this read issued; `null` for anything else. */ +export function decodeThreadsCursor(cursor: string): CursorPosition | null { + if (!/^[A-Za-z0-9_-]+$/.test(cursor)) return null; + try { + const padded = cursor.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (cursor.length % 4)) % 4); + const parsed: unknown = JSON.parse(decodeURIComponent(atob(padded))); + if (!Array.isArray(parsed) || parsed.length !== 2) return null; + const [createdAt, id] = parsed; + if (typeof createdAt !== 'string' || typeof id !== 'string') return null; + // Only what the encoder writes: a stored instant's text and a stored id. + // Anything else was never issued here, and is refused now rather than by + // the engine (its temporal door, its filter-token resolver) about a + // condition the client never wrote. + if (!CURSOR_INSTANT_RE.test(createdAt) || isUninterpretableTemporalComparand('datetime', createdAt)) return null; + if (id === '' || id.trim() !== id || classifyFilterToken(id) !== null) return null; + return { createdAt, id }; + } catch { + return null; + } +} + +/** The refusal of a filter the list read cannot lower: `INVALID_FILTER` / `400`. */ +function filterRefusal(object: string, filter: unknown, why: string): Error { + return refusal( + 'INVALID_FILTER', + 400, + `The filter is not one the list read of '${object}' takes: ${JSON.stringify(filter)} ${why}. ` + + 'A filter is a filter object, or a filter array: a comparison [field, operator, value], a logical node ' + + '["and"|"or", ...conditions], or a list of comparisons. Infix joins ([condA, "or", condB]) are not one of ' + + `the shapes; write the prefix form ["or", condA, condB]. Recognised operators: ${[...VALID_AST_OPERATORS].sort().join(', ')}.`, + ); +} + +/** + * Step 2's filter: the condition the caller's read of `object` is planned + * with, or `undefined` for no filter (absent, `null` or `[]`). A value the + * list read cannot lower is refused, never dropped: a dropped filter would + * answer the threads on every record the caller reads. + */ +export function lowerThreadsFilter(filter: unknown, object: string): Record | undefined { + if (filter === undefined || filter === null) return undefined; + if (Array.isArray(filter)) { + if (filter.length === 0) return undefined; + if (!isFilterAST(filter)) throw filterRefusal(object, filter, 'is not a filter array'); + } else if (typeof filter !== 'object') { + throw filterRefusal(object, filter, 'is neither a filter object nor a filter array'); + } + let lowered: Record | undefined; + try { + lowered = parseFilterAST(filter, `threads of '${object}'`) as Record | undefined; + } catch (err) { + const thrown = resolveThrownHttpError(err, 400); + throw refusal( + thrown.status < 500 ? (thrown.code as ErrorCode) : 'INVALID_FILTER', + thrown.status < 500 ? thrown.status : 400, + `The filter is not one the list read of '${object}' takes: ${thrown.message}`, + ); + } + if (lowered === undefined) throw filterRefusal(object, filter, 'lowers to no condition'); + return lowered; +} + +/** The object definition fields this read reads. */ +interface ObjectDef { + enable?: Record | null; + [k: string]: unknown; +} + +/** + * Steps 3 to 6: the page of threads `request` names, read as `context`. + * Throws the envelope of every refusal (`code` and `status`); `context` + * must name a user. The request is the schema's parsed body. + */ +export async function queryCommentThreads( + engine: CommentThreadsEngine, + request: CommentThreadsQueryRequestParsed, + context: ExecutionContext, +): Promise { + const callerId = context.userId; + if (!callerId) throw new Error('queryCommentThreads: the caller context names no user'); + const object = request.object; + + // Step 2's remainder: the cursor and the filter, judged before any read. + let position: CursorPosition | null = null; + if (request.cursor !== undefined) { + position = decodeThreadsCursor(request.cursor); + if (!position) { + throw refusal( + 'VALIDATION_ERROR', + 400, + 'The cursor is not one this read issued. Send the nextCursor of the previous page exactly as it was answered, ' + + 'or no cursor for the first page.', + { details: { fields: [{ field: 'cursor', code: 'invalid_cursor', message: 'Not a cursor this read issued.' }] } }, + ); + } + } + const where = lowerThreadsFilter(request.filter, object); + + // Step 3: the object. + if (object === COMMENT_OBJECT) { + throw refusal( + 'VALIDATION_ERROR', + 400, + `Name the object whose records the list shows; '${COMMENT_OBJECT}' holds the comments themselves, not records they are on.`, + { details: { fields: [{ field: 'object', code: 'invalid_object', message: `'${COMMENT_OBJECT}' is not a parent object.` }] } }, + ); + } + const def = engine.getSchema(object) as ObjectDef | undefined | null; + if (!def) throw objectNotFoundError(object); + const exposure = apiExposureDenialReason(def.enable as never, 'get'); + if (exposure === 'api-disabled') { + throw refusal('OBJECT_API_DISABLED', 404, `Object '${object}' is not exposed via the API`, { object }); + } + if (exposure === 'method-not-allowed') { + throw refusal('OBJECT_API_METHOD_NOT_ALLOWED', 405, `API operation 'get' is not allowed on object '${object}'`, { object }); + } + if (def.enable?.feeds === false) { + throw refusal('FEEDS_DISABLED', 403, `Comments are disabled for object '${object}' (enable.feeds: false)`, { object }); + } + + // Step 4: the caller's read of the object, planned for THIS request. + const scope = await engine.planReadScope(COMMENT_OBJECT, object, { + ...(where !== undefined ? { where: where as PlanReadScopeOptions['where'] } : {}), + context, + }); + + // Step 5: one read of the page's threads. + const limit = request.limit ?? COMMENT_THREADS_DEFAULT_LIMIT; + const threadWhere: Row = { + object_name: object, + record_id: { $in: scope }, + parent_id: { $null: true }, + ...(request.showResolved === true ? {} : { [COMMENT_RESOLVED_FIELD]: { $ne: true } }), + ...(request.onlyMine === true ? { [COMMENT_PARTICIPANTS_COLUMN]: { $contains: callerId } } : {}), + ...(position + ? { + $or: [ + { created_at: { $lt: position.createdAt } }, + { $and: [{ created_at: position.createdAt }, { id: { $lt: position.id } }] }, + ], + } + : {}), + }; + const found = asRows( + await engine.find(COMMENT_OBJECT, { where: threadWhere, orderBy: NEWEST_FIRST, limit: limit + 1, context }), + ); + const page = found.slice(0, limit); + const last = page[page.length - 1]; + let nextCursor: string | null = null; + if (found.length > limit && last) { + const createdAt = instantText(last.created_at); + const id = idOf(last.id); + if (createdAt && id) nextCursor = encodeThreadsCursor({ createdAt, id }); + } + if (page.length === 0) return { threads: [], nextCursor }; + + // Step 6: the replies and the record names, for this page only. + const recordIds = [...new Set(page.map((row) => idOf(row.record_id)).filter((id): id is string => id !== null))]; + const [replies, names] = await Promise.all([ + readReplies(engine, object, recordIds, context), + readRecordNames(engine, object, def, recordIds, context), + ]); + const extras = threadExtras(page, replies); + + const threads: CommentThread[] = page.map((row) => { + const id = String(row.id); + const recordId = idOf(row.record_id) ?? ''; + const extra = extras.get(id); + return { + comment: row, + record: { id: recordId, name: names.get(recordId) ?? resolveRecordDisplayName(def as never, { id: recordId }) }, + replyCount: extra?.count ?? 0, + repliers: extra?.repliers ?? [], + }; + }); + return { threads, nextCursor }; +} + +/** Every reply on `recordIds` the caller may read, newest first, keyset-paged. */ +async function readReplies( + engine: CommentThreadsEngine, + object: string, + recordIds: readonly string[], + context: ExecutionContext, +): Promise { + const rows: Row[] = []; + let after: CursorPosition | null = null; + for (;;) { + const where: Row = { + object_name: object, + record_id: { $in: [...recordIds] }, + parent_id: { $null: false }, + ...(after + ? { + $or: [ + { created_at: { $lt: after.createdAt } }, + { $and: [{ created_at: after.createdAt }, { id: { $lt: after.id } }] }, + ], + } + : {}), + }; + const batch = asRows( + await engine.find(COMMENT_OBJECT, { where, fields: REPLY_FIELDS, orderBy: NEWEST_FIRST, limit: REPLY_PAGE_SIZE, context }), + ); + rows.push(...batch); + const tail = batch[batch.length - 1]; + const createdAt = tail ? instantText(tail.created_at) : null; + const id = tail ? idOf(tail.id) : null; + if (batch.length < REPLY_PAGE_SIZE || !createdAt || !id) break; + after = { createdAt, id }; + } + return rows; +} + +/** The display name of each of `recordIds` the caller reads, by the object's title field (ADR-0079). */ +async function readRecordNames( + engine: CommentThreadsEngine, + object: string, + def: ObjectDef, + recordIds: readonly string[], + context: ExecutionContext, +): Promise> { + const titleField = resolveDisplayField(def as never); + const rows = asRows( + await engine.find(object, { + where: { id: { $in: [...recordIds] } }, + fields: titleField && titleField !== 'id' ? ['id', titleField] : ['id'], + limit: recordIds.length, + context, + }), + ); + const names = new Map(); + for (const row of rows) { + const id = idOf(row.id); + if (id) names.set(id, resolveRecordDisplayName(def as never, row)); + } + return names; +} + +/** + * Each thread's reply count and latest distinct repliers, from the page's + * threads and the replies on their records (newest first). A reply joins the + * thread of its top-level ancestor, followed at most + * {@link THREAD_ROOT_MAX_HOPS} hops; one whose chain leaves the rows read is + * in no thread. + */ +export function threadExtras( + threads: ReadonlyArray, + replies: ReadonlyArray, +): Map { + const byId = new Map(); + for (const row of [...threads, ...replies]) { + const id = idOf(row.id); + if (id) byId.set(id, row); + } + const out = new Map(); + for (const row of threads) { + const id = idOf(row.id); + if (id) out.set(id, { count: 0, repliers: [] }); + } + const rootIdOf = (row: Row): string | null => { + let current = row; + for (let hop = 0; hop <= THREAD_ROOT_MAX_HOPS; hop++) { + if (!isReplyRow(current)) return idOf(current.id); + const parent = byId.get(String(current.parent_id)); + if (!parent) return null; + current = parent; + } + return null; + }; + for (const reply of replies) { + if (!isReplyRow(reply)) continue; + const rootId = rootIdOf(reply); + const entry = rootId === null ? undefined : out.get(rootId); + if (!entry) continue; + entry.count += 1; + const author = idOf(reply.author_id); + if (!author || entry.repliers.length >= COMMENT_THREADS_MAX_REPLIERS) continue; + if (entry.repliers.some((r) => r.id === author)) continue; + entry.repliers.push({ + id: author, + name: typeof reply.author_name === 'string' && reply.author_name !== '' ? reply.author_name : null, + avatarUrl: typeof reply.author_avatar_url === 'string' && reply.author_avatar_url !== '' ? reply.author_avatar_url : null, + }); + } + return out; +} + +async function handleCommentThreadsQuery(req: IHttpRequest, res: IHttpResponse, deps: CommentThreadsQueryDeps): Promise { + const at = { method: 'POST', path: COMMENT_THREADS_QUERY_ROUTE }; + + // ① The caller. + let context: ExecutionContext | undefined; + try { + context = await deps.resolveCaller(req); + } catch (err) { + if (isAuthzStoreUnavailableError(err) || isApiKeyLifecycleRefusalError(err)) { + sendError(res, err.status, err.code, err.message); + return; + } + sendServerFault(res, 500, 'INTERNAL_ERROR', 'The caller of this request could not be resolved.', err, at); + return; + } + if (!context || shouldDenyAnonymous({ userId: context.userId, method: req.method })) { + sendError(res, ANONYMOUS_DENY_STATUS, ANONYMOUS_DENY_CODE, ANONYMOUS_DENY_MESSAGE); + return; + } + const authGate = evaluateAuthGate(context, ''); + if (authGate) { + sendError(res, 403, authGate.code as ErrorCode, authGate.message); + return; + } + + // ② The request: the closed (empty) query-parameter set, then the strict body. + const query = Object.keys(req.query ?? {}); + if (query.length > 0) { + sendError( + res, + 400, + 'VALIDATION_ERROR', + `Reading comment threads takes no query parameter, and this request carries ${query.map((q) => `'${q}'`).join(', ')}. ` + + 'Send the object, the filter, the toggles, the limit and the cursor in the JSON body.', + { details: { fields: query.map((q) => ({ field: q, code: 'unrecognized_key', message: `'${q}' is not a parameter of this read.` })) } }, + ); + return; + } + const raw: unknown = req.body ?? {}; + const parsed = CommentThreadsQueryRequestSchema.safeParse(raw); + if (!parsed.success) { + sendError(res, 400, 'VALIDATION_ERROR', 'The body is not a comment threads request: see the fields named in details.', { + details: { fields: zodIssuesToFields(parsed.error.issues, raw) }, + }); + return; + } + + const engine = deps.getEngine(); + if (!engine || typeof engine.planReadScope !== 'function' || typeof engine.getSchema !== 'function') { + sendError(res, 503, 'SERVICE_UNAVAILABLE', 'Comment threads cannot be read right now: no data engine that plans a read scope is registered.'); + return; + } + + // ③ – ⑥ + let answer: CommentThreadsQueryResponse; + try { + answer = await queryCommentThreads(engine, parsed.data, context); + } catch (err) { + const thrown = resolveThrownHttpError(err, 500); + if (thrown.status < 500) { + const details = (err as { details?: unknown } | null)?.details; + sendError(res, thrown.status, thrown.code, thrown.message, details ? { details: details as never } : undefined); + return; + } + sendServerFault(res, thrown.status, thrown.code, 'The comment threads could not be read because of an error on the server.', err, at); + return; + } + sendOk(res, answer); +} diff --git a/packages/plugins/plugin-audit/src/index.ts b/packages/plugins/plugin-audit/src/index.ts index e5cd3570550..4eeb8cc56cd 100644 --- a/packages/plugins/plugin-audit/src/index.ts +++ b/packages/plugins/plugin-audit/src/index.ts @@ -152,6 +152,12 @@ export type { CommentParticipantsBackfillEngine, CommentParticipantsBackfillReport, } from './comment-participants-backfill.js'; +// The comment threads read (`POST /api/v1/comments/threads/query`): the +// top-level comments on the records a list filter selects, read as the +// caller. The route is mounted by the comment registrar; the function is the +// read itself, for an in-process caller with an engine and a caller context. +export { COMMENT_THREADS_QUERY_ROUTE, queryCommentThreads } from './comment-threads-query.js'; +export type { CommentThreadsEngine, CommentThreadsQueryDeps } from './comment-threads-query.js'; // [#21120] The one-off rewrite of at-rest cleartext metadata-body copies this // writer left in `sys_audit_log` / `sys_activity`, and the pure planners the // CLI command (`os migrate audit-metadata-bodies`) drives. diff --git a/packages/qa/dogfood/test/comment-threads-query.dogfood.test.ts b/packages/qa/dogfood/test/comment-threads-query.dogfood.test.ts new file mode 100644 index 00000000000..d9433dd2f1c --- /dev/null +++ b/packages/qa/dogfood/test/comment-threads-query.dogfood.test.ts @@ -0,0 +1,663 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// The comment threads read, `POST /api/v1/comments/threads/query`: the +// top-level comments on the records a list filter selects, read as the +// caller — the read a list page's comment panel asks. +// +// ## What is pinned here, and where +// +// The first describe is the HTTP acceptance, on a real org-bound boot (the +// real Hono app, better-auth sign-ups, the real SecurityPlugin with the +// shipped baseline plus the fixture's sets, the real AuditPlugin and its +// comment registrar, the SQLite driver). One request per case, as members +// with different row scope: +// +// - a filter selecting 3 of 5 records answers only their open top-level +// threads, newest first, each with the record's id and name, its reply +// count and its latest three distinct repliers; +// - a member whose row scope hides one of the 3 is not answered its +// threads; a member with no read on the object gets that read's own +// `403 PERMISSION_DENIED`; +// - `showResolved` and `onlyMine`; +// - `limit` + `cursor` walk every thread once while a comment is posted +// between pages; +// - an unknown body key, any query parameter, a `limit` out of range: +// `400 VALIDATION_ERROR`, and neither the planned read nor a read of the +// object or of `sys_comment` happened; a filter on a field the caller +// cannot read: `PERMISSION_DENIED`; comments off: `403`; anonymous: `401`; +// - a view past the engine's id cap (1,005 matching records) answered in +// full, the threads read reaching the driver as ONE statement carrying +// the planned read as a subquery (the driver's call log is the query log). +// +// The second describe drives the same read (`queryCommentThreads`, the body +// the route runs after its shell) on the real engine, the real SecurityPlugin +// and the SQL driver, one cell per dialect: the past-the-cap view and the one +// threads statement on SQLite AND PostgreSQL, the row-scoped member, the +// member with no read, and two users through one engine — each request plans +// its own scope under its own context, never a scope kept from another +// request. The PostgreSQL cell runs where `OS_TEST_POSTGRES_URL` is set (it +// creates a database of its own there and drops it) and is a named skip +// otherwise; no CI job provisions that variable for this suite, so it is +// red-capable and un-run in CI, and the PR that landed this file names its +// local PostgreSQL 16 run. +// +// `@objectstack/plugin-audit` resolves through its BUILT output here. +// Fixtures are synthetic. + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { bootStack, type VerifyStack } from '@objectstack/verify'; +import { AuditPlugin, queryCommentThreads } from '@objectstack/plugin-audit'; +import { SecurityPlugin, securityDefaultPermissionSets } from '@objectstack/plugin-security'; +import { ObjectKernel, assembleExecutionContext, resolveAuthzContext, type Plugin, type PluginContext } from '@objectstack/core'; +import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SysMember, SysOrganization, SysUser } from '@objectstack/platform-objects/identity'; +import { defineStack } from '@objectstack/spec'; +import { ObjectSchema, Field, isComposedReadableIds } from '@objectstack/spec/data'; +import { PermissionSetSchema, type PermissionSet } from '@objectstack/spec/security'; +import { catalogPermissionSet } from './catalog-permission-set.js'; + +const SYS = { isSystem: true } as const; +const COMMENT = 'sys_comment'; +const ROUTE = '/comments/threads/query'; + +type Row = Record; +type Answer = { status: number; json: any }; + +/** Every `$in` comparand in a driver `where`, by kind: a composed leaf over `object`, or a literal id list. */ +function inComparands(where: unknown, object: string): Array<'leaf' | 'list'> { + const found: Array<'leaf' | 'list'> = []; + const walk = (v: unknown) => { + if (Array.isArray(v)) { + v.forEach(walk); + return; + } + if (!v || typeof v !== 'object') return; + for (const [k, x] of Object.entries(v)) { + if (k === '$in') { + if (isComposedReadableIds(x)) { + if ((x as { object: string }).object === object) found.push('leaf'); + } else if (Array.isArray(x)) found.push('list'); + } else walk(x); + } + }; + walk(where); + return found; +} + +/** + * The comment read gate's own probe for rows its parent pair has not reached + * (`object_name IS NULL` ANDed into a read): paid on every `sys_comment` read, + * this read's or any other, and not one of this read's statements. + */ +const isGateNullParentProbe = (where: unknown): boolean => JSON.stringify(where ?? null).includes('{"object_name":{"$null":true}}'); + +/** + * The top-level comment statements of one threads read that carry a planned + * read over `object` as a subquery: the threads statement, and the gate's own + * null-parent probe of that read. (The replies read names the page's record + * ids and carries only the gate's own leaf; it asks `parent_id` not null.) + */ +function plannedStatements(reads: Array<{ object: string; query: any }>, object: string) { + const carrying = reads.filter( + (r) => r.object === COMMENT && inComparands(r.query?.where, object).includes('leaf') && JSON.stringify(r.query?.where).includes('"parent_id":{"$null":true}'), + ); + return { + threads: carrying.filter((r) => !isGateNullParentProbe(r.query?.where)), + gateProbes: carrying.filter((r) => isGateNullParentProbe(r.query?.where)), + }; +} + +/** Every driver read while `run` runs: the object and the query the driver was handed. */ +async function driverReadsDuring(driver: any, run: () => Promise): Promise<{ result: T; reads: Array<{ object: string; query: any }> }> { + const reads: Array<{ object: string; query: any }> = []; + const saved: Record unknown> = {}; + for (const verb of ['find', 'findOne', 'count', 'aggregate', 'findStream']) { + if (typeof driver[verb] !== 'function') continue; + saved[verb] = driver[verb]; + driver[verb] = (object: string, ...rest: unknown[]) => { + reads.push({ object, query: rest[0] }); + return saved[verb].call(driver, object, ...rest); + }; + } + try { + return { result: await run(), reads }; + } finally { + for (const [verb, fn] of Object.entries(saved)) driver[verb] = fn; + } +} + +// ───────────────────────────── the HTTP acceptance ───────────────────────────── + +const DEAL = 'ctq_deal'; +const QUIET = 'ctq_quiet'; + +const CtqDeal = ObjectSchema.create({ + name: DEAL, + label: 'Thread Deal', + pluralLabel: 'Thread Deals', + sharingModel: 'public_read_write', + fields: { + name: Field.text({ label: 'Name', required: true }), + region: Field.text({ label: 'Region' }), + status: Field.text({ label: 'Status' }), + secret: Field.text({ label: 'Secret' }), + }, +}); + +const CtqQuiet = ObjectSchema.create({ + name: QUIET, + label: 'Thread Quiet Record', + pluralLabel: 'Thread Quiet Records', + sharingModel: 'public_read_write', + enable: { feeds: false }, + fields: { name: Field.text({ label: 'Name', required: true }) }, +}); + +const threadsStack = defineStack({ + manifest: { + id: 'com.dogfood.comment-threads-query', + namespace: 'ctq', + version: '0.0.0', + type: 'app', + name: 'Comment Threads Read Fixture', + description: 'Two objects for the comment threads read: one whose records carry threads, one with comments switched off.', + }, + objects: [CtqDeal, CtqQuiet], +}); + +/** The members who read every deal: read and write both fixture objects. */ +const ctqMemberSet: PermissionSet = PermissionSetSchema.parse({ + name: 'ctq_member', + label: 'Threads fixture — deal member', + objects: { + [DEAL]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: false }, + [QUIET]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: false }, + }, +}); + +/** Reads the deals outside region HIDDEN, and may not read `secret`. */ +const ctqScopedSet: PermissionSet = PermissionSetSchema.parse({ + name: 'ctq_scoped', + label: 'Threads fixture — row-scoped deal read', + objects: { [DEAL]: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false } }, + fields: { [`${DEAL}.secret`]: { readable: false, editable: false } }, + rowLevelSecurity: [{ name: 'ctq_deal_region', object: DEAL, operation: 'all', using: "record.region != 'HIDDEN'" }], +}); + +/** Reads the quiet object only: no read on deals at all. */ +const ctqNoDealSet: PermissionSet = PermissionSetSchema.parse({ + name: 'ctq_no_deal', + label: 'Threads fixture — no deal read', + objects: { [QUIET]: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false } }, +}); + +describe('POST /comments/threads/query — at HTTP, as members with different row scope', () => { + let stack: VerifyStack; + let ql: any; + const tok: Record = {}; + const uid: Record = {}; + const deal: Record = {}; + const t: Record = {}; + + const call = async (who: string, body: unknown, path = ROUTE): Promise => { + const res = await stack.apiAs(tok[who], 'POST', path, body); + return { status: res.status, json: await res.json().catch(() => ({})) }; + }; + const ok = async (who: string, body: unknown) => { + const res = await call(who, body); + expect(res.status, JSON.stringify(res.json)).toBe(200); + return res.json.data as { threads: Array; nextCursor: string | null }; + }; + const ids = (data: { threads: Row[] }) => data.threads.map((x) => String(x.comment.id)); + const post = async (who: string, dealKey: string, extra: Row = {}): Promise => { + const res = await stack.apiAs(tok[who], 'POST', `/data/${COMMENT}`, { thread_id: `${DEAL}:${deal[dealKey]}`, body: `${who} on ${dealKey}`, ...extra }); + const json: any = await res.json().catch(() => ({})); + expect(res.status, JSON.stringify(json)).toBeLessThan(300); + return String(json.id ?? json.record?.id ?? json.data?.id); + }; + const OPEN = { object: DEAL, filter: [['status', '=', 'open']] }; + + /** Engine calls the read itself makes during `run`: planned reads, and reads of the object or of sys_comment. */ + const engineCallsDuring = async (run: () => Promise) => { + const calls: string[] = []; + const saved = { planReadScope: ql.planReadScope, find: ql.find, getSchema: ql.getSchema }; + ql.planReadScope = (...a: any[]) => { calls.push(`planReadScope ${a[1]}`); return saved.planReadScope.apply(ql, a); }; + ql.find = (object: string, ...a: any[]) => { if (object === DEAL || object === COMMENT) calls.push(`find ${object}`); return saved.find.call(ql, object, ...a); }; + ql.getSchema = (object: string, ...a: any[]) => { if (object === DEAL) calls.push(`getSchema ${object}`); return saved.getSchema.call(ql, object, ...a); }; + try { + await run(); + } finally { + Object.assign(ql, saved); + } + return calls; + }; + + beforeAll(async () => { + stack = await bootStack(threadsStack as never, { + security: new SecurityPlugin({ + // No fallback set: a fallback is held by every member beside its own grants, and Carol must hold no + // read on deals at all. Each member holds exactly the set granted below. + defaultPermissionSets: [...securityDefaultPermissionSets, ctqMemberSet, ctqScopedSet, ctqNoDealSet], + }), + extraPlugins: [new AuditPlugin()], + orgContext: true, + }); + ql = await stack.kernel.getServiceAsync('objectql'); + tok.admin = await stack.signIn(); + uid.admin = String((await ql.findOne('sys_user', { where: { email: 'admin@objectos.ai' }, context: SYS }))?.id); + for (const who of ['bob', 'carol', 'dee', 'erin', 'fay']) { + const email = `ctq-${who}@verify.test`; + tok[who] = await stack.signUp(email, undefined, who[0].toUpperCase() + who.slice(1)); + uid[who] = String((await ql.findOne('sys_user', { where: { email }, context: SYS }))?.id); + } + for (const [who, set] of [ + ['bob', ctqScopedSet], ['carol', ctqNoDealSet], ['dee', ctqMemberSet], ['erin', ctqMemberSet], ['fay', ctqMemberSet], + ] as const) { + const served = await catalogPermissionSet(ql, set.name); + expect(served, `${set.name} is served by the security catalog`).toBeTruthy(); + await ql.insert('sys_user_permission_set', { user_id: uid[who], permission_set: set.name }, { context: SYS }); + } + + // Five deals; `status = open` selects d1, d2, d3; d3 is in the region Bob cannot read. + for (const [key, region, status] of [ + ['d1', 'NA', 'open'], ['d2', 'EU', 'open'], ['d3', 'HIDDEN', 'open'], ['d4', 'NA', 'closed'], ['d5', 'EU', 'closed'], + ] as const) { + deal[key] = String((await ql.insert(DEAL, { name: `Deal ${key}`, region, status, secret: `s-${key}` }, { context: SYS })).id); + } + + // Threads, oldest first. + t.d1 = await post('admin', 'd1'); + t.d4 = await post('admin', 'd4'); + t.d2resolved = await post('dee', 'd2'); + t.d3 = await post('admin', 'd3'); + t.d2 = await post('erin', 'd2', { mentions: JSON.stringify([uid.fay]) }); + // Replies on d1's thread: four distinct repliers, one nested under another reply. + const r1 = await post('dee', 'd1', { parent_id: t.d1 }); + await post('erin', 'd1', { parent_id: r1 }); + await post('fay', 'd1', { parent_id: t.d1 }); + await post('bob', 'd1', { parent_id: t.d1 }); + const resolved = await stack.apiAs(tok.admin, 'PUT', `/comments/${t.d2resolved}/resolution`, { resolved: true }); + expect(resolved.status).toBe(200); + + // Controls: the row scope this file leans on, through the list read. + const readable = async (who: string) => { + const res = await stack.apiAs(tok[who], 'GET', `/data/${DEAL}?$top=50`); + const json: any = await res.json().catch(() => ({})); + return { status: res.status, ids: (json.records ?? []).map((r: Row) => String(r.id)).sort() }; + }; + expect((await readable('admin')).ids).toEqual(Object.values(deal).sort()); + expect((await readable('bob')).ids).toEqual([deal.d1, deal.d2, deal.d4, deal.d5].sort()); + expect((await readable('carol')).status).toBe(403); + }, 180_000); + + afterAll(async () => { + await stack?.stop(); + }); + + it('a filter selecting 3 of 5 records: only their open top-level threads, newest first, with record, reply count and latest repliers', async () => { + const data = await ok('admin', OPEN); + expect(ids(data)).toEqual([t.d2, t.d3, t.d1]); + expect(data.nextCursor).toBeNull(); + const byId = new Map(data.threads.map((x) => [String(x.comment.id), x])); + expect(byId.get(t.d1)).toMatchObject({ record: { id: deal.d1, name: 'Deal d1' }, replyCount: 4 }); + expect(byId.get(t.d1)!.repliers.map((r: Row) => r.id)).toEqual([uid.bob, uid.fay, uid.erin]); + expect(byId.get(t.d1)!.repliers[0]).toEqual({ id: uid.bob, name: 'Bob', avatarUrl: null }); + expect(byId.get(t.d2)).toMatchObject({ record: { id: deal.d2, name: 'Deal d2' }, replyCount: 0, repliers: [] }); + expect(byId.get(t.d3)!.record).toEqual({ id: deal.d3, name: 'Deal d3' }); + for (const x of data.threads) { + expect(x.comment.parent_id ?? null).toBeNull(); + expect(x.comment.object_name).toBe(DEAL); + } + }); + + it('a member whose row scope hides one of the 3 is not answered its thread; a member with no read on the object gets that read\'s refusal', async () => { + expect(ids(await ok('bob', OPEN))).toEqual([t.d2, t.d1]); + const carol = await call('carol', OPEN); + expect(carol.status).toBe(403); + expect(carol.json?.error?.code).toBe('PERMISSION_DENIED'); + }); + + it('showResolved absent: no resolved thread; true: it appears', async () => { + expect(ids(await ok('admin', OPEN))).not.toContain(t.d2resolved); + expect(ids(await ok('admin', { ...OPEN, showResolved: true }))).toEqual([t.d2, t.d3, t.d2resolved, t.d1]); + }); + + it('onlyMine: only the threads the caller started, replied in or is mentioned in', async () => { + expect(ids(await ok('fay', { ...OPEN, onlyMine: true }))).toEqual([t.d2, t.d1]); // mentioned; replied + expect(ids(await ok('erin', { ...OPEN, onlyMine: true }))).toEqual([t.d2, t.d1]); // started; replied under a reply + expect(ids(await ok('dee', { ...OPEN, onlyMine: true }))).toEqual([t.d1]); // replied (her own thread is resolved) + expect(ids(await ok('dee', { ...OPEN, onlyMine: true, showResolved: true }))).toEqual([t.d2resolved, t.d1]); + expect(ids(await ok('admin', { object: DEAL, filter: [['status', '=', 'closed']], onlyMine: true }))).toEqual([t.d4]); + }); + + it('limit + cursor walk every thread once, with no repeat, while a new comment is posted between pages', async () => { + const seen: string[] = []; + let cursor: string | undefined; + let posted = ''; + for (let page = 0; page < 10; page++) { + const data = await ok('admin', { object: DEAL, showResolved: true, limit: 2, ...(cursor ? { cursor } : {}) }); + seen.push(...ids(data)); + if (page === 0) posted = await post('dee', 'd5'); + if (!data.nextCursor) break; + cursor = data.nextCursor; + } + expect(seen).toEqual([t.d2, t.d3, t.d2resolved, t.d4, t.d1]); + expect(new Set(seen).size).toBe(seen.length); + expect(ids(await ok('admin', { object: DEAL, limit: 1 }))).toEqual([posted]); + await ql.delete(COMMENT, { where: { id: posted }, context: SYS }); + }); + + it('an unknown body key, any query parameter, a limit out of range: 400 VALIDATION_ERROR, and the read never reached the engine', async () => { + const cases: Array<[string, unknown, string]> = [ + ['unknown body key', { ...OPEN, search: 'acme' }, ROUTE], + ['query parameter', OPEN, `${ROUTE}?limit=5`], + ['limit 0', { ...OPEN, limit: 0 }, ROUTE], + ['limit 51', { ...OPEN, limit: 51 }, ROUTE], + ]; + for (const [label, body, path] of cases) { + let res: Answer | undefined; + const calls = await engineCallsDuring(async () => { + res = await call('admin', body, path); + }); + expect(res!.status, label).toBe(400); + expect(res!.json?.error?.code, label).toBe('VALIDATION_ERROR'); + expect(calls, label).toEqual([]); + } + // CONTROL the same spy sees a served request reach the engine. + const served = await engineCallsDuring(() => call('admin', OPEN)); + expect(served).toContain(`planReadScope ${DEAL}`); + expect(served).toContain(`find ${COMMENT}`); + }); + + it('a filter on a field the caller cannot read: PERMISSION_DENIED, never an empty answer', async () => { + const bob = await call('bob', { object: DEAL, filter: { secret: 's-d1' } }); + expect(bob.status).toBe(403); + expect(bob.json?.error?.code).toBe('PERMISSION_DENIED'); + // CONTROL a caller who reads the field is served that record's thread. + expect(ids(await ok('admin', { object: DEAL, filter: { secret: 's-d1' } }))).toEqual([t.d1]); + }); + + it('an object with comments off: 403 FEEDS_DISABLED; anonymous: 401 UNAUTHENTICATED', async () => { + const quiet = await call('admin', { object: QUIET }); + expect(quiet.status).toBe(403); + expect(quiet.json?.error?.code).toBe('FEEDS_DISABLED'); + const anonymous = await stack.api(ROUTE, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(OPEN), + }); + expect(anonymous.status).toBe(401); + expect(((await anonymous.json()) as any)?.error?.code).toBe('UNAUTHENTICATED'); + }); + + it('a view past the id cap (1,005 matching records) is answered in full, and the threads read is ONE driver statement carrying the planned read', async () => { + const bulk = Array.from({ length: 1005 }, (_, i) => ({ name: `Bulk ${i}`, region: 'NA', status: 'bulk', secret: 'x' })); + const inserted: Row[] = await ql.insert(DEAL, bulk, { context: SYS }); + const first = String(inserted[0].id); + const last = String(inserted[inserted.length - 1].id); + deal.bulkFirst = first; + deal.bulkLast = last; + const onFirst = await post('admin', 'bulkFirst'); + const onLast = await post('admin', 'bulkLast'); + + const driver = ql.getDriverForObject(COMMENT); + const { result, reads } = await driverReadsDuring(driver, () => call('bob', { object: DEAL, filter: [['status', '=', 'bulk']] })); + expect(result.status, JSON.stringify(result.json)).toBe(200); + expect(ids(result.json.data)).toEqual([onLast, onFirst]); + expect(result.json.data.threads.map((x: Row) => x.record.name)).toEqual(['Bulk 1004', 'Bulk 0']); + + // The threads statement: ONE comment statement, carrying the planned deal read as a subquery and no id + // list. (The comment read gate also probes, once per comment read, for rows its parent pair has not + // reached — its own statement on every read of sys_comment, ANDed with this read's where.) + const planned = plannedStatements(reads, DEAL); + expect(planned.threads).toHaveLength(1); + expect(planned.threads[0].query.limit).toBe(26); + expect(inComparands(planned.threads[0].query.where, DEAL)).not.toContain('list'); + expect(planned.gateProbes.length).toBeLessThanOrEqual(1); + // The deals were never read for their ids: the only deal read is the page's names, for the page's two ids. + const dealReads = reads.filter((r) => r.object === DEAL); + expect(dealReads).toHaveLength(1); + expect(dealReads[0].query?.limit ?? 0).toBeLessThanOrEqual(2); + }, 120_000); +}); + +// ─────────────────── the engine cells: SQLite and PostgreSQL ─────────────────── + +const ACCOUNT = 'ctqe_account'; +const ORG = 'org_ctqe'; +const ALICE = 'usr_ctqe_alice'; +const BOB = 'usr_ctqe_bob'; +const CAROL = 'usr_ctqe_carol'; +const SYS_ORG = { isSystem: true, tenantId: ORG } as const; + +const FULL_SET = PermissionSetSchema.parse({ + name: 'ctqe_account_full', + label: 'Accounts — full read', + objects: { [ACCOUNT]: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false } }, +}); +const SCOPED_SET = PermissionSetSchema.parse({ + name: 'ctqe_account_scoped', + label: 'Accounts — row-scoped read', + objects: { [ACCOUNT]: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false } }, + fields: { [`${ACCOUNT}.secret`]: { readable: false, editable: false } }, + rowLevelSecurity: [{ name: 'ctqe_account_region', object: ACCOUNT, operation: 'all', using: "record.region != 'HIDDEN'" }], +}); +const NONE_SET = PermissionSetSchema.parse({ + name: 'ctqe_none', + label: 'No account read', + objects: { sys_comment: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false } }, +}); + +interface Cell { + id: 'sqlite' | 'pg'; + label: string; + env: string | null; + url: string | undefined; +} + +const CELLS: readonly Cell[] = [ + { id: 'sqlite', label: 'sqlite', env: null, url: 'sqlite' }, + { id: 'pg', label: 'live postgres', env: 'OS_TEST_POSTGRES_URL', url: process.env.OS_TEST_POSTGRES_URL }, +]; + +function driverPlugin(driver: SqlDriver): Plugin { + return { + name: 'test.driver.sql', + type: 'standard', + version: '1.0.0', + async init(ctx: PluginContext) { + ctx.registerService('driver.default', driver); + }, + }; +} + +function objectsPlugin(): Plugin { + return { + name: 'test.objects', + type: 'standard', + version: '1.0.0', + dependencies: ['com.objectstack.engine.objectql'], + async init(ctx: PluginContext) { + ctx.getService<{ register(m: unknown): unknown }>('manifest').register({ + id: 'test.comment-threads-query', + namespace: 'ctqe', + version: '1.0.0', + type: 'plugin', + name: 'Comment threads read fixture', + objects: [ + SysUser, + SysMember, + SysOrganization, + { + name: ACCOUNT, + label: 'Account', + fields: { + name: { type: 'text', label: 'Name' }, + region: { type: 'text', label: 'Region' }, + status: { type: 'text', label: 'Status' }, + secret: { type: 'text', label: 'Secret' }, + }, + }, + ], + }); + }, + }; +} + +/** A fresh database on the live server for the PostgreSQL cell, and its drop. */ +async function provisionPgDatabase(adminUrl: string): Promise<{ url: string; drop: () => Promise }> { + const name = `os_ctqe_${process.pid}_${Date.now().toString(36)}`; + const admin = new SqlDriver({ client: 'pg', connection: adminUrl } as never); + await admin.execute(`create database ${name}`); + const url = new URL(adminUrl); + url.pathname = `/${name}`; + return { + url: url.toString(), + drop: async () => { + try { + await admin.execute(`drop database if exists ${name} with (force)`); + } finally { + await admin.disconnect().catch(() => {}); + } + }, + }; +} + +const ACCOUNTS = [ + { id: 'acc_na_open', name: 'NA open', region: 'NA', status: 'open', secret: 's1' }, + { id: 'acc_eu_open', name: 'EU open', region: 'EU', status: 'open', secret: 's2' }, + { id: 'acc_hidden_open', name: 'Hidden open', region: 'HIDDEN', status: 'open', secret: 's3' }, + { id: 'acc_na_closed', name: 'NA closed', region: 'NA', status: 'closed', secret: 's4' }, +]; + +for (const cell of CELLS) { + describe.skipIf(!cell.url)( + `queryCommentThreads on the real engine, SecurityPlugin and SQL driver — ${cell.label}${cell.url ? '' : ` (skipped: set ${cell.env} to run this cell)`}`, + () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + let driver: SqlDriver; + let dropDatabase: (() => Promise) | undefined; + const as: Record = {}; + /** account id → its one top-level thread. */ + const threadOn = new Map(); + + const contextOf = async (userId: string): Promise => { + const authz = await resolveAuthzContext({ + ql, + headers: {}, + getSession: async () => ({ + user: { id: userId }, + session: { id: `ses_${userId}`, userId, activeOrganizationId: ORG }, + }), + } as never); + return assembleExecutionContext({ authz, oauth: undefined, localization: undefined, requestLocale: undefined, accessToken: undefined } as never); + }; + const read = (userId: string, request: Row) => queryCommentThreads(ql as any, { object: ACCOUNT, ...request } as any, as[userId]); + const threadIds = (answer: { threads: Row[] }) => answer.threads.map((x) => String(x.comment.id)); + const expectedOn = (accounts: string[]) => accounts.map((a) => threadOn.get(a)!); + + beforeAll(async () => { + let config: Record; + if (cell.id === 'pg') { + const db = await provisionPgDatabase(cell.url!); + dropDatabase = db.drop; + config = { client: 'pg', connection: db.url }; + } else { + config = { client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }; + } + driver = new SqlDriver(config as never); + kernel = new ObjectKernel({ logger: { level: 'silent' } } as never); + await kernel.use(driverPlugin(driver)); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(objectsPlugin()); + await kernel.use(new AuditPlugin()); + await kernel.use(new SecurityPlugin({ defaultPermissionSets: [...securityDefaultPermissionSets, FULL_SET, SCOPED_SET, NONE_SET] })); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + + await ql.insert('sys_organization', { id: ORG, name: 'CTQE', slug: 'ctqe' }, { context: SYS_ORG } as never); + const grants: Record = { [ALICE]: FULL_SET.name, [BOB]: SCOPED_SET.name, [CAROL]: NONE_SET.name }; + for (const [userId, set] of Object.entries(grants)) { + await ql.insert('sys_user', { id: userId, name: userId, email: `${userId}@ctqe.test`, email_verified: true }, { context: SYS_ORG } as never); + await ql.insert('sys_member', { user_id: userId, organization_id: ORG, role: 'member' }, { context: SYS_ORG } as never); + await ql.insert('sys_user_permission_set', { user_id: userId, permission_set: set, organization_id: ORG }, { context: SYS_ORG } as never); + } + for (const userId of Object.keys(grants)) as[userId] = await contextOf(userId); + + for (const account of ACCOUNTS) await ql.insert(ACCOUNT, { ...account }, { context: SYS_ORG } as never); + for (const account of ACCOUNTS) { + const row = await ql.insert(COMMENT, { thread_id: `${ACCOUNT}:${account.id}`, author_id: ALICE, body: account.id }, { context: { ...SYS_ORG, userId: ALICE } } as never); + threadOn.set(account.id, String(row.id)); + await ql.insert(COMMENT, { thread_id: `${ACCOUNT}:${account.id}`, author_id: BOB, body: 'reply', parent_id: row.id }, { context: { ...SYS_ORG, userId: BOB } } as never); + } + }, 180_000); + + afterAll(async () => { + if (kernel) await Promise.race([kernel.shutdown(), new Promise((r) => setTimeout(r, 10_000))]); + if (dropDatabase) await dropDatabase(); + }, 60_000); + + it('a full reader and a row-scoped reader: the open threads on the accounts each reads, newest first', async () => { + const open = { filter: { status: 'open' } }; + expect(threadIds(await read(ALICE, open))).toEqual(expectedOn(['acc_hidden_open', 'acc_eu_open', 'acc_na_open'])); + const bob = await read(BOB, open); + expect(threadIds(bob)).toEqual(expectedOn(['acc_eu_open', 'acc_na_open'])); + expect(bob.threads.map((x) => [x.record, x.replyCount, x.repliers.map((r: Row) => r.id)])).toEqual([ + [{ id: 'acc_eu_open', name: 'EU open' }, 1, [BOB]], + [{ id: 'acc_na_open', name: 'NA open' }, 1, [BOB]], + ]); + }); + + it('a member with no read on the object: that read\'s PERMISSION_DENIED; a filter on a field the caller cannot read: PERMISSION_DENIED', async () => { + const carol = await read(CAROL, { filter: { status: 'open' } }).then(() => null, (e: any) => e); + expect(carol?.code).toBe('PERMISSION_DENIED'); + const secret = await read(BOB, { filter: { secret: 's1' } }).then(() => null, (e: any) => e); + expect(secret?.code).toBe('PERMISSION_DENIED'); + // CONTROL a reader of the field is served the one account's thread. + expect(threadIds(await read(ALICE, { filter: { secret: 's1' } }))).toEqual(expectedOn(['acc_na_open'])); + }); + + it('two users through one engine: each request plans its own scope under its own context, never one kept from another request', async () => { + const plans: string[] = []; + const saved = ql.planReadScope; + (ql as any).planReadScope = (...a: any[]) => { + plans.push(String(a[2]?.context?.userId)); + return saved.apply(ql, a as never); + }; + try { + const open = { filter: { status: 'open' } }; + const answers = []; + for (const userId of [BOB, ALICE, BOB, ALICE]) answers.push(threadIds(await read(userId, open))); + expect(plans).toEqual([BOB, ALICE, BOB, ALICE]); + const bobs = expectedOn(['acc_eu_open', 'acc_na_open']); + const alices = expectedOn(['acc_hidden_open', 'acc_eu_open', 'acc_na_open']); + expect(answers).toEqual([bobs, alices, bobs, alices]); + } finally { + (ql as any).planReadScope = saved; + } + }); + + it('more than 1,000 matching records: answered in full, the threads read ONE statement carrying the planned read, the accounts never read for ids', async () => { + const bulk = Array.from({ length: 1005 }, (_, i) => ({ id: `acc_bulk_${String(i).padStart(4, '0')}`, name: `bulk ${i}`, region: 'NA', status: 'bulk', secret: 'x' })); + await ql.insert(ACCOUNT, bulk, { context: SYS_ORG } as never); + for (const a of [bulk[0], bulk[bulk.length - 1]]) { + const row = await ql.insert(COMMENT, { thread_id: `${ACCOUNT}:${a.id}`, author_id: ALICE, body: a.id }, { context: { ...SYS_ORG, userId: ALICE } } as never); + threadOn.set(a.id, String(row.id)); + } + const { result, reads } = await driverReadsDuring(driver, () => read(BOB, { filter: { status: 'bulk' } })); + expect(threadIds(result)).toEqual(expectedOn([bulk[bulk.length - 1].id, bulk[0].id])); + expect(result.threads.map((x) => x.record.name)).toEqual(['bulk 1004', 'bulk 0']); + const planned = plannedStatements(reads, ACCOUNT); + expect(planned.threads).toHaveLength(1); + expect(planned.threads[0].query.limit).toBe(26); + expect(inComparands(planned.threads[0].query.where, ACCOUNT)).not.toContain('list'); + expect(planned.gateProbes.length).toBeLessThanOrEqual(1); + const accountReads = reads.filter((r) => r.object === ACCOUNT); + expect(accountReads).toHaveLength(1); + expect(accountReads[0].query?.limit ?? 0).toBeLessThanOrEqual(2); + }, 120_000); + }, + ); +} diff --git a/packages/spec/api-surface/api.json b/packages/spec/api-surface/api.json index 586f1dfb752..b8bea962011 100644 --- a/packages/spec/api-surface/api.json +++ b/packages/spec/api-surface/api.json @@ -193,6 +193,10 @@ "BulkResponseParsed (type)", "BulkResponseSchema (const)", "CHANNEL_SURFACE_SLOTS (const)", + "COMMENT_THREADS_DEFAULT_LIMIT (const)", + "COMMENT_THREADS_MAX_CURSOR_LENGTH (const)", + "COMMENT_THREADS_MAX_LIMIT (const)", + "COMMENT_THREADS_MAX_REPLIERS (const)", "CacheControl (type)", "CacheControlSchema (const)", "CacheDirective (const)", @@ -220,6 +224,21 @@ "CloneFlowResponseSchema (const)", "CodeGenerationTemplate (type)", "CodeGenerationTemplateSchema (const)", + "CommentThread (type)", + "CommentThreadParsed (type)", + "CommentThreadRecord (type)", + "CommentThreadRecordParsed (type)", + "CommentThreadRecordSchema (const)", + "CommentThreadReplier (type)", + "CommentThreadReplierParsed (type)", + "CommentThreadReplierSchema (const)", + "CommentThreadSchema (const)", + "CommentThreadsQueryRequest (type)", + "CommentThreadsQueryRequestParsed (type)", + "CommentThreadsQueryRequestSchema (const)", + "CommentThreadsQueryResponse (type)", + "CommentThreadsQueryResponseParsed (type)", + "CommentThreadsQueryResponseSchema (const)", "CompleteChunkedUploadRequest (type)", "CompleteChunkedUploadRequestSchema (const)", "CompleteChunkedUploadResponse (type)", diff --git a/packages/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index 3cbbf1b9108..e2608e515c1 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -402,6 +402,23 @@ "api/CodeGenerationTemplate:name", "api/CodeGenerationTemplate:template", "api/CodeGenerationTemplate:variables", + "api/CommentThread:comment", + "api/CommentThread:record", + "api/CommentThread:repliers", + "api/CommentThread:replyCount", + "api/CommentThreadRecord:id", + "api/CommentThreadRecord:name", + "api/CommentThreadReplier:avatarUrl", + "api/CommentThreadReplier:id", + "api/CommentThreadReplier:name", + "api/CommentThreadsQueryRequest:cursor", + "api/CommentThreadsQueryRequest:filter", + "api/CommentThreadsQueryRequest:limit", + "api/CommentThreadsQueryRequest:object", + "api/CommentThreadsQueryRequest:onlyMine", + "api/CommentThreadsQueryRequest:showResolved", + "api/CommentThreadsQueryResponse:nextCursor", + "api/CommentThreadsQueryResponse:threads", "api/CompleteChunkedUploadRequest:parts", "api/CompleteChunkedUploadRequest:uploadId", "api/CompleteChunkedUploadResponse:data", diff --git a/packages/spec/declaration-map/api.json b/packages/spec/declaration-map/api.json index 141bc8631e2..2498d6b05a7 100644 --- a/packages/spec/declaration-map/api.json +++ b/packages/spec/declaration-map/api.json @@ -171,6 +171,16 @@ "CloneFlowResponseSchema": "api/CloneFlowResponse", "CodeGenerationTemplate": "api/CodeGenerationTemplate", "CodeGenerationTemplateSchema": "api/CodeGenerationTemplate", + "CommentThread": "api/CommentThread", + "CommentThreadRecord": "api/CommentThreadRecord", + "CommentThreadRecordSchema": "api/CommentThreadRecord", + "CommentThreadReplier": "api/CommentThreadReplier", + "CommentThreadReplierSchema": "api/CommentThreadReplier", + "CommentThreadSchema": "api/CommentThread", + "CommentThreadsQueryRequest": "api/CommentThreadsQueryRequest", + "CommentThreadsQueryRequestSchema": "api/CommentThreadsQueryRequest", + "CommentThreadsQueryResponse": "api/CommentThreadsQueryResponse", + "CommentThreadsQueryResponseSchema": "api/CommentThreadsQueryResponse", "CompleteChunkedUploadRequest": "api/CompleteChunkedUploadRequest", "CompleteChunkedUploadRequestSchema": "api/CompleteChunkedUploadRequest", "CompleteChunkedUploadResponse": "api/CompleteChunkedUploadResponse", diff --git a/packages/spec/docs/references/README.md b/packages/spec/docs/references/README.md index dee85b33bea..3605b1c904b 100644 --- a/packages/spec/docs/references/README.md +++ b/packages/spec/docs/references/README.md @@ -13,7 +13,7 @@ Zod sources and JSON Schema, at the version your project uses. | Module | Pages | Description | | :--- | ---: | :--- | -| [API Protocol](api/README.md) | 38 | REST contracts, endpoints, routing, realtime, batch, discovery. | +| [API Protocol](api/README.md) | 39 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Identity Protocol](identity/README.md) | 5 | Users and accounts, organizations, positions, SCIM provisioning. | | [Integration Protocol](integration/README.md) | 1 | The single connector protocol (ADR-0097) — catalog descriptors and provider-bound instances. | | [Kernel Protocol](kernel/README.md) | 30 | Plugin lifecycle and manifests, capabilities and security, metadata loading, service registry. | diff --git a/packages/spec/docs/references/api/README.md b/packages/spec/docs/references/api/README.md index ca6b385c127..519b6df214b 100644 --- a/packages/spec/docs/references/api/README.md +++ b/packages/spec/docs/references/api/README.md @@ -48,6 +48,7 @@ stay there). - [Ai Answer](ai-answer.md) — `packages/spec/src/api/ai-answer.zod.ts` - [App Bundle](app-bundle.md) — `packages/spec/src/api/app-bundle.zod.ts` +- [Comment Threads](comment-threads.md) — `packages/spec/src/api/comment-threads.zod.ts` - [Error Code Ledger](error-code-ledger.md) — `packages/spec/src/api/error-code-ledger.zod.ts` - [Misc](misc.md) - [Package Api Assembled](package-api-assembled.md) — `packages/spec/src/api/package-api-assembled.zod.ts` diff --git a/packages/spec/docs/references/api/comment-threads.md b/packages/spec/docs/references/api/comment-threads.md new file mode 100644 index 00000000000..e8fe152e240 --- /dev/null +++ b/packages/spec/docs/references/api/comment-threads.md @@ -0,0 +1,160 @@ +# Comment Threads — API Protocol reference + + + +The comment threads read — `POST /api/v1/comments/threads/query`. + +One request that answers the discussions on the records a list page shows: +the top-level comments (`sys_comment` rows with no `parent_id`) on the +records of one object that the list's own filter selects, newest first, one +page at a time, each with the record it is on (id and display name), how +many replies it has and the faces of its latest repliers. + +## Which records + +The request names the object and carries the list's filter in the syntax +`GET /data/{object}` accepts (the saved view's filter AND the reader's +temporary filters; a search box is not a filter and is not sent). The +threads are the ones on the records that filter selects AND the caller may +read: the server plans the caller's own read of the object with that filter +and places it, as one subquery, in the comment read. No id list is read +first, so a view of any size is answered in full; where the engine cannot +prove the planned read (a parent narrowed after its driver call, another +datasource), it reads the ids as the caller and refuses past its cap rather +than answer part of the view. An object whose driver cannot run the subquery +(MongoDB, OData) is refused up front. + +## As the caller, every step + +The object read is the caller's: its object grant, row scope and field +rules apply, so a filter naming a field the caller cannot read is a +`PERMISSION_DENIED`, never an empty answer, and a caller with no read on +the object gets that read's own refusal. The comment read is the caller's +too, so the comment read gate decides exactly as it does on +`GET /data/sys_comment`. The record names and the repliers are read as the +caller. The read answers nothing those two list reads do not already answer +the same caller. + +## Paging + +`cursor` is the `nextCursor` of the previous page, opaque. It is a keyset +over the threads' creation time and id, so a comment posted while a reader +pages does not shift the pages after it: no thread is answered twice and +none is skipped. + +## Refusals, before anything is read + +A body key this schema does not declare, any query parameter, a `limit` +out of range or a `cursor` the server did not issue is +`VALIDATION_ERROR` / 400; a `filter` the list read cannot lower is +`INVALID_FILTER` / 400, the answer `GET /data/{object}` gives the same +value, and `null` or `[]` is no filter. An unknown object is `OBJECT_NOT_FOUND` / 404, +an object the data door does not serve answers the data door's own refusal, +`sys_comment` itself is `VALIDATION_ERROR` / 400, and an object whose +comments are switched off (`enable.feeds: false`) is `FEEDS_DISABLED` / 403. + +> **Source:** `packages/spec/src/api/comment-threads.zod.ts` + +## TypeScript Usage + +```typescript +import { CommentThreadSchema, CommentThreadRecordSchema, CommentThreadReplierSchema, CommentThreadsQueryRequestSchema, CommentThreadsQueryResponseSchema } from '@objectstack/spec/api'; +import type { CommentThread, CommentThreadRecord, CommentThreadReplier, CommentThreadsQueryRequest, CommentThreadsQueryResponse } from '@objectstack/spec/api'; + +// Validate data +const result = CommentThreadSchema.parse(data); +``` + +--- + +## CommentThread + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **comment** | `Record` | ✅ | The thread's top-level `sys_comment` row, with the fields the comment read serves this caller. | +| **record** | `{ id: string; name: string }` | ✅ | The record the thread is on. | +| **replyCount** | `integer` | ✅ | How many replies the thread has, at any depth, as the caller may read them. | +| **repliers** | `{ id: string; name: string \| null; avatarUrl: string \| null }[]` | ✅ | The latest distinct repliers, newest first, at most 3. | + +### Nested Shape: `CommentThread.record` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **id** | `string` | ✅ | The record id. | +| **name** | `string` | ✅ | The record's display name, read as the caller from the object's title field; `Record #` and the id when that field is empty or not served to the caller. | + +### Nested Shape: `CommentThread.repliers[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **id** | `string` | ✅ | The replier's user id. | +| **name** | `string \| null` | ✅ | The replier's display name, as the reply stored it. | +| **avatarUrl** | `string \| null` | ✅ | The replier's avatar, as the reply stored it. | + + +--- + +## CommentThreadRecord + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **id** | `string` | ✅ | The record id. | +| **name** | `string` | ✅ | The record's display name, read as the caller from the object's title field; `Record #` and the id when that field is empty or not served to the caller. | + + +--- + +## CommentThreadReplier + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **id** | `string` | ✅ | The replier's user id. | +| **name** | `string \| null` | ✅ | The replier's display name, as the reply stored it. | +| **avatarUrl** | `string \| null` | ✅ | The replier's avatar, as the reply stored it. | + + +--- + +## CommentThreadsQueryRequest + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **object** | `string` | ✅ | The object whose records the list shows, by machine name. Its threads are the ones answered; it may not be `sys_comment` itself. | +| **filter** | `any` | optional | The list's filter, in the filter syntax `GET /data/{object}` accepts: the saved view's filter AND the reader's temporary filters. It is run as the caller's read of the object, so it can only narrow the records the caller may read. Absent: every record of the object the caller may read. | +| **showResolved** | `boolean` | optional | Whether resolved threads are answered too. Absent or false: only threads that are not resolved. | +| **onlyMine** | `boolean` | optional | Only the threads the caller started, replied in or is mentioned in (the thread's stored participants). Absent or false: every thread. | +| **limit** | `integer` | optional | How many threads one page holds, from 1 to 50. Absent: 25. | +| **cursor** | `string` | optional | The `nextCursor` of the previous page, as it was answered. Absent: the first page. | + + +--- + +## CommentThreadsQueryResponse + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **threads** | `{ comment: Record; record: object; replyCount: integer; repliers: object[] }[]` | ✅ | One page of threads, newest first (by creation time, then id). | +| **nextCursor** | `string \| null` | ✅ | The cursor of the next page, or null when this page is the last. | + +### Nested Shape: `CommentThreadsQueryResponse.threads[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **comment** | `Record` | ✅ | The thread's top-level `sys_comment` row, with the fields the comment read serves this caller. | +| **record** | `{ id: string; name: string }` | ✅ | The record the thread is on. | +| **replyCount** | `integer` | ✅ | How many replies the thread has, at any depth, as the caller may read them. | +| **repliers** | `{ id: string; name: string \| null; avatarUrl: string \| null }[]` | ✅ | The latest distinct repliers, newest first, at most 3. | + + +--- + diff --git a/packages/spec/export-origins/api.json b/packages/spec/export-origins/api.json index e68495b75a7..1a486d19140 100644 --- a/packages/spec/export-origins/api.json +++ b/packages/spec/export-origins/api.json @@ -185,6 +185,10 @@ "BulkResponseParsed": "src/api/contract.zod.ts#BulkResponseParsed (type)", "BulkResponseSchema": "src/api/contract.zod.ts#BulkResponseSchema (const)", "CHANNEL_SURFACE_SLOTS": "src/api/discovery.zod.ts#CHANNEL_SURFACE_SLOTS (const)", + "COMMENT_THREADS_DEFAULT_LIMIT": "src/api/comment-threads.zod.ts#COMMENT_THREADS_DEFAULT_LIMIT (const)", + "COMMENT_THREADS_MAX_CURSOR_LENGTH": "src/api/comment-threads.zod.ts#COMMENT_THREADS_MAX_CURSOR_LENGTH (const)", + "COMMENT_THREADS_MAX_LIMIT": "src/api/comment-threads.zod.ts#COMMENT_THREADS_MAX_LIMIT (const)", + "COMMENT_THREADS_MAX_REPLIERS": "src/api/comment-threads.zod.ts#COMMENT_THREADS_MAX_REPLIERS (const)", "CacheControl": "src/api/http-cache.zod.ts#CacheControl (type)", "CacheControlSchema": "src/api/http-cache.zod.ts#CacheControlSchema (const)", "CacheDirective": "src/api/http-cache.zod.ts#CacheDirective (type)", @@ -210,6 +214,21 @@ "CloneFlowResponseSchema": "src/api/automation-api.zod.ts#CloneFlowResponseSchema (const)", "CodeGenerationTemplate": "src/api/documentation.zod.ts#CodeGenerationTemplate (type)", "CodeGenerationTemplateSchema": "src/api/documentation.zod.ts#CodeGenerationTemplateSchema (const)", + "CommentThread": "src/api/comment-threads.zod.ts#CommentThread (type)", + "CommentThreadParsed": "src/api/comment-threads.zod.ts#CommentThreadParsed (type)", + "CommentThreadRecord": "src/api/comment-threads.zod.ts#CommentThreadRecord (type)", + "CommentThreadRecordParsed": "src/api/comment-threads.zod.ts#CommentThreadRecordParsed (type)", + "CommentThreadRecordSchema": "src/api/comment-threads.zod.ts#CommentThreadRecordSchema (const)", + "CommentThreadReplier": "src/api/comment-threads.zod.ts#CommentThreadReplier (type)", + "CommentThreadReplierParsed": "src/api/comment-threads.zod.ts#CommentThreadReplierParsed (type)", + "CommentThreadReplierSchema": "src/api/comment-threads.zod.ts#CommentThreadReplierSchema (const)", + "CommentThreadSchema": "src/api/comment-threads.zod.ts#CommentThreadSchema (const)", + "CommentThreadsQueryRequest": "src/api/comment-threads.zod.ts#CommentThreadsQueryRequest (type)", + "CommentThreadsQueryRequestParsed": "src/api/comment-threads.zod.ts#CommentThreadsQueryRequestParsed (type)", + "CommentThreadsQueryRequestSchema": "src/api/comment-threads.zod.ts#CommentThreadsQueryRequestSchema (const)", + "CommentThreadsQueryResponse": "src/api/comment-threads.zod.ts#CommentThreadsQueryResponse (type)", + "CommentThreadsQueryResponseParsed": "src/api/comment-threads.zod.ts#CommentThreadsQueryResponseParsed (type)", + "CommentThreadsQueryResponseSchema": "src/api/comment-threads.zod.ts#CommentThreadsQueryResponseSchema (const)", "CompleteChunkedUploadRequest": "src/api/storage.zod.ts#CompleteChunkedUploadRequest (type)", "CompleteChunkedUploadRequestSchema": "src/api/storage.zod.ts#CompleteChunkedUploadRequestSchema (const)", "CompleteChunkedUploadResponse": "src/api/storage.zod.ts#CompleteChunkedUploadResponse (type)", diff --git a/packages/spec/json-schema.manifest/api.json b/packages/spec/json-schema.manifest/api.json index a39b5dd4b92..fc5c3166a1d 100644 --- a/packages/spec/json-schema.manifest/api.json +++ b/packages/spec/json-schema.manifest/api.json @@ -90,6 +90,11 @@ "api/CloneFlowRequest", "api/CloneFlowResponse", "api/CodeGenerationTemplate", + "api/CommentThread", + "api/CommentThreadRecord", + "api/CommentThreadReplier", + "api/CommentThreadsQueryRequest", + "api/CommentThreadsQueryResponse", "api/CompleteChunkedUploadRequest", "api/CompleteChunkedUploadResponse", "api/CompleteUploadRequest", diff --git a/packages/spec/llms.txt b/packages/spec/llms.txt index 61b6d8a0fd6..e7587d6b08c 100644 --- a/packages/spec/llms.txt +++ b/packages/spec/llms.txt @@ -77,7 +77,7 @@ const query = { --- -## 3. Schema Inventory by Domain (234 schemas) +## 3. Schema Inventory by Domain (235 schemas) Counted as `*.zod.ts` modules under `packages/spec/src//` — the sources that ship in this tarball (`files` includes `src/**/*.zod.ts`), so every number @@ -88,7 +88,7 @@ here is verifiable from the installed package. | system | 40 | Auth, Cache, Demo Staff, Dev Login, Email / SMS / Push Config, Push Device, Encryption, Fate Supplement (organization ownership), HTTP Server, License, Logging, Metrics, Restriction Profile | | kernel | 31 | Plugin, Manifest, Events (6 sub-modules), Feature, Context, Package Registry, Override Declaration | | data | 37 | Object, Field, Picklist, Query, Filter, Driver (SQL/NoSQL/Memory/Mongo/Postgres/Oracle/SQL Server), Cube, Seed, Recycle Bin, Declared Entry (refusal / text) | -| api | 37 | Endpoint, REST Server, Discovery, OData, Batch, WebSocket, Response Envelope, Package Lifecycle, Package API (assembled stage), Record Page, Record Lock, App Metadata Bundle, Push Delivery, Push Relay, AI Answer Follow-ups | +| api | 38 | Endpoint, REST Server, Discovery, OData, Batch, WebSocket, Response Envelope, Package Lifecycle, Package API (assembled stage), Record Page, Record Lock, App Metadata Bundle, Push Delivery, Push Relay, AI Answer Follow-ups, Comment Threads | | ui | 19 | View, App (incl. AI Chat Nav Params), Action, Dashboard, Page, Chart, Component, Animation | | automation | 16 | Flow, Approval, Assignment Rule, BPMN Interop, Control Flow, Webhook, Schedule Organization | | shared | 16 | Enums, HTTP, Identifiers, Mapping, Metadata Types, Connector Auth, Retry Policy, Conditional Formatting, Value Domain, Epoch Instant (EpochMs), Duration (DurationMs / DurationSeconds) | diff --git a/packages/spec/src/api/comment-threads.test.ts b/packages/spec/src/api/comment-threads.test.ts new file mode 100644 index 00000000000..22d92ae4bb2 --- /dev/null +++ b/packages/spec/src/api/comment-threads.test.ts @@ -0,0 +1,91 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it } from 'vitest'; +import { + COMMENT_THREADS_DEFAULT_LIMIT, + COMMENT_THREADS_MAX_CURSOR_LENGTH, + COMMENT_THREADS_MAX_LIMIT, + COMMENT_THREADS_MAX_REPLIERS, + CommentThreadSchema, + CommentThreadsQueryRequestSchema, + CommentThreadsQueryResponseSchema, +} from './comment-threads.zod'; + +const issueCodes = (value: unknown, schema: { safeParse(v: unknown): any } = CommentThreadsQueryRequestSchema): string[] => { + const parsed = schema.safeParse(value); + return parsed.success ? [] : parsed.error.issues.map((i: { code: string }) => i.code); +}; + +describe('the comment threads request is strict and bounded', () => { + it('takes the object alone, and every declared key', () => { + expect(CommentThreadsQueryRequestSchema.safeParse({ object: 'account' }).success).toBe(true); + expect(CommentThreadsQueryRequestSchema.safeParse({ + object: 'account', + filter: [['status', '=', 'open']], + showResolved: true, + onlyMine: false, + limit: COMMENT_THREADS_MAX_LIMIT, + cursor: 'abc', + }).success).toBe(true); + // The object form of a filter is the same `GET /data/{object}` syntax. + expect(CommentThreadsQueryRequestSchema.safeParse({ object: 'account', filter: { status: 'open' } }).success).toBe(true); + }); + + it('refuses a key it does not declare, and names it', () => { + const parsed = CommentThreadsQueryRequestSchema.safeParse({ object: 'account', search: 'acme' }); + expect(parsed.success).toBe(false); + expect(parsed.error?.issues[0]).toMatchObject({ code: 'unrecognized_keys', keys: ['search'] }); + }); + + it('refuses a request with no object, or an empty one', () => { + expect(issueCodes({})).toContain('invalid_type'); + expect(issueCodes({ object: '' })).toContain('too_small'); + }); + + it('holds limit to 1..max as a whole number, and the default is inside the range', () => { + expect(issueCodes({ object: 'account', limit: 0 })).toContain('too_small'); + expect(issueCodes({ object: 'account', limit: COMMENT_THREADS_MAX_LIMIT + 1 })).toContain('too_big'); + expect(issueCodes({ object: 'account', limit: 2.5 })).toContain('invalid_type'); + expect(issueCodes({ object: 'account', limit: '10' })).toContain('invalid_type'); + expect(COMMENT_THREADS_DEFAULT_LIMIT).toBeGreaterThanOrEqual(1); + expect(COMMENT_THREADS_DEFAULT_LIMIT).toBeLessThanOrEqual(COMMENT_THREADS_MAX_LIMIT); + }); + + it('takes the toggles only as booleans, and a cursor only as a bounded non-empty string', () => { + expect(issueCodes({ object: 'account', showResolved: 'true' })).toContain('invalid_type'); + expect(issueCodes({ object: 'account', onlyMine: 1 })).toContain('invalid_type'); + expect(issueCodes({ object: 'account', cursor: '' })).toContain('too_small'); + expect(issueCodes({ object: 'account', cursor: 'x'.repeat(COMMENT_THREADS_MAX_CURSOR_LENGTH + 1) })).toContain('too_big'); + }); +}); + +describe('the comment threads answer is strict', () => { + const thread = { + comment: { id: 'c1', body: 'hello', created_at: '2026-12-02T00:00:00.000Z' }, + record: { id: 'acc_1', name: 'Acme' }, + replyCount: 2, + repliers: [{ id: 'u1', name: 'Ann', avatarUrl: null }], + }; + + it('takes a page of threads and a next cursor, or null at the end', () => { + expect(CommentThreadsQueryResponseSchema.safeParse({ threads: [thread], nextCursor: 'n' }).success).toBe(true); + expect(CommentThreadsQueryResponseSchema.safeParse({ threads: [], nextCursor: null }).success).toBe(true); + }); + + it('refuses an answer with no nextCursor, or a key it does not declare', () => { + expect(CommentThreadsQueryResponseSchema.safeParse({ threads: [] }).success).toBe(false); + expect(CommentThreadsQueryResponseSchema.safeParse({ threads: [], nextCursor: null, total: 3 }).success).toBe(false); + }); + + it('a thread names at most the declared number of repliers, and a whole non-negative reply count', () => { + const many = Array.from({ length: COMMENT_THREADS_MAX_REPLIERS + 1 }, (_, i) => ({ id: `u${i}`, name: null, avatarUrl: null })); + expect(CommentThreadSchema.safeParse({ ...thread, repliers: many }).success).toBe(false); + expect(CommentThreadSchema.safeParse({ ...thread, replyCount: -1 }).success).toBe(false); + expect(CommentThreadSchema.safeParse({ ...thread, replyCount: 1.5 }).success).toBe(false); + }); + + it('a thread\'s record carries exactly its id and name', () => { + expect(CommentThreadSchema.safeParse({ ...thread, record: { id: 'acc_1' } }).success).toBe(false); + expect(CommentThreadSchema.safeParse({ ...thread, record: { id: 'acc_1', name: 'Acme', region: 'NA' } }).success).toBe(false); + }); +}); diff --git a/packages/spec/src/api/comment-threads.zod.ts b/packages/spec/src/api/comment-threads.zod.ts new file mode 100644 index 00000000000..e1f6e6ed403 --- /dev/null +++ b/packages/spec/src/api/comment-threads.zod.ts @@ -0,0 +1,145 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { z } from 'zod'; +import { lazySchema } from '../shared/lazy-schema'; + +/** + * The comment threads read — `POST /api/v1/comments/threads/query`. + * + * One request that answers the discussions on the records a list page shows: + * the top-level comments (`sys_comment` rows with no `parent_id`) on the + * records of one object that the list's own filter selects, newest first, one + * page at a time, each with the record it is on (id and display name), how + * many replies it has and the faces of its latest repliers. + * + * ## Which records + * + * The request names the object and carries the list's filter in the syntax + * `GET /data/{object}` accepts (the saved view's filter AND the reader's + * temporary filters; a search box is not a filter and is not sent). The + * threads are the ones on the records that filter selects AND the caller may + * read: the server plans the caller's own read of the object with that filter + * and places it, as one subquery, in the comment read. No id list is read + * first, so a view of any size is answered in full; where the engine cannot + * prove the planned read (a parent narrowed after its driver call, another + * datasource), it reads the ids as the caller and refuses past its cap rather + * than answer part of the view. An object whose driver cannot run the subquery + * (MongoDB, OData) is refused up front. + * + * ## As the caller, every step + * + * The object read is the caller's: its object grant, row scope and field + * rules apply, so a filter naming a field the caller cannot read is a + * `PERMISSION_DENIED`, never an empty answer, and a caller with no read on + * the object gets that read's own refusal. The comment read is the caller's + * too, so the comment read gate decides exactly as it does on + * `GET /data/sys_comment`. The record names and the repliers are read as the + * caller. The read answers nothing those two list reads do not already answer + * the same caller. + * + * ## Paging + * + * `cursor` is the `nextCursor` of the previous page, opaque. It is a keyset + * over the threads' creation time and id, so a comment posted while a reader + * pages does not shift the pages after it: no thread is answered twice and + * none is skipped. + * + * ## Refusals, before anything is read + * + * A body key this schema does not declare, any query parameter, a `limit` + * out of range or a `cursor` the server did not issue is + * `VALIDATION_ERROR` / 400; a `filter` the list read cannot lower is + * `INVALID_FILTER` / 400, the answer `GET /data/{object}` gives the same + * value, and `null` or `[]` is no filter. An unknown object is `OBJECT_NOT_FOUND` / 404, + * an object the data door does not serve answers the data door's own refusal, + * `sys_comment` itself is `VALIDATION_ERROR` / 400, and an object whose + * comments are switched off (`enable.feeds: false`) is `FEEDS_DISABLED` / 403. + */ + +/** The page size when the request names none. */ +export const COMMENT_THREADS_DEFAULT_LIMIT = 25; + +/** The largest page one request may ask for. */ +export const COMMENT_THREADS_MAX_LIMIT = 50; + +/** The most repliers one thread names: the latest distinct ones, newest first. */ +export const COMMENT_THREADS_MAX_REPLIERS = 3; + +/** The longest `cursor` the read accepts; the cursors it issues are far shorter. */ +export const COMMENT_THREADS_MAX_CURSOR_LENGTH = 512; + +/** The body of `POST /api/v1/comments/threads/query`. No key outside these is accepted. */ +export const CommentThreadsQueryRequestSchema = lazySchema(() => z.object({ + object: z.string().min(1).describe( + 'The object whose records the list shows, by machine name. Its threads are the ones answered; it may not be ' + + '`sys_comment` itself.', + ), + filter: z.unknown().optional().describe( + 'The list\'s filter, in the filter syntax `GET /data/{object}` accepts: the saved view\'s filter AND the ' + + 'reader\'s temporary filters. It is run as the caller\'s read of the object, so it can only narrow the records ' + + 'the caller may read. Absent: every record of the object the caller may read.', + ), + showResolved: z.boolean().optional().describe( + 'Whether resolved threads are answered too. Absent or false: only threads that are not resolved.', + ), + onlyMine: z.boolean().optional().describe( + 'Only the threads the caller started, replied in or is mentioned in (the thread\'s stored participants). ' + + 'Absent or false: every thread.', + ), + limit: z.number().int().min(1).max(COMMENT_THREADS_MAX_LIMIT).optional().describe( + `How many threads one page holds, from 1 to ${COMMENT_THREADS_MAX_LIMIT}. Absent: ${COMMENT_THREADS_DEFAULT_LIMIT}.`, + ), + cursor: z.string().min(1).max(COMMENT_THREADS_MAX_CURSOR_LENGTH).optional().describe( + 'The `nextCursor` of the previous page, as it was answered. Absent: the first page.', + ), +}).strict()); +export type CommentThreadsQueryRequest = z.input; +export type CommentThreadsQueryRequestParsed = z.infer; + +/** The record a thread is on. */ +export const CommentThreadRecordSchema = lazySchema(() => z.object({ + id: z.string().describe('The record id.'), + name: z.string().describe( + 'The record\'s display name, read as the caller from the object\'s title field; `Record #` and the id when ' + + 'that field is empty or not served to the caller.', + ), +}).strict()); +export type CommentThreadRecord = z.input; +export type CommentThreadRecordParsed = z.infer; + +/** One person who replied in a thread, as the reply stores its author. */ +export const CommentThreadReplierSchema = lazySchema(() => z.object({ + id: z.string().describe('The replier\'s user id.'), + name: z.string().nullable().describe('The replier\'s display name, as the reply stored it.'), + avatarUrl: z.string().nullable().describe('The replier\'s avatar, as the reply stored it.'), +}).strict()); +export type CommentThreadReplier = z.input; +export type CommentThreadReplierParsed = z.infer; + +/** One thread: its top-level comment, the record it is on, its replies' count and latest repliers. */ +export const CommentThreadSchema = lazySchema(() => z.object({ + comment: z.record(z.string(), z.unknown()).describe( + 'The thread\'s top-level `sys_comment` row, with the fields the comment read serves this caller.', + ), + record: CommentThreadRecordSchema.describe('The record the thread is on.'), + replyCount: z.number().int().min(0).describe( + 'How many replies the thread has, at any depth, as the caller may read them.', + ), + repliers: z.array(CommentThreadReplierSchema).max(COMMENT_THREADS_MAX_REPLIERS).describe( + `The latest distinct repliers, newest first, at most ${COMMENT_THREADS_MAX_REPLIERS}.`, + ), +}).strict()); +export type CommentThread = z.input; +export type CommentThreadParsed = z.infer; + +/** The `data` of the answer to `POST /api/v1/comments/threads/query`. */ +export const CommentThreadsQueryResponseSchema = lazySchema(() => z.object({ + threads: z.array(CommentThreadSchema).max(COMMENT_THREADS_MAX_LIMIT).describe( + 'One page of threads, newest first (by creation time, then id).', + ), + nextCursor: z.string().nullable().describe( + 'The cursor of the next page, or null when this page is the last.', + ), +}).strict()); +export type CommentThreadsQueryResponse = z.input; +export type CommentThreadsQueryResponseParsed = z.infer; diff --git a/packages/spec/src/api/index.ts b/packages/spec/src/api/index.ts index ff4a5e31bea..8e114ac0f3c 100644 --- a/packages/spec/src/api/index.ts +++ b/packages/spec/src/api/index.ts @@ -52,6 +52,8 @@ export * from './router.zod'; export * from './odata.zod'; export * from './batch.zod'; export * from './record-page.zod'; +// The comment threads read a list page's comment panel asks (`POST /api/v1/comments/threads/query`). +export * from './comment-threads.zod'; export * from './record-lock.zod'; export * from './app-bundle.zod'; export * from './http-cache.zod'; diff --git a/scripts/cross-package-test-inputs.mjs b/scripts/cross-package-test-inputs.mjs index 229f67aec4b..f4d7e035e85 100644 --- a/scripts/cross-package-test-inputs.mjs +++ b/scripts/cross-package-test-inputs.mjs @@ -885,6 +885,7 @@ export const CROSS_PACKAGE_TEST_INPUTS = { 'packages/services/service-i18n/src/i18n-route-ledger.ts', 'packages/services/service-datasource/src/datasource-route-ledger.ts', 'packages/plugins/plugin-auth/src/auth-route-ledger.ts', + 'packages/plugins/plugin-audit/src/comment-route-ledger.ts', // Below this line: paths these tests NAME in prose rather than read. Each // docblock cross-references the sibling conformance test it mirrors, or // the script that records the envelope shape, and the flat literal diff --git a/turbo.json b/turbo.json index 9bfa9aad877..786eed8e3fe 100644 --- a/turbo.json +++ b/turbo.json @@ -336,6 +336,7 @@ "$TURBO_ROOT$/packages/services/service-i18n/src/i18n-route-ledger.ts", "$TURBO_ROOT$/packages/services/service-datasource/src/datasource-route-ledger.ts", "$TURBO_ROOT$/packages/plugins/plugin-auth/src/auth-route-ledger.ts", + "$TURBO_ROOT$/packages/plugins/plugin-audit/src/comment-route-ledger.ts", "$TURBO_ROOT$/packages/runtime/src/route-ledger.conformance.test.ts", "$TURBO_ROOT$/packages/rest/src/rest-route-ledger.conformance.test.ts", "$TURBO_ROOT$/packages/services/service-storage/src/storage-route-ledger.conformance.test.ts", diff --git a/ui/scripts/check-spec-symbol-derivation.mjs b/ui/scripts/check-spec-symbol-derivation.mjs index 9d0a2b8018d..a563573a993 100644 --- a/ui/scripts/check-spec-symbol-derivation.mjs +++ b/ui/scripts/check-spec-symbol-derivation.mjs @@ -589,6 +589,17 @@ const ALLOW = { "and the node keeps its `ComponentPropsMap['form']` pairing there.", issue: 37086, }, + "@object-ui/collaboration:CommentThread": { + reason: + "Two LAYERS under one name (objectstack#39084): this is the published React COMPONENT " + + "that draws one discussion (threadId, comments, currentUser and the reply / resolve " + + "callbacks), and the spec's `CommentThread`, added with `POST /api/v1/comments/threads/query`, " + + "is one ENTRY of that read's answer (comment, record, replyCount, repliers). A component is " + + "not a wire shape, so neither import nor derivation fits. It is a PUBLISHED export of the " + + "package, so renaming it changes a public name and belongs to its own card; the list-page " + + "comments card that consumes the read imports the spec type under an alias.", + issue: 39084, + }, "@object-ui/types:SelectOptionSchema": { reason: "Spec-derived dialect (objectui#3090): spec keys flow in by reference via " +