@kodelyth/matrix 2026.5.42 → 2026.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (205) hide show
  1. package/klaw.plugin.json +891 -3
  2. package/package.json +16 -4
  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,795 +0,0 @@
1
- import {
2
- VerificationPhase,
3
- VerificationRequestEvent,
4
- VerifierEvent,
5
- } from "matrix-js-sdk/lib/crypto-api/verification.js";
6
- import { VerificationMethod } from "matrix-js-sdk/lib/types.js";
7
- import { formatMatrixErrorMessage } from "../errors.js";
8
-
9
- export type MatrixVerificationMethod = "sas" | "show-qr" | "scan-qr";
10
- type MatrixVerificationPhase = VerificationPhase | -1;
11
-
12
- const MATRIX_VERIFICATION_PHASES = new Set<MatrixVerificationPhase>([
13
- -1,
14
- VerificationPhase.Unsent,
15
- VerificationPhase.Requested,
16
- VerificationPhase.Ready,
17
- VerificationPhase.Started,
18
- VerificationPhase.Cancelled,
19
- VerificationPhase.Done,
20
- ]);
21
-
22
- function isMatrixVerificationPhase(value: unknown): value is MatrixVerificationPhase {
23
- return (
24
- typeof value === "number" && MATRIX_VERIFICATION_PHASES.has(value as MatrixVerificationPhase)
25
- );
26
- }
27
-
28
- export type MatrixVerificationSummary = {
29
- id: string;
30
- transactionId?: string;
31
- roomId?: string;
32
- otherUserId: string;
33
- otherDeviceId?: string;
34
- isSelfVerification: boolean;
35
- initiatedByMe: boolean;
36
- phase: number;
37
- phaseName: string;
38
- pending: boolean;
39
- methods: string[];
40
- chosenMethod?: string | null;
41
- canAccept: boolean;
42
- hasSas: boolean;
43
- sas?: {
44
- decimal?: [number, number, number];
45
- emoji?: Array<[string, string]>;
46
- };
47
- hasReciprocateQr: boolean;
48
- completed: boolean;
49
- error?: string;
50
- createdAt: string;
51
- updatedAt: string;
52
- };
53
-
54
- type MatrixVerificationSummaryListener = (summary: MatrixVerificationSummary) => void;
55
- type MatrixVerificationOwnerTrustCallback = (deviceId: string) => Promise<void>;
56
-
57
- export type MatrixShowSasCallbacks = {
58
- sas: {
59
- decimal?: [number, number, number];
60
- emoji?: Array<[string, string]>;
61
- };
62
- confirm: () => Promise<void>;
63
- mismatch: () => void;
64
- cancel: () => void;
65
- };
66
-
67
- export type MatrixShowQrCodeCallbacks = {
68
- confirm: () => void;
69
- cancel: () => void;
70
- };
71
-
72
- export type MatrixVerifierLike = {
73
- verify: () => Promise<void>;
74
- cancel: (e: Error) => void;
75
- getShowSasCallbacks: () => MatrixShowSasCallbacks | null;
76
- getReciprocateQrCodeCallbacks: () => MatrixShowQrCodeCallbacks | null;
77
- on: (eventName: string, listener: (...args: unknown[]) => void) => void;
78
- };
79
-
80
- export type MatrixVerificationRequestLike = {
81
- transactionId?: string;
82
- roomId?: string;
83
- initiatedByMe: boolean;
84
- otherUserId: string;
85
- otherDeviceId?: string;
86
- isSelfVerification: boolean;
87
- phase: number;
88
- pending: boolean;
89
- accepting: boolean;
90
- declining: boolean;
91
- methods: string[];
92
- chosenMethod?: string | null;
93
- cancellationCode?: string | null;
94
- accept: () => Promise<void>;
95
- cancel: (params?: { reason?: string; code?: string }) => Promise<void>;
96
- startVerification: (method: string) => Promise<MatrixVerifierLike>;
97
- scanQRCode: (qrCodeData: Uint8ClampedArray) => Promise<MatrixVerifierLike>;
98
- generateQRCode: () => Promise<Uint8ClampedArray | undefined>;
99
- verifier?: MatrixVerifierLike;
100
- on: (eventName: string, listener: (...args: unknown[]) => void) => void;
101
- };
102
-
103
- export type MatrixVerificationCryptoApi = {
104
- requestOwnUserVerification: () => Promise<MatrixVerificationRequestLike | null>;
105
- getVerificationRequestsToDeviceInProgress?: (userId: string) => MatrixVerificationRequestLike[];
106
- findVerificationRequestDMInProgress?: (
107
- roomId: string,
108
- userId: string,
109
- ) => MatrixVerificationRequestLike | undefined;
110
- requestDeviceVerification?: (
111
- userId: string,
112
- deviceId: string,
113
- ) => Promise<MatrixVerificationRequestLike>;
114
- requestVerificationDM?: (
115
- userId: string,
116
- roomId: string,
117
- ) => Promise<MatrixVerificationRequestLike>;
118
- };
119
-
120
- type MatrixVerificationSession = {
121
- id: string;
122
- request: MatrixVerificationRequestLike;
123
- createdAtMs: number;
124
- updatedAtMs: number;
125
- error?: string;
126
- activeVerifier?: MatrixVerifierLike;
127
- verifyPromise?: Promise<void>;
128
- verifyStarted: boolean;
129
- startRequested: boolean;
130
- acceptRequested: boolean;
131
- sasAutoConfirmStarted: boolean;
132
- sasAutoConfirmTimer?: ReturnType<typeof setTimeout>;
133
- sasCallbacks?: MatrixShowSasCallbacks;
134
- reciprocateQrCallbacks?: MatrixShowQrCodeCallbacks;
135
- };
136
-
137
- type MatrixVerificationRequestIdentity = {
138
- transactionId: string;
139
- roomId: string;
140
- otherUserId: string;
141
- otherDeviceId: string;
142
- isSelfVerification: boolean;
143
- initiatedByMe: boolean;
144
- };
145
-
146
- const MAX_TRACKED_VERIFICATION_SESSIONS = 256;
147
- const TERMINAL_SESSION_RETENTION_MS = 24 * 60 * 60 * 1000;
148
- const SAS_AUTO_CONFIRM_DELAY_MS = 30_000;
149
-
150
- export class MatrixVerificationManager {
151
- private readonly verificationSessions = new Map<string, MatrixVerificationSession>();
152
- private verificationSessionCounter = 0;
153
- private readonly trackedVerificationRequests = new WeakSet<object>();
154
- private readonly trackedVerificationVerifiers = new WeakSet<object>();
155
- private readonly summaryListeners = new Set<MatrixVerificationSummaryListener>();
156
-
157
- constructor(
158
- private readonly opts: {
159
- trustOwnDeviceAfterSas?: MatrixVerificationOwnerTrustCallback;
160
- } = {},
161
- ) {}
162
-
163
- private readRequestValue<T>(
164
- _request: MatrixVerificationRequestLike,
165
- reader: () => T,
166
- fallback: T,
167
- ): T {
168
- try {
169
- return reader();
170
- } catch {
171
- return fallback;
172
- }
173
- }
174
-
175
- private readVerificationPhase(
176
- request: MatrixVerificationRequestLike,
177
- fallback: MatrixVerificationPhase,
178
- ): MatrixVerificationPhase {
179
- const phase = this.readRequestValue<unknown>(request, () => request.phase, fallback);
180
- return isMatrixVerificationPhase(phase) ? phase : fallback;
181
- }
182
-
183
- private readVerificationRequestIdentity(
184
- request: MatrixVerificationRequestLike,
185
- ): MatrixVerificationRequestIdentity {
186
- return {
187
- transactionId: this.readRequestValue(request, () => request.transactionId?.trim() ?? "", ""),
188
- roomId: this.readRequestValue(request, () => request.roomId ?? "", ""),
189
- otherUserId: this.readRequestValue(request, () => request.otherUserId, ""),
190
- otherDeviceId: this.readRequestValue(request, () => request.otherDeviceId ?? "", ""),
191
- isSelfVerification: this.readRequestValue(request, () => request.isSelfVerification, false),
192
- initiatedByMe: this.readRequestValue(request, () => request.initiatedByMe, false),
193
- };
194
- }
195
-
196
- private isSameLogicalVerificationRequest(
197
- left: MatrixVerificationRequestLike,
198
- right: MatrixVerificationRequestLike,
199
- ): boolean {
200
- const leftIdentity = this.readVerificationRequestIdentity(left);
201
- const rightIdentity = this.readVerificationRequestIdentity(right);
202
- return (
203
- leftIdentity.transactionId !== "" &&
204
- leftIdentity.transactionId === rightIdentity.transactionId &&
205
- leftIdentity.roomId === rightIdentity.roomId &&
206
- leftIdentity.otherUserId === rightIdentity.otherUserId &&
207
- this.isSameOptionalIdentityValue(leftIdentity.otherDeviceId, rightIdentity.otherDeviceId) &&
208
- leftIdentity.isSelfVerification === rightIdentity.isSelfVerification &&
209
- leftIdentity.initiatedByMe === rightIdentity.initiatedByMe
210
- );
211
- }
212
-
213
- private isSameOptionalIdentityValue(left: string, right: string): boolean {
214
- return left === "" || right === "" || left === right;
215
- }
216
-
217
- private pruneVerificationSessions(nowMs: number): void {
218
- for (const [id, session] of this.verificationSessions) {
219
- const phase = this.readVerificationPhase(session.request, -1);
220
- const isTerminal = phase === VerificationPhase.Done || phase === VerificationPhase.Cancelled;
221
- if (isTerminal && nowMs - session.updatedAtMs > TERMINAL_SESSION_RETENTION_MS) {
222
- this.verificationSessions.delete(id);
223
- }
224
- }
225
-
226
- if (this.verificationSessions.size <= MAX_TRACKED_VERIFICATION_SESSIONS) {
227
- return;
228
- }
229
-
230
- const sortedByAge = Array.from(this.verificationSessions.entries()).toSorted(
231
- (a, b) => a[1].updatedAtMs - b[1].updatedAtMs,
232
- );
233
- const overflow = this.verificationSessions.size - MAX_TRACKED_VERIFICATION_SESSIONS;
234
- for (let i = 0; i < overflow; i += 1) {
235
- const entry = sortedByAge[i];
236
- if (entry) {
237
- this.verificationSessions.delete(entry[0]);
238
- }
239
- }
240
- }
241
-
242
- private getVerificationPhaseName(phase: MatrixVerificationPhase): string {
243
- switch (phase) {
244
- case VerificationPhase.Unsent:
245
- return "unsent";
246
- case VerificationPhase.Requested:
247
- return "requested";
248
- case VerificationPhase.Ready:
249
- return "ready";
250
- case VerificationPhase.Started:
251
- return "started";
252
- case VerificationPhase.Cancelled:
253
- return "cancelled";
254
- case VerificationPhase.Done:
255
- return "done";
256
- default:
257
- return `unknown(${phase})`;
258
- }
259
- }
260
-
261
- private emitVerificationSummary(session: MatrixVerificationSession): void {
262
- const summary = this.buildVerificationSummary(session);
263
- for (const listener of this.summaryListeners) {
264
- listener(summary);
265
- }
266
- }
267
-
268
- private touchVerificationSession(session: MatrixVerificationSession): void {
269
- session.updatedAtMs = Date.now();
270
- this.emitVerificationSummary(session);
271
- }
272
-
273
- private clearSasAutoConfirmTimer(session: MatrixVerificationSession): void {
274
- if (!session.sasAutoConfirmTimer) {
275
- return;
276
- }
277
- clearTimeout(session.sasAutoConfirmTimer);
278
- session.sasAutoConfirmTimer = undefined;
279
- }
280
-
281
- private buildVerificationSummary(session: MatrixVerificationSession): MatrixVerificationSummary {
282
- const request = session.request;
283
- const phase = this.readVerificationPhase(request, VerificationPhase.Requested);
284
- const accepting = this.readRequestValue(request, () => request.accepting, false);
285
- const declining = this.readRequestValue(request, () => request.declining, false);
286
- const pending = this.readRequestValue(request, () => request.pending, false);
287
- const methodsRaw = this.readRequestValue<unknown>(request, () => request.methods, []);
288
- const methods = Array.isArray(methodsRaw)
289
- ? methodsRaw.filter((entry): entry is string => typeof entry === "string")
290
- : [];
291
- const sasCallbacks = session.sasCallbacks ?? session.activeVerifier?.getShowSasCallbacks();
292
- if (sasCallbacks) {
293
- session.sasCallbacks = sasCallbacks;
294
- }
295
- const canAccept = phase < VerificationPhase.Ready && !accepting && !declining;
296
- return {
297
- id: session.id,
298
- transactionId: this.readRequestValue(request, () => request.transactionId, undefined),
299
- roomId: this.readRequestValue(request, () => request.roomId, undefined),
300
- otherUserId: this.readRequestValue(request, () => request.otherUserId, "unknown"),
301
- otherDeviceId: this.readRequestValue(request, () => request.otherDeviceId, undefined),
302
- isSelfVerification: this.readRequestValue(request, () => request.isSelfVerification, false),
303
- initiatedByMe: this.readRequestValue(request, () => request.initiatedByMe, false),
304
- phase,
305
- phaseName: this.getVerificationPhaseName(phase),
306
- pending,
307
- methods,
308
- chosenMethod: this.readRequestValue(request, () => request.chosenMethod ?? null, null),
309
- canAccept,
310
- hasSas: Boolean(sasCallbacks),
311
- sas: sasCallbacks
312
- ? {
313
- decimal: sasCallbacks.sas.decimal,
314
- emoji: sasCallbacks.sas.emoji,
315
- }
316
- : undefined,
317
- hasReciprocateQr: Boolean(session.reciprocateQrCallbacks),
318
- completed: phase === VerificationPhase.Done,
319
- error: session.error,
320
- createdAt: new Date(session.createdAtMs).toISOString(),
321
- updatedAt: new Date(session.updatedAtMs).toISOString(),
322
- };
323
- }
324
-
325
- private findVerificationSession(id: string): MatrixVerificationSession {
326
- const direct = this.verificationSessions.get(id);
327
- if (direct) {
328
- return direct;
329
- }
330
- const transactionMatches = Array.from(this.verificationSessions.values()).filter((session) => {
331
- const txId = this.readRequestValue(
332
- session.request,
333
- () => session.request.transactionId?.trim(),
334
- "",
335
- );
336
- return txId === id;
337
- });
338
- if (transactionMatches.length === 1) {
339
- return transactionMatches[0];
340
- }
341
- if (transactionMatches.length > 1) {
342
- throw new Error(
343
- `Matrix verification request id is ambiguous for transaction ${id}; use the verification id instead`,
344
- );
345
- }
346
- throw new Error(`Matrix verification request not found: ${id}`);
347
- }
348
-
349
- private ensureVerificationRequestTracked(session: MatrixVerificationSession): void {
350
- const requestObj = session.request as unknown as object;
351
- if (this.trackedVerificationRequests.has(requestObj)) {
352
- return;
353
- }
354
- this.trackedVerificationRequests.add(requestObj);
355
- session.request.on(VerificationRequestEvent.Change, () => {
356
- this.touchVerificationSession(session);
357
- this.maybeAutoAcceptInboundRequest(session);
358
- const verifier = this.readRequestValue(session.request, () => session.request.verifier, null);
359
- if (verifier) {
360
- this.attachVerifierToVerificationSession(session, verifier);
361
- }
362
- this.maybeAutoStartInboundSas(session);
363
- });
364
- }
365
-
366
- private maybeAutoAcceptInboundRequest(session: MatrixVerificationSession): void {
367
- if (session.acceptRequested) {
368
- return;
369
- }
370
- const request = session.request;
371
- const isSelfVerification = this.readRequestValue(
372
- request,
373
- () => request.isSelfVerification,
374
- false,
375
- );
376
- const initiatedByMe = this.readRequestValue(request, () => request.initiatedByMe, false);
377
- const phase = this.readVerificationPhase(request, VerificationPhase.Requested);
378
- const accepting = this.readRequestValue(request, () => request.accepting, false);
379
- const declining = this.readRequestValue(request, () => request.declining, false);
380
- if (isSelfVerification || initiatedByMe) {
381
- return;
382
- }
383
- if (phase !== VerificationPhase.Requested || accepting || declining) {
384
- return;
385
- }
386
-
387
- session.acceptRequested = true;
388
- void request
389
- .accept()
390
- .then(() => {
391
- this.touchVerificationSession(session);
392
- })
393
- .catch((err) => {
394
- session.acceptRequested = false;
395
- session.error = formatMatrixErrorMessage(err);
396
- this.touchVerificationSession(session);
397
- });
398
- }
399
-
400
- private maybeAutoStartInboundSas(session: MatrixVerificationSession): void {
401
- if (session.activeVerifier || session.verifyStarted || session.startRequested) {
402
- return;
403
- }
404
- if (this.readRequestValue(session.request, () => session.request.initiatedByMe, true)) {
405
- return;
406
- }
407
- if (!this.readRequestValue(session.request, () => session.request.isSelfVerification, false)) {
408
- return;
409
- }
410
- const phase = this.readVerificationPhase(session.request, VerificationPhase.Requested);
411
- if (phase < VerificationPhase.Ready || phase >= VerificationPhase.Cancelled) {
412
- return;
413
- }
414
- const methodsRaw = this.readRequestValue<unknown>(
415
- session.request,
416
- () => session.request.methods,
417
- [],
418
- );
419
- const methods = Array.isArray(methodsRaw)
420
- ? methodsRaw.filter((entry): entry is string => typeof entry === "string")
421
- : [];
422
- const chosenMethod = this.readRequestValue(
423
- session.request,
424
- () => session.request.chosenMethod,
425
- null,
426
- );
427
- const supportsSas =
428
- methods.includes(VerificationMethod.Sas) || chosenMethod === VerificationMethod.Sas;
429
- if (!supportsSas) {
430
- return;
431
- }
432
-
433
- session.startRequested = true;
434
- void session.request
435
- .startVerification(VerificationMethod.Sas)
436
- .then((verifier) => {
437
- this.attachVerifierToVerificationSession(session, verifier);
438
- this.touchVerificationSession(session);
439
- })
440
- .catch(() => {
441
- session.startRequested = false;
442
- });
443
- }
444
-
445
- private attachVerifierToVerificationSession(
446
- session: MatrixVerificationSession,
447
- verifier: MatrixVerifierLike,
448
- ): void {
449
- session.activeVerifier = verifier;
450
- this.touchVerificationSession(session);
451
-
452
- const maybeSas = verifier.getShowSasCallbacks();
453
- if (maybeSas) {
454
- session.sasCallbacks = maybeSas;
455
- this.maybeAutoConfirmSas(session);
456
- }
457
- const maybeReciprocateQr = verifier.getReciprocateQrCodeCallbacks();
458
- if (maybeReciprocateQr) {
459
- session.reciprocateQrCallbacks = maybeReciprocateQr;
460
- }
461
-
462
- const verifierObj = verifier as unknown as object;
463
- if (this.trackedVerificationVerifiers.has(verifierObj)) {
464
- this.ensureVerificationStarted(session);
465
- return;
466
- }
467
- this.trackedVerificationVerifiers.add(verifierObj);
468
-
469
- verifier.on(VerifierEvent.ShowSas, (sas) => {
470
- session.sasCallbacks = sas as MatrixShowSasCallbacks;
471
- this.touchVerificationSession(session);
472
- this.maybeAutoConfirmSas(session);
473
- });
474
- verifier.on(VerifierEvent.ShowReciprocateQr, (qr) => {
475
- session.reciprocateQrCallbacks = qr as MatrixShowQrCodeCallbacks;
476
- this.touchVerificationSession(session);
477
- });
478
- verifier.on(VerifierEvent.Cancel, (err) => {
479
- this.clearSasAutoConfirmTimer(session);
480
- session.error = formatMatrixErrorMessage(err);
481
- this.touchVerificationSession(session);
482
- });
483
- this.ensureVerificationStarted(session);
484
- }
485
-
486
- private maybeAutoConfirmSas(session: MatrixVerificationSession): void {
487
- if (session.sasAutoConfirmStarted || session.sasAutoConfirmTimer) {
488
- return;
489
- }
490
- if (this.readRequestValue(session.request, () => session.request.initiatedByMe, true)) {
491
- return;
492
- }
493
- const callbacks = session.sasCallbacks ?? session.activeVerifier?.getShowSasCallbacks();
494
- if (!callbacks) {
495
- return;
496
- }
497
- session.sasCallbacks = callbacks;
498
- // Give the remote client a moment to surface the compare-emoji UI before
499
- // we send our MAC and finish our side of the SAS flow.
500
- session.sasAutoConfirmTimer = setTimeout(() => {
501
- session.sasAutoConfirmTimer = undefined;
502
- const phase = this.readVerificationPhase(session.request, VerificationPhase.Requested);
503
- if (phase >= VerificationPhase.Cancelled) {
504
- return;
505
- }
506
- session.sasAutoConfirmStarted = true;
507
- // For self-verifications, trustOwnDeviceAfterConfirmedSas is gated on
508
- // isSelfVerification, so non-self requests remain unaffected. Without
509
- // this, the bot's own device never gets cross-signed when SAS lands
510
- // via the auto-confirm timer (initiated remotely).
511
- void this.confirmSasForSession(session, callbacks, { trustOwnDevice: true })
512
- .then(() => {
513
- this.touchVerificationSession(session);
514
- })
515
- .catch((err) => {
516
- session.error = formatMatrixErrorMessage(err);
517
- this.touchVerificationSession(session);
518
- });
519
- }, SAS_AUTO_CONFIRM_DELAY_MS);
520
- }
521
-
522
- private async confirmSasForSession(
523
- session: MatrixVerificationSession,
524
- callbacks: MatrixShowSasCallbacks,
525
- opts: { trustOwnDevice: boolean } = { trustOwnDevice: true },
526
- ): Promise<void> {
527
- await callbacks.confirm();
528
- if (opts.trustOwnDevice) {
529
- await this.trustOwnDeviceAfterConfirmedSas(session);
530
- }
531
- }
532
-
533
- private ensureVerificationStarted(session: MatrixVerificationSession): void {
534
- if (!session.activeVerifier || session.verifyStarted) {
535
- return;
536
- }
537
- session.verifyStarted = true;
538
- const verifier = session.activeVerifier;
539
- session.verifyPromise = verifier
540
- .verify()
541
- .then(() => {
542
- this.touchVerificationSession(session);
543
- })
544
- .catch((err) => {
545
- session.error = formatMatrixErrorMessage(err);
546
- this.touchVerificationSession(session);
547
- });
548
- }
549
-
550
- private async trustOwnDeviceAfterConfirmedSas(session: MatrixVerificationSession): Promise<void> {
551
- if (!this.readRequestValue(session.request, () => session.request.isSelfVerification, false)) {
552
- return;
553
- }
554
- const deviceId = this.readRequestValue(
555
- session.request,
556
- () => session.request.otherDeviceId?.trim(),
557
- "",
558
- );
559
- if (!deviceId || !this.opts.trustOwnDeviceAfterSas) {
560
- return;
561
- }
562
- await this.opts.trustOwnDeviceAfterSas(deviceId);
563
- }
564
-
565
- onSummaryChanged(listener: MatrixVerificationSummaryListener): () => void {
566
- this.summaryListeners.add(listener);
567
- return () => {
568
- this.summaryListeners.delete(listener);
569
- };
570
- }
571
-
572
- trackVerificationRequest(request: MatrixVerificationRequestLike): MatrixVerificationSummary {
573
- this.pruneVerificationSessions(Date.now());
574
- const requestObj = request as unknown as object;
575
- for (const existing of this.verificationSessions.values()) {
576
- if ((existing.request as unknown as object) === requestObj) {
577
- this.touchVerificationSession(existing);
578
- return this.buildVerificationSummary(existing);
579
- }
580
- }
581
- const txId = this.readVerificationRequestIdentity(request).transactionId;
582
- if (txId) {
583
- for (const existing of this.verificationSessions.values()) {
584
- if (this.isSameLogicalVerificationRequest(existing.request, request)) {
585
- existing.request = request;
586
- this.ensureVerificationRequestTracked(existing);
587
- const verifier = this.readRequestValue(request, () => request.verifier, null);
588
- if (verifier) {
589
- this.attachVerifierToVerificationSession(existing, verifier);
590
- }
591
- this.touchVerificationSession(existing);
592
- return this.buildVerificationSummary(existing);
593
- }
594
- }
595
- }
596
-
597
- const now = Date.now();
598
- const id = `verification-${++this.verificationSessionCounter}`;
599
- const session: MatrixVerificationSession = {
600
- id,
601
- request,
602
- createdAtMs: now,
603
- updatedAtMs: now,
604
- verifyStarted: false,
605
- startRequested: false,
606
- acceptRequested: false,
607
- sasAutoConfirmStarted: false,
608
- };
609
- this.verificationSessions.set(session.id, session);
610
- this.ensureVerificationRequestTracked(session);
611
- this.maybeAutoAcceptInboundRequest(session);
612
- const verifier = this.readRequestValue(request, () => request.verifier, null);
613
- if (verifier) {
614
- this.attachVerifierToVerificationSession(session, verifier);
615
- }
616
- this.maybeAutoStartInboundSas(session);
617
- this.emitVerificationSummary(session);
618
- return this.buildVerificationSummary(session);
619
- }
620
-
621
- async requestOwnUserVerification(
622
- crypto: MatrixVerificationCryptoApi | undefined,
623
- ): Promise<MatrixVerificationSummary | null> {
624
- if (!crypto) {
625
- return null;
626
- }
627
- const request = await crypto.requestOwnUserVerification();
628
- if (!request) {
629
- return null;
630
- }
631
- return this.trackVerificationRequest(request);
632
- }
633
-
634
- listVerifications(): MatrixVerificationSummary[] {
635
- this.pruneVerificationSessions(Date.now());
636
- const summaries = Array.from(this.verificationSessions.values()).map((session) =>
637
- this.buildVerificationSummary(session),
638
- );
639
- return summaries.toSorted((a, b) => b.updatedAt.localeCompare(a.updatedAt));
640
- }
641
-
642
- async requestVerification(
643
- crypto: MatrixVerificationCryptoApi | undefined,
644
- params: {
645
- ownUser?: boolean;
646
- userId?: string;
647
- deviceId?: string;
648
- roomId?: string;
649
- },
650
- ): Promise<MatrixVerificationSummary> {
651
- if (!crypto) {
652
- throw new Error("Matrix crypto is not available");
653
- }
654
- let request: MatrixVerificationRequestLike | null = null;
655
- if (params.ownUser) {
656
- request = await crypto.requestOwnUserVerification();
657
- } else if (params.userId && params.deviceId && crypto.requestDeviceVerification) {
658
- request = await crypto.requestDeviceVerification(params.userId, params.deviceId);
659
- } else if (params.userId && params.roomId && crypto.requestVerificationDM) {
660
- request = await crypto.requestVerificationDM(params.userId, params.roomId);
661
- } else {
662
- throw new Error(
663
- "Matrix verification request requires one of: ownUser, userId+deviceId, or userId+roomId",
664
- );
665
- }
666
-
667
- if (!request) {
668
- throw new Error("Matrix verification request could not be created");
669
- }
670
- return this.trackVerificationRequest(request);
671
- }
672
-
673
- async acceptVerification(id: string): Promise<MatrixVerificationSummary> {
674
- const session = this.findVerificationSession(id);
675
- await session.request.accept();
676
- this.touchVerificationSession(session);
677
- return this.buildVerificationSummary(session);
678
- }
679
-
680
- async cancelVerification(
681
- id: string,
682
- params?: { reason?: string; code?: string },
683
- ): Promise<MatrixVerificationSummary> {
684
- const session = this.findVerificationSession(id);
685
- await session.request.cancel(params);
686
- this.touchVerificationSession(session);
687
- return this.buildVerificationSummary(session);
688
- }
689
-
690
- async startVerification(
691
- id: string,
692
- method: MatrixVerificationMethod = "sas",
693
- ): Promise<MatrixVerificationSummary> {
694
- const session = this.findVerificationSession(id);
695
- if (method !== "sas") {
696
- throw new Error("Matrix startVerification currently supports only SAS directly");
697
- }
698
- const verifier = await session.request.startVerification(VerificationMethod.Sas);
699
- this.attachVerifierToVerificationSession(session, verifier);
700
- this.ensureVerificationStarted(session);
701
- return this.buildVerificationSummary(session);
702
- }
703
-
704
- async generateVerificationQr(id: string): Promise<{ qrDataBase64: string }> {
705
- const session = this.findVerificationSession(id);
706
- const qr = await session.request.generateQRCode();
707
- if (!qr) {
708
- throw new Error("Matrix verification QR data is not available yet");
709
- }
710
- return { qrDataBase64: Buffer.from(qr).toString("base64") };
711
- }
712
-
713
- async scanVerificationQr(id: string, qrDataBase64: string): Promise<MatrixVerificationSummary> {
714
- const session = this.findVerificationSession(id);
715
- const trimmed = qrDataBase64.trim();
716
- if (!trimmed) {
717
- throw new Error("Matrix verification QR payload is required");
718
- }
719
- const qrBytes = Buffer.from(trimmed, "base64");
720
- if (qrBytes.length === 0) {
721
- throw new Error("Matrix verification QR payload is invalid base64");
722
- }
723
- const verifier = await session.request.scanQRCode(new Uint8ClampedArray(qrBytes));
724
- this.attachVerifierToVerificationSession(session, verifier);
725
- this.ensureVerificationStarted(session);
726
- return this.buildVerificationSummary(session);
727
- }
728
-
729
- async confirmVerificationSas(id: string): Promise<MatrixVerificationSummary> {
730
- const session = this.findVerificationSession(id);
731
- const callbacks = session.sasCallbacks ?? session.activeVerifier?.getShowSasCallbacks();
732
- if (!callbacks) {
733
- throw new Error("Matrix SAS confirmation is not available for this verification request");
734
- }
735
- this.clearSasAutoConfirmTimer(session);
736
- session.sasCallbacks = callbacks;
737
- session.sasAutoConfirmStarted = true;
738
- await this.confirmSasForSession(session, callbacks);
739
- // Wait for the rust-crypto verifier to fully resolve (done-exchange + any
740
- // pending cross-signing uploads triggered by trustOwnDeviceAfterSas) so
741
- // the operator's client sees a settled state on the next /keys/query.
742
- // verifyPromise is set inside ensureVerificationStarted and already
743
- // funnels its own rejection into session.error, so awaiting it here
744
- // cannot double-throw.
745
- if (session.verifyPromise) {
746
- await session.verifyPromise;
747
- }
748
- this.touchVerificationSession(session);
749
- return this.buildVerificationSummary(session);
750
- }
751
-
752
- mismatchVerificationSas(id: string): MatrixVerificationSummary {
753
- const session = this.findVerificationSession(id);
754
- const callbacks = session.sasCallbacks ?? session.activeVerifier?.getShowSasCallbacks();
755
- if (!callbacks) {
756
- throw new Error("Matrix SAS mismatch is not available for this verification request");
757
- }
758
- this.clearSasAutoConfirmTimer(session);
759
- session.sasCallbacks = callbacks;
760
- callbacks.mismatch();
761
- this.touchVerificationSession(session);
762
- return this.buildVerificationSummary(session);
763
- }
764
-
765
- confirmVerificationReciprocateQr(id: string): MatrixVerificationSummary {
766
- const session = this.findVerificationSession(id);
767
- const callbacks =
768
- session.reciprocateQrCallbacks ?? session.activeVerifier?.getReciprocateQrCodeCallbacks();
769
- if (!callbacks) {
770
- throw new Error(
771
- "Matrix reciprocate-QR confirmation is not available for this verification request",
772
- );
773
- }
774
- session.reciprocateQrCallbacks = callbacks;
775
- callbacks.confirm();
776
- this.touchVerificationSession(session);
777
- return this.buildVerificationSummary(session);
778
- }
779
-
780
- getVerificationSas(id: string): {
781
- decimal?: [number, number, number];
782
- emoji?: Array<[string, string]>;
783
- } {
784
- const session = this.findVerificationSession(id);
785
- const callbacks = session.sasCallbacks ?? session.activeVerifier?.getShowSasCallbacks();
786
- if (!callbacks) {
787
- throw new Error("Matrix SAS data is not available for this verification request");
788
- }
789
- session.sasCallbacks = callbacks;
790
- return {
791
- decimal: callbacks.sas.decimal,
792
- emoji: callbacks.sas.emoji,
793
- };
794
- }
795
- }