@kodelyth/matrix 2026.5.42 → 2026.6.2

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.
Files changed (205) hide show
  1. package/klaw.plugin.json +891 -3
  2. package/package.json +18 -6
  3. package/CHANGELOG.md +0 -321
  4. package/SPEC-SUPPORT.md +0 -116
  5. package/api.ts +0 -38
  6. package/auth-presence.ts +0 -56
  7. package/channel-plugin-api.ts +0 -3
  8. package/cli-metadata.ts +0 -11
  9. package/contract-api.ts +0 -17
  10. package/doctor-contract-api.ts +0 -1
  11. package/helper-api.ts +0 -3
  12. package/index.ts +0 -55
  13. package/plugin-entry.handlers.runtime.ts +0 -1
  14. package/runtime-api.ts +0 -72
  15. package/runtime-heavy-api.ts +0 -1
  16. package/runtime-setter-api.ts +0 -3
  17. package/secret-contract-api.ts +0 -5
  18. package/setup-entry.ts +0 -17
  19. package/setup-plugin-api.ts +0 -3
  20. package/src/account-selection.ts +0 -223
  21. package/src/actions.ts +0 -346
  22. package/src/approval-auth.ts +0 -25
  23. package/src/approval-handler.runtime.ts +0 -592
  24. package/src/approval-ids.ts +0 -6
  25. package/src/approval-native.ts +0 -345
  26. package/src/approval-reaction-auth.ts +0 -45
  27. package/src/approval-reactions.ts +0 -313
  28. package/src/auth-precedence.ts +0 -61
  29. package/src/channel-account-paths.ts +0 -97
  30. package/src/channel.runtime.ts +0 -17
  31. package/src/channel.setup.ts +0 -48
  32. package/src/channel.ts +0 -667
  33. package/src/cli-metadata.ts +0 -19
  34. package/src/cli.ts +0 -2298
  35. package/src/config-adapter.ts +0 -41
  36. package/src/config-schema.ts +0 -159
  37. package/src/config-ui-hints.ts +0 -56
  38. package/src/directory-live.ts +0 -238
  39. package/src/doctor-contract.ts +0 -287
  40. package/src/doctor.ts +0 -262
  41. package/src/env-vars.ts +0 -92
  42. package/src/exec-approval-resolver.ts +0 -23
  43. package/src/exec-approvals.ts +0 -287
  44. package/src/group-mentions.ts +0 -41
  45. package/src/legacy-crypto-inspector-availability.ts +0 -60
  46. package/src/legacy-crypto.ts +0 -531
  47. package/src/legacy-state.ts +0 -156
  48. package/src/matrix/account-config.ts +0 -175
  49. package/src/matrix/accounts.ts +0 -194
  50. package/src/matrix/actions/client.ts +0 -31
  51. package/src/matrix/actions/devices.ts +0 -34
  52. package/src/matrix/actions/limits.ts +0 -6
  53. package/src/matrix/actions/messages.ts +0 -129
  54. package/src/matrix/actions/pins.ts +0 -63
  55. package/src/matrix/actions/polls.ts +0 -109
  56. package/src/matrix/actions/profile.ts +0 -37
  57. package/src/matrix/actions/reactions.ts +0 -59
  58. package/src/matrix/actions/room.ts +0 -71
  59. package/src/matrix/actions/summary.ts +0 -88
  60. package/src/matrix/actions/types.ts +0 -63
  61. package/src/matrix/actions/verification.ts +0 -589
  62. package/src/matrix/actions.ts +0 -37
  63. package/src/matrix/active-client.ts +0 -26
  64. package/src/matrix/async-lock.ts +0 -18
  65. package/src/matrix/backup-health.ts +0 -124
  66. package/src/matrix/client/config-runtime-api.ts +0 -9
  67. package/src/matrix/client/config-secret-input.runtime.ts +0 -1
  68. package/src/matrix/client/config.ts +0 -853
  69. package/src/matrix/client/create-client.ts +0 -105
  70. package/src/matrix/client/env-auth.ts +0 -95
  71. package/src/matrix/client/file-sync-store.ts +0 -289
  72. package/src/matrix/client/logging.ts +0 -140
  73. package/src/matrix/client/migration-snapshot.runtime.ts +0 -1
  74. package/src/matrix/client/private-network-host.ts +0 -1
  75. package/src/matrix/client/runtime.ts +0 -4
  76. package/src/matrix/client/shared.ts +0 -316
  77. package/src/matrix/client/storage.ts +0 -543
  78. package/src/matrix/client/types.ts +0 -50
  79. package/src/matrix/client/url-validation.ts +0 -73
  80. package/src/matrix/client-bootstrap.ts +0 -173
  81. package/src/matrix/client.ts +0 -23
  82. package/src/matrix/config-paths.ts +0 -31
  83. package/src/matrix/config-update.ts +0 -292
  84. package/src/matrix/credentials-read.ts +0 -208
  85. package/src/matrix/credentials-write.runtime.ts +0 -35
  86. package/src/matrix/credentials.ts +0 -95
  87. package/src/matrix/deps.ts +0 -309
  88. package/src/matrix/device-health.ts +0 -29
  89. package/src/matrix/direct-management.ts +0 -349
  90. package/src/matrix/direct-room.ts +0 -128
  91. package/src/matrix/draft-stream.ts +0 -225
  92. package/src/matrix/encryption-guidance.ts +0 -24
  93. package/src/matrix/errors.ts +0 -21
  94. package/src/matrix/format.ts +0 -426
  95. package/src/matrix/legacy-crypto-inspector.ts +0 -95
  96. package/src/matrix/media-errors.ts +0 -20
  97. package/src/matrix/media-text.ts +0 -162
  98. package/src/matrix/monitor/access-state.ts +0 -145
  99. package/src/matrix/monitor/ack-config.ts +0 -27
  100. package/src/matrix/monitor/allowlist.ts +0 -89
  101. package/src/matrix/monitor/auto-join.ts +0 -86
  102. package/src/matrix/monitor/config.ts +0 -569
  103. package/src/matrix/monitor/context-summary.ts +0 -43
  104. package/src/matrix/monitor/direct.ts +0 -296
  105. package/src/matrix/monitor/events.ts +0 -397
  106. package/src/matrix/monitor/handler.ts +0 -2266
  107. package/src/matrix/monitor/inbound-dedupe.ts +0 -267
  108. package/src/matrix/monitor/index.ts +0 -540
  109. package/src/matrix/monitor/legacy-crypto-restore.ts +0 -139
  110. package/src/matrix/monitor/location.ts +0 -108
  111. package/src/matrix/monitor/media.ts +0 -119
  112. package/src/matrix/monitor/mentions.ts +0 -256
  113. package/src/matrix/monitor/reaction-events.ts +0 -197
  114. package/src/matrix/monitor/recent-invite.ts +0 -30
  115. package/src/matrix/monitor/replies.ts +0 -136
  116. package/src/matrix/monitor/reply-context.ts +0 -92
  117. package/src/matrix/monitor/room-history.ts +0 -301
  118. package/src/matrix/monitor/room-info.ts +0 -126
  119. package/src/matrix/monitor/rooms.ts +0 -52
  120. package/src/matrix/monitor/route.ts +0 -179
  121. package/src/matrix/monitor/runtime-api.ts +0 -28
  122. package/src/matrix/monitor/startup-verification.ts +0 -237
  123. package/src/matrix/monitor/startup.ts +0 -218
  124. package/src/matrix/monitor/status.ts +0 -120
  125. package/src/matrix/monitor/sync-lifecycle.ts +0 -91
  126. package/src/matrix/monitor/task-runner.ts +0 -38
  127. package/src/matrix/monitor/test-events.ts +0 -21
  128. package/src/matrix/monitor/thread-context.ts +0 -108
  129. package/src/matrix/monitor/threads.ts +0 -85
  130. package/src/matrix/monitor/types.ts +0 -30
  131. package/src/matrix/monitor/verification-events.ts +0 -643
  132. package/src/matrix/monitor/verification-utils.ts +0 -46
  133. package/src/matrix/outbound-media-runtime.ts +0 -1
  134. package/src/matrix/poll-summary.ts +0 -110
  135. package/src/matrix/poll-types.ts +0 -429
  136. package/src/matrix/probe.runtime.ts +0 -4
  137. package/src/matrix/probe.ts +0 -97
  138. package/src/matrix/profile.ts +0 -184
  139. package/src/matrix/reaction-common.ts +0 -147
  140. package/src/matrix/sdk/crypto-bootstrap.ts +0 -438
  141. package/src/matrix/sdk/crypto-facade.ts +0 -242
  142. package/src/matrix/sdk/crypto-node.runtime.ts +0 -17
  143. package/src/matrix/sdk/crypto-runtime.ts +0 -14
  144. package/src/matrix/sdk/decrypt-bridge.ts +0 -410
  145. package/src/matrix/sdk/event-helpers.ts +0 -83
  146. package/src/matrix/sdk/http-client.ts +0 -87
  147. package/src/matrix/sdk/idb-persistence-lock.ts +0 -51
  148. package/src/matrix/sdk/idb-persistence.ts +0 -288
  149. package/src/matrix/sdk/logger.ts +0 -108
  150. package/src/matrix/sdk/read-response-with-limit.ts +0 -19
  151. package/src/matrix/sdk/recovery-key-store.ts +0 -453
  152. package/src/matrix/sdk/timeout-abort-signal.ts +0 -1
  153. package/src/matrix/sdk/transport-runtime-api.ts +0 -18
  154. package/src/matrix/sdk/transport.ts +0 -352
  155. package/src/matrix/sdk/types.ts +0 -245
  156. package/src/matrix/sdk/verification-manager.ts +0 -795
  157. package/src/matrix/sdk/verification-status.ts +0 -23
  158. package/src/matrix/sdk.ts +0 -2152
  159. package/src/matrix/send/client.ts +0 -93
  160. package/src/matrix/send/formatting.ts +0 -189
  161. package/src/matrix/send/media.ts +0 -244
  162. package/src/matrix/send/targets.ts +0 -104
  163. package/src/matrix/send/types.ts +0 -131
  164. package/src/matrix/send.ts +0 -660
  165. package/src/matrix/session-store-metadata.ts +0 -108
  166. package/src/matrix/startup-abort.ts +0 -44
  167. package/src/matrix/subagent-hooks.ts +0 -308
  168. package/src/matrix/sync-state.ts +0 -27
  169. package/src/matrix/target-ids.ts +0 -79
  170. package/src/matrix/thread-bindings-shared.ts +0 -206
  171. package/src/matrix/thread-bindings.ts +0 -580
  172. package/src/matrix-migration.runtime.ts +0 -9
  173. package/src/migration-config.ts +0 -243
  174. package/src/migration-snapshot-backup.ts +0 -116
  175. package/src/migration-snapshot.ts +0 -53
  176. package/src/onboarding.ts +0 -775
  177. package/src/outbound.ts +0 -248
  178. package/src/plugin-entry.runtime.js +0 -115
  179. package/src/plugin-entry.runtime.ts +0 -70
  180. package/src/profile-update.ts +0 -71
  181. package/src/record-shared.ts +0 -3
  182. package/src/resolve-targets.ts +0 -175
  183. package/src/resolver.runtime.ts +0 -5
  184. package/src/resolver.ts +0 -21
  185. package/src/runtime-api.ts +0 -106
  186. package/src/runtime.ts +0 -13
  187. package/src/secret-contract.ts +0 -174
  188. package/src/session-route.ts +0 -126
  189. package/src/setup-bootstrap.ts +0 -102
  190. package/src/setup-config.ts +0 -222
  191. package/src/setup-contract.ts +0 -90
  192. package/src/setup-core.ts +0 -146
  193. package/src/setup-dm-policy.ts +0 -15
  194. package/src/setup-surface.ts +0 -4
  195. package/src/startup-maintenance.ts +0 -114
  196. package/src/storage-paths.ts +0 -92
  197. package/src/thread-binding-api.ts +0 -23
  198. package/src/tool-actions.runtime.ts +0 -1
  199. package/src/tool-actions.ts +0 -498
  200. package/src/types.ts +0 -257
  201. package/subagent-hooks-api.ts +0 -31
  202. package/test-api.ts +0 -21
  203. package/thread-binding-api.ts +0 -4
  204. package/thread-bindings-runtime.ts +0 -4
  205. package/tsconfig.json +0 -16
@@ -1,438 +0,0 @@
1
- import { setTimeout as sleep } from "node:timers/promises";
2
- import { CryptoEvent } from "matrix-js-sdk/lib/crypto-api/CryptoEvent.js";
3
- import type { MatrixDecryptBridge } from "./decrypt-bridge.js";
4
- import { LogService } from "./logger.js";
5
- import type { MatrixRecoveryKeyStore } from "./recovery-key-store.js";
6
- import { isRepairableSecretStorageAccessError } from "./recovery-key-store.js";
7
- import type {
8
- MatrixAuthDict,
9
- MatrixCryptoBootstrapApi,
10
- MatrixRawEvent,
11
- MatrixUiAuthCallback,
12
- } from "./types.js";
13
- import type {
14
- MatrixVerificationManager,
15
- MatrixVerificationRequestLike,
16
- } from "./verification-manager.js";
17
- import { isMatrixDeviceOwnerVerified } from "./verification-status.js";
18
-
19
- export type MatrixCryptoBootstrapperDeps<TRawEvent extends MatrixRawEvent> = {
20
- getUserId: () => Promise<string>;
21
- getPassword?: () => string | undefined;
22
- getDeviceId: () => string | null | undefined;
23
- verificationManager: MatrixVerificationManager;
24
- recoveryKeyStore: MatrixRecoveryKeyStore;
25
- decryptBridge: Pick<MatrixDecryptBridge<TRawEvent>, "bindCryptoRetrySignals">;
26
- };
27
-
28
- export type MatrixCryptoBootstrapOptions = {
29
- forceResetCrossSigning?: boolean;
30
- allowAutomaticCrossSigningReset?: boolean;
31
- allowSecretStorageRecreateWithoutRecoveryKey?: boolean;
32
- strict?: boolean;
33
- };
34
-
35
- export type MatrixCryptoBootstrapResult = {
36
- crossSigningReady: boolean;
37
- crossSigningPublished: boolean;
38
- ownDeviceVerified: boolean | null;
39
- };
40
-
41
- const CROSS_SIGNING_PUBLICATION_WAIT_MS = 5_000;
42
-
43
- export class MatrixCryptoBootstrapper<TRawEvent extends MatrixRawEvent> {
44
- private verificationHandlerRegistered = false;
45
-
46
- constructor(private readonly deps: MatrixCryptoBootstrapperDeps<TRawEvent>) {}
47
-
48
- async bootstrap(
49
- crypto: MatrixCryptoBootstrapApi,
50
- options: MatrixCryptoBootstrapOptions = {},
51
- ): Promise<MatrixCryptoBootstrapResult> {
52
- const strict = options.strict === true;
53
- const deferSecretStorageBootstrapUntilAfterCrossSigning =
54
- options.forceResetCrossSigning === true;
55
- // Register verification listeners before expensive bootstrap work so incoming requests
56
- // are not missed during startup.
57
- this.registerVerificationRequestHandler(crypto);
58
- if (!deferSecretStorageBootstrapUntilAfterCrossSigning) {
59
- await this.bootstrapSecretStorage(crypto, {
60
- strict,
61
- allowSecretStorageRecreateWithoutRecoveryKey:
62
- options.allowSecretStorageRecreateWithoutRecoveryKey === true,
63
- });
64
- }
65
- let crossSigning = await this.bootstrapCrossSigning(crypto, {
66
- forceResetCrossSigning: options.forceResetCrossSigning === true,
67
- allowAutomaticCrossSigningReset: options.allowAutomaticCrossSigningReset !== false,
68
- allowSecretStorageRecreateWithoutRecoveryKey:
69
- options.allowSecretStorageRecreateWithoutRecoveryKey === true,
70
- strict,
71
- });
72
- // Forced repair may need password UIA to upload new cross-signing keys. Delay any
73
- // secret-storage repair/recreation until after that step succeeds so passwordless bots do
74
- // not partially mutate SSSS on homeservers that require password-based UIA.
75
- await this.bootstrapSecretStorage(crypto, {
76
- strict,
77
- allowSecretStorageRecreateWithoutRecoveryKey:
78
- options.allowSecretStorageRecreateWithoutRecoveryKey === true,
79
- });
80
- if (deferSecretStorageBootstrapUntilAfterCrossSigning) {
81
- crossSigning = await this.bootstrapCrossSigning(crypto, {
82
- forceResetCrossSigning: false,
83
- allowAutomaticCrossSigningReset: false,
84
- allowSecretStorageRecreateWithoutRecoveryKey:
85
- options.allowSecretStorageRecreateWithoutRecoveryKey === true,
86
- strict,
87
- });
88
- }
89
- const ownDeviceVerified = await this.ensureOwnDeviceTrust(crypto, {
90
- strict,
91
- });
92
- return {
93
- crossSigningReady: crossSigning.ready,
94
- crossSigningPublished: crossSigning.published,
95
- ownDeviceVerified,
96
- };
97
- }
98
-
99
- private createSigningKeysUiAuthCallback(params: {
100
- userId: string;
101
- password?: string;
102
- }): MatrixUiAuthCallback {
103
- return async <T>(makeRequest: (authData: MatrixAuthDict | null) => Promise<T>): Promise<T> => {
104
- try {
105
- return await makeRequest(null);
106
- } catch {
107
- // Some homeservers require an explicit dummy UIA stage even when no user interaction is needed.
108
- try {
109
- return await makeRequest({ type: "m.login.dummy" });
110
- } catch {
111
- if (!params.password?.trim()) {
112
- throw new Error(
113
- "Matrix cross-signing key upload requires UIA; provide matrix.password for m.login.password fallback",
114
- );
115
- }
116
- return await makeRequest({
117
- type: "m.login.password",
118
- identifier: { type: "m.id.user", user: params.userId },
119
- password: params.password,
120
- });
121
- }
122
- }
123
- };
124
- }
125
-
126
- private async bootstrapCrossSigning(
127
- crypto: MatrixCryptoBootstrapApi,
128
- options: {
129
- forceResetCrossSigning: boolean;
130
- allowAutomaticCrossSigningReset: boolean;
131
- allowSecretStorageRecreateWithoutRecoveryKey: boolean;
132
- strict: boolean;
133
- },
134
- ): Promise<{ ready: boolean; published: boolean }> {
135
- const userId = await this.deps.getUserId();
136
- const authUploadDeviceSigningKeys = this.createSigningKeysUiAuthCallback({
137
- userId,
138
- password: this.deps.getPassword?.(),
139
- });
140
- const hasPublishedCrossSigningKeys = async (): Promise<boolean> => {
141
- if (typeof crypto.userHasCrossSigningKeys !== "function") {
142
- return true;
143
- }
144
- try {
145
- return await crypto.userHasCrossSigningKeys(userId, true);
146
- } catch {
147
- return false;
148
- }
149
- };
150
- const refreshPublishedCrossSigningKeys = async (): Promise<void> => {
151
- if (typeof crypto.userHasCrossSigningKeys !== "function") {
152
- return;
153
- }
154
- try {
155
- await crypto.userHasCrossSigningKeys(userId, true);
156
- } catch {
157
- // The normal bootstrap flow below handles missing or unavailable keys.
158
- }
159
- };
160
- const isCrossSigningReady = async (): Promise<boolean> => {
161
- if (typeof crypto.isCrossSigningReady !== "function") {
162
- return true;
163
- }
164
- try {
165
- return await crypto.isCrossSigningReady();
166
- } catch {
167
- return false;
168
- }
169
- };
170
-
171
- const finalize = async (): Promise<{ ready: boolean; published: boolean }> => {
172
- const ready = await isCrossSigningReady();
173
- const published = ready
174
- ? await waitForPublishedCrossSigningKeys()
175
- : await hasPublishedCrossSigningKeys();
176
- if (ready && published) {
177
- LogService.info("MatrixClientLite", "Cross-signing bootstrap complete");
178
- return { ready, published };
179
- }
180
- const message = "Cross-signing bootstrap finished but server keys are still not published";
181
- LogService.warn("MatrixClientLite", message);
182
- if (options.strict) {
183
- throw new Error(message);
184
- }
185
- return { ready, published };
186
- };
187
-
188
- const waitForPublishedCrossSigningKeys = async (): Promise<boolean> => {
189
- const startedAt = Date.now();
190
- do {
191
- if (await hasPublishedCrossSigningKeys()) {
192
- return true;
193
- }
194
- await sleep(250);
195
- } while (Date.now() - startedAt < CROSS_SIGNING_PUBLICATION_WAIT_MS);
196
- return false;
197
- };
198
-
199
- if (options.forceResetCrossSigning) {
200
- const resetCrossSigning = async (): Promise<void> => {
201
- await crypto.bootstrapCrossSigning({
202
- setupNewCrossSigning: true,
203
- authUploadDeviceSigningKeys,
204
- });
205
- };
206
- try {
207
- await resetCrossSigning();
208
- await this.trustFreshOwnIdentity(crypto);
209
- } catch (err) {
210
- const shouldRepairSecretStorage =
211
- options.allowSecretStorageRecreateWithoutRecoveryKey &&
212
- isRepairableSecretStorageAccessError(err);
213
- if (shouldRepairSecretStorage) {
214
- LogService.warn(
215
- "MatrixClientLite",
216
- "Forced cross-signing reset could not unlock secret storage; recreating secret storage and retrying.",
217
- );
218
- try {
219
- await this.deps.recoveryKeyStore.bootstrapSecretStorageWithRecoveryKey(crypto, {
220
- allowSecretStorageRecreateWithoutRecoveryKey: true,
221
- forceNewSecretStorage: true,
222
- });
223
- await resetCrossSigning();
224
- await this.trustFreshOwnIdentity(crypto);
225
- } catch (repairErr) {
226
- LogService.warn("MatrixClientLite", "Forced cross-signing reset failed:", repairErr);
227
- if (options.strict) {
228
- throw repairErr instanceof Error ? repairErr : new Error(String(repairErr));
229
- }
230
- return { ready: false, published: false };
231
- }
232
- return await finalize();
233
- }
234
- LogService.warn("MatrixClientLite", "Forced cross-signing reset failed:", err);
235
- if (options.strict) {
236
- throw err instanceof Error ? err : new Error(String(err));
237
- }
238
- return { ready: false, published: false };
239
- }
240
- return await finalize();
241
- }
242
-
243
- // First pass: preserve existing cross-signing identity and ensure public keys are uploaded.
244
- try {
245
- await refreshPublishedCrossSigningKeys();
246
- await crypto.bootstrapCrossSigning({
247
- authUploadDeviceSigningKeys,
248
- });
249
- } catch (err) {
250
- const shouldRepairSecretStorage =
251
- options.allowSecretStorageRecreateWithoutRecoveryKey &&
252
- isRepairableSecretStorageAccessError(err);
253
- if (shouldRepairSecretStorage) {
254
- LogService.warn(
255
- "MatrixClientLite",
256
- "Cross-signing bootstrap could not unlock secret storage; recreating secret storage during explicit bootstrap and retrying.",
257
- );
258
- await this.deps.recoveryKeyStore.bootstrapSecretStorageWithRecoveryKey(crypto, {
259
- allowSecretStorageRecreateWithoutRecoveryKey: true,
260
- forceNewSecretStorage: true,
261
- });
262
- await crypto.bootstrapCrossSigning({
263
- authUploadDeviceSigningKeys,
264
- });
265
- } else if (!options.allowAutomaticCrossSigningReset) {
266
- LogService.warn(
267
- "MatrixClientLite",
268
- "Initial cross-signing bootstrap failed and automatic reset is disabled:",
269
- err,
270
- );
271
- return { ready: false, published: false };
272
- } else {
273
- LogService.warn(
274
- "MatrixClientLite",
275
- "Initial cross-signing bootstrap failed, trying reset:",
276
- err,
277
- );
278
- try {
279
- await crypto.bootstrapCrossSigning({
280
- setupNewCrossSigning: true,
281
- authUploadDeviceSigningKeys,
282
- });
283
- } catch (resetErr) {
284
- LogService.warn("MatrixClientLite", "Failed to bootstrap cross-signing:", resetErr);
285
- if (options.strict) {
286
- throw resetErr instanceof Error ? resetErr : new Error(String(resetErr));
287
- }
288
- return { ready: false, published: false };
289
- }
290
- }
291
- }
292
-
293
- const firstPassReady = await isCrossSigningReady();
294
- const firstPassPublished = await hasPublishedCrossSigningKeys();
295
- if (firstPassReady && firstPassPublished) {
296
- LogService.info("MatrixClientLite", "Cross-signing bootstrap complete");
297
- return { ready: true, published: true };
298
- }
299
-
300
- if (!options.allowAutomaticCrossSigningReset) {
301
- return { ready: firstPassReady, published: firstPassPublished };
302
- }
303
-
304
- // Fallback: recover from broken local/server state by creating a fresh identity.
305
- try {
306
- await crypto.bootstrapCrossSigning({
307
- setupNewCrossSigning: true,
308
- authUploadDeviceSigningKeys,
309
- });
310
- await this.trustFreshOwnIdentity(crypto);
311
- } catch (err) {
312
- LogService.warn("MatrixClientLite", "Fallback cross-signing bootstrap failed:", err);
313
- if (options.strict) {
314
- throw err instanceof Error ? err : new Error(String(err));
315
- }
316
- return { ready: false, published: false };
317
- }
318
-
319
- return await finalize();
320
- }
321
-
322
- private async trustFreshOwnIdentity(crypto: MatrixCryptoBootstrapApi): Promise<void> {
323
- const ownIdentity =
324
- typeof crypto.getOwnIdentity === "function"
325
- ? await crypto.getOwnIdentity().catch(() => undefined)
326
- : undefined;
327
- if (!ownIdentity) {
328
- return;
329
- }
330
-
331
- try {
332
- if (typeof ownIdentity.isVerified === "function" && ownIdentity.isVerified()) {
333
- return;
334
- }
335
- await ownIdentity.verify?.();
336
- } finally {
337
- ownIdentity.free?.();
338
- }
339
- }
340
-
341
- private async bootstrapSecretStorage(
342
- crypto: MatrixCryptoBootstrapApi,
343
- options: {
344
- strict: boolean;
345
- allowSecretStorageRecreateWithoutRecoveryKey: boolean;
346
- },
347
- ): Promise<void> {
348
- try {
349
- await this.deps.recoveryKeyStore.bootstrapSecretStorageWithRecoveryKey(crypto, {
350
- allowSecretStorageRecreateWithoutRecoveryKey:
351
- options.allowSecretStorageRecreateWithoutRecoveryKey,
352
- });
353
- LogService.info("MatrixClientLite", "Secret storage bootstrap complete");
354
- } catch (err) {
355
- LogService.warn("MatrixClientLite", "Failed to bootstrap secret storage:", err);
356
- if (options.strict) {
357
- throw err instanceof Error ? err : new Error(String(err));
358
- }
359
- }
360
- }
361
-
362
- private registerVerificationRequestHandler(crypto: MatrixCryptoBootstrapApi): void {
363
- if (this.verificationHandlerRegistered) {
364
- return;
365
- }
366
- this.verificationHandlerRegistered = true;
367
-
368
- // Track incoming requests; verification lifecycle decisions live in the
369
- // verification manager so acceptance/start/dedupe share one code path.
370
- // Remote-user verifications are only auto-accepted. The human-operated
371
- // client must explicitly choose "Verify by emoji" so we do not race a
372
- // second SAS start from the bot side and end up with mismatched keys.
373
- crypto.on(CryptoEvent.VerificationRequestReceived, async (request) => {
374
- const verificationRequest = request as MatrixVerificationRequestLike;
375
- try {
376
- this.deps.verificationManager.trackVerificationRequest(verificationRequest);
377
- } catch (err) {
378
- LogService.warn(
379
- "MatrixClientLite",
380
- `Failed to track verification request from ${verificationRequest.otherUserId}:`,
381
- err,
382
- );
383
- }
384
- });
385
-
386
- this.deps.decryptBridge.bindCryptoRetrySignals(crypto);
387
- LogService.info("MatrixClientLite", "Verification request handler registered");
388
- }
389
-
390
- private async ensureOwnDeviceTrust(
391
- crypto: MatrixCryptoBootstrapApi,
392
- options: {
393
- strict: boolean;
394
- },
395
- ): Promise<boolean | null> {
396
- const deviceId = this.deps.getDeviceId()?.trim();
397
- if (!deviceId) {
398
- return null;
399
- }
400
- const userId = await this.deps.getUserId();
401
-
402
- const deviceStatus =
403
- typeof crypto.getDeviceVerificationStatus === "function"
404
- ? await crypto.getDeviceVerificationStatus(userId, deviceId).catch(() => null)
405
- : null;
406
- const alreadyVerified = isMatrixDeviceOwnerVerified(deviceStatus);
407
-
408
- if (alreadyVerified) {
409
- return true;
410
- }
411
-
412
- if (typeof crypto.setDeviceVerified === "function") {
413
- await crypto.setDeviceVerified(userId, deviceId, true);
414
- }
415
-
416
- if (typeof crypto.crossSignDevice === "function") {
417
- const crossSigningReady =
418
- typeof crypto.isCrossSigningReady === "function"
419
- ? await crypto.isCrossSigningReady()
420
- : true;
421
- if (crossSigningReady) {
422
- await crypto.crossSignDevice(deviceId);
423
- }
424
- }
425
-
426
- const refreshedStatus =
427
- typeof crypto.getDeviceVerificationStatus === "function"
428
- ? await crypto.getDeviceVerificationStatus(userId, deviceId).catch(() => null)
429
- : null;
430
- const verified = isMatrixDeviceOwnerVerified(refreshedStatus);
431
- if (!verified && options.strict) {
432
- throw new Error(
433
- `Matrix own device ${deviceId} does not have full Matrix identity trust after bootstrap`,
434
- );
435
- }
436
- return verified;
437
- }
438
- }
@@ -1,242 +0,0 @@
1
- import { ensureMatrixCryptoRuntime } from "../deps.js";
2
- import type { MatrixRecoveryKeyStore } from "./recovery-key-store.js";
3
- import type { EncryptedFile } from "./types.js";
4
- import type {
5
- MatrixVerificationCryptoApi,
6
- MatrixVerificationManager,
7
- MatrixVerificationMethod,
8
- MatrixVerificationSummary,
9
- } from "./verification-manager.js";
10
-
11
- type MatrixCryptoFacadeClient = {
12
- getRoom: (roomId: string) => { hasEncryptionStateEvent: () => boolean } | null;
13
- getCrypto: () => unknown;
14
- getUserId: () => string | null;
15
- };
16
-
17
- export type MatrixCryptoFacade = {
18
- prepare: (joinedRooms: string[]) => Promise<void>;
19
- updateSyncData: (
20
- toDeviceMessages: unknown,
21
- otkCounts: unknown,
22
- unusedFallbackKeyAlgs: unknown,
23
- changedDeviceLists: unknown,
24
- leftDeviceLists: unknown,
25
- ) => Promise<void>;
26
- isRoomEncrypted: (roomId: string) => Promise<boolean>;
27
- requestOwnUserVerification: () => Promise<MatrixVerificationSummary | null>;
28
- encryptMedia: (buffer: Buffer) => Promise<{ buffer: Buffer; file: Omit<EncryptedFile, "url"> }>;
29
- decryptMedia: (
30
- file: EncryptedFile,
31
- opts?: { maxBytes?: number; readIdleTimeoutMs?: number },
32
- ) => Promise<Buffer>;
33
- getRecoveryKey: () => Promise<{
34
- encodedPrivateKey?: string;
35
- keyId?: string | null;
36
- createdAt?: string;
37
- } | null>;
38
- listVerifications: () => Promise<MatrixVerificationSummary[]>;
39
- ensureVerificationDmTracked: (params: {
40
- roomId: string;
41
- userId: string;
42
- }) => Promise<MatrixVerificationSummary | null>;
43
- requestVerification: (params: {
44
- ownUser?: boolean;
45
- userId?: string;
46
- deviceId?: string;
47
- roomId?: string;
48
- }) => Promise<MatrixVerificationSummary>;
49
- acceptVerification: (id: string) => Promise<MatrixVerificationSummary>;
50
- cancelVerification: (
51
- id: string,
52
- params?: { reason?: string; code?: string },
53
- ) => Promise<MatrixVerificationSummary>;
54
- startVerification: (
55
- id: string,
56
- method?: MatrixVerificationMethod,
57
- ) => Promise<MatrixVerificationSummary>;
58
- generateVerificationQr: (id: string) => Promise<{ qrDataBase64: string }>;
59
- scanVerificationQr: (id: string, qrDataBase64: string) => Promise<MatrixVerificationSummary>;
60
- confirmVerificationSas: (id: string) => Promise<MatrixVerificationSummary>;
61
- mismatchVerificationSas: (id: string) => Promise<MatrixVerificationSummary>;
62
- confirmVerificationReciprocateQr: (id: string) => Promise<MatrixVerificationSummary>;
63
- getVerificationSas: (
64
- id: string,
65
- ) => Promise<{ decimal?: [number, number, number]; emoji?: Array<[string, string]> }>;
66
- };
67
-
68
- type MatrixCryptoNodeRuntime = typeof import("./crypto-node.runtime.js");
69
- let matrixCryptoNodeRuntimePromise: Promise<MatrixCryptoNodeRuntime> | null = null;
70
-
71
- async function loadMatrixCryptoNodeRuntime(): Promise<MatrixCryptoNodeRuntime> {
72
- // Keep the native crypto package out of the main CLI startup graph.
73
- matrixCryptoNodeRuntimePromise ??= import("./crypto-node.runtime.js").catch((error: unknown) => {
74
- matrixCryptoNodeRuntimePromise = null;
75
- throw error;
76
- });
77
- return await matrixCryptoNodeRuntimePromise;
78
- }
79
-
80
- async function loadMatrixCryptoNodeBindings() {
81
- await ensureMatrixCryptoRuntime();
82
- const runtime = await loadMatrixCryptoNodeRuntime();
83
- return runtime.loadMatrixCryptoNodeBindings();
84
- }
85
-
86
- function trackInProgressToDeviceVerifications(deps: {
87
- client: MatrixCryptoFacadeClient;
88
- verificationManager: MatrixVerificationManager;
89
- }) {
90
- const crypto = deps.client.getCrypto() as MatrixVerificationCryptoApi | undefined;
91
- const userId = deps.client.getUserId();
92
- if (!userId || typeof crypto?.getVerificationRequestsToDeviceInProgress !== "function") {
93
- return;
94
- }
95
- for (const request of crypto.getVerificationRequestsToDeviceInProgress(userId)) {
96
- deps.verificationManager.trackVerificationRequest(request);
97
- }
98
- }
99
-
100
- export function createMatrixCryptoFacade(deps: {
101
- client: MatrixCryptoFacadeClient;
102
- verificationManager: MatrixVerificationManager;
103
- recoveryKeyStore: MatrixRecoveryKeyStore;
104
- getRoomStateEvent: (
105
- roomId: string,
106
- eventType: string,
107
- stateKey?: string,
108
- ) => Promise<Record<string, unknown>>;
109
- downloadContent: (
110
- mxcUrl: string,
111
- opts?: { maxBytes?: number; readIdleTimeoutMs?: number },
112
- ) => Promise<Buffer>;
113
- }): MatrixCryptoFacade {
114
- return {
115
- prepare: async (_joinedRooms: string[]) => {
116
- // matrix-js-sdk performs crypto prep during startup; no extra work required here.
117
- },
118
- updateSyncData: async (
119
- _toDeviceMessages: unknown,
120
- _otkCounts: unknown,
121
- _unusedFallbackKeyAlgs: unknown,
122
- _changedDeviceLists: unknown,
123
- _leftDeviceLists: unknown,
124
- ) => {
125
- // compatibility no-op
126
- },
127
- isRoomEncrypted: async (roomId: string): Promise<boolean> => {
128
- const room = deps.client.getRoom(roomId);
129
- if (room?.hasEncryptionStateEvent()) {
130
- return true;
131
- }
132
- try {
133
- const event = await deps.getRoomStateEvent(roomId, "m.room.encryption", "");
134
- return typeof event.algorithm === "string" && event.algorithm.length > 0;
135
- } catch {
136
- return false;
137
- }
138
- },
139
- requestOwnUserVerification: async () => {
140
- const crypto = deps.client.getCrypto() as MatrixVerificationCryptoApi | undefined;
141
- return await deps.verificationManager.requestOwnUserVerification(crypto);
142
- },
143
- encryptMedia: async (
144
- buffer: Buffer,
145
- ): Promise<{ buffer: Buffer; file: Omit<EncryptedFile, "url"> }> => {
146
- const { Attachment } = await loadMatrixCryptoNodeBindings();
147
- const encrypted = Attachment.encrypt(new Uint8Array(buffer));
148
- const mediaInfoJson = encrypted.mediaEncryptionInfo;
149
- if (!mediaInfoJson) {
150
- throw new Error("Matrix media encryption failed: missing media encryption info");
151
- }
152
- const parsed = JSON.parse(mediaInfoJson) as EncryptedFile;
153
- return {
154
- buffer: Buffer.from(encrypted.encryptedData),
155
- file: {
156
- key: parsed.key,
157
- iv: parsed.iv,
158
- hashes: parsed.hashes,
159
- v: parsed.v,
160
- },
161
- };
162
- },
163
- decryptMedia: async (
164
- file: EncryptedFile,
165
- opts?: { maxBytes?: number; readIdleTimeoutMs?: number },
166
- ): Promise<Buffer> => {
167
- const { Attachment, EncryptedAttachment } = await loadMatrixCryptoNodeBindings();
168
- const encrypted = await deps.downloadContent(file.url, opts);
169
- const metadata: EncryptedFile = {
170
- url: file.url,
171
- key: file.key,
172
- iv: file.iv,
173
- hashes: file.hashes,
174
- v: file.v,
175
- };
176
- const attachment = new EncryptedAttachment(
177
- new Uint8Array(encrypted),
178
- JSON.stringify(metadata),
179
- );
180
- const decrypted = Attachment.decrypt(attachment);
181
- return Buffer.from(decrypted);
182
- },
183
- getRecoveryKey: async () => {
184
- return deps.recoveryKeyStore.getRecoveryKeySummary();
185
- },
186
- listVerifications: async () => {
187
- trackInProgressToDeviceVerifications(deps);
188
- return deps.verificationManager.listVerifications();
189
- },
190
- ensureVerificationDmTracked: async ({ roomId, userId }) => {
191
- const crypto = deps.client.getCrypto() as MatrixVerificationCryptoApi | undefined;
192
- const request =
193
- typeof crypto?.findVerificationRequestDMInProgress === "function"
194
- ? crypto.findVerificationRequestDMInProgress(roomId, userId)
195
- : undefined;
196
- if (!request) {
197
- return null;
198
- }
199
- return deps.verificationManager.trackVerificationRequest(request);
200
- },
201
- requestVerification: async (params) => {
202
- const crypto = deps.client.getCrypto() as MatrixVerificationCryptoApi | undefined;
203
- return await deps.verificationManager.requestVerification(crypto, params);
204
- },
205
- acceptVerification: async (id) => {
206
- trackInProgressToDeviceVerifications(deps);
207
- return await deps.verificationManager.acceptVerification(id);
208
- },
209
- cancelVerification: async (id, params) => {
210
- trackInProgressToDeviceVerifications(deps);
211
- return await deps.verificationManager.cancelVerification(id, params);
212
- },
213
- startVerification: async (id, method = "sas") => {
214
- trackInProgressToDeviceVerifications(deps);
215
- return await deps.verificationManager.startVerification(id, method);
216
- },
217
- generateVerificationQr: async (id) => {
218
- trackInProgressToDeviceVerifications(deps);
219
- return await deps.verificationManager.generateVerificationQr(id);
220
- },
221
- scanVerificationQr: async (id, qrDataBase64) => {
222
- trackInProgressToDeviceVerifications(deps);
223
- return await deps.verificationManager.scanVerificationQr(id, qrDataBase64);
224
- },
225
- confirmVerificationSas: async (id) => {
226
- trackInProgressToDeviceVerifications(deps);
227
- return await deps.verificationManager.confirmVerificationSas(id);
228
- },
229
- mismatchVerificationSas: async (id) => {
230
- trackInProgressToDeviceVerifications(deps);
231
- return deps.verificationManager.mismatchVerificationSas(id);
232
- },
233
- confirmVerificationReciprocateQr: async (id) => {
234
- trackInProgressToDeviceVerifications(deps);
235
- return deps.verificationManager.confirmVerificationReciprocateQr(id);
236
- },
237
- getVerificationSas: async (id) => {
238
- trackInProgressToDeviceVerifications(deps);
239
- return deps.verificationManager.getVerificationSas(id);
240
- },
241
- };
242
- }
@@ -1,17 +0,0 @@
1
- import { createRequire } from "node:module";
2
-
3
- // Load via createRequire so the CJS package gets __dirname (its index.js
4
- // uses __dirname to locate platform-specific native .node bindings).
5
- const require = createRequire(import.meta.url);
6
- type MatrixCryptoNodePackage = typeof import("@matrix-org/matrix-sdk-crypto-nodejs");
7
-
8
- export type MatrixCryptoNodeBindings = Pick<
9
- MatrixCryptoNodePackage,
10
- "Attachment" | "EncryptedAttachment"
11
- >;
12
-
13
- export function loadMatrixCryptoNodeBindings(): MatrixCryptoNodeBindings {
14
- const { Attachment, EncryptedAttachment } =
15
- require("@matrix-org/matrix-sdk-crypto-nodejs") as MatrixCryptoNodePackage;
16
- return { Attachment, EncryptedAttachment };
17
- }