Repository navigation
Expand file tree
/
Copy pathfederation.ts
More file actions
5611 lines (4989 loc) · 199 KB
/
Copy pathfederation.ts
File metadata and controls
5611 lines (4989 loc) · 199 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, Env, PDU } from '../types';
import { Errors } from '../utils/errors';
import { generateSigningKeyPair, signJson, sha256, verifySignature, verifyContentHash } from '../utils/crypto';
import { computeWireEventId, inboundWireEventIdCandidates, isMsc4291RoomVersion, redactEventForSigning, redactionOptionsForEvent, toWireEventObject, omitWireEventId } from '../utils/event-signing';
import { requireFederationAuth } from '../middleware/federation-auth';
import { federationOriginRateLimit } from '../middleware/rate-limit';
import {
federationPost,
fetchRemoteServerKeys,
getRemoteKeysWithNotarySignature,
getServerSigningKey,
type ServerKeyResponse,
} from '../services/federation-keys';
import { verifySignedThirdPartyInvite } from '../services/third-party-invite';
import { validateUrl } from '../utils/url-validator';
import { checkEventAuth } from '../services/event-auth';
import { getRoom, getRoomState, createRoom, getEvent, storeEvent, storeEventIdempotent, updateMembership, notifyUserSync, getInvitePermission } from '../services/database';
import { findServerAcl, isServerAllowedByAcl, isServerAllowedInRoom, serverNameFromId } from '../services/server-acl';
import { getRoomVersion } from '../services/room-versions';
import { performStateEvent } from './rooms';
import { MSC4583_ROOM_VERSION } from './msc4583';
import { evaluateRestrictedJoin, refreshRestrictedRoomState } from '../services/restricted-joins';
import { applyEventRedaction } from '../services/event-redaction';
import {
getActivePolicyRules,
isServerBannedByPolicy,
isUserBannedByPolicy,
} from '../services/moderation-policy';
import {
askPolicyServerSignature,
attachPolicySignature,
eventExemptFromPolicy,
getRoomPolicyServer,
signEventAsPolicyServer,
verifyPolicySignature,
} from '../services/policy-server';
// Spec (PUT /_matrix/federation/v1/send/{txnId}): every entry of the 200
// `pdus` map is either `{}` (accepted) or `{ error: <Matrix error object> }`.
// A bare reason string is not a valid Matrix error object, so all per-PDU
// failures go through this helper. Authorisation/policy denials use
// M_FORBIDDEN; malformed or unverifiable events stay M_UNKNOWN.
const pduError = (error: string, errcode: string = 'M_UNKNOWN') => ({ error: { errcode, error } });
// Spec module "Server ACLs" (MSC4436): denied servers get no room content
// from any federation surface. The transaction, make_join, send_join and
// invite paths enforce this at their auth points; this guard covers the
// read endpoints. Lookup failures fall open (read posture).
async function callerDeniedByRoomAcl(
c: { env: Env; get: (key: string) => unknown },
roomId: string
): Promise<boolean> {
const origin = c.get('federationOrigin') as string | undefined;
if (!origin || !roomId) return false;
try {
return !(await isServerAllowedInRoom(c.env.DB, roomId, origin));
} catch {
return false;
}
}
// Wire derivation rebuilds a whole room's IDs from stored rows. That is only
// sound for rooms WE created: a remote-created room's stored IDs are the
// residents' real IDs (their events can carry fields we never stored, e.g.
// pre-2023 `origin`), so re-deriving them produces phantom references no peer
// resolves. Callers that use deriveRoomWireEvents directly must gate here.
async function roomWireDerivationAllowed(env: Env, roomId: string): Promise<boolean> {
try {
const create = await env.DB.prepare(
`SELECT e.event_id, e.sender FROM room_state rs
JOIN events e ON rs.event_id = e.event_id
WHERE rs.room_id = ? AND rs.event_type = 'm.room.create'`
).bind(roomId).first<{ event_id: string; sender?: string }>();
if (!create) return false;
if (create.sender) return create.sender.endsWith(`:${env.SERVER_NAME}`);
// Some D1 wrappers return only the projected event_id; resolve the
// sender from the event row before deciding.
const eventRow = await env.DB.prepare(
`SELECT sender FROM events WHERE event_id = ?`
).bind(create.event_id).first<{ sender: string }>();
return Boolean(eventRow?.sender?.endsWith(`:${env.SERVER_NAME}`));
} catch {
return false;
}
}
// MSC4284: membership events (invites, joins) in policy-server rooms must
// carry a valid PS countersignature. Timeline events without one are
// soft-failed; membership is refused outright instead — soft-failing a
// join/invite would corrupt local membership views. A fresh signature is
// requested first (the PS key may have rotated between send and receipt).
// Resolution failures fall open: membership must not wedge on our bugs.
async function policySignatureMissing(
c: { env: Env; get: (key: string) => unknown },
event: Record<string, unknown>,
roomVersion: string
): Promise<boolean> {
try {
const roomId = typeof event.room_id === 'string' ? event.room_id : '';
if (!roomId) return false;
const config = await getRoomPolicyServer(c.env.DB, roomId);
if (!config || eventExemptFromPolicy(event)) return false;
if (await verifyPolicySignature(event, config.via, config.ed25519, roomVersion)) {
return false;
}
const asked = await askPolicyServerSignature(c.env, config, event);
if ('signature' in asked) {
const candidate = {
...((event.signatures as Record<string, unknown> | undefined) ?? {}),
};
attachPolicySignature(candidate, config.via, asked.signature);
if (
await verifyPolicySignature(
{ ...event, signatures: candidate },
config.via,
config.ed25519,
roomVersion
)
) {
// Redeemed: keep the fresh countersignature on the event.
event.signatures = candidate;
return false;
}
}
return true;
} catch (err) {
console.warn('[policy] membership countersignature check failed:', err);
return false;
}
}
import { recordKeyChange } from './keys';
import { ensurePresenceUserRow, recordPresenceChange } from './presence';
import { fanoutEventToAppServices } from '../services/appservice-fanout';
import { deliverInboundToDevice } from './to-device';
import { buildWireJoinState, deriveRoomWireEvents, wireForRoom } from '../services/event-wire';
import { checkAuthRules, verifyPdu, type VerifyKey } from '../services/federation-verify';
import { resolveState } from '../services/state-resolution';
// Supported room versions (v1-v12 per Matrix Spec v1.17) plus MSC4583's
// unstable room version.
const SUPPORTED_ROOM_VERSIONS = [
'1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', MSC4583_ROOM_VERSION,
];
// Error bodies for M_INCOMPATIBLE_ROOM_VERSION must advertise the stability
// of each supported version. Keep this in sync with the m.room_versions map
// published by /_matrix/client/v3/capabilities (src/index.ts).
function supportedRoomVersionsMap(): Record<string, 'stable' | 'unstable'> {
return Object.fromEntries(
SUPPORTED_ROOM_VERSIONS.map((version) => [
version,
version === MSC4583_ROOM_VERSION ? 'unstable' : 'stable',
])
);
}
// `ver` values are room version IDs (e.g. `10`). Also accept a leading `v`:
// peers commonly write `v10`, which cannot collide with any room version we
// support (the only non-numeric one is MSC4583's `dev.zirco.msc4583.v1`).
function offersRoomVersion(offered: string[] | undefined, version: string): boolean {
return Boolean(offered?.some((v) => v === version || v === `v${version}`));
}
// "Modern" room versions for the purpose of content-hash enforcement.
// Matrix room versions 3 and later require event integrity via hashes.sha256;
// versions 1 and 2 are legacy where hashes are optional.
// Issue 006.6 — see docs/issues/006-federation-event-validation-state-resolution.md
/** Exported for unit tests. */
export function isModernRoomVersion(version: string): boolean {
// Numeric room versions: anything >= 3 counts as modern. Non-numeric custom
// versions are treated as modern by default (fail-closed).
const n = parseInt(version, 10);
if (Number.isFinite(n)) return n >= 3;
return true;
}
/**
* Get the request body from either the federation auth middleware buffer
* (which already consumed it for signature verification) or from c.req.json()
* as a fallback for endpoints not behind federation auth.
*/
async function getFederationBody<T = any>(c: any): Promise<T> {
// The federation auth middleware stores the parsed body on the context
const buffered = c.get('federationBody');
if (buffered !== undefined) {
return buffered as T;
}
// Fallback: body wasn't consumed by middleware (e.g., unauthenticated endpoint)
return await c.req.json() as T;
}
const app = new Hono<AppEnv>();
// Resolve a remote server's signing keys through the same KV/D1/network key
// chain the rest of federation uses (verifyRemoteSignature -> fetchRemoteServerKeys).
// verifyPdu needs the raw verify keys so it can enforce that the PDU was
// signed by the sender's own server, not merely by *some* signatory.
async function resolvePduVerifyKeys(env: Env, serverName: string): Promise<VerifyKey[]> {
try {
const keys = await fetchRemoteServerKeys(serverName, env.DB, env.CACHE);
return keys.map((key) => ({ keyId: key.key_id, publicKey: key.public_key }));
} catch (err) {
console.warn(`[federation] Cannot resolve signing keys for ${serverName}:`, err);
return [];
}
}
// 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; the version endpoint is also unauthenticated as it is used
// for initial contact.
//
// `3pid/onbind` is called by *identity servers*, not homeservers: they cannot
// sign X-Matrix requests. Each pending invite carries the identity server's
// own signature over {mxid, sender, token}, which the handler verifies against
// the room's m.room.third_party_invite state instead.
const federationAuth = requireFederationAuth();
app.use('/_matrix/federation/v1/*', async (c, next) => {
if (c.req.path === '/_matrix/federation/v1/3pid/onbind') return next();
return federationAuth(c, next);
});
// The v2 endpoints (send_join / send_leave / invite) take the same signed
// X-Matrix requests. Without this the request bodies were trusted verbatim,
// so anyone could inject joins, leaves or invites into a room.
app.use('/_matrix/federation/v2/*', requireFederationAuth());
// MSC4284 (spec v1.18): the policy server signing endpoint lives under its
// own federation-authenticated prefix.
app.use('/_matrix/policy/v1/*', requireFederationAuth());
// Matrix publishes Ed25519 verify keys as standard (non-URL-safe) unpadded
// base64. Keys generated here are stored URL-safe, so normalize on publish --
// strict decoders like Synapse's treat '_'/'-' as invalid alphabet and fail
// authentication for every signed request from us.
function toStandardBase64Key(value: string): string {
return value.replace(/-/g, '+').replace(/_/g, '/').replace(/=+$/, '');
}
// 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,
},
};
}
// Publish only keys we can actually sign with. Legacy v1 placeholder rows and
// duplicates from a concurrent first-request generation can linger as
// is_current = 1; advertising them without a matching signature fails strict
// consumers like the Matrix Federation Tester (AllEd25519ChecksOK).
const signableKeys = keys.results.filter((k) => k.key_version === 2 && k.private_key_jwk);
const verifyKeys: Record<string, { key: string }> = {};
for (const key of signableKeys) {
verifyKeys[key.key_id] = { key: toStandardBase64Key(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 with every published key: signJson merges signatures, so each
// verify_key above gets a matching entry under `signatures`.
let signed: Record<string, unknown> = response;
for (const key of signableKeys) {
if (!key.private_key_jwk) continue;
signed = await signJson(signed, serverName, key.key_id, JSON.parse(key.private_key_jwk));
}
return c.json(signed);
});
// 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, private_key_jwk, key_version, valid_from, valid_until FROM server_keys WHERE key_id = ?`
).bind(keyId).first<{
key_id: string;
public_key: string;
private_key_jwk: string | null;
key_version: number | null;
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: toStandardBase64Key(key.public_key) },
},
old_verify_keys: {},
};
// Conduwuit-family servers fetch THIS parameterized form when they hold a
// specific key id from an Authorization header, and strictly require the
// key response to be self-signed — an unsigned body reads as "unable to
// acquire the signing key" and 401s every federation call. Synapse uses
// the unparameterized form, which is why only these servers failed.
if (key.key_version === 2 && key.private_key_jwk) {
const signed = await signJson(
response,
serverName,
key.key_id,
JSON.parse(key.private_key_jwk)
);
return c.json(signed);
}
// Legacy v1 placeholder rows cannot be signed; serve them as before.
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
/** Exported for unit tests. */
export 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 getFederationBody(c);
} 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: toStandardBase64Key(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: toStandardBase64Key(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: toStandardBase64Key(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 });
});
// Inbound ephemeral EDUs go straight to the Room DO — the same storage path
// local clients use. No outbound queueing here, so remote typing/read state
// can never bounce back to its sender as an echo.
async function inboundEduRoomExists(db: D1Database, roomId: string): Promise<boolean> {
try {
return (await getRoom(db, roomId)) !== null;
} catch (err) {
console.warn('[federation] EDU room lookup failed:', err);
return false;
}
}
async function deliverInboundTypingEdu(env: Env, content: unknown): Promise<void> {
const edu = (content ?? {}) as Record<string, unknown>;
const { room_id: roomId, user_id: userId, typing } = edu;
if (typeof roomId !== 'string' || !roomId ||
typeof userId !== 'string' || !userId ||
typeof typing !== 'boolean') {
console.warn('[federation] Ignoring malformed m.typing EDU');
return;
}
if (!await inboundEduRoomExists(env.DB, roomId)) {
console.warn('[federation] Ignoring m.typing EDU for unknown room', roomId);
return;
}
const roomDO = env.ROOMS.get(env.ROOMS.idFromName(roomId));
await roomDO.fetch(new Request('https://room/typing', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
// The DO applies its own default timeout.
body: JSON.stringify({ user_id: userId, typing }),
}));
}
// A server publishes cross-signing key changes for its OWN users with an
// m.signing_key_update EDU. Cache the keys in the same D1 table + KV shape the
// upload path uses, and mark a key change so clients re-query /keys/query.
// The sender is authenticated by transaction origin: never let one server
// overwrite another server's users' cross-signing keys.
async function storeInboundSigningKeyUpdate(
env: Env,
content: unknown,
origin: string
): Promise<void> {
const edu = (content ?? {}) as Record<string, unknown>;
const userId = edu.user_id;
if (typeof userId !== 'string' || !userId.includes(':')) {
console.warn('[federation] Ignoring m.signing_key_update without user_id');
return;
}
if (!userId.endsWith(`:${origin}`)) {
console.warn(`[federation] Ignoring m.signing_key_update for foreign user ${userId} from ${origin}`);
return;
}
const merged: Record<string, unknown> = {};
const updates: Array<{ type: string; key: Record<string, unknown> }> = [];
for (const [type, field] of [
['master', 'master_key'],
['self_signing', 'self_signing_key'],
['user_signing', 'user_signing_key'],
]) {
const key = edu[field];
if (key && typeof key === 'object' && !Array.isArray(key)) {
updates.push({ type, key: key as Record<string, unknown> });
}
}
for (const { type, key } of updates) {
const keys = key.keys;
if (!keys || typeof keys !== 'object' || Array.isArray(keys)) continue;
const keyId = Object.keys(keys as Record<string, unknown>)[0];
if (!keyId) continue;
await env.DB.prepare(`
INSERT INTO cross_signing_keys (user_id, key_type, key_id, key_data)
VALUES (?, ?, ?, ?)
ON CONFLICT (user_id, key_type) DO UPDATE SET
key_id = excluded.key_id,
key_data = excluded.key_data
`).bind(userId, type, keyId, JSON.stringify(key)).run();
merged[type] = key;
}
if (Object.keys(merged).length === 0) return;
try {
const raw = await env.CROSS_SIGNING_KEYS.get(`user:${userId}`);
const existing = raw ? JSON.parse(raw) as Record<string, unknown> : {};
await env.CROSS_SIGNING_KEYS.put(`user:${userId}`, JSON.stringify({ ...existing, ...merged }));
} catch (kvErr) {
console.warn('[federation] Cross-signing EDU KV cache update failed:', kvErr);
}
try {
// device_key_changes is what /sync uses for device_lists.changed; a
// remote user's next /keys/query then refreshes the client's verification
// state from the freshly cached cross-signing keys.
await recordKeyChange(env.DB, userId, null, 'update');
} catch (changeErr) {
console.warn('[federation] Cross-signing EDU key-change record failed:', changeErr);
}
}
// Spec v1.19 wire shape: room_id plus content keyed by event ID, receipt type,
// then user ID. Only m.read is a public ephemeral receipt: m.read.private is
// never accepted from a remote server, and m.fully_read is local account data.
async function deliverInboundReceiptEdu(env: Env, content: unknown): Promise<void> {
const edu = (content ?? {}) as Record<string, unknown>;
const roomId = edu.room_id;
const byEventId = edu.content;
if (typeof roomId !== 'string' || !roomId ||
!byEventId || typeof byEventId !== 'object' || Array.isArray(byEventId)) {
console.warn('[federation] Ignoring malformed m.receipt EDU');
return;
}
if (!await inboundEduRoomExists(env.DB, roomId)) {
console.warn('[federation] Ignoring m.receipt EDU for unknown room', roomId);
return;
}
const roomDO = env.ROOMS.get(env.ROOMS.idFromName(roomId));
for (const [eventId, byReceiptType] of Object.entries(byEventId as Record<string, unknown>)) {
if (!eventId || !byReceiptType || typeof byReceiptType !== 'object' || Array.isArray(byReceiptType)) continue;
for (const [receiptType, byUserId] of Object.entries(byReceiptType as Record<string, unknown>)) {
if (receiptType !== 'm.read') continue;
if (!byUserId || typeof byUserId !== 'object' || Array.isArray(byUserId)) continue;
for (const [userId, data] of Object.entries(byUserId as Record<string, unknown>)) {
if (!userId) continue;
const threadId = (data as { thread_id?: unknown } | null)?.thread_id;
const remoteTs = (data as { ts?: unknown } | null)?.ts;
const receipt: {
user_id: string;
event_id: string;
receipt_type: string;
ts?: number;
thread_id?: string;
} = {
user_id: userId,
event_id: eventId,
receipt_type: receiptType,
};
// Forward the resident's read time; the Room DO stamps Date.now()
// only when ts is absent (local receipts still use their own clock).
if (typeof remoteTs === 'number' && Number.isFinite(remoteTs)) receipt.ts = remoteTs;
if (typeof threadId === 'string') receipt.thread_id = threadId;
try {
await roomDO.fetch(new Request('https://room/receipt', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(receipt),
}));
} catch (err) {
// One bad receipt must not prevent the rest of the EDU being stored.
console.warn('[federation] Failed to store inbound receipt:', err);
}
}
}
}
}
// 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 getFederationBody(c);
} catch {
return Errors.badJson().toResponse();
}
const { pdus, edus } = body;
const pduResults: Record<string, any> = {};
let transientStorageFailure = false;
// Moderation policy lists (spec module): m.ban server rules deny the
// sending server's PDUs with the same posture as ACL denial. Fetched
// once per transaction; no subscriptions means no-op.
const moderationRules = await getActivePolicyRules(c.env.DB, c.env.CACHE);
// Process incoming PDUs (Persistent Data Units - events)
for (const pdu of pdus || []) {
try {
// The room must be known before deriving the event ID: room versions
// 1-10 hash create/power_levels under different redaction rules than
// v11+, so a version-blind derivation stores the event under a
// phantom ID that neither the sender nor other residents use, and
// every later reference to it fails to resolve.
const roomId = pdu.room_id;
const room = roomId
? await c.env.DB.prepare(
`SELECT room_id, room_version FROM rooms WHERE room_id = ?`
).bind(roomId).first<{ room_id: string; room_version: string }>()
: null;
// v4+ wire events (room versions 3 and up) omit `event_id`; the
// receiving server derives it as the event's reference hash. Use the
// resident's redaction form when the wire carries pre-2023 `origin` /
// `prev_state`, and keep an ID we already stored under authoritative —
// re-deriving a stored remote ID can produce a phantom no peer knows.
const candidates = typeof pdu.event_id === 'string' && pdu.event_id
? [pdu.event_id as string]
: await inboundWireEventIdCandidates(pdu as Record<string, unknown>, room?.room_version);
let eventId = candidates[0];
let existingPdu: { accepted: number; rejection_reason: string | null } | null = null;
for (const candidate of candidates) {
const found = await c.env.DB.prepare(
`SELECT accepted, rejection_reason FROM processed_pdus WHERE event_id = ?`
).bind(candidate).first<{ accepted: number; rejection_reason: string | null }>();
if (found) {
eventId = candidate;
existingPdu = found;
break;
}
}
if (!existingPdu && candidates.length > 1) {
for (const candidate of candidates) {
const stored = await c.env.DB.prepare(
`SELECT 1 FROM events WHERE event_id = ?`
).bind(candidate).first();
if (stored) {
eventId = candidate;
break;
}
}
}
if (existingPdu) {
// Already processed
if (existingPdu.accepted) {
pduResults[eventId] = {};
} else {
pduResults[eventId] = pduError(existingPdu.rejection_reason || 'Previously rejected');
}
continue;
}
// Validate basic PDU structure
if (!eventId || !roomId || !pdu.sender || !pdu.type || !pdu.content) {
pduResults[eventId || 'unknown'] = pduError('Invalid PDU structure');
continue;
}
// Get the origin server from the sender
const pduOrigin = (pdu.sender as string).split(':')[1];
if (!pduOrigin) {
pduResults[eventId] = pduError('Invalid sender format');
continue;
}
// Content hash enforcement.
// - Room versions 1-2: hashes optional (legacy clients may omit).
// - Room versions 3+: hashes.sha256 is REQUIRED — modern room versions
// mandate content integrity. An attacker can otherwise omit `hashes`
// entirely to skip integrity verification.
// If the room is unknown locally, default to the strict (modern) rule —
// we won't accept unverifiable events for rooms we know nothing about.
// (`room` was resolved at the top of the loop so the event ID could be
// derived with the room version's redaction rules.)
const roomVersion = room?.room_version;
const requiresHash = !roomVersion || isModernRoomVersion(roomVersion);
const hasSha256 = typeof pdu.hashes?.sha256 === 'string' && pdu.hashes.sha256.length > 0;
if (requiresHash && !hasSha256) {
const reason = `Missing required hashes.sha256 (room_version=${roomVersion ?? 'unknown'})`;
pduResults[eventId] = pduError(reason);
await c.env.DB.prepare(
`INSERT OR REPLACE INTO processed_pdus (event_id, origin, room_id, processed_at, accepted, rejection_reason)