@wtfalch/chat 0.1.0 → 0.3.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.
@@ -29,6 +29,17 @@ export type FakeMessageSeed = {
29
29
  /** The id of the message this replies to, making it a `m.thread` reply.
30
30
  * Matrix threads are one level, so this is always the root's id. */
31
31
  threadRootId?: string;
32
+ /** Seeds an `m.file`/`m.image` in one step, without a real upload round
33
+ * trip -- what `roomFiles` (#9) reads `content.url`/`content.info` off
34
+ * of. `body` is still the file's name, matching what a real client
35
+ * sends. Cheap enough to seed the hundreds of messages a pagination
36
+ * test needs. */
37
+ attachment?: {
38
+ mxcUri: string;
39
+ mimeType: string;
40
+ size: number;
41
+ isImage?: boolean;
42
+ };
32
43
  };
33
44
  export type FakeMember = {
34
45
  userId: string;
@@ -69,6 +80,11 @@ export declare class FakeChatServer {
69
80
  /** Controls for upload failure and in-flight UI scenarios. */
70
81
  uploadBarrier: Promise<void> | null;
71
82
  uploadStatus: number;
83
+ /** What `PUT .../state/m.room.pinned_events/` answers with -- 403 models
84
+ * the power-level refusal a room whose power levels predate ticket #8
85
+ * gives a member, which `pinMessage`/`unpinMessage` must reject on
86
+ * rather than resolve quietly. */
87
+ pinStatus: number;
72
88
  readonly userId: string;
73
89
  /** The Matrix server name, as `userId` gives it -- what an `mxc://`
74
90
  * reference from this homeserver names. */
@@ -84,6 +100,13 @@ export declare class FakeChatServer {
84
100
  roomId: string;
85
101
  eventId: string;
86
102
  }>;
103
+ /** Every content report the client filed (#29), with the exact body it
104
+ * sent. */
105
+ readonly reports: Array<{
106
+ roomId: string;
107
+ eventId: string;
108
+ body: unknown;
109
+ }>;
87
110
  /** Every room `/createRoom` has made, in order -- for a test that asserts
88
111
  * what shape a DM was created in. */
89
112
  readonly createdRooms: Array<{
@@ -95,6 +118,7 @@ export declare class FakeChatServer {
95
118
  * a test that asserts what relation a reply was sent with. */
96
119
  readonly sent: Array<{
97
120
  roomId: string;
121
+ eventId: string;
98
122
  type: string;
99
123
  content: Record<string, unknown>;
100
124
  }>;
@@ -112,6 +136,35 @@ export declare class FakeChatServer {
112
136
  path: string;
113
137
  authorised: boolean;
114
138
  }>;
139
+ /** Every `PUT .../typing/...` this server has answered, in order -- for a
140
+ * test that asserts `sendTyping` actually reached the wire, with what
141
+ * it sent. */
142
+ readonly sentTyping: Array<{
143
+ roomId: string;
144
+ userId: string;
145
+ typing: boolean;
146
+ timeoutMs?: number;
147
+ }>;
148
+ /** Every `PUT .../presence/{userId}/status` this server has answered, in
149
+ * order -- the immediate half of `announcePresence`. */
150
+ readonly sentPresence: Array<{
151
+ userId: string;
152
+ presence: string;
153
+ }>;
154
+ /** Set to refuse the next presence `PUT` with `M_LIMIT_EXCEEDED`, the
155
+ * way a real Synapse refuses a second presence change inside ten
156
+ * seconds (`rc_presence.per_user`). Clears itself after one refusal. */
157
+ refuseNextPresence: boolean;
158
+ /** The `set_presence` query parameter every `/sync` has carried, in
159
+ * order, `undefined` where the client omitted it. This is the half that
160
+ * actually makes an announcement survive, so a test that only checked
161
+ * `sentPresence` would pass against a client that cannot hold anybody
162
+ * away for longer than one poll. */
163
+ readonly syncPresence: Array<string | undefined>;
164
+ /** Rooms currently carrying the room-scoped `dont_notify` push rule, for
165
+ * a test that wants to assert on the server's own state rather than
166
+ * only through the client's `rooms()`. */
167
+ get mutedRoomIds(): string[];
115
168
  constructor(options?: FakeChatServerOptions);
116
169
  dispose(): void;
117
170
  /** Resolves once a `/sync` request is parked waiting for a test to drive
@@ -147,6 +200,26 @@ export declare class FakeChatServer {
147
200
  * `rooms.leave` block, the way a real incremental `/sync` reports a kick
148
201
  * or a self-leave. Throws if nothing is parked. */
149
202
  leaveRoom(roomId: string): void;
203
+ /** Delivers a parked poll as `m.typing` for `roomId` -- Matrix's own
204
+ * shape: an EDU with no sender of its own, always the room's complete
205
+ * current set of typing user ids, never a diff against the last one.
206
+ * Pass an empty list for what Matrix does on its own once a typing
207
+ * state's timeout elapses server-side; this fake never does that by
208
+ * itself, so a test drives both halves explicitly. Throws if nothing is
209
+ * parked. */
210
+ receiveTyping(roomId: string, userIds: string[]): void;
211
+ /** Delivers a parked poll as `userId`'s public read receipt on
212
+ * `eventId` in `roomId` -- the `m.receipt` EDU another person's client
213
+ * causes by reading. Throws if nothing is parked. */
214
+ receiveReceipt(roomId: string, eventId: string, userId: string): void;
215
+ /** Delivers a parked poll as an `m.presence` EDU for somebody else --
216
+ * Matrix's own three states (`online`/`unavailable`/`offline`), or
217
+ * MSC3026's unstable `org.matrix.msc3026.busy` -- for a test that drives
218
+ * `presence()`/`onPresenceChanged` without a live homeserver. Presence
219
+ * EDUs are account-wide, not room-scoped, so this carries no room id --
220
+ * see `#answerParked`'s own `presence.events`. Throws if nothing is
221
+ * parked. */
222
+ receivePresence(userId: string, presence: string): void;
150
223
  /** Delivers a parked poll as somebody else reacting to a message.
151
224
  * Returns the minted event id, so a test can then redact it. Throws if
152
225
  * nothing is parked. */
@@ -31,6 +31,11 @@ export class FakeChatServer {
31
31
  /** Controls for upload failure and in-flight UI scenarios. */
32
32
  uploadBarrier = null;
33
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;
34
39
  userId;
35
40
  /** The Matrix server name, as `userId` gives it -- what an `mxc://`
36
41
  * reference from this homeserver names. */
@@ -43,6 +48,9 @@ export class FakeChatServer {
43
48
  /** Every `m.read` receipt this server has answered, in arrival order --
44
49
  * for a test that asserts `markRoomRead` actually called the wire. */
45
50
  receipts = [];
51
+ /** Every content report the client filed (#29), with the exact body it
52
+ * sent. */
53
+ reports = [];
46
54
  /** Every room `/createRoom` has made, in order -- for a test that asserts
47
55
  * what shape a DM was created in. */
48
56
  createdRooms = [];
@@ -57,6 +65,29 @@ export class FakeChatServer {
57
65
  * request carried -- for a test that asserts nothing reaches the
58
66
  * legacy unauthenticated endpoints, and that the token was sent. */
59
67
  mediaRequests = [];
68
+ /** Every `PUT .../typing/...` this server has answered, in order -- for a
69
+ * test that asserts `sendTyping` actually reached the wire, with what
70
+ * it sent. */
71
+ sentTyping = [];
72
+ /** Every `PUT .../presence/{userId}/status` this server has answered, in
73
+ * order -- the immediate half of `announcePresence`. */
74
+ sentPresence = [];
75
+ /** Set to refuse the next presence `PUT` with `M_LIMIT_EXCEEDED`, the
76
+ * way a real Synapse refuses a second presence change inside ten
77
+ * seconds (`rc_presence.per_user`). Clears itself after one refusal. */
78
+ refuseNextPresence = false;
79
+ /** The `set_presence` query parameter every `/sync` has carried, in
80
+ * order, `undefined` where the client omitted it. This is the half that
81
+ * actually makes an announcement survive, so a test that only checked
82
+ * `sentPresence` would pass against a client that cannot hold anybody
83
+ * away for longer than one poll. */
84
+ syncPresence = [];
85
+ /** Rooms currently carrying the room-scoped `dont_notify` push rule, for
86
+ * a test that wants to assert on the server's own state rather than
87
+ * only through the client's `rooms()`. */
88
+ get mutedRoomIds() {
89
+ return [...this.#mutedRooms];
90
+ }
60
91
  #dispose;
61
92
  #rooms;
62
93
  #tokenLifetimeMs;
@@ -74,6 +105,12 @@ export class FakeChatServer {
74
105
  * of it -- matrix-js-sdk asks for both while it builds a thread. */
75
106
  #events = new Map();
76
107
  #tags = new Map();
108
+ /** Rooms carrying the account's room-scoped `dont_notify` push rule --
109
+ * what `muteRoom` writes and takes away, and the only rule kind this
110
+ * fake bothers to model. Read back through `/pushrules/`, exactly as
111
+ * Synapse would answer it, so a test never has to reach past the
112
+ * client's own `rooms()` to know a mute landed. */
113
+ #mutedRooms = new Set();
77
114
  #roomSeq = 0;
78
115
  #mediaSeq = 0;
79
116
  /** Deliveries made while no poll was parked, waiting for the next one --
@@ -339,18 +376,34 @@ export class FakeChatServer {
339
376
  * does against Synapse. */
340
377
  #messageEvent(seed) {
341
378
  this.#eventSeq += 1;
379
+ const { attachment } = seed;
380
+ // `threadRootId` applies to either shape: a file shared inside a
381
+ // thread is exactly as real as a text reply inside one, and a seed
382
+ // that silently dropped it on the attachment branch would make it
383
+ // impossible to test `roomFiles`' own thread-spanning behaviour
384
+ // against this fixture at all (confirmed the hard way -- see the
385
+ // refuter report this fixed).
386
+ const threaded = seed.threadRootId
387
+ ? { 'm.relates_to': { rel_type: 'm.thread', event_id: seed.threadRootId } }
388
+ : {};
342
389
  return {
343
390
  type: 'm.room.message',
344
391
  event_id: seed.id ?? `$seeded-${this.#eventSeq}`,
345
392
  sender: seed.sender ?? PEER_USER_ID,
346
393
  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
- },
394
+ content: attachment
395
+ ? {
396
+ msgtype: attachment.isImage ? 'm.image' : 'm.file',
397
+ body: seed.body,
398
+ url: attachment.mxcUri,
399
+ info: { mimetype: attachment.mimeType, size: attachment.size },
400
+ ...threaded,
401
+ }
402
+ : {
403
+ msgtype: 'm.text',
404
+ body: seed.body,
405
+ ...threaded,
406
+ },
354
407
  };
355
408
  }
356
409
  /** Mints a seed's messages once and remembers them. Minting them inside
@@ -364,17 +417,54 @@ export class FakeChatServer {
364
417
  #record(roomId, event) {
365
418
  this.#events.set(roomId, [...(this.#events.get(roomId) ?? []), event]);
366
419
  }
367
- /** One room's incremental entry, carrying just these events. */
368
- #timelineEntry(roomId, events) {
420
+ /** One room's incremental entry, carrying just these events -- and,
421
+ * given some, ephemeral ones (`m.typing`) alongside them, the way a real
422
+ * incremental `/sync` carries both together. */
423
+ #timelineEntry(roomId, events, ephemeralEvents = []) {
369
424
  return {
370
425
  summary: {},
371
426
  state: { events: [] },
372
427
  timeline: { events, limited: false, prev_batch: `t-${roomId}` },
373
- ephemeral: { events: [] },
428
+ ephemeral: { events: ephemeralEvents },
374
429
  account_data: { events: this.#roomAccountDataEvents(roomId) },
375
430
  unread_notifications: { highlight_count: 0, notification_count: 0 },
376
431
  };
377
432
  }
433
+ /** Delivers a parked poll as `m.typing` for `roomId` -- Matrix's own
434
+ * shape: an EDU with no sender of its own, always the room's complete
435
+ * current set of typing user ids, never a diff against the last one.
436
+ * Pass an empty list for what Matrix does on its own once a typing
437
+ * state's timeout elapses server-side; this fake never does that by
438
+ * itself, so a test drives both halves explicitly. Throws if nothing is
439
+ * parked. */
440
+ receiveTyping(roomId, userIds) {
441
+ this.#deliverParked({
442
+ [roomId]: this.#timelineEntry(roomId, [], [{ type: 'm.typing', content: { user_ids: userIds } }]),
443
+ });
444
+ }
445
+ /** Delivers a parked poll as `userId`'s public read receipt on
446
+ * `eventId` in `roomId` -- the `m.receipt` EDU another person's client
447
+ * causes by reading. Throws if nothing is parked. */
448
+ receiveReceipt(roomId, eventId, userId) {
449
+ this.#deliverParked({
450
+ [roomId]: this.#timelineEntry(roomId, [], [
451
+ {
452
+ type: 'm.receipt',
453
+ content: { [eventId]: { 'm.read': { [userId]: { ts: this.#now() } } } },
454
+ },
455
+ ]),
456
+ });
457
+ }
458
+ /** Delivers a parked poll as an `m.presence` EDU for somebody else --
459
+ * Matrix's own three states (`online`/`unavailable`/`offline`), or
460
+ * MSC3026's unstable `org.matrix.msc3026.busy` -- for a test that drives
461
+ * `presence()`/`onPresenceChanged` without a live homeserver. Presence
462
+ * EDUs are account-wide, not room-scoped, so this carries no room id --
463
+ * see `#answerParked`'s own `presence.events`. Throws if nothing is
464
+ * parked. */
465
+ receivePresence(userId, presence) {
466
+ this.#deliverParked({}, {}, [{ type: 'm.presence', sender: userId, content: { presence } }]);
467
+ }
378
468
  /** Delivers a parked poll as somebody else reacting to a message.
379
469
  * Returns the minted event id, so a test can then redact it. Throws if
380
470
  * nothing is parked. */
@@ -462,11 +552,11 @@ export class FakeChatServer {
462
552
  to_device: { events: [] },
463
553
  };
464
554
  }
465
- #deliverParked(join, leave = {}) {
555
+ #deliverParked(join, leave = {}, presenceEvents = []) {
466
556
  if (!this.#pending) {
467
557
  throw new Error('fake chat: addRoom called with no /sync request parked');
468
558
  }
469
- this.#answerParked(join, leave);
559
+ this.#answerParked(join, leave, presenceEvents);
470
560
  }
471
561
  /** Delivers now if a poll is parked, and otherwise holds the payload for
472
562
  * the next one. What `#deliverParked` refuses to do: a test driving the
@@ -481,7 +571,7 @@ export class FakeChatServer {
481
571
  }
482
572
  this.#queued.push({ join, leave });
483
573
  }
484
- #answerParked(join, leave) {
574
+ #answerParked(join, leave, presenceEvents = []) {
485
575
  const pending = this.#pending;
486
576
  if (!pending)
487
577
  return;
@@ -491,7 +581,7 @@ export class FakeChatServer {
491
581
  next_batch: this.#nextBatch(),
492
582
  rooms: { join, leave },
493
583
  account_data: { events: this.#accountDataEvents() },
494
- presence: { events: [] },
584
+ presence: { events: presenceEvents },
495
585
  to_device: { events: [] },
496
586
  }));
497
587
  }
@@ -561,6 +651,7 @@ export class FakeChatServer {
561
651
  if (!token || !this.#validTokens.has(token)) {
562
652
  return Promise.resolve(jsonResponse(401, { errcode: 'M_UNKNOWN_TOKEN', error: 'Invalid access token' }));
563
653
  }
654
+ this.syncPresence.push(url.searchParams.get('set_presence') ?? undefined);
564
655
  if (url.searchParams.get('since') === null) {
565
656
  return Promise.resolve(jsonResponse(200, this.#fullSyncBody()));
566
657
  }
@@ -608,9 +699,38 @@ export class FakeChatServer {
608
699
  }
609
700
  if (url.pathname === '/_matrix/client/v3/pushrules/') {
610
701
  return Promise.resolve(jsonResponse(200, {
611
- global: { content: [], override: [], room: [], sender: [], underride: [] },
702
+ global: {
703
+ content: [],
704
+ override: [],
705
+ room: [...this.#mutedRooms].map((roomId) => ({
706
+ rule_id: roomId,
707
+ default: false,
708
+ enabled: true,
709
+ actions: ['dont_notify'],
710
+ })),
711
+ sender: [],
712
+ underride: [],
713
+ },
612
714
  }));
613
715
  }
716
+ // What `setRoomMutePushRule` PUTs and DELETEs -- see `ChatClient.muteRoom`.
717
+ // This fake only ever sees `'global'`, the one scope the client uses, but
718
+ // matches on it anyway rather than any scope: a client that started
719
+ // writing device-scoped rules should fail here, not be quietly muted.
720
+ const roomPushRule = url.pathname.match(/^\/_matrix\/client\/v3\/pushrules\/global\/room\/([^/]+)$/);
721
+ if (roomPushRule && this.#authorised(init)) {
722
+ const roomId = decodeURIComponent(roomPushRule[1]);
723
+ if (init?.method === 'DELETE') {
724
+ if (!this.#mutedRooms.has(roomId)) {
725
+ return Promise.resolve(jsonResponse(404, { errcode: 'M_NOT_FOUND', error: 'Push rule does not exist' }));
726
+ }
727
+ this.#mutedRooms.delete(roomId);
728
+ }
729
+ else {
730
+ this.#mutedRooms.add(roomId);
731
+ }
732
+ return Promise.resolve(jsonResponse(200, {}));
733
+ }
614
734
  if (url.pathname.startsWith('/_matrix/client/v3/user/') && url.pathname.endsWith('/filter')) {
615
735
  return Promise.resolve(jsonResponse(200, { filter_id: 'fake-filter' }));
616
736
  }
@@ -662,6 +782,55 @@ export class FakeChatServer {
662
782
  // reads false -- which is what a fully-loaded thread should say.
663
783
  return Promise.resolve(jsonResponse(200, { chunk: chunk.map((entry) => ({ ...entry, room_id: roomId })) }));
664
784
  }
785
+ // `roomFiles`' own backward walk, and `paginate`'s plain scrollback:
786
+ // both are `GET .../messages`, and the only thing that tells them
787
+ // apart on the wire is whether a `contains_url` filter came along.
788
+ // `#events` is oldest first, so this reverses it once and paginates
789
+ // with a plain numeric cursor -- there is no real Matrix stream token
790
+ // to imitate here, only "how far back has this walk gone".
791
+ const messages = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/messages$/);
792
+ if (messages && this.#authorised(init)) {
793
+ const roomId = decodeURIComponent(messages[1]);
794
+ let filter = {};
795
+ try {
796
+ const raw = url.searchParams.get('filter');
797
+ if (raw)
798
+ filter = JSON.parse(raw);
799
+ }
800
+ catch {
801
+ // Same tolerance as every other body/param this fake parses.
802
+ }
803
+ const newestFirst = [...(this.#events.get(roomId) ?? [])].reverse();
804
+ // Not what real Synapse does. `entry.content.url` is read live, here,
805
+ // on every call -- so a redacted event (`#record`'s content already
806
+ // emptied, see the `redact` route above) simply has no `url` left to
807
+ // match by the time this runs. Real Synapse computes `contains_url`
808
+ // once, at persist time, and never revisits it on redaction (checked
809
+ // against the installed v1.161.0 source), so a redacted file-bearing
810
+ // event still *matches* the filter there and still comes back from
811
+ // `/messages` -- pruned, but present. `roomFiles`' own
812
+ // `event.isRedacted()` guard is what excludes it in production. A
813
+ // unit test built on this fake exercises that a redacted file is
814
+ // excluded, but not *why* -- `test/integration/roomfiles.test.ts`'s
815
+ // real-Synapse redaction case is what actually proves the guard.
816
+ const matching = newestFirst.filter((entry) => {
817
+ if (filter.types && !filter.types.includes(entry.type))
818
+ return false;
819
+ if (filter.contains_url && entry.content.url === undefined)
820
+ return false;
821
+ return true;
822
+ });
823
+ const limit = Number(url.searchParams.get('limit') ?? '30');
824
+ const from = url.searchParams.get('from');
825
+ const start = from?.startsWith('idx-') ? Number(from.slice('idx-'.length)) : 0;
826
+ const chunk = matching.slice(start, start + limit);
827
+ const nextIndex = start + chunk.length;
828
+ const end = nextIndex < matching.length ? `idx-${nextIndex}` : undefined;
829
+ return Promise.resolve(jsonResponse(200, {
830
+ chunk: chunk.map((entry) => ({ ...entry, room_id: roomId })),
831
+ ...(end ? { end } : {}),
832
+ }));
833
+ }
665
834
  const send = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/send\/([^/]+)\/([^/]+)$/);
666
835
  if (send && this.#authorised(init)) {
667
836
  let content = {};
@@ -675,9 +844,9 @@ export class FakeChatServer {
675
844
  const roomId = decodeURIComponent(send[1]);
676
845
  const type = decodeURIComponent(send[2]);
677
846
  const txnId = decodeURIComponent(send[3]);
678
- this.sent.push({ roomId, type, content });
679
847
  this.#eventSeq += 1;
680
848
  const eventId = `$sent-${this.#eventSeq}`;
849
+ this.sent.push({ roomId, eventId, type, content });
681
850
  // Echoed back through sync, the way a homeserver does, carrying the
682
851
  // transaction id so matrix-js-sdk resolves its own local echo rather
683
852
  // than showing the message twice. Without the echo a reaction would
@@ -717,6 +886,35 @@ export class FakeChatServer {
717
886
  this.#deliverOrQueue({ [roomId]: this.#timelineEntry(roomId, [event]) });
718
887
  return Promise.resolve(jsonResponse(200, { event_id: event.event_id }));
719
888
  }
889
+ // `sendStateEvent`'s own default state key is `''`, never `undefined`
890
+ // (see matrix-js-sdk's `client.js`), so the path this mints always
891
+ // carries the trailing, empty state-key segment.
892
+ const pinnedEvents = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/state\/m\.room\.pinned_events\/?$/);
893
+ if (pinnedEvents && this.#authorised(init)) {
894
+ if (this.pinStatus !== 200) {
895
+ return Promise.resolve(jsonResponse(this.pinStatus, { errcode: 'M_FORBIDDEN', error: 'pinning refused' }));
896
+ }
897
+ let content = {};
898
+ try {
899
+ content = JSON.parse(String(init?.body ?? '{}'));
900
+ }
901
+ catch {
902
+ // Same tolerance as every other route here.
903
+ }
904
+ const roomId = decodeURIComponent(pinnedEvents[1]);
905
+ this.#eventSeq += 1;
906
+ const event = {
907
+ type: 'm.room.pinned_events',
908
+ state_key: '',
909
+ event_id: `$pinned-${this.#eventSeq}`,
910
+ sender: this.userId,
911
+ origin_server_ts: this.#now(),
912
+ content,
913
+ };
914
+ this.#record(roomId, event);
915
+ this.#deliverOrQueue({ [roomId]: this.#timelineEntry(roomId, [event]) });
916
+ return Promise.resolve(jsonResponse(200, { event_id: event.event_id }));
917
+ }
720
918
  // Uploads go to `/_matrix/media/v3/upload`, which is still the
721
919
  // upload endpoint under authenticated media -- only *downloads* moved
722
920
  // to `/_matrix/client/v1/media`.
@@ -745,6 +943,35 @@ export class FakeChatServer {
745
943
  return jsonResponse(200, { content_uri: `mxc://${this.serverName}/${mediaId}` });
746
944
  })();
747
945
  }
946
+ // `apps/chat-service`'s media proxy (wtfalch/chat#32). The same two
947
+ // checks the real one makes: the account is still in `roomId`, and
948
+ // `eventId` is a message sent there that references this media.
949
+ const chatMedia = url.pathname.match(/^\/_chat\/media\/([^/]+)\/([^/]+)$/);
950
+ if (chatMedia) {
951
+ const authorised = this.#authorised(init);
952
+ this.mediaRequests.push({ path: url.pathname, authorised });
953
+ if (!authorised) {
954
+ return Promise.resolve(jsonResponse(401, { error: 'token_invalid' }));
955
+ }
956
+ const roomId = url.searchParams.get('roomId');
957
+ const eventId = url.searchParams.get('eventId');
958
+ if (!roomId || !this.#rooms.some((room) => room.id === roomId)) {
959
+ return Promise.resolve(jsonResponse(403, { error: 'not_a_member' }));
960
+ }
961
+ const mxcUri = `mxc://${decodeURIComponent(chatMedia[1])}/${decodeURIComponent(chatMedia[2])}`;
962
+ const carrier = this.sent.find((entry) => entry.roomId === roomId && entry.eventId === eventId && entry.content.url === mxcUri);
963
+ if (!carrier) {
964
+ return Promise.resolve(jsonResponse(403, { error: 'not_in_room' }));
965
+ }
966
+ const found = this.media.get(decodeURIComponent(chatMedia[2]));
967
+ if (!found) {
968
+ return Promise.resolve(jsonResponse(404, { error: 'not_found' }));
969
+ }
970
+ return Promise.resolve(new Response(found.bytes, {
971
+ status: 200,
972
+ headers: { 'Content-Type': found.contentType || 'application/octet-stream' },
973
+ }));
974
+ }
748
975
  const download = url.pathname.match(/^\/_matrix\/client\/v1\/media\/download\/([^/]+)\/([^/]+)$/);
749
976
  if (download) {
750
977
  const authorised = this.#authorised(init);
@@ -789,6 +1016,58 @@ export class FakeChatServer {
789
1016
  this.#setTag(decodeURIComponent(tag[2]), decodeURIComponent(tag[3]), init?.method !== 'DELETE');
790
1017
  return Promise.resolve(jsonResponse(200, {}));
791
1018
  }
1019
+ // What `client.sendTyping` PUTs -- see `ChatClient.sendTyping`. Recorded
1020
+ // rather than echoed back through sync on its own: a real homeserver's
1021
+ // own typing timer is what turns this into the `m.typing` EDU other
1022
+ // members see, and a test drives that side explicitly with
1023
+ // `receiveTyping` instead of this fake modelling a timer.
1024
+ const typing = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/typing\/([^/]+)$/);
1025
+ if (typing && this.#authorised(init)) {
1026
+ let body = {};
1027
+ try {
1028
+ body = JSON.parse(String(init?.body ?? '{}'));
1029
+ }
1030
+ catch {
1031
+ // Same tolerance as every other write here: a malformed body is
1032
+ // recorded as sent rather than failing the test for a reason it
1033
+ // did not choose.
1034
+ }
1035
+ this.sentTyping.push({
1036
+ roomId: decodeURIComponent(typing[1]),
1037
+ userId: decodeURIComponent(typing[2]),
1038
+ typing: Boolean(body.typing),
1039
+ timeoutMs: body.timeout,
1040
+ });
1041
+ return Promise.resolve(jsonResponse(200, {}));
1042
+ }
1043
+ // The immediate half of `announcePresence`. Recorded rather than fed
1044
+ // back as an `m.presence` event: on a real homeserver this sets the
1045
+ // *signed-in person's own* presence, which is read by everybody else's
1046
+ // client, not by this one -- `presence()` here is driven by
1047
+ // `receivePresence` instead, the same way typing is.
1048
+ const presence = url.pathname.match(/^\/_matrix\/client\/v3\/presence\/([^/]+)\/status$/);
1049
+ if (presence && this.#authorised(init)) {
1050
+ if (this.refuseNextPresence) {
1051
+ this.refuseNextPresence = false;
1052
+ return Promise.resolve(jsonResponse(429, {
1053
+ errcode: 'M_LIMIT_EXCEEDED',
1054
+ error: 'Too many requests',
1055
+ retry_after_ms: 10_000,
1056
+ }));
1057
+ }
1058
+ let body = {};
1059
+ try {
1060
+ body = JSON.parse(String(init?.body ?? '{}'));
1061
+ }
1062
+ catch {
1063
+ // Same tolerance as every other write here.
1064
+ }
1065
+ this.sentPresence.push({
1066
+ userId: decodeURIComponent(presence[1]),
1067
+ presence: String(body.presence),
1068
+ });
1069
+ return Promise.resolve(jsonResponse(200, {}));
1070
+ }
792
1071
  const receipt = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/receipt\/m\.read\/([^/]+)$/);
793
1072
  if (receipt) {
794
1073
  const token = bearerToken(init);
@@ -801,6 +1080,19 @@ export class FakeChatServer {
801
1080
  });
802
1081
  return Promise.resolve(jsonResponse(200, {}));
803
1082
  }
1083
+ const report = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/report\/([^/]+)$/);
1084
+ if (report && init?.method === 'POST') {
1085
+ const token = bearerToken(init);
1086
+ if (!token || !this.#validTokens.has(token)) {
1087
+ return Promise.resolve(jsonResponse(401, { errcode: 'M_UNKNOWN_TOKEN', error: 'Invalid access token' }));
1088
+ }
1089
+ this.reports.push({
1090
+ roomId: decodeURIComponent(report[1]),
1091
+ eventId: decodeURIComponent(report[2]),
1092
+ body: JSON.parse(String(init.body ?? '{}')),
1093
+ });
1094
+ return Promise.resolve(jsonResponse(200, {}));
1095
+ }
804
1096
  // Anything else at this homeserver -- capability discovery, RTC
805
1097
  // transports, and whatever else a client startup probes for -- is
806
1098
  // answered "not recognised" rather than falling through: this origin
@@ -7,4 +7,4 @@
7
7
  * `README.md` and the chat plan, section 9.
8
8
  */
9
9
  export { createChatClient, MAX_UPLOAD_BYTES } from './client.ts';
10
- export type { ChatAttachment, ChatClient, ChatConnectionStatus, ChatPerson, ChatRoomSummary, ChatUploadProgress, CreateChatClientOptions, ExchangeBody, } from './types.ts';
10
+ export type { ChatAttachment, ChatRoomFilesPage, ChatClient, ChatConnectionStatus, ChatPerson, ChatRoomSummary, ChatUploadProgress, CreateChatClientOptions, ExchangeBody, } from './types.ts';
@@ -2,14 +2,7 @@ import type { ChatAttachment, ChatClient, ChatUploadProgress } from '../types.ts
2
2
  /** Bytes as a person reads them. Whole units above a kilobyte: a file's
3
3
  * exact byte count is never what somebody wants to know. */
4
4
  export declare function formatSize(bytes: number): string;
5
- /** Fetches `mxcUri` with the session's token and hands back an object URL
6
- * for as long as the component is mounted, revoking it on the way out.
7
- *
8
- * Synapse serves media only to a request carrying the token, so there is
9
- * no URL to put in an `<img src>` -- the bytes have to come through the
10
- * client. `null` while it is still coming, and `null` for good if it
11
- * cannot be had. */
12
- export declare function useMediaUrl(client: ChatClient, mxcUri: string | null): {
5
+ export declare function useMediaUrl(client: ChatClient, mxcUri: string | null, roomId: string, eventId: string): {
13
6
  url: string | null;
14
7
  failed: boolean;
15
8
  retry: () => void;
@@ -17,6 +10,9 @@ export declare function useMediaUrl(client: ChatClient, mxcUri: string | null):
17
10
  export type AttachmentViewProps = {
18
11
  attachment: ChatAttachment;
19
12
  client: ChatClient;
13
+ /** The room this attachment's message was posted in -- `loadMedia` needs
14
+ * it to prove membership (wtfalch/chat#32). */
15
+ roomId: string;
20
16
  /** Set while the file is still going up, in which case there is nothing
21
17
  * on the server to fetch and this draws the count instead. */
22
18
  upload: ChatUploadProgress | null;
@@ -28,7 +24,7 @@ export type AttachmentViewProps = {
28
24
  * load, or that a reader cannot see, still has to say what it is -- the
29
25
  * agora's Named Station Rule, which is why there is no bare thumbnail
30
26
  * anywhere in here. */
31
- export declare function AttachmentView({ attachment, client, upload }: AttachmentViewProps): import("react").JSX.Element;
27
+ export declare function AttachmentView({ attachment, client, roomId, upload }: AttachmentViewProps): import("react").JSX.Element;
32
28
  /** Fills in the `src` of every `img[data-mxc]` the sanitiser left in a
33
29
  * message's HTML, and revokes what it made when the message goes.
34
30
  *
@@ -36,4 +32,4 @@ export declare function AttachmentView({ attachment, client, upload }: Attachmen
36
32
  * nothing is requested until this runs and nothing is ever requested
37
33
  * without the token. An image whose bytes cannot be had simply stays
38
34
  * blank beside its own `alt`. */
39
- export declare function useInlineMedia(client: ChatClient, host: React.RefObject<HTMLElement | null>, html: string | null): void;
35
+ export declare function useInlineMedia(client: ChatClient, host: React.RefObject<HTMLElement | null>, html: string | null, roomId: string, eventId: string): void;