@kodelyth/matrix 2026.5.42 → 2026.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (205) hide show
  1. package/klaw.plugin.json +891 -3
  2. package/package.json +16 -4
  3. package/CHANGELOG.md +0 -321
  4. package/SPEC-SUPPORT.md +0 -116
  5. package/api.ts +0 -38
  6. package/auth-presence.ts +0 -56
  7. package/channel-plugin-api.ts +0 -3
  8. package/cli-metadata.ts +0 -11
  9. package/contract-api.ts +0 -17
  10. package/doctor-contract-api.ts +0 -1
  11. package/helper-api.ts +0 -3
  12. package/index.ts +0 -55
  13. package/plugin-entry.handlers.runtime.ts +0 -1
  14. package/runtime-api.ts +0 -72
  15. package/runtime-heavy-api.ts +0 -1
  16. package/runtime-setter-api.ts +0 -3
  17. package/secret-contract-api.ts +0 -5
  18. package/setup-entry.ts +0 -17
  19. package/setup-plugin-api.ts +0 -3
  20. package/src/account-selection.ts +0 -223
  21. package/src/actions.ts +0 -346
  22. package/src/approval-auth.ts +0 -25
  23. package/src/approval-handler.runtime.ts +0 -592
  24. package/src/approval-ids.ts +0 -6
  25. package/src/approval-native.ts +0 -345
  26. package/src/approval-reaction-auth.ts +0 -45
  27. package/src/approval-reactions.ts +0 -313
  28. package/src/auth-precedence.ts +0 -61
  29. package/src/channel-account-paths.ts +0 -97
  30. package/src/channel.runtime.ts +0 -17
  31. package/src/channel.setup.ts +0 -48
  32. package/src/channel.ts +0 -667
  33. package/src/cli-metadata.ts +0 -19
  34. package/src/cli.ts +0 -2298
  35. package/src/config-adapter.ts +0 -41
  36. package/src/config-schema.ts +0 -159
  37. package/src/config-ui-hints.ts +0 -56
  38. package/src/directory-live.ts +0 -238
  39. package/src/doctor-contract.ts +0 -287
  40. package/src/doctor.ts +0 -262
  41. package/src/env-vars.ts +0 -92
  42. package/src/exec-approval-resolver.ts +0 -23
  43. package/src/exec-approvals.ts +0 -287
  44. package/src/group-mentions.ts +0 -41
  45. package/src/legacy-crypto-inspector-availability.ts +0 -60
  46. package/src/legacy-crypto.ts +0 -531
  47. package/src/legacy-state.ts +0 -156
  48. package/src/matrix/account-config.ts +0 -175
  49. package/src/matrix/accounts.ts +0 -194
  50. package/src/matrix/actions/client.ts +0 -31
  51. package/src/matrix/actions/devices.ts +0 -34
  52. package/src/matrix/actions/limits.ts +0 -6
  53. package/src/matrix/actions/messages.ts +0 -129
  54. package/src/matrix/actions/pins.ts +0 -63
  55. package/src/matrix/actions/polls.ts +0 -109
  56. package/src/matrix/actions/profile.ts +0 -37
  57. package/src/matrix/actions/reactions.ts +0 -59
  58. package/src/matrix/actions/room.ts +0 -71
  59. package/src/matrix/actions/summary.ts +0 -88
  60. package/src/matrix/actions/types.ts +0 -63
  61. package/src/matrix/actions/verification.ts +0 -589
  62. package/src/matrix/actions.ts +0 -37
  63. package/src/matrix/active-client.ts +0 -26
  64. package/src/matrix/async-lock.ts +0 -18
  65. package/src/matrix/backup-health.ts +0 -124
  66. package/src/matrix/client/config-runtime-api.ts +0 -9
  67. package/src/matrix/client/config-secret-input.runtime.ts +0 -1
  68. package/src/matrix/client/config.ts +0 -853
  69. package/src/matrix/client/create-client.ts +0 -105
  70. package/src/matrix/client/env-auth.ts +0 -95
  71. package/src/matrix/client/file-sync-store.ts +0 -289
  72. package/src/matrix/client/logging.ts +0 -140
  73. package/src/matrix/client/migration-snapshot.runtime.ts +0 -1
  74. package/src/matrix/client/private-network-host.ts +0 -1
  75. package/src/matrix/client/runtime.ts +0 -4
  76. package/src/matrix/client/shared.ts +0 -316
  77. package/src/matrix/client/storage.ts +0 -543
  78. package/src/matrix/client/types.ts +0 -50
  79. package/src/matrix/client/url-validation.ts +0 -73
  80. package/src/matrix/client-bootstrap.ts +0 -173
  81. package/src/matrix/client.ts +0 -23
  82. package/src/matrix/config-paths.ts +0 -31
  83. package/src/matrix/config-update.ts +0 -292
  84. package/src/matrix/credentials-read.ts +0 -208
  85. package/src/matrix/credentials-write.runtime.ts +0 -35
  86. package/src/matrix/credentials.ts +0 -95
  87. package/src/matrix/deps.ts +0 -309
  88. package/src/matrix/device-health.ts +0 -29
  89. package/src/matrix/direct-management.ts +0 -349
  90. package/src/matrix/direct-room.ts +0 -128
  91. package/src/matrix/draft-stream.ts +0 -225
  92. package/src/matrix/encryption-guidance.ts +0 -24
  93. package/src/matrix/errors.ts +0 -21
  94. package/src/matrix/format.ts +0 -426
  95. package/src/matrix/legacy-crypto-inspector.ts +0 -95
  96. package/src/matrix/media-errors.ts +0 -20
  97. package/src/matrix/media-text.ts +0 -162
  98. package/src/matrix/monitor/access-state.ts +0 -145
  99. package/src/matrix/monitor/ack-config.ts +0 -27
  100. package/src/matrix/monitor/allowlist.ts +0 -89
  101. package/src/matrix/monitor/auto-join.ts +0 -86
  102. package/src/matrix/monitor/config.ts +0 -569
  103. package/src/matrix/monitor/context-summary.ts +0 -43
  104. package/src/matrix/monitor/direct.ts +0 -296
  105. package/src/matrix/monitor/events.ts +0 -397
  106. package/src/matrix/monitor/handler.ts +0 -2266
  107. package/src/matrix/monitor/inbound-dedupe.ts +0 -267
  108. package/src/matrix/monitor/index.ts +0 -540
  109. package/src/matrix/monitor/legacy-crypto-restore.ts +0 -139
  110. package/src/matrix/monitor/location.ts +0 -108
  111. package/src/matrix/monitor/media.ts +0 -119
  112. package/src/matrix/monitor/mentions.ts +0 -256
  113. package/src/matrix/monitor/reaction-events.ts +0 -197
  114. package/src/matrix/monitor/recent-invite.ts +0 -30
  115. package/src/matrix/monitor/replies.ts +0 -136
  116. package/src/matrix/monitor/reply-context.ts +0 -92
  117. package/src/matrix/monitor/room-history.ts +0 -301
  118. package/src/matrix/monitor/room-info.ts +0 -126
  119. package/src/matrix/monitor/rooms.ts +0 -52
  120. package/src/matrix/monitor/route.ts +0 -179
  121. package/src/matrix/monitor/runtime-api.ts +0 -28
  122. package/src/matrix/monitor/startup-verification.ts +0 -237
  123. package/src/matrix/monitor/startup.ts +0 -218
  124. package/src/matrix/monitor/status.ts +0 -120
  125. package/src/matrix/monitor/sync-lifecycle.ts +0 -91
  126. package/src/matrix/monitor/task-runner.ts +0 -38
  127. package/src/matrix/monitor/test-events.ts +0 -21
  128. package/src/matrix/monitor/thread-context.ts +0 -108
  129. package/src/matrix/monitor/threads.ts +0 -85
  130. package/src/matrix/monitor/types.ts +0 -30
  131. package/src/matrix/monitor/verification-events.ts +0 -643
  132. package/src/matrix/monitor/verification-utils.ts +0 -46
  133. package/src/matrix/outbound-media-runtime.ts +0 -1
  134. package/src/matrix/poll-summary.ts +0 -110
  135. package/src/matrix/poll-types.ts +0 -429
  136. package/src/matrix/probe.runtime.ts +0 -4
  137. package/src/matrix/probe.ts +0 -97
  138. package/src/matrix/profile.ts +0 -184
  139. package/src/matrix/reaction-common.ts +0 -147
  140. package/src/matrix/sdk/crypto-bootstrap.ts +0 -438
  141. package/src/matrix/sdk/crypto-facade.ts +0 -242
  142. package/src/matrix/sdk/crypto-node.runtime.ts +0 -17
  143. package/src/matrix/sdk/crypto-runtime.ts +0 -14
  144. package/src/matrix/sdk/decrypt-bridge.ts +0 -410
  145. package/src/matrix/sdk/event-helpers.ts +0 -83
  146. package/src/matrix/sdk/http-client.ts +0 -87
  147. package/src/matrix/sdk/idb-persistence-lock.ts +0 -51
  148. package/src/matrix/sdk/idb-persistence.ts +0 -288
  149. package/src/matrix/sdk/logger.ts +0 -108
  150. package/src/matrix/sdk/read-response-with-limit.ts +0 -19
  151. package/src/matrix/sdk/recovery-key-store.ts +0 -453
  152. package/src/matrix/sdk/timeout-abort-signal.ts +0 -1
  153. package/src/matrix/sdk/transport-runtime-api.ts +0 -18
  154. package/src/matrix/sdk/transport.ts +0 -352
  155. package/src/matrix/sdk/types.ts +0 -245
  156. package/src/matrix/sdk/verification-manager.ts +0 -795
  157. package/src/matrix/sdk/verification-status.ts +0 -23
  158. package/src/matrix/sdk.ts +0 -2152
  159. package/src/matrix/send/client.ts +0 -93
  160. package/src/matrix/send/formatting.ts +0 -189
  161. package/src/matrix/send/media.ts +0 -244
  162. package/src/matrix/send/targets.ts +0 -104
  163. package/src/matrix/send/types.ts +0 -131
  164. package/src/matrix/send.ts +0 -660
  165. package/src/matrix/session-store-metadata.ts +0 -108
  166. package/src/matrix/startup-abort.ts +0 -44
  167. package/src/matrix/subagent-hooks.ts +0 -308
  168. package/src/matrix/sync-state.ts +0 -27
  169. package/src/matrix/target-ids.ts +0 -79
  170. package/src/matrix/thread-bindings-shared.ts +0 -206
  171. package/src/matrix/thread-bindings.ts +0 -580
  172. package/src/matrix-migration.runtime.ts +0 -9
  173. package/src/migration-config.ts +0 -243
  174. package/src/migration-snapshot-backup.ts +0 -116
  175. package/src/migration-snapshot.ts +0 -53
  176. package/src/onboarding.ts +0 -775
  177. package/src/outbound.ts +0 -248
  178. package/src/plugin-entry.runtime.js +0 -115
  179. package/src/plugin-entry.runtime.ts +0 -70
  180. package/src/profile-update.ts +0 -71
  181. package/src/record-shared.ts +0 -3
  182. package/src/resolve-targets.ts +0 -175
  183. package/src/resolver.runtime.ts +0 -5
  184. package/src/resolver.ts +0 -21
  185. package/src/runtime-api.ts +0 -106
  186. package/src/runtime.ts +0 -13
  187. package/src/secret-contract.ts +0 -174
  188. package/src/session-route.ts +0 -126
  189. package/src/setup-bootstrap.ts +0 -102
  190. package/src/setup-config.ts +0 -222
  191. package/src/setup-contract.ts +0 -90
  192. package/src/setup-core.ts +0 -146
  193. package/src/setup-dm-policy.ts +0 -15
  194. package/src/setup-surface.ts +0 -4
  195. package/src/startup-maintenance.ts +0 -114
  196. package/src/storage-paths.ts +0 -92
  197. package/src/thread-binding-api.ts +0 -23
  198. package/src/tool-actions.runtime.ts +0 -1
  199. package/src/tool-actions.ts +0 -498
  200. package/src/types.ts +0 -257
  201. package/subagent-hooks-api.ts +0 -31
  202. package/test-api.ts +0 -21
  203. package/thread-binding-api.ts +0 -4
  204. package/thread-bindings-runtime.ts +0 -4
  205. package/tsconfig.json +0 -16
@@ -1,24 +0,0 @@
1
- import { normalizeOptionalAccountId } from "klaw/plugin-sdk/account-id";
2
- import { resolveMatrixDefaultOrOnlyAccountId } from "../account-selection.js";
3
- import type { CoreConfig } from "../types.js";
4
- import { resolveMatrixConfigFieldPath } from "./config-paths.js";
5
-
6
- function resolveMatrixEncryptionConfigPath(cfg: CoreConfig, accountId?: string | null): string {
7
- const effectiveAccountId =
8
- normalizeOptionalAccountId(accountId) ?? resolveMatrixDefaultOrOnlyAccountId(cfg);
9
- return resolveMatrixConfigFieldPath(cfg, effectiveAccountId, "encryption");
10
- }
11
-
12
- export function formatMatrixEncryptionUnavailableError(
13
- cfg: CoreConfig,
14
- accountId?: string | null,
15
- ): string {
16
- return `Matrix encryption is not available (enable ${resolveMatrixEncryptionConfigPath(cfg, accountId)}=true)`;
17
- }
18
-
19
- export function formatMatrixEncryptedEventDisabledWarning(
20
- cfg: CoreConfig,
21
- accountId?: string | null,
22
- ): string {
23
- return `matrix: encrypted event received without encryption enabled; set ${resolveMatrixEncryptionConfigPath(cfg, accountId)}=true and verify the device to decrypt`;
24
- }
@@ -1,21 +0,0 @@
1
- import { formatErrorMessage } from "klaw/plugin-sdk/error-runtime";
2
- import { normalizeLowercaseStringOrEmpty } from "klaw/plugin-sdk/string-coerce-runtime";
3
-
4
- export function formatMatrixErrorMessage(err: unknown): string {
5
- return formatErrorMessage(err);
6
- }
7
-
8
- export function formatMatrixErrorReason(err: unknown): string {
9
- return normalizeLowercaseStringOrEmpty(formatMatrixErrorMessage(err));
10
- }
11
-
12
- export function isMatrixNotFoundError(err: unknown): boolean {
13
- const errObj = err as { statusCode?: number; body?: { errcode?: string } };
14
- if (errObj?.statusCode === 404 || errObj?.body?.errcode === "M_NOT_FOUND") {
15
- return true;
16
- }
17
- const message = formatMatrixErrorReason(err);
18
- return (
19
- message.includes("m_not_found") || message.includes("[404]") || message.includes("not found")
20
- );
21
- }
@@ -1,426 +0,0 @@
1
- import { normalizeLowercaseStringOrEmpty } from "klaw/plugin-sdk/string-coerce-runtime";
2
- import { isAutoLinkedFileRef } from "klaw/plugin-sdk/text-autolink-runtime";
3
- import MarkdownIt from "markdown-it";
4
- import type { MatrixClient } from "./sdk.js";
5
- import { isMatrixQualifiedUserId } from "./target-ids.js";
6
-
7
- const md = new MarkdownIt({
8
- html: false,
9
- linkify: true,
10
- breaks: true,
11
- typographer: false,
12
- });
13
-
14
- md.enable("strikethrough");
15
-
16
- const { escapeHtml } = md.utils;
17
-
18
- export type MatrixMentions = {
19
- room?: boolean;
20
- user_ids?: string[];
21
- };
22
-
23
- type MarkdownToken = ReturnType<typeof md.parse>[number];
24
- type MarkdownInlineToken = NonNullable<MarkdownToken["children"]>[number];
25
- type MatrixMentionCandidate = {
26
- raw: string;
27
- start: number;
28
- end: number;
29
- kind: "room" | "user";
30
- userId?: string;
31
- };
32
-
33
- const ESCAPED_MENTION_SENTINEL = "\uE000";
34
- const MENTION_PATTERN = /@[A-Za-z0-9._=+\-/:[\]]+/g;
35
- const MATRIX_MENTION_USER_ID_PATTERN =
36
- /^@[A-Za-z0-9._=+\-/]+:(?:[A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(?::\d+)?$/;
37
- const TRIMMABLE_MENTION_SUFFIX = /[),.!?:;\]]/;
38
-
39
- function shouldSuppressAutoLink(
40
- tokens: Parameters<NonNullable<typeof md.renderer.rules.link_open>>[0],
41
- idx: number,
42
- ): boolean {
43
- const token = tokens[idx];
44
- if (token?.type !== "link_open" || token.info !== "auto") {
45
- return false;
46
- }
47
- const href = token.attrGet("href") ?? "";
48
- const label = tokens[idx + 1]?.type === "text" ? (tokens[idx + 1]?.content ?? "") : "";
49
- return Boolean(href && label && isAutoLinkedFileRef(href, label));
50
- }
51
-
52
- md.renderer.rules.image = (tokens, idx) => escapeHtml(tokens[idx]?.content ?? "");
53
-
54
- md.renderer.rules.html_block = (tokens, idx) => escapeHtml(tokens[idx]?.content ?? "");
55
- md.renderer.rules.html_inline = (tokens, idx) => escapeHtml(tokens[idx]?.content ?? "");
56
- md.renderer.rules.link_open = (tokens, idx, _options, _env, self) =>
57
- shouldSuppressAutoLink(tokens, idx) ? "" : self.renderToken(tokens, idx, _options);
58
- md.renderer.rules.link_close = (tokens, idx, _options, _env, self) => {
59
- const openIdx = idx - 2;
60
- if (openIdx >= 0 && shouldSuppressAutoLink(tokens, openIdx)) {
61
- return "";
62
- }
63
- return self.renderToken(tokens, idx, _options);
64
- };
65
-
66
- function maskEscapedMentions(markdown: string): string {
67
- let masked = "";
68
- let idx = 0;
69
- let codeFenceLength = 0;
70
-
71
- while (idx < markdown.length) {
72
- if (markdown[idx] === "`" && !isMarkdownEscaped(markdown, idx)) {
73
- let runLength = 1;
74
- while (markdown[idx + runLength] === "`") {
75
- runLength += 1;
76
- }
77
- if (codeFenceLength === 0) {
78
- codeFenceLength = runLength;
79
- } else if (runLength === codeFenceLength) {
80
- codeFenceLength = 0;
81
- }
82
- masked += markdown.slice(idx, idx + runLength);
83
- idx += runLength;
84
- continue;
85
- }
86
- if (codeFenceLength === 0 && markdown[idx] === "\\" && markdown[idx + 1] === "@") {
87
- masked += ESCAPED_MENTION_SENTINEL;
88
- idx += 2;
89
- continue;
90
- }
91
- masked += markdown[idx] ?? "";
92
- idx += 1;
93
- }
94
-
95
- return masked;
96
- }
97
-
98
- function isMarkdownEscaped(markdown: string, idx: number): boolean {
99
- let slashCount = 0;
100
- let cursor = idx - 1;
101
- while (cursor >= 0 && markdown[cursor] === "\\") {
102
- slashCount += 1;
103
- cursor -= 1;
104
- }
105
- return slashCount % 2 === 1;
106
- }
107
-
108
- function restoreEscapedMentions(text: string): string {
109
- return text.replaceAll(ESCAPED_MENTION_SENTINEL, "@");
110
- }
111
-
112
- function restoreEscapedMentionsInCode(text: string): string {
113
- return text.replaceAll(ESCAPED_MENTION_SENTINEL, "\\@");
114
- }
115
-
116
- function restoreEscapedMentionsInBlockTokens(tokens: MarkdownToken[]): void {
117
- for (const token of tokens) {
118
- if ((token.type === "fence" || token.type === "code_block") && token.content) {
119
- token.content = restoreEscapedMentionsInCode(token.content);
120
- }
121
- }
122
- }
123
-
124
- function isMentionStartBoundary(charBefore: string | undefined): boolean {
125
- return !charBefore || !/[A-Za-z0-9_]/.test(charBefore);
126
- }
127
-
128
- function trimMentionSuffix(raw: string, end: number): { raw: string; end: number } | null {
129
- while (raw.length > 1 && TRIMMABLE_MENTION_SUFFIX.test(raw.at(-1) ?? "")) {
130
- if (raw.at(-1) === "]" && /\[[0-9A-Fa-f:.]+\](?::\d+)?$/i.test(raw)) {
131
- break;
132
- }
133
- raw = raw.slice(0, -1);
134
- end -= 1;
135
- }
136
- if (!raw.startsWith("@") || raw === "@") {
137
- return null;
138
- }
139
- return { raw, end };
140
- }
141
-
142
- function isMatrixMentionUserId(raw: string): boolean {
143
- return isMatrixQualifiedUserId(raw) && MATRIX_MENTION_USER_ID_PATTERN.test(raw);
144
- }
145
-
146
- function buildMentionCandidate(raw: string, start: number): MatrixMentionCandidate | null {
147
- const normalized = trimMentionSuffix(raw, start + raw.length);
148
- if (!normalized) {
149
- return null;
150
- }
151
- const kind = normalizeLowercaseStringOrEmpty(normalized.raw) === "@room" ? "room" : "user";
152
- const base: MatrixMentionCandidate = {
153
- raw: normalized.raw,
154
- start,
155
- end: normalized.end,
156
- kind,
157
- };
158
- if (kind === "room") {
159
- return base;
160
- }
161
- const userCandidate = isMatrixMentionUserId(normalized.raw)
162
- ? { ...base, userId: normalized.raw }
163
- : null;
164
- if (!userCandidate) {
165
- return null;
166
- }
167
- return userCandidate;
168
- }
169
-
170
- function collectMentionCandidates(text: string): MatrixMentionCandidate[] {
171
- const mentions: MatrixMentionCandidate[] = [];
172
- for (const match of text.matchAll(MENTION_PATTERN)) {
173
- const raw = match[0];
174
- const start = match.index ?? -1;
175
- if (start < 0 || !raw) {
176
- continue;
177
- }
178
- if (!isMentionStartBoundary(text[start - 1])) {
179
- continue;
180
- }
181
- const candidate = buildMentionCandidate(raw, start);
182
- if (!candidate) {
183
- continue;
184
- }
185
- mentions.push(candidate);
186
- }
187
- return mentions;
188
- }
189
-
190
- function createToken(
191
- sample: MarkdownInlineToken,
192
- type: string,
193
- tag: string,
194
- nesting: number,
195
- ): MarkdownInlineToken {
196
- const TokenCtor = sample.constructor as new (
197
- type: string,
198
- tag: string,
199
- nesting: number,
200
- ) => MarkdownInlineToken;
201
- return new TokenCtor(type, tag, nesting);
202
- }
203
-
204
- function createTextToken(sample: MarkdownInlineToken, content: string): MarkdownInlineToken {
205
- const token = createToken(sample, "text", "", 0);
206
- token.content = content;
207
- return token;
208
- }
209
-
210
- function createMentionLinkTokens(params: {
211
- sample: MarkdownInlineToken;
212
- href: string;
213
- label: string;
214
- }): MarkdownInlineToken[] {
215
- const open = createToken(params.sample, "link_open", "a", 1);
216
- open.attrSet("href", params.href);
217
- const text = createTextToken(params.sample, params.label);
218
- const close = createToken(params.sample, "link_close", "a", -1);
219
- return [open, text, close];
220
- }
221
-
222
- function resolveMentionUserId(match: MatrixMentionCandidate): string | null {
223
- if (match.kind !== "user") {
224
- return null;
225
- }
226
- return match.userId ?? null;
227
- }
228
-
229
- async function resolveMatrixSelfUserId(client: MatrixClient): Promise<string | null> {
230
- const getUserId = (client as { getUserId?: () => Promise<string> | string }).getUserId;
231
- if (typeof getUserId !== "function") {
232
- return null;
233
- }
234
- return await Promise.resolve(getUserId.call(client)).catch(() => null);
235
- }
236
-
237
- function mutateInlineTokensWithMentions(params: {
238
- children: MarkdownInlineToken[];
239
- userIds: string[];
240
- seenUserIds: Set<string>;
241
- selfUserId: string | null;
242
- }): { children: MarkdownInlineToken[]; roomMentioned: boolean } {
243
- const nextChildren: MarkdownInlineToken[] = [];
244
- let roomMentioned = false;
245
- let insideLinkDepth = 0;
246
- for (const child of params.children) {
247
- if (child.type === "link_open") {
248
- insideLinkDepth += 1;
249
- nextChildren.push(child);
250
- continue;
251
- }
252
- if (child.type === "link_close") {
253
- insideLinkDepth = Math.max(0, insideLinkDepth - 1);
254
- nextChildren.push(child);
255
- continue;
256
- }
257
- if (child.type !== "text" || !child.content) {
258
- nextChildren.push(child);
259
- continue;
260
- }
261
-
262
- const visibleContent = restoreEscapedMentions(child.content);
263
- if (insideLinkDepth > 0) {
264
- nextChildren.push(createTextToken(child, visibleContent));
265
- continue;
266
- }
267
- const matches = collectMentionCandidates(child.content);
268
- if (matches.length === 0) {
269
- nextChildren.push(createTextToken(child, visibleContent));
270
- continue;
271
- }
272
-
273
- let cursor = 0;
274
- for (const match of matches) {
275
- if (match.start > cursor) {
276
- nextChildren.push(
277
- createTextToken(child, restoreEscapedMentions(child.content.slice(cursor, match.start))),
278
- );
279
- }
280
- cursor = match.end;
281
- if (match.kind === "room") {
282
- roomMentioned = true;
283
- nextChildren.push(createTextToken(child, match.raw));
284
- continue;
285
- }
286
-
287
- const resolvedUserId = resolveMentionUserId(match);
288
- if (!resolvedUserId || resolvedUserId === params.selfUserId) {
289
- nextChildren.push(createTextToken(child, match.raw));
290
- continue;
291
- }
292
- if (!params.seenUserIds.has(resolvedUserId)) {
293
- params.seenUserIds.add(resolvedUserId);
294
- params.userIds.push(resolvedUserId);
295
- }
296
- nextChildren.push(
297
- ...createMentionLinkTokens({
298
- sample: child,
299
- href: `https://matrix.to/#/${encodeURIComponent(resolvedUserId)}`,
300
- label: match.raw,
301
- }),
302
- );
303
- }
304
- if (cursor < child.content.length) {
305
- nextChildren.push(
306
- createTextToken(child, restoreEscapedMentions(child.content.slice(cursor))),
307
- );
308
- }
309
- }
310
- return { children: nextChildren, roomMentioned };
311
- }
312
-
313
- // Compact loose lists by hiding a list item's single wrapper paragraph,
314
- // mirroring what markdown-it already does for tight lists. Without this
315
- // Element renders <p> margins inside <li>, splitting numbers from content.
316
- //
317
- // Keep multi-paragraph items visible so separate paragraphs do not collapse
318
- // together inside the same list item.
319
- function compactLooseListTokens(tokens: MarkdownToken[]): void {
320
- const listItemStack: Array<{
321
- level: number;
322
- immediateParagraphOpenIndexes: number[];
323
- immediateParagraphCloseIndexes: number[];
324
- }> = [];
325
-
326
- for (const [index, token] of tokens.entries()) {
327
- if (token.type === "list_item_open") {
328
- listItemStack.push({
329
- level: token.level,
330
- immediateParagraphOpenIndexes: [],
331
- immediateParagraphCloseIndexes: [],
332
- });
333
- continue;
334
- }
335
-
336
- if (token.type === "list_item_close") {
337
- const item = listItemStack.pop();
338
- if (
339
- item &&
340
- item.immediateParagraphOpenIndexes.length === 1 &&
341
- item.immediateParagraphCloseIndexes.length === 1
342
- ) {
343
- tokens[item.immediateParagraphOpenIndexes[0]].hidden = true;
344
- tokens[item.immediateParagraphCloseIndexes[0]].hidden = true;
345
- }
346
- continue;
347
- }
348
-
349
- const currentItem = listItemStack.at(-1);
350
- if (!currentItem || token.level !== currentItem.level + 1) {
351
- continue;
352
- }
353
-
354
- if (token.type === "paragraph_open") {
355
- currentItem.immediateParagraphOpenIndexes.push(index);
356
- } else if (token.type === "paragraph_close") {
357
- currentItem.immediateParagraphCloseIndexes.push(index);
358
- }
359
- }
360
- }
361
-
362
- export function markdownToMatrixHtml(markdown: string): string {
363
- const tokens = md.parse(markdown ?? "", {});
364
- compactLooseListTokens(tokens);
365
- return md.renderer.render(tokens, md.options, {}).trimEnd();
366
- }
367
-
368
- async function resolveMarkdownMentionState(params: {
369
- markdown: string;
370
- client: MatrixClient;
371
- }): Promise<{ tokens: MarkdownToken[]; mentions: MatrixMentions }> {
372
- const markdown = maskEscapedMentions(params.markdown ?? "");
373
- const tokens = md.parse(markdown, {});
374
- restoreEscapedMentionsInBlockTokens(tokens);
375
- const selfUserId = await resolveMatrixSelfUserId(params.client);
376
- const userIds: string[] = [];
377
- const seenUserIds = new Set<string>();
378
- let roomMentioned = false;
379
-
380
- for (const token of tokens) {
381
- if (!token.children?.length) {
382
- continue;
383
- }
384
- const mutated = mutateInlineTokensWithMentions({
385
- children: token.children,
386
- userIds,
387
- seenUserIds,
388
- selfUserId,
389
- });
390
- token.children = mutated.children;
391
- roomMentioned ||= mutated.roomMentioned;
392
- }
393
-
394
- const mentions: MatrixMentions = {};
395
- if (userIds.length > 0) {
396
- mentions.user_ids = userIds;
397
- }
398
- if (roomMentioned) {
399
- mentions.room = true;
400
- }
401
- return {
402
- tokens,
403
- mentions,
404
- };
405
- }
406
-
407
- export async function resolveMatrixMentionsInMarkdown(params: {
408
- markdown: string;
409
- client: MatrixClient;
410
- }): Promise<MatrixMentions> {
411
- const state = await resolveMarkdownMentionState(params);
412
- return state.mentions;
413
- }
414
-
415
- export async function renderMarkdownToMatrixHtmlWithMentions(params: {
416
- markdown: string;
417
- client: MatrixClient;
418
- }): Promise<{ html?: string; mentions: MatrixMentions }> {
419
- const state = await resolveMarkdownMentionState(params);
420
- compactLooseListTokens(state.tokens);
421
- const html = md.renderer.render(state.tokens, md.options, {}).trimEnd();
422
- return {
423
- html: html || undefined,
424
- mentions: state.mentions,
425
- };
426
- }
@@ -1,95 +0,0 @@
1
- import crypto from "node:crypto";
2
- import fs from "node:fs";
3
- import { createRequire } from "node:module";
4
- import path from "node:path";
5
- import { ensureMatrixCryptoRuntime } from "./deps.js";
6
-
7
- export type MatrixLegacyCryptoInspectionResult = {
8
- deviceId: string | null;
9
- roomKeyCounts: {
10
- total: number;
11
- backedUp: number;
12
- } | null;
13
- backupVersion: string | null;
14
- decryptionKeyBase64: string | null;
15
- };
16
-
17
- function resolveLegacyMachineStorePath(params: {
18
- cryptoRootDir: string;
19
- deviceId: string;
20
- }): string | null {
21
- const hashedDir = path.join(
22
- params.cryptoRootDir,
23
- crypto.createHash("sha256").update(params.deviceId).digest("hex"),
24
- );
25
- if (fs.existsSync(path.join(hashedDir, "matrix-sdk-crypto.sqlite3"))) {
26
- return hashedDir;
27
- }
28
- if (fs.existsSync(path.join(params.cryptoRootDir, "matrix-sdk-crypto.sqlite3"))) {
29
- return params.cryptoRootDir;
30
- }
31
- const match = fs
32
- .readdirSync(params.cryptoRootDir, { withFileTypes: true })
33
- .find(
34
- (entry) =>
35
- entry.isDirectory() &&
36
- fs.existsSync(path.join(params.cryptoRootDir, entry.name, "matrix-sdk-crypto.sqlite3")),
37
- );
38
- return match ? path.join(params.cryptoRootDir, match.name) : null;
39
- }
40
-
41
- export async function inspectLegacyMatrixCryptoStore(params: {
42
- cryptoRootDir: string;
43
- userId: string;
44
- deviceId: string;
45
- log?: (message: string) => void;
46
- }): Promise<MatrixLegacyCryptoInspectionResult> {
47
- const machineStorePath = resolveLegacyMachineStorePath(params);
48
- if (!machineStorePath) {
49
- throw new Error(`Matrix legacy crypto store not found for device ${params.deviceId}`);
50
- }
51
-
52
- const requireFn = createRequire(import.meta.url);
53
- await ensureMatrixCryptoRuntime({
54
- requireFn,
55
- resolveFn: requireFn.resolve.bind(requireFn),
56
- log: params.log,
57
- });
58
-
59
- const { DeviceId, OlmMachine, StoreType, UserId } = requireFn(
60
- "@matrix-org/matrix-sdk-crypto-nodejs",
61
- ) as typeof import("@matrix-org/matrix-sdk-crypto-nodejs");
62
- const machine = await OlmMachine.initialize(
63
- new UserId(params.userId),
64
- new DeviceId(params.deviceId),
65
- machineStorePath,
66
- "",
67
- StoreType.Sqlite,
68
- );
69
-
70
- try {
71
- const [backupKeys, roomKeyCounts] = await Promise.all([
72
- machine.getBackupKeys(),
73
- machine.roomKeyCounts(),
74
- ]);
75
- return {
76
- deviceId: params.deviceId,
77
- roomKeyCounts: roomKeyCounts
78
- ? {
79
- total: typeof roomKeyCounts.total === "number" ? roomKeyCounts.total : 0,
80
- backedUp: typeof roomKeyCounts.backedUp === "number" ? roomKeyCounts.backedUp : 0,
81
- }
82
- : null,
83
- backupVersion:
84
- typeof backupKeys?.backupVersion === "string" && backupKeys.backupVersion.trim()
85
- ? backupKeys.backupVersion
86
- : null,
87
- decryptionKeyBase64:
88
- typeof backupKeys?.decryptionKeyBase64 === "string" && backupKeys.decryptionKeyBase64.trim()
89
- ? backupKeys.decryptionKeyBase64
90
- : null,
91
- };
92
- } finally {
93
- machine.close();
94
- }
95
- }
@@ -1,20 +0,0 @@
1
- const MATRIX_MEDIA_SIZE_LIMIT_ERROR_MESSAGE = "Matrix media exceeds configured size limit";
2
-
3
- export class MatrixMediaSizeLimitError extends Error {
4
- readonly code = "MATRIX_MEDIA_SIZE_LIMIT" as const;
5
-
6
- constructor(message = MATRIX_MEDIA_SIZE_LIMIT_ERROR_MESSAGE, options?: ErrorOptions) {
7
- super(message, options);
8
- this.name = "MatrixMediaSizeLimitError";
9
- }
10
- }
11
-
12
- export function isMatrixMediaSizeLimitError(err: unknown): err is MatrixMediaSizeLimitError {
13
- if (err instanceof MatrixMediaSizeLimitError) {
14
- return true;
15
- }
16
- if (!(err instanceof Error) || err.cause === undefined) {
17
- return false;
18
- }
19
- return isMatrixMediaSizeLimitError(err.cause);
20
- }