@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,352 @@
1
+ import { MatrixMediaSizeLimitError } from "../media-errors.js";
2
+ import { readResponseWithLimit } from "./read-response-with-limit.js";
3
+ import {
4
+ buildTimeoutAbortSignal,
5
+ closeDispatcher,
6
+ createPinnedDispatcher,
7
+ fetchWithRuntimeDispatcherOrMockedGlobal,
8
+ resolvePinnedHostnameWithPolicy,
9
+ type SsrFPolicy,
10
+ type PinnedDispatcherPolicy,
11
+ } from "./transport-runtime-api.js";
12
+
13
+ export type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
14
+
15
+ type QueryValue =
16
+ | string
17
+ | number
18
+ | boolean
19
+ | null
20
+ | undefined
21
+ | Array<string | number | boolean | null | undefined>;
22
+
23
+ export type QueryParams = Record<string, QueryValue> | null | undefined;
24
+
25
+ type MatrixDispatcherRequestInit = RequestInit & {
26
+ dispatcher?: ReturnType<typeof createPinnedDispatcher>;
27
+ };
28
+
29
+ function normalizeEndpoint(endpoint: string): string {
30
+ if (!endpoint) {
31
+ return "/";
32
+ }
33
+ return endpoint.startsWith("/") ? endpoint : `/${endpoint}`;
34
+ }
35
+
36
+ function applyQuery(url: URL, qs: QueryParams): void {
37
+ if (!qs) {
38
+ return;
39
+ }
40
+ for (const [key, rawValue] of Object.entries(qs)) {
41
+ if (rawValue === undefined || rawValue === null) {
42
+ continue;
43
+ }
44
+ if (Array.isArray(rawValue)) {
45
+ for (const item of rawValue) {
46
+ if (item === undefined || item === null) {
47
+ continue;
48
+ }
49
+ url.searchParams.append(key, String(item));
50
+ }
51
+ continue;
52
+ }
53
+ url.searchParams.set(key, String(rawValue));
54
+ }
55
+ }
56
+
57
+ function isRedirectStatus(statusCode: number): boolean {
58
+ return statusCode >= 300 && statusCode < 400;
59
+ }
60
+
61
+ function toFetchUrl(resource: RequestInfo | URL): string {
62
+ if (resource instanceof URL) {
63
+ return resource.toString();
64
+ }
65
+ if (typeof resource === "string") {
66
+ return resource;
67
+ }
68
+ return resource.url;
69
+ }
70
+
71
+ const MATRIX_STATE_AFTER_SYNC_PARAM = "org.matrix.msc4222.use_state_after";
72
+
73
+ function withoutMatrixStateAfterSyncParam(rawUrl: string): string {
74
+ let url: URL;
75
+ try {
76
+ url = new URL(rawUrl);
77
+ } catch {
78
+ return rawUrl;
79
+ }
80
+
81
+ if (!url.pathname.endsWith("/sync") || !url.searchParams.has(MATRIX_STATE_AFTER_SYNC_PARAM)) {
82
+ return rawUrl;
83
+ }
84
+
85
+ url.searchParams.delete(MATRIX_STATE_AFTER_SYNC_PARAM);
86
+ return url.toString();
87
+ }
88
+
89
+ function buildBufferedResponse(params: {
90
+ source: Response;
91
+ body: ArrayBuffer;
92
+ url: string;
93
+ }): Response {
94
+ const response = new Response(params.body, {
95
+ status: params.source.status,
96
+ statusText: params.source.statusText,
97
+ headers: new Headers(params.source.headers),
98
+ });
99
+ try {
100
+ Object.defineProperty(response, "url", {
101
+ value: params.source.url || params.url,
102
+ configurable: true,
103
+ });
104
+ } catch {
105
+ // Response.url is read-only in some runtimes; metadata is best-effort only.
106
+ }
107
+ return response;
108
+ }
109
+
110
+ async function fetchWithMatrixDispatcher(params: {
111
+ url: string;
112
+ init: MatrixDispatcherRequestInit;
113
+ }): Promise<Response> {
114
+ // Keep this dispatcher-routing logic local to Matrix transport. Shared SSRF
115
+ // fetches must stay fail-closed unless a retry path can preserve the
116
+ // validated pinned-address binding. Route dispatcher-attached requests
117
+ // through undici runtime fetch so the pinned dispatcher is preserved.
118
+ return await fetchWithRuntimeDispatcherOrMockedGlobal(params.url, params.init);
119
+ }
120
+
121
+ async function fetchWithMatrixGuardedRedirects(params: {
122
+ url: string;
123
+ init?: RequestInit;
124
+ signal?: AbortSignal;
125
+ timeoutMs?: number;
126
+ ssrfPolicy?: SsrFPolicy;
127
+ dispatcherPolicy?: PinnedDispatcherPolicy;
128
+ }): Promise<{ response: Response; release: () => Promise<void>; finalUrl: string }> {
129
+ let currentUrl = new URL(params.url);
130
+ let method = (params.init?.method ?? "GET").toUpperCase();
131
+ let body = params.init?.body;
132
+ let headers = new Headers(params.init?.headers ?? {});
133
+ const maxRedirects = 5;
134
+ const visited = new Set<string>();
135
+ const { signal, cleanup } = buildTimeoutAbortSignal({
136
+ timeoutMs: params.timeoutMs,
137
+ signal: params.signal,
138
+ operation: "matrix.guarded-redirect-fetch",
139
+ url: params.url,
140
+ });
141
+
142
+ for (let redirectCount = 0; redirectCount <= maxRedirects; redirectCount += 1) {
143
+ let dispatcher: ReturnType<typeof createPinnedDispatcher> | undefined;
144
+ try {
145
+ const pinned = await resolvePinnedHostnameWithPolicy(currentUrl.hostname, {
146
+ policy: params.ssrfPolicy,
147
+ });
148
+ dispatcher = createPinnedDispatcher(pinned, params.dispatcherPolicy, params.ssrfPolicy);
149
+ const response = await fetchWithMatrixDispatcher({
150
+ url: currentUrl.toString(),
151
+ init: {
152
+ ...params.init,
153
+ method,
154
+ body,
155
+ headers,
156
+ redirect: "manual",
157
+ signal,
158
+ dispatcher,
159
+ } as MatrixDispatcherRequestInit,
160
+ });
161
+
162
+ if (!isRedirectStatus(response.status)) {
163
+ return {
164
+ response,
165
+ release: async () => {
166
+ cleanup();
167
+ await closeDispatcher(dispatcher);
168
+ },
169
+ finalUrl: currentUrl.toString(),
170
+ };
171
+ }
172
+
173
+ const location = response.headers.get("location");
174
+ if (!location) {
175
+ cleanup();
176
+ await closeDispatcher(dispatcher);
177
+ throw new Error(`Matrix redirect missing location header (${currentUrl.toString()})`);
178
+ }
179
+
180
+ const nextUrl = new URL(location, currentUrl);
181
+ if (nextUrl.protocol !== currentUrl.protocol) {
182
+ cleanup();
183
+ await closeDispatcher(dispatcher);
184
+ throw new Error(
185
+ `Blocked cross-protocol redirect (${currentUrl.protocol} -> ${nextUrl.protocol})`,
186
+ );
187
+ }
188
+
189
+ const nextUrlString = nextUrl.toString();
190
+ if (visited.has(nextUrlString)) {
191
+ cleanup();
192
+ await closeDispatcher(dispatcher);
193
+ throw new Error("Redirect loop detected");
194
+ }
195
+ visited.add(nextUrlString);
196
+
197
+ if (nextUrl.origin !== currentUrl.origin) {
198
+ headers = new Headers(headers);
199
+ headers.delete("authorization");
200
+ }
201
+
202
+ if (
203
+ response.status === 303 ||
204
+ ((response.status === 301 || response.status === 302) &&
205
+ method !== "GET" &&
206
+ method !== "HEAD")
207
+ ) {
208
+ method = "GET";
209
+ body = undefined;
210
+ headers = new Headers(headers);
211
+ headers.delete("content-type");
212
+ headers.delete("content-length");
213
+ }
214
+
215
+ void response.body?.cancel();
216
+ await closeDispatcher(dispatcher);
217
+ currentUrl = nextUrl;
218
+ } catch (error) {
219
+ cleanup();
220
+ await closeDispatcher(dispatcher);
221
+ throw error;
222
+ }
223
+ }
224
+
225
+ cleanup();
226
+ throw new Error(`Too many redirects while requesting ${params.url}`);
227
+ }
228
+
229
+ export function createMatrixGuardedFetch(params: {
230
+ ssrfPolicy?: SsrFPolicy;
231
+ dispatcherPolicy?: PinnedDispatcherPolicy;
232
+ }): typeof fetch {
233
+ return (async (resource: RequestInfo | URL, init?: RequestInit) => {
234
+ const url = withoutMatrixStateAfterSyncParam(toFetchUrl(resource));
235
+ const { signal, ...requestInit } = init ?? {};
236
+ const { response, release } = await fetchWithMatrixGuardedRedirects({
237
+ url,
238
+ init: requestInit,
239
+ signal: signal ?? undefined,
240
+ ssrfPolicy: params.ssrfPolicy,
241
+ dispatcherPolicy: params.dispatcherPolicy,
242
+ });
243
+
244
+ try {
245
+ const body = await response.arrayBuffer();
246
+ return buildBufferedResponse({
247
+ source: response,
248
+ body,
249
+ url,
250
+ });
251
+ } finally {
252
+ await release();
253
+ }
254
+ }) as typeof fetch;
255
+ }
256
+
257
+ export async function performMatrixRequest(params: {
258
+ homeserver: string;
259
+ accessToken: string;
260
+ method: HttpMethod;
261
+ endpoint: string;
262
+ qs?: QueryParams;
263
+ body?: unknown;
264
+ timeoutMs: number;
265
+ raw?: boolean;
266
+ maxBytes?: number;
267
+ readIdleTimeoutMs?: number;
268
+ ssrfPolicy?: SsrFPolicy;
269
+ dispatcherPolicy?: PinnedDispatcherPolicy;
270
+ allowAbsoluteEndpoint?: boolean;
271
+ }): Promise<{ response: Response; text: string; buffer: Buffer }> {
272
+ const isAbsoluteEndpoint =
273
+ params.endpoint.startsWith("http://") || params.endpoint.startsWith("https://");
274
+ if (isAbsoluteEndpoint && params.allowAbsoluteEndpoint !== true) {
275
+ throw new Error(
276
+ `Absolute Matrix endpoint is blocked by default: ${params.endpoint}. Set allowAbsoluteEndpoint=true to opt in.`,
277
+ );
278
+ }
279
+
280
+ const baseUrl = isAbsoluteEndpoint
281
+ ? new URL(params.endpoint)
282
+ : new URL(normalizeEndpoint(params.endpoint), params.homeserver);
283
+ applyQuery(baseUrl, params.qs);
284
+
285
+ const headers = new Headers();
286
+ headers.set("Accept", params.raw ? "*/*" : "application/json");
287
+ if (params.accessToken) {
288
+ headers.set("Authorization", `Bearer ${params.accessToken}`);
289
+ }
290
+
291
+ let body: BodyInit | undefined;
292
+ if (params.body !== undefined) {
293
+ if (
294
+ params.body instanceof Uint8Array ||
295
+ params.body instanceof ArrayBuffer ||
296
+ typeof params.body === "string"
297
+ ) {
298
+ body = params.body as BodyInit;
299
+ } else {
300
+ headers.set("Content-Type", "application/json");
301
+ body = JSON.stringify(params.body);
302
+ }
303
+ }
304
+
305
+ const { response, release } = await fetchWithMatrixGuardedRedirects({
306
+ url: baseUrl.toString(),
307
+ init: {
308
+ method: params.method,
309
+ headers,
310
+ body,
311
+ },
312
+ timeoutMs: params.timeoutMs,
313
+ ssrfPolicy: params.ssrfPolicy,
314
+ dispatcherPolicy: params.dispatcherPolicy,
315
+ });
316
+
317
+ try {
318
+ if (params.raw) {
319
+ const contentLength = response.headers.get("content-length");
320
+ if (params.maxBytes && contentLength) {
321
+ const length = Number(contentLength);
322
+ if (Number.isFinite(length) && length > params.maxBytes) {
323
+ throw new MatrixMediaSizeLimitError(
324
+ `Matrix media exceeds configured size limit (${length} bytes > ${params.maxBytes} bytes)`,
325
+ );
326
+ }
327
+ }
328
+ const bytes = params.maxBytes
329
+ ? await readResponseWithLimit(response, params.maxBytes, {
330
+ onOverflow: ({ maxBytes, size }) =>
331
+ new MatrixMediaSizeLimitError(
332
+ `Matrix media exceeds configured size limit (${size} bytes > ${maxBytes} bytes)`,
333
+ ),
334
+ chunkTimeoutMs: params.readIdleTimeoutMs,
335
+ })
336
+ : Buffer.from(await response.arrayBuffer());
337
+ return {
338
+ response,
339
+ text: bytes.toString("utf8"),
340
+ buffer: bytes,
341
+ };
342
+ }
343
+ const text = await response.text();
344
+ return {
345
+ response,
346
+ text,
347
+ buffer: Buffer.from(text, "utf8"),
348
+ };
349
+ } finally {
350
+ await release();
351
+ }
352
+ }
@@ -0,0 +1,245 @@
1
+ import type { MatrixSyncState } from "../sync-state.js";
2
+ import type {
3
+ MatrixVerificationRequestLike,
4
+ MatrixVerificationSummary,
5
+ } from "./verification-manager.js";
6
+
7
+ export type MatrixRawEvent = {
8
+ event_id: string;
9
+ sender: string;
10
+ type: string;
11
+ origin_server_ts: number;
12
+ content: Record<string, unknown>;
13
+ unsigned?: {
14
+ age?: number;
15
+ "m.relations"?: Record<string, unknown>;
16
+ redacted_because?: unknown;
17
+ };
18
+ state_key?: string;
19
+ };
20
+
21
+ export type MatrixRelationsPage = {
22
+ originalEvent?: MatrixRawEvent | null;
23
+ events: MatrixRawEvent[];
24
+ nextBatch?: string | null;
25
+ prevBatch?: string | null;
26
+ };
27
+
28
+ export type MatrixClientEventMap = {
29
+ "room.event": [roomId: string, event: MatrixRawEvent];
30
+ "room.message": [roomId: string, event: MatrixRawEvent];
31
+ "room.encrypted_event": [roomId: string, event: MatrixRawEvent];
32
+ "room.decrypted_event": [roomId: string, event: MatrixRawEvent];
33
+ "room.failed_decryption": [roomId: string, event: MatrixRawEvent, error: Error];
34
+ "room.invite": [roomId: string, event: MatrixRawEvent];
35
+ "room.join": [roomId: string, event: MatrixRawEvent];
36
+ "sync.state": [state: MatrixSyncState, prevState: string | null, error?: unknown];
37
+ "sync.unexpected_error": [error: Error];
38
+ "verification.summary": [summary: MatrixVerificationSummary];
39
+ };
40
+
41
+ export type EncryptedFile = {
42
+ url: string;
43
+ key: {
44
+ kty: string;
45
+ key_ops: string[];
46
+ alg: string;
47
+ k: string;
48
+ ext: boolean;
49
+ };
50
+ iv: string;
51
+ hashes: Record<string, string>;
52
+ v: string;
53
+ };
54
+
55
+ export type FileWithThumbnailInfo = {
56
+ size?: number;
57
+ mimetype?: string;
58
+ thumbnail_url?: string;
59
+ thumbnail_file?: EncryptedFile;
60
+ thumbnail_info?: {
61
+ w?: number;
62
+ h?: number;
63
+ mimetype?: string;
64
+ size?: number;
65
+ };
66
+ };
67
+
68
+ export type DimensionalFileInfo = FileWithThumbnailInfo & {
69
+ w?: number;
70
+ h?: number;
71
+ };
72
+
73
+ export type TimedFileInfo = FileWithThumbnailInfo & {
74
+ duration?: number;
75
+ };
76
+
77
+ export type VideoFileInfo = DimensionalFileInfo &
78
+ TimedFileInfo & {
79
+ duration?: number;
80
+ };
81
+
82
+ export type MessageEventContent = {
83
+ msgtype?: string;
84
+ body?: string;
85
+ format?: string;
86
+ formatted_body?: string;
87
+ filename?: string;
88
+ url?: string;
89
+ file?: EncryptedFile;
90
+ info?: Record<string, unknown>;
91
+ "m.relates_to"?: Record<string, unknown>;
92
+ "m.new_content"?: unknown;
93
+ "m.mentions"?: {
94
+ user_ids?: string[];
95
+ room?: boolean;
96
+ };
97
+ [key: string]: unknown;
98
+ };
99
+
100
+ export type TextualMessageEventContent = MessageEventContent & {
101
+ msgtype: string;
102
+ body: string;
103
+ };
104
+
105
+ export type LocationMessageEventContent = MessageEventContent & {
106
+ msgtype?: string;
107
+ geo_uri?: string;
108
+ };
109
+
110
+ export type MatrixSecretStorageStatus = {
111
+ ready: boolean;
112
+ defaultKeyId: string | null;
113
+ secretStorageKeyValidityMap?: Record<string, boolean>;
114
+ };
115
+
116
+ export type MatrixGeneratedSecretStorageKey = {
117
+ keyId?: string | null;
118
+ keyInfo?: {
119
+ passphrase?: unknown;
120
+ name?: string;
121
+ };
122
+ privateKey: Uint8Array;
123
+ encodedPrivateKey?: string;
124
+ };
125
+
126
+ export type MatrixDeviceVerificationStatusLike = {
127
+ isVerified?: () => boolean;
128
+ localVerified?: boolean;
129
+ crossSigningVerified?: boolean;
130
+ signedByOwner?: boolean;
131
+ };
132
+
133
+ type MatrixKeyBackupInfo = {
134
+ algorithm: string;
135
+ auth_data: Record<string, unknown>;
136
+ count?: number;
137
+ etag?: string;
138
+ version?: string;
139
+ };
140
+
141
+ type MatrixKeyBackupTrustInfo = {
142
+ trusted: boolean;
143
+ matchesDecryptionKey: boolean;
144
+ };
145
+
146
+ type MatrixRoomKeyBackupRestoreResult = {
147
+ total: number;
148
+ imported: number;
149
+ };
150
+
151
+ type MatrixImportRoomKeyProgress = {
152
+ stage: string;
153
+ successes?: number;
154
+ failures?: number;
155
+ total?: number;
156
+ };
157
+
158
+ type MatrixSecretStorageKeyDescription = {
159
+ passphrase?: unknown;
160
+ name?: string;
161
+ [key: string]: unknown;
162
+ };
163
+
164
+ export type MatrixCryptoCallbacks = {
165
+ getSecretStorageKey?: (
166
+ params: { keys: Record<string, MatrixSecretStorageKeyDescription> },
167
+ name: string,
168
+ ) => Promise<[string, Uint8Array] | null>;
169
+ cacheSecretStorageKey?: (
170
+ keyId: string,
171
+ keyInfo: MatrixSecretStorageKeyDescription,
172
+ key: Uint8Array,
173
+ ) => void;
174
+ };
175
+
176
+ export type MatrixStoredRecoveryKey = {
177
+ version: 1;
178
+ createdAt: string;
179
+ keyId?: string | null;
180
+ encodedPrivateKey?: string;
181
+ privateKeyBase64: string;
182
+ keyInfo?: {
183
+ passphrase?: unknown;
184
+ name?: string;
185
+ };
186
+ };
187
+
188
+ export type MatrixAuthDict = Record<string, unknown>;
189
+
190
+ export type MatrixUiAuthCallback = <T>(
191
+ makeRequest: (authData: MatrixAuthDict | null) => Promise<T>,
192
+ ) => Promise<T>;
193
+
194
+ export type MatrixCryptoBootstrapApi = {
195
+ on: (eventName: string, listener: (...args: unknown[]) => void) => void;
196
+ bootstrapCrossSigning: (opts: {
197
+ setupNewCrossSigning?: boolean;
198
+ authUploadDeviceSigningKeys?: MatrixUiAuthCallback;
199
+ }) => Promise<void>;
200
+ bootstrapSecretStorage: (opts?: {
201
+ createSecretStorageKey?: () => Promise<MatrixGeneratedSecretStorageKey>;
202
+ setupNewSecretStorage?: boolean;
203
+ setupNewKeyBackup?: boolean;
204
+ }) => Promise<void>;
205
+ createRecoveryKeyFromPassphrase?: (password?: string) => Promise<MatrixGeneratedSecretStorageKey>;
206
+ getSecretStorageStatus?: () => Promise<MatrixSecretStorageStatus>;
207
+ requestOwnUserVerification: () => Promise<MatrixVerificationRequestLike | null>;
208
+ findVerificationRequestDMInProgress?: (
209
+ roomId: string,
210
+ userId: string,
211
+ ) => MatrixVerificationRequestLike | undefined;
212
+ requestDeviceVerification?: (
213
+ userId: string,
214
+ deviceId: string,
215
+ ) => Promise<MatrixVerificationRequestLike>;
216
+ requestVerificationDM?: (
217
+ userId: string,
218
+ roomId: string,
219
+ ) => Promise<MatrixVerificationRequestLike>;
220
+ getDeviceVerificationStatus?: (
221
+ userId: string,
222
+ deviceId: string,
223
+ ) => Promise<MatrixDeviceVerificationStatusLike | null>;
224
+ getSessionBackupPrivateKey?: () => Promise<Uint8Array | null>;
225
+ loadSessionBackupPrivateKeyFromSecretStorage?: () => Promise<void>;
226
+ getActiveSessionBackupVersion?: () => Promise<string | null>;
227
+ getKeyBackupInfo?: () => Promise<MatrixKeyBackupInfo | null>;
228
+ isKeyBackupTrusted?: (info: MatrixKeyBackupInfo) => Promise<MatrixKeyBackupTrustInfo>;
229
+ checkKeyBackupAndEnable?: () => Promise<unknown>;
230
+ restoreKeyBackup?: (opts?: {
231
+ progressCallback?: (progress: MatrixImportRoomKeyProgress) => void;
232
+ }) => Promise<MatrixRoomKeyBackupRestoreResult>;
233
+ setDeviceVerified?: (userId: string, deviceId: string, verified?: boolean) => Promise<void>;
234
+ crossSignDevice?: (deviceId: string) => Promise<void>;
235
+ getOwnIdentity?: () => Promise<
236
+ | {
237
+ free?: () => void;
238
+ isVerified?: () => boolean;
239
+ verify?: () => Promise<unknown>;
240
+ }
241
+ | undefined
242
+ >;
243
+ isCrossSigningReady?: () => Promise<boolean>;
244
+ userHasCrossSigningKeys?: (userId?: string, downloadUncached?: boolean) => Promise<boolean>;
245
+ };