Repository navigation
Expand file tree
/
Copy pathdatabase.ts
More file actions
1206 lines (1093 loc) · 40.6 KB
/
Copy pathdatabase.ts
File metadata and controls
1206 lines (1093 loc) · 40.6 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
// Database service layer for D1
import type { User, Device, Room, PDU, Membership, Env } from '../types';
import { MatrixApiError } from '../utils/errors';
import { ErrorCodes } from '../types';
// D1 has an approximate 1MB per-row size cap. We validate event size on the
// way in to fail fast with M_TOO_LARGE rather than silently corrupting data.
// EVENT_CONTENT_SOFT_CAP: per-field soft cap matching Matrix spec guidance (64KB content).
// EVENT_ROW_HARD_CAP: full serialized PDU hard cap, leaves headroom under D1's 1MB limit.
const EVENT_CONTENT_SOFT_CAP = 65_536;
const EVENT_ROW_HARD_CAP = 921_600;
export function validateEventSize(event: PDU): void {
const contentJson = JSON.stringify(event.content ?? {});
if (contentJson.length > EVENT_CONTENT_SOFT_CAP) {
throw new MatrixApiError(
ErrorCodes.M_TOO_LARGE,
`Event content exceeds ${EVENT_CONTENT_SOFT_CAP} byte limit (got ${contentJson.length})`,
413
);
}
const fullJson = JSON.stringify(event);
if (fullJson.length > EVENT_ROW_HARD_CAP) {
throw new MatrixApiError(
ErrorCodes.M_TOO_LARGE,
`Serialized event exceeds ${EVENT_ROW_HARD_CAP} byte D1 row limit (got ${fullJson.length})`,
413
);
}
}
// User operations
export async function createUser(
db: D1Database,
userId: string,
localpart: string,
passwordHash: string | null,
isGuest: boolean = false
): Promise<void> {
await db.prepare(
`INSERT INTO users (user_id, localpart, password_hash, is_guest, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?)`
).bind(userId, localpart, passwordHash, isGuest ? 1 : 0, Date.now(), Date.now()).run();
}
export async function getUserById(db: D1Database, userId: string): Promise<User | null> {
const result = await db.prepare(
`SELECT user_id, localpart, display_name, avatar_url, is_guest, is_deactivated, admin, created_at
FROM users WHERE user_id = ?`
).bind(userId).first<{
user_id: string;
localpart: string;
display_name: string | null;
avatar_url: string | null;
is_guest: number;
is_deactivated: number;
admin: number;
created_at: number;
}>();
if (!result) return null;
return {
user_id: result.user_id,
localpart: result.localpart,
display_name: result.display_name ?? undefined,
avatar_url: result.avatar_url ?? undefined,
is_guest: result.is_guest === 1,
is_deactivated: result.is_deactivated === 1,
admin: result.admin === 1,
created_at: result.created_at,
};
}
export async function getUserByLocalpart(db: D1Database, localpart: string): Promise<User | null> {
const result = await db.prepare(
`SELECT user_id, localpart, display_name, avatar_url, is_guest, is_deactivated, admin, created_at
FROM users WHERE localpart = ?`
).bind(localpart).first<{
user_id: string;
localpart: string;
display_name: string | null;
avatar_url: string | null;
is_guest: number;
is_deactivated: number;
admin: number;
created_at: number;
}>();
if (!result) return null;
return {
user_id: result.user_id,
localpart: result.localpart,
display_name: result.display_name ?? undefined,
avatar_url: result.avatar_url ?? undefined,
is_guest: result.is_guest === 1,
is_deactivated: result.is_deactivated === 1,
admin: result.admin === 1,
created_at: result.created_at,
};
}
export async function getPasswordHash(db: D1Database, userId: string): Promise<string | null> {
const result = await db.prepare(
`SELECT password_hash FROM users WHERE user_id = ?`
).bind(userId).first<{ password_hash: string | null }>();
return result?.password_hash ?? null;
}
// MSC4155/MSC4380: invite filtering. The recipient's global account data
// `m.invite_permission_config` (unstable type
// `org.matrix.msc4155.invite_permission_config`) holds glob lists evaluated
// in the MSC's order; `m.ignored_user_list` takes precedence. 'block' means
// invite endpoints must 403; 'ignore' means the invite is accepted but
// withheld from the recipient's sync responses. MSC4380 (stable since spec
// v1.18) adds `default_action: "block"` to the stable event type, rejecting
// every invite that no allow-list redeems.
export type InvitePermission = 'allow' | 'ignore' | 'block';
function globMatches(glob: string, value: string): boolean {
const pattern = glob
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
.replace(/\*/g, '.*')
.replace(/\?/g, '.');
return new RegExp(`^${pattern}$`).test(value);
}
function matchesAny(globs: unknown, value: string): boolean {
if (!Array.isArray(globs)) return false;
return globs.some((g) => typeof g === 'string' && globMatches(g, value));
}
export async function getInvitePermission(
db: D1Database,
recipientUserId: string,
inviterUserId: string
): Promise<InvitePermission> {
const rows = await db.prepare(
`SELECT event_type, content FROM account_data
WHERE user_id = ? AND room_id = ''
AND event_type IN ('m.ignored_user_list', 'm.invite_permission_config', 'org.matrix.msc4155.invite_permission_config')`
).bind(recipientUserId).all<{ event_type: string; content: string }>();
const byType = new Map(rows.results.map((r) => [r.event_type, r.content]));
const parse = (type: string): any => {
try {
return JSON.parse(byType.get(type) ?? 'null');
} catch {
return null;
}
};
const ignoredUsers = parse('m.ignored_user_list')?.ignored_users;
if (Array.isArray(ignoredUsers)) {
if (ignoredUsers.includes(inviterUserId)) return 'ignore';
} else if (ignoredUsers && typeof ignoredUsers === 'object' && inviterUserId in ignoredUsers) {
return 'ignore';
}
const config =
parse('m.invite_permission_config') ?? parse('org.matrix.msc4155.invite_permission_config');
if (!config || typeof config !== 'object') return 'allow';
if (config.enabled === false) return 'allow';
// Server globs match the domain with any port suffix stripped (server ACLs).
const inviterServer = inviterUserId.split(':').slice(1).join(':').replace(/:\d+$/, '');
if (matchesAny(config.allowed_users, inviterUserId)) return 'allow';
if (matchesAny(config.ignored_users, inviterUserId)) return 'ignore';
if (matchesAny(config.blocked_users, inviterUserId)) return 'block';
if (matchesAny(config.allowed_servers, inviterServer)) return 'allow';
if (matchesAny(config.ignored_servers, inviterServer)) return 'ignore';
if (matchesAny(config.blocked_servers, inviterServer)) return 'block';
// MSC4380: with no glob opinion, `default_action: "block"` rejects all
// invites. Missing, invalid or unsupported values mean allow (the user
// explicitly opts back in by writing the event without the property).
if (config.default_action === 'block') return 'block';
return 'allow';
}
export async function updateUserProfile(
db: D1Database,
userId: string,
displayName?: string | null,
avatarUrl?: string | null
): Promise<void> {
if (displayName !== undefined) {
await db.prepare(
`UPDATE users SET display_name = ?, updated_at = ? WHERE user_id = ?`
).bind(displayName, Date.now(), userId).run();
}
if (avatarUrl !== undefined) {
await db.prepare(
`UPDATE users SET avatar_url = ?, updated_at = ? WHERE user_id = ?`
).bind(avatarUrl, Date.now(), userId).run();
}
}
// Device operations
export async function createDevice(
db: D1Database,
userId: string,
deviceId: string,
displayName?: string
): Promise<void> {
await db.prepare(
`INSERT INTO devices (user_id, device_id, display_name, created_at)
VALUES (?, ?, ?, ?)`
).bind(userId, deviceId, displayName ?? null, Date.now()).run();
}
export async function getDevice(
db: D1Database,
userId: string,
deviceId: string
): Promise<Device | null> {
const result = await db.prepare(
`SELECT device_id, user_id, display_name, last_seen_ts, last_seen_ip, created_at
FROM devices WHERE user_id = ? AND device_id = ?`
).bind(userId, deviceId).first<{
device_id: string;
user_id: string;
display_name: string | null;
last_seen_ts: number | null;
last_seen_ip: string | null;
created_at: number;
}>();
if (!result) return null;
return {
device_id: result.device_id,
user_id: result.user_id,
display_name: result.display_name ?? undefined,
last_seen_ts: result.last_seen_ts ?? undefined,
last_seen_ip: result.last_seen_ip ?? undefined,
};
}
export async function getUserDevices(db: D1Database, userId: string): Promise<Device[]> {
const result = await db.prepare(
`SELECT device_id, user_id, display_name, last_seen_ts, last_seen_ip
FROM devices WHERE user_id = ?`
).bind(userId).all<{
device_id: string;
user_id: string;
display_name: string | null;
last_seen_ts: number | null;
last_seen_ip: string | null;
}>();
return result.results.map(r => ({
device_id: r.device_id,
user_id: r.user_id,
display_name: r.display_name ?? undefined,
last_seen_ts: r.last_seen_ts ?? undefined,
last_seen_ip: r.last_seen_ip ?? undefined,
}));
}
export async function deleteDevice(
db: D1Database,
userId: string,
deviceId: string
): Promise<void> {
await db.prepare(
`DELETE FROM devices WHERE user_id = ? AND device_id = ?`
).bind(userId, deviceId).run();
}
// Access token operations
export async function createAccessToken(
db: D1Database,
tokenId: string,
tokenHash: string,
userId: string,
deviceId: string | null
): Promise<void> {
await db.prepare(
`INSERT INTO access_tokens (token_id, token_hash, user_id, device_id, created_at)
VALUES (?, ?, ?, ?, ?)`
).bind(tokenId, tokenHash, userId, deviceId, Date.now()).run();
}
export async function getUserByTokenHash(
db: D1Database,
tokenHash: string
): Promise<
| {
userId: string;
deviceId: string | null;
// MSC4323 account moderation: present only when the account is
// moderated so unmoderated contexts stay shape-identical to before.
locked?: boolean;
suspended?: boolean;
}
| null
> {
// Join users in the same query so every authenticated request learns the
// moderation state without a second D1 round trip.
const result = await db.prepare(
`SELECT at.user_id AS user_id, at.device_id AS device_id,
u.locked AS locked, u.suspended AS suspended
FROM access_tokens at JOIN users u ON u.user_id = at.user_id
WHERE at.token_hash = ?`
).bind(tokenHash).first<{
user_id: string;
device_id: string | null;
locked?: number;
suspended?: number;
}>();
if (!result) return null;
return {
userId: result.user_id,
deviceId: result.device_id,
...(result.locked === 1 ? { locked: true } : {}),
...(result.suspended === 1 ? { suspended: true } : {}),
};
}
export async function deleteAccessToken(db: D1Database, tokenHash: string): Promise<void> {
await db.prepare(
`DELETE FROM access_tokens WHERE token_hash = ?`
).bind(tokenHash).run();
}
export async function deleteAllUserTokens(db: D1Database, userId: string): Promise<void> {
await db.prepare(
`DELETE FROM access_tokens WHERE user_id = ?`
).bind(userId).run();
}
// Room operations
export async function createRoom(
db: D1Database,
roomId: string,
roomVersion: string,
creatorId: string,
isPublic: boolean = false
): Promise<void> {
await db.prepare(
`INSERT INTO rooms (room_id, room_version, creator_id, is_public, created_at)
VALUES (?, ?, ?, ?, ?)`
).bind(roomId, roomVersion, creatorId, isPublic ? 1 : 0, Date.now()).run();
}
export async function getRoom(db: D1Database, roomId: string): Promise<Room | null> {
const result = await db.prepare(
`SELECT room_id, room_version, is_public, creator_id, created_at
FROM rooms WHERE room_id = ?`
).bind(roomId).first<{
room_id: string;
room_version: string;
is_public: number;
creator_id: string | null;
created_at: number;
}>();
if (!result) return null;
return {
room_id: result.room_id,
room_version: result.room_version,
is_public: result.is_public === 1,
creator_id: result.creator_id ?? undefined,
created_at: result.created_at,
};
}
// Event operations
export async function storeEvent(db: D1Database, event: PDU): Promise<number> {
// Validate row size against D1's ~1MB per-row cap before any write.
validateEventSize(event);
// Atomically allocate the next stream ordering using UPDATE...RETURNING.
// This avoids the race condition where two concurrent calls both read
// MAX(stream_ordering) and generate the same value.
const posResult = await db.prepare(
`UPDATE stream_positions SET position = position + 1 WHERE stream_name = 'events' RETURNING position`
).first<{ position: number }>();
const streamOrdering = posResult?.position ?? 1;
await db.prepare(
`INSERT INTO events (event_id, room_id, sender, event_type, state_key, content,
origin_server_ts, unsigned, depth, auth_events, prev_events, hashes, signatures, sticky, received_ts, stream_ordering, origin)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
).bind(
event.event_id,
event.room_id,
event.sender,
event.type,
event.state_key ?? null,
JSON.stringify(event.content),
event.origin_server_ts,
event.unsigned ? JSON.stringify(event.unsigned) : null,
event.depth,
JSON.stringify(event.auth_events),
JSON.stringify(event.prev_events),
event.hashes ? JSON.stringify(event.hashes) : null,
event.signatures ? JSON.stringify(event.signatures) : null,
event.sticky ? JSON.stringify(event.sticky) : null,
Date.now(),
streamOrdering,
event.origin ?? null
).run();
// Update room state if this is a state event
if (event.state_key !== undefined) {
await db.prepare(
`INSERT OR REPLACE INTO room_state (room_id, event_type, state_key, event_id)
VALUES (?, ?, ?, ?)`
).bind(event.room_id, event.type, event.state_key, event.event_id).run();
}
return streamOrdering;
}
// Idempotent variant of storeEvent that uses INSERT OR IGNORE on the events
// table. Returns true if a new row was inserted, false if the event_id was
// already present (indicating a concurrent / retried write was deduplicated).
//
// When the event collides, no stream_ordering is consumed and no state is
// updated — the caller can treat this as "the prior write won".
export async function storeEventIdempotent(
db: D1Database,
event: PDU,
opts: { stateOnly?: boolean } = {}
): Promise<{ inserted: boolean; streamOrdering: number | null }> {
// State-snapshot events (the backfilled CURRENT STATE of a remote room —
// thousands of member joins for a big room) are stored at NEGATIVE stream
// positions: still unique (events.stream_ordering carries a UNIQUE index,
// so a shared sentinel value would fail the second insert), fully usable
// for auth checks, room_state serving and federation responses, but
// excluded by every timeline query's `stream_ordering > 0` filter — so
// paginated history shows the actual conversation instead of a wall of
// join messages. Real history (live /send, timeline backfill, locally
// created events) keeps ascending positive positions.
let streamOrdering: number;
if (opts.stateOnly) {
const posResult = await db.prepare(
`UPDATE stream_positions SET position = position + 1 WHERE stream_name = 'events' RETURNING position`
).first<{ position: number }>();
streamOrdering = -(posResult?.position ?? 1);
} else {
// Allocate stream ordering optimistically. If the event already exists
// we simply waste one stream id; this is preferable to
// checking-then-inserting (which races) and stream ids are cheap.
const posResult = await db.prepare(
`UPDATE stream_positions SET position = position + 1 WHERE stream_name = 'events' RETURNING position`
).first<{ position: number }>();
streamOrdering = posResult?.position ?? 1;
}
const insertResult = await db.prepare(
`INSERT OR IGNORE INTO events (event_id, room_id, sender, event_type, state_key, content,
origin_server_ts, unsigned, depth, auth_events, prev_events, hashes, signatures, sticky, received_ts, stream_ordering, origin)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
).bind(
event.event_id,
event.room_id,
event.sender,
event.type,
event.state_key ?? null,
JSON.stringify(event.content),
event.origin_server_ts,
event.unsigned ? JSON.stringify(event.unsigned) : null,
event.depth,
JSON.stringify(event.auth_events),
JSON.stringify(event.prev_events),
event.hashes ? JSON.stringify(event.hashes) : null,
event.signatures ? JSON.stringify(event.signatures) : null,
event.sticky ? JSON.stringify(event.sticky) : null,
Date.now(),
streamOrdering,
event.origin ?? null
).run();
// D1 reports rows_written / changes — when 0, the row was ignored as a dup.
const inserted = (insertResult.meta?.changes ?? 0) > 0;
if (inserted && event.state_key !== undefined) {
await db.prepare(
`INSERT OR REPLACE INTO room_state (room_id, event_type, state_key, event_id)
VALUES (?, ?, ?, ?)`
).bind(event.room_id, event.type, event.state_key, event.event_id).run();
}
return { inserted, streamOrdering: inserted ? streamOrdering : null };
}
export async function getEvent(db: D1Database, eventId: string): Promise<PDU | null> {
const result = await db.prepare(
`SELECT event_id, room_id, sender, event_type, state_key, content,
origin_server_ts, unsigned, depth, auth_events, prev_events, hashes, signatures, sticky, origin
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;
unsigned: string | null;
depth: number;
auth_events: string;
prev_events: string;
hashes: string | null;
signatures: string | null;
sticky: string | null;
origin: string | null;
}>();
if (!result) return null;
return {
event_id: result.event_id,
room_id: result.room_id,
sender: result.sender,
type: result.event_type,
state_key: result.state_key ?? undefined,
content: JSON.parse(result.content),
origin_server_ts: result.origin_server_ts,
unsigned: result.unsigned ? JSON.parse(result.unsigned) : undefined,
depth: result.depth,
auth_events: JSON.parse(result.auth_events),
prev_events: JSON.parse(result.prev_events),
hashes: result.hashes ? JSON.parse(result.hashes) : undefined,
signatures: result.signatures ? JSON.parse(result.signatures) : undefined,
...(result.sticky ? { sticky: JSON.parse(result.sticky) } : {}),
...(result.origin ? { origin: result.origin } : {}),
};
}
export async function getRoomEvents(
db: D1Database,
roomId: string,
fromToken?: number,
limit: number = 50,
direction: 'f' | 'b' = 'b'
): Promise<{ events: PDU[]; end: number }> {
let query: string;
const params: (string | number)[] = [roomId];
if (direction === 'b') {
// Backwards (newest first). Negative stream_ordering marks state-snapshot
// rows (backfilled current state) — never part of paginated history.
if (fromToken) {
query = `SELECT * FROM events WHERE room_id = ? AND stream_ordering > 0 AND stream_ordering < ? ORDER BY stream_ordering DESC LIMIT ?`;
params.push(fromToken, limit);
} else {
query = `SELECT * FROM events WHERE room_id = ? AND stream_ordering > 0 ORDER BY stream_ordering DESC LIMIT ?`;
params.push(limit);
}
} else {
// Forwards (oldest first)
if (fromToken) {
query = `SELECT * FROM events WHERE room_id = ? AND stream_ordering > ? ORDER BY stream_ordering ASC LIMIT ?`;
params.push(fromToken, limit);
} else {
query = `SELECT * FROM events WHERE room_id = ? AND stream_ordering > 0 ORDER BY stream_ordering ASC LIMIT ?`;
params.push(limit);
}
}
const result = await db.prepare(query).bind(...params).all<{
event_id: string;
room_id: string;
sender: string;
event_type: string;
state_key: string | null;
content: string;
origin_server_ts: number;
unsigned: string | null;
depth: number;
auth_events: string;
prev_events: string;
stream_ordering: number;
redacted_content?: string | null;
sticky?: string | null;
origin?: string | null;
}>();
const events = result.results.map(r => ({
event_id: r.event_id,
room_id: r.room_id,
sender: r.sender,
type: r.event_type,
state_key: r.state_key ?? undefined,
// Redacted events serve their pruned content (SELECT * carries
// redacted_content); send cores only use event_id/depth, so this is
// safe for prev_events resolution too.
content: JSON.parse(r.redacted_content ?? r.content),
origin_server_ts: r.origin_server_ts,
unsigned: r.unsigned ? JSON.parse(r.unsigned) : undefined,
depth: r.depth,
auth_events: JSON.parse(r.auth_events),
prev_events: JSON.parse(r.prev_events),
...(r.sticky ? { sticky: JSON.parse(r.sticky) } : {}),
...(r.origin ? { origin: r.origin } : {}),
}));
const lastEvent = result.results[result.results.length - 1];
const end = lastEvent?.stream_ordering ?? fromToken ?? 0;
return { events, end };
}
// Room state operations
export async function getRoomState(
db: D1Database,
roomId: string
): Promise<PDU[]> {
const result = await db.prepare(
`SELECT e.event_id, e.room_id, e.sender, e.event_type, e.state_key, e.content,
e.origin_server_ts, e.unsigned, e.depth, e.auth_events, e.prev_events, e.sticky, e.origin
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;
unsigned: string | null;
depth: number;
auth_events: string;
prev_events: string;
sticky: string | null;
origin: string | null;
}>();
return result.results.map(r => ({
event_id: r.event_id,
room_id: r.room_id,
sender: r.sender,
type: r.event_type,
state_key: r.state_key ?? undefined,
content: JSON.parse(r.content),
origin_server_ts: r.origin_server_ts,
unsigned: r.unsigned ? JSON.parse(r.unsigned) : undefined,
depth: r.depth,
auth_events: JSON.parse(r.auth_events),
prev_events: JSON.parse(r.prev_events),
...(r.sticky ? { sticky: JSON.parse(r.sticky) } : {}),
...(r.origin ? { origin: r.origin } : {}),
}));
}
export async function getStateEvent(
db: D1Database,
roomId: string,
eventType: string,
stateKey: string = ''
): Promise<PDU | null> {
const result = await db.prepare(
`SELECT e.event_id, e.room_id, e.sender, e.event_type, e.state_key, e.content,
e.origin_server_ts, e.unsigned, e.depth, e.auth_events, e.prev_events, e.sticky, e.origin
FROM room_state rs
JOIN events e ON rs.event_id = e.event_id
WHERE rs.room_id = ? AND rs.event_type = ? AND rs.state_key = ?`
).bind(roomId, eventType, stateKey).first<{
event_id: string;
room_id: string;
sender: string;
event_type: string;
state_key: string | null;
content: string;
origin_server_ts: number;
unsigned: string | null;
depth: number;
auth_events: string;
prev_events: string;
sticky: string | null;
origin: string | null;
}>();
if (!result) return null;
return {
event_id: result.event_id,
room_id: result.room_id,
sender: result.sender,
type: result.event_type,
state_key: result.state_key ?? undefined,
content: JSON.parse(result.content),
origin_server_ts: result.origin_server_ts,
unsigned: result.unsigned ? JSON.parse(result.unsigned) : undefined,
depth: result.depth,
auth_events: JSON.parse(result.auth_events),
prev_events: JSON.parse(result.prev_events),
...(result.sticky ? { sticky: JSON.parse(result.sticky) } : {}),
...(result.origin ? { origin: result.origin } : {}),
};
}
// Membership operations
export async function updateMembership(
db: D1Database,
roomId: string,
userId: string,
membership: Membership,
eventId: string,
displayName?: string,
avatarUrl?: string
): Promise<void> {
await db.prepare(
`INSERT OR REPLACE INTO room_memberships (room_id, user_id, membership, event_id, display_name, avatar_url)
VALUES (?, ?, ?, ?, ?, ?)`
).bind(roomId, userId, membership, eventId, displayName ?? null, avatarUrl ?? null).run();
}
// Idempotent join: only writes a membership row if one does not already
// exist with membership='join'. Returns the event_id that ultimately
// represents this user's join (either the new one or the pre-existing one).
//
// This pairs with deterministic event IDs so that two concurrent join
// requests collapse to a single membership event without producing
// duplicate rows in `events` or flapping `room_memberships`.
export async function tryInsertJoinMembership(
db: D1Database,
roomId: string,
userId: string,
eventId: string,
displayName?: string,
avatarUrl?: string
): Promise<{ inserted: boolean; eventId: string }> {
const result = await db.prepare(
`INSERT INTO room_memberships (room_id, user_id, membership, event_id, display_name, avatar_url)
VALUES (?, ?, 'join', ?, ?, ?)
ON CONFLICT(room_id, user_id) DO UPDATE SET
membership = CASE
WHEN room_memberships.membership = 'join' THEN room_memberships.membership
ELSE excluded.membership
END,
event_id = CASE
WHEN room_memberships.membership = 'join' THEN room_memberships.event_id
ELSE excluded.event_id
END,
display_name = CASE
WHEN room_memberships.membership = 'join' THEN room_memberships.display_name
ELSE excluded.display_name
END,
avatar_url = CASE
WHEN room_memberships.membership = 'join' THEN room_memberships.avatar_url
ELSE excluded.avatar_url
END
RETURNING event_id`
).bind(roomId, userId, eventId, displayName ?? null, avatarUrl ?? null)
.first<{ event_id: string }>();
const finalEventId = result?.event_id ?? eventId;
return { inserted: finalEventId === eventId, eventId: finalEventId };
}
export async function getMembership(
db: D1Database,
roomId: string,
userId: string
): Promise<{ membership: Membership; eventId: string } | null> {
const result = await db.prepare(
`SELECT membership, event_id FROM room_memberships WHERE room_id = ? AND user_id = ?`
).bind(roomId, userId).first<{ membership: Membership; event_id: string }>();
if (!result) return null;
return {
membership: result.membership,
eventId: result.event_id,
};
}
export async function getUserRooms(
db: D1Database,
userId: string,
membership?: Membership
): Promise<string[]> {
let query = `SELECT room_id FROM room_memberships WHERE user_id = ?`;
const params: string[] = [userId];
if (membership) {
query += ` AND membership = ?`;
params.push(membership);
}
const result = await db.prepare(query).bind(...params).all<{ room_id: string }>();
return result.results.map(r => r.room_id);
}
export async function getRoomMembers(
db: D1Database,
roomId: string,
membership?: Membership
): Promise<Array<{ userId: string; membership: Membership; displayName?: string; avatarUrl?: string }>> {
let query = `SELECT user_id, membership, display_name, avatar_url FROM room_memberships WHERE room_id = ?`;
const params: string[] = [roomId];
if (membership) {
query += ` AND membership = ?`;
params.push(membership);
}
const result = await db.prepare(query).bind(...params).all<{
user_id: string;
membership: Membership;
display_name: string | null;
avatar_url: string | null;
}>();
return result.results.map(r => ({
userId: r.user_id,
membership: r.membership,
displayName: r.display_name ?? undefined,
avatarUrl: r.avatar_url ?? undefined,
}));
}
// Room alias operations
export async function createRoomAlias(
db: D1Database,
alias: string,
roomId: string,
creatorId: string
): Promise<void> {
await db.prepare(
`INSERT INTO room_aliases (alias, room_id, creator_id, created_at)
VALUES (?, ?, ?, ?)`
).bind(alias, roomId, creatorId, Date.now()).run();
}
export async function getRoomByAlias(db: D1Database, alias: string): Promise<string | null> {
const result = await db.prepare(
`SELECT room_id FROM room_aliases WHERE alias = ?`
).bind(alias).first<{ room_id: string }>();
return result?.room_id ?? null;
}
export async function deleteRoomAlias(db: D1Database, alias: string): Promise<void> {
await db.prepare(`DELETE FROM room_aliases WHERE alias = ?`).bind(alias).run();
}
// Stream position for sync
export async function getLatestStreamPosition(db: D1Database): Promise<number> {
const result = await db.prepare(
`SELECT MAX(stream_ordering) as max_ordering FROM events`
).first<{ max_ordering: number | null }>();
return result?.max_ordering ?? 0;
}
export async function getEventsSince(
db: D1Database,
roomId: string,
since: number,
limit: number = 100,
order: 'asc' | 'desc' = 'asc'
): Promise<PDU[]> {
const result = await db.prepare(
`SELECT event_id, room_id, sender, event_type, state_key, content,
origin_server_ts, unsigned, depth, auth_events, prev_events, redacted_content, sticky
FROM events
WHERE room_id = ? AND stream_ordering > ?
ORDER BY stream_ordering ${order === 'desc' ? 'DESC' : 'ASC'}
LIMIT ?`
).bind(roomId, since, limit).all<{
event_id: string;
room_id: string;
sender: string;
event_type: string;
state_key: string | null;
content: string;
origin_server_ts: number;
unsigned: string | null;
depth: number;
auth_events: string;
prev_events: string;
redacted_content?: string | null;
sticky?: string | null;
}>();
const events = result.results.map(r => ({
event_id: r.event_id,
room_id: r.room_id,
sender: r.sender,
type: r.event_type,
state_key: r.state_key ?? undefined,
// Redacted events serve their pruned content; the original column
// remains for federation (hashes/signatures are computed over it).
content: JSON.parse(r.redacted_content ?? r.content),
origin_server_ts: r.origin_server_ts,
unsigned: r.unsigned ? JSON.parse(r.unsigned) : undefined,
depth: r.depth,
auth_events: JSON.parse(r.auth_events),
prev_events: JSON.parse(r.prev_events),
...(r.sticky ? { sticky: JSON.parse(r.sticky) } : {}),
}));
// DESC is used to select the newest page; callers still consume events in
// ascending stream order, so restore that order before returning.
return order === 'desc' ? events.reverse() : events;
}
// Batch retrieve events by IDs.
// D1 has limits on placeholders per statement and on response size; we page
// through the input list to keep individual queries bounded.
const GET_EVENTS_PAGE_SIZE = 100;
export async function getEventsByIds(db: D1Database, eventIds: string[]): Promise<PDU[]> {
if (eventIds.length === 0) return [];
const out: PDU[] = [];
for (let i = 0; i < eventIds.length; i += GET_EVENTS_PAGE_SIZE) {
const page = eventIds.slice(i, i + GET_EVENTS_PAGE_SIZE);
// D1 doesn't support array binding, so we batch with placeholders
const placeholders = page.map(() => '?').join(', ');
const result = await db.prepare(
`SELECT event_id, room_id, sender, event_type, state_key, content,
origin_server_ts, unsigned, depth, auth_events, prev_events, hashes, signatures, sticky
FROM events WHERE event_id IN (${placeholders})`
).bind(...page).all<{
event_id: string;
room_id: string;
sender: string;
event_type: string;
state_key: string | null;
content: string;
origin_server_ts: number;
unsigned: string | null;
depth: number;
auth_events: string;
prev_events: string;
hashes: string | null;
signatures: string | null;
sticky: string | null;
}>();
for (const r of result.results) {
out.push({
event_id: r.event_id,
room_id: r.room_id,
sender: r.sender,
type: r.event_type,
state_key: r.state_key ?? undefined,
content: JSON.parse(r.content),
origin_server_ts: r.origin_server_ts,
unsigned: r.unsigned ? JSON.parse(r.unsigned) : undefined,
depth: r.depth,
auth_events: JSON.parse(r.auth_events),
prev_events: JSON.parse(r.prev_events),
hashes: r.hashes ? JSON.parse(r.hashes) : undefined,
signatures: r.signatures ? JSON.parse(r.signatures) : undefined,
...(r.sticky ? { sticky: JSON.parse(r.sticky) } : {}),
});
}
}
return out;
}
// Cap auth chain traversal to avoid pathological recursion fetching thousands
// of events under D1's per-query limits.
const MAX_AUTH_CHAIN_SIZE = 500;
// Get the auth chain for an event (all auth_events recursively)
export async function getAuthChain(db: D1Database, eventIds: string[]): Promise<PDU[]> {
const seen = new Set<string>();
const chain: PDU[] = [];
const queue = [...eventIds];
while (queue.length > 0 && chain.length < MAX_AUTH_CHAIN_SIZE) {
const batch = queue.splice(0, 50).filter(id => !seen.has(id));
if (batch.length === 0) continue;
for (const id of batch) seen.add(id);
const events = await getEventsByIds(db, batch);
for (const event of events) {
chain.push(event);
if (chain.length >= MAX_AUTH_CHAIN_SIZE) {
console.warn('[getAuthChain] reached MAX_AUTH_CHAIN_SIZE cap', MAX_AUTH_CHAIN_SIZE, 'aborting traversal');
break;
}
for (const authId of event.auth_events) {
if (!seen.has(authId)) {
queue.push(authId);
}
}
}
}
return chain;
}