@molecule/api-resource-comment 1.2.6 → 1.4.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 +179 -8
- package/dist/authorizers/index.d.ts +97 -4
- package/dist/authorizers/index.d.ts.map +1 -1
- package/dist/authorizers/index.js +114 -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 +8 -0
- 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 +4 -1
- package/dist/handlers/replies.d.ts.map +1 -1
- package/dist/handlers/replies.js +14 -1
- 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 +90 -22
- package/dist/types.d.ts +15 -0
- package/dist/types.d.ts.map +1 -1
- 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-30T00:33:26.456Z
|
|
7
7
|
-->
|
|
8
8
|
|
|
9
9
|
# @molecule/api-resource-comment
|
|
@@ -45,13 +45,49 @@ 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
|
+
|
|
72
|
+
#### `CommentAuthor`
|
|
73
|
+
|
|
74
|
+
Public display profile attached to a comment when `@molecule/api-resource-user` is loaded.
|
|
75
|
+
|
|
76
|
+
```typescript
|
|
77
|
+
interface CommentAuthor {
|
|
78
|
+
/** The user's canonical id. */
|
|
79
|
+
id: string
|
|
80
|
+
/** The public username, when set. */
|
|
81
|
+
username: string | null
|
|
82
|
+
/** The public display name, when set. */
|
|
83
|
+
name: string | null
|
|
84
|
+
/** The public biography, when set. */
|
|
85
|
+
bio: string | null
|
|
86
|
+
/** The public avatar URL, when set. */
|
|
87
|
+
avatar: string | null
|
|
88
|
+
}
|
|
89
|
+
```
|
|
90
|
+
|
|
55
91
|
#### `Comment`
|
|
56
92
|
|
|
57
93
|
A comment attached to a resource, with optional threading via `parentId`.
|
|
@@ -68,6 +104,8 @@ interface Comment {
|
|
|
68
104
|
resourceId: string
|
|
69
105
|
/** The ID of the user who created this comment. */
|
|
70
106
|
userId: string
|
|
107
|
+
/** Hydrated public author profile when `@molecule/api-resource-user` is loaded. */
|
|
108
|
+
author?: CommentAuthor | null
|
|
71
109
|
/** The parent comment ID for threaded replies, or `null` for top-level comments. */
|
|
72
110
|
parentId: string | null
|
|
73
111
|
/** The comment body text. */
|
|
@@ -137,6 +175,24 @@ interface PaginatedResult<T> {
|
|
|
137
175
|
|
|
138
176
|
### Types
|
|
139
177
|
|
|
178
|
+
#### `CommentResourceAction`
|
|
179
|
+
|
|
180
|
+
The kind of comment operation requesting access to the parent resource.
|
|
181
|
+
|
|
182
|
+
```typescript
|
|
183
|
+
type CommentResourceAction = 'read' | 'create'
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
#### `CommentResourceAccessCheck`
|
|
187
|
+
|
|
188
|
+
Predicate deciding whether a viewer may read or create comments on a parent resource.
|
|
189
|
+
|
|
190
|
+
```typescript
|
|
191
|
+
type CommentResourceAccessCheck = (
|
|
192
|
+
context: CommentResourceAccessContext,
|
|
193
|
+
) => boolean | Promise<boolean>
|
|
194
|
+
```
|
|
195
|
+
|
|
140
196
|
#### `NumberedComment`
|
|
141
197
|
|
|
142
198
|
A comment together with its sequential number.
|
|
@@ -148,8 +204,116 @@ type NumberedComment = Comment & {
|
|
|
148
204
|
}
|
|
149
205
|
```
|
|
150
206
|
|
|
207
|
+
### Classes
|
|
208
|
+
|
|
209
|
+
#### `CommentResourceAccessError`
|
|
210
|
+
|
|
211
|
+
Thrown by `createComment` when a registered parent-resource access policy denies access.
|
|
212
|
+
Handlers translate this to HTTP `404` so private or missing parents are not distinguished.
|
|
213
|
+
|
|
214
|
+
```typescript
|
|
215
|
+
class CommentResourceAccessError extends Error {
|
|
216
|
+
/** HTTP status code to return for a denied or missing parent resource. */
|
|
217
|
+
readonly statusCode = 404
|
|
218
|
+
/** Stable i18n error key matching `@molecule/api-resource`. */
|
|
219
|
+
readonly errorKey = 'resource.error.notFound'
|
|
220
|
+
/** The parent resource type that was denied. */
|
|
221
|
+
readonly resourceType: string
|
|
222
|
+
/** The parent resource identifier that was denied. */
|
|
223
|
+
readonly resourceId: string
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Creates an access-denied error for a comment's parent resource.
|
|
227
|
+
*
|
|
228
|
+
* @param resourceType - The parent resource type.
|
|
229
|
+
* @param resourceId - The parent resource identifier.
|
|
230
|
+
*/
|
|
231
|
+
constructor(resourceType: string, resourceId: string) {
|
|
232
|
+
super(`Resource not accessible for comments: ${resourceType}/${resourceId}`)
|
|
233
|
+
this.name = 'CommentResourceAccessError'
|
|
234
|
+
this.resourceType = resourceType
|
|
235
|
+
this.resourceId = resourceId
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
```
|
|
239
|
+
|
|
151
240
|
### Functions
|
|
152
241
|
|
|
242
|
+
#### `registerResourceAccessPolicy(resourceType, check)`
|
|
243
|
+
|
|
244
|
+
Registers a parent-resource access policy for `resourceType` (or `'*'` as a
|
|
245
|
+
wildcard fallback for any resource type without a specific policy).
|
|
246
|
+
|
|
247
|
+
```typescript
|
|
248
|
+
function registerResourceAccessPolicy(resourceType: string, check: CommentResourceAccessCheck): void
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
- `resourceType` — Canonical resource type slug (e.g. `'article'`, `'project'`, `'*'`).
|
|
252
|
+
- `check` — Predicate returning `true` when the viewer may perform `action`.
|
|
253
|
+
|
|
254
|
+
#### `unregisterResourceAccessPolicy(resourceType)`
|
|
255
|
+
|
|
256
|
+
Removes a previously registered parent-resource access policy.
|
|
257
|
+
|
|
258
|
+
```typescript
|
|
259
|
+
function unregisterResourceAccessPolicy(resourceType: string): void
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
- `resourceType` — Canonical resource type slug to unregister.
|
|
263
|
+
|
|
264
|
+
#### `clearResourceAccessPolicies()`
|
|
265
|
+
|
|
266
|
+
Removes all registered parent-resource access policies. Intended for tests.
|
|
267
|
+
|
|
268
|
+
```typescript
|
|
269
|
+
function clearResourceAccessPolicies(): void
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
#### `getResourceAccessPolicy(resourceType)`
|
|
273
|
+
|
|
274
|
+
Returns the access policy registered for `resourceType`, falling back to `'*'`.
|
|
275
|
+
|
|
276
|
+
```typescript
|
|
277
|
+
function getResourceAccessPolicy(resourceType: string): CommentResourceAccessCheck | undefined
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
- `resourceType` — Canonical resource type slug.
|
|
281
|
+
|
|
282
|
+
**Returns:** The matching policy predicate, or `undefined` when unrestricted.
|
|
283
|
+
|
|
284
|
+
#### `hasResourceAccessPolicies()`
|
|
285
|
+
|
|
286
|
+
Returns `true` when at least one parent-resource access policy is registered.
|
|
287
|
+
|
|
288
|
+
```typescript
|
|
289
|
+
function hasResourceAccessPolicies(): boolean
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
**Returns:** Whether any access policy is active.
|
|
293
|
+
|
|
294
|
+
#### `canAccessCommentResource(resourceType, resourceId, action, viewerId)`
|
|
295
|
+
|
|
296
|
+
Evaluates the registered access policy for `(resourceType, resourceId)`.
|
|
297
|
+
When no policies are registered at all, returns `true`. Once any resource
|
|
298
|
+
access policy is registered, unregistered resource types fail closed (`false`)
|
|
299
|
+
unless a `'*'` wildcard policy explicitly allows them.
|
|
300
|
+
|
|
301
|
+
```typescript
|
|
302
|
+
function canAccessCommentResource(
|
|
303
|
+
resourceType: string,
|
|
304
|
+
resourceId: string,
|
|
305
|
+
action: CommentResourceAction,
|
|
306
|
+
viewerId?: string | null,
|
|
307
|
+
): Promise<boolean>
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
- `resourceType` — Canonical resource type slug.
|
|
311
|
+
- `resourceId` — The parent resource identifier.
|
|
312
|
+
- `action` — `'read'` or `'create'`.
|
|
313
|
+
- `viewerId` — The signed-in viewer ID, or `null`/`undefined` for anonymous callers.
|
|
314
|
+
|
|
315
|
+
**Returns:** Whether access is permitted.
|
|
316
|
+
|
|
153
317
|
#### `commentCount(req, res)`
|
|
154
318
|
|
|
155
319
|
Returns the total comment count for a resource.
|
|
@@ -514,7 +678,7 @@ Peer dependencies:
|
|
|
514
678
|
- `@molecule/api-database` ^1.1.0
|
|
515
679
|
- `@molecule/api-i18n` ^1.0.1
|
|
516
680
|
- `@molecule/api-logger` ^1.0.1
|
|
517
|
-
- `@molecule/api-resource` ^1.0.1
|
|
681
|
+
- `@molecule/api-resource` ^1.0.1 _(optional)_
|
|
518
682
|
- `zod` ^4.0.0
|
|
519
683
|
|
|
520
684
|
### Runtime Dependencies
|
|
@@ -522,7 +686,7 @@ Peer dependencies:
|
|
|
522
686
|
- `@molecule/api-database`
|
|
523
687
|
- `@molecule/api-i18n`
|
|
524
688
|
- `@molecule/api-logger`
|
|
525
|
-
- `@molecule/api-resource`
|
|
689
|
+
- `@molecule/api-resource` _(optional)_
|
|
526
690
|
- `zod`
|
|
527
691
|
|
|
528
692
|
- **List endpoints return a PAGINATED envelope** `{ data, total, limit, offset }`, not a
|
|
@@ -546,10 +710,17 @@ Peer dependencies:
|
|
|
546
710
|
`getCommentByNumber(n)` — never hand-build an id from the UUID, and never read a missing
|
|
547
711
|
`commentNumbers(ids)` entry as `0` (a row inserted without `createComment()` has no number;
|
|
548
712
|
`numberComment(id)` gives it one). Never build your own id-mapping table.
|
|
549
|
-
- **
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
713
|
+
- **Parent-resource visibility and publication policies.** `list`, `read`,
|
|
714
|
+
`replies`, `count`, and `create` enforce any policy registered via
|
|
715
|
+
`registerResourceAccessPolicy(resourceType, check)` (or `'*'` as a fallback).
|
|
716
|
+
When denied, handlers return `404` and `createComment` runs the access check
|
|
717
|
+
and insert atomically inside a database transaction (when supported by the
|
|
718
|
+
bonded pool) to prevent check-then-write races. Sibling resources such as
|
|
719
|
+
`@molecule/api-resource-article` register their visibility rules automatically
|
|
720
|
+
on import (rejecting comments on unpublished drafts and hiding draft comments
|
|
721
|
+
from non-authors). For your own private resources, call
|
|
722
|
+
`registerResourceAccessPolicy('my-type', ({ resourceId, action, viewerId }) => …)`
|
|
723
|
+
at startup. When no policy is registered for a type, reads remain public.
|
|
553
724
|
- **The author is always the session user.** Create/update/delete require
|
|
554
725
|
`authenticate`; the create handler ignores any client-supplied author id,
|
|
555
726
|
and update/delete verify ownership in the handler — keep those properties
|
|
@@ -1,10 +1,103 @@
|
|
|
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
|
+
* When no policies are registered at all, returns `true`. Once any resource
|
|
93
|
+
* access policy is registered, unregistered resource types fail closed (`false`)
|
|
94
|
+
* unless a `'*'` wildcard policy explicitly allows them.
|
|
95
|
+
*
|
|
96
|
+
* @param resourceType - Canonical resource type slug.
|
|
97
|
+
* @param resourceId - The parent resource identifier.
|
|
98
|
+
* @param action - `'read'` or `'create'`.
|
|
99
|
+
* @param viewerId - The signed-in viewer ID, or `null`/`undefined` for anonymous callers.
|
|
100
|
+
* @returns Whether access is permitted.
|
|
101
|
+
*/
|
|
102
|
+
export declare function canAccessCommentResource(resourceType: string, resourceId: string, action: CommentResourceAction, viewerId?: string | null): Promise<boolean>;
|
|
10
103
|
//# 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":[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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,CAMlB"}
|
|
@@ -1,9 +1,119 @@
|
|
|
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
|
+
* When no policies are registered at all, returns `true`. Once any resource
|
|
102
|
+
* access policy is registered, unregistered resource types fail closed (`false`)
|
|
103
|
+
* unless a `'*'` wildcard policy explicitly allows them.
|
|
104
|
+
*
|
|
105
|
+
* @param resourceType - Canonical resource type slug.
|
|
106
|
+
* @param resourceId - The parent resource identifier.
|
|
107
|
+
* @param action - `'read'` or `'create'`.
|
|
108
|
+
* @param viewerId - The signed-in viewer ID, or `null`/`undefined` for anonymous callers.
|
|
109
|
+
* @returns Whether access is permitted.
|
|
110
|
+
*/
|
|
111
|
+
export async function canAccessCommentResource(resourceType, resourceId, action, viewerId) {
|
|
112
|
+
const policies = getPolicyMap();
|
|
113
|
+
if (policies.size === 0)
|
|
114
|
+
return true;
|
|
115
|
+
const policy = policies.get(resourceType) ?? policies.get('*');
|
|
116
|
+
if (!policy)
|
|
117
|
+
return false;
|
|
118
|
+
return Boolean(await policy({ resourceType, resourceId, action, viewerId }));
|
|
119
|
+
}
|
|
@@ -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
|
/**
|
|
@@ -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, {
|
|
@@ -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,9 +22,11 @@ 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
31
|
error: t('resource.error.notFound', undefined, { defaultValue: 'Not found.' }),
|
|
29
32
|
errorKey: 'resource.error.notFound',
|
|
@@ -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/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;AAqBH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAA;AACnD,OAAO,KAAK,EACV,OAAO,EAEP,kBAAkB,EAClB,eAAe,EACf,iBAAiB,EACjB,kBAAkB,EACnB,MAAM,YAAY,CAAA;AAqCnB;;;;;;;;;;;;;;;;;;;;;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,CAoE1B;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,CAK/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,CAgBzB;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,16 +6,40 @@
|
|
|
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, hasResourceAccessPolicies, } from './authorizers/index.js';
|
|
10
11
|
import { allocateCommentNumber, numbersForComments } from './numbering.js';
|
|
11
12
|
const TABLE = 'comments';
|
|
13
|
+
const PUBLIC_PROFILES_KEY = Symbol.for('@molecule/api-resource/public-profiles');
|
|
14
|
+
/** Load public author profiles in one batch query when `@molecule/api-resource-user` is loaded. */
|
|
15
|
+
async function withAuthors(comments) {
|
|
16
|
+
if (comments.length === 0)
|
|
17
|
+
return comments;
|
|
18
|
+
const loader = globalThis[PUBLIC_PROFILES_KEY];
|
|
19
|
+
if (!loader)
|
|
20
|
+
return comments;
|
|
21
|
+
try {
|
|
22
|
+
const profiles = await loader(comments.map((comment) => comment.userId));
|
|
23
|
+
if (profiles.size === 0)
|
|
24
|
+
return comments;
|
|
25
|
+
return comments.map((comment) => {
|
|
26
|
+
const author = profiles.get(comment.userId);
|
|
27
|
+
return author ? { ...comment, author } : comment;
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
catch (_error) {
|
|
31
|
+
// Users table may be absent in isolated comment-only unit tests.
|
|
32
|
+
return comments;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
12
35
|
/** Keep a page's stable integer identities beside its UUIDs without allocating on read. */
|
|
13
36
|
async function withNumbers(comments) {
|
|
14
37
|
const numbers = await numbersForComments(comments.map((comment) => comment.id));
|
|
15
|
-
|
|
38
|
+
const numbered = comments.map((comment) => {
|
|
16
39
|
const number = numbers.get(comment.id);
|
|
17
40
|
return number === undefined ? comment : { ...comment, number };
|
|
18
41
|
});
|
|
42
|
+
return withAuthors(numbered);
|
|
19
43
|
}
|
|
20
44
|
/**
|
|
21
45
|
* Creates a new comment on a resource, with its sequential number.
|
|
@@ -40,28 +64,65 @@ async function withNumbers(comments) {
|
|
|
40
64
|
* removed again so the caller is not told a create failed while it exists.
|
|
41
65
|
*/
|
|
42
66
|
export async function createComment(resourceType, resourceId, userId, data) {
|
|
43
|
-
const
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
67
|
+
const hasPolicies = hasResourceAccessPolicies();
|
|
68
|
+
const policy = getResourceAccessPolicy(resourceType);
|
|
69
|
+
const execute = async () => {
|
|
70
|
+
if (hasPolicies) {
|
|
71
|
+
if (!policy) {
|
|
72
|
+
throw new CommentResourceAccessError(resourceType, resourceId);
|
|
73
|
+
}
|
|
74
|
+
const allowed = await policy({
|
|
75
|
+
resourceType,
|
|
76
|
+
resourceId,
|
|
77
|
+
action: 'create',
|
|
78
|
+
viewerId: userId,
|
|
79
|
+
});
|
|
80
|
+
if (!allowed) {
|
|
81
|
+
throw new CommentResourceAccessError(resourceType, resourceId);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
const result = await dbCreate(TABLE, {
|
|
85
|
+
resourceType,
|
|
86
|
+
resourceId,
|
|
87
|
+
userId,
|
|
88
|
+
parentId: data.parentId ?? null,
|
|
89
|
+
body: data.body,
|
|
90
|
+
editedAt: null,
|
|
91
|
+
});
|
|
92
|
+
const comment = result.data;
|
|
57
93
|
try {
|
|
58
|
-
|
|
94
|
+
const numbered = {
|
|
95
|
+
...comment,
|
|
96
|
+
number: await allocateCommentNumber(comment.id),
|
|
97
|
+
};
|
|
98
|
+
const [hydrated] = await withAuthors([numbered]);
|
|
99
|
+
return hydrated;
|
|
59
100
|
}
|
|
60
|
-
catch (
|
|
61
|
-
|
|
101
|
+
catch (error) {
|
|
102
|
+
// Inside a transaction, throwing rolls back the inserted row automatically.
|
|
103
|
+
// Outside a transaction, remove the unnumbered row manually so the caller is
|
|
104
|
+
// not told a create failed while the row remains behind.
|
|
105
|
+
if (!getActiveTransaction()) {
|
|
106
|
+
try {
|
|
107
|
+
await deleteById(TABLE, comment.id);
|
|
108
|
+
}
|
|
109
|
+
catch (cleanupError) {
|
|
110
|
+
throw new AggregateError([error, cleanupError], `Could not number comment ${comment.id}, and could not remove the unnumbered row`, { cause: cleanupError });
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
throw error;
|
|
62
114
|
}
|
|
63
|
-
|
|
115
|
+
};
|
|
116
|
+
// When a parent-resource policy is active and the bonded pool supports
|
|
117
|
+
// interactive transactions, run the visibility check and insert atomically
|
|
118
|
+
// so a concurrent unpublish/delete cannot race between check and write.
|
|
119
|
+
if (policy &&
|
|
120
|
+
!getActiveTransaction() &&
|
|
121
|
+
hasPool() &&
|
|
122
|
+
typeof getPool().transaction === 'function') {
|
|
123
|
+
return withTransaction(execute);
|
|
64
124
|
}
|
|
125
|
+
return execute();
|
|
65
126
|
}
|
|
66
127
|
/**
|
|
67
128
|
* Retrieves paginated comments for a resource, ordered by creation date descending.
|
|
@@ -104,7 +165,11 @@ export async function getCommentsByResource(resourceType, resourceId, options =
|
|
|
104
165
|
* @returns The comment or `null` if not found.
|
|
105
166
|
*/
|
|
106
167
|
export async function getCommentById(commentId) {
|
|
107
|
-
|
|
168
|
+
const comment = await findById(TABLE, commentId);
|
|
169
|
+
if (!comment)
|
|
170
|
+
return null;
|
|
171
|
+
const [hydrated] = await withAuthors([comment]);
|
|
172
|
+
return hydrated ?? comment;
|
|
108
173
|
}
|
|
109
174
|
/**
|
|
110
175
|
* Updates a comment. Only the comment owner can update.
|
|
@@ -126,7 +191,10 @@ export async function updateComment(commentId, userId, data) {
|
|
|
126
191
|
// still shows a changed updatedAt.
|
|
127
192
|
updatedAt: new Date(Math.max(Date.now(), (Date.parse(String(existing.updatedAt ?? '')) || 0) + 1)).toISOString(),
|
|
128
193
|
});
|
|
129
|
-
|
|
194
|
+
if (!result.data)
|
|
195
|
+
return null;
|
|
196
|
+
const [hydrated] = await withAuthors([result.data]);
|
|
197
|
+
return hydrated ?? result.data;
|
|
130
198
|
}
|
|
131
199
|
/**
|
|
132
200
|
* Deletes a comment. Only the comment owner can delete.
|
package/dist/types.d.ts
CHANGED
|
@@ -6,6 +6,19 @@
|
|
|
6
6
|
*
|
|
7
7
|
* @module
|
|
8
8
|
*/
|
|
9
|
+
/** Public display profile attached to a comment when `@molecule/api-resource-user` is loaded. */
|
|
10
|
+
export interface CommentAuthor {
|
|
11
|
+
/** The user's canonical id. */
|
|
12
|
+
id: string;
|
|
13
|
+
/** The public username, when set. */
|
|
14
|
+
username: string | null;
|
|
15
|
+
/** The public display name, when set. */
|
|
16
|
+
name: string | null;
|
|
17
|
+
/** The public biography, when set. */
|
|
18
|
+
bio: string | null;
|
|
19
|
+
/** The public avatar URL, when set. */
|
|
20
|
+
avatar: string | null;
|
|
21
|
+
}
|
|
9
22
|
/**
|
|
10
23
|
* A comment attached to a resource, with optional threading via `parentId`.
|
|
11
24
|
*/
|
|
@@ -20,6 +33,8 @@ export interface Comment {
|
|
|
20
33
|
resourceId: string;
|
|
21
34
|
/** The ID of the user who created this comment. */
|
|
22
35
|
userId: string;
|
|
36
|
+
/** Hydrated public author profile when `@molecule/api-resource-user` is loaded. */
|
|
37
|
+
author?: CommentAuthor | null;
|
|
23
38
|
/** The parent comment ID for threaded replies, or `null` for top-level comments. */
|
|
24
39
|
parentId: string | null;
|
|
25
40
|
/** The comment body text. */
|
package/dist/types.d.ts.map
CHANGED
|
@@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G;AACH,MAAM,WAAW,iBAAiB;IAChC,2CAA2C;IAC3C,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,iCAAiC;IACjC,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB;AAED;;GAEG;AACH,MAAM,WAAW,eAAe,CAAC,CAAC;IAChC,6CAA6C;IAC7C,IAAI,EAAE,CAAC,EAAE,CAAA;IACT,uDAAuD;IACvD,KAAK,EAAE,MAAM,CAAA;IACb,0CAA0C;IAC1C,KAAK,EAAE,MAAM,CAAA;IACb,iCAAiC;IACjC,MAAM,EAAE,MAAM,CAAA;CACf"}
|
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.4.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",
|