@open-mercato/core 0.9.1-develop.7513.1.ae2715553f → 0.9.1-develop.7516.1.176184247d
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/.turbo/turbo-build.log +1 -1
- package/dist/modules/communication_channels/lib/send-as-user.js.map +2 -2
- package/dist/modules/customers/api/people/[id]/emails/route.js +44 -1
- package/dist/modules/customers/api/people/[id]/emails/route.js.map +2 -2
- package/dist/modules/customers/lib/personEmailThreads.js +36 -1
- package/dist/modules/customers/lib/personEmailThreads.js.map +2 -2
- package/dist/modules/messages/api/[id]/route.js +3 -9
- package/dist/modules/messages/api/[id]/route.js.map +2 -2
- package/dist/modules/messages/api/route.js +33 -16
- package/dist/modules/messages/api/route.js.map +2 -2
- package/dist/modules/messages/commands/messages.js.map +2 -2
- package/dist/modules/messages/lib/routeHelpers.js +40 -1
- package/dist/modules/messages/lib/routeHelpers.js.map +2 -2
- package/dist/modules/shipping_carriers/api/webhook/[provider]/route.js +4 -7
- package/dist/modules/shipping_carriers/api/webhook/[provider]/route.js.map +2 -2
- package/dist/modules/shipping_carriers/lib/shipping-service.js +29 -11
- package/dist/modules/shipping_carriers/lib/shipping-service.js.map +2 -2
- package/dist/modules/shipping_carriers/lib/status-sync.js +2 -2
- package/dist/modules/shipping_carriers/lib/status-sync.js.map +2 -2
- package/dist/modules/shipping_carriers/workers/webhook-processor.js +60 -33
- package/dist/modules/shipping_carriers/workers/webhook-processor.js.map +3 -3
- package/dist/modules/warranty_claims/commands/claim-lines.js +89 -68
- package/dist/modules/warranty_claims/commands/claim-lines.js.map +2 -2
- package/dist/modules/warranty_claims/commands/claims.js +14 -13
- package/dist/modules/warranty_claims/commands/claims.js.map +2 -2
- package/dist/modules/warranty_claims/commands/shared.js +8 -2
- package/dist/modules/warranty_claims/commands/shared.js.map +2 -2
- package/package.json +7 -7
- package/src/modules/communication_channels/lib/send-as-user.ts +4 -0
- package/src/modules/customers/api/people/[id]/emails/route.ts +67 -1
- package/src/modules/customers/i18n/de.json +1 -0
- package/src/modules/customers/i18n/en.json +1 -0
- package/src/modules/customers/i18n/es.json +1 -0
- package/src/modules/customers/i18n/ko.json +1 -0
- package/src/modules/customers/i18n/pl.json +1 -0
- package/src/modules/customers/lib/personEmailThreads.ts +61 -0
- package/src/modules/messages/api/[id]/route.ts +2 -9
- package/src/modules/messages/api/route.ts +42 -20
- package/src/modules/messages/commands/messages.ts +7 -0
- package/src/modules/messages/i18n/de.json +1 -0
- package/src/modules/messages/i18n/en.json +1 -0
- package/src/modules/messages/i18n/es.json +1 -0
- package/src/modules/messages/i18n/ko.json +1 -0
- package/src/modules/messages/i18n/pl.json +1 -0
- package/src/modules/messages/lib/routeHelpers.ts +84 -1
- package/src/modules/shipping_carriers/api/webhook/[provider]/route.ts +4 -7
- package/src/modules/shipping_carriers/lib/shipping-service.ts +29 -11
- package/src/modules/shipping_carriers/lib/status-sync.ts +2 -2
- package/src/modules/shipping_carriers/workers/webhook-processor.ts +71 -39
- package/src/modules/warranty_claims/commands/claim-lines.ts +107 -66
- package/src/modules/warranty_claims/commands/claims.ts +14 -13
- package/src/modules/warranty_claims/commands/shared.ts +7 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/modules/messages/api/%5Bid%5D/route.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { CommandBus } from '@open-mercato/shared/lib/commands/command-bus'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi/types'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { applyResponseEnricherToRecord } from '@open-mercato/shared/lib/crud/enricher-runner'\nimport { enforceCommandOptimisticLock } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { User } from '../../../auth/data/entities'\nimport { Message, MessageObject, MessageRecipient } from '../../data/entities'\nimport { updateDraftSchema } from '../../data/validators'\nimport { buildResolvedMessageActions } from '../../lib/actions'\nimport { MESSAGE_OPTIMISTIC_LOCK_RESOURCE_KIND } from '../../lib/constants'\nimport { getMessageObjectType } from '../../lib/message-objects-registry'\nimport { getMessageTypeOrDefault } from '../../lib/message-types-registry'\nimport { attachOperationMetadataHeader } from '../../lib/operationMetadata'\nimport {\n canPostToChannelThread,\n hasChannelThreadReadAccess,\n hasOrganizationAccess,\n resolveMessageContext,\n} from '../../lib/routeHelpers'\nimport { resolveUserFeatures, runMessageMutationGuardAfterSuccess, runMessageMutationGuards } from '../guards'\nimport {\n errorResponseSchema,\n messageDetailResponseSchema,\n okResponseSchema,\n updateDraftSchema as updateDraftOpenApiSchema,\n} from '../openapi'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getCommandInterceptorHttpRejection } from '@open-mercato/shared/lib/commands/errors'\n\nconst logger = createLogger('messages').child({ component: 'api' })\n\nexport const metadata = {\n GET: { requireAuth: true },\n PATCH: { requireAuth: true, requireFeatures: ['messages.compose'] },\n DELETE: { requireAuth: true, requireFeatures: ['messages.view'] },\n}\n\ntype MessageObjectPreviewPayload = {\n title: string\n subtitle?: string\n status?: string\n statusColor?: string\n metadata?: Record<string, string>\n} | null\n\ntype RbacServiceLike = {\n getGrantedFeatures?: (\n userId: string,\n scope: { tenantId: string | null; organizationId: string | null },\n ) => Promise<string[]>\n}\n\n/**\n * Feature list for the enricher ACL gate, resolved from RBAC.\n *\n * Mirrors `customers/api/interactions/route.ts`. Returning `undefined` on\n * failure is deliberate \u2014 the runner then treats every feature-gated enricher\n * as denied, which is the safe direction.\n */\nasync function resolveGrantedFeatures(\n container: { resolve: (name: string) => unknown },\n scope: { tenantId: string; organizationId: string | null; userId: string },\n): Promise<string[] | undefined> {\n try {\n const rbac = container.resolve('rbacService') as RbacServiceLike | undefined\n if (!rbac?.getGrantedFeatures) return undefined\n return await rbac.getGrantedFeatures(scope.userId, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n } catch {\n return undefined\n }\n}\n\nexport async function GET(req: Request, { params }: { params: { id: string } }) {\n const { ctx, scope } = await resolveMessageContext(req)\n const em = ctx.container.resolve('em') as EntityManager\n const url = new URL(req.url)\n const skipMarkReadParam = url.searchParams.get('skipMarkRead')\n const skipMarkRead = skipMarkReadParam === '1'\n\n const message = await findOneWithDecryption(\n em,\n Message,\n {\n id: params.id,\n tenantId: scope.tenantId,\n deletedAt: null,\n },\n undefined,\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n\n if (!message) {\n return Response.json({ error: 'Message not found' }, { status: 404 })\n }\n\n if (!hasOrganizationAccess(scope.organizationId, message.organizationId)) {\n return Response.json({ error: 'Access denied' }, { status: 403 })\n }\n\n const recipient = await em.findOne(MessageRecipient, {\n messageId: params.id,\n recipientUserId: scope.userId,\n deletedAt: null,\n })\n\n const isSender = message.senderUserId === scope.userId\n const isRecipient = Boolean(recipient)\n\n // #5535: a message that arrived over a communication channel has the channel\n // system user as its sender and, on an unassigned conversation, no recipient\n // rows \u2014 so the participant test below denies every operator and the reply\n // button is unreachable. For a thread the channels hub owns, that hub's access\n // rule applies instead; an internal thread resolves to `null` and keeps the\n // participant rule unchanged.\n //\n // `hasChannelThreadReadAccess` feature-gates the fallback before consulting the\n // hub, because `assertCanAccessChannel` \u2014 the rule behind it \u2014 deliberately\n // ignores features and returns for EVERY shared channel; its documented\n // precondition is a caller the route already feature-gated, and this route is\n // `requireAuth` only so that a participant can always read their own message.\n // The gate goes through RBAC, not through `ctx.auth.features` \u2014 the session JWT\n // carries no `features` claim at all, so reading it would deny everyone.\n const hasChannelThreadAccess = await hasChannelThreadReadAccess(ctx, scope, message)\n\n if (!isSender && !isRecipient && !hasChannelThreadAccess) {\n return Response.json({ error: 'Access denied' }, { status: 403 })\n }\n\n // Channel access says \"you may work this conversation\", not \"you may read what\n // other operators kept off it\". An internal note stays participant-only however\n // the caller reached the thread.\n //\n // The test is \"not explicitly public\" rather than \"explicitly internal\":\n // `data/validators.ts` refines a compose under `value.visibility ?? 'internal'`\n // and `composeMessageCommand` persists `input.visibility ?? null`, so a caller\n // that omits the field files a message the module itself validated as internal\n // yet stored as `null`. `ingest-inbound-message.ts` stamps the inbound message\n // `'public'` and the reply/forward commands copy it forward, so the journey\n // this route exists for is unaffected.\n if (!isSender && !isRecipient && message.visibility !== 'public') {\n return Response.json({ error: 'Access denied' }, { status: 403 })\n }\n\n const autoMarkRead = !skipMarkRead && recipient?.status === 'unread'\n const readAt = autoMarkRead ? new Date() : recipient?.readAt ?? null\n\n const objects = await em.find(MessageObject, { messageId: params.id })\n const objectPreviews = await Promise.all(\n objects.map(async (item): Promise<MessageObjectPreviewPayload> => {\n const objectType = getMessageObjectType(item.entityModule, item.entityType)\n if (!objectType?.loadPreview) return null\n try {\n return await objectType.loadPreview(item.entityId, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n } catch (error) {\n logger.error('Failed to load preview', { entityModule: item.entityModule, entityType: item.entityType, entityId: item.entityId, err: error })\n return null\n }\n }),\n )\n const allRecipients = await em.find(MessageRecipient, { messageId: params.id, deletedAt: null })\n\n const threadMessages = await findWithDecryption(\n em,\n Message,\n {\n threadId: message.threadId ?? message.id,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n isDraft: false,\n },\n { orderBy: { sentAt: 'ASC' } },\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n const threadMessageIds = threadMessages.map((item) => item.id)\n const visibleRecipientRows = threadMessageIds.length > 0\n ? await em.find(MessageRecipient, {\n messageId: { $in: threadMessageIds },\n recipientUserId: scope.userId,\n deletedAt: null,\n })\n : []\n const visibleRecipientMessageIds = new Set(visibleRecipientRows.map((item) => item.messageId))\n // On a channel-linked thread the conversation IS the thread: the correspondent\n // is not a platform user, so filtering by participation would hide the inbound\n // messages and every other operator's answer, leaving the operator looking at\n // half a conversation (#5535).\n //\n // Internal notes are the exception: they are addressed to platform\n // participants, so they keep the participant rule even on a channel thread.\n // Same polarity as the direct-read gate above \u2014 an absent visibility is\n // internal by the messages module's own convention, so only an explicitly\n // public message is shown to a non-participant.\n const isThreadMessageParticipant = (threadMessage: { id: string; senderUserId?: string | null }) => (\n threadMessage.senderUserId === scope.userId || visibleRecipientMessageIds.has(threadMessage.id)\n )\n const actorVisibleThreadMessages = hasChannelThreadAccess\n ? threadMessages.filter((threadMessage) => (\n threadMessage.visibility === 'public' || isThreadMessageParticipant(threadMessage)\n ))\n : threadMessages.filter(isThreadMessageParticipant)\n\n const actorRecipientStatusByMessageId = new Map<string, string>()\n for (const row of visibleRecipientRows) {\n actorRecipientStatusByMessageId.set(row.messageId, row.status)\n }\n if (recipient) {\n actorRecipientStatusByMessageId.set(params.id, autoMarkRead ? 'read' : recipient.status)\n }\n const actorRecipientStatuses = Array.from(actorRecipientStatusByMessageId.values())\n const conversationArchived = actorRecipientStatuses.length > 0\n && actorRecipientStatuses.every((status) => status === 'archived')\n const conversationAllUnread = actorRecipientStatuses.length > 0\n && actorRecipientStatuses.every((status) => status === 'unread')\n\n const threadSenderIds = actorVisibleThreadMessages\n .map((threadMessage) => threadMessage.senderUserId)\n .filter((value): value is string => typeof value === 'string' && value.length > 0)\n\n const threadSenders = threadSenderIds.length > 0\n ? await findWithDecryption(\n em,\n User,\n { id: { $in: Array.from(new Set(threadSenderIds)) } },\n undefined,\n { tenantId: scope.tenantId, organizationId: scope.organizationId }\n )\n : []\n\n const threadSenderMap = new Map(threadSenders.map((user) => [user.id, user]))\n\n const senderUser = await findOneWithDecryption(\n em,\n User,\n { id: message.senderUserId },\n undefined,\n { tenantId: scope.tenantId, organizationId: scope.organizationId }\n )\n\n const senderName = typeof senderUser?.name === 'string' && senderUser.name.trim().length\n ? senderUser.name.trim()\n : null\n const senderEmail = senderUser?.email ?? null\n\n const messageType = getMessageTypeOrDefault(message.type)\n const resolvedActionData = buildResolvedMessageActions(message, objects)\n\n if (autoMarkRead) {\n const commandBus = ctx.container.resolve('commandBus') as CommandBus\n await commandBus.execute('messages.recipients.mark_read', {\n input: {\n messageId: params.id,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n },\n ctx: {\n container: ctx.container,\n auth: ctx.auth ?? null,\n organizationScope: null,\n selectedOrganizationId: scope.organizationId,\n organizationIds: scope.organizationId ? [scope.organizationId] : null,\n request: req,\n },\n })\n }\n\n const detail: Record<string, unknown> = {\n id: message.id,\n updatedAt: message.updatedAt ?? null,\n type: message.type,\n isDraft: message.isDraft,\n canEditDraft: message.isDraft && message.senderUserId === scope.userId,\n canArchive: Boolean(recipient),\n isArchived: recipient?.status === 'archived',\n visibility: message.visibility,\n sourceEntityType: message.sourceEntityType,\n sourceEntityId: message.sourceEntityId,\n externalEmail: message.externalEmail,\n externalName: message.externalName,\n typeDefinition: {\n labelKey: messageType.labelKey,\n icon: messageType.icon,\n color: messageType.color,\n allowReply: messageType.allowReply ?? true,\n allowForward: messageType.allowForward ?? true,\n ui: {\n listItemComponent: messageType.ui?.listItemComponent ?? null,\n contentComponent: messageType.ui?.contentComponent ?? null,\n actionsComponent: messageType.ui?.actionsComponent ?? null,\n },\n },\n threadId: message.threadId,\n parentMessageId: message.parentMessageId,\n senderUserId: message.senderUserId,\n senderName,\n senderEmail,\n subject: message.subject,\n body: message.body,\n bodyFormat: message.bodyFormat,\n priority: message.priority,\n sentAt: message.sentAt,\n actionData: resolvedActionData,\n actionTaken: message.actionTaken,\n actionTakenAt: message.actionTakenAt,\n actionTakenByUserId: message.actionTakenByUserId,\n recipients: allRecipients.map((item) => ({\n userId: item.recipientUserId,\n type: item.recipientType,\n status: autoMarkRead && item.recipientUserId === scope.userId ? 'read' : item.status,\n readAt: autoMarkRead && item.recipientUserId === scope.userId ? readAt : item.readAt,\n })),\n objects: objects.map((item, index) => ({\n id: item.id,\n entityModule: item.entityModule,\n entityType: item.entityType,\n entityId: item.entityId,\n actionRequired: item.actionRequired,\n actionType: item.actionType,\n actionLabel: item.actionLabel,\n snapshot: item.entitySnapshot,\n preview: objectPreviews[index] ?? null,\n })),\n thread: actorVisibleThreadMessages.map((threadMessage) => {\n const sender = threadSenderMap.get(threadMessage.senderUserId)\n const threadSenderName = typeof sender?.name === 'string' && sender.name.trim().length\n ? sender.name.trim()\n : null\n\n return {\n id: threadMessage.id,\n senderUserId: threadMessage.senderUserId,\n senderName: threadSenderName,\n senderEmail: sender?.email ?? null,\n externalName: threadMessage.externalName ?? null,\n externalEmail: threadMessage.externalEmail ?? null,\n sourceEntityType: threadMessage.sourceEntityType ?? null,\n body: threadMessage.body,\n bodyFormat: threadMessage.bodyFormat,\n sentAt: threadMessage.sentAt,\n }\n }),\n isRead: recipient ? (autoMarkRead || recipient.status !== 'unread') : true,\n conversationArchived,\n conversationAllUnread,\n }\n\n // Mirrors `enrichSingleRecord` in `shared/lib/crud/factory.ts`, which every\n // `makeCrudRoute` host gets for free: same `_meta` envelope, and no blanket\n // catch so a `critical: true` enricher still surfaces as an HTTP error.\n // Non-critical failures never escape the runner \u2014 it merges `fallback` and\n // records the id in `_meta.enricherErrors`.\n const enriched = await applyResponseEnricherToRecord(detail, 'messages.message', {\n organizationId: scope.organizationId ?? '',\n tenantId: scope.tenantId,\n userId: scope.userId,\n em,\n container: ctx.container,\n userFeatures: await resolveGrantedFeatures(ctx.container, scope),\n })\n\n if (enriched._meta.enrichedBy.length > 0 || enriched._meta.enricherErrors?.length) {\n return Response.json({ ...enriched.record, _meta: enriched._meta })\n }\n\n return Response.json(enriched.record)\n}\n\nexport async function PATCH(req: Request, { params }: { params: { id: string } }) {\n const { ctx, scope } = await resolveMessageContext(req)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const commandBus = ctx.container.resolve('commandBus') as CommandBus\n const body = await req.json().catch(() => ({}))\n const input = updateDraftSchema.parse(body)\n\n const message = await em.findOne(Message, {\n id: params.id,\n tenantId: scope.tenantId,\n deletedAt: null,\n })\n\n if (!message) {\n return Response.json({ error: 'Message not found' }, { status: 404 })\n }\n\n if (!hasOrganizationAccess(scope.organizationId, message.organizationId)) {\n return Response.json({ error: 'Access denied' }, { status: 403 })\n }\n\n if (message.senderUserId !== scope.userId) {\n return Response.json({ error: 'Access denied' }, { status: 403 })\n }\n\n if (!message.isDraft) {\n return Response.json({ error: 'Only draft messages can be edited' }, { status: 409 })\n }\n\n // `sendAsUser` composes a fresh message rather than updating an existing\n // one, so sending a saved draft through a connected mailbox is not\n // implemented yet. Refuse explicitly instead of silently stripping the\n // field and falling back to the platform sender.\n if (input.senderChannelId) {\n const { t } = await resolveTranslations()\n const errorMessage = t(\n 'messages.errors.senderDraftSendUnsupported',\n 'Sending a saved draft through a connected mailbox is not supported yet.',\n )\n return Response.json(\n { error: errorMessage, fieldErrors: { senderChannelId: errorMessage } },\n { status: 422 },\n )\n }\n\n // A draft is filed on its parent's thread and skips the compose route's\n // channel gate, so sending it publicly must pass the same gate (#6432).\n const finalVisibility = input.visibility !== undefined ? input.visibility : message.visibility\n if (\n input.isDraft === false &&\n finalVisibility === 'public' &&\n !(await canPostToChannelThread(ctx, scope, message.threadId ?? message.id))\n ) {\n return Response.json({ error: 'Access denied' }, { status: 403 })\n }\n\n const guardResult = await runMessageMutationGuards(\n ctx.container,\n {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n resourceKind: 'messages.message',\n resourceId: message.id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: input as Record<string, unknown>,\n },\n resolveUserFeatures(ctx.auth),\n )\n if (!guardResult.ok) {\n return Response.json(\n guardResult.errorBody ?? { error: 'Operation blocked by guard' },\n { status: guardResult.errorStatus ?? 422 },\n )\n }\n\n try {\n // Reject stale draft edits/sends before mutating: compare the client's\n // expected version (extension header) against the loaded draft.\n enforceCommandOptimisticLock({\n resourceKind: MESSAGE_OPTIMISTIC_LOCK_RESOURCE_KIND,\n resourceId: message.id,\n current: message.updatedAt,\n request: req,\n })\n\n const { logEntry } = await commandBus.execute('messages.messages.update_draft', {\n input: {\n ...input,\n messageId: message.id,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n },\n ctx: {\n container: ctx.container,\n auth: ctx.auth ?? null,\n organizationScope: null,\n selectedOrganizationId: scope.organizationId,\n organizationIds: scope.organizationId ? [scope.organizationId] : null,\n request: req,\n },\n })\n\n const response = Response.json({ ok: true, id: message.id })\n attachOperationMetadataHeader(response, logEntry, {\n resourceKind: 'messages.message',\n resourceId: message.id,\n })\n await runMessageMutationGuardAfterSuccess(guardResult.afterSuccessCallbacks, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n resourceKind: 'messages.message',\n resourceId: message.id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n })\n return response\n } catch (error) {\n if (isCrudHttpError(error)) {\n return Response.json(error.body, { status: error.status })\n }\n const interceptorRejection = getCommandInterceptorHttpRejection(error)\n if (interceptorRejection) {\n return Response.json(interceptorRejection.body, { status: interceptorRejection.status })\n }\n if (error instanceof Error) {\n if (error.message === 'Message type cannot be created by users') {\n return Response.json({ error: error.message }, { status: 400 })\n }\n if (error.message === 'Only draft messages can be edited') {\n return Response.json({ error: error.message }, { status: 409 })\n }\n if (error.message === 'Access denied') {\n return Response.json({ error: error.message }, { status: 403 })\n }\n }\n throw error\n }\n\n}\n\nexport async function DELETE(req: Request, { params }: { params: { id: string } }) {\n const { ctx, scope } = await resolveMessageContext(req)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const commandBus = ctx.container.resolve('commandBus') as CommandBus\n\n const message = await em.findOne(Message, {\n id: params.id,\n tenantId: scope.tenantId,\n deletedAt: null,\n })\n\n if (!message) {\n return Response.json({ error: 'Message not found' }, { status: 404 })\n }\n\n if (!hasOrganizationAccess(scope.organizationId, message.organizationId)) {\n return Response.json({ error: 'Access denied' }, { status: 403 })\n }\n\n const isSender = message.senderUserId === scope.userId\n // Only look the recipient row up when the actor is not the sender: deleting one's own\n // message is the common path, and the lookup is a decryption-aware query.\n const isRecipient = isSender\n ? false\n : Boolean(await findOneWithDecryption(\n em,\n MessageRecipient,\n {\n messageId: params.id,\n recipientUserId: scope.userId,\n deletedAt: null,\n },\n undefined,\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n ))\n\n if (!isSender && !isRecipient) {\n return Response.json({ error: 'Access denied' }, { status: 403 })\n }\n\n const guardResult = await runMessageMutationGuards(\n ctx.container,\n {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n resourceKind: 'messages.message',\n resourceId: params.id,\n operation: 'delete',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: null,\n },\n resolveUserFeatures(ctx.auth),\n )\n if (!guardResult.ok) {\n return Response.json(\n guardResult.errorBody ?? { error: 'Operation blocked by guard' },\n { status: guardResult.errorStatus ?? 422 },\n )\n }\n\n try {\n // Reject a stale delete before mutating: a tab that loaded an older version\n // of the message must refresh rather than silently delete a changed record.\n enforceCommandOptimisticLock({\n resourceKind: MESSAGE_OPTIMISTIC_LOCK_RESOURCE_KIND,\n resourceId: message.id,\n current: message.updatedAt,\n request: req,\n })\n\n const { logEntry } = await commandBus.execute('messages.messages.delete_for_actor', {\n input: {\n messageId: params.id,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n },\n ctx: {\n container: ctx.container,\n auth: ctx.auth ?? null,\n organizationScope: null,\n selectedOrganizationId: scope.organizationId,\n organizationIds: scope.organizationId ? [scope.organizationId] : null,\n request: req,\n },\n })\n\n const response = Response.json({ ok: true })\n attachOperationMetadataHeader(response, logEntry, {\n resourceKind: 'messages.message',\n resourceId: params.id,\n })\n await runMessageMutationGuardAfterSuccess(guardResult.afterSuccessCallbacks, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n resourceKind: 'messages.message',\n resourceId: params.id,\n operation: 'delete',\n requestMethod: req.method,\n requestHeaders: req.headers,\n })\n return response\n } catch (error) {\n if (isCrudHttpError(error)) {\n return Response.json(error.body, { status: error.status })\n }\n const interceptorRejection = getCommandInterceptorHttpRejection(error)\n if (interceptorRejection) {\n return Response.json(interceptorRejection.body, { status: interceptorRejection.status })\n }\n if (error instanceof Error && error.message === 'Access denied') {\n return Response.json({ error: 'Access denied' }, { status: 403 })\n }\n throw error\n }\n\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Messages',\n methods: {\n GET: {\n summary: 'Get message detail',\n responses: [\n {\n status: 200,\n description: 'Message detail with actor-visible thread items only',\n schema: messageDetailResponseSchema,\n },\n ],\n errors: [\n { status: 403, description: 'Access denied', schema: errorResponseSchema },\n { status: 404, description: 'Message not found', schema: errorResponseSchema },\n ],\n },\n PATCH: {\n summary: 'Update draft message',\n requestBody: { schema: updateDraftOpenApiSchema },\n responses: [\n { status: 200, description: 'Draft updated', schema: okResponseSchema },\n ],\n errors: [\n { status: 403, description: 'Access denied', schema: errorResponseSchema },\n { status: 404, description: 'Message not found', schema: errorResponseSchema },\n { status: 409, description: 'Only drafts can be edited, or the draft was modified concurrently (optimistic lock conflict)', schema: errorResponseSchema },\n ],\n },\n DELETE: {\n summary: 'Delete message for current sender/recipient context',\n responses: [\n { status: 200, description: 'Message deleted', schema: okResponseSchema },\n ],\n errors: [\n { status: 403, description: 'Access denied', schema: errorResponseSchema },\n { status: 404, description: 'Message not found', schema: errorResponseSchema },\n { status: 409, description: 'Message was modified concurrently (optimistic lock conflict)', schema: errorResponseSchema },\n ],\n },\n },\n}\n"],
|
|
5
|
-
"mappings": "AAGA,SAAS,uBAAuB;AAChC,SAAS,qCAAqC;AAC9C,SAAS,oCAAoC;AAC7C,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,2BAA2B;AACpC,SAAS,YAAY;AACrB,SAAS,SAAS,eAAe,wBAAwB;AACzD,SAAS,yBAAyB;AAClC,SAAS,mCAAmC;AAC5C,SAAS,6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AW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,iBAAiB,QAAQ,iBAAiB;AAAA,MACxE;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,iBAAiB,QAAQ,oBAAoB;AAAA,QACzE,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,oBAAoB;AAAA,QAC7E,EAAE,QAAQ,KAAK,aAAa,gGAAgG,QAAQ,oBAAoB;AAAA,MAC1J;AAAA,IACF;AAAA,IACA,QAAQ;AAAA,MACN,SAAS;AAAA,MACT,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,mBAAmB,QAAQ,iBAAiB;AAAA,MAC1E;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,iBAAiB,QAAQ,oBAAoB;AAAA,QACzE,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,oBAAoB;AAAA,QAC7E,EAAE,QAAQ,KAAK,aAAa,gEAAgE,QAAQ,oBAAoB;AAAA,MAC1H;AAAA,IACF;AAAA,EACF;AACF;",
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { CommandBus } from '@open-mercato/shared/lib/commands/command-bus'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi/types'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { applyResponseEnricherToRecord } from '@open-mercato/shared/lib/crud/enricher-runner'\nimport { enforceCommandOptimisticLock } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { User } from '../../../auth/data/entities'\nimport { Message, MessageObject, MessageRecipient } from '../../data/entities'\nimport { updateDraftSchema } from '../../data/validators'\nimport { buildResolvedMessageActions } from '../../lib/actions'\nimport { MESSAGE_OPTIMISTIC_LOCK_RESOURCE_KIND } from '../../lib/constants'\nimport { getMessageObjectType } from '../../lib/message-objects-registry'\nimport { getMessageTypeOrDefault } from '../../lib/message-types-registry'\nimport { attachOperationMetadataHeader } from '../../lib/operationMetadata'\nimport {\n canPostToChannelThread,\n hasOrganizationAccess,\n resolveMessageContext,\n resolveMessageReadAccess,\n} from '../../lib/routeHelpers'\nimport { resolveUserFeatures, runMessageMutationGuardAfterSuccess, runMessageMutationGuards } from '../guards'\nimport {\n errorResponseSchema,\n messageDetailResponseSchema,\n okResponseSchema,\n updateDraftSchema as updateDraftOpenApiSchema,\n} from '../openapi'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getCommandInterceptorHttpRejection } from '@open-mercato/shared/lib/commands/errors'\n\nconst logger = createLogger('messages').child({ component: 'api' })\n\nexport const metadata = {\n GET: { requireAuth: true },\n PATCH: { requireAuth: true, requireFeatures: ['messages.compose'] },\n DELETE: { requireAuth: true, requireFeatures: ['messages.view'] },\n}\n\ntype MessageObjectPreviewPayload = {\n title: string\n subtitle?: string\n status?: string\n statusColor?: string\n metadata?: Record<string, string>\n} | null\n\ntype RbacServiceLike = {\n getGrantedFeatures?: (\n userId: string,\n scope: { tenantId: string | null; organizationId: string | null },\n ) => Promise<string[]>\n}\n\n/**\n * Feature list for the enricher ACL gate, resolved from RBAC.\n *\n * Mirrors `customers/api/interactions/route.ts`. Returning `undefined` on\n * failure is deliberate \u2014 the runner then treats every feature-gated enricher\n * as denied, which is the safe direction.\n */\nasync function resolveGrantedFeatures(\n container: { resolve: (name: string) => unknown },\n scope: { tenantId: string; organizationId: string | null; userId: string },\n): Promise<string[] | undefined> {\n try {\n const rbac = container.resolve('rbacService') as RbacServiceLike | undefined\n if (!rbac?.getGrantedFeatures) return undefined\n return await rbac.getGrantedFeatures(scope.userId, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n } catch {\n return undefined\n }\n}\n\nexport async function GET(req: Request, { params }: { params: { id: string } }) {\n const { ctx, scope } = await resolveMessageContext(req)\n const em = ctx.container.resolve('em') as EntityManager\n const url = new URL(req.url)\n const skipMarkReadParam = url.searchParams.get('skipMarkRead')\n const skipMarkRead = skipMarkReadParam === '1'\n\n const message = await findOneWithDecryption(\n em,\n Message,\n {\n id: params.id,\n tenantId: scope.tenantId,\n deletedAt: null,\n },\n undefined,\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n\n if (!message) {\n return Response.json({ error: 'Message not found' }, { status: 404 })\n }\n\n if (!hasOrganizationAccess(scope.organizationId, message.organizationId)) {\n return Response.json({ error: 'Access denied' }, { status: 403 })\n }\n\n const { recipient, isSender, hasChannelThreadAccess } = await resolveMessageReadAccess(ctx, scope, message)\n const isRecipient = Boolean(recipient)\n\n // #5535: a message that arrived over a communication channel has the channel\n // system user as its sender and, on an unassigned conversation, no recipient\n // rows \u2014 so the participant test below denies every operator and the reply\n // button is unreachable. For a thread the channels hub owns, that hub's access\n // rule applies instead; an internal thread resolves to `null` and keeps the\n // participant rule unchanged.\n //\n // `hasChannelThreadReadAccess` feature-gates the fallback before consulting the\n // hub, because `assertCanAccessChannel` \u2014 the rule behind it \u2014 deliberately\n // ignores features and returns for EVERY shared channel; its documented\n // precondition is a caller the route already feature-gated, and this route is\n // `requireAuth` only so that a participant can always read their own message.\n // The gate goes through RBAC, not through `ctx.auth.features` \u2014 the session JWT\n // carries no `features` claim at all, so reading it would deny everyone.\n\n if (!isSender && !isRecipient && !hasChannelThreadAccess) {\n return Response.json({ error: 'Access denied' }, { status: 403 })\n }\n\n // Channel access says \"you may work this conversation\", not \"you may read what\n // other operators kept off it\". An internal note stays participant-only however\n // the caller reached the thread.\n //\n // The test is \"not explicitly public\" rather than \"explicitly internal\":\n // `data/validators.ts` refines a compose under `value.visibility ?? 'internal'`\n // and `composeMessageCommand` persists `input.visibility ?? null`, so a caller\n // that omits the field files a message the module itself validated as internal\n // yet stored as `null`. `ingest-inbound-message.ts` stamps the inbound message\n // `'public'` and the reply/forward commands copy it forward, so the journey\n // this route exists for is unaffected.\n if (!isSender && !isRecipient && message.visibility !== 'public') {\n return Response.json({ error: 'Access denied' }, { status: 403 })\n }\n\n const autoMarkRead = !skipMarkRead && recipient?.status === 'unread'\n const readAt = autoMarkRead ? new Date() : recipient?.readAt ?? null\n\n const objects = await em.find(MessageObject, { messageId: params.id })\n const objectPreviews = await Promise.all(\n objects.map(async (item): Promise<MessageObjectPreviewPayload> => {\n const objectType = getMessageObjectType(item.entityModule, item.entityType)\n if (!objectType?.loadPreview) return null\n try {\n return await objectType.loadPreview(item.entityId, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n } catch (error) {\n logger.error('Failed to load preview', { entityModule: item.entityModule, entityType: item.entityType, entityId: item.entityId, err: error })\n return null\n }\n }),\n )\n const allRecipients = await em.find(MessageRecipient, { messageId: params.id, deletedAt: null })\n\n const threadMessages = await findWithDecryption(\n em,\n Message,\n {\n threadId: message.threadId ?? message.id,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n isDraft: false,\n },\n { orderBy: { sentAt: 'ASC' } },\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n const threadMessageIds = threadMessages.map((item) => item.id)\n const visibleRecipientRows = threadMessageIds.length > 0\n ? await em.find(MessageRecipient, {\n messageId: { $in: threadMessageIds },\n recipientUserId: scope.userId,\n deletedAt: null,\n })\n : []\n const visibleRecipientMessageIds = new Set(visibleRecipientRows.map((item) => item.messageId))\n // On a channel-linked thread the conversation IS the thread: the correspondent\n // is not a platform user, so filtering by participation would hide the inbound\n // messages and every other operator's answer, leaving the operator looking at\n // half a conversation (#5535).\n //\n // Internal notes are the exception: they are addressed to platform\n // participants, so they keep the participant rule even on a channel thread.\n // Same polarity as the direct-read gate above \u2014 an absent visibility is\n // internal by the messages module's own convention, so only an explicitly\n // public message is shown to a non-participant.\n const isThreadMessageParticipant = (threadMessage: { id: string; senderUserId?: string | null }) => (\n threadMessage.senderUserId === scope.userId || visibleRecipientMessageIds.has(threadMessage.id)\n )\n const actorVisibleThreadMessages = hasChannelThreadAccess\n ? threadMessages.filter((threadMessage) => (\n threadMessage.visibility === 'public' || isThreadMessageParticipant(threadMessage)\n ))\n : threadMessages.filter(isThreadMessageParticipant)\n\n const actorRecipientStatusByMessageId = new Map<string, string>()\n for (const row of visibleRecipientRows) {\n actorRecipientStatusByMessageId.set(row.messageId, row.status)\n }\n if (recipient) {\n actorRecipientStatusByMessageId.set(params.id, autoMarkRead ? 'read' : recipient.status)\n }\n const actorRecipientStatuses = Array.from(actorRecipientStatusByMessageId.values())\n const conversationArchived = actorRecipientStatuses.length > 0\n && actorRecipientStatuses.every((status) => status === 'archived')\n const conversationAllUnread = actorRecipientStatuses.length > 0\n && actorRecipientStatuses.every((status) => status === 'unread')\n\n const threadSenderIds = actorVisibleThreadMessages\n .map((threadMessage) => threadMessage.senderUserId)\n .filter((value): value is string => typeof value === 'string' && value.length > 0)\n\n const threadSenders = threadSenderIds.length > 0\n ? await findWithDecryption(\n em,\n User,\n { id: { $in: Array.from(new Set(threadSenderIds)) } },\n undefined,\n { tenantId: scope.tenantId, organizationId: scope.organizationId }\n )\n : []\n\n const threadSenderMap = new Map(threadSenders.map((user) => [user.id, user]))\n\n const senderUser = await findOneWithDecryption(\n em,\n User,\n { id: message.senderUserId },\n undefined,\n { tenantId: scope.tenantId, organizationId: scope.organizationId }\n )\n\n const senderName = typeof senderUser?.name === 'string' && senderUser.name.trim().length\n ? senderUser.name.trim()\n : null\n const senderEmail = senderUser?.email ?? null\n\n const messageType = getMessageTypeOrDefault(message.type)\n const resolvedActionData = buildResolvedMessageActions(message, objects)\n\n if (autoMarkRead) {\n const commandBus = ctx.container.resolve('commandBus') as CommandBus\n await commandBus.execute('messages.recipients.mark_read', {\n input: {\n messageId: params.id,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n },\n ctx: {\n container: ctx.container,\n auth: ctx.auth ?? null,\n organizationScope: null,\n selectedOrganizationId: scope.organizationId,\n organizationIds: scope.organizationId ? [scope.organizationId] : null,\n request: req,\n },\n })\n }\n\n const detail: Record<string, unknown> = {\n id: message.id,\n updatedAt: message.updatedAt ?? null,\n type: message.type,\n isDraft: message.isDraft,\n canEditDraft: message.isDraft && message.senderUserId === scope.userId,\n canArchive: Boolean(recipient),\n isArchived: recipient?.status === 'archived',\n visibility: message.visibility,\n sourceEntityType: message.sourceEntityType,\n sourceEntityId: message.sourceEntityId,\n externalEmail: message.externalEmail,\n externalName: message.externalName,\n typeDefinition: {\n labelKey: messageType.labelKey,\n icon: messageType.icon,\n color: messageType.color,\n allowReply: messageType.allowReply ?? true,\n allowForward: messageType.allowForward ?? true,\n ui: {\n listItemComponent: messageType.ui?.listItemComponent ?? null,\n contentComponent: messageType.ui?.contentComponent ?? null,\n actionsComponent: messageType.ui?.actionsComponent ?? null,\n },\n },\n threadId: message.threadId,\n parentMessageId: message.parentMessageId,\n senderUserId: message.senderUserId,\n senderName,\n senderEmail,\n subject: message.subject,\n body: message.body,\n bodyFormat: message.bodyFormat,\n priority: message.priority,\n sentAt: message.sentAt,\n actionData: resolvedActionData,\n actionTaken: message.actionTaken,\n actionTakenAt: message.actionTakenAt,\n actionTakenByUserId: message.actionTakenByUserId,\n recipients: allRecipients.map((item) => ({\n userId: item.recipientUserId,\n type: item.recipientType,\n status: autoMarkRead && item.recipientUserId === scope.userId ? 'read' : item.status,\n readAt: autoMarkRead && item.recipientUserId === scope.userId ? readAt : item.readAt,\n })),\n objects: objects.map((item, index) => ({\n id: item.id,\n entityModule: item.entityModule,\n entityType: item.entityType,\n entityId: item.entityId,\n actionRequired: item.actionRequired,\n actionType: item.actionType,\n actionLabel: item.actionLabel,\n snapshot: item.entitySnapshot,\n preview: objectPreviews[index] ?? null,\n })),\n thread: actorVisibleThreadMessages.map((threadMessage) => {\n const sender = threadSenderMap.get(threadMessage.senderUserId)\n const threadSenderName = typeof sender?.name === 'string' && sender.name.trim().length\n ? sender.name.trim()\n : null\n\n return {\n id: threadMessage.id,\n senderUserId: threadMessage.senderUserId,\n senderName: threadSenderName,\n senderEmail: sender?.email ?? null,\n externalName: threadMessage.externalName ?? null,\n externalEmail: threadMessage.externalEmail ?? null,\n sourceEntityType: threadMessage.sourceEntityType ?? null,\n body: threadMessage.body,\n bodyFormat: threadMessage.bodyFormat,\n sentAt: threadMessage.sentAt,\n }\n }),\n isRead: recipient ? (autoMarkRead || recipient.status !== 'unread') : true,\n conversationArchived,\n conversationAllUnread,\n }\n\n // Mirrors `enrichSingleRecord` in `shared/lib/crud/factory.ts`, which every\n // `makeCrudRoute` host gets for free: same `_meta` envelope, and no blanket\n // catch so a `critical: true` enricher still surfaces as an HTTP error.\n // Non-critical failures never escape the runner \u2014 it merges `fallback` and\n // records the id in `_meta.enricherErrors`.\n const enriched = await applyResponseEnricherToRecord(detail, 'messages.message', {\n organizationId: scope.organizationId ?? '',\n tenantId: scope.tenantId,\n userId: scope.userId,\n em,\n container: ctx.container,\n userFeatures: await resolveGrantedFeatures(ctx.container, scope),\n })\n\n if (enriched._meta.enrichedBy.length > 0 || enriched._meta.enricherErrors?.length) {\n return Response.json({ ...enriched.record, _meta: enriched._meta })\n }\n\n return Response.json(enriched.record)\n}\n\nexport async function PATCH(req: Request, { params }: { params: { id: string } }) {\n const { ctx, scope } = await resolveMessageContext(req)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const commandBus = ctx.container.resolve('commandBus') as CommandBus\n const body = await req.json().catch(() => ({}))\n const input = updateDraftSchema.parse(body)\n\n const message = await em.findOne(Message, {\n id: params.id,\n tenantId: scope.tenantId,\n deletedAt: null,\n })\n\n if (!message) {\n return Response.json({ error: 'Message not found' }, { status: 404 })\n }\n\n if (!hasOrganizationAccess(scope.organizationId, message.organizationId)) {\n return Response.json({ error: 'Access denied' }, { status: 403 })\n }\n\n if (message.senderUserId !== scope.userId) {\n return Response.json({ error: 'Access denied' }, { status: 403 })\n }\n\n if (!message.isDraft) {\n return Response.json({ error: 'Only draft messages can be edited' }, { status: 409 })\n }\n\n // `sendAsUser` composes a fresh message rather than updating an existing\n // one, so sending a saved draft through a connected mailbox is not\n // implemented yet. Refuse explicitly instead of silently stripping the\n // field and falling back to the platform sender.\n if (input.senderChannelId) {\n const { t } = await resolveTranslations()\n const errorMessage = t(\n 'messages.errors.senderDraftSendUnsupported',\n 'Sending a saved draft through a connected mailbox is not supported yet.',\n )\n return Response.json(\n { error: errorMessage, fieldErrors: { senderChannelId: errorMessage } },\n { status: 422 },\n )\n }\n\n // A draft is filed on its parent's thread and skips the compose route's\n // channel gate, so sending it publicly must pass the same gate (#6432).\n const finalVisibility = input.visibility !== undefined ? input.visibility : message.visibility\n if (\n input.isDraft === false &&\n finalVisibility === 'public' &&\n !(await canPostToChannelThread(ctx, scope, message.threadId ?? message.id))\n ) {\n return Response.json({ error: 'Access denied' }, { status: 403 })\n }\n\n const guardResult = await runMessageMutationGuards(\n ctx.container,\n {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n resourceKind: 'messages.message',\n resourceId: message.id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: input as Record<string, unknown>,\n },\n resolveUserFeatures(ctx.auth),\n )\n if (!guardResult.ok) {\n return Response.json(\n guardResult.errorBody ?? { error: 'Operation blocked by guard' },\n { status: guardResult.errorStatus ?? 422 },\n )\n }\n\n try {\n // Reject stale draft edits/sends before mutating: compare the client's\n // expected version (extension header) against the loaded draft.\n enforceCommandOptimisticLock({\n resourceKind: MESSAGE_OPTIMISTIC_LOCK_RESOURCE_KIND,\n resourceId: message.id,\n current: message.updatedAt,\n request: req,\n })\n\n const { logEntry } = await commandBus.execute('messages.messages.update_draft', {\n input: {\n ...input,\n messageId: message.id,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n },\n ctx: {\n container: ctx.container,\n auth: ctx.auth ?? null,\n organizationScope: null,\n selectedOrganizationId: scope.organizationId,\n organizationIds: scope.organizationId ? [scope.organizationId] : null,\n request: req,\n },\n })\n\n const response = Response.json({ ok: true, id: message.id })\n attachOperationMetadataHeader(response, logEntry, {\n resourceKind: 'messages.message',\n resourceId: message.id,\n })\n await runMessageMutationGuardAfterSuccess(guardResult.afterSuccessCallbacks, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n resourceKind: 'messages.message',\n resourceId: message.id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n })\n return response\n } catch (error) {\n if (isCrudHttpError(error)) {\n return Response.json(error.body, { status: error.status })\n }\n const interceptorRejection = getCommandInterceptorHttpRejection(error)\n if (interceptorRejection) {\n return Response.json(interceptorRejection.body, { status: interceptorRejection.status })\n }\n if (error instanceof Error) {\n if (error.message === 'Message type cannot be created by users') {\n return Response.json({ error: error.message }, { status: 400 })\n }\n if (error.message === 'Only draft messages can be edited') {\n return Response.json({ error: error.message }, { status: 409 })\n }\n if (error.message === 'Access denied') {\n return Response.json({ error: error.message }, { status: 403 })\n }\n }\n throw error\n }\n\n}\n\nexport async function DELETE(req: Request, { params }: { params: { id: string } }) {\n const { ctx, scope } = await resolveMessageContext(req)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const commandBus = ctx.container.resolve('commandBus') as CommandBus\n\n const message = await em.findOne(Message, {\n id: params.id,\n tenantId: scope.tenantId,\n deletedAt: null,\n })\n\n if (!message) {\n return Response.json({ error: 'Message not found' }, { status: 404 })\n }\n\n if (!hasOrganizationAccess(scope.organizationId, message.organizationId)) {\n return Response.json({ error: 'Access denied' }, { status: 403 })\n }\n\n const isSender = message.senderUserId === scope.userId\n // Only look the recipient row up when the actor is not the sender: deleting one's own\n // message is the common path, and the lookup is a decryption-aware query.\n const isRecipient = isSender\n ? false\n : Boolean(await findOneWithDecryption(\n em,\n MessageRecipient,\n {\n messageId: params.id,\n recipientUserId: scope.userId,\n deletedAt: null,\n },\n undefined,\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n ))\n\n if (!isSender && !isRecipient) {\n return Response.json({ error: 'Access denied' }, { status: 403 })\n }\n\n const guardResult = await runMessageMutationGuards(\n ctx.container,\n {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n resourceKind: 'messages.message',\n resourceId: params.id,\n operation: 'delete',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: null,\n },\n resolveUserFeatures(ctx.auth),\n )\n if (!guardResult.ok) {\n return Response.json(\n guardResult.errorBody ?? { error: 'Operation blocked by guard' },\n { status: guardResult.errorStatus ?? 422 },\n )\n }\n\n try {\n // Reject a stale delete before mutating: a tab that loaded an older version\n // of the message must refresh rather than silently delete a changed record.\n enforceCommandOptimisticLock({\n resourceKind: MESSAGE_OPTIMISTIC_LOCK_RESOURCE_KIND,\n resourceId: message.id,\n current: message.updatedAt,\n request: req,\n })\n\n const { logEntry } = await commandBus.execute('messages.messages.delete_for_actor', {\n input: {\n messageId: params.id,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n },\n ctx: {\n container: ctx.container,\n auth: ctx.auth ?? null,\n organizationScope: null,\n selectedOrganizationId: scope.organizationId,\n organizationIds: scope.organizationId ? [scope.organizationId] : null,\n request: req,\n },\n })\n\n const response = Response.json({ ok: true })\n attachOperationMetadataHeader(response, logEntry, {\n resourceKind: 'messages.message',\n resourceId: params.id,\n })\n await runMessageMutationGuardAfterSuccess(guardResult.afterSuccessCallbacks, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n resourceKind: 'messages.message',\n resourceId: params.id,\n operation: 'delete',\n requestMethod: req.method,\n requestHeaders: req.headers,\n })\n return response\n } catch (error) {\n if (isCrudHttpError(error)) {\n return Response.json(error.body, { status: error.status })\n }\n const interceptorRejection = getCommandInterceptorHttpRejection(error)\n if (interceptorRejection) {\n return Response.json(interceptorRejection.body, { status: interceptorRejection.status })\n }\n if (error instanceof Error && error.message === 'Access denied') {\n return Response.json({ error: 'Access denied' }, { status: 403 })\n }\n throw error\n }\n\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Messages',\n methods: {\n GET: {\n summary: 'Get message detail',\n responses: [\n {\n status: 200,\n description: 'Message detail with actor-visible thread items only',\n schema: messageDetailResponseSchema,\n },\n ],\n errors: [\n { status: 403, description: 'Access denied', schema: errorResponseSchema },\n { status: 404, description: 'Message not found', schema: errorResponseSchema },\n ],\n },\n PATCH: {\n summary: 'Update draft message',\n requestBody: { schema: updateDraftOpenApiSchema },\n responses: [\n { status: 200, description: 'Draft updated', schema: okResponseSchema },\n ],\n errors: [\n { status: 403, description: 'Access denied', schema: errorResponseSchema },\n { status: 404, description: 'Message not found', schema: errorResponseSchema },\n { status: 409, description: 'Only drafts can be edited, or the draft was modified concurrently (optimistic lock conflict)', schema: errorResponseSchema },\n ],\n },\n DELETE: {\n summary: 'Delete message for current sender/recipient context',\n responses: [\n { status: 200, description: 'Message deleted', schema: okResponseSchema },\n ],\n errors: [\n { status: 403, description: 'Access denied', schema: errorResponseSchema },\n { status: 404, description: 'Message not found', schema: errorResponseSchema },\n { status: 409, description: 'Message was modified concurrently (optimistic lock conflict)', schema: errorResponseSchema },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAGA,SAAS,uBAAuB;AAChC,SAAS,qCAAqC;AAC9C,SAAS,oCAAoC;AAC7C,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,2BAA2B;AACpC,SAAS,YAAY;AACrB,SAAS,SAAS,eAAe,wBAAwB;AACzD,SAAS,yBAAyB;AAClC,SAAS,mCAAmC;AAC5C,SAAS,6CAA6C;AACtD,SAAS,4BAA4B;AACrC,SAAS,+BAA+B;AACxC,SAAS,qCAAqC;AAC9C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,qBAAqB,qCAAqC,gCAAgC;AACnG;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA,qBAAqB;AAAA,OAChB;AACP,SAAS,oBAAoB;AAC7B,SAAS,0CAA0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MAC1E;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,iBAAiB,QAAQ,oBAAoB;AAAA,QACzE,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,oBAAoB;AAAA,QAC7E,EAAE,QAAQ,KAAK,aAAa,gEAAgE,QAAQ,oBAAoB;AAAA,MAC1H;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
normalizeTagSegment,
|
|
10
10
|
resolveCrudCache
|
|
11
11
|
} from "@open-mercato/shared/lib/crud/cache";
|
|
12
|
-
import {
|
|
12
|
+
import { findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
13
13
|
import { lookupHashCandidates } from "@open-mercato/shared/lib/encryption/aes";
|
|
14
14
|
import { User } from "../../auth/data/entities.js";
|
|
15
15
|
import { Message, MessageObject } from "../data/entities.js";
|
|
@@ -33,6 +33,7 @@ import { attachOperationMetadataHeader } from "../lib/operationMetadata.js";
|
|
|
33
33
|
import {
|
|
34
34
|
canPostToChannelThread,
|
|
35
35
|
canUseChannelThreadFallback,
|
|
36
|
+
resolveReplyParentMessage,
|
|
36
37
|
canUseMessageEmailFeature,
|
|
37
38
|
resolveMessageContext
|
|
38
39
|
} from "../lib/routeHelpers.js";
|
|
@@ -42,6 +43,7 @@ import { findMessageIdsBySearchTokens } from "../lib/searchLookup.js";
|
|
|
42
43
|
import {
|
|
43
44
|
composeMessageRequestSchema as composeSchema,
|
|
44
45
|
composeResponseSchema,
|
|
46
|
+
errorResponseSchema,
|
|
45
47
|
listMessagesSchema as listSchema,
|
|
46
48
|
messageListItemSchema
|
|
47
49
|
} from "./openapi.js";
|
|
@@ -327,6 +329,30 @@ async function POST(req) {
|
|
|
327
329
|
return Response.json({ error: objectValidationError }, { status: 400 });
|
|
328
330
|
}
|
|
329
331
|
}
|
|
332
|
+
let replyParent = null;
|
|
333
|
+
if (input.parentMessageId) {
|
|
334
|
+
const resolution = await resolveReplyParentMessage(
|
|
335
|
+
ctx,
|
|
336
|
+
{ tenantId: scope.tenantId, organizationId: scope.organizationId ?? null, userId: scope.userId },
|
|
337
|
+
input.parentMessageId
|
|
338
|
+
);
|
|
339
|
+
if (resolution.status === "not_found") {
|
|
340
|
+
const { translate } = await resolveTranslations();
|
|
341
|
+
return Response.json(
|
|
342
|
+
{
|
|
343
|
+
error: translate(
|
|
344
|
+
"messages.errors.parentMessageNotFound",
|
|
345
|
+
"The message you are replying to was not found"
|
|
346
|
+
)
|
|
347
|
+
},
|
|
348
|
+
{ status: 404 }
|
|
349
|
+
);
|
|
350
|
+
}
|
|
351
|
+
if (resolution.status === "forbidden") {
|
|
352
|
+
return Response.json({ error: "Access denied" }, { status: 403 });
|
|
353
|
+
}
|
|
354
|
+
replyParent = resolution.message;
|
|
355
|
+
}
|
|
330
356
|
let composeParentMessageId = input.parentMessageId;
|
|
331
357
|
if (isPublicVisibility && !input.isDraft && !input.parentMessageId && input.sourceEntityType === EXTERNAL_CONVERSATION_SOURCE_ENTITY_TYPE && input.sourceEntityId) {
|
|
332
358
|
const channelThread = await resolveMessageChannelThreadAccess(
|
|
@@ -352,21 +378,8 @@ async function POST(req) {
|
|
|
352
378
|
}
|
|
353
379
|
composeParentMessageId = channelThread.messageThreadId;
|
|
354
380
|
}
|
|
355
|
-
if (isPublicVisibility && !input.isDraft &&
|
|
356
|
-
const
|
|
357
|
-
const parentMessage = await findOneWithDecryption(
|
|
358
|
-
em,
|
|
359
|
-
Message,
|
|
360
|
-
{
|
|
361
|
-
id: input.parentMessageId,
|
|
362
|
-
tenantId: scope.tenantId,
|
|
363
|
-
organizationId: scope.organizationId,
|
|
364
|
-
deletedAt: null
|
|
365
|
-
},
|
|
366
|
-
void 0,
|
|
367
|
-
{ tenantId: scope.tenantId, organizationId: scope.organizationId }
|
|
368
|
-
);
|
|
369
|
-
const parentThreadId = parentMessage?.threadId ?? input.parentMessageId;
|
|
381
|
+
if (isPublicVisibility && !input.isDraft && replyParent) {
|
|
382
|
+
const parentThreadId = replyParent.threadId ?? replyParent.id;
|
|
370
383
|
if (!await canPostToChannelThread(ctx, scope, parentThreadId)) {
|
|
371
384
|
return Response.json({ error: "Access denied" }, { status: 403 });
|
|
372
385
|
}
|
|
@@ -492,6 +505,10 @@ const openApi = {
|
|
|
492
505
|
description: "Message created",
|
|
493
506
|
schema: composeResponseSchema
|
|
494
507
|
}
|
|
508
|
+
],
|
|
509
|
+
errors: [
|
|
510
|
+
{ status: 403, description: "Access denied, including a parentMessageId the caller cannot read", schema: errorResponseSchema },
|
|
511
|
+
{ status: 404, description: "parentMessageId is unknown, deleted, or outside the caller organization", schema: errorResponseSchema }
|
|
495
512
|
]
|
|
496
513
|
}
|
|
497
514
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/messages/api/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { createHash } from 'node:crypto'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { type Kysely, sql } from 'kysely'\nimport { runWithCacheTenant } from '@open-mercato/cache'\nimport type { CommandBus } from '@open-mercato/shared/lib/commands/command-bus'\nimport {\n buildCollectionTags,\n debugCrudCache,\n isCrudCacheEnabled,\n normalizeTagSegment,\n resolveCrudCache,\n} from '@open-mercato/shared/lib/crud/cache'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi/types'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { lookupHashCandidates } from '@open-mercato/shared/lib/encryption/aes'\nimport { User } from '../../auth/data/entities'\nimport { Message, MessageObject } from '../data/entities'\nimport { composeMessageSchema, listMessagesSchema, type ListMessagesInput } from '../data/validators'\nimport {\n composeRequiresChannelTypeResolution,\n composeSourceHintSchema,\n resolveComposeSourceChannelType,\n} from '../lib/composeSourceChannelType'\nimport { delegateComposeToSender, requiresSenderDelegation } from '../lib/composeSenderDelegation'\nimport {\n EXTERNAL_CONVERSATION_SOURCE_ENTITY_TYPE,\n resolveMessageChannelThreadAccess,\n} from '../lib/channelThreadAccess'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { resolveMessageActionData } from '../lib/actions'\nimport { MESSAGE_ATTACHMENT_ENTITY_ID } from '../lib/constants'\nimport { getMessageType } from '../lib/message-types-registry'\nimport { validateMessageObjectsForType } from '../lib/object-validation'\nimport { attachOperationMetadataHeader } from '../lib/operationMetadata'\nimport {\n canPostToChannelThread,\n canUseChannelThreadFallback,\n canUseMessageEmailFeature,\n resolveMessageContext,\n} from '../lib/routeHelpers'\nimport { applyMessageParticipantScope } from '../lib/participantScope'\nimport { resolveUserFeatures, runMessageMutationGuardAfterSuccess, runMessageMutationGuards } from './guards'\nimport { findMessageIdsBySearchTokens } from '../lib/searchLookup'\nimport { MessageCommandExecuteResult } from '../commands/shared'\nimport {\n composeMessageRequestSchema as composeSchema,\n composeResponseSchema,\n listMessagesSchema as listSchema,\n messageListItemSchema,\n} from './openapi'\n\ntype MessageCommandExecuteResultWithThreadId = MessageCommandExecuteResult & {\n threadId: string\n}\n\nconst NO_MATCH_ID = '00000000-0000-0000-0000-000000000000'\nconst MESSAGE_LIST_CACHE_TTL_MS = 30_000\nconst MESSAGE_LIST_RESOURCE = 'messages.message'\n\nfunction getDb(em: EntityManager): Kysely<any> {\n return em.getKysely<any>()\n}\n\ntype MessageListScopeRow = {\n id: string\n sender_user_id: string\n is_draft: boolean\n recipient_status: string | null\n read_at: string | null\n}\n\ntype AttachmentCountRow = {\n record_id: string\n count: string | number\n}\n\ntype RecipientCountRow = {\n message_id: string\n count: string | number\n}\n\ntype MessageListPayload = {\n items: Array<Record<string, unknown>>\n page: number\n pageSize: number\n total: number\n totalPages: number\n}\n\ntype MessageListScope = Awaited<ReturnType<typeof resolveMessageContext>>['scope']\n\nfunction normalizeCacheFilterValue(value: unknown): unknown {\n if (value === undefined) return null\n if (value instanceof Date) return value.toISOString()\n if (Array.isArray(value)) return value.map(normalizeCacheFilterValue)\n if (value && typeof value === 'object') {\n return Object.entries(value as Record<string, unknown>)\n .sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey))\n .map(([key, entryValue]) => [key, normalizeCacheFilterValue(entryValue)])\n }\n return value\n}\n\nfunction buildMessageListFilterSignature(input: ListMessagesInput): string {\n const canonicalInput = Object.entries(input)\n .sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey))\n .map(([key, value]) => [key, normalizeCacheFilterValue(value)])\n\n return createHash('sha256')\n .update(JSON.stringify(canonicalInput))\n .digest('hex')\n .slice(0, 32)\n}\n\nfunction buildMessageListCacheKey(scope: MessageListScope, input: ListMessagesInput): string {\n return [\n 'messages:list:v1',\n `tenant:${normalizeTagSegment(scope.tenantId)}`,\n `org:${normalizeTagSegment(scope.organizationId)}`,\n `user:${normalizeTagSegment(scope.userId)}`,\n `filters:${buildMessageListFilterSignature(input)}`,\n ].join('|')\n}\n\nfunction isMessageListPayload(value: unknown): value is MessageListPayload {\n if (!value || typeof value !== 'object') return false\n const payload = value as Partial<MessageListPayload>\n return Array.isArray(payload.items)\n && typeof payload.page === 'number'\n && typeof payload.pageSize === 'number'\n && typeof payload.total === 'number'\n && typeof payload.totalPages === 'number'\n}\n\nexport const metadata = {\n GET: { requireAuth: true },\n POST: { requireAuth: true, requireFeatures: ['messages.compose'] },\n}\n\nexport async function GET(req: Request) {\n const { ctx, scope } = await resolveMessageContext(req)\n const url = new URL(req.url)\n const params = Object.fromEntries(url.searchParams)\n const input = listMessagesSchema.parse(params)\n\n const cache = isCrudCacheEnabled() ? resolveCrudCache(ctx.container) : null\n const cacheKey = cache ? buildMessageListCacheKey(scope, input) : null\n if (cache && cacheKey) {\n try {\n const cached = await runWithCacheTenant(scope.tenantId, () => cache.get(cacheKey))\n if (isMessageListPayload(cached)) {\n return Response.json(cached)\n }\n } catch (error) {\n debugCrudCache('messages-list-cache-read-failed', {\n error: error instanceof Error ? error.message : String(error),\n })\n }\n }\n\n const em = ctx.container.resolve('em') as EntityManager\n const db = getDb(em) as any\n\n const searchIds = input.search\n ? await findMessageIdsBySearchTokens({\n em,\n query: input.search,\n tenantId: scope.tenantId ?? null,\n organizationId: scope.organizationId,\n })\n : undefined\n\n const buildBaseQuery = () => {\n let q: any = db\n .selectFrom('messages as m')\n .where('m.tenant_id', '=', scope.tenantId)\n .where('m.deleted_at', 'is', null)\n\n if (scope.organizationId) {\n q = q.where('m.organization_id', '=', scope.organizationId)\n } else {\n q = q.where('m.organization_id', 'is', null)\n }\n\n const joinRecipient = () => {\n q = q.leftJoin('message_recipients as r', (jb: any) => jb\n .onRef('m.id', '=', 'r.message_id')\n .on('r.recipient_user_id', '=', scope.userId))\n }\n\n switch (input.folder) {\n case 'inbox':\n joinRecipient()\n q = q\n .where('r.message_id', 'is not', null)\n .where('r.deleted_at', 'is', null)\n .where('r.archived_at', 'is', null)\n .where('m.is_draft', '=', false)\n break\n case 'archived':\n joinRecipient()\n q = q\n .where('r.message_id', 'is not', null)\n .where('r.deleted_at', 'is', null)\n .where('r.archived_at', 'is not', null)\n break\n case 'sent':\n q = q\n .where('m.sender_user_id', '=', scope.userId)\n .where('m.is_draft', '=', false)\n joinRecipient()\n break\n case 'drafts':\n q = q\n .where('m.sender_user_id', '=', scope.userId)\n .where('m.is_draft', '=', true)\n joinRecipient()\n break\n case 'all':\n // Sender-OR-recipient participant scope shared with the\n // communication_channels message enricher \u2014 see participantScope.ts (#4133).\n q = applyMessageParticipantScope(q, scope.userId)\n break\n default: {\n const unsupportedFolder: never = input.folder\n throw new Error(`Unsupported folder: ${String(unsupportedFolder)}`)\n }\n }\n\n if (input.status) q = q.where('r.status', '=', input.status)\n if (input.type) q = q.where('m.type', '=', input.type)\n if (input.visibility) q = q.where('m.visibility', '=', input.visibility)\n if (input.sourceEntityType) q = q.where('m.source_entity_type', '=', input.sourceEntityType)\n if (input.sourceEntityId) q = q.where('m.source_entity_id', '=', input.sourceEntityId)\n if (input.externalEmail) q = q.where('m.external_email_hash', 'in', lookupHashCandidates(input.externalEmail))\n if (input.senderId) q = q.where('m.sender_user_id', '=', input.senderId)\n\n if (input.search) {\n if (!searchIds || searchIds.length === 0) {\n q = q.where('m.id', '=', NO_MATCH_ID)\n } else {\n q = q.where('m.id', 'in', searchIds)\n }\n }\n\n if (input.since) q = q.where('m.sent_at', '>', new Date(input.since))\n\n if (input.hasObjects !== undefined) {\n const existsFn = (eb: any) => eb.exists(\n eb.selectFrom('message_objects')\n .select(sql<number>`1`.as('one'))\n .whereRef('message_objects.message_id', '=', 'm.id')\n )\n const notExistsFn = (eb: any) => eb.not(eb.exists(\n eb.selectFrom('message_objects')\n .select(sql<number>`1`.as('one'))\n .whereRef('message_objects.message_id', '=', 'm.id')\n ))\n q = input.hasObjects ? q.where(existsFn) : q.where(notExistsFn)\n }\n\n if (input.hasAttachments !== undefined) {\n const existsFn = (eb: any) => eb.exists(\n eb.selectFrom('attachments')\n .select(sql<number>`1`.as('one'))\n .where('attachments.entity_id', '=', MESSAGE_ATTACHMENT_ENTITY_ID)\n .where(sql<boolean>`attachments.record_id = m.id::text`)\n )\n const notExistsFn = (eb: any) => eb.not(eb.exists(\n eb.selectFrom('attachments')\n .select(sql<number>`1`.as('one'))\n .where('attachments.entity_id', '=', MESSAGE_ATTACHMENT_ENTITY_ID)\n .where(sql<boolean>`attachments.record_id = m.id::text`)\n ))\n q = input.hasAttachments ? q.where(existsFn) : q.where(notExistsFn)\n }\n\n if (input.hasActions !== undefined) {\n q = input.hasActions\n ? q.where('m.action_data', 'is not', null)\n : q.where('m.action_data', 'is', null)\n }\n\n return q\n }\n\n // Audited for #3386 rollout (P3): sort is on m.sent_at (a plain timestamp \u2014\n // not in the messages:message encryption map whose encrypted fields are:\n // subject, body, external_email, external_name, action_data, action_result).\n // The handler already uses the correct two-phase shape: Kysely SQL\n // ORDER BY + LIMIT/OFFSET produces a bounded page of IDs, then\n // findWithDecryption is called only for those IDs \u2014 never for the full\n // result set. The #3278 unbounded-decrypt hazard does not apply here.\n // Covered by __tests__/list.test.ts.\n const countResult = await buildBaseQuery()\n .select(sql<number>`count(*)`.as('count'))\n .executeTakeFirst() as { count: string | number } | undefined\n const total = Number(countResult?.count ?? 0)\n\n const offset = (input.page - 1) * input.pageSize\n const scopeRows = await buildBaseQuery()\n .select([\n 'm.id',\n 'm.sender_user_id',\n 'm.is_draft',\n 'r.status as recipient_status',\n 'r.read_at',\n ])\n .orderBy('m.sent_at', 'desc')\n .offset(offset)\n .limit(input.pageSize)\n .execute()\n\n const typedRows = scopeRows as MessageListScopeRow[]\n const messageIds = typedRows.map((row) => row.id)\n\n const messageEntities = messageIds.length > 0\n ? await findWithDecryption(\n em,\n Message,\n { id: { $in: messageIds } },\n undefined,\n { tenantId: scope.tenantId, organizationId: scope.organizationId }\n )\n : []\n\n const messagesById = new Map<string, Message>()\n for (const message of messageEntities) {\n messagesById.set(message.id, message)\n }\n\n const objects = messageIds.length > 0\n ? await em.find(MessageObject, { messageId: { $in: messageIds } })\n : []\n\n const objectsByMessage = objects.reduce((acc, obj) => {\n if (!acc[obj.messageId]) acc[obj.messageId] = []\n acc[obj.messageId].push(obj)\n return acc\n }, {} as Record<string, MessageObject[]>)\n\n const attachmentCounts: AttachmentCountRow[] = messageIds.length > 0\n ? await (getDb(em) as any)\n .selectFrom('attachments')\n .select(['record_id', sql<string>`count(*)`.as('count')])\n .where('entity_id', '=', MESSAGE_ATTACHMENT_ENTITY_ID)\n .where('record_id', 'in', messageIds)\n .groupBy('record_id')\n .execute()\n : []\n\n const attachmentCountByMessage = attachmentCounts.reduce((acc: Record<string, number>, row) => {\n acc[row.record_id] = Number(row.count)\n return acc\n }, {})\n\n const recipientCounts: RecipientCountRow[] = messageIds.length > 0\n ? await (getDb(em) as any)\n .selectFrom('message_recipients')\n .select(['message_id', sql<string>`count(*)`.as('count')])\n .where('message_id', 'in', messageIds)\n .where('deleted_at', 'is', null)\n .groupBy('message_id')\n .execute()\n : []\n\n const recipientCountByMessage = recipientCounts.reduce((acc: Record<string, number>, row) => {\n acc[row.message_id] = Number(row.count)\n return acc\n }, {})\n\n const senderUserIds = Array.from(new Set(typedRows.map((row) => row.sender_user_id).filter(Boolean)))\n const senderUsers = senderUserIds.length > 0\n ? await findWithDecryption(\n em,\n User,\n { id: { $in: senderUserIds } },\n undefined,\n { tenantId: scope.tenantId, organizationId: scope.organizationId }\n )\n : []\n\n const senderMetaById = new Map<string, { name: string | null; email: string | null }>()\n senderUsers.forEach((user) => {\n const name = typeof user.name === 'string' && user.name.trim().length ? user.name.trim() : null\n senderMetaById.set(user.id, { name, email: user.email ?? null })\n })\n\n const payload: MessageListPayload = {\n items: typedRows\n .map((row) => {\n const message = messagesById.get(row.id)\n if (!message) return null\n const body = typeof message.body === 'string' ? message.body : ''\n const bodyPreview = body.substring(0, 150) + (body.length > 150 ? '...' : '')\n const actionData = resolveMessageActionData(message)\n return {\n ...(senderMetaById.get(row.sender_user_id)\n ? {\n senderName: senderMetaById.get(row.sender_user_id)?.name ?? null,\n senderEmail: senderMetaById.get(row.sender_user_id)?.email ?? null,\n }\n : { senderName: null, senderEmail: null }),\n id: message.id,\n type: message.type,\n visibility: message.visibility ?? null,\n sourceEntityType: message.sourceEntityType ?? null,\n sourceEntityId: message.sourceEntityId ?? null,\n externalEmail: message.externalEmail ?? null,\n externalName: message.externalName ?? null,\n subject: message.subject,\n bodyPreview,\n senderUserId: message.senderUserId,\n priority: message.priority,\n status: row.recipient_status ?? (row.is_draft ? 'draft' : 'sent'),\n hasObjects: (objectsByMessage[message.id] || []).length > 0,\n objectCount: (objectsByMessage[message.id] || []).length,\n hasAttachments: (attachmentCountByMessage[message.id] || 0) > 0,\n attachmentCount: attachmentCountByMessage[message.id] || 0,\n recipientCount: recipientCountByMessage[message.id] || 0,\n hasActions:\n Boolean(actionData?.actions?.length)\n || Boolean(getMessageType(message.type)?.defaultActions?.length)\n || (objectsByMessage[message.id] || []).some((item) => item.actionRequired && Boolean(item.actionType)),\n actionTaken: message.actionTaken ?? null,\n sentAt: message.sentAt ? message.sentAt.toISOString() : null,\n readAt: row.read_at,\n threadId: message.threadId ?? null,\n }\n })\n .filter((item): item is NonNullable<typeof item> => item !== null),\n page: input.page,\n pageSize: input.pageSize,\n total,\n totalPages: Math.ceil(total / input.pageSize),\n }\n\n if (cache && cacheKey) {\n try {\n await runWithCacheTenant(scope.tenantId, () =>\n cache.set(cacheKey, payload, {\n ttl: MESSAGE_LIST_CACHE_TTL_MS,\n tags: buildCollectionTags(\n MESSAGE_LIST_RESOURCE,\n scope.tenantId,\n [scope.organizationId],\n ),\n }),\n )\n } catch (error) {\n debugCrudCache('messages-list-cache-write-failed', {\n error: error instanceof Error ? error.message : String(error),\n })\n }\n }\n\n return Response.json(payload)\n}\n\nexport async function POST(req: Request) {\n const { ctx, scope } = await resolveMessageContext(req)\n const commandBus = ctx.container.resolve('commandBus') as CommandBus\n const body = await req.json().catch(() => ({}))\n\n // #4975: whether `externalEmail` is required depends on the channel this\n // message originates from, so the channel type has to be established BEFORE\n // validation. It is resolved server-side from the referenced conversation or\n // parent message and any client-sent `sourceChannelType` is dropped \u2014\n // otherwise a caller could waive the requirement by asserting its own type.\n // An unresolvable source stays `undefined`, which the validator fails closed on.\n // Only the \"public, non-draft, no address\" branch of the validator reads the\n // answer, so every other compose skips the lookup instead of discarding it.\n const sourceHint = composeRequiresChannelTypeResolution(body)\n ? composeSourceHintSchema.safeParse(body)\n : null\n const sourceChannelType = sourceHint?.success\n ? await resolveComposeSourceChannelType(\n ctx.container,\n { tenantId: scope.tenantId, organizationId: scope.organizationId ?? null },\n sourceHint.data,\n )\n : undefined\n // `inboundFromChannel` and `sentAt` are likewise server-only (#6093, #6095):\n // channel ingest sets them so an inbound message can be addressed to the\n // conversation's assignee and stamped with the provider's receive time, but\n // a request body must not be able to waive the recipients rule or backdate\n // a message with them.\n const {\n sourceChannelType: _clientSuppliedChannelType,\n inboundFromChannel: _clientSuppliedInboundFlag,\n sentAt: _clientSuppliedSentAt,\n ...clientBody\n } = (body ?? {}) as Record<string, unknown>\n const input = composeMessageSchema.parse({\n ...clientBody,\n ...(sourceChannelType ? { sourceChannelType } : {}),\n })\n\n const isPublicVisibility = input.visibility === 'public'\n const sendViaEmail = isPublicVisibility ? true : input.sendViaEmail\n if (sendViaEmail && !(await canUseMessageEmailFeature(ctx, scope))) {\n return Response.json({ error: 'Missing feature: messages.email' }, { status: 403 })\n }\n\n if (input.objects?.length) {\n const objectValidationError = validateMessageObjectsForType(input.type, input.objects)\n if (objectValidationError) {\n return Response.json({ error: objectValidationError }, { status: 400 })\n }\n }\n\n // #5535: composing on a channel conversation without naming a parent message\n // used to open a brand-new thread. A fresh thread has no `ChannelThreadMapping`,\n // so the outbound bridge had nothing to route on and the operator got a 201 for\n // a message that was never delivered \u2014 a silent failure worse than a refusal.\n // Attach the message to the conversation's existing thread instead, and refuse\n // outright when there is no such thread to attach it to. Only messages meant to\n // leave the platform are affected: a draft, or an internal note filed against\n // the same conversation, is never delivered anyway and stays untouched.\n let composeParentMessageId = input.parentMessageId\n if (\n isPublicVisibility &&\n !input.isDraft &&\n !input.parentMessageId &&\n input.sourceEntityType === EXTERNAL_CONVERSATION_SOURCE_ENTITY_TYPE &&\n input.sourceEntityId\n ) {\n const channelThread = await resolveMessageChannelThreadAccess(\n ctx.container,\n { tenantId: scope.tenantId, organizationId: scope.organizationId ?? null },\n { externalConversationId: input.sourceEntityId },\n { userId: scope.userId, features: resolveUserFeatures(ctx.auth) },\n )\n if (!channelThread) {\n const { translate } = await resolveTranslations()\n return Response.json(\n {\n error: translate(\n 'messages.errors.conversationHasNoChannelThread',\n 'Conversation has no channel thread to deliver into',\n ),\n },\n { status: 409 },\n )\n }\n if (!channelThread.canAccess || !(await canUseChannelThreadFallback(ctx, scope))) {\n return Response.json({ error: 'Access denied' }, { status: 403 })\n }\n composeParentMessageId = channelThread.messageThreadId\n }\n\n // #5645 review: the gate above only runs when the client omits a parent. A\n // caller-supplied `parentMessageId` reaches `messages.messages.compose`, which\n // derives the thread from that parent alone \u2014 so a public, non-draft message\n // could be threaded onto a channel-linked conversation and delivered to the\n // external correspondent without any channel-access check. A tenant-wide\n // channel accepts delivery from any sender, so `messages.compose` plus a known\n // message id was enough. Apply the same check to the thread the command will\n // actually derive. An internal thread, a thread outside the caller's scope,\n // and an absent hub all resolve to `null` and keep the pre-existing rule.\n // Both channel branches also require `messages.view`, like reply and forward:\n // the hub grants every shared channel regardless of features (#6432).\n if (isPublicVisibility && !input.isDraft && input.parentMessageId) {\n const em = ctx.container.resolve('em') as EntityManager\n const parentMessage = await findOneWithDecryption(\n em,\n Message,\n {\n id: input.parentMessageId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n },\n undefined,\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n const parentThreadId = parentMessage?.threadId ?? input.parentMessageId\n if (!(await canPostToChannelThread(ctx, scope, parentThreadId))) {\n return Response.json({ error: 'Access denied' }, { status: 403 })\n }\n }\n\n const guardResult = await runMessageMutationGuards(\n ctx.container,\n {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n resourceKind: 'messages.message',\n resourceId: null,\n operation: 'create',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: input as Record<string, unknown>,\n },\n resolveUserFeatures(ctx.auth),\n )\n if (!guardResult.ok) {\n return Response.json(\n guardResult.errorBody ?? { error: 'Operation blocked by guard' },\n { status: guardResult.errorStatus ?? 422 },\n )\n }\n\n // #6258: an explicitly chosen mailbox routes the whole send through the\n // communication-channels facade, which writes the conversation, thread mapping\n // and outbound channel link the inbound thread matcher needs. Without the\n // field this stays the platform-sender path, unchanged.\n if (requiresSenderDelegation(input)) {\n const delegated = await delegateComposeToSender(\n ctx.container,\n {\n userId: scope.userId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId ?? null,\n auth: ctx.auth ?? null,\n },\n { ...input, parentMessageId: composeParentMessageId },\n )\n if (!delegated.ok) {\n return Response.json(\n { error: delegated.error, fieldErrors: delegated.fieldErrors },\n { status: delegated.status },\n )\n }\n const delegatedResponse = Response.json(\n { id: delegated.messageId, threadId: delegated.threadId },\n { status: 201 },\n )\n await runMessageMutationGuardAfterSuccess(guardResult.afterSuccessCallbacks, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n resourceKind: 'messages.message',\n resourceId: delegated.messageId,\n operation: 'create',\n requestMethod: req.method,\n requestHeaders: req.headers,\n })\n return delegatedResponse\n }\n\n const { result, logEntry } = await commandBus.execute('messages.messages.compose', {\n input: {\n ...input,\n parentMessageId: composeParentMessageId,\n sendViaEmail,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n },\n ctx: {\n container: ctx.container,\n auth: ctx.auth ?? null,\n organizationScope: null,\n selectedOrganizationId: scope.organizationId,\n organizationIds: scope.organizationId ? [scope.organizationId] : null,\n request: req,\n },\n })\n const { id: messageId, threadId: responseThreadId } = result as unknown as MessageCommandExecuteResultWithThreadId\n\n const response = Response.json({ id: messageId, threadId: responseThreadId }, { status: 201 })\n attachOperationMetadataHeader(response, logEntry, {\n resourceKind: 'messages.message',\n resourceId: messageId,\n })\n await runMessageMutationGuardAfterSuccess(guardResult.afterSuccessCallbacks, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n resourceKind: 'messages.message',\n resourceId: messageId,\n operation: 'create',\n requestMethod: req.method,\n requestHeaders: req.headers,\n })\n return response\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Messages',\n methods: {\n GET: {\n summary: 'List messages',\n query: listSchema,\n responses: [\n {\n status: 200,\n description: 'Message list',\n schema: z.object({\n items: z.array(messageListItemSchema),\n page: z.number(),\n pageSize: z.number(),\n total: z.number(),\n totalPages: z.number(),\n }),\n },\n ],\n },\n POST: {\n summary: 'Compose a message',\n requestBody: {\n schema: composeSchema,\n },\n responses: [\n {\n status: 201,\n description: 'Message created',\n schema: composeResponseSchema,\n },\n ],\n },\n },\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,kBAAkB;AAC3B,SAAS,SAAS;AAElB,SAAsB,WAAW;AACjC,SAAS,0BAA0B;AAEnC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,4BAA4B;AACrC,SAAS,YAAY;AACrB,SAAS,SAAS,qBAAqB;AACvC,SAAS,sBAAsB,0BAAkD;AACjF;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,yBAAyB,gCAAgC;AAClE;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,gCAAgC;AACzC,SAAS,oCAAoC;AAC7C,SAAS,sBAAsB;AAC/B,SAAS,qCAAqC;AAC9C,SAAS,qCAAqC;AAC9C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oCAAoC;AAC7C,SAAS,qBAAqB,qCAAqC,gCAAgC;AACnG,SAAS,oCAAoC;AAE7C;AAAA,EACE,+BAA+B;AAAA,EAC/B;AAAA,EACA,sBAAsB;AAAA,EACtB;AAAA,OACK;AAMP,MAAM,cAAc;AACpB,MAAM,4BAA4B;AAClC,MAAM,wBAAwB;AAE9B,SAAS,MAAM,IAAgC;AAC7C,SAAO,GAAG,UAAe;AAC3B;AA8BA,SAAS,0BAA0B,OAAyB;AAC1D,MAAI,UAAU,OAAW,QAAO;AAChC,MAAI,iBAAiB,KAAM,QAAO,MAAM,YAAY;AACpD,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,IAAI,yBAAyB;AACpE,MAAI,SAAS,OAAO,UAAU,UAAU;AACtC,WAAO,OAAO,QAAQ,KAAgC,EACnD,KAAK,CAAC,CAAC,OAAO,GAAG,CAAC,QAAQ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'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { type Kysely, sql } from 'kysely'\nimport { runWithCacheTenant } from '@open-mercato/cache'\nimport type { CommandBus } from '@open-mercato/shared/lib/commands/command-bus'\nimport {\n buildCollectionTags,\n debugCrudCache,\n isCrudCacheEnabled,\n normalizeTagSegment,\n resolveCrudCache,\n} from '@open-mercato/shared/lib/crud/cache'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi/types'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { lookupHashCandidates } from '@open-mercato/shared/lib/encryption/aes'\nimport { User } from '../../auth/data/entities'\nimport { Message, MessageObject } from '../data/entities'\nimport { composeMessageSchema, listMessagesSchema, type ListMessagesInput } from '../data/validators'\nimport {\n composeRequiresChannelTypeResolution,\n composeSourceHintSchema,\n resolveComposeSourceChannelType,\n} from '../lib/composeSourceChannelType'\nimport { delegateComposeToSender, requiresSenderDelegation } from '../lib/composeSenderDelegation'\nimport {\n EXTERNAL_CONVERSATION_SOURCE_ENTITY_TYPE,\n resolveMessageChannelThreadAccess,\n} from '../lib/channelThreadAccess'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { resolveMessageActionData } from '../lib/actions'\nimport { MESSAGE_ATTACHMENT_ENTITY_ID } from '../lib/constants'\nimport { getMessageType } from '../lib/message-types-registry'\nimport { validateMessageObjectsForType } from '../lib/object-validation'\nimport { attachOperationMetadataHeader } from '../lib/operationMetadata'\nimport {\n canPostToChannelThread,\n canUseChannelThreadFallback,\n resolveReplyParentMessage,\n canUseMessageEmailFeature,\n resolveMessageContext,\n} from '../lib/routeHelpers'\nimport { applyMessageParticipantScope } from '../lib/participantScope'\nimport { resolveUserFeatures, runMessageMutationGuardAfterSuccess, runMessageMutationGuards } from './guards'\nimport { findMessageIdsBySearchTokens } from '../lib/searchLookup'\nimport { MessageCommandExecuteResult } from '../commands/shared'\nimport {\n composeMessageRequestSchema as composeSchema,\n composeResponseSchema,\n errorResponseSchema,\n listMessagesSchema as listSchema,\n messageListItemSchema,\n} from './openapi'\n\ntype MessageCommandExecuteResultWithThreadId = MessageCommandExecuteResult & {\n threadId: string\n}\n\nconst NO_MATCH_ID = '00000000-0000-0000-0000-000000000000'\nconst MESSAGE_LIST_CACHE_TTL_MS = 30_000\nconst MESSAGE_LIST_RESOURCE = 'messages.message'\n\nfunction getDb(em: EntityManager): Kysely<any> {\n return em.getKysely<any>()\n}\n\ntype MessageListScopeRow = {\n id: string\n sender_user_id: string\n is_draft: boolean\n recipient_status: string | null\n read_at: string | null\n}\n\ntype AttachmentCountRow = {\n record_id: string\n count: string | number\n}\n\ntype RecipientCountRow = {\n message_id: string\n count: string | number\n}\n\ntype MessageListPayload = {\n items: Array<Record<string, unknown>>\n page: number\n pageSize: number\n total: number\n totalPages: number\n}\n\ntype MessageListScope = Awaited<ReturnType<typeof resolveMessageContext>>['scope']\n\nfunction normalizeCacheFilterValue(value: unknown): unknown {\n if (value === undefined) return null\n if (value instanceof Date) return value.toISOString()\n if (Array.isArray(value)) return value.map(normalizeCacheFilterValue)\n if (value && typeof value === 'object') {\n return Object.entries(value as Record<string, unknown>)\n .sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey))\n .map(([key, entryValue]) => [key, normalizeCacheFilterValue(entryValue)])\n }\n return value\n}\n\nfunction buildMessageListFilterSignature(input: ListMessagesInput): string {\n const canonicalInput = Object.entries(input)\n .sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey))\n .map(([key, value]) => [key, normalizeCacheFilterValue(value)])\n\n return createHash('sha256')\n .update(JSON.stringify(canonicalInput))\n .digest('hex')\n .slice(0, 32)\n}\n\nfunction buildMessageListCacheKey(scope: MessageListScope, input: ListMessagesInput): string {\n return [\n 'messages:list:v1',\n `tenant:${normalizeTagSegment(scope.tenantId)}`,\n `org:${normalizeTagSegment(scope.organizationId)}`,\n `user:${normalizeTagSegment(scope.userId)}`,\n `filters:${buildMessageListFilterSignature(input)}`,\n ].join('|')\n}\n\nfunction isMessageListPayload(value: unknown): value is MessageListPayload {\n if (!value || typeof value !== 'object') return false\n const payload = value as Partial<MessageListPayload>\n return Array.isArray(payload.items)\n && typeof payload.page === 'number'\n && typeof payload.pageSize === 'number'\n && typeof payload.total === 'number'\n && typeof payload.totalPages === 'number'\n}\n\nexport const metadata = {\n GET: { requireAuth: true },\n POST: { requireAuth: true, requireFeatures: ['messages.compose'] },\n}\n\nexport async function GET(req: Request) {\n const { ctx, scope } = await resolveMessageContext(req)\n const url = new URL(req.url)\n const params = Object.fromEntries(url.searchParams)\n const input = listMessagesSchema.parse(params)\n\n const cache = isCrudCacheEnabled() ? resolveCrudCache(ctx.container) : null\n const cacheKey = cache ? buildMessageListCacheKey(scope, input) : null\n if (cache && cacheKey) {\n try {\n const cached = await runWithCacheTenant(scope.tenantId, () => cache.get(cacheKey))\n if (isMessageListPayload(cached)) {\n return Response.json(cached)\n }\n } catch (error) {\n debugCrudCache('messages-list-cache-read-failed', {\n error: error instanceof Error ? error.message : String(error),\n })\n }\n }\n\n const em = ctx.container.resolve('em') as EntityManager\n const db = getDb(em) as any\n\n const searchIds = input.search\n ? await findMessageIdsBySearchTokens({\n em,\n query: input.search,\n tenantId: scope.tenantId ?? null,\n organizationId: scope.organizationId,\n })\n : undefined\n\n const buildBaseQuery = () => {\n let q: any = db\n .selectFrom('messages as m')\n .where('m.tenant_id', '=', scope.tenantId)\n .where('m.deleted_at', 'is', null)\n\n if (scope.organizationId) {\n q = q.where('m.organization_id', '=', scope.organizationId)\n } else {\n q = q.where('m.organization_id', 'is', null)\n }\n\n const joinRecipient = () => {\n q = q.leftJoin('message_recipients as r', (jb: any) => jb\n .onRef('m.id', '=', 'r.message_id')\n .on('r.recipient_user_id', '=', scope.userId))\n }\n\n switch (input.folder) {\n case 'inbox':\n joinRecipient()\n q = q\n .where('r.message_id', 'is not', null)\n .where('r.deleted_at', 'is', null)\n .where('r.archived_at', 'is', null)\n .where('m.is_draft', '=', false)\n break\n case 'archived':\n joinRecipient()\n q = q\n .where('r.message_id', 'is not', null)\n .where('r.deleted_at', 'is', null)\n .where('r.archived_at', 'is not', null)\n break\n case 'sent':\n q = q\n .where('m.sender_user_id', '=', scope.userId)\n .where('m.is_draft', '=', false)\n joinRecipient()\n break\n case 'drafts':\n q = q\n .where('m.sender_user_id', '=', scope.userId)\n .where('m.is_draft', '=', true)\n joinRecipient()\n break\n case 'all':\n // Sender-OR-recipient participant scope shared with the\n // communication_channels message enricher \u2014 see participantScope.ts (#4133).\n q = applyMessageParticipantScope(q, scope.userId)\n break\n default: {\n const unsupportedFolder: never = input.folder\n throw new Error(`Unsupported folder: ${String(unsupportedFolder)}`)\n }\n }\n\n if (input.status) q = q.where('r.status', '=', input.status)\n if (input.type) q = q.where('m.type', '=', input.type)\n if (input.visibility) q = q.where('m.visibility', '=', input.visibility)\n if (input.sourceEntityType) q = q.where('m.source_entity_type', '=', input.sourceEntityType)\n if (input.sourceEntityId) q = q.where('m.source_entity_id', '=', input.sourceEntityId)\n if (input.externalEmail) q = q.where('m.external_email_hash', 'in', lookupHashCandidates(input.externalEmail))\n if (input.senderId) q = q.where('m.sender_user_id', '=', input.senderId)\n\n if (input.search) {\n if (!searchIds || searchIds.length === 0) {\n q = q.where('m.id', '=', NO_MATCH_ID)\n } else {\n q = q.where('m.id', 'in', searchIds)\n }\n }\n\n if (input.since) q = q.where('m.sent_at', '>', new Date(input.since))\n\n if (input.hasObjects !== undefined) {\n const existsFn = (eb: any) => eb.exists(\n eb.selectFrom('message_objects')\n .select(sql<number>`1`.as('one'))\n .whereRef('message_objects.message_id', '=', 'm.id')\n )\n const notExistsFn = (eb: any) => eb.not(eb.exists(\n eb.selectFrom('message_objects')\n .select(sql<number>`1`.as('one'))\n .whereRef('message_objects.message_id', '=', 'm.id')\n ))\n q = input.hasObjects ? q.where(existsFn) : q.where(notExistsFn)\n }\n\n if (input.hasAttachments !== undefined) {\n const existsFn = (eb: any) => eb.exists(\n eb.selectFrom('attachments')\n .select(sql<number>`1`.as('one'))\n .where('attachments.entity_id', '=', MESSAGE_ATTACHMENT_ENTITY_ID)\n .where(sql<boolean>`attachments.record_id = m.id::text`)\n )\n const notExistsFn = (eb: any) => eb.not(eb.exists(\n eb.selectFrom('attachments')\n .select(sql<number>`1`.as('one'))\n .where('attachments.entity_id', '=', MESSAGE_ATTACHMENT_ENTITY_ID)\n .where(sql<boolean>`attachments.record_id = m.id::text`)\n ))\n q = input.hasAttachments ? q.where(existsFn) : q.where(notExistsFn)\n }\n\n if (input.hasActions !== undefined) {\n q = input.hasActions\n ? q.where('m.action_data', 'is not', null)\n : q.where('m.action_data', 'is', null)\n }\n\n return q\n }\n\n // Audited for #3386 rollout (P3): sort is on m.sent_at (a plain timestamp \u2014\n // not in the messages:message encryption map whose encrypted fields are:\n // subject, body, external_email, external_name, action_data, action_result).\n // The handler already uses the correct two-phase shape: Kysely SQL\n // ORDER BY + LIMIT/OFFSET produces a bounded page of IDs, then\n // findWithDecryption is called only for those IDs \u2014 never for the full\n // result set. The #3278 unbounded-decrypt hazard does not apply here.\n // Covered by __tests__/list.test.ts.\n const countResult = await buildBaseQuery()\n .select(sql<number>`count(*)`.as('count'))\n .executeTakeFirst() as { count: string | number } | undefined\n const total = Number(countResult?.count ?? 0)\n\n const offset = (input.page - 1) * input.pageSize\n const scopeRows = await buildBaseQuery()\n .select([\n 'm.id',\n 'm.sender_user_id',\n 'm.is_draft',\n 'r.status as recipient_status',\n 'r.read_at',\n ])\n .orderBy('m.sent_at', 'desc')\n .offset(offset)\n .limit(input.pageSize)\n .execute()\n\n const typedRows = scopeRows as MessageListScopeRow[]\n const messageIds = typedRows.map((row) => row.id)\n\n const messageEntities = messageIds.length > 0\n ? await findWithDecryption(\n em,\n Message,\n { id: { $in: messageIds } },\n undefined,\n { tenantId: scope.tenantId, organizationId: scope.organizationId }\n )\n : []\n\n const messagesById = new Map<string, Message>()\n for (const message of messageEntities) {\n messagesById.set(message.id, message)\n }\n\n const objects = messageIds.length > 0\n ? await em.find(MessageObject, { messageId: { $in: messageIds } })\n : []\n\n const objectsByMessage = objects.reduce((acc, obj) => {\n if (!acc[obj.messageId]) acc[obj.messageId] = []\n acc[obj.messageId].push(obj)\n return acc\n }, {} as Record<string, MessageObject[]>)\n\n const attachmentCounts: AttachmentCountRow[] = messageIds.length > 0\n ? await (getDb(em) as any)\n .selectFrom('attachments')\n .select(['record_id', sql<string>`count(*)`.as('count')])\n .where('entity_id', '=', MESSAGE_ATTACHMENT_ENTITY_ID)\n .where('record_id', 'in', messageIds)\n .groupBy('record_id')\n .execute()\n : []\n\n const attachmentCountByMessage = attachmentCounts.reduce((acc: Record<string, number>, row) => {\n acc[row.record_id] = Number(row.count)\n return acc\n }, {})\n\n const recipientCounts: RecipientCountRow[] = messageIds.length > 0\n ? await (getDb(em) as any)\n .selectFrom('message_recipients')\n .select(['message_id', sql<string>`count(*)`.as('count')])\n .where('message_id', 'in', messageIds)\n .where('deleted_at', 'is', null)\n .groupBy('message_id')\n .execute()\n : []\n\n const recipientCountByMessage = recipientCounts.reduce((acc: Record<string, number>, row) => {\n acc[row.message_id] = Number(row.count)\n return acc\n }, {})\n\n const senderUserIds = Array.from(new Set(typedRows.map((row) => row.sender_user_id).filter(Boolean)))\n const senderUsers = senderUserIds.length > 0\n ? await findWithDecryption(\n em,\n User,\n { id: { $in: senderUserIds } },\n undefined,\n { tenantId: scope.tenantId, organizationId: scope.organizationId }\n )\n : []\n\n const senderMetaById = new Map<string, { name: string | null; email: string | null }>()\n senderUsers.forEach((user) => {\n const name = typeof user.name === 'string' && user.name.trim().length ? user.name.trim() : null\n senderMetaById.set(user.id, { name, email: user.email ?? null })\n })\n\n const payload: MessageListPayload = {\n items: typedRows\n .map((row) => {\n const message = messagesById.get(row.id)\n if (!message) return null\n const body = typeof message.body === 'string' ? message.body : ''\n const bodyPreview = body.substring(0, 150) + (body.length > 150 ? '...' : '')\n const actionData = resolveMessageActionData(message)\n return {\n ...(senderMetaById.get(row.sender_user_id)\n ? {\n senderName: senderMetaById.get(row.sender_user_id)?.name ?? null,\n senderEmail: senderMetaById.get(row.sender_user_id)?.email ?? null,\n }\n : { senderName: null, senderEmail: null }),\n id: message.id,\n type: message.type,\n visibility: message.visibility ?? null,\n sourceEntityType: message.sourceEntityType ?? null,\n sourceEntityId: message.sourceEntityId ?? null,\n externalEmail: message.externalEmail ?? null,\n externalName: message.externalName ?? null,\n subject: message.subject,\n bodyPreview,\n senderUserId: message.senderUserId,\n priority: message.priority,\n status: row.recipient_status ?? (row.is_draft ? 'draft' : 'sent'),\n hasObjects: (objectsByMessage[message.id] || []).length > 0,\n objectCount: (objectsByMessage[message.id] || []).length,\n hasAttachments: (attachmentCountByMessage[message.id] || 0) > 0,\n attachmentCount: attachmentCountByMessage[message.id] || 0,\n recipientCount: recipientCountByMessage[message.id] || 0,\n hasActions:\n Boolean(actionData?.actions?.length)\n || Boolean(getMessageType(message.type)?.defaultActions?.length)\n || (objectsByMessage[message.id] || []).some((item) => item.actionRequired && Boolean(item.actionType)),\n actionTaken: message.actionTaken ?? null,\n sentAt: message.sentAt ? message.sentAt.toISOString() : null,\n readAt: row.read_at,\n threadId: message.threadId ?? null,\n }\n })\n .filter((item): item is NonNullable<typeof item> => item !== null),\n page: input.page,\n pageSize: input.pageSize,\n total,\n totalPages: Math.ceil(total / input.pageSize),\n }\n\n if (cache && cacheKey) {\n try {\n await runWithCacheTenant(scope.tenantId, () =>\n cache.set(cacheKey, payload, {\n ttl: MESSAGE_LIST_CACHE_TTL_MS,\n tags: buildCollectionTags(\n MESSAGE_LIST_RESOURCE,\n scope.tenantId,\n [scope.organizationId],\n ),\n }),\n )\n } catch (error) {\n debugCrudCache('messages-list-cache-write-failed', {\n error: error instanceof Error ? error.message : String(error),\n })\n }\n }\n\n return Response.json(payload)\n}\n\nexport async function POST(req: Request) {\n const { ctx, scope } = await resolveMessageContext(req)\n const commandBus = ctx.container.resolve('commandBus') as CommandBus\n const body = await req.json().catch(() => ({}))\n\n // #4975: whether `externalEmail` is required depends on the channel this\n // message originates from, so the channel type has to be established BEFORE\n // validation. It is resolved server-side from the referenced conversation or\n // parent message and any client-sent `sourceChannelType` is dropped \u2014\n // otherwise a caller could waive the requirement by asserting its own type.\n // An unresolvable source stays `undefined`, which the validator fails closed on.\n // Only the \"public, non-draft, no address\" branch of the validator reads the\n // answer, so every other compose skips the lookup instead of discarding it.\n const sourceHint = composeRequiresChannelTypeResolution(body)\n ? composeSourceHintSchema.safeParse(body)\n : null\n const sourceChannelType = sourceHint?.success\n ? await resolveComposeSourceChannelType(\n ctx.container,\n { tenantId: scope.tenantId, organizationId: scope.organizationId ?? null },\n sourceHint.data,\n )\n : undefined\n // `inboundFromChannel` and `sentAt` are likewise server-only (#6093, #6095):\n // channel ingest sets them so an inbound message can be addressed to the\n // conversation's assignee and stamped with the provider's receive time, but\n // a request body must not be able to waive the recipients rule or backdate\n // a message with them.\n const {\n sourceChannelType: _clientSuppliedChannelType,\n inboundFromChannel: _clientSuppliedInboundFlag,\n sentAt: _clientSuppliedSentAt,\n ...clientBody\n } = (body ?? {}) as Record<string, unknown>\n const input = composeMessageSchema.parse({\n ...clientBody,\n ...(sourceChannelType ? { sourceChannelType } : {}),\n })\n\n const isPublicVisibility = input.visibility === 'public'\n const sendViaEmail = isPublicVisibility ? true : input.sendViaEmail\n if (sendViaEmail && !(await canUseMessageEmailFeature(ctx, scope))) {\n return Response.json({ error: 'Missing feature: messages.email' }, { status: 403 })\n }\n\n if (input.objects?.length) {\n const objectValidationError = validateMessageObjectsForType(input.type, input.objects)\n if (objectValidationError) {\n return Response.json({ error: objectValidationError }, { status: 400 })\n }\n }\n\n // A parent decides which conversation the new message joins, so it is held to\n // the same rule as reading it: knowing a message id is not enough to thread\n // onto someone else's conversation. Checked on the parent the client sent, for\n // drafts and every visibility, before any guard, delegation or write runs.\n let replyParent: Message | null = null\n if (input.parentMessageId) {\n const resolution = await resolveReplyParentMessage(\n ctx,\n { tenantId: scope.tenantId, organizationId: scope.organizationId ?? null, userId: scope.userId },\n input.parentMessageId,\n )\n if (resolution.status === 'not_found') {\n const { translate } = await resolveTranslations()\n return Response.json(\n {\n error: translate(\n 'messages.errors.parentMessageNotFound',\n 'The message you are replying to was not found',\n ),\n },\n { status: 404 },\n )\n }\n if (resolution.status === 'forbidden') {\n return Response.json({ error: 'Access denied' }, { status: 403 })\n }\n replyParent = resolution.message\n }\n\n // #5535: composing on a channel conversation without naming a parent message\n // used to open a brand-new thread. A fresh thread has no `ChannelThreadMapping`,\n // so the outbound bridge had nothing to route on and the operator got a 201 for\n // a message that was never delivered \u2014 a silent failure worse than a refusal.\n // Attach the message to the conversation's existing thread instead, and refuse\n // outright when there is no such thread to attach it to. Only messages meant to\n // leave the platform are affected: a draft, or an internal note filed against\n // the same conversation, is never delivered anyway and stays untouched.\n let composeParentMessageId = input.parentMessageId\n if (\n isPublicVisibility &&\n !input.isDraft &&\n !input.parentMessageId &&\n input.sourceEntityType === EXTERNAL_CONVERSATION_SOURCE_ENTITY_TYPE &&\n input.sourceEntityId\n ) {\n const channelThread = await resolveMessageChannelThreadAccess(\n ctx.container,\n { tenantId: scope.tenantId, organizationId: scope.organizationId ?? null },\n { externalConversationId: input.sourceEntityId },\n { userId: scope.userId, features: resolveUserFeatures(ctx.auth) },\n )\n if (!channelThread) {\n const { translate } = await resolveTranslations()\n return Response.json(\n {\n error: translate(\n 'messages.errors.conversationHasNoChannelThread',\n 'Conversation has no channel thread to deliver into',\n ),\n },\n { status: 409 },\n )\n }\n if (!channelThread.canAccess || !(await canUseChannelThreadFallback(ctx, scope))) {\n return Response.json({ error: 'Access denied' }, { status: 403 })\n }\n composeParentMessageId = channelThread.messageThreadId\n }\n\n // #5645 review: the gate above only runs when the client omits a parent. A\n // caller-supplied `parentMessageId` reaches `messages.messages.compose`, which\n // derives the thread from that parent alone \u2014 so a public, non-draft message\n // could be threaded onto a channel-linked conversation and delivered to the\n // external correspondent without any channel-access check. A tenant-wide\n // channel accepts delivery from any sender, so reading a message is not\n // enough to post onto its thread. Apply the same check to the thread the\n // command will actually derive. An internal thread and an absent hub resolve\n // to `null` and keep the pre-existing rule.\n // Both channel branches also require `messages.view`, like reply and forward:\n // the hub grants every shared channel regardless of features (#6432).\n if (isPublicVisibility && !input.isDraft && replyParent) {\n const parentThreadId = replyParent.threadId ?? replyParent.id\n if (!(await canPostToChannelThread(ctx, scope, parentThreadId))) {\n return Response.json({ error: 'Access denied' }, { status: 403 })\n }\n }\n\n const guardResult = await runMessageMutationGuards(\n ctx.container,\n {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n resourceKind: 'messages.message',\n resourceId: null,\n operation: 'create',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: input as Record<string, unknown>,\n },\n resolveUserFeatures(ctx.auth),\n )\n if (!guardResult.ok) {\n return Response.json(\n guardResult.errorBody ?? { error: 'Operation blocked by guard' },\n { status: guardResult.errorStatus ?? 422 },\n )\n }\n\n // #6258: an explicitly chosen mailbox routes the whole send through the\n // communication-channels facade, which writes the conversation, thread mapping\n // and outbound channel link the inbound thread matcher needs. Without the\n // field this stays the platform-sender path, unchanged.\n if (requiresSenderDelegation(input)) {\n const delegated = await delegateComposeToSender(\n ctx.container,\n {\n userId: scope.userId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId ?? null,\n auth: ctx.auth ?? null,\n },\n { ...input, parentMessageId: composeParentMessageId },\n )\n if (!delegated.ok) {\n return Response.json(\n { error: delegated.error, fieldErrors: delegated.fieldErrors },\n { status: delegated.status },\n )\n }\n const delegatedResponse = Response.json(\n { id: delegated.messageId, threadId: delegated.threadId },\n { status: 201 },\n )\n await runMessageMutationGuardAfterSuccess(guardResult.afterSuccessCallbacks, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n resourceKind: 'messages.message',\n resourceId: delegated.messageId,\n operation: 'create',\n requestMethod: req.method,\n requestHeaders: req.headers,\n })\n return delegatedResponse\n }\n\n const { result, logEntry } = await commandBus.execute('messages.messages.compose', {\n input: {\n ...input,\n parentMessageId: composeParentMessageId,\n sendViaEmail,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n },\n ctx: {\n container: ctx.container,\n auth: ctx.auth ?? null,\n organizationScope: null,\n selectedOrganizationId: scope.organizationId,\n organizationIds: scope.organizationId ? [scope.organizationId] : null,\n request: req,\n },\n })\n const { id: messageId, threadId: responseThreadId } = result as unknown as MessageCommandExecuteResultWithThreadId\n\n const response = Response.json({ id: messageId, threadId: responseThreadId }, { status: 201 })\n attachOperationMetadataHeader(response, logEntry, {\n resourceKind: 'messages.message',\n resourceId: messageId,\n })\n await runMessageMutationGuardAfterSuccess(guardResult.afterSuccessCallbacks, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n resourceKind: 'messages.message',\n resourceId: messageId,\n operation: 'create',\n requestMethod: req.method,\n requestHeaders: req.headers,\n })\n return response\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Messages',\n methods: {\n GET: {\n summary: 'List messages',\n query: listSchema,\n responses: [\n {\n status: 200,\n description: 'Message list',\n schema: z.object({\n items: z.array(messageListItemSchema),\n page: z.number(),\n pageSize: z.number(),\n total: z.number(),\n totalPages: z.number(),\n }),\n },\n ],\n },\n POST: {\n summary: 'Compose a message',\n requestBody: {\n schema: composeSchema,\n },\n responses: [\n {\n status: 201,\n description: 'Message created',\n schema: composeResponseSchema,\n },\n ],\n errors: [\n { status: 403, description: 'Access denied, including a parentMessageId the caller cannot read', schema: errorResponseSchema },\n { status: 404, description: 'parentMessageId is unknown, deleted, or outside the caller organization', schema: errorResponseSchema },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,kBAAkB;AAC3B,SAAS,SAAS;AAElB,SAAsB,WAAW;AACjC,SAAS,0BAA0B;AAEnC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,0BAA0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