forked from nkuntz1934/matrix-workers
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
428 lines (363 loc) · 12.7 KB
/
index.ts
File metadata and controls
428 lines (363 loc) · 12.7 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
// Matrix Homeserver on Cloudflare Workers
// Main entry point
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { logger } from 'hono/logger';
import type { AppEnv } from './types';
// Import API routes
import versions from './api/versions';
import login from './api/login';
import rooms from './api/rooms';
import sync from './api/sync';
import slidingSync from './api/sliding-sync';
import profile from './api/profile';
import media from './api/media';
import voip from './api/voip';
import keys from './api/keys';
import federation from './api/federation';
import admin from './api/admin';
import keyBackups from './api/key-backups';
import toDevice from './api/to-device';
import push from './api/push';
import accountData from './api/account-data';
import typing from './api/typing';
import receipts from './api/receipts';
import tags from './api/tags';
import devices from './api/devices';
import presence from './api/presence';
import aliases from './api/aliases';
import relations from './api/relations';
import spaces from './api/spaces';
import account from './api/account';
import search from './api/search';
import serverNotices from './api/server-notices';
import report from './api/report';
import calls from './api/calls';
import rtc from './api/rtc';
import appservice from './api/appservice';
import identity from './api/identity';
// import qrLogin from './api/qr-login'; // QR feature commented out - requires MSC4108/OIDC for Element X
import oidcAuth from './api/oidc-auth';
import oauth from './api/oauth';
import { adminDashboardHtml } from './admin/dashboard';
import { rateLimitMiddleware } from './middleware/rate-limit';
import { requireAuth } from './middleware/auth';
import { analyticsMiddleware } from './middleware/analytics';
// Import Durable Objects
export { RoomDurableObject, SyncDurableObject, FederationDurableObject, CallRoomDurableObject, AdminDurableObject, UserKeysDurableObject, PushDurableObject, RateLimitDurableObject } from './durable-objects';
// Import Workflows
export { RoomJoinWorkflow, PushNotificationWorkflow, FederationCatchupWorkflow, MediaCleanupWorkflow, StateCompactionWorkflow } from './workflows';
// Create the main app
const app = new Hono<AppEnv>();
// CORS for Matrix clients - MUST BE FIRST to ensure headers are always sent
// (even on error responses from rate limiter or other middleware)
app.use('*', cors({
origin: '*',
allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowHeaders: ['Content-Type', 'Authorization', 'X-Matrix-Origin'],
exposeHeaders: ['Content-Type', 'Content-Length'],
maxAge: 86400,
}));
// Global middleware
app.use('*', logger());
app.use('*', analyticsMiddleware());
// Rate limiting for Matrix API endpoints
app.use('/_matrix/*', rateLimitMiddleware);
// Health check
app.get('/health', (c) => c.json({ status: 'ok', server: 'matrix-worker' }));
// Admin dashboard - serve HTML with security headers
app.get('/admin', (c) => {
const html = adminDashboardHtml(c.env.SERVER_NAME);
return c.html(html, 200, {
// Content-Security-Policy for XSS protection
// 'unsafe-inline' is needed for the inline scripts/styles in the dashboard
// This could be improved by moving scripts to external files with nonces
'Content-Security-Policy':
"default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self'; frame-ancestors 'none'",
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'Referrer-Policy': 'strict-origin-when-cross-origin',
});
});
app.get('/admin/', (c) => {
const html = adminDashboardHtml(c.env.SERVER_NAME);
return c.html(html, 200, {
'Content-Security-Policy':
"default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self'; frame-ancestors 'none'",
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'Referrer-Policy': 'strict-origin-when-cross-origin',
});
});
// Admin API routes
app.route('/', admin);
// QR code login landing page - commented out, requires MSC4108/OIDC for Element X
// app.route('/', qrLogin);
// OIDC/SSO authentication
app.route('/', oidcAuth);
// OAuth 2.0 provider endpoints
app.route('/', oauth);
// Matrix version discovery
app.route('/', versions);
// Client-Server API
app.route('/', login);
app.route('/', rooms);
app.route('/', sync);
app.route('/', slidingSync);
app.route('/', profile);
app.route('/', media);
app.route('/', voip);
app.route('/', keys);
app.route('/', keyBackups);
app.route('/', toDevice);
app.route('/', push);
app.route('/', accountData);
app.route('/', typing);
app.route('/', receipts);
app.route('/', tags);
app.route('/', devices);
app.route('/', presence);
app.route('/', aliases);
app.route('/', relations);
app.route('/', spaces);
app.route('/', account);
app.route('/', serverNotices);
app.route('/', report);
// Cloudflare Calls-based video calling API
app.route('/', calls);
// MatrixRTC (LiveKit) JWT service for Element X calls
app.route('/', rtc);
// Application Service API
app.route('/', appservice);
// Identity Service API
app.route('/', identity);
// Server-Server (Federation) API
app.route('/', federation);
// Capabilities endpoint
app.get('/_matrix/client/v3/capabilities', (c) => {
return c.json({
capabilities: {
'm.change_password': {
enabled: true,
},
'm.room_versions': {
default: '10',
available: {
'1': 'stable',
'2': 'stable',
'3': 'stable',
'4': 'stable',
'5': 'stable',
'6': 'stable',
'7': 'stable',
'8': 'stable',
'9': 'stable',
'10': 'stable',
'11': 'stable',
'12': 'stable',
},
},
'm.set_displayname': {
enabled: true,
},
'm.set_avatar_url': {
enabled: true,
},
'm.3pid_changes': {
enabled: true,
},
},
});
});
// Push rules now handled by push.ts
// Filter endpoints - persist filters in KV for sync optimization
app.post('/_matrix/client/v3/user/:userId/filter', requireAuth(), async (c) => {
const userId = c.get('userId');
const requestedUserId = c.req.param('userId');
// Users can only create filters for themselves
if (userId !== requestedUserId) {
return c.json({ errcode: 'M_FORBIDDEN', error: 'Cannot create filters for other users' }, 403);
}
let filter: Record<string, unknown>;
try {
filter = await c.req.json();
} catch {
return c.json({ errcode: 'M_BAD_JSON', error: 'Invalid JSON' }, 400);
}
// Generate filter ID and store in KV
const filterId = crypto.randomUUID().split('-')[0];
await c.env.CACHE.put(
`filter:${userId}:${filterId}`,
JSON.stringify(filter),
{ expirationTtl: 30 * 24 * 60 * 60 } // 30 days TTL
);
return c.json({ filter_id: filterId });
});
app.get('/_matrix/client/v3/user/:userId/filter/:filterId', requireAuth(), async (c) => {
const userId = c.get('userId');
const requestedUserId = c.req.param('userId');
const filterId = c.req.param('filterId');
// Users can only read their own filters
if (userId !== requestedUserId) {
return c.json({ errcode: 'M_FORBIDDEN', error: 'Cannot read filters for other users' }, 403);
}
const filterJson = await c.env.CACHE.get(`filter:${userId}:${filterId}`);
if (!filterJson) {
// Return empty filter if not found (per spec, unknown filter IDs should return empty)
return c.json({});
}
try {
const filter = JSON.parse(filterJson);
return c.json(filter);
} catch {
return c.json({});
}
});
// Account data endpoints now handled by account-data.ts
// Presence endpoints now handled by presence.ts
// Search endpoint - now handled by search.ts
app.route('/', search);
// Typing notifications now handled by typing.ts
// Read receipts now handled by receipts.ts
// Device management now handled by devices.ts
// Public rooms directory
app.get('/_matrix/client/v3/publicRooms', async (c) => {
const db = c.env.DB;
const rooms = await db.prepare(
`SELECT r.room_id, r.room_version
FROM rooms r
WHERE r.is_public = 1
LIMIT 100`
).all<{ room_id: string; room_version: string }>();
const publicRooms: any[] = [];
for (const room of rooms.results) {
// Get room name and topic from state
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 }>();
const topicEvent = 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.topic'`
).bind(room.room_id).first<{ content: string }>();
// Get member count
const memberCount = await db.prepare(
`SELECT COUNT(*) as count FROM room_memberships WHERE room_id = ? AND membership = 'join'`
).bind(room.room_id).first<{ count: number }>();
publicRooms.push({
room_id: room.room_id,
name: nameEvent ? JSON.parse(nameEvent.content).name : undefined,
topic: topicEvent ? JSON.parse(topicEvent.content).topic : undefined,
num_joined_members: memberCount?.count || 0,
world_readable: false,
guest_can_join: false,
});
}
return c.json({
chunk: publicRooms,
total_room_count_estimate: publicRooms.length,
});
});
app.post('/_matrix/client/v3/publicRooms', async (c) => {
// Same as GET but with search/filter support
return c.json({
chunk: [],
total_room_count_estimate: 0,
});
});
// User directory search (requires authentication per Matrix spec)
app.post('/_matrix/client/v3/user_directory/search', requireAuth(), async (c) => {
const db = c.env.DB;
const requestingUserId = c.get('userId');
let body: { search_term: string; limit?: number };
try {
body = await c.req.json();
} catch {
return c.json({ errcode: 'M_BAD_JSON', error: 'Invalid JSON' }, 400);
}
const searchTerm = body.search_term || '';
const limit = Math.min(body.limit || 10, 50);
console.log('[user_directory] Search request:', {
requestingUserId,
searchTerm,
limit,
userAgent: c.req.header('User-Agent'),
});
if (!searchTerm) {
return c.json({ results: [], limited: false });
}
// Search for users using FTS5 for ranked full-text search
const ftsSearchTerm = searchTerm.replace(/['"*()]/g, ' ').trim();
const results = await db.prepare(`
SELECT u.user_id, u.display_name, u.avatar_url
FROM users_fts fts
JOIN users u ON fts.user_id = u.user_id
WHERE users_fts MATCH ?
AND u.is_deactivated = 0
AND u.is_guest = 0
AND u.user_id != ?
ORDER BY bm25(users_fts)
LIMIT ?
`).bind(ftsSearchTerm, requestingUserId, limit + 1).all<{
user_id: string;
display_name: string | null;
avatar_url: string | null;
}>();
const limited = results.results.length > limit;
// Return explicit null values (not undefined/omitted) so Element X knows user exists
const users = results.results.slice(0, limit).map(u => ({
user_id: u.user_id,
display_name: u.display_name || null,
avatar_url: u.avatar_url || null,
}));
console.log('[user_directory] Search results:', {
searchTerm,
resultCount: users.length,
limited,
firstResult: users[0],
});
return c.json({ results: users, limited });
});
// Third-party protocols (stub - no bridges configured)
app.get('/_matrix/client/v3/thirdparty/protocols', async (c) => {
return c.json({});
});
// Dehydrated device (MSC3814 - stub)
app.get('/_matrix/client/unstable/org.matrix.msc3814.v1/dehydrated_device', async (c) => {
return c.json({
errcode: 'M_NOT_FOUND',
error: 'No dehydrated device found',
}, 404);
});
// OIDC auth metadata endpoints are now handled by oidc-auth.ts
// Legacy unstable endpoint for backwards compatibility
app.get('/_matrix/client/unstable/org.matrix.msc2965/auth_issuer', async (c) => {
// Redirect to the stable endpoint implementation
return c.redirect('/_matrix/client/v1/auth_metadata', 307);
});
app.get('/_matrix/client/unstable/org.matrix.msc2965/auth_metadata', async (c) => {
// Redirect to the stable endpoint implementation
return c.redirect('/_matrix/client/v1/auth_metadata', 307);
});
// Fallback for unknown endpoints
app.all('/_matrix/*', (c) => {
return c.json({
errcode: 'M_UNRECOGNIZED',
error: 'Unrecognized request',
}, 404);
});
// 404 handler
app.notFound((c) => {
return c.json({ error: 'Not found' }, 404);
});
// Error handler
app.onError((err, c) => {
console.error('Unhandled error:', err);
return c.json({
errcode: 'M_UNKNOWN',
error: 'An internal error occurred',
}, 500);
});
export default app;