@wtfalch/chat 0.5.1 → 0.7.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.
@@ -36,6 +36,16 @@ export class FakeChatServer {
36
36
  * gives a member, which `pinMessage`/`unpinMessage` must reject on
37
37
  * rather than resolve quietly. */
38
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
+ /** Every call to the thread follow route, in arrival order. */
48
+ threadFollowRequests = [];
39
49
  userId;
40
50
  /** The Matrix server name, as `userId` gives it -- what an `mxc://`
41
51
  * reference from this homeserver names. */
@@ -65,6 +75,10 @@ export class FakeChatServer {
65
75
  * request carried -- for a test that asserts nothing reaches the
66
76
  * legacy unauthenticated endpoints, and that the token was sent. */
67
77
  mediaRequests = [];
78
+ /** Who follows which thread, as `apps/chat-service`'s thread follow
79
+ * route keeps it: `roomId rootId` -> whether the person unfollowed. A
80
+ * thread with no entry is not followed. */
81
+ threadFollows = new Map();
68
82
  /** Every `PUT .../typing/...` this server has answered, in order -- for a
69
83
  * test that asserts `sendTyping` actually reached the wire, with what
70
84
  * it sent. */
@@ -82,12 +96,29 @@ export class FakeChatServer {
82
96
  * `sentPresence` would pass against a client that cannot hold anybody
83
97
  * away for longer than one poll. */
84
98
  syncPresence = [];
99
+ /** Every `PUT`/`DELETE` on an MSC4133 extended-profile property this
100
+ * server has answered, in order -- what `ChatClient.setOwnStatus`
101
+ * writes. `value: undefined` records a delete. */
102
+ extendedProfileWrites = [];
103
+ /** Every `PUT .../sendToDevice/...` this server has answered, in order --
104
+ * what a `CryptoApi` verification request (chat#69) sends on its way
105
+ * out. Recorded rather than delivered to another device: the methods
106
+ * this fake exists for (`getVerificationRequestsToDeviceInProgress`)
107
+ * read the sender's own `OlmMachine` state, which only needs the send to
108
+ * succeed, not to be received. */
109
+ sentToDevice = [];
85
110
  /** Rooms currently carrying the room-scoped `dont_notify` push rule, for
86
111
  * a test that wants to assert on the server's own state rather than
87
112
  * only through the client's `rooms()`. */
88
113
  get mutedRoomIds() {
89
114
  return [...this.#mutedRooms];
90
115
  }
116
+ /** Rooms currently carrying MSC2867's marked-unread flag, for a test that
117
+ * wants to assert on the server's own state rather than only through the
118
+ * client's `rooms()`. */
119
+ get markedUnreadRoomIds() {
120
+ return [...this.#markedUnread.entries()].filter(([, unread]) => unread).map(([id]) => id);
121
+ }
91
122
  #dispose;
92
123
  #rooms;
93
124
  #tokenLifetimeMs;
@@ -106,17 +137,65 @@ export class FakeChatServer {
106
137
  #parkedWaiters = [];
107
138
  #disposed = false;
108
139
  #direct = {};
140
+ /** User-level account data beyond `m.direct`, keyed by event type -- what
141
+ * `CryptoApi.bootstrapSecretStorage` (chat#68) reads and writes through
142
+ * `setAccountData`/`getAccountDataFromServer`. `m.direct` keeps its own
143
+ * field above rather than moving in here: it has its own typed shape and
144
+ * its own seeding from room members, and nothing about chat#67-69 needs
145
+ * that to change. */
146
+ #globalAccountData = new Map();
147
+ /** Which device a minted token belongs to -- set at exchange time, read
148
+ * by `/keys/upload` so an uploaded device's keys land under its own
149
+ * device id rather than the fake account's single fixed `userId`. Both
150
+ * `CryptoApi.bootstrapCrossSigning`'s own `resetCrossSigning` (chat#68,
151
+ * through `CrossSigningIdentity.resetCrossSigning`'s plain
152
+ * `uploadKeysRequest`) and a running `OlmMachine`'s regular background
153
+ * upload (chat#69's device discovery) go through this one route. */
154
+ #tokenDeviceId = new Map();
155
+ /** Every device's own `device_keys` upload, keyed by device id -- what
156
+ * `/keys/query` (chat#69) answers a querying device with, verbatim.
157
+ * Verbatim matters: the Olm machine verifies the self-signature on
158
+ * whatever `/keys/query` returns, so a fabricated or edited entry would
159
+ * fail that check rather than prove device verification reaches a real
160
+ * device. */
161
+ #deviceKeysByDevice = new Map();
162
+ /** The one server-side key backup this fake can hold at a time, or `null`
163
+ * before `CryptoApi.resetKeyBackup` (chat#67) has ever created one, or
164
+ * again once `disableKeyStorage`/a version delete removes it. Real
165
+ * Synapse allows several historical versions; nothing this package does
166
+ * reads an old one, so this fake only ever keeps the live one. */
167
+ #keyBackup = null;
168
+ #keyBackupSeq = 0;
109
169
  /** Every message event this server has ever had in a room, in order. The
110
170
  * full sync replays it, and `/event` and `/relations` are answered out
111
171
  * of it -- matrix-js-sdk asks for both while it builds a thread. */
112
172
  #events = new Map();
113
173
  #tags = new Map();
174
+ /** Room-scoped account data a test or the client has set on a room,
175
+ * keyed by room id then event type -- what `client.setDraft` and
176
+ * `client.setRoomAccountData` more generally write, distinct from
177
+ * `#tags`'s own `m.tag` shape. */
178
+ #roomAccountData = new Map();
114
179
  /** Rooms carrying the account's room-scoped `dont_notify` push rule --
115
180
  * what `muteRoom` writes and takes away, and the only rule kind this
116
181
  * fake bothers to model. Read back through `/pushrules/`, exactly as
117
182
  * Synapse would answer it, so a test never has to reach past the
118
183
  * client's own `rooms()` to know a mute landed. */
119
184
  #mutedRooms = new Set();
185
+ /** Rooms carrying MSC2867's marked-unread flag -- what `markRoomUnread`
186
+ * writes as room-scoped account data under both `m.marked_unread` and
187
+ * `com.famedly.marked_unread`. One value stands for both keys: a real
188
+ * client never has a reason to disagree with itself about which key
189
+ * means what it wrote. */
190
+ #markedUnread = new Map();
191
+ /** MSC4133 extended-profile properties, keyed by user id then property
192
+ * key -- what `setOwnStatus` PUTs and DELETEs on the signed-in
193
+ * account's own entry, and `status`'s background fetch GETs for
194
+ * anyone. `seedExtendedProfile` writes another (peer) user's entry
195
+ * directly, since real Matrix never lets a client set anyone's profile
196
+ * but its own. */
197
+ #extendedProfiles = new Map();
198
+ #extendedProfilesEnabled;
120
199
  #roomSeq = 0;
121
200
  #mediaSeq = 0;
122
201
  /** Deliveries made while no poll was parked, waiting for the next one --
@@ -132,6 +211,7 @@ export class FakeChatServer {
132
211
  this.#rooms = [...(options.rooms ?? [])];
133
212
  this.#tokenLifetimeMs = options.tokenLifetimeMs ?? 10 * 60_000;
134
213
  this.#now = options.now ?? Date.now;
214
+ this.#extendedProfilesEnabled = options.extendedProfilesEnabled ?? true;
135
215
  for (const room of this.#rooms)
136
216
  this.#materialise(room);
137
217
  for (const room of this.#rooms) {
@@ -143,6 +223,20 @@ export class FakeChatServer {
143
223
  }
144
224
  this.#dispose = installFetchRoute((input, init) => this.#route(input, init));
145
225
  }
226
+ /** Sets `userId`'s MSC4133 extended-profile `key` directly, for a test
227
+ * simulating "somebody else already has this set on the server" --
228
+ * `ChatClient.status`'s background fetch then reads it exactly as it
229
+ * would a real peer's. Real Matrix never lets a client PUT anyone's
230
+ * profile but its own, which is why this exists as a server-side seed
231
+ * rather than something `setOwnStatus` could reach. */
232
+ seedExtendedProfile(userId, key, value) {
233
+ let profile = this.#extendedProfiles.get(userId);
234
+ if (!profile) {
235
+ profile = new Map();
236
+ this.#extendedProfiles.set(userId, profile);
237
+ }
238
+ profile.set(key, value);
239
+ }
146
240
  dispose() {
147
241
  if (this.#disposed)
148
242
  return;
@@ -162,6 +256,18 @@ export class FakeChatServer {
162
256
  return;
163
257
  await new Promise((resolve) => this.#parkedWaiters.push(resolve));
164
258
  }
259
+ /** Delivers a parked poll as if another of this account's own devices
260
+ * had just written `type` room account data for `roomId` -- a draft,
261
+ * most likely -- the way a real incremental `/sync` carries a change
262
+ * made from elsewhere. Throws if nothing is parked -- await
263
+ * `waitForParkedPoll()` first. */
264
+ receiveRoomAccountData(roomId, type, content) {
265
+ this.#storeRoomAccountData(roomId, type, content);
266
+ const seed = this.#rooms.find((room) => room.id === roomId);
267
+ if (!seed)
268
+ return;
269
+ this.#deliverParked({ [roomId]: this.#joinEntry(seed) });
270
+ }
165
271
  /** Adds a room and, if a poll is parked, delivers it now. Throws if
166
272
  * nothing is parked -- await `waitForParkedPoll()` first. */
167
273
  addRoom(seed) {
@@ -203,9 +309,12 @@ export class FakeChatServer {
203
309
  /** Delivers a parked poll as an existing, already-known room receiving
204
310
  * one new message from the fake peer -- a timeline event and a bumped
205
311
  * notification count together, the way a real incremental `/sync`
206
- * carries both at once. Returns the minted event id, for a test that
207
- * then calls `markRoomRead` against it. Throws if nothing is parked. */
208
- receiveMessage(roomId, notificationCount = 1) {
312
+ * carries both at once. `highlightCount` defaults to `0`: an ordinary
313
+ * message that does not mention this account, same as Matrix would
314
+ * report. Pass it to simulate a mention arriving. Returns the minted
315
+ * event id, for a test that then calls `markRoomRead` against it.
316
+ * Throws if nothing is parked. */
317
+ receiveMessage(roomId, notificationCount = 1, highlightCount = 0) {
209
318
  this.#eventSeq += 1;
210
319
  const eventId = `$msg-${this.#eventSeq}`;
211
320
  this.#deliverParked({
@@ -227,7 +336,10 @@ export class FakeChatServer {
227
336
  },
228
337
  ephemeral: { events: [] },
229
338
  account_data: { events: [] },
230
- unread_notifications: { highlight_count: 0, notification_count: notificationCount },
339
+ unread_notifications: {
340
+ highlight_count: highlightCount,
341
+ notification_count: notificationCount,
342
+ },
231
343
  },
232
344
  });
233
345
  return eventId;
@@ -294,20 +406,37 @@ export class FakeChatServer {
294
406
  return `batch-${this.#batchSeq}`;
295
407
  }
296
408
  #accountDataEvents() {
297
- return Object.keys(this.#direct).length
298
- ? [{ type: 'm.direct', content: { ...this.#direct } }]
299
- : [];
409
+ const events = [];
410
+ if (Object.keys(this.#direct).length) {
411
+ events.push({ type: 'm.direct', content: { ...this.#direct } });
412
+ }
413
+ for (const [type, content] of this.#globalAccountData) {
414
+ events.push({ type, content });
415
+ }
416
+ return events;
300
417
  }
301
418
  /** A room's own account data: the tags a test or the client has set on
302
- * it. `m.tag` is how `hideDirectMessage` reaches `room.tags`. */
419
+ * it (`m.tag`, how `hideDirectMessage` reaches `room.tags`), MSC2867's
420
+ * marked-unread flag under both keys `markRoomUnread` writes, plus
421
+ * whatever else `#roomAccountData` holds -- a draft, most likely. */
303
422
  #roomAccountDataEvents(roomId) {
423
+ const events = [];
304
424
  const tags = this.#tags.get(roomId);
305
- if (!tags)
306
- return [];
307
- const content = {};
308
- for (const tag of tags)
309
- content[tag] = {};
310
- return [{ type: 'm.tag', content: { tags: content } }];
425
+ if (tags) {
426
+ const content = {};
427
+ for (const tag of tags)
428
+ content[tag] = {};
429
+ events.push({ type: 'm.tag', content: { tags: content } });
430
+ }
431
+ const unread = this.#markedUnread.get(roomId);
432
+ if (unread !== undefined) {
433
+ events.push({ type: 'm.marked_unread', content: { unread } });
434
+ events.push({ type: 'com.famedly.marked_unread', content: { unread } });
435
+ }
436
+ for (const [type, content] of this.#roomAccountData.get(roomId) ?? []) {
437
+ events.push({ type, content });
438
+ }
439
+ return events;
311
440
  }
312
441
  #memberEvent(seed, member, membership) {
313
442
  return {
@@ -316,7 +445,14 @@ export class FakeChatServer {
316
445
  event_id: `$member-${seed.id}-${member.userId}-${membership}`,
317
446
  sender: this.userId,
318
447
  origin_server_ts: this.#now(),
319
- content: { membership, displayname: member.name ?? member.userId },
448
+ content: {
449
+ membership,
450
+ displayname: member.name ?? member.userId,
451
+ // 'dev.wtfalch.chat.guest' -- see `client.ts`'s `GUEST_MARKER_KEY`.
452
+ ...(member.guestUntil !== undefined
453
+ ? { 'dev.wtfalch.chat.guest': { until: member.guestUntil } }
454
+ : {}),
455
+ },
320
456
  };
321
457
  }
322
458
  #joinEntry(seed) {
@@ -373,6 +509,16 @@ export class FakeChatServer {
373
509
  content: { algorithm: 'm.megolm.v1.aes-sha2' },
374
510
  });
375
511
  }
512
+ if (seed.archived) {
513
+ events.push({
514
+ type: 'm.room.power_levels',
515
+ state_key: '',
516
+ event_id: `$power-levels-${seed.id}`,
517
+ sender: this.userId,
518
+ origin_server_ts: now,
519
+ content: { events_default: 100 },
520
+ });
521
+ }
376
522
  return {
377
523
  summary: {},
378
524
  state: { events },
@@ -383,7 +529,10 @@ export class FakeChatServer {
383
529
  },
384
530
  ephemeral: { events: [] },
385
531
  account_data: { events: this.#roomAccountDataEvents(seed.id) },
386
- unread_notifications: { highlight_count: 0, notification_count: seed.notificationCount ?? 0 },
532
+ unread_notifications: {
533
+ highlight_count: seed.highlightCount ?? 0,
534
+ notification_count: seed.notificationCount ?? 0,
535
+ },
387
536
  };
388
537
  }
389
538
  /** A room's invite-state entry: the stripped state real Matrix delivers
@@ -620,9 +769,29 @@ export class FakeChatServer {
620
769
  rooms: { join, invite },
621
770
  account_data: { events: this.#accountDataEvents() },
622
771
  presence: { events: [] },
623
- to_device: { events: [] },
772
+ to_device: { events: this.#drainToDevice() },
624
773
  };
625
774
  }
775
+ /** The device ids that have uploaded `device_keys` so far. */
776
+ uploadedDeviceIds() {
777
+ return [...this.#deviceKeysByDevice.keys()];
778
+ }
779
+ /** To-device events waiting for the next `/sync` this account answers --
780
+ * see `deliverToDevice`. */
781
+ #toDeviceQueue = [];
782
+ #drainToDevice() {
783
+ return this.#toDeviceQueue.splice(0);
784
+ }
785
+ /** Delivers to-device events (a verification request, say) to the one
786
+ * client this fake serves, on its next `/sync` -- straight away if a poll
787
+ * is parked. Each event is `{ type, sender, content }`. Only one client
788
+ * can be answered at a time: this fake has a single parked poll, so it
789
+ * cannot route a to-device message from one live client to another, and
790
+ * `sendToDevice` writes stay recorded in `sentToDevice` only. */
791
+ deliverToDevice(events) {
792
+ this.#toDeviceQueue.push(...events);
793
+ this.#deliverOrQueue({});
794
+ }
626
795
  #deliverParked(join, leave = {}, presenceEvents = []) {
627
796
  if (!this.#pending) {
628
797
  throw new Error('fake chat: addRoom called with no /sync request parked');
@@ -653,7 +822,7 @@ export class FakeChatServer {
653
822
  rooms: { join, leave },
654
823
  account_data: { events: this.#accountDataEvents() },
655
824
  presence: { events: presenceEvents },
656
- to_device: { events: [] },
825
+ to_device: { events: this.#drainToDevice() },
657
826
  }));
658
827
  }
659
828
  /** The fake account's own view of a created direct room: the invitees
@@ -686,6 +855,32 @@ export class FakeChatServer {
686
855
  if (seed)
687
856
  this.#deliverOrQueue({ [roomId]: this.#joinEntry(seed) });
688
857
  }
858
+ /** What `markRoomUnread` PUTs, under either key it writes -- see
859
+ * `ChatClient.markRoomUnread`. Echoed back the same way `#setTag` echoes
860
+ * a tag: as part of the room's own next join entry, so a client that
861
+ * actually reads its account data off `/sync` (rather than trusting its
862
+ * own local echo) sees the same answer. */
863
+ #setMarkedUnread(roomId, unread) {
864
+ this.#markedUnread.set(roomId, unread);
865
+ const seed = this.#rooms.find((room) => room.id === roomId);
866
+ if (seed)
867
+ this.#deliverOrQueue({ [roomId]: this.#joinEntry(seed) });
868
+ }
869
+ #storeRoomAccountData(roomId, type, content) {
870
+ const forRoom = this.#roomAccountData.get(roomId) ?? new Map();
871
+ forRoom.set(type, content);
872
+ this.#roomAccountData.set(roomId, forRoom);
873
+ }
874
+ /** What `PUT .../rooms/{roomId}/account_data/{type}` writes -- a draft,
875
+ * most likely. Delivered back through the room's `join` entry exactly
876
+ * like `#setTag`, so the writing client's own next poll sees it the
877
+ * same way real Matrix account data comes back through `/sync`. */
878
+ #setRoomAccountData(roomId, type, content) {
879
+ this.#storeRoomAccountData(roomId, type, content);
880
+ const seed = this.#rooms.find((room) => room.id === roomId);
881
+ if (seed)
882
+ this.#deliverOrQueue({ [roomId]: this.#joinEntry(seed) });
883
+ }
689
884
  #handleExchange(init) {
690
885
  this.exchangeCount += 1;
691
886
  const zitadelToken = bearerToken(init);
@@ -705,6 +900,7 @@ export class FakeChatServer {
705
900
  const token = `fake-matrix-token-${++this.#tokenSeq}`;
706
901
  this.#validTokens.add(token);
707
902
  this.mintedTokens.push(token);
903
+ this.#tokenDeviceId.set(token, deviceId);
708
904
  return Promise.resolve(jsonResponse(200, {
709
905
  homeserver: this.homeserver,
710
906
  user_id: this.userId,
@@ -733,7 +929,7 @@ export class FakeChatServer {
733
929
  rooms: { join: queued.join, leave: queued.leave },
734
930
  account_data: { events: this.#accountDataEvents() },
735
931
  presence: { events: [] },
736
- to_device: { events: [] },
932
+ to_device: { events: this.#drainToDevice() },
737
933
  }));
738
934
  }
739
935
  return new Promise((resolve, reject) => {
@@ -766,7 +962,17 @@ export class FakeChatServer {
766
962
  return null;
767
963
  const url = new URL(rawUrl);
768
964
  if (url.pathname === '/_matrix/client/versions') {
769
- return Promise.resolve(jsonResponse(200, { versions: ['v1.4'], unstable_features: {} }));
965
+ return Promise.resolve(jsonResponse(200, {
966
+ versions: ['v1.4'],
967
+ // Only the unstable flag, never `.stable` -- `doesServerSupport
968
+ // ExtendedProfiles` reads either, but `getExtendedProfileRequest
969
+ // Prefix` only takes the `/_matrix/client/v3` path for `.stable`
970
+ // or a real v1.16, so this keeps every extended-profile request
971
+ // on the `/_matrix/client/unstable/uk.tcpip.msc4133` prefix the
972
+ // route below answers -- the same "off by default" MSC4133 gate
973
+ // `docs/status.md` describes for real Synapse.
974
+ unstable_features: { 'uk.tcpip.msc4133': this.#extendedProfilesEnabled },
975
+ }));
770
976
  }
771
977
  if (url.pathname === '/_matrix/client/v3/pushrules/') {
772
978
  return Promise.resolve(jsonResponse(200, {
@@ -972,6 +1178,9 @@ export class FakeChatServer {
972
1178
  }
973
1179
  const send = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/send\/([^/]+)\/([^/]+)$/);
974
1180
  if (send && this.#authorised(init)) {
1181
+ if (this.sendStatus !== 200) {
1182
+ return Promise.resolve(jsonResponse(this.sendStatus, { errcode: 'M_FORBIDDEN' }));
1183
+ }
975
1184
  let content = {};
976
1185
  try {
977
1186
  content = JSON.parse(String(init?.body ?? '{}'));
@@ -1082,6 +1291,44 @@ export class FakeChatServer {
1082
1291
  return jsonResponse(200, { content_uri: `mxc://${this.serverName}/${mediaId}` });
1083
1292
  })();
1084
1293
  }
1294
+ // `apps/chat-service`'s thread follow route: the same rule the real one
1295
+ // has -- an automatic follow never undoes an unfollow.
1296
+ const chatThread = url.pathname.match(/^\/_chat\/threads\/([^/]+)\/([^/]+)\/follow$/);
1297
+ if (chatThread) {
1298
+ if (!this.#authorised(init)) {
1299
+ return Promise.resolve(jsonResponse(401, { error: 'token_invalid' }));
1300
+ }
1301
+ const roomId = decodeURIComponent(chatThread[1]);
1302
+ if (!this.#rooms.some((room) => room.id === roomId)) {
1303
+ return Promise.resolve(jsonResponse(403, { error: 'not_a_member' }));
1304
+ }
1305
+ const rootId = decodeURIComponent(chatThread[2]);
1306
+ const key = `${roomId} ${rootId}`;
1307
+ const method = init?.method ?? 'GET';
1308
+ this.threadFollowRequests.push({ method, roomId, rootId });
1309
+ if (method === 'GET') {
1310
+ // The answer is what was true when the request arrived, however
1311
+ // long the barrier holds it.
1312
+ const barrier = this.threadFollowReadBarrier;
1313
+ const status = this.threadFollowReadStatus;
1314
+ const found = this.threadFollows.get(key);
1315
+ return (async () => {
1316
+ await barrier;
1317
+ if (status !== 200)
1318
+ return jsonResponse(status, { error: 'internal_error' });
1319
+ return jsonResponse(200, { following: found !== undefined && !found.muted });
1320
+ })();
1321
+ }
1322
+ if (method === 'DELETE')
1323
+ this.threadFollows.set(key, { muted: true });
1324
+ if (method === 'PUT') {
1325
+ const auto = JSON.parse(String(init?.body ?? '{}')).auto === true;
1326
+ if (!auto || !this.threadFollows.has(key))
1327
+ this.threadFollows.set(key, { muted: false });
1328
+ }
1329
+ const found = this.threadFollows.get(key);
1330
+ return Promise.resolve(jsonResponse(200, { following: found !== undefined && !found.muted }));
1331
+ }
1085
1332
  // `apps/chat-service`'s media proxy (wtfalch/chat#32). The same two
1086
1333
  // checks the real one makes: the account is still in `roomId`, and
1087
1334
  // `eventId` is a message sent there that references this media.
@@ -1137,16 +1384,215 @@ export class FakeChatServer {
1137
1384
  this.mediaRequests.push({ path: url.pathname, authorised: false });
1138
1385
  return Promise.resolve(jsonResponse(404, { errcode: 'M_UNRECOGNIZED', error: 'authenticated media only' }));
1139
1386
  }
1140
- const accountData = url.pathname.match(/^\/_matrix\/client\/v3\/user\/([^/]+)\/account_data\/([^/]+)$/);
1141
- if (accountData && this.#authorised(init)) {
1142
- if (accountData[2] === 'm.direct') {
1387
+ // What `CryptoApi.getKeyBackupInfo`/`checkKeyBackupAndEnable`/
1388
+ // `resetKeyBackup` (chat#67) call through `requestKeyBackupVersion`
1389
+ // (matrix-js-sdk's `rust-crypto/backup.js`): that helper treats an
1390
+ // `M_NOT_FOUND` response as "no backup" and anything else as a real
1391
+ // failure, so the catch-all `M_UNRECOGNIZED` 404 at the bottom of this
1392
+ // method is not a substitute for this route existing. This fake keeps
1393
+ // only the one live backup a company's account can have at a time --
1394
+ // nothing in this package ever reads an old version.
1395
+ const keyBackupVersion = url.pathname.match(/^\/_matrix\/client\/v3\/room_keys\/version(?:\/([^/]+))?$/);
1396
+ if (keyBackupVersion && this.#authorised(init)) {
1397
+ const requestedVersion = keyBackupVersion[1]
1398
+ ? decodeURIComponent(keyBackupVersion[1])
1399
+ : undefined;
1400
+ if (init?.method === 'POST') {
1401
+ let body = {};
1143
1402
  try {
1144
- this.#direct = JSON.parse(String(init?.body ?? '{}'));
1403
+ body = JSON.parse(String(init?.body ?? '{}'));
1145
1404
  }
1146
1405
  catch {
1147
- this.#direct = {};
1406
+ // Same tolerance as every other write here.
1148
1407
  }
1149
- this.#deliverOrQueue({});
1408
+ this.#keyBackupSeq += 1;
1409
+ this.#keyBackup = {
1410
+ algorithm: body.algorithm ?? '',
1411
+ auth_data: body.auth_data ?? {},
1412
+ version: `${this.#keyBackupSeq}`,
1413
+ count: 0,
1414
+ etag: `etag-${this.#keyBackupSeq}`,
1415
+ };
1416
+ return Promise.resolve(jsonResponse(200, { version: this.#keyBackup.version }));
1417
+ }
1418
+ const missing = !this.#keyBackup || (requestedVersion && this.#keyBackup.version !== requestedVersion);
1419
+ if (init?.method === 'DELETE') {
1420
+ if (missing) {
1421
+ return Promise.resolve(jsonResponse(404, { errcode: 'M_NOT_FOUND', error: 'Unknown backup version' }));
1422
+ }
1423
+ this.#keyBackup = null;
1424
+ return Promise.resolve(jsonResponse(200, {}));
1425
+ }
1426
+ if (missing) {
1427
+ return Promise.resolve(jsonResponse(404, { errcode: 'M_NOT_FOUND', error: 'No current backup version' }));
1428
+ }
1429
+ return Promise.resolve(jsonResponse(200, { ...this.#keyBackup }));
1430
+ }
1431
+ // What `CryptoApi.restoreKeyBackup` (chat#68's recovery-key entry)
1432
+ // downloads. This fake stores no session keys, so every download is an
1433
+ // empty backup.
1434
+ if (/^\/_matrix\/client\/v3\/room_keys\/keys(?:\/.*)?$/.test(url.pathname) &&
1435
+ init?.method !== 'PUT' &&
1436
+ this.#authorised(init)) {
1437
+ return Promise.resolve(jsonResponse(200, { rooms: {} }));
1438
+ }
1439
+ // What a running `OlmMachine` uploads once `initRustCrypto()` has
1440
+ // created it, including as part of `CryptoApi.bootstrapCrossSigning`'s
1441
+ // own `resetCrossSigning` (chat#68) -- `CrossSigningIdentity.
1442
+ // resetCrossSigning` sends a plain `uploadKeysRequest` through this
1443
+ // same route alongside its signing-key and signature uploads. Stored
1444
+ // per device id (`#handleExchange` records which token belongs to
1445
+ // which) rather than merely accepted, so `/keys/query` (chat#69) has
1446
+ // something real to answer a querying device with.
1447
+ if (url.pathname === '/_matrix/client/v3/keys/upload' && this.#authorised(init)) {
1448
+ const token = bearerToken(init);
1449
+ const deviceId = token ? this.#tokenDeviceId.get(token) : undefined;
1450
+ let body = {};
1451
+ try {
1452
+ body = JSON.parse(String(init?.body ?? '{}'));
1453
+ }
1454
+ catch {
1455
+ // Same tolerance as every other write here.
1456
+ }
1457
+ if (deviceId && body.device_keys) {
1458
+ this.#deviceKeysByDevice.set(deviceId, body.device_keys);
1459
+ }
1460
+ return Promise.resolve(jsonResponse(200, { one_time_key_counts: {} }));
1461
+ }
1462
+ // What a peer device's own machine queries to find another device --
1463
+ // chat#69's device verification needs a *real* device to resolve
1464
+ // through `CryptoApi.getUserDeviceInfo`/`requestDeviceVerification`,
1465
+ // which a fabricated response cannot satisfy: the querying machine
1466
+ // verifies the self-signature on whatever this returns, so it only
1467
+ // ever echoes a device's own `/keys/upload` body back, verbatim.
1468
+ if (url.pathname === '/_matrix/client/v3/keys/query' && this.#authorised(init)) {
1469
+ let body = {};
1470
+ try {
1471
+ body = JSON.parse(String(init?.body ?? '{}'));
1472
+ }
1473
+ catch {
1474
+ // Same tolerance as every other write here.
1475
+ }
1476
+ const requested = body.device_keys ?? {};
1477
+ const deviceKeys = {};
1478
+ // This fake only ever has one account on it (`this.userId`), so a
1479
+ // query for anybody else comes back empty rather than failing --
1480
+ // nothing this package does queries a second user's devices through
1481
+ // a single-account fake.
1482
+ if (Object.hasOwn(requested, this.userId)) {
1483
+ const wantedDeviceIds = requested[this.userId] ?? [];
1484
+ const devices = {};
1485
+ for (const [deviceId, keys] of this.#deviceKeysByDevice) {
1486
+ if (wantedDeviceIds.length === 0 || wantedDeviceIds.includes(deviceId)) {
1487
+ devices[deviceId] = keys;
1488
+ }
1489
+ }
1490
+ deviceKeys[this.userId] = devices;
1491
+ }
1492
+ return Promise.resolve(jsonResponse(200, { device_keys: deviceKeys, failures: {} }));
1493
+ }
1494
+ // What `CryptoApi.bootstrapSecretStorage` (chat#68) needs cross-signing
1495
+ // bootstrapped through first (`getCrypto()?.bootstrapCrossSigning`):
1496
+ // `getSecretStorageStatus` always checks the three cross-signing
1497
+ // secrets are in secret storage, with no way to turn that check off, so
1498
+ // nothing in this package can reach a "ready" secret storage without
1499
+ // these two succeeding first. Real Synapse protects both with
1500
+ // user-interactive auth; this fake does not model that dance -- a
1501
+ // caller with no `authUploadDeviceSigningKeys` skips straight past it
1502
+ // (`OutgoingRequestProcessor.makeRequestWithUIA`), and this fake simply
1503
+ // accepts whatever reaches it, the same tolerance every other write
1504
+ // here has for a body it does not otherwise validate.
1505
+ if (url.pathname === '/_matrix/client/v3/keys/device_signing/upload' &&
1506
+ this.#authorised(init)) {
1507
+ return Promise.resolve(jsonResponse(200, {}));
1508
+ }
1509
+ if (url.pathname === '/_matrix/client/v3/keys/signatures/upload' && this.#authorised(init)) {
1510
+ return Promise.resolve(jsonResponse(200, { failures: {} }));
1511
+ }
1512
+ // What `CryptoApi.requestDeviceVerification`/`requestOwnUserVerification`
1513
+ // (chat#69) send on their way out. Recorded in `sentToDevice` rather
1514
+ // than delivered to another device: `getVerificationRequestsToDevice
1515
+ // InProgress` reads the sender's own `OlmMachine` state, which only
1516
+ // needs the send to succeed, not to be received by anybody.
1517
+ const sendToDevice = url.pathname.match(/^\/_matrix\/client\/v3\/sendToDevice\/([^/]+)\/([^/]+)$/);
1518
+ if (sendToDevice && this.#authorised(init)) {
1519
+ let body = {};
1520
+ try {
1521
+ body = JSON.parse(String(init?.body ?? '{}'));
1522
+ }
1523
+ catch {
1524
+ // Same tolerance as every other write here.
1525
+ }
1526
+ this.sentToDevice.push({ eventType: decodeURIComponent(sendToDevice[1]), body });
1527
+ return Promise.resolve(jsonResponse(200, {}));
1528
+ }
1529
+ // User-level account data: `m.direct` keeps its own typed field and its
1530
+ // own seeding from room members; `CryptoApi.bootstrapSecretStorage`
1531
+ // (chat#68) and everything it writes (`m.secret_storage.default_key`,
1532
+ // `m.secret_storage.key.*`, the cross-signing and backup secrets) go
1533
+ // through `#globalAccountData` instead. `MatrixClient.setAccountData`
1534
+ // waits for the write's own remote echo on `ClientEvent.AccountData`
1535
+ // before resolving (`client.js`), so a PUT answered `200` is not
1536
+ // enough on its own -- `#deliverOrQueue({})` is what lets the next
1537
+ // `/sync` carry it back, same as `m.direct` already relied on.
1538
+ // `getAccountDataFromServer` falls back to a direct `GET` only before
1539
+ // the first sync completes (`client.js`), which nothing in this
1540
+ // package's crypto bootstrap does -- but a real homeserver still
1541
+ // answers `M_NOT_FOUND` for a type nobody has written, so this fake
1542
+ // does too rather than the `{}` every method here used to return
1543
+ // regardless of type or verb.
1544
+ const accountData = url.pathname.match(/^\/_matrix\/client\/v3\/user\/([^/]+)\/account_data\/([^/]+)$/);
1545
+ if (accountData && this.#authorised(init)) {
1546
+ const type = decodeURIComponent(accountData[2]);
1547
+ if (init?.method === 'GET') {
1548
+ if (type === 'm.direct') {
1549
+ return Object.keys(this.#direct).length
1550
+ ? Promise.resolve(jsonResponse(200, { ...this.#direct }))
1551
+ : Promise.resolve(jsonResponse(404, { errcode: 'M_NOT_FOUND', error: 'Account data not found' }));
1552
+ }
1553
+ const stored = this.#globalAccountData.get(type);
1554
+ return stored
1555
+ ? Promise.resolve(jsonResponse(200, stored))
1556
+ : Promise.resolve(jsonResponse(404, { errcode: 'M_NOT_FOUND', error: 'Account data not found' }));
1557
+ }
1558
+ let content = {};
1559
+ try {
1560
+ content = JSON.parse(String(init?.body ?? '{}'));
1561
+ }
1562
+ catch {
1563
+ // Same tolerance as every other write here.
1564
+ }
1565
+ if (type === 'm.direct') {
1566
+ this.#direct = content;
1567
+ }
1568
+ else {
1569
+ this.#globalAccountData.set(type, content);
1570
+ }
1571
+ this.#deliverOrQueue({});
1572
+ return Promise.resolve(jsonResponse(200, {}));
1573
+ }
1574
+ // What `client.setRoomAccountData` PUTs -- both keys `markRoomUnread`
1575
+ // writes (see `ChatClient.markRoomUnread`) get the marked-unread
1576
+ // treatment; any other room-scoped account data type -- a draft, most
1577
+ // likely -- is stored generically through `#setRoomAccountData`.
1578
+ const roomAccountData = url.pathname.match(/^\/_matrix\/client\/v3\/user\/([^/]+)\/rooms\/([^/]+)\/account_data\/([^/]+)$/);
1579
+ if (roomAccountData && this.#authorised(init)) {
1580
+ const roomId = decodeURIComponent(roomAccountData[2]);
1581
+ const type = decodeURIComponent(roomAccountData[3]);
1582
+ let content = {};
1583
+ try {
1584
+ content = JSON.parse(String(init?.body ?? '{}'));
1585
+ }
1586
+ catch {
1587
+ // Same tolerance as every other write here: a malformed body is
1588
+ // recorded as sent rather than failing the test for a reason it
1589
+ // did not choose.
1590
+ }
1591
+ if (type === 'm.marked_unread' || type === 'com.famedly.marked_unread') {
1592
+ this.#setMarkedUnread(roomId, Boolean(content.unread));
1593
+ }
1594
+ else {
1595
+ this.#setRoomAccountData(roomId, type, content);
1150
1596
  }
1151
1597
  return Promise.resolve(jsonResponse(200, {}));
1152
1598
  }
@@ -1207,6 +1653,39 @@ export class FakeChatServer {
1207
1653
  });
1208
1654
  return Promise.resolve(jsonResponse(200, {}));
1209
1655
  }
1656
+ // What `getExtendedProfileProperty`/`setExtendedProfileProperty`/
1657
+ // `deleteExtendedProfileProperty` read and write -- MSC4133 extended
1658
+ // profiles, `ChatClient.status`'s own storage (`docs/status.md`). This
1659
+ // fake only ever advertises the unstable feature flag (see `/versions`
1660
+ // above), so matrix-js-sdk always asks this prefix, never `/_matrix/
1661
+ // client/v3/profile/...`.
1662
+ const extendedProfileProperty = url.pathname.match(/^\/_matrix\/client\/unstable\/uk\.tcpip\.msc4133\/profile\/([^/]+)\/([^/]+)$/);
1663
+ if (extendedProfileProperty && this.#authorised(init)) {
1664
+ const profileUserId = decodeURIComponent(extendedProfileProperty[1]);
1665
+ const key = decodeURIComponent(extendedProfileProperty[2]);
1666
+ if (init?.method === 'PUT') {
1667
+ let body = {};
1668
+ try {
1669
+ body = JSON.parse(String(init?.body ?? '{}'));
1670
+ }
1671
+ catch {
1672
+ // Same tolerance as every other write here.
1673
+ }
1674
+ this.seedExtendedProfile(profileUserId, key, body[key]);
1675
+ this.extendedProfileWrites.push({ userId: profileUserId, key, value: body[key] });
1676
+ return Promise.resolve(jsonResponse(200, {}));
1677
+ }
1678
+ if (init?.method === 'DELETE') {
1679
+ this.#extendedProfiles.get(profileUserId)?.delete(key);
1680
+ this.extendedProfileWrites.push({ userId: profileUserId, key, value: undefined });
1681
+ return Promise.resolve(jsonResponse(200, {}));
1682
+ }
1683
+ const value = this.#extendedProfiles.get(profileUserId)?.get(key);
1684
+ if (value === undefined) {
1685
+ return Promise.resolve(jsonResponse(404, { errcode: 'M_NOT_FOUND', error: 'Not found' }));
1686
+ }
1687
+ return Promise.resolve(jsonResponse(200, { [key]: value }));
1688
+ }
1210
1689
  const receipt = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/receipt\/m\.read\/([^/]+)$/);
1211
1690
  if (receipt) {
1212
1691
  const token = bearerToken(init);