@kodelyth/matrix 2026.5.39 → 2026.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/dist/account-selection-Y50DNJ2l.js +158 -0
  2. package/dist/active-client-CmFdvPdO.js +20 -0
  3. package/dist/api.js +12 -0
  4. package/dist/approval-handler.runtime-BIi4fL0R.js +377 -0
  5. package/dist/approval-ids-BGHK7PnZ.js +7 -0
  6. package/dist/approval-reaction-auth-CL0-nCNV.js +27 -0
  7. package/dist/approval-reactions-nDm2x-K5.js +162 -0
  8. package/dist/async-lock-SsmtFXtt.js +19 -0
  9. package/dist/auth-presence.js +26 -0
  10. package/dist/backup-health-3BHbHxyd.js +60 -0
  11. package/dist/channel-C0kCyTNB.js +1380 -0
  12. package/dist/channel-plugin-api.js +2 -0
  13. package/dist/channel.runtime-CdrdEN-0.js +250 -0
  14. package/dist/cli-FtY6Nuzw.js +1338 -0
  15. package/dist/cli-metadata-Dkwua7CB.js +22 -0
  16. package/dist/cli-metadata.js +2 -0
  17. package/dist/client-BnohYygh.js +25 -0
  18. package/dist/client-PhrTwuC4.js +30 -0
  19. package/dist/client-bootstrap-Mcj8ChJ5.js +114 -0
  20. package/dist/config-paths-DVvt6vM3.js +114 -0
  21. package/dist/config-schema-BMGOlhdI.js +308 -0
  22. package/dist/config-secret-input.runtime-Dv_4Br_f.js +2 -0
  23. package/dist/contract-api.js +8 -0
  24. package/dist/create-client-J0htTaRj.js +64 -0
  25. package/dist/credentials-B7GsBbgQ.js +56 -0
  26. package/dist/credentials-read-8fE4qoWs.js +112 -0
  27. package/dist/credentials-write.runtime-BibplB4Y.js +17 -0
  28. package/dist/crypto-node.runtime-D9qxgRPa.js +12 -0
  29. package/dist/crypto-runtime-1pKW4O2F.js +1214 -0
  30. package/dist/deps-DVpDS81G.js +208 -0
  31. package/dist/device-health-Ct2wDSPG.js +16 -0
  32. package/dist/directory-live-i3T8uORc.js +150 -0
  33. package/dist/doctor-contract-BLzYHl_9.js +246 -0
  34. package/dist/doctor-contract-api.js +2 -0
  35. package/dist/doctor-diR5gE7D.js +153 -0
  36. package/dist/draft-stream-HpPJ_VJt.js +143 -0
  37. package/dist/encryption-guidance-BNEgckrZ.js +15 -0
  38. package/dist/env-auth-UFiTGkDM.js +63 -0
  39. package/dist/env-vars-EQKQv-FE.js +63 -0
  40. package/dist/errors-BETj3zr9.js +17 -0
  41. package/dist/exec-approval-resolver-BxPorU_t.js +15 -0
  42. package/dist/helper-api.js +4 -0
  43. package/dist/http-client-DoQgbQsU.js +331 -0
  44. package/dist/index.js +46 -0
  45. package/dist/legacy-crypto-inspector-zK0hDCbt.js +41 -0
  46. package/dist/legacy-crypto-restore-DSFIXuDo.js +85 -0
  47. package/dist/logging-Df7aPD1z.js +99 -0
  48. package/dist/matrix-migration.runtime-BNoT1Prt.js +525 -0
  49. package/dist/media-text-ZhGA8Pcs.js +146 -0
  50. package/dist/messages-CRA9WGg0.js +140 -0
  51. package/dist/migration-snapshot-backup-BR-xD7Ew.js +69 -0
  52. package/dist/migration-snapshot.runtime-BLcy_Nvw.js +2 -0
  53. package/dist/monitor-DQm7_13y.js +4331 -0
  54. package/dist/plugin-entry.handlers.runtime.js +51 -0
  55. package/dist/probe.runtime-CjJS53Kz.js +3 -0
  56. package/dist/profile-update-DqkPgZ1P.js +68 -0
  57. package/dist/reaction-common-CmVLzP-u.js +71 -0
  58. package/dist/reaction-events-D0nUJuZV.js +121 -0
  59. package/dist/record-shared-DGvSFn5M.js +2 -0
  60. package/dist/resolve-targets-ChECUzD2.js +140 -0
  61. package/dist/resolver.runtime-hdY3n0GO.js +5 -0
  62. package/dist/rolldown-runtime-DUslC3ob.js +14 -0
  63. package/dist/route-xRKj_ESW.js +161 -0
  64. package/dist/runtime-B-Fyrmxo.js +8 -0
  65. package/dist/runtime-api-BYXXkxq2.js +24 -0
  66. package/dist/runtime-api.js +25 -0
  67. package/dist/runtime-heavy-api.js +3 -0
  68. package/dist/runtime-lwTSy9Yt.js +6 -0
  69. package/dist/runtime-setter-api.js +2 -0
  70. package/dist/sdk-Jhq7mLtD.js +1704 -0
  71. package/dist/secret-contract-DEMcDsjl.js +120 -0
  72. package/dist/secret-contract-api.js +2 -0
  73. package/dist/send-CJunc6QM.js +1517 -0
  74. package/dist/setup-bootstrap-rJ0qZWPe.js +62 -0
  75. package/dist/setup-core-BEYoXF3J.js +677 -0
  76. package/dist/setup-entry.js +19 -0
  77. package/dist/setup-plugin-api.js +43 -0
  78. package/dist/setup-surface-c28ON6jq.js +537 -0
  79. package/dist/shared-D6MFMnpG.js +642 -0
  80. package/dist/startup-abort-B2J3MU_h.js +109 -0
  81. package/dist/startup-verification-CkD4Cwce.js +132 -0
  82. package/dist/storage-nyO0DOFE.js +281 -0
  83. package/dist/storage-paths-BTAketfg.js +52 -0
  84. package/dist/subagent-hooks-api-Dr_xnMRG.js +170 -0
  85. package/dist/subagent-hooks-api.js +2 -0
  86. package/dist/sync-state-Bx0gPaGA.js +12 -0
  87. package/dist/target-ids-Bsazo8si.js +77 -0
  88. package/dist/test-api.js +4 -0
  89. package/dist/thread-binding-api-IGU0-L70.js +17 -0
  90. package/dist/thread-binding-api.js +2 -0
  91. package/dist/thread-bindings-FjAZmDUP.js +352 -0
  92. package/dist/thread-bindings-runtime.js +2 -0
  93. package/dist/thread-bindings-shared-fvfP7jVs.js +97 -0
  94. package/dist/timeout-abort-signal-DpSHDHhR.js +2 -0
  95. package/dist/tool-actions.runtime-Cbo7YcYZ.js +532 -0
  96. package/dist/url-validation-DlrXNjAE.js +36 -0
  97. package/dist/verification-7tDPRpJU.js +345 -0
  98. package/package.json +19 -7
  99. package/api.js +0 -7
  100. package/auth-presence.js +0 -7
  101. package/channel-plugin-api.js +0 -7
  102. package/cli-metadata.js +0 -7
  103. package/contract-api.js +0 -7
  104. package/doctor-contract-api.js +0 -7
  105. package/helper-api.js +0 -7
  106. package/index.js +0 -7
  107. package/plugin-entry.handlers.runtime.js +0 -7
  108. package/runtime-api.js +0 -7
  109. package/runtime-heavy-api.js +0 -7
  110. package/runtime-setter-api.js +0 -7
  111. package/secret-contract-api.js +0 -7
  112. package/setup-entry.js +0 -7
  113. package/setup-plugin-api.js +0 -7
  114. package/subagent-hooks-api.js +0 -7
  115. package/test-api.js +0 -7
  116. package/thread-binding-api.js +0 -7
  117. package/thread-bindings-runtime.js +0 -7
@@ -0,0 +1,642 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-DUslC3ob.js";
2
+ import { a as resolveMatrixDefaultOrOnlyAccountId, n as requiresExplicitMatrixDefaultAccount, o as resolveMatrixAccountStringValues } from "./account-selection-Y50DNJ2l.js";
3
+ import { t as getMatrixScopedEnvVarNames } from "./env-vars-EQKQv-FE.js";
4
+ import { i as findMatrixAccountConfig, l as resolveMatrixBaseConfig, o as listNormalizedMatrixAccountIds, t as resolveMatrixConfigFieldPath } from "./config-paths-DVvt6vM3.js";
5
+ import { i as resolveScopedMatrixEnvConfig, n as resolveGlobalMatrixEnvConfig } from "./env-auth-UFiTGkDM.js";
6
+ import { t as resolveValidatedMatrixHomeserverUrl } from "./url-validation-DlrXNjAE.js";
7
+ import { r as repairCurrentTokenStorageMetaDeviceId } from "./storage-nyO0DOFE.js";
8
+ import { o as LogService, t as awaitMatrixStartupWithAbort } from "./startup-abort-B2J3MU_h.js";
9
+ import { DEFAULT_ACCOUNT_ID as DEFAULT_ACCOUNT_ID$1, normalizeAccountId as normalizeAccountId$1, normalizeOptionalAccountId, normalizeOptionalAccountId as normalizeOptionalAccountId$1 } from "klaw/plugin-sdk/account-id";
10
+ import { coerceSecretRef, normalizeResolvedSecretInputString } from "klaw/plugin-sdk/secret-input-runtime";
11
+ import { formatErrorMessage } from "klaw/plugin-sdk/error-runtime";
12
+ import { isPrivateNetworkOptInEnabled, ssrfPolicyFromDangerouslyAllowPrivateNetwork as ssrfPolicyFromDangerouslyAllowPrivateNetwork$1 } from "klaw/plugin-sdk/ssrf-runtime";
13
+ import { requireRuntimeConfig } from "klaw/plugin-sdk/plugin-config-runtime";
14
+ import { retryAsync } from "klaw/plugin-sdk/retry-runtime";
15
+ //#region extensions/matrix/src/matrix/client/config.ts
16
+ let matrixAuthClientDepsPromise;
17
+ let matrixCredentialsReadDepsPromise;
18
+ let matrixCredentialsWriteRuntimePromise;
19
+ let matrixSecretInputDepsPromise;
20
+ let matrixAuthClientDepsForTest;
21
+ const MATRIX_AUTH_REQUEST_RETRY_RE = /\b(fetch failed|econnreset|econnrefused|enotfound|etimedout|ehostunreach|enetunreach|eai_again|und_err_|socket hang up|network|headers timeout|body timeout|connect timeout)\b/i;
22
+ async function loadMatrixAuthClientDeps() {
23
+ matrixAuthClientDepsPromise ??= Promise.all([import("./sdk-Jhq7mLtD.js").then((n) => n.n), import("./logging-Df7aPD1z.js").then((n) => n.n)]).then(([sdkModule, loggingModule]) => ({
24
+ MatrixClient: sdkModule.MatrixClient,
25
+ ensureMatrixSdkLoggingConfigured: loggingModule.ensureMatrixSdkLoggingConfigured
26
+ }));
27
+ return await matrixAuthClientDepsPromise;
28
+ }
29
+ async function loadMatrixCredentialsReadDeps() {
30
+ matrixCredentialsReadDepsPromise ??= import("./credentials-read-8fE4qoWs.js").then((n) => n.r).then((credentialsReadModule) => ({
31
+ loadMatrixCredentials: credentialsReadModule.loadMatrixCredentials,
32
+ credentialsMatchConfig: credentialsReadModule.credentialsMatchConfig
33
+ }));
34
+ return await matrixCredentialsReadDepsPromise;
35
+ }
36
+ async function loadMatrixCredentialsWriteRuntime() {
37
+ matrixCredentialsWriteRuntimePromise ??= import("./credentials-write.runtime-BibplB4Y.js");
38
+ return await matrixCredentialsWriteRuntimePromise;
39
+ }
40
+ async function loadMatrixSecretInputDeps() {
41
+ matrixSecretInputDepsPromise ??= import("./config-secret-input.runtime-Dv_4Br_f.js").then((runtime) => ({ resolveConfiguredSecretInputString: runtime.resolveConfiguredSecretInputString }));
42
+ return await matrixSecretInputDepsPromise;
43
+ }
44
+ function shouldRetryMatrixAuthRequest(err) {
45
+ return MATRIX_AUTH_REQUEST_RETRY_RE.test(formatErrorMessage(err));
46
+ }
47
+ function isAbortSignalTriggered(signal) {
48
+ return signal?.aborted === true;
49
+ }
50
+ function credentialsMatchBackfillAuthLineage(params) {
51
+ if (!params.stored) return true;
52
+ return params.stored.homeserver === params.auth.homeserver && params.stored.userId === params.auth.userId && params.stored.accessToken === params.auth.accessToken;
53
+ }
54
+ async function retryMatrixAuthRequest(label, run) {
55
+ return await retryAsync(run, {
56
+ attempts: 3,
57
+ minDelayMs: matrixAuthClientDepsForTest?.retryMinDelayMs ?? 250,
58
+ maxDelayMs: 1500,
59
+ jitter: .1,
60
+ label,
61
+ shouldRetry: (err) => shouldRetryMatrixAuthRequest(err)
62
+ });
63
+ }
64
+ async function fetchMatrixWhoamiIdentity(params) {
65
+ const { MatrixClient, ensureMatrixSdkLoggingConfigured } = await loadMatrixAuthClientDeps();
66
+ ensureMatrixSdkLoggingConfigured();
67
+ const tempClient = new MatrixClient(params.homeserver, params.accessToken, {
68
+ userId: params.userId,
69
+ ssrfPolicy: params.ssrfPolicy,
70
+ dispatcherPolicy: params.dispatcherPolicy
71
+ });
72
+ return await retryMatrixAuthRequest("matrix auth whoami", async () => {
73
+ return await tempClient.doRequest("GET", "/_matrix/client/v3/account/whoami");
74
+ });
75
+ }
76
+ function readEnvSecretRefFallback(params) {
77
+ const ref = coerceSecretRef(params.value, params.config?.secrets?.defaults);
78
+ if (!ref || ref.source !== "env" || !params.env) return;
79
+ const providerConfig = params.config?.secrets?.providers?.[ref.provider];
80
+ if (providerConfig) {
81
+ if (providerConfig.source !== "env") throw new Error(`Secret provider "${ref.provider}" has source "${providerConfig.source}" but ref requests "env".`);
82
+ if (providerConfig.allowlist && !providerConfig.allowlist.includes(ref.id)) throw new Error(`Environment variable "${ref.id}" is not allowlisted in secrets.providers.${ref.provider}.allowlist.`);
83
+ } else if (ref.provider !== (params.config?.secrets?.defaults?.env?.trim() || "default")) throw new Error(`Secret provider "${ref.provider}" is not configured (ref: ${ref.source}:${ref.provider}:${ref.id}).`);
84
+ const resolved = params.env[ref.id];
85
+ if (typeof resolved !== "string") return;
86
+ const trimmed = resolved.trim();
87
+ return trimmed.length > 0 ? trimmed : void 0;
88
+ }
89
+ function clean(value, path, opts) {
90
+ const ref = coerceSecretRef(value, opts?.config?.secrets?.defaults);
91
+ if (opts?.suppressSecretRef && ref) return "";
92
+ return normalizeResolvedSecretInputString({
93
+ value: opts?.allowEnvSecretRefFallback ? ref?.source === "env" ? readEnvSecretRefFallback({
94
+ value,
95
+ env: opts.env,
96
+ config: opts.config
97
+ }) ?? value : ref ? "" : value : value,
98
+ path,
99
+ defaults: opts?.config?.secrets?.defaults
100
+ }) ?? "";
101
+ }
102
+ function resolveMatrixBaseConfigFieldPath(field) {
103
+ return `channels.matrix.${field}`;
104
+ }
105
+ function shouldAllowEnvSecretRefFallback(field) {
106
+ return field === "accessToken" || field === "password";
107
+ }
108
+ function hasConfiguredSecretInputValue(value, cfg) {
109
+ return typeof value === "string" && value.trim().length > 0 || Boolean(coerceSecretRef(value, cfg.secrets?.defaults));
110
+ }
111
+ function hasConfiguredMatrixAccessTokenSource(params) {
112
+ const normalizedAccountId = normalizeAccountId$1(params.accountId);
113
+ const account = findMatrixAccountConfig(params.cfg, normalizedAccountId) ?? {};
114
+ const scopedAccessTokenVar = getMatrixScopedEnvVarNames(normalizedAccountId).accessToken;
115
+ if (hasConfiguredSecretInputValue(account.accessToken, params.cfg) || clean(params.env[scopedAccessTokenVar], scopedAccessTokenVar).length > 0) return true;
116
+ if (normalizedAccountId !== DEFAULT_ACCOUNT_ID$1) return false;
117
+ return hasConfiguredSecretInputValue(resolveMatrixBaseConfig(params.cfg).accessToken, params.cfg) || clean(params.env.MATRIX_ACCESS_TOKEN, "MATRIX_ACCESS_TOKEN").length > 0;
118
+ }
119
+ function resolveConfiguredMatrixAuthInput(params) {
120
+ const normalizedAccountId = normalizeAccountId$1(params.accountId);
121
+ const accountValue = (findMatrixAccountConfig(params.cfg, normalizedAccountId) ?? {})[params.field];
122
+ if (accountValue !== void 0) return {
123
+ value: accountValue,
124
+ path: resolveMatrixConfigFieldPath(params.cfg, normalizedAccountId, params.field)
125
+ };
126
+ const scopedKeys = getMatrixScopedEnvVarNames(normalizedAccountId);
127
+ const scopedValue = resolveScopedMatrixEnvConfig(normalizedAccountId, params.env)[params.field];
128
+ if (scopedValue !== void 0) return {
129
+ value: scopedValue,
130
+ path: params.field === "accessToken" ? scopedKeys.accessToken : scopedKeys.password
131
+ };
132
+ if (normalizedAccountId !== DEFAULT_ACCOUNT_ID$1) return;
133
+ const baseValue = resolveMatrixBaseConfig(params.cfg)[params.field];
134
+ if (baseValue !== void 0) return {
135
+ value: baseValue,
136
+ path: resolveMatrixBaseConfigFieldPath(params.field)
137
+ };
138
+ const globalValue = params.field === "accessToken" ? params.env.MATRIX_ACCESS_TOKEN : params.env.MATRIX_PASSWORD;
139
+ if (globalValue !== void 0) return {
140
+ value: globalValue,
141
+ path: params.field === "accessToken" ? "MATRIX_ACCESS_TOKEN" : "MATRIX_PASSWORD"
142
+ };
143
+ }
144
+ async function resolveConfiguredMatrixAuthSecretInput(params) {
145
+ const configured = resolveConfiguredMatrixAuthInput(params);
146
+ if (!configured) return;
147
+ if (!coerceSecretRef(configured.value, params.cfg.secrets?.defaults)) return normalizeResolvedSecretInputString({
148
+ value: configured.value,
149
+ path: configured.path,
150
+ defaults: params.cfg.secrets?.defaults
151
+ });
152
+ const { resolveConfiguredSecretInputString } = await loadMatrixSecretInputDeps();
153
+ const resolved = await resolveConfiguredSecretInputString({
154
+ config: params.cfg,
155
+ env: params.env,
156
+ value: configured.value,
157
+ path: configured.path,
158
+ unresolvedReasonStyle: "detailed"
159
+ });
160
+ if (resolved.value !== void 0) return resolved.value;
161
+ throw new Error(resolved.unresolvedRefReason ?? `${configured.path} SecretRef could not be resolved.`);
162
+ }
163
+ function readMatrixBaseConfigField(matrix, field, opts) {
164
+ return clean(matrix[field], resolveMatrixBaseConfigFieldPath(field), {
165
+ env: opts?.env,
166
+ config: opts?.config,
167
+ allowEnvSecretRefFallback: shouldAllowEnvSecretRefFallback(field),
168
+ suppressSecretRef: opts?.suppressSecretRef
169
+ });
170
+ }
171
+ function readMatrixAccountConfigField(cfg, accountId, account, field, opts) {
172
+ return clean(account[field], resolveMatrixConfigFieldPath(cfg, accountId, field), {
173
+ env: opts?.env,
174
+ config: opts?.config,
175
+ allowEnvSecretRefFallback: shouldAllowEnvSecretRefFallback(field),
176
+ suppressSecretRef: opts?.suppressSecretRef
177
+ });
178
+ }
179
+ function clampMatrixInitialSyncLimit(value) {
180
+ return typeof value === "number" ? Math.max(0, Math.floor(value)) : void 0;
181
+ }
182
+ function buildMatrixNetworkFields(params) {
183
+ const dispatcherPolicy = params.dispatcherPolicy ?? (params.proxy ? {
184
+ mode: "explicit-proxy",
185
+ proxyUrl: params.proxy
186
+ } : void 0);
187
+ if (!params.allowPrivateNetwork && !dispatcherPolicy) return {};
188
+ return {
189
+ ...params.allowPrivateNetwork ? {
190
+ allowPrivateNetwork: true,
191
+ ssrfPolicy: ssrfPolicyFromDangerouslyAllowPrivateNetwork$1(true)
192
+ } : {},
193
+ ...dispatcherPolicy ? { dispatcherPolicy } : {}
194
+ };
195
+ }
196
+ function hasScopedMatrixEnvConfig(accountId, env) {
197
+ const scoped = resolveScopedMatrixEnvConfig(accountId, env);
198
+ return Boolean(scoped.homeserver || scoped.userId || scoped.accessToken || scoped.password || scoped.deviceId || scoped.deviceName);
199
+ }
200
+ function resolveMatrixConfigForAccount(cfg, accountId, env = process.env) {
201
+ const matrix = resolveMatrixBaseConfig(cfg);
202
+ const account = findMatrixAccountConfig(cfg, accountId) ?? {};
203
+ const normalizedAccountId = normalizeAccountId$1(accountId);
204
+ const suppressInactivePasswordSecretRef = hasConfiguredMatrixAccessTokenSource({
205
+ cfg,
206
+ env,
207
+ accountId: normalizedAccountId
208
+ });
209
+ const fieldReadOptions = {
210
+ env,
211
+ config: cfg
212
+ };
213
+ const scopedEnv = resolveScopedMatrixEnvConfig(normalizedAccountId, env);
214
+ const globalEnv = resolveGlobalMatrixEnvConfig(env);
215
+ const accountField = (field) => readMatrixAccountConfigField(cfg, normalizedAccountId, account, field, {
216
+ ...fieldReadOptions,
217
+ suppressSecretRef: field === "password" ? suppressInactivePasswordSecretRef : void 0
218
+ });
219
+ const resolvedStrings = resolveMatrixAccountStringValues({
220
+ accountId: normalizedAccountId,
221
+ account: {
222
+ homeserver: accountField("homeserver"),
223
+ userId: accountField("userId"),
224
+ accessToken: accountField("accessToken"),
225
+ password: accountField("password"),
226
+ deviceId: accountField("deviceId"),
227
+ deviceName: accountField("deviceName")
228
+ },
229
+ scopedEnv,
230
+ channel: {
231
+ homeserver: readMatrixBaseConfigField(matrix, "homeserver", fieldReadOptions),
232
+ userId: readMatrixBaseConfigField(matrix, "userId", fieldReadOptions),
233
+ accessToken: readMatrixBaseConfigField(matrix, "accessToken", fieldReadOptions),
234
+ password: readMatrixBaseConfigField(matrix, "password", {
235
+ ...fieldReadOptions,
236
+ suppressSecretRef: suppressInactivePasswordSecretRef
237
+ }),
238
+ deviceId: readMatrixBaseConfigField(matrix, "deviceId", fieldReadOptions),
239
+ deviceName: readMatrixBaseConfigField(matrix, "deviceName", fieldReadOptions)
240
+ },
241
+ globalEnv
242
+ });
243
+ const initialSyncLimit = clampMatrixInitialSyncLimit(account.initialSyncLimit) ?? clampMatrixInitialSyncLimit(matrix.initialSyncLimit);
244
+ const encryption = typeof account.encryption === "boolean" ? account.encryption : matrix.encryption ?? false;
245
+ const allowPrivateNetwork = isPrivateNetworkOptInEnabled(account) || isPrivateNetworkOptInEnabled(matrix) ? true : void 0;
246
+ return {
247
+ homeserver: resolvedStrings.homeserver,
248
+ userId: resolvedStrings.userId,
249
+ accessToken: resolvedStrings.accessToken || void 0,
250
+ password: resolvedStrings.password || void 0,
251
+ deviceId: resolvedStrings.deviceId || void 0,
252
+ deviceName: resolvedStrings.deviceName || void 0,
253
+ initialSyncLimit,
254
+ encryption,
255
+ ...buildMatrixNetworkFields({
256
+ allowPrivateNetwork,
257
+ proxy: account.proxy ?? matrix.proxy
258
+ })
259
+ };
260
+ }
261
+ function resolveImplicitMatrixAccountId(cfg, env = process.env) {
262
+ if (requiresExplicitMatrixDefaultAccount(cfg, env)) return null;
263
+ return normalizeAccountId$1(resolveMatrixDefaultOrOnlyAccountId(cfg, env));
264
+ }
265
+ function resolveMatrixAuthContext(params) {
266
+ const cfg = requireRuntimeConfig(params.cfg, "Matrix auth context");
267
+ const env = params?.env ?? process.env;
268
+ const explicitAccountId = normalizeOptionalAccountId$1(params?.accountId);
269
+ const effectiveAccountId = explicitAccountId ?? resolveImplicitMatrixAccountId(cfg, env);
270
+ if (!effectiveAccountId) throw new Error("Multiple Matrix accounts are configured and channels.matrix.defaultAccount is not set. Set \"channels.matrix.defaultAccount\" to the intended account or pass --account <id>.");
271
+ if (explicitAccountId && explicitAccountId !== DEFAULT_ACCOUNT_ID$1 && !listNormalizedMatrixAccountIds(cfg).includes(explicitAccountId) && !hasScopedMatrixEnvConfig(explicitAccountId, env)) throw new Error(`Matrix account "${explicitAccountId}" is not configured. Add channels.matrix.accounts.${explicitAccountId} or define scoped ${getMatrixScopedEnvVarNames(explicitAccountId).accessToken.replace(/_ACCESS_TOKEN$/, "")}_* variables.`);
272
+ return {
273
+ cfg,
274
+ env,
275
+ accountId: effectiveAccountId,
276
+ resolved: resolveMatrixConfigForAccount(cfg, effectiveAccountId, env)
277
+ };
278
+ }
279
+ async function resolveMatrixAuth(params) {
280
+ if (!params?.cfg) throw new Error("Matrix auth requires a resolved runtime config. Load and resolve config at the command or gateway boundary, then pass cfg through the runtime path.");
281
+ const { cfg, env, accountId, resolved } = resolveMatrixAuthContext({
282
+ cfg: params.cfg,
283
+ env: params.env,
284
+ accountId: params.accountId
285
+ });
286
+ const accessToken = await resolveConfiguredMatrixAuthSecretInput({
287
+ cfg,
288
+ env,
289
+ accountId,
290
+ field: "accessToken"
291
+ }) ?? resolved.accessToken;
292
+ const tokenAuthPassword = resolved.password;
293
+ const homeserver = await resolveValidatedMatrixHomeserverUrl(resolved.homeserver, { dangerouslyAllowPrivateNetwork: resolved.allowPrivateNetwork });
294
+ const { loadMatrixCredentials, credentialsMatchConfig } = await loadMatrixCredentialsReadDeps();
295
+ const cached = loadMatrixCredentials(env, accountId);
296
+ const cachedCredentials = cached && credentialsMatchConfig(cached, {
297
+ homeserver,
298
+ userId: resolved.userId || "",
299
+ accessToken
300
+ }) ? cached : null;
301
+ if (accessToken) {
302
+ let userId = resolved.userId;
303
+ const hasMatchingCachedToken = cachedCredentials?.accessToken === accessToken;
304
+ let knownDeviceId = hasMatchingCachedToken ? cachedCredentials?.deviceId || resolved.deviceId : resolved.deviceId;
305
+ if (!userId) {
306
+ const whoami = await fetchMatrixWhoamiIdentity({
307
+ homeserver,
308
+ accessToken,
309
+ userId,
310
+ ssrfPolicy: resolved.ssrfPolicy,
311
+ dispatcherPolicy: resolved.dispatcherPolicy
312
+ });
313
+ const fetchedUserId = whoami.user_id?.trim();
314
+ if (!fetchedUserId) throw new Error("Matrix whoami did not return user_id");
315
+ userId = fetchedUserId;
316
+ knownDeviceId = knownDeviceId || whoami.device_id?.trim() || resolved.deviceId;
317
+ }
318
+ if (!cachedCredentials || !hasMatchingCachedToken || cachedCredentials.userId !== userId || (cachedCredentials.deviceId || void 0) !== knownDeviceId) {
319
+ const { saveMatrixCredentials } = await loadMatrixCredentialsWriteRuntime();
320
+ await saveMatrixCredentials({
321
+ homeserver,
322
+ userId,
323
+ accessToken,
324
+ deviceId: knownDeviceId
325
+ }, env, accountId);
326
+ } else if (hasMatchingCachedToken) {
327
+ const { touchMatrixCredentials } = await loadMatrixCredentialsWriteRuntime();
328
+ await touchMatrixCredentials(env, accountId);
329
+ }
330
+ return {
331
+ accountId,
332
+ homeserver,
333
+ userId,
334
+ accessToken,
335
+ password: tokenAuthPassword,
336
+ deviceId: knownDeviceId,
337
+ deviceName: resolved.deviceName,
338
+ initialSyncLimit: resolved.initialSyncLimit,
339
+ encryption: resolved.encryption,
340
+ ...buildMatrixNetworkFields({
341
+ allowPrivateNetwork: resolved.allowPrivateNetwork,
342
+ dispatcherPolicy: resolved.dispatcherPolicy
343
+ })
344
+ };
345
+ }
346
+ if (cachedCredentials) {
347
+ const { touchMatrixCredentials } = await loadMatrixCredentialsWriteRuntime();
348
+ await touchMatrixCredentials(env, accountId);
349
+ return {
350
+ accountId,
351
+ homeserver: cachedCredentials.homeserver,
352
+ userId: cachedCredentials.userId,
353
+ accessToken: cachedCredentials.accessToken,
354
+ password: tokenAuthPassword,
355
+ deviceId: cachedCredentials.deviceId || resolved.deviceId,
356
+ deviceName: resolved.deviceName,
357
+ initialSyncLimit: resolved.initialSyncLimit,
358
+ encryption: resolved.encryption,
359
+ ...buildMatrixNetworkFields({
360
+ allowPrivateNetwork: resolved.allowPrivateNetwork,
361
+ dispatcherPolicy: resolved.dispatcherPolicy
362
+ })
363
+ };
364
+ }
365
+ if (!resolved.userId) throw new Error("Matrix userId is required when no access token is configured (matrix.userId)");
366
+ const password = await resolveConfiguredMatrixAuthSecretInput({
367
+ cfg,
368
+ env,
369
+ accountId,
370
+ field: "password"
371
+ }) ?? resolved.password;
372
+ if (!password) throw new Error("Matrix password is required when no access token is configured (matrix.password)");
373
+ const { MatrixClient, ensureMatrixSdkLoggingConfigured } = await loadMatrixAuthClientDeps();
374
+ ensureMatrixSdkLoggingConfigured();
375
+ const loginClient = new MatrixClient(homeserver, "", {
376
+ ssrfPolicy: resolved.ssrfPolicy,
377
+ dispatcherPolicy: resolved.dispatcherPolicy
378
+ });
379
+ const login = await retryMatrixAuthRequest("matrix auth login", async () => {
380
+ return await loginClient.doRequest("POST", "/_matrix/client/v3/login", void 0, {
381
+ type: "m.login.password",
382
+ identifier: {
383
+ type: "m.id.user",
384
+ user: resolved.userId
385
+ },
386
+ password,
387
+ device_id: resolved.deviceId,
388
+ initial_device_display_name: resolved.deviceName ?? "Klaw Gateway"
389
+ });
390
+ });
391
+ const loginAccessToken = login.access_token?.trim();
392
+ if (!loginAccessToken) throw new Error("Matrix login did not return an access token");
393
+ const auth = {
394
+ accountId,
395
+ homeserver,
396
+ userId: login.user_id ?? resolved.userId,
397
+ accessToken: loginAccessToken,
398
+ password,
399
+ deviceId: login.device_id ?? resolved.deviceId,
400
+ deviceName: resolved.deviceName,
401
+ initialSyncLimit: resolved.initialSyncLimit,
402
+ encryption: resolved.encryption,
403
+ ...buildMatrixNetworkFields({
404
+ allowPrivateNetwork: resolved.allowPrivateNetwork,
405
+ dispatcherPolicy: resolved.dispatcherPolicy
406
+ })
407
+ };
408
+ const { saveMatrixCredentials } = await loadMatrixCredentialsWriteRuntime();
409
+ await saveMatrixCredentials({
410
+ homeserver: auth.homeserver,
411
+ userId: auth.userId,
412
+ accessToken: auth.accessToken,
413
+ deviceId: auth.deviceId
414
+ }, env, accountId);
415
+ return auth;
416
+ }
417
+ async function backfillMatrixAuthDeviceIdAfterStartup(params) {
418
+ const knownDeviceId = params.auth.deviceId?.trim();
419
+ if (knownDeviceId) return knownDeviceId;
420
+ if (isAbortSignalTriggered(params.abortSignal)) return;
421
+ const deviceId = (await fetchMatrixWhoamiIdentity({
422
+ homeserver: params.auth.homeserver,
423
+ accessToken: params.auth.accessToken,
424
+ userId: params.auth.userId,
425
+ ssrfPolicy: params.auth.ssrfPolicy,
426
+ dispatcherPolicy: params.auth.dispatcherPolicy
427
+ })).device_id?.trim();
428
+ if (!deviceId) return;
429
+ if (isAbortSignalTriggered(params.abortSignal)) return;
430
+ const env = params.env ?? process.env;
431
+ const { loadMatrixCredentials } = await loadMatrixCredentialsReadDeps();
432
+ if (!credentialsMatchBackfillAuthLineage({
433
+ stored: loadMatrixCredentials(env, params.auth.accountId),
434
+ auth: params.auth
435
+ })) return;
436
+ if (!repairCurrentTokenStorageMetaDeviceId({
437
+ homeserver: params.auth.homeserver,
438
+ userId: params.auth.userId,
439
+ accessToken: params.auth.accessToken,
440
+ accountId: params.auth.accountId,
441
+ deviceId,
442
+ env: params.env
443
+ })) throw new Error("Matrix deviceId backfill failed to repair current-token storage metadata");
444
+ if (isAbortSignalTriggered(params.abortSignal)) return;
445
+ return await (await loadMatrixCredentialsWriteRuntime()).saveBackfilledMatrixDeviceId({
446
+ homeserver: params.auth.homeserver,
447
+ userId: params.auth.userId,
448
+ accessToken: params.auth.accessToken,
449
+ deviceId
450
+ }, env, params.auth.accountId) === "saved" ? deviceId : void 0;
451
+ }
452
+ //#endregion
453
+ //#region extensions/matrix/src/matrix/client/shared.ts
454
+ var shared_exports = /* @__PURE__ */ __exportAll({
455
+ acquireSharedMatrixClient: () => acquireSharedMatrixClient,
456
+ releaseSharedClientInstance: () => releaseSharedClientInstance,
457
+ removeSharedClientInstance: () => removeSharedClientInstance,
458
+ resolveSharedMatrixClient: () => resolveSharedMatrixClient,
459
+ stopSharedClient: () => stopSharedClient,
460
+ stopSharedClientForAccount: () => stopSharedClientForAccount,
461
+ stopSharedClientInstance: () => stopSharedClientInstance
462
+ });
463
+ let matrixCreateClientDepsPromise;
464
+ async function loadMatrixCreateClientDeps() {
465
+ matrixCreateClientDepsPromise ??= import("./create-client-J0htTaRj.js").then((n) => n.n).then((runtime) => ({ createMatrixClient: runtime.createMatrixClient }));
466
+ return await matrixCreateClientDepsPromise;
467
+ }
468
+ const sharedClientStates = /* @__PURE__ */ new Map();
469
+ const sharedClientPromises = /* @__PURE__ */ new Map();
470
+ function serializeDispatcherPolicyKey(auth) {
471
+ return JSON.stringify(auth.dispatcherPolicy ?? null);
472
+ }
473
+ function buildSharedClientKey(auth) {
474
+ return [
475
+ auth.homeserver,
476
+ auth.userId,
477
+ auth.accessToken,
478
+ auth.encryption ? "e2ee" : "plain",
479
+ auth.allowPrivateNetwork ? "private-net" : "strict-net",
480
+ serializeDispatcherPolicyKey(auth),
481
+ auth.accountId
482
+ ].join("|");
483
+ }
484
+ async function createSharedMatrixClient(params) {
485
+ const { createMatrixClient } = await loadMatrixCreateClientDeps();
486
+ return {
487
+ client: await createMatrixClient({
488
+ homeserver: params.auth.homeserver,
489
+ userId: params.auth.userId,
490
+ accessToken: params.auth.accessToken,
491
+ password: params.auth.password,
492
+ deviceId: params.auth.deviceId,
493
+ encryption: params.auth.encryption,
494
+ localTimeoutMs: params.timeoutMs,
495
+ initialSyncLimit: params.auth.initialSyncLimit,
496
+ accountId: params.auth.accountId,
497
+ allowPrivateNetwork: params.auth.allowPrivateNetwork,
498
+ ssrfPolicy: params.auth.ssrfPolicy,
499
+ dispatcherPolicy: params.auth.dispatcherPolicy
500
+ }),
501
+ key: buildSharedClientKey(params.auth),
502
+ started: false,
503
+ cryptoReady: false,
504
+ startPromise: null,
505
+ leases: 0
506
+ };
507
+ }
508
+ function findSharedClientStateByInstance(client) {
509
+ for (const state of sharedClientStates.values()) if (state.client === client) return state;
510
+ return null;
511
+ }
512
+ function deleteSharedClientState(state) {
513
+ sharedClientStates.delete(state.key);
514
+ sharedClientPromises.delete(state.key);
515
+ }
516
+ async function ensureSharedClientStarted(params) {
517
+ const waitForStart = async (startPromise) => {
518
+ await awaitMatrixStartupWithAbort(startPromise, params.abortSignal);
519
+ };
520
+ if (params.state.started) return;
521
+ if (params.state.startPromise) {
522
+ await waitForStart(params.state.startPromise);
523
+ return;
524
+ }
525
+ const guardedStart = (async () => {
526
+ const client = params.state.client;
527
+ if (params.encryption && !params.state.cryptoReady) try {
528
+ const joinedRooms = await client.getJoinedRooms();
529
+ if (client.crypto) {
530
+ await client.crypto.prepare(joinedRooms);
531
+ params.state.cryptoReady = true;
532
+ }
533
+ } catch (err) {
534
+ LogService.warn("MatrixClientLite", "Failed to prepare crypto:", err);
535
+ }
536
+ await client.start({ abortSignal: params.abortSignal });
537
+ params.state.started = true;
538
+ })().finally(() => {
539
+ if (params.state.startPromise === guardedStart) params.state.startPromise = null;
540
+ });
541
+ params.state.startPromise = guardedStart;
542
+ await waitForStart(guardedStart);
543
+ }
544
+ async function resolveSharedMatrixClientState(params = {}) {
545
+ const requestedAccountId = normalizeOptionalAccountId(params.accountId);
546
+ if (params.auth && requestedAccountId && requestedAccountId !== params.auth.accountId) throw new Error(`Matrix shared client account mismatch: requested ${requestedAccountId}, auth resolved ${params.auth.accountId}`);
547
+ const authContext = (() => {
548
+ if (params.auth) return null;
549
+ if (!params.cfg) throw new Error("Matrix shared client requires a resolved runtime config. Load and resolve config at the command or gateway boundary, then pass cfg through the runtime path.");
550
+ return resolveMatrixAuthContext({
551
+ cfg: params.cfg,
552
+ env: params.env,
553
+ accountId: params.accountId
554
+ });
555
+ })();
556
+ const auth = params.auth ?? await resolveMatrixAuth({
557
+ cfg: authContext?.cfg ?? params.cfg,
558
+ env: authContext?.env ?? params.env,
559
+ accountId: authContext?.accountId
560
+ });
561
+ const key = buildSharedClientKey(auth);
562
+ const shouldStart = params.startClient !== false;
563
+ const existingState = sharedClientStates.get(key);
564
+ if (existingState) {
565
+ if (shouldStart) await ensureSharedClientStarted({
566
+ state: existingState,
567
+ encryption: auth.encryption,
568
+ abortSignal: params.abortSignal
569
+ });
570
+ return existingState;
571
+ }
572
+ const existingPromise = sharedClientPromises.get(key);
573
+ if (existingPromise) {
574
+ const pending = await existingPromise;
575
+ if (shouldStart) await ensureSharedClientStarted({
576
+ state: pending,
577
+ encryption: auth.encryption,
578
+ abortSignal: params.abortSignal
579
+ });
580
+ return pending;
581
+ }
582
+ const creationPromise = createSharedMatrixClient({
583
+ auth,
584
+ timeoutMs: params.timeoutMs
585
+ });
586
+ sharedClientPromises.set(key, creationPromise);
587
+ try {
588
+ const created = await creationPromise;
589
+ sharedClientStates.set(key, created);
590
+ if (shouldStart) await ensureSharedClientStarted({
591
+ state: created,
592
+ encryption: auth.encryption,
593
+ abortSignal: params.abortSignal
594
+ });
595
+ return created;
596
+ } finally {
597
+ sharedClientPromises.delete(key);
598
+ }
599
+ }
600
+ async function resolveSharedMatrixClient(params = {}) {
601
+ return (await resolveSharedMatrixClientState(params)).client;
602
+ }
603
+ async function acquireSharedMatrixClient(params = {}) {
604
+ const state = await resolveSharedMatrixClientState(params);
605
+ state.leases += 1;
606
+ return state.client;
607
+ }
608
+ function stopSharedClient() {
609
+ for (const state of sharedClientStates.values()) state.client.stop();
610
+ sharedClientStates.clear();
611
+ sharedClientPromises.clear();
612
+ }
613
+ function stopSharedClientForAccount(auth) {
614
+ const key = buildSharedClientKey(auth);
615
+ const state = sharedClientStates.get(key);
616
+ if (!state) return;
617
+ state.client.stop();
618
+ deleteSharedClientState(state);
619
+ }
620
+ function removeSharedClientInstance(client) {
621
+ const state = findSharedClientStateByInstance(client);
622
+ if (!state) return false;
623
+ deleteSharedClientState(state);
624
+ return true;
625
+ }
626
+ function stopSharedClientInstance(client) {
627
+ if (!removeSharedClientInstance(client)) return;
628
+ client.stop();
629
+ }
630
+ async function releaseSharedClientInstance(client, mode = "stop") {
631
+ const state = findSharedClientStateByInstance(client);
632
+ if (!state) return false;
633
+ state.leases = Math.max(0, state.leases - 1);
634
+ if (state.leases > 0) return false;
635
+ deleteSharedClientState(state);
636
+ if (mode === "persist") await client.stopAndPersist();
637
+ else if (mode === "discard") client.stopWithoutPersist();
638
+ else client.stop();
639
+ return true;
640
+ }
641
+ //#endregion
642
+ export { shared_exports as a, backfillMatrixAuthDeviceIdAfterStartup as c, resolveMatrixConfigForAccount as d, resolveSharedMatrixClient as i, resolveMatrixAuth as l, releaseSharedClientInstance as n, stopSharedClientForAccount as o, removeSharedClientInstance as r, stopSharedClientInstance as s, acquireSharedMatrixClient as t, resolveMatrixAuthContext as u };