diff --git a/.changeset/36186-36191-comment-doors.md b/.changeset/36186-36191-comment-doors.md new file mode 100644 index 00000000000..8475dddd071 --- /dev/null +++ b/.changeset/36186-36191-comment-doors.md @@ -0,0 +1,29 @@ +--- +'@objectstack/plugin-audit': patch +'@objectstack/core': patch +'@object-ui/app-shell': patch +'@object-ui/plugin-detail': patch +'@object-ui/react': patch +'@object-ui/core': patch +--- + +feat(comments): a member resolves and reopens any thread they can read, and deletes their own comments + +Clause-②: yes (widening) — `@objectstack/plugin-audit`'s `AuditPlugin` mounts two new HTTP routes, `PUT /api/v1/comments/:id/resolution` and `DELETE /api/v1/comments/:id`, and the stamp of who resolved a thread now reads a system write's `provenance.attributedUserId`. `@objectstack/core`'s `OwnRowDeleteDoor` adds an optional member, `refuseRemoval(row, engine, context)`, asked after the owner check. `@object-ui/react`'s `DiscussionContextValue` adds the optional `ownCommentDeletesOnly`; `@object-ui/plugin-detail`'s `RecordCommentsData` adds the optional `ownDeletesOnly`, and `RecordCommentThreadProps['comments']` may carry it; `@object-ui/core`'s affordance-to-grant map adds the row `feedCommentDeleteOwn`. Nothing existing is removed or re-typed. +Metadata-protocol: none + +Two server doors carry the maintainer's comment permission rulings past the platform's row floor (`owner_only_writes`, which lets a rank-and-file member update only the rows they created) and past the delete grant no every-member set may hold (ADR-0090 D5). Neither changes the floor, `sys_comment_moderation` or any permission set, and the data API answers exactly what it answered before. + +- **Resolve and reopen: `PUT /api/v1/comments/:id/resolution`** with the body `{ "resolved": true }` or `{ "resolved": false }` and nothing else. Whoever can read the thread and may post a comment on it may, external members included (ruling record 7063285032, option A: anyone who can see the record, the same gate as posting a comment): the door reads the comment as the caller (a comment they cannot read answers `404 RECORD_NOT_FOUND`, as an unknown id does), refuses a caller who reads comments but may not post one (`403 PERMISSION_DENIED`), refuses a reply (`400 VALIDATION_ERROR`) and then writes `is_resolved` alone, attributed to the caller. `resolved_by` names the caller. It answers `200` with `{ id, is_resolved, resolved_by, resolved_at }`. Any other query parameter or body is `400 VALIDATION_ERROR`; a signed-out request is `401`. +- **Delete your own comment: `DELETE /api/v1/comments/:id`.** It removes a comment the caller wrote (`author_id`), with no delete grant needed, on the platform's shared own-row delete door. Another member's comment is `403 PERMISSION_DENIED` and stays, even for a record editor: moderating someone else's comment stays the data API's, behind the delete grant. A comment that has replies stays too, whoever wrote them, `409 DELETE_RESTRICTED`, because removing it would turn each reply into a thread of its own (ruling record 7069889899: no one deletes or rewrites someone else's comment); its author may still edit its text. It answers `200` with `{ id, deleted: true }`. +- **Unchanged:** comment text stays its author's alone; a member's data-API update of a colleague's comment, `is_resolved` included, and a member's data-API delete are still `403`; administrators keep the data API for resolving, editing and deleting anyone's comment. + +The desktop comment panel follows the doors: + +- ✓ is on every thread, the viewer's and anyone else's, for a viewer holding the `sys_comment` create grant, and writes through the resolution door. It no longer asks the explain engine; that probe now gates only Edit on someone else's comment. +- A viewer without the `sys_comment` delete grant (an ordinary member) is offered Delete on their own comments that have no reply, and it goes through the own-comment delete door; a viewer with the grant deletes through the data API as before, others' comments included where they may edit the record. + +Corrections to two earlier notes of this release, which stay as written: + +- A rank-and-file member now resolves and reopens a colleague's thread through the resolution door; this replaces the #36071 note's line "This is the one widening: an update that changes nothing but `is_resolved` is admitted without the author-or-record-editor rule", because the platform's row floor (`owner_only_writes`) runs first, so through the data API such a member still resolves only the threads they started and an administrator resolves any. +- The desktop comment panel offers ✓ on every thread to a viewer who may post a comment and writes it through the resolution door; this replaces the #36075 note's line "✓ is offered under the `sys_comment` update grant: on a thread the viewer started, and on anyone's only where the explain engine admits …", and its "Unchanged" line's "a deployment without the explain service shows ✓ and Edit on the viewer's own rows only" now holds for Edit alone. diff --git a/content/docs/frontend/plugins/plugin-detail.mdx b/content/docs/frontend/plugins/plugin-detail.mdx index aa3328ff247..8e013c9c525 100644 --- a/content/docs/frontend/plugins/plugin-detail.mdx +++ b/content/docs/frontend/plugins/plugin-detail.mdx @@ -210,14 +210,19 @@ the record drawer), and no longer inside the 动态 (Activity) tab first, the comment box at the foot. A thread's replies fold to 「N 条回复」 and open in place. A comment's actions (Reply, an emoji, ✓ on a thread's first comment, and More with Edit and Delete) appear at its top right while - the pointer is over it. Edit and Delete are on your own comments. On other - people's they appear only where the server would accept them: Delete for a - member who may edit the record, Edit when the server also lets you change a - comment you did not write (today, administrators). + the pointer is over it. Edit and Delete are on your own comments; Delete is + not on a comment of yours that has replies, unless you hold the + `sys_comment` delete grant (administrators do), because the platform keeps + it for the replies under it. On other people's comments they appear only + where the server would accept them: Delete for someone who holds the + `sys_comment` delete grant and may edit the record, Edit when the server + also lets you change a comment you did not write (today, administrators). - **Resolved threads**: ✓ marks a thread resolved and it leaves the list; the - icon's number drops by one. It is on the threads you started, and on other - people's only where the server would accept it: today administrators, since - the platform lets a member change only the rows they wrote. The + icon's number drops by one. It is on every thread, yours and other people's: + whoever can read the record and may comment on it may resolve and reopen its + threads, through the platform's resolution door + (`PUT /api/v1/comments/:id/resolution`); someone who can read the comments + but not post one sees no ✓. The filter menu at the panel's top right holds 「显示已解决」, which shows resolved threads marked with who resolved them (their ✓ reopens them), and 「只看我参与的」, the threads you started, replied in or are mentioned in. A @@ -392,8 +397,13 @@ affordances, so the feed offers them wherever its host does: on a `comment` row (or a reply) whose `authoredByViewer` the host set, with the host's `onEditComment` / `onDeleteComment`. The console's record page marks each row with `@object-ui/collaboration`'s `isCommentAuthor`, the rule `CommentThread` -uses, and hands each handler over under the caller's update or delete grant on -`sys_comment`. Edit opens the text in place; Delete asks through the console's +uses, and hands Edit over under the caller's update grant on `sys_comment`. +Delete uses the data API under the caller's delete grant; a caller without it +(an ordinary member) deletes through the platform's own-comment delete door +(`DELETE /api/v1/comments/:id`) under the grant they comment with. That door +removes only the caller's own comment, and not one that has replies, so the +host sets `ownCommentDeletesOnly` and the feed offers Delete on exactly those +rows. Edit opens the text in place; Delete asks through the console's destructive-action confirm. The server still decides the write, and a refusal shows as an error with the comment unchanged. An edited comment reads as edited (`is_edited` on the row). diff --git a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-audit.md b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-audit.md index d9cd594f14a..2d3ff9b3fd3 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-audit.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-audit.md @@ -14,24 +14,24 @@ a row or a number here — fix the code, or the census, and regenerate. | Measure | Value | |---|---:| -| Write call sites | 20 | -| Object name statically decidable | 14 | +| Write call sites | 21 | +| Object name statically decidable | 15 | | Object name chosen at run time | 6 | | Object name spelled inline | 11 | -| Object name spelled through a `const` | 3 | +| Object name spelled through a `const` | 4 | | Object name is an `object: string` parameter | 0 | | Object name is some other run-time expression | 6 | -| Against a tenancy-enabled object | 14 | +| Against a tenancy-enabled object | 15 | | Against an object declaring tenancy off | 0 | -| Threading a tenant context | 15 | +| Threading a tenant context | 16 | | Provably carrying none (options read, no context key) | 0 | | …and decidably tenancy-enabled | 0 | | Options argument unreadable | 5 | | …and decidably tenancy-enabled | 4 | -| Threading a decidably elevated (`isSystem`) context | 15 | +| Threading a decidably elevated (`isSystem`) context | 16 | | Threading a decidably non-elevated context | 0 | | Threading a context of undecidable elevation | 5 | -| Receiver carried a readable engine type | 20 | +| Receiver carried a readable engine type | 21 | | Receiver erased, placed by the object NAME | 0 | | Receiver erased, placed by an `object: string` PARAMETER | 0 | | Receiver erased, placed by an `UNTYPED_RECEIVERS` row | 0 | @@ -58,6 +58,7 @@ a row or a number here — fix the code, or the census, and regenerate. | `packages/plugins/plugin-audit/src/auth-event-audit.ts` | `insert` | `sys_audit_log` | enabled | options unreadable | 1 | | `packages/plugins/plugin-audit/src/comment-parent-pair-backfill.ts` | `update` | `sys_comment` | enabled | elevated | 1 | | `packages/plugins/plugin-audit/src/comment-resolution.ts` | `update` | `sys_comment` | enabled | elevated | 1 | +| `packages/plugins/plugin-audit/src/comment-routes.ts` | `update` | `sys_comment` | enabled | elevated | 1 | | `packages/plugins/plugin-audit/src/credential-use-audit.ts` | `insert` | `sys_audit_log` | enabled | elevated | 1 | | `packages/plugins/plugin-audit/src/data-export-audit.ts` | `insert` | `sys_audit_log` | enabled | elevated | 1 | | `packages/plugins/plugin-audit/src/dataset-query-audit.ts` | `insert` | `sys_audit_log` | enabled | elevated | 1 | diff --git a/packages/core/src/security/own-row-delete-routes.test.ts b/packages/core/src/security/own-row-delete-routes.test.ts index c8d7f801c1c..4f31d090a88 100644 --- a/packages/core/src/security/own-row-delete-routes.test.ts +++ b/packages/core/src/security/own-row-delete-routes.test.ts @@ -14,7 +14,7 @@ import type { IHttpRequest } from '@objectstack/spec/contracts'; import { hashApiKey } from './api-key.js'; import { currentCredentialUseClient } from './credential-use-client.js'; -import { ownRowDeleteCallerResolver } from './own-row-delete-routes.js'; +import { ownRowDeleteCallerResolver, removeOwnRow, type OwnRowDeleteDoor } from './own-row-delete-routes.js'; const KEY = 'osk_own_row_delete_31898'; const OWNER = 'u_key_owner'; @@ -63,3 +63,59 @@ describe('[#31898] the own-row delete doors hand their client facts to the key\' expect(stamps).toEqual([{ ipAddress: '203.0.113.7', userAgent: 'ci-agent/3.1' }]); }); }); + +describe("the own-row delete door's step 7: the object's own refusal", () => { + const OWN = { id: 'row_1', owner_id: 'u_me' }; + const makeEngine = () => { + const deleted: unknown[] = []; + return { + deleted, + findOne: async () => ({ ...OWN }), + delete: async (_object: string, options: { where: Record }) => { + deleted.push(options.where); + return 1; + }, + }; + }; + const door = (refuseRemoval?: OwnRowDeleteDoor['refuseRemoval']): OwnRowDeleteDoor => ({ + route: '/api/v1/things/:id', + object: 'thing', + ownerField: 'owner_id', + words: { noun: 'thing', shortNoun: 'thing', owner: 'member' }, + ...(refuseRemoval ? { refuseRemoval } : {}), + }); + const ME = { userId: 'u_me', tenantId: 'org_1' } as never; + + it('a refusal it throws reaches the caller and nothing is removed', async () => { + const engine = makeEngine(); + const refusal = Object.assign(new Error('kept'), { code: 'DELETE_RESTRICTED', status: 409 }); + const seen: unknown[] = []; + await expect( + removeOwnRow(engine, door(async (row) => { + seen.push(row); + throw refusal; + }), 'row_1', ME), + ).rejects.toBe(refusal); + expect(seen).toEqual([OWN]); + expect(engine.deleted).toEqual([]); + }); + + it('is asked only after the owner check: a foreign row is refused 403 before it runs', async () => { + const engine = { ...makeEngine(), findOne: async () => ({ id: 'row_1', owner_id: 'u_other' }) }; + let asked = false; + await expect( + removeOwnRow(engine, door(async () => { + asked = true; + }), 'row_1', ME), + ).rejects.toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(asked).toBe(false); + }); + + it('resolving admits the removal, as a door that declares none does', async () => { + for (const refuse of [async () => undefined, undefined]) { + const engine = makeEngine(); + await removeOwnRow(engine, door(refuse), 'row_1', ME); + expect(engine.deleted).toEqual([{ id: 'row_1' }]); + } + }); +}); diff --git a/packages/core/src/security/own-row-delete-routes.ts b/packages/core/src/security/own-row-delete-routes.ts index 38356bd606f..ab1e69d3b9a 100644 --- a/packages/core/src/security/own-row-delete-routes.ts +++ b/packages/core/src/security/own-row-delete-routes.ts @@ -59,10 +59,14 @@ import { resolveRequestExecutionContext, type RequestAuthService } from './reque * gives both, so the door says nothing about a row the caller cannot see. * 6. **The owner.** A row the caller CAN read whose owner column names anyone * else is refused loudly, `PERMISSION_DENIED` / `403`, and stays. + * 7. **The object's own refusal**, for a door whose object declares one + * ({@link OwnRowDeleteDoor.refuseRemoval}): a row the caller owns that the + * object still may not lose. The door that declares it says why; its + * refusal is answered with its own `code` and `status`, and the row stays. * * ## The removal * - * Only after all six does the door remove the row, by id, under a system + * Only after all seven does the door remove the row, by id, under a system * context. That elevation is what lets the door reach a row the caller holds * no `delete` grant on, and step 6 is the only thing that admits it: the * elevated write is reached by no other path. The context keeps the caller as @@ -89,6 +93,14 @@ export interface OwnRowDeleteDoor { ownerField: string; /** The words the door's answers name the row with. */ words: OwnRowDeleteWords; + /** + * Step 7, optional: refuse the removal of a row the caller owns that the + * object still may not lose. Asked after the owner check with the row as the + * caller read it, the engine and the caller's context; it throws the refusal + * (an error carrying the ADR-0112 `code` and `status` the door answers) or + * resolves to admit. Nothing is removed before it resolves. + */ + refuseRemoval?(row: Record, engine: OwnRowDeleteEngine, context: ExecutionContext): Promise; } /** How a door's answers name its row: `reaction` / `reaction` / `member`, `personal view` / `view` / `user`. */ @@ -197,10 +209,11 @@ function notYourRowError(door: OwnRowDeleteDoor, id: string): Error { } /** - * Remove the caller's own row `id` of `door.object` — steps 5 and 6 of the + * Remove the caller's own row `id` of `door.object` — steps 5 to 7 of the * door, and the removal. Throws `RECORD_NOT_FOUND` / `404` for a row the - * caller cannot read or that does not exist, and `PERMISSION_DENIED` / `403` - * for a row whose owner is someone else. `context` must name a user. + * caller cannot read or that does not exist, `PERMISSION_DENIED` / `403` + * for a row whose owner is someone else, and the door's own refusal (step 7). + * `context` must name a user. */ export async function removeOwnRow( engine: OwnRowDeleteEngine, @@ -221,6 +234,9 @@ export async function removeOwnRow( // Step 6: the structural check, and the only thing that admits the write below. if (row[door.ownerField] !== callerId) throw notYourRowError(door, id); + // Step 7: the object's own refusal, where it declares one. + if (door.refuseRemoval) await door.refuseRemoval(row, engine, context); + const removed = await engine.delete(door.object, { where: { id }, context: { @@ -292,7 +308,7 @@ async function handleRemoveOwnRow( return; } - // ⑤ ⑥ and the removal. + // ⑤ ⑥ ⑦ and the removal. try { await removeOwnRow(engine, door, id, context); } catch (err) { diff --git a/packages/plugins/plugin-audit/src/audit-plugin.ts b/packages/plugins/plugin-audit/src/audit-plugin.ts index c843f3fdd37..6f043bfbbb0 100644 --- a/packages/plugins/plugin-audit/src/audit-plugin.ts +++ b/packages/plugins/plugin-audit/src/audit-plugin.ts @@ -63,6 +63,13 @@ import { registerCommentReactionRoutes, type CommentReactionEngine, } from './comment-reaction-routes.js'; +import { + COMMENT_REMOVE_ROUTE, + COMMENT_RESOLUTION_ROUTE, + registerCommentDoorsRoutes, + type CommentDoorsEngine, + type CommentPostingGate, +} from './comment-routes.js'; import { admitMentionRecipients } from './mention-recipient-gate.js'; import { installActivityReadVisibility } from './activity-read-visibility.js'; import { installActivityFieldRedaction } from './activity-field-redaction.js'; @@ -541,7 +548,7 @@ export class AuditPlugin implements Plugin { } async start(ctx: PluginContext): Promise { - this.mountUnreactDoor(ctx); + this.mountCommentDoors(ctx); // ObjectQL engine is only resolvable after the kernel is ready. ctx.hook('kernel:ready', async () => { let engine: IDataEngine | null = null; @@ -1062,14 +1069,22 @@ export class AuditPlugin implements Plugin { } /** - * Mount the unreact door (`comment-reaction-routes.ts`) on the kernel's HTTP - * server: a member removes their own comment reaction, and only theirs, - * without an object-level `delete` grant (maintainer ruling 6422861164, - * letter A). Every service the door reads is read per request, so a provider - * that registers after this hook is still seen. A kernel with no HTTP server + * Mount the comment doors on the kernel's HTTP server: + * + * - the unreact door (`comment-reaction-routes.ts`): a member removes their + * own comment reaction, and only theirs, without an object-level `delete` + * grant (maintainer ruling 6422861164, letter A); + * - the resolution door and the own-comment delete door + * (`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. + * + * 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 * mounts nothing, and says so. */ - private mountUnreactDoor(ctx: PluginContext): void { + private mountCommentDoors(ctx: PluginContext): void { const optional = (name: string): T | undefined => { try { return ctx.getService(name) ?? undefined; @@ -1081,21 +1096,31 @@ export class AuditPlugin implements Plugin { const http = optional('http.server') ?? optional('http-server'); if (!http) { ctx.logger.warn( - `AuditPlugin: no HTTP server is registered, so the unreact door (DELETE ${COMMENT_REACTION_REMOVE_ROUTE}) ` + - 'is not mounted, and a member whose grants carry no delete on sys_comment_reaction cannot remove their own reaction.', + `AuditPlugin: no HTTP server is registered, so the comment doors (DELETE ${COMMENT_REACTION_REMOVE_ROUTE}, ` + + `PUT ${COMMENT_RESOLUTION_ROUTE}, DELETE ${COMMENT_REMOVE_ROUTE}) are not mounted: a member whose grants carry ` + + 'no delete cannot remove their own reaction or comment, and resolves only the threads they started.', ); return; } const getEngine = () => optional('objectql') ?? optional('data'); + const resolveCaller = platformCallerResolver({ + getEngine, + getAuth: () => optional('auth'), + tenancy: tenancyServiceResolver(ctx), + }); registerCommentReactionRoutes(http, { getEngine: () => getEngine() as unknown as CommentReactionEngine | undefined, - resolveCaller: platformCallerResolver({ - getEngine, - getAuth: () => optional('auth'), - tenancy: tenancyServiceResolver(ctx), - }), + resolveCaller, + }); + registerCommentDoorsRoutes(http, { + getEngine: () => getEngine() as unknown as CommentDoorsEngine | undefined, + resolveCaller, + getSecurity: () => optional('security'), }); - ctx.logger.info(`AuditPlugin: unreact door mounted at DELETE ${COMMENT_REACTION_REMOVE_ROUTE}`); + ctx.logger.info( + `AuditPlugin: comment doors mounted at DELETE ${COMMENT_REACTION_REMOVE_ROUTE}, PUT ${COMMENT_RESOLUTION_ROUTE} ` + + `and DELETE ${COMMENT_REMOVE_ROUTE}`, + ); } /** diff --git a/packages/plugins/plugin-audit/src/comment-resolution.test.ts b/packages/plugins/plugin-audit/src/comment-resolution.test.ts index a254f29ff67..17e5a6f49f6 100644 --- a/packages/plugins/plugin-audit/src/comment-resolution.test.ts +++ b/packages/plugins/plugin-audit/src/comment-resolution.test.ts @@ -85,6 +85,27 @@ describe('stampCommentResolution — the arms the real-engine pins do not reach' expect(data.resolved_by).toBeNull(); expect(typeof data.resolved_at).toBe('string'); }); + it('a system write attributed to a caller (the resolution door) records that caller as the resolver', async () => { + const data: Record = { is_resolved: true }; + await stampCommentResolution({ + input: { data }, + previous: { is_resolved: false }, + session: { isSystem: true }, + provenance: { attributedUserId: 'u_door_caller' }, + }); + expect(data.resolved_by).toBe('u_door_caller'); + expect(typeof data.resolved_at).toBe('string'); + }); + it("an attribution never outranks a non-system write's own session user", async () => { + const data: Record = { is_resolved: true }; + await stampCommentResolution({ + input: { data }, + previous: { is_resolved: false }, + session: { userId: 'u_session' }, + provenance: { attributedUserId: 'u_other' }, + }); + expect(data.resolved_by).toBe('u_session'); + }); it('a non-boolean is_resolved is left to the record validator, unstamped', async () => { const data: Record = { is_resolved: 'yes' }; await stampCommentResolution({ input: { data }, previous: { is_resolved: false }, session: { userId: 'u' } }); diff --git a/packages/plugins/plugin-audit/src/comment-resolution.ts b/packages/plugins/plugin-audit/src/comment-resolution.ts index adb77167f6f..e52174fded5 100644 --- a/packages/plugins/plugin-audit/src/comment-resolution.ts +++ b/packages/plugins/plugin-audit/src/comment-resolution.ts @@ -21,7 +21,11 @@ * server clock; turning `false` clears both. * - **Who may resolve** ({@link isResolutionOnlyUpdate}; maintainer ruling * record 7063285032, option A): whoever may comment on the record may - * resolve and reopen its threads. An update that changes nothing but + * resolve and reopen its threads. On the data door the platform's row floor + * (`owner_only_writes`) runs first and admits a rank-and-file member's + * update of their own rows alone, so a member resolves a colleague's thread + * through the resolution door (`comment-routes.ts`), which writes this one + * column for any reader of the thread. An update that changes nothing but * `is_resolved` is authorized by the rule that admits a new comment — the * caller can read the record the thread is on — instead of the * author-or-parent-editor rule every other update meets. It is a narrow, @@ -130,9 +134,10 @@ export function refuseResolutionOnReply(rows: ReadonlyArray { data[key] = value; }; if (next) { - const userId: unknown = ctx?.session?.userId; + // A system write a door performs for a caller (the resolution door, + // `comment-routes.ts`) carries that caller as its attribution, never in + // `session`, where every gating hook would read them as the caller. The + // precedence is the audit writer's own (#4586): the session subject wins + // when present, and the attribution names the resolver otherwise. + const userId: unknown = ctx?.session?.userId ?? ctx?.provenance?.attributedUserId; assign( COMMENT_RESOLVED_BY_FIELD, (typeof userId === 'string' || typeof userId === 'number') && String(userId) !== '' ? String(userId) : null, 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 new file mode 100644 index 00000000000..dc45bce63f6 --- /dev/null +++ b/packages/plugins/plugin-audit/src/comment-route-ledger.conformance.test.ts @@ -0,0 +1,61 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * 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 + * 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 + * package. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { registerCommentDoorsRoutes } from './comment-routes.js'; +import { COMMENT_ROUTE_LEDGER } from './comment-route-ledger.js'; + +function createMockServer() { + return { + get: vi.fn(), + post: vi.fn(), + put: vi.fn(), + delete: vi.fn(), + patch: vi.fn(), + use: vi.fn(), + listen: vi.fn().mockResolvedValue(undefined), + close: vi.fn().mockResolvedValue(undefined), + }; +} + +function enumerateRoutes(): Set { + const server = createMockServer(); + registerCommentDoorsRoutes(server as any, {} as any); + const keys = new Set(); + for (const verb of ['get', 'post', 'put', 'patch', 'delete'] as const) { + for (const call of server[verb].mock.calls) keys.add(`${verb.toUpperCase()} ${call[0]}`); + } + return keys; +} + +const ledgerKeys = (): Set => new Set(COMMENT_ROUTE_LEDGER.map((e) => e.route)); + +describe('comment-door route ledger ↔ registerCommentDoorsRoutes enumeration', () => { + it('every mounted route has a ledger entry', () => { + const ledger = ledgerKeys(); + const missing = [...enumerateRoutes()].filter((k) => !ledger.has(k)); + expect(missing, `comment-door routes with no ledger entry: ${missing.join(', ')}`).toEqual([]); + }); + + it('every ledger entry is really mounted by the registrar', () => { + const live = enumerateRoutes(); + const stale = [...ledgerKeys()].filter((k) => !live.has(k)); + expect(stale, `comment-door ledger entries the registrar no longer mounts: ${stale.join(', ')}`).toEqual([]); + }); + + it('the ledger is compared against a real enumeration, not an empty one', () => { + const live = enumerateRoutes(); + expect(live.size).toBeGreaterThan(0); + expect(live.size).toBe(ledgerKeys().size); + expect(COMMENT_ROUTE_LEDGER.every((e) => e.disposition === 'sdk' || (e.note ?? '').length > 0)).toBe(true); + }); +}); diff --git a/packages/plugins/plugin-audit/src/comment-route-ledger.ts b/packages/plugins/plugin-audit/src/comment-route-ledger.ts new file mode 100644 index 00000000000..361bca2bbe7 --- /dev/null +++ b/packages/plugins/plugin-audit/src/comment-route-ledger.ts @@ -0,0 +1,40 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Comment-door route ledger — the audited disposition of every HTTP route + * `registerCommentDoorsRoutes` (`comment-routes.ts`) mounts. + * + * WHY THIS EXISTS. `AuditPlugin` reaches for the `http.server` service and + * registers straight on `IHttpServer`, so neither the dispatcher ledger nor the + * REST ledger sees these routes, the same shape as the unreact door's + * (`comment-reaction-route-ledger.ts`). `comment-route-ledger.conformance.test.ts` + * 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. + * + * This module is package-internal (not exported from the index): it is the + * guard's data, not public API. It stays import-free. + */ + +/** One row: the same shape and vocabulary as the unreact door's ledger and the REST ledger. */ +export interface CommentRouteLedgerEntry { + /** `VERB /api/v1/...` — the full wire path. */ + route: string; + /** Registrar family, for grouping and diff messages. */ + family: string; + disposition: 'sdk' | 'gap' | 'server-only' | 'public' | 'mismatch'; + /** Dotted method path on `ObjectStackClient` — required when disposition is `sdk`. */ + client?: string; + /** One-line rationale. Required for every non-`sdk` disposition. */ + note?: string; +} + +export const COMMENT_ROUTE_LEDGER: readonly CommentRouteLedgerEntry[] = [ + { route: 'PUT /api/v1/comments/:id/resolution', family: 'comments', disposition: 'gap', + 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" }, +]; diff --git a/packages/plugins/plugin-audit/src/comment-routes.test.ts b/packages/plugins/plugin-audit/src/comment-routes.test.ts new file mode 100644 index 00000000000..2234ca13050 --- /dev/null +++ b/packages/plugins/plugin-audit/src/comment-routes.test.ts @@ -0,0 +1,215 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The comment doors' own shell (`comment-routes.ts`): which routes the + * registrar mounts, and the answers the resolution door gives before the + * engine is ever asked. The authorization itself — a member resolving a + * colleague's thread, removing their own comment and no one else's, a comment + * with replies kept, the data door unchanged — is pinned on the real kernel, + * security plugin and caller resolution in plugin-security's + * `comment-doors.integration.test.ts`, which can compose plugin-security where + * this package cannot. + */ + +import { assertEngineFindOnePredicate } from '@objectstack/metadata-core'; +import { describe, it, expect, vi } from 'vitest'; +import { AuthzStoreUnavailableError } from '@objectstack/core'; + +import { + COMMENT_REMOVE_ROUTE, + COMMENT_RESOLUTION_ROUTE, + registerCommentDoorsRoutes, + type CommentDoorsEngine, + type CommentDoorsRoutesDeps, +} from './comment-routes.js'; + +type Handler = (req: unknown, res: unknown) => unknown; + +function mount(deps: CommentDoorsRoutesDeps) { + const routes = new Map(); + const record = (verb: string) => (path: string, handler: Handler) => { + routes.set(`${verb} ${path}`, handler); + }; + registerCommentDoorsRoutes( + { get: record('GET'), post: record('POST'), put: record('PUT'), patch: record('PATCH'), delete: record('DELETE') } as any, + deps, + ); + return routes; +} + +async function resolveCall(deps: CommentDoorsRoutesDeps, req: Partial<{ params: any; query: any; body: any }>) { + const handler = mount(deps).get(`PUT ${COMMENT_RESOLUTION_ROUTE}`); + if (!handler) throw new Error('the registrar mounted no resolution door'); + 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 handler({ method: 'PUT', path: '/api/v1/comments/c1/resolution', params: { id: 'c1' }, query: {}, headers: {}, ...req }, res); + return answer; +} + +function untouchedEngine() { + const engine = { findOne: vi.fn(), delete: vi.fn(), update: vi.fn() }; + return engine as typeof engine & CommentDoorsEngine; +} + +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', () => { + 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(getEngine).not.toHaveBeenCalled(); + expect(resolveCaller).not.toHaveBeenCalled(); + }); +}); + +describe('the resolution door — answers given before the engine is asked', () => { + it('a permission store that cannot be read answers its own 503, not a denial', async () => { + const engine = untouchedEngine(); + const answer = await resolveCall( + { + getEngine: () => engine, + resolveCaller: async () => { + throw new AuthzStoreUnavailableError('sys_user_permission_set', new Error('connection refused')); + }, + }, + { body: { resolved: true } }, + ); + expect(answer.status).toBe(503); + expect(answer.body?.error?.code).toBe('SERVICE_UNAVAILABLE'); + expect(engine.findOne).not.toHaveBeenCalled(); + }); + + it('a request naming nobody is 401 UNAUTHENTICATED', async () => { + const engine = untouchedEngine(); + const answer = await resolveCall({ getEngine: () => engine, resolveCaller: async () => ({}) as any }, { body: { resolved: true } }); + expect(answer.status).toBe(401); + expect(answer.body?.error?.code).toBe('UNAUTHENTICATED'); + expect(engine.findOne).not.toHaveBeenCalled(); + }); + + it('a held sign-in answers the authentication policy’s own 403', async () => { + const engine = untouchedEngine(); + const held = { ...MEMBER, authGate: { code: 'PASSWORD_EXPIRED', message: 'Your password has expired.' } }; + const answer = await resolveCall({ getEngine: () => engine, resolveCaller: async () => held }, { body: { resolved: true } }); + expect(answer.status).toBe(403); + expect(answer.body?.error?.code).toBe('PASSWORD_EXPIRED'); + expect(engine.findOne).not.toHaveBeenCalled(); + }); + + it('no data engine registered is 503 SERVICE_UNAVAILABLE', async () => { + const answer = await resolveCall({ getEngine: () => undefined, resolveCaller: async () => MEMBER }, { body: { resolved: false } }); + expect(answer.status).toBe(503); + expect(answer.body?.error?.code).toBe('SERVICE_UNAVAILABLE'); + }); + + it('a body other than exactly { resolved: boolean } is 400 VALIDATION_ERROR, and the engine is not asked', async () => { + for (const body of [undefined, null, {}, [], { resolved: 1 }, { resolved: true, extra: 1 }, { is_resolved: true }]) { + const engine = untouchedEngine(); + const answer = await resolveCall({ getEngine: () => engine, resolveCaller: async () => MEMBER }, { body }); + expect(answer.status, JSON.stringify(body)).toBe(400); + expect(answer.body?.error?.code).toBe('VALIDATION_ERROR'); + expect(engine.findOne).not.toHaveBeenCalled(); + expect(engine.update).not.toHaveBeenCalled(); + } + }); + + it('a query parameter is refused, not ignored: 400 VALIDATION_ERROR', async () => { + const engine = untouchedEngine(); + const answer = await resolveCall( + { getEngine: () => engine, resolveCaller: async () => MEMBER }, + { body: { resolved: true }, query: { force: 'true' } }, + ); + expect(answer.status).toBe(400); + expect(answer.body?.error?.code).toBe('VALIDATION_ERROR'); + expect(engine.findOne).not.toHaveBeenCalled(); + }); + + it('the write sends is_resolved alone, under a system context attributed to the caller and kept in their organization', async () => { + const engine = { + findOne: vi.fn(async (o: string, q: any) => { + assertEngineFindOnePredicate(o, q); + return q.context?.isSystem ? { id: 'c1', is_resolved: true, resolved_by: 'u_member', resolved_at: '2026-11-21T00:00:00.000Z' } : { id: 'c1' }; + }), + update: vi.fn(async () => ({})), + delete: vi.fn(), + }; + const caller = { ...MEMBER, tenantId: 'org_1' }; + const answer = await resolveCall({ getEngine: () => engine as any, resolveCaller: async () => caller }, { body: { resolved: true } }); + expect(answer.status, JSON.stringify(answer.body)).toBe(200); + expect(engine.findOne.mock.calls[0][1].context).toBe(caller); + expect(engine.update).toHaveBeenCalledWith('sys_comment', { is_resolved: true }, { + where: { id: 'c1' }, + context: { isSystem: true, attributedUserId: 'u_member', tenantId: 'org_1' }, + }); + expect(answer.body?.data).toEqual({ id: 'c1', is_resolved: true, resolved_by: 'u_member', resolved_at: '2026-11-21T00:00:00.000Z' }); + }); +}); + +describe('the resolution door — the posting gate (step 6)', () => { + const readableComment = () => ({ + findOne: vi.fn(async (o: string, q: any) => { + assertEngineFindOnePredicate(o, q); + return { id: 'c1' }; + }), + update: vi.fn(async () => ({})), + delete: vi.fn(), + }); + + it('a caller who reads the comment but may not post one is 403 PERMISSION_DENIED, and nothing is written', async () => { + const engine = readableComment(); + const canWriteObject = vi.fn(async () => false); + const answer = await resolveCall( + { getEngine: () => engine as any, resolveCaller: async () => MEMBER, getSecurity: () => ({ canWriteObject }) }, + { body: { resolved: true } }, + ); + expect(answer.status).toBe(403); + expect(answer.body?.error?.code).toBe('PERMISSION_DENIED'); + expect(canWriteObject).toHaveBeenCalledWith('sys_comment', 'insert', MEMBER); + expect(engine.update).not.toHaveBeenCalled(); + }); + + it('a posting check that throws refuses, as the check itself says a throw does', async () => { + const engine = readableComment(); + const answer = await resolveCall( + { + getEngine: () => engine as any, + resolveCaller: async () => MEMBER, + getSecurity: () => ({ canWriteObject: async () => { throw new Error('store down'); } }), + }, + { body: { resolved: true } }, + ); + expect(answer.status).toBe(403); + expect(engine.update).not.toHaveBeenCalled(); + }); + + it('an unreadable comment is still 404, asked before the posting gate', async () => { + const engine = { ...readableComment(), findOne: vi.fn(async (o: string, q: any) => { assertEngineFindOnePredicate(o, q); return null; }) }; + const canWriteObject = vi.fn(async () => false); + const answer = await resolveCall( + { getEngine: () => engine as any, resolveCaller: async () => MEMBER, getSecurity: () => ({ canWriteObject }) }, + { body: { resolved: true } }, + ); + expect(answer.status).toBe(404); + expect(canWriteObject).not.toHaveBeenCalled(); + }); + + it('a caller who may post resolves', async () => { + const engine = readableComment(); + const answer = await resolveCall( + { getEngine: () => engine as any, resolveCaller: async () => MEMBER, getSecurity: () => ({ canWriteObject: async () => true }) }, + { body: { resolved: true } }, + ); + expect(answer.status, JSON.stringify(answer.body)).toBe(200); + expect(engine.update).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/plugins/plugin-audit/src/comment-routes.ts b/packages/plugins/plugin-audit/src/comment-routes.ts new file mode 100644 index 00000000000..02620df1f63 --- /dev/null +++ b/packages/plugins/plugin-audit/src/comment-routes.ts @@ -0,0 +1,351 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { + ANONYMOUS_DENY_CODE, + ANONYMOUS_DENY_MESSAGE, + ANONYMOUS_DENY_STATUS, + evaluateAuthGate, + isApiKeyLifecycleRefusalError, + isAuthzStoreUnavailableError, + recordNotFoundError, + registerOwnRowDeleteRoute, + shouldDenyAnonymous, + type OwnRowDeleteDoor, + type OwnRowDeleteEngine, + type OwnRowDeleteRoutesDeps, +} from '@objectstack/core'; +import type { ErrorCode } from '@objectstack/spec/api'; +import type { IHttpRequest, IHttpResponse, IHttpServer } from '@objectstack/spec/contracts'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { resolveThrownHttpError, sendError, sendOk, sendServerFault } from '@objectstack/types'; + +import { + COMMENT_RESOLVED_AT_FIELD, + COMMENT_RESOLVED_BY_FIELD, + COMMENT_RESOLVED_FIELD, + refuseResolutionOnReply, +} from './comment-resolution.js'; + +/** + * The comment doors: two verbs a member uses on `sys_comment` rows that the + * data door's `update` and `delete` cannot serve them, each with exactly the + * reach the maintainer ruled (ruling record 7069889899 on the comments redo): + * + * - **The resolution door**, `PUT /api/v1/comments/:id/resolution`: resolve + * or reopen a thread, by its top-level comment. + * - **The own-comment delete door**, `DELETE /api/v1/comments/:id`: remove a + * comment the caller wrote. + * + * ## Why doors, and not the data door + * + * The platform's row floor (`owner_only_writes`, the default permission sets) + * lets a rank-and-file member update only the rows they created, and it runs + * before the comment access hooks. Resolving is an update, so on the data + * door a member could resolve only the threads they started, although whoever + * may comment on the record may resolve its threads (ruling record 7063285032, + * option A). The floor cannot be loosened for one column: a row policy decides + * WHICH rows, never which columns, so admitting the resolve update would also + * admit a member's edit of a colleague's words, which stays the author's alone + * (ruling record 7069889899). The resolution door writes one column and + * nothing else, so it reaches the threads the ruling names without touching + * the floor. + * + * Removing is a `delete`, and `delete` needs an object-level grant that no + * every-member set may carry (ADR-0090 D5; `member_default` has none on + * `sys_comment`), so a member could post a comment and never take it back. + * The own-comment delete door is the platform's shared own-row delete door + * (`own-row-delete-routes.ts` in `@objectstack/core`), as the unreact door + * (`comment-reaction-routes.ts`) is. + * + * Neither door changes what the data door answers: a member's data-door + * update of a colleague's comment, `is_resolved` included, and a member's + * data-door delete are refused exactly as before. + * + * ## The resolution door — every refusal before anything is written + * + * 1. **The caller**, resolved by the platform's one composition, as the + * own-row doors resolve it (`ownRowDeleteCallerResolver`, passed by the + * mounting plugin). A permission store that cannot be read answers its own + * `503`, and an API key its lifecycle refuses its own `403`. + * 2. **Anonymous**: `UNAUTHENTICATED` / `401`. + * 3. **A held sign-in**: `403` with the authentication policy's own code. + * 4. **The request**: no query parameter, and a body that is exactly + * `{ "resolved": true }` or `{ "resolved": false }`; anything else is + * `VALIDATION_ERROR` / `400`. + * 5. **The comment, read AS THE CALLER**: the object grant, the organization + * wall, and the comment read gate (a comment is readable exactly when the + * record its thread is on is). A comment the caller cannot read and an id + * that names none get the same answer, `RECORD_NOT_FOUND` / `404`. + * 6. **The posting gate**: the caller must be one who may post a comment + * here, the security service's own object-level answer for a `sys_comment` + * insert (`canWriteObject`). Ruling record 7063285032 (option A) names both + * "anyone who can see the record" and "the same gate as posting a + * comment"; the door takes the narrower reading, so a principal who reads + * comments but may not post one (a read-only grant on its own) is refused, + * `PERMISSION_DENIED` / `403`. Every stock member posts, so for them the + * two readings agree. A deployment with no security service has no gate + * on posting either, and this step admits there. + * 7. **A reply** is refused, `VALIDATION_ERROR` / `400`: a thread is resolved + * on its top-level comment (`refuseResolutionOnReply`, the data door's + * own sentence). + * + * Only then is `is_resolved` written, by id, under a system context that keeps + * the caller as `attributedUserId` and keeps the caller's organization. The + * platform stamps who and when from that attribution + * (`stampCommentResolution`), so `resolved_by` names the caller; the audit + * ledger credits the caller too. The door answers `200` with + * `{ id, is_resolved, resolved_by, resolved_at }` as stored. + * + * ## The own-comment delete door + * + * - **The owner column** is `author_id`, the author the platform stamps from + * the session and keeps read-only: the column the comment rules mean by + * "authors govern their own words". Another member's comment is refused, + * `PERMISSION_DENIED` / `403`, even on a record the caller can edit: the + * moderator's delete stays the data door's, behind an explicit delete grant. + * - **A comment that has replies stays** (the door's step 7), whoever wrote them: + * `DELETE_RESTRICTED` / `409`. Removing it would rewrite the replies: + * `parent_id` is a lookup that clears on delete, so each reply would become + * a thread of its own. The author may still edit its text. A known limit: + * the reply check and the removal are two engine calls, and the data + * engine offers no conditional delete to join them, so a reply posted in + * the one request between them is promoted to a thread of its own, as it + * is under an administrator's data-door delete today. + * - **The removal** is a system delete attributed to the caller, so the + * comment gates do not run a second time and the audit ledger credits the + * caller. + * + * Both routes and their ledger rows: `comment-route-ledger.ts`. + */ + +/** The object the doors read and write. */ +const COMMENT_OBJECT = 'sys_comment'; + +/** The resolution door's route pattern. */ +export const COMMENT_RESOLUTION_ROUTE = '/api/v1/comments/:id/resolution'; + +/** The own-comment delete door's route pattern. */ +export const COMMENT_REMOVE_ROUTE = '/api/v1/comments/:id'; + +/** The one body key the resolution door reads. */ +const RESOLVED_BODY_KEY = 'resolved'; + +/** + * Step 7 of the own-comment delete door: a comment with a reply under it + * stays. Asked through a system read, so a reply the caller's read scope would + * hide still counts. + */ +async function refuseRemovalUnderReplies( + row: Record, + engine: OwnRowDeleteEngine, +): Promise { + const reply = await engine.findOne(COMMENT_OBJECT, { + where: { parent_id: row.id }, + context: { isSystem: true } as ExecutionContext, + }); + if (!reply) return; + const err = new Error( + `Comment ${String(row.id)} was not removed: it has replies, and removing it would turn each reply ` + + 'into a thread of its own. Edit its text instead. The comment is unchanged.', + ) as Error & { code?: string; status?: number }; + err.code = 'DELETE_RESTRICTED'; + err.status = 409; + throw err; +} + +/** The own-comment delete door's part of the shared own-row delete door. */ +export const COMMENT_REMOVAL_DOOR: OwnRowDeleteDoor = Object.freeze({ + route: COMMENT_REMOVE_ROUTE, + object: COMMENT_OBJECT, + ownerField: 'author_id', + words: Object.freeze({ noun: 'comment', shortNoun: 'comment', owner: 'member' }), + refuseRemoval: refuseRemovalUnderReplies, +}); + +/** The slice of the data engine the doors read and write through. */ +export interface CommentDoorsEngine extends OwnRowDeleteEngine { + update(object: string, data: Record, options: { where: Record; context: ExecutionContext }): Promise; +} + +/** What the doors are composed over — every service read when a request arrives. */ +export interface CommentDoorsRoutesDeps { + /** The data engine; `undefined` when none is registered. */ + getEngine(): CommentDoorsEngine | undefined; + /** Resolve the caller of a request (`ownRowDeleteCallerResolver`); `undefined` names nobody. */ + resolveCaller: OwnRowDeleteRoutesDeps['resolveCaller']; + /** + * The security service, read per request for the resolution door's posting + * gate (step 6); `undefined` when none is registered. + */ + getSecurity?(): CommentPostingGate | undefined; +} + +/** The slice of the security service the posting gate asks (plugin-security's `canWriteObject`). */ +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. */ +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); +} + +/** The stored resolution the door answers with. */ +export interface CommentResolutionAnswer { + id: string; + is_resolved: boolean; + resolved_by: string | null; + resolved_at: string | null; +} + +/** + * Resolve or reopen the thread whose top-level comment is `id` — steps 5 and + * 6 of the resolution door, and the write. Throws `RECORD_NOT_FOUND` / `404` + * for a comment the caller cannot read or that does not exist, and + * `VALIDATION_ERROR` / `400` for a reply. `context` must name a user. + */ +export async function resolveCommentThread( + engine: CommentDoorsEngine, + id: string, + resolved: boolean, + context: ExecutionContext, + security?: CommentPostingGate, +): Promise { + const callerId = context.userId; + if (!callerId) throw new Error('resolveCommentThread: the caller context names no user'); + + // Step 5: read the comment as the caller, so every read gate decides. + const row = (await engine.findOne(COMMENT_OBJECT, { where: { id }, context })) as + | Record + | null + | undefined; + if (!row) throw recordNotFoundError(COMMENT_OBJECT, id, context); + + // Step 6: the posting gate. Asked after the read, so a comment the caller + // cannot read still answers as an unknown id. A check that throws refuses. + if (typeof security?.canWriteObject === 'function') { + let mayPost = false; + try { + mayPost = (await security.canWriteObject(COMMENT_OBJECT, 'insert', context)) === true; + } catch { + mayPost = false; + } + if (!mayPost) { + const err = new Error( + `The thread of comment ${id} was not changed: resolving and reopening a thread takes the same access as ` + + 'posting a comment on it, and you can read this thread but not comment on it.', + ) as Error & { code?: string; status?: number }; + err.code = 'PERMISSION_DENIED'; + err.status = 403; + throw err; + } + } + + // Step 7: a thread is resolved on its top-level comment. + refuseResolutionOnReply([row]); + + const system = { + isSystem: true, + attributedUserId: callerId, + ...(context.tenantId ? { tenantId: context.tenantId } : {}), + } as ExecutionContext; + await engine.update(COMMENT_OBJECT, { [COMMENT_RESOLVED_FIELD]: resolved }, { where: { id }, context: system }); + + const stored = (await engine.findOne(COMMENT_OBJECT, { where: { id }, context: system })) as + | Record + | null + | undefined; + // The driver's own "nothing matched": the comment went between the read and here. + if (!stored) throw recordNotFoundError(COMMENT_OBJECT, id, context); + const text = (v: unknown): string | null => (v === undefined || v === null || v === '' ? null : String(v)); + return { + id, + is_resolved: stored[COMMENT_RESOLVED_FIELD] === true, + resolved_by: text(stored[COMMENT_RESOLVED_BY_FIELD]), + resolved_at: text(stored[COMMENT_RESOLVED_AT_FIELD]), + }; +} + +async function handleResolution(req: IHttpRequest, res: IHttpResponse, deps: CommentDoorsRoutesDeps): Promise { + const where = { method: 'PUT', path: COMMENT_RESOLUTION_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, where); + return; + } + + // ② Anonymous. + if (!context || shouldDenyAnonymous({ userId: context.userId, method: req.method })) { + sendError(res, ANONYMOUS_DENY_STATUS, ANONYMOUS_DENY_CODE, ANONYMOUS_DENY_MESSAGE); + return; + } + + // ③ A held sign-in. + const authGate = evaluateAuthGate(context, ''); + if (authGate) { + sendError(res, 403, authGate.code as ErrorCode, authGate.message); + return; + } + + // ④ The request. The body is read outside any catch: a transport that + // refuses it answers the request itself. + const query = Object.keys(req.query ?? {}); + if (query.length > 0) { + sendError( + res, + 400, + 'VALIDATION_ERROR', + `Resolving a comment thread takes no query parameter, and this request carries ${query.map((q) => `'${q}'`).join(', ')}. ` + + 'Name the comment by its id in the path and send { "resolved": true } or { "resolved": false } as the body.', + ); + return; + } + const id = typeof req.params?.id === 'string' ? req.params.id.trim() : ''; + if (id === '') { + sendError(res, 400, 'VALIDATION_ERROR', 'Name the comment whose thread to resolve by its id in the path.'); + return; + } + const body: unknown = req.body; + const keys = body && typeof body === 'object' && !Array.isArray(body) ? Object.keys(body) : null; + const resolved = keys ? (body as Record)[RESOLVED_BODY_KEY] : undefined; + if (!keys || keys.length !== 1 || keys[0] !== RESOLVED_BODY_KEY || typeof resolved !== 'boolean') { + sendError( + res, + 400, + 'VALIDATION_ERROR', + 'The body must be exactly { "resolved": true } to resolve the thread or { "resolved": false } to reopen it, ' + + 'and nothing else.', + ); + return; + } + + const engine = deps.getEngine(); + if (!engine) { + sendError(res, 503, 'SERVICE_UNAVAILABLE', 'Comment threads cannot be resolved right now: no data engine is registered.'); + return; + } + + // ⑤ ⑥ ⑦ and the write. + let answer: CommentResolutionAnswer; + try { + answer = await resolveCommentThread(engine, id, resolved, context, deps.getSecurity?.()); + } catch (err) { + const thrown = resolveThrownHttpError(err, 500); + if (thrown.status < 500) { + sendError(res, thrown.status, thrown.code, thrown.message); + return; + } + sendServerFault(res, thrown.status, thrown.code, 'The comment thread could not be updated because of an error on the server.', err, where); + return; + } + sendOk(res, answer); +} diff --git a/packages/plugins/plugin-security/src/comment-doors.integration.test.ts b/packages/plugins/plugin-security/src/comment-doors.integration.test.ts new file mode 100644 index 00000000000..a1366e7d0b3 --- /dev/null +++ b/packages/plugins/plugin-security/src/comment-doors.integration.test.ts @@ -0,0 +1,476 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The comment doors (`plugin-audit`'s `comment-routes.ts`) on the real stack: + * a rank-and-file member resolves and reopens a colleague's thread through the + * resolution door, and removes a comment they wrote through the own-comment + * delete door, while the data door answers exactly what it answered before + * (ruling records 7063285032 and 7069889899). + * + * The members here hold what every signed-in member holds: the platform + * baseline `member_default` (read, create and update on `sys_comment`, no + * delete; the row floor `owner_only_writes` admits their update of their own + * rows alone) and an application's every-member set that reads the parent + * object. An organization administrator is the unchanged control. + * + * - the REAL `AuditPlugin` (the comment object, its access hooks, the + * resolution stamp, and the doors it mounts on the kernel's HTTP server); + * - the REAL `SecurityPlugin` with the shipped permission sets; + * - the REAL caller resolution, over the identity rows seeded below and an + * auth service whose session read names the user the request names. + * + * The one stand-in is the HTTP transport: a capturing `http.server` records + * the doors' registrations, and each case calls a registered handler with a + * request and a recording response. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { ObjectKernel, assembleExecutionContext, resolveAuthzContext, type Plugin, type PluginContext } from '@objectstack/core'; +import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { AuditPlugin } from '@objectstack/plugin-audit'; +import { SysMember, SysOrganization, SysUser } from '@objectstack/platform-objects/identity'; +import { PermissionSetSchema } from '@objectstack/spec/security'; +import { mapDataError } from '@objectstack/types'; +import { SecurityPlugin } from './security-plugin.js'; +import { defaultPermissionSets } from './objects/default-permission-sets.js'; + +const COMMENT = 'sys_comment'; +/** A parent object every member reads. */ +const OPEN = 'cmd_board'; +/** A parent object no member reads. */ +const SECRET = 'cmd_vault'; +const ORG = 'org_acme'; +const RESOLUTION_ROUTE = '/api/v1/comments/:id/resolution'; +const REMOVE_ROUTE = '/api/v1/comments/:id'; +/** The header the test auth service reads the signed-in user from. */ +const SIGNED_IN_AS = 'x-test-signed-in-as'; + +const ALICE = 'usr_alice'; +const BOB = 'usr_bob'; +const CAROL = 'usr_carol'; +/** An external member granted the board and its comments to read, and nothing to post. */ +const DAVE = 'usr_dave'; +/** An external member granted the board to read and its comments to read and post. */ +const ERIN = 'usr_erin'; + +/** The application's every-member set: it reads the parent; comments come from `member_default`. */ +const APP_EVERYONE_SET = PermissionSetSchema.parse({ + name: 'cmd_app_member', + label: 'App member (every-member set)', + objects: { + [OPEN]: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false }, + }, +}); + +/** An explicit external grant that reads the thread and cannot post into it. */ +const READ_ONLY_PORTAL_SET = PermissionSetSchema.parse({ + name: 'cmd_portal_reader', + label: 'Portal reader (explicit external grant)', + objects: { + [OPEN]: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false }, + sys_comment: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false }, + }, +}); + +/** An explicit external grant that reads the thread and posts into it. */ +const POSTING_PORTAL_SET = PermissionSetSchema.parse({ + name: 'cmd_portal_commenter', + label: 'Portal commenter (explicit external grant)', + objects: { + [OPEN]: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false }, + sys_comment: { allowRead: true, allowCreate: true, allowEdit: false, allowDelete: false }, + }, +}); + +const SYS = { isSystem: true, tenantId: ORG } as const; + +type Handler = (req: unknown, res: unknown) => unknown; +const routes = new Map(); + +/** A capturing HTTP server: the doors' registrations are recorded, never served. */ +function httpServerPlugin(): Plugin { + const record = (verb: string) => (path: string, handler: Handler) => { + routes.set(`${verb} ${path}`, handler); + }; + const server = { + get: record('GET'), + post: record('POST'), + put: record('PUT'), + patch: record('PATCH'), + delete: record('DELETE'), + use: () => undefined, + listen: async () => undefined, + close: async () => undefined, + }; + return { + name: 'test.http', + type: 'standard', + version: '1.0.0', + async init(ctx: PluginContext) { + ctx.registerService('http.server', server); + }, + }; +} + +/** An auth service whose in-process session read names the user the request names. */ +function authPlugin(): Plugin { + const api = { + async getSession(input: { headers: Headers }) { + const userId = input.headers.get(SIGNED_IN_AS); + if (!userId) return null; + return { + user: { id: userId, email: `${userId}@acme.test` }, + session: { id: `ses_${userId}`, userId, activeOrganizationId: ORG }, + }; + }, + }; + return { + name: 'test.auth', + type: 'standard', + version: '1.0.0', + async init(ctx: PluginContext) { + ctx.registerService('auth', { api }); + }, + }; +} + +function sqliteDriverPlugin(): Plugin { + return { + name: 'test.driver.sqlite', + type: 'standard', + version: '1.0.0', + async init(ctx: PluginContext) { + ctx.registerService( + 'driver.default', + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), + ); + }, + }; +} + +function objectsPlugin(): Plugin { + const parent = (name: string, label: string) => ({ + name, + label, + fields: { name: { type: 'text', label: 'Name' } }, + }); + 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-doors', + namespace: 'cmd', + version: '1.0.0', + type: 'plugin', + name: 'Comment doors fixture', + objects: [SysUser, SysMember, SysOrganization, parent(OPEN, 'Board'), parent(SECRET, 'Vault')], + }); + }, + }; +} + +interface Answer { + status: number; + body: any; +} + +/** Call the door mounted at `VERB route` as `signedInAs` (or nobody). */ +async function callDoor( + verb: 'PUT' | 'DELETE', + route: string, + id: string, + signedInAs: string | undefined, + extra: { body?: unknown; query?: Record } = {}, +): Promise { + const handler = routes.get(`${verb} ${route}`); + if (!handler) throw new Error(`no ${verb} ${route} is mounted on the kernel's HTTP server`); + const answer: Answer = { status: 200, body: undefined }; + const res = { + status(code: number) { + answer.status = code; + return res; + }, + json(body: unknown) { + answer.body = body; + }, + send(body: unknown) { + answer.body = body; + }, + header() { + return res; + }, + }; + await handler( + { + method: verb, + path: route.replace(':id', id), + params: { id }, + query: extra.query ?? {}, + body: extra.body, + headers: signedInAs ? { [SIGNED_IN_AS]: signedInAs } : {}, + }, + res, + ); + return answer; +} + +const resolve = (id: string, as: string | undefined, body: unknown = { resolved: true }, query?: Record) => + callDoor('PUT', RESOLUTION_ROUTE, id, as, { body, query }); +const remove = (id: string, as: string | undefined) => callDoor('DELETE', REMOVE_ROUTE, id, as); + +describe('the comment doors — a member resolves any thread they can read, and removes only their own comment', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + let boardThread: string; + let vaultThread: string; + /** Each persona's context as the platform's one resolver gives it, for the data door's path. */ + const as: Record = {}; + 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 rowById = async (id: string) => ql.findOne(COMMENT, { where: { id }, context: SYS }); + /** A comment written as `author` (the engine stamps `created_by` from the writer). */ + const commentAs = async (author: string, threadId: string, body: string, parentId?: string): Promise => { + const row = await ql.insert( + COMMENT, + { thread_id: threadId, author_id: author, body, ...(parentId ? { parent_id: parentId } : {}) }, + { context: { ...SYS, userId: author } }, + ); + return String(row.id); + }; + /** The data door's own path: the engine write under the caller's context, mapped to the wire as the REST door maps it. */ + const viaDataDoor = async (write: () => Promise): Promise => { + try { + await write(); + return 200; + } catch (e) { + return mapDataError(e, COMMENT).status; + } + }; + + beforeAll(async () => { + routes.clear(); + kernel = new ObjectKernel({ logger: { level: 'silent' } }); + await kernel.use(sqliteDriverPlugin()); + await kernel.use(httpServerPlugin()); + await kernel.use(authPlugin()); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(objectsPlugin()); + await kernel.use(new AuditPlugin()); + await kernel.use( + new SecurityPlugin({ + defaultPermissionSets: [...defaultPermissionSets, APP_EVERYONE_SET, READ_ONLY_PORTAL_SET, POSTING_PORTAL_SET], + fallbackPermissionSet: APP_EVERYONE_SET.name, + }), + ); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + + await ql.insert('sys_organization', { id: ORG, name: 'Acme', slug: 'acme' }, { context: SYS }); + const roles: Record = { + [ALICE]: 'member', + [BOB]: 'member', + [CAROL]: 'admin', + [DAVE]: 'external', + [ERIN]: 'external', + }; + for (const [userId, role] of Object.entries(roles)) { + await ql.insert( + 'sys_user', + { id: userId, name: userId, email: `${userId}@acme.test`, email_verified: true }, + { context: SYS }, + ); + await ql.insert('sys_member', { user_id: userId, organization_id: ORG, role }, { context: SYS }); + } + await ql.insert('sys_user_permission_set', { user_id: DAVE, permission_set: READ_ONLY_PORTAL_SET.name, organization_id: ORG }, { context: SYS } as never); + await ql.insert('sys_user_permission_set', { user_id: ERIN, permission_set: POSTING_PORTAL_SET.name, organization_id: ORG }, { context: SYS } as never); + for (const userId of Object.keys(roles)) as[userId] = await contextOf(userId); + + const board = await ql.insert(OPEN, { name: 'board' }, { context: SYS }); + const vault = await ql.insert(SECRET, { name: 'vault' }, { context: SYS }); + boardThread = `${OPEN}:${board.id}`; + vaultThread = `${SECRET}:${vault.id}`; + }, 120_000); + + afterAll(async () => { + if (kernel) { + await Promise.race([kernel.shutdown(), new Promise((r) => setTimeout(r, 10_000))]); + } + }, 30_000); + + it('the fixture is armed: two plain members and an administrator', () => { + expect(as[ALICE].positions).toEqual(expect.arrayContaining(['org_member', 'everyone'])); + expect(as[ALICE].positions).not.toContain('org_admin'); + expect(as[CAROL].positions).toEqual(expect.arrayContaining(['org_admin', 'everyone'])); + }); + + describe('the resolution door', () => { + it("a member resolves a colleague's thread — 200, resolved_by is the member — and reopens it", async () => { + const id = await commentAs(BOB, boardThread, "Bob's question"); + const resolved = await resolve(id, ALICE); + expect(resolved.status, JSON.stringify(resolved.body)).toBe(200); + expect(resolved.body?.data).toMatchObject({ id, is_resolved: true, resolved_by: ALICE }); + expect(typeof resolved.body?.data?.resolved_at).toBe('string'); + expect(await rowById(id)).toMatchObject({ is_resolved: true, resolved_by: ALICE, body: "Bob's question" }); + + const reopened = await resolve(id, ALICE, { resolved: false }); + expect(reopened.status).toBe(200); + expect(reopened.body?.data).toEqual({ id, is_resolved: false, resolved_by: null, resolved_at: null }); + const stored = await rowById(id); + expect(stored?.is_resolved).toBe(false); + expect(stored?.resolved_by ?? null).toBeNull(); + }); + + it("the data door does not move: a member's update of a colleague's comment is refused, is_resolved alone or with body", async () => { + const id = await commentAs(BOB, boardThread, 'unchanged words'); + expect(await viaDataDoor(() => ql.update(COMMENT, { body: 'rewritten' }, { where: { id }, context: as[ALICE] }))).toBe(403); + expect(await viaDataDoor(() => ql.update(COMMENT, { is_resolved: true }, { where: { id }, context: as[ALICE] }))).toBe(403); + expect( + await viaDataDoor(() => ql.update(COMMENT, { is_resolved: true, body: 'rewritten' }, { where: { id }, context: as[ALICE] })), + ).toBe(403); + expect(await rowById(id)).toMatchObject({ body: 'unchanged words', is_resolved: false }); + }); + + it('a reply is refused — 400 VALIDATION_ERROR — and nothing is written', async () => { + const root = await commentAs(BOB, boardThread, 'root'); + const reply = await commentAs(BOB, boardThread, 'reply', root); + const answer = await resolve(reply, ALICE); + expect(answer.status).toBe(400); + expect(answer.body?.error?.code).toBe('VALIDATION_ERROR'); + expect((await rowById(reply))?.is_resolved ?? false).toBe(false); + }); + + it('a thread the member cannot read answers as an unknown id — 404 RECORD_NOT_FOUND — and stays', async () => { + const id = await commentAs(BOB, vaultThread, 'vault talk'); + const hidden = await resolve(id, ALICE); + const unknown = await resolve('cmd_no_such_comment', ALICE); + expect(hidden.status).toBe(404); + expect(hidden.body?.error?.code).toBe('RECORD_NOT_FOUND'); + expect({ status: unknown.status, code: unknown.body?.error?.code }).toEqual({ + status: hidden.status, + code: hidden.body?.error?.code, + }); + expect((await rowById(id))?.is_resolved ?? false).toBe(false); + }); + + it('anonymous is 401; a query parameter or any body but { resolved: boolean } is 400; nothing is written', async () => { + const id = await commentAs(BOB, boardThread, 'shape'); + expect((await resolve(id, undefined)).status).toBe(401); + expect((await resolve(id, ALICE, { resolved: true }, { force: 'true' })).status).toBe(400); + for (const body of [undefined, {}, { resolved: 'yes' }, { resolved: true, body: 'x' }, { is_resolved: true }, [true]]) { + const answer = await callDoor('PUT', RESOLUTION_ROUTE, id, ALICE, { body }); + expect(answer.status, JSON.stringify(body)).toBe(400); + expect(answer.body?.error?.code).toBe('VALIDATION_ERROR'); + } + expect((await rowById(id))?.is_resolved ?? false).toBe(false); + }); + + it('takes the same gate as posting: an external who reads the thread and may not post is 403, and still reads it', async () => { + expect(as[DAVE].positions).toContain('org_external'); + const id = await commentAs(BOB, boardThread, 'a question the portal can read'); + const seen = await ql.findOne(COMMENT, { where: { id }, context: as[DAVE] }); + expect(seen).toMatchObject({ id, body: 'a question the portal can read' }); + const answer = await resolve(id, DAVE); + expect(answer.status, JSON.stringify(answer.body)).toBe(403); + expect(answer.body?.error?.code).toBe('PERMISSION_DENIED'); + expect(await rowById(id)).toMatchObject({ is_resolved: false, resolved_by: null }); + expect(await ql.findOne(COMMENT, { where: { id }, context: as[DAVE] })).toMatchObject({ id }); + }); + + it('an external who reads the thread and may post into it resolves it, as the ruling reads', async () => { + expect(as[ERIN].positions).toContain('org_external'); + const id = await commentAs(BOB, boardThread, 'a question the portal may answer'); + const answer = await resolve(id, ERIN); + expect(answer.status, JSON.stringify(answer.body)).toBe(200); + expect(answer.body?.data).toMatchObject({ id, is_resolved: true, resolved_by: ERIN }); + }); + }); + + describe('the own-comment delete door', () => { + it('own comment: removed — 200 — and gone', async () => { + const id = await commentAs(ALICE, boardThread, 'mine'); + const answer = await remove(id, ALICE); + expect(answer.status, JSON.stringify(answer.body)).toBe(200); + expect(answer.body).toEqual({ success: true, data: { id, deleted: true } }); + expect(await rowById(id)).toBeNull(); + }); + + it("a colleague's comment: 403 PERMISSION_DENIED, and it stays", async () => { + const id = await commentAs(BOB, boardThread, "Bob's"); + const answer = await remove(id, ALICE); + expect(answer.status).toBe(403); + expect(answer.body?.error?.code).toBe('PERMISSION_DENIED'); + expect((await rowById(id))?.id).toBe(id); + }); + + it('an own comment others replied under stays: 409 DELETE_RESTRICTED, root and reply unchanged', async () => { + const root = await commentAs(ALICE, boardThread, 'my question'); + const reply = await commentAs(BOB, boardThread, "Bob's answer", root); + const answer = await remove(root, ALICE); + expect(answer.status).toBe(409); + expect(answer.body?.error?.code).toBe('DELETE_RESTRICTED'); + expect((await rowById(root))?.id).toBe(root); + expect((await rowById(reply))?.parent_id).toBe(root); + }); + + it('an own reply with nothing under it: removed — 200', async () => { + const root = await commentAs(BOB, boardThread, "Bob's question"); + const reply = await commentAs(ALICE, boardThread, 'my reply', root); + expect((await remove(reply, ALICE)).status).toBe(200); + expect(await rowById(reply)).toBeNull(); + expect((await rowById(root))?.id).toBe(root); + }); + + it('an own comment on a record the member cannot read: 404, and it stays', async () => { + const id = await commentAs(ALICE, vaultThread, 'mine, hidden'); + const answer = await remove(id, ALICE); + expect(answer.status).toBe(404); + expect(answer.body?.error?.code).toBe('RECORD_NOT_FOUND'); + expect((await rowById(id))?.id).toBe(id); + }); + + it("the grant model does not move: a member's data-door delete of their own comment still answers 403", async () => { + const id = await commentAs(ALICE, boardThread, 'mine via data door'); + expect(await viaDataDoor(() => ql.delete(COMMENT, { where: { id }, context: as[ALICE] }))).toBe(403); + expect((await rowById(id))?.id).toBe(id); + }); + }); + + describe('an administrator is unchanged', () => { + it("the data door: an administrator resolves a member's thread as before (the row floor does not bind them), and the comment rule still decides edits and deletes", async () => { + const id = await commentAs(BOB, boardThread, "Bob's words"); + expect(await viaDataDoor(() => ql.update(COMMENT, { is_resolved: true }, { where: { id }, context: as[CAROL] }))).toBe(200); + expect(await rowById(id)).toMatchObject({ is_resolved: true, resolved_by: CAROL }); + // This fixture's administrator cannot edit the board, so the comment + // rule (author or record editor) refuses them, as it did before. + expect(await viaDataDoor(() => ql.update(COMMENT, { body: 'moderated' }, { where: { id }, context: as[CAROL] }))).toBe(403); + expect(await viaDataDoor(() => ql.delete(COMMENT, { where: { id }, context: as[CAROL] }))).toBe(403); + expect(await rowById(id)).toMatchObject({ body: "Bob's words" }); + }); + + it("the doors: an administrator's own-comment door still refuses a member's comment (the moderator's delete is the data door's)", async () => { + const id = await commentAs(BOB, boardThread, "Bob's, again"); + expect((await remove(id, CAROL)).status).toBe(403); + expect((await resolve(id, CAROL)).status).toBe(200); + }); + }); +}); diff --git a/scripts/check-route-envelope.mjs b/scripts/check-route-envelope.mjs index a468b41644e..5b6a842a940 100644 --- a/scripts/check-route-envelope.mjs +++ b/scripts/check-route-envelope.mjs @@ -321,6 +321,14 @@ const MODULES = { // own-row delete door below and answers nothing itself, so it builds no body. 'packages/plugins/plugin-audit/src/comment-reaction-routes.ts': { responses: 0, ok: 0, err: 0 }, + // The comment doors (`PUT /api/v1/comments/:id/resolution`, the resolution + // door, and `DELETE /api/v1/comments/:id`, the own-comment delete door), + // mounted by `AuditPlugin` beside the unreact door. Every body they answer is + // written by the shared pair (`sendOk` / `sendError` / `sendServerFault`) or + // by the shared own-row delete door below, so the module builds none itself. + // Declared in the same PR that created the module. + 'packages/plugins/plugin-audit/src/comment-routes.ts': { responses: 0, ok: 0, err: 0 }, + // The owner's delete door for a personal view (`DELETE /api/v1/personal-views/:id`), // mounted by `AuthPlugin` straight on `IHttpServer`. It supplies its part of the // shared own-row delete door below and answers nothing itself, so it builds no body. diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index f4d5ad077e5..de307a030b3 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -3771,6 +3771,11 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/plugins/plugin-audit/src/comment-routes.test.ts", + "verb": "findOne", + "pinned": 2 + }, { "file": "packages/plugins/plugin-audit/src/stored-metadata-body-migration.test.ts", "verb": "findOne", diff --git a/ui/packages/app-shell/src/views/RecordDetailView.commentsResolved-36075.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.commentsResolved-36075.test.tsx index 7fc6cd0b7e4..3372f6433f4 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.commentsResolved-36075.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.commentsResolved-36075.test.tsx @@ -7,8 +7,12 @@ * - The rows' `is_resolved` / `resolved_by` (#36071) reach the panel: the * icon counts the unresolved threads, a resolved one is hidden until * 「显示已解决」 and names its resolver (an author of the discussion here). - * - ✓ writes `{ is_resolved: true }` and nothing else on the top-level - * comment; the thread leaves the list and the count drops. + * - ✓ resolves through the resolution door (`PUT /api/v1/comments/:id/resolution` + * with `{ resolved }`, objectstack#36186), on every thread, the viewer's + * and others'; the thread leaves the list and the count drops. + * - Without the `sys_comment` delete grant, the viewer's Delete goes through + * the own-comment delete door (`DELETE /api/v1/comments/:id`, + * objectstack#36191), on their own comments with no reply alone. * - A reply into a resolved thread shows it reopened, as the platform stores. * - Edit and Delete on another member's comment only on the explain engine's * definite allow of a by-id update of the record; an unanswered verdict @@ -21,10 +25,12 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { render, cleanup, within, act, waitFor, fireEvent } from '@testing-library/react'; import { MemoryRouter } from 'react-router-dom'; +/** The page's authenticated fetch: the comment doors answer through it. */ +const doorFetch = vi.hoisted(() => vi.fn()); vi.mock('@object-ui/auth', async (importOriginal) => ({ ...(await importOriginal>()), useAuth: () => ({ user: { id: 'u-ada', name: 'Ada', image: null }, activeOrganization: null }), - createAuthenticatedFetch: () => vi.fn(), + createAuthenticatedFetch: () => doorFetch, })); vi.mock('@object-ui/collaboration', async (importOriginal) => ({ ...(await importOriginal>()), @@ -168,6 +174,7 @@ const PERMS = { } as MePermissionsAuthenticatedResponse; interface MountOptions { + perms?: MePermissionsAuthenticatedResponse; objectName?: string; pages?: unknown[]; embedded?: boolean; @@ -175,11 +182,11 @@ interface MountOptions { users?: ReadonlyArray>; } -async function mount({ objectName = OBJECT_NAME, pages = [], embedded = false, rows, users }: MountOptions = {}) { +async function mount({ perms = PERMS, objectName = OBJECT_NAME, pages = [], embedded = false, rows, users }: MountOptions = {}) { const dataSource = makeDataSource(rows, users); const rendered = render( - + { + const path = String(url); + const resolution = path.match(/\/api\/v1\/comments\/([^/]+)\/resolution$/); + if (resolution && init?.method === 'PUT') { + const resolved = JSON.parse(String(init.body)).resolved === true; + const data = { + id: decodeURIComponent(resolution[1]), + is_resolved: resolved, + resolved_by: resolved ? 'u-ada' : null, + resolved_at: resolved ? '2026-10-02T00:00:00.000Z' : null, + }; + return new Response(JSON.stringify({ success: true, data }), { status: 200, headers: { 'content-type': 'application/json' } }); + } + const removal = path.match(/\/api\/v1\/comments\/([^/]+)$/); + if (removal && init?.method === 'DELETE') { + return new Response(JSON.stringify({ success: true, data: { id: decodeURIComponent(removal[1]), deleted: true } }), { status: 200 }); + } + return new Response(JSON.stringify({ data: [] }), { status: 200, headers: { 'content-type': 'application/json' } }); + }); +} +const doorCalls = (method: string) => + (doorFetch.mock.calls as Array<[unknown, { method?: string; body?: unknown }?]>) + .filter(([url, init]) => init?.method === method && String(url).includes('/api/v1/comments/')) + .map(([url, init]) => ({ url: String(url), body: init?.body === undefined ? undefined : JSON.parse(String(init.body)) })); + beforeEach(() => { + answerDoors(); window.localStorage.clear(); setWindowWidth(1440); // The explain verdicts live in a module-level cache: each case asks afresh. @@ -307,14 +342,15 @@ describe('resolved threads in the record comment panel (objectstack#36075)', () expect(dataSource.find.mock.calls.some(([o]: [string]) => o === 'sys_user')).toBe(false); }); - it('✓ writes is_resolved alone on the top-level comment; the thread leaves and the count drops', async () => { + it('✓ resolves through the resolution door with { resolved: true } alone; the thread leaves and the count drops', async () => { const { container, dataSource } = await openPanel(); await waitFor(() => expect(count(container)).toBe('1')); const ada = commentIn(container, ADA_BODY)!; await act(async () => { fireEvent.click(ada.querySelector('[data-comment-action="resolve"]')!); }); - expect(dataSource.update).toHaveBeenCalledWith('sys_comment', 'c-ada', { is_resolved: true }); + expect(doorCalls('PUT')).toEqual([{ url: expect.stringMatching(/\/api\/v1\/comments\/c-ada\/resolution$/), body: { resolved: true } }]); + expect(dataSource.update).not.toHaveBeenCalled(); await waitFor(() => expect(within(panel(container)!).queryByText(ADA_BODY)).toBeNull()); // No unresolved thread: the icon draws no number. expect(count(container)).toBeNull(); @@ -323,8 +359,8 @@ describe('resolved threads in the record comment panel (objectstack#36075)', () }); it('a refused ✓ says so and leaves the thread where it was', async () => { - const { container, dataSource } = await openPanel(); - dataSource.update.mockRejectedValueOnce(new Error('403')); + const { container } = await openPanel(); + doorFetch.mockResolvedValueOnce(new Response(JSON.stringify({ success: false }), { status: 403 })); const ada = commentIn(container, ADA_BODY)!; await act(async () => { fireEvent.click(ada.querySelector('[data-comment-action="resolve"]')!); @@ -334,9 +370,8 @@ describe('resolved threads in the record comment panel (objectstack#36075)', () expect(count(container)).toBe('1'); }); - it('the reopen ✓ writes is_resolved false and the thread counts again', async () => { - stubExplain(null, true); - const { container, dataSource } = await openPanel(); + it('the reopen ✓ sends { resolved: false } and the thread counts again, with no explain answer at all', async () => { + const { container } = await openPanel(); await showResolved(); const grace = await waitFor(() => { const el = commentIn(container, GRACE_BODY)!; @@ -346,7 +381,7 @@ describe('resolved threads in the record comment panel (objectstack#36075)', () await act(async () => { fireEvent.click(grace.querySelector('[data-comment-action="reopen"]')!); }); - expect(dataSource.update).toHaveBeenCalledWith('sys_comment', 'c-grace', { is_resolved: false }); + expect(doorCalls('PUT')).toEqual([{ url: expect.stringMatching(/\/api\/v1\/comments\/c-grace\/resolution$/), body: { resolved: false } }]); await waitFor(() => expect(count(container)).toBe('2')); }); @@ -364,6 +399,21 @@ describe('resolved threads in the record comment panel (objectstack#36075)', () await waitFor(() => expect(thread).not.toHaveAttribute('data-comment-thread-resolved')); expect(count(container)).toBe('2'); }); + + it('a viewer who reads comments but may not post one is offered no ✓: the door takes the posting gate (objectstack#36186)', async () => { + const readOnly = { + ...PERMS, + objects: { ...PERMS.objects, sys_comment: { ...FULL, allowCreate: false } }, + } as MePermissionsAuthenticatedResponse; + const mounted = await mount({ perms: readOnly }); + await waitFor(() => expect(button(mounted.container)).not.toBeNull()); + fireEvent.click(button(mounted.container)!); + await within(panel(mounted.container)!).findByText(ADA_BODY); + engage(mounted.container); + expect(commentIn(mounted.container, ADA_BODY)!.querySelector('[data-comment-action="resolve"]')).toBeNull(); + expect(panel(mounted.container)!.querySelector('[data-comment-action="resolve"]')).toBeNull(); + expect(doorCalls('PUT')).toEqual([]); + }); }); describe("Edit and Delete on another member's comment (objectstack#36075 item 6)", () => { @@ -428,12 +478,12 @@ describe("the row floor on another member's comment (objectstack#36075)", () => ); }); - it('refused: no ✓ and no Edit on another member\'s rows, Delete still where the viewer moderates, own rows unchanged', async () => { + it('refused: no Edit on another member\'s rows, Delete still where the viewer moderates, ✓ still (the resolution door), own rows unchanged', async () => { stubExplain(true, false); const { container } = await openPanel(); await showResolved(); await waitFor(() => expect(moreOn(container, GRACE_BODY)).not.toBeNull()); - expect(reopenOn(container, GRACE_BODY)).toBeNull(); + expect(reopenOn(container, GRACE_BODY)).not.toBeNull(); fireEvent.pointerDown(moreOn(container, GRACE_BODY)!, { button: 0, ctrlKey: false, pointerType: 'mouse' }); expect(await within(document.body).findByRole('menuitem', { name: 'Delete' })).toBeInTheDocument(); expect(within(document.body).queryByRole('menuitem', { name: 'Edit' })).toBeNull(); @@ -449,13 +499,11 @@ describe("the row floor on another member's comment (objectstack#36075)", () => expect(await within(document.body).findByRole('menuitem', { name: 'Edit' })).toBeInTheDocument(); }); - it('not on a guess: no answer offers ✓ on the viewer\'s own threads alone', async () => { + it('✓ asks no explain: with no answer it is on the viewer\'s threads and on another member\'s', async () => { stubExplain(null); const { container } = await openPanel(); await showResolved(); - await waitFor(() => expect(commentIn(container, GRACE_BODY)).toBeDefined()); - await act(async () => {}); - expect(reopenOn(container, GRACE_BODY)).toBeNull(); + await waitFor(() => expect(reopenOn(container, GRACE_BODY)).not.toBeNull()); expect(commentIn(container, ADA_BODY)!.querySelector('[data-comment-action="resolve"]')).not.toBeNull(); }); @@ -469,3 +517,63 @@ describe("the row floor on another member's comment (objectstack#36075)", () => expect(moreOn(container, ADA_BODY)).not.toBeNull(); }); }); + +describe('a member without the sys_comment delete grant deletes through the own-comment delete door (objectstack#36191)', () => { + const MEMBER_PERMS = { + ...PERMS, + objects: { ...PERMS.objects, sys_comment: { ...FULL, allowDelete: false } }, + } as MePermissionsAuthenticatedResponse; + const moreOn = (root: HTMLElement, text: string) => commentIn(root, text)?.querySelector(':scope > [data-comment-actions] [data-comment-action="more"]') ?? null; + + async function openAsMember(rows?: ReadonlyArray>) { + stubExplain(true, false); + const mounted = await mount({ perms: MEMBER_PERMS, rows }); + await waitFor(() => expect(button(mounted.container)).not.toBeNull()); + fireEvent.click(button(mounted.container)!); + await within(panel(mounted.container)!).findByText(ADA_BODY); + engage(mounted.container); + return mounted; + } + + it('Delete on the viewer\'s own comment goes through the door, never the data door, and the row leaves', async () => { + const { container, dataSource } = await openAsMember(); + fireEvent.pointerDown(moreOn(container, ADA_BODY)!, { button: 0, ctrlKey: false, pointerType: 'mouse' }); + fireEvent.click(await within(document.body).findByRole('menuitem', { name: 'Delete' })); + const dialog = await within(document.body).findByRole('alertdialog'); + await act(async () => { + fireEvent.click(within(dialog).getByRole('button', { name: 'Delete' })); + }); + expect(doorCalls('DELETE')).toEqual([{ url: expect.stringMatching(/\/api\/v1\/comments\/c-ada$/), body: undefined }]); + expect(dataSource.delete).not.toHaveBeenCalled(); + await waitFor(() => expect(within(panel(container)!).queryByText(ADA_BODY)).toBeNull()); + expect(toast.success).toHaveBeenCalledWith('Comment deleted'); + }); + + it('no Delete on another member\'s comment even where the viewer may edit the record, and none on their own once someone replied', async () => { + const withReply = [ + ...ROWS, + { ...ROWS[2], id: 'c-linus-on-ada', parent_id: 'c-ada', body: 'Linus: on it' }, + ]; + const { container } = await openAsMember(withReply); + await showResolved(); + await waitFor(() => expect(commentIn(container, GRACE_BODY)).toBeDefined()); + await act(async () => {}); + expect(moreOn(container, GRACE_BODY)).toBeNull(); + fireEvent.pointerDown(moreOn(container, ADA_BODY)!, { button: 0, ctrlKey: false, pointerType: 'mouse' }); + expect(await within(document.body).findByRole('menuitem', { name: 'Edit' })).toBeInTheDocument(); + expect(within(document.body).queryByRole('menuitem', { name: 'Delete' })).toBeNull(); + }); + + it('a refused door delete says so and keeps the row', async () => { + const { container } = await openAsMember(); + doorFetch.mockResolvedValueOnce(new Response(JSON.stringify({ success: false }), { status: 409 })); + fireEvent.pointerDown(moreOn(container, ADA_BODY)!, { button: 0, ctrlKey: false, pointerType: 'mouse' }); + fireEvent.click(await within(document.body).findByRole('menuitem', { name: 'Delete' })); + const dialog = await within(document.body).findByRole('alertdialog'); + await act(async () => { + fireEvent.click(within(dialog).getByRole('button', { name: 'Delete' })); + }); + expect(toast.error).toHaveBeenCalledWith('The comment was not deleted. Please try again.'); + expect(within(panel(container)!).getByText(ADA_BODY)).toBeInTheDocument(); + }); +}); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.feedCommentEditDelete-12268.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.feedCommentEditDelete-12268.test.tsx index dc2f750f2bc..9c5770efb25 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.feedCommentEditDelete-12268.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.feedCommentEditDelete-12268.test.tsx @@ -53,10 +53,14 @@ import { builtInLocales } from '@object-ui/i18n/locales'; const auth = vi.hoisted(() => ({ user: { id: 'u-ada', name: 'Ada', image: null as string | null } })); const authorship = vi.hoisted(() => ({ calls: [] as Array<[unknown, unknown]> })); +/** The page's authenticated fetch: the own-comment delete door answers through it (objectstack#36191). */ +const doorFetch = vi.hoisted(() => + vi.fn(async () => new Response(JSON.stringify({ success: true, data: { deleted: true } }), { status: 200 })), +); vi.mock('@object-ui/auth', async (importOriginal) => ({ ...(await importOriginal>()), useAuth: () => ({ user: auth.user, activeOrganization: null }), - createAuthenticatedFetch: () => vi.fn(), + createAuthenticatedFetch: () => doorFetch, })); vi.mock('@object-ui/collaboration', async (importOriginal) => { @@ -510,8 +514,24 @@ describe('each control is handed over under its own grant on sys_comment (object expect(deleteIn(rowOf(view, ADA_BODY))).not.toBeNull(); }); - it('without the delete grant there is no Delete, and Edit stays', async () => { - const { view } = await mount('record:activity', answer({ ...FULL, allowDelete: false })); + it('without the delete grant, Delete goes through the own-comment delete door, never the data door, and Edit stays (objectstack#36191)', async () => { + const dataSource = makeDataSource(); + const { view } = await mount('record:activity', answer({ ...FULL, allowDelete: false }), { dataSource }); + expect(editIn(rowOf(view, ADA_BODY))).not.toBeNull(); + fireEvent.click(deleteIn(rowOf(view, ADA_BODY))!); + const dialog = await screen.findByRole('alertdialog'); + await act(async () => { + fireEvent.click(within(dialog).getByRole('button', { name: EN.objectActions.deleteConfirmButton })); + }); + expect(dataSource.delete).not.toHaveBeenCalled(); + expect( + (doorFetch.mock.calls as unknown as Array<[unknown, { method?: string }?]>).filter(([, init]) => init?.method === 'DELETE').map(([url]) => String(url)), + ).toEqual([expect.stringMatching(/\/api\/v1\/comments\/c-ada$/)]); + }); + + it('without the delete grant, no Delete on the author\'s comment once another member replied to it; Edit stays', async () => { + const dataSource = makeDataSource([ADA_ROW, GRACE_ROW, GRACE_REPLY_ROW]); + const { view } = await mount('record:activity', answer({ ...FULL, allowDelete: false }), { dataSource }); expect(editIn(rowOf(view, ADA_BODY))).not.toBeNull(); expect(deleteIn(rowOf(view, ADA_BODY))).toBeNull(); }); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index 25e1e787cc7..b2dd3df956b 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -715,6 +715,19 @@ const COMMENT_REACTION_OBJECT = 'sys_comment_reaction'; */ const COMMENT_REACTION_REMOVE_PATH = '/api/v1/comments/reactions'; +/** + * The comment doors (objectstack#36186, #36191), each `+ /:id` of a + * `sys_comment` row: `PUT …/resolution` with `{ resolved }` resolves or reopens + * the thread of a top-level comment for anyone who can read it, writing + * `is_resolved` alone; `DELETE` removes the caller's own comment, refuses + * anyone else's (`403 PERMISSION_DENIED`) and keeps one others replied under + * (`409 DELETE_RESTRICTED`). They exist because the data door cannot serve a + * rank-and-file member either write: the platform's row floor admits their + * update of their own rows alone, and no every-member set may carry the + * `delete` grant (ADR-0090 D5). + */ +const COMMENT_DOOR_PATH = '/api/v1/comments'; + /** The object the record feed's comments and replies are rows of. */ const COMMENT_OBJECT = 'sys_comment'; @@ -765,6 +778,7 @@ function resolveFeedWriteGates( comment: boolean; commentEdit: boolean; commentDelete: boolean; + commentDeleteOwn: boolean; reactionAdd: boolean; reactionRemove: boolean; reactionColumn: boolean; @@ -781,6 +795,9 @@ function resolveFeedWriteGates( // under its own grant on `sys_comment`. commentEdit: resolveAffordance('feedCommentEdit', source(COMMENT_OBJECT)).allowed, commentDelete: resolveAffordance('feedCommentDelete', source(COMMENT_OBJECT)).allowed, + // objectstack#36191: without the delete grant, the author's Delete is the + // own-comment delete door, asked under the grant the comment was posted under. + commentDeleteOwn: resolveAffordance('feedCommentDeleteOwn', source(COMMENT_OBJECT)).allowed, reactionAdd: resolveAffordance('feedReactionAdd', source(COMMENT_REACTION_OBJECT)).allowed, reactionRemove: resolveAffordance('feedReactionRemove', source(COMMENT_REACTION_OBJECT)).allowed, reactionColumn: resolveAffordance('feedReactionColumn', source(COMMENT_OBJECT)).allowed, @@ -4183,7 +4200,13 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri /** * The author's Delete on their own comment or reply (objectui#12268), offered - * on the same rows under the delete grant (`feedGates.commentDelete`). + * on the same rows under the delete grant (`feedGates.commentDelete`), and, + * for a viewer without it, under the comment grant through the own-comment + * delete door (`feedGates.commentDeleteOwn`, objectstack#36191): that door + * removes the viewer's own comment alone and keeps one others replied under, + * so the panel offers it on exactly those rows (`ownCommentDeletesOnly`). + * With the grant, the data door's delete is used as before, a moderator's + * delete of another member's comment included. * * It asks first, through the console's ordinary destructive-action confirm: * this page's own `confirmHandler`, the `ActionConfirmDialog` the record's @@ -4211,8 +4234,16 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri ); if (!confirmed) return; try { - if ((await dataSource.delete(COMMENT_OBJECT, String(itemId))) === false) { - throw new Error('The comment was not deleted.'); + if (feedGates.commentDelete) { + if ((await dataSource.delete(COMMENT_OBJECT, String(itemId))) === false) { + throw new Error('The comment was not deleted.'); + } + } else { + const res = await authFetch( + `${import.meta.env.VITE_SERVER_URL || ''}${COMMENT_DOOR_PATH}/${encodeURIComponent(String(itemId))}`, + { method: 'DELETE', credentials: 'include' }, + ); + if (!res.ok) throw new Error(`The comment was not deleted (HTTP ${res.status}).`); } } catch (err) { toast.error( @@ -4237,17 +4268,22 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // and the comment did not just scroll away (objectstack#36070). toast.success(t('detail.commentDeleted', { defaultValue: 'Comment deleted' })); }, - [dataSource, feedRecordKey, feedItemsByRecord, confirmHandler, t], + [dataSource, feedRecordKey, feedItemsByRecord, confirmHandler, t, feedGates.commentDelete, authFetch], ); /** * Resolve or reopen a thread (objectstack#36071, #36075 item 7), by its - * top-level comment: `{ is_resolved }` and nothing else, the one update - * whoever may comment on the record is admitted to (maintainer ruling - * record 7063285032). The platform stamps who and when; the row changes - * only once the server has stored it, from the stored record it answers - * with, and a refused write raises a localized error and leaves the thread - * as it was. + * top-level comment, through the platform's resolution door + * (`PUT /api/v1/comments/:id/resolution` with `{ resolved }`, + * objectstack#36186). The door admits whoever can read the thread and may + * post a comment on it (maintainer ruling record 7063285032: the same gate + * as posting) and writes `is_resolved` alone, so a + * rank-and-file member resolves a colleague's thread too: on the data door + * the platform's row floor refuses their update of a row they did not + * create. The platform stamps who and when; the row changes only once the + * server has stored it, from the stored resolution the door answers with, + * and a refused write raises a localized error and leaves the thread as it + * was. */ const handleResolveComment = useCallback( async (itemId: string | number, resolved: boolean) => { @@ -4257,7 +4293,18 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri if (!row || row.type !== 'comment' || row.parentId != null) return; let stored: Record | null | undefined; try { - stored = await dataSource.update(COMMENT_OBJECT, String(itemId), { is_resolved: resolved }); + const res = await authFetch( + `${import.meta.env.VITE_SERVER_URL || ''}${COMMENT_DOOR_PATH}/${encodeURIComponent(String(itemId))}/resolution`, + { + method: 'PUT', + credentials: 'include', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ resolved }), + }, + ); + if (!res.ok) throw new Error(`The thread was not updated (HTTP ${res.status}).`); + const envelope = (await res.json().catch(() => null)) as { data?: unknown } | null; + stored = envelope && typeof envelope.data === 'object' ? (envelope.data as Record | null) : null; } catch (err) { toast.error( t('detail.commentResolveFailed', { defaultValue: 'The thread was not updated. Please try again.' }), @@ -4289,7 +4336,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri ), })); }, - [currentUser, dataSource, feedRecordKey, feedItemsByRecord, t], + [currentUser, dataSource, feedRecordKey, feedItemsByRecord, t, authFetch], ); // objectstack#36075 item 6 — may the viewer edit and delete OTHER people's @@ -4314,12 +4361,12 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // objectstack#36075 — may the viewer update a comment they did NOT write? // The platform's row floor (`owner_only_writes`) lets a rank-and-file member // update only the rows they created, and it runs before the comment rules - // (the resolve rule of #36104 and the parent-editor rule above), so today a - // member's ✓ on a colleague's thread and Edit of a colleague's comment are - // refused. The explain engine answers the floor: ONE probe, `update` of the - // first top-level comment here the viewer did not write; the floor answers - // the same for every such row. ✓ and Edit on others' rows are offered only - // on its definite allow (pending, a refusal, an error, no explain service, + // (the parent-editor rule above), so a member's Edit of a colleague's + // comment is refused; ✓ goes through the resolution door instead + // (objectstack#36186) and does not ask this. The explain engine answers the + // floor: ONE probe, `update` of the first top-level comment here the viewer + // did not write; the floor answers the same for every such row. Edit on + // others' rows is offered only on its definite allow (pending, a refusal, an error, no explain service, // or a stale answer offer them on the viewer's own rows alone). Asked when // the reader first reaches into the open panel (pointer or focus), so // opening the record, and opening the panel, still read nothing more @@ -6061,15 +6108,18 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // grant; the panel offers them only on the rows the read marked // `authoredByViewer`. onEditComment={feedGates.commentEdit ? handleEditComment : undefined} - onDeleteComment={feedGates.commentDelete ? handleDeleteComment : undefined} - // objectstack#36071 / #36075 — resolve and reopen are an update of - // the top-level `sys_comment` row, under the same grant as Edit. The - // server's rule is any reader of the record (ruling 7063285032), but - // its row floor admits a member's update of their own rows alone, so - // the panel offers ✓ on a thread the viewer started, and on others' - // only where `updatesOthersComments` holds; and only where the rows - // say the deployment stores resolution. - onResolveComment={feedsEnabled && feedGates.commentEdit ? handleResolveComment : undefined} + // objectstack#36191: under the delete grant, the data door's delete; + // without it, the own-comment delete door, which removes the + // viewer's own comment alone and keeps one others replied under. + onDeleteComment={feedGates.commentDelete || feedGates.commentDeleteOwn ? handleDeleteComment : undefined} + ownCommentDeletesOnly={!feedGates.commentDelete} + // objectstack#36071 / #36075 / #36186 — resolve and reopen go + // through the resolution door, which admits whoever can read the + // thread and may post a comment on it (ruling 7063285032: the same + // gate as posting), so the panel offers ✓ on every thread, the + // viewer's and others', under the comment grant and wherever the + // rows say the deployment stores resolution. + onResolveComment={feedsEnabled && feedGates.comment ? handleResolveComment : undefined} moderatesComments={moderatesComments} updatesOthersComments={updatesOthersComments} onToggleReaction={ diff --git a/ui/packages/core/src/utils/affordanceGrants.ts b/ui/packages/core/src/utils/affordanceGrants.ts index e7d9a004273..9f3c1cc2f4a 100644 --- a/ui/packages/core/src/utils/affordanceGrants.ts +++ b/ui/packages/core/src/utils/affordanceGrants.ts @@ -236,6 +236,17 @@ export const AFFORDANCE_GRANTS = { feedCommentEdit: { crud: 'edit', grant: 'update' }, /** The same rows' Delete, asked of `sys_comment`: it deletes that comment row. */ feedCommentDelete: { crud: 'delete', grant: 'delete' }, + /** + * The same Delete for a caller who holds no `delete` grant on `sys_comment`, + * asked of `sys_comment`: it removes the caller's own comment through the + * own-comment delete door (`DELETE /api/v1/comments/:id`), not the data + * door, so no CRUD bit is read. That door admits exactly the caller's own + * comment, and only one nobody replied under, and needs no `delete` grant, + * which no every-member set may carry (ADR-0090 D5), so it asks the grant + * the comment was posted under: whoever may comment may take their own + * comment back, as `feedReactionRemove` asks for a reaction. + */ + feedCommentDeleteOwn: { crud: null, grant: 'create' }, /** A calendar's quick-create: an empty-day click, or a time-range drag in the week / day grid. */ calendarQuickCreate: { crud: 'create', grant: 'create' }, /** A calendar's drag-to-reschedule: moving or resizing an event writes its date fields. */ diff --git a/ui/packages/plugin-detail/src/CommentAuthorControls.tsx b/ui/packages/plugin-detail/src/CommentAuthorControls.tsx index 42735937601..2606d1c0301 100644 --- a/ui/packages/plugin-detail/src/CommentAuthorControls.tsx +++ b/ui/packages/plugin-detail/src/CommentAuthorControls.tsx @@ -10,6 +10,7 @@ import * as React from 'react'; import { Button, Textarea } from '@object-ui/components'; import { Pencil, Trash2 } from 'lucide-react'; import type { FeedItem } from '@object-ui/types'; +import { useDiscussionContext } from '@object-ui/react'; import { useDetailTranslation } from './useDetailTranslation'; /** @@ -68,7 +69,11 @@ export const CommentBody: React.FC = ({ const { t } = useDetailTranslation(); const own = offersAuthorControls(item); const edit = own ? onEditComment : undefined; - const remove = own ? onDeleteComment : undefined; + // Where the host's Delete is the own-comment delete door + // (`ownCommentDeletesOnly`, objectstack#36191), a comment that has replies + // is kept by the door, so it offers no Delete. + const keptForReplies = useDiscussionContext()?.ownCommentDeletesOnly === true && (item.replyCount ?? 0) > 0; + const remove = own && !keptForReplies ? onDeleteComment : undefined; // `null` while the text is shown; the draft while the editor is open. const [draft, setDraft] = React.useState(null); const [saving, setSaving] = React.useState(false); diff --git a/ui/packages/plugin-detail/src/comments/CommentThread.tsx b/ui/packages/plugin-detail/src/comments/CommentThread.tsx index 0c4ee743024..04eeb9509d6 100644 --- a/ui/packages/plugin-detail/src/comments/CommentThread.tsx +++ b/ui/packages/plugin-detail/src/comments/CommentThread.tsx @@ -52,6 +52,7 @@ export interface RecordCommentThreadProps { | 'onResolveComment' | 'moderates' | 'updatesOthers' + | 'ownDeletesOnly' | 'mentionSuggestions' | 'onMentionSuggestionsWanted' >; @@ -83,8 +84,19 @@ function editableComment(item: FeedItem, moderates: boolean | undefined, updates return ownComment(item) || (item.type === 'comment' && moderates === true && updatesOthers === true); } -/** Whether the viewer may delete this comment: their own, or anyone's where they moderate. */ -function deletableComment(item: FeedItem, moderates: boolean | undefined): boolean { +/** + * Whether the viewer may delete this comment: their own, or anyone's where + * they moderate. Where the host's Delete is the own-comment delete door + * (`ownDeletesOnly`, objectstack#36191), only their own, and only one with no + * reply under it: the door keeps a comment that has replies. + */ +function deletableComment( + item: FeedItem, + moderates: boolean | undefined, + ownDeletesOnly: boolean | undefined, + hasReplies: boolean, +): boolean { + if (ownDeletesOnly === true) return ownComment(item) && !hasReplies; return ownComment(item) || (item.type === 'comment' && moderates === true); } @@ -123,8 +135,16 @@ export const CommentThread: React.FC = ({ // on an open thread still lands it there. const [replyFocus, setReplyFocus] = React.useState(0); const [editingId, setEditingId] = React.useState(null); - const { onAddReply, onToggleReaction, onEditComment, onDeleteComment, onResolveComment, moderates, updatesOthers } = - comments; + const { + onAddReply, + onToggleReaction, + onEditComment, + onDeleteComment, + onResolveComment, + moderates, + updatesOthers, + ownDeletesOnly, + } = comments; const resolvable = threadResolvable(thread); const resolved = threadResolved(thread); // The host names the resolver (a by-id read of the ids it could not name); @@ -145,10 +165,11 @@ export const CommentThread: React.FC = ({ isRoot, onReply: onAddReply ? openReply : undefined, onReact: onToggleReaction ? (emoji: string) => void onToggleReaction(item.id, emoji) : undefined, - // ✓ writes the top-level row: on a thread the viewer started, or anyone's - // where the server admits their update of a row they did not write. + // ✓ resolves the thread by its top-level row, anyone's: the host hands + // the handler over only where its write admits every thread the viewer + // can read (the resolution door, objectstack#36186). onResolve: - isRoot && resolvable && onResolveComment && (ownComment(item) || updatesOthers === true) + isRoot && resolvable && onResolveComment ? () => { // A refused write changed nothing, and the host has said so. void Promise.resolve(onResolveComment(item.id, !resolved)).catch(() => undefined); @@ -156,7 +177,19 @@ export const CommentThread: React.FC = ({ : undefined, resolved: isRoot && resolved, onEdit: onEditComment && editableComment(item, moderates, updatesOthers) ? () => setEditingId(item.id) : undefined, - onDelete: onDeleteComment && deletableComment(item, moderates) ? () => void onDeleteComment(item.id) : undefined, + onDelete: + onDeleteComment && + deletableComment( + item, + moderates, + ownDeletesOnly, + (item.replyCount ?? 0) > 0 || replies.some((reply) => reply.parentId != null && String(reply.parentId) === String(item.id)), + ) + ? () => { + // A refused delete kept the row, and the host has said so. + void Promise.resolve(onDeleteComment(item.id)).catch(() => undefined); + } + : undefined, }); const itemOf = (item: FeedItem, isRoot: boolean, footer?: React.ReactNode, itemClassName?: string) => ( diff --git a/ui/packages/plugin-detail/src/comments/CommentsPanel.resolved-36075.test.tsx b/ui/packages/plugin-detail/src/comments/CommentsPanel.resolved-36075.test.tsx index 54a8477ee05..0a354ccf153 100644 --- a/ui/packages/plugin-detail/src/comments/CommentsPanel.resolved-36075.test.tsx +++ b/ui/packages/plugin-detail/src/comments/CommentsPanel.resolved-36075.test.tsx @@ -18,8 +18,13 @@ * replied in or is mentioned in. * - Edit and Delete on OTHER people's comments only where the host says the * viewer may moderate this record's comments. - * - ✓ and Edit on a row the viewer did not write only where the host says the - * server admits their update of such a row (the platform's row floor). + * - Edit on a row the viewer did not write only where the host says the + * server admits their update of such a row (the platform's row floor); ✓ + * on every thread wherever the host hands the resolve write, which goes + * through the resolution door any reader may use (objectstack#36186). + * - Where the host's Delete is the own-comment delete door + * (`ownCommentDeletesOnly`, objectstack#36191), Delete only on the viewer's + * own comments that nobody replied under. */ import * as React from 'react'; @@ -95,7 +100,6 @@ describe('CommentsPanel — resolved threads (objectstack#36075)', () => { it('✓ on a top-level comment resolves its thread; a reply has none', () => { const { onResolveComment } = renderPanel({ updatesOthersComments: true }); fireEvent.click(screen.getByRole('button', { name: /1 reply/ })); - expect(actionIn('r3', 'resolve')).toBeNull(); fireEvent.click(actionIn('t5', 'resolve')!); expect(onResolveComment).toHaveBeenCalledWith('t5', true); }); @@ -165,15 +169,15 @@ describe('CommentsPanel — resolved threads (objectstack#36075)', () => { expect(shownRoots()).toEqual(['t1', 't2', 't3', 't4', 't5']); }); - it('without the host’s word that others’ rows take the viewer’s update, ✓ only on the viewer’s own threads', async () => { - const { onResolveComment } = renderPanel(); + it('✓ is on every thread, the viewer’s and others’, without the host’s word that others’ rows take the viewer’s update (objectstack#36186)', async () => { + const { onResolveComment } = renderPanel({ updatesOthersComments: false }); expect(actionIn('t1', 'resolve')).not.toBeNull(); - expect(actionIn('t3', 'resolve')).toBeNull(); - expect(actionIn('t5', 'resolve')).toBeNull(); + expect(actionIn('t3', 'resolve')).not.toBeNull(); + expect(actionIn('t5', 'resolve')).not.toBeNull(); await toggleFilter('Show resolved'); - expect(actionIn('t2', 'reopen')).toBeNull(); - fireEvent.click(actionIn('t1', 'resolve')!); - expect(onResolveComment).toHaveBeenCalledWith('t1', true); + expect(actionIn('t2', 'reopen')).not.toBeNull(); + fireEvent.click(actionIn('t5', 'resolve')!); + expect(onResolveComment).toHaveBeenCalledWith('t5', true); }); it('offers no ✓ where the host hands no resolve write', () => { @@ -221,6 +225,44 @@ describe('CommentsPanel — Edit and Delete for people with permission (objectst }); }); +describe('CommentsPanel — Delete through the own-comment delete door (objectstack#36191)', () => { + // t6: the viewer's, with Linus's reply r6 under it. + const WITH_REPLIED_OWN: FeedItem[] = [ + ...ITEMS, + { id: 't6', type: 'comment', actor: 'Me', body: 'mine, answered', createdAt: at(7), authoredByViewer: true, resolved: false, replyCount: 1 }, + { id: 'r6', type: 'comment', actor: 'Linus', body: 'an answer', createdAt: at(8), parentId: 't6' }, + ]; + const menuItems = async (id: string) => { + fireEvent.pointerDown(actionIn(id, 'more')!, { button: 0, ctrlKey: false, pointerType: 'mouse' }); + await screen.findByRole('menuitem', { name: 'Edit' }); + return screen.queryAllByRole('menuitem').map((el) => el.textContent); + }; + + it('Delete on the viewer’s own comment with no reply under it, and it hands that comment over', async () => { + const { onDeleteComment } = renderPanel({ items: WITH_REPLIED_OWN as any[], ownCommentDeletesOnly: true }); + expect(await menuItems('t1')).toContain('Delete'); + fireEvent.click(screen.getByRole('menuitem', { name: 'Delete' })); + expect(onDeleteComment).toHaveBeenCalledWith('t1'); + }); + + it('no Delete on the viewer’s own comment that has replies; Edit stays', async () => { + renderPanel({ items: WITH_REPLIED_OWN as any[], ownCommentDeletesOnly: true }); + const items = await menuItems('t6'); + expect(items).toContain('Edit'); + expect(items).not.toContain('Delete'); + }); + + it('nothing on others’ comments, whatever the moderation verdict says', () => { + renderPanel({ items: WITH_REPLIED_OWN as any[], ownCommentDeletesOnly: true, moderatesComments: true, updatesOthersComments: false }); + expect(actionIn('t5', 'more')).toBeNull(); + }); + + it('CONTROL: without it (the delete grant), the viewer’s own replied-under comment keeps Delete', async () => { + renderPanel({ items: WITH_REPLIED_OWN as any[] }); + expect(await menuItems('t6')).toContain('Delete'); + }); +}); + describe('useRecordComments — the icon’s count (objectstack#36075 item 8)', () => { const Probe: React.FC = () => {String(useRecordComments().count)}; it('counts the unresolved threads', () => { diff --git a/ui/packages/plugin-detail/src/comments/useRecordComments.ts b/ui/packages/plugin-detail/src/comments/useRecordComments.ts index 311fb10ed00..9e5b9fa3782 100644 --- a/ui/packages/plugin-detail/src/comments/useRecordComments.ts +++ b/ui/packages/plugin-detail/src/comments/useRecordComments.ts @@ -52,10 +52,15 @@ export interface RecordCommentsData { moderates?: boolean; /** * The server admits the viewer's update of a comment they did not write - * (the host's definite verdict; objectstack#36075). ✓ on another person's - * thread and Edit on another person's comment need it. + * (the host's definite verdict; objectstack#36075). Edit on another + * person's comment needs it. */ updatesOthers?: boolean; + /** + * The viewer's Delete removes only their own comments that nobody replied + * under (the own-comment delete door; objectstack#36191). + */ + ownDeletesOnly?: boolean; mentionSuggestions?: DiscussionMentionSuggestion[]; onMentionSuggestionsWanted?: () => void; } @@ -94,6 +99,7 @@ export function useRecordComments(): RecordCommentsData { onResolveComment: discussion?.onResolveComment, moderates: discussion?.moderatesComments === true, updatesOthers: discussion?.updatesOthersComments === true, + ownDeletesOnly: discussion?.ownCommentDeletesOnly === true, mentionSuggestions: discussion?.mentionSuggestions, onMentionSuggestionsWanted: discussion?.onMentionSuggestionsWanted, }; diff --git a/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx b/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx index 9bbd1771b9d..692427a5436 100644 --- a/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx +++ b/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx @@ -132,6 +132,10 @@ const EXPECTED_GRANT: Record = { // asked of `sys_comment`. feedCommentEdit: 'update', feedCommentDelete: 'delete', + // objectstack#36191: the same Delete through the own-comment delete door, + // which needs no delete grant, so it asks the grant the comment was posted + // under (as `feedReactionRemove` does for a reaction). + feedCommentDeleteOwn: 'create', // objectui#12982: Setup's Clone of a declared sharing rule, asked of // `sys_sharing_rule`: it creates an organization rule. declarationClone: 'create', @@ -709,10 +713,6 @@ const WRITE_SITES: Record = { mapped(['feedComment'], RECORD_PAGE), 'packages/app-shell/src/views/RecordDetailView.tsx :: RecordDetailView > handleEditComment :: update': mapped(['feedCommentEdit'], RECORD_PAGE), - // Resolve / reopen a thread (objectstack#36075) is a by-id update of the - // root `sys_comment` row, offered behind the same row as Edit. - 'packages/app-shell/src/views/RecordDetailView.tsx :: RecordDetailView > handleResolveComment :: update': - mapped(['feedCommentEdit'], RECORD_PAGE), 'packages/app-shell/src/views/RecordDetailView.tsx :: RecordDetailView > handleDeleteComment :: delete': mapped(['feedCommentDelete'], RECORD_PAGE), 'packages/app-shell/src/views/RecordDetailView.tsx :: RecordDetailView > handleToggleReaction :: update': diff --git a/ui/packages/react/src/context/DiscussionContext.tsx b/ui/packages/react/src/context/DiscussionContext.tsx index 2d9cbfeb521..9836c94eebf 100644 --- a/ui/packages/react/src/context/DiscussionContext.tsx +++ b/ui/packages/react/src/context/DiscussionContext.tsx @@ -62,10 +62,11 @@ export interface DiscussionContextValue { onDeleteComment?: (itemId: string | number) => void | Promise; /** * Resolve (`true`) or reopen (`false`) the thread of a top-level comment - * (objectstack#36071, #36075). Offered under the viewer's `update` grant on - * `sys_comment`; the comment panel draws it on the rows whose `resolved` the - * host set, on a thread the viewer started, and on anyone's only where - * {@link updatesOthersComments} holds. A rejection means nothing changed. + * (objectstack#36071, #36075, #36186). The comment panel draws it on every + * top-level row whose `resolved` the host set, the viewer's own and anyone + * else's: the host hands it over only where its write admits every thread + * the viewer can read (the platform's resolution door, + * `PUT /api/v1/comments/:id/resolution`). A rejection means nothing changed. */ onResolveComment?: (itemId: string | number, resolved: boolean) => void | Promise; /** @@ -81,11 +82,21 @@ export interface DiscussionContextValue { * The server admits the viewer's update of a comment they did NOT write * (objectstack#36075): the platform's row floor lets most members update * only the rows they created, before any comment rule is asked. `true` only - * on a definite allow; absent or `false`, the panel offers ✓ and Edit on the + * on a definite allow; absent or `false`, the panel offers Edit on the * viewer's own rows alone. Edit on others' comments also needs - * {@link moderatesComments}; Delete does not read this. + * {@link moderatesComments}; ✓ and Delete do not read this. */ updatesOthersComments?: boolean; + /** + * The viewer's Delete removes only their own comments, and only one nobody + * replied under (objectstack#36191): the host's {@link onDeleteComment} + * goes through the platform's own-comment delete door + * (`DELETE /api/v1/comments/:id`), because the viewer holds no `delete` + * grant on `sys_comment`. `true`: Delete is offered on the viewer's own + * comments that have no reply, and on nobody else's, whatever + * {@link moderatesComments} says. Absent or `false`: as before. + */ + ownCommentDeletesOnly?: boolean; /** Optional list of users (or any mentionable entities) the comment * input can suggest after the user types `@`. When omitted the input * falls back to free-text @-mentions without autocompletion. */ @@ -153,6 +164,7 @@ export const DiscussionContextProvider: React.FC value.onResolveComment, value.moderatesComments, value.updatesOthersComments, + value.ownCommentDeletesOnly, value.mentionSuggestions, value.onMentionSuggestionsWanted, value.onUploadAttachments,