forked from nkuntz1934/matrix-workers
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreport.ts
More file actions
350 lines (291 loc) · 10.4 KB
/
report.ts
File metadata and controls
350 lines (291 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
// Content Reporting API
// Implements: https://spec.matrix.org/v1.12/client-server-api/#reporting-content
//
// Allows users to report inappropriate content to server admins
import { Hono } from 'hono';
import type { AppEnv } from '../types';
import { Errors } from '../utils/errors';
import { requireAuth } from '../middleware/auth';
const app = new Hono<AppEnv>();
// ============================================
// Types
// ============================================
interface ContentReport {
id: number;
reporter_user_id: string;
room_id: string;
event_id: string;
reason: string;
score: number;
created_at: number;
resolved: boolean;
resolved_by?: string;
resolved_at?: number;
resolution_note?: string;
}
// ============================================
// Endpoints
// ============================================
// POST /_matrix/client/v3/rooms/:roomId/report/:eventId - Report content
app.post('/_matrix/client/v3/rooms/:roomId/report/:eventId', requireAuth(), async (c) => {
const userId = c.get('userId');
const roomId = c.req.param('roomId');
const eventId = c.req.param('eventId');
const db = c.env.DB;
let body: { reason?: string; score?: number };
try {
body = await c.req.json();
} catch {
body = {};
}
const reason = body.reason || '';
const score = typeof body.score === 'number' ? Math.max(-100, Math.min(0, body.score)) : -100;
// Check if user is a member of the room
const membership = await db.prepare(`
SELECT membership FROM room_memberships WHERE room_id = ? AND user_id = ?
`).bind(roomId, userId).first<{ membership: string }>();
if (!membership || !['join', 'leave'].includes(membership.membership)) {
return Errors.forbidden('Not a member of this room').toResponse();
}
// Check if event exists
const event = await db.prepare(`
SELECT event_id FROM events WHERE event_id = ? AND room_id = ?
`).bind(eventId, roomId).first();
if (!event) {
return Errors.notFound('Event not found').toResponse();
}
// Check for duplicate report
const existing = await db.prepare(`
SELECT id FROM content_reports
WHERE reporter_user_id = ? AND room_id = ? AND event_id = ?
`).bind(userId, roomId, eventId).first();
if (existing) {
// Update existing report
await db.prepare(`
UPDATE content_reports SET reason = ?, score = ?, created_at = ?
WHERE reporter_user_id = ? AND room_id = ? AND event_id = ?
`).bind(reason, score, Date.now(), userId, roomId, eventId).run();
} else {
// Create new report
await db.prepare(`
INSERT INTO content_reports (reporter_user_id, room_id, event_id, reason, score, created_at)
VALUES (?, ?, ?, ?, ?, ?)
`).bind(userId, roomId, eventId, reason, score, Date.now()).run();
}
return c.json({});
});
// POST /_matrix/client/v3/rooms/:roomId/report - Report a room
app.post('/_matrix/client/v3/rooms/:roomId/report', requireAuth(), async (c) => {
const userId = c.get('userId');
const roomId = c.req.param('roomId');
const db = c.env.DB;
let body: { reason?: string; score?: number };
try {
body = await c.req.json();
} catch {
body = {};
}
const reason = body.reason || '';
const score = typeof body.score === 'number' ? Math.max(-100, Math.min(0, body.score)) : -100;
// Check if room exists
const room = await db.prepare(`
SELECT room_id FROM rooms WHERE room_id = ?
`).bind(roomId).first();
if (!room) {
return Errors.notFound('Room not found').toResponse();
}
// Check for duplicate report (using NULL event_id for room reports)
const existing = await db.prepare(`
SELECT id FROM content_reports
WHERE reporter_user_id = ? AND room_id = ? AND event_id IS NULL AND report_type = 'room'
`).bind(userId, roomId).first();
if (existing) {
// Update existing report
await db.prepare(`
UPDATE content_reports SET reason = ?, score = ?, created_at = ?
WHERE reporter_user_id = ? AND room_id = ? AND event_id IS NULL AND report_type = 'room'
`).bind(reason, score, Date.now(), userId, roomId).run();
} else {
// Create new report
await db.prepare(`
INSERT INTO content_reports (reporter_user_id, room_id, event_id, reason, score, created_at, report_type)
VALUES (?, ?, NULL, ?, ?, ?, 'room')
`).bind(userId, roomId, reason, score, Date.now()).run();
}
return c.json({});
});
// POST /_matrix/client/v3/users/:reportedUserId/report - Report a user
app.post('/_matrix/client/v3/users/:reportedUserId/report', requireAuth(), async (c) => {
const reporterId = c.get('userId');
const reportedUserId = decodeURIComponent(c.req.param('reportedUserId'));
const db = c.env.DB;
let body: { reason?: string };
try {
body = await c.req.json();
} catch {
body = {};
}
const reason = body.reason || '';
// Check if reported user exists
const user = await db.prepare(`
SELECT user_id FROM users WHERE user_id = ?
`).bind(reportedUserId).first();
if (!user) {
return Errors.notFound('User not found').toResponse();
}
// Check for duplicate report
const existing = await db.prepare(`
SELECT id FROM content_reports
WHERE reporter_user_id = ? AND reported_user_id = ? AND report_type = 'user'
`).bind(reporterId, reportedUserId).first();
if (existing) {
// Update existing report
await db.prepare(`
UPDATE content_reports SET reason = ?, created_at = ?
WHERE reporter_user_id = ? AND reported_user_id = ? AND report_type = 'user'
`).bind(reason, Date.now(), reporterId, reportedUserId).run();
} else {
// Create new report
await db.prepare(`
INSERT INTO content_reports (reporter_user_id, room_id, event_id, reason, score, created_at, report_type, reported_user_id)
VALUES (?, NULL, NULL, ?, -100, ?, 'user', ?)
`).bind(reporterId, reason, Date.now(), reportedUserId).run();
}
return c.json({});
});
// ============================================
// Admin Endpoints for Managing Reports
// ============================================
// GET /_matrix/client/v3/admin/reports - List reports (admin only)
app.get('/_matrix/client/v3/admin/reports', requireAuth(), async (c) => {
const userId = c.get('userId');
const db = c.env.DB;
// Check if user is admin
const user = await db.prepare(`
SELECT admin FROM users WHERE user_id = ?
`).bind(userId).first<{ admin: number }>();
if (!user || user.admin !== 1) {
return Errors.forbidden('Admin access required').toResponse();
}
const from = c.req.query('from');
const limit = Math.min(parseInt(c.req.query('limit') || '50'), 100);
const resolved = c.req.query('resolved');
let query = `
SELECT cr.*, e.sender as reported_user_id, e.event_type, e.content
FROM content_reports cr
LEFT JOIN events e ON cr.event_id = e.event_id
WHERE 1=1
`;
const params: any[] = [];
if (resolved === 'true') {
query += ` AND cr.resolved = 1`;
} else if (resolved === 'false') {
query += ` AND cr.resolved = 0`;
}
if (from) {
query += ` AND cr.id < ?`;
params.push(parseInt(from));
}
query += ` ORDER BY cr.created_at DESC LIMIT ?`;
params.push(limit + 1);
const reports = await db.prepare(query).bind(...params).all<ContentReport & {
reported_user_id: string;
event_type: string;
content: string;
}>();
const hasMore = reports.results.length > limit;
const results = reports.results.slice(0, limit);
const response: any = {
reports: results.map(r => ({
id: r.id,
reporter_user_id: r.reporter_user_id,
reported_user_id: r.reported_user_id,
room_id: r.room_id,
event_id: r.event_id,
event_type: r.event_type,
event_content: r.content ? JSON.parse(r.content) : null,
reason: r.reason,
score: r.score,
created_at: r.created_at,
resolved: r.resolved,
resolved_by: r.resolved_by,
resolved_at: r.resolved_at,
resolution_note: r.resolution_note,
})),
};
if (hasMore && results.length > 0) {
response.next_token = String(results[results.length - 1].id);
}
return c.json(response);
});
// GET /_matrix/client/v3/admin/reports/:reportId - Get specific report
app.get('/_matrix/client/v3/admin/reports/:reportId', requireAuth(), async (c) => {
const userId = c.get('userId');
const reportId = c.req.param('reportId');
const db = c.env.DB;
// Check if user is admin
const user = await db.prepare(`
SELECT admin FROM users WHERE user_id = ?
`).bind(userId).first<{ admin: number }>();
if (!user || user.admin !== 1) {
return Errors.forbidden('Admin access required').toResponse();
}
const report = await db.prepare(`
SELECT cr.*, e.sender as reported_user_id, e.event_type, e.content
FROM content_reports cr
LEFT JOIN events e ON cr.event_id = e.event_id
WHERE cr.id = ?
`).bind(parseInt(reportId)).first<ContentReport & {
reported_user_id: string;
event_type: string;
content: string;
}>();
if (!report) {
return Errors.notFound('Report not found').toResponse();
}
return c.json({
id: report.id,
reporter_user_id: report.reporter_user_id,
reported_user_id: report.reported_user_id,
room_id: report.room_id,
event_id: report.event_id,
event_type: report.event_type,
event_content: report.content ? JSON.parse(report.content) : null,
reason: report.reason,
score: report.score,
created_at: report.created_at,
resolved: report.resolved,
resolved_by: report.resolved_by,
resolved_at: report.resolved_at,
resolution_note: report.resolution_note,
});
});
// POST /_matrix/client/v3/admin/reports/:reportId/resolve - Resolve a report
app.post('/_matrix/client/v3/admin/reports/:reportId/resolve', requireAuth(), async (c) => {
const userId = c.get('userId');
const reportId = c.req.param('reportId');
const db = c.env.DB;
// Check if user is admin
const user = await db.prepare(`
SELECT admin FROM users WHERE user_id = ?
`).bind(userId).first<{ admin: number }>();
if (!user || user.admin !== 1) {
return Errors.forbidden('Admin access required').toResponse();
}
let body: { note?: string };
try {
body = await c.req.json();
} catch {
body = {};
}
const result = await db.prepare(`
UPDATE content_reports
SET resolved = 1, resolved_by = ?, resolved_at = ?, resolution_note = ?
WHERE id = ?
`).bind(userId, Date.now(), body.note || null, parseInt(reportId)).run();
if (result.meta.changes === 0) {
return Errors.notFound('Report not found').toResponse();
}
return c.json({});
});
export default app;