"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.isStaffRole = isStaffRole; exports.assertConversationAccess = assertConversationAccess; exports.findCurrentConversation = findCurrentConversation; exports.ensureCurrentConversation = ensureCurrentConversation; exports.sendToCurrentConversation = sendToCurrentConversation; exports.listUserConversations = listUserConversations; exports.getConversationMessages = getConversationMessages; exports.sendMessage = sendMessage; exports.editMessage = editMessage; exports.deleteMessage = deleteMessage; exports.setTyping = setTyping; exports.listAdminConversations = listAdminConversations; exports.getAdminConversationDetail = getAdminConversationDetail; exports.updateAdminConversation = updateAdminConversation; exports.getStaffUnreadCount = getStaffUnreadCount; exports.resolveUploadPath = resolveUploadPath; exports.ensureUploadDir = ensureUploadDir; exports.publicAttachmentUrl = publicAttachmentUrl; exports.parseSupportAttachmentFilename = parseSupportAttachmentFilename; exports.finalizeSupportUpload = finalizeSupportUpload; exports.assertSupportFileDownloadAccess = assertSupportFileDownloadAccess; exports.attachmentContentDisposition = attachmentContentDisposition; exports.mergeVisitorSupportForUser = mergeVisitorSupportForUser; const path_1 = __importDefault(require("path")); const fs_1 = __importDefault(require("fs")); const uuid_1 = require("uuid"); const crypto_1 = require("../utils/crypto"); const repo = __importStar(require("../repositories/supportRepository")); const supportRealtimeService_1 = require("./supportRealtimeService"); const settingsRepository = __importStar(require("../repositories/settingsRepository")); const supportMessagePolicy_1 = require("./supportMessagePolicy"); const fileMagic_1 = require("../utils/fileMagic"); const uploadValidation_1 = require("../utils/uploadValidation"); const supportUpload_1 = require("../middleware/supportUpload"); const fileIntegrityService_1 = require("./fileIntegrityService"); const STAFF_ROLES = new Set(['admin', 'moderator', 'super_admin']); function isStaffRole(role) { return !!role && STAFF_ROLES.has(role); } function previewForMessage(body, attachmentName) { if (body?.trim()) return body.trim().slice(0, 200); if (attachmentName) return `📎 ${attachmentName}`; return 'Message'; } function mapMessage(row, staffNames, actions) { const staffName = row.sender_type === 'staff' && row.sender_user_id ? staffNames?.get(row.sender_user_id) ?? null : null; const deleted = !!row.deleted_at; return { id: row.id, conversationId: row.conversation_id, senderType: row.sender_type, senderUserId: row.sender_user_id, senderDisplayName: staffName, body: deleted ? null : row.body, attachmentUrl: deleted ? null : row.attachment_url, attachmentName: deleted ? null : row.attachment_name, attachmentMime: deleted ? null : row.attachment_mime, readAt: row.read_at?.toISOString() ?? null, editedAt: row.edited_at?.toISOString() ?? null, deletedAt: row.deleted_at?.toISOString() ?? null, deleted, createdAt: row.created_at.toISOString(), canEdit: actions?.canEdit ?? false, canDelete: actions?.canDelete ?? false, editAvailableUntil: actions?.editAvailableUntil ?? null, deleteAvailableUntil: actions?.deleteAvailableUntil ?? null, }; } async function loadActionWindows() { const settings = await settingsRepository.getSettings(); return { editWindowMinutes: settings.support_message_edit_window_minutes, deleteWindowMinutes: settings.support_message_delete_window_minutes, }; } function ownerFlags(row, conv, ctx) { return (0, supportMessagePolicy_1.isSupportMessageOwner)({ senderType: row.sender_type, senderUserId: row.sender_user_id, conversationVisitorToken: conv.visitor_token, actorUserId: ctx.userId, actorVisitorToken: ctx.visitorToken, }); } function messageActions(row, conv, ctx, windows) { return (0, supportMessagePolicy_1.resolveSupportMessageActions)({ createdAt: row.created_at, deleted: !!row.deleted_at, isOwner: ownerFlags(row, conv, ctx), editWindowMinutes: windows.editWindowMinutes, deleteWindowMinutes: windows.deleteWindowMinutes, }); } async function refreshConversationPreview(conversationId) { const latest = await repo.findLatestVisibleMessage(conversationId); if (!latest) { await repo.updateConversationPreview(conversationId, '', null); return; } await repo.updateConversationPreview(conversationId, previewForMessage(latest.body, latest.attachment_name), latest.created_at); } function mapConversation(row) { return { id: row.id, userId: row.user_id, visitorToken: row.visitor_token, isAnonymous: row.user_id == null, subject: row.subject, status: row.status, assignedTo: row.assigned_to, lastMessageAt: row.last_message_at?.toISOString() ?? null, lastMessagePreview: row.last_message_preview, unreadUser: row.unread_user, unreadStaff: row.unread_staff, createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString(), }; } function decryptEmail(encrypted) { if (!encrypted) return null; try { return (0, crypto_1.decrypt)(encrypted); } catch { return null; } } async function assertConversationAccess(conversationId, ctx) { const conv = await repo.findConversationById(conversationId); if (!conv) throw new Error('Conversation not found'); if (isStaffRole(ctx.role)) return conv; if (ctx.userId && conv.user_id === ctx.userId) return conv; if (ctx.visitorToken && conv.visitor_token === ctx.visitorToken && conv.user_id == null) { return conv; } throw new Error('Forbidden'); } async function findCurrentConversation(ctx) { const conv = await findActiveConversationRow(ctx); return conv ? mapConversation(conv) : null; } async function findActiveConversationRow(ctx) { if (ctx.userId) { let conv = await repo.findActiveConversationForUser(ctx.userId); if (!conv && ctx.visitorToken) { const visitorConv = await repo.findActiveConversationForVisitor(ctx.visitorToken); if (visitorConv && !visitorConv.user_id) { conv = await repo.attachVisitorConversationToUser(visitorConv.id, ctx.userId); } } return conv; } if (!ctx.visitorToken) return null; return repo.findActiveConversationForVisitor(ctx.visitorToken); } async function ensureConversationRow(ctx) { const existing = await findActiveConversationRow(ctx); if (existing) return existing; if (ctx.userId) { return repo.createConversation({ userId: ctx.userId }); } if (!ctx.visitorToken) { throw new Error('Visitor token is required for anonymous support'); } return repo.createConversation({ visitorToken: ctx.visitorToken }); } async function ensureCurrentConversation(ctx) { return mapConversation(await ensureConversationRow(ctx)); } async function sendToCurrentConversation(ctx, input) { const conv = await ensureConversationRow(ctx); return sendMessage(conv.id, ctx, input); } async function listUserConversations(ctx) { if (!ctx.userId) { if (!ctx.visitorToken) throw new Error('Not authenticated'); const conv = await repo.findActiveConversationForVisitor(ctx.visitorToken); return conv ? [mapConversation(conv)] : []; } const rows = await repo.listConversationsForUser(ctx.userId); return rows.map(mapConversation); } async function getConversationMessages(conversationId, ctx, after) { const conv = await assertConversationAccess(conversationId, ctx); const rows = await repo.listMessages(conversationId, after); const staffIds = rows .filter((m) => m.sender_type === 'staff' && m.sender_user_id) .map((m) => m.sender_user_id); const staffNames = new Map(); for (const id of [...new Set(staffIds)]) { const name = await repo.getStaffDisplayName(id); if (name) staffNames.set(id, name); } const readerSide = isStaffRole(ctx.role) ? 'staff' : 'user'; await repo.markMessagesRead(conversationId, readerSide); await repo.resetUnreadCounters(conversationId, readerSide); await (0, supportRealtimeService_1.publishSupportEvent)(conversationId, { type: 'message.read', conversationId, }); const typing = await (0, supportRealtimeService_1.getTypingIndicators)(conversationId); const windows = await loadActionWindows(); return { messages: rows.map((r) => mapMessage(r, staffNames, messageActions(r, conv, ctx, windows))), typing, policy: windows, }; } async function sendMessage(conversationId, ctx, input) { const conv = await assertConversationAccess(conversationId, ctx); const body = input.body?.trim() ?? null; if (!body && !input.attachmentUrl) { throw new Error('Message body or attachment is required'); } let attachmentUrl = input.attachmentUrl ?? null; let attachmentName = input.attachmentName ?? null; let attachmentMime = input.attachmentMime ?? null; if (attachmentUrl) { const meta = await assertOwnedSupportAttachment(attachmentUrl, ctx); attachmentUrl = publicAttachmentUrl(meta.filename); attachmentName = attachmentName || meta.original_name || meta.filename; attachmentMime = meta.mime; await repo.bindUploadedFileConversation(meta.filename, conversationId); } let senderType; let senderUserId = null; if (isStaffRole(ctx.role)) { senderType = 'staff'; senderUserId = ctx.userId ?? null; } else if (ctx.userId && conv.user_id === ctx.userId) { senderType = 'user'; senderUserId = ctx.userId; } else { senderType = 'visitor'; } const msg = await repo.createMessage({ conversationId, senderType, senderUserId, body, attachmentUrl, attachmentName, attachmentMime, }); const preview = previewForMessage(body, attachmentName); const staffSent = senderType === 'staff'; await repo.touchConversationLastMessage(conversationId, preview, staffSent, !staffSent); if (conv.status === 'resolved' || conv.status === 'closed') { await repo.updateConversation(conversationId, { status: 'open' }); } const windows = await loadActionWindows(); const mapped = mapMessage(msg, undefined, messageActions(msg, conv, ctx, windows)); await (0, supportRealtimeService_1.publishSupportEvent)(conversationId, { type: 'message.new', conversationId, messageId: msg.id, message: mapped, }); return mapped; } async function editMessage(conversationId, messageId, ctx, body) { const conv = await assertConversationAccess(conversationId, ctx); const row = await repo.findMessageById(messageId); if (!row || row.conversation_id !== conversationId) { throw new Error('Message not found'); } const windows = await loadActionWindows(); (0, supportMessagePolicy_1.assertSupportMessageAction)('edit', { createdAt: row.created_at, deleted: !!row.deleted_at, isOwner: ownerFlags(row, conv, ctx), editWindowMinutes: windows.editWindowMinutes, deleteWindowMinutes: windows.deleteWindowMinutes, }); const trimmed = body.trim(); if (!trimmed && !row.attachment_url) { throw new Error('Message body or attachment is required'); } const updated = await repo.updateMessageBody(messageId, trimmed); if (!updated) { throw new Error('Message already deleted'); } await refreshConversationPreview(conversationId); const mapped = mapMessage(updated, undefined, messageActions(updated, conv, ctx, windows)); await (0, supportRealtimeService_1.publishSupportEvent)(conversationId, { type: 'message.updated', conversationId, messageId: updated.id, message: mapped, }); return mapped; } async function deleteMessage(conversationId, messageId, ctx) { const conv = await assertConversationAccess(conversationId, ctx); const row = await repo.findMessageById(messageId); if (!row || row.conversation_id !== conversationId) { throw new Error('Message not found'); } const windows = await loadActionWindows(); (0, supportMessagePolicy_1.assertSupportMessageAction)('delete', { createdAt: row.created_at, deleted: !!row.deleted_at, isOwner: ownerFlags(row, conv, ctx), editWindowMinutes: windows.editWindowMinutes, deleteWindowMinutes: windows.deleteWindowMinutes, }); const updated = await repo.softDeleteMessage(messageId); if (!updated) { throw new Error('Message already deleted'); } await refreshConversationPreview(conversationId); const mapped = mapMessage(updated, undefined, messageActions(updated, conv, ctx, windows)); await (0, supportRealtimeService_1.publishSupportEvent)(conversationId, { type: 'message.deleted', conversationId, messageId: updated.id, message: mapped, }); return mapped; } async function setTyping(conversationId, ctx, active) { await assertConversationAccess(conversationId, ctx); const party = isStaffRole(ctx.role) ? 'staff' : 'user'; await (0, supportRealtimeService_1.setTypingIndicator)(conversationId, party, active); return { ok: true }; } async function listAdminConversations(filters) { const pageSize = Math.min(filters.pageSize ?? 30, 100); const page = Math.max(filters.page ?? 1, 1); const { rows, total } = await repo.listConversationsAdmin({ status: filters.status, assignedTo: filters.assignedTo, search: filters.search, limit: pageSize, offset: (page - 1) * pageSize, }); return { items: rows.map(mapConversation), total, page, pageSize, totalPages: Math.ceil(total / pageSize) || 1, }; } async function getAdminConversationDetail(conversationId) { const conv = await repo.findConversationById(conversationId); if (!conv) throw new Error('Conversation not found'); let userContext = null; if (conv.user_id) { const u = await repo.getUserContextForSupport(conv.user_id); if (u) { userContext = { id: u.id, email: decryptEmail(u.email_encrypted), firstName: u.first_name, lastName: u.last_name, displayName: [u.first_name, u.last_name].filter(Boolean).join(' ').trim() || null, role: u.role_name, emailVerified: u.email_verified, isEnabled: u.is_enabled, createdAt: u.created_at.toISOString(), }; } } return { conversation: mapConversation(conv), user: userContext, }; } async function updateAdminConversation(conversationId, staffUserId, patch) { const conv = await repo.findConversationById(conversationId); if (!conv) throw new Error('Conversation not found'); const updated = await repo.updateConversation(conversationId, { status: patch.status, assignedTo: patch.assignedTo !== undefined ? patch.assignedTo : conv.assigned_to ?? (patch.status === 'open' ? staffUserId : conv.assigned_to), subject: patch.subject, }); await (0, supportRealtimeService_1.publishSupportEvent)(conversationId, { type: 'conversation.updated', conversationId, }); return mapConversation(updated); } async function getStaffUnreadCount() { return repo.countUnreadStaffInbox(); } function resolveUploadPath(storedName) { const base = path_1.default.resolve(process.cwd(), 'data', 'support-uploads'); const safe = path_1.default.basename(storedName); return path_1.default.join(base, safe); } function ensureUploadDir() { const dir = path_1.default.resolve(process.cwd(), 'data', 'support-uploads'); fs_1.default.mkdirSync(dir, { recursive: true }); return dir; } function publicAttachmentUrl(storedName) { return `/api/v1/support/files/${encodeURIComponent(storedName)}`; } const SUPPORT_FILE_RE = /^\/api\/v1\/support\/files\/([^/?#]+)$/i; /** Extract basename from a support attachment URL (relative or absolute). */ function parseSupportAttachmentFilename(url) { try { const pathOnly = url.startsWith('http') ? new URL(url).pathname : url.split('?')[0] ?? url; const m = pathOnly.match(SUPPORT_FILE_RE); if (!m?.[1]) return null; const name = path_1.default.basename(decodeURIComponent(m[1])); if (!name || name === '.' || name === '..') return null; return name; } catch { return null; } } function safeDisplayName(originalName, mime) { const base = path_1.default.basename(originalName || 'attachment').replace(/[^\w.\-()+ ]+/g, '_').slice(0, 180); const ext = (0, fileMagic_1.extensionForMime)(mime); const withoutExt = base.replace(/\.[^.]+$/, '') || 'attachment'; return `${withoutExt}${ext}`; } /** * Validate magic/ClamAV, rename to uuid+safeExt, register ACL row. */ async function finalizeSupportUpload(input) { const tempPath = resolveUploadPath(input.tempFilename); let detected; try { detected = await (0, uploadValidation_1.validateUploadedFile)(tempPath, supportUpload_1.SUPPORT_ALLOWED_MIMES); } catch (e) { (0, fileMagic_1.removeUploadedFile)(tempPath); throw e; } const ext = (0, fileMagic_1.extensionForMime)(detected); const finalName = `${(0, uuid_1.v4)()}${ext}`; const finalPath = resolveUploadPath(finalName); fs_1.default.renameSync(tempPath, finalPath); const originalName = safeDisplayName(input.originalName, detected); await repo.insertUploadedFile({ filename: finalName, mime: detected, originalName, conversationId: input.conversationId ?? null, uploadedByUserId: input.ctx.userId ?? null, visitorToken: input.ctx.visitorToken ?? null, }); await (0, fileIntegrityService_1.recordUploadedFile)(fileIntegrityService_1.FILE_INTEGRITY_ROOTS.support, finalName); return { filename: finalName, mime: detected, originalName, url: publicAttachmentUrl(finalName), }; } async function assertOwnedSupportAttachment(url, ctx) { const filename = parseSupportAttachmentFilename(url); if (!filename) throw new Error('Invalid attachment URL'); const row = await repo.findUploadedFile(filename); if (!row) throw new Error('Attachment not found'); if (isStaffRole(ctx.role)) return row; if (ctx.userId && row.uploaded_by_user_id === ctx.userId) return row; if (ctx.visitorToken && row.visitor_token === ctx.visitorToken) return row; if (row.conversation_id) { await assertConversationAccess(row.conversation_id, ctx); return row; } throw new Error('Forbidden'); } /** Authorize download of a stored support file. */ async function assertSupportFileDownloadAccess(filename, ctx) { const safe = path_1.default.basename(filename); const filePath = resolveUploadPath(safe); if (!fs_1.default.existsSync(filePath)) throw new Error('Not found'); if (isStaffRole(ctx.role)) { const row = await repo.findUploadedFile(safe); return { mime: row?.mime || mimeFromFilename(safe), originalName: row?.original_name ?? null, filePath, }; } const row = await repo.findUploadedFile(safe); if (row) { if (ctx.userId && row.uploaded_by_user_id === ctx.userId) { return { mime: row.mime, originalName: row.original_name, filePath }; } if (ctx.visitorToken && row.visitor_token === ctx.visitorToken) { return { mime: row.mime, originalName: row.original_name, filePath }; } if (row.conversation_id) { await assertConversationAccess(row.conversation_id, ctx); return { mime: row.mime, originalName: row.original_name, filePath }; } } // Legacy files uploaded before ACL registry: allow if referenced by an accessible message. const msg = await repo.findMessageByAttachmentFilename(safe); if (msg) { await assertConversationAccess(msg.conversation_id, ctx); return { mime: mimeFromFilename(safe), originalName: null, filePath, }; } throw new Error('Forbidden'); } function mimeFromFilename(filename) { const ext = path_1.default.extname(filename).toLowerCase(); switch (ext) { case '.jpg': case '.jpeg': return 'image/jpeg'; case '.png': return 'image/png'; case '.gif': return 'image/gif'; case '.webp': return 'image/webp'; case '.pdf': return 'application/pdf'; case '.txt': return 'text/plain'; case '.doc': return 'application/msword'; case '.docx': return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'; default: return 'application/octet-stream'; } } /** Content-Disposition filename* / filename header value. */ function attachmentContentDisposition(downloadName) { const ascii = downloadName.replace(/[^\x20-\x7E]/g, '_').replace(/"/g, ''); const encoded = encodeURIComponent(downloadName); return `attachment; filename="${ascii}"; filename*=UTF-8''${encoded}`; } /** Links all anonymous visitor conversations to a newly registered or logged-in user. */ async function mergeVisitorSupportForUser(userId, visitorToken) { if (!visitorToken || visitorToken.length < 16) return 0; const count = await repo.mergeAllVisitorConversationsToUser(visitorToken, userId); if (count > 0) { const rows = await repo.listConversationsForUser(userId, count); for (const row of rows.slice(0, count)) { await (0, supportRealtimeService_1.publishSupportEvent)(row.id, { type: 'conversation.updated', conversationId: row.id, }); } } return count; } //# sourceMappingURL=supportService.js.map