Skip to content

Commit d12ac84

Browse files
feat(comments): a member resolves any thread they can read and deletes their own comments, through two server doors (#36186, #36191) (#36200)
<!-- claude-projects-attribution: {"github_login":"os-sales"} --> _Requested by **Sales** · [project thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4UuQDMVvYbduXkDz6CEaA8Q1G)_ repo:objectstack#1 · os-sales · session_01L6bhgUH1jEKbDzYRc4nghq Fixes #36186 Fixes #36191 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 resolution stamp reads a system write's `provenance.attributedUserId`. `@objectstack/core`'s `OwnRowDeleteDoor` adds the optional `refuseRemoval(row, engine, context)` (step 7, after the owner check). `@object-ui/react`'s `DiscussionContextValue` adds the optional `ownCommentDeletesOnly`; `@object-ui/plugin-detail`'s `RecordCommentsData` adds the optional `ownDeletesOnly`, which `RecordCommentThreadProps['comments']` may carry; `@object-ui/core`'s affordance-to-grant map adds the row `feedCommentDeleteOwn`. Nothing existing is removed or re-typed. Metadata-protocol: none ## 维护者速读 - 普通成员现在能给**任何**自己看得到、也能在上面发评论的评论串点对勾(标成已解决),也能恢复。以前只能点自己发起的串,别人发起的只有管理员能点。点了以后「已由 某某 解决」写的是点的人。这就是你 13:25Z 的裁定 A(能看记录就能解决,门槛和发评论一样)真正生效。 - 普通成员现在能**删自己的评论**。以前成员的「更多」里只有编辑。删别人的评论还是不行,能编辑记录也不行;管理员照旧。 - **自己的评论下面已经有回复(不管是谁回的,自己回的也算),就不能删**(可以改文字)。原因:平台删一条顶层评论时会把下面的回复各自变成独立的串,等于改动了别人的评论,这不符合你 21:59Z 的裁定(别人的评论删不了)。座位核过,认为这是裁定本身的结论,不再单独问你。管理员有删除权限,删法和以前一样。 - 评论的文字照旧只有作者能改。平台的底线规则、删除权限一行没动:两个新的服务端入口各只做一件事(一个只改「已解决」,一个只删自己的那一行)。走原来的数据接口,成员改别人评论、改别人的「已解决」、删任何评论,仍然是 403。 - 只能看评论、不能发评论的人(比如只给了只读权限的外部成员),**点不了对勾**,控制台也不显示对勾。审核指出裁定 A 里同时写了「能看记录的人」和「和发评论同一道门槛」,座位定了按后者,较窄。普通成员都能发评论,所以对他们没有区别;能发评论的外部成员照样能点。 - 已知限制:删评论时「下面有没有回复」的检查和真正删除是两步。如果恰好在这一瞬间有人发了回复,这条回复会变成独立的串,和今天管理员用数据接口删评论时一样。平台的数据引擎没有「条件删除」可以把两步并成一步,套一层事务在默认隔离级别下也挡不住别的请求插进来的回复,所以先写明,不在这次改。 ## What changes **The resolution door** (`plugin-audit` `comment-routes.ts`, #36186) - `PUT /api/v1/comments/:id/resolution`, body exactly `{ "resolved": boolean }`. Order: caller (the own-row doors' one composition, `ownRowDeleteCallerResolver`), anonymous `401`, held sign-in `403`, any query parameter or other body `400 VALIDATION_ERROR`, the comment read AS THE CALLER (object grant + organization wall + the comment read gate; unreadable and unknown both `404 RECORD_NOT_FOUND`), the posting gate (the security service's `canWriteObject('sys_comment', 'insert', caller)`: a caller who reads comments but may not post one is `403 PERMISSION_DENIED`, a check that throws refuses, and a deployment with no security service has no posting gate either; ruling 7063285032 names "the same gate as posting a comment", contract review F1), a reply `400` (`refuseResolutionOnReply`, the data door's sentence), then a system write of `{ is_resolved }` alone by id, `attributedUserId` = caller, the caller's organization kept. Answers `200 { id, is_resolved, resolved_by, resolved_at }` read back as stored. - `stampCommentResolution` (`comment-resolution.ts`): on a system write the resolver is `provenance.attributedUserId` (the audit writer's own read of the attribution), so `resolved_by` names the door's caller. A non-system write still stamps its session user; a system write with no attribution still stamps `null`. - Untouched: `owner_only_writes`, `sys_comment_moderation`, `member_default`, the data door's resolve limb (#36104). No `sys_comment` update twin: a row policy cannot scope a column, so one would also admit a member's edit of a colleague's words, which ruling 7069889899 keeps author-only. **The own-comment delete door** (same file, #36191) - `DELETE /api/v1/comments/:id` on `@objectstack/core`'s shared own-row delete door; owner column `author_id`. Another member's comment `403 PERMISSION_DENIED`, even for a record editor (the moderator's delete stays the data door's, behind the delete grant). - Step 7, new in the kit: `OwnRowDeleteDoor.refuseRemoval`, asked after the owner check. The comment door's refuses a comment with any reply under it (a system read of `parent_id = id`), `409 DELETE_RESTRICTED`: `parent_id` is a lookup that clears on delete, so the removal would turn each reply into a thread of its own, a rewrite of other members' rows. The other three doors on the kit declare none and are unchanged. Known limit (contract review F2): the reply check and the removal are two engine calls and the data engine offers no conditional delete to join them (wrapping both in a transaction would not close it either: at the stores' default isolation another request's reply insert still lands between the probe and the delete), so a reply posted within that one request is promoted to a thread of its own, the same result as an administrator's data-door delete today; stated in the module doc. - Both doors mount beside the unreact door (`mountCommentDoors`, renamed from `mountUnreactDoor`); one `warn` names all three routes when no HTTP server is registered. Ledger rows in `comment-route-ledger.ts` (`gap`: the console is the consumer, the SDK has no method), with their conformance test; `scripts/check-route-envelope.mjs` declares the module. **Console** (`RecordDetailView`, `plugin-detail`, `react`, `core`) - ✓ calls the resolution door and is offered on every thread, the viewer's and anyone else's, under the `sys_comment` create grant (the door's posting gate), wherever the rows store resolution; it no longer depends on `updatesOthersComments`. The explain probe of a foreign `sys_comment` update stays, and gates Edit on someone else's comment alone. - Delete: with the `sys_comment` delete grant, the data door as before (others' comments included where the viewer moderates). Without it, the new affordance row `feedCommentDeleteOwn` (`grant: 'create'`, as `feedReactionRemove`) hands Delete over, it calls the own-comment door, and the host sets `ownCommentDeletesOnly`: `CommentThread` and the legacy `CommentBody` then offer Delete on the viewer's own comments with no reply and on nobody else's, whatever `moderatesComments` says. So the panel offers exactly what the doors admit. - `handleResolveComment`'s jsdoc says what the write is now (L2 S-D1 on #36178). `affordanceGrantMap-12082`: `handleResolveComment` is no longer a data-source write site (its row is gone); `feedCommentDeleteOwn` is in the grant table. **Prose**: `plugin-detail.mdx` (Delete wording; ✓ on every thread; the own-comment door). The two unreleased notes of #36104 (`36071-comment-threads-resolved.md`) and #36178 (`36075-comments-resolved.md`) stay as written; the new changeset `36186-36191-comment-doors.md` ends with one sentence for each, naming the line it replaces. ## Why Ruling 7063285032 (any reader may resolve) never reached a rank-and-file member: the row floor runs before the comment hook (L1-c HOLD 7068026256, readings in #36178). Ruling 7069889899 kept comment text author-only, which rules out loosening the floor for `update`, and added the own-comment delete (`member_default` may carry no delete bit, ADR-0090 D5). Shape agreed in the premise read and the seat's claims 7069978538 / 7069989751. ## Verification - `plugin-security` `comment-doors.integration.test.ts` (16 cases, real kernel + `SecurityPlugin` with the shipped sets + `AuditPlugin` + the real caller resolution, SQLite, two plain `org_member` principals, an `org_admin` and two `org_external` principals with explicit grants): member resolves and reopens a colleague's thread (200, `resolved_by` = member, cleared on reopen); data door unchanged (member's `body`, `is_resolved`, `{ is_resolved, body }` on a colleague's comment all 403); reply 400; unreadable = unknown 404; anonymous 401, query and every malformed body 400; own delete 200; colleague's 403 and stays; own comment with a reply 409, root and reply unchanged; own reply 200; own comment on an unreadable record 404; an external who reads the thread but may not post is 403 on resolve and still reads the comment, an external who may post resolves (200); member's data-door delete of their own still 403; admin resolves through the data door (floor does not bind) and the comment rule still decides edits. - `plugin-audit`: `comment-routes.test.ts` (mount, pre-engine answers, the write's exact shape and context; +4 for the posting gate: refused 403 with no write, a throwing check refuses, an unreadable comment still 404 before the gate, a poster resolves), `comment-resolution.test.ts` (+2: attribution stamps a system write; never outranks a session user), `comment-route-ledger.conformance.test.ts`; unreact ledger unchanged. `core`: `own-row-delete-routes.test.ts` (+3: step 7 refuses before any removal, runs only after the owner check, resolving admits). - UI: `RecordDetailView.commentsResolved-36075` also pins no ✓ for a viewer without the `sys_comment` create grant. `CommentsPanel.resolved-36075` (✓ on others' threads without the floor verdict; own-door Delete matrix), `RecordDetailView.commentsResolved-36075` (✓ → door URL and body, no data-source update; refused ✓; member without delete grant deletes through the door, none on others', none on own-with-reply; refused door delete), `RecordDetailView.feedCommentEditDelete-12268` (the no-delete-grant pin now asserts the door, plus own-with-reply). Local: app-shell comment/feed/discussion/reaction/explain RecordDetailView files + all of `plugin-detail` + `react` context: 437 files, 4067 passed. - Typecheck: `plugin-audit`, `core`, `plugin-security` clean. `check-route-envelope`, `check-single-authz-resolver` green. `check-governed-merges --test` on the file list: not governed. - Rig readings, CRM dev server (`objectstack dev --fresh`). Before: the #36178 hold readings at `a2dc85896` (reader and a record editor, both plain org members). After: this branch at `dd9f5571`; a fresh rig is `invite_only` now, so the admin creates both members through `POST /api/v1/auth/admin/create-user`, the reader with `viewer_readonly` and the record editor with `crm_sales_user`. | Reading | Before | After | |---|---|---| | Member resolves the admin's thread | data API `403 PERMISSION_DENIED` | door `200`, `resolved_by` = the member | | Member resolves a colleague's thread / reopens it | data API `403` | door `200` / `200`, `resolved_by` and `resolved_at` cleared | | Member resolves a reply | n/a | door `400 VALIDATION_ERROR` | | Member's data-API `is_resolved` on the admin's thread | `403` | `403` (unchanged) | | Record editor edits a member's comment (data API) | `403` | `403` (unchanged) | | Member edits the admin's comment | `403` | `403` (unchanged) | | Member deletes own comment, data API | `403` | `403` (unchanged) | | Member deletes own comment, door | n/a | `200 { deleted: true }` | | Member deletes a colleague's comment, door | n/a | `403 PERMISSION_DENIED` | | Member deletes own comment with a reply, door | n/a | `409 DELETE_RESTRICTED`, root and reply kept | | Colleague deletes that reply, door; member then deletes the root | n/a | `200`, then `200` | | Admin edits / resolves / deletes a member's comment (data API) | `200` | `200` / `200` / `200` (unchanged) | Rows left on the record afterwards: the admin's thread (resolved by the member), the record editor's thread (reopened); nothing else. Script and report: `build-seat1/36186-36191/rig/doors.cjs`, `doors-report.json` in the project files. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (No `packages/spec` change.) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. (eslint on the touched files: 0 errors.) - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. (Two folded cards, one `Fixes` line each.) - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (Not touched.) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. (The 维护者速读 section is the maintainer's Chinese summary, as on this seat's other PRs.) - [x] The *Before Submitting* list in CONTRIBUTING.md is done. ## Follow-ups - None filed. A "comment deleted" placeholder that would let an author remove a comment that has replies is a product question of its own (needs a stored marker), not in scope. Contract review F3 (the console asks the create grant for own-comment Delete while the door asks none) is left as is, consistent with `feedReactionRemove`. --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L6bhgUH1jEKbDzYRc4nghq <!-- signed: repo:objectstack#1 · os-sales · session_01L6bhgUH1jEKbDzYRc4nghq --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 5e8e243 commit d12ac84

25 files changed

Lines changed: 1733 additions & 122 deletions
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
---
2+
'@objectstack/plugin-audit': patch
3+
'@objectstack/core': patch
4+
'@object-ui/app-shell': patch
5+
'@object-ui/plugin-detail': patch
6+
'@object-ui/react': patch
7+
'@object-ui/core': patch
8+
---
9+
10+
feat(comments): a member resolves and reopens any thread they can read, and deletes their own comments
11+
12+
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.
13+
Metadata-protocol: none
14+
15+
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.
16+
17+
- **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`.
18+
- **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 }`.
19+
- **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.
20+
21+
The desktop comment panel follows the doors:
22+
23+
- ✓ 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.
24+
- 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.
25+
26+
Corrections to two earlier notes of this release, which stay as written:
27+
28+
- 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.
29+
- 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.

‎content/docs/frontend/plugins/plugin-detail.mdx‎

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -210,14 +210,19 @@ the record drawer), and no longer inside the 动态 (Activity) tab
210210
first, the comment box at the foot. A thread's replies fold to 「N 条回复」
211211
and open in place. A comment's actions (Reply, an emoji, ✓ on a thread's
212212
first comment, and More with Edit and Delete) appear at its top right while
213-
the pointer is over it. Edit and Delete are on your own comments. On other
214-
people's they appear only where the server would accept them: Delete for a
215-
member who may edit the record, Edit when the server also lets you change a
216-
comment you did not write (today, administrators).
213+
the pointer is over it. Edit and Delete are on your own comments; Delete is
214+
not on a comment of yours that has replies, unless you hold the
215+
`sys_comment` delete grant (administrators do), because the platform keeps
216+
it for the replies under it. On other people's comments they appear only
217+
where the server would accept them: Delete for someone who holds the
218+
`sys_comment` delete grant and may edit the record, Edit when the server
219+
also lets you change a comment you did not write (today, administrators).
217220
- **Resolved threads**: ✓ marks a thread resolved and it leaves the list; the
218-
icon's number drops by one. It is on the threads you started, and on other
219-
people's only where the server would accept it: today administrators, since
220-
the platform lets a member change only the rows they wrote. The
221+
icon's number drops by one. It is on every thread, yours and other people's:
222+
whoever can read the record and may comment on it may resolve and reopen its
223+
threads, through the platform's resolution door
224+
(`PUT /api/v1/comments/:id/resolution`); someone who can read the comments
225+
but not post one sees no ✓. The
221226
filter menu at the panel's top right holds 「显示已解决」, which shows resolved
222227
threads marked with who resolved them (their ✓ reopens them), and
223228
「只看我参与的」, 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`
392397
row (or a reply) whose `authoredByViewer` the host set, with the host's
393398
`onEditComment` / `onDeleteComment`. The console's record page marks each row
394399
with `@object-ui/collaboration`'s `isCommentAuthor`, the rule `CommentThread`
395-
uses, and hands each handler over under the caller's update or delete grant on
396-
`sys_comment`. Edit opens the text in place; Delete asks through the console's
400+
uses, and hands Edit over under the caller's update grant on `sys_comment`.
401+
Delete uses the data API under the caller's delete grant; a caller without it
402+
(an ordinary member) deletes through the platform's own-comment delete door
403+
(`DELETE /api/v1/comments/:id`) under the grant they comment with. That door
404+
removes only the caller's own comment, and not one that has replies, so the
405+
host sets `ownCommentDeletesOnly` and the feed offers Delete on exactly those
406+
rows. Edit opens the text in place; Delete asks through the console's
397407
destructive-action confirm. The server still decides the write, and a refusal
398408
shows as an error with the comment unchanged. An edited comment reads as
399409
edited (`is_edited` on the row).

‎docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-audit.md‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,24 +14,24 @@ a row or a number here — fix the code, or the census, and regenerate.
1414

1515
| Measure | Value |
1616
|---|---:|
17-
| Write call sites | 20 |
18-
| Object name statically decidable | 14 |
17+
| Write call sites | 21 |
18+
| Object name statically decidable | 15 |
1919
| Object name chosen at run time | 6 |
2020
| Object name spelled inline | 11 |
21-
| Object name spelled through a `const` | 3 |
21+
| Object name spelled through a `const` | 4 |
2222
| Object name is an `object: string` parameter | 0 |
2323
| Object name is some other run-time expression | 6 |
24-
| Against a tenancy-enabled object | 14 |
24+
| Against a tenancy-enabled object | 15 |
2525
| Against an object declaring tenancy off | 0 |
26-
| Threading a tenant context | 15 |
26+
| Threading a tenant context | 16 |
2727
| Provably carrying none (options read, no context key) | 0 |
2828
| …and decidably tenancy-enabled | 0 |
2929
| Options argument unreadable | 5 |
3030
| …and decidably tenancy-enabled | 4 |
31-
| Threading a decidably elevated (`isSystem`) context | 15 |
31+
| Threading a decidably elevated (`isSystem`) context | 16 |
3232
| Threading a decidably non-elevated context | 0 |
3333
| Threading a context of undecidable elevation | 5 |
34-
| Receiver carried a readable engine type | 20 |
34+
| Receiver carried a readable engine type | 21 |
3535
| Receiver erased, placed by the object NAME | 0 |
3636
| Receiver erased, placed by an `object: string` PARAMETER | 0 |
3737
| 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.
5858
| `packages/plugins/plugin-audit/src/auth-event-audit.ts` | `insert` | `sys_audit_log` | enabled | options unreadable | 1 |
5959
| `packages/plugins/plugin-audit/src/comment-parent-pair-backfill.ts` | `update` | `sys_comment` | enabled | elevated | 1 |
6060
| `packages/plugins/plugin-audit/src/comment-resolution.ts` | `update` | `sys_comment` | enabled | elevated | 1 |
61+
| `packages/plugins/plugin-audit/src/comment-routes.ts` | `update` | `sys_comment` | enabled | elevated | 1 |
6162
| `packages/plugins/plugin-audit/src/credential-use-audit.ts` | `insert` | `sys_audit_log` | enabled | elevated | 1 |
6263
| `packages/plugins/plugin-audit/src/data-export-audit.ts` | `insert` | `sys_audit_log` | enabled | elevated | 1 |
6364
| `packages/plugins/plugin-audit/src/dataset-query-audit.ts` | `insert` | `sys_audit_log` | enabled | elevated | 1 |

‎packages/core/src/security/own-row-delete-routes.test.ts‎

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import type { IHttpRequest } from '@objectstack/spec/contracts';
1414

1515
import { hashApiKey } from './api-key.js';
1616
import { currentCredentialUseClient } from './credential-use-client.js';
17-
import { ownRowDeleteCallerResolver } from './own-row-delete-routes.js';
17+
import { ownRowDeleteCallerResolver, removeOwnRow, type OwnRowDeleteDoor } from './own-row-delete-routes.js';
1818

1919
const KEY = 'osk_own_row_delete_31898';
2020
const OWNER = 'u_key_owner';
@@ -63,3 +63,59 @@ describe('[#31898] the own-row delete doors hand their client facts to the key\'
6363
expect(stamps).toEqual([{ ipAddress: '203.0.113.7', userAgent: 'ci-agent/3.1' }]);
6464
});
6565
});
66+
67+
describe("the own-row delete door's step 7: the object's own refusal", () => {
68+
const OWN = { id: 'row_1', owner_id: 'u_me' };
69+
const makeEngine = () => {
70+
const deleted: unknown[] = [];
71+
return {
72+
deleted,
73+
findOne: async () => ({ ...OWN }),
74+
delete: async (_object: string, options: { where: Record<string, unknown> }) => {
75+
deleted.push(options.where);
76+
return 1;
77+
},
78+
};
79+
};
80+
const door = (refuseRemoval?: OwnRowDeleteDoor['refuseRemoval']): OwnRowDeleteDoor => ({
81+
route: '/api/v1/things/:id',
82+
object: 'thing',
83+
ownerField: 'owner_id',
84+
words: { noun: 'thing', shortNoun: 'thing', owner: 'member' },
85+
...(refuseRemoval ? { refuseRemoval } : {}),
86+
});
87+
const ME = { userId: 'u_me', tenantId: 'org_1' } as never;
88+
89+
it('a refusal it throws reaches the caller and nothing is removed', async () => {
90+
const engine = makeEngine();
91+
const refusal = Object.assign(new Error('kept'), { code: 'DELETE_RESTRICTED', status: 409 });
92+
const seen: unknown[] = [];
93+
await expect(
94+
removeOwnRow(engine, door(async (row) => {
95+
seen.push(row);
96+
throw refusal;
97+
}), 'row_1', ME),
98+
).rejects.toBe(refusal);
99+
expect(seen).toEqual([OWN]);
100+
expect(engine.deleted).toEqual([]);
101+
});
102+
103+
it('is asked only after the owner check: a foreign row is refused 403 before it runs', async () => {
104+
const engine = { ...makeEngine(), findOne: async () => ({ id: 'row_1', owner_id: 'u_other' }) };
105+
let asked = false;
106+
await expect(
107+
removeOwnRow(engine, door(async () => {
108+
asked = true;
109+
}), 'row_1', ME),
110+
).rejects.toMatchObject({ code: 'PERMISSION_DENIED', status: 403 });
111+
expect(asked).toBe(false);
112+
});
113+
114+
it('resolving admits the removal, as a door that declares none does', async () => {
115+
for (const refuse of [async () => undefined, undefined]) {
116+
const engine = makeEngine();
117+
await removeOwnRow(engine, door(refuse), 'row_1', ME);
118+
expect(engine.deleted).toEqual([{ id: 'row_1' }]);
119+
}
120+
});
121+
});

‎packages/core/src/security/own-row-delete-routes.ts‎

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -59,10 +59,14 @@ import { resolveRequestExecutionContext, type RequestAuthService } from './reque
5959
* gives both, so the door says nothing about a row the caller cannot see.
6060
* 6. **The owner.** A row the caller CAN read whose owner column names anyone
6161
* else is refused loudly, `PERMISSION_DENIED` / `403`, and stays.
62+
* 7. **The object's own refusal**, for a door whose object declares one
63+
* ({@link OwnRowDeleteDoor.refuseRemoval}): a row the caller owns that the
64+
* object still may not lose. The door that declares it says why; its
65+
* refusal is answered with its own `code` and `status`, and the row stays.
6266
*
6367
* ## The removal
6468
*
65-
* Only after all six does the door remove the row, by id, under a system
69+
* Only after all seven does the door remove the row, by id, under a system
6670
* context. That elevation is what lets the door reach a row the caller holds
6771
* no `delete` grant on, and step 6 is the only thing that admits it: the
6872
* elevated write is reached by no other path. The context keeps the caller as
@@ -89,6 +93,14 @@ export interface OwnRowDeleteDoor {
8993
ownerField: string;
9094
/** The words the door's answers name the row with. */
9195
words: OwnRowDeleteWords;
96+
/**
97+
* Step 7, optional: refuse the removal of a row the caller owns that the
98+
* object still may not lose. Asked after the owner check with the row as the
99+
* caller read it, the engine and the caller's context; it throws the refusal
100+
* (an error carrying the ADR-0112 `code` and `status` the door answers) or
101+
* resolves to admit. Nothing is removed before it resolves.
102+
*/
103+
refuseRemoval?(row: Record<string, unknown>, engine: OwnRowDeleteEngine, context: ExecutionContext): Promise<void>;
92104
}
93105

94106
/** 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 {
197209
}
198210

199211
/**
200-
* Remove the caller's own row `id` of `door.object` — steps 5 and 6 of the
212+
* Remove the caller's own row `id` of `door.object` — steps 5 to 7 of the
201213
* door, and the removal. Throws `RECORD_NOT_FOUND` / `404` for a row the
202-
* caller cannot read or that does not exist, and `PERMISSION_DENIED` / `403`
203-
* for a row whose owner is someone else. `context` must name a user.
214+
* caller cannot read or that does not exist, `PERMISSION_DENIED` / `403`
215+
* for a row whose owner is someone else, and the door's own refusal (step 7).
216+
* `context` must name a user.
204217
*/
205218
export async function removeOwnRow(
206219
engine: OwnRowDeleteEngine,
@@ -221,6 +234,9 @@ export async function removeOwnRow(
221234
// Step 6: the structural check, and the only thing that admits the write below.
222235
if (row[door.ownerField] !== callerId) throw notYourRowError(door, id);
223236

237+
// Step 7: the object's own refusal, where it declares one.
238+
if (door.refuseRemoval) await door.refuseRemoval(row, engine, context);
239+
224240
const removed = await engine.delete(door.object, {
225241
where: { id },
226242
context: {
@@ -292,7 +308,7 @@ async function handleRemoveOwnRow(
292308
return;
293309
}
294310

295-
// ⑤ ⑥ and the removal.
311+
// ⑤ ⑥ ⑦ and the removal.
296312
try {
297313
await removeOwnRow(engine, door, id, context);
298314
} catch (err) {

0 commit comments

Comments
 (0)