diff --git a/server/db/schema.pg.sql b/server/db/schema.pg.sql index b9e1ff3..a23b2aa 100644 --- a/server/db/schema.pg.sql +++ b/server/db/schema.pg.sql @@ -163,6 +163,31 @@ CREATE TABLE IF NOT EXISTS message_reactions ( PRIMARY KEY (message_id, user_id, emoji) ); +-- UGC moderation (App Store Review guideline 1.2): report a message + block a user. +-- Reports are workspace-internal — surfaced to the tenant's admins, who can delete the message / act. +CREATE TABLE IF NOT EXISTS message_reports ( + id TEXT PRIMARY KEY, + team_id TEXT NOT NULL, + message_id TEXT NOT NULL, + reporter_id TEXT NOT NULL, + reported_id TEXT NOT NULL, + reason TEXT, + snippet TEXT, + created_at BIGINT NOT NULL, + status TEXT NOT NULL DEFAULT 'open' +); +CREATE INDEX IF NOT EXISTS idx_reports_team ON message_reports(team_id, created_at); + +-- A one-directional block: blocker no longer receives the blocked user's messages or calls. +CREATE TABLE IF NOT EXISTS user_blocks ( + blocker_id TEXT NOT NULL, + blocked_id TEXT NOT NULL, + team_id TEXT NOT NULL, + created_at BIGINT NOT NULL, + PRIMARY KEY (blocker_id, blocked_id) +); +CREATE INDEX IF NOT EXISTS idx_blocks_blocker ON user_blocks(blocker_id); + CREATE TABLE IF NOT EXISTS attachments ( id TEXT PRIMARY KEY, team_id TEXT NOT NULL, diff --git a/server/public/home.html b/server/public/home.html index 56380cd..3daabd9 100644 --- a/server/public/home.html +++ b/server/public/home.html @@ -1507,6 +1507,8 @@ function profileHTML(u){ + '
' + ''+ic('layoutDashboard',16)+' Dashboard' + ''+ic('settings',16)+' Settings' + + ''+ic('ban',16)+' Blocked users' + + (u.role==='admin'?''+ic('flag',16)+' Reported messages':'') + ''+ic('logOut',16)+' Logout' + ''; } @@ -1519,6 +1521,10 @@ function wireProfile(){ if(lo)lo.onclick=async()=>{ await unsubscribePush(); try{await fetch('/api/logout',{method:'POST'});}catch(_){} location.href='/';}; const ps=document.getElementById('psettings'); if(ps)ps.onclick=()=>{ menu.classList.remove('open'); openSettings(); }; + const pbk=document.getElementById('pblocked'); + if(pbk)pbk.onclick=()=>{ menu.classList.remove('open'); openBlockedManager(); }; + const prp=document.getElementById('preports'); + if(prp)prp.onclick=()=>{ menu.classList.remove('open'); openReportsAdmin(); }; const stog=menu.querySelector('#psStatusToggle'); if(stog) stog.onclick=(e)=>{ e.stopPropagation(); const o=menu.querySelector('#psOptions'); if(o) o.style.display=(o.style.display==='none'?'block':'none'); }; menu.querySelectorAll('.ps-opt').forEach(a=>a.onclick=async(e)=>{ e.stopPropagation(); const st=a.dataset.st; ME.status=st; const cd=menu.querySelector('.ps-current .st-dot'); if(cd) cd.className='st-dot '+st; @@ -1665,6 +1671,8 @@ function openStorage(){ // ---------- Chat (1:1 + groups) ---------- let ME={}; let CONTACTS=[]; // team users (for new DMs / picking group members) +let BLOCKED=new Set(); // ids of users I've blocked (UGC guideline 1.2) — hide their content, gate calls +async function loadBlocked(){ try{ const b=await fetch('/api/users/blocked').then(r=>r.json()); if(b&&Array.isArray(b.ids)) BLOCKED=new Set(b.ids); }catch(_){} } let ROWS=[]; // sidebar items: {kind:'dm'|'group', id, name, online?, members?, last_body, last_at, last_from_me, unread} const _lastSeen={}; // #8: userId -> last-seen ts, kept STICKY so a rebuild/presence event that lacks it can't flap the label back to "Offline" let selected=null; // {kind,id} or null = welcome @@ -2102,7 +2110,7 @@ async function loadSidebar(){ // the last_seen DB write), which used to flip the subtitle from "last seen …" to "Offline". Remember any // known value and backfill nulls from it so the label stays stable. items.forEach(it=>{ if(it.kind==='dm'&&!it.self){ if(it.lastSeen) _lastSeen[it.id]=it.lastSeen; else if(_lastSeen[it.id]) it.lastSeen=_lastSeen[it.id]; } }); - ROWS=items; + ROWS=(BLOCKED&&BLOCKED.size)?items.filter(it=>!(it.kind==='dm' && !it.self && BLOCKED.has(it.id))):items; // hide blocked DMs renderChats(searchVal()); updateRailUnread(); prewarmNotifAvatars(); @@ -2313,9 +2321,102 @@ function msgMenuItems(m){ if(m.body) items.push({ic:'copy', label:'Copy', fn:()=>copyMessageText(m)}); if(m.attachment && !m.deleted) items.push({ic:'download', label:'Save', fn:()=>saveAttachment(m)}); // #9: native long-press "Save" is disabled now, so offer Save explicitly if(!m.deleted && !m.poll) items.push({ic:(m.pinned?'pinOff':'pin'), label:(m.pinned?'Unpin':'Pin'), fn:()=>pinMessage(m.id, !m.pinned)}); // #13 + // UGC moderation (App Store guideline 1.2): report someone else's message + block its sender. + const sys=(m.from==='__system__'||m.system); + if(!mine && !sys && m.from){ + items.push({ic:'flag', label:'Report', fn:()=>reportMessage(m)}); + const blk=BLOCKED.has(m.from); + items.push({ic:'ban', label:(blk?'Unblock user':'Block user'), danger:!blk, fn:()=>toggleBlock(m.from, m.fromName||nameForId(m.from))}); + } items.push({ic:'trash', label:'Delete', danger:true, fn:()=>openDeleteDialog(m)}); // #18: branded dialog offers "for me" / "for everyone" return items; } +// Best-effort display name for a user id (block confirmations / labels). +function nameForId(id){ if(!id) return 'this user'; if(id===(ME&&ME.id)) return 'you'; const c=(CONTACTS||[]).find(x=>x&&x.id===id); if(c&&c.name) return c.name; const r=(ROWS||[]).find(x=>x&&x.kind==='dm'&&x.id===id); return (r&&r.name)||'this user'; } +// Report a message to the workspace admins. Small branded picker of canned reasons. +function reportMessage(m){ + if(!m||!m.id) return; + document.querySelectorAll('.bz-modal-ov').forEach(x=>x.remove()); + const reasons=['Spam','Harassment or bullying','Inappropriate or offensive','Other']; + const ov=document.createElement('div'); ov.className='bz-modal-ov'; + ov.style.cssText='position:fixed;inset:0;z-index:100000;background:rgba(16,26,53,.45);backdrop-filter:blur(2px);display:flex;align-items:center;justify-content:center;padding:20px'; + ov.innerHTML='
' + +'

'+ic('flag',18)+'Report message

' + +'

This message is sent to your workspace admins for review.

' + +'
'+reasons.map(r=>'').join('')+'
' + +'
' + +'
'; + document.body.appendChild(ov); + ov.addEventListener('click', async (e)=>{ + if(e.target===ov||e.target.closest('[data-x]')){ ov.remove(); return; } + const rb=e.target.closest('[data-r]'); if(!rb) return; + ov.remove(); + try{ await postJSON('/api/messages/report',{ id:m.id, reason:rb.dataset.r }); toast('Reported. Your admins will review it.'); } + catch(err){ toast((err&&err.message)||'Could not report'); } + }); +} +// Block / unblock a user. Blocking severs their messages + calls to me (server-enforced); reloads views. +async function toggleBlock(uid, name){ + if(!uid || uid===(ME&&ME.id)) return; + const nm=name||nameForId(uid); + if(BLOCKED.has(uid)){ + try{ await postJSON('/api/users/unblock',{ userId:uid }); BLOCKED.delete(uid); toast('Unblocked '+nm); }catch(e){ toast((e&&e.message)||'Could not unblock'); return; } + } else { + const ok=await bzConfirm("You won't receive messages or calls from "+nm+". You can unblock them anytime.", {title:'Block '+nm+'?', okText:'Block', danger:true}); + if(!ok) return; + try{ await postJSON('/api/users/block',{ userId:uid }); BLOCKED.add(uid); toast('Blocked '+nm); }catch(e){ toast((e&&e.message)||'Could not block'); return; } + } + try{ await loadSidebar(); }catch(_){} + try{ if(typeof reloadThread==='function') reloadThread(); }catch(_){} +} +// "Blocked users" manager (profile menu) — list + unblock. +async function openBlockedManager(){ + let list=[]; try{ const b=await fetch('/api/users/blocked').then(r=>r.json()); if(b&&Array.isArray(b.users)) list=b.users; if(b&&Array.isArray(b.ids)) BLOCKED=new Set(b.ids); }catch(_){} + document.querySelectorAll('.bz-modal-ov').forEach(x=>x.remove()); + const ov=document.createElement('div'); ov.className='bz-modal-ov'; + ov.style.cssText='position:fixed;inset:0;z-index:100000;background:rgba(16,26,53,.45);backdrop-filter:blur(2px);display:flex;align-items:center;justify-content:center;padding:20px'; + const rows=list.length?list.map(u=>'
'+pEsc(u.name||'Unknown')+'
').join(''):'

You haven’t blocked anyone.

'; + ov.innerHTML='
' + +'

'+ic('ban',18)+'Blocked users

' + +'
'+rows+'
' + +'
' + +'
'; + document.body.appendChild(ov); + ov.addEventListener('click', async (e)=>{ + if(e.target===ov||e.target.closest('[data-x]')){ ov.remove(); return; } + const ub=e.target.closest('[data-u]'); if(!ub) return; + try{ await postJSON('/api/users/unblock',{ userId:ub.dataset.u }); BLOCKED.delete(ub.dataset.u); ub.parentNode.remove(); toast('Unblocked'); await loadSidebar(); }catch(err){ toast((err&&err.message)||'Could not unblock'); } + }); +} +// Admin: reported-messages review (profile menu, admins only). +async function openReportsAdmin(){ + let list=[]; try{ list=await fetch('/api/reports').then(r=>r.json()); }catch(_){} if(!Array.isArray(list)) list=[]; + document.querySelectorAll('.bz-modal-ov').forEach(x=>x.remove()); + const ov=document.createElement('div'); ov.className='bz-modal-ov'; + ov.style.cssText='position:fixed;inset:0;z-index:100000;background:rgba(16,26,53,.45);backdrop-filter:blur(2px);display:flex;align-items:center;justify-content:center;padding:20px'; + const row=(r)=>'
' + +'
'+pEsc(r.reported)+' reported by '+pEsc(r.reporter)+(r.status==='resolved'?' · resolved':'')+'
' + +(r.reason?'
'+pEsc(r.reason)+'
':'') + +(r.snippet?'
“'+pEsc(r.snippet)+'”
':'') + +'
' + +'' + +'' + +(r.status!=='resolved'?'':'') + +'
'; + const bodyHTML=list.length?list.map(row).join(''):'

No reports.

'; + ov.innerHTML='
' + +'

'+ic('flag',18)+'Reported messages

' + +'
'+bodyHTML+'
' + +'
' + +'
'; + document.body.appendChild(ov); + ov.addEventListener('click', async (e)=>{ + if(e.target===ov||e.target.closest('[data-x]')){ ov.remove(); return; } + const del=e.target.closest('[data-del]'); if(del){ if(await bzConfirm('Delete this message for everyone in the chat?', {title:'Delete message?', okText:'Delete', danger:true})){ try{ await postJSON('/api/messages/delete',{ id:del.dataset.del }); try{ markMsgDeleted(del.dataset.del); }catch(_){} toast('Message deleted'); del.textContent='Deleted'; del.disabled=true; }catch(err){ toast((err&&err.message)||'Could not delete'); } } return; } + const bl=e.target.closest('[data-block]'); if(bl){ await toggleBlock(bl.dataset.block, bl.dataset.name); return; } + const rs=e.target.closest('[data-resolve]'); if(rs){ try{ await postJSON('/api/reports/resolve',{ id:rs.dataset.resolve, status:'resolved' }); const row=rs.closest('[data-id]'); if(row) row.style.opacity=.55; rs.remove(); toast('Marked resolved'); }catch(err){ toast('Could not update'); } return; } + }); +} // #9 (mobile): long-press a message → a dimmed + blurred backdrop and a bottom action sheet with quick // reactions and every action (reply / forward / copy / pin / delete). This replaces the old hover-style // ".show-actions" reveal on touch — which could sit hidden behind an image and stopped working after the @@ -6453,6 +6554,7 @@ window.addEventListener('message',(e)=>{ if(_meet && /^\d{6}$/.test(_meet) && !me){ document.getElementById('loading').style.display='none'; return startGuestMeeting(_meet); } if(!me){ await renderLogin(); document.getElementById('loading').style.display='none'; return; } ME=me; + loadBlocked(); // fetch my block list (UGC moderation) — non-blocking document.getElementById('hdrRight').innerHTML=bellHTML()+profileHTML(me); loadNotifs(); wireBell(); wireProfile(); placeHdrRight(); window.addEventListener('resize', placeHdrRight); // mobile: bell+profile live in the chat-list header (no top bar) diff --git a/server/public/icons.js b/server/public/icons.js index 16e6556..bcee59f 100644 --- a/server/public/icons.js +++ b/server/public/icons.js @@ -75,6 +75,8 @@ bluetooth: '', speaker: '', speakerOff: '', + flag: '', + ban: '', }; window.ICON = P; window.ic = function (name, size) { diff --git a/server/repos.js b/server/repos.js index 8568a11..8dee6f2 100644 --- a/server/repos.js +++ b/server/repos.js @@ -54,6 +54,8 @@ const users = { enableMfa: (id) => db.prepare('UPDATE users SET mfa_enabled=1 WHERE id=?').run(id), setName: (id, name) => db.prepare('UPDATE users SET name=? WHERE id=?').run(name, id), setRole: (id, role) => db.prepare('UPDATE users SET role=? WHERE id=?').run(role, id), + // Workspace admins (for routing UGC reports to a moderator). + adminsOf: async (tenantId) => (await db.prepare("SELECT id FROM users WHERE team_id=? AND role='admin'").all(tenantId)).map((r) => r.id), setPassword: (id, hash, salt) => db.prepare('UPDATE users SET pw_hash=?, pw_salt=? WHERE id=?').run(hash, salt, id), setActive: (id, active) => db.prepare('UPDATE users SET active=? WHERE id=?').run(active ? 1 : 0, id), setAvatar: (id, url) => db.prepare('UPDATE users SET avatar_url=? WHERE id=?').run(url || null, id), @@ -234,13 +236,16 @@ const messages = { // JS afterwards — so the LIMIT counts only VISIBLE messages. Filtering after the LIMIT returned < PAGE rows // whenever a recent message had been hidden, and the client read that as "no older history" and stopped // paginating (a chat with a deleted recent message wouldn't scroll back). + // `a` is the VIEWER. Exclude messages from users the viewer has blocked (in SQL, like message_hidden, + // so the LIMIT counts only VISIBLE messages and pagination doesn't stall). thread: (teamId, a, b, limit = 500, before = null) => { const cond = before != null ? ' AND created_at < ?' : ''; - const args = before != null ? [teamId, a, b, b, a, a, before, limit] : [teamId, a, b, b, a, a, limit]; + const args = before != null ? [teamId, a, b, b, a, a, a, before, limit] : [teamId, a, b, b, a, a, a, limit]; return db.prepare(`SELECT * FROM ( SELECT * FROM messages WHERE team_id=? AND conversation_id IS NULL AND ((sender_id=? AND recipient_id=?) OR (sender_id=? AND recipient_id=?)) - AND id NOT IN (SELECT message_id FROM message_hidden WHERE user_id=?)${cond} + AND id NOT IN (SELECT message_id FROM message_hidden WHERE user_id=?) + AND sender_id NOT IN (SELECT blocked_id FROM user_blocks WHERE blocker_id=?)${cond} ORDER BY created_at DESC LIMIT ? ) t ORDER BY created_at ASC`).all(...args); }, @@ -259,10 +264,11 @@ const messages = { // Group conversation helpers. threadByConversation: (conversationId, userId, limit = 500, before = null) => { const cond = before != null ? ' AND created_at < ?' : ''; - const args = before != null ? [conversationId, userId, before, limit] : [conversationId, userId, limit]; + const args = before != null ? [conversationId, userId, userId, before, limit] : [conversationId, userId, userId, limit]; return db.prepare(`SELECT * FROM ( SELECT * FROM messages WHERE conversation_id=? - AND id NOT IN (SELECT message_id FROM message_hidden WHERE user_id=?)${cond} + AND id NOT IN (SELECT message_id FROM message_hidden WHERE user_id=?) + AND sender_id NOT IN (SELECT blocked_id FROM user_blocks WHERE blocker_id=?)${cond} ORDER BY created_at DESC LIMIT ? ) t ORDER BY created_at ASC`).all(...args); }, @@ -431,4 +437,22 @@ const appInstalls = { listForTenant: (tenantId) => db.prepare('SELECT * FROM app_installs WHERE tenant_id=? ORDER BY last_seen DESC').all(tenantId), }; -module.exports = { teams, users, authSessions, machines, audit, sessionsLog, refreshTokens, apiKeys, webhooks, messages, reactions, attachments, conversations, scheduledMeetings, callHistory, recordings, polls, pollVotes, pushSubs, favorites, deviceTokens, appInstalls }; +// UGC moderation (App Store guideline 1.2). +const reports = { + add: ({ id, teamId, messageId, reporterId, reportedId, reason, snippet }) => + db.prepare('INSERT INTO message_reports (id,team_id,message_id,reporter_id,reported_id,reason,snippet,created_at,status) VALUES (?,?,?,?,?,?,?,?,?)') + .run(id, teamId, messageId, reporterId, reportedId, reason || null, snippet || null, now(), 'open'), + listForTeam: (teamId, limit = 200) => db.prepare('SELECT * FROM message_reports WHERE team_id=? ORDER BY created_at DESC LIMIT ?').all(teamId, limit), + setStatus: (id, status) => db.prepare('UPDATE message_reports SET status=? WHERE id=?').run(status, id), + openCountForTeam: async (teamId) => (await db.prepare("SELECT COUNT(*) AS c FROM message_reports WHERE team_id=? AND status='open'").get(teamId)).c, +}; + +const blocks = { + add: (blockerId, blockedId, teamId) => + db.prepare('INSERT INTO user_blocks (blocker_id,blocked_id,team_id,created_at) VALUES (?,?,?,?) ON CONFLICT(blocker_id,blocked_id) DO NOTHING').run(blockerId, blockedId, teamId, now()), + remove: (blockerId, blockedId) => db.prepare('DELETE FROM user_blocks WHERE blocker_id=? AND blocked_id=?').run(blockerId, blockedId), + has: async (blockerId, blockedId) => !!(await db.prepare('SELECT 1 FROM user_blocks WHERE blocker_id=? AND blocked_id=?').get(blockerId, blockedId)), + listFor: async (blockerId) => (await db.prepare('SELECT blocked_id FROM user_blocks WHERE blocker_id=? ORDER BY created_at DESC').all(blockerId)).map((r) => r.blocked_id), +}; + +module.exports = { teams, users, authSessions, machines, audit, sessionsLog, refreshTokens, apiKeys, webhooks, messages, reactions, attachments, conversations, scheduledMeetings, callHistory, recordings, polls, pollVotes, pushSubs, favorites, deviceTokens, appInstalls, reports, blocks }; diff --git a/server/routes.js b/server/routes.js index 393f6ef..38a1bea 100644 --- a/server/routes.js +++ b/server/routes.js @@ -968,6 +968,7 @@ route('POST', '/api/calls/dm/start', async (req, res) => { if (!u) return json(res, 401, { error: 'unauthorized' }); const { to } = await readBody(req); if (!to || !await R.users.inTenant(to, u.team_id)) return json(res, 404, { error: 'no such contact' }); + if (await R.blocks.has(to, u.id)) return json(res, 403, { error: 'This user is unavailable.' }); // callee blocked the caller → don't ring json(res, 200, await CALLS.startDmCall(u, to, u.team_id)); }); @@ -978,7 +979,7 @@ route('POST', '/api/calls/invite', async (req, res) => { if (!u) return json(res, 401, { error: 'unauthorized' }); const { room, userIds } = await readBody(req); if (!room || !meetingRooms.has(String(room))) return json(res, 404, { error: 'call not found' }); - const ids = await asyncFilter((Array.isArray(userIds) ? userIds : []), async (x) => typeof x === 'string' && x !== u.id && await R.users.inTenant(x, u.team_id)); + const ids = await asyncFilter((Array.isArray(userIds) ? userIds : []), async (x) => typeof x === 'string' && x !== u.id && await R.users.inTenant(x, u.team_id) && !(await R.blocks.has(x, u.id))); // skip anyone who blocked the caller // #15: adding people to a 1:1 call promotes it to a persistent GROUP call (survives leaves + lets an added // person rejoin after dropping). When that happens promoteDmToGroup's own group-call broadcast already rings // the invitees in, so we only send the plain call-invite for a call that WASN'T promoted (group/ad-hoc). @@ -1587,6 +1588,7 @@ route('POST', '/api/messages', async (req, res) => { const conv = await R.conversations.byId(group); const gname = (conv && conv.name) || 'Group'; const pushBody = (u.name || u.email) + ': ' + (text ? (text.length > 80 ? text.slice(0, 80) + '…' : text) : '📎 Attachment'); for (const mid of await R.conversations.members(group)) { + if (mid !== u.id && await R.blocks.has(mid, u.id)) continue; // member blocked the sender → deliver nothing to them try { CHAT.pushToUser(mid, push); } catch (_) {} // includes sender's other tabs if (mid !== u.id) PUSH.sendToUser(mid, { title: gname, body: pushBody, kind: 'group', id: group, tag: 'group:' + group }); } @@ -1600,10 +1602,13 @@ route('POST', '/api/messages', async (req, res) => { await R.messages.send({ id, teamId: u.team_id, senderId: u.id, recipientId: toId, body: text, replyTo: replyTo || null, attachmentId: attachmentId || null }); const dto = await buildMsgDTO(await R.messages.byId(id), await namesFor(u.team_id), u.id); const push = { type: 'chat-message', message: { ...dto, fromName: u.name || u.email } }; - try { CHAT.pushToUser(toId, push); } catch (_) {} + // If the recipient has blocked the sender, persist the message but deliver nothing to them (no live + // push, no background notification). The sender's own devices still sync it, so from their side it looks sent. + const blockedByRcpt = (toId !== u.id) && await R.blocks.has(toId, u.id); + if (!blockedByRcpt) try { CHAT.pushToUser(toId, push); } catch (_) {} if (toId !== u.id) try { CHAT.pushToUser(u.id, push); } catch (_) {} // sync the sender's other devices (skip for self-notes) - // Background/closed-tab push to the recipient (opens the DM). Not for a note-to-self. - if (toId !== u.id) PUSH.sendToUser(toId, { title: (u.name || u.email), body: (text ? (text.length > 80 ? text.slice(0, 80) + '…' : text) : '📎 Attachment'), kind: 'dm', id: u.id, tag: 'dm:' + u.id, icon: u.avatar_url || undefined }); + // Background/closed-tab push to the recipient (opens the DM). Not for a note-to-self, not if blocked. + if (toId !== u.id && !blockedByRcpt) PUSH.sendToUser(toId, { title: (u.name || u.email), body: (text ? (text.length > 80 ? text.slice(0, 80) + '…' : text) : '📎 Attachment'), kind: 'dm', id: u.id, tag: 'dm:' + u.id, icon: u.avatar_url || undefined }); json(res, 200, dto); }); @@ -1653,13 +1658,80 @@ route('POST', '/api/messages/delete', async (req, res) => { if (!id) return json(res, 400, { error: 'id required' }); const m = await R.messages.byId(id); if (!m || m.team_id !== u.team_id) return json(res, 404, { error: 'not found' }); - if (m.sender_id !== u.id) return json(res, 403, { error: 'you can only delete your own messages' }); + if (m.sender_id !== u.id && u.role !== 'admin') return json(res, 403, { error: 'you can only delete your own messages' }); // admins can remove reported content (guideline 1.2) await R.messages.markDeleted(id); const evt = { type: 'chat-deleted', id, conversation_id: m.conversation_id || null }; if (m.conversation_id) { for (const mid of await R.conversations.members(m.conversation_id)) { try { CHAT.pushToUser(mid, evt); } catch (_) {} } } else { try { CHAT.pushToUser(m.recipient_id, evt); } catch (_) {} try { CHAT.pushToUser(u.id, evt); } catch (_) {} } json(res, 200, { ok: true }); }); +// ── UGC moderation (App Store Review guideline 1.2) ──────────────────────────────────────────────── +// Report a message. Stored + surfaced to the workspace admins (who can delete it / act). Internal only. +route('POST', '/api/messages/report', async (req, res) => { + const u = await currentUser(req); + if (!u) return json(res, 401, { error: 'unauthorized' }); + const { id, reason } = await readBody(req); + if (!id) return json(res, 400, { error: 'id required' }); + const m = await R.messages.byId(id); + if (!m || m.team_id !== u.team_id) return json(res, 404, { error: 'not found' }); + const canSee = m.conversation_id ? await R.conversations.isMember(m.conversation_id, u.id) : (m.sender_id === u.id || m.recipient_id === u.id); + if (!canSee) return json(res, 403, { error: 'not allowed' }); + const snippet = String(m.body || (m.attachment_id ? '[attachment]' : '')).slice(0, 160); + await R.reports.add({ id: A.id(), teamId: u.team_id, messageId: m.id, reporterId: u.id, reportedId: m.sender_id, reason: String(reason || '').slice(0, 200), snippet }); + try { for (const aid of await R.users.adminsOf(u.team_id)) { if (aid !== u.id) { try { CHAT.pushToUser(aid, { type: 'report-new' }); } catch (_) {} } } } catch (_) {} + json(res, 200, { ok: true }); +}); + +// Block a user: I stop receiving their messages and calls (one-directional). +route('POST', '/api/users/block', async (req, res) => { + const u = await currentUser(req); + if (!u) return json(res, 401, { error: 'unauthorized' }); + const { userId } = await readBody(req); + const target = await R.users.resolve(userId); + if (!target || target === u.id) return json(res, 400, { error: 'invalid user' }); + if (!await R.users.inTenant(target, u.team_id)) return json(res, 404, { error: 'no such user' }); + await R.blocks.add(u.id, target, u.team_id); + json(res, 200, { ok: true }); +}); + +route('POST', '/api/users/unblock', async (req, res) => { + const u = await currentUser(req); + if (!u) return json(res, 401, { error: 'unauthorized' }); + const { userId } = await readBody(req); + if (!userId) return json(res, 400, { error: 'userId required' }); + await R.blocks.remove(u.id, await R.users.resolve(userId)); + json(res, 200, { ok: true }); +}); + +// My block list (ids + names) — powers the "Blocked users" manager and the client-side hide. +route('GET', '/api/users/blocked', async (req, res) => { + const u = await currentUser(req); + if (!u) return json(res, 401, { error: 'unauthorized' }); + const ids = await R.blocks.listFor(u.id); + const names = await namesFor(u.team_id); + json(res, 200, { ids, users: ids.map((id) => ({ id, name: names[id] || 'Unknown' })) }); +}); + +// Admin: list the workspace's reports + resolve them. +route('GET', '/api/reports', async (req, res) => { + const u = await currentUser(req); + if (!u) return json(res, 401, { error: 'unauthorized' }); + if (u.role !== 'admin') return json(res, 403, { error: 'admins only' }); + const names = await namesFor(u.team_id); + const rows = await R.reports.listForTeam(u.team_id); + json(res, 200, rows.map((r) => ({ id: r.id, messageId: r.message_id, reporter: names[r.reporter_id] || 'Unknown', reported: names[r.reported_id] || 'Unknown', reportedId: r.reported_id, reason: r.reason || '', snippet: r.snippet || '', at: r.created_at, status: r.status }))); +}); + +route('POST', '/api/reports/resolve', async (req, res) => { + const u = await currentUser(req); + if (!u) return json(res, 401, { error: 'unauthorized' }); + if (u.role !== 'admin') return json(res, 403, { error: 'admins only' }); + const { id, status } = await readBody(req); + if (!id) return json(res, 400, { error: 'id required' }); + await R.reports.setStatus(id, status === 'open' ? 'open' : 'resolved'); + json(res, 200, { ok: true }); +}); + // #18 Delete-for-me: hide a message from MY view only (any message I can see, mine or not). The row and // everyone else are untouched. Echoed to my OTHER devices so it disappears there too. route('POST', '/api/messages/hide', async (req, res) => {