@molecule/api-resource-comment 1.2.5 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +156 -8
- package/dist/authorizers/index.d.ts +95 -4
- package/dist/authorizers/index.d.ts.map +1 -1
- package/dist/authorizers/index.js +109 -4
- package/dist/handlers/count.d.ts.map +1 -1
- package/dist/handlers/count.js +9 -0
- package/dist/handlers/create.d.ts.map +1 -1
- package/dist/handlers/create.js +9 -1
- package/dist/handlers/del.js +2 -2
- package/dist/handlers/list.d.ts.map +1 -1
- package/dist/handlers/list.js +9 -0
- package/dist/handlers/read.d.ts.map +1 -1
- package/dist/handlers/read.js +5 -2
- package/dist/handlers/replies.d.ts.map +1 -1
- package/dist/handlers/replies.js +14 -1
- package/dist/handlers/update.js +2 -2
- package/dist/index.d.ts +11 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +11 -4
- package/dist/service.d.ts.map +1 -1
- package/dist/service.js +48 -19
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@ AUTO-GENERATED — DO NOT EDIT THIS FILE.
|
|
|
3
3
|
Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
|
|
4
4
|
Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
|
|
5
5
|
To change this document, edit the module-level JSDoc in src/index.ts.
|
|
6
|
-
Generated: 2026-11-
|
|
6
|
+
Generated: 2026-11-29T18:22:50.146Z
|
|
7
7
|
-->
|
|
8
8
|
|
|
9
9
|
# @molecule/api-resource-comment
|
|
@@ -45,13 +45,30 @@ import { routes, requestHandlerMap } from '@molecule/api-resource-comment'
|
|
|
45
45
|
## Installation
|
|
46
46
|
|
|
47
47
|
```bash
|
|
48
|
-
npm install @molecule/api-resource-comment @molecule/api-database @molecule/api-i18n @molecule/api-logger
|
|
48
|
+
npm install @molecule/api-resource-comment @molecule/api-database @molecule/api-i18n @molecule/api-logger zod
|
|
49
49
|
```
|
|
50
50
|
|
|
51
51
|
## API
|
|
52
52
|
|
|
53
53
|
### Interfaces
|
|
54
54
|
|
|
55
|
+
#### `CommentResourceAccessContext`
|
|
56
|
+
|
|
57
|
+
Context passed to a registered parent-resource access policy.
|
|
58
|
+
|
|
59
|
+
```typescript
|
|
60
|
+
interface CommentResourceAccessContext {
|
|
61
|
+
/** The polymorphic parent resource type (e.g. `'article'`, `'post'`, `'project'`). */
|
|
62
|
+
resourceType: string
|
|
63
|
+
/** The polymorphic parent resource identifier. */
|
|
64
|
+
resourceId: string
|
|
65
|
+
/** Whether the caller is reading comments (`'read'`) or posting a new comment (`'create'`). */
|
|
66
|
+
action: CommentResourceAction
|
|
67
|
+
/** The signed-in user ID, or `null`/`undefined` for anonymous callers. */
|
|
68
|
+
viewerId?: string | null
|
|
69
|
+
}
|
|
70
|
+
```
|
|
71
|
+
|
|
55
72
|
#### `Comment`
|
|
56
73
|
|
|
57
74
|
A comment attached to a resource, with optional threading via `parentId`.
|
|
@@ -137,6 +154,24 @@ interface PaginatedResult<T> {
|
|
|
137
154
|
|
|
138
155
|
### Types
|
|
139
156
|
|
|
157
|
+
#### `CommentResourceAction`
|
|
158
|
+
|
|
159
|
+
The kind of comment operation requesting access to the parent resource.
|
|
160
|
+
|
|
161
|
+
```typescript
|
|
162
|
+
type CommentResourceAction = 'read' | 'create'
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
#### `CommentResourceAccessCheck`
|
|
166
|
+
|
|
167
|
+
Predicate deciding whether a viewer may read or create comments on a parent resource.
|
|
168
|
+
|
|
169
|
+
```typescript
|
|
170
|
+
type CommentResourceAccessCheck = (
|
|
171
|
+
context: CommentResourceAccessContext,
|
|
172
|
+
) => boolean | Promise<boolean>
|
|
173
|
+
```
|
|
174
|
+
|
|
140
175
|
#### `NumberedComment`
|
|
141
176
|
|
|
142
177
|
A comment together with its sequential number.
|
|
@@ -148,8 +183,114 @@ type NumberedComment = Comment & {
|
|
|
148
183
|
}
|
|
149
184
|
```
|
|
150
185
|
|
|
186
|
+
### Classes
|
|
187
|
+
|
|
188
|
+
#### `CommentResourceAccessError`
|
|
189
|
+
|
|
190
|
+
Thrown by `createComment` when a registered parent-resource access policy denies access.
|
|
191
|
+
Handlers translate this to HTTP `404` so private or missing parents are not distinguished.
|
|
192
|
+
|
|
193
|
+
```typescript
|
|
194
|
+
class CommentResourceAccessError extends Error {
|
|
195
|
+
/** HTTP status code to return for a denied or missing parent resource. */
|
|
196
|
+
readonly statusCode = 404
|
|
197
|
+
/** Stable i18n error key matching `@molecule/api-resource`. */
|
|
198
|
+
readonly errorKey = 'resource.error.notFound'
|
|
199
|
+
/** The parent resource type that was denied. */
|
|
200
|
+
readonly resourceType: string
|
|
201
|
+
/** The parent resource identifier that was denied. */
|
|
202
|
+
readonly resourceId: string
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Creates an access-denied error for a comment's parent resource.
|
|
206
|
+
*
|
|
207
|
+
* @param resourceType - The parent resource type.
|
|
208
|
+
* @param resourceId - The parent resource identifier.
|
|
209
|
+
*/
|
|
210
|
+
constructor(resourceType: string, resourceId: string) {
|
|
211
|
+
super(`Resource not accessible for comments: ${resourceType}/${resourceId}`)
|
|
212
|
+
this.name = 'CommentResourceAccessError'
|
|
213
|
+
this.resourceType = resourceType
|
|
214
|
+
this.resourceId = resourceId
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
```
|
|
218
|
+
|
|
151
219
|
### Functions
|
|
152
220
|
|
|
221
|
+
#### `registerResourceAccessPolicy(resourceType, check)`
|
|
222
|
+
|
|
223
|
+
Registers a parent-resource access policy for `resourceType` (or `'*'` as a
|
|
224
|
+
wildcard fallback for any resource type without a specific policy).
|
|
225
|
+
|
|
226
|
+
```typescript
|
|
227
|
+
function registerResourceAccessPolicy(resourceType: string, check: CommentResourceAccessCheck): void
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
- `resourceType` — Canonical resource type slug (e.g. `'article'`, `'project'`, `'*'`).
|
|
231
|
+
- `check` — Predicate returning `true` when the viewer may perform `action`.
|
|
232
|
+
|
|
233
|
+
#### `unregisterResourceAccessPolicy(resourceType)`
|
|
234
|
+
|
|
235
|
+
Removes a previously registered parent-resource access policy.
|
|
236
|
+
|
|
237
|
+
```typescript
|
|
238
|
+
function unregisterResourceAccessPolicy(resourceType: string): void
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
- `resourceType` — Canonical resource type slug to unregister.
|
|
242
|
+
|
|
243
|
+
#### `clearResourceAccessPolicies()`
|
|
244
|
+
|
|
245
|
+
Removes all registered parent-resource access policies. Intended for tests.
|
|
246
|
+
|
|
247
|
+
```typescript
|
|
248
|
+
function clearResourceAccessPolicies(): void
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
#### `getResourceAccessPolicy(resourceType)`
|
|
252
|
+
|
|
253
|
+
Returns the access policy registered for `resourceType`, falling back to `'*'`.
|
|
254
|
+
|
|
255
|
+
```typescript
|
|
256
|
+
function getResourceAccessPolicy(resourceType: string): CommentResourceAccessCheck | undefined
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
- `resourceType` — Canonical resource type slug.
|
|
260
|
+
|
|
261
|
+
**Returns:** The matching policy predicate, or `undefined` when unrestricted.
|
|
262
|
+
|
|
263
|
+
#### `hasResourceAccessPolicies()`
|
|
264
|
+
|
|
265
|
+
Returns `true` when at least one parent-resource access policy is registered.
|
|
266
|
+
|
|
267
|
+
```typescript
|
|
268
|
+
function hasResourceAccessPolicies(): boolean
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
**Returns:** Whether any access policy is active.
|
|
272
|
+
|
|
273
|
+
#### `canAccessCommentResource(resourceType, resourceId, action, viewerId)`
|
|
274
|
+
|
|
275
|
+
Evaluates the registered access policy for `(resourceType, resourceId)`.
|
|
276
|
+
Returns `true` when no policy is registered for that type (or `'*'`).
|
|
277
|
+
|
|
278
|
+
```typescript
|
|
279
|
+
function canAccessCommentResource(
|
|
280
|
+
resourceType: string,
|
|
281
|
+
resourceId: string,
|
|
282
|
+
action: CommentResourceAction,
|
|
283
|
+
viewerId?: string | null,
|
|
284
|
+
): Promise<boolean>
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
- `resourceType` — Canonical resource type slug.
|
|
288
|
+
- `resourceId` — The parent resource identifier.
|
|
289
|
+
- `action` — `'read'` or `'create'`.
|
|
290
|
+
- `viewerId` — The signed-in viewer ID, or `null`/`undefined` for anonymous callers.
|
|
291
|
+
|
|
292
|
+
**Returns:** Whether access is permitted.
|
|
293
|
+
|
|
153
294
|
#### `commentCount(req, res)`
|
|
154
295
|
|
|
155
296
|
Returns the total comment count for a resource.
|
|
@@ -514,7 +655,7 @@ Peer dependencies:
|
|
|
514
655
|
- `@molecule/api-database` ^1.1.0
|
|
515
656
|
- `@molecule/api-i18n` ^1.0.1
|
|
516
657
|
- `@molecule/api-logger` ^1.0.1
|
|
517
|
-
- `@molecule/api-resource` ^1.0.1
|
|
658
|
+
- `@molecule/api-resource` ^1.0.1 _(optional)_
|
|
518
659
|
- `zod` ^4.0.0
|
|
519
660
|
|
|
520
661
|
### Runtime Dependencies
|
|
@@ -522,7 +663,7 @@ Peer dependencies:
|
|
|
522
663
|
- `@molecule/api-database`
|
|
523
664
|
- `@molecule/api-i18n`
|
|
524
665
|
- `@molecule/api-logger`
|
|
525
|
-
- `@molecule/api-resource`
|
|
666
|
+
- `@molecule/api-resource` _(optional)_
|
|
526
667
|
- `zod`
|
|
527
668
|
|
|
528
669
|
- **List endpoints return a PAGINATED envelope** `{ data, total, limit, offset }`, not a
|
|
@@ -546,10 +687,17 @@ Peer dependencies:
|
|
|
546
687
|
`getCommentByNumber(n)` — never hand-build an id from the UUID, and never read a missing
|
|
547
688
|
`commentNumbers(ids)` entry as `0` (a row inserted without `createComment()` has no number;
|
|
548
689
|
`numberComment(id)` gives it one). Never build your own id-mapping table.
|
|
549
|
-
- **
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
690
|
+
- **Parent-resource visibility and publication policies.** `list`, `read`,
|
|
691
|
+
`replies`, `count`, and `create` enforce any policy registered via
|
|
692
|
+
`registerResourceAccessPolicy(resourceType, check)` (or `'*'` as a fallback).
|
|
693
|
+
When denied, handlers return `404` and `createComment` runs the access check
|
|
694
|
+
and insert atomically inside a database transaction (when supported by the
|
|
695
|
+
bonded pool) to prevent check-then-write races. Sibling resources such as
|
|
696
|
+
`@molecule/api-resource-article` register their visibility rules automatically
|
|
697
|
+
on import (rejecting comments on unpublished drafts and hiding draft comments
|
|
698
|
+
from non-authors). For your own private resources, call
|
|
699
|
+
`registerResourceAccessPolicy('my-type', ({ resourceId, action, viewerId }) => …)`
|
|
700
|
+
at startup. When no policy is registered for a type, reads remain public.
|
|
553
701
|
- **The author is always the session user.** Create/update/delete require
|
|
554
702
|
`authenticate`; the create handler ignores any client-supplied author id,
|
|
555
703
|
and update/delete verify ownership in the handler — keep those properties
|
|
@@ -1,10 +1,101 @@
|
|
|
1
|
-
export {};
|
|
2
1
|
/**
|
|
3
|
-
* Comment authorizers.
|
|
2
|
+
* Comment parent-resource access policies and authorizers.
|
|
4
3
|
*
|
|
5
|
-
* Comment ownership is enforced in the service layer — only the
|
|
6
|
-
* owner can update or delete their comments.
|
|
4
|
+
* Comment ownership (update/delete) is enforced in the service layer — only the
|
|
5
|
+
* comment owner can update or delete their comments.
|
|
6
|
+
*
|
|
7
|
+
* For polymorphic attachment reads and creates (`/:resourceType/:resourceId/comments`,
|
|
8
|
+
* `/comments/:commentId`, `/comments/:commentId/replies`), sibling resource packages
|
|
9
|
+
* (such as `@molecule/api-resource-article`) and app code can register a parent-resource
|
|
10
|
+
* access policy via {@link registerResourceAccessPolicy}. When a policy is registered for
|
|
11
|
+
* a resource type (or `'*'`), every read and create checks it before serving or inserting
|
|
12
|
+
* comments, and `createComment` runs the check and insert inside a single database
|
|
13
|
+
* transaction when the bonded pool supports transactions.
|
|
7
14
|
*
|
|
8
15
|
* @module
|
|
9
16
|
*/
|
|
17
|
+
/**
|
|
18
|
+
* The kind of comment operation requesting access to the parent resource.
|
|
19
|
+
*/
|
|
20
|
+
export type CommentResourceAction = 'read' | 'create';
|
|
21
|
+
/**
|
|
22
|
+
* Context passed to a registered parent-resource access policy.
|
|
23
|
+
*/
|
|
24
|
+
export interface CommentResourceAccessContext {
|
|
25
|
+
/** The polymorphic parent resource type (e.g. `'article'`, `'post'`, `'project'`). */
|
|
26
|
+
resourceType: string;
|
|
27
|
+
/** The polymorphic parent resource identifier. */
|
|
28
|
+
resourceId: string;
|
|
29
|
+
/** Whether the caller is reading comments (`'read'`) or posting a new comment (`'create'`). */
|
|
30
|
+
action: CommentResourceAction;
|
|
31
|
+
/** The signed-in user ID, or `null`/`undefined` for anonymous callers. */
|
|
32
|
+
viewerId?: string | null;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Predicate deciding whether a viewer may read or create comments on a parent resource.
|
|
36
|
+
*/
|
|
37
|
+
export type CommentResourceAccessCheck = (context: CommentResourceAccessContext) => boolean | Promise<boolean>;
|
|
38
|
+
/**
|
|
39
|
+
* Thrown by `createComment` when a registered parent-resource access policy denies access.
|
|
40
|
+
* Handlers translate this to HTTP `404` so private or missing parents are not distinguished.
|
|
41
|
+
*/
|
|
42
|
+
export declare class CommentResourceAccessError extends Error {
|
|
43
|
+
/** HTTP status code to return for a denied or missing parent resource. */
|
|
44
|
+
readonly statusCode = 404;
|
|
45
|
+
/** Stable i18n error key matching `@molecule/api-resource`. */
|
|
46
|
+
readonly errorKey = "resource.error.notFound";
|
|
47
|
+
/** The parent resource type that was denied. */
|
|
48
|
+
readonly resourceType: string;
|
|
49
|
+
/** The parent resource identifier that was denied. */
|
|
50
|
+
readonly resourceId: string;
|
|
51
|
+
/**
|
|
52
|
+
* Creates an access-denied error for a comment's parent resource.
|
|
53
|
+
*
|
|
54
|
+
* @param resourceType - The parent resource type.
|
|
55
|
+
* @param resourceId - The parent resource identifier.
|
|
56
|
+
*/
|
|
57
|
+
constructor(resourceType: string, resourceId: string);
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Registers a parent-resource access policy for `resourceType` (or `'*'` as a
|
|
61
|
+
* wildcard fallback for any resource type without a specific policy).
|
|
62
|
+
*
|
|
63
|
+
* @param resourceType - Canonical resource type slug (e.g. `'article'`, `'project'`, `'*'`).
|
|
64
|
+
* @param check - Predicate returning `true` when the viewer may perform `action`.
|
|
65
|
+
*/
|
|
66
|
+
export declare function registerResourceAccessPolicy(resourceType: string, check: CommentResourceAccessCheck): void;
|
|
67
|
+
/**
|
|
68
|
+
* Removes a previously registered parent-resource access policy.
|
|
69
|
+
*
|
|
70
|
+
* @param resourceType - Canonical resource type slug to unregister.
|
|
71
|
+
*/
|
|
72
|
+
export declare function unregisterResourceAccessPolicy(resourceType: string): void;
|
|
73
|
+
/**
|
|
74
|
+
* Removes all registered parent-resource access policies. Intended for tests.
|
|
75
|
+
*/
|
|
76
|
+
export declare function clearResourceAccessPolicies(): void;
|
|
77
|
+
/**
|
|
78
|
+
* Returns the access policy registered for `resourceType`, falling back to `'*'`.
|
|
79
|
+
*
|
|
80
|
+
* @param resourceType - Canonical resource type slug.
|
|
81
|
+
* @returns The matching policy predicate, or `undefined` when unrestricted.
|
|
82
|
+
*/
|
|
83
|
+
export declare function getResourceAccessPolicy(resourceType: string): CommentResourceAccessCheck | undefined;
|
|
84
|
+
/**
|
|
85
|
+
* Returns `true` when at least one parent-resource access policy is registered.
|
|
86
|
+
*
|
|
87
|
+
* @returns Whether any access policy is active.
|
|
88
|
+
*/
|
|
89
|
+
export declare function hasResourceAccessPolicies(): boolean;
|
|
90
|
+
/**
|
|
91
|
+
* Evaluates the registered access policy for `(resourceType, resourceId)`.
|
|
92
|
+
* Returns `true` when no policy is registered for that type (or `'*'`).
|
|
93
|
+
*
|
|
94
|
+
* @param resourceType - Canonical resource type slug.
|
|
95
|
+
* @param resourceId - The parent resource identifier.
|
|
96
|
+
* @param action - `'read'` or `'create'`.
|
|
97
|
+
* @param viewerId - The signed-in viewer ID, or `null`/`undefined` for anonymous callers.
|
|
98
|
+
* @returns Whether access is permitted.
|
|
99
|
+
*/
|
|
100
|
+
export declare function canAccessCommentResource(resourceType: string, resourceId: string, action: CommentResourceAction, viewerId?: string | null): Promise<boolean>;
|
|
10
101
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/authorizers/index.ts"],"names":[],"mappings":";
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/authorizers/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH;;GAEG;AACH,MAAM,MAAM,qBAAqB,GAAG,MAAM,GAAG,QAAQ,CAAA;AAErD;;GAEG;AACH,MAAM,WAAW,4BAA4B;IAC3C,sFAAsF;IACtF,YAAY,EAAE,MAAM,CAAA;IACpB,kDAAkD;IAClD,UAAU,EAAE,MAAM,CAAA;IAClB,+FAA+F;IAC/F,MAAM,EAAE,qBAAqB,CAAA;IAC7B,0EAA0E;IAC1E,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CACzB;AAED;;GAEG;AACH,MAAM,MAAM,0BAA0B,GAAG,CACvC,OAAO,EAAE,4BAA4B,KAClC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;AAE/B;;;GAGG;AACH,qBAAa,0BAA2B,SAAQ,KAAK;IACnD,0EAA0E;IAC1E,QAAQ,CAAC,UAAU,OAAM;IACzB,+DAA+D;IAC/D,QAAQ,CAAC,QAAQ,6BAA4B;IAC7C,gDAAgD;IAChD,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAA;IAC7B,sDAAsD;IACtD,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAA;IAE3B;;;;;OAKG;gBACS,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM;CAMrD;AAoBD;;;;;;GAMG;AACH,wBAAgB,4BAA4B,CAC1C,YAAY,EAAE,MAAM,EACpB,KAAK,EAAE,0BAA0B,GAChC,IAAI,CAEN;AAED;;;;GAIG;AACH,wBAAgB,8BAA8B,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI,CAEzE;AAED;;GAEG;AACH,wBAAgB,2BAA2B,IAAI,IAAI,CAElD;AAED;;;;;GAKG;AACH,wBAAgB,uBAAuB,CACrC,YAAY,EAAE,MAAM,GACnB,0BAA0B,GAAG,SAAS,CAGxC;AAED;;;;GAIG;AACH,wBAAgB,yBAAyB,IAAI,OAAO,CAEnD;AAED;;;;;;;;;GASG;AACH,wBAAsB,wBAAwB,CAC5C,YAAY,EAAE,MAAM,EACpB,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,qBAAqB,EAC7B,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,GACvB,OAAO,CAAC,OAAO,CAAC,CAIlB"}
|
|
@@ -1,9 +1,114 @@
|
|
|
1
|
-
export {};
|
|
2
1
|
/**
|
|
3
|
-
* Comment authorizers.
|
|
2
|
+
* Comment parent-resource access policies and authorizers.
|
|
4
3
|
*
|
|
5
|
-
* Comment ownership is enforced in the service layer — only the
|
|
6
|
-
* owner can update or delete their comments.
|
|
4
|
+
* Comment ownership (update/delete) is enforced in the service layer — only the
|
|
5
|
+
* comment owner can update or delete their comments.
|
|
6
|
+
*
|
|
7
|
+
* For polymorphic attachment reads and creates (`/:resourceType/:resourceId/comments`,
|
|
8
|
+
* `/comments/:commentId`, `/comments/:commentId/replies`), sibling resource packages
|
|
9
|
+
* (such as `@molecule/api-resource-article`) and app code can register a parent-resource
|
|
10
|
+
* access policy via {@link registerResourceAccessPolicy}. When a policy is registered for
|
|
11
|
+
* a resource type (or `'*'`), every read and create checks it before serving or inserting
|
|
12
|
+
* comments, and `createComment` runs the check and insert inside a single database
|
|
13
|
+
* transaction when the bonded pool supports transactions.
|
|
7
14
|
*
|
|
8
15
|
* @module
|
|
9
16
|
*/
|
|
17
|
+
/**
|
|
18
|
+
* Thrown by `createComment` when a registered parent-resource access policy denies access.
|
|
19
|
+
* Handlers translate this to HTTP `404` so private or missing parents are not distinguished.
|
|
20
|
+
*/
|
|
21
|
+
export class CommentResourceAccessError extends Error {
|
|
22
|
+
/** HTTP status code to return for a denied or missing parent resource. */
|
|
23
|
+
statusCode = 404;
|
|
24
|
+
/** Stable i18n error key matching `@molecule/api-resource`. */
|
|
25
|
+
errorKey = 'resource.error.notFound';
|
|
26
|
+
/** The parent resource type that was denied. */
|
|
27
|
+
resourceType;
|
|
28
|
+
/** The parent resource identifier that was denied. */
|
|
29
|
+
resourceId;
|
|
30
|
+
/**
|
|
31
|
+
* Creates an access-denied error for a comment's parent resource.
|
|
32
|
+
*
|
|
33
|
+
* @param resourceType - The parent resource type.
|
|
34
|
+
* @param resourceId - The parent resource identifier.
|
|
35
|
+
*/
|
|
36
|
+
constructor(resourceType, resourceId) {
|
|
37
|
+
super(`Resource not accessible for comments: ${resourceType}/${resourceId}`);
|
|
38
|
+
this.name = 'CommentResourceAccessError';
|
|
39
|
+
this.resourceType = resourceType;
|
|
40
|
+
this.resourceId = resourceId;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const POLICIES_KEY = Symbol.for('@molecule/api-resource/access-policies');
|
|
44
|
+
/**
|
|
45
|
+
* Process-wide map of parent-resource access policies shared across resource
|
|
46
|
+
* packages via `Symbol.for('@molecule/api-resource/access-policies')`, so
|
|
47
|
+
* sibling packages (e.g. `@molecule/api-resource-article`) can register their
|
|
48
|
+
* visibility rules without importing `@molecule/api-resource-comment`.
|
|
49
|
+
*
|
|
50
|
+
* @returns The shared policy map.
|
|
51
|
+
*/
|
|
52
|
+
function getPolicyMap() {
|
|
53
|
+
const holder = globalThis;
|
|
54
|
+
holder[POLICIES_KEY] ??= new Map();
|
|
55
|
+
return holder[POLICIES_KEY];
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Registers a parent-resource access policy for `resourceType` (or `'*'` as a
|
|
59
|
+
* wildcard fallback for any resource type without a specific policy).
|
|
60
|
+
*
|
|
61
|
+
* @param resourceType - Canonical resource type slug (e.g. `'article'`, `'project'`, `'*'`).
|
|
62
|
+
* @param check - Predicate returning `true` when the viewer may perform `action`.
|
|
63
|
+
*/
|
|
64
|
+
export function registerResourceAccessPolicy(resourceType, check) {
|
|
65
|
+
getPolicyMap().set(resourceType, check);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Removes a previously registered parent-resource access policy.
|
|
69
|
+
*
|
|
70
|
+
* @param resourceType - Canonical resource type slug to unregister.
|
|
71
|
+
*/
|
|
72
|
+
export function unregisterResourceAccessPolicy(resourceType) {
|
|
73
|
+
getPolicyMap().delete(resourceType);
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Removes all registered parent-resource access policies. Intended for tests.
|
|
77
|
+
*/
|
|
78
|
+
export function clearResourceAccessPolicies() {
|
|
79
|
+
getPolicyMap().clear();
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Returns the access policy registered for `resourceType`, falling back to `'*'`.
|
|
83
|
+
*
|
|
84
|
+
* @param resourceType - Canonical resource type slug.
|
|
85
|
+
* @returns The matching policy predicate, or `undefined` when unrestricted.
|
|
86
|
+
*/
|
|
87
|
+
export function getResourceAccessPolicy(resourceType) {
|
|
88
|
+
const policies = getPolicyMap();
|
|
89
|
+
return policies.get(resourceType) ?? policies.get('*');
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Returns `true` when at least one parent-resource access policy is registered.
|
|
93
|
+
*
|
|
94
|
+
* @returns Whether any access policy is active.
|
|
95
|
+
*/
|
|
96
|
+
export function hasResourceAccessPolicies() {
|
|
97
|
+
return getPolicyMap().size > 0;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Evaluates the registered access policy for `(resourceType, resourceId)`.
|
|
101
|
+
* Returns `true` when no policy is registered for that type (or `'*'`).
|
|
102
|
+
*
|
|
103
|
+
* @param resourceType - Canonical resource type slug.
|
|
104
|
+
* @param resourceId - The parent resource identifier.
|
|
105
|
+
* @param action - `'read'` or `'create'`.
|
|
106
|
+
* @param viewerId - The signed-in viewer ID, or `null`/`undefined` for anonymous callers.
|
|
107
|
+
* @returns Whether access is permitted.
|
|
108
|
+
*/
|
|
109
|
+
export async function canAccessCommentResource(resourceType, resourceId, action, viewerId) {
|
|
110
|
+
const policy = getResourceAccessPolicy(resourceType);
|
|
111
|
+
if (!policy)
|
|
112
|
+
return true;
|
|
113
|
+
return Boolean(await policy({ resourceType, resourceId, action, viewerId }));
|
|
114
|
+
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"count.d.ts","sourceRoot":"","sources":["../../src/handlers/count.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;
|
|
1
|
+
{"version":3,"file":"count.d.ts","sourceRoot":"","sources":["../../src/handlers/count.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AAK/E;;;;;GAKG;AACH,wBAAsB,YAAY,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAiC7F"}
|
package/dist/handlers/count.js
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import { t } from '@molecule/api-i18n';
|
|
7
7
|
import { logger } from '@molecule/api-logger';
|
|
8
|
+
import { canAccessCommentResource } from '../authorizers/index.js';
|
|
8
9
|
import { getCommentCount } from '../service.js';
|
|
9
10
|
/**
|
|
10
11
|
* Returns the total comment count for a resource.
|
|
@@ -23,7 +24,15 @@ export async function commentCount(req, res) {
|
|
|
23
24
|
});
|
|
24
25
|
return;
|
|
25
26
|
}
|
|
27
|
+
const viewerId = res.locals.session?.userId;
|
|
26
28
|
try {
|
|
29
|
+
if (!(await canAccessCommentResource(resourceType, resourceId, 'read', viewerId))) {
|
|
30
|
+
res.status(404).json({
|
|
31
|
+
error: t('resource.error.notFound', undefined, { defaultValue: 'Not found.' }),
|
|
32
|
+
errorKey: 'resource.error.notFound',
|
|
33
|
+
});
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
27
36
|
const total = await getCommentCount(resourceType, resourceId);
|
|
28
37
|
res.json({ count: total });
|
|
29
38
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create.d.ts","sourceRoot":"","sources":["../../src/handlers/create.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;
|
|
1
|
+
{"version":3,"file":"create.d.ts","sourceRoot":"","sources":["../../src/handlers/create.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AAM/E;;;;;GAKG;AACH,wBAAsB,MAAM,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CA+CvF"}
|
package/dist/handlers/create.js
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import { t } from '@molecule/api-i18n';
|
|
7
7
|
import { logger } from '@molecule/api-logger';
|
|
8
|
+
import { CommentResourceAccessError } from '../authorizers/index.js';
|
|
8
9
|
import { createComment } from '../service.js';
|
|
9
10
|
import { createCommentSchema } from '../validation.js';
|
|
10
11
|
/**
|
|
@@ -17,7 +18,7 @@ export async function create(req, res) {
|
|
|
17
18
|
const userId = res.locals.session?.userId;
|
|
18
19
|
if (!userId) {
|
|
19
20
|
res.status(401).json({
|
|
20
|
-
error: t('resource.error.unauthorized', undefined, { defaultValue: 'Unauthorized' }),
|
|
21
|
+
error: t('resource.error.unauthorized', undefined, { defaultValue: 'Unauthorized.' }),
|
|
21
22
|
errorKey: 'resource.error.unauthorized',
|
|
22
23
|
});
|
|
23
24
|
return;
|
|
@@ -43,6 +44,13 @@ export async function create(req, res) {
|
|
|
43
44
|
res.status(201).json(comment);
|
|
44
45
|
}
|
|
45
46
|
catch (error) {
|
|
47
|
+
if (error instanceof CommentResourceAccessError) {
|
|
48
|
+
res.status(404).json({
|
|
49
|
+
error: t('resource.error.notFound', undefined, { defaultValue: 'Not found.' }),
|
|
50
|
+
errorKey: 'resource.error.notFound',
|
|
51
|
+
});
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
46
54
|
logger.error('Failed to create comment', { resourceType, resourceId, userId, error });
|
|
47
55
|
res.status(500).json({
|
|
48
56
|
error: t('comment.error.createFailed', undefined, {
|
package/dist/handlers/del.js
CHANGED
|
@@ -16,7 +16,7 @@ export async function del(req, res) {
|
|
|
16
16
|
const userId = res.locals.session?.userId;
|
|
17
17
|
if (!userId) {
|
|
18
18
|
res.status(401).json({
|
|
19
|
-
error: t('resource.error.unauthorized', undefined, { defaultValue: 'Unauthorized' }),
|
|
19
|
+
error: t('resource.error.unauthorized', undefined, { defaultValue: 'Unauthorized.' }),
|
|
20
20
|
errorKey: 'resource.error.unauthorized',
|
|
21
21
|
});
|
|
22
22
|
return;
|
|
@@ -33,7 +33,7 @@ export async function del(req, res) {
|
|
|
33
33
|
const deleted = await deleteComment(commentId, userId);
|
|
34
34
|
if (!deleted) {
|
|
35
35
|
res.status(404).json({
|
|
36
|
-
error: t('resource.error.notFound', undefined, { defaultValue: 'Not found' }),
|
|
36
|
+
error: t('resource.error.notFound', undefined, { defaultValue: 'Not found.' }),
|
|
37
37
|
errorKey: 'resource.error.notFound',
|
|
38
38
|
});
|
|
39
39
|
return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"list.d.ts","sourceRoot":"","sources":["../../src/handlers/list.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;
|
|
1
|
+
{"version":3,"file":"list.d.ts","sourceRoot":"","sources":["../../src/handlers/list.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AAQ/E;;;;;GAKG;AACH,wBAAsB,IAAI,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAoCrF"}
|
package/dist/handlers/list.js
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import { t } from '@molecule/api-i18n';
|
|
7
7
|
import { logger } from '@molecule/api-logger';
|
|
8
|
+
import { canAccessCommentResource } from '../authorizers/index.js';
|
|
8
9
|
import { getCommentsByResource } from '../service.js';
|
|
9
10
|
/** Upper bound for the list page size — an uncapped `limit` is a table-dump primitive (e.g. `?limit=999999999`). */
|
|
10
11
|
const MAX_LIST_LIMIT = 500;
|
|
@@ -27,7 +28,15 @@ export async function list(req, res) {
|
|
|
27
28
|
}
|
|
28
29
|
const limit = Math.min(MAX_LIST_LIMIT, Math.max(1, parseInt(req.query.limit, 10) || 20));
|
|
29
30
|
const offset = parseInt(req.query.offset, 10) || 0;
|
|
31
|
+
const viewerId = res.locals.session?.userId;
|
|
30
32
|
try {
|
|
33
|
+
if (!(await canAccessCommentResource(resourceType, resourceId, 'read', viewerId))) {
|
|
34
|
+
res.status(404).json({
|
|
35
|
+
error: t('resource.error.notFound', undefined, { defaultValue: 'Not found.' }),
|
|
36
|
+
errorKey: 'resource.error.notFound',
|
|
37
|
+
});
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
31
40
|
const result = await getCommentsByResource(resourceType, resourceId, { limit, offset });
|
|
32
41
|
res.json(result);
|
|
33
42
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"read.d.ts","sourceRoot":"","sources":["../../src/handlers/read.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;
|
|
1
|
+
{"version":3,"file":"read.d.ts","sourceRoot":"","sources":["../../src/handlers/read.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AAK/E;;;;;GAKG;AACH,wBAAsB,IAAI,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAgCrF"}
|
package/dist/handlers/read.js
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import { t } from '@molecule/api-i18n';
|
|
7
7
|
import { logger } from '@molecule/api-logger';
|
|
8
|
+
import { canAccessCommentResource } from '../authorizers/index.js';
|
|
8
9
|
import { getCommentById } from '../service.js';
|
|
9
10
|
/**
|
|
10
11
|
* Retrieves a single comment by ID.
|
|
@@ -21,11 +22,13 @@ export async function read(req, res) {
|
|
|
21
22
|
});
|
|
22
23
|
return;
|
|
23
24
|
}
|
|
25
|
+
const viewerId = res.locals.session?.userId;
|
|
24
26
|
try {
|
|
25
27
|
const comment = await getCommentById(commentId);
|
|
26
|
-
if (!comment
|
|
28
|
+
if (!comment ||
|
|
29
|
+
!(await canAccessCommentResource(comment.resourceType, comment.resourceId, 'read', viewerId))) {
|
|
27
30
|
res.status(404).json({
|
|
28
|
-
error: t('resource.error.notFound', undefined, { defaultValue: 'Not found' }),
|
|
31
|
+
error: t('resource.error.notFound', undefined, { defaultValue: 'Not found.' }),
|
|
29
32
|
errorKey: 'resource.error.notFound',
|
|
30
33
|
});
|
|
31
34
|
return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"replies.d.ts","sourceRoot":"","sources":["../../src/handlers/replies.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;
|
|
1
|
+
{"version":3,"file":"replies.d.ts","sourceRoot":"","sources":["../../src/handlers/replies.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AAQ/E;;;;;GAKG;AACH,wBAAsB,OAAO,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAwCxF"}
|
package/dist/handlers/replies.js
CHANGED
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import { t } from '@molecule/api-i18n';
|
|
7
7
|
import { logger } from '@molecule/api-logger';
|
|
8
|
-
import {
|
|
8
|
+
import { canAccessCommentResource, hasResourceAccessPolicies } from '../authorizers/index.js';
|
|
9
|
+
import { getCommentById, getReplies } from '../service.js';
|
|
9
10
|
/** Upper bound for the list page size — an uncapped `limit` is a table-dump primitive (e.g. `?limit=999999999`). */
|
|
10
11
|
const MAX_LIST_LIMIT = 500;
|
|
11
12
|
/**
|
|
@@ -25,7 +26,19 @@ export async function replies(req, res) {
|
|
|
25
26
|
}
|
|
26
27
|
const limit = Math.min(MAX_LIST_LIMIT, Math.max(1, parseInt(req.query.limit, 10) || 20));
|
|
27
28
|
const offset = parseInt(req.query.offset, 10) || 0;
|
|
29
|
+
const viewerId = res.locals.session?.userId;
|
|
28
30
|
try {
|
|
31
|
+
if (hasResourceAccessPolicies()) {
|
|
32
|
+
const parent = await getCommentById(commentId);
|
|
33
|
+
if (!parent ||
|
|
34
|
+
!(await canAccessCommentResource(parent.resourceType, parent.resourceId, 'read', viewerId))) {
|
|
35
|
+
res.status(404).json({
|
|
36
|
+
error: t('resource.error.notFound', undefined, { defaultValue: 'Not found.' }),
|
|
37
|
+
errorKey: 'resource.error.notFound',
|
|
38
|
+
});
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
29
42
|
const result = await getReplies(commentId, { limit, offset });
|
|
30
43
|
res.json(result);
|
|
31
44
|
}
|
package/dist/handlers/update.js
CHANGED
|
@@ -17,7 +17,7 @@ export async function update(req, res) {
|
|
|
17
17
|
const userId = res.locals.session?.userId;
|
|
18
18
|
if (!userId) {
|
|
19
19
|
res.status(401).json({
|
|
20
|
-
error: t('resource.error.unauthorized', undefined, { defaultValue: 'Unauthorized' }),
|
|
20
|
+
error: t('resource.error.unauthorized', undefined, { defaultValue: 'Unauthorized.' }),
|
|
21
21
|
errorKey: 'resource.error.unauthorized',
|
|
22
22
|
});
|
|
23
23
|
return;
|
|
@@ -40,7 +40,7 @@ export async function update(req, res) {
|
|
|
40
40
|
const comment = await updateComment(commentId, userId, parsed.data);
|
|
41
41
|
if (!comment) {
|
|
42
42
|
res.status(404).json({
|
|
43
|
-
error: t('resource.error.notFound', undefined, { defaultValue: 'Not found' }),
|
|
43
|
+
error: t('resource.error.notFound', undefined, { defaultValue: 'Not found.' }),
|
|
44
44
|
errorKey: 'resource.error.notFound',
|
|
45
45
|
});
|
|
46
46
|
return;
|
package/dist/index.d.ts
CHANGED
|
@@ -47,10 +47,17 @@
|
|
|
47
47
|
* `getCommentByNumber(n)` — never hand-build an id from the UUID, and never read a missing
|
|
48
48
|
* `commentNumbers(ids)` entry as `0` (a row inserted without `createComment()` has no number;
|
|
49
49
|
* `numberComment(id)` gives it one). Never build your own id-mapping table.
|
|
50
|
-
* - **
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
50
|
+
* - **Parent-resource visibility and publication policies.** `list`, `read`,
|
|
51
|
+
* `replies`, `count`, and `create` enforce any policy registered via
|
|
52
|
+
* `registerResourceAccessPolicy(resourceType, check)` (or `'*'` as a fallback).
|
|
53
|
+
* When denied, handlers return `404` and `createComment` runs the access check
|
|
54
|
+
* and insert atomically inside a database transaction (when supported by the
|
|
55
|
+
* bonded pool) to prevent check-then-write races. Sibling resources such as
|
|
56
|
+
* `@molecule/api-resource-article` register their visibility rules automatically
|
|
57
|
+
* on import (rejecting comments on unpublished drafts and hiding draft comments
|
|
58
|
+
* from non-authors). For your own private resources, call
|
|
59
|
+
* `registerResourceAccessPolicy('my-type', ({ resourceId, action, viewerId }) => …)`
|
|
60
|
+
* at startup. When no policy is registered for a type, reads remain public.
|
|
54
61
|
* - **The author is always the session user.** Create/update/delete require
|
|
55
62
|
* `authenticate`; the create handler ignores any client-supplied author id,
|
|
56
63
|
* and update/delete verify ownership in the handler — keep those properties
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6FG;AAEH,cAAc,wBAAwB,CAAA;AACtC,cAAc,oBAAoB,CAAA;AAClC,cAAc,qBAAqB,CAAA;AACnC,cAAc,cAAc,CAAA;AAC5B,cAAc,wBAAwB,CAAA;AACtC,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,cAAc,YAAY,CAAA;AAC1B,cAAc,iBAAiB,CAAA"}
|
package/dist/index.js
CHANGED
|
@@ -47,10 +47,17 @@
|
|
|
47
47
|
* `getCommentByNumber(n)` — never hand-build an id from the UUID, and never read a missing
|
|
48
48
|
* `commentNumbers(ids)` entry as `0` (a row inserted without `createComment()` has no number;
|
|
49
49
|
* `numberComment(id)` gives it one). Never build your own id-mapping table.
|
|
50
|
-
* - **
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
50
|
+
* - **Parent-resource visibility and publication policies.** `list`, `read`,
|
|
51
|
+
* `replies`, `count`, and `create` enforce any policy registered via
|
|
52
|
+
* `registerResourceAccessPolicy(resourceType, check)` (or `'*'` as a fallback).
|
|
53
|
+
* When denied, handlers return `404` and `createComment` runs the access check
|
|
54
|
+
* and insert atomically inside a database transaction (when supported by the
|
|
55
|
+
* bonded pool) to prevent check-then-write races. Sibling resources such as
|
|
56
|
+
* `@molecule/api-resource-article` register their visibility rules automatically
|
|
57
|
+
* on import (rejecting comments on unpublished drafts and hiding draft comments
|
|
58
|
+
* from non-authors). For your own private resources, call
|
|
59
|
+
* `registerResourceAccessPolicy('my-type', ({ resourceId, action, viewerId }) => …)`
|
|
60
|
+
* at startup. When no policy is registered for a type, reads remain public.
|
|
54
61
|
* - **The author is always the session user.** Create/update/delete require
|
|
55
62
|
* `authenticate`; the create handler ignores any client-supplied author id,
|
|
56
63
|
* and update/delete verify ownership in the handler — keep those properties
|
package/dist/service.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../src/service.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;
|
|
1
|
+
{"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../src/service.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAiBH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAA;AACnD,OAAO,KAAK,EACV,OAAO,EACP,kBAAkB,EAClB,eAAe,EACf,iBAAiB,EACjB,kBAAkB,EACnB,MAAM,YAAY,CAAA;AAanB;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAsB,aAAa,CACjC,YAAY,EAAE,MAAM,EACpB,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,kBAAkB,GACvB,OAAO,CAAC,eAAe,CAAC,CA2D1B;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAsB,qBAAqB,CACzC,YAAY,EAAE,MAAM,EACpB,UAAU,EAAE,MAAM,EAClB,OAAO,GAAE,iBAAsB,GAC9B,OAAO,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC,CAqBnC;AAED;;;;;;GAMG;AACH,wBAAsB,cAAc,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,CAE/E;AAED;;;;;;;;GAQG;AACH,wBAAsB,aAAa,CACjC,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,kBAAkB,GACvB,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,CAczB;AAED;;;;;;;;GAQG;AACH,wBAAsB,aAAa,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAMvF;AAED;;;;;;;GAOG;AACH,wBAAsB,UAAU,CAC9B,SAAS,EAAE,MAAM,EACjB,OAAO,GAAE,iBAAsB,GAC9B,OAAO,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC,CAiBnC;AAED;;;;;;GAMG;AACH,wBAAsB,eAAe,CAAC,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAK/F"}
|
package/dist/service.js
CHANGED
|
@@ -6,7 +6,8 @@
|
|
|
6
6
|
*
|
|
7
7
|
* @module
|
|
8
8
|
*/
|
|
9
|
-
import { count, create as dbCreate, deleteById, findById, findMany, updateById, } from '@molecule/api-database';
|
|
9
|
+
import { count, create as dbCreate, deleteById, findById, findMany, getActiveTransaction, getPool, hasPool, updateById, withTransaction, } from '@molecule/api-database';
|
|
10
|
+
import { CommentResourceAccessError, getResourceAccessPolicy } from './authorizers/index.js';
|
|
10
11
|
import { allocateCommentNumber, numbersForComments } from './numbering.js';
|
|
11
12
|
const TABLE = 'comments';
|
|
12
13
|
/** Keep a page's stable integer identities beside its UUIDs without allocating on read. */
|
|
@@ -40,28 +41,56 @@ async function withNumbers(comments) {
|
|
|
40
41
|
* removed again so the caller is not told a create failed while it exists.
|
|
41
42
|
*/
|
|
42
43
|
export async function createComment(resourceType, resourceId, userId, data) {
|
|
43
|
-
const
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
44
|
+
const policy = getResourceAccessPolicy(resourceType);
|
|
45
|
+
const execute = async () => {
|
|
46
|
+
if (policy) {
|
|
47
|
+
const allowed = await policy({
|
|
48
|
+
resourceType,
|
|
49
|
+
resourceId,
|
|
50
|
+
action: 'create',
|
|
51
|
+
viewerId: userId,
|
|
52
|
+
});
|
|
53
|
+
if (!allowed) {
|
|
54
|
+
throw new CommentResourceAccessError(resourceType, resourceId);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const result = await dbCreate(TABLE, {
|
|
58
|
+
resourceType,
|
|
59
|
+
resourceId,
|
|
60
|
+
userId,
|
|
61
|
+
parentId: data.parentId ?? null,
|
|
62
|
+
body: data.body,
|
|
63
|
+
editedAt: null,
|
|
64
|
+
});
|
|
65
|
+
const comment = result.data;
|
|
57
66
|
try {
|
|
58
|
-
await
|
|
67
|
+
return { ...comment, number: await allocateCommentNumber(comment.id) };
|
|
59
68
|
}
|
|
60
|
-
catch (
|
|
61
|
-
|
|
69
|
+
catch (error) {
|
|
70
|
+
// Inside a transaction, throwing rolls back the inserted row automatically.
|
|
71
|
+
// Outside a transaction, remove the unnumbered row manually so the caller is
|
|
72
|
+
// not told a create failed while the row remains behind.
|
|
73
|
+
if (!getActiveTransaction()) {
|
|
74
|
+
try {
|
|
75
|
+
await deleteById(TABLE, comment.id);
|
|
76
|
+
}
|
|
77
|
+
catch (cleanupError) {
|
|
78
|
+
throw new AggregateError([error, cleanupError], `Could not number comment ${comment.id}, and could not remove the unnumbered row`, { cause: cleanupError });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
throw error;
|
|
62
82
|
}
|
|
63
|
-
|
|
83
|
+
};
|
|
84
|
+
// When a parent-resource policy is active and the bonded pool supports
|
|
85
|
+
// interactive transactions, run the visibility check and insert atomically
|
|
86
|
+
// so a concurrent unpublish/delete cannot race between check and write.
|
|
87
|
+
if (policy &&
|
|
88
|
+
!getActiveTransaction() &&
|
|
89
|
+
hasPool() &&
|
|
90
|
+
typeof getPool().transaction === 'function') {
|
|
91
|
+
return withTransaction(execute);
|
|
64
92
|
}
|
|
93
|
+
return execute();
|
|
65
94
|
}
|
|
66
95
|
/**
|
|
67
96
|
* Retrieves paginated comments for a resource, ordered by creation date descending.
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@molecule/api-resource-comment",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "Threaded comments on any resource with polymorphic attachment and
|
|
3
|
+
"version": "1.3.0",
|
|
4
|
+
"description": "Threaded comments on any resource with polymorphic attachment, pagination and sequential integer comment numbers (createNumberedComment)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
7
7
|
"types": "dist/index.d.ts",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"license": "Apache-2.0",
|
|
31
31
|
"devDependencies": {
|
|
32
32
|
"@molecule/api-database": "1.2.2",
|
|
33
|
-
"@molecule/api-database-sqlite": "1.4.
|
|
33
|
+
"@molecule/api-database-sqlite": "1.4.4",
|
|
34
34
|
"@types/node": "26.6.5",
|
|
35
35
|
"typescript": "6.0.3",
|
|
36
36
|
"vitest": "4.1.12",
|