@gakr-gakr/matrix 0.1.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 (205) hide show
  1. package/CHANGELOG.md +285 -0
  2. package/SPEC-SUPPORT.md +116 -0
  3. package/api.ts +38 -0
  4. package/auth-presence.ts +56 -0
  5. package/autobot.plugin.json +28 -0
  6. package/channel-plugin-api.ts +3 -0
  7. package/cli-metadata.ts +11 -0
  8. package/contract-api.ts +17 -0
  9. package/doctor-contract-api.ts +1 -0
  10. package/helper-api.ts +3 -0
  11. package/index.ts +55 -0
  12. package/package.json +101 -0
  13. package/plugin-entry.handlers.runtime.ts +1 -0
  14. package/runtime-api.ts +72 -0
  15. package/runtime-heavy-api.ts +1 -0
  16. package/runtime-setter-api.ts +3 -0
  17. package/secret-contract-api.ts +5 -0
  18. package/setup-entry.ts +17 -0
  19. package/setup-plugin-api.ts +3 -0
  20. package/src/account-selection.ts +223 -0
  21. package/src/actions.ts +346 -0
  22. package/src/approval-auth.ts +25 -0
  23. package/src/approval-handler.runtime.ts +595 -0
  24. package/src/approval-ids.ts +6 -0
  25. package/src/approval-native.ts +348 -0
  26. package/src/approval-reaction-auth.ts +45 -0
  27. package/src/approval-reactions.ts +313 -0
  28. package/src/auth-precedence.ts +61 -0
  29. package/src/channel-account-paths.ts +97 -0
  30. package/src/channel.runtime.ts +17 -0
  31. package/src/channel.setup.ts +48 -0
  32. package/src/channel.ts +667 -0
  33. package/src/cli-metadata.ts +19 -0
  34. package/src/cli.ts +2298 -0
  35. package/src/config-adapter.ts +41 -0
  36. package/src/config-schema.ts +159 -0
  37. package/src/config-ui-hints.ts +56 -0
  38. package/src/directory-live.ts +238 -0
  39. package/src/doctor-contract.ts +287 -0
  40. package/src/doctor.ts +262 -0
  41. package/src/env-vars.ts +92 -0
  42. package/src/exec-approval-resolver.ts +23 -0
  43. package/src/exec-approvals.ts +293 -0
  44. package/src/group-mentions.ts +41 -0
  45. package/src/legacy-crypto-inspector-availability.ts +60 -0
  46. package/src/legacy-crypto.ts +531 -0
  47. package/src/legacy-state.ts +156 -0
  48. package/src/matrix/account-config.ts +175 -0
  49. package/src/matrix/accounts.ts +194 -0
  50. package/src/matrix/actions/client.ts +31 -0
  51. package/src/matrix/actions/devices.ts +34 -0
  52. package/src/matrix/actions/limits.ts +6 -0
  53. package/src/matrix/actions/messages.ts +129 -0
  54. package/src/matrix/actions/pins.ts +63 -0
  55. package/src/matrix/actions/polls.ts +109 -0
  56. package/src/matrix/actions/profile.ts +37 -0
  57. package/src/matrix/actions/reactions.ts +59 -0
  58. package/src/matrix/actions/room.ts +71 -0
  59. package/src/matrix/actions/summary.ts +88 -0
  60. package/src/matrix/actions/types.ts +63 -0
  61. package/src/matrix/actions/verification.ts +589 -0
  62. package/src/matrix/actions.ts +37 -0
  63. package/src/matrix/active-client.ts +26 -0
  64. package/src/matrix/async-lock.ts +18 -0
  65. package/src/matrix/backup-health.ts +124 -0
  66. package/src/matrix/client/config-runtime-api.ts +9 -0
  67. package/src/matrix/client/config-secret-input.runtime.ts +1 -0
  68. package/src/matrix/client/config.ts +853 -0
  69. package/src/matrix/client/create-client.ts +105 -0
  70. package/src/matrix/client/env-auth.ts +95 -0
  71. package/src/matrix/client/file-sync-store.ts +289 -0
  72. package/src/matrix/client/logging.ts +140 -0
  73. package/src/matrix/client/migration-snapshot.runtime.ts +1 -0
  74. package/src/matrix/client/private-network-host.ts +1 -0
  75. package/src/matrix/client/runtime.ts +4 -0
  76. package/src/matrix/client/shared.ts +316 -0
  77. package/src/matrix/client/storage.ts +543 -0
  78. package/src/matrix/client/types.ts +50 -0
  79. package/src/matrix/client/url-validation.ts +76 -0
  80. package/src/matrix/client-bootstrap.ts +173 -0
  81. package/src/matrix/client.ts +23 -0
  82. package/src/matrix/config-paths.ts +31 -0
  83. package/src/matrix/config-update.ts +292 -0
  84. package/src/matrix/credentials-read.ts +207 -0
  85. package/src/matrix/credentials-write.runtime.ts +35 -0
  86. package/src/matrix/credentials.ts +95 -0
  87. package/src/matrix/deps.ts +309 -0
  88. package/src/matrix/device-health.ts +31 -0
  89. package/src/matrix/direct-management.ts +349 -0
  90. package/src/matrix/direct-room.ts +128 -0
  91. package/src/matrix/draft-stream.ts +225 -0
  92. package/src/matrix/encryption-guidance.ts +24 -0
  93. package/src/matrix/errors.ts +21 -0
  94. package/src/matrix/format.ts +426 -0
  95. package/src/matrix/legacy-crypto-inspector.ts +95 -0
  96. package/src/matrix/media-errors.ts +20 -0
  97. package/src/matrix/media-text.ts +162 -0
  98. package/src/matrix/monitor/access-state.ts +145 -0
  99. package/src/matrix/monitor/ack-config.ts +27 -0
  100. package/src/matrix/monitor/allowlist.ts +92 -0
  101. package/src/matrix/monitor/auto-join.ts +86 -0
  102. package/src/matrix/monitor/config.ts +569 -0
  103. package/src/matrix/monitor/context-summary.ts +43 -0
  104. package/src/matrix/monitor/direct.ts +296 -0
  105. package/src/matrix/monitor/events.ts +397 -0
  106. package/src/matrix/monitor/handler.ts +2271 -0
  107. package/src/matrix/monitor/inbound-dedupe.ts +267 -0
  108. package/src/matrix/monitor/index.ts +540 -0
  109. package/src/matrix/monitor/legacy-crypto-restore.ts +139 -0
  110. package/src/matrix/monitor/location.ts +108 -0
  111. package/src/matrix/monitor/media.ts +119 -0
  112. package/src/matrix/monitor/mentions.ts +256 -0
  113. package/src/matrix/monitor/reaction-events.ts +197 -0
  114. package/src/matrix/monitor/recent-invite.ts +30 -0
  115. package/src/matrix/monitor/replies.ts +136 -0
  116. package/src/matrix/monitor/reply-context.ts +92 -0
  117. package/src/matrix/monitor/room-history.ts +301 -0
  118. package/src/matrix/monitor/room-info.ts +126 -0
  119. package/src/matrix/monitor/rooms.ts +52 -0
  120. package/src/matrix/monitor/route.ts +179 -0
  121. package/src/matrix/monitor/runtime-api.ts +28 -0
  122. package/src/matrix/monitor/startup-verification.ts +237 -0
  123. package/src/matrix/monitor/startup.ts +218 -0
  124. package/src/matrix/monitor/status.ts +120 -0
  125. package/src/matrix/monitor/sync-lifecycle.ts +91 -0
  126. package/src/matrix/monitor/task-runner.ts +38 -0
  127. package/src/matrix/monitor/test-events.ts +21 -0
  128. package/src/matrix/monitor/thread-context.ts +108 -0
  129. package/src/matrix/monitor/threads.ts +85 -0
  130. package/src/matrix/monitor/types.ts +30 -0
  131. package/src/matrix/monitor/verification-events.ts +643 -0
  132. package/src/matrix/monitor/verification-utils.ts +46 -0
  133. package/src/matrix/outbound-media-runtime.ts +1 -0
  134. package/src/matrix/poll-summary.ts +110 -0
  135. package/src/matrix/poll-types.ts +429 -0
  136. package/src/matrix/probe.runtime.ts +4 -0
  137. package/src/matrix/probe.ts +97 -0
  138. package/src/matrix/profile.ts +184 -0
  139. package/src/matrix/reaction-common.ts +147 -0
  140. package/src/matrix/sdk/crypto-bootstrap.ts +438 -0
  141. package/src/matrix/sdk/crypto-facade.ts +242 -0
  142. package/src/matrix/sdk/crypto-node.runtime.ts +17 -0
  143. package/src/matrix/sdk/crypto-runtime.ts +14 -0
  144. package/src/matrix/sdk/decrypt-bridge.ts +410 -0
  145. package/src/matrix/sdk/event-helpers.ts +83 -0
  146. package/src/matrix/sdk/http-client.ts +87 -0
  147. package/src/matrix/sdk/idb-persistence-lock.ts +51 -0
  148. package/src/matrix/sdk/idb-persistence.ts +286 -0
  149. package/src/matrix/sdk/logger.ts +108 -0
  150. package/src/matrix/sdk/read-response-with-limit.ts +19 -0
  151. package/src/matrix/sdk/recovery-key-store.ts +453 -0
  152. package/src/matrix/sdk/timeout-abort-signal.ts +1 -0
  153. package/src/matrix/sdk/transport-runtime-api.ts +18 -0
  154. package/src/matrix/sdk/transport.ts +352 -0
  155. package/src/matrix/sdk/types.ts +245 -0
  156. package/src/matrix/sdk/verification-manager.ts +795 -0
  157. package/src/matrix/sdk/verification-status.ts +23 -0
  158. package/src/matrix/sdk.ts +2152 -0
  159. package/src/matrix/send/client.ts +93 -0
  160. package/src/matrix/send/formatting.ts +189 -0
  161. package/src/matrix/send/media.ts +244 -0
  162. package/src/matrix/send/targets.ts +104 -0
  163. package/src/matrix/send/types.ts +131 -0
  164. package/src/matrix/send.ts +660 -0
  165. package/src/matrix/session-store-metadata.ts +108 -0
  166. package/src/matrix/startup-abort.ts +44 -0
  167. package/src/matrix/subagent-hooks.ts +308 -0
  168. package/src/matrix/sync-state.ts +27 -0
  169. package/src/matrix/target-ids.ts +79 -0
  170. package/src/matrix/thread-bindings-shared.ts +206 -0
  171. package/src/matrix/thread-bindings.ts +580 -0
  172. package/src/matrix-migration.runtime.ts +9 -0
  173. package/src/migration-config.ts +243 -0
  174. package/src/migration-snapshot-backup.ts +116 -0
  175. package/src/migration-snapshot.ts +53 -0
  176. package/src/onboarding.ts +775 -0
  177. package/src/outbound.ts +248 -0
  178. package/src/plugin-entry.runtime.js +115 -0
  179. package/src/plugin-entry.runtime.ts +70 -0
  180. package/src/profile-update.ts +71 -0
  181. package/src/record-shared.ts +3 -0
  182. package/src/resolve-targets.ts +175 -0
  183. package/src/resolver.runtime.ts +5 -0
  184. package/src/resolver.ts +21 -0
  185. package/src/runtime-api.ts +106 -0
  186. package/src/runtime.ts +13 -0
  187. package/src/secret-contract.ts +174 -0
  188. package/src/session-route.ts +126 -0
  189. package/src/setup-bootstrap.ts +102 -0
  190. package/src/setup-config.ts +222 -0
  191. package/src/setup-contract.ts +90 -0
  192. package/src/setup-core.ts +146 -0
  193. package/src/setup-dm-policy.ts +15 -0
  194. package/src/setup-surface.ts +4 -0
  195. package/src/startup-maintenance.ts +114 -0
  196. package/src/storage-paths.ts +92 -0
  197. package/src/thread-binding-api.ts +23 -0
  198. package/src/tool-actions.runtime.ts +1 -0
  199. package/src/tool-actions.ts +498 -0
  200. package/src/types.ts +257 -0
  201. package/subagent-hooks-api.ts +31 -0
  202. package/test-api.ts +21 -0
  203. package/thread-binding-api.ts +4 -0
  204. package/thread-bindings-runtime.ts +4 -0
  205. package/tsconfig.json +16 -0
@@ -0,0 +1,795 @@
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
+ }