@wtfalch/chat 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1739 +0,0 @@
1
- import { installFetchRoute } from "./intercept.js";
2
- const PEER_USER_ID = '@peer:fake';
3
- function jsonResponse(status, body) {
4
- return new Response(JSON.stringify(body), {
5
- status,
6
- headers: { 'Content-Type': 'application/json' },
7
- });
8
- }
9
- function bearerToken(init) {
10
- const value = new Headers(init?.headers).get('authorization') ?? '';
11
- return value.startsWith('Bearer ') ? value.slice('Bearer '.length) : undefined;
12
- }
13
- /**
14
- * A fake exchange endpoint and a fake homeserver, both answered by
15
- * intercepting `fetch` -- so `createChatClient`'s real wire code, and the
16
- * real matrix-js-sdk underneath it, run exactly as they would against
17
- * `apps/chat-service` and Synapse. See `intercept.ts`'s module comment.
18
- *
19
- * It implements only what `createChatClient`'s startup needs: `/versions`,
20
- * `/pushrules/`, filter creation, and `/sync`. Anything else falls through
21
- * to whatever else is installed, or the real network.
22
- *
23
- * `/sync` beyond the first request is a manual long-poll: it never answers
24
- * on its own. A test drives it explicitly with `addRoom` and
25
- * `invalidateCurrentToken`, after confirming the request has arrived with
26
- * `waitForParkedPoll()`.
27
- */
28
- export class FakeChatServer {
29
- homeserver;
30
- exchangeUrl;
31
- /** Controls for upload failure and in-flight UI scenarios. */
32
- uploadBarrier = null;
33
- uploadStatus = 200;
34
- /** What `PUT .../state/m.room.pinned_events/` answers with -- 403 models
35
- * the power-level refusal a room whose power levels predate ticket #8
36
- * gives a member, which `pinMessage`/`unpinMessage` must reject on
37
- * rather than resolve quietly. */
38
- pinStatus = 200;
39
- /** What `PUT .../send/...` answers with -- anything but 200 fails the
40
- * send, with nothing stored. */
41
- sendStatus = 200;
42
- /** Holds every thread follow `GET` until it resolves -- for a test of a
43
- * read that is still in flight when the person clicks. */
44
- threadFollowReadBarrier = null;
45
- /** What a thread follow `GET` answers with. */
46
- threadFollowReadStatus = 200;
47
- /** What a thread follow `PUT`/`DELETE` answers with -- anything but 200
48
- * fails the follow or unfollow, with nothing stored. */
49
- threadFollowWriteStatus = 200;
50
- /** Every call to the thread follow route, in arrival order. */
51
- threadFollowRequests = [];
52
- userId;
53
- /** The Matrix server name, as `userId` gives it -- what an `mxc://`
54
- * reference from this homeserver names. */
55
- serverName;
56
- /** How many times `/_chat/exchange` has been called. */
57
- exchangeCount = 0;
58
- /** Every Matrix access token this server has ever minted, oldest first --
59
- * for a test that asserts one was never logged. */
60
- mintedTokens = [];
61
- /** Every `m.read` receipt this server has answered, in arrival order --
62
- * for a test that asserts `markRoomRead` actually called the wire. */
63
- receipts = [];
64
- /** Every content report the client filed (#29), with the exact body it
65
- * sent. */
66
- reports = [];
67
- /** Every room `/createRoom` has made, in order -- for a test that asserts
68
- * what shape a DM was created in. */
69
- createdRooms = [];
70
- /** Every event this server has accepted from the client, in order -- for
71
- * a test that asserts what relation a reply was sent with. */
72
- sent = [];
73
- /** Every file the client has uploaded, by media id -- so a test can
74
- * assert what went up, and so the download route has something to
75
- * answer with. */
76
- media = new Map();
77
- /** Every media download this server has answered, with the header the
78
- * request carried -- for a test that asserts nothing reaches the
79
- * legacy unauthenticated endpoints, and that the token was sent. */
80
- mediaRequests = [];
81
- /** Who follows which thread, as `apps/chat-service`'s thread follow
82
- * route keeps it: `roomId rootId` -> whether the person unfollowed. A
83
- * thread with no entry is not followed. */
84
- threadFollows = new Map();
85
- /** What `apps/chat-service`'s `GET /_chat/status/{userId}` holds per
86
- * person: the automatic `meeting` overlay a call pushed. No entry reads
87
- * as `{ kind: null, sequence: 0 }`, as the real route does. */
88
- automaticStatuses = new Map();
89
- /** Every `PUT .../typing/...` this server has answered, in order -- for a
90
- * test that asserts `sendTyping` actually reached the wire, with what
91
- * it sent. */
92
- sentTyping = [];
93
- /** Every `PUT .../presence/{userId}/status` this server has answered, in
94
- * order -- the immediate half of `announcePresence`. */
95
- sentPresence = [];
96
- /** Set to refuse the next presence `PUT` with `M_LIMIT_EXCEEDED`, the
97
- * way a real Synapse refuses a second presence change inside ten
98
- * seconds (`rc_presence.per_user`). Clears itself after one refusal. */
99
- refuseNextPresence = false;
100
- /** The `set_presence` query parameter every `/sync` has carried, in
101
- * order, `undefined` where the client omitted it. This is the half that
102
- * actually makes an announcement survive, so a test that only checked
103
- * `sentPresence` would pass against a client that cannot hold anybody
104
- * away for longer than one poll. */
105
- syncPresence = [];
106
- /** Every `PUT`/`DELETE` on an MSC4133 extended-profile property this
107
- * server has answered, in order -- what `ChatClient.setOwnStatus`
108
- * writes. `value: undefined` records a delete. */
109
- extendedProfileWrites = [];
110
- /** Every `PUT .../sendToDevice/...` this server has answered, in order --
111
- * what a `CryptoApi` verification request (chat#69) sends on its way
112
- * out. Recorded rather than delivered to another device: the methods
113
- * this fake exists for (`getVerificationRequestsToDeviceInProgress`)
114
- * read the sender's own `OlmMachine` state, which only needs the send to
115
- * succeed, not to be received. */
116
- sentToDevice = [];
117
- /** Rooms currently carrying the room-scoped `dont_notify` push rule, for
118
- * a test that wants to assert on the server's own state rather than
119
- * only through the client's `rooms()`. */
120
- get mutedRoomIds() {
121
- return [...this.#mutedRooms];
122
- }
123
- /** Rooms currently carrying MSC2867's marked-unread flag, for a test that
124
- * wants to assert on the server's own state rather than only through the
125
- * client's `rooms()`. */
126
- get markedUnreadRoomIds() {
127
- return [...this.#markedUnread.entries()].filter(([, unread]) => unread).map(([id]) => id);
128
- }
129
- #dispose;
130
- #rooms;
131
- #tokenLifetimeMs;
132
- #now;
133
- #validTokens = new Set();
134
- #tokenSeq = 0;
135
- #batchSeq = 0;
136
- #eventSeq = 0;
137
- /** Every event's own place in this server's history, oldest first, keyed
138
- * by event id -- what `/search`'s "newest first" sorts by. Kept apart
139
- * from `#events` itself (rather than reading array position) so a
140
- * redaction rewriting an entry in place never disturbs where it sorts. */
141
- #insertOrder = new Map();
142
- #insertSeq = 0;
143
- #pending;
144
- #parkedWaiters = [];
145
- #disposed = false;
146
- #direct = {};
147
- /** User-level account data beyond `m.direct`, keyed by event type -- what
148
- * `CryptoApi.bootstrapSecretStorage` (chat#68) reads and writes through
149
- * `setAccountData`/`getAccountDataFromServer`. `m.direct` keeps its own
150
- * field above rather than moving in here: it has its own typed shape and
151
- * its own seeding from room members, and nothing about chat#67-69 needs
152
- * that to change. */
153
- #globalAccountData = new Map();
154
- /** Which device a minted token belongs to -- set at exchange time, read
155
- * by `/keys/upload` so an uploaded device's keys land under its own
156
- * device id rather than the fake account's single fixed `userId`. Both
157
- * `CryptoApi.bootstrapCrossSigning`'s own `resetCrossSigning` (chat#68,
158
- * through `CrossSigningIdentity.resetCrossSigning`'s plain
159
- * `uploadKeysRequest`) and a running `OlmMachine`'s regular background
160
- * upload (chat#69's device discovery) go through this one route. */
161
- #tokenDeviceId = new Map();
162
- /** Every device's own `device_keys` upload, keyed by device id -- what
163
- * `/keys/query` (chat#69) answers a querying device with, verbatim.
164
- * Verbatim matters: the Olm machine verifies the self-signature on
165
- * whatever `/keys/query` returns, so a fabricated or edited entry would
166
- * fail that check rather than prove device verification reaches a real
167
- * device. */
168
- #deviceKeysByDevice = new Map();
169
- /** The one server-side key backup this fake can hold at a time, or `null`
170
- * before `CryptoApi.resetKeyBackup` (chat#67) has ever created one, or
171
- * again once `disableKeyStorage`/a version delete removes it. Real
172
- * Synapse allows several historical versions; nothing this package does
173
- * reads an old one, so this fake only ever keeps the live one. */
174
- #keyBackup = null;
175
- #keyBackupSeq = 0;
176
- /** Every message event this server has ever had in a room, in order. The
177
- * full sync replays it, and `/event` and `/relations` are answered out
178
- * of it -- matrix-js-sdk asks for both while it builds a thread. */
179
- #events = new Map();
180
- #tags = new Map();
181
- /** Room-scoped account data a test or the client has set on a room,
182
- * keyed by room id then event type -- what `client.setDraft` and
183
- * `client.setRoomAccountData` more generally write, distinct from
184
- * `#tags`'s own `m.tag` shape. */
185
- #roomAccountData = new Map();
186
- /** Rooms carrying the account's room-scoped `dont_notify` push rule --
187
- * what `muteRoom` writes and takes away, and the only rule kind this
188
- * fake bothers to model. Read back through `/pushrules/`, exactly as
189
- * Synapse would answer it, so a test never has to reach past the
190
- * client's own `rooms()` to know a mute landed. */
191
- #mutedRooms = new Set();
192
- /** Rooms carrying MSC2867's marked-unread flag -- what `markRoomUnread`
193
- * writes as room-scoped account data under both `m.marked_unread` and
194
- * `com.famedly.marked_unread`. One value stands for both keys: a real
195
- * client never has a reason to disagree with itself about which key
196
- * means what it wrote. */
197
- #markedUnread = new Map();
198
- /** MSC4133 extended-profile properties, keyed by user id then property
199
- * key -- what `setOwnStatus` PUTs and DELETEs on the signed-in
200
- * account's own entry, and `status`'s background fetch GETs for
201
- * anyone. `seedExtendedProfile` writes another (peer) user's entry
202
- * directly, since real Matrix never lets a client set anyone's profile
203
- * but its own. */
204
- #extendedProfiles = new Map();
205
- #extendedProfilesEnabled;
206
- #roomSeq = 0;
207
- #mediaSeq = 0;
208
- /** Deliveries made while no poll was parked, waiting for the next one --
209
- * so a test never has to interleave its own `waitForParkedPoll()` with
210
- * a client call that itself writes and then waits for the echo. */
211
- #queued = [];
212
- constructor(options = {}) {
213
- this.homeserver =
214
- options.homeserver ?? `https://chat.${Math.random().toString(36).slice(2)}.example.test`;
215
- this.exchangeUrl = `${this.homeserver}/_chat/exchange`;
216
- this.userId = options.userId ?? '@zfake:chat.example.test';
217
- this.serverName = this.userId.split(':').slice(1).join(':');
218
- this.#rooms = [...(options.rooms ?? [])];
219
- this.#tokenLifetimeMs = options.tokenLifetimeMs ?? 10 * 60_000;
220
- this.#now = options.now ?? Date.now;
221
- this.#extendedProfilesEnabled = options.extendedProfilesEnabled ?? true;
222
- for (const room of this.#rooms)
223
- this.#materialise(room);
224
- for (const room of this.#rooms) {
225
- if (!room.isDirect)
226
- continue;
227
- for (const member of room.members?.length ? room.members : [{ userId: PEER_USER_ID }]) {
228
- this.#direct[member.userId] = [...(this.#direct[member.userId] ?? []), room.id];
229
- }
230
- }
231
- this.#dispose = installFetchRoute((input, init) => this.#route(input, init));
232
- }
233
- /** Sets `userId`'s MSC4133 extended-profile `key` directly, for a test
234
- * simulating "somebody else already has this set on the server" --
235
- * `ChatClient.status`'s background fetch then reads it exactly as it
236
- * would a real peer's. Real Matrix never lets a client PUT anyone's
237
- * profile but its own, which is why this exists as a server-side seed
238
- * rather than something `setOwnStatus` could reach. */
239
- seedExtendedProfile(userId, key, value) {
240
- let profile = this.#extendedProfiles.get(userId);
241
- if (!profile) {
242
- profile = new Map();
243
- this.#extendedProfiles.set(userId, profile);
244
- }
245
- profile.set(key, value);
246
- }
247
- dispose() {
248
- if (this.#disposed)
249
- return;
250
- this.#disposed = true;
251
- if (this.#pending) {
252
- const pending = this.#pending;
253
- this.#pending = undefined;
254
- pending.cleanup();
255
- pending.reject(new DOMException('The operation was aborted.', 'AbortError'));
256
- }
257
- this.#dispose();
258
- }
259
- /** Resolves once a `/sync` request is parked waiting for a test to drive
260
- * it -- immediately if one already is. */
261
- async waitForParkedPoll() {
262
- if (this.#pending)
263
- return;
264
- await new Promise((resolve) => this.#parkedWaiters.push(resolve));
265
- }
266
- /** Delivers a parked poll as if another of this account's own devices
267
- * had just written `type` room account data for `roomId` -- a draft,
268
- * most likely -- the way a real incremental `/sync` carries a change
269
- * made from elsewhere. Throws if nothing is parked -- await
270
- * `waitForParkedPoll()` first. */
271
- receiveRoomAccountData(roomId, type, content) {
272
- this.#storeRoomAccountData(roomId, type, content);
273
- const seed = this.#rooms.find((room) => room.id === roomId);
274
- if (!seed)
275
- return;
276
- this.#deliverParked({ [roomId]: this.#joinEntry(seed) });
277
- }
278
- /** Adds a room and, if a poll is parked, delivers it now. Throws if
279
- * nothing is parked -- await `waitForParkedPoll()` first. */
280
- addRoom(seed) {
281
- this.#rooms.push(seed);
282
- this.#materialise(seed);
283
- this.#deliverParked({ [seed.id]: this.#joinEntry(seed) });
284
- }
285
- /** Answers a parked poll with nothing new -- proving the connection is
286
- * healthy (a real incremental sync, just an empty one) without adding a
287
- * room. Throws if nothing is parked. */
288
- respondEmpty() {
289
- this.#deliverParked({});
290
- }
291
- /** Ends every currently-minted token, as if the person's session had been
292
- * revoked or the token had simply expired server-side. If a poll is
293
- * parked, it is answered with `M_UNKNOWN_TOKEN` immediately; otherwise
294
- * the next request to arrive gets it. */
295
- invalidateCurrentToken() {
296
- this.#validTokens.clear();
297
- if (!this.#pending)
298
- return;
299
- const pending = this.#pending;
300
- this.#pending = undefined;
301
- pending.cleanup();
302
- pending.resolve(jsonResponse(401, { errcode: 'M_UNKNOWN_TOKEN', error: 'Invalid access token' }));
303
- }
304
- /** Answers a parked poll with a `400`, as Synapse does when it refuses
305
- * the client's stored `since` position (confirmed live after a long
306
- * enough time offline). Throws if nothing is parked. */
307
- refuseCurrentPoll() {
308
- if (!this.#pending) {
309
- throw new Error('fake chat: refuseCurrentPoll called with no /sync request parked');
310
- }
311
- const pending = this.#pending;
312
- this.#pending = undefined;
313
- pending.cleanup();
314
- pending.resolve(jsonResponse(400, { errcode: 'M_UNKNOWN', error: 'Invalid pagination token' }));
315
- }
316
- /** Delivers a parked poll as an existing, already-known room receiving
317
- * one new message from the fake peer -- a timeline event and a bumped
318
- * notification count together, the way a real incremental `/sync`
319
- * carries both at once. `highlightCount` defaults to `0`: an ordinary
320
- * message that does not mention this account, same as Matrix would
321
- * report. Pass it to simulate a mention arriving. Returns the minted
322
- * event id, for a test that then calls `markRoomRead` against it.
323
- * Throws if nothing is parked. */
324
- receiveMessage(roomId, notificationCount = 1, highlightCount = 0) {
325
- this.#eventSeq += 1;
326
- const eventId = `$msg-${this.#eventSeq}`;
327
- this.#deliverParked({
328
- [roomId]: {
329
- summary: {},
330
- state: { events: [] },
331
- timeline: {
332
- events: [
333
- {
334
- type: 'm.room.message',
335
- event_id: eventId,
336
- sender: PEER_USER_ID,
337
- origin_server_ts: this.#now(),
338
- content: { msgtype: 'm.text', body: 'hi' },
339
- },
340
- ],
341
- limited: false,
342
- prev_batch: `t-${roomId}`,
343
- },
344
- ephemeral: { events: [] },
345
- account_data: { events: [] },
346
- unread_notifications: {
347
- highlight_count: highlightCount,
348
- notification_count: notificationCount,
349
- },
350
- },
351
- });
352
- return eventId;
353
- }
354
- /** Delivers a parked poll renaming an already-known room -- an
355
- * `m.room.name` state event, the way a real incremental `/sync` carries
356
- * a rename. Throws if nothing is parked. */
357
- renameRoom(roomId, name) {
358
- const seed = this.#rooms.find((room) => room.id === roomId);
359
- if (seed)
360
- seed.name = name;
361
- this.#eventSeq += 1;
362
- this.#deliverParked({
363
- [roomId]: {
364
- summary: {},
365
- state: {
366
- events: [
367
- {
368
- type: 'm.room.name',
369
- state_key: '',
370
- event_id: `$rename-${this.#eventSeq}`,
371
- sender: this.userId,
372
- origin_server_ts: this.#now(),
373
- content: { name },
374
- },
375
- ],
376
- },
377
- timeline: { events: [], limited: false, prev_batch: `t-${roomId}` },
378
- ephemeral: { events: [] },
379
- account_data: { events: [] },
380
- unread_notifications: { highlight_count: 0, notification_count: 0 },
381
- },
382
- });
383
- }
384
- /** Delivers a parked poll with the fake account leaving `roomId` -- a
385
- * `rooms.leave` block, the way a real incremental `/sync` reports a kick
386
- * or a self-leave. Throws if nothing is parked. */
387
- leaveRoom(roomId) {
388
- this.#rooms = this.#rooms.filter((room) => room.id !== roomId);
389
- this.#eventSeq += 1;
390
- this.#deliverParked({}, {
391
- [roomId]: {
392
- state: { events: [] },
393
- timeline: {
394
- events: [
395
- {
396
- type: 'm.room.member',
397
- state_key: this.userId,
398
- event_id: `$leave-${this.#eventSeq}`,
399
- sender: this.userId,
400
- origin_server_ts: this.#now(),
401
- content: { membership: 'leave' },
402
- },
403
- ],
404
- limited: false,
405
- prev_batch: `t-${roomId}`,
406
- },
407
- account_data: { events: [] },
408
- },
409
- });
410
- }
411
- #nextBatch() {
412
- this.#batchSeq += 1;
413
- return `batch-${this.#batchSeq}`;
414
- }
415
- #accountDataEvents() {
416
- const events = [];
417
- if (Object.keys(this.#direct).length) {
418
- events.push({ type: 'm.direct', content: { ...this.#direct } });
419
- }
420
- for (const [type, content] of this.#globalAccountData) {
421
- events.push({ type, content });
422
- }
423
- return events;
424
- }
425
- /** A room's own account data: the tags a test or the client has set on
426
- * it (`m.tag`, how `hideDirectMessage` reaches `room.tags`), MSC2867's
427
- * marked-unread flag under both keys `markRoomUnread` writes, plus
428
- * whatever else `#roomAccountData` holds -- a draft, most likely. */
429
- #roomAccountDataEvents(roomId) {
430
- const events = [];
431
- const tags = this.#tags.get(roomId);
432
- if (tags) {
433
- const content = {};
434
- for (const tag of tags)
435
- content[tag] = {};
436
- events.push({ type: 'm.tag', content: { tags: content } });
437
- }
438
- const unread = this.#markedUnread.get(roomId);
439
- if (unread !== undefined) {
440
- events.push({ type: 'm.marked_unread', content: { unread } });
441
- events.push({ type: 'com.famedly.marked_unread', content: { unread } });
442
- }
443
- for (const [type, content] of this.#roomAccountData.get(roomId) ?? []) {
444
- events.push({ type, content });
445
- }
446
- return events;
447
- }
448
- #memberEvent(seed, member, membership) {
449
- return {
450
- type: 'm.room.member',
451
- state_key: member.userId,
452
- event_id: `$member-${seed.id}-${member.userId}-${membership}`,
453
- sender: this.userId,
454
- origin_server_ts: this.#now(),
455
- content: {
456
- membership,
457
- displayname: member.name ?? member.userId,
458
- // 'dev.wtfalch.chat.guest' -- see `client.ts`'s `GUEST_MARKER_KEY`.
459
- ...(member.guestUntil !== undefined
460
- ? { 'dev.wtfalch.chat.guest': { until: member.guestUntil } }
461
- : {}),
462
- },
463
- };
464
- }
465
- #joinEntry(seed) {
466
- const now = this.#now();
467
- const events = [
468
- {
469
- type: 'm.room.create',
470
- state_key: '',
471
- event_id: `$create-${seed.id}`,
472
- sender: this.userId,
473
- origin_server_ts: now,
474
- // A space is a room whose create event carries `type: 'm.space'`;
475
- // that one field is the whole difference `isSpaceRoom()` reads.
476
- content: {
477
- creator: this.userId,
478
- room_version: '10',
479
- ...(seed.isSpace ? { type: 'm.space' } : {}),
480
- },
481
- },
482
- {
483
- type: 'm.room.member',
484
- state_key: this.userId,
485
- event_id: `$member-${seed.id}`,
486
- sender: this.userId,
487
- origin_server_ts: now,
488
- content: { membership: 'join' },
489
- },
490
- ];
491
- for (const member of seed.members ?? [])
492
- events.push(this.#memberEvent(seed, member, 'join'));
493
- for (const member of seed.invited ?? [])
494
- events.push(this.#memberEvent(seed, member, 'invite'));
495
- // Every seeded room carries an `m.room.name`, including a direct one.
496
- // A real member-created DM cannot: the Synapse gate refuses a `name`
497
- // from anyone but the chat admin, and Synapse names such a room from
498
- // its members instead. The fake names it up front so a story and a
499
- // test have something to read; nothing in the client depends on where
500
- // a room's name came from.
501
- events.push({
502
- type: 'm.room.name',
503
- state_key: '',
504
- event_id: `$name-${seed.id}`,
505
- sender: this.userId,
506
- origin_server_ts: now,
507
- content: { name: seed.name },
508
- });
509
- if (seed.encrypted) {
510
- events.push({
511
- type: 'm.room.encryption',
512
- state_key: '',
513
- event_id: `$encryption-${seed.id}`,
514
- sender: this.userId,
515
- origin_server_ts: now,
516
- content: { algorithm: 'm.megolm.v1.aes-sha2' },
517
- });
518
- }
519
- if (seed.archived) {
520
- events.push({
521
- type: 'm.room.power_levels',
522
- state_key: '',
523
- event_id: `$power-levels-${seed.id}`,
524
- sender: this.userId,
525
- origin_server_ts: now,
526
- content: { events_default: 100 },
527
- });
528
- }
529
- return {
530
- summary: {},
531
- state: { events },
532
- timeline: {
533
- events: this.#events.get(seed.id) ?? [],
534
- limited: false,
535
- prev_batch: `t-${seed.id}`,
536
- },
537
- ephemeral: { events: [] },
538
- account_data: { events: this.#roomAccountDataEvents(seed.id) },
539
- unread_notifications: {
540
- highlight_count: seed.highlightCount ?? 0,
541
- notification_count: seed.notificationCount ?? 0,
542
- },
543
- };
544
- }
545
- /** A room's invite-state entry: the stripped state real Matrix delivers
546
- * in `rooms.invite`, for a seed carrying `invitedAccount` -- the one
547
- * shape `membership: 'invite'` ever comes from, and the only entry with
548
- * no timeline of its own: a real invitee's client gets none to read
549
- * before joining, which is why `ChatRoomSummary.lastMessage` is always
550
- * `null` for such a room. `messages` on the seed is ignored, for the
551
- * same reason. */
552
- #inviteEntry(seed) {
553
- const now = this.#now();
554
- const inviter = seed.invitedAccount?.inviter ?? this.userId;
555
- const events = [
556
- {
557
- type: 'm.room.create',
558
- state_key: '',
559
- event_id: `$create-${seed.id}`,
560
- sender: inviter,
561
- origin_server_ts: now,
562
- content: { creator: inviter, room_version: '10' },
563
- },
564
- {
565
- type: 'm.room.name',
566
- state_key: '',
567
- event_id: `$name-${seed.id}`,
568
- sender: inviter,
569
- origin_server_ts: now,
570
- content: { name: seed.name },
571
- },
572
- {
573
- type: 'm.room.member',
574
- state_key: inviter,
575
- event_id: `$member-${seed.id}-inviter`,
576
- sender: inviter,
577
- origin_server_ts: now,
578
- content: { membership: 'join', displayname: inviter },
579
- },
580
- {
581
- type: 'm.room.member',
582
- state_key: this.userId,
583
- event_id: `$member-${seed.id}-self`,
584
- sender: inviter,
585
- origin_server_ts: now,
586
- content: { membership: 'invite', ...(seed.isDirect ? { is_direct: true } : {}) },
587
- },
588
- ];
589
- return { invite_state: { events } };
590
- }
591
- /** One `m.room.message`, threaded when the seed names a root. The
592
- * `m.thread` relation is the whole of what makes a reply a thread reply
593
- * -- matrix-js-sdk reads it off the event and routes it, exactly as it
594
- * does against Synapse. */
595
- #messageEvent(seed) {
596
- this.#eventSeq += 1;
597
- const { attachment } = seed;
598
- // `threadRootId` applies to either shape: a file shared inside a
599
- // thread is exactly as real as a text reply inside one, and a seed
600
- // that silently dropped it on the attachment branch would make it
601
- // impossible to test `roomFiles`' own thread-spanning behaviour
602
- // against this fixture at all (confirmed the hard way -- see the
603
- // refuter report this fixed).
604
- const threaded = seed.threadRootId
605
- ? { 'm.relates_to': { rel_type: 'm.thread', event_id: seed.threadRootId } }
606
- : {};
607
- return {
608
- type: 'm.room.message',
609
- event_id: seed.id ?? `$seeded-${this.#eventSeq}`,
610
- sender: seed.sender ?? PEER_USER_ID,
611
- origin_server_ts: this.#now(),
612
- content: attachment
613
- ? {
614
- msgtype: attachment.isImage ? 'm.image' : 'm.file',
615
- body: seed.body,
616
- url: attachment.mxcUri,
617
- info: { mimetype: attachment.mimeType, size: attachment.size },
618
- ...threaded,
619
- }
620
- : {
621
- msgtype: 'm.text',
622
- body: seed.body,
623
- ...threaded,
624
- },
625
- };
626
- }
627
- /** Mints a seed's messages once and remembers them. Minting them inside
628
- * `#joinEntry` instead would give the same seeded message a new id every
629
- * time an entry is rebuilt -- which happens on every tag change. */
630
- #materialise(seed) {
631
- if (this.#events.has(seed.id))
632
- return;
633
- const events = (seed.messages ?? []).map((message) => this.#messageEvent(message));
634
- this.#events.set(seed.id, events);
635
- for (const event of events)
636
- this.#insertOrder.set(event.event_id, this.#insertSeq++);
637
- }
638
- #record(roomId, event) {
639
- this.#events.set(roomId, [...(this.#events.get(roomId) ?? []), event]);
640
- this.#insertOrder.set(event.event_id, this.#insertSeq++);
641
- }
642
- /** One room's incremental entry, carrying just these events -- and,
643
- * given some, ephemeral ones (`m.typing`) alongside them, the way a real
644
- * incremental `/sync` carries both together. */
645
- #timelineEntry(roomId, events, ephemeralEvents = []) {
646
- return {
647
- summary: {},
648
- state: { events: [] },
649
- timeline: { events, limited: false, prev_batch: `t-${roomId}` },
650
- ephemeral: { events: ephemeralEvents },
651
- account_data: { events: this.#roomAccountDataEvents(roomId) },
652
- unread_notifications: { highlight_count: 0, notification_count: 0 },
653
- };
654
- }
655
- /** Delivers a parked poll as `m.typing` for `roomId` -- Matrix's own
656
- * shape: an EDU with no sender of its own, always the room's complete
657
- * current set of typing user ids, never a diff against the last one.
658
- * Pass an empty list for what Matrix does on its own once a typing
659
- * state's timeout elapses server-side; this fake never does that by
660
- * itself, so a test drives both halves explicitly. Throws if nothing is
661
- * parked. */
662
- receiveTyping(roomId, userIds) {
663
- this.#deliverParked({
664
- [roomId]: this.#timelineEntry(roomId, [], [{ type: 'm.typing', content: { user_ids: userIds } }]),
665
- });
666
- }
667
- /** Delivers a parked poll as `userId`'s public read receipt on
668
- * `eventId` in `roomId` -- the `m.receipt` EDU another person's client
669
- * causes by reading. Throws if nothing is parked. */
670
- receiveReceipt(roomId, eventId, userId) {
671
- this.#deliverParked({
672
- [roomId]: this.#timelineEntry(roomId, [], [
673
- {
674
- type: 'm.receipt',
675
- content: { [eventId]: { 'm.read': { [userId]: { ts: this.#now() } } } },
676
- },
677
- ]),
678
- });
679
- }
680
- /** Delivers a parked poll as an `m.presence` EDU for somebody else --
681
- * Matrix's own three states (`online`/`unavailable`/`offline`), or
682
- * MSC3026's unstable `org.matrix.msc3026.busy` -- for a test that drives
683
- * `presence()`/`onPresenceChanged` without a live homeserver. Presence
684
- * EDUs are account-wide, not room-scoped, so this carries no room id --
685
- * see `#answerParked`'s own `presence.events`. Throws if nothing is
686
- * parked. */
687
- receivePresence(userId, presence) {
688
- this.#deliverParked({}, {}, [{ type: 'm.presence', sender: userId, content: { presence } }]);
689
- }
690
- /** Delivers a parked poll as somebody else reacting to a message.
691
- * Returns the minted event id, so a test can then redact it. Throws if
692
- * nothing is parked. */
693
- receiveReaction(roomId, targetId, key, sender = PEER_USER_ID) {
694
- this.#eventSeq += 1;
695
- const event = {
696
- type: 'm.reaction',
697
- event_id: `$react-${this.#eventSeq}`,
698
- sender,
699
- origin_server_ts: this.#now(),
700
- content: { 'm.relates_to': { rel_type: 'm.annotation', event_id: targetId, key } },
701
- };
702
- this.#record(roomId, event);
703
- this.#deliverParked({ [roomId]: this.#timelineEntry(roomId, [event]) });
704
- return event.event_id;
705
- }
706
- /** Delivers a parked poll as one more message arriving in an existing
707
- * room -- threaded, when `threadRootId` is given. Returns the minted
708
- * event id. Throws if nothing is parked. */
709
- receiveThreadReply(roomId, threadRootId, body = 'a reply') {
710
- const event = this.#messageEvent({ body, threadRootId });
711
- this.#record(roomId, event);
712
- this.#deliverParked({
713
- [roomId]: {
714
- summary: {},
715
- state: { events: [] },
716
- timeline: { events: [event], limited: false, prev_batch: `t-${roomId}` },
717
- ephemeral: { events: [] },
718
- account_data: { events: this.#roomAccountDataEvents(roomId) },
719
- unread_notifications: { highlight_count: 0, notification_count: 0 },
720
- },
721
- });
722
- return event.event_id;
723
- }
724
- /** Delivers a parked poll as somebody else editing one of their own
725
- * messages: an `m.replace` carrying `m.new_content`, which is the whole
726
- * of how Matrix edits a message. Returns the edit's own event id.
727
- * Throws if nothing is parked. */
728
- receiveEdit(roomId, targetId, body, sender = PEER_USER_ID) {
729
- this.#eventSeq += 1;
730
- const event = {
731
- type: 'm.room.message',
732
- event_id: `$edit-${this.#eventSeq}`,
733
- sender,
734
- origin_server_ts: this.#now(),
735
- content: {
736
- msgtype: 'm.text',
737
- body: `* ${body}`,
738
- 'm.new_content': { msgtype: 'm.text', body },
739
- 'm.relates_to': { rel_type: 'm.replace', event_id: targetId },
740
- },
741
- };
742
- this.#record(roomId, event);
743
- this.#deliverParked({ [roomId]: this.#timelineEntry(roomId, [event]) });
744
- return event.event_id;
745
- }
746
- /** Delivers a parked poll as a message being redacted. The target keeps
747
- * its place in the room's record with its content emptied, exactly as
748
- * `#route`'s own redact endpoint does and as Synapse does -- a redacted
749
- * event is still an event. Throws if nothing is parked. */
750
- receiveRedaction(roomId, targetId, sender = PEER_USER_ID) {
751
- this.#eventSeq += 1;
752
- const event = {
753
- type: 'm.room.redaction',
754
- event_id: `$redact-${this.#eventSeq}`,
755
- sender,
756
- origin_server_ts: this.#now(),
757
- content: {},
758
- redacts: targetId,
759
- };
760
- this.#events.set(roomId, (this.#events.get(roomId) ?? []).map((entry) => entry.event_id === targetId ? { ...entry, content: {} } : entry));
761
- this.#record(roomId, event);
762
- this.#deliverParked({ [roomId]: this.#timelineEntry(roomId, [event]) });
763
- return event.event_id;
764
- }
765
- #fullSyncBody() {
766
- const join = {};
767
- const invite = {};
768
- for (const room of this.#rooms) {
769
- if (room.invitedAccount)
770
- invite[room.id] = this.#inviteEntry(room);
771
- else
772
- join[room.id] = this.#joinEntry(room);
773
- }
774
- return {
775
- next_batch: this.#nextBatch(),
776
- rooms: { join, invite },
777
- account_data: { events: this.#accountDataEvents() },
778
- presence: { events: [] },
779
- to_device: { events: this.#drainToDevice() },
780
- };
781
- }
782
- /** The device ids that have uploaded `device_keys` so far. */
783
- uploadedDeviceIds() {
784
- return [...this.#deviceKeysByDevice.keys()];
785
- }
786
- /** To-device events waiting for the next `/sync` this account answers --
787
- * see `deliverToDevice`. */
788
- #toDeviceQueue = [];
789
- #drainToDevice() {
790
- return this.#toDeviceQueue.splice(0);
791
- }
792
- /** Delivers to-device events (a verification request, say) to the one
793
- * client this fake serves, on its next `/sync` -- straight away if a poll
794
- * is parked. Each event is `{ type, sender, content }`. Only one client
795
- * can be answered at a time: this fake has a single parked poll, so it
796
- * cannot route a to-device message from one live client to another, and
797
- * `sendToDevice` writes stay recorded in `sentToDevice` only. */
798
- deliverToDevice(events) {
799
- this.#toDeviceQueue.push(...events);
800
- this.#deliverOrQueue({});
801
- }
802
- #deliverParked(join, leave = {}, presenceEvents = []) {
803
- if (!this.#pending) {
804
- throw new Error('fake chat: addRoom called with no /sync request parked');
805
- }
806
- this.#answerParked(join, leave, presenceEvents);
807
- }
808
- /** Delivers now if a poll is parked, and otherwise holds the payload for
809
- * the next one. What `#deliverParked` refuses to do: a test driving the
810
- * server by hand wants the throw, because "nothing was parked" means its
811
- * own sequencing is wrong -- but a write the *client* made (a tag, an
812
- * `m.direct` update, a created room) is answered whenever the client
813
- * next polls, exactly as Synapse would. */
814
- #deliverOrQueue(join, leave = {}) {
815
- if (this.#pending) {
816
- this.#answerParked(join, leave);
817
- return;
818
- }
819
- this.#queued.push({ join, leave });
820
- }
821
- #answerParked(join, leave, presenceEvents = []) {
822
- const pending = this.#pending;
823
- if (!pending)
824
- return;
825
- this.#pending = undefined;
826
- pending.cleanup();
827
- pending.resolve(jsonResponse(200, {
828
- next_batch: this.#nextBatch(),
829
- rooms: { join, leave },
830
- account_data: { events: this.#accountDataEvents() },
831
- presence: { events: presenceEvents },
832
- to_device: { events: this.#drainToDevice() },
833
- }));
834
- }
835
- /** The fake account's own view of a created direct room: the invitees
836
- * are invited, nobody else has joined yet, and it carries whatever tags
837
- * it has picked up. */
838
- #createRoom(body) {
839
- this.#roomSeq += 1;
840
- const id = `!created-${this.#roomSeq}:${new URL(this.homeserver).host}`;
841
- const invited = (body.invite ?? []).map((userId) => ({ userId }));
842
- const seed = {
843
- id,
844
- name: invited.map((member) => member.userId).join(', ') || 'New room',
845
- isDirect: Boolean(body.is_direct),
846
- invited,
847
- };
848
- this.#rooms.push(seed);
849
- this.#materialise(seed);
850
- this.createdRooms.push({ id, isDirect: Boolean(body.is_direct), invite: body.invite ?? [] });
851
- this.#deliverOrQueue({ [id]: this.#joinEntry(seed) });
852
- return id;
853
- }
854
- #setTag(roomId, tag, on) {
855
- const tags = this.#tags.get(roomId) ?? new Set();
856
- if (on)
857
- tags.add(tag);
858
- else
859
- tags.delete(tag);
860
- this.#tags.set(roomId, tags);
861
- const seed = this.#rooms.find((room) => room.id === roomId);
862
- if (seed)
863
- this.#deliverOrQueue({ [roomId]: this.#joinEntry(seed) });
864
- }
865
- /** What `markRoomUnread` PUTs, under either key it writes -- see
866
- * `ChatClient.markRoomUnread`. Echoed back the same way `#setTag` echoes
867
- * a tag: as part of the room's own next join entry, so a client that
868
- * actually reads its account data off `/sync` (rather than trusting its
869
- * own local echo) sees the same answer. */
870
- #setMarkedUnread(roomId, unread) {
871
- this.#markedUnread.set(roomId, unread);
872
- const seed = this.#rooms.find((room) => room.id === roomId);
873
- if (seed)
874
- this.#deliverOrQueue({ [roomId]: this.#joinEntry(seed) });
875
- }
876
- #storeRoomAccountData(roomId, type, content) {
877
- const forRoom = this.#roomAccountData.get(roomId) ?? new Map();
878
- forRoom.set(type, content);
879
- this.#roomAccountData.set(roomId, forRoom);
880
- }
881
- /** What `PUT .../rooms/{roomId}/account_data/{type}` writes -- a draft,
882
- * most likely. Delivered back through the room's `join` entry exactly
883
- * like `#setTag`, so the writing client's own next poll sees it the
884
- * same way real Matrix account data comes back through `/sync`. */
885
- #setRoomAccountData(roomId, type, content) {
886
- this.#storeRoomAccountData(roomId, type, content);
887
- const seed = this.#rooms.find((room) => room.id === roomId);
888
- if (seed)
889
- this.#deliverOrQueue({ [roomId]: this.#joinEntry(seed) });
890
- }
891
- #handleExchange(init) {
892
- this.exchangeCount += 1;
893
- const zitadelToken = bearerToken(init);
894
- if (!zitadelToken) {
895
- return Promise.resolve(jsonResponse(401, { reason: 'token_expired' }));
896
- }
897
- let deviceId = 'fake-device';
898
- try {
899
- const body = JSON.parse(String(init?.body ?? '{}'));
900
- if (typeof body.device_id === 'string')
901
- deviceId = body.device_id;
902
- }
903
- catch {
904
- // Malformed body: fall through with the default device id, same as
905
- // any other field this fake does not validate strictly.
906
- }
907
- const token = `fake-matrix-token-${++this.#tokenSeq}`;
908
- this.#validTokens.add(token);
909
- this.mintedTokens.push(token);
910
- this.#tokenDeviceId.set(token, deviceId);
911
- return Promise.resolve(jsonResponse(200, {
912
- homeserver: this.homeserver,
913
- user_id: this.userId,
914
- device_id: deviceId,
915
- access_token: token,
916
- expires_at: new Date(this.#now() + this.#tokenLifetimeMs).toISOString(),
917
- }));
918
- }
919
- #authorised(init) {
920
- const token = bearerToken(init);
921
- return Boolean(token && this.#validTokens.has(token));
922
- }
923
- #handleSync(url, init) {
924
- const token = bearerToken(init);
925
- if (!token || !this.#validTokens.has(token)) {
926
- return Promise.resolve(jsonResponse(401, { errcode: 'M_UNKNOWN_TOKEN', error: 'Invalid access token' }));
927
- }
928
- this.syncPresence.push(url.searchParams.get('set_presence') ?? undefined);
929
- if (url.searchParams.get('since') === null) {
930
- return Promise.resolve(jsonResponse(200, this.#fullSyncBody()));
931
- }
932
- const queued = this.#queued.shift();
933
- if (queued) {
934
- return Promise.resolve(jsonResponse(200, {
935
- next_batch: this.#nextBatch(),
936
- rooms: { join: queued.join, leave: queued.leave },
937
- account_data: { events: this.#accountDataEvents() },
938
- presence: { events: [] },
939
- to_device: { events: this.#drainToDevice() },
940
- }));
941
- }
942
- return new Promise((resolve, reject) => {
943
- const signal = init?.signal;
944
- const onAbort = () => {
945
- this.#pending = undefined;
946
- signal?.removeEventListener('abort', onAbort);
947
- reject(new DOMException('The operation was aborted.', 'AbortError'));
948
- };
949
- signal?.addEventListener('abort', onAbort);
950
- this.#pending = {
951
- resolve: (response) => {
952
- signal?.removeEventListener('abort', onAbort);
953
- resolve(response);
954
- },
955
- reject,
956
- cleanup: () => signal?.removeEventListener('abort', onAbort),
957
- };
958
- const waiters = this.#parkedWaiters;
959
- this.#parkedWaiters = [];
960
- for (const waiter of waiters)
961
- waiter();
962
- });
963
- }
964
- #route(input, init) {
965
- const rawUrl = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
966
- if (rawUrl.startsWith(this.exchangeUrl))
967
- return this.#handleExchange(init);
968
- if (!rawUrl.startsWith(this.homeserver))
969
- return null;
970
- const url = new URL(rawUrl);
971
- if (url.pathname === '/_matrix/client/versions') {
972
- return Promise.resolve(jsonResponse(200, {
973
- versions: ['v1.4'],
974
- // Only the unstable flag, never `.stable` -- `doesServerSupport
975
- // ExtendedProfiles` reads either, but `getExtendedProfileRequest
976
- // Prefix` only takes the `/_matrix/client/v3` path for `.stable`
977
- // or a real v1.16, so this keeps every extended-profile request
978
- // on the `/_matrix/client/unstable/uk.tcpip.msc4133` prefix the
979
- // route below answers -- the same "off by default" MSC4133 gate
980
- // `docs/status.md` describes for real Synapse.
981
- unstable_features: { 'uk.tcpip.msc4133': this.#extendedProfilesEnabled },
982
- }));
983
- }
984
- if (url.pathname === '/_matrix/client/v3/pushrules/') {
985
- return Promise.resolve(jsonResponse(200, {
986
- global: {
987
- content: [],
988
- override: [],
989
- room: [...this.#mutedRooms].map((roomId) => ({
990
- rule_id: roomId,
991
- default: false,
992
- enabled: true,
993
- actions: ['dont_notify'],
994
- })),
995
- sender: [],
996
- underride: [],
997
- },
998
- }));
999
- }
1000
- // What `setRoomMutePushRule` PUTs and DELETEs -- see `ChatClient.muteRoom`.
1001
- // This fake only ever sees `'global'`, the one scope the client uses, but
1002
- // matches on it anyway rather than any scope: a client that started
1003
- // writing device-scoped rules should fail here, not be quietly muted.
1004
- const roomPushRule = url.pathname.match(/^\/_matrix\/client\/v3\/pushrules\/global\/room\/([^/]+)$/);
1005
- if (roomPushRule && this.#authorised(init)) {
1006
- const roomId = decodeURIComponent(roomPushRule[1]);
1007
- if (init?.method === 'DELETE') {
1008
- if (!this.#mutedRooms.has(roomId)) {
1009
- return Promise.resolve(jsonResponse(404, { errcode: 'M_NOT_FOUND', error: 'Push rule does not exist' }));
1010
- }
1011
- this.#mutedRooms.delete(roomId);
1012
- }
1013
- else {
1014
- this.#mutedRooms.add(roomId);
1015
- }
1016
- return Promise.resolve(jsonResponse(200, {}));
1017
- }
1018
- if (url.pathname.startsWith('/_matrix/client/v3/user/') && url.pathname.endsWith('/filter')) {
1019
- return Promise.resolve(jsonResponse(200, { filter_id: 'fake-filter' }));
1020
- }
1021
- if (url.pathname === '/_matrix/client/v3/sync') {
1022
- return this.#handleSync(url, init);
1023
- }
1024
- if (url.pathname === '/_matrix/client/v3/createRoom' && this.#authorised(init)) {
1025
- let body = {};
1026
- try {
1027
- body = JSON.parse(String(init?.body ?? '{}'));
1028
- }
1029
- catch {
1030
- // Same tolerance as the exchange: a malformed body creates a plain
1031
- // room rather than failing a test for a reason it did not choose.
1032
- }
1033
- // What the Synapse gate does to a member-created room dressed as a
1034
- // channel (chat plan section 5). The fake refuses it for the same
1035
- // reason: a client that starts sending a `name` should fail here
1036
- // rather than in production.
1037
- if (body.name !== undefined) {
1038
- return Promise.resolve(jsonResponse(403, { errcode: 'M_FORBIDDEN', error: 'Not allowed' }));
1039
- }
1040
- return Promise.resolve(jsonResponse(200, { room_id: this.#createRoom(body) }));
1041
- }
1042
- // What matrix-js-sdk asks for while it builds a thread: the root event
1043
- // itself, and everything related to it.
1044
- const event = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/event\/([^/]+)$/);
1045
- if (event && this.#authorised(init)) {
1046
- const roomId = decodeURIComponent(event[1]);
1047
- const eventId = decodeURIComponent(event[2]);
1048
- const found = this.#events.get(roomId)?.find((entry) => entry.event_id === eventId);
1049
- return Promise.resolve(found
1050
- ? jsonResponse(200, { ...found, room_id: roomId })
1051
- : jsonResponse(404, { errcode: 'M_NOT_FOUND', error: 'Event not found' }));
1052
- }
1053
- const relations = url.pathname.match(/^\/_matrix\/client\/v1\/rooms\/([^/]+)\/relations\/([^/]+)(?:\/([^/]+))?(?:\/([^/]+))?$/);
1054
- if (relations && this.#authorised(init)) {
1055
- const roomId = decodeURIComponent(relations[1]);
1056
- const targetId = decodeURIComponent(relations[2]);
1057
- const relType = relations[3] ? decodeURIComponent(relations[3]) : undefined;
1058
- const chunk = (this.#events.get(roomId) ?? []).filter((entry) => {
1059
- const relatesTo = entry.content['m.relates_to'];
1060
- if (relatesTo?.event_id !== targetId)
1061
- return false;
1062
- return relType === undefined || relatesTo.rel_type === relType;
1063
- });
1064
- // No `next_batch`: everything this fake has is in one page, so the
1065
- // thread's own back-pagination token ends up `null` and `hasMore`
1066
- // reads false -- which is what a fully-loaded thread should say.
1067
- return Promise.resolve(jsonResponse(200, { chunk: chunk.map((entry) => ({ ...entry, room_id: roomId })) }));
1068
- }
1069
- // `roomFiles`' own backward walk, and `paginate`'s plain scrollback:
1070
- // both are `GET .../messages`, and the only thing that tells them
1071
- // apart on the wire is whether a `contains_url` filter came along.
1072
- // `#events` is oldest first, so this reverses it once and paginates
1073
- // with a plain numeric cursor -- there is no real Matrix stream token
1074
- // to imitate here, only "how far back has this walk gone".
1075
- const messages = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/messages$/);
1076
- if (messages && this.#authorised(init)) {
1077
- const roomId = decodeURIComponent(messages[1]);
1078
- let filter = {};
1079
- try {
1080
- const raw = url.searchParams.get('filter');
1081
- if (raw)
1082
- filter = JSON.parse(raw);
1083
- }
1084
- catch {
1085
- // Same tolerance as every other body/param this fake parses.
1086
- }
1087
- const newestFirst = [...(this.#events.get(roomId) ?? [])].reverse();
1088
- // Not what real Synapse does. `entry.content.url` is read live, here,
1089
- // on every call -- so a redacted event (`#record`'s content already
1090
- // emptied, see the `redact` route above) simply has no `url` left to
1091
- // match by the time this runs. Real Synapse computes `contains_url`
1092
- // once, at persist time, and never revisits it on redaction (checked
1093
- // against the installed v1.161.0 source), so a redacted file-bearing
1094
- // event still *matches* the filter there and still comes back from
1095
- // `/messages` -- pruned, but present. `roomFiles`' own
1096
- // `event.isRedacted()` guard is what excludes it in production. A
1097
- // unit test built on this fake exercises that a redacted file is
1098
- // excluded, but not *why* -- `test/integration/roomfiles.test.ts`'s
1099
- // real-Synapse redaction case is what actually proves the guard.
1100
- const matching = newestFirst.filter((entry) => {
1101
- if (filter.types && !filter.types.includes(entry.type))
1102
- return false;
1103
- if (filter.contains_url && entry.content.url === undefined)
1104
- return false;
1105
- return true;
1106
- });
1107
- const limit = Number(url.searchParams.get('limit') ?? '30');
1108
- const from = url.searchParams.get('from');
1109
- const start = from?.startsWith('idx-') ? Number(from.slice('idx-'.length)) : 0;
1110
- const chunk = matching.slice(start, start + limit);
1111
- const nextIndex = start + chunk.length;
1112
- const end = nextIndex < matching.length ? `idx-${nextIndex}` : undefined;
1113
- return Promise.resolve(jsonResponse(200, {
1114
- chunk: chunk.map((entry) => ({ ...entry, room_id: roomId })),
1115
- ...(end ? { end } : {}),
1116
- }));
1117
- }
1118
- // `ChatClient.search`'s own wire call (agora#252, agora#31): a plain
1119
- // case-insensitive substring match over every `m.room.message` body
1120
- // this fake has recorded, newest first, scoped to `filter.rooms` when
1121
- // the client sent one. Reads `#events` live rather than a snapshot
1122
- // taken at record time, so a redacted message (its content already
1123
- // emptied by the `redact` route) stops matching immediately, the same
1124
- // as a real search index would once Synapse's own redaction handling
1125
- // catches up to it. `next_batch` pages a deliberately small five at a
1126
- // time, so a unit test can prove `search`'s own paging without seeding
1127
- // hundreds of messages.
1128
- //
1129
- // An encrypted room's messages never match. This fake stores every
1130
- // body as plain text regardless of `encrypted` -- there is no real
1131
- // Megolm session here to encrypt against -- but a real Synapse never
1132
- // has a cleartext body to index for such a room in the first place, so
1133
- // a fake that let one match would prove `search` filters encrypted
1134
- // rooms out itself, which is exactly what it must not do (the fake's
1135
- // own module comment, and `ChatSearchResults`).
1136
- if (url.pathname === '/_matrix/client/v3/search' &&
1137
- init?.method === 'POST' &&
1138
- this.#authorised(init)) {
1139
- let body = {};
1140
- try {
1141
- body = JSON.parse(String(init?.body ?? '{}'));
1142
- }
1143
- catch {
1144
- // Same tolerance as every other body this fake parses.
1145
- }
1146
- const term = (body.search_categories?.room_events?.search_term ?? '').toLowerCase();
1147
- const roomFilter = body.search_categories?.room_events?.filter?.rooms;
1148
- const encryptedRoomIds = new Set(this.#rooms.filter((room) => room.encrypted).map((room) => room.id));
1149
- const flattened = [];
1150
- for (const [roomId, events] of this.#events) {
1151
- if (roomFilter && !roomFilter.includes(roomId))
1152
- continue;
1153
- if (encryptedRoomIds.has(roomId))
1154
- continue;
1155
- for (const event of events)
1156
- flattened.push({ roomId, event });
1157
- }
1158
- const matches = flattened
1159
- .filter((entry) => entry.event.type === 'm.room.message')
1160
- .filter((entry) => {
1161
- const value = entry.event.content.body;
1162
- return typeof value === 'string' && value.toLowerCase().includes(term);
1163
- })
1164
- .sort((a, b) => (this.#insertOrder.get(b.event.event_id) ?? 0) -
1165
- (this.#insertOrder.get(a.event.event_id) ?? 0));
1166
- const pageSize = 5;
1167
- const from = url.searchParams.get('next_batch');
1168
- const start = from?.startsWith('idx-') ? Number(from.slice('idx-'.length)) : 0;
1169
- const chunk = matches.slice(start, start + pageSize);
1170
- const nextIndex = start + chunk.length;
1171
- const nextBatch = nextIndex < matches.length ? `idx-${nextIndex}` : undefined;
1172
- return Promise.resolve(jsonResponse(200, {
1173
- search_categories: {
1174
- room_events: {
1175
- count: matches.length,
1176
- results: chunk.map((entry) => ({
1177
- rank: 1,
1178
- result: { ...entry.event, room_id: entry.roomId },
1179
- })),
1180
- highlights: [],
1181
- ...(nextBatch ? { next_batch: nextBatch } : {}),
1182
- },
1183
- },
1184
- }));
1185
- }
1186
- const send = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/send\/([^/]+)\/([^/]+)$/);
1187
- if (send && this.#authorised(init)) {
1188
- if (this.sendStatus !== 200) {
1189
- return Promise.resolve(jsonResponse(this.sendStatus, { errcode: 'M_FORBIDDEN' }));
1190
- }
1191
- let content = {};
1192
- try {
1193
- content = JSON.parse(String(init?.body ?? '{}'));
1194
- }
1195
- catch {
1196
- // Same tolerance as everywhere else here: a malformed body is
1197
- // accepted with nothing in it rather than failing the test.
1198
- }
1199
- const roomId = decodeURIComponent(send[1]);
1200
- const type = decodeURIComponent(send[2]);
1201
- const txnId = decodeURIComponent(send[3]);
1202
- this.#eventSeq += 1;
1203
- const eventId = `$sent-${this.#eventSeq}`;
1204
- this.sent.push({ roomId, eventId, type, content });
1205
- // Echoed back through sync, the way a homeserver does, carrying the
1206
- // transaction id so matrix-js-sdk resolves its own local echo rather
1207
- // than showing the message twice. Without the echo a reaction would
1208
- // never appear at all: only `m.room.message` has a local echo, and a
1209
- // reaction is aggregated out of what sync delivers.
1210
- const event = {
1211
- type,
1212
- event_id: eventId,
1213
- sender: this.userId,
1214
- origin_server_ts: this.#now(),
1215
- content,
1216
- unsigned: { transaction_id: txnId },
1217
- };
1218
- this.#record(roomId, event);
1219
- this.#deliverOrQueue({ [roomId]: this.#timelineEntry(roomId, [event]) });
1220
- return Promise.resolve(jsonResponse(200, { event_id: eventId }));
1221
- }
1222
- const redact = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/redact\/([^/]+)\/([^/]+)$/);
1223
- if (redact && this.#authorised(init)) {
1224
- const roomId = decodeURIComponent(redact[1]);
1225
- const target = decodeURIComponent(redact[2]);
1226
- this.#eventSeq += 1;
1227
- const event = {
1228
- type: 'm.room.redaction',
1229
- event_id: `$redact-${this.#eventSeq}`,
1230
- sender: this.userId,
1231
- origin_server_ts: this.#now(),
1232
- content: {},
1233
- redacts: target,
1234
- };
1235
- // The redacted event stays in the room's record with its content
1236
- // emptied, which is what Synapse does and what makes a taken-back
1237
- // reaction stop counting rather than vanish from `/relations`.
1238
- const events = (this.#events.get(roomId) ?? []).map((entry) => entry.event_id === target ? { ...entry, content: {} } : entry);
1239
- this.#events.set(roomId, events);
1240
- this.#record(roomId, event);
1241
- this.#deliverOrQueue({ [roomId]: this.#timelineEntry(roomId, [event]) });
1242
- return Promise.resolve(jsonResponse(200, { event_id: event.event_id }));
1243
- }
1244
- // `sendStateEvent`'s own default state key is `''`, never `undefined`
1245
- // (see matrix-js-sdk's `client.js`), so the path this mints always
1246
- // carries the trailing, empty state-key segment.
1247
- const pinnedEvents = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/state\/m\.room\.pinned_events\/?$/);
1248
- if (pinnedEvents && this.#authorised(init)) {
1249
- if (this.pinStatus !== 200) {
1250
- return Promise.resolve(jsonResponse(this.pinStatus, { errcode: 'M_FORBIDDEN', error: 'pinning refused' }));
1251
- }
1252
- let content = {};
1253
- try {
1254
- content = JSON.parse(String(init?.body ?? '{}'));
1255
- }
1256
- catch {
1257
- // Same tolerance as every other route here.
1258
- }
1259
- const roomId = decodeURIComponent(pinnedEvents[1]);
1260
- this.#eventSeq += 1;
1261
- const event = {
1262
- type: 'm.room.pinned_events',
1263
- state_key: '',
1264
- event_id: `$pinned-${this.#eventSeq}`,
1265
- sender: this.userId,
1266
- origin_server_ts: this.#now(),
1267
- content,
1268
- };
1269
- this.#record(roomId, event);
1270
- this.#deliverOrQueue({ [roomId]: this.#timelineEntry(roomId, [event]) });
1271
- return Promise.resolve(jsonResponse(200, { event_id: event.event_id }));
1272
- }
1273
- // Uploads go to `/_matrix/media/v3/upload`, which is still the
1274
- // upload endpoint under authenticated media -- only *downloads* moved
1275
- // to `/_matrix/client/v1/media`.
1276
- if (url.pathname === '/_matrix/media/v3/upload' && this.#authorised(init)) {
1277
- this.#mediaSeq += 1;
1278
- const mediaId = `media-${this.#mediaSeq}`;
1279
- const body = init?.body;
1280
- return (async () => {
1281
- await this.uploadBarrier;
1282
- if (init?.signal?.aborted)
1283
- throw new DOMException('Aborted', 'AbortError');
1284
- if (this.uploadStatus !== 200)
1285
- return jsonResponse(this.uploadStatus, {
1286
- errcode: 'M_FORBIDDEN',
1287
- error: 'upload refused',
1288
- });
1289
- const bytes = body instanceof Blob
1290
- ? await body.arrayBuffer()
1291
- : body instanceof ArrayBuffer
1292
- ? body
1293
- : ArrayBuffer.isView(body)
1294
- ? body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength)
1295
- : new ArrayBuffer(0);
1296
- const contentType = new Headers(init?.headers).get('content-type') ?? '';
1297
- this.media.set(mediaId, { bytes, contentType });
1298
- return jsonResponse(200, { content_uri: `mxc://${this.serverName}/${mediaId}` });
1299
- })();
1300
- }
1301
- const chatStatus = url.pathname.match(/^\/_chat\/status\/([^/]+)$/);
1302
- if (chatStatus) {
1303
- if (!this.#authorised(init)) {
1304
- return Promise.resolve(jsonResponse(401, { error: 'token_invalid' }));
1305
- }
1306
- const found = this.automaticStatuses.get(decodeURIComponent(chatStatus[1]));
1307
- return Promise.resolve(jsonResponse(200, found ?? { kind: null, sequence: 0 }));
1308
- }
1309
- // `apps/chat-service`'s thread follow route: the same rule the real one
1310
- // has -- an automatic follow never undoes an unfollow.
1311
- const chatThread = url.pathname.match(/^\/_chat\/threads\/([^/]+)\/([^/]+)\/follow$/);
1312
- if (chatThread) {
1313
- if (!this.#authorised(init)) {
1314
- return Promise.resolve(jsonResponse(401, { error: 'token_invalid' }));
1315
- }
1316
- const roomId = decodeURIComponent(chatThread[1]);
1317
- if (!this.#rooms.some((room) => room.id === roomId)) {
1318
- return Promise.resolve(jsonResponse(403, { error: 'not_a_member' }));
1319
- }
1320
- const rootId = decodeURIComponent(chatThread[2]);
1321
- const key = `${roomId} ${rootId}`;
1322
- const method = init?.method ?? 'GET';
1323
- this.threadFollowRequests.push({ method, roomId, rootId });
1324
- if (method === 'GET') {
1325
- // The answer is what was true when the request arrived, however
1326
- // long the barrier holds it.
1327
- const barrier = this.threadFollowReadBarrier;
1328
- const status = this.threadFollowReadStatus;
1329
- const found = this.threadFollows.get(key);
1330
- return (async () => {
1331
- await barrier;
1332
- if (status !== 200)
1333
- return jsonResponse(status, { error: 'internal_error' });
1334
- return jsonResponse(200, { following: found !== undefined && !found.muted });
1335
- })();
1336
- }
1337
- if (this.threadFollowWriteStatus !== 200) {
1338
- return Promise.resolve(jsonResponse(this.threadFollowWriteStatus, { error: 'internal_error' }));
1339
- }
1340
- if (method === 'DELETE')
1341
- this.threadFollows.set(key, { muted: true });
1342
- if (method === 'PUT') {
1343
- const auto = JSON.parse(String(init?.body ?? '{}')).auto === true;
1344
- if (!auto || !this.threadFollows.has(key))
1345
- this.threadFollows.set(key, { muted: false });
1346
- }
1347
- const found = this.threadFollows.get(key);
1348
- return Promise.resolve(jsonResponse(200, { following: found !== undefined && !found.muted }));
1349
- }
1350
- // `apps/chat-service`'s media proxy (wtfalch/chat#32). The same two
1351
- // checks the real one makes: the account is still in `roomId`, and
1352
- // `eventId` is a message sent there that references this media.
1353
- const chatMedia = url.pathname.match(/^\/_chat\/media\/([^/]+)\/([^/]+)$/);
1354
- if (chatMedia) {
1355
- const authorised = this.#authorised(init);
1356
- this.mediaRequests.push({ path: url.pathname, authorised });
1357
- if (!authorised) {
1358
- return Promise.resolve(jsonResponse(401, { error: 'token_invalid' }));
1359
- }
1360
- const roomId = url.searchParams.get('roomId');
1361
- const eventId = url.searchParams.get('eventId');
1362
- if (!roomId || !this.#rooms.some((room) => room.id === roomId)) {
1363
- return Promise.resolve(jsonResponse(403, { error: 'not_a_member' }));
1364
- }
1365
- const mxcUri = `mxc://${decodeURIComponent(chatMedia[1])}/${decodeURIComponent(chatMedia[2])}`;
1366
- const carrier = this.sent.find((entry) => entry.roomId === roomId && entry.eventId === eventId && entry.content.url === mxcUri);
1367
- if (!carrier) {
1368
- return Promise.resolve(jsonResponse(403, { error: 'not_in_room' }));
1369
- }
1370
- const found = this.media.get(decodeURIComponent(chatMedia[2]));
1371
- if (!found) {
1372
- return Promise.resolve(jsonResponse(404, { error: 'not_found' }));
1373
- }
1374
- return Promise.resolve(new Response(found.bytes, {
1375
- status: 200,
1376
- headers: { 'Content-Type': found.contentType || 'application/octet-stream' },
1377
- }));
1378
- }
1379
- const download = url.pathname.match(/^\/_matrix\/client\/v1\/media\/download\/([^/]+)\/([^/]+)$/);
1380
- if (download) {
1381
- const authorised = this.#authorised(init);
1382
- this.mediaRequests.push({ path: url.pathname, authorised });
1383
- // Synapse serves media only to a request carrying the token
1384
- // (`enable_authenticated_media`), so this does too -- otherwise a
1385
- // client that forgot the header would pass its own test.
1386
- if (!authorised) {
1387
- return Promise.resolve(jsonResponse(401, { errcode: 'M_MISSING_TOKEN', error: 'no token' }));
1388
- }
1389
- const found = this.media.get(decodeURIComponent(download[2]));
1390
- if (!found) {
1391
- return Promise.resolve(jsonResponse(404, { errcode: 'M_NOT_FOUND', error: 'no media' }));
1392
- }
1393
- return Promise.resolve(new Response(found.bytes, {
1394
- status: 200,
1395
- headers: { 'Content-Type': found.contentType || 'application/octet-stream' },
1396
- }));
1397
- }
1398
- // The legacy, unauthenticated download paths. Answered with a refusal
1399
- // rather than left to fall through, so a test that expects one to work
1400
- // fails here and says why (ticket #13).
1401
- if (url.pathname.startsWith('/_matrix/media/v3/download')) {
1402
- this.mediaRequests.push({ path: url.pathname, authorised: false });
1403
- return Promise.resolve(jsonResponse(404, { errcode: 'M_UNRECOGNIZED', error: 'authenticated media only' }));
1404
- }
1405
- // What `CryptoApi.getKeyBackupInfo`/`checkKeyBackupAndEnable`/
1406
- // `resetKeyBackup` (chat#67) call through `requestKeyBackupVersion`
1407
- // (matrix-js-sdk's `rust-crypto/backup.js`): that helper treats an
1408
- // `M_NOT_FOUND` response as "no backup" and anything else as a real
1409
- // failure, so the catch-all `M_UNRECOGNIZED` 404 at the bottom of this
1410
- // method is not a substitute for this route existing. This fake keeps
1411
- // only the one live backup a company's account can have at a time --
1412
- // nothing in this package ever reads an old version.
1413
- const keyBackupVersion = url.pathname.match(/^\/_matrix\/client\/v3\/room_keys\/version(?:\/([^/]+))?$/);
1414
- if (keyBackupVersion && this.#authorised(init)) {
1415
- const requestedVersion = keyBackupVersion[1]
1416
- ? decodeURIComponent(keyBackupVersion[1])
1417
- : undefined;
1418
- if (init?.method === 'POST') {
1419
- let body = {};
1420
- try {
1421
- body = JSON.parse(String(init?.body ?? '{}'));
1422
- }
1423
- catch {
1424
- // Same tolerance as every other write here.
1425
- }
1426
- this.#keyBackupSeq += 1;
1427
- this.#keyBackup = {
1428
- algorithm: body.algorithm ?? '',
1429
- auth_data: body.auth_data ?? {},
1430
- version: `${this.#keyBackupSeq}`,
1431
- count: 0,
1432
- etag: `etag-${this.#keyBackupSeq}`,
1433
- };
1434
- return Promise.resolve(jsonResponse(200, { version: this.#keyBackup.version }));
1435
- }
1436
- const missing = !this.#keyBackup || (requestedVersion && this.#keyBackup.version !== requestedVersion);
1437
- if (init?.method === 'DELETE') {
1438
- if (missing) {
1439
- return Promise.resolve(jsonResponse(404, { errcode: 'M_NOT_FOUND', error: 'Unknown backup version' }));
1440
- }
1441
- this.#keyBackup = null;
1442
- return Promise.resolve(jsonResponse(200, {}));
1443
- }
1444
- if (missing) {
1445
- return Promise.resolve(jsonResponse(404, { errcode: 'M_NOT_FOUND', error: 'No current backup version' }));
1446
- }
1447
- return Promise.resolve(jsonResponse(200, { ...this.#keyBackup }));
1448
- }
1449
- // What `CryptoApi.restoreKeyBackup` (chat#68's recovery-key entry)
1450
- // downloads. This fake stores no session keys, so every download is an
1451
- // empty backup.
1452
- if (/^\/_matrix\/client\/v3\/room_keys\/keys(?:\/.*)?$/.test(url.pathname) &&
1453
- init?.method !== 'PUT' &&
1454
- this.#authorised(init)) {
1455
- return Promise.resolve(jsonResponse(200, { rooms: {} }));
1456
- }
1457
- // What a running `OlmMachine` uploads once `initRustCrypto()` has
1458
- // created it, including as part of `CryptoApi.bootstrapCrossSigning`'s
1459
- // own `resetCrossSigning` (chat#68) -- `CrossSigningIdentity.
1460
- // resetCrossSigning` sends a plain `uploadKeysRequest` through this
1461
- // same route alongside its signing-key and signature uploads. Stored
1462
- // per device id (`#handleExchange` records which token belongs to
1463
- // which) rather than merely accepted, so `/keys/query` (chat#69) has
1464
- // something real to answer a querying device with.
1465
- if (url.pathname === '/_matrix/client/v3/keys/upload' && this.#authorised(init)) {
1466
- const token = bearerToken(init);
1467
- const deviceId = token ? this.#tokenDeviceId.get(token) : undefined;
1468
- let body = {};
1469
- try {
1470
- body = JSON.parse(String(init?.body ?? '{}'));
1471
- }
1472
- catch {
1473
- // Same tolerance as every other write here.
1474
- }
1475
- if (deviceId && body.device_keys) {
1476
- this.#deviceKeysByDevice.set(deviceId, body.device_keys);
1477
- }
1478
- return Promise.resolve(jsonResponse(200, { one_time_key_counts: {} }));
1479
- }
1480
- // What a peer device's own machine queries to find another device --
1481
- // chat#69's device verification needs a *real* device to resolve
1482
- // through `CryptoApi.getUserDeviceInfo`/`requestDeviceVerification`,
1483
- // which a fabricated response cannot satisfy: the querying machine
1484
- // verifies the self-signature on whatever this returns, so it only
1485
- // ever echoes a device's own `/keys/upload` body back, verbatim.
1486
- if (url.pathname === '/_matrix/client/v3/keys/query' && this.#authorised(init)) {
1487
- let body = {};
1488
- try {
1489
- body = JSON.parse(String(init?.body ?? '{}'));
1490
- }
1491
- catch {
1492
- // Same tolerance as every other write here.
1493
- }
1494
- const requested = body.device_keys ?? {};
1495
- const deviceKeys = {};
1496
- // This fake only ever has one account on it (`this.userId`), so a
1497
- // query for anybody else comes back empty rather than failing --
1498
- // nothing this package does queries a second user's devices through
1499
- // a single-account fake.
1500
- if (Object.hasOwn(requested, this.userId)) {
1501
- const wantedDeviceIds = requested[this.userId] ?? [];
1502
- const devices = {};
1503
- for (const [deviceId, keys] of this.#deviceKeysByDevice) {
1504
- if (wantedDeviceIds.length === 0 || wantedDeviceIds.includes(deviceId)) {
1505
- devices[deviceId] = keys;
1506
- }
1507
- }
1508
- deviceKeys[this.userId] = devices;
1509
- }
1510
- return Promise.resolve(jsonResponse(200, { device_keys: deviceKeys, failures: {} }));
1511
- }
1512
- // What `CryptoApi.bootstrapSecretStorage` (chat#68) needs cross-signing
1513
- // bootstrapped through first (`getCrypto()?.bootstrapCrossSigning`):
1514
- // `getSecretStorageStatus` always checks the three cross-signing
1515
- // secrets are in secret storage, with no way to turn that check off, so
1516
- // nothing in this package can reach a "ready" secret storage without
1517
- // these two succeeding first. Real Synapse protects both with
1518
- // user-interactive auth; this fake does not model that dance -- a
1519
- // caller with no `authUploadDeviceSigningKeys` skips straight past it
1520
- // (`OutgoingRequestProcessor.makeRequestWithUIA`), and this fake simply
1521
- // accepts whatever reaches it, the same tolerance every other write
1522
- // here has for a body it does not otherwise validate.
1523
- if (url.pathname === '/_matrix/client/v3/keys/device_signing/upload' &&
1524
- this.#authorised(init)) {
1525
- return Promise.resolve(jsonResponse(200, {}));
1526
- }
1527
- if (url.pathname === '/_matrix/client/v3/keys/signatures/upload' && this.#authorised(init)) {
1528
- return Promise.resolve(jsonResponse(200, { failures: {} }));
1529
- }
1530
- // What `CryptoApi.requestDeviceVerification`/`requestOwnUserVerification`
1531
- // (chat#69) send on their way out. Recorded in `sentToDevice` rather
1532
- // than delivered to another device: `getVerificationRequestsToDevice
1533
- // InProgress` reads the sender's own `OlmMachine` state, which only
1534
- // needs the send to succeed, not to be received by anybody.
1535
- const sendToDevice = url.pathname.match(/^\/_matrix\/client\/v3\/sendToDevice\/([^/]+)\/([^/]+)$/);
1536
- if (sendToDevice && this.#authorised(init)) {
1537
- let body = {};
1538
- try {
1539
- body = JSON.parse(String(init?.body ?? '{}'));
1540
- }
1541
- catch {
1542
- // Same tolerance as every other write here.
1543
- }
1544
- this.sentToDevice.push({ eventType: decodeURIComponent(sendToDevice[1]), body });
1545
- return Promise.resolve(jsonResponse(200, {}));
1546
- }
1547
- // User-level account data: `m.direct` keeps its own typed field and its
1548
- // own seeding from room members; `CryptoApi.bootstrapSecretStorage`
1549
- // (chat#68) and everything it writes (`m.secret_storage.default_key`,
1550
- // `m.secret_storage.key.*`, the cross-signing and backup secrets) go
1551
- // through `#globalAccountData` instead. `MatrixClient.setAccountData`
1552
- // waits for the write's own remote echo on `ClientEvent.AccountData`
1553
- // before resolving (`client.js`), so a PUT answered `200` is not
1554
- // enough on its own -- `#deliverOrQueue({})` is what lets the next
1555
- // `/sync` carry it back, same as `m.direct` already relied on.
1556
- // `getAccountDataFromServer` falls back to a direct `GET` only before
1557
- // the first sync completes (`client.js`), which nothing in this
1558
- // package's crypto bootstrap does -- but a real homeserver still
1559
- // answers `M_NOT_FOUND` for a type nobody has written, so this fake
1560
- // does too rather than the `{}` every method here used to return
1561
- // regardless of type or verb.
1562
- const accountData = url.pathname.match(/^\/_matrix\/client\/v3\/user\/([^/]+)\/account_data\/([^/]+)$/);
1563
- if (accountData && this.#authorised(init)) {
1564
- const type = decodeURIComponent(accountData[2]);
1565
- if (init?.method === 'GET') {
1566
- if (type === 'm.direct') {
1567
- return Object.keys(this.#direct).length
1568
- ? Promise.resolve(jsonResponse(200, { ...this.#direct }))
1569
- : Promise.resolve(jsonResponse(404, { errcode: 'M_NOT_FOUND', error: 'Account data not found' }));
1570
- }
1571
- const stored = this.#globalAccountData.get(type);
1572
- return stored
1573
- ? Promise.resolve(jsonResponse(200, stored))
1574
- : Promise.resolve(jsonResponse(404, { errcode: 'M_NOT_FOUND', error: 'Account data not found' }));
1575
- }
1576
- let content = {};
1577
- try {
1578
- content = JSON.parse(String(init?.body ?? '{}'));
1579
- }
1580
- catch {
1581
- // Same tolerance as every other write here.
1582
- }
1583
- if (type === 'm.direct') {
1584
- this.#direct = content;
1585
- }
1586
- else {
1587
- this.#globalAccountData.set(type, content);
1588
- }
1589
- this.#deliverOrQueue({});
1590
- return Promise.resolve(jsonResponse(200, {}));
1591
- }
1592
- // What `client.setRoomAccountData` PUTs -- both keys `markRoomUnread`
1593
- // writes (see `ChatClient.markRoomUnread`) get the marked-unread
1594
- // treatment; any other room-scoped account data type -- a draft, most
1595
- // likely -- is stored generically through `#setRoomAccountData`.
1596
- const roomAccountData = url.pathname.match(/^\/_matrix\/client\/v3\/user\/([^/]+)\/rooms\/([^/]+)\/account_data\/([^/]+)$/);
1597
- if (roomAccountData && this.#authorised(init)) {
1598
- const roomId = decodeURIComponent(roomAccountData[2]);
1599
- const type = decodeURIComponent(roomAccountData[3]);
1600
- let content = {};
1601
- try {
1602
- content = JSON.parse(String(init?.body ?? '{}'));
1603
- }
1604
- catch {
1605
- // Same tolerance as every other write here: a malformed body is
1606
- // recorded as sent rather than failing the test for a reason it
1607
- // did not choose.
1608
- }
1609
- if (type === 'm.marked_unread' || type === 'com.famedly.marked_unread') {
1610
- this.#setMarkedUnread(roomId, Boolean(content.unread));
1611
- }
1612
- else {
1613
- this.#setRoomAccountData(roomId, type, content);
1614
- }
1615
- return Promise.resolve(jsonResponse(200, {}));
1616
- }
1617
- const tag = url.pathname.match(/^\/_matrix\/client\/v3\/user\/([^/]+)\/rooms\/([^/]+)\/tags\/([^/]+)$/);
1618
- if (tag && this.#authorised(init)) {
1619
- this.#setTag(decodeURIComponent(tag[2]), decodeURIComponent(tag[3]), init?.method !== 'DELETE');
1620
- return Promise.resolve(jsonResponse(200, {}));
1621
- }
1622
- // What `client.sendTyping` PUTs -- see `ChatClient.sendTyping`. Recorded
1623
- // rather than echoed back through sync on its own: a real homeserver's
1624
- // own typing timer is what turns this into the `m.typing` EDU other
1625
- // members see, and a test drives that side explicitly with
1626
- // `receiveTyping` instead of this fake modelling a timer.
1627
- const typing = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/typing\/([^/]+)$/);
1628
- if (typing && this.#authorised(init)) {
1629
- let body = {};
1630
- try {
1631
- body = JSON.parse(String(init?.body ?? '{}'));
1632
- }
1633
- catch {
1634
- // Same tolerance as every other write here: a malformed body is
1635
- // recorded as sent rather than failing the test for a reason it
1636
- // did not choose.
1637
- }
1638
- this.sentTyping.push({
1639
- roomId: decodeURIComponent(typing[1]),
1640
- userId: decodeURIComponent(typing[2]),
1641
- typing: Boolean(body.typing),
1642
- timeoutMs: body.timeout,
1643
- });
1644
- return Promise.resolve(jsonResponse(200, {}));
1645
- }
1646
- // The immediate half of `announcePresence`. Recorded rather than fed
1647
- // back as an `m.presence` event: on a real homeserver this sets the
1648
- // *signed-in person's own* presence, which is read by everybody else's
1649
- // client, not by this one -- `presence()` here is driven by
1650
- // `receivePresence` instead, the same way typing is.
1651
- const presence = url.pathname.match(/^\/_matrix\/client\/v3\/presence\/([^/]+)\/status$/);
1652
- if (presence && this.#authorised(init)) {
1653
- if (this.refuseNextPresence) {
1654
- this.refuseNextPresence = false;
1655
- return Promise.resolve(jsonResponse(429, {
1656
- errcode: 'M_LIMIT_EXCEEDED',
1657
- error: 'Too many requests',
1658
- retry_after_ms: 10_000,
1659
- }));
1660
- }
1661
- let body = {};
1662
- try {
1663
- body = JSON.parse(String(init?.body ?? '{}'));
1664
- }
1665
- catch {
1666
- // Same tolerance as every other write here.
1667
- }
1668
- this.sentPresence.push({
1669
- userId: decodeURIComponent(presence[1]),
1670
- presence: String(body.presence),
1671
- });
1672
- return Promise.resolve(jsonResponse(200, {}));
1673
- }
1674
- // What `getExtendedProfileProperty`/`setExtendedProfileProperty`/
1675
- // `deleteExtendedProfileProperty` read and write -- MSC4133 extended
1676
- // profiles, `ChatClient.status`'s own storage (`docs/status.md`). This
1677
- // fake only ever advertises the unstable feature flag (see `/versions`
1678
- // above), so matrix-js-sdk always asks this prefix, never `/_matrix/
1679
- // client/v3/profile/...`.
1680
- const extendedProfileProperty = url.pathname.match(/^\/_matrix\/client\/unstable\/uk\.tcpip\.msc4133\/profile\/([^/]+)\/([^/]+)$/);
1681
- if (extendedProfileProperty && this.#authorised(init)) {
1682
- const profileUserId = decodeURIComponent(extendedProfileProperty[1]);
1683
- const key = decodeURIComponent(extendedProfileProperty[2]);
1684
- if (init?.method === 'PUT') {
1685
- let body = {};
1686
- try {
1687
- body = JSON.parse(String(init?.body ?? '{}'));
1688
- }
1689
- catch {
1690
- // Same tolerance as every other write here.
1691
- }
1692
- this.seedExtendedProfile(profileUserId, key, body[key]);
1693
- this.extendedProfileWrites.push({ userId: profileUserId, key, value: body[key] });
1694
- return Promise.resolve(jsonResponse(200, {}));
1695
- }
1696
- if (init?.method === 'DELETE') {
1697
- this.#extendedProfiles.get(profileUserId)?.delete(key);
1698
- this.extendedProfileWrites.push({ userId: profileUserId, key, value: undefined });
1699
- return Promise.resolve(jsonResponse(200, {}));
1700
- }
1701
- const value = this.#extendedProfiles.get(profileUserId)?.get(key);
1702
- if (value === undefined) {
1703
- return Promise.resolve(jsonResponse(404, { errcode: 'M_NOT_FOUND', error: 'Not found' }));
1704
- }
1705
- return Promise.resolve(jsonResponse(200, { [key]: value }));
1706
- }
1707
- const receipt = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/receipt\/m\.read\/([^/]+)$/);
1708
- if (receipt) {
1709
- const token = bearerToken(init);
1710
- if (!token || !this.#validTokens.has(token)) {
1711
- return Promise.resolve(jsonResponse(401, { errcode: 'M_UNKNOWN_TOKEN', error: 'Invalid access token' }));
1712
- }
1713
- this.receipts.push({
1714
- roomId: decodeURIComponent(receipt[1]),
1715
- eventId: decodeURIComponent(receipt[2]),
1716
- });
1717
- return Promise.resolve(jsonResponse(200, {}));
1718
- }
1719
- const report = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/report\/([^/]+)$/);
1720
- if (report && init?.method === 'POST') {
1721
- const token = bearerToken(init);
1722
- if (!token || !this.#validTokens.has(token)) {
1723
- return Promise.resolve(jsonResponse(401, { errcode: 'M_UNKNOWN_TOKEN', error: 'Invalid access token' }));
1724
- }
1725
- this.reports.push({
1726
- roomId: decodeURIComponent(report[1]),
1727
- eventId: decodeURIComponent(report[2]),
1728
- body: JSON.parse(String(init.body ?? '{}')),
1729
- });
1730
- return Promise.resolve(jsonResponse(200, {}));
1731
- }
1732
- // Anything else at this homeserver -- capability discovery, RTC
1733
- // transports, and whatever else a client startup probes for -- is
1734
- // answered "not recognised" rather than falling through: this origin
1735
- // does not exist on the real network, and a client startup that reaches
1736
- // past what this fake implements must never make a real DNS lookup.
1737
- return Promise.resolve(jsonResponse(404, { errcode: 'M_UNRECOGNIZED', error: 'Unrecognised request' }));
1738
- }
1739
- }