@kodelyth/matrix 2026.5.39 → 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 (117) hide show
  1. package/dist/account-selection-Y50DNJ2l.js +158 -0
  2. package/dist/active-client-CmFdvPdO.js +20 -0
  3. package/dist/api.js +12 -0
  4. package/dist/approval-handler.runtime-BIi4fL0R.js +377 -0
  5. package/dist/approval-ids-BGHK7PnZ.js +7 -0
  6. package/dist/approval-reaction-auth-CL0-nCNV.js +27 -0
  7. package/dist/approval-reactions-nDm2x-K5.js +162 -0
  8. package/dist/async-lock-SsmtFXtt.js +19 -0
  9. package/dist/auth-presence.js +26 -0
  10. package/dist/backup-health-3BHbHxyd.js +60 -0
  11. package/dist/channel-C0kCyTNB.js +1380 -0
  12. package/dist/channel-plugin-api.js +2 -0
  13. package/dist/channel.runtime-CdrdEN-0.js +250 -0
  14. package/dist/cli-FtY6Nuzw.js +1338 -0
  15. package/dist/cli-metadata-Dkwua7CB.js +22 -0
  16. package/dist/cli-metadata.js +2 -0
  17. package/dist/client-BnohYygh.js +25 -0
  18. package/dist/client-PhrTwuC4.js +30 -0
  19. package/dist/client-bootstrap-Mcj8ChJ5.js +114 -0
  20. package/dist/config-paths-DVvt6vM3.js +114 -0
  21. package/dist/config-schema-BMGOlhdI.js +308 -0
  22. package/dist/config-secret-input.runtime-Dv_4Br_f.js +2 -0
  23. package/dist/contract-api.js +8 -0
  24. package/dist/create-client-J0htTaRj.js +64 -0
  25. package/dist/credentials-B7GsBbgQ.js +56 -0
  26. package/dist/credentials-read-8fE4qoWs.js +112 -0
  27. package/dist/credentials-write.runtime-BibplB4Y.js +17 -0
  28. package/dist/crypto-node.runtime-D9qxgRPa.js +12 -0
  29. package/dist/crypto-runtime-1pKW4O2F.js +1214 -0
  30. package/dist/deps-DVpDS81G.js +208 -0
  31. package/dist/device-health-Ct2wDSPG.js +16 -0
  32. package/dist/directory-live-i3T8uORc.js +150 -0
  33. package/dist/doctor-contract-BLzYHl_9.js +246 -0
  34. package/dist/doctor-contract-api.js +2 -0
  35. package/dist/doctor-diR5gE7D.js +153 -0
  36. package/dist/draft-stream-HpPJ_VJt.js +143 -0
  37. package/dist/encryption-guidance-BNEgckrZ.js +15 -0
  38. package/dist/env-auth-UFiTGkDM.js +63 -0
  39. package/dist/env-vars-EQKQv-FE.js +63 -0
  40. package/dist/errors-BETj3zr9.js +17 -0
  41. package/dist/exec-approval-resolver-BxPorU_t.js +15 -0
  42. package/dist/helper-api.js +4 -0
  43. package/dist/http-client-DoQgbQsU.js +331 -0
  44. package/dist/index.js +46 -0
  45. package/dist/legacy-crypto-inspector-zK0hDCbt.js +41 -0
  46. package/dist/legacy-crypto-restore-DSFIXuDo.js +85 -0
  47. package/dist/logging-Df7aPD1z.js +99 -0
  48. package/dist/matrix-migration.runtime-BNoT1Prt.js +525 -0
  49. package/dist/media-text-ZhGA8Pcs.js +146 -0
  50. package/dist/messages-CRA9WGg0.js +140 -0
  51. package/dist/migration-snapshot-backup-BR-xD7Ew.js +69 -0
  52. package/dist/migration-snapshot.runtime-BLcy_Nvw.js +2 -0
  53. package/dist/monitor-DQm7_13y.js +4331 -0
  54. package/dist/plugin-entry.handlers.runtime.js +51 -0
  55. package/dist/probe.runtime-CjJS53Kz.js +3 -0
  56. package/dist/profile-update-DqkPgZ1P.js +68 -0
  57. package/dist/reaction-common-CmVLzP-u.js +71 -0
  58. package/dist/reaction-events-D0nUJuZV.js +121 -0
  59. package/dist/record-shared-DGvSFn5M.js +2 -0
  60. package/dist/resolve-targets-ChECUzD2.js +140 -0
  61. package/dist/resolver.runtime-hdY3n0GO.js +5 -0
  62. package/dist/rolldown-runtime-DUslC3ob.js +14 -0
  63. package/dist/route-xRKj_ESW.js +161 -0
  64. package/dist/runtime-B-Fyrmxo.js +8 -0
  65. package/dist/runtime-api-BYXXkxq2.js +24 -0
  66. package/dist/runtime-api.js +25 -0
  67. package/dist/runtime-heavy-api.js +3 -0
  68. package/dist/runtime-lwTSy9Yt.js +6 -0
  69. package/dist/runtime-setter-api.js +2 -0
  70. package/dist/sdk-Jhq7mLtD.js +1704 -0
  71. package/dist/secret-contract-DEMcDsjl.js +120 -0
  72. package/dist/secret-contract-api.js +2 -0
  73. package/dist/send-CJunc6QM.js +1517 -0
  74. package/dist/setup-bootstrap-rJ0qZWPe.js +62 -0
  75. package/dist/setup-core-BEYoXF3J.js +677 -0
  76. package/dist/setup-entry.js +19 -0
  77. package/dist/setup-plugin-api.js +43 -0
  78. package/dist/setup-surface-c28ON6jq.js +537 -0
  79. package/dist/shared-D6MFMnpG.js +642 -0
  80. package/dist/startup-abort-B2J3MU_h.js +109 -0
  81. package/dist/startup-verification-CkD4Cwce.js +132 -0
  82. package/dist/storage-nyO0DOFE.js +281 -0
  83. package/dist/storage-paths-BTAketfg.js +52 -0
  84. package/dist/subagent-hooks-api-Dr_xnMRG.js +170 -0
  85. package/dist/subagent-hooks-api.js +2 -0
  86. package/dist/sync-state-Bx0gPaGA.js +12 -0
  87. package/dist/target-ids-Bsazo8si.js +77 -0
  88. package/dist/test-api.js +4 -0
  89. package/dist/thread-binding-api-IGU0-L70.js +17 -0
  90. package/dist/thread-binding-api.js +2 -0
  91. package/dist/thread-bindings-FjAZmDUP.js +352 -0
  92. package/dist/thread-bindings-runtime.js +2 -0
  93. package/dist/thread-bindings-shared-fvfP7jVs.js +97 -0
  94. package/dist/timeout-abort-signal-DpSHDHhR.js +2 -0
  95. package/dist/tool-actions.runtime-Cbo7YcYZ.js +532 -0
  96. package/dist/url-validation-DlrXNjAE.js +36 -0
  97. package/dist/verification-7tDPRpJU.js +345 -0
  98. package/package.json +19 -7
  99. package/api.js +0 -7
  100. package/auth-presence.js +0 -7
  101. package/channel-plugin-api.js +0 -7
  102. package/cli-metadata.js +0 -7
  103. package/contract-api.js +0 -7
  104. package/doctor-contract-api.js +0 -7
  105. package/helper-api.js +0 -7
  106. package/index.js +0 -7
  107. package/plugin-entry.handlers.runtime.js +0 -7
  108. package/runtime-api.js +0 -7
  109. package/runtime-heavy-api.js +0 -7
  110. package/runtime-setter-api.js +0 -7
  111. package/secret-contract-api.js +0 -7
  112. package/setup-entry.js +0 -7
  113. package/setup-plugin-api.js +0 -7
  114. package/subagent-hooks-api.js +0 -7
  115. package/test-api.js +0 -7
  116. package/thread-binding-api.js +0 -7
  117. package/thread-bindings-runtime.js +0 -7
@@ -0,0 +1,331 @@
1
+ import { t as buildTimeoutAbortSignal } from "./timeout-abort-signal-DpSHDHhR.js";
2
+ import { readResponseWithLimit } from "klaw/plugin-sdk/response-limit-runtime";
3
+ import { fetchWithRuntimeDispatcherOrMockedGlobal } from "klaw/plugin-sdk/runtime-fetch";
4
+ import { closeDispatcher, createPinnedDispatcher, resolvePinnedHostnameWithPolicy } from "klaw/plugin-sdk/ssrf-dispatcher";
5
+ //#region extensions/matrix/src/matrix/sdk/event-helpers.ts
6
+ function matrixEventToRaw(event, opts = {}) {
7
+ const unsigned = event.getUnsigned?.() ?? {};
8
+ const eventWithOriginalContent = event;
9
+ const content = opts.contentMode === "original" ? eventWithOriginalContent.getOriginalContent?.() ?? event.getContent?.() ?? {} : event.getContent?.() ?? eventWithOriginalContent.getOriginalContent?.() ?? {};
10
+ const raw = {
11
+ event_id: event.getId() ?? "",
12
+ sender: event.getSender() ?? "",
13
+ type: event.getType() ?? "",
14
+ origin_server_ts: event.getTs() ?? 0,
15
+ content: content || {},
16
+ unsigned
17
+ };
18
+ const stateKey = resolveMatrixStateKey(event);
19
+ if (typeof stateKey === "string") raw.state_key = stateKey;
20
+ return raw;
21
+ }
22
+ function parseMxc(url) {
23
+ const match = /^mxc:\/\/([^/]+)\/(.+)$/.exec(url.trim());
24
+ if (!match) return null;
25
+ return {
26
+ server: match[1],
27
+ mediaId: match[2]
28
+ };
29
+ }
30
+ function buildHttpError(statusCode, bodyText) {
31
+ let message = `Matrix HTTP ${statusCode}`;
32
+ if (bodyText.trim()) try {
33
+ const parsed = JSON.parse(bodyText);
34
+ if (typeof parsed.error === "string" && parsed.error.trim()) message = parsed.error.trim();
35
+ else message = bodyText.slice(0, 500);
36
+ } catch {
37
+ message = bodyText.slice(0, 500);
38
+ }
39
+ return Object.assign(new Error(message), { statusCode });
40
+ }
41
+ function resolveMatrixStateKey(event) {
42
+ const direct = event.getStateKey?.();
43
+ if (typeof direct === "string") return direct;
44
+ const wireContent = event.getWireContent?.();
45
+ if (wireContent && typeof wireContent.state_key === "string") return wireContent.state_key;
46
+ const rawEvent = event.event;
47
+ if (rawEvent && typeof rawEvent.state_key === "string") return rawEvent.state_key;
48
+ }
49
+ //#endregion
50
+ //#region extensions/matrix/src/matrix/media-errors.ts
51
+ const MATRIX_MEDIA_SIZE_LIMIT_ERROR_MESSAGE = "Matrix media exceeds configured size limit";
52
+ var MatrixMediaSizeLimitError = class extends Error {
53
+ constructor(message = MATRIX_MEDIA_SIZE_LIMIT_ERROR_MESSAGE, options) {
54
+ super(message, options);
55
+ this.code = "MATRIX_MEDIA_SIZE_LIMIT";
56
+ this.name = "MatrixMediaSizeLimitError";
57
+ }
58
+ };
59
+ function isMatrixMediaSizeLimitError(err) {
60
+ if (err instanceof MatrixMediaSizeLimitError) return true;
61
+ if (!(err instanceof Error) || err.cause === void 0) return false;
62
+ return isMatrixMediaSizeLimitError(err.cause);
63
+ }
64
+ //#endregion
65
+ //#region extensions/matrix/src/matrix/sdk/read-response-with-limit.ts
66
+ async function readResponseWithLimit$1(res, maxBytes, opts) {
67
+ return await readResponseWithLimit(res, maxBytes, {
68
+ ...opts,
69
+ onIdleTimeout: opts?.onIdleTimeout ?? (({ chunkTimeoutMs }) => /* @__PURE__ */ new Error(`Matrix media download stalled: no data received for ${chunkTimeoutMs}ms`))
70
+ });
71
+ }
72
+ //#endregion
73
+ //#region extensions/matrix/src/matrix/sdk/transport.ts
74
+ function normalizeEndpoint(endpoint) {
75
+ if (!endpoint) return "/";
76
+ return endpoint.startsWith("/") ? endpoint : `/${endpoint}`;
77
+ }
78
+ function applyQuery(url, qs) {
79
+ if (!qs) return;
80
+ for (const [key, rawValue] of Object.entries(qs)) {
81
+ if (rawValue === void 0 || rawValue === null) continue;
82
+ if (Array.isArray(rawValue)) {
83
+ for (const item of rawValue) {
84
+ if (item === void 0 || item === null) continue;
85
+ url.searchParams.append(key, String(item));
86
+ }
87
+ continue;
88
+ }
89
+ url.searchParams.set(key, String(rawValue));
90
+ }
91
+ }
92
+ function isRedirectStatus(statusCode) {
93
+ return statusCode >= 300 && statusCode < 400;
94
+ }
95
+ function toFetchUrl(resource) {
96
+ if (resource instanceof URL) return resource.toString();
97
+ if (typeof resource === "string") return resource;
98
+ return resource.url;
99
+ }
100
+ const MATRIX_STATE_AFTER_SYNC_PARAM = "org.matrix.msc4222.use_state_after";
101
+ function withoutMatrixStateAfterSyncParam(rawUrl) {
102
+ let url;
103
+ try {
104
+ url = new URL(rawUrl);
105
+ } catch {
106
+ return rawUrl;
107
+ }
108
+ if (!url.pathname.endsWith("/sync") || !url.searchParams.has(MATRIX_STATE_AFTER_SYNC_PARAM)) return rawUrl;
109
+ url.searchParams.delete(MATRIX_STATE_AFTER_SYNC_PARAM);
110
+ return url.toString();
111
+ }
112
+ function buildBufferedResponse(params) {
113
+ const response = new Response(params.body, {
114
+ status: params.source.status,
115
+ statusText: params.source.statusText,
116
+ headers: new Headers(params.source.headers)
117
+ });
118
+ try {
119
+ Object.defineProperty(response, "url", {
120
+ value: params.source.url || params.url,
121
+ configurable: true
122
+ });
123
+ } catch {}
124
+ return response;
125
+ }
126
+ async function fetchWithMatrixDispatcher(params) {
127
+ return await fetchWithRuntimeDispatcherOrMockedGlobal(params.url, params.init);
128
+ }
129
+ async function fetchWithMatrixGuardedRedirects(params) {
130
+ let currentUrl = new URL(params.url);
131
+ let method = (params.init?.method ?? "GET").toUpperCase();
132
+ let body = params.init?.body;
133
+ let headers = new Headers(params.init?.headers ?? {});
134
+ const maxRedirects = 5;
135
+ const visited = /* @__PURE__ */ new Set();
136
+ const { signal, cleanup } = buildTimeoutAbortSignal({
137
+ timeoutMs: params.timeoutMs,
138
+ signal: params.signal,
139
+ operation: "matrix.guarded-redirect-fetch",
140
+ url: params.url
141
+ });
142
+ for (let redirectCount = 0; redirectCount <= maxRedirects; redirectCount += 1) {
143
+ let dispatcher;
144
+ try {
145
+ dispatcher = createPinnedDispatcher(await resolvePinnedHostnameWithPolicy(currentUrl.hostname, { policy: params.ssrfPolicy }), params.dispatcherPolicy, params.ssrfPolicy);
146
+ const response = await fetchWithMatrixDispatcher({
147
+ url: currentUrl.toString(),
148
+ init: {
149
+ ...params.init,
150
+ method,
151
+ body,
152
+ headers,
153
+ redirect: "manual",
154
+ signal,
155
+ dispatcher
156
+ }
157
+ });
158
+ if (!isRedirectStatus(response.status)) return {
159
+ response,
160
+ release: async () => {
161
+ cleanup();
162
+ await closeDispatcher(dispatcher);
163
+ },
164
+ finalUrl: currentUrl.toString()
165
+ };
166
+ const location = response.headers.get("location");
167
+ if (!location) {
168
+ cleanup();
169
+ await closeDispatcher(dispatcher);
170
+ throw new Error(`Matrix redirect missing location header (${currentUrl.toString()})`);
171
+ }
172
+ const nextUrl = new URL(location, currentUrl);
173
+ if (nextUrl.protocol !== currentUrl.protocol) {
174
+ cleanup();
175
+ await closeDispatcher(dispatcher);
176
+ throw new Error(`Blocked cross-protocol redirect (${currentUrl.protocol} -> ${nextUrl.protocol})`);
177
+ }
178
+ const nextUrlString = nextUrl.toString();
179
+ if (visited.has(nextUrlString)) {
180
+ cleanup();
181
+ await closeDispatcher(dispatcher);
182
+ throw new Error("Redirect loop detected");
183
+ }
184
+ visited.add(nextUrlString);
185
+ if (nextUrl.origin !== currentUrl.origin) {
186
+ headers = new Headers(headers);
187
+ headers.delete("authorization");
188
+ }
189
+ if (response.status === 303 || (response.status === 301 || response.status === 302) && method !== "GET" && method !== "HEAD") {
190
+ method = "GET";
191
+ body = void 0;
192
+ headers = new Headers(headers);
193
+ headers.delete("content-type");
194
+ headers.delete("content-length");
195
+ }
196
+ response.body?.cancel();
197
+ await closeDispatcher(dispatcher);
198
+ currentUrl = nextUrl;
199
+ } catch (error) {
200
+ cleanup();
201
+ await closeDispatcher(dispatcher);
202
+ throw error;
203
+ }
204
+ }
205
+ cleanup();
206
+ throw new Error(`Too many redirects while requesting ${params.url}`);
207
+ }
208
+ function createMatrixGuardedFetch(params) {
209
+ return (async (resource, init) => {
210
+ const url = withoutMatrixStateAfterSyncParam(toFetchUrl(resource));
211
+ const { signal, ...requestInit } = init ?? {};
212
+ const { response, release } = await fetchWithMatrixGuardedRedirects({
213
+ url,
214
+ init: requestInit,
215
+ signal: signal ?? void 0,
216
+ ssrfPolicy: params.ssrfPolicy,
217
+ dispatcherPolicy: params.dispatcherPolicy
218
+ });
219
+ try {
220
+ return buildBufferedResponse({
221
+ source: response,
222
+ body: await response.arrayBuffer(),
223
+ url
224
+ });
225
+ } finally {
226
+ await release();
227
+ }
228
+ });
229
+ }
230
+ async function performMatrixRequest(params) {
231
+ const isAbsoluteEndpoint = params.endpoint.startsWith("http://") || params.endpoint.startsWith("https://");
232
+ if (isAbsoluteEndpoint && params.allowAbsoluteEndpoint !== true) throw new Error(`Absolute Matrix endpoint is blocked by default: ${params.endpoint}. Set allowAbsoluteEndpoint=true to opt in.`);
233
+ const baseUrl = isAbsoluteEndpoint ? new URL(params.endpoint) : new URL(normalizeEndpoint(params.endpoint), params.homeserver);
234
+ applyQuery(baseUrl, params.qs);
235
+ const headers = new Headers();
236
+ headers.set("Accept", params.raw ? "*/*" : "application/json");
237
+ if (params.accessToken) headers.set("Authorization", `Bearer ${params.accessToken}`);
238
+ let body;
239
+ if (params.body !== void 0) if (params.body instanceof Uint8Array || params.body instanceof ArrayBuffer || typeof params.body === "string") body = params.body;
240
+ else {
241
+ headers.set("Content-Type", "application/json");
242
+ body = JSON.stringify(params.body);
243
+ }
244
+ const { response, release } = await fetchWithMatrixGuardedRedirects({
245
+ url: baseUrl.toString(),
246
+ init: {
247
+ method: params.method,
248
+ headers,
249
+ body
250
+ },
251
+ timeoutMs: params.timeoutMs,
252
+ ssrfPolicy: params.ssrfPolicy,
253
+ dispatcherPolicy: params.dispatcherPolicy
254
+ });
255
+ try {
256
+ if (params.raw) {
257
+ const contentLength = response.headers.get("content-length");
258
+ if (params.maxBytes && contentLength) {
259
+ const length = Number(contentLength);
260
+ if (Number.isFinite(length) && length > params.maxBytes) throw new MatrixMediaSizeLimitError(`Matrix media exceeds configured size limit (${length} bytes > ${params.maxBytes} bytes)`);
261
+ }
262
+ const bytes = params.maxBytes ? await readResponseWithLimit$1(response, params.maxBytes, {
263
+ onOverflow: ({ maxBytes, size }) => new MatrixMediaSizeLimitError(`Matrix media exceeds configured size limit (${size} bytes > ${maxBytes} bytes)`),
264
+ chunkTimeoutMs: params.readIdleTimeoutMs
265
+ }) : Buffer.from(await response.arrayBuffer());
266
+ return {
267
+ response,
268
+ text: bytes.toString("utf8"),
269
+ buffer: bytes
270
+ };
271
+ }
272
+ const text = await response.text();
273
+ return {
274
+ response,
275
+ text,
276
+ buffer: Buffer.from(text, "utf8")
277
+ };
278
+ } finally {
279
+ await release();
280
+ }
281
+ }
282
+ //#endregion
283
+ //#region extensions/matrix/src/matrix/sdk/http-client.ts
284
+ var MatrixAuthedHttpClient = class {
285
+ constructor(params) {
286
+ this.homeserver = params.homeserver;
287
+ this.accessToken = params.accessToken;
288
+ this.ssrfPolicy = params.ssrfPolicy;
289
+ this.dispatcherPolicy = params.dispatcherPolicy;
290
+ }
291
+ async requestJson(params) {
292
+ const { response, text } = await performMatrixRequest({
293
+ homeserver: this.homeserver,
294
+ accessToken: this.accessToken,
295
+ method: params.method,
296
+ endpoint: params.endpoint,
297
+ qs: params.qs,
298
+ body: params.body,
299
+ timeoutMs: params.timeoutMs,
300
+ ssrfPolicy: this.ssrfPolicy,
301
+ dispatcherPolicy: this.dispatcherPolicy,
302
+ allowAbsoluteEndpoint: params.allowAbsoluteEndpoint
303
+ });
304
+ if (!response.ok) throw buildHttpError(response.status, text);
305
+ if ((response.headers.get("content-type") ?? "").includes("application/json")) {
306
+ if (!text.trim()) return {};
307
+ return JSON.parse(text);
308
+ }
309
+ return text;
310
+ }
311
+ async requestRaw(params) {
312
+ const { response, buffer } = await performMatrixRequest({
313
+ homeserver: this.homeserver,
314
+ accessToken: this.accessToken,
315
+ method: params.method,
316
+ endpoint: params.endpoint,
317
+ qs: params.qs,
318
+ timeoutMs: params.timeoutMs,
319
+ raw: true,
320
+ maxBytes: params.maxBytes,
321
+ readIdleTimeoutMs: params.readIdleTimeoutMs,
322
+ ssrfPolicy: this.ssrfPolicy,
323
+ dispatcherPolicy: this.dispatcherPolicy,
324
+ allowAbsoluteEndpoint: params.allowAbsoluteEndpoint
325
+ });
326
+ if (!response.ok) throw buildHttpError(response.status, buffer.toString("utf8"));
327
+ return buffer;
328
+ }
329
+ };
330
+ //#endregion
331
+ export { matrixEventToRaw as a, isMatrixMediaSizeLimitError as i, createMatrixGuardedFetch as n, parseMxc as o, MatrixMediaSizeLimitError as r, MatrixAuthedHttpClient as t };
package/dist/index.js ADDED
@@ -0,0 +1,46 @@
1
+ import { n as registerMatrixCliMetadata } from "./cli-metadata-Dkwua7CB.js";
2
+ import { t as registerMatrixSubagentHooks } from "./subagent-hooks-api-Dr_xnMRG.js";
3
+ import { defineBundledChannelEntry } from "klaw/plugin-sdk/channel-entry-contract";
4
+ //#region extensions/matrix/index.ts
5
+ let matrixHandlersRuntimePromise = null;
6
+ function loadMatrixHandlersRuntimeModule() {
7
+ matrixHandlersRuntimePromise ??= import("./plugin-entry.handlers.runtime.js");
8
+ return matrixHandlersRuntimePromise;
9
+ }
10
+ function registerMatrixFullRuntime(api) {
11
+ api.registerGatewayMethod("matrix.verify.recoveryKey", async (ctx) => {
12
+ const { handleVerifyRecoveryKey } = await loadMatrixHandlersRuntimeModule();
13
+ await handleVerifyRecoveryKey(ctx);
14
+ });
15
+ api.registerGatewayMethod("matrix.verify.bootstrap", async (ctx) => {
16
+ const { handleVerificationBootstrap } = await loadMatrixHandlersRuntimeModule();
17
+ await handleVerificationBootstrap(ctx);
18
+ });
19
+ api.registerGatewayMethod("matrix.verify.status", async (ctx) => {
20
+ const { handleVerificationStatus } = await loadMatrixHandlersRuntimeModule();
21
+ await handleVerificationStatus(ctx);
22
+ });
23
+ registerMatrixSubagentHooks(api);
24
+ }
25
+ var matrix_default = defineBundledChannelEntry({
26
+ id: "matrix",
27
+ name: "Matrix",
28
+ description: "Matrix channel plugin (matrix-js-sdk)",
29
+ importMetaUrl: import.meta.url,
30
+ plugin: {
31
+ specifier: "./channel-plugin-api.js",
32
+ exportName: "matrixPlugin"
33
+ },
34
+ secrets: {
35
+ specifier: "./secret-contract-api.js",
36
+ exportName: "channelSecrets"
37
+ },
38
+ runtime: {
39
+ specifier: "./runtime-setter-api.js",
40
+ exportName: "setMatrixRuntime"
41
+ },
42
+ registerCliMetadata: registerMatrixCliMetadata,
43
+ registerFull: registerMatrixFullRuntime
44
+ });
45
+ //#endregion
46
+ export { matrix_default as default, registerMatrixFullRuntime };
@@ -0,0 +1,41 @@
1
+ import { t as ensureMatrixCryptoRuntime } from "./deps-DVpDS81G.js";
2
+ import { createRequire } from "node:module";
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import crypto from "node:crypto";
6
+ //#region extensions/matrix/src/matrix/legacy-crypto-inspector.ts
7
+ function resolveLegacyMachineStorePath(params) {
8
+ const hashedDir = path.join(params.cryptoRootDir, crypto.createHash("sha256").update(params.deviceId).digest("hex"));
9
+ if (fs.existsSync(path.join(hashedDir, "matrix-sdk-crypto.sqlite3"))) return hashedDir;
10
+ if (fs.existsSync(path.join(params.cryptoRootDir, "matrix-sdk-crypto.sqlite3"))) return params.cryptoRootDir;
11
+ const match = fs.readdirSync(params.cryptoRootDir, { withFileTypes: true }).find((entry) => entry.isDirectory() && fs.existsSync(path.join(params.cryptoRootDir, entry.name, "matrix-sdk-crypto.sqlite3")));
12
+ return match ? path.join(params.cryptoRootDir, match.name) : null;
13
+ }
14
+ async function inspectLegacyMatrixCryptoStore(params) {
15
+ const machineStorePath = resolveLegacyMachineStorePath(params);
16
+ if (!machineStorePath) throw new Error(`Matrix legacy crypto store not found for device ${params.deviceId}`);
17
+ const requireFn = createRequire(import.meta.url);
18
+ await ensureMatrixCryptoRuntime({
19
+ requireFn,
20
+ resolveFn: requireFn.resolve.bind(requireFn),
21
+ log: params.log
22
+ });
23
+ const { DeviceId, OlmMachine, StoreType, UserId } = requireFn("@matrix-org/matrix-sdk-crypto-nodejs");
24
+ const machine = await OlmMachine.initialize(new UserId(params.userId), new DeviceId(params.deviceId), machineStorePath, "", StoreType.Sqlite);
25
+ try {
26
+ const [backupKeys, roomKeyCounts] = await Promise.all([machine.getBackupKeys(), machine.roomKeyCounts()]);
27
+ return {
28
+ deviceId: params.deviceId,
29
+ roomKeyCounts: roomKeyCounts ? {
30
+ total: typeof roomKeyCounts.total === "number" ? roomKeyCounts.total : 0,
31
+ backedUp: typeof roomKeyCounts.backedUp === "number" ? roomKeyCounts.backedUp : 0
32
+ } : null,
33
+ backupVersion: typeof backupKeys?.backupVersion === "string" && backupKeys.backupVersion.trim() ? backupKeys.backupVersion : null,
34
+ decryptionKeyBase64: typeof backupKeys?.decryptionKeyBase64 === "string" && backupKeys.decryptionKeyBase64.trim() ? backupKeys.decryptionKeyBase64 : null
35
+ };
36
+ } finally {
37
+ machine.close();
38
+ }
39
+ }
40
+ //#endregion
41
+ export { inspectLegacyMatrixCryptoStore };
@@ -0,0 +1,85 @@
1
+ import { t as getMatrixRuntime } from "./runtime-B-Fyrmxo.js";
2
+ import { a as resolveMatrixStoragePaths } from "./storage-nyO0DOFE.js";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { readJsonFileWithFallback, writeJsonFileAtomically } from "klaw/plugin-sdk/json-store";
6
+ import fs from "node:fs/promises";
7
+ //#region extensions/matrix/src/matrix/monitor/legacy-crypto-restore.ts
8
+ function isMigrationState(value) {
9
+ return Boolean(value) && typeof value === "object" && value.version === 1;
10
+ }
11
+ async function resolvePendingMigrationStatePath(params) {
12
+ const { rootDir } = resolveMatrixStoragePaths({
13
+ homeserver: params.auth.homeserver,
14
+ userId: params.auth.userId,
15
+ accessToken: params.auth.accessToken,
16
+ accountId: params.auth.accountId,
17
+ deviceId: params.auth.deviceId,
18
+ stateDir: params.stateDir
19
+ });
20
+ const directStatePath = path.join(rootDir, "legacy-crypto-migration.json");
21
+ const { value: directValue } = await readJsonFileWithFallback(directStatePath, null);
22
+ if (isMigrationState(directValue) && directValue.restoreStatus === "pending") return {
23
+ statePath: directStatePath,
24
+ value: directValue
25
+ };
26
+ const accountStorageDir = path.dirname(rootDir);
27
+ let siblingEntries = [];
28
+ try {
29
+ siblingEntries = (await fs.readdir(accountStorageDir, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).filter((entry) => path.join(accountStorageDir, entry) !== rootDir).toSorted((left, right) => left.localeCompare(right));
30
+ } catch {
31
+ return {
32
+ statePath: directStatePath,
33
+ value: directValue
34
+ };
35
+ }
36
+ for (const sibling of siblingEntries) {
37
+ const siblingStatePath = path.join(accountStorageDir, sibling, "legacy-crypto-migration.json");
38
+ const { value } = await readJsonFileWithFallback(siblingStatePath, null);
39
+ if (isMigrationState(value) && value.restoreStatus === "pending") return {
40
+ statePath: siblingStatePath,
41
+ value
42
+ };
43
+ }
44
+ return {
45
+ statePath: directStatePath,
46
+ value: directValue
47
+ };
48
+ }
49
+ async function maybeRestoreLegacyMatrixBackup(params) {
50
+ const env = params.env ?? process.env;
51
+ const { statePath, value } = await resolvePendingMigrationStatePath({
52
+ stateDir: params.stateDir ?? getMatrixRuntime().state.resolveStateDir(env, os.homedir),
53
+ auth: params.auth
54
+ });
55
+ if (!isMigrationState(value) || value.restoreStatus !== "pending") return { kind: "skipped" };
56
+ const restore = await params.client.restoreRoomKeyBackup();
57
+ const localOnlyKeys = value.roomKeyCounts && value.roomKeyCounts.total > value.roomKeyCounts.backedUp ? value.roomKeyCounts.total - value.roomKeyCounts.backedUp : 0;
58
+ if (restore.success) {
59
+ await writeJsonFileAtomically(statePath, {
60
+ ...value,
61
+ restoreStatus: "completed",
62
+ restoredAt: restore.restoredAt ?? (/* @__PURE__ */ new Date()).toISOString(),
63
+ importedCount: restore.imported,
64
+ totalCount: restore.total,
65
+ lastError: null
66
+ });
67
+ return {
68
+ kind: "restored",
69
+ imported: restore.imported,
70
+ total: restore.total,
71
+ localOnlyKeys
72
+ };
73
+ }
74
+ await writeJsonFileAtomically(statePath, {
75
+ ...value,
76
+ lastError: restore.error ?? "unknown"
77
+ });
78
+ return {
79
+ kind: "failed",
80
+ error: restore.error ?? "unknown",
81
+ localOnlyKeys
82
+ };
83
+ }
84
+ //#endregion
85
+ export { maybeRestoreLegacyMatrixBackup };
@@ -0,0 +1,99 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-DUslC3ob.js";
2
+ import { a as ConsoleLogger, c as setMatrixConsoleLogging, o as LogService } from "./startup-abort-B2J3MU_h.js";
3
+ import { logger } from "matrix-js-sdk/lib/logger.js";
4
+ //#region extensions/matrix/src/matrix/client/logging.ts
5
+ var logging_exports = /* @__PURE__ */ __exportAll({
6
+ createMatrixJsSdkClientLogger: () => createMatrixJsSdkClientLogger,
7
+ ensureMatrixSdkLoggingConfigured: () => ensureMatrixSdkLoggingConfigured,
8
+ setMatrixSdkConsoleLogging: () => setMatrixSdkConsoleLogging,
9
+ setMatrixSdkLogMode: () => setMatrixSdkLogMode
10
+ });
11
+ let matrixSdkLoggingConfigured = false;
12
+ let matrixSdkLogMode = "default";
13
+ const matrixSdkBaseLogger = new ConsoleLogger();
14
+ let matrixJsSdkRootLoggerSnapshot = null;
15
+ function shouldSuppressMatrixHttpNotFound(module, messageOrObject) {
16
+ if (!module.includes("MatrixHttpClient")) return false;
17
+ return messageOrObject.some((entry) => {
18
+ if (!entry || typeof entry !== "object") return false;
19
+ return entry.errcode === "M_NOT_FOUND";
20
+ });
21
+ }
22
+ function ensureMatrixSdkLoggingConfigured() {
23
+ if (!matrixSdkLoggingConfigured) matrixSdkLoggingConfigured = true;
24
+ applyMatrixSdkLogger();
25
+ }
26
+ function setMatrixSdkLogMode(mode) {
27
+ matrixSdkLogMode = mode;
28
+ if (!matrixSdkLoggingConfigured) return;
29
+ applyMatrixSdkLogger();
30
+ }
31
+ function setMatrixSdkConsoleLogging(enabled) {
32
+ setMatrixConsoleLogging(enabled);
33
+ }
34
+ function createMatrixJsSdkClientLogger(prefix = "matrix") {
35
+ return createMatrixJsSdkLoggerInstance(prefix);
36
+ }
37
+ function applyMatrixSdkLogger() {
38
+ if (matrixSdkLogMode === "quiet") {
39
+ setMatrixJsSdkRootLoggerLevel("silent");
40
+ LogService.setLogger({
41
+ trace: () => {},
42
+ debug: () => {},
43
+ info: () => {},
44
+ warn: () => {},
45
+ error: () => {}
46
+ });
47
+ return;
48
+ }
49
+ setMatrixJsSdkRootLoggerLevel("debug");
50
+ LogService.setLogger({
51
+ trace: (module, ...messageOrObject) => matrixSdkBaseLogger.trace(module, ...messageOrObject),
52
+ debug: (module, ...messageOrObject) => matrixSdkBaseLogger.debug(module, ...messageOrObject),
53
+ info: (module, ...messageOrObject) => matrixSdkBaseLogger.info(module, ...messageOrObject),
54
+ warn: (module, ...messageOrObject) => matrixSdkBaseLogger.warn(module, ...messageOrObject),
55
+ error: (module, ...messageOrObject) => {
56
+ if (shouldSuppressMatrixHttpNotFound(module, messageOrObject)) return;
57
+ matrixSdkBaseLogger.error(module, ...messageOrObject);
58
+ }
59
+ });
60
+ }
61
+ function setMatrixJsSdkRootLoggerLevel(level) {
62
+ const logger$1 = logger;
63
+ matrixJsSdkRootLoggerSnapshot ??= {
64
+ level: logger$1.getLevel?.(),
65
+ methodFactory: logger$1.methodFactory
66
+ };
67
+ if (level === "silent") {
68
+ logger$1.methodFactory = () => () => void 0;
69
+ logger$1.setLevel?.("silent", false);
70
+ logger$1.rebuild?.();
71
+ return;
72
+ }
73
+ logger$1.methodFactory = matrixJsSdkRootLoggerSnapshot.methodFactory;
74
+ const previousLevel = matrixJsSdkRootLoggerSnapshot.level;
75
+ if (typeof previousLevel === "string" || typeof previousLevel === "number") logger$1.setLevel?.(previousLevel, false);
76
+ logger$1.rebuild?.();
77
+ }
78
+ function createMatrixJsSdkLoggerInstance(prefix) {
79
+ const log = (method, ...messageOrObject) => {
80
+ if (matrixSdkLogMode === "quiet") return;
81
+ matrixSdkBaseLogger[method](prefix, ...messageOrObject);
82
+ };
83
+ return {
84
+ trace: (...messageOrObject) => log("trace", ...messageOrObject),
85
+ debug: (...messageOrObject) => log("debug", ...messageOrObject),
86
+ info: (...messageOrObject) => log("info", ...messageOrObject),
87
+ warn: (...messageOrObject) => log("warn", ...messageOrObject),
88
+ error: (...messageOrObject) => {
89
+ if (shouldSuppressMatrixHttpNotFound(prefix, messageOrObject)) return;
90
+ log("error", ...messageOrObject);
91
+ },
92
+ getChild: (namespace) => {
93
+ const nextNamespace = namespace.trim();
94
+ return createMatrixJsSdkLoggerInstance(nextNamespace ? `${prefix}.${nextNamespace}` : prefix);
95
+ }
96
+ };
97
+ }
98
+ //#endregion
99
+ export { setMatrixSdkLogMode as i, logging_exports as n, setMatrixSdkConsoleLogging as r, createMatrixJsSdkClientLogger as t };