@wtfalch/chat 0.5.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,8 @@
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';
1
+ import { ClientEvent, ContentHelpers, Direction, EventStatus, EventTimeline, EventType, Filter, HttpApiEvent, KnownMembership, MatrixError, MatrixEvent, MatrixEventEvent, Method, MsgType, NotificationCountType, Preset, PushRuleActionName, RelationType, RoomEvent, RoomMemberEvent, SetPresence, SyncState, UserEvent, createClient as createMatrixClient, } from 'matrix-js-sdk';
2
+ import { CryptoEvent, decodeRecoveryKey, } from 'matrix-js-sdk/lib/crypto-api';
2
3
  import { exchange } from "./exchange.js";
3
4
  import { toFormattedBody } from "./markdown.js";
4
- import { createChatStore } from "./store.js";
5
+ import { createChatStore, cryptoStoreDbPrefix, purgeStaleChatStores } from "./store.js";
5
6
  /** A Matrix token never outlives the ZITADEL token it was swapped for (see
6
7
  * the chat plan section 4), and Synapse's own introspection cache is only
7
8
  * good for two minutes -- so a minute of headroom before `expires_at` is
@@ -12,11 +13,48 @@ const REFRESH_MARGIN_MS = 60_000;
12
13
  * margin above, so a client that cannot refresh keeps trying while the
13
14
  * token it holds is still good. */
14
15
  const REFRESH_RETRY_MS = 5_000;
16
+ /** First and longest wait between attempts to rebuild a client whose crypto
17
+ * failed to come up during a recovery (`swapClient`). */
18
+ const REBUILD_RETRY_MS = 1_000;
19
+ const REBUILD_RETRY_MAX_MS = 30_000;
20
+ /** The custom `m.room.member` content key `readGuest` looks for, carrying
21
+ * `{ until }` -- see `docs/guests.md`, "What the SDK shows", and
22
+ * `ChatPerson.guest`. Nothing writes it yet, and nothing should until the
23
+ * chat-service half is designed: review on #73 found that a member's own
24
+ * join event replaces an invite's content wholesale, so a marker
25
+ * `@chat-admin` set on the invite does not survive the guest's own accept,
26
+ * and in the meantime this key is as writable as a display name -- any
27
+ * member could set or clear it on themselves. A trustworthy marker needs
28
+ * the chat service's grant list as source of truth, read through an
29
+ * authenticated route, not a field on event content the room's own
30
+ * members control. This constant and `readGuest` are the one place that
31
+ * changes once that lands. */
32
+ const GUEST_MARKER_KEY = 'dev.wtfalch.chat.guest';
15
33
  /** The room tag that takes a direct room out of the sidebar. A tag, not a
16
34
  * leave: the person stays joined, so the room's history is exactly where
17
35
  * they left it when the DM is reopened (ticket #16). Namespaced, as the
18
36
  * Matrix spec requires of any tag outside `m.` and `u.`. */
19
37
  const HIDDEN_TAG = 'com.wtfalch.hidden';
38
+ /** The pre-merge key for MSC2867's marked-unread flag. `markRoomUnread`
39
+ * writes it alongside the now-stable `m.marked_unread` (`EventType.
40
+ * MarkedUnread`) so a client that has not caught up to the merged MSC
41
+ * still reads the flag; `isMarkedUnread` falls back to it for the same
42
+ * reason. Not in matrix-js-sdk's `RoomAccountDataEvents` map -- it only
43
+ * knows the stable key -- so it is written the same way `reportMessage`
44
+ * reaches an endpoint the typed client has no wrapper for: by hand. */
45
+ const FAMEDLY_MARKED_UNREAD = 'com.famedly.marked_unread';
46
+ /** The room account data type a draft is stored under -- namespaced the
47
+ * same way `HIDDEN_TAG` namespaces this package's custom room tag. See
48
+ * `ChatClient.getDraft`. */
49
+ const DRAFT_EVENT_TYPE = 'com.wtfalch.draft';
50
+ /** The Matrix spec's own tag for a starred room -- `starRoom` writes and
51
+ * deletes it exactly as `hideDirectMessage` does `HIDDEN_TAG`, and
52
+ * `readRooms()` reads it the same way (agora#27). */
53
+ const FAVOURITE_TAG = 'm.favourite';
54
+ /** The MSC4133 extended-profile key `setOwnStatus` writes and `personStatus`
55
+ * reads -- namespaced the same way `HIDDEN_TAG` and `DRAFT_EVENT_TYPE` are.
56
+ * See `ChatClient.status` and `docs/status.md`. */
57
+ const STATUS_PROFILE_KEY = 'com.wtfalch.status';
20
58
  /** Every `startClient()` in this file passes these, including the two
21
59
  * recoveries: a restart that dropped `threadSupport` would quietly put
22
60
  * every later thread reply back into the room's own timeline. */
@@ -39,6 +77,15 @@ function mediaProxyUrl(exchangeUrl, mxc, roomId, eventId) {
39
77
  url.searchParams.set('eventId', eventId);
40
78
  return url.toString();
41
79
  }
80
+ /** Where a thread's follow state lives: `apps/chat-service`'s
81
+ * `/_chat/threads/...`, next to `exchangeUrl` like the media proxy. */
82
+ function threadFollowUrl(exchangeUrl, roomId, threadId) {
83
+ const base = exchangeUrl.replace(/\/_chat\/exchange\/?$/, '');
84
+ return `${base}/_chat/threads/${encodeURIComponent(roomId)}/${encodeURIComponent(threadId)}/follow`;
85
+ }
86
+ function setDraftAccountData(target, roomId, content) {
87
+ return target.setRoomAccountData(roomId, DRAFT_EVENT_TYPE, content);
88
+ }
42
89
  /** What `sendTyping` asks the server to auto-expire a typing state after,
43
90
  * in ms -- matrix-js-sdk's own default when a caller passes none
44
91
  * (`client.js`'s `sendTyping`), used explicitly here since this package's
@@ -62,13 +109,21 @@ const SEARCH_LIMIT_DEFAULT = 50;
62
109
  * A chat session behind the exchange: a matrix-js-sdk `MatrixClient` the
63
110
  * caller never sees, refreshed on its own, exposing only what a UI needs.
64
111
  *
65
- * **Crypto stays off.** Encryption is not in the first ship (chat plan
66
- * section 6), so this never calls `initRustCrypto()`. matrix-js-sdk only
67
- * imports its Rust crypto WASM when that is called (`client.js`: "importing
68
- * rust-crypto will download the webassembly, so we delay it until we know
69
- * it will be [needed]") -- so skipping it means the WASM module is never
70
- * loaded, in the browser or under vitest. No shim or polyfill for it is
71
- * needed either way.
112
+ * **Crypto stays off unless asked for.** `encryptionEnabled` gates a call
113
+ * to `initRustCrypto()`, made once, right after the `MatrixClient` exists
114
+ * and before anything else touches this closure's own state -- key
115
+ * backup, recovery key and device verification (chat#67-69) all need a
116
+ * running `CryptoApi` (`getCrypto()`) to build against. Omitted or
117
+ * `false`, this behaves exactly as it always has and never calls it at
118
+ * all: matrix-js-sdk only imports its Rust crypto WASM when
119
+ * `initRustCrypto()` is called (`client.js`: "importing rust-crypto will
120
+ * download the webassembly, so we delay it until we know it will be
121
+ * [needed]") -- so skipping it means the WASM module is never loaded, in
122
+ * the browser or under vitest. No shim or polyfill for it is needed
123
+ * either way. Its own store, bound to the exchanged identity the same
124
+ * tuple `createChatStore` binds the sync one to (`cryptoStoreDbPrefix`) --
125
+ * without that, matrix-js-sdk's fixed default name is shared by every
126
+ * client in the browser (chat#71 review).
72
127
  *
73
128
  * **Refresh, not a Matrix refresh token.** There is no such thing (section
74
129
  * 4): a near-expiry timer and a `Session.logged_out` listener (fired by
@@ -82,8 +137,33 @@ const SEARCH_LIMIT_DEFAULT = 50;
82
137
  * resume syncing.
83
138
  */
84
139
  export function createChatClient(options) {
85
- const { exchangeUrl, getAccessToken, deviceId, storeName } = options;
140
+ const { exchangeUrl, getAccessToken, deviceId, storeName, encryptionEnabled } = options;
86
141
  let client;
142
+ /** True while `swapClient` has disposed `client` and not yet replaced it:
143
+ * its crypto is closed, so `getCrypto()` must not hand it out. */
144
+ let cryptoClosed = false;
145
+ /** The one piece of secret-storage plumbing `bootstrapSecretStorage`
146
+ * (chat#68) cannot work without: matrix-js-sdk calls back into
147
+ * `getSecretStorageKey` every time it needs to encrypt or decrypt
148
+ * something in secret storage, and refuses outright
149
+ * ("No getSecretStorageKey callback supplied") with no `cryptoCallbacks`
150
+ * configured at all. `cacheSecretStorageKey` is matrix-js-sdk's own
151
+ * suggested pattern for answering it: `bootstrapSecretStorage` calls it
152
+ * with the key it just generated (or that a caller's own
153
+ * `createSecretStorageKey` returned), and this cache is what
154
+ * `getSecretStorageKey` reads back for as long as this session runs.
155
+ * Scoped to the closure, not persisted: a new sign-in needing a secret
156
+ * it cannot answer from here falls through to `null`, which
157
+ * matrix-js-sdk turns into a failed operation rather than a crash --
158
+ * the recovery-key entry flow (`enterRecoveryKey`, chat#68's "entry"
159
+ * half) is what populates this from a key a person types back in:
160
+ * it decodes and checks the key against the stored one, then caches it
161
+ * here. (`bootstrapSecretStorage` is not that path: it would replace
162
+ * secret storage with a new key rather than unlock the existing one.)
163
+ * Cleared by `stop()` and whenever the account changes. */
164
+ const secretStorageKeys = new Map();
165
+ /** The account `secretStorageKeys` belongs to. */
166
+ let secretStorageUserId;
87
167
  let starting;
88
168
  let refreshTimer;
89
169
  let recovering;
@@ -99,6 +179,18 @@ export function createChatClient(options) {
99
179
  const statusListeners = new Set();
100
180
  const presenceListeners = new Set();
101
181
  const typingListeners = new Map();
182
+ /** See `ChatClient.onVerificationRequestReceived`. Attached once per
183
+ * live `MatrixClient` in `attachListeners`, the same as every other
184
+ * listener there -- a restart needs it rebound to the new client the
185
+ * same way it needs `onSync` or `RoomEvent.Timeline` rebound. */
186
+ const verificationListeners = new Set();
187
+ /** See `ChatClient.status`. A `userId` missing from this map has never
188
+ * been asked about; `personStatus` uses that (not the value once
189
+ * present) to decide whether to start a fetch, so a placeholder `null`
190
+ * written the moment a fetch starts never triggers a second one while
191
+ * the first is still in flight. */
192
+ const chatStatusCache = new Map();
193
+ const chatStatusListeners = new Set();
102
194
  /** Who is currently typing, per room -- built up from `RoomMemberEvent.
103
195
  * Typing` one member at a time, the signed-in person's own id never
104
196
  * added (see `ChatClient.onTypingChanged`). Cleared on `stop()`: it is
@@ -124,8 +216,14 @@ export function createChatClient(options) {
124
216
  * have agreed again -- an unmute alone is not that proof. Every other
125
217
  * room never pays for the walk at all. */
126
218
  const unreliableServerCount = new Set();
219
+ /** The newest token any exchange returned. `buildClient` reads it, so a
220
+ * client rebuilt after a refresh that landed on its disposed predecessor
221
+ * still starts on the current token. */
222
+ let latestToken;
127
223
  async function performExchange() {
128
- return exchange(exchangeUrl, getAccessToken, deviceId);
224
+ const body = await exchange(exchangeUrl, getAccessToken, deviceId);
225
+ latestToken = body.access_token;
226
+ return body;
129
227
  }
130
228
  /** A failed proactive refresh must not end proactive refreshing: nothing
131
229
  * else re-arms this timer, so without the retry the client would go
@@ -205,23 +303,37 @@ export function createChatClient(options) {
205
303
  async function recoverFromRefusedPosition() {
206
304
  if (resyncing)
207
305
  return resyncing;
306
+ if (encryptionEnabled && recovering)
307
+ return recovering;
208
308
  const target = client;
209
309
  if (!target)
210
310
  return;
211
- resyncing = (async () => {
212
- target.stopClient();
213
- await target.store.deleteAllData();
214
- const outcome = nextSyncOutcome(target);
215
- await target.startClient(START_OPTIONS);
216
- reapplyAnnouncedPresence(target);
311
+ const run = (async () => {
312
+ const created = await restartClient(target, {
313
+ baseUrl: target.baseUrl,
314
+ userId: target.getUserId() ?? '',
315
+ accessToken: target.getAccessToken() ?? '',
316
+ deviceId: target.getDeviceId() ?? '',
317
+ }, true);
318
+ if (!created)
319
+ return;
320
+ const outcome = nextSyncOutcome(created);
321
+ await created.startClient(START_OPTIONS);
322
+ if (client !== created)
323
+ return;
324
+ reapplyAnnouncedPresence(created);
217
325
  await outcome;
326
+ if (client !== created)
327
+ return;
218
328
  notify();
219
329
  })();
330
+ resyncing = run;
220
331
  try {
221
- await resyncing;
332
+ await run;
222
333
  }
223
334
  finally {
224
- resyncing = undefined;
335
+ if (resyncing === run)
336
+ resyncing = undefined;
225
337
  }
226
338
  }
227
339
  /** Waits for the next sync to either land or fail, so callers can await a
@@ -260,25 +372,41 @@ export function createChatClient(options) {
260
372
  async function recoverFromLoggedOut() {
261
373
  if (recovering)
262
374
  return recovering;
375
+ if (encryptionEnabled && resyncing)
376
+ return resyncing;
263
377
  const target = client;
264
378
  if (!target)
265
379
  return;
266
- recovering = (async () => {
380
+ const run = (async () => {
267
381
  const body = await performExchange();
268
- target.stopClient();
269
- target.setAccessToken(body.access_token);
382
+ if (client !== target)
383
+ return;
384
+ const created = await restartClient(target, {
385
+ baseUrl: body.homeserver,
386
+ userId: body.user_id,
387
+ accessToken: body.access_token,
388
+ deviceId: body.device_id,
389
+ }, false);
390
+ if (!created)
391
+ return;
270
392
  scheduleRefresh(body.expires_at);
271
- const outcome = nextSyncOutcome(target);
272
- await target.startClient(START_OPTIONS);
273
- reapplyAnnouncedPresence(target);
393
+ const outcome = nextSyncOutcome(created);
394
+ await created.startClient(START_OPTIONS);
395
+ if (client !== created)
396
+ return;
397
+ reapplyAnnouncedPresence(created);
274
398
  await outcome;
399
+ if (client !== created)
400
+ return;
275
401
  notify();
276
402
  })();
403
+ recovering = run;
277
404
  try {
278
- await recovering;
405
+ await run;
279
406
  }
280
407
  finally {
281
- recovering = undefined;
408
+ if (recovering === run)
409
+ recovering = undefined;
282
410
  }
283
411
  }
284
412
  /** matrix-js-sdk only emits this for `M_UNKNOWN_TOKEN` (`http-api/fetch.ts`),
@@ -339,7 +467,15 @@ export function createChatClient(options) {
339
467
  isDirect: direct.has(room.roomId) || Boolean(room.getDMInviter()),
340
468
  membership,
341
469
  unreadCount: membership === 'invite' ? 1 : roomUnreadCount(target, room, muted),
470
+ // No invite-state equivalent of a highlight to read -- an
471
+ // unanswered invitation is never "mentioned", only invited.
472
+ mentionCount: membership === 'invite'
473
+ ? 0
474
+ : room.getUnreadNotificationCount(NotificationCountType.Highlight),
342
475
  muted,
476
+ markedUnread: isMarkedUnread(room),
477
+ archived: roomArchived(room),
478
+ starred: FAVOURITE_TAG in room.tags,
343
479
  };
344
480
  });
345
481
  }
@@ -388,6 +524,18 @@ export function createChatClient(options) {
388
524
  const rule = target.pushRules && target.getRoomPushRule('global', roomId);
389
525
  return Boolean(rule?.actions.includes(PushRuleActionName.DontNotify));
390
526
  }
527
+ /** See `ChatRoomSummary.markedUnread`. Reads the stable `m.marked_unread`
528
+ * key first and only falls back to the pre-merge `com.famedly.marked_
529
+ * unread` one when the stable key is entirely absent -- `markRoomUnread`
530
+ * always writes both together, so the two disagreeing means only a
531
+ * client that predates this package wrote the legacy key alone. */
532
+ function isMarkedUnread(room) {
533
+ const stable = room.getAccountData(EventType.MarkedUnread)?.getContent();
534
+ if (stable)
535
+ return Boolean(stable.unread);
536
+ const legacy = room.getAccountData(FAMEDLY_MARKED_UNREAD)?.getContent();
537
+ return Boolean(legacy?.unread);
538
+ }
391
539
  /** A muted room's own `unreadCount`, counted here rather than read off
392
540
  * Synapse. Confirmed live against Synapse v1.161.0: the room-scoped
393
541
  * `dont_notify` rule `muteRoom` writes does not merely withhold the
@@ -429,23 +577,44 @@ export function createChatClient(options) {
429
577
  .getRooms()
430
578
  .find((room) => room.isSpaceRoom() && room.getMyMembership() === KnownMembership.Join);
431
579
  }
580
+ /** `GUEST_MARKER_KEY` off `member`'s own `m.room.member` event, if
581
+ * chat-service marked one -- see `ChatPerson.guest`. */
582
+ function readGuest(member) {
583
+ const marker = member.events.member?.getContent()[GUEST_MARKER_KEY];
584
+ return typeof marker?.until === 'string' ? { until: marker.until } : undefined;
585
+ }
432
586
  function toPerson(member) {
433
- return { userId: member.userId, name: member.name };
587
+ const guest = readGuest(member);
588
+ return { userId: member.userId, name: member.name, ...(guest ? { guest } : {}) };
434
589
  }
435
- /** Everyone in the company space but the signed-in person. Guests are not
436
- * in the space, so this cannot offer one -- see `ChatPerson`. */
590
+ /** Everyone in the company space but the signed-in person, plus every
591
+ * guest sharing a joined room with them -- see `ChatClient.people`. A
592
+ * guest is never in the space, so the second half is the only way one is
593
+ * ever offered here. */
437
594
  function readPeople() {
438
595
  if (!client)
439
596
  return [];
440
- const space = companySpace(client);
441
- if (!space)
442
- return [];
443
597
  const me = client.getUserId();
444
- return space
445
- .getMembersWithMembership(KnownMembership.Join)
446
- .filter((member) => member.userId !== me)
447
- .map(toPerson)
448
- .sort((a, b) => a.name.localeCompare(b.name));
598
+ const people = new Map();
599
+ const space = companySpace(client);
600
+ if (space) {
601
+ for (const member of space.getMembersWithMembership(KnownMembership.Join)) {
602
+ if (member.userId !== me)
603
+ people.set(member.userId, toPerson(member));
604
+ }
605
+ }
606
+ for (const room of client.getRooms()) {
607
+ if (room.isSpaceRoom() || room.getMyMembership() !== KnownMembership.Join)
608
+ continue;
609
+ for (const member of room.getMembersWithMembership(KnownMembership.Join)) {
610
+ if (member.userId === me || people.has(member.userId))
611
+ continue;
612
+ const person = toPerson(member);
613
+ if (person.guest)
614
+ people.set(member.userId, person);
615
+ }
616
+ }
617
+ return [...people.values()].sort((a, b) => a.name.localeCompare(b.name));
449
618
  }
450
619
  /** Who else is in a room, joined or still invited -- an invitee counts,
451
620
  * or a DM started a second ago would not be found as an existing one
@@ -1056,7 +1225,13 @@ export function createChatClient(options) {
1056
1225
  // `threadId ?? null` rather than the two-argument overload: passing the
1057
1226
  // thread's root id is what makes the reply relate to the *root*, which
1058
1227
  // is the only shape Matrix has -- there is no replying to a reply.
1059
- client.sendMessage(roomId, threadId ?? null, content).catch(() => {
1228
+ client
1229
+ .sendMessage(roomId, threadId ?? null, content)
1230
+ .then(() => {
1231
+ if (threadId)
1232
+ autoFollowThread(roomId, threadId);
1233
+ })
1234
+ .catch(() => {
1060
1235
  // The failure already lives on the event's own status (`NOT_SENT`);
1061
1236
  // a caller reads that through `timeline()`, not this promise.
1062
1237
  });
@@ -1225,7 +1400,16 @@ export function createChatClient(options) {
1225
1400
  // it is an ordinary message: a send that fails is retried and
1226
1401
  // cancelled through the event, with the bytes already up.
1227
1402
  dropUpload(roomId, pending.id);
1228
- void target.sendMessage(roomId, pending.threadId, content).catch(() => { });
1403
+ const threadId = pending.threadId;
1404
+ // A file sent into a thread is a reply, so it follows the thread
1405
+ // just as `sendMessage` does, once it is sent.
1406
+ void target
1407
+ .sendMessage(roomId, threadId, content)
1408
+ .then(() => {
1409
+ if (threadId)
1410
+ autoFollowThread(roomId, threadId);
1411
+ })
1412
+ .catch(() => { });
1229
1413
  })
1230
1414
  .catch(() => {
1231
1415
  if (pending.abort.signal.aborted)
@@ -1385,6 +1569,16 @@ export function createChatClient(options) {
1385
1569
  * matrix-js-sdk's own current state -- there is no higher-level helper
1386
1570
  * for it the way `room.name` is one for `m.room.name`. `[]` for a room
1387
1571
  * with no such state at all, which is every room until the first pin. */
1572
+ /** Whether the room's `m.room.power_levels` has locked member writes --
1573
+ * the same `events_default >= 100` test `apps/chat-service/src/manage.ts`
1574
+ * uses for `AdminChannel.archived`, read straight off matrix-js-sdk's own
1575
+ * current state the same way `pinnedEventIds` reads pinned events. */
1576
+ function roomArchived(room) {
1577
+ const eventsDefault = room.currentState
1578
+ .getStateEvents(EventType.RoomPowerLevels, '')
1579
+ ?.getContent()?.events_default;
1580
+ return Number(eventsDefault ?? 0) >= 100;
1581
+ }
1388
1582
  function pinnedEventIds(room) {
1389
1583
  const content = room.currentState
1390
1584
  .getStateEvents(EventType.RoomPinnedEvents, '')
@@ -1420,6 +1614,26 @@ export function createChatClient(options) {
1420
1614
  return;
1421
1615
  pinnedKnown.set(room.roomId, pinned.filter((id) => typeof id === 'string'));
1422
1616
  }
1617
+ /** This client's own current draft per room -- not a cache with a
1618
+ * lifetime, kept current two ways: a successful `setDraft`/`clearDraft`
1619
+ * updates it immediately, and `watchForDraft` updates it the moment the
1620
+ * account data lands through `/sync`, this client's own echo or
1621
+ * another device's -- the same two-way pattern `pinnedKnown` keeps for
1622
+ * `m.room.pinned_events`. Absent for a room whose draft this client has
1623
+ * not seen; `getDraft` reads that as `''`. */
1624
+ const drafts = new Map();
1625
+ /** Keeps `drafts` current with whatever this client has actually seen
1626
+ * land -- this client's own echo, or another device's -- registered
1627
+ * directly against `RoomEvent.AccountData` rather than folded into
1628
+ * `onRoomTimelineChanged`: a draft is account data, not a timeline
1629
+ * event, and fires on its own event. */
1630
+ function watchForDraft(event, room) {
1631
+ if (event.getType() !== DRAFT_EVENT_TYPE)
1632
+ return;
1633
+ const text = event.getContent().text;
1634
+ drafts.set(room.roomId, text ?? '');
1635
+ notifyTimeline(room.roomId);
1636
+ }
1423
1637
  /** Queues one read-modify-write of `room`'s `m.room.pinned_events`
1424
1638
  * behind whatever `pinMessage`/`unpinMessage` already have in flight
1425
1639
  * for it, so `await pinMessage(a); await pinMessage(b);` -- or even
@@ -1511,6 +1725,31 @@ export function createChatClient(options) {
1511
1725
  }
1512
1726
  return events;
1513
1727
  }
1728
+ /** See `ChatClient.getDraft`. */
1729
+ function getDraft(roomId) {
1730
+ return drafts.get(roomId) ?? '';
1731
+ }
1732
+ /** See `ChatClient.setDraft`. */
1733
+ async function setDraft(roomId, text) {
1734
+ if (!client)
1735
+ return;
1736
+ const target = client;
1737
+ if (!target.getRoom(roomId))
1738
+ return;
1739
+ drafts.set(roomId, text);
1740
+ await setDraftAccountData(target, roomId, { text });
1741
+ }
1742
+ /** See `ChatClient.clearDraft`. Writes `{}`, the same empty shape
1743
+ * `hideDirectMessage` writes to clear a room tag. */
1744
+ async function clearDraft(roomId) {
1745
+ if (!client)
1746
+ return;
1747
+ const target = client;
1748
+ if (!target.getRoom(roomId))
1749
+ return;
1750
+ drafts.set(roomId, '');
1751
+ await setDraftAccountData(target, roomId, {});
1752
+ }
1514
1753
  function readUpToEventId(roomId) {
1515
1754
  const room = client?.getRoom(roomId);
1516
1755
  const userId = client?.getUserId();
@@ -1533,6 +1772,73 @@ export function createChatClient(options) {
1533
1772
  ? { serverName, mediaId }
1534
1773
  : undefined;
1535
1774
  }
1775
+ /** One call to the thread follow route, refreshing the token once on a
1776
+ * 401 like `loadMedia` does. Resolves with whether the person now
1777
+ * follows the thread; rejects when the service refuses. */
1778
+ async function threadFollowRequest(method, roomId, threadId, body) {
1779
+ if (!client)
1780
+ throw new Error('chat: thread follow called before start()');
1781
+ const target = client;
1782
+ const url = threadFollowUrl(exchangeUrl, roomId, threadId);
1783
+ const request = () => fetch(url, {
1784
+ method,
1785
+ headers: {
1786
+ Authorization: `Bearer ${target.getAccessToken() ?? ''}`,
1787
+ ...(body ? { 'Content-Type': 'application/json' } : {}),
1788
+ },
1789
+ body: body ? JSON.stringify(body) : undefined,
1790
+ redirect: 'error',
1791
+ credentials: 'omit',
1792
+ });
1793
+ let response = await request();
1794
+ if (response.status === 401 && client === target) {
1795
+ await refreshToken();
1796
+ response = await request();
1797
+ }
1798
+ if (!response.ok)
1799
+ throw new Error(`chat: thread follow refused: ${response.status}`);
1800
+ return (await response.json()).following === true;
1801
+ }
1802
+ /** `onThreadFollowChanged` listeners, by `roomId threadId`. */
1803
+ const threadFollowListeners = new Map();
1804
+ function notifyThreadFollow(roomId, threadId, following) {
1805
+ for (const listener of threadFollowListeners.get(`${roomId} ${threadId}`) ?? []) {
1806
+ listener(following);
1807
+ }
1808
+ }
1809
+ /** See `ChatClient.onThreadFollowChanged`. */
1810
+ function onThreadFollowChanged(roomId, threadId, listener) {
1811
+ const key = `${roomId} ${threadId}`;
1812
+ let set = threadFollowListeners.get(key);
1813
+ if (!set) {
1814
+ set = new Set();
1815
+ threadFollowListeners.set(key, set);
1816
+ }
1817
+ set.add(listener);
1818
+ return () => {
1819
+ set.delete(listener);
1820
+ };
1821
+ }
1822
+ /** Posting in a thread follows it, once the post is sent. Best effort: a
1823
+ * failed follow loses nothing the person wrote, and the thread's Follow
1824
+ * control still works. */
1825
+ function autoFollowThread(roomId, threadId) {
1826
+ threadFollowRequest('PUT', roomId, threadId, { auto: true })
1827
+ .then((following) => notifyThreadFollow(roomId, threadId, following))
1828
+ .catch(() => { });
1829
+ }
1830
+ /** See `ChatClient.threadFollowing`. */
1831
+ function threadFollowing(roomId, threadId) {
1832
+ return threadFollowRequest('GET', roomId, threadId);
1833
+ }
1834
+ /** See `ChatClient.followThread`. */
1835
+ async function followThread(roomId, threadId) {
1836
+ await threadFollowRequest('PUT', roomId, threadId);
1837
+ }
1838
+ /** See `ChatClient.unfollowThread`. */
1839
+ async function unfollowThread(roomId, threadId) {
1840
+ await threadFollowRequest('DELETE', roomId, threadId);
1841
+ }
1536
1842
  /** See `ChatClient.canLoadMedia`. */
1537
1843
  function canLoadMedia(mxcUri) {
1538
1844
  return parseMxc(mxcUri) !== undefined;
@@ -1601,46 +1907,147 @@ export function createChatClient(options) {
1601
1907
  isImage: msgtype === MsgType.Image && mimeType.startsWith('image/'),
1602
1908
  };
1603
1909
  }
1910
+ /** Restarts `target` for a recovery, returning the client that is now
1911
+ * live, or `undefined` when `stop()` or another start replaced `target`
1912
+ * meanwhile. Without encryption it is the same client, restarted by the
1913
+ * caller: nothing here is lost, and the rooms keep their pending and
1914
+ * local-echo events. With encryption it is a fresh client, because
1915
+ * matrix-js-sdk cannot bring crypto back on a stopped one --
1916
+ * `initRustCrypto` binds listeners that outlive the freed OlmMachine --
1917
+ * and a rebuild drops those pending events, so only crypto pays for it. */
1918
+ async function restartClient(target, creds, wipeStore) {
1919
+ if (!encryptionEnabled) {
1920
+ target.stopClient();
1921
+ target.setAccessToken(creds.accessToken);
1922
+ if (wipeStore)
1923
+ await target.store.deleteAllData();
1924
+ return client === target ? target : undefined;
1925
+ }
1926
+ return swapClient(target, creds, wipeStore);
1927
+ }
1928
+ /** The old client is disposed before the new one is built, so two
1929
+ * OlmMachines never share one crypto store. A failed build (WASM fetch,
1930
+ * blocked IndexedDB) is retried with a growing delay until it works or
1931
+ * `stop()` lands: nothing else would restart a client whose listeners
1932
+ * are gone. `getCrypto()` answers `undefined` meanwhile. */
1933
+ async function swapClient(target, creds, wipeStore) {
1934
+ disposeClient(target);
1935
+ cryptoClosed = true;
1936
+ let wiped = !wipeStore;
1937
+ let created;
1938
+ for (let delay = REBUILD_RETRY_MS; !created; delay = Math.min(delay * 2, REBUILD_RETRY_MAX_MS)) {
1939
+ if (client !== target)
1940
+ return undefined;
1941
+ try {
1942
+ if (!wiped)
1943
+ await target.store.deleteAllData();
1944
+ wiped = true;
1945
+ created = await buildClient(creds);
1946
+ }
1947
+ catch {
1948
+ await new Promise((resolve) => setTimeout(resolve, delay));
1949
+ }
1950
+ }
1951
+ if (client !== target) {
1952
+ disposeClient(created);
1953
+ return undefined;
1954
+ }
1955
+ if (latestToken)
1956
+ created.setAccessToken(latestToken);
1957
+ client = created;
1958
+ cryptoClosed = false;
1959
+ attachListeners(created);
1960
+ return created;
1961
+ }
1962
+ function disposeClient(target) {
1963
+ target.stopClient();
1964
+ target.removeAllListeners();
1965
+ }
1966
+ async function buildClient(creds) {
1967
+ if (secretStorageUserId !== creds.userId)
1968
+ secretStorageKeys.clear();
1969
+ secretStorageUserId = creds.userId;
1970
+ await purgeStaleChatStores(storeName, creds.baseUrl, creds.userId);
1971
+ const store = createChatStore(storeName, creds.baseUrl, creds.userId);
1972
+ const created = createMatrixClient({
1973
+ ...creds,
1974
+ accessToken: latestToken ?? creds.accessToken,
1975
+ store,
1976
+ cryptoCallbacks: {
1977
+ getSecretStorageKey: async ({ keys }) => {
1978
+ for (const keyId of Object.keys(keys)) {
1979
+ const key = secretStorageKeys.get(keyId);
1980
+ if (key)
1981
+ return [keyId, key];
1982
+ }
1983
+ return null;
1984
+ },
1985
+ cacheSecretStorageKey: (keyId, _keyInfo, key) => {
1986
+ secretStorageKeys.set(keyId, key);
1987
+ },
1988
+ },
1989
+ });
1990
+ if (encryptionEnabled)
1991
+ await initCrypto(created);
1992
+ await store.startup();
1993
+ return created;
1994
+ }
1995
+ function attachListeners(created) {
1996
+ created.on(HttpApiEvent.SessionLoggedOut, onLoggedOut);
1997
+ created.on(ClientEvent.Sync, onSync);
1998
+ created.on(RoomEvent.Timeline, onRoomTimelineChanged);
1999
+ created.on(RoomEvent.LocalEchoUpdated, onRoomTimelineChanged);
2000
+ created.on(RoomEvent.Receipt, onRoomReceipt);
2001
+ created.on(RoomEvent.AccountData, watchForDraft);
2002
+ created.on(UserEvent.Presence, onUserPresence);
2003
+ created.on(RoomMemberEvent.Typing, onRoomMemberTyping);
2004
+ created.on(CryptoEvent.VerificationRequestReceived, onVerificationRequestEvent);
2005
+ }
2006
+ /** `client.js` re-emits `CryptoEvent.VerificationRequestReceived` onto
2007
+ * the `MatrixClient` itself once `initRustCrypto()` has run -- never
2008
+ * fired at all with encryption off, same as every other crypto event.
2009
+ * See `ChatClient.onVerificationRequestReceived` for the public side. */
2010
+ function onVerificationRequestEvent(request) {
2011
+ // One throwing subscriber must not skip the rest. There is no error
2012
+ // callback on this client, so a failure is reported on the console
2013
+ // rather than rethrown into matrix-js-sdk's emitter.
2014
+ for (const listener of [...verificationListeners]) {
2015
+ try {
2016
+ listener(request);
2017
+ }
2018
+ catch (error) {
2019
+ console.error('chat: a onVerificationRequestReceived listener threw', error);
2020
+ }
2021
+ }
2022
+ }
2023
+ function initCrypto(target) {
2024
+ // Per account and device, not `storeName` alone: the Rust store refuses
2025
+ // a different device id, so a fresh sign-in needs its own database.
2026
+ const prefix = cryptoStoreDbPrefix(storeName, target.getUserId() ?? '', target.getDeviceId() ?? '');
2027
+ return target.initRustCrypto({ cryptoDatabasePrefix: prefix });
2028
+ }
1604
2029
  async function start() {
1605
2030
  if (starting)
1606
2031
  return starting;
1607
- starting = (async () => {
2032
+ const attempt = (async () => {
1608
2033
  const body = await performExchange();
1609
- const store = createChatStore(storeName);
1610
- const created = createMatrixClient({
2034
+ // Built before anything touches the outer closure's state (`client`,
2035
+ // the listeners, the refresh timer): a WASM fetch or a blocked
2036
+ // IndexedDB can throw inside `buildClient`, and `created` is still a
2037
+ // local the caller never saw, so a failure needs nothing undone and
2038
+ // `start()` can simply be called again. `buildClient` scopes the crypto
2039
+ // store per account and device and runs `store.startup()` after the
2040
+ // client exists, as `IndexedDBStore` requires (it needs
2041
+ // `setUserCreator`, which the client constructor calls, before it can
2042
+ // replay persisted `m.presence`).
2043
+ const created = await buildClient({
1611
2044
  baseUrl: body.homeserver,
1612
2045
  userId: body.user_id,
1613
2046
  accessToken: body.access_token,
1614
2047
  deviceId: body.device_id,
1615
- store,
1616
2048
  });
1617
- // Loads any previously-persisted sync data before the sync loop can
1618
- // touch the store; skipping it leaves `store.backend` unset, and the
1619
- // store silently degrades to an in-memory one on first access
1620
- // (`IndexedDBStore`'s own `degradable()`), defeating `storeName`.
1621
- //
1622
- // Must run after `createMatrixClient`, not before: matrix-js-sdk's
1623
- // own constructor is what calls `store.setUserCreator` (`client.ts`'s
1624
- // `this._store.setUserCreator(...)`), and `IndexedDBStore.startup`
1625
- // needs that already set before it can replay any `m.presence`
1626
- // persisted from a earlier session -- calling this any earlier
1627
- // throws matrix-js-sdk's own "IndexedDBStore.startup must be called
1628
- // after assigning it to the client, not before!" the moment a store
1629
- // actually has presence to replay. Dormant the whole time presence
1630
- // was off (ticket #7): every store's persisted `userPresenceEvents`
1631
- // was empty, so the guard this trips was never reached. Confirmed
1632
- // live: `test/integration/sync.test.ts`'s restarted-client case is
1633
- // the one that surfaced it, the moment the test stack turned
1634
- // presence on.
1635
- await store.startup();
1636
2049
  client = created;
1637
- created.on(HttpApiEvent.SessionLoggedOut, onLoggedOut);
1638
- created.on(ClientEvent.Sync, onSync);
1639
- created.on(RoomEvent.Timeline, onRoomTimelineChanged);
1640
- created.on(RoomEvent.LocalEchoUpdated, onRoomTimelineChanged);
1641
- created.on(RoomEvent.Receipt, onRoomReceipt);
1642
- created.on(UserEvent.Presence, onUserPresence);
1643
- created.on(RoomMemberEvent.Typing, onRoomMemberTyping);
2050
+ attachListeners(created);
1644
2051
  scheduleRefresh(body.expires_at);
1645
2052
  const outcome = nextSyncOutcome(created);
1646
2053
  // Without `threadSupport`, matrix-js-sdk puts every `m.thread` reply
@@ -1652,7 +2059,14 @@ export function createChatClient(options) {
1652
2059
  reapplyAnnouncedPresence(created);
1653
2060
  await outcome;
1654
2061
  })();
1655
- return starting;
2062
+ starting = attempt;
2063
+ // Undo a failed start, so a later `start()` retries from scratch
2064
+ // instead of returning this same rejection until `stop()`.
2065
+ attempt.catch(() => {
2066
+ if (starting === attempt)
2067
+ stop();
2068
+ });
2069
+ return attempt;
1656
2070
  }
1657
2071
  function stop() {
1658
2072
  for (const pending of uploads.values()) {
@@ -1666,20 +2080,25 @@ export function createChatClient(options) {
1666
2080
  // a future write on either.
1667
2081
  pinnedChain.clear();
1668
2082
  pinnedKnown.clear();
2083
+ drafts.clear();
1669
2084
  typingUsers.clear();
2085
+ secretStorageKeys.clear();
2086
+ secretStorageUserId = undefined;
2087
+ // Whatever this session had fetched may be stale by the time a caller
2088
+ // restarts it -- a status set or cleared while this client was down --
2089
+ // and the cache is cheap to rebuild: `personStatus` refetches on the
2090
+ // next read for anyone still of interest.
2091
+ chatStatusCache.clear();
1670
2092
  starting = undefined;
1671
2093
  clearTimeout(refreshTimer);
1672
2094
  refreshTimer = undefined;
1673
- if (client) {
1674
- client.removeListener(HttpApiEvent.SessionLoggedOut, onLoggedOut);
1675
- client.removeListener(ClientEvent.Sync, onSync);
1676
- client.removeListener(RoomEvent.Timeline, onRoomTimelineChanged);
1677
- client.removeListener(RoomEvent.LocalEchoUpdated, onRoomTimelineChanged);
1678
- client.removeListener(RoomEvent.Receipt, onRoomReceipt);
1679
- client.removeListener(UserEvent.Presence, onUserPresence);
1680
- client.removeListener(RoomMemberEvent.Typing, onRoomMemberTyping);
1681
- client.stopClient();
1682
- }
2095
+ if (client)
2096
+ disposeClient(client);
2097
+ cryptoClosed = false;
2098
+ // A recovery still sleeping in `swapClient` must not make the next
2099
+ // client's recovery wait on it.
2100
+ recovering = undefined;
2101
+ resyncing = undefined;
1683
2102
  client = undefined;
1684
2103
  setStatus('offline');
1685
2104
  }
@@ -1791,6 +2210,83 @@ export function createChatClient(options) {
1791
2210
  presenceListeners.add(listener);
1792
2211
  return () => presenceListeners.delete(listener);
1793
2212
  }
2213
+ /** Whether `value` is shaped enough to be a `ChatStatus` -- checked
2214
+ * before trusting anything read off a profile field nothing in this
2215
+ * package wrote, whether that is a stale shape from an older client or
2216
+ * simply someone else's unrelated custom profile data. */
2217
+ function isChatStatus(value) {
2218
+ if (!value || typeof value !== 'object')
2219
+ return false;
2220
+ const kind = value.kind;
2221
+ return (kind === 'here' ||
2222
+ kind === 'busy' ||
2223
+ kind === 'meeting' ||
2224
+ kind === 'vacation' ||
2225
+ kind === 'sick');
2226
+ }
2227
+ function notifyStatusChanged(userId, next) {
2228
+ chatStatusCache.set(userId, next);
2229
+ const changed = new Map([[userId, next]]);
2230
+ for (const listener of chatStatusListeners)
2231
+ listener(changed);
2232
+ }
2233
+ /** See `ChatClient.status`. `getExtendedProfileProperty` already checks
2234
+ * matrix-js-sdk's own store before reaching the network (populated only
2235
+ * by a sync filter this package does not set up, so in practice this
2236
+ * always makes a real request) -- a 404 and a server with MSC4133 off
2237
+ * both land here as "nothing to show", the same honest `null` either
2238
+ * way. */
2239
+ async function fetchPersonStatus(userId) {
2240
+ const target = client;
2241
+ if (!target)
2242
+ return;
2243
+ try {
2244
+ const raw = await target.getExtendedProfileProperty(userId, STATUS_PROFILE_KEY);
2245
+ notifyStatusChanged(userId, isChatStatus(raw) ? raw : null);
2246
+ }
2247
+ catch {
2248
+ notifyStatusChanged(userId, null);
2249
+ }
2250
+ }
2251
+ /** See `ChatClient.status`. Exported as `status` on the returned client
2252
+ * -- named differently in here only because this closure already has a
2253
+ * `status` variable of its own (`ChatConnectionStatus`, see above). */
2254
+ function personStatus(userId) {
2255
+ if (!chatStatusCache.has(userId)) {
2256
+ chatStatusCache.set(userId, null);
2257
+ void fetchPersonStatus(userId);
2258
+ }
2259
+ return chatStatusCache.get(userId) ?? null;
2260
+ }
2261
+ /** See `ChatClient.setOwnStatus`. The optimistic write is rolled back on
2262
+ * a rejection -- unlike `starRoom`/`muteRoom`, a write here fails for an
2263
+ * entirely ordinary reason in production today (MSC4133 off until
2264
+ * wtfalch/foundry#41), so leaving the cache holding a status that was
2265
+ * never actually saved would be a common bug, not a rare one. */
2266
+ async function setOwnStatus(next) {
2267
+ const target = client;
2268
+ if (!target)
2269
+ return;
2270
+ const userId = target.getUserId();
2271
+ if (!userId)
2272
+ return;
2273
+ const previous = chatStatusCache.get(userId) ?? null;
2274
+ notifyStatusChanged(userId, next);
2275
+ try {
2276
+ if (next === null)
2277
+ await target.deleteExtendedProfileProperty(STATUS_PROFILE_KEY);
2278
+ else
2279
+ await target.setExtendedProfileProperty(STATUS_PROFILE_KEY, next);
2280
+ }
2281
+ catch (error) {
2282
+ notifyStatusChanged(userId, previous);
2283
+ throw error;
2284
+ }
2285
+ }
2286
+ function onStatusChanged(listener) {
2287
+ chatStatusListeners.add(listener);
2288
+ return () => chatStatusListeners.delete(listener);
2289
+ }
1794
2290
  function notifyTyping(roomId) {
1795
2291
  const userIds = [...(typingUsers.get(roomId) ?? [])];
1796
2292
  for (const listener of typingListeners.get(roomId) ?? [])
@@ -1864,6 +2360,11 @@ export function createChatClient(options) {
1864
2360
  // `muteRoom(roomId, false)` alone must not be read as that proof: see
1865
2361
  // `unreliableServerCount`.
1866
2362
  unreliableServerCount.delete(roomId);
2363
+ // A person opening a room they had marked unread has, by definition,
2364
+ // just read it -- a flag a real read left standing would be a flag no
2365
+ // read ever clears.
2366
+ if (isMarkedUnread(room))
2367
+ await markRoomUnread(roomId, false);
1867
2368
  notify();
1868
2369
  }
1869
2370
  /** See `ChatClient.muteRoom`. `setRoomMutePushRule` PUTs (or, unmuting,
@@ -1891,6 +2392,148 @@ export function createChatClient(options) {
1891
2392
  unreliableServerCount.add(roomId);
1892
2393
  notify();
1893
2394
  }
2395
+ /** See `ChatClient.markRoomUnread`. Unlike `muteRoom`'s push rule, room
2396
+ * account data has no refetch-on-write matrix-js-sdk does for us -- it
2397
+ * only lands locally once a `/sync` echoes it back (`RoomEvent.
2398
+ * AccountData`, which nothing here listens for). Waiting for that round
2399
+ * trip would make this the one write in the file that resolves before
2400
+ * its own effect is visible, so the room's local `accountData` is
2401
+ * updated by hand the moment the server has accepted the write --
2402
+ * exactly the event a landed sync would otherwise hand back, which is
2403
+ * why a later, real echo of the same content is harmless. */
2404
+ async function markRoomUnread(roomId, unread) {
2405
+ if (!client)
2406
+ return;
2407
+ const room = client.getRoom(roomId);
2408
+ if (!room)
2409
+ return;
2410
+ await client.setRoomAccountData(roomId, EventType.MarkedUnread, { unread });
2411
+ const userId = client.getUserId();
2412
+ if (userId) {
2413
+ await client.http.authedRequest(Method.Put, `/user/${encodeURIComponent(userId)}/rooms/${encodeURIComponent(roomId)}/account_data/${FAMEDLY_MARKED_UNREAD}`, undefined, { unread });
2414
+ }
2415
+ room.addAccountData([
2416
+ new MatrixEvent({ type: EventType.MarkedUnread, content: { unread } }),
2417
+ new MatrixEvent({ type: FAMEDLY_MARKED_UNREAD, content: { unread } }),
2418
+ ]);
2419
+ notify();
2420
+ }
2421
+ /** See `ChatClient.starRoom`. `setRoomTag`/`deleteRoomTag` are the same
2422
+ * two calls `hideDirectMessage` uses for `HIDDEN_TAG`, and carry the
2423
+ * same lack of local echo: Synapse pushes the tag straight back down
2424
+ * the already-parked `/sync`, and `readRooms()` picks it up from
2425
+ * there a round trip later, not a render later. */
2426
+ async function starRoom(roomId, starred) {
2427
+ if (!client)
2428
+ return;
2429
+ if (!client.getRoom(roomId))
2430
+ return;
2431
+ if (starred)
2432
+ await client.setRoomTag(roomId, FAVOURITE_TAG, {});
2433
+ else
2434
+ await client.deleteRoomTag(roomId, FAVOURITE_TAG);
2435
+ }
2436
+ /** What every key-backup, secret-storage and verification method below
2437
+ * calls first -- the same `cryptoClosed`-aware check `getCrypto()`
2438
+ * answers with, but throwing rather than handing back `undefined`:
2439
+ * unlike a room lookup, there is no sensible no-op result for "enable a
2440
+ * backup" or "verify a device" called before encryption is running.
2441
+ * `method` names the call in the thrown message, the same way every
2442
+ * other `throw new Error('chat: ...')` in this file does. */
2443
+ function requireCrypto(method) {
2444
+ const crypto = cryptoClosed ? undefined : client?.getCrypto();
2445
+ if (!crypto)
2446
+ throw new Error(`chat: ${method} called without encryption running`);
2447
+ return crypto;
2448
+ }
2449
+ // Every one of these is `async` on purpose, even though each body is one
2450
+ // call: `requireCrypto` throws, and only an `async` function turns a
2451
+ // throw into a rejected promise rather than letting it escape the call
2452
+ // synchronously, the same contract every `Promise`-returning method in
2453
+ // this file keeps (`if (!client) throw ...` above is always inside an
2454
+ // `async function`, never a plain one with a `Promise` return type).
2455
+ async function getActiveSessionBackupVersion() {
2456
+ return requireCrypto('getActiveSessionBackupVersion').getActiveSessionBackupVersion();
2457
+ }
2458
+ async function getKeyBackupInfo() {
2459
+ return requireCrypto('getKeyBackupInfo').getKeyBackupInfo();
2460
+ }
2461
+ async function isKeyBackupTrusted(info) {
2462
+ return requireCrypto('isKeyBackupTrusted').isKeyBackupTrusted(info);
2463
+ }
2464
+ async function checkKeyBackupAndEnable() {
2465
+ return requireCrypto('checkKeyBackupAndEnable').checkKeyBackupAndEnable();
2466
+ }
2467
+ async function resetKeyBackup() {
2468
+ return requireCrypto('resetKeyBackup').resetKeyBackup();
2469
+ }
2470
+ async function isSecretStorageReady() {
2471
+ return requireCrypto('isSecretStorageReady').isSecretStorageReady();
2472
+ }
2473
+ async function getSecretStorageStatus() {
2474
+ return requireCrypto('getSecretStorageStatus').getSecretStorageStatus();
2475
+ }
2476
+ async function bootstrapSecretStorage(opts) {
2477
+ return requireCrypto('bootstrapSecretStorage').bootstrapSecretStorage(opts);
2478
+ }
2479
+ async function enterRecoveryKey(encodedRecoveryKey) {
2480
+ const crypto = requireCrypto('enterRecoveryKey');
2481
+ const target = client;
2482
+ if (!target)
2483
+ throw new Error('chat: enterRecoveryKey called before start()');
2484
+ const stored = await target.secretStorage.getKey();
2485
+ if (!stored)
2486
+ throw new Error('chat: enterRecoveryKey called with no secret storage set up');
2487
+ const [keyId, keyInfo] = stored;
2488
+ let key;
2489
+ try {
2490
+ key = decodeRecoveryKey(encodedRecoveryKey);
2491
+ }
2492
+ catch {
2493
+ throw new Error('chat: that is not a valid recovery key');
2494
+ }
2495
+ if (!(await target.secretStorage.checkKey(key, keyInfo))) {
2496
+ throw new Error('chat: that recovery key does not match this account');
2497
+ }
2498
+ secretStorageKeys.set(keyId, key);
2499
+ if (await crypto.getKeyBackupInfo()) {
2500
+ await crypto.loadSessionBackupPrivateKeyFromSecretStorage();
2501
+ await crypto.checkKeyBackupAndEnable();
2502
+ await crypto.restoreKeyBackup();
2503
+ }
2504
+ }
2505
+ async function bootstrapCrossSigning(opts) {
2506
+ return requireCrypto('bootstrapCrossSigning').bootstrapCrossSigning(opts);
2507
+ }
2508
+ async function createRecoveryKeyFromPassphrase(password) {
2509
+ return requireCrypto('createRecoveryKeyFromPassphrase').createRecoveryKeyFromPassphrase(password);
2510
+ }
2511
+ async function getUserVerificationStatus(userId) {
2512
+ return requireCrypto('getUserVerificationStatus').getUserVerificationStatus(userId);
2513
+ }
2514
+ async function getDeviceVerificationStatus(userId, deviceId) {
2515
+ return requireCrypto('getDeviceVerificationStatus').getDeviceVerificationStatus(userId, deviceId);
2516
+ }
2517
+ // Synchronous on purpose: `CryptoApi.getVerificationRequestsToDeviceIn
2518
+ // Progress` itself returns `VerificationRequest[]`, not a promise, so
2519
+ // `requireCrypto`'s throw reaching the caller directly is the correct
2520
+ // behaviour here, not the bug it would be above.
2521
+ function getVerificationRequestsToDeviceInProgress(userId) {
2522
+ return requireCrypto('getVerificationRequestsToDeviceInProgress').getVerificationRequestsToDeviceInProgress(userId);
2523
+ }
2524
+ async function requestOwnUserVerification() {
2525
+ return requireCrypto('requestOwnUserVerification').requestOwnUserVerification();
2526
+ }
2527
+ async function requestDeviceVerification(userId, deviceId) {
2528
+ return requireCrypto('requestDeviceVerification').requestDeviceVerification(userId, deviceId);
2529
+ }
2530
+ async function requestVerificationDM(userId, roomId) {
2531
+ return requireCrypto('requestVerificationDM').requestVerificationDM(userId, roomId);
2532
+ }
2533
+ function onVerificationRequestReceived(listener) {
2534
+ verificationListeners.add(listener);
2535
+ return () => verificationListeners.delete(listener);
2536
+ }
1894
2537
  return {
1895
2538
  start,
1896
2539
  stop,
@@ -1898,10 +2541,31 @@ export function createChatClient(options) {
1898
2541
  totalUnreadCount: () => readRooms().reduce((sum, room) => sum + room.unreadCount, 0),
1899
2542
  markRoomRead,
1900
2543
  muteRoom,
2544
+ markRoomUnread,
2545
+ starRoom,
1901
2546
  connectionStatus: () => status,
1902
2547
  onConnectionStatusChanged,
1903
2548
  onRoomsChanged,
1904
2549
  userId: () => client?.getUserId() ?? null,
2550
+ getCrypto: () => (cryptoClosed ? undefined : client?.getCrypto()),
2551
+ getActiveSessionBackupVersion,
2552
+ getKeyBackupInfo,
2553
+ isKeyBackupTrusted,
2554
+ checkKeyBackupAndEnable,
2555
+ resetKeyBackup,
2556
+ isSecretStorageReady,
2557
+ getSecretStorageStatus,
2558
+ bootstrapSecretStorage,
2559
+ createRecoveryKeyFromPassphrase,
2560
+ enterRecoveryKey,
2561
+ bootstrapCrossSigning,
2562
+ getUserVerificationStatus,
2563
+ getDeviceVerificationStatus,
2564
+ getVerificationRequestsToDeviceInProgress,
2565
+ requestOwnUserVerification,
2566
+ requestDeviceVerification,
2567
+ requestVerificationDM,
2568
+ onVerificationRequestReceived,
1905
2569
  people: readPeople,
1906
2570
  roomMembers,
1907
2571
  readBy,
@@ -1925,12 +2589,22 @@ export function createChatClient(options) {
1925
2589
  retryMessage,
1926
2590
  cancelMessage,
1927
2591
  readUpToEventId,
2592
+ getDraft,
2593
+ setDraft,
2594
+ clearDraft,
2595
+ threadFollowing,
2596
+ followThread,
2597
+ unfollowThread,
2598
+ onThreadFollowChanged,
1928
2599
  canLoadMedia,
1929
2600
  loadMedia,
1930
2601
  sendFile,
1931
2602
  presence,
1932
2603
  announcePresence,
1933
2604
  onPresenceChanged,
2605
+ status: personStatus,
2606
+ setOwnStatus,
2607
+ onStatusChanged,
1934
2608
  sendTyping,
1935
2609
  onTypingChanged,
1936
2610
  };