-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathfederation.ts
More file actions
3481 lines (3003 loc) · 108 KB
/
federation.ts
File metadata and controls
3481 lines (3003 loc) · 108 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
// Matrix Server-Server (Federation) API endpoints
import { Hono } from 'hono';
import type { AppEnv, PDU } from '../types';
import { Errors } from '../utils/errors';
import { generateSigningKeyPair, signJson, sha256, verifySignature, verifyContentHash } from '../utils/crypto';
import { requireFederationAuth } from '../middleware/federation-auth';
import {
getRemoteKeysWithNotarySignature,
verifyRemoteSignature,
type ServerKeyResponse,
} from '../services/federation-keys';
import { validateUrl } from '../utils/url-validator';
import { checkEventAuth } from '../services/event-auth';
import { getRoomState } from '../services/database';
import { resolveState } from '../services/state-resolution';
// Supported room versions (v1-v12 per Matrix Spec v1.17)
const SUPPORTED_ROOM_VERSIONS = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'];
const app = new Hono<AppEnv>();
// GET /_matrix/federation/v1/version - Server version info (unauthenticated)
// This must be defined BEFORE the auth middleware is applied
app.get('/_matrix/federation/v1/version', async (c) => {
return c.json({
server: {
name: 'matrix-worker',
version: c.env.SERVER_VERSION || '0.1.0',
},
});
});
// Apply federation authentication to all other federation v1 endpoints
// Key endpoints (/_matrix/key/*) remain unauthenticated as they are used to establish trust
// Version endpoint is also unauthenticated as it's used for initial contact
app.use('/_matrix/federation/v1/*', requireFederationAuth());
// GET /_matrix/key/v2/server - Get server signing keys
app.get('/_matrix/key/v2/server', async (c) => {
const serverName = c.env.SERVER_NAME;
// Get or create server signing keys (prefer v2 keys with proper Ed25519)
let keys = await c.env.DB.prepare(
`SELECT key_id, public_key, private_key_jwk, key_version, valid_from, valid_until
FROM server_keys WHERE is_current = 1 ORDER BY key_version DESC`
).all<{
key_id: string;
public_key: string;
private_key_jwk: string | null;
key_version: number | null;
valid_from: number;
valid_until: number | null;
}>();
// Check if we need to generate a new secure key
const hasSecureKey = keys.results.some((k) => k.key_version === 2 && k.private_key_jwk);
if (keys.results.length === 0 || !hasSecureKey) {
// Generate new secure signing key with proper Ed25519
const keyPair = await generateSigningKeyPair();
const validFrom = Date.now();
const validUntil = validFrom + 365 * 24 * 60 * 60 * 1000; // 1 year
// Mark old keys as not current
await c.env.DB.prepare(`UPDATE server_keys SET is_current = 0`).run();
// Insert new secure key
await c.env.DB.prepare(
`INSERT INTO server_keys (key_id, public_key, private_key, private_key_jwk, key_version, valid_from, valid_until, is_current)
VALUES (?, ?, ?, ?, 2, ?, ?, 1)`
)
.bind(
keyPair.keyId,
keyPair.publicKey,
JSON.stringify(keyPair.privateKeyJwk), // Store JWK as string in legacy column too
JSON.stringify(keyPair.privateKeyJwk),
validFrom,
validUntil
)
.run();
keys = {
results: [
{
key_id: keyPair.keyId,
public_key: keyPair.publicKey,
private_key_jwk: JSON.stringify(keyPair.privateKeyJwk),
key_version: 2,
valid_from: validFrom,
valid_until: validUntil,
},
],
success: true,
meta: {
duration: 0,
size_after: 0,
rows_read: 0,
rows_written: 0,
last_row_id: 0,
changed_db: false,
changes: 0,
},
};
}
const verifyKeys: Record<string, { key: string }> = {};
for (const key of keys.results) {
verifyKeys[key.key_id] = { key: key.public_key };
}
const validUntilTs = keys.results[0]?.valid_until || Date.now() + 365 * 24 * 60 * 60 * 1000;
const response = {
server_name: serverName,
valid_until_ts: validUntilTs,
verify_keys: verifyKeys,
old_verify_keys: {},
};
// Sign the response with the secure key
const currentKey = keys.results.find((k) => k.key_version === 2 && k.private_key_jwk);
if (currentKey && currentKey.private_key_jwk) {
const signed = await signJson(
response,
serverName,
currentKey.key_id,
JSON.parse(currentKey.private_key_jwk)
);
return c.json(signed);
}
return c.json(response);
});
// GET /_matrix/key/v2/server/:keyId - Get specific key
app.get('/_matrix/key/v2/server/:keyId', async (c) => {
const keyId = c.req.param('keyId');
const serverName = c.env.SERVER_NAME;
const key = await c.env.DB.prepare(
`SELECT key_id, public_key, valid_from, valid_until FROM server_keys WHERE key_id = ?`
).bind(keyId).first<{ key_id: string; public_key: string; valid_from: number; valid_until: number | null }>();
if (!key) {
return Errors.notFound('Key not found').toResponse();
}
const response = {
server_name: serverName,
valid_until_ts: key.valid_until || (Date.now() + 365 * 24 * 60 * 60 * 1000),
verify_keys: {
[key.key_id]: { key: key.public_key },
},
old_verify_keys: {},
};
return c.json(response);
});
// Helper function to get our server's notary signing key
async function getNotarySigningKey(db: D1Database): Promise<{
keyId: string;
privateKeyJwk: JsonWebKey;
} | null> {
const key = await db.prepare(
`SELECT key_id, private_key_jwk FROM server_keys WHERE is_current = 1 AND key_version = 2`
).first<{ key_id: string; private_key_jwk: string | null }>();
if (!key || !key.private_key_jwk) {
return null;
}
return {
keyId: key.key_id,
privateKeyJwk: JSON.parse(key.private_key_jwk),
};
}
// Helper function to validate server name
function isValidServerName(serverName: string): boolean {
// Basic server name validation
// Server names should be hostname:port or just hostname
// Must not contain SSRF-vulnerable patterns
// Check for empty or too long
if (!serverName || serverName.length > 255) {
return false;
}
// Check using URL validation (construct a fake URL to validate the hostname)
const testUrl = `https://${serverName}/`;
const validation = validateUrl(testUrl);
return validation.valid;
}
// Maximum number of servers in a batch query
const MAX_BATCH_SERVERS = 100;
// POST /_matrix/key/v2/query - Batch query for server keys (notary endpoint)
app.post('/_matrix/key/v2/query', async (c) => {
let body: {
server_keys?: Record<string, Record<string, { minimum_valid_until_ts?: number }>>;
};
try {
body = await c.req.json();
} catch {
return Errors.badJson().toResponse();
}
const serverKeys = body.server_keys;
if (!serverKeys || typeof serverKeys !== 'object') {
return Errors.missingParam('server_keys').toResponse();
}
// Check batch size limit
const serverCount = Object.keys(serverKeys).length;
if (serverCount > MAX_BATCH_SERVERS) {
return c.json(
{
errcode: 'M_LIMIT_EXCEEDED',
error: `Too many servers in batch request (max ${MAX_BATCH_SERVERS})`,
},
400
);
}
// Get our notary signing key
const notaryKey = await getNotarySigningKey(c.env.DB);
if (!notaryKey) {
return c.json(
{
errcode: 'M_UNKNOWN',
error: 'Server signing key not configured',
},
500
);
}
const results: ServerKeyResponse[] = [];
// Process each server in the request
for (const [serverName, keyRequests] of Object.entries(serverKeys)) {
// Validate server name to prevent SSRF
if (!isValidServerName(serverName)) {
console.warn(`Invalid server name in key query: ${serverName}`);
continue;
}
// If querying our own server, return our keys directly
if (serverName === c.env.SERVER_NAME) {
const ownKeys = await c.env.DB.prepare(
`SELECT key_id, public_key, valid_until FROM server_keys WHERE is_current = 1`
).all<{ key_id: string; public_key: string; valid_until: number | null }>();
if (ownKeys.results.length > 0) {
const verifyKeys: Record<string, { key: string }> = {};
let maxValidUntil = 0;
for (const key of ownKeys.results) {
verifyKeys[key.key_id] = { key: key.public_key };
if (key.valid_until && key.valid_until > maxValidUntil) {
maxValidUntil = key.valid_until;
}
}
const ownResponse: ServerKeyResponse = {
server_name: serverName,
valid_until_ts: maxValidUntil || Date.now() + 365 * 24 * 60 * 60 * 1000,
verify_keys: verifyKeys,
old_verify_keys: {},
};
// Sign with our own key
const signed = (await signJson(
ownResponse,
c.env.SERVER_NAME,
notaryKey.keyId,
notaryKey.privateKeyJwk
)) as ServerKeyResponse;
results.push(signed);
}
continue;
}
// Process each key request for this server
for (const [keyId, keyRequest] of Object.entries(keyRequests)) {
const minimumValidUntilTs = keyRequest.minimum_valid_until_ts || 0;
// Fetch keys with notary signature
const keyResponses = await getRemoteKeysWithNotarySignature(
serverName,
keyId === '' ? null : keyId, // Empty key ID means all keys
minimumValidUntilTs,
c.env.DB,
c.env.CACHE,
c.env.SERVER_NAME,
notaryKey.keyId,
notaryKey.privateKeyJwk
);
results.push(...keyResponses);
}
}
return c.json({ server_keys: results });
});
// GET /_matrix/key/v2/query/:serverName - Query all keys for a server
app.get('/_matrix/key/v2/query/:serverName', async (c) => {
const serverName = c.req.param('serverName');
const minimumValidUntilTs = parseInt(c.req.query('minimum_valid_until_ts') || '0', 10);
// Validate server name to prevent SSRF
if (!isValidServerName(serverName)) {
return c.json(
{
errcode: 'M_INVALID_PARAM',
error: 'Invalid server name',
},
400
);
}
// Get our notary signing key
const notaryKey = await getNotarySigningKey(c.env.DB);
if (!notaryKey) {
return c.json(
{
errcode: 'M_UNKNOWN',
error: 'Server signing key not configured',
},
500
);
}
// If querying our own server, return our keys directly
if (serverName === c.env.SERVER_NAME) {
const ownKeys = await c.env.DB.prepare(
`SELECT key_id, public_key, valid_until FROM server_keys WHERE is_current = 1`
).all<{ key_id: string; public_key: string; valid_until: number | null }>();
if (ownKeys.results.length === 0) {
return Errors.notFound('No keys found').toResponse();
}
const verifyKeys: Record<string, { key: string }> = {};
let maxValidUntil = 0;
for (const key of ownKeys.results) {
verifyKeys[key.key_id] = { key: key.public_key };
if (key.valid_until && key.valid_until > maxValidUntil) {
maxValidUntil = key.valid_until;
}
}
const ownResponse: ServerKeyResponse = {
server_name: serverName,
valid_until_ts: maxValidUntil || Date.now() + 365 * 24 * 60 * 60 * 1000,
verify_keys: verifyKeys,
old_verify_keys: {},
};
// Sign with our own key
const signed = (await signJson(
ownResponse,
c.env.SERVER_NAME,
notaryKey.keyId,
notaryKey.privateKeyJwk
)) as ServerKeyResponse;
return c.json({ server_keys: [signed] });
}
// Fetch keys from remote server with notary signature
const keyResponses = await getRemoteKeysWithNotarySignature(
serverName,
null, // All keys
minimumValidUntilTs,
c.env.DB,
c.env.CACHE,
c.env.SERVER_NAME,
notaryKey.keyId,
notaryKey.privateKeyJwk
);
if (keyResponses.length === 0) {
return Errors.notFound('No keys found for server').toResponse();
}
return c.json({ server_keys: keyResponses });
});
// GET /_matrix/key/v2/query/:serverName/:keyId - Query specific key for a server
app.get('/_matrix/key/v2/query/:serverName/:keyId', async (c) => {
const serverName = c.req.param('serverName');
const keyId = c.req.param('keyId');
const minimumValidUntilTs = parseInt(c.req.query('minimum_valid_until_ts') || '0', 10);
// Validate server name to prevent SSRF
if (!isValidServerName(serverName)) {
return c.json(
{
errcode: 'M_INVALID_PARAM',
error: 'Invalid server name',
},
400
);
}
// Get our notary signing key
const notaryKey = await getNotarySigningKey(c.env.DB);
if (!notaryKey) {
return c.json(
{
errcode: 'M_UNKNOWN',
error: 'Server signing key not configured',
},
500
);
}
// If querying our own server, return the specific key
if (serverName === c.env.SERVER_NAME) {
const ownKey = await c.env.DB.prepare(
`SELECT key_id, public_key, valid_until FROM server_keys WHERE key_id = ?`
).bind(keyId).first<{ key_id: string; public_key: string; valid_until: number | null }>();
if (!ownKey) {
return Errors.notFound('Key not found').toResponse();
}
const ownResponse: ServerKeyResponse = {
server_name: serverName,
valid_until_ts: ownKey.valid_until || Date.now() + 365 * 24 * 60 * 60 * 1000,
verify_keys: {
[ownKey.key_id]: { key: ownKey.public_key },
},
old_verify_keys: {},
};
// Sign with our own key
const signed = (await signJson(
ownResponse,
c.env.SERVER_NAME,
notaryKey.keyId,
notaryKey.privateKeyJwk
)) as ServerKeyResponse;
return c.json({ server_keys: [signed] });
}
// Fetch specific key from remote server with notary signature
const keyResponses = await getRemoteKeysWithNotarySignature(
serverName,
keyId,
minimumValidUntilTs,
c.env.DB,
c.env.CACHE,
c.env.SERVER_NAME,
notaryKey.keyId,
notaryKey.privateKeyJwk
);
if (keyResponses.length === 0) {
return Errors.notFound('Key not found').toResponse();
}
return c.json({ server_keys: keyResponses });
});
// PUT /_matrix/federation/v1/send/:txnId - Receive events from remote server
// This endpoint is now protected by requireFederationAuth middleware
app.put('/_matrix/federation/v1/send/:txnId', async (c) => {
const txnId = c.req.param('txnId');
// Origin is now authenticated via the federation auth middleware
const origin = c.get('federationOrigin' as any) as string | undefined;
if (!origin) {
return Errors.unauthorized('Federation authentication required').toResponse();
}
// Check for duplicate transaction (idempotency)
const existingTxn = await c.env.DB.prepare(
`SELECT response FROM federation_transactions WHERE origin = ? AND txn_id = ?`
).bind(origin, txnId).first<{ response: string | null }>();
if (existingTxn?.response) {
// Return cached response for duplicate transaction
return c.json(JSON.parse(existingTxn.response));
}
let body: any;
try {
body = await c.req.json();
} catch {
return Errors.badJson().toResponse();
}
const { pdus, edus } = body;
const pduResults: Record<string, any> = {};
// Process incoming PDUs (Persistent Data Units - events)
for (const pdu of pdus || []) {
try {
const eventId = pdu.event_id;
const roomId = pdu.room_id;
// Check if we've already processed this PDU
const existingPdu = await c.env.DB.prepare(
`SELECT accepted, rejection_reason FROM processed_pdus WHERE event_id = ?`
).bind(eventId).first<{ accepted: number; rejection_reason: string | null }>();
if (existingPdu) {
// Already processed
if (existingPdu.accepted) {
pduResults[eventId] = {};
} else {
pduResults[eventId] = {
error: existingPdu.rejection_reason || 'Previously rejected',
};
}
continue;
}
// Validate basic PDU structure
if (!eventId || !roomId || !pdu.sender || !pdu.type || !pdu.content) {
pduResults[eventId || 'unknown'] = {
error: 'Invalid PDU structure',
};
continue;
}
// Get the origin server from the sender
const pduOrigin = (pdu.sender as string).split(':')[1];
if (!pduOrigin) {
pduResults[eventId] = { error: 'Invalid sender format' };
continue;
}
// Verify PDU signatures
if (pdu.signatures) {
let signatureValid = false;
const signatories = Object.keys(pdu.signatures);
for (const signatory of signatories) {
const keyIds = Object.keys(pdu.signatures[signatory]);
for (const keyId of keyIds) {
try {
const isValid = await verifyRemoteSignature(
pdu,
signatory,
keyId,
c.env.DB,
c.env.CACHE
);
if (isValid) {
signatureValid = true;
break;
}
} catch (e) {
console.warn(`Signature verification failed for ${signatory}:${keyId}:`, e);
}
}
if (signatureValid) break;
}
if (!signatureValid && pduOrigin !== origin) {
// PDU from third party without valid signature
pduResults[eventId] = { error: 'Invalid signature' };
await c.env.DB.prepare(
`INSERT OR REPLACE INTO processed_pdus (event_id, origin, room_id, processed_at, accepted, rejection_reason)
VALUES (?, ?, ?, ?, 0, ?)`
).bind(eventId, pduOrigin, roomId, Date.now(), 'Invalid signature').run();
continue;
}
}
// Verify content hash if present
if (pdu.hashes?.sha256) {
try {
const hashValid = await verifyContentHash(pdu as Record<string, unknown>, pdu.hashes.sha256);
if (!hashValid) {
pduResults[eventId] = { error: 'Content hash mismatch' };
await c.env.DB.prepare(
`INSERT OR REPLACE INTO processed_pdus (event_id, origin, room_id, processed_at, accepted, rejection_reason)
VALUES (?, ?, ?, ?, 0, ?)`
).bind(eventId, pduOrigin, roomId, Date.now(), 'Content hash mismatch').run();
continue;
}
} catch (hashErr) {
console.warn(`[federation] Content hash check failed for ${eventId}:`, hashErr);
}
}
// Check if the room exists locally
const room = await c.env.DB.prepare(
`SELECT room_id, room_version FROM rooms WHERE room_id = ?`
).bind(roomId).first<{ room_id: string; room_version: string }>();
// Run event authorization check if we have room state
if (room) {
try {
const roomState = await getRoomState(c.env.DB, roomId);
const authResult = checkEventAuth(pdu as PDU, roomState, room.room_version);
if (!authResult.allowed) {
pduResults[eventId] = { error: authResult.error || 'Event authorization failed' };
await c.env.DB.prepare(
`INSERT OR REPLACE INTO processed_pdus (event_id, origin, room_id, processed_at, accepted, rejection_reason)
VALUES (?, ?, ?, ?, 0, ?)`
).bind(eventId, pduOrigin, roomId, Date.now(), authResult.error || 'Auth failed').run();
continue;
}
} catch (authErr) {
console.warn(`[federation] Auth check failed for ${eventId}, accepting anyway:`, authErr);
}
}
// Accept the PDU
pduResults[eventId] = {};
// Record that we processed this PDU
await c.env.DB.prepare(
`INSERT OR REPLACE INTO processed_pdus (event_id, origin, room_id, processed_at, accepted, rejection_reason)
VALUES (?, ?, ?, ?, 1, NULL)`
).bind(eventId, pduOrigin, roomId, Date.now()).run();
// If room exists, store the event
if (room) {
try {
await c.env.DB.prepare(
`INSERT OR IGNORE INTO events
(event_id, room_id, sender, event_type, state_key, content, origin_server_ts, depth, auth_events, prev_events, hashes, signatures)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
).bind(
eventId,
roomId,
pdu.sender,
pdu.type,
pdu.state_key ?? null,
JSON.stringify(pdu.content),
pdu.origin_server_ts,
pdu.depth || 0,
JSON.stringify(pdu.auth_events || []),
JSON.stringify(pdu.prev_events || []),
pdu.hashes ? JSON.stringify(pdu.hashes) : null,
pdu.signatures ? JSON.stringify(pdu.signatures) : null
).run();
// Update room state
if (pdu.state_key !== undefined) {
// If the PDU has multiple prev_events, we may need state resolution
const prevEvents = pdu.prev_events || [];
if (prevEvents.length > 1 && room) {
try {
// Fetch current room state and resolve with new event
const currentState = await getRoomState(c.env.DB, roomId);
const newEvent: PDU = {
event_id: eventId,
room_id: roomId,
sender: pdu.sender,
type: pdu.type,
state_key: pdu.state_key,
content: pdu.content,
origin_server_ts: pdu.origin_server_ts,
depth: pdu.depth || 0,
auth_events: pdu.auth_events || [],
prev_events: prevEvents,
};
const resolved = resolveState(room.room_version, [currentState, [newEvent]]);
// Apply resolved state
for (const stateEvent of resolved) {
if (stateEvent.state_key !== undefined) {
await c.env.DB.prepare(
`INSERT OR REPLACE INTO room_state (room_id, event_type, state_key, event_id)
VALUES (?, ?, ?, ?)`
).bind(roomId, stateEvent.type, stateEvent.state_key, stateEvent.event_id).run();
}
}
} catch (resolveErr) {
console.warn(`[federation] State resolution failed for ${eventId}, falling back:`, resolveErr);
await c.env.DB.prepare(
`INSERT OR REPLACE INTO room_state (room_id, event_type, state_key, event_id)
VALUES (?, ?, ?, ?)`
).bind(roomId, pdu.type, pdu.state_key, eventId).run();
}
} else {
await c.env.DB.prepare(
`INSERT OR REPLACE INTO room_state (room_id, event_type, state_key, event_id)
VALUES (?, ?, ?, ?)`
).bind(roomId, pdu.type, pdu.state_key, eventId).run();
}
}
} catch (e) {
console.error(`Failed to store event ${eventId}:`, e);
}
}
} catch (e: any) {
const eventId = pdu?.event_id || 'unknown';
pduResults[eventId] = {
error: e.message || 'Unknown error',
};
// Record rejection
if (pdu?.event_id && pdu?.room_id) {
const pduOrigin = (pdu.sender as string)?.split(':')[1] || origin;
await c.env.DB.prepare(
`INSERT OR REPLACE INTO processed_pdus (event_id, origin, room_id, processed_at, accepted, rejection_reason)
VALUES (?, ?, ?, ?, 0, ?)`
).bind(pdu.event_id, pduOrigin, pdu.room_id, Date.now(), e.message || 'Unknown error').run();
}
}
}
// Process EDUs (Ephemeral Data Units)
for (const edu of edus || []) {
try {
const eduType = edu.edu_type;
const content = edu.content;
switch (eduType) {
case 'm.typing':
// Handle typing notification
// In a full implementation, this would notify connected clients
break;
case 'm.presence': {
// Process inbound presence EDUs from federated servers
const presencePush = content?.push as Array<{
user_id: string;
presence: string;
status_msg?: string;
last_active_ago?: number;
currently_active?: boolean;
}> | undefined;
if (presencePush) {
for (const update of presencePush) {
if (update.user_id && update.presence) {
const now = Date.now();
const lastActive = update.last_active_ago
? now - update.last_active_ago
: now;
try {
await c.env.DB.prepare(`
INSERT INTO presence (user_id, presence, status_msg, last_active_ts, currently_active)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT (user_id) DO UPDATE SET
presence = excluded.presence,
status_msg = excluded.status_msg,
last_active_ts = excluded.last_active_ts,
currently_active = excluded.currently_active
`).bind(
update.user_id,
update.presence,
update.status_msg || null,
lastActive,
update.currently_active ? 1 : 0
).run();
} catch (presErr) {
console.warn(`[federation] Failed to update presence for ${update.user_id}:`, presErr);
}
}
}
}
break;
}
case 'm.device_list_update': {
// Process inbound device list update EDUs from federated servers
const deviceUserId = content?.user_id as string;
const deviceId = content?.device_id as string;
const streamId = (content?.stream_id as number) || 0;
const deviceKeys = content?.keys;
const deviceDisplayName = content?.device_display_name as string | undefined;
const deleted = content?.deleted as boolean;
if (deviceUserId && deviceId) {
try {
if (deleted) {
await c.env.DB.prepare(
`DELETE FROM remote_device_lists WHERE user_id = ? AND device_id = ?`
).bind(deviceUserId, deviceId).run();
} else {
await c.env.DB.prepare(`
INSERT INTO remote_device_lists (user_id, device_id, device_display_name, keys, stream_id, updated_at)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT (user_id, device_id) DO UPDATE SET
device_display_name = excluded.device_display_name,
keys = excluded.keys,
stream_id = excluded.stream_id,
updated_at = excluded.updated_at
`).bind(
deviceUserId,
deviceId,
deviceDisplayName || null,
deviceKeys ? JSON.stringify(deviceKeys) : null,
streamId,
Date.now()
).run();
}
// Update stream tracking
await c.env.DB.prepare(`
INSERT INTO remote_device_list_streams (user_id, stream_id, updated_at)
VALUES (?, ?, ?)
ON CONFLICT (user_id) DO UPDATE SET
stream_id = MAX(remote_device_list_streams.stream_id, excluded.stream_id),
updated_at = excluded.updated_at
`).bind(deviceUserId, streamId, Date.now()).run();
} catch (devErr) {
console.warn(`[federation] Failed to update device list for ${deviceUserId}:`, devErr);
}
}
break;
}
case 'm.receipt':
// Handle read receipts
break;
case 'm.direct_to_device':
// Handle to-device messages
break;
case 'm.signing_key_update':
// Handle cross-signing key updates
break;
default:
// Unknown EDU type - log and continue
console.log(`Received unknown EDU type: ${eduType}`);
}
// Store EDU for record keeping
const eduId = await sha256(`${origin}:${eduType}:${Date.now()}:${Math.random()}`);
await c.env.DB.prepare(
`INSERT OR REPLACE INTO processed_edus (edu_id, edu_type, origin, processed_at, content)
VALUES (?, ?, ?, ?, ?)`
).bind(eduId, eduType, origin, Date.now(), JSON.stringify(content)).run();
} catch (e) {
console.error(`Failed to process EDU:`, e);
}
}
const response = { pdus: pduResults };
// Store transaction for idempotency
await c.env.DB.prepare(
`INSERT OR REPLACE INTO federation_transactions (txn_id, origin, received_at, response)
VALUES (?, ?, ?, ?)`
).bind(txnId, origin, Date.now(), JSON.stringify(response)).run();
return c.json(response);
});
// GET /_matrix/federation/v1/event/:eventId - Get a single event
app.get('/_matrix/federation/v1/event/:eventId', async (c) => {
const eventId = c.req.param('eventId');
const event = await c.env.DB.prepare(
`SELECT event_id, room_id, sender, event_type, state_key, content,
origin_server_ts, depth, auth_events, prev_events, hashes, signatures
FROM events WHERE event_id = ?`
).bind(eventId).first<{
event_id: string;
room_id: string;
sender: string;
event_type: string;
state_key: string | null;
content: string;
origin_server_ts: number;
depth: number;
auth_events: string;
prev_events: string;
hashes: string | null;
signatures: string | null;
}>();
if (!event) {
return Errors.notFound('Event not found').toResponse();
}
const pdu: PDU = {
event_id: event.event_id,
room_id: event.room_id,
sender: event.sender,
type: event.event_type,
state_key: event.state_key ?? undefined,
content: JSON.parse(event.content),
origin_server_ts: event.origin_server_ts,
depth: event.depth,
auth_events: JSON.parse(event.auth_events),
prev_events: JSON.parse(event.prev_events),
hashes: event.hashes ? JSON.parse(event.hashes) : undefined,
signatures: event.signatures ? JSON.parse(event.signatures) : undefined,
};
return c.json({
origin: c.env.SERVER_NAME,
origin_server_ts: Date.now(),
pdus: [pdu],
});
});
// GET /_matrix/federation/v1/state/:roomId - Get room state
app.get('/_matrix/federation/v1/state/:roomId', async (c) => {
const roomId = c.req.param('roomId');
// Note: eventId could be used to get state at a specific point in time
void c.req.query('event_id');
// Get current room state
const stateEvents = await c.env.DB.prepare(
`SELECT e.event_id, e.room_id, e.sender, e.event_type, e.state_key, e.content,
e.origin_server_ts, e.depth, e.auth_events, e.prev_events
FROM room_state rs
JOIN events e ON rs.event_id = e.event_id
WHERE rs.room_id = ?`
).bind(roomId).all<{
event_id: string;
room_id: string;
sender: string;
event_type: string;
state_key: string | null;
content: string;
origin_server_ts: number;
depth: number;
auth_events: string;
prev_events: string;
}>();
const pdus = stateEvents.results.map(e => ({
event_id: e.event_id,
room_id: e.room_id,
sender: e.sender,
type: e.event_type,
state_key: e.state_key ?? '',
content: JSON.parse(e.content),
origin_server_ts: e.origin_server_ts,
depth: e.depth,
auth_events: JSON.parse(e.auth_events),
prev_events: JSON.parse(e.prev_events),
}));
// Get auth chain
const authEventIds = new Set<string>();
for (const pdu of pdus) {
for (const authId of pdu.auth_events) {
authEventIds.add(authId);
}
}
const authChain: any[] = [];
for (const authId of authEventIds) {
const authEvent = await c.env.DB.prepare(
`SELECT event_id, room_id, sender, event_type, state_key, content,
origin_server_ts, depth, auth_events, prev_events
FROM events WHERE event_id = ?`
).bind(authId).first();
if (authEvent) {
authChain.push({
...authEvent,
type: (authEvent as any).event_type,
content: JSON.parse((authEvent as any).content),
auth_events: JSON.parse((authEvent as any).auth_events),
prev_events: JSON.parse((authEvent as any).prev_events),
});
}
}
return c.json({
origin: c.env.SERVER_NAME,
origin_server_ts: Date.now(),
pdus,
auth_chain: authChain,
});
});
// GET /_matrix/federation/v1/state_ids/:roomId - Get room state event IDs only
app.get('/_matrix/federation/v1/state_ids/:roomId', async (c) => {
const roomId = c.req.param('roomId');
const eventId = c.req.query('event_id');
// Verify room exists
const room = await c.env.DB.prepare(
`SELECT room_id FROM rooms WHERE room_id = ?`
).bind(roomId).first<{ room_id: string }>();
if (!room) {
return Errors.notFound('Room not found').toResponse();
}
// Get state event IDs
let stateEventIds: string[];
let authChainIds: string[];
if (eventId) {