@gakr-gakr/matrix 0.1.0

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