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