@archipelagolab/lobi 1.0.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.
Files changed (315) hide show
  1. package/CHANGELOG.md +164 -0
  2. package/ENDOFFILE +0 -0
  3. package/EOF +0 -0
  4. package/LICENSE +21 -0
  5. package/SPEC-SUPPORT.md +116 -0
  6. package/YAMLEND +0 -0
  7. package/api.ts +18 -0
  8. package/archipelagolab-lobi-1.0.0.tgz +0 -0
  9. package/auth-presence.ts +56 -0
  10. package/channel-plugin-api.ts +3 -0
  11. package/cli-metadata.ts +11 -0
  12. package/contract-api.ts +17 -0
  13. package/docs/CHECKLIST.md +83 -0
  14. package/docs/FORK_SDK_GUIDE.md +279 -0
  15. package/helper-api.ts +3 -0
  16. package/index.test.ts +61 -0
  17. package/index.ts +65 -0
  18. package/openclaw.plugin.json +23 -0
  19. package/package.json +52 -0
  20. package/plugin-entry.handlers.runtime.ts +1 -0
  21. package/runtime-api.ts +54 -0
  22. package/runtime-heavy-api.ts +1 -0
  23. package/scripts/migrate-to-lobi.sh +72 -0
  24. package/secret-contract-api.ts +5 -0
  25. package/setup-entry.ts +13 -0
  26. package/src/account-selection.test.ts +124 -0
  27. package/src/account-selection.ts +226 -0
  28. package/src/actions.account-propagation.test.ts +251 -0
  29. package/src/actions.test.ts +251 -0
  30. package/src/actions.ts +336 -0
  31. package/src/approval-auth.test.ts +23 -0
  32. package/src/approval-auth.ts +25 -0
  33. package/src/approval-handler.runtime.test.ts +46 -0
  34. package/src/approval-handler.runtime.ts +400 -0
  35. package/src/approval-ids.ts +6 -0
  36. package/src/approval-native.test.ts +329 -0
  37. package/src/approval-native.ts +336 -0
  38. package/src/approval-reactions.test.ts +107 -0
  39. package/src/approval-reactions.ts +158 -0
  40. package/src/auth-precedence.ts +61 -0
  41. package/src/channel-account-paths.ts +92 -0
  42. package/src/channel.account-paths.test.ts +102 -0
  43. package/src/channel.directory.test.ts +601 -0
  44. package/src/channel.resolve.test.ts +38 -0
  45. package/src/channel.runtime.ts +16 -0
  46. package/src/channel.setup.test.ts +269 -0
  47. package/src/channel.ts +570 -0
  48. package/src/cli-metadata.ts +19 -0
  49. package/src/cli.test.ts +1015 -0
  50. package/src/cli.ts +1198 -0
  51. package/src/config-adapter.ts +41 -0
  52. package/src/config-schema.test.ts +90 -0
  53. package/src/config-schema.ts +114 -0
  54. package/src/directory-live.test.ts +200 -0
  55. package/src/directory-live.ts +238 -0
  56. package/src/doctor-contract.ts +287 -0
  57. package/src/doctor.test.ts +440 -0
  58. package/src/doctor.ts +262 -0
  59. package/src/env-vars.ts +92 -0
  60. package/src/exec-approval-resolver.test.ts +68 -0
  61. package/src/exec-approval-resolver.ts +23 -0
  62. package/src/exec-approvals.test.ts +483 -0
  63. package/src/exec-approvals.ts +290 -0
  64. package/src/group-mentions.ts +41 -0
  65. package/src/legacy-crypto-inspector-availability.test.ts +81 -0
  66. package/src/legacy-crypto-inspector-availability.ts +60 -0
  67. package/src/legacy-crypto.test.ts +234 -0
  68. package/src/legacy-crypto.ts +549 -0
  69. package/src/legacy-state.test.ts +86 -0
  70. package/src/legacy-state.ts +156 -0
  71. package/src/matrix/account-config.ts +150 -0
  72. package/src/matrix/accounts.readiness.test.ts +27 -0
  73. package/src/matrix/accounts.test.ts +757 -0
  74. package/src/matrix/accounts.ts +194 -0
  75. package/src/matrix/actions/client.test.ts +215 -0
  76. package/src/matrix/actions/client.ts +31 -0
  77. package/src/matrix/actions/devices.test.ts +114 -0
  78. package/src/matrix/actions/devices.ts +34 -0
  79. package/src/matrix/actions/limits.test.ts +15 -0
  80. package/src/matrix/actions/limits.ts +6 -0
  81. package/src/matrix/actions/messages.test.ts +289 -0
  82. package/src/matrix/actions/messages.ts +123 -0
  83. package/src/matrix/actions/pins.test.ts +74 -0
  84. package/src/matrix/actions/pins.ts +64 -0
  85. package/src/matrix/actions/polls.test.ts +71 -0
  86. package/src/matrix/actions/polls.ts +109 -0
  87. package/src/matrix/actions/profile.test.ts +109 -0
  88. package/src/matrix/actions/profile.ts +37 -0
  89. package/src/matrix/actions/reactions.test.ts +135 -0
  90. package/src/matrix/actions/reactions.ts +59 -0
  91. package/src/matrix/actions/room.test.ts +79 -0
  92. package/src/matrix/actions/room.ts +71 -0
  93. package/src/matrix/actions/summary.test.ts +87 -0
  94. package/src/matrix/actions/summary.ts +88 -0
  95. package/src/matrix/actions/types.ts +82 -0
  96. package/src/matrix/actions/verification.test.ts +105 -0
  97. package/src/matrix/actions/verification.ts +237 -0
  98. package/src/matrix/actions.ts +37 -0
  99. package/src/matrix/active-client.ts +26 -0
  100. package/src/matrix/async-lock.ts +18 -0
  101. package/src/matrix/backup-health.ts +115 -0
  102. package/src/matrix/client/config-runtime-api.ts +14 -0
  103. package/src/matrix/client/config-secret-input.runtime.ts +1 -0
  104. package/src/matrix/client/config.ts +982 -0
  105. package/src/matrix/client/create-client.test.ts +115 -0
  106. package/src/matrix/client/create-client.ts +101 -0
  107. package/src/matrix/client/env-auth.ts +6 -0
  108. package/src/matrix/client/file-sync-store.test.ts +265 -0
  109. package/src/matrix/client/file-sync-store.ts +289 -0
  110. package/src/matrix/client/logging.ts +123 -0
  111. package/src/matrix/client/migration-snapshot.runtime.ts +1 -0
  112. package/src/matrix/client/private-network-host.ts +56 -0
  113. package/src/matrix/client/runtime.ts +4 -0
  114. package/src/matrix/client/shared.test.ts +344 -0
  115. package/src/matrix/client/shared.ts +306 -0
  116. package/src/matrix/client/storage.test.ts +634 -0
  117. package/src/matrix/client/storage.ts +544 -0
  118. package/src/matrix/client/types.ts +50 -0
  119. package/src/matrix/client-bootstrap.test.ts +84 -0
  120. package/src/matrix/client-bootstrap.ts +164 -0
  121. package/src/matrix/client-resolver.test-helpers.ts +147 -0
  122. package/src/matrix/client.test.ts +1521 -0
  123. package/src/matrix/client.ts +23 -0
  124. package/src/matrix/config-paths.ts +31 -0
  125. package/src/matrix/config-update.test.ts +237 -0
  126. package/src/matrix/config-update.ts +291 -0
  127. package/src/matrix/credentials-read.ts +206 -0
  128. package/src/matrix/credentials-write.runtime.ts +26 -0
  129. package/src/matrix/credentials.test.ts +501 -0
  130. package/src/matrix/credentials.ts +95 -0
  131. package/src/matrix/deps.test.ts +74 -0
  132. package/src/matrix/deps.ts +225 -0
  133. package/src/matrix/device-health.test.ts +45 -0
  134. package/src/matrix/device-health.ts +31 -0
  135. package/src/matrix/direct-management.test.ts +350 -0
  136. package/src/matrix/direct-management.ts +347 -0
  137. package/src/matrix/direct-room.test.ts +61 -0
  138. package/src/matrix/direct-room.ts +128 -0
  139. package/src/matrix/draft-stream.test.ts +406 -0
  140. package/src/matrix/draft-stream.ts +216 -0
  141. package/src/matrix/encryption-guidance.ts +27 -0
  142. package/src/matrix/errors.ts +21 -0
  143. package/src/matrix/format.test.ts +340 -0
  144. package/src/matrix/format.ts +428 -0
  145. package/src/matrix/legacy-crypto-inspector.ts +95 -0
  146. package/src/matrix/media-errors.ts +20 -0
  147. package/src/matrix/media-text.ts +169 -0
  148. package/src/matrix/monitor/access-state.test.ts +45 -0
  149. package/src/matrix/monitor/access-state.ts +77 -0
  150. package/src/matrix/monitor/ack-config.test.ts +57 -0
  151. package/src/matrix/monitor/ack-config.ts +26 -0
  152. package/src/matrix/monitor/allowlist.test.ts +45 -0
  153. package/src/matrix/monitor/allowlist.ts +94 -0
  154. package/src/matrix/monitor/auto-join.test.ts +203 -0
  155. package/src/matrix/monitor/auto-join.ts +86 -0
  156. package/src/matrix/monitor/config.test.ts +197 -0
  157. package/src/matrix/monitor/config.ts +303 -0
  158. package/src/matrix/monitor/context-summary.ts +43 -0
  159. package/src/matrix/monitor/direct.test.ts +529 -0
  160. package/src/matrix/monitor/direct.ts +270 -0
  161. package/src/matrix/monitor/events.test.ts +1524 -0
  162. package/src/matrix/monitor/events.ts +213 -0
  163. package/src/matrix/monitor/handler.body-for-agent.test.ts +396 -0
  164. package/src/matrix/monitor/handler.group-history.test.ts +648 -0
  165. package/src/matrix/monitor/handler.media-failure.test.ts +267 -0
  166. package/src/matrix/monitor/handler.test-helpers.ts +308 -0
  167. package/src/matrix/monitor/handler.test.ts +2952 -0
  168. package/src/matrix/monitor/handler.thread-root-media.test.ts +82 -0
  169. package/src/matrix/monitor/handler.ts +1679 -0
  170. package/src/matrix/monitor/inbound-dedupe.test.ts +146 -0
  171. package/src/matrix/monitor/inbound-dedupe.ts +267 -0
  172. package/src/matrix/monitor/index.test.ts +920 -0
  173. package/src/matrix/monitor/index.ts +434 -0
  174. package/src/matrix/monitor/legacy-crypto-restore.test.ts +206 -0
  175. package/src/matrix/monitor/legacy-crypto-restore.ts +139 -0
  176. package/src/matrix/monitor/location.ts +100 -0
  177. package/src/matrix/monitor/media.test.ts +159 -0
  178. package/src/matrix/monitor/media.ts +119 -0
  179. package/src/matrix/monitor/mentions.test.ts +289 -0
  180. package/src/matrix/monitor/mentions.ts +177 -0
  181. package/src/matrix/monitor/reaction-events.test.ts +326 -0
  182. package/src/matrix/monitor/reaction-events.ts +187 -0
  183. package/src/matrix/monitor/recent-invite.test.ts +92 -0
  184. package/src/matrix/monitor/recent-invite.ts +30 -0
  185. package/src/matrix/monitor/replies.test.ts +265 -0
  186. package/src/matrix/monitor/replies.ts +136 -0
  187. package/src/matrix/monitor/reply-context.test.ts +276 -0
  188. package/src/matrix/monitor/reply-context.ts +92 -0
  189. package/src/matrix/monitor/room-history.test.ts +258 -0
  190. package/src/matrix/monitor/room-history.ts +301 -0
  191. package/src/matrix/monitor/room-info.test.ts +201 -0
  192. package/src/matrix/monitor/room-info.ts +126 -0
  193. package/src/matrix/monitor/rooms.test.ts +121 -0
  194. package/src/matrix/monitor/rooms.ts +52 -0
  195. package/src/matrix/monitor/route.test.ts +255 -0
  196. package/src/matrix/monitor/route.ts +178 -0
  197. package/src/matrix/monitor/runtime-api.ts +31 -0
  198. package/src/matrix/monitor/startup-verification.test.ts +294 -0
  199. package/src/matrix/monitor/startup-verification.ts +237 -0
  200. package/src/matrix/monitor/startup.test.ts +257 -0
  201. package/src/matrix/monitor/startup.ts +218 -0
  202. package/src/matrix/monitor/status.ts +111 -0
  203. package/src/matrix/monitor/sync-lifecycle.test.ts +224 -0
  204. package/src/matrix/monitor/sync-lifecycle.ts +91 -0
  205. package/src/matrix/monitor/task-runner.ts +38 -0
  206. package/src/matrix/monitor/thread-context.test.ts +149 -0
  207. package/src/matrix/monitor/thread-context.ts +108 -0
  208. package/src/matrix/monitor/threads.test.ts +68 -0
  209. package/src/matrix/monitor/threads.ts +85 -0
  210. package/src/matrix/monitor/types.ts +30 -0
  211. package/src/matrix/monitor/verification-events.ts +627 -0
  212. package/src/matrix/monitor/verification-utils.test.ts +47 -0
  213. package/src/matrix/monitor/verification-utils.ts +46 -0
  214. package/src/matrix/outbound-media-runtime.ts +1 -0
  215. package/src/matrix/poll-summary.ts +110 -0
  216. package/src/matrix/poll-types.test.ts +205 -0
  217. package/src/matrix/poll-types.ts +433 -0
  218. package/src/matrix/probe.runtime.ts +4 -0
  219. package/src/matrix/probe.test.ts +154 -0
  220. package/src/matrix/probe.ts +96 -0
  221. package/src/matrix/profile.test.ts +154 -0
  222. package/src/matrix/profile.ts +184 -0
  223. package/src/matrix/reaction-common.test.ts +96 -0
  224. package/src/matrix/reaction-common.ts +147 -0
  225. package/src/matrix/sdk/crypto-bootstrap.test.ts +505 -0
  226. package/src/matrix/sdk/crypto-bootstrap.ts +341 -0
  227. package/src/matrix/sdk/crypto-facade.test.ts +197 -0
  228. package/src/matrix/sdk/crypto-facade.ts +207 -0
  229. package/src/matrix/sdk/crypto-node.runtime.test.ts +27 -0
  230. package/src/matrix/sdk/crypto-node.runtime.ts +9 -0
  231. package/src/matrix/sdk/crypto-runtime.ts +11 -0
  232. package/src/matrix/sdk/decrypt-bridge.ts +356 -0
  233. package/src/matrix/sdk/event-helpers.test.ts +60 -0
  234. package/src/matrix/sdk/event-helpers.ts +71 -0
  235. package/src/matrix/sdk/http-client.test.ts +134 -0
  236. package/src/matrix/sdk/http-client.ts +87 -0
  237. package/src/matrix/sdk/idb-persistence-lock.ts +51 -0
  238. package/src/matrix/sdk/idb-persistence.lock-order.test.ts +108 -0
  239. package/src/matrix/sdk/idb-persistence.test-helpers.ts +88 -0
  240. package/src/matrix/sdk/idb-persistence.test.ts +149 -0
  241. package/src/matrix/sdk/idb-persistence.ts +283 -0
  242. package/src/matrix/sdk/logger.test.ts +25 -0
  243. package/src/matrix/sdk/logger.ts +108 -0
  244. package/src/matrix/sdk/read-response-with-limit.ts +19 -0
  245. package/src/matrix/sdk/recovery-key-store.test.ts +385 -0
  246. package/src/matrix/sdk/recovery-key-store.ts +430 -0
  247. package/src/matrix/sdk/transport.test.ts +161 -0
  248. package/src/matrix/sdk/transport.ts +344 -0
  249. package/src/matrix/sdk/types.ts +236 -0
  250. package/src/matrix/sdk/verification-manager.test.ts +509 -0
  251. package/src/matrix/sdk/verification-manager.ts +694 -0
  252. package/src/matrix/sdk/verification-status.ts +23 -0
  253. package/src/matrix/sdk.test.ts +2568 -0
  254. package/src/matrix/sdk.ts +1789 -0
  255. package/src/matrix/send/client.test.ts +174 -0
  256. package/src/matrix/send/client.ts +90 -0
  257. package/src/matrix/send/formatting.ts +189 -0
  258. package/src/matrix/send/media.ts +244 -0
  259. package/src/matrix/send/targets.test.ts +254 -0
  260. package/src/matrix/send/targets.ts +104 -0
  261. package/src/matrix/send/types.ts +134 -0
  262. package/src/matrix/send.test.ts +958 -0
  263. package/src/matrix/send.ts +609 -0
  264. package/src/matrix/session-store-metadata.ts +108 -0
  265. package/src/matrix/startup-abort.ts +44 -0
  266. package/src/matrix/sync-state.ts +27 -0
  267. package/src/matrix/target-ids.ts +102 -0
  268. package/src/matrix/thread-bindings-shared.ts +201 -0
  269. package/src/matrix/thread-bindings.test.ts +673 -0
  270. package/src/matrix/thread-bindings.ts +577 -0
  271. package/src/matrix-migration.runtime.ts +9 -0
  272. package/src/migration-config.test.ts +228 -0
  273. package/src/migration-config.ts +243 -0
  274. package/src/migration-snapshot-backup.ts +117 -0
  275. package/src/migration-snapshot.test.ts +184 -0
  276. package/src/migration-snapshot.ts +55 -0
  277. package/src/onboarding.resolve.test.ts +55 -0
  278. package/src/onboarding.test-harness.ts +158 -0
  279. package/src/onboarding.test.ts +665 -0
  280. package/src/onboarding.ts +773 -0
  281. package/src/outbound.test.ts +173 -0
  282. package/src/outbound.ts +78 -0
  283. package/src/plugin-entry.runtime.js +159 -0
  284. package/src/plugin-entry.runtime.test.ts +108 -0
  285. package/src/plugin-entry.runtime.ts +68 -0
  286. package/src/profile-update.ts +68 -0
  287. package/src/record-shared.ts +3 -0
  288. package/src/resolve-targets.test.ts +178 -0
  289. package/src/resolve-targets.ts +175 -0
  290. package/src/resolver.ts +21 -0
  291. package/src/runtime-api.ts +144 -0
  292. package/src/runtime.ts +7 -0
  293. package/src/secret-contract.ts +174 -0
  294. package/src/session-route.test.ts +315 -0
  295. package/src/session-route.ts +113 -0
  296. package/src/setup-bootstrap.ts +94 -0
  297. package/src/setup-config.ts +222 -0
  298. package/src/setup-contract.ts +89 -0
  299. package/src/setup-core.test.ts +326 -0
  300. package/src/setup-core.ts +50 -0
  301. package/src/setup-surface.ts +4 -0
  302. package/src/startup-maintenance.test.ts +227 -0
  303. package/src/startup-maintenance.ts +114 -0
  304. package/src/storage-paths.ts +92 -0
  305. package/src/test-helpers.ts +42 -0
  306. package/src/test-mocks.ts +55 -0
  307. package/src/test-runtime.ts +72 -0
  308. package/src/test-support/monitor-route-test-support.ts +8 -0
  309. package/src/tool-actions.runtime.ts +1 -0
  310. package/src/tool-actions.test.ts +422 -0
  311. package/src/tool-actions.ts +498 -0
  312. package/src/types.ts +230 -0
  313. package/test-api.ts +2 -0
  314. package/thread-bindings-runtime.ts +4 -0
  315. package/tsconfig.json +16 -0
@@ -0,0 +1,1789 @@
1
+ import { EventEmitter } from "node:events";
2
+ import {
3
+ ClientEvent,
4
+ MatrixEventEvent,
5
+ Preset,
6
+ createClient as createMatrixJsClient,
7
+ type MatrixClient as MatrixJsClient,
8
+ type MatrixEvent,
9
+ } from "@archipelagolab/lobi-js-sdk/lib/lobi.js";
10
+ import { VerificationMethod } from "@archipelagolab/lobi-js-sdk/lib/types.js";
11
+ import type { PinnedDispatcherPolicy } from "openclaw/plugin-sdk/infra-runtime";
12
+ import { KeyedAsyncQueue } from "openclaw/plugin-sdk/keyed-async-queue";
13
+ import { normalizeNullableString } from "openclaw/plugin-sdk/text-runtime";
14
+ import type { SsrFPolicy } from "../runtime-api.js";
15
+ import { resolveMatrixRoomKeyBackupReadinessError } from "./backup-health.js";
16
+ import { FileBackedMatrixSyncStore } from "./client/file-sync-store.js";
17
+ import { createMatrixJsSdkClientLogger } from "./client/logging.js";
18
+ import {
19
+ formatMatrixErrorMessage,
20
+ formatMatrixErrorReason,
21
+ isMatrixNotFoundError,
22
+ } from "./errors.js";
23
+ import type {
24
+ MatrixCryptoBootstrapOptions,
25
+ MatrixCryptoBootstrapResult,
26
+ } from "./sdk/crypto-bootstrap.js";
27
+ import type { MatrixCryptoFacade } from "./sdk/crypto-facade.js";
28
+ import type { MatrixDecryptBridge } from "./sdk/decrypt-bridge.js";
29
+ import { matrixEventToRaw, parseMxc } from "./sdk/event-helpers.js";
30
+ import { MatrixAuthedHttpClient } from "./sdk/http-client.js";
31
+ import { MATRIX_IDB_PERSIST_INTERVAL_MS } from "./sdk/idb-persistence-lock.js";
32
+ import { ConsoleLogger, LogService, noop } from "./sdk/logger.js";
33
+ import {
34
+ MatrixRecoveryKeyStore,
35
+ isRepairableSecretStorageAccessError,
36
+ } from "./sdk/recovery-key-store.js";
37
+ import { createMatrixGuardedFetch, type HttpMethod, type QueryParams } from "./sdk/transport.js";
38
+ import type {
39
+ MatrixClientEventMap,
40
+ MatrixCryptoBootstrapApi,
41
+ MatrixDeviceVerificationStatusLike,
42
+ MatrixRelationsPage,
43
+ MatrixRawEvent,
44
+ MessageEventContent,
45
+ } from "./sdk/types.js";
46
+ import type { MatrixVerificationSummary } from "./sdk/verification-manager.js";
47
+ import { createMatrixStartupAbortError, throwIfMatrixStartupAborted } from "./startup-abort.js";
48
+ import {
49
+ isMatrixReadySyncState,
50
+ isMatrixTerminalSyncState,
51
+ type MatrixSyncState,
52
+ } from "./sync-state.js";
53
+
54
+ export { ConsoleLogger, LogService };
55
+ export type {
56
+ DimensionalFileInfo,
57
+ FileWithThumbnailInfo,
58
+ TimedFileInfo,
59
+ VideoFileInfo,
60
+ } from "./sdk/types.js";
61
+ export type {
62
+ EncryptedFile,
63
+ LocationMessageEventContent,
64
+ MatrixRawEvent,
65
+ MessageEventContent,
66
+ TextualMessageEventContent,
67
+ } from "./sdk/types.js";
68
+
69
+ export type MatrixOwnDeviceVerificationStatus = {
70
+ encryptionEnabled: boolean;
71
+ userId: string | null;
72
+ deviceId: string | null;
73
+ // "verified" is intentionally strict: other Matrix clients should trust messages
74
+ // from this device without showing "not verified by its owner" warnings.
75
+ verified: boolean;
76
+ localVerified: boolean;
77
+ crossSigningVerified: boolean;
78
+ signedByOwner: boolean;
79
+ recoveryKeyStored: boolean;
80
+ recoveryKeyCreatedAt: string | null;
81
+ recoveryKeyId: string | null;
82
+ backupVersion: string | null;
83
+ backup: MatrixRoomKeyBackupStatus;
84
+ };
85
+
86
+ export type MatrixRoomKeyBackupStatus = {
87
+ serverVersion: string | null;
88
+ activeVersion: string | null;
89
+ trusted: boolean | null;
90
+ matchesDecryptionKey: boolean | null;
91
+ decryptionKeyCached: boolean | null;
92
+ keyLoadAttempted: boolean;
93
+ keyLoadError: string | null;
94
+ };
95
+
96
+ export type MatrixRoomKeyBackupRestoreResult = {
97
+ success: boolean;
98
+ error?: string;
99
+ backupVersion: string | null;
100
+ imported: number;
101
+ total: number;
102
+ loadedFromSecretStorage: boolean;
103
+ restoredAt?: string;
104
+ backup: MatrixRoomKeyBackupStatus;
105
+ };
106
+
107
+ export type MatrixRoomKeyBackupResetResult = {
108
+ success: boolean;
109
+ error?: string;
110
+ previousVersion: string | null;
111
+ deletedVersion: string | null;
112
+ createdVersion: string | null;
113
+ resetAt?: string;
114
+ backup: MatrixRoomKeyBackupStatus;
115
+ };
116
+
117
+ export type MatrixRecoveryKeyVerificationResult = MatrixOwnDeviceVerificationStatus & {
118
+ success: boolean;
119
+ verifiedAt?: string;
120
+ error?: string;
121
+ };
122
+
123
+ export type MatrixOwnCrossSigningPublicationStatus = {
124
+ userId: string | null;
125
+ masterKeyPublished: boolean;
126
+ selfSigningKeyPublished: boolean;
127
+ userSigningKeyPublished: boolean;
128
+ published: boolean;
129
+ };
130
+
131
+ export type MatrixVerificationBootstrapResult = {
132
+ success: boolean;
133
+ error?: string;
134
+ verification: MatrixOwnDeviceVerificationStatus;
135
+ crossSigning: MatrixOwnCrossSigningPublicationStatus;
136
+ pendingVerifications: number;
137
+ cryptoBootstrap: MatrixCryptoBootstrapResult | null;
138
+ };
139
+
140
+ const MATRIX_INITIAL_CRYPTO_BOOTSTRAP_OPTIONS = {
141
+ allowAutomaticCrossSigningReset: false,
142
+ } satisfies MatrixCryptoBootstrapOptions;
143
+
144
+ const MATRIX_AUTOMATIC_REPAIR_BOOTSTRAP_OPTIONS = {
145
+ forceResetCrossSigning: true,
146
+ allowSecretStorageRecreateWithoutRecoveryKey: true,
147
+ strict: true,
148
+ } satisfies MatrixCryptoBootstrapOptions;
149
+
150
+ function createMatrixExplicitBootstrapOptions(params?: {
151
+ forceResetCrossSigning?: boolean;
152
+ }): MatrixCryptoBootstrapOptions {
153
+ return {
154
+ forceResetCrossSigning: params?.forceResetCrossSigning === true,
155
+ allowSecretStorageRecreateWithoutRecoveryKey: true,
156
+ strict: true,
157
+ };
158
+ }
159
+
160
+ export type MatrixOwnDeviceInfo = {
161
+ deviceId: string;
162
+ displayName: string | null;
163
+ lastSeenIp: string | null;
164
+ lastSeenTs: number | null;
165
+ current: boolean;
166
+ };
167
+
168
+ export type MatrixOwnDeviceDeleteResult = {
169
+ currentDeviceId: string | null;
170
+ deletedDeviceIds: string[];
171
+ remainingDevices: MatrixOwnDeviceInfo[];
172
+ };
173
+
174
+ type MatrixCryptoRuntime = typeof import("./sdk/crypto-runtime.js");
175
+
176
+ let loadedMatrixCryptoRuntime: MatrixCryptoRuntime | null = null;
177
+ let matrixCryptoRuntimePromise: Promise<MatrixCryptoRuntime> | null = null;
178
+
179
+ async function loadMatrixCryptoRuntime(): Promise<MatrixCryptoRuntime> {
180
+ matrixCryptoRuntimePromise ??= import("./sdk/crypto-runtime.js").then((runtime) => {
181
+ loadedMatrixCryptoRuntime = runtime;
182
+ return runtime;
183
+ });
184
+ return await matrixCryptoRuntimePromise;
185
+ }
186
+
187
+ const normalizeOptionalString = normalizeNullableString;
188
+
189
+ function isUnsupportedAuthenticatedMediaEndpointError(err: unknown): boolean {
190
+ const statusCode = (err as { statusCode?: number })?.statusCode;
191
+ if (statusCode === 404 || statusCode === 405 || statusCode === 501) {
192
+ return true;
193
+ }
194
+ const message = formatMatrixErrorReason(err);
195
+ return (
196
+ message.includes("m_unrecognized") ||
197
+ message.includes("unrecognized request") ||
198
+ message.includes("method not allowed") ||
199
+ message.includes("not implemented")
200
+ );
201
+ }
202
+
203
+ export class MatrixClient {
204
+ private readonly client: MatrixJsClient;
205
+ private readonly emitter = new EventEmitter();
206
+ private readonly httpClient: MatrixAuthedHttpClient;
207
+ private readonly localTimeoutMs: number;
208
+ private readonly initialSyncLimit?: number;
209
+ private readonly encryptionEnabled: boolean;
210
+ private readonly password?: string;
211
+ private readonly syncStore?: FileBackedMatrixSyncStore;
212
+ private readonly idbSnapshotPath?: string;
213
+ private readonly cryptoDatabasePrefix?: string;
214
+ private bridgeRegistered = false;
215
+ private started = false;
216
+ private cryptoBootstrapped = false;
217
+ private selfUserId: string | null;
218
+ private readonly dmRoomIds = new Set<string>();
219
+ private cryptoInitialized = false;
220
+ private decryptBridge?: MatrixDecryptBridge<MatrixRawEvent>;
221
+ private verificationManager?: import("./sdk/verification-manager.js").MatrixVerificationManager;
222
+ private readonly sendQueue = new KeyedAsyncQueue();
223
+ private readonly recoveryKeyStore: MatrixRecoveryKeyStore;
224
+ private cryptoBootstrapper?:
225
+ | import("./sdk/crypto-bootstrap.js").MatrixCryptoBootstrapper<MatrixRawEvent>
226
+ | undefined;
227
+ private readonly autoBootstrapCrypto: boolean;
228
+ private stopPersistPromise: Promise<void> | null = null;
229
+ private verificationSummaryListenerBound = false;
230
+ private currentSyncState: MatrixSyncState | null = null;
231
+
232
+ readonly dms = {
233
+ update: async (): Promise<boolean> => {
234
+ return await this.refreshDmCache();
235
+ },
236
+ isDm: (roomId: string): boolean => this.dmRoomIds.has(roomId),
237
+ };
238
+
239
+ crypto?: MatrixCryptoFacade;
240
+
241
+ constructor(
242
+ homeserver: string,
243
+ accessToken: string,
244
+ opts: {
245
+ userId?: string;
246
+ password?: string;
247
+ deviceId?: string;
248
+ localTimeoutMs?: number;
249
+ encryption?: boolean;
250
+ initialSyncLimit?: number;
251
+ storagePath?: string;
252
+ recoveryKeyPath?: string;
253
+ idbSnapshotPath?: string;
254
+ cryptoDatabasePrefix?: string;
255
+ autoBootstrapCrypto?: boolean;
256
+ ssrfPolicy?: SsrFPolicy;
257
+ dispatcherPolicy?: PinnedDispatcherPolicy;
258
+ } = {},
259
+ ) {
260
+ this.httpClient = new MatrixAuthedHttpClient({
261
+ homeserver,
262
+ accessToken,
263
+ ssrfPolicy: opts.ssrfPolicy,
264
+ dispatcherPolicy: opts.dispatcherPolicy,
265
+ });
266
+ this.localTimeoutMs = Math.max(1, opts.localTimeoutMs ?? 60_000);
267
+ this.initialSyncLimit = opts.initialSyncLimit;
268
+ this.encryptionEnabled = opts.encryption === true;
269
+ this.password = opts.password;
270
+ this.syncStore = opts.storagePath ? new FileBackedMatrixSyncStore(opts.storagePath) : undefined;
271
+ this.idbSnapshotPath = opts.idbSnapshotPath;
272
+ this.cryptoDatabasePrefix = opts.cryptoDatabasePrefix;
273
+ this.selfUserId = opts.userId?.trim() || null;
274
+ this.autoBootstrapCrypto = opts.autoBootstrapCrypto !== false;
275
+ this.recoveryKeyStore = new MatrixRecoveryKeyStore(opts.recoveryKeyPath);
276
+ const cryptoCallbacks = this.encryptionEnabled
277
+ ? this.recoveryKeyStore.buildCryptoCallbacks()
278
+ : undefined;
279
+ this.client = createMatrixJsClient({
280
+ baseUrl: homeserver,
281
+ accessToken,
282
+ userId: opts.userId,
283
+ deviceId: opts.deviceId,
284
+ logger: createMatrixJsSdkClientLogger("MatrixClient"),
285
+ localTimeoutMs: this.localTimeoutMs,
286
+ fetchFn: createMatrixGuardedFetch({
287
+ ssrfPolicy: opts.ssrfPolicy,
288
+ dispatcherPolicy: opts.dispatcherPolicy,
289
+ }),
290
+ store: this.syncStore,
291
+ cryptoCallbacks: cryptoCallbacks as never,
292
+ verificationMethods: [
293
+ VerificationMethod.Sas,
294
+ VerificationMethod.ShowQrCode,
295
+ VerificationMethod.ScanQrCode,
296
+ VerificationMethod.Reciprocate,
297
+ ],
298
+ });
299
+ }
300
+
301
+ on<TEvent extends keyof MatrixClientEventMap>(
302
+ eventName: TEvent,
303
+ listener: (...args: MatrixClientEventMap[TEvent]) => void,
304
+ ): this;
305
+ on(eventName: string, listener: (...args: unknown[]) => void): this;
306
+ on(eventName: string, listener: (...args: unknown[]) => void): this {
307
+ this.emitter.on(eventName, listener as (...args: unknown[]) => void);
308
+ return this;
309
+ }
310
+
311
+ off<TEvent extends keyof MatrixClientEventMap>(
312
+ eventName: TEvent,
313
+ listener: (...args: MatrixClientEventMap[TEvent]) => void,
314
+ ): this;
315
+ off(eventName: string, listener: (...args: unknown[]) => void): this;
316
+ off(eventName: string, listener: (...args: unknown[]) => void): this {
317
+ this.emitter.off(eventName, listener as (...args: unknown[]) => void);
318
+ return this;
319
+ }
320
+
321
+ private idbPersistTimer: ReturnType<typeof setInterval> | null = null;
322
+
323
+ private async ensureCryptoSupportInitialized(): Promise<void> {
324
+ if (
325
+ this.decryptBridge &&
326
+ (!this.encryptionEnabled ||
327
+ (this.verificationManager && this.cryptoBootstrapper && this.crypto))
328
+ ) {
329
+ return;
330
+ }
331
+
332
+ const runtime = await loadMatrixCryptoRuntime();
333
+ this.decryptBridge ??= new runtime.MatrixDecryptBridge<MatrixRawEvent>({
334
+ client: this.client,
335
+ toRaw: (event) => matrixEventToRaw(event),
336
+ emitDecryptedEvent: (roomId, event) => {
337
+ this.emitter.emit("room.decrypted_event", roomId, event);
338
+ },
339
+ emitMessage: (roomId, event) => {
340
+ this.emitter.emit("room.message", roomId, event);
341
+ },
342
+ emitFailedDecryption: (roomId, event, error) => {
343
+ this.emitter.emit("room.failed_decryption", roomId, event, error);
344
+ },
345
+ });
346
+ if (!this.encryptionEnabled) {
347
+ return;
348
+ }
349
+
350
+ this.verificationManager ??= new runtime.MatrixVerificationManager();
351
+ this.cryptoBootstrapper ??= new runtime.MatrixCryptoBootstrapper<MatrixRawEvent>({
352
+ getUserId: () => this.getUserId(),
353
+ getPassword: () => this.password,
354
+ getDeviceId: () => this.client.getDeviceId(),
355
+ verificationManager: this.verificationManager,
356
+ recoveryKeyStore: this.recoveryKeyStore,
357
+ decryptBridge: this.decryptBridge,
358
+ });
359
+ if (!this.crypto) {
360
+ this.crypto = runtime.createMatrixCryptoFacade({
361
+ client: this.client,
362
+ verificationManager: this.verificationManager,
363
+ recoveryKeyStore: this.recoveryKeyStore,
364
+ getRoomStateEvent: (roomId, eventType, stateKey = "") =>
365
+ this.getRoomStateEvent(roomId, eventType, stateKey),
366
+ downloadContent: (mxcUrl) => this.downloadContent(mxcUrl),
367
+ });
368
+ }
369
+ if (!this.verificationSummaryListenerBound) {
370
+ this.verificationSummaryListenerBound = true;
371
+ this.verificationManager.onSummaryChanged((summary: MatrixVerificationSummary) => {
372
+ this.emitter.emit("verification.summary", summary);
373
+ });
374
+ }
375
+ }
376
+
377
+ async start(opts: { abortSignal?: AbortSignal; readyTimeoutMs?: number } = {}): Promise<void> {
378
+ await this.startSyncSession({
379
+ bootstrapCrypto: true,
380
+ abortSignal: opts.abortSignal,
381
+ readyTimeoutMs: opts.readyTimeoutMs,
382
+ });
383
+ }
384
+
385
+ private async waitForInitialSyncReady(
386
+ params: {
387
+ timeoutMs?: number;
388
+ abortSignal?: AbortSignal;
389
+ } = {},
390
+ ): Promise<void> {
391
+ const timeoutMs = params.timeoutMs ?? 30_000;
392
+ if (isMatrixReadySyncState(this.currentSyncState)) {
393
+ return;
394
+ }
395
+ if (isMatrixTerminalSyncState(this.currentSyncState)) {
396
+ throw new Error(`Matrix sync entered ${this.currentSyncState} during startup`);
397
+ }
398
+
399
+ await new Promise<void>((resolve, reject) => {
400
+ let settled = false;
401
+ let timeoutId: ReturnType<typeof setTimeout> | undefined;
402
+ const abortSignal = params.abortSignal;
403
+
404
+ const cleanup = () => {
405
+ this.off("sync.state", onSyncState);
406
+ this.off("sync.unexpected_error", onUnexpectedError);
407
+ abortSignal?.removeEventListener("abort", onAbort);
408
+ if (timeoutId) {
409
+ clearTimeout(timeoutId);
410
+ timeoutId = undefined;
411
+ }
412
+ };
413
+
414
+ const settleResolve = () => {
415
+ if (settled) {
416
+ return;
417
+ }
418
+ settled = true;
419
+ cleanup();
420
+ resolve();
421
+ };
422
+
423
+ const settleReject = (error: Error) => {
424
+ if (settled) {
425
+ return;
426
+ }
427
+ settled = true;
428
+ cleanup();
429
+ reject(error);
430
+ };
431
+
432
+ const onSyncState = (state: MatrixSyncState, _prevState: string | null, error?: unknown) => {
433
+ if (isMatrixReadySyncState(state)) {
434
+ settleResolve();
435
+ return;
436
+ }
437
+ if (isMatrixTerminalSyncState(state)) {
438
+ settleReject(
439
+ new Error(
440
+ error instanceof Error && error.message
441
+ ? error.message
442
+ : `Matrix sync entered ${state} during startup`,
443
+ ),
444
+ );
445
+ }
446
+ };
447
+
448
+ const onUnexpectedError = (error: Error) => {
449
+ settleReject(error);
450
+ };
451
+
452
+ const onAbort = () => {
453
+ settleReject(createMatrixStartupAbortError());
454
+ };
455
+
456
+ this.on("sync.state", onSyncState);
457
+ this.on("sync.unexpected_error", onUnexpectedError);
458
+ if (abortSignal?.aborted) {
459
+ onAbort();
460
+ return;
461
+ }
462
+ abortSignal?.addEventListener("abort", onAbort, { once: true });
463
+ timeoutId = setTimeout(() => {
464
+ settleReject(
465
+ new Error(`Matrix client did not reach a ready sync state within ${timeoutMs}ms`),
466
+ );
467
+ }, timeoutMs);
468
+ timeoutId.unref?.();
469
+ });
470
+ }
471
+
472
+ private async startSyncSession(opts: {
473
+ bootstrapCrypto: boolean;
474
+ abortSignal?: AbortSignal;
475
+ readyTimeoutMs?: number;
476
+ }): Promise<void> {
477
+ if (this.started) {
478
+ return;
479
+ }
480
+
481
+ throwIfMatrixStartupAborted(opts.abortSignal);
482
+ await this.ensureCryptoSupportInitialized();
483
+ throwIfMatrixStartupAborted(opts.abortSignal);
484
+ this.registerBridge();
485
+ await this.initializeCryptoIfNeeded(opts.abortSignal);
486
+
487
+ await this.client.startClient({
488
+ initialSyncLimit: this.initialSyncLimit,
489
+ });
490
+ await this.waitForInitialSyncReady({
491
+ abortSignal: opts.abortSignal,
492
+ timeoutMs: opts.readyTimeoutMs,
493
+ });
494
+ throwIfMatrixStartupAborted(opts.abortSignal);
495
+ if (opts.bootstrapCrypto && this.autoBootstrapCrypto) {
496
+ await this.bootstrapCryptoIfNeeded(opts.abortSignal);
497
+ }
498
+ throwIfMatrixStartupAborted(opts.abortSignal);
499
+ this.started = true;
500
+ this.emitOutstandingInviteEvents();
501
+ await this.refreshDmCache().catch(noop);
502
+ }
503
+
504
+ async prepareForOneOff(): Promise<void> {
505
+ if (!this.encryptionEnabled) {
506
+ return;
507
+ }
508
+ await this.ensureCryptoSupportInitialized();
509
+ await this.initializeCryptoIfNeeded();
510
+ if (!this.crypto) {
511
+ return;
512
+ }
513
+ try {
514
+ const joinedRooms = await this.getJoinedRooms();
515
+ await this.crypto.prepare(joinedRooms);
516
+ } catch {
517
+ // One-off commands should continue even if crypto room prep is incomplete.
518
+ }
519
+ }
520
+
521
+ hasPersistedSyncState(): boolean {
522
+ // Only trust restart replay when the previous process completed a final
523
+ // sync-store persist. A stale cursor can make Matrix re-surface old events.
524
+ return this.syncStore?.hasSavedSyncFromCleanShutdown() === true;
525
+ }
526
+
527
+ private async ensureStartedForCryptoControlPlane(): Promise<void> {
528
+ if (this.started) {
529
+ return;
530
+ }
531
+ await this.startSyncSession({ bootstrapCrypto: false });
532
+ }
533
+
534
+ stopSyncWithoutPersist(): void {
535
+ if (this.idbPersistTimer) {
536
+ clearInterval(this.idbPersistTimer);
537
+ this.idbPersistTimer = null;
538
+ }
539
+ this.currentSyncState = null;
540
+ this.client.stopClient();
541
+ this.started = false;
542
+ }
543
+
544
+ async drainPendingDecryptions(reason = "matrix client shutdown"): Promise<void> {
545
+ await this.decryptBridge?.drainPendingDecryptions(reason);
546
+ }
547
+
548
+ stop(): void {
549
+ this.stopSyncWithoutPersist();
550
+ this.decryptBridge?.stop();
551
+ // Final persist on shutdown
552
+ this.syncStore?.markCleanShutdown();
553
+ if (loadedMatrixCryptoRuntime) {
554
+ const { persistIdbToDisk } = loadedMatrixCryptoRuntime;
555
+ this.stopPersistPromise = Promise.all([
556
+ persistIdbToDisk({
557
+ snapshotPath: this.idbSnapshotPath,
558
+ databasePrefix: this.cryptoDatabasePrefix,
559
+ }).catch(noop),
560
+ this.syncStore?.flush().catch(noop),
561
+ ]).then(() => undefined);
562
+ return;
563
+ }
564
+ this.stopPersistPromise = loadMatrixCryptoRuntime()
565
+ .then(async ({ persistIdbToDisk }) => {
566
+ await Promise.all([
567
+ persistIdbToDisk({
568
+ snapshotPath: this.idbSnapshotPath,
569
+ databasePrefix: this.cryptoDatabasePrefix,
570
+ }).catch(noop),
571
+ this.syncStore?.flush().catch(noop),
572
+ ]);
573
+ })
574
+ .catch(noop)
575
+ .then(() => undefined);
576
+ }
577
+
578
+ async stopAndPersist(): Promise<void> {
579
+ this.stop();
580
+ await this.stopPersistPromise;
581
+ }
582
+
583
+ private async bootstrapCryptoIfNeeded(abortSignal?: AbortSignal): Promise<void> {
584
+ if (!this.encryptionEnabled || !this.cryptoInitialized || this.cryptoBootstrapped) {
585
+ return;
586
+ }
587
+ throwIfMatrixStartupAborted(abortSignal);
588
+ await this.ensureCryptoSupportInitialized();
589
+ const crypto = this.client.getCrypto() as MatrixCryptoBootstrapApi | undefined;
590
+ if (!crypto) {
591
+ return;
592
+ }
593
+ const cryptoBootstrapper = this.cryptoBootstrapper;
594
+ if (!cryptoBootstrapper) {
595
+ return;
596
+ }
597
+ const initial = await cryptoBootstrapper.bootstrap(
598
+ crypto,
599
+ MATRIX_INITIAL_CRYPTO_BOOTSTRAP_OPTIONS,
600
+ );
601
+ throwIfMatrixStartupAborted(abortSignal);
602
+ if (!initial.crossSigningPublished || initial.ownDeviceVerified === false) {
603
+ const status = await this.getOwnDeviceVerificationStatus();
604
+ if (status.signedByOwner) {
605
+ LogService.warn(
606
+ "MatrixClientLite",
607
+ "Cross-signing/bootstrap is incomplete for an already owner-signed device; skipping automatic reset and preserving the current identity. Restore the recovery key or run an explicit verification bootstrap if repair is needed.",
608
+ );
609
+ } else if (this.password?.trim()) {
610
+ try {
611
+ // The repair path already force-resets cross-signing; allow secret storage
612
+ // recreation so the new keys can be persisted. Without this, a device that
613
+ // lost its recovery key enters a permanent failure loop because the new
614
+ // cross-signing keys have nowhere to be stored.
615
+ const repaired = await cryptoBootstrapper.bootstrap(
616
+ crypto,
617
+ MATRIX_AUTOMATIC_REPAIR_BOOTSTRAP_OPTIONS,
618
+ );
619
+ throwIfMatrixStartupAborted(abortSignal);
620
+ if (repaired.crossSigningPublished && repaired.ownDeviceVerified !== false) {
621
+ LogService.info(
622
+ "MatrixClientLite",
623
+ "Cross-signing/bootstrap recovered after forced reset",
624
+ );
625
+ }
626
+ } catch (err) {
627
+ LogService.warn(
628
+ "MatrixClientLite",
629
+ "Failed to recover cross-signing/bootstrap with forced reset:",
630
+ err,
631
+ );
632
+ }
633
+ } else {
634
+ LogService.warn(
635
+ "MatrixClientLite",
636
+ "Cross-signing/bootstrap incomplete and no password is configured for UIA fallback",
637
+ );
638
+ }
639
+ }
640
+ this.cryptoBootstrapped = true;
641
+ }
642
+
643
+ private async initializeCryptoIfNeeded(abortSignal?: AbortSignal): Promise<void> {
644
+ if (!this.encryptionEnabled || this.cryptoInitialized) {
645
+ return;
646
+ }
647
+ throwIfMatrixStartupAborted(abortSignal);
648
+ const { persistIdbToDisk, restoreIdbFromDisk } = await loadMatrixCryptoRuntime();
649
+
650
+ // Restore persisted IndexedDB crypto store before initializing WASM crypto.
651
+ await restoreIdbFromDisk(this.idbSnapshotPath);
652
+ throwIfMatrixStartupAborted(abortSignal);
653
+
654
+ try {
655
+ await this.client.initRustCrypto({
656
+ cryptoDatabasePrefix: this.cryptoDatabasePrefix,
657
+ });
658
+ this.cryptoInitialized = true;
659
+ throwIfMatrixStartupAborted(abortSignal);
660
+
661
+ // Persist the crypto store after successful init (captures fresh keys on first run).
662
+ await persistIdbToDisk({
663
+ snapshotPath: this.idbSnapshotPath,
664
+ databasePrefix: this.cryptoDatabasePrefix,
665
+ });
666
+ throwIfMatrixStartupAborted(abortSignal);
667
+
668
+ // Periodically persist to capture new Olm sessions and room keys.
669
+ this.idbPersistTimer = setInterval(() => {
670
+ persistIdbToDisk({
671
+ snapshotPath: this.idbSnapshotPath,
672
+ databasePrefix: this.cryptoDatabasePrefix,
673
+ }).catch(noop);
674
+ }, MATRIX_IDB_PERSIST_INTERVAL_MS);
675
+ } catch (err) {
676
+ LogService.warn("MatrixClientLite", "Failed to initialize rust crypto:", err);
677
+ }
678
+ }
679
+
680
+ async getUserId(): Promise<string> {
681
+ const fromClient = this.client.getUserId();
682
+ if (fromClient) {
683
+ this.selfUserId = fromClient;
684
+ return fromClient;
685
+ }
686
+ if (this.selfUserId) {
687
+ return this.selfUserId;
688
+ }
689
+ const whoami = (await this.doRequest("GET", "/_lobi/client/v3/account/whoami")) as {
690
+ user_id?: string;
691
+ };
692
+ const resolved = whoami.user_id?.trim();
693
+ if (!resolved) {
694
+ throw new Error("Matrix whoami did not return user_id");
695
+ }
696
+ this.selfUserId = resolved;
697
+ return resolved;
698
+ }
699
+
700
+ async getJoinedRooms(): Promise<string[]> {
701
+ const joined = await this.client.getJoinedRooms();
702
+ return Array.isArray(joined.joined_rooms) ? joined.joined_rooms : [];
703
+ }
704
+
705
+ async getJoinedRoomMembers(roomId: string): Promise<string[]> {
706
+ const members = await this.client.getJoinedRoomMembers(roomId);
707
+ const joined = members?.joined;
708
+ if (!joined || typeof joined !== "object") {
709
+ return [];
710
+ }
711
+ return Object.keys(joined);
712
+ }
713
+
714
+ async getRoomStateEvent(
715
+ roomId: string,
716
+ eventType: string,
717
+ stateKey = "",
718
+ ): Promise<Record<string, unknown>> {
719
+ const state = await this.client.getStateEvent(roomId, eventType, stateKey);
720
+ return (state ?? {}) as Record<string, unknown>;
721
+ }
722
+
723
+ async getAccountData(eventType: string): Promise<Record<string, unknown> | undefined> {
724
+ const event = this.client.getAccountData(eventType as never);
725
+ return (event?.getContent() as Record<string, unknown> | undefined) ?? undefined;
726
+ }
727
+
728
+ async setAccountData(eventType: string, content: Record<string, unknown>): Promise<void> {
729
+ await this.client.setAccountData(eventType as never, content as never);
730
+ await this.refreshDmCache().catch(noop);
731
+ }
732
+
733
+ async resolveRoom(aliasOrRoomId: string): Promise<string | null> {
734
+ if (aliasOrRoomId.startsWith("!")) {
735
+ return aliasOrRoomId;
736
+ }
737
+ if (!aliasOrRoomId.startsWith("#")) {
738
+ return aliasOrRoomId;
739
+ }
740
+ try {
741
+ const resolved = await this.client.getRoomIdForAlias(aliasOrRoomId);
742
+ return resolved.room_id ?? null;
743
+ } catch {
744
+ return null;
745
+ }
746
+ }
747
+
748
+ async createDirectRoom(
749
+ remoteUserId: string,
750
+ opts: { encrypted?: boolean } = {},
751
+ ): Promise<string> {
752
+ const initialState = opts.encrypted
753
+ ? [
754
+ {
755
+ type: "m.room.encryption",
756
+ state_key: "",
757
+ content: {
758
+ algorithm: "m.megolm.v1.aes-sha2",
759
+ },
760
+ },
761
+ ]
762
+ : undefined;
763
+ const result = await this.client.createRoom({
764
+ invite: [remoteUserId],
765
+ is_direct: true,
766
+ preset: Preset.TrustedPrivateChat,
767
+ initial_state: initialState,
768
+ });
769
+ return result.room_id;
770
+ }
771
+
772
+ async sendMessage(roomId: string, content: MessageEventContent): Promise<string> {
773
+ return await this.runSerializedRoomSend(roomId, async () => {
774
+ const sent = await this.client.sendMessage(roomId, content as never);
775
+ return sent.event_id;
776
+ });
777
+ }
778
+
779
+ async sendEvent(
780
+ roomId: string,
781
+ eventType: string,
782
+ content: Record<string, unknown>,
783
+ ): Promise<string> {
784
+ return await this.runSerializedRoomSend(roomId, async () => {
785
+ const sent = await this.client.sendEvent(roomId, eventType as never, content as never);
786
+ return sent.event_id;
787
+ });
788
+ }
789
+
790
+ // Keep outbound room events ordered when multiple plugin paths emit
791
+ // messages/reactions/polls into the same Matrix room concurrently.
792
+ private async runSerializedRoomSend<T>(roomId: string, task: () => Promise<T>): Promise<T> {
793
+ return await this.sendQueue.enqueue(roomId, task);
794
+ }
795
+
796
+ async sendStateEvent(
797
+ roomId: string,
798
+ eventType: string,
799
+ stateKey: string,
800
+ content: Record<string, unknown>,
801
+ ): Promise<string> {
802
+ const sent = await this.client.sendStateEvent(
803
+ roomId,
804
+ eventType as never,
805
+ content as never,
806
+ stateKey,
807
+ );
808
+ return sent.event_id;
809
+ }
810
+
811
+ async redactEvent(roomId: string, eventId: string, reason?: string): Promise<string> {
812
+ const sent = await this.client.redactEvent(
813
+ roomId,
814
+ eventId,
815
+ undefined,
816
+ reason?.trim() ? { reason } : undefined,
817
+ );
818
+ return sent.event_id;
819
+ }
820
+
821
+ async doRequest(
822
+ method: HttpMethod,
823
+ endpoint: string,
824
+ qs?: QueryParams,
825
+ body?: unknown,
826
+ opts?: { allowAbsoluteEndpoint?: boolean },
827
+ ): Promise<unknown> {
828
+ return await this.httpClient.requestJson({
829
+ method,
830
+ endpoint,
831
+ qs,
832
+ body,
833
+ timeoutMs: this.localTimeoutMs,
834
+ allowAbsoluteEndpoint: opts?.allowAbsoluteEndpoint,
835
+ });
836
+ }
837
+
838
+ async getUserProfile(userId: string): Promise<{ displayname?: string; avatar_url?: string }> {
839
+ return await this.client.getProfileInfo(userId);
840
+ }
841
+
842
+ async setDisplayName(displayName: string): Promise<void> {
843
+ await this.client.setDisplayName(displayName);
844
+ }
845
+
846
+ async setAvatarUrl(avatarUrl: string): Promise<void> {
847
+ await this.client.setAvatarUrl(avatarUrl);
848
+ }
849
+
850
+ async joinRoom(roomId: string): Promise<void> {
851
+ await this.client.joinRoom(roomId);
852
+ }
853
+
854
+ mxcToHttp(mxcUrl: string): string | null {
855
+ return this.client.mxcUrlToHttp(mxcUrl, undefined, undefined, undefined, true, false, true);
856
+ }
857
+
858
+ async downloadContent(
859
+ mxcUrl: string,
860
+ opts: {
861
+ allowRemote?: boolean;
862
+ maxBytes?: number;
863
+ readIdleTimeoutMs?: number;
864
+ } = {},
865
+ ): Promise<Buffer> {
866
+ const parsed = parseMxc(mxcUrl);
867
+ if (!parsed) {
868
+ throw new Error(`Invalid Matrix content URI: ${mxcUrl}`);
869
+ }
870
+ const encodedServer = encodeURIComponent(parsed.server);
871
+ const encodedMediaId = encodeURIComponent(parsed.mediaId);
872
+ const request = async (endpoint: string): Promise<Buffer> =>
873
+ await this.httpClient.requestRaw({
874
+ method: "GET",
875
+ endpoint,
876
+ qs: { allow_remote: opts.allowRemote ?? true },
877
+ timeoutMs: this.localTimeoutMs,
878
+ maxBytes: opts.maxBytes,
879
+ readIdleTimeoutMs: opts.readIdleTimeoutMs,
880
+ });
881
+
882
+ const authenticatedEndpoint = `/_lobi/client/v1/media/download/${encodedServer}/${encodedMediaId}`;
883
+ try {
884
+ return await request(authenticatedEndpoint);
885
+ } catch (err) {
886
+ if (!isUnsupportedAuthenticatedMediaEndpointError(err)) {
887
+ throw err;
888
+ }
889
+ }
890
+
891
+ const legacyEndpoint = `/_lobi/media/v3/download/${encodedServer}/${encodedMediaId}`;
892
+ return await request(legacyEndpoint);
893
+ }
894
+
895
+ async uploadContent(file: Buffer, contentType?: string, filename?: string): Promise<string> {
896
+ const uploaded = await this.client.uploadContent(new Uint8Array(file), {
897
+ type: contentType || "application/octet-stream",
898
+ name: filename,
899
+ includeFilename: Boolean(filename),
900
+ });
901
+ return uploaded.content_uri;
902
+ }
903
+
904
+ async getEvent(roomId: string, eventId: string): Promise<Record<string, unknown>> {
905
+ const rawEvent = (await this.client.fetchRoomEvent(roomId, eventId)) as Record<string, unknown>;
906
+ if (rawEvent.type !== "m.room.encrypted") {
907
+ return rawEvent;
908
+ }
909
+
910
+ const mapper = this.client.getEventMapper();
911
+ const event = mapper(rawEvent);
912
+ let decryptedEvent: MatrixEvent | undefined;
913
+ const onDecrypted = (candidate: MatrixEvent) => {
914
+ decryptedEvent = candidate;
915
+ };
916
+ event.once(MatrixEventEvent.Decrypted, onDecrypted);
917
+ try {
918
+ await this.client.decryptEventIfNeeded(event);
919
+ } finally {
920
+ event.off(MatrixEventEvent.Decrypted, onDecrypted);
921
+ }
922
+ return matrixEventToRaw(decryptedEvent ?? event);
923
+ }
924
+
925
+ async getRelations(
926
+ roomId: string,
927
+ eventId: string,
928
+ relationType: string | null,
929
+ eventType?: string | null,
930
+ opts: {
931
+ from?: string;
932
+ } = {},
933
+ ): Promise<MatrixRelationsPage> {
934
+ const result = await this.client.relations(roomId, eventId, relationType, eventType, opts);
935
+ return {
936
+ originalEvent: result.originalEvent ? matrixEventToRaw(result.originalEvent) : null,
937
+ events: result.events.map((event) => matrixEventToRaw(event)),
938
+ nextBatch: result.nextBatch ?? null,
939
+ prevBatch: result.prevBatch ?? null,
940
+ };
941
+ }
942
+
943
+ async hydrateEvents(
944
+ roomId: string,
945
+ events: Array<Record<string, unknown>>,
946
+ ): Promise<MatrixRawEvent[]> {
947
+ if (events.length === 0) {
948
+ return [];
949
+ }
950
+
951
+ const mapper = this.client.getEventMapper();
952
+ const mappedEvents = events.map((event) =>
953
+ mapper({
954
+ room_id: roomId,
955
+ ...event,
956
+ }),
957
+ );
958
+ await Promise.all(mappedEvents.map((event) => this.client.decryptEventIfNeeded(event)));
959
+ return mappedEvents.map((event) => matrixEventToRaw(event));
960
+ }
961
+
962
+ async setTyping(roomId: string, typing: boolean, timeoutMs: number): Promise<void> {
963
+ await this.client.sendTyping(roomId, typing, timeoutMs);
964
+ }
965
+
966
+ async sendReadReceipt(roomId: string, eventId: string): Promise<void> {
967
+ await this.httpClient.requestJson({
968
+ method: "POST",
969
+ endpoint: `/_lobi/client/v3/rooms/${encodeURIComponent(roomId)}/receipt/m.read/${encodeURIComponent(
970
+ eventId,
971
+ )}`,
972
+ body: {},
973
+ timeoutMs: this.localTimeoutMs,
974
+ });
975
+ }
976
+
977
+ async getRoomKeyBackupStatus(): Promise<MatrixRoomKeyBackupStatus> {
978
+ if (!this.encryptionEnabled) {
979
+ return {
980
+ serverVersion: null,
981
+ activeVersion: null,
982
+ trusted: null,
983
+ matchesDecryptionKey: null,
984
+ decryptionKeyCached: null,
985
+ keyLoadAttempted: false,
986
+ keyLoadError: null,
987
+ };
988
+ }
989
+
990
+ const crypto = this.client.getCrypto() as MatrixCryptoBootstrapApi | undefined;
991
+ const serverVersionFallback = await this.resolveRoomKeyBackupVersion();
992
+ if (!crypto) {
993
+ return {
994
+ serverVersion: serverVersionFallback,
995
+ activeVersion: null,
996
+ trusted: null,
997
+ matchesDecryptionKey: null,
998
+ decryptionKeyCached: null,
999
+ keyLoadAttempted: false,
1000
+ keyLoadError: null,
1001
+ };
1002
+ }
1003
+
1004
+ let { activeVersion, decryptionKeyCached } = await this.resolveRoomKeyBackupLocalState(crypto);
1005
+ let { serverVersion, trusted, matchesDecryptionKey } =
1006
+ await this.resolveRoomKeyBackupTrustState(crypto, serverVersionFallback);
1007
+ const shouldLoadBackupKey =
1008
+ Boolean(serverVersion) && (decryptionKeyCached === false || matchesDecryptionKey === false);
1009
+ const shouldActivateBackup = Boolean(serverVersion) && !activeVersion;
1010
+ let keyLoadAttempted = false;
1011
+ let keyLoadError: string | null = null;
1012
+ if (serverVersion && (shouldLoadBackupKey || shouldActivateBackup)) {
1013
+ if (shouldLoadBackupKey) {
1014
+ if (
1015
+ typeof crypto.loadSessionBackupPrivateKeyFromSecretStorage ===
1016
+ "function" /* pragma: allowlist secret */
1017
+ ) {
1018
+ keyLoadAttempted = true;
1019
+ try {
1020
+ await crypto.loadSessionBackupPrivateKeyFromSecretStorage(); // pragma: allowlist secret
1021
+ } catch (err) {
1022
+ keyLoadError = formatMatrixErrorMessage(err);
1023
+ }
1024
+ } else {
1025
+ keyLoadError =
1026
+ "Matrix crypto backend does not support loading backup keys from secret storage";
1027
+ }
1028
+ }
1029
+ if (!keyLoadError) {
1030
+ await this.enableTrustedRoomKeyBackupIfPossible(crypto);
1031
+ }
1032
+ ({ activeVersion, decryptionKeyCached } = await this.resolveRoomKeyBackupLocalState(crypto));
1033
+ ({ serverVersion, trusted, matchesDecryptionKey } = await this.resolveRoomKeyBackupTrustState(
1034
+ crypto,
1035
+ serverVersion,
1036
+ ));
1037
+ }
1038
+
1039
+ return {
1040
+ serverVersion,
1041
+ activeVersion,
1042
+ trusted,
1043
+ matchesDecryptionKey,
1044
+ decryptionKeyCached,
1045
+ keyLoadAttempted,
1046
+ keyLoadError,
1047
+ };
1048
+ }
1049
+
1050
+ async getOwnDeviceVerificationStatus(): Promise<MatrixOwnDeviceVerificationStatus> {
1051
+ const recoveryKey = this.recoveryKeyStore.getRecoveryKeySummary();
1052
+ const userId = this.client.getUserId() ?? this.selfUserId ?? null;
1053
+ const deviceId = this.client.getDeviceId()?.trim() || null;
1054
+ const backup = await this.getRoomKeyBackupStatus();
1055
+
1056
+ if (!this.encryptionEnabled) {
1057
+ return {
1058
+ encryptionEnabled: false,
1059
+ userId,
1060
+ deviceId,
1061
+ verified: false,
1062
+ localVerified: false,
1063
+ crossSigningVerified: false,
1064
+ signedByOwner: false,
1065
+ recoveryKeyStored: Boolean(recoveryKey),
1066
+ recoveryKeyCreatedAt: recoveryKey?.createdAt ?? null,
1067
+ recoveryKeyId: recoveryKey?.keyId ?? null,
1068
+ backupVersion: backup.serverVersion,
1069
+ backup,
1070
+ };
1071
+ }
1072
+
1073
+ const crypto = this.client.getCrypto() as MatrixCryptoBootstrapApi | undefined;
1074
+ let deviceStatus: MatrixDeviceVerificationStatusLike | null = null;
1075
+ if (crypto && userId && deviceId && typeof crypto.getDeviceVerificationStatus === "function") {
1076
+ deviceStatus = await crypto.getDeviceVerificationStatus(userId, deviceId).catch(() => null);
1077
+ }
1078
+ const { isMatrixDeviceOwnerVerified } = await loadMatrixCryptoRuntime();
1079
+
1080
+ return {
1081
+ encryptionEnabled: true,
1082
+ userId,
1083
+ deviceId,
1084
+ verified: isMatrixDeviceOwnerVerified(deviceStatus),
1085
+ localVerified: deviceStatus?.localVerified === true,
1086
+ crossSigningVerified: deviceStatus?.crossSigningVerified === true,
1087
+ signedByOwner: deviceStatus?.signedByOwner === true,
1088
+ recoveryKeyStored: Boolean(recoveryKey),
1089
+ recoveryKeyCreatedAt: recoveryKey?.createdAt ?? null,
1090
+ recoveryKeyId: recoveryKey?.keyId ?? null,
1091
+ backupVersion: backup.serverVersion,
1092
+ backup,
1093
+ };
1094
+ }
1095
+
1096
+ async verifyWithRecoveryKey(
1097
+ rawRecoveryKey: string,
1098
+ ): Promise<MatrixRecoveryKeyVerificationResult> {
1099
+ const fail = async (error: string): Promise<MatrixRecoveryKeyVerificationResult> => ({
1100
+ success: false,
1101
+ error,
1102
+ ...(await this.getOwnDeviceVerificationStatus()),
1103
+ });
1104
+
1105
+ if (!this.encryptionEnabled) {
1106
+ return await fail("Matrix encryption is disabled for this client");
1107
+ }
1108
+
1109
+ await this.ensureStartedForCryptoControlPlane();
1110
+ await this.ensureCryptoSupportInitialized();
1111
+ const crypto = this.client.getCrypto() as MatrixCryptoBootstrapApi | undefined;
1112
+ if (!crypto) {
1113
+ return await fail("Matrix crypto is not available (start client with encryption enabled)");
1114
+ }
1115
+
1116
+ const trimmedRecoveryKey = rawRecoveryKey.trim();
1117
+ if (!trimmedRecoveryKey) {
1118
+ return await fail("Matrix recovery key is required");
1119
+ }
1120
+
1121
+ try {
1122
+ this.recoveryKeyStore.stageEncodedRecoveryKey({
1123
+ encodedPrivateKey: trimmedRecoveryKey,
1124
+ keyId: await this.resolveDefaultSecretStorageKeyId(crypto),
1125
+ });
1126
+ } catch (err) {
1127
+ return await fail(formatMatrixErrorMessage(err));
1128
+ }
1129
+
1130
+ try {
1131
+ const cryptoBootstrapper = this.cryptoBootstrapper;
1132
+ if (!cryptoBootstrapper) {
1133
+ return await fail("Matrix crypto bootstrapper is not available");
1134
+ }
1135
+ await cryptoBootstrapper.bootstrap(crypto, {
1136
+ allowAutomaticCrossSigningReset: false,
1137
+ });
1138
+ await this.enableTrustedRoomKeyBackupIfPossible(crypto);
1139
+ const status = await this.getOwnDeviceVerificationStatus();
1140
+ if (!status.verified) {
1141
+ this.recoveryKeyStore.discardStagedRecoveryKey();
1142
+ return {
1143
+ success: false,
1144
+ error:
1145
+ "Matrix device is still not verified by its owner after applying the recovery key. Ensure cross-signing is available and the device is signed.",
1146
+ ...status,
1147
+ };
1148
+ }
1149
+ const backupError = resolveMatrixRoomKeyBackupReadinessError(status.backup, {
1150
+ requireServerBackup: false,
1151
+ });
1152
+ if (backupError) {
1153
+ this.recoveryKeyStore.discardStagedRecoveryKey();
1154
+ return {
1155
+ success: false,
1156
+ error: backupError,
1157
+ ...status,
1158
+ };
1159
+ }
1160
+
1161
+ this.recoveryKeyStore.commitStagedRecoveryKey({
1162
+ keyId: await this.resolveDefaultSecretStorageKeyId(crypto),
1163
+ });
1164
+ const committedStatus = await this.getOwnDeviceVerificationStatus();
1165
+ return {
1166
+ success: true,
1167
+ verifiedAt: new Date().toISOString(),
1168
+ ...committedStatus,
1169
+ };
1170
+ } catch (err) {
1171
+ this.recoveryKeyStore.discardStagedRecoveryKey();
1172
+ return await fail(formatMatrixErrorMessage(err));
1173
+ }
1174
+ }
1175
+
1176
+ async restoreRoomKeyBackup(
1177
+ params: {
1178
+ recoveryKey?: string;
1179
+ } = {},
1180
+ ): Promise<MatrixRoomKeyBackupRestoreResult> {
1181
+ let loadedFromSecretStorage = false;
1182
+ const fail = async (error: string): Promise<MatrixRoomKeyBackupRestoreResult> => {
1183
+ const backup = await this.getRoomKeyBackupStatus();
1184
+ return {
1185
+ success: false,
1186
+ error,
1187
+ backupVersion: backup.serverVersion,
1188
+ imported: 0,
1189
+ total: 0,
1190
+ loadedFromSecretStorage,
1191
+ backup,
1192
+ };
1193
+ };
1194
+
1195
+ if (!this.encryptionEnabled) {
1196
+ return await fail("Matrix encryption is disabled for this client");
1197
+ }
1198
+
1199
+ await this.ensureStartedForCryptoControlPlane();
1200
+ const crypto = this.client.getCrypto() as MatrixCryptoBootstrapApi | undefined;
1201
+ if (!crypto) {
1202
+ return await fail("Matrix crypto is not available (start client with encryption enabled)");
1203
+ }
1204
+
1205
+ try {
1206
+ const rawRecoveryKey = params.recoveryKey?.trim();
1207
+ if (rawRecoveryKey) {
1208
+ this.recoveryKeyStore.stageEncodedRecoveryKey({
1209
+ encodedPrivateKey: rawRecoveryKey,
1210
+ keyId: await this.resolveDefaultSecretStorageKeyId(crypto),
1211
+ });
1212
+ }
1213
+
1214
+ const backup = await this.getRoomKeyBackupStatus();
1215
+ loadedFromSecretStorage = backup.keyLoadAttempted && !backup.keyLoadError;
1216
+ const backupError = resolveMatrixRoomKeyBackupReadinessError(backup, {
1217
+ requireServerBackup: true,
1218
+ });
1219
+ if (backupError) {
1220
+ this.recoveryKeyStore.discardStagedRecoveryKey();
1221
+ return await fail(backupError);
1222
+ }
1223
+ if (typeof crypto.restoreKeyBackup !== "function") {
1224
+ this.recoveryKeyStore.discardStagedRecoveryKey();
1225
+ return await fail("Matrix crypto backend does not support full key backup restore");
1226
+ }
1227
+
1228
+ const restore = await crypto.restoreKeyBackup();
1229
+ if (rawRecoveryKey) {
1230
+ this.recoveryKeyStore.commitStagedRecoveryKey({
1231
+ keyId: await this.resolveDefaultSecretStorageKeyId(crypto),
1232
+ });
1233
+ }
1234
+ const finalBackup = await this.getRoomKeyBackupStatus();
1235
+ return {
1236
+ success: true,
1237
+ backupVersion: backup.serverVersion,
1238
+ imported: typeof restore.imported === "number" ? restore.imported : 0,
1239
+ total: typeof restore.total === "number" ? restore.total : 0,
1240
+ loadedFromSecretStorage,
1241
+ restoredAt: new Date().toISOString(),
1242
+ backup: finalBackup,
1243
+ };
1244
+ } catch (err) {
1245
+ this.recoveryKeyStore.discardStagedRecoveryKey();
1246
+ return await fail(formatMatrixErrorMessage(err));
1247
+ }
1248
+ }
1249
+
1250
+ async resetRoomKeyBackup(): Promise<MatrixRoomKeyBackupResetResult> {
1251
+ let previousVersion: string | null = null;
1252
+ let deletedVersion: string | null = null;
1253
+ const fail = async (error: string): Promise<MatrixRoomKeyBackupResetResult> => {
1254
+ const backup = await this.getRoomKeyBackupStatus();
1255
+ return {
1256
+ success: false,
1257
+ error,
1258
+ previousVersion,
1259
+ deletedVersion,
1260
+ createdVersion: backup.serverVersion,
1261
+ backup,
1262
+ };
1263
+ };
1264
+
1265
+ if (!this.encryptionEnabled) {
1266
+ return await fail("Matrix encryption is disabled for this client");
1267
+ }
1268
+
1269
+ await this.ensureStartedForCryptoControlPlane();
1270
+ const crypto = this.client.getCrypto() as MatrixCryptoBootstrapApi | undefined;
1271
+ if (!crypto) {
1272
+ return await fail("Matrix crypto is not available (start client with encryption enabled)");
1273
+ }
1274
+
1275
+ previousVersion = await this.resolveRoomKeyBackupVersion();
1276
+
1277
+ // Probe backup-secret access directly before reset. This keeps the reset preflight
1278
+ // focused on durable secret-storage health instead of the broader backup status flow,
1279
+ // and still catches stale SSSS/recovery-key state even when the server backup is gone.
1280
+ const forceNewSecretStorage =
1281
+ await this.shouldForceSecretStorageRecreationForBackupReset(crypto);
1282
+
1283
+ try {
1284
+ if (previousVersion) {
1285
+ try {
1286
+ await this.doRequest(
1287
+ "DELETE",
1288
+ `/_lobi/client/v3/room_keys/version/${encodeURIComponent(previousVersion)}`,
1289
+ );
1290
+ } catch (err) {
1291
+ if (!isMatrixNotFoundError(err)) {
1292
+ throw err;
1293
+ }
1294
+ }
1295
+ deletedVersion = previousVersion;
1296
+ }
1297
+
1298
+ await this.recoveryKeyStore.bootstrapSecretStorageWithRecoveryKey(crypto, {
1299
+ setupNewKeyBackup: true,
1300
+ // Force SSSS recreation when the existing SSSS key is broken (bad MAC), so
1301
+ // the new backup key is written into a fresh SSSS consistent with recovery_key.json.
1302
+ forceNewSecretStorage,
1303
+ // Also allow recreation if bootstrapSecretStorage itself surfaces a repairable
1304
+ // error (e.g. bad MAC from a different SSSS entry).
1305
+ allowSecretStorageRecreateWithoutRecoveryKey: true,
1306
+ });
1307
+ await this.enableTrustedRoomKeyBackupIfPossible(crypto);
1308
+
1309
+ const backup = await this.getRoomKeyBackupStatus();
1310
+ const createdVersion = backup.serverVersion;
1311
+ if (!createdVersion) {
1312
+ return await fail("Matrix room key backup is still missing after reset.");
1313
+ }
1314
+ if (backup.activeVersion !== createdVersion) {
1315
+ return await fail(
1316
+ "Matrix room key backup was recreated on the server but is not active on this device.",
1317
+ );
1318
+ }
1319
+ if (backup.decryptionKeyCached === false) {
1320
+ return await fail(
1321
+ "Matrix room key backup was recreated but its decryption key is not cached on this device.",
1322
+ );
1323
+ }
1324
+ if (backup.matchesDecryptionKey === false) {
1325
+ return await fail(
1326
+ "Matrix room key backup was recreated but this device does not have the matching backup decryption key.",
1327
+ );
1328
+ }
1329
+ if (backup.trusted === false) {
1330
+ return await fail(
1331
+ "Matrix room key backup was recreated but is not trusted on this device.",
1332
+ );
1333
+ }
1334
+
1335
+ return {
1336
+ success: true,
1337
+ previousVersion,
1338
+ deletedVersion,
1339
+ createdVersion,
1340
+ resetAt: new Date().toISOString(),
1341
+ backup,
1342
+ };
1343
+ } catch (err) {
1344
+ return await fail(formatMatrixErrorMessage(err));
1345
+ }
1346
+ }
1347
+
1348
+ async getOwnCrossSigningPublicationStatus(): Promise<MatrixOwnCrossSigningPublicationStatus> {
1349
+ const userId = this.client.getUserId() ?? this.selfUserId ?? null;
1350
+ if (!userId) {
1351
+ return {
1352
+ userId: null,
1353
+ masterKeyPublished: false,
1354
+ selfSigningKeyPublished: false,
1355
+ userSigningKeyPublished: false,
1356
+ published: false,
1357
+ };
1358
+ }
1359
+
1360
+ try {
1361
+ const response = (await this.doRequest("POST", "/_lobi/client/v3/keys/query", undefined, {
1362
+ device_keys: { [userId]: [] as string[] },
1363
+ })) as {
1364
+ master_keys?: Record<string, unknown>;
1365
+ self_signing_keys?: Record<string, unknown>;
1366
+ user_signing_keys?: Record<string, unknown>;
1367
+ };
1368
+ const masterKeyPublished = Boolean(response.master_keys?.[userId]);
1369
+ const selfSigningKeyPublished = Boolean(response.self_signing_keys?.[userId]);
1370
+ const userSigningKeyPublished = Boolean(response.user_signing_keys?.[userId]);
1371
+ return {
1372
+ userId,
1373
+ masterKeyPublished,
1374
+ selfSigningKeyPublished,
1375
+ userSigningKeyPublished,
1376
+ published: masterKeyPublished && selfSigningKeyPublished && userSigningKeyPublished,
1377
+ };
1378
+ } catch {
1379
+ return {
1380
+ userId,
1381
+ masterKeyPublished: false,
1382
+ selfSigningKeyPublished: false,
1383
+ userSigningKeyPublished: false,
1384
+ published: false,
1385
+ };
1386
+ }
1387
+ }
1388
+
1389
+ async bootstrapOwnDeviceVerification(params?: {
1390
+ recoveryKey?: string;
1391
+ forceResetCrossSigning?: boolean;
1392
+ }): Promise<MatrixVerificationBootstrapResult> {
1393
+ const pendingVerifications = async (): Promise<number> =>
1394
+ this.crypto ? (await this.crypto.listVerifications()).length : 0;
1395
+ if (!this.encryptionEnabled) {
1396
+ return {
1397
+ success: false,
1398
+ error: "Matrix encryption is disabled for this client",
1399
+ verification: await this.getOwnDeviceVerificationStatus(),
1400
+ crossSigning: await this.getOwnCrossSigningPublicationStatus(),
1401
+ pendingVerifications: await pendingVerifications(),
1402
+ cryptoBootstrap: null,
1403
+ };
1404
+ }
1405
+
1406
+ let bootstrapError: string | undefined;
1407
+ let bootstrapSummary: MatrixCryptoBootstrapResult | null = null;
1408
+ try {
1409
+ await this.ensureStartedForCryptoControlPlane();
1410
+ await this.ensureCryptoSupportInitialized();
1411
+ const crypto = this.client.getCrypto() as MatrixCryptoBootstrapApi | undefined;
1412
+ if (!crypto) {
1413
+ throw new Error("Matrix crypto is not available (start client with encryption enabled)");
1414
+ }
1415
+
1416
+ const rawRecoveryKey = params?.recoveryKey?.trim();
1417
+ if (rawRecoveryKey) {
1418
+ this.recoveryKeyStore.stageEncodedRecoveryKey({
1419
+ encodedPrivateKey: rawRecoveryKey,
1420
+ keyId: await this.resolveDefaultSecretStorageKeyId(crypto),
1421
+ });
1422
+ }
1423
+
1424
+ const cryptoBootstrapper = this.cryptoBootstrapper;
1425
+ if (!cryptoBootstrapper) {
1426
+ throw new Error("Matrix crypto bootstrapper is not available");
1427
+ }
1428
+ bootstrapSummary = await cryptoBootstrapper.bootstrap(
1429
+ crypto,
1430
+ createMatrixExplicitBootstrapOptions(params),
1431
+ );
1432
+ await this.ensureRoomKeyBackupEnabled(crypto);
1433
+ } catch (err) {
1434
+ this.recoveryKeyStore.discardStagedRecoveryKey();
1435
+ bootstrapError = formatMatrixErrorMessage(err);
1436
+ }
1437
+
1438
+ const verification = await this.getOwnDeviceVerificationStatus();
1439
+ const crossSigning = await this.getOwnCrossSigningPublicationStatus();
1440
+ const verificationError =
1441
+ verification.verified && crossSigning.published
1442
+ ? null
1443
+ : (bootstrapError ??
1444
+ "Matrix verification bootstrap did not produce a device verified by its owner with published cross-signing keys");
1445
+ const backupError =
1446
+ verificationError === null
1447
+ ? resolveMatrixRoomKeyBackupReadinessError(verification.backup, {
1448
+ requireServerBackup: true,
1449
+ })
1450
+ : null;
1451
+ const success = verificationError === null && backupError === null;
1452
+ if (success) {
1453
+ this.recoveryKeyStore.commitStagedRecoveryKey({
1454
+ keyId: await this.resolveDefaultSecretStorageKeyId(
1455
+ this.client.getCrypto() as MatrixCryptoBootstrapApi | undefined,
1456
+ ),
1457
+ });
1458
+ } else {
1459
+ this.recoveryKeyStore.discardStagedRecoveryKey();
1460
+ }
1461
+ const error = success ? undefined : (backupError ?? verificationError ?? undefined);
1462
+ return {
1463
+ success,
1464
+ error,
1465
+ verification: success ? await this.getOwnDeviceVerificationStatus() : verification,
1466
+ crossSigning,
1467
+ pendingVerifications: await pendingVerifications(),
1468
+ cryptoBootstrap: bootstrapSummary,
1469
+ };
1470
+ }
1471
+
1472
+ async listOwnDevices(): Promise<MatrixOwnDeviceInfo[]> {
1473
+ const currentDeviceId = this.client.getDeviceId()?.trim() || null;
1474
+ const devices = await this.client.getDevices();
1475
+ const entries = Array.isArray(devices?.devices) ? devices.devices : [];
1476
+ return entries.map((device) => ({
1477
+ deviceId: device.device_id,
1478
+ displayName: device.display_name?.trim() || null,
1479
+ lastSeenIp: device.last_seen_ip?.trim() || null,
1480
+ lastSeenTs:
1481
+ typeof device.last_seen_ts === "number" && Number.isFinite(device.last_seen_ts)
1482
+ ? device.last_seen_ts
1483
+ : null,
1484
+ current: currentDeviceId !== null && device.device_id === currentDeviceId,
1485
+ }));
1486
+ }
1487
+
1488
+ async deleteOwnDevices(deviceIds: string[]): Promise<MatrixOwnDeviceDeleteResult> {
1489
+ const uniqueDeviceIds = [...new Set(deviceIds.map((value) => value.trim()).filter(Boolean))];
1490
+ const currentDeviceId = this.client.getDeviceId()?.trim() || null;
1491
+ const protectedDeviceIds = uniqueDeviceIds.filter((deviceId) => deviceId === currentDeviceId);
1492
+ if (protectedDeviceIds.length > 0) {
1493
+ throw new Error(`Refusing to delete the current Matrix device: ${protectedDeviceIds[0]}`);
1494
+ }
1495
+
1496
+ const deleteWithAuth = async (authData?: Record<string, unknown>): Promise<void> => {
1497
+ await this.client.deleteMultipleDevices(uniqueDeviceIds, authData as never);
1498
+ };
1499
+
1500
+ if (uniqueDeviceIds.length > 0) {
1501
+ try {
1502
+ await deleteWithAuth();
1503
+ } catch (err) {
1504
+ const session =
1505
+ err &&
1506
+ typeof err === "object" &&
1507
+ "data" in err &&
1508
+ err.data &&
1509
+ typeof err.data === "object" &&
1510
+ "session" in err.data &&
1511
+ typeof err.data.session === "string"
1512
+ ? err.data.session
1513
+ : null;
1514
+ const userId = await this.getUserId().catch(() => this.selfUserId);
1515
+ if (!session || !userId || !this.password?.trim()) {
1516
+ throw err;
1517
+ }
1518
+ await deleteWithAuth({
1519
+ type: "m.login.password",
1520
+ session,
1521
+ identifier: { type: "m.id.user", user: userId },
1522
+ password: this.password,
1523
+ });
1524
+ }
1525
+ }
1526
+
1527
+ return {
1528
+ currentDeviceId,
1529
+ deletedDeviceIds: uniqueDeviceIds,
1530
+ remainingDevices: await this.listOwnDevices(),
1531
+ };
1532
+ }
1533
+
1534
+ private async resolveActiveRoomKeyBackupVersion(
1535
+ crypto: MatrixCryptoBootstrapApi,
1536
+ ): Promise<string | null> {
1537
+ if (typeof crypto.getActiveSessionBackupVersion !== "function") {
1538
+ return null;
1539
+ }
1540
+ const version = await crypto.getActiveSessionBackupVersion().catch(() => null);
1541
+ return normalizeOptionalString(version);
1542
+ }
1543
+
1544
+ private async resolveCachedRoomKeyBackupDecryptionKey(
1545
+ crypto: MatrixCryptoBootstrapApi,
1546
+ ): Promise<boolean | null> {
1547
+ const getSessionBackupPrivateKey = crypto.getSessionBackupPrivateKey; // pragma: allowlist secret
1548
+ if (typeof getSessionBackupPrivateKey !== "function") {
1549
+ return null;
1550
+ }
1551
+ const key = await getSessionBackupPrivateKey.call(crypto).catch(() => null); // pragma: allowlist secret
1552
+ return key ? key.length > 0 : false;
1553
+ }
1554
+
1555
+ private async resolveRoomKeyBackupLocalState(
1556
+ crypto: MatrixCryptoBootstrapApi,
1557
+ ): Promise<{ activeVersion: string | null; decryptionKeyCached: boolean | null }> {
1558
+ const [activeVersion, decryptionKeyCached] = await Promise.all([
1559
+ this.resolveActiveRoomKeyBackupVersion(crypto),
1560
+ this.resolveCachedRoomKeyBackupDecryptionKey(crypto),
1561
+ ]);
1562
+ return { activeVersion, decryptionKeyCached };
1563
+ }
1564
+
1565
+ private async shouldForceSecretStorageRecreationForBackupReset(
1566
+ crypto: MatrixCryptoBootstrapApi,
1567
+ ): Promise<boolean> {
1568
+ const decryptionKeyCached = await this.resolveCachedRoomKeyBackupDecryptionKey(crypto);
1569
+ if (decryptionKeyCached !== false) {
1570
+ return false;
1571
+ }
1572
+ const loadSessionBackupPrivateKeyFromSecretStorage =
1573
+ crypto.loadSessionBackupPrivateKeyFromSecretStorage; // pragma: allowlist secret
1574
+ if (typeof loadSessionBackupPrivateKeyFromSecretStorage !== "function") {
1575
+ return false;
1576
+ }
1577
+ try {
1578
+ await loadSessionBackupPrivateKeyFromSecretStorage.call(crypto); // pragma: allowlist secret
1579
+ return false;
1580
+ } catch (err) {
1581
+ return isRepairableSecretStorageAccessError(err);
1582
+ }
1583
+ }
1584
+
1585
+ private async resolveRoomKeyBackupTrustState(
1586
+ crypto: MatrixCryptoBootstrapApi,
1587
+ fallbackVersion: string | null,
1588
+ ): Promise<{
1589
+ serverVersion: string | null;
1590
+ trusted: boolean | null;
1591
+ matchesDecryptionKey: boolean | null;
1592
+ }> {
1593
+ let serverVersion = fallbackVersion;
1594
+ let trusted: boolean | null = null;
1595
+ let matchesDecryptionKey: boolean | null = null;
1596
+ if (typeof crypto.getKeyBackupInfo === "function") {
1597
+ const info = await crypto.getKeyBackupInfo().catch(() => null);
1598
+ serverVersion = normalizeOptionalString(info?.version) ?? serverVersion;
1599
+ if (info && typeof crypto.isKeyBackupTrusted === "function") {
1600
+ const trustInfo = await crypto.isKeyBackupTrusted(info).catch(() => null);
1601
+ trusted = typeof trustInfo?.trusted === "boolean" ? trustInfo.trusted : null;
1602
+ matchesDecryptionKey =
1603
+ typeof trustInfo?.matchesDecryptionKey === "boolean"
1604
+ ? trustInfo.matchesDecryptionKey
1605
+ : null;
1606
+ }
1607
+ }
1608
+ return { serverVersion, trusted, matchesDecryptionKey };
1609
+ }
1610
+
1611
+ private async resolveDefaultSecretStorageKeyId(
1612
+ crypto: MatrixCryptoBootstrapApi | undefined,
1613
+ ): Promise<string | null | undefined> {
1614
+ const getSecretStorageStatus = crypto?.getSecretStorageStatus; // pragma: allowlist secret
1615
+ if (typeof getSecretStorageStatus !== "function") {
1616
+ return undefined;
1617
+ }
1618
+ const status = await getSecretStorageStatus.call(crypto).catch(() => null); // pragma: allowlist secret
1619
+ return status?.defaultKeyId;
1620
+ }
1621
+
1622
+ private async resolveRoomKeyBackupVersion(): Promise<string | null> {
1623
+ try {
1624
+ const response = (await this.doRequest("GET", "/_lobi/client/v3/room_keys/version")) as {
1625
+ version?: string;
1626
+ };
1627
+ return normalizeOptionalString(response.version);
1628
+ } catch {
1629
+ return null;
1630
+ }
1631
+ }
1632
+
1633
+ private async enableTrustedRoomKeyBackupIfPossible(
1634
+ crypto: MatrixCryptoBootstrapApi,
1635
+ ): Promise<void> {
1636
+ if (typeof crypto.checkKeyBackupAndEnable !== "function") {
1637
+ return;
1638
+ }
1639
+ await crypto.checkKeyBackupAndEnable();
1640
+ }
1641
+
1642
+ private async ensureRoomKeyBackupEnabled(crypto: MatrixCryptoBootstrapApi): Promise<void> {
1643
+ const existingVersion = await this.resolveRoomKeyBackupVersion();
1644
+ if (existingVersion) {
1645
+ return;
1646
+ }
1647
+ LogService.info(
1648
+ "MatrixClientLite",
1649
+ "No room key backup version found on server, creating one via secret storage bootstrap",
1650
+ );
1651
+ await this.recoveryKeyStore.bootstrapSecretStorageWithRecoveryKey(crypto, {
1652
+ setupNewKeyBackup: true,
1653
+ });
1654
+ const createdVersion = await this.resolveRoomKeyBackupVersion();
1655
+ if (!createdVersion) {
1656
+ throw new Error("Matrix room key backup is still missing after bootstrap");
1657
+ }
1658
+ LogService.info("MatrixClientLite", `Room key backup enabled (version ${createdVersion})`);
1659
+ }
1660
+
1661
+ private registerBridge(): void {
1662
+ if (this.bridgeRegistered || !this.decryptBridge) {
1663
+ return;
1664
+ }
1665
+ this.bridgeRegistered = true;
1666
+ const decryptBridge = this.decryptBridge;
1667
+
1668
+ this.client.on(ClientEvent.Event, (event: MatrixEvent) => {
1669
+ const roomId = event.getRoomId();
1670
+ if (!roomId) {
1671
+ return;
1672
+ }
1673
+
1674
+ const raw = matrixEventToRaw(event);
1675
+ const isEncryptedEvent = raw.type === "m.room.encrypted";
1676
+ this.emitter.emit("room.event", roomId, raw);
1677
+ if (isEncryptedEvent) {
1678
+ this.emitter.emit("room.encrypted_event", roomId, raw);
1679
+ } else {
1680
+ if (decryptBridge.shouldEmitUnencryptedMessage(roomId, raw.event_id)) {
1681
+ this.emitter.emit("room.message", roomId, raw);
1682
+ }
1683
+ }
1684
+
1685
+ const stateKey = raw.state_key ?? "";
1686
+ const selfUserId = this.client.getUserId() ?? this.selfUserId ?? "";
1687
+ const membership =
1688
+ raw.type === "m.room.member"
1689
+ ? (raw.content as { membership?: string }).membership
1690
+ : undefined;
1691
+ if (stateKey && selfUserId && stateKey === selfUserId) {
1692
+ if (membership === "invite") {
1693
+ this.emitter.emit("room.invite", roomId, raw);
1694
+ } else if (membership === "join") {
1695
+ this.emitter.emit("room.join", roomId, raw);
1696
+ }
1697
+ }
1698
+
1699
+ if (isEncryptedEvent) {
1700
+ decryptBridge.attachEncryptedEvent(event, roomId);
1701
+ }
1702
+ });
1703
+
1704
+ // Some SDK invite transitions are surfaced as room lifecycle events instead of raw timeline events.
1705
+ this.client.on(ClientEvent.Room, (room) => {
1706
+ this.emitMembershipForRoom(room);
1707
+ });
1708
+ this.client.on(
1709
+ ClientEvent.Sync,
1710
+ (state: MatrixSyncState, prevState: string | null, data?: unknown) => {
1711
+ this.currentSyncState = state;
1712
+ const error =
1713
+ data && typeof data === "object" && "error" in data
1714
+ ? (data as { error?: unknown }).error
1715
+ : undefined;
1716
+ this.emitter.emit("sync.state", state, prevState, error);
1717
+ },
1718
+ );
1719
+ this.client.on(ClientEvent.SyncUnexpectedError, (error: Error) => {
1720
+ this.emitter.emit("sync.unexpected_error", error);
1721
+ });
1722
+ }
1723
+
1724
+ private emitMembershipForRoom(room: unknown): void {
1725
+ const roomObj = room as {
1726
+ roomId?: string;
1727
+ getMyMembership?: () => string | null | undefined;
1728
+ selfMembership?: string | null | undefined;
1729
+ };
1730
+ const roomId = roomObj.roomId?.trim();
1731
+ if (!roomId) {
1732
+ return;
1733
+ }
1734
+ const membership = roomObj.getMyMembership?.() ?? roomObj.selfMembership ?? undefined;
1735
+ const selfUserId = this.client.getUserId() ?? this.selfUserId ?? "";
1736
+ if (!selfUserId) {
1737
+ return;
1738
+ }
1739
+ const raw: MatrixRawEvent = {
1740
+ event_id: `$membership-${roomId}-${Date.now()}`,
1741
+ type: "m.room.member",
1742
+ sender: selfUserId,
1743
+ state_key: selfUserId,
1744
+ content: { membership },
1745
+ origin_server_ts: Date.now(),
1746
+ unsigned: { age: 0 },
1747
+ };
1748
+ if (membership === "invite") {
1749
+ this.emitter.emit("room.invite", roomId, raw);
1750
+ return;
1751
+ }
1752
+ if (membership === "join") {
1753
+ this.emitter.emit("room.join", roomId, raw);
1754
+ }
1755
+ }
1756
+
1757
+ private emitOutstandingInviteEvents(): void {
1758
+ const listRooms = (this.client as { getRooms?: () => unknown[] }).getRooms;
1759
+ if (typeof listRooms !== "function") {
1760
+ return;
1761
+ }
1762
+ const rooms = listRooms.call(this.client);
1763
+ if (!Array.isArray(rooms)) {
1764
+ return;
1765
+ }
1766
+ for (const room of rooms) {
1767
+ this.emitMembershipForRoom(room);
1768
+ }
1769
+ }
1770
+
1771
+ private async refreshDmCache(): Promise<boolean> {
1772
+ const direct = await this.getAccountData("m.direct");
1773
+ this.dmRoomIds.clear();
1774
+ if (!direct || typeof direct !== "object") {
1775
+ return false;
1776
+ }
1777
+ for (const value of Object.values(direct)) {
1778
+ if (!Array.isArray(value)) {
1779
+ continue;
1780
+ }
1781
+ for (const roomId of value) {
1782
+ if (typeof roomId === "string" && roomId.trim()) {
1783
+ this.dmRoomIds.add(roomId);
1784
+ }
1785
+ }
1786
+ }
1787
+ return true;
1788
+ }
1789
+ }