Repository navigation
Expand file tree
/
Copy pathadmin.ts
More file actions
3591 lines (3093 loc) · 127 KB
/
Copy pathadmin.ts
File metadata and controls
3591 lines (3093 loc) · 127 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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Admin API endpoints
import { Hono } from 'hono';
import { createMiddleware } from 'hono/factory';
import type { AppEnv } from '../types';
import { Errors } from '../utils/errors';
import { requireAuth } from '../middleware/auth';
import { getUserById, createRegistrationToken, listRegistrationTokens, revokeRegistrationToken, storeEventIdempotent, updateMembership, getRoom } from '../services/database';
import { invalidatePolicyRulesCache } from '../services/moderation-policy';
import { generateLoginToken, generateOpaqueId, generateRegistrationToken } from '../utils/ids';
import { base64UrlDecode, hashToken, verifySignature } from '../utils/crypto';
import { inboundWireEventIdCandidates } from '../utils/event-signing';
import { federationGet } from '../services/federation-keys';
import { encryptSecret } from './oidc-auth';
import { fetchOIDCDiscovery } from '../services/oidc';
import { logAdminAction } from '../services/admin-audit';
import federation from './federation';
import versions from './versions';
import { QR_LOGIN_REFERENCE_PREFIX, type QrLoginReferenceRecord } from './login';
const app = new Hono<AppEnv>();
// Admin authentication middleware
const requireAdmin = createMiddleware<AppEnv>(async (c, next) => {
const userId = c.get('userId');
if (!userId) {
return Errors.unauthorized('Admin access required').toResponse();
}
const user = await getUserById(c.env.DB, userId);
if (!user || !user.admin) {
return Errors.forbidden('Admin privileges required').toResponse();
}
return next();
});
// Helper to get AdminDurableObject instance
function getAdminDO(env: import('../types').Env) {
const id = env.ADMIN.idFromName('global');
return env.ADMIN.get(id);
}
// Invalidate stats cache after data-modifying operations
async function invalidateStatsCache(env: import('../types').Env) {
const adminDO = getAdminDO(env);
await adminDO.fetch('http://internal/invalidate-cache');
}
// GET /admin/api/stats - Server statistics (via AdminDurableObject for caching)
app.get('/admin/api/stats', requireAuth(), requireAdmin, async (c) => {
const refresh = c.req.query('refresh') === 'true';
const adminDO = getAdminDO(c.env);
const url = new URL('/stats', 'http://internal');
if (refresh) {
url.searchParams.set('refresh', 'true');
}
const response = await adminDO.fetch(url.toString());
const stats = await response.json() as Record<string, unknown>;
// Add server info
return c.json({
...stats,
server: {
name: c.env.SERVER_NAME,
version: c.env.SERVER_VERSION,
},
});
});
// GET /admin/api/stats/history - Time-series statistics for dashboard charts
app.get('/admin/api/stats/history', requireAuth(), requireAdmin, async (c) => {
const db = c.env.DB;
const period = c.req.query('period') || '7d';
// Parse period and calculate date range
let days: number;
if (period === '30d') {
days = 30;
} else {
days = 7; // Default to 7d
}
const now = Date.now();
const startTime = now - days * 24 * 60 * 60 * 1000;
// Generate array of dates for the period (to fill in gaps with zeros)
const dateKeys: string[] = [];
for (let i = days - 1; i >= 0; i--) {
const date = new Date(now - i * 24 * 60 * 60 * 1000);
dateKeys.push(date.toISOString().split('T')[0]); // YYYY-MM-DD format
}
// Query events grouped by day
// D1/SQLite: divide by 86400000 (ms per day) to get day buckets
const eventsQuery = await db.prepare(`
SELECT DATE(origin_server_ts / 1000, 'unixepoch') as date, COUNT(*) as count
FROM events
WHERE origin_server_ts >= ?
GROUP BY DATE(origin_server_ts / 1000, 'unixepoch')
ORDER BY date
`).bind(startTime).all<{ date: string; count: number }>();
// Query user registrations grouped by day
const registrationsQuery = await db.prepare(`
SELECT DATE(created_at / 1000, 'unixepoch') as date, COUNT(*) as count
FROM users
WHERE created_at >= ?
GROUP BY DATE(created_at / 1000, 'unixepoch')
ORDER BY date
`).bind(startTime).all<{ date: string; count: number }>();
// Convert query results to maps for easy lookup
const eventsMap = new Map<string, number>();
for (const row of eventsQuery.results) {
eventsMap.set(row.date, row.count);
}
const registrationsMap = new Map<string, number>();
for (const row of registrationsQuery.results) {
registrationsMap.set(row.date, row.count);
}
// Build the response data array, filling in zeros for missing dates
const data = dateKeys.map(date => ({
date,
events: eventsMap.get(date) || 0,
registrations: registrationsMap.get(date) || 0,
}));
return c.json({
period: period === '30d' ? '30d' : '7d',
data,
});
});
// GET /admin/api/users - List all users
app.get('/admin/api/users', requireAuth(), requireAdmin, async (c) => {
const db = c.env.DB;
const limit = Math.max(1, Math.min(parseInt(c.req.query('limit') || '50', 10) || 50, 100));
const offset = Math.max(0, parseInt(c.req.query('offset') || '0', 10) || 0);
const search = c.req.query('search');
let query = `
SELECT user_id, localpart, display_name, avatar_url, is_guest, is_deactivated, admin, created_at, locked, suspended
FROM users
WHERE is_guest = 0
`;
const params: any[] = [];
if (search) {
query += ' AND (localpart LIKE ? OR display_name LIKE ?)';
params.push(`%${search}%`, `%${search}%`);
}
query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
params.push(limit, offset);
const users = await db.prepare(query).bind(...params).all();
// Get total count (guest presence stubs are hidden from Admin → Users)
let countQuery = 'SELECT COUNT(*) as count FROM users WHERE is_guest = 0';
if (search) {
countQuery += ' AND (localpart LIKE ? OR display_name LIKE ?)';
}
const total = search
? await db.prepare(countQuery).bind(`%${search}%`, `%${search}%`).first<{ count: number }>()
: await db.prepare(countQuery).first<{ count: number }>();
return c.json({
users: users.results,
total: total?.count || 0,
limit,
offset,
});
});
// GET /admin/api/users/:userId - Get user details
app.get('/admin/api/users/:userId', requireAuth(), requireAdmin, async (c) => {
const userId = decodeURIComponent(c.req.param('userId'));
const db = c.env.DB;
const user = await db.prepare(`
SELECT user_id, localpart, display_name, avatar_url, is_guest, is_deactivated, admin, created_at, updated_at, locked, suspended
FROM users WHERE user_id = ?
`).bind(userId).first();
if (!user) {
return Errors.notFound('User not found').toResponse();
}
// Get user's devices
const devices = await db.prepare(
'SELECT device_id, display_name, last_seen_ts, last_seen_ip FROM devices WHERE user_id = ?'
).bind(userId).all();
// Get user's rooms
const rooms = await db.prepare(`
SELECT rm.room_id, rm.membership, r.room_id as room_exists
FROM room_memberships rm
LEFT JOIN rooms r ON rm.room_id = r.room_id
WHERE rm.user_id = ?
`).bind(userId).all();
return c.json({
...user,
devices: devices.results,
rooms: rooms.results,
});
});
// PUT /admin/api/users/:userId - Update user
app.put('/admin/api/users/:userId', requireAuth(), requireAdmin, async (c) => {
const userId = decodeURIComponent(c.req.param('userId'));
const db = c.env.DB;
let body: any;
try {
body = await c.req.json();
} catch {
return Errors.badJson().toResponse();
}
const { display_name, admin, deactivated } = body;
// Build update query
const updates: string[] = [];
const params: any[] = [];
if (display_name !== undefined) {
updates.push('display_name = ?');
params.push(display_name);
}
if (admin !== undefined) {
updates.push('admin = ?');
params.push(admin ? 1 : 0);
}
if (deactivated !== undefined) {
updates.push('is_deactivated = ?');
params.push(deactivated ? 1 : 0);
}
if (updates.length === 0) {
return Errors.missingParam('No fields to update').toResponse();
}
updates.push('updated_at = ?');
params.push(Date.now());
params.push(userId);
await db.prepare(`UPDATE users SET ${updates.join(', ')} WHERE user_id = ?`).bind(...params).run();
await logAdminAction(c, {
action: 'user.update',
target: userId,
details: {
display_name: display_name !== undefined,
admin: admin !== undefined ? !!admin : undefined,
deactivated: deactivated !== undefined ? !!deactivated : undefined,
},
});
return c.json({ success: true });
});
// DELETE /admin/api/users/:userId - Deactivate user
app.delete('/admin/api/users/:userId', requireAuth(), requireAdmin, async (c) => {
const userId = decodeURIComponent(c.req.param('userId'));
const db = c.env.DB;
// Deactivate instead of delete (preserve history)
await db.prepare(
'UPDATE users SET is_deactivated = 1, updated_at = ? WHERE user_id = ?'
).bind(Date.now(), userId).run();
// Revoke all access tokens
await db.prepare('DELETE FROM access_tokens WHERE user_id = ?').bind(userId).run();
// Invalidate stats cache
await invalidateStatsCache(c.env);
await logAdminAction(c, { action: 'user.deactivate', target: userId });
return c.json({ success: true });
});
// POST /admin/api/users/:userId/reset-password - Reset user password
app.post('/admin/api/users/:userId/reset-password', requireAuth(), requireAdmin, async (c) => {
const userId = decodeURIComponent(c.req.param('userId'));
const db = c.env.DB;
let body: any;
try {
body = await c.req.json();
} catch {
return Errors.badJson().toResponse();
}
const { password } = body;
if (!password) {
await logAdminAction(c, {
action: 'user.reset_password',
target: userId,
success: false,
details: { reason: 'missing_password' },
});
return Errors.missingParam('password').toResponse();
}
// Import hash function
const { hashPassword } = await import('../utils/crypto');
const passwordHash = await hashPassword(password);
await db.prepare(
'UPDATE users SET password_hash = ?, updated_at = ? WHERE user_id = ?'
).bind(passwordHash, Date.now(), userId).run();
// Revoke all access tokens to force re-login
await db.prepare('DELETE FROM access_tokens WHERE user_id = ?').bind(userId).run();
await logAdminAction(c, { action: 'user.reset_password', target: userId });
return c.json({ success: true });
});
// ============================================================================
// MSC4323 (stable since spec v1.18): standard account lock/suspend admin
// endpoints. Authorisation is always checked before any account lookup so
// callers cannot enumerate users; locked/suspended state never touches
// sessions or credentials.
// ============================================================================
// Shared validation for the four moderation endpoints. Returns either the
// target row or an error response; ordering follows the spec: 403 for
// non-admins (handled by requireAdmin), then 400 for non-local user IDs,
// then 404 for unknown/deactivated users, then 403 for self/other-admin
// targets on PUT.
async function moderationTarget(
c: { env: import('../types').Env; get: (key: string) => unknown },
userId: string,
opts: { forWrite: boolean }
): Promise<
| {
row: {
user_id: string;
admin: number;
is_deactivated: number;
locked: number;
suspended: number;
};
}
| { error: Response }
> {
const db = c.env.DB;
const requester = c.get('userId');
const serverName = c.env.SERVER_NAME;
const userMatch = userId.match(/^@([^:]+):(.+)$/);
if (!userMatch || userMatch[2] !== serverName) {
return {
error: Errors.invalidParam('userId', 'User does not belong to the local server.').toResponse(),
};
}
const row = await db
.prepare(
`SELECT user_id, admin, is_deactivated, locked, suspended FROM users WHERE user_id = ?`
)
.bind(userId)
.first<{
user_id: string;
admin: number;
is_deactivated: number;
locked: number;
suspended: number;
}>();
if (!row || row.is_deactivated === 1) {
return { error: Errors.notFound('User not found.').toResponse() };
}
if (opts.forWrite && (userId === requester || row.admin === 1)) {
return {
error: Errors.forbidden('Cannot moderate yourself or another administrator.').toResponse(),
};
}
return { row };
}
// GET /_matrix/client/v1/admin/lock/:userId - Lock status of a local user
app.get('/_matrix/client/v1/admin/lock/:userId', requireAuth(), requireAdmin, async (c) => {
const userId = decodeURIComponent(c.req.param('userId'));
const target = await moderationTarget(c, userId, { forWrite: false });
if ('error' in target) return target.error;
return c.json({ locked: target.row.locked === 1 });
});
// PUT /_matrix/client/v1/admin/lock/:userId - Set lock status
app.put('/_matrix/client/v1/admin/lock/:userId', requireAuth(), requireAdmin, async (c) => {
const userId = decodeURIComponent(c.req.param('userId'));
let body: { locked?: boolean };
try {
body = await c.req.json();
} catch {
return Errors.badJson().toResponse();
}
if (typeof body.locked !== 'boolean') {
return Errors.missingParam('locked').toResponse();
}
const target = await moderationTarget(c, userId, { forWrite: true });
if ('error' in target) return target.error;
await c.env.DB.prepare(
`UPDATE users SET locked = ?, updated_at = ? WHERE user_id = ?`
).bind(body.locked ? 1 : 0, Date.now(), userId).run();
await logAdminAction(c, {
action: 'user.lock',
target: userId,
details: { locked: body.locked },
});
// Sessions are intentionally left intact (soft logout semantics).
return c.json({ locked: body.locked });
});
// ============================================================================
// Moderation policy lists (spec module): server-side subscriptions.
//
// A subscription points the server at a policy room, joined by a
// dedicated local system user (@moderation:<server>, created on first
// use with an unknowable random password). m.ban rules in that room's
// m.policy.rule.{user,room,server} state are enforced at our invite/
// join/PDU gates (see src/services/moderation-policy.ts).
// ============================================================================
async function getOrCreateModerationUser(
db: D1Database,
serverName: string
): Promise<string> {
const userId = `@moderation:${serverName}`;
const existing = await db
.prepare('SELECT user_id FROM users WHERE user_id = ?')
.bind(userId)
.first<{ user_id: string }>();
if (existing) return userId;
// Random, discarded credential: the account only acts server-side via
// workflows, never logs in.
const randomPassword = crypto.randomUUID() + crypto.randomUUID();
const { hashPassword } = await import('../utils/crypto');
const passwordHash = await hashPassword(randomPassword);
await db.prepare(
`INSERT INTO users (user_id, localpart, password_hash, display_name, admin, created_at, updated_at)
VALUES (?, 'moderation', ?, 'Moderation Policy Subscriber', 0, ?, ?)`
).bind(userId, passwordHash, Date.now(), Date.now()).run();
return userId;
}
// GET /admin/api/policy-lists - List subscriptions with rule counts
app.get('/admin/api/policy-lists', requireAuth(), requireAdmin, async (c) => {
const db = c.env.DB;
const rows = await db
.prepare(
`SELECT room_id, enabled, subscriber_user_id, added_at, added_by
FROM policy_list_subscriptions ORDER BY added_at DESC`
)
.all<{
room_id: string;
enabled: number;
subscriber_user_id: string;
added_at: number;
added_by: string;
}>();
const lists = [];
for (const row of rows.results) {
let ruleCount = 0;
try {
const counted = await db
.prepare(
`SELECT COUNT(*) AS count FROM room_state rs
JOIN events e ON rs.event_id = e.event_id
WHERE rs.room_id = ? AND rs.event_type IN
('m.policy.rule.user', 'm.policy.rule.room', 'm.policy.rule.server')`
)
.bind(row.room_id)
.first<{ count: number }>();
ruleCount = counted?.count ?? 0;
} catch {
// rules unreadable (room state not synced yet)
}
lists.push({ ...row, enabled: row.enabled === 1, rule_count: ruleCount });
}
return c.json({ lists, total: lists.length });
});
// POST /admin/api/policy-lists - Subscribe to a policy room
app.post('/admin/api/policy-lists', requireAuth(), requireAdmin, async (c) => {
const db = c.env.DB;
const requester = c.get('userId');
let body: { room_id?: string };
try {
body = await c.req.json();
} catch {
return Errors.badJson().toResponse();
}
const roomId = body.room_id;
if (!roomId || !roomId.startsWith('!')) {
return Errors.invalidParam('room_id', 'A room ID (!...) is required').toResponse();
}
// The dedicated subscriber user keeps state flowing to us.
const subscriber = await getOrCreateModerationUser(db, c.env.SERVER_NAME);
const room = await getRoom(db, roomId);
const roomServer = roomId.includes(':') ? roomId.slice(roomId.indexOf(':') + 1) : null;
const isRemoteRoom = Boolean(roomServer && roomServer !== c.env.SERVER_NAME);
await db.prepare(
`INSERT INTO policy_list_subscriptions (room_id, enabled, subscriber_user_id, added_at, added_by)
VALUES (?, 1, ?, ?, ?)
ON CONFLICT(room_id) DO UPDATE SET enabled = 1, subscriber_user_id = excluded.subscriber_user_id`
).bind(roomId, subscriber, Date.now(), requester).run();
// Join the policy room so the rules actually flow to us. Local rooms
// with public join rules can be joined directly; remote rooms (or
// invite-only rooms) go through the join workflow — invite-only lists
// need an invite for @moderation:<server> first.
if (!room || isRemoteRoom) {
const targetServer = roomServer ?? c.env.SERVER_NAME;
try {
await c.env.ROOM_JOIN_WORKFLOW.create({
params: {
roomId,
userId: subscriber,
isRemote: isRemoteRoom,
remoteServer: targetServer,
backfill: true,
},
});
} catch (wfErr) {
console.warn('[admin] policy list join workflow failed:', wfErr);
}
} else {
try {
const { joinBotUserToRoom } = await import('./rooms');
await joinBotUserToRoom(c.env, roomId, subscriber);
} catch (joinErr) {
console.warn('[admin] policy list local join failed:', joinErr);
}
}
await invalidatePolicyRulesCache(c.env.CACHE).catch(() => {});
await logAdminAction(c, { action: 'policy_list.subscribe', target: roomId });
return c.json({
success: true,
room_id: roomId,
subscriber_user_id: subscriber,
note: isRemoteRoom
? 'Joining in the background; invite-only lists require an invite for the subscriber user first.'
: 'Subscribed; rules are enforced within the cache TTL.',
});
});
// DELETE /admin/api/policy-lists/:roomId - Unsubscribe (rules stop
// applying; the subscriber's membership is left alone — it is harmless
// and leaving remote rooms requires a federated leave event).
app.delete('/admin/api/policy-lists/:roomId', requireAuth(), requireAdmin, async (c) => {
const db = c.env.DB;
const roomId = c.req.param('roomId');
const result = await db.prepare(
`UPDATE policy_list_subscriptions SET enabled = 0 WHERE room_id = ?`
).bind(roomId).run();
if ((result.meta?.changes ?? 0) === 0) {
return Errors.notFound('Subscription not found').toResponse();
}
await invalidatePolicyRulesCache(c.env.CACHE).catch(() => {});
await logAdminAction(c, { action: 'policy_list.unsubscribe', target: roomId });
return c.json({ success: true });
});
// GET /_matrix/client/v1/admin/suspend/:userId - Suspension status
app.get('/_matrix/client/v1/admin/suspend/:userId', requireAuth(), requireAdmin, async (c) => {
const userId = decodeURIComponent(c.req.param('userId'));
const target = await moderationTarget(c, userId, { forWrite: false });
if ('error' in target) return target.error;
return c.json({ suspended: target.row.suspended === 1 });
});
// PUT /_matrix/client/v1/admin/suspend/:userId - Set suspension status
app.put('/_matrix/client/v1/admin/suspend/:userId', requireAuth(), requireAdmin, async (c) => {
const userId = decodeURIComponent(c.req.param('userId'));
let body: { suspended?: boolean };
try {
body = await c.req.json();
} catch {
return Errors.badJson().toResponse();
}
if (typeof body.suspended !== 'boolean') {
return Errors.missingParam('suspended').toResponse();
}
const target = await moderationTarget(c, userId, { forWrite: true });
if ('error' in target) return target.error;
await c.env.DB.prepare(
`UPDATE users SET suspended = ?, updated_at = ? WHERE user_id = ?`
).bind(body.suspended ? 1 : 0, Date.now(), userId).run();
await logAdminAction(c, {
action: 'user.suspend',
target: userId,
details: { suspended: body.suspended },
});
return c.json({ suspended: body.suspended });
});
// GET /admin/api/rooms - List all rooms
app.get('/admin/api/rooms', requireAuth(), requireAdmin, async (c) => {
const db = c.env.DB;
const limit = Math.max(1, Math.min(parseInt(c.req.query('limit') || '50', 10) || 50, 100));
const offset = Math.max(0, parseInt(c.req.query('offset') || '0', 10) || 0);
const rooms = await db.prepare(`
SELECT r.room_id, r.room_version, r.is_public, r.creator_id, r.created_at,
(SELECT COUNT(*) FROM room_memberships WHERE room_id = r.room_id AND membership = 'join') as member_count,
(SELECT COUNT(*) FROM events WHERE room_id = r.room_id) as event_count
FROM rooms r
ORDER BY r.created_at DESC
LIMIT ? OFFSET ?
`).bind(limit, offset).all();
// Get room names
const roomsWithNames = await Promise.all(rooms.results.map(async (room: any) => {
const nameEvent = await db.prepare(`
SELECT e.content FROM room_state rs
JOIN events e ON rs.event_id = e.event_id
WHERE rs.room_id = ? AND rs.event_type = 'm.room.name'
`).bind(room.room_id).first<{ content: string }>();
return {
...room,
name: nameEvent ? JSON.parse(nameEvent.content).name : null,
};
}));
const total = await db.prepare('SELECT COUNT(*) as count FROM rooms').first<{ count: number }>();
return c.json({
rooms: roomsWithNames,
total: total?.count || 0,
limit,
offset,
});
});
// GET /admin/api/rooms/:roomId - Get room details
app.get('/admin/api/rooms/:roomId', requireAuth(), requireAdmin, async (c) => {
const roomId = decodeURIComponent(c.req.param('roomId'));
const db = c.env.DB;
const room = await db.prepare(`
SELECT room_id, room_version, is_public, creator_id, created_at
FROM rooms WHERE room_id = ?
`).bind(roomId).first();
if (!room) {
return Errors.notFound('Room not found').toResponse();
}
// Get room state
const state = await db.prepare(`
SELECT e.event_type, e.state_key, e.content, e.sender, e.origin_server_ts
FROM room_state rs
JOIN events e ON rs.event_id = e.event_id
WHERE rs.room_id = ?
`).bind(roomId).all();
// Get members
const members = await db.prepare(`
SELECT user_id, membership, display_name, avatar_url
FROM room_memberships WHERE room_id = ?
`).bind(roomId).all();
// Get aliases
const aliases = await db.prepare(
'SELECT alias FROM room_aliases WHERE room_id = ?'
).bind(roomId).all();
// Parse state
const stateMap: Record<string, any> = {};
for (const s of state.results as any[]) {
stateMap[`${s.event_type}|${s.state_key}`] = {
type: s.event_type,
state_key: s.state_key,
content: JSON.parse(s.content),
sender: s.sender,
};
}
return c.json({
...room,
name: stateMap['m.room.name|']?.content?.name,
topic: stateMap['m.room.topic|']?.content?.topic,
avatar_url: stateMap['m.room.avatar|']?.content?.url,
join_rule: stateMap['m.room.join_rules|']?.content?.join_rule,
members: members.results,
member_count: members.results.length,
aliases: aliases.results.map((a: any) => a.alias),
state: state.results.map((s: any) => ({
...s,
content: JSON.parse(s.content),
})),
});
});
// DELETE /admin/api/rooms/:roomId - Delete room
app.delete('/admin/api/rooms/:roomId', requireAuth(), requireAdmin, async (c) => {
const roomId = decodeURIComponent(c.req.param('roomId'));
const db = c.env.DB;
// Delete in order (foreign key constraints)
await db.prepare('DELETE FROM room_aliases WHERE room_id = ?').bind(roomId).run();
await db.prepare('DELETE FROM room_memberships WHERE room_id = ?').bind(roomId).run();
await db.prepare('DELETE FROM room_state WHERE room_id = ?').bind(roomId).run();
await db.prepare('DELETE FROM events WHERE room_id = ?').bind(roomId).run();
await db.prepare('DELETE FROM rooms WHERE room_id = ?').bind(roomId).run();
// Invalidate stats cache
await invalidateStatsCache(c.env);
await logAdminAction(c, { action: 'room.delete', target: roomId });
return c.json({ success: true });
});
// GET /admin/api/federation/status - Get federation status
app.get('/admin/api/federation/status', requireAuth(), requireAdmin, async (c) => {
const db = c.env.DB;
const serverName = c.env.SERVER_NAME;
// Get known servers count
const serversCount = await db.prepare('SELECT COUNT(*) as count FROM servers').first<{ count: number }>();
// Get signing key info
let signingKeyId = null;
try {
const keyData = await c.env.CACHE.get('server_signing_key');
if (keyData) {
const parsed = JSON.parse(keyData);
signingKeyId = parsed.keyId || `ed25519:${serverName.split('.')[0]}`;
}
} catch (e) {
// Key might not be cached
}
return c.json({
server_name: serverName,
federation_enabled: true,
signing_key_id: signingKeyId || `ed25519:a_${serverName.replace(/\./g, '_').substring(0, 4)}`,
known_servers_count: serversCount?.count || 0,
}, 200, { 'Cache-Control': 'no-store' });
});
// GET /admin/api/federation/test - Run federation self-tests
app.get('/admin/api/federation/test', requireAuth(), requireAdmin, async (c) => {
const serverName = c.env.SERVER_NAME;
const tests: Array<{ name: string; passed: boolean; message: string }> = [];
// Self-tests run in-process. A same-zone fetch() to a route-based URL is
// not permitted on Cloudflare and falls through to the website Worker, so
// the public fetch path cannot verify this server (it returned 404/Network
// error under path routing). Mirrors the key-check endpoint's approach.
// Test 1: Check .well-known/matrix/server
try {
const resp = await versions.request('http://localhost/.well-known/matrix/server', {}, c.env);
if (resp.ok) {
const data = await resp.json() as any;
tests.push({
name: '.well-known/matrix/server',
passed: true,
message: `Delegates to ${data['m.server'] || serverName}`,
});
} else {
tests.push({
name: '.well-known/matrix/server',
passed: false,
message: `HTTP ${resp.status}`,
});
}
} catch (e: any) {
tests.push({
name: '.well-known/matrix/server',
passed: false,
message: e.message || 'Failed to fetch',
});
}
// Test 2: Check /_matrix/key/v2/server
try {
const resp = await federation.request('http://localhost/_matrix/key/v2/server', {}, c.env);
if (resp.ok) {
const data = await resp.json() as any;
const hasSigningKeys = data.verify_keys && Object.keys(data.verify_keys).length > 0;
tests.push({
name: 'Server signing keys',
passed: hasSigningKeys,
message: hasSigningKeys ? `${Object.keys(data.verify_keys).length} key(s) published` : 'No signing keys found',
});
} else {
tests.push({
name: 'Server signing keys',
passed: false,
message: `HTTP ${resp.status}`,
});
}
} catch (e: any) {
tests.push({
name: 'Server signing keys',
passed: false,
message: e.message || 'Failed to fetch',
});
}
// Test 3: Check /_matrix/federation/v1/version
try {
const resp = await federation.request('http://localhost/_matrix/federation/v1/version', {}, c.env);
if (resp.ok) {
const data = await resp.json() as any;
tests.push({
name: 'Federation API',
passed: true,
message: `Server: ${data.server?.name || 'Unknown'} ${data.server?.version || ''}`,
});
} else {
tests.push({
name: 'Federation API',
passed: false,
message: `HTTP ${resp.status}`,
});
}
} catch (e: any) {
tests.push({
name: 'Federation API',
passed: false,
message: e.message || 'Failed to fetch',
});
}
// Test 4: Check .well-known/matrix/client
try {
const resp = await versions.request('http://localhost/.well-known/matrix/client', {}, c.env);
if (resp.ok) {
const data = await resp.json() as any;
tests.push({
name: '.well-known/matrix/client',
passed: true,
message: `Homeserver: ${data['m.homeserver']?.base_url || 'configured'}`,
});
} else {
tests.push({
name: '.well-known/matrix/client',
passed: false,
message: `HTTP ${resp.status}`,
});
}
} catch (e: any) {
tests.push({
name: '.well-known/matrix/client',
passed: false,
message: e.message || 'Failed to fetch',
});
}
const allPassed = tests.every(t => t.passed);
return c.json({
success: allPassed,
server_name: serverName,
tests,
}, 200, { 'Cache-Control': 'no-store' });
});
// GET /admin/api/federation/key-check - Tester-equivalent validation of our own
// server key response. Mirrors the gomatrixserverlib CheckKeys semantics the
// Matrix Federation Tester applies: every published verify_key must be a valid
// ed25519 key AND carry a matching signature, otherwise strict peers reject
// the whole response (AllEd25519ChecksOK = false).
// The check runs against our /_matrix/key/v2/server handler in-process, so
// regressions are caught before the public network path is involved.
app.get('/admin/api/federation/key-check', requireAuth(), requireAdmin, async (c) => {
const serverName = c.env.SERVER_NAME;
const res = await federation.request('http://localhost/_matrix/key/v2/server', {}, c.env);
if (!res.ok) {
return c.json({
AllChecksOK: false,
MatchingServerName: false,
FutureValidUntilTS: false,
HasEd25519Key: false,
AllEd25519ChecksOK: null,
Ed25519Checks: {},
error: `/_matrix/key/v2/server responded HTTP ${res.status}`,
});
}
const body = (await res.json()) as Record<string, unknown>;
const verifyKeys = (body.verify_keys ?? {}) as Record<string, { key?: string }>;
const ed25519Checks: Record<string, { ValidEd25519: boolean; MatchingSignature: boolean }> = {};
let hasEd25519Key = false;
let allEd25519ChecksOK = true;
for (const [keyId, keyData] of Object.entries(verifyKeys)) {
if (keyId.split(':', 2)[0] !== 'ed25519') continue;
hasEd25519Key = true;
let validEd25519 = false;
if (typeof keyData.key === 'string') {
try {
validEd25519 = base64UrlDecode(keyData.key).length === 32;
} catch {
validEd25519 = false;
}
}
const matchingSignature =
validEd25519 && typeof keyData.key === 'string'
? await verifySignature(body, serverName, keyId, keyData.key)
: false;
ed25519Checks[keyId] = { ValidEd25519: validEd25519, MatchingSignature: matchingSignature };
if (!matchingSignature) allEd25519ChecksOK = false;
}
const matchingServerName = body.server_name === serverName;
const futureValidUntilTS =
(typeof body.valid_until_ts === 'number' ? body.valid_until_ts : 0) > Date.now();
return c.json({
AllChecksOK: matchingServerName && futureValidUntilTS && hasEd25519Key && allEd25519ChecksOK,
MatchingServerName: matchingServerName,
FutureValidUntilTS: futureValidUntilTS,
HasEd25519Key: hasEd25519Key,
AllEd25519ChecksOK: hasEd25519Key ? allEd25519ChecksOK : null,
Ed25519Checks: ed25519Checks,
});
});
// GET /admin/api/federation/servers - List known federation servers
app.get('/admin/api/federation/servers', requireAuth(), requireAdmin, async (c) => {
const db = c.env.DB;
const servers = await db.prepare(`
SELECT server_name, valid_until_ts, last_successful_fetch, retry_count
FROM servers
ORDER BY last_successful_fetch DESC
`).all();
return c.json({ servers: servers.results });
});
// GET /admin/api/media - List media files
app.get('/admin/api/media', requireAuth(), requireAdmin, async (c) => {
const db = c.env.DB;
const limit = Math.max(1, Math.min(parseInt(c.req.query('limit') || '50', 10) || 50, 100));
const offset = Math.max(0, parseInt(c.req.query('offset') || '0', 10) || 0);
const media = await db.prepare(`
SELECT media_id, user_id, content_type, content_length, filename, created_at, quarantined
FROM media
ORDER BY created_at DESC
LIMIT ? OFFSET ?
`).bind(limit, offset).all();
const total = await db.prepare('SELECT COUNT(*) as count FROM media').first<{ count: number }>();
return c.json({
media: media.results,
total: total?.count || 0,
limit,
offset,
});
});