@wtfalch/chat 0.6.0 → 0.7.1

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,4 +1,5 @@
1
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/index.js';
2
3
  import { exchange } from "./exchange.js";
3
4
  import { toFormattedBody } from "./markdown.js";
4
5
  import { createChatStore, cryptoStoreDbPrefix, purgeStaleChatStores } from "./store.js";
@@ -141,6 +142,28 @@ export function createChatClient(options) {
141
142
  /** True while `swapClient` has disposed `client` and not yet replaced it:
142
143
  * its crypto is closed, so `getCrypto()` must not hand it out. */
143
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;
144
167
  let starting;
145
168
  let refreshTimer;
146
169
  let recovering;
@@ -156,6 +179,11 @@ export function createChatClient(options) {
156
179
  const statusListeners = new Set();
157
180
  const presenceListeners = new Set();
158
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();
159
187
  /** See `ChatClient.status`. A `userId` missing from this map has never
160
188
  * been asked about; `personStatus` uses that (not the value once
161
189
  * present) to decide whether to start a fetch, so a placeholder `null`
@@ -1936,12 +1964,28 @@ export function createChatClient(options) {
1936
1964
  target.removeAllListeners();
1937
1965
  }
1938
1966
  async function buildClient(creds) {
1967
+ if (secretStorageUserId !== creds.userId)
1968
+ secretStorageKeys.clear();
1969
+ secretStorageUserId = creds.userId;
1939
1970
  await purgeStaleChatStores(storeName, creds.baseUrl, creds.userId);
1940
1971
  const store = createChatStore(storeName, creds.baseUrl, creds.userId);
1941
1972
  const created = createMatrixClient({
1942
1973
  ...creds,
1943
1974
  accessToken: latestToken ?? creds.accessToken,
1944
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
+ },
1945
1989
  });
1946
1990
  if (encryptionEnabled)
1947
1991
  await initCrypto(created);
@@ -1957,6 +2001,24 @@ export function createChatClient(options) {
1957
2001
  created.on(RoomEvent.AccountData, watchForDraft);
1958
2002
  created.on(UserEvent.Presence, onUserPresence);
1959
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
+ }
1960
2022
  }
1961
2023
  function initCrypto(target) {
1962
2024
  // Per account and device, not `storeName` alone: the Rust store refuses
@@ -2020,6 +2082,8 @@ export function createChatClient(options) {
2020
2082
  pinnedKnown.clear();
2021
2083
  drafts.clear();
2022
2084
  typingUsers.clear();
2085
+ secretStorageKeys.clear();
2086
+ secretStorageUserId = undefined;
2023
2087
  // Whatever this session had fetched may be stale by the time a caller
2024
2088
  // restarts it -- a status set or cleared while this client was down --
2025
2089
  // and the cache is cheap to rebuild: `personStatus` refetches on the
@@ -2369,6 +2433,107 @@ export function createChatClient(options) {
2369
2433
  else
2370
2434
  await client.deleteRoomTag(roomId, FAVOURITE_TAG);
2371
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
+ }
2372
2537
  return {
2373
2538
  start,
2374
2539
  stop,
@@ -2383,6 +2548,24 @@ export function createChatClient(options) {
2383
2548
  onRoomsChanged,
2384
2549
  userId: () => client?.getUserId() ?? null,
2385
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,
2386
2569
  people: readPeople,
2387
2570
  roomMembers,
2388
2571
  readBy,
@@ -222,6 +222,16 @@ export declare class FakeChatServer {
222
222
  key: string;
223
223
  value: unknown;
224
224
  }>;
225
+ /** Every `PUT .../sendToDevice/...` this server has answered, in order --
226
+ * what a `CryptoApi` verification request (chat#69) sends on its way
227
+ * out. Recorded rather than delivered to another device: the methods
228
+ * this fake exists for (`getVerificationRequestsToDeviceInProgress`)
229
+ * read the sender's own `OlmMachine` state, which only needs the send to
230
+ * succeed, not to be received. */
231
+ readonly sentToDevice: Array<{
232
+ eventType: string;
233
+ body: unknown;
234
+ }>;
225
235
  /** Rooms currently carrying the room-scoped `dont_notify` push rule, for
226
236
  * a test that wants to assert on the server's own state rather than
227
237
  * only through the client's `rooms()`. */
@@ -319,4 +329,17 @@ export declare class FakeChatServer {
319
329
  * `#route`'s own redact endpoint does and as Synapse does -- a redacted
320
330
  * event is still an event. Throws if nothing is parked. */
321
331
  receiveRedaction(roomId: string, targetId: string, sender?: string): string;
332
+ /** The device ids that have uploaded `device_keys` so far. */
333
+ uploadedDeviceIds(): string[];
334
+ /** Delivers to-device events (a verification request, say) to the one
335
+ * client this fake serves, on its next `/sync` -- straight away if a poll
336
+ * is parked. Each event is `{ type, sender, content }`. Only one client
337
+ * can be answered at a time: this fake has a single parked poll, so it
338
+ * cannot route a to-device message from one live client to another, and
339
+ * `sendToDevice` writes stay recorded in `sentToDevice` only. */
340
+ deliverToDevice(events: Array<{
341
+ type: string;
342
+ sender: string;
343
+ content: unknown;
344
+ }>): void;
322
345
  }
@@ -100,6 +100,13 @@ export class FakeChatServer {
100
100
  * server has answered, in order -- what `ChatClient.setOwnStatus`
101
101
  * writes. `value: undefined` records a delete. */
102
102
  extendedProfileWrites = [];
103
+ /** Every `PUT .../sendToDevice/...` this server has answered, in order --
104
+ * what a `CryptoApi` verification request (chat#69) sends on its way
105
+ * out. Recorded rather than delivered to another device: the methods
106
+ * this fake exists for (`getVerificationRequestsToDeviceInProgress`)
107
+ * read the sender's own `OlmMachine` state, which only needs the send to
108
+ * succeed, not to be received. */
109
+ sentToDevice = [];
103
110
  /** Rooms currently carrying the room-scoped `dont_notify` push rule, for
104
111
  * a test that wants to assert on the server's own state rather than
105
112
  * only through the client's `rooms()`. */
@@ -130,6 +137,35 @@ export class FakeChatServer {
130
137
  #parkedWaiters = [];
131
138
  #disposed = false;
132
139
  #direct = {};
140
+ /** User-level account data beyond `m.direct`, keyed by event type -- what
141
+ * `CryptoApi.bootstrapSecretStorage` (chat#68) reads and writes through
142
+ * `setAccountData`/`getAccountDataFromServer`. `m.direct` keeps its own
143
+ * field above rather than moving in here: it has its own typed shape and
144
+ * its own seeding from room members, and nothing about chat#67-69 needs
145
+ * that to change. */
146
+ #globalAccountData = new Map();
147
+ /** Which device a minted token belongs to -- set at exchange time, read
148
+ * by `/keys/upload` so an uploaded device's keys land under its own
149
+ * device id rather than the fake account's single fixed `userId`. Both
150
+ * `CryptoApi.bootstrapCrossSigning`'s own `resetCrossSigning` (chat#68,
151
+ * through `CrossSigningIdentity.resetCrossSigning`'s plain
152
+ * `uploadKeysRequest`) and a running `OlmMachine`'s regular background
153
+ * upload (chat#69's device discovery) go through this one route. */
154
+ #tokenDeviceId = new Map();
155
+ /** Every device's own `device_keys` upload, keyed by device id -- what
156
+ * `/keys/query` (chat#69) answers a querying device with, verbatim.
157
+ * Verbatim matters: the Olm machine verifies the self-signature on
158
+ * whatever `/keys/query` returns, so a fabricated or edited entry would
159
+ * fail that check rather than prove device verification reaches a real
160
+ * device. */
161
+ #deviceKeysByDevice = new Map();
162
+ /** The one server-side key backup this fake can hold at a time, or `null`
163
+ * before `CryptoApi.resetKeyBackup` (chat#67) has ever created one, or
164
+ * again once `disableKeyStorage`/a version delete removes it. Real
165
+ * Synapse allows several historical versions; nothing this package does
166
+ * reads an old one, so this fake only ever keeps the live one. */
167
+ #keyBackup = null;
168
+ #keyBackupSeq = 0;
133
169
  /** Every message event this server has ever had in a room, in order. The
134
170
  * full sync replays it, and `/event` and `/relations` are answered out
135
171
  * of it -- matrix-js-sdk asks for both while it builds a thread. */
@@ -370,9 +406,14 @@ export class FakeChatServer {
370
406
  return `batch-${this.#batchSeq}`;
371
407
  }
372
408
  #accountDataEvents() {
373
- return Object.keys(this.#direct).length
374
- ? [{ type: 'm.direct', content: { ...this.#direct } }]
375
- : [];
409
+ const events = [];
410
+ if (Object.keys(this.#direct).length) {
411
+ events.push({ type: 'm.direct', content: { ...this.#direct } });
412
+ }
413
+ for (const [type, content] of this.#globalAccountData) {
414
+ events.push({ type, content });
415
+ }
416
+ return events;
376
417
  }
377
418
  /** A room's own account data: the tags a test or the client has set on
378
419
  * it (`m.tag`, how `hideDirectMessage` reaches `room.tags`), MSC2867's
@@ -728,9 +769,29 @@ export class FakeChatServer {
728
769
  rooms: { join, invite },
729
770
  account_data: { events: this.#accountDataEvents() },
730
771
  presence: { events: [] },
731
- to_device: { events: [] },
772
+ to_device: { events: this.#drainToDevice() },
732
773
  };
733
774
  }
775
+ /** The device ids that have uploaded `device_keys` so far. */
776
+ uploadedDeviceIds() {
777
+ return [...this.#deviceKeysByDevice.keys()];
778
+ }
779
+ /** To-device events waiting for the next `/sync` this account answers --
780
+ * see `deliverToDevice`. */
781
+ #toDeviceQueue = [];
782
+ #drainToDevice() {
783
+ return this.#toDeviceQueue.splice(0);
784
+ }
785
+ /** Delivers to-device events (a verification request, say) to the one
786
+ * client this fake serves, on its next `/sync` -- straight away if a poll
787
+ * is parked. Each event is `{ type, sender, content }`. Only one client
788
+ * can be answered at a time: this fake has a single parked poll, so it
789
+ * cannot route a to-device message from one live client to another, and
790
+ * `sendToDevice` writes stay recorded in `sentToDevice` only. */
791
+ deliverToDevice(events) {
792
+ this.#toDeviceQueue.push(...events);
793
+ this.#deliverOrQueue({});
794
+ }
734
795
  #deliverParked(join, leave = {}, presenceEvents = []) {
735
796
  if (!this.#pending) {
736
797
  throw new Error('fake chat: addRoom called with no /sync request parked');
@@ -761,7 +822,7 @@ export class FakeChatServer {
761
822
  rooms: { join, leave },
762
823
  account_data: { events: this.#accountDataEvents() },
763
824
  presence: { events: presenceEvents },
764
- to_device: { events: [] },
825
+ to_device: { events: this.#drainToDevice() },
765
826
  }));
766
827
  }
767
828
  /** The fake account's own view of a created direct room: the invitees
@@ -839,6 +900,7 @@ export class FakeChatServer {
839
900
  const token = `fake-matrix-token-${++this.#tokenSeq}`;
840
901
  this.#validTokens.add(token);
841
902
  this.mintedTokens.push(token);
903
+ this.#tokenDeviceId.set(token, deviceId);
842
904
  return Promise.resolve(jsonResponse(200, {
843
905
  homeserver: this.homeserver,
844
906
  user_id: this.userId,
@@ -867,7 +929,7 @@ export class FakeChatServer {
867
929
  rooms: { join: queued.join, leave: queued.leave },
868
930
  account_data: { events: this.#accountDataEvents() },
869
931
  presence: { events: [] },
870
- to_device: { events: [] },
932
+ to_device: { events: this.#drainToDevice() },
871
933
  }));
872
934
  }
873
935
  return new Promise((resolve, reject) => {
@@ -1322,17 +1384,191 @@ export class FakeChatServer {
1322
1384
  this.mediaRequests.push({ path: url.pathname, authorised: false });
1323
1385
  return Promise.resolve(jsonResponse(404, { errcode: 'M_UNRECOGNIZED', error: 'authenticated media only' }));
1324
1386
  }
1325
- const accountData = url.pathname.match(/^\/_matrix\/client\/v3\/user\/([^/]+)\/account_data\/([^/]+)$/);
1326
- if (accountData && this.#authorised(init)) {
1327
- if (accountData[2] === 'm.direct') {
1387
+ // What `CryptoApi.getKeyBackupInfo`/`checkKeyBackupAndEnable`/
1388
+ // `resetKeyBackup` (chat#67) call through `requestKeyBackupVersion`
1389
+ // (matrix-js-sdk's `rust-crypto/backup.js`): that helper treats an
1390
+ // `M_NOT_FOUND` response as "no backup" and anything else as a real
1391
+ // failure, so the catch-all `M_UNRECOGNIZED` 404 at the bottom of this
1392
+ // method is not a substitute for this route existing. This fake keeps
1393
+ // only the one live backup a company's account can have at a time --
1394
+ // nothing in this package ever reads an old version.
1395
+ const keyBackupVersion = url.pathname.match(/^\/_matrix\/client\/v3\/room_keys\/version(?:\/([^/]+))?$/);
1396
+ if (keyBackupVersion && this.#authorised(init)) {
1397
+ const requestedVersion = keyBackupVersion[1]
1398
+ ? decodeURIComponent(keyBackupVersion[1])
1399
+ : undefined;
1400
+ if (init?.method === 'POST') {
1401
+ let body = {};
1328
1402
  try {
1329
- this.#direct = JSON.parse(String(init?.body ?? '{}'));
1403
+ body = JSON.parse(String(init?.body ?? '{}'));
1330
1404
  }
1331
1405
  catch {
1332
- this.#direct = {};
1406
+ // Same tolerance as every other write here.
1407
+ }
1408
+ this.#keyBackupSeq += 1;
1409
+ this.#keyBackup = {
1410
+ algorithm: body.algorithm ?? '',
1411
+ auth_data: body.auth_data ?? {},
1412
+ version: `${this.#keyBackupSeq}`,
1413
+ count: 0,
1414
+ etag: `etag-${this.#keyBackupSeq}`,
1415
+ };
1416
+ return Promise.resolve(jsonResponse(200, { version: this.#keyBackup.version }));
1417
+ }
1418
+ const missing = !this.#keyBackup || (requestedVersion && this.#keyBackup.version !== requestedVersion);
1419
+ if (init?.method === 'DELETE') {
1420
+ if (missing) {
1421
+ return Promise.resolve(jsonResponse(404, { errcode: 'M_NOT_FOUND', error: 'Unknown backup version' }));
1422
+ }
1423
+ this.#keyBackup = null;
1424
+ return Promise.resolve(jsonResponse(200, {}));
1425
+ }
1426
+ if (missing) {
1427
+ return Promise.resolve(jsonResponse(404, { errcode: 'M_NOT_FOUND', error: 'No current backup version' }));
1428
+ }
1429
+ return Promise.resolve(jsonResponse(200, { ...this.#keyBackup }));
1430
+ }
1431
+ // What `CryptoApi.restoreKeyBackup` (chat#68's recovery-key entry)
1432
+ // downloads. This fake stores no session keys, so every download is an
1433
+ // empty backup.
1434
+ if (/^\/_matrix\/client\/v3\/room_keys\/keys(?:\/.*)?$/.test(url.pathname) &&
1435
+ init?.method !== 'PUT' &&
1436
+ this.#authorised(init)) {
1437
+ return Promise.resolve(jsonResponse(200, { rooms: {} }));
1438
+ }
1439
+ // What a running `OlmMachine` uploads once `initRustCrypto()` has
1440
+ // created it, including as part of `CryptoApi.bootstrapCrossSigning`'s
1441
+ // own `resetCrossSigning` (chat#68) -- `CrossSigningIdentity.
1442
+ // resetCrossSigning` sends a plain `uploadKeysRequest` through this
1443
+ // same route alongside its signing-key and signature uploads. Stored
1444
+ // per device id (`#handleExchange` records which token belongs to
1445
+ // which) rather than merely accepted, so `/keys/query` (chat#69) has
1446
+ // something real to answer a querying device with.
1447
+ if (url.pathname === '/_matrix/client/v3/keys/upload' && this.#authorised(init)) {
1448
+ const token = bearerToken(init);
1449
+ const deviceId = token ? this.#tokenDeviceId.get(token) : undefined;
1450
+ let body = {};
1451
+ try {
1452
+ body = JSON.parse(String(init?.body ?? '{}'));
1453
+ }
1454
+ catch {
1455
+ // Same tolerance as every other write here.
1456
+ }
1457
+ if (deviceId && body.device_keys) {
1458
+ this.#deviceKeysByDevice.set(deviceId, body.device_keys);
1459
+ }
1460
+ return Promise.resolve(jsonResponse(200, { one_time_key_counts: {} }));
1461
+ }
1462
+ // What a peer device's own machine queries to find another device --
1463
+ // chat#69's device verification needs a *real* device to resolve
1464
+ // through `CryptoApi.getUserDeviceInfo`/`requestDeviceVerification`,
1465
+ // which a fabricated response cannot satisfy: the querying machine
1466
+ // verifies the self-signature on whatever this returns, so it only
1467
+ // ever echoes a device's own `/keys/upload` body back, verbatim.
1468
+ if (url.pathname === '/_matrix/client/v3/keys/query' && this.#authorised(init)) {
1469
+ let body = {};
1470
+ try {
1471
+ body = JSON.parse(String(init?.body ?? '{}'));
1472
+ }
1473
+ catch {
1474
+ // Same tolerance as every other write here.
1475
+ }
1476
+ const requested = body.device_keys ?? {};
1477
+ const deviceKeys = {};
1478
+ // This fake only ever has one account on it (`this.userId`), so a
1479
+ // query for anybody else comes back empty rather than failing --
1480
+ // nothing this package does queries a second user's devices through
1481
+ // a single-account fake.
1482
+ if (Object.hasOwn(requested, this.userId)) {
1483
+ const wantedDeviceIds = requested[this.userId] ?? [];
1484
+ const devices = {};
1485
+ for (const [deviceId, keys] of this.#deviceKeysByDevice) {
1486
+ if (wantedDeviceIds.length === 0 || wantedDeviceIds.includes(deviceId)) {
1487
+ devices[deviceId] = keys;
1488
+ }
1489
+ }
1490
+ deviceKeys[this.userId] = devices;
1491
+ }
1492
+ return Promise.resolve(jsonResponse(200, { device_keys: deviceKeys, failures: {} }));
1493
+ }
1494
+ // What `CryptoApi.bootstrapSecretStorage` (chat#68) needs cross-signing
1495
+ // bootstrapped through first (`getCrypto()?.bootstrapCrossSigning`):
1496
+ // `getSecretStorageStatus` always checks the three cross-signing
1497
+ // secrets are in secret storage, with no way to turn that check off, so
1498
+ // nothing in this package can reach a "ready" secret storage without
1499
+ // these two succeeding first. Real Synapse protects both with
1500
+ // user-interactive auth; this fake does not model that dance -- a
1501
+ // caller with no `authUploadDeviceSigningKeys` skips straight past it
1502
+ // (`OutgoingRequestProcessor.makeRequestWithUIA`), and this fake simply
1503
+ // accepts whatever reaches it, the same tolerance every other write
1504
+ // here has for a body it does not otherwise validate.
1505
+ if (url.pathname === '/_matrix/client/v3/keys/device_signing/upload' &&
1506
+ this.#authorised(init)) {
1507
+ return Promise.resolve(jsonResponse(200, {}));
1508
+ }
1509
+ if (url.pathname === '/_matrix/client/v3/keys/signatures/upload' && this.#authorised(init)) {
1510
+ return Promise.resolve(jsonResponse(200, { failures: {} }));
1511
+ }
1512
+ // What `CryptoApi.requestDeviceVerification`/`requestOwnUserVerification`
1513
+ // (chat#69) send on their way out. Recorded in `sentToDevice` rather
1514
+ // than delivered to another device: `getVerificationRequestsToDevice
1515
+ // InProgress` reads the sender's own `OlmMachine` state, which only
1516
+ // needs the send to succeed, not to be received by anybody.
1517
+ const sendToDevice = url.pathname.match(/^\/_matrix\/client\/v3\/sendToDevice\/([^/]+)\/([^/]+)$/);
1518
+ if (sendToDevice && this.#authorised(init)) {
1519
+ let body = {};
1520
+ try {
1521
+ body = JSON.parse(String(init?.body ?? '{}'));
1522
+ }
1523
+ catch {
1524
+ // Same tolerance as every other write here.
1525
+ }
1526
+ this.sentToDevice.push({ eventType: decodeURIComponent(sendToDevice[1]), body });
1527
+ return Promise.resolve(jsonResponse(200, {}));
1528
+ }
1529
+ // User-level account data: `m.direct` keeps its own typed field and its
1530
+ // own seeding from room members; `CryptoApi.bootstrapSecretStorage`
1531
+ // (chat#68) and everything it writes (`m.secret_storage.default_key`,
1532
+ // `m.secret_storage.key.*`, the cross-signing and backup secrets) go
1533
+ // through `#globalAccountData` instead. `MatrixClient.setAccountData`
1534
+ // waits for the write's own remote echo on `ClientEvent.AccountData`
1535
+ // before resolving (`client.js`), so a PUT answered `200` is not
1536
+ // enough on its own -- `#deliverOrQueue({})` is what lets the next
1537
+ // `/sync` carry it back, same as `m.direct` already relied on.
1538
+ // `getAccountDataFromServer` falls back to a direct `GET` only before
1539
+ // the first sync completes (`client.js`), which nothing in this
1540
+ // package's crypto bootstrap does -- but a real homeserver still
1541
+ // answers `M_NOT_FOUND` for a type nobody has written, so this fake
1542
+ // does too rather than the `{}` every method here used to return
1543
+ // regardless of type or verb.
1544
+ const accountData = url.pathname.match(/^\/_matrix\/client\/v3\/user\/([^/]+)\/account_data\/([^/]+)$/);
1545
+ if (accountData && this.#authorised(init)) {
1546
+ const type = decodeURIComponent(accountData[2]);
1547
+ if (init?.method === 'GET') {
1548
+ if (type === 'm.direct') {
1549
+ return Object.keys(this.#direct).length
1550
+ ? Promise.resolve(jsonResponse(200, { ...this.#direct }))
1551
+ : Promise.resolve(jsonResponse(404, { errcode: 'M_NOT_FOUND', error: 'Account data not found' }));
1333
1552
  }
1334
- this.#deliverOrQueue({});
1553
+ const stored = this.#globalAccountData.get(type);
1554
+ return stored
1555
+ ? Promise.resolve(jsonResponse(200, stored))
1556
+ : Promise.resolve(jsonResponse(404, { errcode: 'M_NOT_FOUND', error: 'Account data not found' }));
1557
+ }
1558
+ let content = {};
1559
+ try {
1560
+ content = JSON.parse(String(init?.body ?? '{}'));
1561
+ }
1562
+ catch {
1563
+ // Same tolerance as every other write here.
1564
+ }
1565
+ if (type === 'm.direct') {
1566
+ this.#direct = content;
1567
+ }
1568
+ else {
1569
+ this.#globalAccountData.set(type, content);
1335
1570
  }
1571
+ this.#deliverOrQueue({});
1336
1572
  return Promise.resolve(jsonResponse(200, {}));
1337
1573
  }
1338
1574
  // What `client.setRoomAccountData` PUTs -- both keys `markRoomUnread`
@@ -1,4 +1,4 @@
1
- import type { CryptoApi } from 'matrix-js-sdk/lib/crypto-api';
1
+ import type { BackupTrustInfo, BootstrapCrossSigningOpts, CreateSecretStorageOpts, CryptoApi, DeviceVerificationStatus, GeneratedSecretStorageKey, KeyBackupCheck, KeyBackupInfo, SecretStorageStatus, UserVerificationStatus, VerificationRequest } from 'matrix-js-sdk/lib/crypto-api/index.js';
2
2
  /**
3
3
  * The exchange contract, as `apps/chat-service`'s README and
4
4
  * `src/exchange.ts` define it: `POST <exchangeUrl>` with a ZITADEL bearer
@@ -358,6 +358,104 @@ export type ChatClient = {
358
358
  * reach matrix-js-sdk's `CryptoApi` through, rather than each holding
359
359
  * its own closed-over `MatrixClient`. */
360
360
  getCrypto: () => CryptoApi | undefined;
361
+ /** The `version` of the server-side key backup currently being uploaded
362
+ * to, or `null` if automatic backup is off -- `CryptoApi.
363
+ * getActiveSessionBackupVersion` (chat#67). Throws if called before
364
+ * `start()` or without `encryptionEnabled: true`, the same as every
365
+ * method below it. */
366
+ getActiveSessionBackupVersion: () => Promise<string | null>;
367
+ /** The latest backup on the server, as matrix-js-sdk last checked it, or
368
+ * `null` if there is none -- `CryptoApi.getKeyBackupInfo`. Normally a
369
+ * cached answer; fires one request if nothing has checked yet. */
370
+ getKeyBackupInfo: () => Promise<KeyBackupInfo | null>;
371
+ /** Whether `info` -- a `getKeyBackupInfo()` result -- is signed by a
372
+ * trusted device, or matches the decryption key already held --
373
+ * `CryptoApi.isKeyBackupTrusted`. */
374
+ isKeyBackupTrusted: (info: KeyBackupInfo) => Promise<BackupTrustInfo>;
375
+ /** Re-checks the server's backup and starts or stops uploading to it as
376
+ * trust dictates -- `CryptoApi.checkKeyBackupAndEnable`. `null` if the
377
+ * server has no backup at all; otherwise the backup and whether it is
378
+ * trusted. */
379
+ checkKeyBackupAndEnable: () => Promise<KeyBackupCheck | null>;
380
+ /** Creates a new backup version, replacing any existing one, and starts
381
+ * uploading to it -- `CryptoApi.resetKeyBackup`. The generated
382
+ * decryption key is saved to secret storage when one is set up
383
+ * (chat#68's `bootstrapSecretStorage`); otherwise it exists only on
384
+ * this device until a caller does something with it. */
385
+ resetKeyBackup: () => Promise<void>;
386
+ /** Whether secret storage is fully set up: cross-signing's private keys
387
+ * and (if backup is on) the backup decryption key are all stored,
388
+ * encrypted, in account data -- `CryptoApi.isSecretStorageReady`.
389
+ * `false` means `bootstrapSecretStorage` can fix it. */
390
+ isSecretStorageReady: () => Promise<boolean>;
391
+ /** The same answer as `isSecretStorageReady`, broken down by which of
392
+ * the secrets it checked are actually present -- `CryptoApi.
393
+ * getSecretStorageStatus`. */
394
+ getSecretStorageStatus: () => Promise<SecretStorageStatus>;
395
+ /** Sets up secret storage -- `CryptoApi.bootstrapSecretStorage`. `opts.
396
+ * createSecretStorageKey` is how a caller gets the generated recovery
397
+ * key back to show the person; omitted, matrix-js-sdk still creates and
398
+ * stores one, just without handing it to anything that can display it.
399
+ * `opts.setupNewKeyBackup` also resets key backup (see `resetKeyBackup`)
400
+ * as part of the same bootstrap. Secret storage's own readiness check
401
+ * always covers the cross-signing secrets too, so a caller needing
402
+ * `isSecretStorageReady()` to ever answer `true` bootstraps
403
+ * cross-signing first, through `bootstrapCrossSigning` below. */
404
+ bootstrapSecretStorage: (opts: CreateSecretStorageOpts) => Promise<void>;
405
+ /** Unlocks existing secret storage with a recovery key a person typed
406
+ * in on a new device: decodes it, checks it against the account's
407
+ * default secret-storage key, and only then caches it for this session
408
+ * so secret storage can be read, then loads and restores the key backup
409
+ * (if one exists). Rejects without touching storage when the key is
410
+ * malformed or wrong, or when no secret storage exists. Unlike
411
+ * `bootstrapSecretStorage`, never replaces anything. */
412
+ enterRecoveryKey: (encodedRecoveryKey: string) => Promise<void>;
413
+ /** Sets up cross-signing -- `CryptoApi.bootstrapCrossSigning`. Real
414
+ * Synapse protects the device-signing key upload with user-interactive
415
+ * auth, so the app must supply `opts.authUploadDeviceSigningKeys` (it
416
+ * runs the UIA dance with the person's credentials); without it, the
417
+ * upload is refused. The fake server does not model that dance. */
418
+ bootstrapCrossSigning: (opts: BootstrapCrossSigningOpts) => Promise<void>;
419
+ /** Derives a new recovery key from `password`, or generates one at
420
+ * random if omitted -- `CryptoApi.createRecoveryKeyFromPassphrase`. The
421
+ * result's `encodedPrivateKey` is what a person types back in on
422
+ * another device; this does not itself store anything in secret
423
+ * storage -- pass it to `bootstrapSecretStorage` for that. */
424
+ createRecoveryKeyFromPassphrase: (password?: string) => Promise<GeneratedSecretStorageKey>;
425
+ /** The verification status of `userId` -- whether their identity is
426
+ * cross-signing verified, and whether it changed since it was last
427
+ * verified -- `CryptoApi.getUserVerificationStatus`. */
428
+ getUserVerificationStatus: (userId: string) => Promise<UserVerificationStatus>;
429
+ /** The verification status of one of `userId`'s devices, or `null` if
430
+ * the device is unknown or has published no encryption keys --
431
+ * `CryptoApi.getDeviceVerificationStatus`. */
432
+ getDeviceVerificationStatus: (userId: string, deviceId: string) => Promise<DeviceVerificationStatus | null>;
433
+ /** Verification requests sent to specific devices (not through a DM) that
434
+ * are still in progress for `userId` -- `CryptoApi.
435
+ * getVerificationRequestsToDeviceInProgress`. Includes both a request
436
+ * this session started and one it received but has not resolved yet. */
437
+ getVerificationRequestsToDeviceInProgress: (userId: string) => VerificationRequest[];
438
+ /** Asks this account's own other devices to verify the current one --
439
+ * `CryptoApi.requestOwnUserVerification`. Throws if this device has no
440
+ * cross-signing identity yet (`bootstrapSecretStorage`, or
441
+ * `getUserVerificationStatus` on this account's own id, come first). */
442
+ requestOwnUserVerification: () => Promise<VerificationRequest>;
443
+ /** Requests verification of one specific device of `userId`'s --
444
+ * `CryptoApi.requestDeviceVerification`. The device must already be
445
+ * known to this client (a prior `getCrypto()?.getUserDeviceInfo(...)`,
446
+ * or sync having already delivered its keys); throws otherwise. */
447
+ requestDeviceVerification: (userId: string, deviceId: string) => Promise<VerificationRequest>;
448
+ /** Requests verification of `userId` over a DM in `roomId` --
449
+ * `CryptoApi.requestVerificationDM`. Unlike `requestDeviceVerification`,
450
+ * this targets the user's whole identity, not one device, and is how
451
+ * two people verify each other rather than one person's own devices. */
452
+ requestVerificationDM: (userId: string, roomId: string) => Promise<VerificationRequest>;
453
+ /** Called with each verification request this session receives from
454
+ * somebody else -- a UI's cue to prompt the person to accept or decline
455
+ * it. Returns a function that stops listening. Nothing here accepts,
456
+ * declines, or times a request out on its own; the `VerificationRequest`
457
+ * itself carries those methods. */
458
+ onVerificationRequestReceived: (listener: (request: VerificationRequest) => void) => () => void;
361
459
  /** A room's currently-known timeline, or -- given `threadId`, the id of
362
460
  * the message that started one -- that thread's own, root first. Empty,
363
461
  * with `hasMore: true`, for a room `start()` has not caught up to yet.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wtfalch/chat",
3
- "version": "0.6.0",
3
+ "version": "0.7.1",
4
4
  "description": "A Matrix chat client behind the agora's token exchange.",
5
5
  "license": "MIT",
6
6
  "type": "module",