@wtfalch/chat 0.1.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/LICENSE +21 -0
- package/README.md +293 -0
- package/dist/chat/admin/admin.css +78 -0
- package/dist/chat/admin/index.d.ts +92 -0
- package/dist/chat/admin/index.js +124 -0
- package/dist/chat/admin/react.d.ts +40 -0
- package/dist/chat/admin/react.js +169 -0
- package/dist/chat/chat.css +1003 -0
- package/dist/chat/client.d.ts +30 -0
- package/dist/chat/client.js +1300 -0
- package/dist/chat/exchange.d.ts +9 -0
- package/dist/chat/exchange.js +31 -0
- package/dist/chat/fake/index.d.ts +27 -0
- package/dist/chat/fake/index.js +48 -0
- package/dist/chat/fake/intercept.d.ts +21 -0
- package/dist/chat/fake/intercept.js +57 -0
- package/dist/chat/fake/sample.d.ts +4 -0
- package/dist/chat/fake/sample.js +6 -0
- package/dist/chat/fake/server.d.ts +168 -0
- package/dist/chat/fake/server.js +811 -0
- package/dist/chat/fake/xhr.d.ts +3 -0
- package/dist/chat/fake/xhr.js +104 -0
- package/dist/chat/index.d.ts +10 -0
- package/dist/chat/index.js +9 -0
- package/dist/chat/markdown.d.ts +29 -0
- package/dist/chat/markdown.js +161 -0
- package/dist/chat/react/Attachment.d.ts +39 -0
- package/dist/chat/react/Attachment.js +113 -0
- package/dist/chat/react/Chat.d.ts +48 -0
- package/dist/chat/react/Chat.js +139 -0
- package/dist/chat/react/Composer.d.ts +25 -0
- package/dist/chat/react/Composer.js +157 -0
- package/dist/chat/react/MessageRow.d.ts +21 -0
- package/dist/chat/react/MessageRow.js +114 -0
- package/dist/chat/react/NewDirectMessage.d.ts +23 -0
- package/dist/chat/react/NewDirectMessage.js +47 -0
- package/dist/chat/react/ThreadPanel.d.ts +25 -0
- package/dist/chat/react/ThreadPanel.js +17 -0
- package/dist/chat/react/Timeline.d.ts +27 -0
- package/dist/chat/react/Timeline.js +120 -0
- package/dist/chat/react/index.d.ts +7 -0
- package/dist/chat/react/index.js +6 -0
- package/dist/chat/react/mentions.d.ts +34 -0
- package/dist/chat/react/mentions.js +70 -0
- package/dist/chat/react/scroll.d.ts +26 -0
- package/dist/chat/react/scroll.js +27 -0
- package/dist/chat/react/timelineLayout.d.ts +26 -0
- package/dist/chat/react/timelineLayout.js +47 -0
- package/dist/chat/sanitize.d.ts +49 -0
- package/dist/chat/sanitize.js +264 -0
- package/dist/chat/store.d.ts +16 -0
- package/dist/chat/store.js +25 -0
- package/dist/chat/types.d.ts +340 -0
- package/dist/chat/types.js +1 -0
- package/package.json +88 -0
|
@@ -0,0 +1,811 @@
|
|
|
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
|
+
userId;
|
|
35
|
+
/** The Matrix server name, as `userId` gives it -- what an `mxc://`
|
|
36
|
+
* reference from this homeserver names. */
|
|
37
|
+
serverName;
|
|
38
|
+
/** How many times `/_chat/exchange` has been called. */
|
|
39
|
+
exchangeCount = 0;
|
|
40
|
+
/** Every Matrix access token this server has ever minted, oldest first --
|
|
41
|
+
* for a test that asserts one was never logged. */
|
|
42
|
+
mintedTokens = [];
|
|
43
|
+
/** Every `m.read` receipt this server has answered, in arrival order --
|
|
44
|
+
* for a test that asserts `markRoomRead` actually called the wire. */
|
|
45
|
+
receipts = [];
|
|
46
|
+
/** Every room `/createRoom` has made, in order -- for a test that asserts
|
|
47
|
+
* what shape a DM was created in. */
|
|
48
|
+
createdRooms = [];
|
|
49
|
+
/** Every event this server has accepted from the client, in order -- for
|
|
50
|
+
* a test that asserts what relation a reply was sent with. */
|
|
51
|
+
sent = [];
|
|
52
|
+
/** Every file the client has uploaded, by media id -- so a test can
|
|
53
|
+
* assert what went up, and so the download route has something to
|
|
54
|
+
* answer with. */
|
|
55
|
+
media = new Map();
|
|
56
|
+
/** Every media download this server has answered, with the header the
|
|
57
|
+
* request carried -- for a test that asserts nothing reaches the
|
|
58
|
+
* legacy unauthenticated endpoints, and that the token was sent. */
|
|
59
|
+
mediaRequests = [];
|
|
60
|
+
#dispose;
|
|
61
|
+
#rooms;
|
|
62
|
+
#tokenLifetimeMs;
|
|
63
|
+
#now;
|
|
64
|
+
#validTokens = new Set();
|
|
65
|
+
#tokenSeq = 0;
|
|
66
|
+
#batchSeq = 0;
|
|
67
|
+
#eventSeq = 0;
|
|
68
|
+
#pending;
|
|
69
|
+
#parkedWaiters = [];
|
|
70
|
+
#disposed = false;
|
|
71
|
+
#direct = {};
|
|
72
|
+
/** Every message event this server has ever had in a room, in order. The
|
|
73
|
+
* full sync replays it, and `/event` and `/relations` are answered out
|
|
74
|
+
* of it -- matrix-js-sdk asks for both while it builds a thread. */
|
|
75
|
+
#events = new Map();
|
|
76
|
+
#tags = new Map();
|
|
77
|
+
#roomSeq = 0;
|
|
78
|
+
#mediaSeq = 0;
|
|
79
|
+
/** Deliveries made while no poll was parked, waiting for the next one --
|
|
80
|
+
* so a test never has to interleave its own `waitForParkedPoll()` with
|
|
81
|
+
* a client call that itself writes and then waits for the echo. */
|
|
82
|
+
#queued = [];
|
|
83
|
+
constructor(options = {}) {
|
|
84
|
+
this.homeserver =
|
|
85
|
+
options.homeserver ?? `https://chat.${Math.random().toString(36).slice(2)}.example.test`;
|
|
86
|
+
this.exchangeUrl = `${this.homeserver}/_chat/exchange`;
|
|
87
|
+
this.userId = options.userId ?? '@zfake:chat.example.test';
|
|
88
|
+
this.serverName = this.userId.split(':').slice(1).join(':');
|
|
89
|
+
this.#rooms = [...(options.rooms ?? [])];
|
|
90
|
+
this.#tokenLifetimeMs = options.tokenLifetimeMs ?? 10 * 60_000;
|
|
91
|
+
this.#now = options.now ?? Date.now;
|
|
92
|
+
for (const room of this.#rooms)
|
|
93
|
+
this.#materialise(room);
|
|
94
|
+
for (const room of this.#rooms) {
|
|
95
|
+
if (!room.isDirect)
|
|
96
|
+
continue;
|
|
97
|
+
for (const member of room.members?.length ? room.members : [{ userId: PEER_USER_ID }]) {
|
|
98
|
+
this.#direct[member.userId] = [...(this.#direct[member.userId] ?? []), room.id];
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
this.#dispose = installFetchRoute((input, init) => this.#route(input, init));
|
|
102
|
+
}
|
|
103
|
+
dispose() {
|
|
104
|
+
if (this.#disposed)
|
|
105
|
+
return;
|
|
106
|
+
this.#disposed = true;
|
|
107
|
+
if (this.#pending) {
|
|
108
|
+
const pending = this.#pending;
|
|
109
|
+
this.#pending = undefined;
|
|
110
|
+
pending.cleanup();
|
|
111
|
+
pending.reject(new DOMException('The operation was aborted.', 'AbortError'));
|
|
112
|
+
}
|
|
113
|
+
this.#dispose();
|
|
114
|
+
}
|
|
115
|
+
/** Resolves once a `/sync` request is parked waiting for a test to drive
|
|
116
|
+
* it -- immediately if one already is. */
|
|
117
|
+
async waitForParkedPoll() {
|
|
118
|
+
if (this.#pending)
|
|
119
|
+
return;
|
|
120
|
+
await new Promise((resolve) => this.#parkedWaiters.push(resolve));
|
|
121
|
+
}
|
|
122
|
+
/** Adds a room and, if a poll is parked, delivers it now. Throws if
|
|
123
|
+
* nothing is parked -- await `waitForParkedPoll()` first. */
|
|
124
|
+
addRoom(seed) {
|
|
125
|
+
this.#rooms.push(seed);
|
|
126
|
+
this.#materialise(seed);
|
|
127
|
+
this.#deliverParked({ [seed.id]: this.#joinEntry(seed) });
|
|
128
|
+
}
|
|
129
|
+
/** Answers a parked poll with nothing new -- proving the connection is
|
|
130
|
+
* healthy (a real incremental sync, just an empty one) without adding a
|
|
131
|
+
* room. Throws if nothing is parked. */
|
|
132
|
+
respondEmpty() {
|
|
133
|
+
this.#deliverParked({});
|
|
134
|
+
}
|
|
135
|
+
/** Ends every currently-minted token, as if the person's session had been
|
|
136
|
+
* revoked or the token had simply expired server-side. If a poll is
|
|
137
|
+
* parked, it is answered with `M_UNKNOWN_TOKEN` immediately; otherwise
|
|
138
|
+
* the next request to arrive gets it. */
|
|
139
|
+
invalidateCurrentToken() {
|
|
140
|
+
this.#validTokens.clear();
|
|
141
|
+
if (!this.#pending)
|
|
142
|
+
return;
|
|
143
|
+
const pending = this.#pending;
|
|
144
|
+
this.#pending = undefined;
|
|
145
|
+
pending.cleanup();
|
|
146
|
+
pending.resolve(jsonResponse(401, { errcode: 'M_UNKNOWN_TOKEN', error: 'Invalid access token' }));
|
|
147
|
+
}
|
|
148
|
+
/** Answers a parked poll with a `400`, as Synapse does when it refuses
|
|
149
|
+
* the client's stored `since` position (confirmed live after a long
|
|
150
|
+
* enough time offline). Throws if nothing is parked. */
|
|
151
|
+
refuseCurrentPoll() {
|
|
152
|
+
if (!this.#pending) {
|
|
153
|
+
throw new Error('fake chat: refuseCurrentPoll called with no /sync request parked');
|
|
154
|
+
}
|
|
155
|
+
const pending = this.#pending;
|
|
156
|
+
this.#pending = undefined;
|
|
157
|
+
pending.cleanup();
|
|
158
|
+
pending.resolve(jsonResponse(400, { errcode: 'M_UNKNOWN', error: 'Invalid pagination token' }));
|
|
159
|
+
}
|
|
160
|
+
/** Delivers a parked poll as an existing, already-known room receiving
|
|
161
|
+
* one new message from the fake peer -- a timeline event and a bumped
|
|
162
|
+
* notification count together, the way a real incremental `/sync`
|
|
163
|
+
* carries both at once. Returns the minted event id, for a test that
|
|
164
|
+
* then calls `markRoomRead` against it. Throws if nothing is parked. */
|
|
165
|
+
receiveMessage(roomId, notificationCount = 1) {
|
|
166
|
+
this.#eventSeq += 1;
|
|
167
|
+
const eventId = `$msg-${this.#eventSeq}`;
|
|
168
|
+
this.#deliverParked({
|
|
169
|
+
[roomId]: {
|
|
170
|
+
summary: {},
|
|
171
|
+
state: { events: [] },
|
|
172
|
+
timeline: {
|
|
173
|
+
events: [
|
|
174
|
+
{
|
|
175
|
+
type: 'm.room.message',
|
|
176
|
+
event_id: eventId,
|
|
177
|
+
sender: PEER_USER_ID,
|
|
178
|
+
origin_server_ts: this.#now(),
|
|
179
|
+
content: { msgtype: 'm.text', body: 'hi' },
|
|
180
|
+
},
|
|
181
|
+
],
|
|
182
|
+
limited: false,
|
|
183
|
+
prev_batch: `t-${roomId}`,
|
|
184
|
+
},
|
|
185
|
+
ephemeral: { events: [] },
|
|
186
|
+
account_data: { events: [] },
|
|
187
|
+
unread_notifications: { highlight_count: 0, notification_count: notificationCount },
|
|
188
|
+
},
|
|
189
|
+
});
|
|
190
|
+
return eventId;
|
|
191
|
+
}
|
|
192
|
+
/** Delivers a parked poll renaming an already-known room -- an
|
|
193
|
+
* `m.room.name` state event, the way a real incremental `/sync` carries
|
|
194
|
+
* a rename. Throws if nothing is parked. */
|
|
195
|
+
renameRoom(roomId, name) {
|
|
196
|
+
const seed = this.#rooms.find((room) => room.id === roomId);
|
|
197
|
+
if (seed)
|
|
198
|
+
seed.name = name;
|
|
199
|
+
this.#eventSeq += 1;
|
|
200
|
+
this.#deliverParked({
|
|
201
|
+
[roomId]: {
|
|
202
|
+
summary: {},
|
|
203
|
+
state: {
|
|
204
|
+
events: [
|
|
205
|
+
{
|
|
206
|
+
type: 'm.room.name',
|
|
207
|
+
state_key: '',
|
|
208
|
+
event_id: `$rename-${this.#eventSeq}`,
|
|
209
|
+
sender: this.userId,
|
|
210
|
+
origin_server_ts: this.#now(),
|
|
211
|
+
content: { name },
|
|
212
|
+
},
|
|
213
|
+
],
|
|
214
|
+
},
|
|
215
|
+
timeline: { events: [], limited: false, prev_batch: `t-${roomId}` },
|
|
216
|
+
ephemeral: { events: [] },
|
|
217
|
+
account_data: { events: [] },
|
|
218
|
+
unread_notifications: { highlight_count: 0, notification_count: 0 },
|
|
219
|
+
},
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
/** Delivers a parked poll with the fake account leaving `roomId` -- a
|
|
223
|
+
* `rooms.leave` block, the way a real incremental `/sync` reports a kick
|
|
224
|
+
* or a self-leave. Throws if nothing is parked. */
|
|
225
|
+
leaveRoom(roomId) {
|
|
226
|
+
this.#rooms = this.#rooms.filter((room) => room.id !== roomId);
|
|
227
|
+
this.#eventSeq += 1;
|
|
228
|
+
this.#deliverParked({}, {
|
|
229
|
+
[roomId]: {
|
|
230
|
+
state: { events: [] },
|
|
231
|
+
timeline: {
|
|
232
|
+
events: [
|
|
233
|
+
{
|
|
234
|
+
type: 'm.room.member',
|
|
235
|
+
state_key: this.userId,
|
|
236
|
+
event_id: `$leave-${this.#eventSeq}`,
|
|
237
|
+
sender: this.userId,
|
|
238
|
+
origin_server_ts: this.#now(),
|
|
239
|
+
content: { membership: 'leave' },
|
|
240
|
+
},
|
|
241
|
+
],
|
|
242
|
+
limited: false,
|
|
243
|
+
prev_batch: `t-${roomId}`,
|
|
244
|
+
},
|
|
245
|
+
account_data: { events: [] },
|
|
246
|
+
},
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
#nextBatch() {
|
|
250
|
+
this.#batchSeq += 1;
|
|
251
|
+
return `batch-${this.#batchSeq}`;
|
|
252
|
+
}
|
|
253
|
+
#accountDataEvents() {
|
|
254
|
+
return Object.keys(this.#direct).length
|
|
255
|
+
? [{ type: 'm.direct', content: { ...this.#direct } }]
|
|
256
|
+
: [];
|
|
257
|
+
}
|
|
258
|
+
/** A room's own account data: the tags a test or the client has set on
|
|
259
|
+
* it. `m.tag` is how `hideDirectMessage` reaches `room.tags`. */
|
|
260
|
+
#roomAccountDataEvents(roomId) {
|
|
261
|
+
const tags = this.#tags.get(roomId);
|
|
262
|
+
if (!tags)
|
|
263
|
+
return [];
|
|
264
|
+
const content = {};
|
|
265
|
+
for (const tag of tags)
|
|
266
|
+
content[tag] = {};
|
|
267
|
+
return [{ type: 'm.tag', content: { tags: content } }];
|
|
268
|
+
}
|
|
269
|
+
#memberEvent(seed, member, membership) {
|
|
270
|
+
return {
|
|
271
|
+
type: 'm.room.member',
|
|
272
|
+
state_key: member.userId,
|
|
273
|
+
event_id: `$member-${seed.id}-${member.userId}-${membership}`,
|
|
274
|
+
sender: this.userId,
|
|
275
|
+
origin_server_ts: this.#now(),
|
|
276
|
+
content: { membership, displayname: member.name ?? member.userId },
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
#joinEntry(seed) {
|
|
280
|
+
const now = this.#now();
|
|
281
|
+
const events = [
|
|
282
|
+
{
|
|
283
|
+
type: 'm.room.create',
|
|
284
|
+
state_key: '',
|
|
285
|
+
event_id: `$create-${seed.id}`,
|
|
286
|
+
sender: this.userId,
|
|
287
|
+
origin_server_ts: now,
|
|
288
|
+
// A space is a room whose create event carries `type: 'm.space'`;
|
|
289
|
+
// that one field is the whole difference `isSpaceRoom()` reads.
|
|
290
|
+
content: {
|
|
291
|
+
creator: this.userId,
|
|
292
|
+
room_version: '10',
|
|
293
|
+
...(seed.isSpace ? { type: 'm.space' } : {}),
|
|
294
|
+
},
|
|
295
|
+
},
|
|
296
|
+
{
|
|
297
|
+
type: 'm.room.member',
|
|
298
|
+
state_key: this.userId,
|
|
299
|
+
event_id: `$member-${seed.id}`,
|
|
300
|
+
sender: this.userId,
|
|
301
|
+
origin_server_ts: now,
|
|
302
|
+
content: { membership: 'join' },
|
|
303
|
+
},
|
|
304
|
+
];
|
|
305
|
+
for (const member of seed.members ?? [])
|
|
306
|
+
events.push(this.#memberEvent(seed, member, 'join'));
|
|
307
|
+
for (const member of seed.invited ?? [])
|
|
308
|
+
events.push(this.#memberEvent(seed, member, 'invite'));
|
|
309
|
+
// Every seeded room carries an `m.room.name`, including a direct one.
|
|
310
|
+
// A real member-created DM cannot: the Synapse gate refuses a `name`
|
|
311
|
+
// from anyone but the chat admin, and Synapse names such a room from
|
|
312
|
+
// its members instead. The fake names it up front so a story and a
|
|
313
|
+
// test have something to read; nothing in the client depends on where
|
|
314
|
+
// a room's name came from.
|
|
315
|
+
events.push({
|
|
316
|
+
type: 'm.room.name',
|
|
317
|
+
state_key: '',
|
|
318
|
+
event_id: `$name-${seed.id}`,
|
|
319
|
+
sender: this.userId,
|
|
320
|
+
origin_server_ts: now,
|
|
321
|
+
content: { name: seed.name },
|
|
322
|
+
});
|
|
323
|
+
return {
|
|
324
|
+
summary: {},
|
|
325
|
+
state: { events },
|
|
326
|
+
timeline: {
|
|
327
|
+
events: this.#events.get(seed.id) ?? [],
|
|
328
|
+
limited: false,
|
|
329
|
+
prev_batch: `t-${seed.id}`,
|
|
330
|
+
},
|
|
331
|
+
ephemeral: { events: [] },
|
|
332
|
+
account_data: { events: this.#roomAccountDataEvents(seed.id) },
|
|
333
|
+
unread_notifications: { highlight_count: 0, notification_count: seed.notificationCount ?? 0 },
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
/** One `m.room.message`, threaded when the seed names a root. The
|
|
337
|
+
* `m.thread` relation is the whole of what makes a reply a thread reply
|
|
338
|
+
* -- matrix-js-sdk reads it off the event and routes it, exactly as it
|
|
339
|
+
* does against Synapse. */
|
|
340
|
+
#messageEvent(seed) {
|
|
341
|
+
this.#eventSeq += 1;
|
|
342
|
+
return {
|
|
343
|
+
type: 'm.room.message',
|
|
344
|
+
event_id: seed.id ?? `$seeded-${this.#eventSeq}`,
|
|
345
|
+
sender: seed.sender ?? PEER_USER_ID,
|
|
346
|
+
origin_server_ts: this.#now(),
|
|
347
|
+
content: {
|
|
348
|
+
msgtype: 'm.text',
|
|
349
|
+
body: seed.body,
|
|
350
|
+
...(seed.threadRootId
|
|
351
|
+
? { 'm.relates_to': { rel_type: 'm.thread', event_id: seed.threadRootId } }
|
|
352
|
+
: {}),
|
|
353
|
+
},
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
/** Mints a seed's messages once and remembers them. Minting them inside
|
|
357
|
+
* `#joinEntry` instead would give the same seeded message a new id every
|
|
358
|
+
* time an entry is rebuilt -- which happens on every tag change. */
|
|
359
|
+
#materialise(seed) {
|
|
360
|
+
if (this.#events.has(seed.id))
|
|
361
|
+
return;
|
|
362
|
+
this.#events.set(seed.id, (seed.messages ?? []).map((message) => this.#messageEvent(message)));
|
|
363
|
+
}
|
|
364
|
+
#record(roomId, event) {
|
|
365
|
+
this.#events.set(roomId, [...(this.#events.get(roomId) ?? []), event]);
|
|
366
|
+
}
|
|
367
|
+
/** One room's incremental entry, carrying just these events. */
|
|
368
|
+
#timelineEntry(roomId, events) {
|
|
369
|
+
return {
|
|
370
|
+
summary: {},
|
|
371
|
+
state: { events: [] },
|
|
372
|
+
timeline: { events, limited: false, prev_batch: `t-${roomId}` },
|
|
373
|
+
ephemeral: { events: [] },
|
|
374
|
+
account_data: { events: this.#roomAccountDataEvents(roomId) },
|
|
375
|
+
unread_notifications: { highlight_count: 0, notification_count: 0 },
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
/** Delivers a parked poll as somebody else reacting to a message.
|
|
379
|
+
* Returns the minted event id, so a test can then redact it. Throws if
|
|
380
|
+
* nothing is parked. */
|
|
381
|
+
receiveReaction(roomId, targetId, key, sender = PEER_USER_ID) {
|
|
382
|
+
this.#eventSeq += 1;
|
|
383
|
+
const event = {
|
|
384
|
+
type: 'm.reaction',
|
|
385
|
+
event_id: `$react-${this.#eventSeq}`,
|
|
386
|
+
sender,
|
|
387
|
+
origin_server_ts: this.#now(),
|
|
388
|
+
content: { 'm.relates_to': { rel_type: 'm.annotation', event_id: targetId, key } },
|
|
389
|
+
};
|
|
390
|
+
this.#record(roomId, event);
|
|
391
|
+
this.#deliverParked({ [roomId]: this.#timelineEntry(roomId, [event]) });
|
|
392
|
+
return event.event_id;
|
|
393
|
+
}
|
|
394
|
+
/** Delivers a parked poll as one more message arriving in an existing
|
|
395
|
+
* room -- threaded, when `threadRootId` is given. Returns the minted
|
|
396
|
+
* event id. Throws if nothing is parked. */
|
|
397
|
+
receiveThreadReply(roomId, threadRootId, body = 'a reply') {
|
|
398
|
+
const event = this.#messageEvent({ body, threadRootId });
|
|
399
|
+
this.#record(roomId, event);
|
|
400
|
+
this.#deliverParked({
|
|
401
|
+
[roomId]: {
|
|
402
|
+
summary: {},
|
|
403
|
+
state: { events: [] },
|
|
404
|
+
timeline: { events: [event], limited: false, prev_batch: `t-${roomId}` },
|
|
405
|
+
ephemeral: { events: [] },
|
|
406
|
+
account_data: { events: this.#roomAccountDataEvents(roomId) },
|
|
407
|
+
unread_notifications: { highlight_count: 0, notification_count: 0 },
|
|
408
|
+
},
|
|
409
|
+
});
|
|
410
|
+
return event.event_id;
|
|
411
|
+
}
|
|
412
|
+
/** Delivers a parked poll as somebody else editing one of their own
|
|
413
|
+
* messages: an `m.replace` carrying `m.new_content`, which is the whole
|
|
414
|
+
* of how Matrix edits a message. Returns the edit's own event id.
|
|
415
|
+
* Throws if nothing is parked. */
|
|
416
|
+
receiveEdit(roomId, targetId, body, sender = PEER_USER_ID) {
|
|
417
|
+
this.#eventSeq += 1;
|
|
418
|
+
const event = {
|
|
419
|
+
type: 'm.room.message',
|
|
420
|
+
event_id: `$edit-${this.#eventSeq}`,
|
|
421
|
+
sender,
|
|
422
|
+
origin_server_ts: this.#now(),
|
|
423
|
+
content: {
|
|
424
|
+
msgtype: 'm.text',
|
|
425
|
+
body: `* ${body}`,
|
|
426
|
+
'm.new_content': { msgtype: 'm.text', body },
|
|
427
|
+
'm.relates_to': { rel_type: 'm.replace', event_id: targetId },
|
|
428
|
+
},
|
|
429
|
+
};
|
|
430
|
+
this.#record(roomId, event);
|
|
431
|
+
this.#deliverParked({ [roomId]: this.#timelineEntry(roomId, [event]) });
|
|
432
|
+
return event.event_id;
|
|
433
|
+
}
|
|
434
|
+
/** Delivers a parked poll as a message being redacted. The target keeps
|
|
435
|
+
* its place in the room's record with its content emptied, exactly as
|
|
436
|
+
* `#route`'s own redact endpoint does and as Synapse does -- a redacted
|
|
437
|
+
* event is still an event. Throws if nothing is parked. */
|
|
438
|
+
receiveRedaction(roomId, targetId, sender = PEER_USER_ID) {
|
|
439
|
+
this.#eventSeq += 1;
|
|
440
|
+
const event = {
|
|
441
|
+
type: 'm.room.redaction',
|
|
442
|
+
event_id: `$redact-${this.#eventSeq}`,
|
|
443
|
+
sender,
|
|
444
|
+
origin_server_ts: this.#now(),
|
|
445
|
+
content: {},
|
|
446
|
+
redacts: targetId,
|
|
447
|
+
};
|
|
448
|
+
this.#events.set(roomId, (this.#events.get(roomId) ?? []).map((entry) => entry.event_id === targetId ? { ...entry, content: {} } : entry));
|
|
449
|
+
this.#record(roomId, event);
|
|
450
|
+
this.#deliverParked({ [roomId]: this.#timelineEntry(roomId, [event]) });
|
|
451
|
+
return event.event_id;
|
|
452
|
+
}
|
|
453
|
+
#fullSyncBody() {
|
|
454
|
+
const join = {};
|
|
455
|
+
for (const room of this.#rooms)
|
|
456
|
+
join[room.id] = this.#joinEntry(room);
|
|
457
|
+
return {
|
|
458
|
+
next_batch: this.#nextBatch(),
|
|
459
|
+
rooms: { join },
|
|
460
|
+
account_data: { events: this.#accountDataEvents() },
|
|
461
|
+
presence: { events: [] },
|
|
462
|
+
to_device: { events: [] },
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
#deliverParked(join, leave = {}) {
|
|
466
|
+
if (!this.#pending) {
|
|
467
|
+
throw new Error('fake chat: addRoom called with no /sync request parked');
|
|
468
|
+
}
|
|
469
|
+
this.#answerParked(join, leave);
|
|
470
|
+
}
|
|
471
|
+
/** Delivers now if a poll is parked, and otherwise holds the payload for
|
|
472
|
+
* the next one. What `#deliverParked` refuses to do: a test driving the
|
|
473
|
+
* server by hand wants the throw, because "nothing was parked" means its
|
|
474
|
+
* own sequencing is wrong -- but a write the *client* made (a tag, an
|
|
475
|
+
* `m.direct` update, a created room) is answered whenever the client
|
|
476
|
+
* next polls, exactly as Synapse would. */
|
|
477
|
+
#deliverOrQueue(join, leave = {}) {
|
|
478
|
+
if (this.#pending) {
|
|
479
|
+
this.#answerParked(join, leave);
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
this.#queued.push({ join, leave });
|
|
483
|
+
}
|
|
484
|
+
#answerParked(join, leave) {
|
|
485
|
+
const pending = this.#pending;
|
|
486
|
+
if (!pending)
|
|
487
|
+
return;
|
|
488
|
+
this.#pending = undefined;
|
|
489
|
+
pending.cleanup();
|
|
490
|
+
pending.resolve(jsonResponse(200, {
|
|
491
|
+
next_batch: this.#nextBatch(),
|
|
492
|
+
rooms: { join, leave },
|
|
493
|
+
account_data: { events: this.#accountDataEvents() },
|
|
494
|
+
presence: { events: [] },
|
|
495
|
+
to_device: { events: [] },
|
|
496
|
+
}));
|
|
497
|
+
}
|
|
498
|
+
/** The fake account's own view of a created direct room: the invitees
|
|
499
|
+
* are invited, nobody else has joined yet, and it carries whatever tags
|
|
500
|
+
* it has picked up. */
|
|
501
|
+
#createRoom(body) {
|
|
502
|
+
this.#roomSeq += 1;
|
|
503
|
+
const id = `!created-${this.#roomSeq}:${new URL(this.homeserver).host}`;
|
|
504
|
+
const invited = (body.invite ?? []).map((userId) => ({ userId }));
|
|
505
|
+
const seed = {
|
|
506
|
+
id,
|
|
507
|
+
name: invited.map((member) => member.userId).join(', ') || 'New room',
|
|
508
|
+
isDirect: Boolean(body.is_direct),
|
|
509
|
+
invited,
|
|
510
|
+
};
|
|
511
|
+
this.#rooms.push(seed);
|
|
512
|
+
this.#materialise(seed);
|
|
513
|
+
this.createdRooms.push({ id, isDirect: Boolean(body.is_direct), invite: body.invite ?? [] });
|
|
514
|
+
this.#deliverOrQueue({ [id]: this.#joinEntry(seed) });
|
|
515
|
+
return id;
|
|
516
|
+
}
|
|
517
|
+
#setTag(roomId, tag, on) {
|
|
518
|
+
const tags = this.#tags.get(roomId) ?? new Set();
|
|
519
|
+
if (on)
|
|
520
|
+
tags.add(tag);
|
|
521
|
+
else
|
|
522
|
+
tags.delete(tag);
|
|
523
|
+
this.#tags.set(roomId, tags);
|
|
524
|
+
const seed = this.#rooms.find((room) => room.id === roomId);
|
|
525
|
+
if (seed)
|
|
526
|
+
this.#deliverOrQueue({ [roomId]: this.#joinEntry(seed) });
|
|
527
|
+
}
|
|
528
|
+
#handleExchange(init) {
|
|
529
|
+
this.exchangeCount += 1;
|
|
530
|
+
const zitadelToken = bearerToken(init);
|
|
531
|
+
if (!zitadelToken) {
|
|
532
|
+
return Promise.resolve(jsonResponse(401, { reason: 'token_expired' }));
|
|
533
|
+
}
|
|
534
|
+
let deviceId = 'fake-device';
|
|
535
|
+
try {
|
|
536
|
+
const body = JSON.parse(String(init?.body ?? '{}'));
|
|
537
|
+
if (typeof body.device_id === 'string')
|
|
538
|
+
deviceId = body.device_id;
|
|
539
|
+
}
|
|
540
|
+
catch {
|
|
541
|
+
// Malformed body: fall through with the default device id, same as
|
|
542
|
+
// any other field this fake does not validate strictly.
|
|
543
|
+
}
|
|
544
|
+
const token = `fake-matrix-token-${++this.#tokenSeq}`;
|
|
545
|
+
this.#validTokens.add(token);
|
|
546
|
+
this.mintedTokens.push(token);
|
|
547
|
+
return Promise.resolve(jsonResponse(200, {
|
|
548
|
+
homeserver: this.homeserver,
|
|
549
|
+
user_id: this.userId,
|
|
550
|
+
device_id: deviceId,
|
|
551
|
+
access_token: token,
|
|
552
|
+
expires_at: new Date(this.#now() + this.#tokenLifetimeMs).toISOString(),
|
|
553
|
+
}));
|
|
554
|
+
}
|
|
555
|
+
#authorised(init) {
|
|
556
|
+
const token = bearerToken(init);
|
|
557
|
+
return Boolean(token && this.#validTokens.has(token));
|
|
558
|
+
}
|
|
559
|
+
#handleSync(url, init) {
|
|
560
|
+
const token = bearerToken(init);
|
|
561
|
+
if (!token || !this.#validTokens.has(token)) {
|
|
562
|
+
return Promise.resolve(jsonResponse(401, { errcode: 'M_UNKNOWN_TOKEN', error: 'Invalid access token' }));
|
|
563
|
+
}
|
|
564
|
+
if (url.searchParams.get('since') === null) {
|
|
565
|
+
return Promise.resolve(jsonResponse(200, this.#fullSyncBody()));
|
|
566
|
+
}
|
|
567
|
+
const queued = this.#queued.shift();
|
|
568
|
+
if (queued) {
|
|
569
|
+
return Promise.resolve(jsonResponse(200, {
|
|
570
|
+
next_batch: this.#nextBatch(),
|
|
571
|
+
rooms: { join: queued.join, leave: queued.leave },
|
|
572
|
+
account_data: { events: this.#accountDataEvents() },
|
|
573
|
+
presence: { events: [] },
|
|
574
|
+
to_device: { events: [] },
|
|
575
|
+
}));
|
|
576
|
+
}
|
|
577
|
+
return new Promise((resolve, reject) => {
|
|
578
|
+
const signal = init?.signal;
|
|
579
|
+
const onAbort = () => {
|
|
580
|
+
this.#pending = undefined;
|
|
581
|
+
signal?.removeEventListener('abort', onAbort);
|
|
582
|
+
reject(new DOMException('The operation was aborted.', 'AbortError'));
|
|
583
|
+
};
|
|
584
|
+
signal?.addEventListener('abort', onAbort);
|
|
585
|
+
this.#pending = {
|
|
586
|
+
resolve: (response) => {
|
|
587
|
+
signal?.removeEventListener('abort', onAbort);
|
|
588
|
+
resolve(response);
|
|
589
|
+
},
|
|
590
|
+
reject,
|
|
591
|
+
cleanup: () => signal?.removeEventListener('abort', onAbort),
|
|
592
|
+
};
|
|
593
|
+
const waiters = this.#parkedWaiters;
|
|
594
|
+
this.#parkedWaiters = [];
|
|
595
|
+
for (const waiter of waiters)
|
|
596
|
+
waiter();
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
#route(input, init) {
|
|
600
|
+
const rawUrl = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
|
|
601
|
+
if (rawUrl.startsWith(this.exchangeUrl))
|
|
602
|
+
return this.#handleExchange(init);
|
|
603
|
+
if (!rawUrl.startsWith(this.homeserver))
|
|
604
|
+
return null;
|
|
605
|
+
const url = new URL(rawUrl);
|
|
606
|
+
if (url.pathname === '/_matrix/client/versions') {
|
|
607
|
+
return Promise.resolve(jsonResponse(200, { versions: ['v1.4'], unstable_features: {} }));
|
|
608
|
+
}
|
|
609
|
+
if (url.pathname === '/_matrix/client/v3/pushrules/') {
|
|
610
|
+
return Promise.resolve(jsonResponse(200, {
|
|
611
|
+
global: { content: [], override: [], room: [], sender: [], underride: [] },
|
|
612
|
+
}));
|
|
613
|
+
}
|
|
614
|
+
if (url.pathname.startsWith('/_matrix/client/v3/user/') && url.pathname.endsWith('/filter')) {
|
|
615
|
+
return Promise.resolve(jsonResponse(200, { filter_id: 'fake-filter' }));
|
|
616
|
+
}
|
|
617
|
+
if (url.pathname === '/_matrix/client/v3/sync') {
|
|
618
|
+
return this.#handleSync(url, init);
|
|
619
|
+
}
|
|
620
|
+
if (url.pathname === '/_matrix/client/v3/createRoom' && this.#authorised(init)) {
|
|
621
|
+
let body = {};
|
|
622
|
+
try {
|
|
623
|
+
body = JSON.parse(String(init?.body ?? '{}'));
|
|
624
|
+
}
|
|
625
|
+
catch {
|
|
626
|
+
// Same tolerance as the exchange: a malformed body creates a plain
|
|
627
|
+
// room rather than failing a test for a reason it did not choose.
|
|
628
|
+
}
|
|
629
|
+
// What the Synapse gate does to a member-created room dressed as a
|
|
630
|
+
// channel (chat plan section 5). The fake refuses it for the same
|
|
631
|
+
// reason: a client that starts sending a `name` should fail here
|
|
632
|
+
// rather than in production.
|
|
633
|
+
if (body.name !== undefined) {
|
|
634
|
+
return Promise.resolve(jsonResponse(403, { errcode: 'M_FORBIDDEN', error: 'Not allowed' }));
|
|
635
|
+
}
|
|
636
|
+
return Promise.resolve(jsonResponse(200, { room_id: this.#createRoom(body) }));
|
|
637
|
+
}
|
|
638
|
+
// What matrix-js-sdk asks for while it builds a thread: the root event
|
|
639
|
+
// itself, and everything related to it.
|
|
640
|
+
const event = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/event\/([^/]+)$/);
|
|
641
|
+
if (event && this.#authorised(init)) {
|
|
642
|
+
const roomId = decodeURIComponent(event[1]);
|
|
643
|
+
const eventId = decodeURIComponent(event[2]);
|
|
644
|
+
const found = this.#events.get(roomId)?.find((entry) => entry.event_id === eventId);
|
|
645
|
+
return Promise.resolve(found
|
|
646
|
+
? jsonResponse(200, { ...found, room_id: roomId })
|
|
647
|
+
: jsonResponse(404, { errcode: 'M_NOT_FOUND', error: 'Event not found' }));
|
|
648
|
+
}
|
|
649
|
+
const relations = url.pathname.match(/^\/_matrix\/client\/v1\/rooms\/([^/]+)\/relations\/([^/]+)(?:\/([^/]+))?(?:\/([^/]+))?$/);
|
|
650
|
+
if (relations && this.#authorised(init)) {
|
|
651
|
+
const roomId = decodeURIComponent(relations[1]);
|
|
652
|
+
const targetId = decodeURIComponent(relations[2]);
|
|
653
|
+
const relType = relations[3] ? decodeURIComponent(relations[3]) : undefined;
|
|
654
|
+
const chunk = (this.#events.get(roomId) ?? []).filter((entry) => {
|
|
655
|
+
const relatesTo = entry.content['m.relates_to'];
|
|
656
|
+
if (relatesTo?.event_id !== targetId)
|
|
657
|
+
return false;
|
|
658
|
+
return relType === undefined || relatesTo.rel_type === relType;
|
|
659
|
+
});
|
|
660
|
+
// No `next_batch`: everything this fake has is in one page, so the
|
|
661
|
+
// thread's own back-pagination token ends up `null` and `hasMore`
|
|
662
|
+
// reads false -- which is what a fully-loaded thread should say.
|
|
663
|
+
return Promise.resolve(jsonResponse(200, { chunk: chunk.map((entry) => ({ ...entry, room_id: roomId })) }));
|
|
664
|
+
}
|
|
665
|
+
const send = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/send\/([^/]+)\/([^/]+)$/);
|
|
666
|
+
if (send && this.#authorised(init)) {
|
|
667
|
+
let content = {};
|
|
668
|
+
try {
|
|
669
|
+
content = JSON.parse(String(init?.body ?? '{}'));
|
|
670
|
+
}
|
|
671
|
+
catch {
|
|
672
|
+
// Same tolerance as everywhere else here: a malformed body is
|
|
673
|
+
// accepted with nothing in it rather than failing the test.
|
|
674
|
+
}
|
|
675
|
+
const roomId = decodeURIComponent(send[1]);
|
|
676
|
+
const type = decodeURIComponent(send[2]);
|
|
677
|
+
const txnId = decodeURIComponent(send[3]);
|
|
678
|
+
this.sent.push({ roomId, type, content });
|
|
679
|
+
this.#eventSeq += 1;
|
|
680
|
+
const eventId = `$sent-${this.#eventSeq}`;
|
|
681
|
+
// Echoed back through sync, the way a homeserver does, carrying the
|
|
682
|
+
// transaction id so matrix-js-sdk resolves its own local echo rather
|
|
683
|
+
// than showing the message twice. Without the echo a reaction would
|
|
684
|
+
// never appear at all: only `m.room.message` has a local echo, and a
|
|
685
|
+
// reaction is aggregated out of what sync delivers.
|
|
686
|
+
const event = {
|
|
687
|
+
type,
|
|
688
|
+
event_id: eventId,
|
|
689
|
+
sender: this.userId,
|
|
690
|
+
origin_server_ts: this.#now(),
|
|
691
|
+
content,
|
|
692
|
+
unsigned: { transaction_id: txnId },
|
|
693
|
+
};
|
|
694
|
+
this.#record(roomId, event);
|
|
695
|
+
this.#deliverOrQueue({ [roomId]: this.#timelineEntry(roomId, [event]) });
|
|
696
|
+
return Promise.resolve(jsonResponse(200, { event_id: eventId }));
|
|
697
|
+
}
|
|
698
|
+
const redact = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/redact\/([^/]+)\/([^/]+)$/);
|
|
699
|
+
if (redact && this.#authorised(init)) {
|
|
700
|
+
const roomId = decodeURIComponent(redact[1]);
|
|
701
|
+
const target = decodeURIComponent(redact[2]);
|
|
702
|
+
this.#eventSeq += 1;
|
|
703
|
+
const event = {
|
|
704
|
+
type: 'm.room.redaction',
|
|
705
|
+
event_id: `$redact-${this.#eventSeq}`,
|
|
706
|
+
sender: this.userId,
|
|
707
|
+
origin_server_ts: this.#now(),
|
|
708
|
+
content: {},
|
|
709
|
+
redacts: target,
|
|
710
|
+
};
|
|
711
|
+
// The redacted event stays in the room's record with its content
|
|
712
|
+
// emptied, which is what Synapse does and what makes a taken-back
|
|
713
|
+
// reaction stop counting rather than vanish from `/relations`.
|
|
714
|
+
const events = (this.#events.get(roomId) ?? []).map((entry) => entry.event_id === target ? { ...entry, content: {} } : entry);
|
|
715
|
+
this.#events.set(roomId, events);
|
|
716
|
+
this.#record(roomId, event);
|
|
717
|
+
this.#deliverOrQueue({ [roomId]: this.#timelineEntry(roomId, [event]) });
|
|
718
|
+
return Promise.resolve(jsonResponse(200, { event_id: event.event_id }));
|
|
719
|
+
}
|
|
720
|
+
// Uploads go to `/_matrix/media/v3/upload`, which is still the
|
|
721
|
+
// upload endpoint under authenticated media -- only *downloads* moved
|
|
722
|
+
// to `/_matrix/client/v1/media`.
|
|
723
|
+
if (url.pathname === '/_matrix/media/v3/upload' && this.#authorised(init)) {
|
|
724
|
+
this.#mediaSeq += 1;
|
|
725
|
+
const mediaId = `media-${this.#mediaSeq}`;
|
|
726
|
+
const body = init?.body;
|
|
727
|
+
return (async () => {
|
|
728
|
+
await this.uploadBarrier;
|
|
729
|
+
if (init?.signal?.aborted)
|
|
730
|
+
throw new DOMException('Aborted', 'AbortError');
|
|
731
|
+
if (this.uploadStatus !== 200)
|
|
732
|
+
return jsonResponse(this.uploadStatus, {
|
|
733
|
+
errcode: 'M_FORBIDDEN',
|
|
734
|
+
error: 'upload refused',
|
|
735
|
+
});
|
|
736
|
+
const bytes = body instanceof Blob
|
|
737
|
+
? await body.arrayBuffer()
|
|
738
|
+
: body instanceof ArrayBuffer
|
|
739
|
+
? body
|
|
740
|
+
: ArrayBuffer.isView(body)
|
|
741
|
+
? body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength)
|
|
742
|
+
: new ArrayBuffer(0);
|
|
743
|
+
const contentType = new Headers(init?.headers).get('content-type') ?? '';
|
|
744
|
+
this.media.set(mediaId, { bytes, contentType });
|
|
745
|
+
return jsonResponse(200, { content_uri: `mxc://${this.serverName}/${mediaId}` });
|
|
746
|
+
})();
|
|
747
|
+
}
|
|
748
|
+
const download = url.pathname.match(/^\/_matrix\/client\/v1\/media\/download\/([^/]+)\/([^/]+)$/);
|
|
749
|
+
if (download) {
|
|
750
|
+
const authorised = this.#authorised(init);
|
|
751
|
+
this.mediaRequests.push({ path: url.pathname, authorised });
|
|
752
|
+
// Synapse serves media only to a request carrying the token
|
|
753
|
+
// (`enable_authenticated_media`), so this does too -- otherwise a
|
|
754
|
+
// client that forgot the header would pass its own test.
|
|
755
|
+
if (!authorised) {
|
|
756
|
+
return Promise.resolve(jsonResponse(401, { errcode: 'M_MISSING_TOKEN', error: 'no token' }));
|
|
757
|
+
}
|
|
758
|
+
const found = this.media.get(decodeURIComponent(download[2]));
|
|
759
|
+
if (!found) {
|
|
760
|
+
return Promise.resolve(jsonResponse(404, { errcode: 'M_NOT_FOUND', error: 'no media' }));
|
|
761
|
+
}
|
|
762
|
+
return Promise.resolve(new Response(found.bytes, {
|
|
763
|
+
status: 200,
|
|
764
|
+
headers: { 'Content-Type': found.contentType || 'application/octet-stream' },
|
|
765
|
+
}));
|
|
766
|
+
}
|
|
767
|
+
// The legacy, unauthenticated download paths. Answered with a refusal
|
|
768
|
+
// rather than left to fall through, so a test that expects one to work
|
|
769
|
+
// fails here and says why (ticket #13).
|
|
770
|
+
if (url.pathname.startsWith('/_matrix/media/v3/download')) {
|
|
771
|
+
this.mediaRequests.push({ path: url.pathname, authorised: false });
|
|
772
|
+
return Promise.resolve(jsonResponse(404, { errcode: 'M_UNRECOGNIZED', error: 'authenticated media only' }));
|
|
773
|
+
}
|
|
774
|
+
const accountData = url.pathname.match(/^\/_matrix\/client\/v3\/user\/([^/]+)\/account_data\/([^/]+)$/);
|
|
775
|
+
if (accountData && this.#authorised(init)) {
|
|
776
|
+
if (accountData[2] === 'm.direct') {
|
|
777
|
+
try {
|
|
778
|
+
this.#direct = JSON.parse(String(init?.body ?? '{}'));
|
|
779
|
+
}
|
|
780
|
+
catch {
|
|
781
|
+
this.#direct = {};
|
|
782
|
+
}
|
|
783
|
+
this.#deliverOrQueue({});
|
|
784
|
+
}
|
|
785
|
+
return Promise.resolve(jsonResponse(200, {}));
|
|
786
|
+
}
|
|
787
|
+
const tag = url.pathname.match(/^\/_matrix\/client\/v3\/user\/([^/]+)\/rooms\/([^/]+)\/tags\/([^/]+)$/);
|
|
788
|
+
if (tag && this.#authorised(init)) {
|
|
789
|
+
this.#setTag(decodeURIComponent(tag[2]), decodeURIComponent(tag[3]), init?.method !== 'DELETE');
|
|
790
|
+
return Promise.resolve(jsonResponse(200, {}));
|
|
791
|
+
}
|
|
792
|
+
const receipt = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/receipt\/m\.read\/([^/]+)$/);
|
|
793
|
+
if (receipt) {
|
|
794
|
+
const token = bearerToken(init);
|
|
795
|
+
if (!token || !this.#validTokens.has(token)) {
|
|
796
|
+
return Promise.resolve(jsonResponse(401, { errcode: 'M_UNKNOWN_TOKEN', error: 'Invalid access token' }));
|
|
797
|
+
}
|
|
798
|
+
this.receipts.push({
|
|
799
|
+
roomId: decodeURIComponent(receipt[1]),
|
|
800
|
+
eventId: decodeURIComponent(receipt[2]),
|
|
801
|
+
});
|
|
802
|
+
return Promise.resolve(jsonResponse(200, {}));
|
|
803
|
+
}
|
|
804
|
+
// Anything else at this homeserver -- capability discovery, RTC
|
|
805
|
+
// transports, and whatever else a client startup probes for -- is
|
|
806
|
+
// answered "not recognised" rather than falling through: this origin
|
|
807
|
+
// does not exist on the real network, and a client startup that reaches
|
|
808
|
+
// past what this fake implements must never make a real DNS lookup.
|
|
809
|
+
return Promise.resolve(jsonResponse(404, { errcode: 'M_UNRECOGNIZED', error: 'Unrecognised request' }));
|
|
810
|
+
}
|
|
811
|
+
}
|