@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,222 +0,0 @@
1
- import {
2
- applyAccountNameToChannelSection,
3
- DEFAULT_ACCOUNT_ID,
4
- normalizeAccountId,
5
- normalizeSecretInputString,
6
- type ChannelSetupInput,
7
- } from "klaw/plugin-sdk/setup";
8
- import { normalizeOptionalString } from "klaw/plugin-sdk/string-coerce-runtime";
9
- import { resolveMatrixEnvAuthReadiness } from "./matrix/client/env-auth.js";
10
- import { updateMatrixAccountConfig } from "./matrix/config-update.js";
11
- import { isSupportedMatrixAvatarSource } from "./matrix/profile.js";
12
- import {
13
- matrixNamedAccountPromotionKeys,
14
- resolveSingleAccountPromotionTarget,
15
- matrixSingleAccountKeysToMove,
16
- } from "./setup-contract.js";
17
- import type { CoreConfig } from "./types.js";
18
-
19
- const channel = "matrix" as const;
20
- const COMMON_SINGLE_ACCOUNT_KEYS_TO_MOVE = new Set([
21
- "name",
22
- "enabled",
23
- "httpPort",
24
- "webhookPath",
25
- "webhookUrl",
26
- "webhookSecret",
27
- "service",
28
- "region",
29
- "homeserver",
30
- "userId",
31
- "accessToken",
32
- "password",
33
- "deviceName",
34
- "url",
35
- "code",
36
- "dmPolicy",
37
- "allowFrom",
38
- "groupPolicy",
39
- "groupAllowFrom",
40
- "defaultTo",
41
- ]);
42
- const MATRIX_SINGLE_ACCOUNT_KEYS_TO_MOVE = new Set<string>(matrixSingleAccountKeysToMove);
43
- const MATRIX_NAMED_ACCOUNT_PROMOTION_KEYS = new Set<string>(matrixNamedAccountPromotionKeys);
44
-
45
- function cloneIfObject<T>(value: T): T {
46
- if (value && typeof value === "object") {
47
- return structuredClone(value);
48
- }
49
- return value;
50
- }
51
-
52
- function resolveSetupAvatarUrl(input: ChannelSetupInput): string | undefined {
53
- const avatarUrl = input.avatarUrl;
54
- if (typeof avatarUrl !== "string") {
55
- return undefined;
56
- }
57
- const trimmed = avatarUrl.trim();
58
- return trimmed || undefined;
59
- }
60
-
61
- function resolveExistingMatrixAccountKey(
62
- accounts: Record<string, Record<string, unknown>>,
63
- targetAccountId: string,
64
- ): string {
65
- const normalizedTargetAccountId = normalizeAccountId(targetAccountId);
66
- return (
67
- Object.keys(accounts).find(
68
- (accountId) => normalizeAccountId(accountId) === normalizedTargetAccountId,
69
- ) ?? targetAccountId
70
- );
71
- }
72
-
73
- export function moveSingleMatrixAccountConfigToNamedAccount(cfg: CoreConfig): CoreConfig {
74
- const channels = cfg.channels as Record<string, unknown> | undefined;
75
- const baseConfig = channels?.[channel];
76
- const base =
77
- typeof baseConfig === "object" && baseConfig
78
- ? (baseConfig as Record<string, unknown>)
79
- : undefined;
80
- if (!base) {
81
- return cfg;
82
- }
83
-
84
- const accounts =
85
- typeof base.accounts === "object" && base.accounts
86
- ? (base.accounts as Record<string, Record<string, unknown>>)
87
- : {};
88
- const hasNamedAccounts = Object.keys(accounts).some(Boolean);
89
- const keysToMove = Object.entries(base)
90
- .filter(([key, value]) => {
91
- if (key === "accounts" || key === "enabled" || value === undefined) {
92
- return false;
93
- }
94
- if (
95
- !COMMON_SINGLE_ACCOUNT_KEYS_TO_MOVE.has(key) &&
96
- !MATRIX_SINGLE_ACCOUNT_KEYS_TO_MOVE.has(key)
97
- ) {
98
- return false;
99
- }
100
- if (hasNamedAccounts && !MATRIX_NAMED_ACCOUNT_PROMOTION_KEYS.has(key)) {
101
- return false;
102
- }
103
- return true;
104
- })
105
- .map(([key]) => key);
106
- if (keysToMove.length === 0) {
107
- return cfg;
108
- }
109
-
110
- const targetAccountId = resolveSingleAccountPromotionTarget({ channel: base });
111
- const resolvedTargetAccountId = resolveExistingMatrixAccountKey(accounts, targetAccountId);
112
-
113
- const nextAccount: Record<string, unknown> = { ...accounts[resolvedTargetAccountId] };
114
- for (const key of keysToMove) {
115
- nextAccount[key] = cloneIfObject(base[key]);
116
- }
117
- const nextChannel = { ...base };
118
- for (const key of keysToMove) {
119
- delete nextChannel[key];
120
- }
121
-
122
- return {
123
- ...cfg,
124
- channels: {
125
- ...cfg.channels,
126
- [channel]: {
127
- ...nextChannel,
128
- accounts: {
129
- ...accounts,
130
- [resolvedTargetAccountId]: nextAccount,
131
- },
132
- },
133
- },
134
- };
135
- }
136
-
137
- export function validateMatrixSetupInput(params: {
138
- accountId: string;
139
- input: ChannelSetupInput;
140
- }): string | null {
141
- const avatarUrl = resolveSetupAvatarUrl(params.input);
142
- if (avatarUrl && !isSupportedMatrixAvatarSource(avatarUrl)) {
143
- return "Matrix avatar URL must be an mxc:// URI or an http(s) URL.";
144
- }
145
- if (params.input.useEnv) {
146
- const envReadiness = resolveMatrixEnvAuthReadiness(params.accountId, process.env);
147
- return envReadiness.ready ? null : envReadiness.missingMessage;
148
- }
149
- if (!params.input.homeserver?.trim()) {
150
- return "Matrix requires --homeserver";
151
- }
152
- const accessToken = params.input.accessToken?.trim();
153
- const password = normalizeSecretInputString(params.input.password);
154
- const userId = params.input.userId?.trim();
155
- if (!accessToken && !password) {
156
- return "Matrix requires --access-token or --password";
157
- }
158
- if (!accessToken) {
159
- if (!userId) {
160
- return "Matrix requires --user-id when using --password";
161
- }
162
- if (!password) {
163
- return "Matrix requires --password when using --user-id";
164
- }
165
- }
166
- return null;
167
- }
168
-
169
- export function applyMatrixSetupAccountConfig(params: {
170
- cfg: CoreConfig;
171
- accountId: string;
172
- input: ChannelSetupInput;
173
- }): CoreConfig {
174
- const normalizedAccountId = normalizeAccountId(params.accountId);
175
- const migratedCfg =
176
- normalizedAccountId !== DEFAULT_ACCOUNT_ID
177
- ? moveSingleMatrixAccountConfigToNamedAccount(params.cfg)
178
- : params.cfg;
179
- const next = applyAccountNameToChannelSection({
180
- cfg: migratedCfg,
181
- channelKey: channel,
182
- accountId: normalizedAccountId,
183
- name: params.input.name,
184
- }) as CoreConfig;
185
- const avatarUrl = resolveSetupAvatarUrl(params.input);
186
-
187
- if (params.input.useEnv) {
188
- return updateMatrixAccountConfig(next, normalizedAccountId, {
189
- enabled: true,
190
- homeserver: null,
191
- allowPrivateNetwork: null,
192
- proxy: null,
193
- userId: null,
194
- accessToken: null,
195
- password: null,
196
- deviceId: null,
197
- deviceName: null,
198
- avatarUrl,
199
- });
200
- }
201
-
202
- const accessToken = params.input.accessToken?.trim();
203
- const password = normalizeSecretInputString(params.input.password);
204
- const userId = params.input.userId?.trim();
205
- return updateMatrixAccountConfig(next, normalizedAccountId, {
206
- enabled: true,
207
- homeserver: params.input.homeserver?.trim(),
208
- allowPrivateNetwork:
209
- typeof params.input.dangerouslyAllowPrivateNetwork === "boolean"
210
- ? params.input.dangerouslyAllowPrivateNetwork
211
- : typeof params.input.allowPrivateNetwork === "boolean"
212
- ? params.input.allowPrivateNetwork
213
- : undefined,
214
- proxy: normalizeOptionalString(params.input.proxy),
215
- userId: password && !userId ? null : userId,
216
- accessToken: accessToken || (password ? null : undefined),
217
- password: password || (accessToken ? null : undefined),
218
- deviceName: params.input.deviceName?.trim(),
219
- avatarUrl,
220
- initialSyncLimit: params.input.initialSyncLimit,
221
- });
222
- }
@@ -1,90 +0,0 @@
1
- import { DEFAULT_ACCOUNT_ID, normalizeAccountId } from "klaw/plugin-sdk/routing";
2
-
3
- export const matrixSingleAccountKeysToMove = [
4
- "deviceId",
5
- "avatarUrl",
6
- "initialSyncLimit",
7
- "encryption",
8
- "allowlistOnly",
9
- "dangerouslyAllowNameMatching",
10
- "allowBots",
11
- "blockStreaming",
12
- "replyToMode",
13
- "threadReplies",
14
- "textChunkLimit",
15
- "chunkMode",
16
- "responsePrefix",
17
- "ackReaction",
18
- "ackReactionScope",
19
- "reactionNotifications",
20
- "threadBindings",
21
- "startupVerification",
22
- "startupVerificationCooldownHours",
23
- "mediaMaxMb",
24
- "autoJoin",
25
- "autoJoinAllowlist",
26
- "dm",
27
- "groups",
28
- "rooms",
29
- "actions",
30
- ] as const;
31
-
32
- export const matrixNamedAccountPromotionKeys = [
33
- // When named accounts already exist, only move auth/bootstrap fields into the
34
- // promoted account. Shared delivery-policy fields stay at the top level.
35
- "name",
36
- "homeserver",
37
- "userId",
38
- "accessToken",
39
- "password",
40
- "deviceId",
41
- "deviceName",
42
- "avatarUrl",
43
- "initialSyncLimit",
44
- "encryption",
45
- ] as const;
46
-
47
- export const singleAccountKeysToMove = [...matrixSingleAccountKeysToMove];
48
- export const namedAccountPromotionKeys = [...matrixNamedAccountPromotionKeys];
49
-
50
- export function resolveSingleAccountPromotionTarget(params: {
51
- channel: Record<string, unknown>;
52
- }): string {
53
- const accounts =
54
- typeof params.channel.accounts === "object" && params.channel.accounts
55
- ? (params.channel.accounts as Record<string, unknown>)
56
- : {};
57
- const normalizedDefaultAccount =
58
- typeof params.channel.defaultAccount === "string" && params.channel.defaultAccount.trim()
59
- ? normalizeAccountId(params.channel.defaultAccount)
60
- : undefined;
61
- const matchedAccountId = normalizedDefaultAccount
62
- ? Object.entries(accounts).find(
63
- ([accountId, value]) =>
64
- accountId &&
65
- value &&
66
- typeof value === "object" &&
67
- normalizeAccountId(accountId) === normalizedDefaultAccount,
68
- )?.[0]
69
- : undefined;
70
- if (matchedAccountId) {
71
- return matchedAccountId;
72
- }
73
- if (normalizedDefaultAccount) {
74
- return DEFAULT_ACCOUNT_ID;
75
- }
76
- const namedAccounts = Object.entries(accounts).filter(
77
- ([accountId, value]) => accountId && typeof value === "object" && value,
78
- );
79
- if (namedAccounts.length === 1) {
80
- return namedAccounts[0][0];
81
- }
82
- if (
83
- namedAccounts.length > 1 &&
84
- accounts[DEFAULT_ACCOUNT_ID] &&
85
- typeof accounts[DEFAULT_ACCOUNT_ID] === "object"
86
- ) {
87
- return DEFAULT_ACCOUNT_ID;
88
- }
89
- return DEFAULT_ACCOUNT_ID;
90
- }
package/src/setup-core.ts DELETED
@@ -1,146 +0,0 @@
1
- import type { KlawConfig } from "klaw/plugin-sdk/config-contracts";
2
- import {
3
- DEFAULT_ACCOUNT_ID,
4
- type DmPolicy,
5
- normalizeAccountId,
6
- prepareScopedSetupConfig,
7
- type ChannelSetupAdapter,
8
- type ChannelSetupWizardAdapter,
9
- } from "klaw/plugin-sdk/setup";
10
- import { resolveDefaultMatrixAccountId, resolveMatrixAccountConfig } from "./matrix/accounts.js";
11
- import { resolveMatrixConfigFieldPath, updateMatrixAccountConfig } from "./matrix/config-update.js";
12
- import { applyMatrixSetupAccountConfig, validateMatrixSetupInput } from "./setup-config.js";
13
- import { resolveMatrixSetupDmAllowFrom } from "./setup-dm-policy.js";
14
- import type { CoreConfig } from "./types.js";
15
-
16
- const channel = "matrix" as const;
17
- type MatrixSetupWizardModule = { matrixSetupWizard: ChannelSetupWizardAdapter };
18
-
19
- function resolveMatrixSetupAccountId(params: { accountId?: string; name?: string }): string {
20
- return normalizeAccountId(params.accountId?.trim() || params.name?.trim() || DEFAULT_ACCOUNT_ID);
21
- }
22
-
23
- function resolveMatrixSetupWizardAccountId(cfg: CoreConfig, accountId?: string): string {
24
- return normalizeAccountId(
25
- accountId?.trim() || resolveDefaultMatrixAccountId(cfg) || DEFAULT_ACCOUNT_ID,
26
- );
27
- }
28
-
29
- function setMatrixDmPolicy(cfg: CoreConfig, policy: DmPolicy, accountId?: string): CoreConfig {
30
- const resolvedAccountId = resolveMatrixSetupWizardAccountId(cfg, accountId);
31
- const existing = resolveMatrixAccountConfig({
32
- cfg,
33
- accountId: resolvedAccountId,
34
- });
35
- const allowFrom = resolveMatrixSetupDmAllowFrom(policy, existing.dm?.allowFrom);
36
- return updateMatrixAccountConfig(cfg, resolvedAccountId, {
37
- dm: {
38
- ...existing.dm,
39
- policy,
40
- allowFrom,
41
- },
42
- });
43
- }
44
-
45
- export function createMatrixSetupWizardProxy(
46
- loadWizardModule: () => Promise<MatrixSetupWizardModule>,
47
- ): ChannelSetupWizardAdapter {
48
- let wizardPromise: Promise<ChannelSetupWizardAdapter> | null = null;
49
- const loadWizard = () => {
50
- wizardPromise ??= loadWizardModule().then((module) => module.matrixSetupWizard);
51
- return wizardPromise;
52
- };
53
- return {
54
- channel,
55
- getStatus: async (ctx) => await (await loadWizard()).getStatus(ctx),
56
- configure: async (ctx) => await (await loadWizard()).configure(ctx),
57
- configureInteractive: async (ctx) => {
58
- const wizard = await loadWizard();
59
- return await (wizard.configureInteractive ?? wizard.configure)(ctx);
60
- },
61
- configureWhenConfigured: async (ctx) => {
62
- const wizard = await loadWizard();
63
- return await (
64
- wizard.configureWhenConfigured ??
65
- wizard.configureInteractive ??
66
- wizard.configure
67
- )(ctx);
68
- },
69
- afterConfigWritten: async (ctx) => await (await loadWizard()).afterConfigWritten?.(ctx),
70
- dmPolicy: {
71
- label: "Matrix",
72
- channel,
73
- policyKey: "channels.matrix.dm.policy",
74
- allowFromKey: "channels.matrix.dm.allowFrom",
75
- resolveConfigKeys: (cfg, accountId) => {
76
- const resolvedAccountId = resolveMatrixSetupWizardAccountId(cfg as CoreConfig, accountId);
77
- return {
78
- policyKey: resolveMatrixConfigFieldPath(
79
- cfg as CoreConfig,
80
- resolvedAccountId,
81
- "dm.policy",
82
- ),
83
- allowFromKey: resolveMatrixConfigFieldPath(
84
- cfg as CoreConfig,
85
- resolvedAccountId,
86
- "dm.allowFrom",
87
- ),
88
- };
89
- },
90
- getCurrent: (cfg, accountId) =>
91
- resolveMatrixAccountConfig({
92
- cfg: cfg as CoreConfig,
93
- accountId: resolveMatrixSetupWizardAccountId(cfg as CoreConfig, accountId),
94
- }).dm?.policy ?? "pairing",
95
- setPolicy: (cfg, policy, accountId) =>
96
- setMatrixDmPolicy(cfg as CoreConfig, policy, accountId) as KlawConfig,
97
- promptAllowFrom: async (params) => {
98
- const promptAllowFrom = (await loadWizard()).dmPolicy?.promptAllowFrom;
99
- return promptAllowFrom ? await promptAllowFrom(params) : params.cfg;
100
- },
101
- },
102
- disable: (cfg) => ({
103
- ...(cfg as CoreConfig),
104
- channels: {
105
- ...(cfg as CoreConfig).channels,
106
- matrix: { ...(cfg as CoreConfig).channels?.matrix, enabled: false },
107
- },
108
- }),
109
- };
110
- }
111
-
112
- export const matrixSetupAdapter: ChannelSetupAdapter = {
113
- resolveAccountId: ({ accountId, input }) =>
114
- resolveMatrixSetupAccountId({
115
- accountId,
116
- name: input?.name,
117
- }),
118
- resolveBindingAccountId: ({ accountId, agentId }) =>
119
- resolveMatrixSetupAccountId({
120
- accountId,
121
- name: agentId,
122
- }),
123
- applyAccountName: ({ cfg, accountId, name }) =>
124
- prepareScopedSetupConfig({
125
- cfg: cfg as CoreConfig,
126
- channelKey: channel,
127
- accountId,
128
- name,
129
- }) as CoreConfig,
130
- validateInput: ({ accountId, input }) => validateMatrixSetupInput({ accountId, input }),
131
- applyAccountConfig: ({ cfg, accountId, input }) =>
132
- applyMatrixSetupAccountConfig({
133
- cfg: cfg as CoreConfig,
134
- accountId,
135
- input,
136
- }),
137
- afterAccountConfigWritten: async ({ previousCfg, cfg, accountId, runtime }) => {
138
- const { runMatrixSetupBootstrapAfterConfigWrite } = await import("./setup-bootstrap.js");
139
- await runMatrixSetupBootstrapAfterConfigWrite({
140
- previousCfg: previousCfg as CoreConfig,
141
- cfg: cfg as CoreConfig,
142
- accountId,
143
- runtime,
144
- });
145
- },
146
- };
@@ -1,15 +0,0 @@
1
- import type { DmPolicy } from "klaw/plugin-sdk/config-contracts";
2
- import { addWildcardAllowFrom, normalizeAllowFromEntries } from "klaw/plugin-sdk/setup";
3
- import type { MatrixConfig } from "./types.js";
4
-
5
- type MatrixDmAllowFrom = NonNullable<MatrixConfig["dm"]>["allowFrom"];
6
-
7
- export function resolveMatrixSetupDmAllowFrom(
8
- policy: DmPolicy,
9
- allowFrom: MatrixDmAllowFrom,
10
- ): string[] {
11
- if (policy === "open") {
12
- return addWildcardAllowFrom(allowFrom);
13
- }
14
- return normalizeAllowFromEntries(allowFrom ?? []).filter((entry) => entry !== "*");
15
- }
@@ -1,4 +0,0 @@
1
- export {
2
- matrixOnboardingAdapter,
3
- matrixOnboardingAdapter as matrixSetupWizard,
4
- } from "./onboarding.js";
@@ -1,114 +0,0 @@
1
- import type { KlawConfig } from "klaw/plugin-sdk/config-contracts";
2
- import {
3
- autoMigrateLegacyMatrixState,
4
- autoPrepareLegacyMatrixCrypto,
5
- maybeCreateMatrixMigrationSnapshot,
6
- resolveMatrixMigrationStatus,
7
- type MatrixMigrationStatus,
8
- } from "./matrix-migration.runtime.js";
9
-
10
- type MatrixStartupLogger = {
11
- info?: (message: string) => void;
12
- warn?: (message: string) => void;
13
- };
14
-
15
- function logWarningOnlyMatrixMigrationReasons(params: {
16
- status: MatrixMigrationStatus;
17
- log: MatrixStartupLogger;
18
- }): void {
19
- if (params.status.legacyState && "warning" in params.status.legacyState) {
20
- params.log.warn?.(`matrix: ${params.status.legacyState.warning}`);
21
- }
22
-
23
- if (params.status.legacyCrypto.warnings.length > 0) {
24
- params.log.warn?.(
25
- `matrix: legacy encrypted-state warnings:\n${params.status.legacyCrypto.warnings.map((entry) => `- ${entry}`).join("\n")}`,
26
- );
27
- }
28
- }
29
-
30
- async function runBestEffortMatrixMigrationStep(params: {
31
- label: string;
32
- log: MatrixStartupLogger;
33
- logPrefix?: string;
34
- run: () => Promise<unknown>;
35
- }): Promise<void> {
36
- try {
37
- await params.run();
38
- } catch (err) {
39
- params.log.warn?.(
40
- `${params.logPrefix?.trim() || "gateway"}: ${params.label} failed during Matrix migration; continuing startup: ${String(err)}`,
41
- );
42
- }
43
- }
44
-
45
- export async function runMatrixStartupMaintenance(params: {
46
- cfg: KlawConfig;
47
- env?: NodeJS.ProcessEnv;
48
- log: MatrixStartupLogger;
49
- trigger?: string;
50
- logPrefix?: string;
51
- deps?: {
52
- maybeCreateMatrixMigrationSnapshot?: typeof maybeCreateMatrixMigrationSnapshot;
53
- autoMigrateLegacyMatrixState?: typeof autoMigrateLegacyMatrixState;
54
- autoPrepareLegacyMatrixCrypto?: typeof autoPrepareLegacyMatrixCrypto;
55
- };
56
- }): Promise<void> {
57
- const env = params.env ?? process.env;
58
- const createSnapshot =
59
- params.deps?.maybeCreateMatrixMigrationSnapshot ?? maybeCreateMatrixMigrationSnapshot;
60
- const migrateLegacyState =
61
- params.deps?.autoMigrateLegacyMatrixState ?? autoMigrateLegacyMatrixState;
62
- const prepareLegacyCrypto =
63
- params.deps?.autoPrepareLegacyMatrixCrypto ?? autoPrepareLegacyMatrixCrypto;
64
- const trigger = params.trigger?.trim() || "gateway-startup";
65
- const logPrefix = params.logPrefix?.trim() || "gateway";
66
- const migrationStatus = resolveMatrixMigrationStatus({ cfg: params.cfg, env });
67
-
68
- if (!migrationStatus.pending) {
69
- return;
70
- }
71
- if (!migrationStatus.actionable) {
72
- params.log.info?.(
73
- "matrix: migration remains in a warning-only state; no pre-migration snapshot was needed yet",
74
- );
75
- logWarningOnlyMatrixMigrationReasons({ status: migrationStatus, log: params.log });
76
- return;
77
- }
78
-
79
- try {
80
- await createSnapshot({
81
- trigger,
82
- env,
83
- log: params.log,
84
- });
85
- } catch (err) {
86
- params.log.warn?.(
87
- `${logPrefix}: failed creating a Matrix migration snapshot; skipping Matrix migration for now: ${String(err)}`,
88
- );
89
- return;
90
- }
91
-
92
- await runBestEffortMatrixMigrationStep({
93
- label: "legacy Matrix state migration",
94
- log: params.log,
95
- logPrefix,
96
- run: () =>
97
- migrateLegacyState({
98
- cfg: params.cfg,
99
- env,
100
- log: params.log,
101
- }),
102
- });
103
- await runBestEffortMatrixMigrationStep({
104
- label: "legacy Matrix encrypted-state preparation",
105
- log: params.log,
106
- logPrefix,
107
- run: () =>
108
- prepareLegacyCrypto({
109
- cfg: params.cfg,
110
- env,
111
- log: params.log,
112
- }),
113
- });
114
- }
@@ -1,92 +0,0 @@
1
- import crypto from "node:crypto";
2
- import path from "node:path";
3
- import { DEFAULT_ACCOUNT_ID, normalizeAccountId } from "klaw/plugin-sdk/account-id";
4
- import { normalizeLowercaseStringOrEmpty } from "klaw/plugin-sdk/string-coerce-runtime";
5
-
6
- export function sanitizeMatrixPathSegment(value: string): string {
7
- const cleaned = normalizeLowercaseStringOrEmpty(value)
8
- .replace(/[^a-z0-9._-]+/g, "_")
9
- .replace(/^_+|_+$/g, "");
10
- return cleaned || "unknown";
11
- }
12
-
13
- export function resolveMatrixHomeserverKey(homeserver: string): string {
14
- try {
15
- const url = new URL(homeserver);
16
- if (url.host) {
17
- return sanitizeMatrixPathSegment(url.host);
18
- }
19
- } catch {
20
- // fall through
21
- }
22
- return sanitizeMatrixPathSegment(homeserver);
23
- }
24
-
25
- export function hashMatrixAccessToken(accessToken: string): string {
26
- return crypto.createHash("sha256").update(accessToken).digest("hex").slice(0, 16);
27
- }
28
-
29
- export function resolveMatrixCredentialsFilename(accountId?: string | null): string {
30
- const normalized = normalizeAccountId(accountId);
31
- return normalized === DEFAULT_ACCOUNT_ID ? "credentials.json" : `credentials-${normalized}.json`;
32
- }
33
-
34
- export function resolveMatrixCredentialsDir(stateDir: string): string {
35
- return path.join(stateDir, "credentials", "matrix");
36
- }
37
-
38
- export function resolveMatrixCredentialsPath(params: {
39
- stateDir: string;
40
- accountId?: string | null;
41
- }): string {
42
- return path.join(
43
- resolveMatrixCredentialsDir(params.stateDir),
44
- resolveMatrixCredentialsFilename(params.accountId),
45
- );
46
- }
47
-
48
- export function resolveMatrixLegacyFlatStoreRoot(stateDir: string): string {
49
- return path.join(stateDir, "matrix");
50
- }
51
-
52
- export function resolveMatrixLegacyFlatStoragePaths(stateDir: string): {
53
- rootDir: string;
54
- storagePath: string;
55
- cryptoPath: string;
56
- } {
57
- const rootDir = resolveMatrixLegacyFlatStoreRoot(stateDir);
58
- return {
59
- rootDir,
60
- storagePath: path.join(rootDir, "bot-storage.json"),
61
- cryptoPath: path.join(rootDir, "crypto"),
62
- };
63
- }
64
-
65
- export function resolveMatrixAccountStorageRoot(params: {
66
- stateDir: string;
67
- homeserver: string;
68
- userId: string;
69
- accessToken: string;
70
- accountId?: string | null;
71
- }): {
72
- rootDir: string;
73
- accountKey: string;
74
- tokenHash: string;
75
- } {
76
- const accountKey = sanitizeMatrixPathSegment(params.accountId ?? DEFAULT_ACCOUNT_ID);
77
- const userKey = sanitizeMatrixPathSegment(params.userId);
78
- const serverKey = resolveMatrixHomeserverKey(params.homeserver);
79
- const tokenHash = hashMatrixAccessToken(params.accessToken);
80
- return {
81
- rootDir: path.join(
82
- params.stateDir,
83
- "matrix",
84
- "accounts",
85
- accountKey,
86
- `${serverKey}__${userKey}`,
87
- tokenHash,
88
- ),
89
- accountKey,
90
- tokenHash,
91
- };
92
- }