@wtfalch/chat 0.2.0 → 0.4.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 CHANGED
@@ -183,8 +183,14 @@ next reload; the reply itself is never lost.
183
183
  Both refuse a message somebody else sent, and `event.mine` is what a UI draws
184
184
  that rule from. Ownership is the whole rule: Matrix ignores an `m.replace`
185
185
  from anybody but the original sender, and the default power levels let a
186
- member redact their own event and nobody else's. Moderating other people's
187
- messages is the manage app's, later.
186
+ member redact their own event and nobody else's.
187
+
188
+ **Moderation** ([#29](https://github.com/wtfalch/chat/issues/29)). A member
189
+ reports a message with `reportMessage(roomId, eventId, reason)`. The admin SDK
190
+ reads reports with `listReports()`, removes anyone's message from a channel
191
+ with `redactMessage(roomId, eventId)`, and bans a person from a channel with
192
+ `banPerson(roomId, subject, reason?)` until `unbanPerson(roomId, subject)`.
193
+ Admins act as `@chat-admin`, and only in channels the service created.
188
194
 
189
195
  **Pinned messages** ([#8](https://github.com/wtfalch/chat/issues/8)).
190
196
  `chat.pinMessage(roomId, eventId)` and `chat.unpinMessage(roomId, eventId)` add
@@ -250,7 +256,11 @@ reply, and answers `/event` and `/relations`, which is what matrix-js-sdk
250
256
  asks for while it builds a thread. It echoes every accepted send back
251
257
  through sync carrying its transaction id, so a reaction shows up the way it
252
258
  does against a homeserver, and it answers redactions -- which is how a
253
- reaction is taken back.
259
+ reaction is taken back. It also answers `/search`, a plain case-insensitive
260
+ substring match over every message body it has recorded, newest first,
261
+ scoped to `filter.rooms` when the client sends one -- a room seeded with
262
+ `encrypted: true` never matches, the same as a real, unindexed encrypted
263
+ room would not.
254
264
 
255
265
  ## Integration tests
256
266
 
@@ -287,30 +297,73 @@ id from `timeline()` before calling `retryMessage` or `cancelMessage`.
287
297
  until the upload completes. Images preview inline and all files have a named
288
298
  Download link. A failed download offers Retry download.
289
299
 
290
- Media bytes are fetched with the session bearer token from
291
- `/_matrix/client/v1/media/download/*`, including images inside formatted messages.
292
- There is no legacy unauthenticated download fallback. `loadMedia(mxcUri)` returns
293
- a blob URL or null; callers must revoke returned URLs. The React views revoke
294
- theirs on replacement and unmount, including downloads that finish after unmount.
295
- Uploads use Matrix's separate authenticated `/_matrix/media/v3/upload` endpoint.
296
- Only references on the session's own homeserver are accepted.
297
-
298
- **Known limit: files are not locked to their channels.** A person with a valid
299
- homeserver token and a media id may retrieve that file without membership in the
300
- room where it was posted. Deleting the message removes its visible reference;
301
- it does not delete the stored media. No malware scanning or file search is included.
300
+ Media bytes are fetched with the session bearer token from `apps/chat-service`'s
301
+ `GET /_chat/media/{serverName}/{mediaId}?roomId=...&eventId=...`, never from
302
+ Synapse's `/_matrix/client/v1/media/download/*` directly, including images inside
303
+ formatted messages. `loadMedia(mxcUri, roomId, eventId)` returns a blob URL or
304
+ null; every `ChatAttachment` carries the `eventId` of its message. Callers must
305
+ revoke returned URLs. The React views revoke theirs on replacement and unmount,
306
+ including downloads that finish after unmount. Uploads use Matrix's separate
307
+ authenticated `/_matrix/media/v3/upload` endpoint. Only references on the
308
+ session's own homeserver are accepted.
309
+
310
+ **Files are locked to their channels** ([#32](https://github.com/wtfalch/chat/issues/32)).
311
+ Synapse serves a file to any valid token that names its media id, whatever room
312
+ it was posted in. The media route in `apps/chat-service` (`src/media.ts`) makes
313
+ the check Synapse does not. It serves the file only when the caller is currently
314
+ joined to `roomId`, `eventId` is a message in that room that references the
315
+ file, and that message was sent by the person who uploaded it. An ex-member, or
316
+ someone who re-posts a kept media id in a room of their own, is refused. A
317
+ deleted message's file is refused too. The deleted file itself stays stored.
318
+ This only holds when the reverse proxy in front of Synapse does not route
319
+ Synapse's own media download and thumbnail paths to clients. No malware
320
+ scanning or file search is included.
302
321
 
303
322
  **Every file in a room** ([#9](https://github.com/wtfalch/chat/issues/9)).
304
323
  `chat.roomFiles(roomId, { limit, before })` lists a room's files without paging
305
324
  its timeline: `GET .../messages` takes Matrix's own `contains_url` filter, and
306
325
  Synapse answers with only file-bearing events no matter how much plain
307
326
  conversation sits between them, confirmed live against this package's own test
308
- Synapse. `limit` stops once that many are collected; omitted, this walks pages
309
- until Synapse says there is nothing older. `before` continues where a walk left
310
- off -- Synapse's own opaque `/messages` token, not an event id; `roomFiles`
311
- does not hand one back yet, so there is no way to obtain one from this package
312
- alone. It returns `ChatAttachment`s, the same shape `event.attachment` already
313
- carries, and bytes still only ever come through `loadMedia`.
327
+ Synapse. It resolves with `{ files, next }`. `files` are `ChatAttachment`s, the
328
+ same shape `event.attachment` already carries, and bytes still only ever come
329
+ through `loadMedia`. `limit` stops once that many are collected; omitted, this
330
+ walks pages until Synapse says there is nothing older.
331
+
332
+ **Loading more files** ([#33](https://github.com/wtfalch/chat/issues/33)).
333
+ `next` is the cursor for the files after these. Pass it back as `before` to load
334
+ the next page; it is `null` once there is nothing older. It resumes exactly
335
+ after the last file returned, so none is skipped or repeated. The last page can
336
+ come back empty.
337
+
338
+ ## Search
339
+
340
+ ([wtfalch/agora#252](https://github.com/wtfalch/agora/issues/252),
341
+ [wtfalch/agora#31](https://github.com/wtfalch/agora/issues/31)).
342
+ `chat.search(query, { roomId, limit })` finds a message by a word or phrase,
343
+ across every room this account is joined to, or just `roomId` when given,
344
+ through Synapse's own `POST /search` (`room_events`, newest first) -- the
345
+ same event-mapping code `timeline()` uses, so a result is a plain
346
+ `ChatTimelineEvent` next to the room it came from. `limit` (default 50)
347
+ stops collection once that many results are in, following Synapse's own
348
+ `next_batch` as far as it takes to get there.
349
+
350
+ Permission filtering is Synapse's own: it only ever searches rooms this
351
+ account has joined, and this package layers nothing of its own on top --
352
+ a person who left a room, or was removed, finds nothing from it on their
353
+ next search, with no filter this package wrote itself.
354
+
355
+ **Encrypted rooms say so, rather than returning nothing.** Crypto stays off
356
+ in this package today (the module comment says why), so a real encrypted
357
+ room's cleartext was never in Synapse's index to begin with -- an empty
358
+ `results` from one would read as "nothing found" when the honest answer is
359
+ "cannot search here". `search` returns
360
+ `{ results, unsearchableRoomIds }`: `unsearchableRoomIds` lists every
361
+ joined room this search could not look inside because it carries
362
+ `m.room.encryption` state. A room-scoped search of an encrypted room is
363
+ `[roomId]` with `results` always empty; a search across every room lists
364
+ every encrypted one it is in, whatever it did or did not find elsewhere.
365
+ This is the one deviation from agora#252's own bare-array shape, a campaign
366
+ decision recorded against it.
314
367
 
315
368
  ## First-ship local proof
316
369
 
@@ -331,6 +384,12 @@ The React timeline calls `markRoomRead` when the visible room is at the bottom.
331
384
  Reading a thread, viewing older history, or leaving a tab in the background does
332
385
  not clear unread room messages.
333
386
 
387
+ `readBy(roomId, eventId)` names who has seen a message
388
+ ([#31](https://github.com/wtfalch/chat/issues/31)): every joined person whose
389
+ read receipt is on that message or a newer one. It leaves out the signed-in
390
+ person and the message's sender. `onTimelineChanged` fires when a receipt
391
+ moves, so a view re-reads it then. Only public read receipts count.
392
+
334
393
  ## Administration in Manage
335
394
 
336
395
  `@wtfalch/chat/admin` exports `createChatAdmin`, the typed management
@@ -345,7 +404,10 @@ const page = await admin.listChannels({ limit: 25 });
345
404
  ```
346
405
 
347
406
  It exposes channel list/details/create/update/archive/delete, private-channel
348
- invitations/removals, Chat-user deactivation and audit pagination. Redirects are
407
+ invitations/removals, moderation (`banPerson`, `unbanPerson`, `redactMessage`,
408
+ `listReports`), Chat-user deactivation, a person's Matrix sessions
409
+ (`listSessions(subject)` and `revokeSession(subject, sessionId)`,
410
+ [#30](https://github.com/wtfalch/chat/issues/30)) and audit pagination. Redirects are
349
411
  refused; tokens never appear in URLs or rendered errors. Service authorization
350
412
  still verifies the token, organisation and Chat project's admin role on every
351
413
  request. Request the Chat project audience and qualified project-role claims
@@ -42,6 +42,23 @@ export type AuditPage = {
42
42
  rows: AuditRow[];
43
43
  next_cursor: string | null;
44
44
  };
45
+ /** One Matrix session the exchange minted for a person -- one per device. */
46
+ export type PersonSession = {
47
+ session_id: string;
48
+ device_id: string | null;
49
+ created_at: string | null;
50
+ last_active_at: string | null;
51
+ };
52
+ /** A member's report of a message (#29). Never the message text. */
53
+ export type ContentReport = {
54
+ id: string;
55
+ received_at: string | null;
56
+ room_id: string | null;
57
+ event_id: string | null;
58
+ reporter: string | null;
59
+ sender: string | null;
60
+ reason: string | null;
61
+ };
45
62
  export type PageInput = {
46
63
  limit?: number;
47
64
  cursor?: string;
@@ -80,10 +97,46 @@ export declare function createChatAdmin(options: ChatAdminOptions): {
80
97
  room_id: string;
81
98
  deleted: true;
82
99
  }>;
100
+ /** Bans a person from one channel until `unbanPerson` (#29). */
101
+ banPerson: (roomId: string, subject: string, reason?: string) => Promise<{
102
+ room_id: string;
103
+ user_id: string;
104
+ banned: true;
105
+ }>;
106
+ unbanPerson: (roomId: string, subject: string) => Promise<{
107
+ room_id: string;
108
+ user_id: string;
109
+ banned: false;
110
+ }>;
111
+ /** Removes anyone's message from a channel (#29). */
112
+ redactMessage: (roomId: string, eventId: string) => Promise<{
113
+ room_id: string;
114
+ event_id: string;
115
+ redacted: true;
116
+ }>;
117
+ /** What members reported with `reportMessage`, newest first. */
118
+ listReports: (input?: PageInput) => Promise<{
119
+ reports: ContentReport[];
120
+ next_cursor: string | null;
121
+ }>;
83
122
  deactivatePerson: (subject: string) => Promise<{
84
123
  user_id: string;
85
124
  deactivated: true;
86
125
  }>;
126
+ /** Every Matrix session signed in as `subject` (#30). */
127
+ listSessions: (subject: string) => Promise<{
128
+ user_id: string;
129
+ sessions: PersonSession[];
130
+ }>;
131
+ /** Ends one of `subject`'s sessions; its Matrix token stops working at
132
+ * once. The person's next exchange on that device signs in again, so
133
+ * a stolen ZITADEL credential needs `deactivatePerson` or revoking in
134
+ * ZITADEL. */
135
+ revokeSession: (subject: string, sessionId: string) => Promise<{
136
+ user_id: string;
137
+ session_id: string;
138
+ revoked: true;
139
+ }>;
87
140
  audit: (input?: PageInput) => Promise<AuditPage>;
88
141
  };
89
142
  export type ChatAdmin = ReturnType<typeof createChatAdmin>;
@@ -106,7 +106,40 @@ export function createChatAdmin(options) {
106
106
  removePerson: (roomId, subject) => request('DELETE', `${roomPath(roomId)}/people/${identifier(subject)}`, personResult),
107
107
  archiveChannel: (roomId) => request('POST', `${roomPath(roomId)}/archive`, (data) => roomResult(data) && 'archived' in data && data.archived === true),
108
108
  deleteChannel: (roomId) => request('DELETE', roomPath(roomId), (data) => roomResult(data) && 'deleted' in data && data.deleted === true),
109
+ /** Bans a person from one channel until `unbanPerson` (#29). */
110
+ banPerson: (roomId, subject, reason) => request('POST', `${roomPath(roomId)}/bans`, (data) => personResult(data) && 'banned' in data && data.banned === true, reason === undefined ? { subject } : { subject, reason }),
111
+ unbanPerson: (roomId, subject) => request('DELETE', `${roomPath(roomId)}/bans/${identifier(subject)}`, (data) => personResult(data) && 'banned' in data && data.banned === false),
112
+ /** Removes anyone's message from a channel (#29). */
113
+ redactMessage: (roomId, eventId) => request('DELETE', `${roomPath(roomId)}/messages/${identifier(eventId)}`, (data) => roomResult(data) &&
114
+ 'event_id' in data &&
115
+ typeof data.event_id === 'string' &&
116
+ 'redacted' in data &&
117
+ data.redacted === true),
118
+ /** What members reported with `reportMessage`, newest first. */
119
+ listReports: (input) => request('GET', `/reports${pageQuery(100, input)}`, (data) => record(data) &&
120
+ Array.isArray(data.reports) &&
121
+ data.reports.every((report) => record(report) &&
122
+ typeof report.id === 'string' &&
123
+ ['received_at', 'room_id', 'event_id', 'reporter', 'sender', 'reason'].every((key) => nullableString(report[key]))) &&
124
+ nullableString(data.next_cursor)),
109
125
  deactivatePerson: (subject) => request('DELETE', `/people/${identifier(subject)}`, (data) => record(data) && typeof data.user_id === 'string' && data.deactivated === true),
126
+ /** Every Matrix session signed in as `subject` (#30). */
127
+ listSessions: (subject) => request('GET', `/people/${identifier(subject)}/sessions`, (data) => record(data) &&
128
+ typeof data.user_id === 'string' &&
129
+ Array.isArray(data.sessions) &&
130
+ data.sessions.every((entry) => record(entry) &&
131
+ typeof entry.session_id === 'string' &&
132
+ nullableString(entry.device_id) &&
133
+ nullableString(entry.created_at) &&
134
+ nullableString(entry.last_active_at))),
135
+ /** Ends one of `subject`'s sessions; its Matrix token stops working at
136
+ * once. The person's next exchange on that device signs in again, so
137
+ * a stolen ZITADEL credential needs `deactivatePerson` or revoking in
138
+ * ZITADEL. */
139
+ revokeSession: (subject, sessionId) => request('DELETE', `/people/${identifier(subject)}/sessions/${identifier(sessionId)}`, (data) => record(data) &&
140
+ typeof data.user_id === 'string' &&
141
+ typeof data.session_id === 'string' &&
142
+ data.revoked === true),
110
143
  audit: (input) => request('GET', `/audit${pageQuery(200, input)}`, (data) => record(data) &&
111
144
  Array.isArray(data.rows) &&
112
145
  data.rows.every(auditRow) &&
@@ -1,4 +1,4 @@
1
- import { ClientEvent, ContentHelpers, Direction, EventStatus, EventTimeline, EventType, Filter, HttpApiEvent, KnownMembership, MatrixError, MatrixEventEvent, MsgType, NotificationCountType, Preset, PushRuleActionName, RelationType, RoomEvent, RoomMemberEvent, SetPresence, SyncState, UserEvent, createClient as createMatrixClient, } from 'matrix-js-sdk';
1
+ import { ClientEvent, ContentHelpers, Direction, EventStatus, EventTimeline, EventType, Filter, HttpApiEvent, KnownMembership, MatrixError, MatrixEventEvent, Method, MsgType, NotificationCountType, Preset, PushRuleActionName, RelationType, RoomEvent, RoomMemberEvent, SetPresence, SyncState, UserEvent, createClient as createMatrixClient, } from 'matrix-js-sdk';
2
2
  import { exchange } from "./exchange.js";
3
3
  import { toFormattedBody } from "./markdown.js";
4
4
  import { createChatStore } from "./store.js";
@@ -26,11 +26,19 @@ const START_OPTIONS = { threadSupport: true };
26
26
  * so at once, rather than after the whole thing has gone up and Synapse
27
27
  * has refused it. */
28
28
  export const MAX_UPLOAD_BYTES = 50 * 1024 * 1024;
29
- /** Synapse serves media only to a request carrying the token
30
- * (`enable_authenticated_media`), and only on this endpoint. The legacy
29
+ /** Where `loadMedia` asks for bytes: `apps/chat-service`'s media proxy,
30
+ * next to `exchangeUrl`, never Synapse's `/_matrix/client/v1/media/download`
31
+ * directly. Synapse serves media to any valid token without checking the
32
+ * room it was posted in (wtfalch/chat#32); the proxy checks. The legacy
31
33
  * `/_matrix/media/...` download paths are unauthenticated and are never
32
34
  * used by this package (ticket #13). */
33
- const MEDIA_DOWNLOAD_PATH = '/_matrix/client/v1/media/download';
35
+ function mediaProxyUrl(exchangeUrl, mxc, roomId, eventId) {
36
+ const base = exchangeUrl.replace(/\/_chat\/exchange\/?$/, '');
37
+ const url = new URL(`${base}/_chat/media/${encodeURIComponent(mxc.serverName)}/${encodeURIComponent(mxc.mediaId)}`);
38
+ url.searchParams.set('roomId', roomId);
39
+ url.searchParams.set('eventId', eventId);
40
+ return url.toString();
41
+ }
34
42
  /** What `sendTyping` asks the server to auto-expire a typing state after,
35
43
  * in ms -- matrix-js-sdk's own default when a caller passes none
36
44
  * (`client.js`'s `sendTyping`), used explicitly here since this package's
@@ -44,6 +52,12 @@ const TYPING_TIMEOUT_MS = 20_000;
44
52
  * already passed the `contains_url` filter server-side, so a larger page
45
53
  * costs one round trip, not one screenful. */
46
54
  const ROOM_FILES_PAGE_SIZE = 50;
55
+ /** `search`'s own default when a caller passes no `limit`. Unlike
56
+ * `roomFiles`, which walks every page Synapse has when given none, a
57
+ * search with no cap at all would follow `next_batch` across a room's
58
+ * entire history for one keystroke -- a bound by default is the safer
59
+ * read of "search this" than "fetch everything ever said". */
60
+ const SEARCH_LIMIT_DEFAULT = 50;
47
61
  /**
48
62
  * A chat session behind the exchange: a matrix-js-sdk `MatrixClient` the
49
63
  * caller never sees, refreshed on its own, exposing only what a UI needs.
@@ -878,36 +892,107 @@ export function createChatClient(options) {
878
892
  * the caller has torn down. */
879
893
  async function roomFiles(roomId, options) {
880
894
  if (!client)
881
- return [];
895
+ return { files: [], next: null };
882
896
  const target = client;
883
897
  if (!target.getRoom(roomId))
884
- return [];
898
+ return { files: [], next: null };
885
899
  const filter = new Filter(target.getUserId());
886
900
  filter.setDefinition({
887
901
  room: { timeline: { types: [EventType.RoomMessage], contains_url: true } },
888
902
  });
889
903
  const mapper = target.getEventMapper();
890
904
  const limit = options?.limit;
891
- const attachments = [];
905
+ const files = [];
892
906
  let from = options?.before ?? null;
893
907
  while (client === target) {
894
- const page = await target.createMessagesRequest(roomId, from, ROOM_FILES_PAGE_SIZE, Direction.Backward, filter);
908
+ if (limit !== undefined && files.length >= limit)
909
+ break;
910
+ // Never ask for more than the limit still wants. Every event in a
911
+ // page is then either returned or skipped, so the page's own `end`
912
+ // is an exact cursor for the next call.
913
+ const size = limit === undefined
914
+ ? ROOM_FILES_PAGE_SIZE
915
+ : Math.min(ROOM_FILES_PAGE_SIZE, limit - files.length);
916
+ const page = await target.createMessagesRequest(roomId, from, size, Direction.Backward, filter);
895
917
  for (const raw of page.chunk) {
896
918
  const event = mapper(raw);
897
919
  if (event.isRedacted())
898
920
  continue;
899
921
  const attachment = toAttachment(event);
900
- if (!attachment)
901
- continue;
902
- attachments.push(attachment);
903
- if (limit !== undefined && attachments.length >= limit)
904
- return attachments;
922
+ if (attachment)
923
+ files.push(attachment);
905
924
  }
906
- if (!page.end || page.chunk.length === 0)
925
+ from = page.end && page.chunk.length > 0 ? page.end : null;
926
+ if (from === null)
907
927
  break;
908
- from = page.end;
909
928
  }
910
- return attachments;
929
+ return { files, next: from };
930
+ }
931
+ /** Joined rooms this account cannot search inside, because Synapse never
932
+ * indexed their cleartext -- an `m.room.encryption` state event is the
933
+ * one thing that means that (see `ChatSearchResults`). Scoped to
934
+ * `roomId` when given, since that is the only room a room-scoped search
935
+ * could ever have reported unsearchable. The company space is excluded
936
+ * the same way `readRooms` excludes it: it is what `people()` reads,
937
+ * not a room in Chat's sense, and never one `search` was ever asked
938
+ * about. */
939
+ function unsearchableRoomIds(target, roomId) {
940
+ return target
941
+ .getRooms()
942
+ .filter((room) => room.getMyMembership() === KnownMembership.Join)
943
+ .filter((room) => !room.isSpaceRoom())
944
+ .filter((room) => (roomId ? room.roomId === roomId : true))
945
+ .filter((room) => room.hasEncryptionStateEvent())
946
+ .map((room) => room.roomId);
947
+ }
948
+ /** `query`, across `options.roomId` or every room this account is
949
+ * joined to, through Synapse's own `POST /search` -- see
950
+ * `ChatClient.search`'s own doc for what that means for permissions and
951
+ * encryption. `filter.rooms` is the one thing that ever narrows the
952
+ * request itself; everything else Synapse decides on its own, including
953
+ * how many results one page of `next_batch` carries. */
954
+ async function search(query, options) {
955
+ if (!client)
956
+ throw new Error('chat: search called before start()');
957
+ const target = client;
958
+ const roomId = options?.roomId;
959
+ const limit = options?.limit ?? SEARCH_LIMIT_DEFAULT;
960
+ // A room-scoped search of an encrypted room has nothing to ask Synapse
961
+ // at all: its messages were never in the index to begin with, and the
962
+ // one room this search could ever have reported unsearchable already
963
+ // is that room.
964
+ if (roomId && target.getRoom(roomId)?.hasEncryptionStateEvent()) {
965
+ return { results: [], unsearchableRoomIds: [roomId] };
966
+ }
967
+ const mapper = target.getEventMapper();
968
+ const results = [];
969
+ let nextBatch;
970
+ do {
971
+ const body = {
972
+ search_categories: {
973
+ room_events: {
974
+ search_term: query,
975
+ order_by: 'recent',
976
+ ...(roomId ? { filter: { rooms: [roomId] } } : {}),
977
+ },
978
+ },
979
+ };
980
+ const response = await target.search({ body, next_batch: nextBatch });
981
+ const roomEvents = response.search_categories.room_events;
982
+ for (const hit of roomEvents.results ?? []) {
983
+ if (results.length >= limit)
984
+ break;
985
+ const raw = hit.result;
986
+ const room = target.getRoom(raw.room_id);
987
+ if (!room)
988
+ continue;
989
+ const mapped = toTimelineEvent(mapper(raw), room, false);
990
+ if (mapped)
991
+ results.push({ roomId: raw.room_id, event: mapped });
992
+ }
993
+ nextBatch = roomEvents.next_batch;
994
+ } while (nextBatch && results.length < limit);
995
+ return { results, unsearchableRoomIds: unsearchableRoomIds(target, roomId) };
911
996
  }
912
997
  /** Builds the Matrix content once, here rather than in `markdown.ts`:
913
998
  * `msgtype`/`format`/`formatted_body` are Matrix's own shape, and this
@@ -1039,6 +1124,14 @@ export function createChatClient(options) {
1039
1124
  return;
1040
1125
  await client.redactEvent(roomId, eventId);
1041
1126
  }
1127
+ /** See `ChatClient.reportMessage`. Sent by hand rather than through
1128
+ * matrix-js-sdk's `reportEvent`, which always attaches a `score` the
1129
+ * spec has deprecated; a report here carries only the reason. */
1130
+ async function reportMessage(roomId, eventId, reason) {
1131
+ if (!client)
1132
+ throw new Error('chat: reportMessage called before start()');
1133
+ await client.http.authedRequest(Method.Post, `/rooms/${encodeURIComponent(roomId)}/report/${encodeURIComponent(eventId)}`, undefined, { reason });
1134
+ }
1042
1135
  /** See `ChatClient.sendFile`. The row appears before the upload starts,
1043
1136
  * so a person sees the file they just picked rather than a pause. */
1044
1137
  function sendFile(roomId, file, options) {
@@ -1155,6 +1248,7 @@ export function createChatClient(options) {
1155
1248
  // Nothing to point at yet: the bytes have no id until the upload
1156
1249
  // finishes, and by then this row is gone.
1157
1250
  mxcUri: '',
1251
+ eventId: '',
1158
1252
  isImage: upload.file.type.startsWith('image/'),
1159
1253
  },
1160
1254
  upload: { loaded: upload.loaded, total: upload.file.size },
@@ -1217,6 +1311,27 @@ export function createChatClient(options) {
1217
1311
  .map(toPerson)
1218
1312
  .sort((a, b) => a.name.localeCompare(b.name));
1219
1313
  }
1314
+ /** See `ChatClient.readBy`. matrix-js-sdk's `getUsersReadUpTo` only
1315
+ * names receipts sitting *on* this event, so a person whose receipt has
1316
+ * since moved to a newer message would drop out. `hasUserReadEvent`
1317
+ * compares positions instead, which is what "seen" means. */
1318
+ function readBy(roomId, eventId) {
1319
+ const room = client?.getRoom(roomId);
1320
+ const event = room?.findEventById(eventId);
1321
+ if (!room || !event)
1322
+ return [];
1323
+ const skip = new Set([client?.getUserId(), event.getSender()]);
1324
+ return room
1325
+ .getMembersWithMembership(KnownMembership.Join)
1326
+ .filter((member) => !skip.has(member.userId) && room.hasUserReadEvent(member.userId, eventId))
1327
+ .map(toPerson)
1328
+ .sort((a, b) => a.name.localeCompare(b.name));
1329
+ }
1330
+ /** A receipt moving changes what `readBy` answers, so a view drawing it
1331
+ * is told the same way it is told about a new message. */
1332
+ function onRoomReceipt(_event, room) {
1333
+ notifyTimeline(room.roomId);
1334
+ }
1220
1335
  /** See `ChatClient.toggleReaction`. Removing is a redaction of the
1221
1336
  * person's own reaction event, which is the only way Matrix has to take
1222
1337
  * one back. */
@@ -1400,15 +1515,15 @@ export function createChatClient(options) {
1400
1515
  }
1401
1516
  /** See `ChatClient.loadMedia`. The request is made by hand rather than
1402
1517
  * through matrix-js-sdk's `mxcUrlToHttp`, which answers with a URL: a
1403
- * URL is exactly what cannot work here, because Synapse serves media
1518
+ * URL is exactly what cannot work here, because the proxy serves media
1404
1519
  * only to a request carrying the token. So the bytes are fetched with
1405
1520
  * the header on and handed back as an object URL. */
1406
- async function loadMedia(mxcUri) {
1521
+ async function loadMedia(mxcUri, roomId, eventId) {
1407
1522
  const parsed = parseMxc(mxcUri);
1408
1523
  if (!parsed || !client)
1409
1524
  return null;
1410
1525
  const target = client;
1411
- const url = `${target.baseUrl}${MEDIA_DOWNLOAD_PATH}/${encodeURIComponent(parsed.serverName)}/${encodeURIComponent(parsed.mediaId)}`;
1526
+ const url = mediaProxyUrl(exchangeUrl, parsed, roomId, eventId);
1412
1527
  try {
1413
1528
  const request = () => fetch(url, {
1414
1529
  headers: { Authorization: `Bearer ${target.getAccessToken() ?? ''}` },
@@ -1438,6 +1553,9 @@ export function createChatClient(options) {
1438
1553
  * audio and video are their own `msgtype`s with their own players, and
1439
1554
  * neither is in the first ship. */
1440
1555
  function toAttachment(event) {
1556
+ const eventId = event.getId();
1557
+ if (!eventId)
1558
+ return null;
1441
1559
  const content = event.getContent();
1442
1560
  const msgtype = content.msgtype;
1443
1561
  if (msgtype !== MsgType.Image && msgtype !== MsgType.File)
@@ -1452,6 +1570,7 @@ export function createChatClient(options) {
1452
1570
  mimeType,
1453
1571
  size: typeof info.size === 'number' ? info.size : 0,
1454
1572
  mxcUri,
1573
+ eventId,
1455
1574
  // The sender's own `msgtype` decides, not the name: a `.png` that is
1456
1575
  // not one would draw a broken picture, and the preview is fetched
1457
1576
  // through `loadMedia` either way.
@@ -1495,6 +1614,7 @@ export function createChatClient(options) {
1495
1614
  created.on(ClientEvent.Sync, onSync);
1496
1615
  created.on(RoomEvent.Timeline, onRoomTimelineChanged);
1497
1616
  created.on(RoomEvent.LocalEchoUpdated, onRoomTimelineChanged);
1617
+ created.on(RoomEvent.Receipt, onRoomReceipt);
1498
1618
  created.on(UserEvent.Presence, onUserPresence);
1499
1619
  created.on(RoomMemberEvent.Typing, onRoomMemberTyping);
1500
1620
  scheduleRefresh(body.expires_at);
@@ -1531,6 +1651,7 @@ export function createChatClient(options) {
1531
1651
  client.removeListener(ClientEvent.Sync, onSync);
1532
1652
  client.removeListener(RoomEvent.Timeline, onRoomTimelineChanged);
1533
1653
  client.removeListener(RoomEvent.LocalEchoUpdated, onRoomTimelineChanged);
1654
+ client.removeListener(RoomEvent.Receipt, onRoomReceipt);
1534
1655
  client.removeListener(UserEvent.Presence, onUserPresence);
1535
1656
  client.removeListener(RoomMemberEvent.Typing, onRoomMemberTyping);
1536
1657
  client.stopClient();
@@ -1759,6 +1880,8 @@ export function createChatClient(options) {
1759
1880
  userId: () => client?.getUserId() ?? null,
1760
1881
  people: readPeople,
1761
1882
  roomMembers,
1883
+ readBy,
1884
+ reportMessage,
1762
1885
  toggleReaction,
1763
1886
  pinMessage,
1764
1887
  unpinMessage,
@@ -1771,6 +1894,7 @@ export function createChatClient(options) {
1771
1894
  onTimelineChanged,
1772
1895
  paginate,
1773
1896
  roomFiles,
1897
+ search,
1774
1898
  sendMessage,
1775
1899
  editMessage,
1776
1900
  deleteMessage,
@@ -19,6 +19,10 @@ export type FakeRoomSeed = {
19
19
  /** Messages already in the room when the first sync lands, oldest first.
20
20
  * Defaults to none. */
21
21
  messages?: FakeMessageSeed[];
22
+ /** Seeds an `m.room.encryption` state event -- the one thing `search`
23
+ * reads to report a room unsearchable (agora#252). Defaults to
24
+ * `false`. */
25
+ encrypted?: boolean;
22
26
  };
23
27
  export type FakeMessageSeed = {
24
28
  /** Defaults to a minted `$seeded-<n>`. Give one to reply to it. */
@@ -100,6 +104,13 @@ export declare class FakeChatServer {
100
104
  roomId: string;
101
105
  eventId: string;
102
106
  }>;
107
+ /** Every content report the client filed (#29), with the exact body it
108
+ * sent. */
109
+ readonly reports: Array<{
110
+ roomId: string;
111
+ eventId: string;
112
+ body: unknown;
113
+ }>;
103
114
  /** Every room `/createRoom` has made, in order -- for a test that asserts
104
115
  * what shape a DM was created in. */
105
116
  readonly createdRooms: Array<{
@@ -111,6 +122,7 @@ export declare class FakeChatServer {
111
122
  * a test that asserts what relation a reply was sent with. */
112
123
  readonly sent: Array<{
113
124
  roomId: string;
125
+ eventId: string;
114
126
  type: string;
115
127
  content: Record<string, unknown>;
116
128
  }>;
@@ -200,6 +212,10 @@ export declare class FakeChatServer {
200
212
  * itself, so a test drives both halves explicitly. Throws if nothing is
201
213
  * parked. */
202
214
  receiveTyping(roomId: string, userIds: string[]): void;
215
+ /** Delivers a parked poll as `userId`'s public read receipt on
216
+ * `eventId` in `roomId` -- the `m.receipt` EDU another person's client
217
+ * causes by reading. Throws if nothing is parked. */
218
+ receiveReceipt(roomId: string, eventId: string, userId: string): void;
203
219
  /** Delivers a parked poll as an `m.presence` EDU for somebody else --
204
220
  * Matrix's own three states (`online`/`unavailable`/`offline`), or
205
221
  * MSC3026's unstable `org.matrix.msc3026.busy` -- for a test that drives
@@ -48,6 +48,9 @@ export class FakeChatServer {
48
48
  /** Every `m.read` receipt this server has answered, in arrival order --
49
49
  * for a test that asserts `markRoomRead` actually called the wire. */
50
50
  receipts = [];
51
+ /** Every content report the client filed (#29), with the exact body it
52
+ * sent. */
53
+ reports = [];
51
54
  /** Every room `/createRoom` has made, in order -- for a test that asserts
52
55
  * what shape a DM was created in. */
53
56
  createdRooms = [];
@@ -93,6 +96,12 @@ export class FakeChatServer {
93
96
  #tokenSeq = 0;
94
97
  #batchSeq = 0;
95
98
  #eventSeq = 0;
99
+ /** Every event's own place in this server's history, oldest first, keyed
100
+ * by event id -- what `/search`'s "newest first" sorts by. Kept apart
101
+ * from `#events` itself (rather than reading array position) so a
102
+ * redaction rewriting an entry in place never disturbs where it sorts. */
103
+ #insertOrder = new Map();
104
+ #insertSeq = 0;
96
105
  #pending;
97
106
  #parkedWaiters = [];
98
107
  #disposed = false;
@@ -354,6 +363,16 @@ export class FakeChatServer {
354
363
  origin_server_ts: now,
355
364
  content: { name: seed.name },
356
365
  });
366
+ if (seed.encrypted) {
367
+ events.push({
368
+ type: 'm.room.encryption',
369
+ state_key: '',
370
+ event_id: `$encryption-${seed.id}`,
371
+ sender: this.userId,
372
+ origin_server_ts: now,
373
+ content: { algorithm: 'm.megolm.v1.aes-sha2' },
374
+ });
375
+ }
357
376
  return {
358
377
  summary: {},
359
378
  state: { events },
@@ -409,10 +428,14 @@ export class FakeChatServer {
409
428
  #materialise(seed) {
410
429
  if (this.#events.has(seed.id))
411
430
  return;
412
- this.#events.set(seed.id, (seed.messages ?? []).map((message) => this.#messageEvent(message)));
431
+ const events = (seed.messages ?? []).map((message) => this.#messageEvent(message));
432
+ this.#events.set(seed.id, events);
433
+ for (const event of events)
434
+ this.#insertOrder.set(event.event_id, this.#insertSeq++);
413
435
  }
414
436
  #record(roomId, event) {
415
437
  this.#events.set(roomId, [...(this.#events.get(roomId) ?? []), event]);
438
+ this.#insertOrder.set(event.event_id, this.#insertSeq++);
416
439
  }
417
440
  /** One room's incremental entry, carrying just these events -- and,
418
441
  * given some, ephemeral ones (`m.typing`) alongside them, the way a real
@@ -439,6 +462,19 @@ export class FakeChatServer {
439
462
  [roomId]: this.#timelineEntry(roomId, [], [{ type: 'm.typing', content: { user_ids: userIds } }]),
440
463
  });
441
464
  }
465
+ /** Delivers a parked poll as `userId`'s public read receipt on
466
+ * `eventId` in `roomId` -- the `m.receipt` EDU another person's client
467
+ * causes by reading. Throws if nothing is parked. */
468
+ receiveReceipt(roomId, eventId, userId) {
469
+ this.#deliverParked({
470
+ [roomId]: this.#timelineEntry(roomId, [], [
471
+ {
472
+ type: 'm.receipt',
473
+ content: { [eventId]: { 'm.read': { [userId]: { ts: this.#now() } } } },
474
+ },
475
+ ]),
476
+ });
477
+ }
442
478
  /** Delivers a parked poll as an `m.presence` EDU for somebody else --
443
479
  * Matrix's own three states (`online`/`unavailable`/`offline`), or
444
480
  * MSC3026's unstable `org.matrix.msc3026.busy` -- for a test that drives
@@ -815,6 +851,74 @@ export class FakeChatServer {
815
851
  ...(end ? { end } : {}),
816
852
  }));
817
853
  }
854
+ // `ChatClient.search`'s own wire call (agora#252, agora#31): a plain
855
+ // case-insensitive substring match over every `m.room.message` body
856
+ // this fake has recorded, newest first, scoped to `filter.rooms` when
857
+ // the client sent one. Reads `#events` live rather than a snapshot
858
+ // taken at record time, so a redacted message (its content already
859
+ // emptied by the `redact` route) stops matching immediately, the same
860
+ // as a real search index would once Synapse's own redaction handling
861
+ // catches up to it. `next_batch` pages a deliberately small five at a
862
+ // time, so a unit test can prove `search`'s own paging without seeding
863
+ // hundreds of messages.
864
+ //
865
+ // An encrypted room's messages never match. This fake stores every
866
+ // body as plain text regardless of `encrypted` -- there is no real
867
+ // Megolm session here to encrypt against -- but a real Synapse never
868
+ // has a cleartext body to index for such a room in the first place, so
869
+ // a fake that let one match would prove `search` filters encrypted
870
+ // rooms out itself, which is exactly what it must not do (the fake's
871
+ // own module comment, and `ChatSearchResults`).
872
+ if (url.pathname === '/_matrix/client/v3/search' &&
873
+ init?.method === 'POST' &&
874
+ this.#authorised(init)) {
875
+ let body = {};
876
+ try {
877
+ body = JSON.parse(String(init?.body ?? '{}'));
878
+ }
879
+ catch {
880
+ // Same tolerance as every other body this fake parses.
881
+ }
882
+ const term = (body.search_categories?.room_events?.search_term ?? '').toLowerCase();
883
+ const roomFilter = body.search_categories?.room_events?.filter?.rooms;
884
+ const encryptedRoomIds = new Set(this.#rooms.filter((room) => room.encrypted).map((room) => room.id));
885
+ const flattened = [];
886
+ for (const [roomId, events] of this.#events) {
887
+ if (roomFilter && !roomFilter.includes(roomId))
888
+ continue;
889
+ if (encryptedRoomIds.has(roomId))
890
+ continue;
891
+ for (const event of events)
892
+ flattened.push({ roomId, event });
893
+ }
894
+ const matches = flattened
895
+ .filter((entry) => entry.event.type === 'm.room.message')
896
+ .filter((entry) => {
897
+ const value = entry.event.content.body;
898
+ return typeof value === 'string' && value.toLowerCase().includes(term);
899
+ })
900
+ .sort((a, b) => (this.#insertOrder.get(b.event.event_id) ?? 0) -
901
+ (this.#insertOrder.get(a.event.event_id) ?? 0));
902
+ const pageSize = 5;
903
+ const from = url.searchParams.get('next_batch');
904
+ const start = from?.startsWith('idx-') ? Number(from.slice('idx-'.length)) : 0;
905
+ const chunk = matches.slice(start, start + pageSize);
906
+ const nextIndex = start + chunk.length;
907
+ const nextBatch = nextIndex < matches.length ? `idx-${nextIndex}` : undefined;
908
+ return Promise.resolve(jsonResponse(200, {
909
+ search_categories: {
910
+ room_events: {
911
+ count: matches.length,
912
+ results: chunk.map((entry) => ({
913
+ rank: 1,
914
+ result: { ...entry.event, room_id: entry.roomId },
915
+ })),
916
+ highlights: [],
917
+ ...(nextBatch ? { next_batch: nextBatch } : {}),
918
+ },
919
+ },
920
+ }));
921
+ }
818
922
  const send = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/send\/([^/]+)\/([^/]+)$/);
819
923
  if (send && this.#authorised(init)) {
820
924
  let content = {};
@@ -828,9 +932,9 @@ export class FakeChatServer {
828
932
  const roomId = decodeURIComponent(send[1]);
829
933
  const type = decodeURIComponent(send[2]);
830
934
  const txnId = decodeURIComponent(send[3]);
831
- this.sent.push({ roomId, type, content });
832
935
  this.#eventSeq += 1;
833
936
  const eventId = `$sent-${this.#eventSeq}`;
937
+ this.sent.push({ roomId, eventId, type, content });
834
938
  // Echoed back through sync, the way a homeserver does, carrying the
835
939
  // transaction id so matrix-js-sdk resolves its own local echo rather
836
940
  // than showing the message twice. Without the echo a reaction would
@@ -927,6 +1031,35 @@ export class FakeChatServer {
927
1031
  return jsonResponse(200, { content_uri: `mxc://${this.serverName}/${mediaId}` });
928
1032
  })();
929
1033
  }
1034
+ // `apps/chat-service`'s media proxy (wtfalch/chat#32). The same two
1035
+ // checks the real one makes: the account is still in `roomId`, and
1036
+ // `eventId` is a message sent there that references this media.
1037
+ const chatMedia = url.pathname.match(/^\/_chat\/media\/([^/]+)\/([^/]+)$/);
1038
+ if (chatMedia) {
1039
+ const authorised = this.#authorised(init);
1040
+ this.mediaRequests.push({ path: url.pathname, authorised });
1041
+ if (!authorised) {
1042
+ return Promise.resolve(jsonResponse(401, { error: 'token_invalid' }));
1043
+ }
1044
+ const roomId = url.searchParams.get('roomId');
1045
+ const eventId = url.searchParams.get('eventId');
1046
+ if (!roomId || !this.#rooms.some((room) => room.id === roomId)) {
1047
+ return Promise.resolve(jsonResponse(403, { error: 'not_a_member' }));
1048
+ }
1049
+ const mxcUri = `mxc://${decodeURIComponent(chatMedia[1])}/${decodeURIComponent(chatMedia[2])}`;
1050
+ const carrier = this.sent.find((entry) => entry.roomId === roomId && entry.eventId === eventId && entry.content.url === mxcUri);
1051
+ if (!carrier) {
1052
+ return Promise.resolve(jsonResponse(403, { error: 'not_in_room' }));
1053
+ }
1054
+ const found = this.media.get(decodeURIComponent(chatMedia[2]));
1055
+ if (!found) {
1056
+ return Promise.resolve(jsonResponse(404, { error: 'not_found' }));
1057
+ }
1058
+ return Promise.resolve(new Response(found.bytes, {
1059
+ status: 200,
1060
+ headers: { 'Content-Type': found.contentType || 'application/octet-stream' },
1061
+ }));
1062
+ }
930
1063
  const download = url.pathname.match(/^\/_matrix\/client\/v1\/media\/download\/([^/]+)\/([^/]+)$/);
931
1064
  if (download) {
932
1065
  const authorised = this.#authorised(init);
@@ -1035,6 +1168,19 @@ export class FakeChatServer {
1035
1168
  });
1036
1169
  return Promise.resolve(jsonResponse(200, {}));
1037
1170
  }
1171
+ const report = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/report\/([^/]+)$/);
1172
+ if (report && init?.method === 'POST') {
1173
+ const token = bearerToken(init);
1174
+ if (!token || !this.#validTokens.has(token)) {
1175
+ return Promise.resolve(jsonResponse(401, { errcode: 'M_UNKNOWN_TOKEN', error: 'Invalid access token' }));
1176
+ }
1177
+ this.reports.push({
1178
+ roomId: decodeURIComponent(report[1]),
1179
+ eventId: decodeURIComponent(report[2]),
1180
+ body: JSON.parse(String(init.body ?? '{}')),
1181
+ });
1182
+ return Promise.resolve(jsonResponse(200, {}));
1183
+ }
1038
1184
  // Anything else at this homeserver -- capability discovery, RTC
1039
1185
  // transports, and whatever else a client startup probes for -- is
1040
1186
  // 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, ChatSearchResults, ChatTimelineEvent, 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;
@@ -22,7 +22,14 @@ export function formatSize(bytes) {
22
22
  * no URL to put in an `<img src>` -- the bytes have to come through the
23
23
  * client. `null` while it is still coming, and `null` for good if it
24
24
  * cannot be had. */
25
- export function useMediaUrl(client, mxcUri) {
25
+ /** A Matrix event id from the server starts with `$`. A local echo's
26
+ * (`~...`) is not one yet, and the media proxy only serves a file whose
27
+ * message it can find (wtfalch/chat#32), so nothing is fetched until the
28
+ * server's id arrives. */
29
+ function isServerEventId(eventId) {
30
+ return eventId.startsWith('$');
31
+ }
32
+ export function useMediaUrl(client, mxcUri, roomId, eventId) {
26
33
  const [attempt, setAttempt] = useState(0);
27
34
  const [result, setResult] = useState(null);
28
35
  useEffect(() => {
@@ -32,7 +39,7 @@ export function useMediaUrl(client, mxcUri) {
32
39
  let current = null;
33
40
  let cancelled = false;
34
41
  void client
35
- .loadMedia(mxcUri)
42
+ .loadMedia(mxcUri, roomId, eventId)
36
43
  .catch(() => null)
37
44
  .then((url) => {
38
45
  if (cancelled) {
@@ -41,15 +48,18 @@ export function useMediaUrl(client, mxcUri) {
41
48
  return;
42
49
  }
43
50
  current = url;
44
- setResult({ client, mxcUri, url, attempt });
51
+ setResult({ client, mxcUri, eventId, url, attempt });
45
52
  });
46
53
  return () => {
47
54
  cancelled = true;
48
55
  if (current)
49
56
  URL.revokeObjectURL(current);
50
57
  };
51
- }, [client, mxcUri, attempt]);
52
- const current = result?.client === client && result.mxcUri === mxcUri && result.attempt === attempt
58
+ }, [client, mxcUri, roomId, eventId, attempt]);
59
+ const current = result?.client === client &&
60
+ result.mxcUri === mxcUri &&
61
+ result.eventId === eventId &&
62
+ result.attempt === attempt
53
63
  ? result
54
64
  : null;
55
65
  return {
@@ -65,8 +75,8 @@ export function useMediaUrl(client, mxcUri) {
65
75
  * load, or that a reader cannot see, still has to say what it is -- the
66
76
  * agora's Named Station Rule, which is why there is no bare thumbnail
67
77
  * anywhere in here. */
68
- export function AttachmentView({ attachment, client, upload }) {
69
- const { url, failed, retry } = useMediaUrl(client, upload ? null : attachment.mxcUri);
78
+ export function AttachmentView({ attachment, client, roomId, upload }) {
79
+ const { url, failed, retry } = useMediaUrl(client, upload || !isServerEventId(attachment.eventId) ? null : attachment.mxcUri, roomId, attachment.eventId);
70
80
  return (_jsxs("div", { className: "chat-file", children: [attachment.isImage && url && (_jsx("img", { className: "chat-file-image", src: url, alt: attachment.name })), _jsxs("div", { className: "chat-file-row", children: [_jsx("span", { className: "chat-file-name", children: attachment.name }), _jsx("span", { className: "chat-file-size", children: formatSize(attachment.size) }), url && (_jsx("a", { className: "chat-file-get", href: url, download: attachment.name, children: "Download" }))] }), failed && (_jsxs("p", { className: "chat-message-status", children: ["Could not load this file.", ' ', _jsx(Button, { kind: "ghost", size: "sm", onPress: retry, children: "Retry download" })] })), upload && (_jsxs("p", { className: "chat-file-progress", children: [_jsx("progress", { "aria-label": `Uploading ${attachment.name}`, value: upload.loaded, max: upload.total || 1 }), _jsxs("span", { children: [Math.round((upload.loaded / (upload.total || 1)) * 100), "% sent"] })] }))] }));
71
81
  }
72
82
  /** Fills in the `src` of every `img[data-mxc]` the sanitiser left in a
@@ -76,10 +86,10 @@ export function AttachmentView({ attachment, client, upload }) {
76
86
  * nothing is requested until this runs and nothing is ever requested
77
87
  * without the token. An image whose bytes cannot be had simply stays
78
88
  * blank beside its own `alt`. */
79
- export function useInlineMedia(client, host, html) {
89
+ export function useInlineMedia(client, host, html, roomId, eventId) {
80
90
  useEffect(() => {
81
91
  const element = host.current;
82
- if (!element || !html)
92
+ if (!element || !html || !isServerEventId(eventId))
83
93
  return;
84
94
  const images = Array.from(element.querySelectorAll('img[data-mxc]'));
85
95
  if (images.length === 0)
@@ -91,7 +101,7 @@ export function useInlineMedia(client, host, html) {
91
101
  if (!mxcUri)
92
102
  continue;
93
103
  client
94
- .loadMedia(mxcUri)
104
+ .loadMedia(mxcUri, roomId, eventId)
95
105
  .then((url) => {
96
106
  if (!url)
97
107
  return;
@@ -109,5 +119,5 @@ export function useInlineMedia(client, host, html) {
109
119
  for (const url of made)
110
120
  URL.revokeObjectURL(url);
111
121
  };
112
- }, [client, host, html]);
122
+ }, [client, host, html, roomId, eventId]);
113
123
  }
@@ -25,7 +25,7 @@ export function MessageRow({ event, client, roomId, onOpenThread, highlighted })
25
25
  // The sanitiser leaves an allowed image with a reference and no `src`;
26
26
  // this is what puts one there, with the bytes fetched under the token.
27
27
  const body = useRef(null);
28
- useInlineMedia(client, body, html);
28
+ useInlineMedia(client, body, html, roomId, event.id);
29
29
  const [picking, setPicking] = useState(false);
30
30
  const [editing, setEditing] = useState(false);
31
31
  const [confirmingDelete, setConfirmingDelete] = useState(false);
@@ -56,7 +56,7 @@ export function MessageRow({ event, client, roomId, onOpenThread, highlighted })
56
56
  dangerouslySetInnerHTML: { __html: html } })) : event.attachment ? (
57
57
  // A file names itself in its own row, so the body would say the
58
58
  // same thing twice.
59
- _jsx(AttachmentView, { attachment: event.attachment, client: client, upload: event.upload })) : (_jsx("div", { className: "chat-message-body", children: event.body })), (event.reactions.length > 0 || (event.status === 'sent' && !event.deleted)) && (_jsxs("div", { className: "chat-reactions", children: [event.reactions.map((reaction) => (_jsx(ReactionPill, { reaction: reaction, onPress: react }, reaction.key))), event.status === 'sent' && !event.deleted && (_jsxs(_Fragment, { children: [_jsx("button", { type: "button", className: "chat-react", onClick: () => setPicking((open) => !open), "aria-expanded": picking, children: "React" }), picking && (_jsx("span", { className: "chat-react-choices", children: QUICK_REACTIONS.map((key) => (_jsx("button", { type: "button", className: "chat-react-choice", onClick: () => react(key), "aria-label": `React with ${key}`, children: key }, key))) }))] })), own && !editing && !confirmingDelete && (_jsxs(_Fragment, { children: [!event.attachment && (_jsx("button", { type: "button", className: "chat-react", onClick: () => setEditing(true), children: "Edit" })), _jsx("button", { type: "button", className: "chat-react", onClick: () => setConfirmingDelete(true), children: "Delete" })] })), own && confirmingDelete && (
59
+ _jsx(AttachmentView, { attachment: event.attachment, client: client, roomId: roomId, upload: event.upload })) : (_jsx("div", { className: "chat-message-body", children: event.body })), (event.reactions.length > 0 || (event.status === 'sent' && !event.deleted)) && (_jsxs("div", { className: "chat-reactions", children: [event.reactions.map((reaction) => (_jsx(ReactionPill, { reaction: reaction, onPress: react }, reaction.key))), event.status === 'sent' && !event.deleted && (_jsxs(_Fragment, { children: [_jsx("button", { type: "button", className: "chat-react", onClick: () => setPicking((open) => !open), "aria-expanded": picking, children: "React" }), picking && (_jsx("span", { className: "chat-react-choices", children: QUICK_REACTIONS.map((key) => (_jsx("button", { type: "button", className: "chat-react-choice", onClick: () => react(key), "aria-label": `React with ${key}`, children: key }, key))) }))] })), own && !editing && !confirmingDelete && (_jsxs(_Fragment, { children: [!event.attachment && (_jsx("button", { type: "button", className: "chat-react", onClick: () => setEditing(true), children: "Edit" })), _jsx("button", { type: "button", className: "chat-react", onClick: () => setConfirmingDelete(true), children: "Delete" })] })), own && confirmingDelete && (
60
60
  // Asked in the row rather than in a dialog: a redaction cannot
61
61
  // be taken back, and a browser dialog would take the whole
62
62
  // conversation away to ask one question.
@@ -91,11 +91,21 @@ export type ChatAttachment = {
91
91
  /** Bytes, as the sender reported them. `0` when the sender sent none. */
92
92
  readonly size: number;
93
93
  readonly mxcUri: string;
94
+ /** The message this file was posted in. `loadMedia` needs it: the media
95
+ * proxy only serves a file whose message it can find in the room
96
+ * (wtfalch/chat#32). */
97
+ readonly eventId: string;
94
98
  /** Whether this package will preview it inline. An image, and only ever
95
99
  * by the `mimeType` the sender declared -- which is why the preview is
96
100
  * still fetched through `loadMedia` rather than pointed at. */
97
101
  readonly isImage: boolean;
98
102
  };
103
+ /** One page of `roomFiles`. `next` is `null` when the room has no older
104
+ * files; otherwise pass it back as `before` to continue. */
105
+ export type ChatRoomFilesPage = {
106
+ readonly files: readonly ChatAttachment[];
107
+ readonly next: string | null;
108
+ };
99
109
  /** A file still going up, as `timeline()` shows it: a message that is not
100
110
  * a message yet. `total` is the file's own size, so a caller draws a
101
111
  * proportion without knowing anything about chunks. */
@@ -172,6 +182,24 @@ export type ChatTimelinePage = {
172
182
  * comes back with nothing more behind it. */
173
183
  readonly hasMore: boolean;
174
184
  };
185
+ /** What `search` finds, across the rooms it was allowed to look in.
186
+ * `results` is newest first, each carrying the room it was found in
187
+ * alongside the message itself -- a global search has no single room to
188
+ * hang the result off, so it travels with every one. `unsearchableRoomIds`
189
+ * is every joined room this search could not look inside because it is
190
+ * encrypted: `[roomId]` for a room-scoped search of an encrypted room
191
+ * (`results` is then always empty), or every encrypted room this account
192
+ * is in for a search across all of them. Synapse never indexes an
193
+ * encrypted room's cleartext, so an empty `results` there is silence, not
194
+ * "nothing found" -- a caller reads `unsearchableRoomIds` to tell the two
195
+ * apart (agora#252, agora#31). */
196
+ export type ChatSearchResults = {
197
+ readonly results: readonly {
198
+ roomId: string;
199
+ event: ChatTimelineEvent;
200
+ }[];
201
+ readonly unsearchableRoomIds: readonly string[];
202
+ };
175
203
  /** Whether the sync loop is caught up, working to catch up (after a
176
204
  * network drop, or recovering from a refused sync position with a fresh
177
205
  * full sync), or not connected at all. */
@@ -246,13 +274,14 @@ export type ChatClient = {
246
274
  * caller ever paging the room's timeline to find them -- see
247
275
  * `ChatAttachment` for what counts as a file. `options.limit` stops
248
276
  * once that many have been collected; omitted, this keeps going until
249
- * Synapse says there is nothing older. `options.before` continues a
250
- * walk this method already started: Synapse's own opaque `/messages`
251
- * pagination token (its `end` field) -- not a `ChatTimelineEvent.id`.
252
- * This method does not hand one back yet, so nothing here can produce a
253
- * value for a caller to pass in; see the ticket's own report for why
254
- * that is left for whoever needs it next rather than reshaping the
255
- * return type now.
277
+ * Synapse says there is nothing older. The result's `next` is the
278
+ * cursor for the files after these: pass it back as `options.before` to
279
+ * load more (#33). It is Synapse's own opaque `/messages` token, not a
280
+ * `ChatTimelineEvent.id`, and `null` once there is nothing older. With
281
+ * a `limit`, `next` resumes exactly after the last file returned: no
282
+ * file is skipped and none comes back twice. Synapse can hand back a
283
+ * cursor that turns out to have nothing behind it, so the last page may
284
+ * be empty.
256
285
  *
257
286
  * Filtered server-side, not paged client-side: `GET .../messages`
258
287
  * takes Matrix's own `contains_url` filter, and Synapse answers it with
@@ -287,17 +316,41 @@ export type ChatClient = {
287
316
  * module comment), so an encrypted room's whole timeline is already
288
317
  * unusable, not just this method.
289
318
  *
290
- * Empty before `start()` resolves, or for a room this client does not
291
- * know. */
319
+ * No files and a `null` cursor before `start()` resolves, or for a room
320
+ * this client does not know. */
292
321
  roomFiles: (roomId: string, options?: {
293
322
  limit?: number;
294
323
  before?: string;
295
- }) => Promise<readonly ChatAttachment[]>;
324
+ }) => Promise<ChatRoomFilesPage>;
325
+ /** A word or phrase, across every room this account is joined to, or just
326
+ * `options.roomId`, through Synapse's own server-side search
327
+ * (`POST /search`, `room_events`, newest first) -- so permission
328
+ * filtering is Synapse's: a room this account has left never appears,
329
+ * with no filter of this package's own layered on top (agora#31).
330
+ * `limit` stops once that many results are collected, following
331
+ * `next_batch` as far as it takes to get there; defaults to 50.
332
+ *
333
+ * Encrypted rooms are reported, not silently skipped -- see
334
+ * `ChatSearchResults`. That is the one search this package can commit to
335
+ * today: crypto stays off (the module comment says why), so a real
336
+ * encrypted room's cleartext was never in Synapse's index to begin with
337
+ * (agora#252). */
338
+ search: (query: string, options?: {
339
+ roomId?: string;
340
+ limit?: number;
341
+ }) => Promise<ChatSearchResults>;
296
342
  /** Everyone joined to `roomId`, by name, the signed-in person included --
297
343
  * who a message in this room can mention. A room's own membership, not
298
344
  * the company's: mentioning somebody who is not here would notify
299
345
  * nobody. Empty for a room this client does not know. */
300
346
  roomMembers: (roomId: string) => ChatPerson[];
347
+ /** Who has seen `eventId` in `roomId`: every joined person whose read
348
+ * receipt is at this message or a newer one, by name (#31). Leaves out
349
+ * the signed-in person and the message's own sender. Only people who
350
+ * send public read receipts appear. `onTimelineChanged` fires when a
351
+ * receipt moves, so a view re-reads this then. Empty for a room or
352
+ * message this client does not have loaded. */
353
+ readBy: (roomId: string, eventId: string) => ChatPerson[];
301
354
  /** Adds the signed-in person's reaction to `eventId`, or takes it away
302
355
  * if it is already theirs -- one call for both, because that is the one
303
356
  * thing a person ever means by pressing a reaction.
@@ -334,6 +387,12 @@ export type ChatClient = {
334
387
  * thread hanging off a deleted message keeps every reply, and a reader
335
388
  * scrolling past does not have the page move under them. */
336
389
  deleteMessage: (roomId: string, eventId: string) => Promise<void>;
390
+ /** Reports someone's message to the company's chat admins, with a
391
+ * reason (#29). The admins see who reported which message and why
392
+ * (`listReports` in `@wtfalch/chat/admin`), and can remove it or ban
393
+ * its sender. The message stays until they act. Rejects if the server
394
+ * refuses, for instance for a message this person cannot see. */
395
+ reportMessage: (roomId: string, eventId: string, reason: string) => Promise<void>;
337
396
  /** Retries a `'failed'` send with the same content. A no-op if `localId`
338
397
  * is no longer in the room's pending events (already retried, already
339
398
  * settled). */
@@ -355,14 +414,18 @@ export type ChatClient = {
355
414
  * `loadMedia`. This is what the sanitiser asks before it keeps an
356
415
  * `img` at all. */
357
416
  canLoadMedia: (mxcUri: string) => boolean;
358
- /** Fetches `mxcUri` from `/_matrix/client/v1/media/download` with this
359
- * session's token and resolves with an object URL for the bytes, or
360
- * `null` if this session may not load it or the fetch failed.
417
+ /** Fetches `mxcUri` through `apps/chat-service`'s media proxy and
418
+ * resolves with an object URL for the bytes. Synapse's own download
419
+ * endpoint serves any valid token without checking the room
420
+ * (wtfalch/chat#32), so this package never asks it directly. The proxy
421
+ * checks that this session is still in `roomId` and that `eventId`, a
422
+ * message in that room, references `mxcUri`. Resolves with `null` if
423
+ * this session may not load it, either check fails, or the fetch fails.
361
424
  *
362
425
  * **The caller owns the URL and must `URL.revokeObjectURL` it**, or the
363
426
  * blob is held for the life of the document. The React components in
364
427
  * `@wtfalch/chat/react` do that on unmount. */
365
- loadMedia: (mxcUri: string) => Promise<string | null>;
428
+ loadMedia: (mxcUri: string, roomId: string, eventId: string) => Promise<string | null>;
366
429
  /** Sends `file` to `roomId` as `m.image` (an image) or `m.file`, and
367
430
  * returns the id its row carries in `timeline()` at once -- before a
368
431
  * byte has gone up. That row is `'pending'` with `upload` counting, and
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wtfalch/chat",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "A Matrix chat client behind the agora's token exchange.",
5
5
  "license": "MIT",
6
6
  "type": "module",