Repository navigation
Expand file tree
/
Copy pathaccount-data.ts
More file actions
939 lines (825 loc) · 30.9 KB
/
Copy pathaccount-data.ts
File metadata and controls
939 lines (825 loc) · 30.9 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
// Account Data API
// Implements: https://spec.matrix.org/v1.12/client-server-api/#client-config
//
// Account data is arbitrary JSON that clients can store per-user or per-room.
// Common uses:
// - m.direct: Direct message room mappings
// - m.ignored_user_list: Blocked users
// - m.fully_read: Read marker position
// - im.vector.setting.*: Element-specific settings
// - m.secret_storage.*: Secret storage keys
//
// IMPORTANT: E2EE-related account data uses Durable Objects for strong consistency.
// This is critical during initial SSSS setup where client writes and immediately
// reads via sliding sync.
import { Hono } from 'hono';
import type { AppEnv, Env } from '../types';
import { Errors } from '../utils/errors';
import { requireAuth } from '../middleware/auth';
import { notifyUserSync } from '../services/database';
const app = new Hono<AppEnv>();
// Helper to get the UserKeys Durable Object stub for a user
function getUserKeysDO(env: Env, userId: string): DurableObjectStub {
const id = env.USER_KEYS.idFromName(userId);
return env.USER_KEYS.get(id);
}
// Get E2EE account data from Durable Object (strongly consistent)
export async function getE2EEAccountDataFromDO(env: Env, userId: string, eventType?: string): Promise<any> {
const stub = getUserKeysDO(env, userId);
const url = eventType
? `http://internal/account-data/get?event_type=${encodeURIComponent(eventType)}`
: 'http://internal/account-data/get';
const response = await stub.fetch(new Request(url));
if (!response.ok) {
const errorText = await response.text().catch(() => 'unknown error');
console.error('[account-data] DO get failed:', response.status, errorText, 'eventType:', eventType);
throw new Error(`DO get failed: ${response.status} - ${errorText}`);
}
return await response.json();
}
// Store E2EE account data in Durable Object (strongly consistent)
async function putE2EEAccountDataToDO(env: Env, userId: string, eventType: string, content: any): Promise<void> {
const stub = getUserKeysDO(env, userId);
const response = await stub.fetch(new Request('http://internal/account-data/put', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ event_type: eventType, content }),
}));
if (!response.ok) {
const errorText = await response.text().catch(() => 'unknown error');
console.error('[account-data] DO put failed:', response.status, errorText, 'eventType:', eventType);
throw new Error(`DO put failed: ${response.status} - ${errorText}`);
}
}
// ============================================
// Helper Functions
// ============================================
async function getNextStreamPosition(db: D1Database, streamName: string): Promise<number> {
await db.prepare(`
UPDATE stream_positions SET position = position + 1 WHERE stream_name = ?
`).bind(streamName).run();
const result = await db.prepare(`
SELECT position FROM stream_positions WHERE stream_name = ?
`).bind(streamName).first<{ position: number }>();
return result?.position || 1;
}
async function recordAccountDataChange(
db: D1Database,
userId: string,
roomId: string,
eventType: string
): Promise<void> {
const streamPosition = await getNextStreamPosition(db, 'account_data');
await db.prepare(`
INSERT INTO account_data_changes (user_id, room_id, event_type, stream_position)
VALUES (?, ?, ?, ?)
`).bind(userId, roomId, eventType, streamPosition).run();
}
// ============================================
// MSC4354 / MSC4480 sticky events
// ============================================
// Sticky events are normal room PDUs with a top-level `sticky.duration_ms`
// (MSC4354). MSC4480 is the sliding-sync extension that delivers them. We
// reuse the existing account_data table under a reserved event-type prefix so
// no new table or migration is needed. Sticky rows are keyed by the sender's
// user_id and the room_id, which makes them room-scoped and visible to every
// joined user, as MSC4354 requires.
export const STICKY_EVENT_TYPE_PREFIX = 'org.matrix.msc4354.sticky.';
const STICKY_EVENT_TYPE_LIKE = `${STICKY_EVENT_TYPE_PREFIX}%`;
const MAX_STICKY_DURATION_MS = 3_600_000;
const DEFAULT_STICKY_LIMIT = 100;
export interface StickyEventRecord {
event_id: string;
type: string;
sender: string;
room_id: string;
origin_server_ts: number;
received_ts: number;
duration_ms: number;
content: Record<string, unknown>;
}
export interface StickyClientEvent {
type: string;
event_id: string;
sender: string;
room_id: string;
origin_server_ts: number;
content: Record<string, unknown>;
sticky: { duration_ms: number };
// Unstable duplicates are emitted for the legacy account-data-backed store
// only; sticky events stored as real PDUs (spec v1.20) omit them.
msc4354_sticky?: { duration_ms: number };
unsigned: {
sticky_duration_remaining_ms: number;
msc4354_sticky_duration_ttl_ms?: number;
};
}
/** True for reserved sticky event_types; callers must hide these from account_data. */
export function isStickyEventType(eventType: string): boolean {
return eventType.startsWith(STICKY_EVENT_TYPE_PREFIX);
}
/** MSC4354 requires a strictly positive integer sticky_duration_ms. */
export function parseStickyDuration(value: unknown): number | null {
if (typeof value === 'number' && Number.isInteger(value) && value > 0) return value;
if (typeof value === 'string' && /^\d+$/.test(value)) {
const parsed = Number(value);
if (parsed > 0) return parsed;
}
return null;
}
function stickyExpiresAt(record: StickyEventRecord): number {
// MSC4354: start = min(received_ts, origin_server_ts); end is capped at 1h.
const start = Math.min(record.received_ts, record.origin_server_ts);
return start + Math.min(record.duration_ms, MAX_STICKY_DURATION_MS);
}
/** Exported for tests. Returns null once the event is no longer sticky. */
export function toStickyClientEvent(
record: StickyEventRecord,
now: number = Date.now()
): StickyClientEvent | null {
const remaining = stickyExpiresAt(record) - now;
if (!Number.isFinite(remaining) || remaining <= 0) return null;
return {
type: record.type,
event_id: record.event_id,
sender: record.sender,
room_id: record.room_id,
origin_server_ts: record.origin_server_ts,
content: record.content,
sticky: { duration_ms: record.duration_ms },
msc4354_sticky: { duration_ms: record.duration_ms },
unsigned: {
sticky_duration_remaining_ms: remaining,
msc4354_sticky_duration_ttl_ms: remaining,
},
};
}
/** Write a sticky event and record it on the account_data stream for /sync. */
export async function putStickyEvent(
db: D1Database,
args: {
userId: string;
roomId: string;
eventType: string;
txnId: string;
durationMs: number;
content: Record<string, unknown>;
eventId?: string;
originServerTs?: number;
receivedTs?: number;
}
): Promise<StickyEventRecord> {
const now = Date.now();
const rawId = args.eventId ?? `msc4354_${args.userId}_${args.roomId}_${args.txnId}`;
const eventId = rawId.startsWith('$') ? rawId : `$${rawId}`;
const record: StickyEventRecord = {
event_id: eventId,
type: args.eventType,
sender: args.userId,
room_id: args.roomId,
origin_server_ts: args.originServerTs ?? now,
received_ts: args.receivedTs ?? now,
duration_ms: args.durationMs,
content: args.content,
};
const accountDataType = `${STICKY_EVENT_TYPE_PREFIX}${eventId}`;
await db.prepare(`
INSERT INTO account_data (user_id, room_id, event_type, content)
VALUES (?, ?, ?, ?)
ON CONFLICT (user_id, room_id, event_type) DO UPDATE SET
content = excluded.content
`).bind(args.userId, args.roomId, accountDataType, JSON.stringify(record)).run();
// Reuses the account_data stream: no extra sequence column or migration.
await recordAccountDataChange(db, args.userId, args.roomId, accountDataType);
return record;
}
interface StickyRow {
user_id: string;
room_id: string;
event_type: string;
content: string;
stream_position?: number;
}
function decodeStickyRow(row: StickyRow): StickyEventRecord | null {
try {
const parsed = JSON.parse(row.content) as StickyEventRecord;
if (!parsed || typeof parsed !== 'object' || typeof parsed.duration_ms !== 'number') {
return null;
}
return parsed;
} catch {
return null;
}
}
/**
* Unexpired sticky events for the given rooms, oldest first, capped per room.
* `since` is an account_data stream position; changes recorded by
* putStickyEvent are delivered exactly once as the token advances.
*/
export async function getStickyEventsForRooms(
db: D1Database,
roomIds: string[],
opts: { since?: number; limit?: number; now?: number } = {}
): Promise<Record<string, StickyClientEvent[]>> {
const byRoom: Record<string, StickyClientEvent[]> = {};
if (roomIds.length === 0) return byRoom;
const now = opts.now ?? Date.now();
const limit = Math.max(1, Math.min(opts.limit ?? DEFAULT_STICKY_LIMIT, DEFAULT_STICKY_LIMIT));
const rows: StickyRow[] = [];
// Stay below D1's bind-variable limit (see the presence query in sync.ts).
for (let i = 0; i < roomIds.length; i += 90) {
const chunk = roomIds.slice(i, i + 90);
const placeholders = chunk.map(() => '?').join(',');
if (opts.since !== undefined) {
const result = await db.prepare(`
SELECT ad.user_id, ad.room_id, ad.event_type, ad.content,
MAX(adc.stream_position) AS stream_position
FROM account_data ad
INNER JOIN account_data_changes adc ON
ad.user_id = adc.user_id AND ad.room_id = adc.room_id AND ad.event_type = adc.event_type
WHERE ad.room_id IN (${placeholders}) AND ad.event_type LIKE ?
GROUP BY ad.user_id, ad.room_id, ad.event_type, ad.content
HAVING MAX(adc.stream_position) > ?
`).bind(...chunk, STICKY_EVENT_TYPE_LIKE, opts.since).all<StickyRow>();
rows.push(...result.results);
} else {
const result = await db.prepare(`
SELECT user_id, room_id, event_type, content FROM account_data
WHERE room_id IN (${placeholders}) AND event_type LIKE ?
`).bind(...chunk, STICKY_EVENT_TYPE_LIKE).all<StickyRow>();
rows.push(...result.results);
}
}
rows.sort((a, b) => {
const ra = decodeStickyRow(a);
const rb = decodeStickyRow(b);
return (ra?.received_ts ?? 0) - (rb?.received_ts ?? 0) || a.event_type.localeCompare(b.event_type);
});
for (const row of rows) {
const record = decodeStickyRow(row);
if (!record) continue;
const event = toStickyClientEvent(record, now);
if (!event) continue;
const roomId = row.room_id;
if (!byRoom[roomId]) byRoom[roomId] = [];
if (byRoom[roomId].length >= limit) continue;
if (byRoom[roomId].some(existing => existing.event_id === event.event_id)) continue;
byRoom[roomId].push(event);
}
return byRoom;
}
/**
* Spec v1.20 (MSC4354): unexpired sticky events that exist as real room PDUs.
*
* These live in the timeline like any other message event; this helper exists
* so `/sync` can also surface the ones that fall outside the timeline window
* (history visibility MUST NOT be applied to unexpired sticky events, so the
* query is deliberately unfiltered).
*/
export async function getStickyPduEventsForRooms(
db: D1Database,
roomIds: string[],
opts: { now?: number; limitPerRoom?: number } = {}
): Promise<Record<string, StickyClientEvent[]>> {
const byRoom: Record<string, StickyClientEvent[]> = {};
if (roomIds.length === 0) return byRoom;
const now = opts.now ?? Date.now();
const perRoom = Math.max(1, Math.min(opts.limitPerRoom ?? DEFAULT_STICKY_LIMIT, DEFAULT_STICKY_LIMIT));
// Stay below D1's bind-variable limit.
for (let i = 0; i < roomIds.length; i += 90) {
const chunk = roomIds.slice(i, i + 90);
const placeholders = chunk.map(() => '?').join(',');
let rows: Array<{
event_id: string;
room_id: string;
sender: string;
event_type: string;
content: string;
origin_server_ts: number;
received_ts: number | null;
sticky: string;
}>;
try {
const result = await db.prepare(`
SELECT event_id, room_id, sender, event_type, content,
origin_server_ts, received_ts, sticky, stream_ordering
FROM events
WHERE room_id IN (${placeholders})
AND sticky IS NOT NULL AND sticky != ''
AND stream_ordering > 0
ORDER BY stream_ordering DESC
LIMIT ?
`).bind(...chunk, perRoom * chunk.length).all<{
event_id: string;
room_id: string;
sender: string;
event_type: string;
content: string;
origin_server_ts: number;
received_ts: number | null;
sticky: string;
}>();
rows = result.results ?? [];
} catch (error) {
console.warn('[sticky] PDU sticky lookup failed:', error);
continue;
}
for (const row of rows) {
let sticky: { duration_ms?: unknown };
try {
sticky = JSON.parse(row.sticky) as { duration_ms?: unknown };
} catch {
continue;
}
if (!sticky || typeof sticky.duration_ms !== 'number') continue;
const durationMs = Math.min(
Math.max(sticky.duration_ms, 0),
MAX_STICKY_DURATION_MS
);
if (durationMs <= 0) continue;
const start = Math.min(row.received_ts ?? row.origin_server_ts, row.origin_server_ts);
const remaining = start + durationMs - now;
if (remaining <= 0) continue;
const list = (byRoom[row.room_id] ??= []);
if (list.length >= perRoom) continue;
list.push({
type: row.event_type,
event_id: row.event_id,
sender: row.sender,
room_id: row.room_id,
origin_server_ts: row.origin_server_ts,
content: JSON.parse(row.content) as Record<string, unknown>,
sticky: { duration_ms: sticky.duration_ms },
unsigned: { sticky_duration_remaining_ms: remaining },
});
}
}
return byRoom;
}
export async function getStickyEventsForRoom(
db: D1Database,
roomId: string,
opts: { now?: number } = {}
): Promise<StickyClientEvent[]> {
const byRoom = await getStickyEventsForRooms(db, [roomId], opts);
return byRoom[roomId] ?? [];
}
// ============================================
// Global Account Data
// ============================================
// Helper to check if event type should use KV for faster access
function isKVAccountData(eventType: string): boolean {
return eventType.startsWith('m.secret_storage') ||
eventType.startsWith('m.cross_signing') ||
eventType === 'm.megolm_backup.v1';
}
// GET /_matrix/client/v3/user/:userId/account_data/:type
app.get('/_matrix/client/v3/user/:userId/account_data/:type', requireAuth(), async (c) => {
const requestingUserId = c.get('userId');
const targetUserId = decodeURIComponent(c.req.param('userId'));
const eventType = decodeURIComponent(c.req.param('type'));
const db = c.env.DB;
// Users can only access their own account data
if (requestingUserId !== targetUserId) {
return c.json({
errcode: 'M_FORBIDDEN',
error: 'Cannot access other users account data',
}, 403);
}
// For E2EE types, read from Durable Object (strongly consistent)
if (isKVAccountData(eventType)) {
// Try DO first (strongly consistent)
try {
const doData = await getE2EEAccountDataFromDO(c.env, targetUserId, eventType);
if (doData !== null && doData !== undefined) {
console.log('[account_data] Retrieved from DO:', eventType);
return c.json(doData);
}
} catch (error) {
console.error('[account_data] DO unavailable, trying fallbacks:', error);
}
// Fallback 1: KV (backup storage)
try {
const kvData = await c.env.ACCOUNT_DATA.get(`global:${targetUserId}:${eventType}`);
if (kvData) {
console.log('[account_data] Retrieved from KV:', eventType);
return c.json(JSON.parse(kvData));
}
} catch (err) {
console.error('[account_data] KV fallback failed:', err);
}
}
// Fallback 2: D1
const data = await db.prepare(`
SELECT content FROM account_data
WHERE user_id = ? AND event_type = ? AND room_id = ''
`).bind(targetUserId, eventType).first<{ content: string }>();
if (!data) {
return c.json({
errcode: 'M_NOT_FOUND',
error: 'Account data not found',
}, 404);
}
try {
return c.json(JSON.parse(data.content));
} catch {
return c.json({});
}
});
// PUT /_matrix/client/v3/user/:userId/account_data/:type
app.put('/_matrix/client/v3/user/:userId/account_data/:type', requireAuth(), async (c) => {
const requestingUserId = c.get('userId');
const targetUserId = decodeURIComponent(c.req.param('userId'));
const eventType = decodeURIComponent(c.req.param('type'));
const db = c.env.DB;
// Users can only modify their own account data
if (requestingUserId !== targetUserId) {
return c.json({
errcode: 'M_FORBIDDEN',
error: 'Cannot modify other users account data',
}, 403);
}
let content: any;
try {
content = await c.req.json();
} catch {
return Errors.badJson().toResponse();
}
// Debug logging for ALL account_data PUT requests
const contentStr = JSON.stringify(content);
console.log('[account_data] PUT', eventType, 'for user:', targetUserId, 'content length:', contentStr.length);
// Extra detailed logging for secret storage related events
if (eventType.startsWith('m.secret_storage') || eventType.startsWith('m.cross_signing') || eventType.startsWith('m.megolm')) {
console.log('[account_data] E2EE content:', contentStr);
}
// Log SSSS content for debugging but ALWAYS store it
// Per Matrix spec MSC-1946, m.secret_storage.default_key SHOULD have a "key" property
// but the server should NOT validate/reject - that causes client-side issues where
// Element X thinks SSSS setup failed when it actually just got silently rejected
if (eventType === 'm.secret_storage.default_key') {
if (!content || typeof content !== 'object' || !content.key || typeof content.key !== 'string') {
console.warn('[account_data] WARNING: m.secret_storage.default_key has unusual content:', contentStr);
// Still store it - the client may be doing partial setup or recovery
} else {
console.log('[account_data] Valid m.secret_storage.default_key with key:', content.key);
}
}
// Log m.secret_storage.key.* but ALWAYS store it
if (eventType.startsWith('m.secret_storage.key.')) {
if (!content || typeof content !== 'object' || !content.algorithm || typeof content.algorithm !== 'string') {
console.warn('[account_data] WARNING:', eventType, 'has unusual content:', contentStr);
// Still store it - the client may be doing partial setup
} else {
console.log('[account_data] Valid', eventType, 'with algorithm:', content.algorithm);
}
}
// For E2EE types, write to Durable Object FIRST (strongly consistent)
// This is critical for SSSS setup where client writes then immediately reads via sync
if (isKVAccountData(eventType)) {
try {
await putE2EEAccountDataToDO(c.env, targetUserId, eventType, content);
console.log('[account_data] Stored in Durable Object:', eventType);
} catch (error) {
console.error('[account_data] Failed to store in DO:', error);
return c.json({
errcode: 'M_UNKNOWN',
error: 'Failed to store E2EE data',
}, 503);
}
// Also write to KV as backup/cache
await c.env.ACCOUNT_DATA.put(
`global:${targetUserId}:${eventType}`,
JSON.stringify(content)
);
}
// Also store in D1 as backup
await db.prepare(`
INSERT INTO account_data (user_id, room_id, event_type, content)
VALUES (?, '', ?, ?)
ON CONFLICT (user_id, room_id, event_type) DO UPDATE SET
content = excluded.content
`).bind(targetUserId, eventType, JSON.stringify(content)).run();
// Record change for sync
await recordAccountDataChange(db, targetUserId, '', eventType);
// Wake this user's in-flight /sync long-poll so the write is echoed back
// promptly. js-sdk's `setAccountData` only resolves once its write comes
// back over sync; without this the caller waits for the long-poll timeout.
// (Correctness does not depend on the wake: the next_batch snapshot fix in
// sync.ts guarantees the change is delivered on the next sync either way.)
// Best-effort like notifyUsersOfEvent — it never fails the write.
await notifyUserSync(c.env, targetUserId, 'account_data');
return c.json({});
});
// ============================================
// Room Account Data
// ============================================
// GET /_matrix/client/v3/user/:userId/rooms/:roomId/account_data/:type
app.get('/_matrix/client/v3/user/:userId/rooms/:roomId/account_data/:type', requireAuth(), async (c) => {
const requestingUserId = c.get('userId');
const targetUserId = decodeURIComponent(c.req.param('userId'));
const roomId = decodeURIComponent(c.req.param('roomId'));
const eventType = decodeURIComponent(c.req.param('type'));
const db = c.env.DB;
// Users can only access their own account data
if (requestingUserId !== targetUserId) {
return c.json({
errcode: 'M_FORBIDDEN',
error: 'Cannot access other users account data',
}, 403);
}
// Verify user is in the room
const membership = await db.prepare(`
SELECT membership FROM room_memberships
WHERE room_id = ? AND user_id = ?
`).bind(roomId, targetUserId).first<{ membership: string }>();
if (!membership || membership.membership !== 'join') {
return c.json({
errcode: 'M_FORBIDDEN',
error: 'User not in room',
}, 403);
}
const data = await db.prepare(`
SELECT content FROM account_data
WHERE user_id = ? AND room_id = ? AND event_type = ?
`).bind(targetUserId, roomId, eventType).first<{ content: string }>();
if (!data) {
return c.json({
errcode: 'M_NOT_FOUND',
error: 'Account data not found',
}, 404);
}
try {
return c.json(JSON.parse(data.content));
} catch {
return c.json({});
}
});
// PUT /_matrix/client/v3/user/:userId/rooms/:roomId/account_data/:type
app.put('/_matrix/client/v3/user/:userId/rooms/:roomId/account_data/:type', requireAuth(), async (c) => {
const requestingUserId = c.get('userId');
const targetUserId = decodeURIComponent(c.req.param('userId'));
const roomId = decodeURIComponent(c.req.param('roomId'));
const eventType = decodeURIComponent(c.req.param('type'));
const db = c.env.DB;
// Users can only modify their own account data
if (requestingUserId !== targetUserId) {
return c.json({
errcode: 'M_FORBIDDEN',
error: 'Cannot modify other users account data',
}, 403);
}
// Verify user is in the room
const membership = await db.prepare(`
SELECT membership FROM room_memberships
WHERE room_id = ? AND user_id = ?
`).bind(roomId, targetUserId).first<{ membership: string }>();
if (!membership || membership.membership !== 'join') {
return c.json({
errcode: 'M_FORBIDDEN',
error: 'User not in room',
}, 403);
}
let content: any;
try {
content = await c.req.json();
} catch {
return Errors.badJson().toResponse();
}
// Store account data
await db.prepare(`
INSERT INTO account_data (user_id, room_id, event_type, content)
VALUES (?, ?, ?, ?)
ON CONFLICT (user_id, room_id, event_type) DO UPDATE SET
content = excluded.content
`).bind(targetUserId, roomId, eventType, JSON.stringify(content)).run();
// Record change for sync
await recordAccountDataChange(db, targetUserId, roomId, eventType);
return c.json({});
});
// ============================================
// MSC4354 / MSC4480 sticky event endpoints
// ============================================
async function requireJoinedRoom(
db: D1Database,
roomId: string,
userId: string
): Promise<boolean> {
const membership = await db.prepare(`
SELECT membership FROM room_memberships
WHERE room_id = ? AND user_id = ?
`).bind(roomId, userId).first<{ membership: string }>();
return membership?.membership === 'join';
}
async function handlePutStickyEvent(c: any): Promise<Response> {
const userId = c.get('userId') as string;
const roomId = decodeURIComponent(c.req.param('roomId'));
const eventType = decodeURIComponent(c.req.param('eventType'));
const txnId = decodeURIComponent(c.req.param('txnId'));
const db = c.env.DB as D1Database;
if (!eventType || !(await requireJoinedRoom(db, roomId, userId))) {
return c.json({ errcode: 'M_FORBIDDEN', error: 'User not in room' }, 403);
}
// MSC4354's unstable query parameter, with the stable name accepted too.
const durationMs = parseStickyDuration(
c.req.query('org.matrix.msc4354.sticky_duration_ms') ?? c.req.query('sticky_duration_ms')
);
if (durationMs === null) {
return c.json({
errcode: 'M_INVALID_PARAM',
error: 'sticky_duration_ms must be a strictly positive integer',
}, 400);
}
let body: Record<string, unknown>;
try {
const parsed = await c.req.json();
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
return Errors.badJson().toResponse();
}
body = parsed as Record<string, unknown>;
} catch {
return Errors.badJson().toResponse();
}
const content = (body.content && typeof body.content === 'object' && !Array.isArray(body.content))
? body.content as Record<string, unknown>
: body;
const eventId = typeof body.event_id === 'string' ? body.event_id : undefined;
const originServerTs = typeof body.origin_server_ts === 'number'
? body.origin_server_ts
: Date.now();
await putStickyEvent(db, {
userId,
roomId,
eventType,
txnId,
durationMs,
content,
eventId,
originServerTs,
});
// Best-effort wake of this user's long-poll so the write is echoed promptly.
try {
await notifyUserSync(c.env, userId, 'account_data');
} catch (error) {
console.error('[account-data] sticky notify failed:', error);
}
return c.json({});
}
async function handleGetStickyEvents(c: any): Promise<Response> {
const userId = c.get('userId') as string;
const roomId = decodeURIComponent(c.req.param('roomId'));
const db = c.env.DB as D1Database;
if (!(await requireJoinedRoom(db, roomId, userId))) {
return c.json({ errcode: 'M_FORBIDDEN', error: 'User not in room' }, 403);
}
const events = await getStickyEventsForRoom(db, roomId);
return c.json({ events });
}
// MSC4354 owns the sticky-event identifiers; MSC4480 is the sliding-sync
// extension, so both unstable namespaces are accepted for the client endpoint.
for (const prefix of ['org.matrix.msc4354', 'org.matrix.msc4480']) {
app.put(
`/_matrix/client/unstable/${prefix}/rooms/:roomId/sticky/:eventType/:txnId`,
requireAuth(),
handlePutStickyEvent
);
app.get(
`/_matrix/client/unstable/${prefix}/rooms/:roomId/sticky`,
requireAuth(),
handleGetStickyEvents
);
}
// ============================================
// Batch Account Data (for sync)
// ============================================
export async function getGlobalAccountData(
db: D1Database,
userId: string,
since?: number
): Promise<{ type: string; content: any }[]> {
let query: string;
const params: any[] = [userId];
if (since !== undefined) {
// Get only changed account data since the given position
query = `
SELECT ad.event_type, ad.content
FROM account_data ad
INNER JOIN account_data_changes adc ON
ad.user_id = adc.user_id AND
ad.event_type = adc.event_type AND
ad.room_id = adc.room_id
WHERE ad.user_id = ? AND ad.room_id = '' AND adc.stream_position > ?
AND ad.event_type NOT LIKE 'org.matrix.msc4354.sticky.%'
GROUP BY ad.event_type
`;
params.push(since);
} else {
// Get all account data
query = `
SELECT event_type, content FROM account_data
WHERE user_id = ? AND room_id = ''
AND event_type NOT LIKE 'org.matrix.msc4354.sticky.%'
`;
}
const results = await db.prepare(query).bind(...params).all<{
event_type: string;
content: string;
}>();
return results.results.map(row => ({
type: row.event_type,
content: JSON.parse(row.content || '{}'),
}));
}
export async function getRoomAccountData(
db: D1Database,
userId: string,
roomId: string,
since?: number
): Promise<{ type: string; content: any }[]> {
let query: string;
const params: any[] = [userId, roomId];
if (since !== undefined) {
query = `
SELECT ad.event_type, ad.content
FROM account_data ad
INNER JOIN account_data_changes adc ON
ad.user_id = adc.user_id AND
ad.event_type = adc.event_type AND
ad.room_id = adc.room_id
WHERE ad.user_id = ? AND ad.room_id = ? AND adc.stream_position > ?
AND ad.event_type NOT LIKE 'org.matrix.msc4354.sticky.%'
GROUP BY ad.event_type
`;
params.push(since);
} else {
query = `
SELECT event_type, content FROM account_data
WHERE user_id = ? AND room_id = ?
AND event_type NOT LIKE 'org.matrix.msc4354.sticky.%'
`;
}
const results = await db.prepare(query).bind(...params).all<{
event_type: string;
content: string;
}>();
return results.results.map(row => ({
type: row.event_type,
content: JSON.parse(row.content || '{}'),
}));
}
export async function getAllRoomAccountData(
db: D1Database,
userId: string,
roomIds: string[],
since?: number
): Promise<Record<string, { type: string; content: any }[]>> {
if (roomIds.length === 0) return {};
const placeholders = roomIds.map(() => '?').join(',');
const params: any[] = [userId, ...roomIds];
let query: string;
if (since !== undefined) {
query = `
SELECT ad.room_id, ad.event_type, ad.content
FROM account_data ad
INNER JOIN account_data_changes adc ON
ad.user_id = adc.user_id AND
ad.event_type = adc.event_type AND
ad.room_id = adc.room_id
WHERE ad.user_id = ? AND ad.room_id IN (${placeholders}) AND adc.stream_position > ?
AND ad.event_type NOT LIKE 'org.matrix.msc4354.sticky.%'
GROUP BY ad.room_id, ad.event_type
`;
params.push(since);
} else {
query = `
SELECT room_id, event_type, content FROM account_data
WHERE user_id = ? AND room_id IN (${placeholders})
AND event_type NOT LIKE 'org.matrix.msc4354.sticky.%'
`;
}
const results = await db.prepare(query).bind(...params).all<{
room_id: string;
event_type: string;
content: string;
}>();
const byRoom: Record<string, { type: string; content: any }[]> = {};
for (const row of results.results) {
if (!byRoom[row.room_id]) {
byRoom[row.room_id] = [];
}
byRoom[row.room_id].push({
type: row.event_type,
content: JSON.parse(row.content || '{}'),
});
}
return byRoom;
}
// ============================================
// Get current stream position
// ============================================
export async function getAccountDataStreamPosition(db: D1Database): Promise<number> {
const result = await db.prepare(`
SELECT position FROM stream_positions WHERE stream_name = 'account_data'
`).first<{ position: number }>();
return result?.position || 0;
}
export default app;