forked from nkuntz1934/matrix-workers
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaccount-data.ts
More file actions
502 lines (430 loc) · 16.1 KB
/
account-data.ts
File metadata and controls
502 lines (430 loc) · 16.1 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
// 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';
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();
}
// ============================================
// 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);
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({});
});
// ============================================
// 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 > ?
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 = ''
`;
}
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 > ?
GROUP BY ad.event_type
`;
params.push(since);
} else {
query = `
SELECT event_type, content FROM account_data
WHERE user_id = ? AND room_id = ?
`;
}
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 > ?
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})
`;
}
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;