@open-mercato/documents 0.10.1-develop.7709.1.046124599c → 0.10.1-develop.7715.1.9483283afa
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/dist/modules/documents/commands/comments.js +2 -2
- package/dist/modules/documents/commands/comments.js.map +2 -2
- package/dist/modules/documents/commands/interceptors.js +11 -0
- package/dist/modules/documents/commands/interceptors.js.map +2 -2
- package/dist/modules/documents/lib/permissions.js +30 -2
- package/dist/modules/documents/lib/permissions.js.map +2 -2
- package/package.json +6 -6
- package/src/modules/documents/commands/comments.ts +2 -2
- package/src/modules/documents/commands/interceptors.ts +11 -0
- package/src/modules/documents/lib/permissions.ts +43 -0
|
@@ -20,7 +20,7 @@ import {
|
|
|
20
20
|
} from "../data/validators.js";
|
|
21
21
|
import { DOCUMENTS_ENTITY_IDS } from "../lib/constants.js";
|
|
22
22
|
import { assertDocumentCommentCapacity } from "../lib/historyLimits.js";
|
|
23
|
-
import { resolveUserAccess } from "../lib/permissions.js";
|
|
23
|
+
import { resolveUserAccess, resolveUserDocumentTier } from "../lib/permissions.js";
|
|
24
24
|
import { resolveWatcherRecipients } from "../lib/watchers.js";
|
|
25
25
|
import {
|
|
26
26
|
assertDocumentCommandCapability,
|
|
@@ -462,7 +462,7 @@ const createCommentCommand = {
|
|
|
462
462
|
for (const mentionedUserId of mentionUserIds) {
|
|
463
463
|
const grantIdentity = grantIdentityByUserId.get(mentionedUserId);
|
|
464
464
|
if (!grantIdentity || !canShare) continue;
|
|
465
|
-
const tier = await
|
|
465
|
+
const tier = await resolveUserDocumentTier(em, input.documentId, input, mentionedUserId, ctx.container);
|
|
466
466
|
if (tier) continue;
|
|
467
467
|
await assertUserPrincipal(ctx.container, input, mentionedUserId);
|
|
468
468
|
let share = await loadMentionShare(em, input, mentionedUserId, true);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/documents/commands/comments.ts"],
|
|
4
|
-
"sourcesContent": ["import { LockMode } from '@mikro-orm/core'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { z } from 'zod'\nimport { registerCommand, type CommandHandler } from '@open-mercato/shared/lib/commands'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport { extractUndoPayload } from '@open-mercato/shared/lib/commands/undo'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport {\n assertOptimisticLock,\n buildOptimisticLockConflictBody,\n} from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport {\n findOneWithDecryption,\n findWithDecryption,\n} from '@open-mercato/shared/lib/encryption/find'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { Document, DocumentComment, DocumentShare } from '../data/entities'\nimport {\n documentCommentCreateSchema,\n documentSharePermissionSchema,\n} from '../data/validators'\nimport { DOCUMENTS_ENTITY_IDS } from '../lib/constants'\nimport { assertDocumentCommentCapacity } from '../lib/historyLimits'\nimport { resolveUserAccess } from '../lib/permissions'\nimport { resolveWatcherRecipients } from '../lib/watchers'\nimport type { DocumentsProjectionDescriptor } from './projection-types'\nimport {\n assertDocumentCommandCapability,\n resolveDocumentsCommandActor,\n resolveDocumentsCommandScope,\n} from './shared'\nimport { nextDocumentVersion } from './mutation-helpers'\nimport { resolveAuthPrincipalService, type DocumentsServiceContainer } from '../lib/platformServices'\n\nconst scopeSchema = z.object({\n tenantId: z.string().uuid(),\n organizationId: z.string().uuid(),\n})\n\nconst commentStateSchema = z.object({\n id: z.string().uuid(),\n existed: z.boolean(),\n parentCommentId: z.string().uuid().nullable(),\n authorUserId: z.string().uuid(),\n body: z.string(),\n // Snapshots must remain permissive for legacy anchors. New command input is\n // still validated by documentCommentCreateSchema's strict write union.\n anchor: z.record(z.string(), z.unknown()).nullable(),\n mentions: z.array(z.object({ userId: z.string().uuid() })).nullable(),\n resolvedAt: z.string().datetime().nullable(),\n resolvedByUserId: z.string().uuid().nullable(),\n deletedAt: z.string().datetime().nullable(),\n updatedAt: z.string().datetime().nullable(),\n})\n\nconst mentionShareStateSchema = z.object({\n id: z.string().uuid(),\n userId: z.string().uuid(),\n existed: z.boolean(),\n permission: documentSharePermissionSchema,\n createdByUserId: z.string().uuid(),\n deletedAt: z.string().datetime().nullable(),\n updatedAt: z.string().datetime().nullable(),\n})\n\nconst commentRedoExpectationSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('snapshot'), state: commentStateSchema }),\n z.object({ kind: z.literal('soft-deleted-created'), state: commentStateSchema }),\n])\n\nconst commentCommandBaseSchema = scopeSchema.extend({\n documentId: z.string().uuid(),\n actorUserId: z.string().uuid(),\n})\n\nexport const commentCreateCommandSchema = commentCommandBaseSchema.extend({\n commentId: z.string().uuid(),\n comment: documentCommentCreateSchema,\n grantShares: z.array(z.object({ userId: z.string().uuid(), shareId: z.string().uuid() })).max(50),\n redoExpectation: commentRedoExpectationSchema.optional(),\n}).superRefine((input, context) => {\n const grantIds = Array.from(new Set((input.comment.grantAccessTo ?? []).map((id) => id.toLowerCase())))\n const identities = Array.from(new Set(input.grantShares.map((grant) => grant.userId.toLowerCase())))\n if (grantIds.length !== identities.length || grantIds.some((id) => !identities.includes(id))) {\n context.addIssue({ code: 'custom', message: 'documents.comments.grantIdentityMismatch' })\n }\n})\n\nexport const commentResolveCommandSchema = commentCommandBaseSchema.extend({\n comment: z.object({ id: z.string().uuid(), resolved: z.boolean() }),\n expectedUpdatedAt: z.string().datetime().nullable().optional(),\n redoExpectation: commentRedoExpectationSchema.optional(),\n})\n\nexport type CommentCreateCommandInput = z.infer<typeof commentCreateCommandSchema>\nexport type CommentResolveCommandInput = z.infer<typeof commentResolveCommandSchema>\nexport type CommentState = z.infer<typeof commentStateSchema>\nexport type MentionShareState = z.infer<typeof mentionShareStateSchema>\n\nexport type CommentCreateCommandResult = {\n id: string\n updatedAt: string\n projections?: DocumentsProjectionDescriptor[]\n undo: CommentCreateUndoPayload\n}\n\nexport type CommentResolveCommandResult = {\n id: string\n resolvedAt: string | null\n resolvedByUserId: string | null\n updatedAt: string\n before: CommentState\n after: CommentState\n projections?: DocumentsProjectionDescriptor[]\n}\n\ntype MentionShareMutation = {\n before: MentionShareState\n after: MentionShareState\n}\n\ntype PendingMentionShareMutation = {\n before: MentionShareState\n share: DocumentShare\n fallback: { shareId: string; userId: string; actorUserId: string }\n}\n\ntype CommentCreateUndoPayload = {\n before?: CommentState | null\n after?: CommentState | null\n shareMutations: MentionShareMutation[]\n projectionsAfterUndo?: DocumentsProjectionDescriptor[]\n}\n\ntype CommentResolveUndoPayload = {\n before?: CommentState | null\n after?: CommentState | null\n projectionsAfterUndo?: DocumentsProjectionDescriptor[]\n}\n\nfunction extractMentionedUserIds(body: string): string[] {\n const pattern = /@\\[([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\\]/gi\n return Array.from(new Set(\n Array.from(body.matchAll(pattern))\n .map((match) => match[1])\n .filter((value): value is string => typeof value === 'string')\n .map((value) => value.toLowerCase()),\n ))\n}\n\nfunction dedupeUserIds(values: string[]): string[] {\n return Array.from(new Set(values.map((value) => value.toLowerCase())))\n}\n\nfunction commentFallback(input: CommentCreateCommandInput): Omit<CommentState, 'existed' | 'deletedAt' | 'updatedAt'> {\n const mentionUserIds = dedupeUserIds([\n ...(input.comment.mentions ?? []).map((mention) => mention.userId),\n ...extractMentionedUserIds(input.comment.body),\n ])\n return {\n id: input.commentId,\n parentCommentId: input.comment.parentCommentId ?? null,\n authorUserId: input.actorUserId,\n body: input.comment.body,\n anchor: input.comment.anchor ?? null,\n mentions: mentionUserIds.length ? mentionUserIds.map((userId) => ({ userId })) : null,\n resolvedAt: null,\n resolvedByUserId: null,\n }\n}\n\nfunction captureCommentState(\n comment: DocumentComment | null,\n fallback: Omit<CommentState, 'existed' | 'deletedAt' | 'updatedAt'>,\n): CommentState {\n return {\n id: comment?.id ?? fallback.id,\n existed: comment !== null,\n parentCommentId: comment?.parentCommentId ?? fallback.parentCommentId,\n authorUserId: comment?.authorUserId ?? fallback.authorUserId,\n body: comment?.body ?? fallback.body,\n anchor: (comment?.anchor ?? fallback.anchor) as CommentState['anchor'],\n mentions: comment?.mentions ?? fallback.mentions,\n resolvedAt: comment?.resolvedAt?.toISOString() ?? fallback.resolvedAt,\n resolvedByUserId: comment?.resolvedByUserId ?? fallback.resolvedByUserId,\n deletedAt: comment?.deletedAt?.toISOString() ?? null,\n updatedAt: comment?.updatedAt?.toISOString() ?? null,\n }\n}\n\nfunction captureMentionShareState(\n share: DocumentShare | null,\n fallback: { shareId: string; userId: string; actorUserId: string },\n): MentionShareState {\n return {\n id: share?.id ?? fallback.shareId,\n userId: share?.principalId ?? fallback.userId,\n existed: share !== null,\n permission: share?.permission ?? 'commenter',\n createdByUserId: share?.createdByUserId ?? fallback.actorUserId,\n deletedAt: share?.deletedAt?.toISOString() ?? null,\n updatedAt: share?.updatedAt?.toISOString() ?? null,\n }\n}\n\nfunction assertActor(input: { actorUserId: string }, ctx: Parameters<CommandHandler['execute']>[1]): void {\n if (resolveDocumentsCommandActor(ctx) !== input.actorUserId) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n}\n\nasync function loadLockedDocument(\n em: EntityManager,\n input: { tenantId: string; organizationId: string; documentId: string },\n): Promise<Document> {\n const document = await findOneWithDecryption(\n em,\n Document,\n {\n id: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n deletedAt: null,\n },\n { lockMode: LockMode.PESSIMISTIC_WRITE },\n { tenantId: input.tenantId, organizationId: input.organizationId },\n )\n if (!document) throw new CrudHttpError(404, { error: 'Document not found' })\n return document\n}\n\nasync function loadComment(\n em: EntityManager,\n input: { tenantId: string; organizationId: string; documentId: string },\n commentId: string,\n lock = false,\n): Promise<DocumentComment | null> {\n return findOneWithDecryption(\n em,\n DocumentComment,\n {\n id: commentId,\n documentId: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n },\n {\n filters: false,\n ...(lock ? { lockMode: LockMode.PESSIMISTIC_WRITE } : {}),\n },\n { tenantId: input.tenantId, organizationId: input.organizationId },\n )\n}\n\nasync function assertNoActiveReplies(\n em: EntityManager,\n input: { tenantId: string; organizationId: string; documentId: string },\n commentId: string,\n): Promise<void> {\n const replies = await findWithDecryption(\n em,\n DocumentComment,\n {\n documentId: input.documentId,\n parentCommentId: commentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n deletedAt: null,\n },\n { limit: 1 },\n { tenantId: input.tenantId, organizationId: input.organizationId },\n )\n if (replies.length > 0) {\n throw new CrudHttpError(409, { error: 'Record changed by another user' })\n }\n}\n\nasync function loadMentionShare(\n em: EntityManager,\n input: { tenantId: string; organizationId: string; documentId: string },\n userId: string,\n lock = false,\n): Promise<DocumentShare | null> {\n return findOneWithDecryption(\n em,\n DocumentShare,\n {\n documentId: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n principalType: 'user',\n principalId: userId,\n },\n {\n filters: false,\n orderBy: { updatedAt: 'DESC' },\n ...(lock ? { lockMode: LockMode.PESSIMISTIC_WRITE } : {}),\n },\n { tenantId: input.tenantId, organizationId: input.organizationId },\n )\n}\n\nasync function assertUserPrincipal(\n container: DocumentsServiceContainer,\n input: { tenantId: string; organizationId: string },\n userId: string,\n): Promise<void> {\n const exists = await resolveAuthPrincipalService(container)?.principalExists({\n type: 'user',\n id: userId,\n scope: { tenantId: input.tenantId, organizationId: input.organizationId },\n }) ?? false\n if (!exists) throw new CrudHttpError(400, { error: 'Share principal not found in this organization' })\n}\n\nasync function hasDocumentCapability(\n ctx: Parameters<CommandHandler['execute']>[1],\n em: EntityManager,\n input: { tenantId: string; organizationId: string; documentId: string },\n capability: 'canComment' | 'canShare',\n): Promise<boolean> {\n try {\n await assertDocumentCommandCapability(\n ctx,\n em,\n input.documentId,\n resolveDocumentsCommandScope(ctx, input),\n capability,\n )\n return true\n } catch (error) {\n if (isCrudHttpError(error) && error.status === 403) return false\n throw error\n }\n}\n\nasync function assertCanCreateComment(\n ctx: Parameters<CommandHandler['execute']>[1],\n em: EntityManager,\n input: CommentCreateCommandInput,\n): Promise<void> {\n resolveDocumentsCommandScope(ctx, input)\n if (!(await hasDocumentCapability(ctx, em, input, 'canComment'))) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n}\n\nasync function assertCanMutateMentionShares(\n ctx: Parameters<CommandHandler['execute']>[1],\n em: EntityManager,\n input: CommentCreateCommandInput,\n): Promise<void> {\n const scope = resolveDocumentsCommandScope(ctx, input)\n await assertDocumentCommandCapability(ctx, em, input.documentId, scope, 'canShare')\n}\n\nasync function assertCanResolveComment(\n ctx: Parameters<CommandHandler['execute']>[1],\n em: EntityManager,\n input: CommentResolveCommandInput,\n comment: DocumentComment,\n): Promise<void> {\n const scope = resolveDocumentsCommandScope(ctx, input)\n await assertDocumentCommandCapability(ctx, em, input.documentId, scope, 'canView')\n if (comment.authorUserId === resolveDocumentsCommandActor(ctx)) return\n if (!(await hasDocumentCapability(ctx, em, input, 'canComment'))) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n}\n\nfunction assertCommentMatchesState(\n comment: DocumentComment | null,\n expected: CommentState,\n softDeletedCreated = false,\n): void {\n if (!comment || !expected.existed) throw new CrudHttpError(409, { error: 'Record changed by another user' })\n const scalarsMatch = comment.id === expected.id\n && (comment.parentCommentId ?? null) === expected.parentCommentId\n && comment.authorUserId === expected.authorUserId\n && comment.body === expected.body\n && JSON.stringify(comment.anchor ?? null) === JSON.stringify(expected.anchor)\n && JSON.stringify(comment.mentions ?? null) === JSON.stringify(expected.mentions)\n && (comment.resolvedAt?.toISOString() ?? null) === expected.resolvedAt\n && (comment.resolvedByUserId ?? null) === expected.resolvedByUserId\n const deletedAt = comment.deletedAt?.toISOString() ?? null\n const deletionMatches = softDeletedCreated ? deletedAt !== null : deletedAt === expected.deletedAt\n if (!scalarsMatch || !deletionMatches) {\n throw new CrudHttpError(409, buildOptimisticLockConflictBody(\n comment.updatedAt.toISOString(),\n expected.updatedAt ?? comment.updatedAt.toISOString(),\n ))\n }\n}\n\nfunction assertCommentUnchanged(\n comment: DocumentComment | null,\n expected: CommentState,\n): asserts comment is DocumentComment {\n if (!comment || !expected.existed || !expected.updatedAt) {\n throw new CrudHttpError(409, { error: 'Record changed by another user' })\n }\n assertOptimisticLock({\n resourceKind: DOCUMENTS_ENTITY_IDS.documentComment,\n resourceId: expected.id,\n current: comment.updatedAt,\n expected: expected.updatedAt,\n envValue: 'all',\n })\n assertCommentMatchesState(comment, expected)\n}\n\nfunction assertMentionShareUnchanged(share: DocumentShare | null, expected: MentionShareState): asserts share is DocumentShare {\n if (!share || !expected.existed || !expected.updatedAt) {\n throw new CrudHttpError(409, { error: 'Record changed by another user' })\n }\n assertOptimisticLock({\n resourceKind: DOCUMENTS_ENTITY_IDS.documentShare,\n resourceId: expected.id,\n current: share.updatedAt,\n expected: expected.updatedAt,\n envValue: 'all',\n })\n if (\n share.id !== expected.id\n || share.principalType !== 'user'\n || share.principalId !== expected.userId\n || share.permission !== expected.permission\n || share.createdByUserId !== expected.createdByUserId\n || (share.deletedAt?.toISOString() ?? null) !== expected.deletedAt\n ) {\n throw new CrudHttpError(409, { error: 'Record changed by another user' })\n }\n}\n\nfunction restoreCommentState(comment: DocumentComment, before: CommentState): void {\n const now = nextDocumentVersion(comment.updatedAt)\n if (!before.existed) {\n comment.deletedAt = now\n comment.updatedAt = now\n return\n }\n comment.parentCommentId = before.parentCommentId\n comment.authorUserId = before.authorUserId\n comment.body = before.body\n comment.anchor = before.anchor\n comment.mentions = before.mentions\n comment.resolvedAt = before.resolvedAt ? new Date(before.resolvedAt) : null\n comment.resolvedByUserId = before.resolvedByUserId\n comment.deletedAt = before.deletedAt ? new Date(before.deletedAt) : null\n comment.updatedAt = now\n}\n\nfunction restoreMentionShareState(share: DocumentShare, before: MentionShareState): void {\n const now = nextDocumentVersion(share.updatedAt)\n if (!before.existed) {\n share.deletedAt = now\n share.updatedAt = now\n return\n }\n share.permission = before.permission\n share.createdByUserId = before.createdByUserId\n share.deletedAt = before.deletedAt ? new Date(before.deletedAt) : null\n share.updatedAt = now\n}\n\nfunction shareProjection(\n eventId: 'documents.document.shared' | 'documents.document.unshared',\n input: CommentCreateCommandInput,\n state: MentionShareState,\n includeActor = true,\n): DocumentsProjectionDescriptor {\n return {\n kind: 'event',\n eventId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n payload: {\n id: input.documentId,\n shareId: state.id,\n principalType: 'user',\n principalId: state.userId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n ...(includeActor ? { userId: input.actorUserId } : {}),\n },\n }\n}\n\nfunction resolutionProjection(\n input: CommentResolveCommandInput,\n state: CommentState,\n includeActor = true,\n): DocumentsProjectionDescriptor {\n return {\n kind: 'event',\n eventId: 'documents.comment.resolved',\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n payload: {\n id: state.id,\n documentId: input.documentId,\n resolved: state.resolvedAt !== null,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n ...(includeActor ? { userId: input.actorUserId } : {}),\n },\n }\n}\n\nfunction mentionProjections(\n input: CommentCreateCommandInput,\n document: Document,\n mentionedUserIds: string[],\n): DocumentsProjectionDescriptor[] {\n return mentionedUserIds.flatMap((recipientUserId): DocumentsProjectionDescriptor[] => [\n {\n kind: 'event',\n eventId: 'documents.comment.mentioned',\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n payload: {\n id: input.commentId,\n documentId: input.documentId,\n mentionedUserId: recipientUserId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n userId: input.actorUserId,\n },\n },\n {\n kind: 'mention-notification',\n recipientUserId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n documentId: input.documentId,\n documentTitle: document.title,\n commentId: input.commentId,\n authorUserId: input.actorUserId,\n },\n ])\n}\n\nfunction watchCommentProjections(\n input: { tenantId: string; organizationId: string; documentId: string; commentId: string },\n documentTitle: string,\n recipientUserIds: readonly string[],\n bodyKey: string,\n): DocumentsProjectionDescriptor[] {\n return recipientUserIds.map((recipientUserId) => ({\n kind: 'watch-notification',\n recipientUserId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n documentId: input.documentId,\n documentTitle,\n notificationType: 'documents.watch.commented',\n bodyKey,\n sourceEntityType: DOCUMENTS_ENTITY_IDS.documentComment,\n sourceEntityId: input.commentId,\n linkHref: `/backend/documents/${encodeURIComponent(input.documentId)}?commentId=${encodeURIComponent(input.commentId)}`,\n }))\n}\n\nfunction commentCreatedProjection(\n input: CommentCreateCommandInput,\n): DocumentsProjectionDescriptor {\n return {\n kind: 'event',\n eventId: 'documents.comment.created',\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n payload: {\n id: input.commentId,\n documentId: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n userId: input.actorUserId,\n },\n }\n}\n\nfunction readRedoInput<T>(logEntry: { commandPayload?: unknown }, schema: z.ZodType<T>): T {\n const raw = logEntry.commandPayload && typeof logEntry.commandPayload === 'object'\n ? (logEntry.commandPayload as { __redoInput?: unknown }).__redoInput\n : null\n return schema.parse(raw)\n}\n\nexport const createCommentCommand: CommandHandler<CommentCreateCommandInput, CommentCreateCommandResult> = {\n id: 'documents.comment.create',\n async prepare(rawInput, ctx) {\n const input = commentCreateCommandSchema.parse(rawInput)\n assertActor(input, ctx)\n const em = ctx.container.resolve('em') as EntityManager\n await assertCanCreateComment(ctx, em, input)\n return null\n },\n async execute(rawInput, ctx) {\n const input = commentCreateCommandSchema.parse(rawInput)\n const em = ctx.transactionalEm ?? (ctx.container.resolve('em') as EntityManager).fork()\n const fallback = commentFallback(input)\n const mentionUserIds = fallback.mentions?.map((mention) => mention.userId) ?? []\n const grantIdentityByUserId = new Map(input.grantShares.map((grant) => [grant.userId.toLowerCase(), grant]))\n const shareMutations: MentionShareMutation[] = []\n const pendingShareMutations: PendingMentionShareMutation[] = []\n const notifyMentionedIds: string[] = []\n let document: Document | null = null\n let comment: DocumentComment | null = null\n let before: CommentState | null = null\n let after: CommentState | null = null\n await withAtomicFlush(em, [async () => {\n document = await loadLockedDocument(em, input)\n assertActor(input, ctx)\n await assertCanCreateComment(ctx, em, input)\n comment = await loadComment(em, input, input.commentId, true)\n if (input.redoExpectation) {\n assertCommentMatchesState(\n comment,\n input.redoExpectation.state,\n input.redoExpectation.kind === 'soft-deleted-created',\n )\n } else if (comment) {\n throw new CrudHttpError(409, { error: 'Record changed by another user' })\n }\n before = captureCommentState(comment, fallback)\n if (fallback.parentCommentId) {\n const parent = await loadComment(em, input, fallback.parentCommentId, true)\n if (!parent || parent.deletedAt) throw new CrudHttpError(404, { error: 'Comment not found' })\n }\n await assertDocumentCommentCapacity(em, input)\n\n const canShare = await hasDocumentCapability(ctx, em, input, 'canShare')\n // An explicit grant request from an actor without the share capability\n // must fail loudly instead of returning 201 with the grants silently\n // dropped. Redo replays are exempt: their grants either already exist\n // (mentioned users resolve a tier below) or were legitimately created\n // by the original execution.\n if (input.grantShares.length > 0 && !canShare && !input.redoExpectation) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n for (const mentionedUserId of mentionUserIds) {\n const grantIdentity = grantIdentityByUserId.get(mentionedUserId)\n if (!grantIdentity || !canShare) continue\n const tier = await resolveUserAccess(em, input.documentId, input, mentionedUserId, ctx.container)\n if (tier) continue\n await assertUserPrincipal(ctx.container, input, mentionedUserId)\n let share = await loadMentionShare(em, input, mentionedUserId, true)\n const shareFallback = {\n shareId: share?.id ?? grantIdentity.shareId,\n userId: mentionedUserId,\n actorUserId: input.actorUserId,\n }\n const shareBefore = captureMentionShareState(share, shareFallback)\n const created = !share\n share = share ?? em.create(DocumentShare, {\n id: grantIdentity.shareId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n documentId: input.documentId,\n principalType: 'user',\n principalId: mentionedUserId,\n permission: 'commenter',\n createdByUserId: input.actorUserId,\n })\n share.permission = 'commenter'\n share.deletedAt = null\n share.updatedAt = nextDocumentVersion(share.updatedAt)\n if (created) em.persist(share)\n pendingShareMutations.push({ before: shareBefore, share, fallback: shareFallback })\n }\n\n const created = !comment\n comment = comment ?? em.create(DocumentComment, {\n id: input.commentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n documentId: input.documentId,\n parentCommentId: fallback.parentCommentId,\n authorUserId: fallback.authorUserId,\n body: fallback.body,\n anchor: fallback.anchor,\n mentions: fallback.mentions,\n })\n comment.parentCommentId = fallback.parentCommentId\n comment.authorUserId = fallback.authorUserId\n comment.body = fallback.body\n comment.anchor = fallback.anchor\n comment.mentions = fallback.mentions\n comment.resolvedAt = null\n comment.resolvedByUserId = null\n comment.deletedAt = null\n comment.updatedAt = nextDocumentVersion(comment.updatedAt)\n if (created) em.persist(comment)\n }, async () => {\n after = captureCommentState(comment, fallback)\n for (const mutation of pendingShareMutations) {\n shareMutations.push({\n before: mutation.before,\n after: captureMentionShareState(mutation.share, mutation.fallback),\n })\n }\n for (const mentionedUserId of mentionUserIds) {\n const tier = await resolveUserAccess(em, input.documentId, input, mentionedUserId, ctx.container)\n if (tier) notifyMentionedIds.push(mentionedUserId)\n }\n }], { transaction: true, label: 'documents.comment.create' })\n\n const finalDocument = document as Document | null\n const finalComment = comment as DocumentComment | null\n const beforeState = before as CommentState | null\n if (!finalDocument || !finalComment || !beforeState) {\n throw new Error('[internal] comment create produced no row')\n }\n const afterState = after as CommentState | null\n if (!afterState) throw new Error('[internal] comment create produced no after snapshot')\n const watcherRecipientIds = await resolveWatcherRecipients({\n em,\n container: ctx.container,\n scope: { tenantId: input.tenantId, organizationId: input.organizationId },\n documentId: input.documentId,\n actorUserId: input.actorUserId,\n excludeUserIds: notifyMentionedIds,\n })\n const projections = [\n commentCreatedProjection(input),\n ...shareMutations.map((mutation) => shareProjection('documents.document.shared', input, mutation.after)),\n ...mentionProjections(input, finalDocument, notifyMentionedIds),\n ...watchCommentProjections(\n { ...input, commentId: input.commentId },\n finalDocument.title,\n watcherRecipientIds,\n 'documents.notifications.watch.commented.body',\n ),\n ]\n const projectionsAfterUndo: DocumentsProjectionDescriptor[] = [\n ...shareMutations.map((mutation) => shareProjection(\n mutation.before.existed && mutation.before.deletedAt === null\n ? 'documents.document.shared'\n : 'documents.document.unshared',\n input,\n mutation.before,\n false,\n )),\n {\n kind: 'mention-notification-delete',\n commentId: input.commentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n },\n ]\n return {\n id: finalComment.id,\n updatedAt: finalComment.updatedAt.toISOString(),\n projections,\n undo: { before: beforeState, after: afterState, shareMutations, projectionsAfterUndo },\n }\n },\n async buildLog({ input, result }) {\n const before = commentStateSchema.parse(result.undo.before)\n const after = commentStateSchema.parse(result.undo.after)\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('documents.audit.commentCreated', 'Add comment'),\n resourceKind: DOCUMENTS_ENTITY_IDS.documentComment,\n resourceId: result.id,\n parentResourceKind: DOCUMENTS_ENTITY_IDS.document,\n parentResourceId: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n payload: {\n undo: result.undo,\n __redoInput: {\n ...input,\n redoExpectation: before.existed\n ? { kind: 'snapshot', state: before }\n : { kind: 'soft-deleted-created', state: after },\n } satisfies CommentCreateCommandInput,\n },\n }\n },\n async undo({ logEntry, ctx }) {\n const undo = extractUndoPayload<CommentCreateUndoPayload>(logEntry)\n if (!undo?.before || !undo.after) return\n const input = readRedoInput(logEntry, commentCreateCommandSchema)\n const em = ctx.transactionalEm ?? (ctx.container.resolve('em') as EntityManager).fork()\n await withAtomicFlush(em, [async () => {\n await loadLockedDocument(em, input)\n if (undo.shareMutations.length > 0) {\n await assertCanMutateMentionShares(ctx, em, input)\n }\n const comment = await loadComment(em, input, undo.after!.id, true)\n if (!comment) throw new CrudHttpError(409, { error: 'Record changed by another user' })\n await assertCanResolveComment(ctx, em, {\n ...input,\n comment: { id: comment.id, resolved: false },\n expectedUpdatedAt: null,\n }, comment)\n assertCommentUnchanged(comment, undo.after!)\n await assertNoActiveReplies(em, input, comment.id)\n for (const mutation of undo.shareMutations) {\n const share = await loadMentionShare(em, input, mutation.after.userId, true)\n assertMentionShareUnchanged(share, mutation.after)\n restoreMentionShareState(share, mutation.before)\n }\n restoreCommentState(comment, undo.before!)\n }], { transaction: true, label: 'documents.comment.create.undo' })\n },\n}\n\nexport const resolveCommentCommand: CommandHandler<CommentResolveCommandInput, CommentResolveCommandResult> = {\n id: 'documents.comment.resolve',\n async prepare(rawInput, ctx) {\n const input = commentResolveCommandSchema.parse(rawInput)\n assertActor(input, ctx)\n const em = ctx.container.resolve('em') as EntityManager\n const comment = await loadComment(em, input, input.comment.id)\n if (!comment || comment.deletedAt) throw new CrudHttpError(404, { error: 'Comment not found' })\n await assertCanResolveComment(ctx, em, input, comment)\n return null\n },\n async execute(rawInput, ctx) {\n const input = commentResolveCommandSchema.parse(rawInput)\n const em = ctx.transactionalEm ?? (ctx.container.resolve('em') as EntityManager).fork()\n let comment: DocumentComment | null = null\n let before: CommentState | null = null\n let after: CommentState | null = null\n await withAtomicFlush(em, [async () => {\n await loadLockedDocument(em, input)\n assertActor(input, ctx)\n comment = await loadComment(em, input, input.comment.id, true)\n if (!comment || comment.deletedAt) throw new CrudHttpError(404, { error: 'Comment not found' })\n await assertCanResolveComment(ctx, em, input, comment)\n if (input.redoExpectation) {\n assertCommentMatchesState(comment, input.redoExpectation.state)\n } else {\n assertOptimisticLock({\n resourceKind: DOCUMENTS_ENTITY_IDS.documentComment,\n resourceId: comment.id,\n current: comment.updatedAt,\n expected: input.expectedUpdatedAt,\n })\n }\n before = captureCommentState(comment, {\n id: comment.id,\n parentCommentId: comment.parentCommentId ?? null,\n authorUserId: comment.authorUserId,\n body: comment.body,\n anchor: comment.anchor as CommentState['anchor'],\n mentions: comment.mentions ?? null,\n resolvedAt: comment.resolvedAt?.toISOString() ?? null,\n resolvedByUserId: comment.resolvedByUserId ?? null,\n })\n const now = new Date()\n ;(comment as DocumentComment).resolvedAt = input.comment.resolved ? now : null\n ;(comment as DocumentComment).resolvedByUserId = input.comment.resolved ? input.actorUserId : null\n ;(comment as DocumentComment).updatedAt = nextDocumentVersion(\n (comment as DocumentComment).updatedAt,\n now,\n )\n }, async () => {\n const finalComment = comment as DocumentComment | null\n if (!finalComment) throw new Error('[internal] comment resolve produced no row')\n after = captureCommentState(finalComment, {\n id: finalComment.id,\n parentCommentId: finalComment.parentCommentId ?? null,\n authorUserId: finalComment.authorUserId,\n body: finalComment.body,\n anchor: finalComment.anchor as CommentState['anchor'],\n mentions: finalComment.mentions ?? null,\n resolvedAt: finalComment.resolvedAt?.toISOString() ?? null,\n resolvedByUserId: finalComment.resolvedByUserId ?? null,\n })\n }], { transaction: true, label: 'documents.comment.resolve' })\n const finalComment = comment as DocumentComment | null\n const beforeState = before as CommentState | null\n const afterState = after as CommentState | null\n if (!finalComment || !beforeState || !afterState) throw new Error('[internal] comment resolve produced no row')\n const resolvedDocument = await findOneWithDecryption(\n em,\n Document,\n {\n id: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n deletedAt: null,\n },\n { fields: ['id', 'title'] },\n { tenantId: input.tenantId, organizationId: input.organizationId },\n )\n const watcherRecipientIds = resolvedDocument\n ? await resolveWatcherRecipients({\n em,\n container: ctx.container,\n scope: { tenantId: input.tenantId, organizationId: input.organizationId },\n documentId: input.documentId,\n actorUserId: input.actorUserId,\n })\n : []\n return {\n id: finalComment.id,\n resolvedAt: afterState.resolvedAt,\n resolvedByUserId: afterState.resolvedByUserId,\n updatedAt: finalComment.updatedAt.toISOString(),\n before: beforeState,\n after: afterState,\n projections: [\n resolutionProjection(input, afterState),\n ...(resolvedDocument\n ? watchCommentProjections(\n { ...input, commentId: finalComment.id },\n resolvedDocument.title,\n watcherRecipientIds,\n 'documents.notifications.watch.commented.resolvedBody',\n )\n : []),\n ],\n }\n },\n async buildLog({ input, result }) {\n const before = commentStateSchema.parse(result.before)\n const after = commentStateSchema.parse(result.after)\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('documents.audit.commentResolved', 'Resolve comment'),\n resourceKind: DOCUMENTS_ENTITY_IDS.documentComment,\n resourceId: result.id,\n parentResourceKind: DOCUMENTS_ENTITY_IDS.document,\n parentResourceId: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n payload: {\n undo: {\n before,\n after,\n projectionsAfterUndo: [resolutionProjection(input, before, false)],\n } satisfies CommentResolveUndoPayload,\n __redoInput: {\n ...input,\n expectedUpdatedAt: null,\n redoExpectation: { kind: 'snapshot', state: before },\n } satisfies CommentResolveCommandInput,\n },\n }\n },\n async undo({ logEntry, ctx }) {\n const undo = extractUndoPayload<CommentResolveUndoPayload>(logEntry)\n if (!undo?.before || !undo.after) return\n const input = readRedoInput(logEntry, commentResolveCommandSchema)\n const em = ctx.transactionalEm ?? (ctx.container.resolve('em') as EntityManager).fork()\n await withAtomicFlush(em, [async () => {\n await loadLockedDocument(em, input)\n const comment = await loadComment(em, input, undo.after!.id, true)\n if (!comment) throw new CrudHttpError(409, { error: 'Record changed by another user' })\n await assertCanResolveComment(ctx, em, input, comment)\n assertCommentUnchanged(comment, undo.after!)\n restoreCommentState(comment, undo.before!)\n }], { transaction: true, label: 'documents.comment.resolve.undo' })\n },\n}\n\nregisterCommand(createCommentCommand)\nregisterCommand(resolveCommentCommand)\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,gBAAgB;AAEzB,SAAS,SAAS;AAClB,SAAS,uBAA4C;AACrD,SAAS,uBAAuB;AAChC,SAAS,0BAA0B;AACnC,SAAS,eAAe,uBAAuB;AAC/C;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,UAAU,iBAAiB,qBAAqB;AACzD;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,4BAA4B;AACrC,SAAS,qCAAqC;AAC9C,SAAS,yBAA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U,CAAC,KAAK,MAAO;AAClC,UAAM,QAAQ,cAAc,UAAU,2BAA2B;AACjE,UAAM,KAAK,IAAI,mBAAoB,IAAI,UAAU,QAAQ,IAAI,EAAoB,KAAK;AACtF,UAAM,gBAAgB,IAAI,CAAC,YAAY;AACrC,YAAM,mBAAmB,IAAI,KAAK;AAClC,YAAM,UAAU,MAAM,YAAY,IAAI,OAAO,KAAK,MAAO,IAAI,IAAI;AACjE,UAAI,CAAC,QAAS,OAAM,IAAI,cAAc,KAAK,EAAE,OAAO,iCAAiC,CAAC;AACtF,YAAM,wBAAwB,KAAK,IAAI,OAAO,OAAO;AACrD,6BAAuB,SAAS,KAAK,KAAM;AAC3C,0BAAoB,SAAS,KAAK,MAAO;AAAA,IAC3C,CAAC,GAAG,EAAE,aAAa,MAAM,OAAO,iCAAiC,CAAC;AAAA,EACpE;AACF;AAEA,gBAAgB,oBAAoB;AACpC,gBAAgB,qBAAqB;",
|
|
4
|
+
"sourcesContent": ["import { LockMode } from '@mikro-orm/core'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { z } from 'zod'\nimport { registerCommand, type CommandHandler } from '@open-mercato/shared/lib/commands'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport { extractUndoPayload } from '@open-mercato/shared/lib/commands/undo'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport {\n assertOptimisticLock,\n buildOptimisticLockConflictBody,\n} from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport {\n findOneWithDecryption,\n findWithDecryption,\n} from '@open-mercato/shared/lib/encryption/find'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { Document, DocumentComment, DocumentShare } from '../data/entities'\nimport {\n documentCommentCreateSchema,\n documentSharePermissionSchema,\n} from '../data/validators'\nimport { DOCUMENTS_ENTITY_IDS } from '../lib/constants'\nimport { assertDocumentCommentCapacity } from '../lib/historyLimits'\nimport { resolveUserAccess, resolveUserDocumentTier } from '../lib/permissions'\nimport { resolveWatcherRecipients } from '../lib/watchers'\nimport type { DocumentsProjectionDescriptor } from './projection-types'\nimport {\n assertDocumentCommandCapability,\n resolveDocumentsCommandActor,\n resolveDocumentsCommandScope,\n} from './shared'\nimport { nextDocumentVersion } from './mutation-helpers'\nimport { resolveAuthPrincipalService, type DocumentsServiceContainer } from '../lib/platformServices'\n\nconst scopeSchema = z.object({\n tenantId: z.string().uuid(),\n organizationId: z.string().uuid(),\n})\n\nconst commentStateSchema = z.object({\n id: z.string().uuid(),\n existed: z.boolean(),\n parentCommentId: z.string().uuid().nullable(),\n authorUserId: z.string().uuid(),\n body: z.string(),\n // Snapshots must remain permissive for legacy anchors. New command input is\n // still validated by documentCommentCreateSchema's strict write union.\n anchor: z.record(z.string(), z.unknown()).nullable(),\n mentions: z.array(z.object({ userId: z.string().uuid() })).nullable(),\n resolvedAt: z.string().datetime().nullable(),\n resolvedByUserId: z.string().uuid().nullable(),\n deletedAt: z.string().datetime().nullable(),\n updatedAt: z.string().datetime().nullable(),\n})\n\nconst mentionShareStateSchema = z.object({\n id: z.string().uuid(),\n userId: z.string().uuid(),\n existed: z.boolean(),\n permission: documentSharePermissionSchema,\n createdByUserId: z.string().uuid(),\n deletedAt: z.string().datetime().nullable(),\n updatedAt: z.string().datetime().nullable(),\n})\n\nconst commentRedoExpectationSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('snapshot'), state: commentStateSchema }),\n z.object({ kind: z.literal('soft-deleted-created'), state: commentStateSchema }),\n])\n\nconst commentCommandBaseSchema = scopeSchema.extend({\n documentId: z.string().uuid(),\n actorUserId: z.string().uuid(),\n})\n\nexport const commentCreateCommandSchema = commentCommandBaseSchema.extend({\n commentId: z.string().uuid(),\n comment: documentCommentCreateSchema,\n grantShares: z.array(z.object({ userId: z.string().uuid(), shareId: z.string().uuid() })).max(50),\n redoExpectation: commentRedoExpectationSchema.optional(),\n}).superRefine((input, context) => {\n const grantIds = Array.from(new Set((input.comment.grantAccessTo ?? []).map((id) => id.toLowerCase())))\n const identities = Array.from(new Set(input.grantShares.map((grant) => grant.userId.toLowerCase())))\n if (grantIds.length !== identities.length || grantIds.some((id) => !identities.includes(id))) {\n context.addIssue({ code: 'custom', message: 'documents.comments.grantIdentityMismatch' })\n }\n})\n\nexport const commentResolveCommandSchema = commentCommandBaseSchema.extend({\n comment: z.object({ id: z.string().uuid(), resolved: z.boolean() }),\n expectedUpdatedAt: z.string().datetime().nullable().optional(),\n redoExpectation: commentRedoExpectationSchema.optional(),\n})\n\nexport type CommentCreateCommandInput = z.infer<typeof commentCreateCommandSchema>\nexport type CommentResolveCommandInput = z.infer<typeof commentResolveCommandSchema>\nexport type CommentState = z.infer<typeof commentStateSchema>\nexport type MentionShareState = z.infer<typeof mentionShareStateSchema>\n\nexport type CommentCreateCommandResult = {\n id: string\n updatedAt: string\n projections?: DocumentsProjectionDescriptor[]\n undo: CommentCreateUndoPayload\n}\n\nexport type CommentResolveCommandResult = {\n id: string\n resolvedAt: string | null\n resolvedByUserId: string | null\n updatedAt: string\n before: CommentState\n after: CommentState\n projections?: DocumentsProjectionDescriptor[]\n}\n\ntype MentionShareMutation = {\n before: MentionShareState\n after: MentionShareState\n}\n\ntype PendingMentionShareMutation = {\n before: MentionShareState\n share: DocumentShare\n fallback: { shareId: string; userId: string; actorUserId: string }\n}\n\ntype CommentCreateUndoPayload = {\n before?: CommentState | null\n after?: CommentState | null\n shareMutations: MentionShareMutation[]\n projectionsAfterUndo?: DocumentsProjectionDescriptor[]\n}\n\ntype CommentResolveUndoPayload = {\n before?: CommentState | null\n after?: CommentState | null\n projectionsAfterUndo?: DocumentsProjectionDescriptor[]\n}\n\nfunction extractMentionedUserIds(body: string): string[] {\n const pattern = /@\\[([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\\]/gi\n return Array.from(new Set(\n Array.from(body.matchAll(pattern))\n .map((match) => match[1])\n .filter((value): value is string => typeof value === 'string')\n .map((value) => value.toLowerCase()),\n ))\n}\n\nfunction dedupeUserIds(values: string[]): string[] {\n return Array.from(new Set(values.map((value) => value.toLowerCase())))\n}\n\nfunction commentFallback(input: CommentCreateCommandInput): Omit<CommentState, 'existed' | 'deletedAt' | 'updatedAt'> {\n const mentionUserIds = dedupeUserIds([\n ...(input.comment.mentions ?? []).map((mention) => mention.userId),\n ...extractMentionedUserIds(input.comment.body),\n ])\n return {\n id: input.commentId,\n parentCommentId: input.comment.parentCommentId ?? null,\n authorUserId: input.actorUserId,\n body: input.comment.body,\n anchor: input.comment.anchor ?? null,\n mentions: mentionUserIds.length ? mentionUserIds.map((userId) => ({ userId })) : null,\n resolvedAt: null,\n resolvedByUserId: null,\n }\n}\n\nfunction captureCommentState(\n comment: DocumentComment | null,\n fallback: Omit<CommentState, 'existed' | 'deletedAt' | 'updatedAt'>,\n): CommentState {\n return {\n id: comment?.id ?? fallback.id,\n existed: comment !== null,\n parentCommentId: comment?.parentCommentId ?? fallback.parentCommentId,\n authorUserId: comment?.authorUserId ?? fallback.authorUserId,\n body: comment?.body ?? fallback.body,\n anchor: (comment?.anchor ?? fallback.anchor) as CommentState['anchor'],\n mentions: comment?.mentions ?? fallback.mentions,\n resolvedAt: comment?.resolvedAt?.toISOString() ?? fallback.resolvedAt,\n resolvedByUserId: comment?.resolvedByUserId ?? fallback.resolvedByUserId,\n deletedAt: comment?.deletedAt?.toISOString() ?? null,\n updatedAt: comment?.updatedAt?.toISOString() ?? null,\n }\n}\n\nfunction captureMentionShareState(\n share: DocumentShare | null,\n fallback: { shareId: string; userId: string; actorUserId: string },\n): MentionShareState {\n return {\n id: share?.id ?? fallback.shareId,\n userId: share?.principalId ?? fallback.userId,\n existed: share !== null,\n permission: share?.permission ?? 'commenter',\n createdByUserId: share?.createdByUserId ?? fallback.actorUserId,\n deletedAt: share?.deletedAt?.toISOString() ?? null,\n updatedAt: share?.updatedAt?.toISOString() ?? null,\n }\n}\n\nfunction assertActor(input: { actorUserId: string }, ctx: Parameters<CommandHandler['execute']>[1]): void {\n if (resolveDocumentsCommandActor(ctx) !== input.actorUserId) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n}\n\nasync function loadLockedDocument(\n em: EntityManager,\n input: { tenantId: string; organizationId: string; documentId: string },\n): Promise<Document> {\n const document = await findOneWithDecryption(\n em,\n Document,\n {\n id: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n deletedAt: null,\n },\n { lockMode: LockMode.PESSIMISTIC_WRITE },\n { tenantId: input.tenantId, organizationId: input.organizationId },\n )\n if (!document) throw new CrudHttpError(404, { error: 'Document not found' })\n return document\n}\n\nasync function loadComment(\n em: EntityManager,\n input: { tenantId: string; organizationId: string; documentId: string },\n commentId: string,\n lock = false,\n): Promise<DocumentComment | null> {\n return findOneWithDecryption(\n em,\n DocumentComment,\n {\n id: commentId,\n documentId: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n },\n {\n filters: false,\n ...(lock ? { lockMode: LockMode.PESSIMISTIC_WRITE } : {}),\n },\n { tenantId: input.tenantId, organizationId: input.organizationId },\n )\n}\n\nasync function assertNoActiveReplies(\n em: EntityManager,\n input: { tenantId: string; organizationId: string; documentId: string },\n commentId: string,\n): Promise<void> {\n const replies = await findWithDecryption(\n em,\n DocumentComment,\n {\n documentId: input.documentId,\n parentCommentId: commentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n deletedAt: null,\n },\n { limit: 1 },\n { tenantId: input.tenantId, organizationId: input.organizationId },\n )\n if (replies.length > 0) {\n throw new CrudHttpError(409, { error: 'Record changed by another user' })\n }\n}\n\nasync function loadMentionShare(\n em: EntityManager,\n input: { tenantId: string; organizationId: string; documentId: string },\n userId: string,\n lock = false,\n): Promise<DocumentShare | null> {\n return findOneWithDecryption(\n em,\n DocumentShare,\n {\n documentId: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n principalType: 'user',\n principalId: userId,\n },\n {\n filters: false,\n orderBy: { updatedAt: 'DESC' },\n ...(lock ? { lockMode: LockMode.PESSIMISTIC_WRITE } : {}),\n },\n { tenantId: input.tenantId, organizationId: input.organizationId },\n )\n}\n\nasync function assertUserPrincipal(\n container: DocumentsServiceContainer,\n input: { tenantId: string; organizationId: string },\n userId: string,\n): Promise<void> {\n const exists = await resolveAuthPrincipalService(container)?.principalExists({\n type: 'user',\n id: userId,\n scope: { tenantId: input.tenantId, organizationId: input.organizationId },\n }) ?? false\n if (!exists) throw new CrudHttpError(400, { error: 'Share principal not found in this organization' })\n}\n\nasync function hasDocumentCapability(\n ctx: Parameters<CommandHandler['execute']>[1],\n em: EntityManager,\n input: { tenantId: string; organizationId: string; documentId: string },\n capability: 'canComment' | 'canShare',\n): Promise<boolean> {\n try {\n await assertDocumentCommandCapability(\n ctx,\n em,\n input.documentId,\n resolveDocumentsCommandScope(ctx, input),\n capability,\n )\n return true\n } catch (error) {\n if (isCrudHttpError(error) && error.status === 403) return false\n throw error\n }\n}\n\nasync function assertCanCreateComment(\n ctx: Parameters<CommandHandler['execute']>[1],\n em: EntityManager,\n input: CommentCreateCommandInput,\n): Promise<void> {\n resolveDocumentsCommandScope(ctx, input)\n if (!(await hasDocumentCapability(ctx, em, input, 'canComment'))) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n}\n\nasync function assertCanMutateMentionShares(\n ctx: Parameters<CommandHandler['execute']>[1],\n em: EntityManager,\n input: CommentCreateCommandInput,\n): Promise<void> {\n const scope = resolveDocumentsCommandScope(ctx, input)\n await assertDocumentCommandCapability(ctx, em, input.documentId, scope, 'canShare')\n}\n\nasync function assertCanResolveComment(\n ctx: Parameters<CommandHandler['execute']>[1],\n em: EntityManager,\n input: CommentResolveCommandInput,\n comment: DocumentComment,\n): Promise<void> {\n const scope = resolveDocumentsCommandScope(ctx, input)\n await assertDocumentCommandCapability(ctx, em, input.documentId, scope, 'canView')\n if (comment.authorUserId === resolveDocumentsCommandActor(ctx)) return\n if (!(await hasDocumentCapability(ctx, em, input, 'canComment'))) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n}\n\nfunction assertCommentMatchesState(\n comment: DocumentComment | null,\n expected: CommentState,\n softDeletedCreated = false,\n): void {\n if (!comment || !expected.existed) throw new CrudHttpError(409, { error: 'Record changed by another user' })\n const scalarsMatch = comment.id === expected.id\n && (comment.parentCommentId ?? null) === expected.parentCommentId\n && comment.authorUserId === expected.authorUserId\n && comment.body === expected.body\n && JSON.stringify(comment.anchor ?? null) === JSON.stringify(expected.anchor)\n && JSON.stringify(comment.mentions ?? null) === JSON.stringify(expected.mentions)\n && (comment.resolvedAt?.toISOString() ?? null) === expected.resolvedAt\n && (comment.resolvedByUserId ?? null) === expected.resolvedByUserId\n const deletedAt = comment.deletedAt?.toISOString() ?? null\n const deletionMatches = softDeletedCreated ? deletedAt !== null : deletedAt === expected.deletedAt\n if (!scalarsMatch || !deletionMatches) {\n throw new CrudHttpError(409, buildOptimisticLockConflictBody(\n comment.updatedAt.toISOString(),\n expected.updatedAt ?? comment.updatedAt.toISOString(),\n ))\n }\n}\n\nfunction assertCommentUnchanged(\n comment: DocumentComment | null,\n expected: CommentState,\n): asserts comment is DocumentComment {\n if (!comment || !expected.existed || !expected.updatedAt) {\n throw new CrudHttpError(409, { error: 'Record changed by another user' })\n }\n assertOptimisticLock({\n resourceKind: DOCUMENTS_ENTITY_IDS.documentComment,\n resourceId: expected.id,\n current: comment.updatedAt,\n expected: expected.updatedAt,\n envValue: 'all',\n })\n assertCommentMatchesState(comment, expected)\n}\n\nfunction assertMentionShareUnchanged(share: DocumentShare | null, expected: MentionShareState): asserts share is DocumentShare {\n if (!share || !expected.existed || !expected.updatedAt) {\n throw new CrudHttpError(409, { error: 'Record changed by another user' })\n }\n assertOptimisticLock({\n resourceKind: DOCUMENTS_ENTITY_IDS.documentShare,\n resourceId: expected.id,\n current: share.updatedAt,\n expected: expected.updatedAt,\n envValue: 'all',\n })\n if (\n share.id !== expected.id\n || share.principalType !== 'user'\n || share.principalId !== expected.userId\n || share.permission !== expected.permission\n || share.createdByUserId !== expected.createdByUserId\n || (share.deletedAt?.toISOString() ?? null) !== expected.deletedAt\n ) {\n throw new CrudHttpError(409, { error: 'Record changed by another user' })\n }\n}\n\nfunction restoreCommentState(comment: DocumentComment, before: CommentState): void {\n const now = nextDocumentVersion(comment.updatedAt)\n if (!before.existed) {\n comment.deletedAt = now\n comment.updatedAt = now\n return\n }\n comment.parentCommentId = before.parentCommentId\n comment.authorUserId = before.authorUserId\n comment.body = before.body\n comment.anchor = before.anchor\n comment.mentions = before.mentions\n comment.resolvedAt = before.resolvedAt ? new Date(before.resolvedAt) : null\n comment.resolvedByUserId = before.resolvedByUserId\n comment.deletedAt = before.deletedAt ? new Date(before.deletedAt) : null\n comment.updatedAt = now\n}\n\nfunction restoreMentionShareState(share: DocumentShare, before: MentionShareState): void {\n const now = nextDocumentVersion(share.updatedAt)\n if (!before.existed) {\n share.deletedAt = now\n share.updatedAt = now\n return\n }\n share.permission = before.permission\n share.createdByUserId = before.createdByUserId\n share.deletedAt = before.deletedAt ? new Date(before.deletedAt) : null\n share.updatedAt = now\n}\n\nfunction shareProjection(\n eventId: 'documents.document.shared' | 'documents.document.unshared',\n input: CommentCreateCommandInput,\n state: MentionShareState,\n includeActor = true,\n): DocumentsProjectionDescriptor {\n return {\n kind: 'event',\n eventId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n payload: {\n id: input.documentId,\n shareId: state.id,\n principalType: 'user',\n principalId: state.userId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n ...(includeActor ? { userId: input.actorUserId } : {}),\n },\n }\n}\n\nfunction resolutionProjection(\n input: CommentResolveCommandInput,\n state: CommentState,\n includeActor = true,\n): DocumentsProjectionDescriptor {\n return {\n kind: 'event',\n eventId: 'documents.comment.resolved',\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n payload: {\n id: state.id,\n documentId: input.documentId,\n resolved: state.resolvedAt !== null,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n ...(includeActor ? { userId: input.actorUserId } : {}),\n },\n }\n}\n\nfunction mentionProjections(\n input: CommentCreateCommandInput,\n document: Document,\n mentionedUserIds: string[],\n): DocumentsProjectionDescriptor[] {\n return mentionedUserIds.flatMap((recipientUserId): DocumentsProjectionDescriptor[] => [\n {\n kind: 'event',\n eventId: 'documents.comment.mentioned',\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n payload: {\n id: input.commentId,\n documentId: input.documentId,\n mentionedUserId: recipientUserId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n userId: input.actorUserId,\n },\n },\n {\n kind: 'mention-notification',\n recipientUserId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n documentId: input.documentId,\n documentTitle: document.title,\n commentId: input.commentId,\n authorUserId: input.actorUserId,\n },\n ])\n}\n\nfunction watchCommentProjections(\n input: { tenantId: string; organizationId: string; documentId: string; commentId: string },\n documentTitle: string,\n recipientUserIds: readonly string[],\n bodyKey: string,\n): DocumentsProjectionDescriptor[] {\n return recipientUserIds.map((recipientUserId) => ({\n kind: 'watch-notification',\n recipientUserId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n documentId: input.documentId,\n documentTitle,\n notificationType: 'documents.watch.commented',\n bodyKey,\n sourceEntityType: DOCUMENTS_ENTITY_IDS.documentComment,\n sourceEntityId: input.commentId,\n linkHref: `/backend/documents/${encodeURIComponent(input.documentId)}?commentId=${encodeURIComponent(input.commentId)}`,\n }))\n}\n\nfunction commentCreatedProjection(\n input: CommentCreateCommandInput,\n): DocumentsProjectionDescriptor {\n return {\n kind: 'event',\n eventId: 'documents.comment.created',\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n payload: {\n id: input.commentId,\n documentId: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n userId: input.actorUserId,\n },\n }\n}\n\nfunction readRedoInput<T>(logEntry: { commandPayload?: unknown }, schema: z.ZodType<T>): T {\n const raw = logEntry.commandPayload && typeof logEntry.commandPayload === 'object'\n ? (logEntry.commandPayload as { __redoInput?: unknown }).__redoInput\n : null\n return schema.parse(raw)\n}\n\nexport const createCommentCommand: CommandHandler<CommentCreateCommandInput, CommentCreateCommandResult> = {\n id: 'documents.comment.create',\n async prepare(rawInput, ctx) {\n const input = commentCreateCommandSchema.parse(rawInput)\n assertActor(input, ctx)\n const em = ctx.container.resolve('em') as EntityManager\n await assertCanCreateComment(ctx, em, input)\n return null\n },\n async execute(rawInput, ctx) {\n const input = commentCreateCommandSchema.parse(rawInput)\n const em = ctx.transactionalEm ?? (ctx.container.resolve('em') as EntityManager).fork()\n const fallback = commentFallback(input)\n const mentionUserIds = fallback.mentions?.map((mention) => mention.userId) ?? []\n const grantIdentityByUserId = new Map(input.grantShares.map((grant) => [grant.userId.toLowerCase(), grant]))\n const shareMutations: MentionShareMutation[] = []\n const pendingShareMutations: PendingMentionShareMutation[] = []\n const notifyMentionedIds: string[] = []\n let document: Document | null = null\n let comment: DocumentComment | null = null\n let before: CommentState | null = null\n let after: CommentState | null = null\n await withAtomicFlush(em, [async () => {\n document = await loadLockedDocument(em, input)\n assertActor(input, ctx)\n await assertCanCreateComment(ctx, em, input)\n comment = await loadComment(em, input, input.commentId, true)\n if (input.redoExpectation) {\n assertCommentMatchesState(\n comment,\n input.redoExpectation.state,\n input.redoExpectation.kind === 'soft-deleted-created',\n )\n } else if (comment) {\n throw new CrudHttpError(409, { error: 'Record changed by another user' })\n }\n before = captureCommentState(comment, fallback)\n if (fallback.parentCommentId) {\n const parent = await loadComment(em, input, fallback.parentCommentId, true)\n if (!parent || parent.deletedAt) throw new CrudHttpError(404, { error: 'Comment not found' })\n }\n await assertDocumentCommentCapacity(em, input)\n\n const canShare = await hasDocumentCapability(ctx, em, input, 'canShare')\n // An explicit grant request from an actor without the share capability\n // must fail loudly instead of returning 201 with the grants silently\n // dropped. Redo replays are exempt: their grants either already exist\n // (mentioned users resolve a tier below) or were legitimately created\n // by the original execution.\n if (input.grantShares.length > 0 && !canShare && !input.redoExpectation) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n for (const mentionedUserId of mentionUserIds) {\n const grantIdentity = grantIdentityByUserId.get(mentionedUserId)\n if (!grantIdentity || !canShare) continue\n const tier = await resolveUserDocumentTier(em, input.documentId, input, mentionedUserId, ctx.container)\n if (tier) continue\n await assertUserPrincipal(ctx.container, input, mentionedUserId)\n let share = await loadMentionShare(em, input, mentionedUserId, true)\n const shareFallback = {\n shareId: share?.id ?? grantIdentity.shareId,\n userId: mentionedUserId,\n actorUserId: input.actorUserId,\n }\n const shareBefore = captureMentionShareState(share, shareFallback)\n const created = !share\n share = share ?? em.create(DocumentShare, {\n id: grantIdentity.shareId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n documentId: input.documentId,\n principalType: 'user',\n principalId: mentionedUserId,\n permission: 'commenter',\n createdByUserId: input.actorUserId,\n })\n share.permission = 'commenter'\n share.deletedAt = null\n share.updatedAt = nextDocumentVersion(share.updatedAt)\n if (created) em.persist(share)\n pendingShareMutations.push({ before: shareBefore, share, fallback: shareFallback })\n }\n\n const created = !comment\n comment = comment ?? em.create(DocumentComment, {\n id: input.commentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n documentId: input.documentId,\n parentCommentId: fallback.parentCommentId,\n authorUserId: fallback.authorUserId,\n body: fallback.body,\n anchor: fallback.anchor,\n mentions: fallback.mentions,\n })\n comment.parentCommentId = fallback.parentCommentId\n comment.authorUserId = fallback.authorUserId\n comment.body = fallback.body\n comment.anchor = fallback.anchor\n comment.mentions = fallback.mentions\n comment.resolvedAt = null\n comment.resolvedByUserId = null\n comment.deletedAt = null\n comment.updatedAt = nextDocumentVersion(comment.updatedAt)\n if (created) em.persist(comment)\n }, async () => {\n after = captureCommentState(comment, fallback)\n for (const mutation of pendingShareMutations) {\n shareMutations.push({\n before: mutation.before,\n after: captureMentionShareState(mutation.share, mutation.fallback),\n })\n }\n for (const mentionedUserId of mentionUserIds) {\n const tier = await resolveUserAccess(em, input.documentId, input, mentionedUserId, ctx.container)\n if (tier) notifyMentionedIds.push(mentionedUserId)\n }\n }], { transaction: true, label: 'documents.comment.create' })\n\n const finalDocument = document as Document | null\n const finalComment = comment as DocumentComment | null\n const beforeState = before as CommentState | null\n if (!finalDocument || !finalComment || !beforeState) {\n throw new Error('[internal] comment create produced no row')\n }\n const afterState = after as CommentState | null\n if (!afterState) throw new Error('[internal] comment create produced no after snapshot')\n const watcherRecipientIds = await resolveWatcherRecipients({\n em,\n container: ctx.container,\n scope: { tenantId: input.tenantId, organizationId: input.organizationId },\n documentId: input.documentId,\n actorUserId: input.actorUserId,\n excludeUserIds: notifyMentionedIds,\n })\n const projections = [\n commentCreatedProjection(input),\n ...shareMutations.map((mutation) => shareProjection('documents.document.shared', input, mutation.after)),\n ...mentionProjections(input, finalDocument, notifyMentionedIds),\n ...watchCommentProjections(\n { ...input, commentId: input.commentId },\n finalDocument.title,\n watcherRecipientIds,\n 'documents.notifications.watch.commented.body',\n ),\n ]\n const projectionsAfterUndo: DocumentsProjectionDescriptor[] = [\n ...shareMutations.map((mutation) => shareProjection(\n mutation.before.existed && mutation.before.deletedAt === null\n ? 'documents.document.shared'\n : 'documents.document.unshared',\n input,\n mutation.before,\n false,\n )),\n {\n kind: 'mention-notification-delete',\n commentId: input.commentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n },\n ]\n return {\n id: finalComment.id,\n updatedAt: finalComment.updatedAt.toISOString(),\n projections,\n undo: { before: beforeState, after: afterState, shareMutations, projectionsAfterUndo },\n }\n },\n async buildLog({ input, result }) {\n const before = commentStateSchema.parse(result.undo.before)\n const after = commentStateSchema.parse(result.undo.after)\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('documents.audit.commentCreated', 'Add comment'),\n resourceKind: DOCUMENTS_ENTITY_IDS.documentComment,\n resourceId: result.id,\n parentResourceKind: DOCUMENTS_ENTITY_IDS.document,\n parentResourceId: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n payload: {\n undo: result.undo,\n __redoInput: {\n ...input,\n redoExpectation: before.existed\n ? { kind: 'snapshot', state: before }\n : { kind: 'soft-deleted-created', state: after },\n } satisfies CommentCreateCommandInput,\n },\n }\n },\n async undo({ logEntry, ctx }) {\n const undo = extractUndoPayload<CommentCreateUndoPayload>(logEntry)\n if (!undo?.before || !undo.after) return\n const input = readRedoInput(logEntry, commentCreateCommandSchema)\n const em = ctx.transactionalEm ?? (ctx.container.resolve('em') as EntityManager).fork()\n await withAtomicFlush(em, [async () => {\n await loadLockedDocument(em, input)\n if (undo.shareMutations.length > 0) {\n await assertCanMutateMentionShares(ctx, em, input)\n }\n const comment = await loadComment(em, input, undo.after!.id, true)\n if (!comment) throw new CrudHttpError(409, { error: 'Record changed by another user' })\n await assertCanResolveComment(ctx, em, {\n ...input,\n comment: { id: comment.id, resolved: false },\n expectedUpdatedAt: null,\n }, comment)\n assertCommentUnchanged(comment, undo.after!)\n await assertNoActiveReplies(em, input, comment.id)\n for (const mutation of undo.shareMutations) {\n const share = await loadMentionShare(em, input, mutation.after.userId, true)\n assertMentionShareUnchanged(share, mutation.after)\n restoreMentionShareState(share, mutation.before)\n }\n restoreCommentState(comment, undo.before!)\n }], { transaction: true, label: 'documents.comment.create.undo' })\n },\n}\n\nexport const resolveCommentCommand: CommandHandler<CommentResolveCommandInput, CommentResolveCommandResult> = {\n id: 'documents.comment.resolve',\n async prepare(rawInput, ctx) {\n const input = commentResolveCommandSchema.parse(rawInput)\n assertActor(input, ctx)\n const em = ctx.container.resolve('em') as EntityManager\n const comment = await loadComment(em, input, input.comment.id)\n if (!comment || comment.deletedAt) throw new CrudHttpError(404, { error: 'Comment not found' })\n await assertCanResolveComment(ctx, em, input, comment)\n return null\n },\n async execute(rawInput, ctx) {\n const input = commentResolveCommandSchema.parse(rawInput)\n const em = ctx.transactionalEm ?? (ctx.container.resolve('em') as EntityManager).fork()\n let comment: DocumentComment | null = null\n let before: CommentState | null = null\n let after: CommentState | null = null\n await withAtomicFlush(em, [async () => {\n await loadLockedDocument(em, input)\n assertActor(input, ctx)\n comment = await loadComment(em, input, input.comment.id, true)\n if (!comment || comment.deletedAt) throw new CrudHttpError(404, { error: 'Comment not found' })\n await assertCanResolveComment(ctx, em, input, comment)\n if (input.redoExpectation) {\n assertCommentMatchesState(comment, input.redoExpectation.state)\n } else {\n assertOptimisticLock({\n resourceKind: DOCUMENTS_ENTITY_IDS.documentComment,\n resourceId: comment.id,\n current: comment.updatedAt,\n expected: input.expectedUpdatedAt,\n })\n }\n before = captureCommentState(comment, {\n id: comment.id,\n parentCommentId: comment.parentCommentId ?? null,\n authorUserId: comment.authorUserId,\n body: comment.body,\n anchor: comment.anchor as CommentState['anchor'],\n mentions: comment.mentions ?? null,\n resolvedAt: comment.resolvedAt?.toISOString() ?? null,\n resolvedByUserId: comment.resolvedByUserId ?? null,\n })\n const now = new Date()\n ;(comment as DocumentComment).resolvedAt = input.comment.resolved ? now : null\n ;(comment as DocumentComment).resolvedByUserId = input.comment.resolved ? input.actorUserId : null\n ;(comment as DocumentComment).updatedAt = nextDocumentVersion(\n (comment as DocumentComment).updatedAt,\n now,\n )\n }, async () => {\n const finalComment = comment as DocumentComment | null\n if (!finalComment) throw new Error('[internal] comment resolve produced no row')\n after = captureCommentState(finalComment, {\n id: finalComment.id,\n parentCommentId: finalComment.parentCommentId ?? null,\n authorUserId: finalComment.authorUserId,\n body: finalComment.body,\n anchor: finalComment.anchor as CommentState['anchor'],\n mentions: finalComment.mentions ?? null,\n resolvedAt: finalComment.resolvedAt?.toISOString() ?? null,\n resolvedByUserId: finalComment.resolvedByUserId ?? null,\n })\n }], { transaction: true, label: 'documents.comment.resolve' })\n const finalComment = comment as DocumentComment | null\n const beforeState = before as CommentState | null\n const afterState = after as CommentState | null\n if (!finalComment || !beforeState || !afterState) throw new Error('[internal] comment resolve produced no row')\n const resolvedDocument = await findOneWithDecryption(\n em,\n Document,\n {\n id: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n deletedAt: null,\n },\n { fields: ['id', 'title'] },\n { tenantId: input.tenantId, organizationId: input.organizationId },\n )\n const watcherRecipientIds = resolvedDocument\n ? await resolveWatcherRecipients({\n em,\n container: ctx.container,\n scope: { tenantId: input.tenantId, organizationId: input.organizationId },\n documentId: input.documentId,\n actorUserId: input.actorUserId,\n })\n : []\n return {\n id: finalComment.id,\n resolvedAt: afterState.resolvedAt,\n resolvedByUserId: afterState.resolvedByUserId,\n updatedAt: finalComment.updatedAt.toISOString(),\n before: beforeState,\n after: afterState,\n projections: [\n resolutionProjection(input, afterState),\n ...(resolvedDocument\n ? watchCommentProjections(\n { ...input, commentId: finalComment.id },\n resolvedDocument.title,\n watcherRecipientIds,\n 'documents.notifications.watch.commented.resolvedBody',\n )\n : []),\n ],\n }\n },\n async buildLog({ input, result }) {\n const before = commentStateSchema.parse(result.before)\n const after = commentStateSchema.parse(result.after)\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('documents.audit.commentResolved', 'Resolve comment'),\n resourceKind: DOCUMENTS_ENTITY_IDS.documentComment,\n resourceId: result.id,\n parentResourceKind: DOCUMENTS_ENTITY_IDS.document,\n parentResourceId: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n payload: {\n undo: {\n before,\n after,\n projectionsAfterUndo: [resolutionProjection(input, before, false)],\n } satisfies CommentResolveUndoPayload,\n __redoInput: {\n ...input,\n expectedUpdatedAt: null,\n redoExpectation: { kind: 'snapshot', state: before },\n } satisfies CommentResolveCommandInput,\n },\n }\n },\n async undo({ logEntry, ctx }) {\n const undo = extractUndoPayload<CommentResolveUndoPayload>(logEntry)\n if (!undo?.before || !undo.after) return\n const input = readRedoInput(logEntry, commentResolveCommandSchema)\n const em = ctx.transactionalEm ?? (ctx.container.resolve('em') as EntityManager).fork()\n await withAtomicFlush(em, [async () => {\n await loadLockedDocument(em, input)\n const comment = await loadComment(em, input, undo.after!.id, true)\n if (!comment) throw new CrudHttpError(409, { error: 'Record changed by another user' })\n await assertCanResolveComment(ctx, em, input, comment)\n assertCommentUnchanged(comment, undo.after!)\n restoreCommentState(comment, undo.before!)\n }], { transaction: true, label: 'documents.comment.resolve.undo' })\n },\n}\n\nregisterCommand(createCommentCommand)\nregisterCommand(resolveCommentCommand)\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,gBAAgB;AAEzB,SAAS,SAAS;AAClB,SAAS,uBAA4C;AACrD,SAAS,uBAAuB;AAChC,SAAS,0BAA0B;AACnC,SAAS,eAAe,uBAAuB;AAC/C;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,UAAU,iBAAiB,qBAAqB;AACzD;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,4BAA4B;AACrC,SAAS,qCAAqC;AAC9C,SAAS,mBAAmB,+BAA+B;AAC3D,SAAS,gCAAgC;AAEzC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,mCAAmE;AAE5E,MAAM,cAAc,EAAE,OAAO;AAAA,EAC3B,UAAU,EAAE,OAAO,EAAE,KAAK;AAAA,EAC1B,gBAAgB,EAAE,OAAO,EAAE,KAAK;AAClC,CAAC;AAED,MAAM,qBAAqB,EAAE,OAAO;AAAA,EAClC,IAAI,EAAE,OAAO,EAAE,KAAK;AAAA,EACpB,SAAS,EAAE,QAAQ;AAAA,EACnB,iBAAiB,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AAAA,EAC5C,cAAc,EAAE,OAAO,EAAE,KAAK;AAAA,EAC9B,MAAM,EAAE,OAAO;AAAA;AAAA;AAAA,EAGf,QAAQ,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,EAAE,SAAS;AAAA,EACnD,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,OAA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 +4,7 @@ import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find"
|
|
|
4
4
|
import { createLogger } from "@open-mercato/shared/lib/logger";
|
|
5
5
|
import { Document } from "../data/entities.js";
|
|
6
6
|
import { DOCUMENTS_ENTITY_IDS } from "../lib/constants.js";
|
|
7
|
+
import { resolveUserAccess } from "../lib/permissions.js";
|
|
7
8
|
import { resolveWatcherRecipients } from "../lib/watchers.js";
|
|
8
9
|
import { emitDocumentsEvent } from "../events.js";
|
|
9
10
|
const logger = createLogger("documents").child({ component: "command-projections" });
|
|
@@ -53,6 +54,11 @@ async function emitProjectedEvent(descriptor, context, options = {}) {
|
|
|
53
54
|
async function emitMentionProjection(descriptor, context) {
|
|
54
55
|
try {
|
|
55
56
|
const notificationService = resolveDocumentsNotificationService(context.container);
|
|
57
|
+
const em = context.container.resolve("em");
|
|
58
|
+
if (!await resolveUserAccess(em, descriptor.documentId, {
|
|
59
|
+
tenantId: descriptor.tenantId,
|
|
60
|
+
organizationId: descriptor.organizationId
|
|
61
|
+
}, descriptor.recipientUserId, context.container)) return;
|
|
56
62
|
await notificationService.create(
|
|
57
63
|
{
|
|
58
64
|
recipientUserId: descriptor.recipientUserId,
|
|
@@ -90,6 +96,11 @@ const WATCH_NOTIFICATION_TITLE_KEYS = {
|
|
|
90
96
|
async function emitWatchProjection(descriptor, context) {
|
|
91
97
|
try {
|
|
92
98
|
const notificationService = resolveDocumentsNotificationService(context.container);
|
|
99
|
+
const em = context.container.resolve("em");
|
|
100
|
+
if (!await resolveUserAccess(em, descriptor.documentId, {
|
|
101
|
+
tenantId: descriptor.tenantId,
|
|
102
|
+
organizationId: descriptor.organizationId
|
|
103
|
+
}, descriptor.recipientUserId, context.container)) return;
|
|
93
104
|
await notificationService.create(
|
|
94
105
|
{
|
|
95
106
|
recipientUserId: descriptor.recipientUserId,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/documents/commands/interceptors.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type {\n CommandInterceptor,\n CommandInterceptorContext,\n CommandInterceptorUndoContext,\n} from '@open-mercato/shared/lib/commands/command-interceptor'\nimport { extractUndoPayload } from '@open-mercato/shared/lib/commands/undo'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { Document } from '../data/entities'\nimport { DOCUMENTS_ENTITY_IDS } from '../lib/constants'\nimport { resolveWatcherRecipients } from '../lib/watchers'\nimport type { DocumentsServiceContainer } from '../lib/platformServices'\nimport { emitDocumentsEvent } from '../events'\nimport type {\n DocumentsProjectedCommandResult,\n DocumentsProjectionDescriptor,\n DocumentsProjectionUndoPayload,\n} from './projection-types'\n\nconst logger = createLogger('documents').child({ component: 'command-projections' })\n\nconst PROJECTED_COMMAND_IDS = [\n 'documents.content.replace',\n 'documents.share.create',\n 'documents.share.update',\n 'documents.share.delete',\n 'documents.comment.create',\n 'documents.comment.resolve',\n 'documents.version.restore',\n 'documents.document.archive',\n 'documents.document.unarchive',\n 'documents.document.duplicate',\n] as const\n\ntype DocumentsNotificationService = {\n create: (\n input: Record<string, unknown>,\n scope: { tenantId: string; organizationId: string },\n ) => Promise<unknown>\n deleteBySource: (\n sourceEntityType: string,\n sourceEntityId: string,\n scope: { tenantId: string; organizationId: string },\n ) => Promise<unknown>\n}\n\nfunction resolveDocumentsNotificationService(\n container: CommandInterceptorContext['container'],\n): DocumentsNotificationService {\n const service = container.resolve('notificationService') as Partial<DocumentsNotificationService> | null\n if (!service || typeof service.create !== 'function' || typeof service.deleteBySource !== 'function') {\n throw new Error('[internal] Notification service is unavailable')\n }\n return service as DocumentsNotificationService\n}\n\nfunction readResultProjections(result: unknown): DocumentsProjectionDescriptor[] {\n if (!result || typeof result !== 'object' || Array.isArray(result)) return []\n const projections = (result as DocumentsProjectedCommandResult).projections\n return Array.isArray(projections) ? projections : []\n}\n\nasync function emitProjectedEvent(\n descriptor: Extract<DocumentsProjectionDescriptor, { kind: 'event' }>,\n context: CommandInterceptorContext,\n options: { overrideActor?: boolean } = {},\n): Promise<void> {\n const currentActorUserId = context.auth?.userId ?? context.auth?.sub ?? null\n const payload = {\n ...descriptor.payload,\n ...(currentActorUserId && (options.overrideActor || !('userId' in descriptor.payload))\n ? { userId: currentActorUserId }\n : {}),\n }\n try {\n await emitDocumentsEvent(descriptor.eventId, payload, {\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n })\n } catch (error) {\n logger.error('Command event projection failed', {\n commandId: context.commandId,\n eventId: descriptor.eventId,\n err: error,\n })\n }\n}\n\nasync function emitMentionProjection(\n descriptor: Extract<DocumentsProjectionDescriptor, { kind: 'mention-notification' }>,\n context: CommandInterceptorContext,\n): Promise<void> {\n try {\n const notificationService = resolveDocumentsNotificationService(context.container)\n await notificationService.create(\n {\n recipientUserId: descriptor.recipientUserId,\n type: 'documents.comment.mentioned',\n titleKey: 'documents.notifications.comment.mentioned.title',\n bodyKey: 'documents.notifications.comment.mentioned.body',\n severity: 'info',\n titleVariables: { documentTitle: descriptor.documentTitle },\n bodyVariables: {\n documentTitle: descriptor.documentTitle,\n authorUserId: descriptor.authorUserId,\n },\n sourceEntityType: DOCUMENTS_ENTITY_IDS.documentComment,\n sourceEntityId: descriptor.commentId,\n linkHref: `/backend/documents/${encodeURIComponent(descriptor.documentId)}?commentId=${encodeURIComponent(descriptor.commentId)}`,\n },\n {\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n },\n )\n } catch (error) {\n logger.error('Mention notification projection failed', {\n commandId: context.commandId,\n commentId: descriptor.commentId,\n recipientUserId: descriptor.recipientUserId,\n err: error,\n })\n }\n}\n\nconst WATCH_NOTIFICATION_TITLE_KEYS: Record<string, string> = {\n 'documents.watch.commented': 'documents.notifications.watch.commented.title',\n 'documents.watch.changed': 'documents.notifications.watch.changed.title',\n}\n\nasync function emitWatchProjection(\n descriptor: Extract<DocumentsProjectionDescriptor, { kind: 'watch-notification' }>,\n context: CommandInterceptorContext,\n): Promise<void> {\n try {\n const notificationService = resolveDocumentsNotificationService(context.container)\n await notificationService.create(\n {\n recipientUserId: descriptor.recipientUserId,\n type: descriptor.notificationType,\n titleKey: WATCH_NOTIFICATION_TITLE_KEYS[descriptor.notificationType],\n bodyKey: descriptor.bodyKey,\n severity: 'info',\n titleVariables: { documentTitle: descriptor.documentTitle },\n bodyVariables: { documentTitle: descriptor.documentTitle },\n sourceEntityType: descriptor.sourceEntityType,\n sourceEntityId: descriptor.sourceEntityId,\n linkHref: descriptor.linkHref,\n },\n {\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n },\n )\n } catch (error) {\n logger.error('Watch notification projection failed', {\n commandId: context.commandId,\n documentId: descriptor.documentId,\n recipientUserId: descriptor.recipientUserId,\n err: error,\n })\n }\n}\n\nasync function emitWatchFanoutProjection(\n descriptor: Extract<DocumentsProjectionDescriptor, { kind: 'watch-notification-fanout' }>,\n context: CommandInterceptorContext,\n): Promise<void> {\n try {\n const em = context.container.resolve('em') as EntityManager\n const scope = { tenantId: descriptor.tenantId, organizationId: descriptor.organizationId }\n const document = await findOneWithDecryption(\n em,\n Document,\n { id: descriptor.documentId, tenantId: scope.tenantId, organizationId: scope.organizationId, deletedAt: null },\n { fields: ['id', 'title'] },\n scope,\n )\n if (!document) return\n const recipientUserIds = await resolveWatcherRecipients({\n em,\n container: context.container as unknown as DocumentsServiceContainer,\n scope,\n documentId: descriptor.documentId,\n actorUserId: context.auth?.userId ?? context.auth?.sub ?? descriptor.actorUserId,\n })\n for (const recipientUserId of recipientUserIds) {\n await emitWatchProjection(\n {\n kind: 'watch-notification',\n recipientUserId,\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n documentId: descriptor.documentId,\n documentTitle: document.title,\n notificationType: descriptor.notificationType,\n bodyKey: descriptor.bodyKey,\n sourceEntityType: descriptor.sourceEntityType,\n sourceEntityId: descriptor.sourceEntityId,\n linkHref: descriptor.linkHref,\n },\n context,\n )\n }\n } catch (error) {\n logger.error('Watch notification fanout projection failed', {\n commandId: context.commandId,\n documentId: descriptor.documentId,\n err: error,\n })\n }\n}\n\nasync function emitDocumentIndexProjection(\n descriptor: Extract<DocumentsProjectionDescriptor, { kind: 'document-index' }>,\n context: CommandInterceptorContext,\n): Promise<void> {\n try {\n const searchIndexer = context.container.resolve('searchIndexer') as {\n indexRecordById: (input: {\n entityId: string\n recordId: string\n tenantId: string\n organizationId: string\n }) => Promise<unknown>\n }\n await searchIndexer.indexRecordById({\n entityId: DOCUMENTS_ENTITY_IDS.document,\n recordId: descriptor.documentId,\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n })\n } catch (error) {\n logger.error('Document index projection failed', {\n commandId: context.commandId,\n documentId: descriptor.documentId,\n err: error,\n })\n }\n}\n\nasync function deleteMentionNotificationProjection(\n descriptor: Extract<DocumentsProjectionDescriptor, { kind: 'mention-notification-delete' }>,\n context: CommandInterceptorContext,\n): Promise<void> {\n try {\n const notificationService = resolveDocumentsNotificationService(context.container)\n await notificationService.deleteBySource(\n DOCUMENTS_ENTITY_IDS.documentComment,\n descriptor.commentId,\n {\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n },\n )\n } catch (error) {\n logger.error('Mention notification cleanup projection failed', {\n commandId: context.commandId,\n commentId: descriptor.commentId,\n err: error,\n })\n }\n}\n\nasync function projectDescriptors(\n projections: readonly DocumentsProjectionDescriptor[],\n context: CommandInterceptorContext,\n options: { overrideEventActor?: boolean } = {},\n): Promise<void> {\n for (const projection of projections) {\n if (projection.kind === 'event') {\n await emitProjectedEvent(projection, context, { overrideActor: options.overrideEventActor })\n }\n else if (projection.kind === 'mention-notification') await emitMentionProjection(projection, context)\n else if (projection.kind === 'watch-notification') await emitWatchProjection(projection, context)\n else if (projection.kind === 'watch-notification-fanout') await emitWatchFanoutProjection(projection, context)\n else if (projection.kind === 'document-index') await emitDocumentIndexProjection(projection, context)\n else await deleteMentionNotificationProjection(projection, context)\n }\n}\n\nfunction buildProjectionInterceptor(commandId: typeof PROJECTED_COMMAND_IDS[number]): CommandInterceptor {\n return {\n id: `documents.${commandId.slice('documents.'.length).replaceAll('.', '-')}-projections`,\n targetCommand: commandId,\n priority: 90,\n async afterExecute(_input, result, context): Promise<void> {\n await projectDescriptors(readResultProjections(result), context)\n },\n async afterUndo(\n undoContext: CommandInterceptorUndoContext,\n context: CommandInterceptorContext,\n ): Promise<void> {\n const undo = extractUndoPayload<DocumentsProjectionUndoPayload>(\n undoContext.logEntry as Parameters<typeof extractUndoPayload>[0],\n )\n await projectDescriptors(\n undo?.projectionsAfterUndo ?? [],\n context,\n { overrideEventActor: true },\n )\n },\n }\n}\n\nconst ARCHIVED_UNDO_GUARDED_COMMAND_IDS = [\n 'documents.document.update',\n 'documents.share.create',\n 'documents.share.update',\n 'documents.share.delete',\n 'documents.comment.create',\n 'documents.comment.resolve',\n 'documents.link.create',\n 'documents.link.delete',\n 'documents.version.restore',\n] as const\n\ntype UndoLogEntryShape = {\n resourceKind?: string | null\n resourceId?: string | null\n parentResourceKind?: string | null\n parentResourceId?: string | null\n tenantId?: string | null\n organizationId?: string | null\n commandPayload?: unknown\n}\n\nfunction resolveUndoDocumentId(logEntry: UndoLogEntryShape): string | null {\n if (logEntry.parentResourceKind === DOCUMENTS_ENTITY_IDS.document && logEntry.parentResourceId) {\n return logEntry.parentResourceId\n }\n if (logEntry.resourceKind === DOCUMENTS_ENTITY_IDS.document && logEntry.resourceId) {\n return logEntry.resourceId\n }\n const payload = logEntry.commandPayload\n if (payload && typeof payload === 'object') {\n const redoInput = (payload as { __redoInput?: unknown }).__redoInput\n if (redoInput && typeof redoInput === 'object') {\n const documentId = (redoInput as { documentId?: unknown }).documentId\n if (typeof documentId === 'string' && documentId.length > 0) return documentId\n }\n }\n return null\n}\n\n/**\n * Read-only means the undo path too: reversing a pre-archive share, comment,\n * link, or restore would mutate an archived document, so the guard refuses\n * with the same error the execute path uses. Delete-like undos (duplicate,\n * instantiate) stay allowed, matching delete-of-archived semantics.\n */\nfunction buildArchivedUndoGuard(commandId: typeof ARCHIVED_UNDO_GUARDED_COMMAND_IDS[number]): CommandInterceptor {\n return {\n id: `documents.${commandId.slice('documents.'.length).replaceAll('.', '-')}-archived-undo-guard`,\n targetCommand: commandId,\n priority: 100,\n async beforeUndo(\n undoContext: CommandInterceptorUndoContext,\n context: CommandInterceptorContext,\n ): Promise<void> {\n const logEntry = undoContext.logEntry as UndoLogEntryShape\n const documentId = resolveUndoDocumentId(logEntry)\n if (!documentId || !logEntry.tenantId || !logEntry.organizationId) {\n // Every guarded command records the document and its scope. Without\n // them the archived state cannot be read, so refuse the undo instead of\n // waving through a mutation this guard was unable to check.\n logger.error('Archived-undo guard could not resolve the guarded document scope', {\n commandId,\n resourceKind: logEntry.resourceKind ?? null,\n resourceId: logEntry.resourceId ?? null,\n })\n throw new CrudHttpError(403, { error: 'api.errors.forbidden' })\n }\n const em = context.container.resolve('em') as EntityManager\n const scope = { tenantId: logEntry.tenantId, organizationId: logEntry.organizationId }\n const document = await findOneWithDecryption(\n em,\n Document,\n { id: documentId, tenantId: scope.tenantId, organizationId: scope.organizationId },\n { fields: ['id', 'archivedAt'], filters: false },\n scope,\n )\n if (document?.archivedAt) {\n throw new CrudHttpError(403, { error: 'documents.errors.documentArchived' })\n }\n },\n }\n}\n\n/**\n * Projection hooks are deliberately post-command. CommandBus persists the\n * ActionLog (or marks it undone) before these hooks run, so a flaky event bus\n * or notification store can never roll back an acknowledged document write.\n */\nexport const interceptors: CommandInterceptor[] = [\n ...PROJECTED_COMMAND_IDS.map(buildProjectionInterceptor),\n ...ARCHIVED_UNDO_GUARDED_COMMAND_IDS.map(buildArchivedUndoGuard),\n]\n\nexport default interceptors\n"],
|
|
5
|
-
"mappings": "AAMA,SAAS,0BAA0B;AACnC,SAAS,qBAAqB;A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KAAK,GAAG,CAAC;AAAA,IAC1E,eAAe;AAAA,IACf,UAAU;AAAA,IACV,MAAM,WACJ,aACA,SACe;AACf,YAAM,WAAW,YAAY;AAC7B,YAAM,aAAa,sBAAsB,QAAQ;AACjD,UAAI,CAAC,cAAc,CAAC,SAAS,YAAY,CAAC,SAAS,gBAAgB;AAIjE,eAAO,MAAM,oEAAoE;AAAA,UAC/E;AAAA,UACA,cAAc,SAAS,gBAAgB;AAAA,UACvC,YAAY,SAAS,cAAc;AAAA,QACrC,CAAC;AACD,cAAM,IAAI,cAAc,KAAK,EAAE,OAAO,uBAAuB,CAAC;AAAA,MAChE;AACA,YAAM,KAAK,QAAQ,UAAU,QAAQ,IAAI;AACzC,YAAM,QAAQ,EAAE,UAAU,SAAS,UAAU,gBAAgB,SAAS,eAAe;AACrF,YAAM,WAAW,MAAM;AAAA,QACrB;AAAA,QACA;AAAA,QACA,EAAE,IAAI,YAAY,UAAU,MAAM,UAAU,gBAAgB,MAAM,eAAe;AAAA,QACjF,EAAE,QAAQ,CAAC,MAAM,YAAY,GAAG,SAAS,MAAM;AAAA,QAC/C;AAAA,MACF;AACA,UAAI,UAAU,YAAY;AACxB,cAAM,IAAI,cAAc,KAAK,EAAE,OAAO,oCAAoC,CAAC;AAAA,MAC7E;AAAA,IACF;AAAA,EACF;AACF;AAOO,MAAM,eAAqC;AAAA,EAChD,GAAG,sBAAsB,IAAI,0BAA0B;AAAA,EACvD,GAAG,kCAAkC,IAAI,sBAAsB;AACjE;AAEA,IAAO,uBAAQ;",
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type {\n CommandInterceptor,\n CommandInterceptorContext,\n CommandInterceptorUndoContext,\n} from '@open-mercato/shared/lib/commands/command-interceptor'\nimport { extractUndoPayload } from '@open-mercato/shared/lib/commands/undo'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { Document } from '../data/entities'\nimport { DOCUMENTS_ENTITY_IDS } from '../lib/constants'\nimport { resolveUserAccess } from '../lib/permissions'\nimport { resolveWatcherRecipients } from '../lib/watchers'\nimport type { DocumentsServiceContainer } from '../lib/platformServices'\nimport { emitDocumentsEvent } from '../events'\nimport type {\n DocumentsProjectedCommandResult,\n DocumentsProjectionDescriptor,\n DocumentsProjectionUndoPayload,\n} from './projection-types'\n\nconst logger = createLogger('documents').child({ component: 'command-projections' })\n\nconst PROJECTED_COMMAND_IDS = [\n 'documents.content.replace',\n 'documents.share.create',\n 'documents.share.update',\n 'documents.share.delete',\n 'documents.comment.create',\n 'documents.comment.resolve',\n 'documents.version.restore',\n 'documents.document.archive',\n 'documents.document.unarchive',\n 'documents.document.duplicate',\n] as const\n\ntype DocumentsNotificationService = {\n create: (\n input: Record<string, unknown>,\n scope: { tenantId: string; organizationId: string },\n ) => Promise<unknown>\n deleteBySource: (\n sourceEntityType: string,\n sourceEntityId: string,\n scope: { tenantId: string; organizationId: string },\n ) => Promise<unknown>\n}\n\nfunction resolveDocumentsNotificationService(\n container: CommandInterceptorContext['container'],\n): DocumentsNotificationService {\n const service = container.resolve('notificationService') as Partial<DocumentsNotificationService> | null\n if (!service || typeof service.create !== 'function' || typeof service.deleteBySource !== 'function') {\n throw new Error('[internal] Notification service is unavailable')\n }\n return service as DocumentsNotificationService\n}\n\nfunction readResultProjections(result: unknown): DocumentsProjectionDescriptor[] {\n if (!result || typeof result !== 'object' || Array.isArray(result)) return []\n const projections = (result as DocumentsProjectedCommandResult).projections\n return Array.isArray(projections) ? projections : []\n}\n\nasync function emitProjectedEvent(\n descriptor: Extract<DocumentsProjectionDescriptor, { kind: 'event' }>,\n context: CommandInterceptorContext,\n options: { overrideActor?: boolean } = {},\n): Promise<void> {\n const currentActorUserId = context.auth?.userId ?? context.auth?.sub ?? null\n const payload = {\n ...descriptor.payload,\n ...(currentActorUserId && (options.overrideActor || !('userId' in descriptor.payload))\n ? { userId: currentActorUserId }\n : {}),\n }\n try {\n await emitDocumentsEvent(descriptor.eventId, payload, {\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n })\n } catch (error) {\n logger.error('Command event projection failed', {\n commandId: context.commandId,\n eventId: descriptor.eventId,\n err: error,\n })\n }\n}\n\nasync function emitMentionProjection(\n descriptor: Extract<DocumentsProjectionDescriptor, { kind: 'mention-notification' }>,\n context: CommandInterceptorContext,\n): Promise<void> {\n try {\n const notificationService = resolveDocumentsNotificationService(context.container)\n const em = context.container.resolve('em') as EntityManager\n if (!await resolveUserAccess(em, descriptor.documentId, {\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n }, descriptor.recipientUserId, context.container)) return\n await notificationService.create(\n {\n recipientUserId: descriptor.recipientUserId,\n type: 'documents.comment.mentioned',\n titleKey: 'documents.notifications.comment.mentioned.title',\n bodyKey: 'documents.notifications.comment.mentioned.body',\n severity: 'info',\n titleVariables: { documentTitle: descriptor.documentTitle },\n bodyVariables: {\n documentTitle: descriptor.documentTitle,\n authorUserId: descriptor.authorUserId,\n },\n sourceEntityType: DOCUMENTS_ENTITY_IDS.documentComment,\n sourceEntityId: descriptor.commentId,\n linkHref: `/backend/documents/${encodeURIComponent(descriptor.documentId)}?commentId=${encodeURIComponent(descriptor.commentId)}`,\n },\n {\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n },\n )\n } catch (error) {\n logger.error('Mention notification projection failed', {\n commandId: context.commandId,\n commentId: descriptor.commentId,\n recipientUserId: descriptor.recipientUserId,\n err: error,\n })\n }\n}\n\nconst WATCH_NOTIFICATION_TITLE_KEYS: Record<string, string> = {\n 'documents.watch.commented': 'documents.notifications.watch.commented.title',\n 'documents.watch.changed': 'documents.notifications.watch.changed.title',\n}\n\nasync function emitWatchProjection(\n descriptor: Extract<DocumentsProjectionDescriptor, { kind: 'watch-notification' }>,\n context: CommandInterceptorContext,\n): Promise<void> {\n try {\n const notificationService = resolveDocumentsNotificationService(context.container)\n const em = context.container.resolve('em') as EntityManager\n if (!await resolveUserAccess(em, descriptor.documentId, {\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n }, descriptor.recipientUserId, context.container)) return\n await notificationService.create(\n {\n recipientUserId: descriptor.recipientUserId,\n type: descriptor.notificationType,\n titleKey: WATCH_NOTIFICATION_TITLE_KEYS[descriptor.notificationType],\n bodyKey: descriptor.bodyKey,\n severity: 'info',\n titleVariables: { documentTitle: descriptor.documentTitle },\n bodyVariables: { documentTitle: descriptor.documentTitle },\n sourceEntityType: descriptor.sourceEntityType,\n sourceEntityId: descriptor.sourceEntityId,\n linkHref: descriptor.linkHref,\n },\n {\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n },\n )\n } catch (error) {\n logger.error('Watch notification projection failed', {\n commandId: context.commandId,\n documentId: descriptor.documentId,\n recipientUserId: descriptor.recipientUserId,\n err: error,\n })\n }\n}\n\nasync function emitWatchFanoutProjection(\n descriptor: Extract<DocumentsProjectionDescriptor, { kind: 'watch-notification-fanout' }>,\n context: CommandInterceptorContext,\n): Promise<void> {\n try {\n const em = context.container.resolve('em') as EntityManager\n const scope = { tenantId: descriptor.tenantId, organizationId: descriptor.organizationId }\n const document = await findOneWithDecryption(\n em,\n Document,\n { id: descriptor.documentId, tenantId: scope.tenantId, organizationId: scope.organizationId, deletedAt: null },\n { fields: ['id', 'title'] },\n scope,\n )\n if (!document) return\n const recipientUserIds = await resolveWatcherRecipients({\n em,\n container: context.container as unknown as DocumentsServiceContainer,\n scope,\n documentId: descriptor.documentId,\n actorUserId: context.auth?.userId ?? context.auth?.sub ?? descriptor.actorUserId,\n })\n for (const recipientUserId of recipientUserIds) {\n await emitWatchProjection(\n {\n kind: 'watch-notification',\n recipientUserId,\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n documentId: descriptor.documentId,\n documentTitle: document.title,\n notificationType: descriptor.notificationType,\n bodyKey: descriptor.bodyKey,\n sourceEntityType: descriptor.sourceEntityType,\n sourceEntityId: descriptor.sourceEntityId,\n linkHref: descriptor.linkHref,\n },\n context,\n )\n }\n } catch (error) {\n logger.error('Watch notification fanout projection failed', {\n commandId: context.commandId,\n documentId: descriptor.documentId,\n err: error,\n })\n }\n}\n\nasync function emitDocumentIndexProjection(\n descriptor: Extract<DocumentsProjectionDescriptor, { kind: 'document-index' }>,\n context: CommandInterceptorContext,\n): Promise<void> {\n try {\n const searchIndexer = context.container.resolve('searchIndexer') as {\n indexRecordById: (input: {\n entityId: string\n recordId: string\n tenantId: string\n organizationId: string\n }) => Promise<unknown>\n }\n await searchIndexer.indexRecordById({\n entityId: DOCUMENTS_ENTITY_IDS.document,\n recordId: descriptor.documentId,\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n })\n } catch (error) {\n logger.error('Document index projection failed', {\n commandId: context.commandId,\n documentId: descriptor.documentId,\n err: error,\n })\n }\n}\n\nasync function deleteMentionNotificationProjection(\n descriptor: Extract<DocumentsProjectionDescriptor, { kind: 'mention-notification-delete' }>,\n context: CommandInterceptorContext,\n): Promise<void> {\n try {\n const notificationService = resolveDocumentsNotificationService(context.container)\n await notificationService.deleteBySource(\n DOCUMENTS_ENTITY_IDS.documentComment,\n descriptor.commentId,\n {\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n },\n )\n } catch (error) {\n logger.error('Mention notification cleanup projection failed', {\n commandId: context.commandId,\n commentId: descriptor.commentId,\n err: error,\n })\n }\n}\n\nasync function projectDescriptors(\n projections: readonly DocumentsProjectionDescriptor[],\n context: CommandInterceptorContext,\n options: { overrideEventActor?: boolean } = {},\n): Promise<void> {\n for (const projection of projections) {\n if (projection.kind === 'event') {\n await emitProjectedEvent(projection, context, { overrideActor: options.overrideEventActor })\n }\n else if (projection.kind === 'mention-notification') await emitMentionProjection(projection, context)\n else if (projection.kind === 'watch-notification') await emitWatchProjection(projection, context)\n else if (projection.kind === 'watch-notification-fanout') await emitWatchFanoutProjection(projection, context)\n else if (projection.kind === 'document-index') await emitDocumentIndexProjection(projection, context)\n else await deleteMentionNotificationProjection(projection, context)\n }\n}\n\nfunction buildProjectionInterceptor(commandId: typeof PROJECTED_COMMAND_IDS[number]): CommandInterceptor {\n return {\n id: `documents.${commandId.slice('documents.'.length).replaceAll('.', '-')}-projections`,\n targetCommand: commandId,\n priority: 90,\n async afterExecute(_input, result, context): Promise<void> {\n await projectDescriptors(readResultProjections(result), context)\n },\n async afterUndo(\n undoContext: CommandInterceptorUndoContext,\n context: CommandInterceptorContext,\n ): Promise<void> {\n const undo = extractUndoPayload<DocumentsProjectionUndoPayload>(\n undoContext.logEntry as Parameters<typeof extractUndoPayload>[0],\n )\n await projectDescriptors(\n undo?.projectionsAfterUndo ?? [],\n context,\n { overrideEventActor: true },\n )\n },\n }\n}\n\nconst ARCHIVED_UNDO_GUARDED_COMMAND_IDS = [\n 'documents.document.update',\n 'documents.share.create',\n 'documents.share.update',\n 'documents.share.delete',\n 'documents.comment.create',\n 'documents.comment.resolve',\n 'documents.link.create',\n 'documents.link.delete',\n 'documents.version.restore',\n] as const\n\ntype UndoLogEntryShape = {\n resourceKind?: string | null\n resourceId?: string | null\n parentResourceKind?: string | null\n parentResourceId?: string | null\n tenantId?: string | null\n organizationId?: string | null\n commandPayload?: unknown\n}\n\nfunction resolveUndoDocumentId(logEntry: UndoLogEntryShape): string | null {\n if (logEntry.parentResourceKind === DOCUMENTS_ENTITY_IDS.document && logEntry.parentResourceId) {\n return logEntry.parentResourceId\n }\n if (logEntry.resourceKind === DOCUMENTS_ENTITY_IDS.document && logEntry.resourceId) {\n return logEntry.resourceId\n }\n const payload = logEntry.commandPayload\n if (payload && typeof payload === 'object') {\n const redoInput = (payload as { __redoInput?: unknown }).__redoInput\n if (redoInput && typeof redoInput === 'object') {\n const documentId = (redoInput as { documentId?: unknown }).documentId\n if (typeof documentId === 'string' && documentId.length > 0) return documentId\n }\n }\n return null\n}\n\n/**\n * Read-only means the undo path too: reversing a pre-archive share, comment,\n * link, or restore would mutate an archived document, so the guard refuses\n * with the same error the execute path uses. Delete-like undos (duplicate,\n * instantiate) stay allowed, matching delete-of-archived semantics.\n */\nfunction buildArchivedUndoGuard(commandId: typeof ARCHIVED_UNDO_GUARDED_COMMAND_IDS[number]): CommandInterceptor {\n return {\n id: `documents.${commandId.slice('documents.'.length).replaceAll('.', '-')}-archived-undo-guard`,\n targetCommand: commandId,\n priority: 100,\n async beforeUndo(\n undoContext: CommandInterceptorUndoContext,\n context: CommandInterceptorContext,\n ): Promise<void> {\n const logEntry = undoContext.logEntry as UndoLogEntryShape\n const documentId = resolveUndoDocumentId(logEntry)\n if (!documentId || !logEntry.tenantId || !logEntry.organizationId) {\n // Every guarded command records the document and its scope. Without\n // them the archived state cannot be read, so refuse the undo instead of\n // waving through a mutation this guard was unable to check.\n logger.error('Archived-undo guard could not resolve the guarded document scope', {\n commandId,\n resourceKind: logEntry.resourceKind ?? null,\n resourceId: logEntry.resourceId ?? null,\n })\n throw new CrudHttpError(403, { error: 'api.errors.forbidden' })\n }\n const em = context.container.resolve('em') as EntityManager\n const scope = { tenantId: logEntry.tenantId, organizationId: logEntry.organizationId }\n const document = await findOneWithDecryption(\n em,\n Document,\n { id: documentId, tenantId: scope.tenantId, organizationId: scope.organizationId },\n { fields: ['id', 'archivedAt'], filters: false },\n scope,\n )\n if (document?.archivedAt) {\n throw new CrudHttpError(403, { error: 'documents.errors.documentArchived' })\n }\n },\n }\n}\n\n/**\n * Projection hooks are deliberately post-command. CommandBus persists the\n * ActionLog (or marks it undone) before these hooks run, so a flaky event bus\n * or notification store can never roll back an acknowledged document write.\n */\nexport const interceptors: CommandInterceptor[] = [\n ...PROJECTED_COMMAND_IDS.map(buildProjectionInterceptor),\n ...ARCHIVED_UNDO_GUARDED_COMMAND_IDS.map(buildArchivedUndoGuard),\n]\n\nexport default interceptors\n"],
|
|
5
|
+
"mappings": "AAMA,SAAS,0BAA0B;AACnC,SAAS,qBAAqB;AAC9B,SAAS,6BAA6B;A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qC;AAAA,EAChD,GAAG,sBAAsB,IAAI,0BAA0B;AAAA,EACvD,GAAG,kCAAkC,IAAI,sBAAsB;AACjE;AAEA,IAAO,uBAAQ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import { hasAllFeatures } from "@open-mercato/shared/lib/auth/featureMatch";
|
|
2
|
+
import { authorizeFeatures } from "@open-mercato/shared/security/featurePolicy";
|
|
2
3
|
import { forbidden } from "@open-mercato/shared/lib/crud/errors";
|
|
3
4
|
import { findOneWithDecryption, findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
4
5
|
import { Document, DocumentShare } from "../data/entities.js";
|
|
6
|
+
import { hasResolvedDocumentsOrganizationAccess } from "./organizationAccess.js";
|
|
5
7
|
import {
|
|
6
8
|
resolveApiKeyPrincipalService,
|
|
7
9
|
resolveAuthPrincipalService,
|
|
8
|
-
resolveDocumentsRbacService
|
|
10
|
+
resolveDocumentsRbacService,
|
|
11
|
+
resolveOrganizationScopeService
|
|
9
12
|
} from "./platformServices.js";
|
|
10
13
|
const TIER_RANK = {
|
|
11
14
|
owner: 3,
|
|
@@ -126,6 +129,25 @@ async function loadScopedDocument(em, documentId, scope) {
|
|
|
126
129
|
);
|
|
127
130
|
}
|
|
128
131
|
async function resolveLoadedDocumentUserAccess(em, document, scope, userId, container) {
|
|
132
|
+
const rbacService = resolveDocumentsRbacService(container);
|
|
133
|
+
if (!rbacService) return null;
|
|
134
|
+
if (!await rbacService.userHasAllFeatures(userId, ["documents.view"], scope)) {
|
|
135
|
+
const organizationScopeService = resolveOrganizationScopeService(container);
|
|
136
|
+
if (!organizationScopeService) return null;
|
|
137
|
+
const authorization = await organizationScopeService.resolveFresh({
|
|
138
|
+
auth: { sub: userId, userId, tenantId: scope.tenantId, orgId: scope.organizationId, isSuperAdmin: false },
|
|
139
|
+
selectedId: scope.organizationId,
|
|
140
|
+
tenantId: scope.tenantId
|
|
141
|
+
});
|
|
142
|
+
if (!authorizeFeatures(["documents.view"], {
|
|
143
|
+
grantedFeatures: authorization.acl.features,
|
|
144
|
+
unrestricted: authorization.acl.isSuperAdmin,
|
|
145
|
+
scopeAllowed: authorization.scope.tenantId === scope.tenantId && !authorization.scope.selectionRejected && hasResolvedDocumentsOrganizationAccess(authorization.acl, scope.organizationId, authorization.scope)
|
|
146
|
+
})) return null;
|
|
147
|
+
}
|
|
148
|
+
return resolveLoadedDocumentUserTier(em, document, scope, userId, container);
|
|
149
|
+
}
|
|
150
|
+
async function resolveLoadedDocumentUserTier(em, document, scope, userId, container) {
|
|
129
151
|
if (document.ownerUserId === userId) return "owner";
|
|
130
152
|
if (await resolveDocumentsRbacService(container)?.userHasAllFeatures(
|
|
131
153
|
userId,
|
|
@@ -154,6 +176,11 @@ async function resolveLoadedDocumentUserAccess(em, document, scope, userId, cont
|
|
|
154
176
|
);
|
|
155
177
|
return maxShareTier(shares);
|
|
156
178
|
}
|
|
179
|
+
async function resolveUserDocumentTier(em, documentId, scope, userId, container) {
|
|
180
|
+
const document = await loadScopedDocument(em, documentId, scope);
|
|
181
|
+
if (!document) return null;
|
|
182
|
+
return resolveLoadedDocumentUserTier(em, document, scope, userId, container);
|
|
183
|
+
}
|
|
157
184
|
async function resolveUserAccess(em, documentId, scope, userId, container) {
|
|
158
185
|
const document = await loadScopedDocument(em, documentId, scope);
|
|
159
186
|
if (!document) return null;
|
|
@@ -217,6 +244,7 @@ export {
|
|
|
217
244
|
resolveLoadedDocumentUserAccess,
|
|
218
245
|
resolvePermission,
|
|
219
246
|
resolveSubjectAccess,
|
|
220
|
-
resolveUserAccess
|
|
247
|
+
resolveUserAccess,
|
|
248
|
+
resolveUserDocumentTier
|
|
221
249
|
};
|
|
222
250
|
//# sourceMappingURL=permissions.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/documents/lib/permissions.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { FilterQuery } from '@mikro-orm/core'\nimport type { AuthContext } from '@open-mercato/shared/lib/auth/server'\nimport { hasAllFeatures } from '@open-mercato/shared/lib/auth/featureMatch'\nimport { forbidden } from '@open-mercato/shared/lib/crud/errors'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { Document, DocumentShare } from '../data/entities'\nimport {\n resolveApiKeyPrincipalService,\n resolveAuthPrincipalService,\n resolveDocumentsRbacService,\n type DocumentsServiceContainer,\n} from './platformServices'\n\nexport type DocumentTier = 'owner' | 'editor' | 'commenter' | 'viewer'\n\nexport const TIER_RANK: Record<DocumentTier, number> = {\n owner: 3,\n editor: 2,\n commenter: 1,\n viewer: 0,\n}\n\ntype DocumentsPermissionContext = NonNullable<AuthContext> & {\n features?: string[]\n roleIds?: string[]\n resolvedRoleIds?: string[]\n organizationId?: string | null\n}\n\nfunction resolveUserId(ctx: AuthContext): string | null {\n if (!ctx) return null\n if (typeof ctx.userId === 'string' && ctx.userId.trim().length > 0) return ctx.userId\n if (typeof ctx.sub === 'string' && ctx.sub.trim().length > 0 && !ctx.sub.startsWith('api_key:')) return ctx.sub\n return null\n}\n\nfunction resolveOrganizationId(ctx: DocumentsPermissionContext): string | null {\n if (typeof ctx.organizationId === 'string' && ctx.organizationId.trim().length > 0) {\n return ctx.organizationId\n }\n if (typeof ctx.orgId === 'string' && ctx.orgId.trim().length > 0) return ctx.orgId\n return null\n}\n\nfunction normalizeStrings(values: unknown): string[] {\n if (!Array.isArray(values)) return []\n return Array.from(\n new Set(\n values\n .map((value) => (typeof value === 'string' ? value.trim() : ''))\n .filter((value) => value.length > 0),\n ),\n )\n}\n\nfunction hasDocumentsManage(ctx: DocumentsPermissionContext): boolean {\n if (ctx.isSuperAdmin === true) return true\n const features = normalizeStrings(ctx.features)\n return hasAllFeatures(['documents.manage'], features)\n}\n\nexport async function resolveActiveUserRoleIds(\n container: DocumentsServiceContainer | null | undefined,\n scope: { tenantId: string; organizationId: string },\n userId: string,\n): Promise<string[]> {\n const service = resolveAuthPrincipalService(container)\n if (!service) return []\n return normalizeStrings(await service.resolveActiveUserRoleIds(userId, scope))\n}\n\nexport async function resolveActiveSubjectRoleIds(\n container: DocumentsServiceContainer | null | undefined,\n scope: { tenantId: string; organizationId: string },\n subject: string,\n): Promise<string[]> {\n if (!subject.startsWith('api_key:')) {\n return resolveActiveUserRoleIds(container, scope, subject)\n }\n\n const apiKeyId = subject.slice('api_key:'.length).trim()\n if (!apiKeyId) return []\n const apiKeyService = resolveApiKeyPrincipalService(container)\n const authService = resolveAuthPrincipalService(container)\n if (!apiKeyService || !authService) return []\n const assigned = normalizeStrings(await apiKeyService.resolveAssignedRoleIds(apiKeyId, scope))\n if (assigned.length === 0) return []\n return normalizeStrings(await authService.filterActiveRoleIds(assigned, scope))\n}\n\nfunction maxShareTier(shares: DocumentShare[]): DocumentTier | null {\n let best: DocumentTier | null = null\n for (const share of shares) {\n const permission = share.permission\n if (permission !== 'viewer' && permission !== 'commenter' && permission !== 'editor') continue\n if (!best || TIER_RANK[permission] > TIER_RANK[best]) best = permission\n }\n return best\n}\n\nexport async function resolvePermission(\n em: EntityManager,\n documentId: string,\n ctx: AuthContext,\n): Promise<DocumentTier | null> {\n if (!ctx || !ctx.tenantId) return null\n const permissionCtx = ctx as DocumentsPermissionContext\n const organizationId = resolveOrganizationId(permissionCtx)\n if (!organizationId) return null\n\n const document = await findOneWithDecryption(\n em,\n Document,\n {\n id: documentId,\n tenantId: ctx.tenantId,\n organizationId,\n deletedAt: null,\n },\n undefined,\n { tenantId: ctx.tenantId, organizationId },\n )\n if (!document) return null\n\n const userId = resolveUserId(ctx)\n if ((userId && document.ownerUserId === userId) || hasDocumentsManage(permissionCtx)) {\n return 'owner'\n }\n if (!userId) return null\n\n // Never trust role ids/names carried by the request token. Role shares are\n // resolved from active UserRole links to active roles in the current tenant.\n // Only consume the server-projected role set. Raw token roleIds/roles are\n // authentication hints and can outlive an assignment revocation.\n const roleIds = normalizeStrings(permissionCtx.resolvedRoleIds)\n const principals: Array<FilterQuery<DocumentShare>> = [\n { principalType: 'user', principalId: userId },\n ]\n if (roleIds.length > 0) {\n principals.push({ principalType: 'role', principalId: { $in: roleIds } } as FilterQuery<DocumentShare>)\n }\n\n const shares = await findWithDecryption(\n em,\n DocumentShare,\n {\n documentId,\n tenantId: ctx.tenantId,\n organizationId,\n deletedAt: null,\n $or: principals,\n } as FilterQuery<DocumentShare>,\n undefined,\n { tenantId: ctx.tenantId, organizationId },\n )\n\n return maxShareTier(shares)\n}\n\nexport async function loadScopedDocument(\n em: EntityManager,\n documentId: string,\n scope: { tenantId: string; organizationId: string },\n): Promise<Document | null> {\n return findOneWithDecryption(\n em,\n Document,\n {\n id: documentId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n },\n undefined,\n scope,\n )\n}\n\n/**\n * Resolve one user's tier against an already scoped document. Callers that\n * evaluate many users for the same document load it once and reuse it here\n * instead of re-reading the identical row per user.\n */\nexport async function resolveLoadedDocumentUserAccess(\n em: EntityManager,\n document: Document,\n scope: { tenantId: string; organizationId: string },\n userId: string,\n container?: DocumentsServiceContainer | null,\n): Promise<DocumentTier | null> {\n if (document.ownerUserId === userId) return 'owner'\n if (await resolveDocumentsRbacService(container)?.userHasAllFeatures(\n userId,\n ['documents.manage'],\n scope,\n )) return 'owner'\n\n const roleIds = await resolveActiveUserRoleIds(container, scope, userId)\n\n const principals: Array<FilterQuery<DocumentShare>> = [\n { principalType: 'user', principalId: userId },\n ]\n if (roleIds.length > 0) {\n principals.push({ principalType: 'role', principalId: { $in: roleIds } } as FilterQuery<DocumentShare>)\n }\n\n const shares = await findWithDecryption(\n em,\n DocumentShare,\n {\n documentId: document.id,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n $or: principals,\n } as FilterQuery<DocumentShare>,\n undefined,\n scope,\n )\n\n return maxShareTier(shares)\n}\n\nexport async function resolveUserAccess(\n em: EntityManager,\n documentId: string,\n scope: { tenantId: string; organizationId: string },\n userId: string,\n container?: DocumentsServiceContainer | null,\n): Promise<DocumentTier | null> {\n const document = await loadScopedDocument(em, documentId, scope)\n if (!document) return null\n return resolveLoadedDocumentUserAccess(em, document, scope, userId, container)\n}\n\nexport async function resolveSubjectAccess(\n em: EntityManager,\n documentId: string,\n scope: { tenantId: string; organizationId: string },\n identity: { subject: string; userId: string },\n container?: DocumentsServiceContainer | null,\n): Promise<DocumentTier | null> {\n const document = await findOneWithDecryption(\n em,\n Document,\n {\n id: documentId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n },\n undefined,\n scope,\n )\n if (!document) return null\n if (document.ownerUserId === identity.userId) return 'owner'\n\n const roleIds = await resolveActiveSubjectRoleIds(container, scope, identity.subject)\n const principals: Array<FilterQuery<DocumentShare>> = [\n { principalType: 'user', principalId: identity.userId },\n ]\n if (roleIds.length > 0) {\n principals.push({ principalType: 'role', principalId: { $in: roleIds } } as FilterQuery<DocumentShare>)\n }\n\n const shares = await findWithDecryption(\n em,\n DocumentShare,\n {\n documentId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n $or: principals,\n } as FilterQuery<DocumentShare>,\n undefined,\n scope,\n )\n return maxShareTier(shares)\n}\n\nexport function hasTier(tier: DocumentTier | null, required: DocumentTier): boolean {\n if (!tier) return false\n return TIER_RANK[tier] >= TIER_RANK[required]\n}\n\nexport async function assertTier(\n em: EntityManager,\n documentId: string,\n ctx: AuthContext,\n required: DocumentTier,\n): Promise<DocumentTier> {\n const tier = await resolvePermission(em, documentId, ctx)\n if (!tier || !hasTier(tier, required)) {\n throw forbidden('Forbidden')\n }\n return tier\n}\n"],
|
|
5
|
-
"mappings": "AAGA,SAAS,sBAAsB;AAC/B,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,UAAU,qBAAqB;AACxC;AAAA,EACE;AAA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AiC;AAClF,MAAI,CAAC,KAAM,QAAO;AAClB,SAAO,UAAU,IAAI,KAAK,UAAU,QAAQ;AAC9C;AAEA,eAAsB,WACpB,IACA,YACA,KACA,UACuB;AACvB,QAAM,OAAO,MAAM,kBAAkB,IAAI,YAAY,GAAG;AACxD,MAAI,CAAC,QAAQ,CAAC,QAAQ,MAAM,QAAQ,GAAG;AACrC,UAAM,UAAU,WAAW;AAAA,EAC7B;AACA,SAAO;AACT;",
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { FilterQuery } from '@mikro-orm/core'\nimport type { AuthContext } from '@open-mercato/shared/lib/auth/server'\nimport { hasAllFeatures } from '@open-mercato/shared/lib/auth/featureMatch'\nimport { authorizeFeatures } from '@open-mercato/shared/security/featurePolicy'\nimport { forbidden } from '@open-mercato/shared/lib/crud/errors'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { Document, DocumentShare } from '../data/entities'\nimport { hasResolvedDocumentsOrganizationAccess } from './organizationAccess'\nimport {\n resolveApiKeyPrincipalService,\n resolveAuthPrincipalService,\n resolveDocumentsRbacService,\n resolveOrganizationScopeService,\n type DocumentsServiceContainer,\n} from './platformServices'\n\nexport type DocumentTier = 'owner' | 'editor' | 'commenter' | 'viewer'\n\nexport const TIER_RANK: Record<DocumentTier, number> = {\n owner: 3,\n editor: 2,\n commenter: 1,\n viewer: 0,\n}\n\ntype DocumentsPermissionContext = NonNullable<AuthContext> & {\n features?: string[]\n roleIds?: string[]\n resolvedRoleIds?: string[]\n organizationId?: string | null\n}\n\nfunction resolveUserId(ctx: AuthContext): string | null {\n if (!ctx) return null\n if (typeof ctx.userId === 'string' && ctx.userId.trim().length > 0) return ctx.userId\n if (typeof ctx.sub === 'string' && ctx.sub.trim().length > 0 && !ctx.sub.startsWith('api_key:')) return ctx.sub\n return null\n}\n\nfunction resolveOrganizationId(ctx: DocumentsPermissionContext): string | null {\n if (typeof ctx.organizationId === 'string' && ctx.organizationId.trim().length > 0) {\n return ctx.organizationId\n }\n if (typeof ctx.orgId === 'string' && ctx.orgId.trim().length > 0) return ctx.orgId\n return null\n}\n\nfunction normalizeStrings(values: unknown): string[] {\n if (!Array.isArray(values)) return []\n return Array.from(\n new Set(\n values\n .map((value) => (typeof value === 'string' ? value.trim() : ''))\n .filter((value) => value.length > 0),\n ),\n )\n}\n\nfunction hasDocumentsManage(ctx: DocumentsPermissionContext): boolean {\n if (ctx.isSuperAdmin === true) return true\n const features = normalizeStrings(ctx.features)\n return hasAllFeatures(['documents.manage'], features)\n}\n\nexport async function resolveActiveUserRoleIds(\n container: DocumentsServiceContainer | null | undefined,\n scope: { tenantId: string; organizationId: string },\n userId: string,\n): Promise<string[]> {\n const service = resolveAuthPrincipalService(container)\n if (!service) return []\n return normalizeStrings(await service.resolveActiveUserRoleIds(userId, scope))\n}\n\nexport async function resolveActiveSubjectRoleIds(\n container: DocumentsServiceContainer | null | undefined,\n scope: { tenantId: string; organizationId: string },\n subject: string,\n): Promise<string[]> {\n if (!subject.startsWith('api_key:')) {\n return resolveActiveUserRoleIds(container, scope, subject)\n }\n\n const apiKeyId = subject.slice('api_key:'.length).trim()\n if (!apiKeyId) return []\n const apiKeyService = resolveApiKeyPrincipalService(container)\n const authService = resolveAuthPrincipalService(container)\n if (!apiKeyService || !authService) return []\n const assigned = normalizeStrings(await apiKeyService.resolveAssignedRoleIds(apiKeyId, scope))\n if (assigned.length === 0) return []\n return normalizeStrings(await authService.filterActiveRoleIds(assigned, scope))\n}\n\nfunction maxShareTier(shares: DocumentShare[]): DocumentTier | null {\n let best: DocumentTier | null = null\n for (const share of shares) {\n const permission = share.permission\n if (permission !== 'viewer' && permission !== 'commenter' && permission !== 'editor') continue\n if (!best || TIER_RANK[permission] > TIER_RANK[best]) best = permission\n }\n return best\n}\n\nexport async function resolvePermission(\n em: EntityManager,\n documentId: string,\n ctx: AuthContext,\n): Promise<DocumentTier | null> {\n if (!ctx || !ctx.tenantId) return null\n const permissionCtx = ctx as DocumentsPermissionContext\n const organizationId = resolveOrganizationId(permissionCtx)\n if (!organizationId) return null\n\n const document = await findOneWithDecryption(\n em,\n Document,\n {\n id: documentId,\n tenantId: ctx.tenantId,\n organizationId,\n deletedAt: null,\n },\n undefined,\n { tenantId: ctx.tenantId, organizationId },\n )\n if (!document) return null\n\n const userId = resolveUserId(ctx)\n if ((userId && document.ownerUserId === userId) || hasDocumentsManage(permissionCtx)) {\n return 'owner'\n }\n if (!userId) return null\n\n // Never trust role ids/names carried by the request token. Role shares are\n // resolved from active UserRole links to active roles in the current tenant.\n // Only consume the server-projected role set. Raw token roleIds/roles are\n // authentication hints and can outlive an assignment revocation.\n const roleIds = normalizeStrings(permissionCtx.resolvedRoleIds)\n const principals: Array<FilterQuery<DocumentShare>> = [\n { principalType: 'user', principalId: userId },\n ]\n if (roleIds.length > 0) {\n principals.push({ principalType: 'role', principalId: { $in: roleIds } } as FilterQuery<DocumentShare>)\n }\n\n const shares = await findWithDecryption(\n em,\n DocumentShare,\n {\n documentId,\n tenantId: ctx.tenantId,\n organizationId,\n deletedAt: null,\n $or: principals,\n } as FilterQuery<DocumentShare>,\n undefined,\n { tenantId: ctx.tenantId, organizationId },\n )\n\n return maxShareTier(shares)\n}\n\nexport async function loadScopedDocument(\n em: EntityManager,\n documentId: string,\n scope: { tenantId: string; organizationId: string },\n): Promise<Document | null> {\n return findOneWithDecryption(\n em,\n Document,\n {\n id: documentId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n },\n undefined,\n scope,\n )\n}\n\n/**\n * Resolve one user's tier against an already scoped document. Callers that\n * evaluate many users for the same document load it once and reuse it here\n * instead of re-reading the identical row per user.\n */\nexport async function resolveLoadedDocumentUserAccess(\n em: EntityManager,\n document: Document,\n scope: { tenantId: string; organizationId: string },\n userId: string,\n container?: DocumentsServiceContainer | null,\n): Promise<DocumentTier | null> {\n const rbacService = resolveDocumentsRbacService(container)\n if (!rbacService) return null\n if (!await rbacService.userHasAllFeatures(userId, ['documents.view'], scope)) {\n const organizationScopeService = resolveOrganizationScopeService(container)\n if (!organizationScopeService) return null\n const authorization = await organizationScopeService.resolveFresh({\n auth: { sub: userId, userId, tenantId: scope.tenantId, orgId: scope.organizationId, isSuperAdmin: false },\n selectedId: scope.organizationId,\n tenantId: scope.tenantId,\n })\n if (!authorizeFeatures(['documents.view'], {\n grantedFeatures: authorization.acl.features,\n unrestricted: authorization.acl.isSuperAdmin,\n scopeAllowed: authorization.scope.tenantId === scope.tenantId\n && !authorization.scope.selectionRejected\n && hasResolvedDocumentsOrganizationAccess(authorization.acl, scope.organizationId, authorization.scope),\n })) return null\n }\n return resolveLoadedDocumentUserTier(em, document, scope, userId, container)\n}\n\nasync function resolveLoadedDocumentUserTier(\n em: EntityManager,\n document: Document,\n scope: { tenantId: string; organizationId: string },\n userId: string,\n container?: DocumentsServiceContainer | null,\n): Promise<DocumentTier | null> {\n if (document.ownerUserId === userId) return 'owner'\n if (await resolveDocumentsRbacService(container)?.userHasAllFeatures(\n userId,\n ['documents.manage'],\n scope,\n )) return 'owner'\n\n const roleIds = await resolveActiveUserRoleIds(container, scope, userId)\n\n const principals: Array<FilterQuery<DocumentShare>> = [\n { principalType: 'user', principalId: userId },\n ]\n if (roleIds.length > 0) {\n principals.push({ principalType: 'role', principalId: { $in: roleIds } } as FilterQuery<DocumentShare>)\n }\n\n const shares = await findWithDecryption(\n em,\n DocumentShare,\n {\n documentId: document.id,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n $or: principals,\n } as FilterQuery<DocumentShare>,\n undefined,\n scope,\n )\n\n return maxShareTier(shares)\n}\n\nexport async function resolveUserDocumentTier(\n em: EntityManager,\n documentId: string,\n scope: { tenantId: string; organizationId: string },\n userId: string,\n container?: DocumentsServiceContainer | null,\n): Promise<DocumentTier | null> {\n const document = await loadScopedDocument(em, documentId, scope)\n if (!document) return null\n return resolveLoadedDocumentUserTier(em, document, scope, userId, container)\n}\n\nexport async function resolveUserAccess(\n em: EntityManager,\n documentId: string,\n scope: { tenantId: string; organizationId: string },\n userId: string,\n container?: DocumentsServiceContainer | null,\n): Promise<DocumentTier | null> {\n const document = await loadScopedDocument(em, documentId, scope)\n if (!document) return null\n return resolveLoadedDocumentUserAccess(em, document, scope, userId, container)\n}\n\nexport async function resolveSubjectAccess(\n em: EntityManager,\n documentId: string,\n scope: { tenantId: string; organizationId: string },\n identity: { subject: string; userId: string },\n container?: DocumentsServiceContainer | null,\n): Promise<DocumentTier | null> {\n const document = await findOneWithDecryption(\n em,\n Document,\n {\n id: documentId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n },\n undefined,\n scope,\n )\n if (!document) return null\n if (document.ownerUserId === identity.userId) return 'owner'\n\n const roleIds = await resolveActiveSubjectRoleIds(container, scope, identity.subject)\n const principals: Array<FilterQuery<DocumentShare>> = [\n { principalType: 'user', principalId: identity.userId },\n ]\n if (roleIds.length > 0) {\n principals.push({ principalType: 'role', principalId: { $in: roleIds } } as FilterQuery<DocumentShare>)\n }\n\n const shares = await findWithDecryption(\n em,\n DocumentShare,\n {\n documentId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n $or: principals,\n } as FilterQuery<DocumentShare>,\n undefined,\n scope,\n )\n return maxShareTier(shares)\n}\n\nexport function hasTier(tier: DocumentTier | null, required: DocumentTier): boolean {\n if (!tier) return false\n return TIER_RANK[tier] >= TIER_RANK[required]\n}\n\nexport async function assertTier(\n em: EntityManager,\n documentId: string,\n ctx: AuthContext,\n required: DocumentTier,\n): Promise<DocumentTier> {\n const tier = await resolvePermission(em, documentId, ctx)\n if (!tier || !hasTier(tier, required)) {\n throw forbidden('Forbidden')\n }\n return tier\n}\n"],
|
|
5
|
+
"mappings": "AAGA,SAAS,sBAAsB;AAC/B,SAAS,yBAAyB;AAClC,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,UAAU,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AQ,CAAC,QAAQ,MAAM,QAAQ,GAAG;AACrC,UAAM,UAAU,WAAW;AAAA,EAC7B;AACA,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/documents",
|
|
3
|
-
"version": "0.10.1-develop.
|
|
3
|
+
"version": "0.10.1-develop.7715.1.9483283afa",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -75,8 +75,8 @@
|
|
|
75
75
|
"@hocuspocus/server": "^4.4.0",
|
|
76
76
|
"@hocuspocus/transformer": "^4.3.0",
|
|
77
77
|
"@mikro-orm/core": "^7.1.14",
|
|
78
|
-
"@open-mercato/events": "0.10.1-develop.
|
|
79
|
-
"@open-mercato/ui": "0.10.1-develop.
|
|
78
|
+
"@open-mercato/events": "0.10.1-develop.7715.1.9483283afa",
|
|
79
|
+
"@open-mercato/ui": "0.10.1-develop.7715.1.9483283afa",
|
|
80
80
|
"@tiptap/core": "^3",
|
|
81
81
|
"@tiptap/extension-bubble-menu": "^3",
|
|
82
82
|
"@tiptap/extension-collaboration": "^3.27.3",
|
|
@@ -113,13 +113,13 @@
|
|
|
113
113
|
},
|
|
114
114
|
"peerDependencies": {
|
|
115
115
|
"@mikro-orm/postgresql": "^7.0.14",
|
|
116
|
-
"@open-mercato/shared": "0.10.1-develop.
|
|
116
|
+
"@open-mercato/shared": "0.10.1-develop.7715.1.9483283afa",
|
|
117
117
|
"react": "^19.0.0",
|
|
118
118
|
"react-dom": "^19.0.0"
|
|
119
119
|
},
|
|
120
120
|
"devDependencies": {
|
|
121
|
-
"@open-mercato/core": "0.10.1-develop.
|
|
122
|
-
"@open-mercato/shared": "0.10.1-develop.
|
|
121
|
+
"@open-mercato/core": "0.10.1-develop.7715.1.9483283afa",
|
|
122
|
+
"@open-mercato/shared": "0.10.1-develop.7715.1.9483283afa",
|
|
123
123
|
"@types/jest": "^30.0.0",
|
|
124
124
|
"@types/pg": "^8.23.1",
|
|
125
125
|
"@types/react": "^19.2.18",
|
|
@@ -21,7 +21,7 @@ import {
|
|
|
21
21
|
} from '../data/validators'
|
|
22
22
|
import { DOCUMENTS_ENTITY_IDS } from '../lib/constants'
|
|
23
23
|
import { assertDocumentCommentCapacity } from '../lib/historyLimits'
|
|
24
|
-
import { resolveUserAccess } from '../lib/permissions'
|
|
24
|
+
import { resolveUserAccess, resolveUserDocumentTier } from '../lib/permissions'
|
|
25
25
|
import { resolveWatcherRecipients } from '../lib/watchers'
|
|
26
26
|
import type { DocumentsProjectionDescriptor } from './projection-types'
|
|
27
27
|
import {
|
|
@@ -641,7 +641,7 @@ export const createCommentCommand: CommandHandler<CommentCreateCommandInput, Com
|
|
|
641
641
|
for (const mentionedUserId of mentionUserIds) {
|
|
642
642
|
const grantIdentity = grantIdentityByUserId.get(mentionedUserId)
|
|
643
643
|
if (!grantIdentity || !canShare) continue
|
|
644
|
-
const tier = await
|
|
644
|
+
const tier = await resolveUserDocumentTier(em, input.documentId, input, mentionedUserId, ctx.container)
|
|
645
645
|
if (tier) continue
|
|
646
646
|
await assertUserPrincipal(ctx.container, input, mentionedUserId)
|
|
647
647
|
let share = await loadMentionShare(em, input, mentionedUserId, true)
|
|
@@ -10,6 +10,7 @@ import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
|
|
|
10
10
|
import { createLogger } from '@open-mercato/shared/lib/logger'
|
|
11
11
|
import { Document } from '../data/entities'
|
|
12
12
|
import { DOCUMENTS_ENTITY_IDS } from '../lib/constants'
|
|
13
|
+
import { resolveUserAccess } from '../lib/permissions'
|
|
13
14
|
import { resolveWatcherRecipients } from '../lib/watchers'
|
|
14
15
|
import type { DocumentsServiceContainer } from '../lib/platformServices'
|
|
15
16
|
import { emitDocumentsEvent } from '../events'
|
|
@@ -94,6 +95,11 @@ async function emitMentionProjection(
|
|
|
94
95
|
): Promise<void> {
|
|
95
96
|
try {
|
|
96
97
|
const notificationService = resolveDocumentsNotificationService(context.container)
|
|
98
|
+
const em = context.container.resolve('em') as EntityManager
|
|
99
|
+
if (!await resolveUserAccess(em, descriptor.documentId, {
|
|
100
|
+
tenantId: descriptor.tenantId,
|
|
101
|
+
organizationId: descriptor.organizationId,
|
|
102
|
+
}, descriptor.recipientUserId, context.container)) return
|
|
97
103
|
await notificationService.create(
|
|
98
104
|
{
|
|
99
105
|
recipientUserId: descriptor.recipientUserId,
|
|
@@ -136,6 +142,11 @@ async function emitWatchProjection(
|
|
|
136
142
|
): Promise<void> {
|
|
137
143
|
try {
|
|
138
144
|
const notificationService = resolveDocumentsNotificationService(context.container)
|
|
145
|
+
const em = context.container.resolve('em') as EntityManager
|
|
146
|
+
if (!await resolveUserAccess(em, descriptor.documentId, {
|
|
147
|
+
tenantId: descriptor.tenantId,
|
|
148
|
+
organizationId: descriptor.organizationId,
|
|
149
|
+
}, descriptor.recipientUserId, context.container)) return
|
|
139
150
|
await notificationService.create(
|
|
140
151
|
{
|
|
141
152
|
recipientUserId: descriptor.recipientUserId,
|
|
@@ -2,13 +2,16 @@ import type { EntityManager } from '@mikro-orm/postgresql'
|
|
|
2
2
|
import type { FilterQuery } from '@mikro-orm/core'
|
|
3
3
|
import type { AuthContext } from '@open-mercato/shared/lib/auth/server'
|
|
4
4
|
import { hasAllFeatures } from '@open-mercato/shared/lib/auth/featureMatch'
|
|
5
|
+
import { authorizeFeatures } from '@open-mercato/shared/security/featurePolicy'
|
|
5
6
|
import { forbidden } from '@open-mercato/shared/lib/crud/errors'
|
|
6
7
|
import { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'
|
|
7
8
|
import { Document, DocumentShare } from '../data/entities'
|
|
9
|
+
import { hasResolvedDocumentsOrganizationAccess } from './organizationAccess'
|
|
8
10
|
import {
|
|
9
11
|
resolveApiKeyPrincipalService,
|
|
10
12
|
resolveAuthPrincipalService,
|
|
11
13
|
resolveDocumentsRbacService,
|
|
14
|
+
resolveOrganizationScopeService,
|
|
12
15
|
type DocumentsServiceContainer,
|
|
13
16
|
} from './platformServices'
|
|
14
17
|
|
|
@@ -188,6 +191,34 @@ export async function resolveLoadedDocumentUserAccess(
|
|
|
188
191
|
scope: { tenantId: string; organizationId: string },
|
|
189
192
|
userId: string,
|
|
190
193
|
container?: DocumentsServiceContainer | null,
|
|
194
|
+
): Promise<DocumentTier | null> {
|
|
195
|
+
const rbacService = resolveDocumentsRbacService(container)
|
|
196
|
+
if (!rbacService) return null
|
|
197
|
+
if (!await rbacService.userHasAllFeatures(userId, ['documents.view'], scope)) {
|
|
198
|
+
const organizationScopeService = resolveOrganizationScopeService(container)
|
|
199
|
+
if (!organizationScopeService) return null
|
|
200
|
+
const authorization = await organizationScopeService.resolveFresh({
|
|
201
|
+
auth: { sub: userId, userId, tenantId: scope.tenantId, orgId: scope.organizationId, isSuperAdmin: false },
|
|
202
|
+
selectedId: scope.organizationId,
|
|
203
|
+
tenantId: scope.tenantId,
|
|
204
|
+
})
|
|
205
|
+
if (!authorizeFeatures(['documents.view'], {
|
|
206
|
+
grantedFeatures: authorization.acl.features,
|
|
207
|
+
unrestricted: authorization.acl.isSuperAdmin,
|
|
208
|
+
scopeAllowed: authorization.scope.tenantId === scope.tenantId
|
|
209
|
+
&& !authorization.scope.selectionRejected
|
|
210
|
+
&& hasResolvedDocumentsOrganizationAccess(authorization.acl, scope.organizationId, authorization.scope),
|
|
211
|
+
})) return null
|
|
212
|
+
}
|
|
213
|
+
return resolveLoadedDocumentUserTier(em, document, scope, userId, container)
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async function resolveLoadedDocumentUserTier(
|
|
217
|
+
em: EntityManager,
|
|
218
|
+
document: Document,
|
|
219
|
+
scope: { tenantId: string; organizationId: string },
|
|
220
|
+
userId: string,
|
|
221
|
+
container?: DocumentsServiceContainer | null,
|
|
191
222
|
): Promise<DocumentTier | null> {
|
|
192
223
|
if (document.ownerUserId === userId) return 'owner'
|
|
193
224
|
if (await resolveDocumentsRbacService(container)?.userHasAllFeatures(
|
|
@@ -222,6 +253,18 @@ export async function resolveLoadedDocumentUserAccess(
|
|
|
222
253
|
return maxShareTier(shares)
|
|
223
254
|
}
|
|
224
255
|
|
|
256
|
+
export async function resolveUserDocumentTier(
|
|
257
|
+
em: EntityManager,
|
|
258
|
+
documentId: string,
|
|
259
|
+
scope: { tenantId: string; organizationId: string },
|
|
260
|
+
userId: string,
|
|
261
|
+
container?: DocumentsServiceContainer | null,
|
|
262
|
+
): Promise<DocumentTier | null> {
|
|
263
|
+
const document = await loadScopedDocument(em, documentId, scope)
|
|
264
|
+
if (!document) return null
|
|
265
|
+
return resolveLoadedDocumentUserTier(em, document, scope, userId, container)
|
|
266
|
+
}
|
|
267
|
+
|
|
225
268
|
export async function resolveUserAccess(
|
|
226
269
|
em: EntityManager,
|
|
227
270
|
documentId: string,
|